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