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