]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/amd64/linux32/linux32_sysvec.c
Import DTS files for riscv from Linux 5.4
[FreeBSD/FreeBSD.git] / sys / amd64 / linux32 / linux32_sysvec.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 2004 Tim J. Robbins
5  * Copyright (c) 2003 Peter Wemm
6  * Copyright (c) 2002 Doug Rabson
7  * Copyright (c) 1998-1999 Andrew Gallatin
8  * Copyright (c) 1994-1996 Søren Schmidt
9  * All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer
16  *    in this position and unchanged.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. The name of the author may not be used to endorse or promote products
21  *    derived from this software without specific prior written permission
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
24  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
26  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
27  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
28  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
32  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33  */
34
35 #include "opt_compat.h"
36
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39
40 #ifndef COMPAT_FREEBSD32
41 #error "Unable to compile Linux-emulator due to missing COMPAT_FREEBSD32 option!"
42 #endif
43
44 #define __ELF_WORD_SIZE 32
45
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/exec.h>
49 #include <sys/fcntl.h>
50 #include <sys/imgact.h>
51 #include <sys/imgact_elf.h>
52 #include <sys/kernel.h>
53 #include <sys/lock.h>
54 #include <sys/malloc.h>
55 #include <sys/module.h>
56 #include <sys/mutex.h>
57 #include <sys/proc.h>
58 #include <sys/resourcevar.h>
59 #include <sys/signalvar.h>
60 #include <sys/syscallsubr.h>
61 #include <sys/sysctl.h>
62 #include <sys/sysent.h>
63 #include <sys/sysproto.h>
64 #include <sys/vnode.h>
65 #include <sys/eventhandler.h>
66
67 #include <vm/vm.h>
68 #include <vm/pmap.h>
69 #include <vm/vm_extern.h>
70 #include <vm/vm_map.h>
71 #include <vm/vm_object.h>
72 #include <vm/vm_page.h>
73 #include <vm/vm_param.h>
74
75 #include <machine/cpu.h>
76 #include <machine/md_var.h>
77 #include <machine/pcb.h>
78 #include <machine/specialreg.h>
79 #include <machine/trap.h>
80
81 #include <amd64/linux32/linux.h>
82 #include <amd64/linux32/linux32_proto.h>
83 #include <compat/linux/linux_emul.h>
84 #include <compat/linux/linux_ioctl.h>
85 #include <compat/linux/linux_mib.h>
86 #include <compat/linux/linux_misc.h>
87 #include <compat/linux/linux_signal.h>
88 #include <compat/linux/linux_util.h>
89 #include <compat/linux/linux_vdso.h>
90
91 MODULE_VERSION(linux, 1);
92
93 const char *linux_kplatform;
94 static int linux_szsigcode;
95 static vm_object_t linux_shared_page_obj;
96 static char *linux_shared_page_mapping;
97 extern char _binary_linux32_locore_o_start;
98 extern char _binary_linux32_locore_o_end;
99
100 extern struct sysent linux32_sysent[LINUX32_SYS_MAXSYSCALL];
101
102 SET_DECLARE(linux_ioctl_handler_set, struct linux_ioctl_handler);
103
104 static int      linux_fixup_elf(register_t **stack_base,
105                     struct image_params *iparams);
106 static int      linux_copyout_strings(struct image_params *imgp,
107                     register_t **stack_base);
108 static void     linux_sendsig(sig_t catcher, ksiginfo_t *ksi, sigset_t *mask);
109 static void     linux_exec_setregs(struct thread *td,
110                                    struct image_params *imgp, u_long stack);
111 static void     linux32_fixlimit(struct rlimit *rl, int which);
112 static bool     linux32_trans_osrel(const Elf_Note *note, int32_t *osrel);
113 static void     linux_vdso_install(void *param);
114 static void     linux_vdso_deinstall(void *param);
115
116 #define LINUX_T_UNKNOWN  255
117 static int _bsd_to_linux_trapcode[] = {
118         LINUX_T_UNKNOWN,        /* 0 */
119         6,                      /* 1  T_PRIVINFLT */
120         LINUX_T_UNKNOWN,        /* 2 */
121         3,                      /* 3  T_BPTFLT */
122         LINUX_T_UNKNOWN,        /* 4 */
123         LINUX_T_UNKNOWN,        /* 5 */
124         16,                     /* 6  T_ARITHTRAP */
125         254,                    /* 7  T_ASTFLT */
126         LINUX_T_UNKNOWN,        /* 8 */
127         13,                     /* 9  T_PROTFLT */
128         1,                      /* 10 T_TRCTRAP */
129         LINUX_T_UNKNOWN,        /* 11 */
130         14,                     /* 12 T_PAGEFLT */
131         LINUX_T_UNKNOWN,        /* 13 */
132         17,                     /* 14 T_ALIGNFLT */
133         LINUX_T_UNKNOWN,        /* 15 */
134         LINUX_T_UNKNOWN,        /* 16 */
135         LINUX_T_UNKNOWN,        /* 17 */
136         0,                      /* 18 T_DIVIDE */
137         2,                      /* 19 T_NMI */
138         4,                      /* 20 T_OFLOW */
139         5,                      /* 21 T_BOUND */
140         7,                      /* 22 T_DNA */
141         8,                      /* 23 T_DOUBLEFLT */
142         9,                      /* 24 T_FPOPFLT */
143         10,                     /* 25 T_TSSFLT */
144         11,                     /* 26 T_SEGNPFLT */
145         12,                     /* 27 T_STKFLT */
146         18,                     /* 28 T_MCHK */
147         19,                     /* 29 T_XMMFLT */
148         15                      /* 30 T_RESERVED */
149 };
150 #define bsd_to_linux_trapcode(code) \
151     ((code)<nitems(_bsd_to_linux_trapcode)? \
152      _bsd_to_linux_trapcode[(code)]: \
153      LINUX_T_UNKNOWN)
154
155 struct linux32_ps_strings {
156         u_int32_t ps_argvstr;   /* first of 0 or more argument strings */
157         u_int ps_nargvstr;      /* the number of argument strings */
158         u_int32_t ps_envstr;    /* first of 0 or more environment strings */
159         u_int ps_nenvstr;       /* the number of environment strings */
160 };
161
162 LINUX_VDSO_SYM_INTPTR(linux32_sigcode);
163 LINUX_VDSO_SYM_INTPTR(linux32_rt_sigcode);
164 LINUX_VDSO_SYM_INTPTR(linux32_vsyscall);
165 LINUX_VDSO_SYM_CHAR(linux_platform);
166
167 /*
168  * If FreeBSD & Linux have a difference of opinion about what a trap
169  * means, deal with it here.
170  *
171  * MPSAFE
172  */
173 static int
174 linux_translate_traps(int signal, int trap_code)
175 {
176         if (signal != SIGBUS)
177                 return (signal);
178         switch (trap_code) {
179         case T_PROTFLT:
180         case T_TSSFLT:
181         case T_DOUBLEFLT:
182         case T_PAGEFLT:
183                 return (SIGSEGV);
184         default:
185                 return (signal);
186         }
187 }
188
189 static int
190 linux_copyout_auxargs(struct image_params *imgp, u_long *base)
191 {
192         Elf32_Auxargs *args;
193         Elf32_Auxinfo *argarray, *pos;
194         u_long auxlen;
195         int error, issetugid;
196
197         args = (Elf32_Auxargs *)imgp->auxargs;
198         argarray = pos = malloc(LINUX_AT_COUNT * sizeof(*pos), M_TEMP,
199             M_WAITOK | M_ZERO);
200
201         issetugid = imgp->proc->p_flag & P_SUGID ? 1 : 0;
202         AUXARGS_ENTRY(pos, LINUX_AT_SYSINFO_EHDR,
203             imgp->proc->p_sysent->sv_shared_page_base);
204         AUXARGS_ENTRY(pos, LINUX_AT_SYSINFO, linux32_vsyscall);
205         AUXARGS_ENTRY(pos, LINUX_AT_HWCAP, cpu_feature);
206
207         /*
208          * Do not export AT_CLKTCK when emulating Linux kernel prior to 2.4.0,
209          * as it has appeared in the 2.4.0-rc7 first time.
210          * Being exported, AT_CLKTCK is returned by sysconf(_SC_CLK_TCK),
211          * glibc falls back to the hard-coded CLK_TCK value when aux entry
212          * is not present.
213          * Also see linux_times() implementation.
214          */
215         if (linux_kernver(curthread) >= LINUX_KERNVER_2004000)
216                 AUXARGS_ENTRY(pos, LINUX_AT_CLKTCK, stclohz);
217         AUXARGS_ENTRY(pos, AT_PHDR, args->phdr);
218         AUXARGS_ENTRY(pos, AT_PHENT, args->phent);
219         AUXARGS_ENTRY(pos, AT_PHNUM, args->phnum);
220         AUXARGS_ENTRY(pos, AT_PAGESZ, args->pagesz);
221         AUXARGS_ENTRY(pos, AT_FLAGS, args->flags);
222         AUXARGS_ENTRY(pos, AT_ENTRY, args->entry);
223         AUXARGS_ENTRY(pos, AT_BASE, args->base);
224         AUXARGS_ENTRY(pos, LINUX_AT_SECURE, issetugid);
225         AUXARGS_ENTRY(pos, AT_UID, imgp->proc->p_ucred->cr_ruid);
226         AUXARGS_ENTRY(pos, AT_EUID, imgp->proc->p_ucred->cr_svuid);
227         AUXARGS_ENTRY(pos, AT_GID, imgp->proc->p_ucred->cr_rgid);
228         AUXARGS_ENTRY(pos, AT_EGID, imgp->proc->p_ucred->cr_svgid);
229         AUXARGS_ENTRY(pos, LINUX_AT_PLATFORM, PTROUT(linux_platform));
230         AUXARGS_ENTRY(pos, LINUX_AT_RANDOM, PTROUT(imgp->canary));
231         if (imgp->execpathp != 0)
232                 AUXARGS_ENTRY(pos, LINUX_AT_EXECFN, PTROUT(imgp->execpathp));
233         if (args->execfd != -1)
234                 AUXARGS_ENTRY(pos, AT_EXECFD, args->execfd);
235         AUXARGS_ENTRY(pos, AT_NULL, 0);
236
237         free(imgp->auxargs, M_TEMP);
238         imgp->auxargs = NULL;
239         KASSERT(pos - argarray <= LINUX_AT_COUNT, ("Too many auxargs"));
240
241         auxlen = sizeof(*argarray) * (pos - argarray);
242         *base -= auxlen;
243         error = copyout(argarray, (void *)*base, auxlen);
244         free(argarray, M_TEMP);
245         return (error);
246 }
247
248 static int
249 linux_fixup_elf(register_t **stack_base, struct image_params *imgp)
250 {
251         Elf32_Addr *base;
252
253         base = (Elf32_Addr *)*stack_base;
254         base--;
255         if (suword32(base, (uint32_t)imgp->args->argc) == -1)
256                 return (EFAULT);
257         *stack_base = (register_t *)base;
258         return (0);
259 }
260
261 static void
262 linux_rt_sendsig(sig_t catcher, ksiginfo_t *ksi, sigset_t *mask)
263 {
264         struct thread *td = curthread;
265         struct proc *p = td->td_proc;
266         struct sigacts *psp;
267         struct trapframe *regs;
268         struct l_rt_sigframe *fp, frame;
269         int oonstack;
270         int sig;
271         int code;
272
273         sig = ksi->ksi_signo;
274         code = ksi->ksi_code;
275         PROC_LOCK_ASSERT(p, MA_OWNED);
276         psp = p->p_sigacts;
277         mtx_assert(&psp->ps_mtx, MA_OWNED);
278         regs = td->td_frame;
279         oonstack = sigonstack(regs->tf_rsp);
280
281         /* Allocate space for the signal handler context. */
282         if ((td->td_pflags & TDP_ALTSTACK) && !oonstack &&
283             SIGISMEMBER(psp->ps_sigonstack, sig)) {
284                 fp = (struct l_rt_sigframe *)((uintptr_t)td->td_sigstk.ss_sp +
285                     td->td_sigstk.ss_size - sizeof(struct l_rt_sigframe));
286         } else
287                 fp = (struct l_rt_sigframe *)regs->tf_rsp - 1;
288         mtx_unlock(&psp->ps_mtx);
289
290         /* Build the argument list for the signal handler. */
291         sig = bsd_to_linux_signal(sig);
292
293         bzero(&frame, sizeof(frame));
294
295         frame.sf_handler = PTROUT(catcher);
296         frame.sf_sig = sig;
297         frame.sf_siginfo = PTROUT(&fp->sf_si);
298         frame.sf_ucontext = PTROUT(&fp->sf_sc);
299
300         /* Fill in POSIX parts. */
301         ksiginfo_to_lsiginfo(ksi, &frame.sf_si, sig);
302
303         /*
304          * Build the signal context to be used by sigreturn and libgcc unwind.
305          */
306         frame.sf_sc.uc_flags = 0;               /* XXX ??? */
307         frame.sf_sc.uc_link = 0;                /* XXX ??? */
308
309         frame.sf_sc.uc_stack.ss_sp = PTROUT(td->td_sigstk.ss_sp);
310         frame.sf_sc.uc_stack.ss_size = td->td_sigstk.ss_size;
311         frame.sf_sc.uc_stack.ss_flags = (td->td_pflags & TDP_ALTSTACK)
312             ? ((oonstack) ? LINUX_SS_ONSTACK : 0) : LINUX_SS_DISABLE;
313         PROC_UNLOCK(p);
314
315         bsd_to_linux_sigset(mask, &frame.sf_sc.uc_sigmask);
316
317         frame.sf_sc.uc_mcontext.sc_mask   = frame.sf_sc.uc_sigmask.__mask;
318         frame.sf_sc.uc_mcontext.sc_edi    = regs->tf_rdi;
319         frame.sf_sc.uc_mcontext.sc_esi    = regs->tf_rsi;
320         frame.sf_sc.uc_mcontext.sc_ebp    = regs->tf_rbp;
321         frame.sf_sc.uc_mcontext.sc_ebx    = regs->tf_rbx;
322         frame.sf_sc.uc_mcontext.sc_esp    = regs->tf_rsp;
323         frame.sf_sc.uc_mcontext.sc_edx    = regs->tf_rdx;
324         frame.sf_sc.uc_mcontext.sc_ecx    = regs->tf_rcx;
325         frame.sf_sc.uc_mcontext.sc_eax    = regs->tf_rax;
326         frame.sf_sc.uc_mcontext.sc_eip    = regs->tf_rip;
327         frame.sf_sc.uc_mcontext.sc_cs     = regs->tf_cs;
328         frame.sf_sc.uc_mcontext.sc_gs     = regs->tf_gs;
329         frame.sf_sc.uc_mcontext.sc_fs     = regs->tf_fs;
330         frame.sf_sc.uc_mcontext.sc_es     = regs->tf_es;
331         frame.sf_sc.uc_mcontext.sc_ds     = regs->tf_ds;
332         frame.sf_sc.uc_mcontext.sc_eflags = regs->tf_rflags;
333         frame.sf_sc.uc_mcontext.sc_esp_at_signal = regs->tf_rsp;
334         frame.sf_sc.uc_mcontext.sc_ss     = regs->tf_ss;
335         frame.sf_sc.uc_mcontext.sc_err    = regs->tf_err;
336         frame.sf_sc.uc_mcontext.sc_cr2    = (u_int32_t)(uintptr_t)ksi->ksi_addr;
337         frame.sf_sc.uc_mcontext.sc_trapno = bsd_to_linux_trapcode(code);
338
339         if (copyout(&frame, fp, sizeof(frame)) != 0) {
340                 /*
341                  * Process has trashed its stack; give it an illegal
342                  * instruction to halt it in its tracks.
343                  */
344                 PROC_LOCK(p);
345                 sigexit(td, SIGILL);
346         }
347
348         /* Build context to run handler in. */
349         regs->tf_rsp = PTROUT(fp);
350         regs->tf_rip = linux32_rt_sigcode;
351         regs->tf_rflags &= ~(PSL_T | PSL_D);
352         regs->tf_cs = _ucode32sel;
353         regs->tf_ss = _udatasel;
354         regs->tf_ds = _udatasel;
355         regs->tf_es = _udatasel;
356         regs->tf_fs = _ufssel;
357         regs->tf_gs = _ugssel;
358         regs->tf_flags = TF_HASSEGS;
359         set_pcb_flags(td->td_pcb, PCB_FULL_IRET);
360         PROC_LOCK(p);
361         mtx_lock(&psp->ps_mtx);
362 }
363
364
365 /*
366  * Send an interrupt to process.
367  *
368  * Stack is set up to allow sigcode stored
369  * in u. to call routine, followed by kcall
370  * to sigreturn routine below.  After sigreturn
371  * resets the signal mask, the stack, and the
372  * frame pointer, it returns to the user
373  * specified pc, psl.
374  */
375 static void
376 linux_sendsig(sig_t catcher, ksiginfo_t *ksi, sigset_t *mask)
377 {
378         struct thread *td = curthread;
379         struct proc *p = td->td_proc;
380         struct sigacts *psp;
381         struct trapframe *regs;
382         struct l_sigframe *fp, frame;
383         l_sigset_t lmask;
384         int oonstack;
385         int sig, code;
386
387         sig = ksi->ksi_signo;
388         code = ksi->ksi_code;
389         PROC_LOCK_ASSERT(p, MA_OWNED);
390         psp = p->p_sigacts;
391         mtx_assert(&psp->ps_mtx, MA_OWNED);
392         if (SIGISMEMBER(psp->ps_siginfo, sig)) {
393                 /* Signal handler installed with SA_SIGINFO. */
394                 linux_rt_sendsig(catcher, ksi, mask);
395                 return;
396         }
397
398         regs = td->td_frame;
399         oonstack = sigonstack(regs->tf_rsp);
400
401         /* Allocate space for the signal handler context. */
402         if ((td->td_pflags & TDP_ALTSTACK) && !oonstack &&
403             SIGISMEMBER(psp->ps_sigonstack, sig)) {
404                 fp = (struct l_sigframe *)((uintptr_t)td->td_sigstk.ss_sp +
405                     td->td_sigstk.ss_size - sizeof(struct l_sigframe));
406         } else
407                 fp = (struct l_sigframe *)regs->tf_rsp - 1;
408         mtx_unlock(&psp->ps_mtx);
409         PROC_UNLOCK(p);
410
411         /* Build the argument list for the signal handler. */
412         sig = bsd_to_linux_signal(sig);
413
414         bzero(&frame, sizeof(frame));
415
416         frame.sf_handler = PTROUT(catcher);
417         frame.sf_sig = sig;
418
419         bsd_to_linux_sigset(mask, &lmask);
420
421         /* Build the signal context to be used by sigreturn. */
422         frame.sf_sc.sc_mask   = lmask.__mask;
423         frame.sf_sc.sc_gs     = regs->tf_gs;
424         frame.sf_sc.sc_fs     = regs->tf_fs;
425         frame.sf_sc.sc_es     = regs->tf_es;
426         frame.sf_sc.sc_ds     = regs->tf_ds;
427         frame.sf_sc.sc_edi    = regs->tf_rdi;
428         frame.sf_sc.sc_esi    = regs->tf_rsi;
429         frame.sf_sc.sc_ebp    = regs->tf_rbp;
430         frame.sf_sc.sc_ebx    = regs->tf_rbx;
431         frame.sf_sc.sc_esp    = regs->tf_rsp;
432         frame.sf_sc.sc_edx    = regs->tf_rdx;
433         frame.sf_sc.sc_ecx    = regs->tf_rcx;
434         frame.sf_sc.sc_eax    = regs->tf_rax;
435         frame.sf_sc.sc_eip    = regs->tf_rip;
436         frame.sf_sc.sc_cs     = regs->tf_cs;
437         frame.sf_sc.sc_eflags = regs->tf_rflags;
438         frame.sf_sc.sc_esp_at_signal = regs->tf_rsp;
439         frame.sf_sc.sc_ss     = regs->tf_ss;
440         frame.sf_sc.sc_err    = regs->tf_err;
441         frame.sf_sc.sc_cr2    = (u_int32_t)(uintptr_t)ksi->ksi_addr;
442         frame.sf_sc.sc_trapno = bsd_to_linux_trapcode(code);
443
444         frame.sf_extramask[0] = lmask.__mask;
445
446         if (copyout(&frame, fp, sizeof(frame)) != 0) {
447                 /*
448                  * Process has trashed its stack; give it an illegal
449                  * instruction to halt it in its tracks.
450                  */
451                 PROC_LOCK(p);
452                 sigexit(td, SIGILL);
453         }
454
455         /* Build context to run handler in. */
456         regs->tf_rsp = PTROUT(fp);
457         regs->tf_rip = linux32_sigcode;
458         regs->tf_rflags &= ~(PSL_T | PSL_D);
459         regs->tf_cs = _ucode32sel;
460         regs->tf_ss = _udatasel;
461         regs->tf_ds = _udatasel;
462         regs->tf_es = _udatasel;
463         regs->tf_fs = _ufssel;
464         regs->tf_gs = _ugssel;
465         regs->tf_flags = TF_HASSEGS;
466         set_pcb_flags(td->td_pcb, PCB_FULL_IRET);
467         PROC_LOCK(p);
468         mtx_lock(&psp->ps_mtx);
469 }
470
471 /*
472  * System call to cleanup state after a signal
473  * has been taken.  Reset signal mask and
474  * stack state from context left by sendsig (above).
475  * Return to previous pc and psl as specified by
476  * context left by sendsig. Check carefully to
477  * make sure that the user has not modified the
478  * psl to gain improper privileges or to cause
479  * a machine fault.
480  */
481 int
482 linux_sigreturn(struct thread *td, struct linux_sigreturn_args *args)
483 {
484         struct l_sigframe frame;
485         struct trapframe *regs;
486         sigset_t bmask;
487         l_sigset_t lmask;
488         int eflags;
489         ksiginfo_t ksi;
490
491         regs = td->td_frame;
492
493         /*
494          * The trampoline code hands us the sigframe.
495          * It is unsafe to keep track of it ourselves, in the event that a
496          * program jumps out of a signal handler.
497          */
498         if (copyin(args->sfp, &frame, sizeof(frame)) != 0)
499                 return (EFAULT);
500
501         /* Check for security violations. */
502 #define EFLAGS_SECURE(ef, oef)  ((((ef) ^ (oef)) & ~PSL_USERCHANGE) == 0)
503         eflags = frame.sf_sc.sc_eflags;
504         if (!EFLAGS_SECURE(eflags, regs->tf_rflags))
505                 return(EINVAL);
506
507         /*
508          * Don't allow users to load a valid privileged %cs.  Let the
509          * hardware check for invalid selectors, excess privilege in
510          * other selectors, invalid %eip's and invalid %esp's.
511          */
512 #define CS_SECURE(cs)   (ISPL(cs) == SEL_UPL)
513         if (!CS_SECURE(frame.sf_sc.sc_cs)) {
514                 ksiginfo_init_trap(&ksi);
515                 ksi.ksi_signo = SIGBUS;
516                 ksi.ksi_code = BUS_OBJERR;
517                 ksi.ksi_trapno = T_PROTFLT;
518                 ksi.ksi_addr = (void *)regs->tf_rip;
519                 trapsignal(td, &ksi);
520                 return(EINVAL);
521         }
522
523         lmask.__mask = frame.sf_sc.sc_mask;
524         lmask.__mask = frame.sf_extramask[0];
525         linux_to_bsd_sigset(&lmask, &bmask);
526         kern_sigprocmask(td, SIG_SETMASK, &bmask, NULL, 0);
527
528         /* Restore signal context. */
529         regs->tf_rdi    = frame.sf_sc.sc_edi;
530         regs->tf_rsi    = frame.sf_sc.sc_esi;
531         regs->tf_rbp    = frame.sf_sc.sc_ebp;
532         regs->tf_rbx    = frame.sf_sc.sc_ebx;
533         regs->tf_rdx    = frame.sf_sc.sc_edx;
534         regs->tf_rcx    = frame.sf_sc.sc_ecx;
535         regs->tf_rax    = frame.sf_sc.sc_eax;
536         regs->tf_rip    = frame.sf_sc.sc_eip;
537         regs->tf_cs     = frame.sf_sc.sc_cs;
538         regs->tf_ds     = frame.sf_sc.sc_ds;
539         regs->tf_es     = frame.sf_sc.sc_es;
540         regs->tf_fs     = frame.sf_sc.sc_fs;
541         regs->tf_gs     = frame.sf_sc.sc_gs;
542         regs->tf_rflags = eflags;
543         regs->tf_rsp    = frame.sf_sc.sc_esp_at_signal;
544         regs->tf_ss     = frame.sf_sc.sc_ss;
545         set_pcb_flags(td->td_pcb, PCB_FULL_IRET);
546
547         return (EJUSTRETURN);
548 }
549
550 /*
551  * System call to cleanup state after a signal
552  * has been taken.  Reset signal mask and
553  * stack state from context left by rt_sendsig (above).
554  * Return to previous pc and psl as specified by
555  * context left by sendsig. Check carefully to
556  * make sure that the user has not modified the
557  * psl to gain improper privileges or to cause
558  * a machine fault.
559  */
560 int
561 linux_rt_sigreturn(struct thread *td, struct linux_rt_sigreturn_args *args)
562 {
563         struct l_ucontext uc;
564         struct l_sigcontext *context;
565         sigset_t bmask;
566         l_stack_t *lss;
567         stack_t ss;
568         struct trapframe *regs;
569         int eflags;
570         ksiginfo_t ksi;
571
572         regs = td->td_frame;
573
574         /*
575          * The trampoline code hands us the ucontext.
576          * It is unsafe to keep track of it ourselves, in the event that a
577          * program jumps out of a signal handler.
578          */
579         if (copyin(args->ucp, &uc, sizeof(uc)) != 0)
580                 return (EFAULT);
581
582         context = &uc.uc_mcontext;
583
584         /* Check for security violations. */
585 #define EFLAGS_SECURE(ef, oef)  ((((ef) ^ (oef)) & ~PSL_USERCHANGE) == 0)
586         eflags = context->sc_eflags;
587         if (!EFLAGS_SECURE(eflags, regs->tf_rflags))
588                 return(EINVAL);
589
590         /*
591          * Don't allow users to load a valid privileged %cs.  Let the
592          * hardware check for invalid selectors, excess privilege in
593          * other selectors, invalid %eip's and invalid %esp's.
594          */
595 #define CS_SECURE(cs)   (ISPL(cs) == SEL_UPL)
596         if (!CS_SECURE(context->sc_cs)) {
597                 ksiginfo_init_trap(&ksi);
598                 ksi.ksi_signo = SIGBUS;
599                 ksi.ksi_code = BUS_OBJERR;
600                 ksi.ksi_trapno = T_PROTFLT;
601                 ksi.ksi_addr = (void *)regs->tf_rip;
602                 trapsignal(td, &ksi);
603                 return(EINVAL);
604         }
605
606         linux_to_bsd_sigset(&uc.uc_sigmask, &bmask);
607         kern_sigprocmask(td, SIG_SETMASK, &bmask, NULL, 0);
608
609         /*
610          * Restore signal context
611          */
612         regs->tf_gs     = context->sc_gs;
613         regs->tf_fs     = context->sc_fs;
614         regs->tf_es     = context->sc_es;
615         regs->tf_ds     = context->sc_ds;
616         regs->tf_rdi    = context->sc_edi;
617         regs->tf_rsi    = context->sc_esi;
618         regs->tf_rbp    = context->sc_ebp;
619         regs->tf_rbx    = context->sc_ebx;
620         regs->tf_rdx    = context->sc_edx;
621         regs->tf_rcx    = context->sc_ecx;
622         regs->tf_rax    = context->sc_eax;
623         regs->tf_rip    = context->sc_eip;
624         regs->tf_cs     = context->sc_cs;
625         regs->tf_rflags = eflags;
626         regs->tf_rsp    = context->sc_esp_at_signal;
627         regs->tf_ss     = context->sc_ss;
628         set_pcb_flags(td->td_pcb, PCB_FULL_IRET);
629
630         /*
631          * call sigaltstack & ignore results..
632          */
633         lss = &uc.uc_stack;
634         ss.ss_sp = PTRIN(lss->ss_sp);
635         ss.ss_size = lss->ss_size;
636         ss.ss_flags = linux_to_bsd_sigaltstack(lss->ss_flags);
637
638         (void)kern_sigaltstack(td, &ss, NULL);
639
640         return (EJUSTRETURN);
641 }
642
643 static int
644 linux32_fetch_syscall_args(struct thread *td)
645 {
646         struct proc *p;
647         struct trapframe *frame;
648         struct syscall_args *sa;
649
650         p = td->td_proc;
651         frame = td->td_frame;
652         sa = &td->td_sa;
653
654         sa->args[0] = frame->tf_rbx;
655         sa->args[1] = frame->tf_rcx;
656         sa->args[2] = frame->tf_rdx;
657         sa->args[3] = frame->tf_rsi;
658         sa->args[4] = frame->tf_rdi;
659         sa->args[5] = frame->tf_rbp;    /* Unconfirmed */
660         sa->code = frame->tf_rax;
661
662         if (sa->code >= p->p_sysent->sv_size)
663                 /* nosys */
664                 sa->callp = &p->p_sysent->sv_table[p->p_sysent->sv_size - 1];
665         else
666                 sa->callp = &p->p_sysent->sv_table[sa->code];
667         sa->narg = sa->callp->sy_narg;
668
669         td->td_retval[0] = 0;
670         td->td_retval[1] = frame->tf_rdx;
671
672         return (0);
673 }
674
675 /*
676  * Clear registers on exec
677  * XXX copied from ia32_signal.c.
678  */
679 static void
680 linux_exec_setregs(struct thread *td, struct image_params *imgp, u_long stack)
681 {
682         struct trapframe *regs = td->td_frame;
683         struct pcb *pcb = td->td_pcb;
684         register_t saved_rflags;
685
686         regs = td->td_frame;
687         pcb = td->td_pcb;
688
689         if (td->td_proc->p_md.md_ldt != NULL)
690                 user_ldt_free(td);
691
692         critical_enter();
693         wrmsr(MSR_FSBASE, 0);
694         wrmsr(MSR_KGSBASE, 0);  /* User value while we're in the kernel */
695         pcb->pcb_fsbase = 0;
696         pcb->pcb_gsbase = 0;
697         critical_exit();
698         pcb->pcb_initial_fpucw = __LINUX_NPXCW__;
699
700         saved_rflags = regs->tf_rflags & PSL_T;
701         bzero((char *)regs, sizeof(struct trapframe));
702         regs->tf_rip = imgp->entry_addr;
703         regs->tf_rsp = stack;
704         regs->tf_rflags = PSL_USER | saved_rflags;
705         regs->tf_gs = _ugssel;
706         regs->tf_fs = _ufssel;
707         regs->tf_es = _udatasel;
708         regs->tf_ds = _udatasel;
709         regs->tf_ss = _udatasel;
710         regs->tf_flags = TF_HASSEGS;
711         regs->tf_cs = _ucode32sel;
712         regs->tf_rbx = imgp->ps_strings;
713
714         fpstate_drop(td);
715
716         /* Do full restore on return so that we can change to a different %cs */
717         set_pcb_flags(pcb, PCB_32BIT | PCB_FULL_IRET);
718 }
719
720 /*
721  * XXX copied from ia32_sysvec.c.
722  */
723 static int
724 linux_copyout_strings(struct image_params *imgp, register_t **stack_base)
725 {
726         int argc, envc, error;
727         u_int32_t *vectp;
728         char *stringp, *destp;
729         struct linux32_ps_strings *arginfo;
730         char canary[LINUX_AT_RANDOM_LEN];
731         size_t execpath_len;
732
733         /* Calculate string base and vector table pointers. */
734         if (imgp->execpath != NULL && imgp->auxargs != NULL)
735                 execpath_len = strlen(imgp->execpath) + 1;
736         else
737                 execpath_len = 0;
738
739         arginfo = (struct linux32_ps_strings *)LINUX32_PS_STRINGS;
740         destp = (caddr_t)arginfo - SPARE_USRSPACE -
741             roundup(sizeof(canary), sizeof(char *)) -
742             roundup(execpath_len, sizeof(char *)) -
743             roundup(ARG_MAX - imgp->args->stringspace, sizeof(char *));
744
745         if (execpath_len != 0) {
746                 imgp->execpathp = (uintptr_t)arginfo - execpath_len;
747                 error = copyout(imgp->execpath, (void *)imgp->execpathp,
748                     execpath_len);
749                 if (error != 0)
750                         return (error);
751         }
752
753         /* Prepare the canary for SSP. */
754         arc4rand(canary, sizeof(canary), 0);
755         imgp->canary = (uintptr_t)arginfo -
756             roundup(execpath_len, sizeof(char *)) -
757             roundup(sizeof(canary), sizeof(char *));
758         error = copyout(canary, (void *)imgp->canary, sizeof(canary));
759         if (error != 0)
760                 return (error);
761
762         vectp = (uint32_t *)destp;
763         if (imgp->auxargs) {
764                 error = imgp->sysent->sv_copyout_auxargs(imgp,
765                     (u_long *)&vectp);
766                 if (error != 0)
767                         return (error);
768         }
769
770         /*
771          * Allocate room for the argv[] and env vectors including the
772          * terminating NULL pointers.
773          */
774         vectp -= imgp->args->argc + 1 + imgp->args->envc + 1;
775
776         /* vectp also becomes our initial stack base. */
777         *stack_base = (register_t *)vectp;
778
779         stringp = imgp->args->begin_argv;
780         argc = imgp->args->argc;
781         envc = imgp->args->envc;
782         /* Copy out strings - arguments and environment. */
783         error = copyout(stringp, destp, ARG_MAX - imgp->args->stringspace);
784         if (error != 0)
785                 return (error);
786
787         /* Fill in "ps_strings" struct for ps, w, etc. */
788         if (suword32(&arginfo->ps_argvstr, (uint32_t)(intptr_t)vectp) != 0 ||
789             suword32(&arginfo->ps_nargvstr, argc) != 0)
790                 return (EFAULT);
791
792         /* Fill in argument portion of vector table. */
793         for (; argc > 0; --argc) {
794                 if (suword32(vectp++, (uint32_t)(intptr_t)destp) != 0)
795                         return (EFAULT);
796                 while (*stringp++ != 0)
797                         destp++;
798                 destp++;
799         }
800
801         /* A null vector table pointer separates the argp's from the envp's. */
802         if (suword32(vectp++, 0) != 0)
803                 return (EFAULT);
804
805         if (suword32(&arginfo->ps_envstr, (uint32_t)(intptr_t)vectp) != 0 ||
806             suword32(&arginfo->ps_nenvstr, envc) != 0)
807                 return (EFAULT);
808
809         /* Fill in environment portion of vector table. */
810         for (; envc > 0; --envc) {
811                 if (suword32(vectp++, (uint32_t)(intptr_t)destp) != 0)
812                         return (EFAULT);
813                 while (*stringp++ != 0)
814                         destp++;
815                 destp++;
816         }
817
818         /* The end of the vector table is a null pointer. */
819         if (suword32(vectp, 0) != 0)
820                 return (EFAULT);
821
822         return (0);
823 }
824
825 static SYSCTL_NODE(_compat, OID_AUTO, linux32, CTLFLAG_RW, 0,
826     "32-bit Linux emulation");
827
828 static u_long   linux32_maxdsiz = LINUX32_MAXDSIZ;
829 SYSCTL_ULONG(_compat_linux32, OID_AUTO, maxdsiz, CTLFLAG_RW,
830     &linux32_maxdsiz, 0, "");
831 static u_long   linux32_maxssiz = LINUX32_MAXSSIZ;
832 SYSCTL_ULONG(_compat_linux32, OID_AUTO, maxssiz, CTLFLAG_RW,
833     &linux32_maxssiz, 0, "");
834 static u_long   linux32_maxvmem = LINUX32_MAXVMEM;
835 SYSCTL_ULONG(_compat_linux32, OID_AUTO, maxvmem, CTLFLAG_RW,
836     &linux32_maxvmem, 0, "");
837
838 static void
839 linux32_fixlimit(struct rlimit *rl, int which)
840 {
841
842         switch (which) {
843         case RLIMIT_DATA:
844                 if (linux32_maxdsiz != 0) {
845                         if (rl->rlim_cur > linux32_maxdsiz)
846                                 rl->rlim_cur = linux32_maxdsiz;
847                         if (rl->rlim_max > linux32_maxdsiz)
848                                 rl->rlim_max = linux32_maxdsiz;
849                 }
850                 break;
851         case RLIMIT_STACK:
852                 if (linux32_maxssiz != 0) {
853                         if (rl->rlim_cur > linux32_maxssiz)
854                                 rl->rlim_cur = linux32_maxssiz;
855                         if (rl->rlim_max > linux32_maxssiz)
856                                 rl->rlim_max = linux32_maxssiz;
857                 }
858                 break;
859         case RLIMIT_VMEM:
860                 if (linux32_maxvmem != 0) {
861                         if (rl->rlim_cur > linux32_maxvmem)
862                                 rl->rlim_cur = linux32_maxvmem;
863                         if (rl->rlim_max > linux32_maxvmem)
864                                 rl->rlim_max = linux32_maxvmem;
865                 }
866                 break;
867         }
868 }
869
870 struct sysentvec elf_linux_sysvec = {
871         .sv_size        = LINUX32_SYS_MAXSYSCALL,
872         .sv_table       = linux32_sysent,
873         .sv_errsize     = ELAST + 1,
874         .sv_errtbl      = linux_errtbl,
875         .sv_transtrap   = linux_translate_traps,
876         .sv_fixup       = linux_fixup_elf,
877         .sv_sendsig     = linux_sendsig,
878         .sv_sigcode     = &_binary_linux32_locore_o_start,
879         .sv_szsigcode   = &linux_szsigcode,
880         .sv_name        = "Linux ELF32",
881         .sv_coredump    = elf32_coredump,
882         .sv_imgact_try  = linux_exec_imgact_try,
883         .sv_minsigstksz = LINUX_MINSIGSTKSZ,
884         .sv_minuser     = VM_MIN_ADDRESS,
885         .sv_maxuser     = LINUX32_MAXUSER,
886         .sv_usrstack    = LINUX32_USRSTACK,
887         .sv_psstrings   = LINUX32_PS_STRINGS,
888         .sv_stackprot   = VM_PROT_ALL,
889         .sv_copyout_auxargs = linux_copyout_auxargs,
890         .sv_copyout_strings = linux_copyout_strings,
891         .sv_setregs     = linux_exec_setregs,
892         .sv_fixlimit    = linux32_fixlimit,
893         .sv_maxssiz     = &linux32_maxssiz,
894         .sv_flags       = SV_ABI_LINUX | SV_ILP32 | SV_IA32 | SV_SHP,
895         .sv_set_syscall_retval = cpu_set_syscall_retval,
896         .sv_fetch_syscall_args = linux32_fetch_syscall_args,
897         .sv_syscallnames = NULL,
898         .sv_shared_page_base = LINUX32_SHAREDPAGE,
899         .sv_shared_page_len = PAGE_SIZE,
900         .sv_schedtail   = linux_schedtail,
901         .sv_thread_detach = linux_thread_detach,
902         .sv_trap        = NULL,
903 };
904
905 static void
906 linux_vdso_install(void *param)
907 {
908
909         linux_szsigcode = (&_binary_linux32_locore_o_end -
910             &_binary_linux32_locore_o_start);
911
912         if (linux_szsigcode > elf_linux_sysvec.sv_shared_page_len)
913                 panic("Linux invalid vdso size\n");
914
915         __elfN(linux_vdso_fixup)(&elf_linux_sysvec);
916
917         linux_shared_page_obj = __elfN(linux_shared_page_init)
918             (&linux_shared_page_mapping);
919
920         __elfN(linux_vdso_reloc)(&elf_linux_sysvec);
921
922         bcopy(elf_linux_sysvec.sv_sigcode, linux_shared_page_mapping,
923             linux_szsigcode);
924         elf_linux_sysvec.sv_shared_page_obj = linux_shared_page_obj;
925
926         linux_kplatform = linux_shared_page_mapping +
927             (linux_platform - (caddr_t)elf_linux_sysvec.sv_shared_page_base);
928 }
929 SYSINIT(elf_linux_vdso_init, SI_SUB_EXEC, SI_ORDER_ANY,
930     linux_vdso_install, NULL);
931
932 static void
933 linux_vdso_deinstall(void *param)
934 {
935
936         __elfN(linux_shared_page_fini)(linux_shared_page_obj);
937 }
938 SYSUNINIT(elf_linux_vdso_uninit, SI_SUB_EXEC, SI_ORDER_FIRST,
939     linux_vdso_deinstall, NULL);
940
941 static char GNU_ABI_VENDOR[] = "GNU";
942 static int GNULINUX_ABI_DESC = 0;
943
944 static bool
945 linux32_trans_osrel(const Elf_Note *note, int32_t *osrel)
946 {
947         const Elf32_Word *desc;
948         uintptr_t p;
949
950         p = (uintptr_t)(note + 1);
951         p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
952
953         desc = (const Elf32_Word *)p;
954         if (desc[0] != GNULINUX_ABI_DESC)
955                 return (false);
956
957         /*
958          * For Linux we encode osrel using the Linux convention of
959          *      (version << 16) | (major << 8) | (minor)
960          * See macro in linux_mib.h
961          */
962         *osrel = LINUX_KERNVER(desc[1], desc[2], desc[3]);
963
964         return (true);
965 }
966
967 static Elf_Brandnote linux32_brandnote = {
968         .hdr.n_namesz   = sizeof(GNU_ABI_VENDOR),
969         .hdr.n_descsz   = 16,   /* XXX at least 16 */
970         .hdr.n_type     = 1,
971         .vendor         = GNU_ABI_VENDOR,
972         .flags          = BN_TRANSLATE_OSREL,
973         .trans_osrel    = linux32_trans_osrel
974 };
975
976 static Elf32_Brandinfo linux_brand = {
977         .brand          = ELFOSABI_LINUX,
978         .machine        = EM_386,
979         .compat_3_brand = "Linux",
980         .emul_path      = "/compat/linux",
981         .interp_path    = "/lib/ld-linux.so.1",
982         .sysvec         = &elf_linux_sysvec,
983         .interp_newpath = NULL,
984         .brand_note     = &linux32_brandnote,
985         .flags          = BI_CAN_EXEC_DYN | BI_BRAND_NOTE
986 };
987
988 static Elf32_Brandinfo linux_glibc2brand = {
989         .brand          = ELFOSABI_LINUX,
990         .machine        = EM_386,
991         .compat_3_brand = "Linux",
992         .emul_path      = "/compat/linux",
993         .interp_path    = "/lib/ld-linux.so.2",
994         .sysvec         = &elf_linux_sysvec,
995         .interp_newpath = NULL,
996         .brand_note     = &linux32_brandnote,
997         .flags          = BI_CAN_EXEC_DYN | BI_BRAND_NOTE
998 };
999
1000 static Elf32_Brandinfo linux_muslbrand = {
1001         .brand          = ELFOSABI_LINUX,
1002         .machine        = EM_386,
1003         .compat_3_brand = "Linux",
1004         .emul_path      = "/compat/linux",
1005         .interp_path    = "/lib/ld-musl-i386.so.1",
1006         .sysvec         = &elf_linux_sysvec,
1007         .interp_newpath = NULL,
1008         .brand_note     = &linux32_brandnote,
1009         .flags          = BI_CAN_EXEC_DYN | BI_BRAND_NOTE
1010 };
1011
1012 Elf32_Brandinfo *linux_brandlist[] = {
1013         &linux_brand,
1014         &linux_glibc2brand,
1015         &linux_muslbrand,
1016         NULL
1017 };
1018
1019 static int
1020 linux_elf_modevent(module_t mod, int type, void *data)
1021 {
1022         Elf32_Brandinfo **brandinfo;
1023         int error;
1024         struct linux_ioctl_handler **lihp;
1025
1026         error = 0;
1027
1028         switch(type) {
1029         case MOD_LOAD:
1030                 for (brandinfo = &linux_brandlist[0]; *brandinfo != NULL;
1031                      ++brandinfo)
1032                         if (elf32_insert_brand_entry(*brandinfo) < 0)
1033                                 error = EINVAL;
1034                 if (error == 0) {
1035                         SET_FOREACH(lihp, linux_ioctl_handler_set)
1036                                 linux32_ioctl_register_handler(*lihp);
1037                         stclohz = (stathz ? stathz : hz);
1038                         if (bootverbose)
1039                                 printf("Linux ELF exec handler installed\n");
1040                 } else
1041                         printf("cannot insert Linux ELF brand handler\n");
1042                 break;
1043         case MOD_UNLOAD:
1044                 for (brandinfo = &linux_brandlist[0]; *brandinfo != NULL;
1045                      ++brandinfo)
1046                         if (elf32_brand_inuse(*brandinfo))
1047                                 error = EBUSY;
1048                 if (error == 0) {
1049                         for (brandinfo = &linux_brandlist[0];
1050                              *brandinfo != NULL; ++brandinfo)
1051                                 if (elf32_remove_brand_entry(*brandinfo) < 0)
1052                                         error = EINVAL;
1053                 }
1054                 if (error == 0) {
1055                         SET_FOREACH(lihp, linux_ioctl_handler_set)
1056                                 linux32_ioctl_unregister_handler(*lihp);
1057                         if (bootverbose)
1058                                 printf("Linux ELF exec handler removed\n");
1059                 } else
1060                         printf("Could not deinstall ELF interpreter entry\n");
1061                 break;
1062         default:
1063                 return (EOPNOTSUPP);
1064         }
1065         return (error);
1066 }
1067
1068 static moduledata_t linux_elf_mod = {
1069         "linuxelf",
1070         linux_elf_modevent,
1071         0
1072 };
1073
1074 DECLARE_MODULE_TIED(linuxelf, linux_elf_mod, SI_SUB_EXEC, SI_ORDER_ANY);
1075 MODULE_DEPEND(linuxelf, linux_common, 1, 1, 1);
1076 FEATURE(linux, "Linux 32bit support");