xref: /freebsd/sys/amd64/linux32/linux32_sysvec.c (revision 4e8d558c)
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 <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37 
38 #ifndef COMPAT_FREEBSD32
39 #error "Unable to compile Linux-emulator due to missing COMPAT_FREEBSD32 option!"
40 #endif
41 
42 #define	__ELF_WORD_SIZE	32
43 
44 #include <sys/param.h>
45 #include <sys/exec.h>
46 #include <sys/fcntl.h>
47 #include <sys/imgact.h>
48 #include <sys/imgact_elf.h>
49 #include <sys/kernel.h>
50 #include <sys/lock.h>
51 #include <sys/malloc.h>
52 #include <sys/module.h>
53 #include <sys/mutex.h>
54 #include <sys/proc.h>
55 #include <sys/stddef.h>
56 #include <sys/syscallsubr.h>
57 #include <sys/sysctl.h>
58 #include <sys/sysent.h>
59 
60 #include <vm/pmap.h>
61 #include <vm/vm.h>
62 #include <vm/vm_map.h>
63 #include <vm/vm_page.h>
64 
65 #include <machine/cpu.h>
66 #include <machine/md_var.h>
67 #include <machine/pcb.h>
68 #include <machine/specialreg.h>
69 #include <machine/trap.h>
70 
71 #include <x86/linux/linux_x86.h>
72 #include <amd64/linux32/linux.h>
73 #include <amd64/linux32/linux32_proto.h>
74 #include <compat/linux/linux_elf.h>
75 #include <compat/linux/linux_emul.h>
76 #include <compat/linux/linux_fork.h>
77 #include <compat/linux/linux_ioctl.h>
78 #include <compat/linux/linux_mib.h>
79 #include <compat/linux/linux_misc.h>
80 #include <compat/linux/linux_signal.h>
81 #include <compat/linux/linux_util.h>
82 #include <compat/linux/linux_vdso.h>
83 
84 #include <x86/linux/linux_x86_sigframe.h>
85 
86 MODULE_VERSION(linux, 1);
87 
88 #define	LINUX32_MAXUSER		((1ul << 32) - PAGE_SIZE)
89 #define	LINUX32_VDSOPAGE_SIZE	PAGE_SIZE * 2
90 #define	LINUX32_VDSOPAGE	(LINUX32_MAXUSER - LINUX32_VDSOPAGE_SIZE)
91 #define	LINUX32_SHAREDPAGE	(LINUX32_VDSOPAGE - PAGE_SIZE)
92 				/*
93 				 * PAGE_SIZE - the size
94 				 * of the native SHAREDPAGE
95 				 */
96 #define	LINUX32_USRSTACK	LINUX32_SHAREDPAGE
97 
98 static int linux_szsigcode;
99 static vm_object_t linux_vdso_obj;
100 static char *linux_vdso_mapping;
101 extern char _binary_linux32_vdso_so_o_start;
102 extern char _binary_linux32_vdso_so_o_end;
103 static vm_offset_t linux_vdso_base;
104 
105 extern struct sysent linux32_sysent[LINUX32_SYS_MAXSYSCALL];
106 extern const char *linux32_syscallnames[];
107 
108 SET_DECLARE(linux_ioctl_handler_set, struct linux_ioctl_handler);
109 
110 static int	linux_copyout_strings(struct image_params *imgp,
111 		    uintptr_t *stack_base);
112 static void     linux_sendsig(sig_t catcher, ksiginfo_t *ksi, sigset_t *mask);
113 static void	linux_exec_setregs(struct thread *td,
114 				   struct image_params *imgp, uintptr_t stack);
115 static void	linux_exec_sysvec_init(void *param);
116 static int	linux_on_exec_vmspace(struct proc *p,
117 		    struct image_params *imgp);
118 static void	linux32_fixlimit(struct rlimit *rl, int which);
119 static void	linux_vdso_install(const void *param);
120 static void	linux_vdso_deinstall(const void *param);
121 static void	linux_vdso_reloc(char *mapping, Elf_Addr offset);
122 static void	linux32_set_fork_retval(struct thread *td);
123 static void	linux32_set_syscall_retval(struct thread *td, int error);
124 
125 struct linux32_ps_strings {
126 	u_int32_t ps_argvstr;	/* first of 0 or more argument strings */
127 	u_int ps_nargvstr;	/* the number of argument strings */
128 	u_int32_t ps_envstr;	/* first of 0 or more environment strings */
129 	u_int ps_nenvstr;	/* the number of environment strings */
130 };
131 #define	LINUX32_PS_STRINGS	(LINUX32_USRSTACK - \
132 				    sizeof(struct linux32_ps_strings))
133 
134 LINUX_VDSO_SYM_INTPTR(__kernel_vsyscall);
135 LINUX_VDSO_SYM_INTPTR(linux32_vdso_sigcode);
136 LINUX_VDSO_SYM_INTPTR(linux32_vdso_rt_sigcode);
137 LINUX_VDSO_SYM_INTPTR(kern_timekeep_base);
138 LINUX_VDSO_SYM_INTPTR(kern_tsc_selector);
139 LINUX_VDSO_SYM_INTPTR(kern_cpu_selector);
140 LINUX_VDSO_SYM_CHAR(linux_platform);
141 
142 void
143 linux32_arch_copyout_auxargs(struct image_params *imgp, Elf_Auxinfo **pos)
144 {
145 
146 	AUXARGS_ENTRY((*pos), LINUX_AT_SYSINFO, __kernel_vsyscall);
147 	AUXARGS_ENTRY((*pos), LINUX_AT_SYSINFO_EHDR, linux_vdso_base);
148 	AUXARGS_ENTRY((*pos), LINUX_AT_HWCAP, cpu_feature);
149 	AUXARGS_ENTRY((*pos), LINUX_AT_HWCAP2, 0);
150 	AUXARGS_ENTRY((*pos), LINUX_AT_PLATFORM, PTROUT(linux_platform));
151 }
152 
153 static void
154 linux_rt_sendsig(sig_t catcher, ksiginfo_t *ksi, sigset_t *mask)
155 {
156 	struct thread *td = curthread;
157 	struct proc *p = td->td_proc;
158 	struct sigacts *psp;
159 	struct trapframe *regs;
160 	struct l_rt_sigframe *fp, frame;
161 	int oonstack;
162 	int sig;
163 	int code;
164 
165 	sig = linux_translate_traps(ksi->ksi_signo, ksi->ksi_trapno);
166 	code = ksi->ksi_code;
167 	PROC_LOCK_ASSERT(p, MA_OWNED);
168 	psp = p->p_sigacts;
169 	mtx_assert(&psp->ps_mtx, MA_OWNED);
170 	regs = td->td_frame;
171 	oonstack = sigonstack(regs->tf_rsp);
172 
173 	/* Allocate space for the signal handler context. */
174 	if ((td->td_pflags & TDP_ALTSTACK) && !oonstack &&
175 	    SIGISMEMBER(psp->ps_sigonstack, sig)) {
176 		fp = (struct l_rt_sigframe *)((uintptr_t)td->td_sigstk.ss_sp +
177 		    td->td_sigstk.ss_size - sizeof(struct l_rt_sigframe));
178 	} else
179 		fp = (struct l_rt_sigframe *)regs->tf_rsp - 1;
180 	mtx_unlock(&psp->ps_mtx);
181 
182 	/* Build the argument list for the signal handler. */
183 	sig = bsd_to_linux_signal(sig);
184 
185 	bzero(&frame, sizeof(frame));
186 
187 	frame.sf_sig = sig;
188 	frame.sf_siginfo = PTROUT(&fp->sf_si);
189 	frame.sf_ucontext = PTROUT(&fp->sf_uc);
190 
191 	/* Fill in POSIX parts. */
192 	siginfo_to_lsiginfo(&ksi->ksi_info, &frame.sf_si, sig);
193 
194 	/*
195 	 * Build the signal context to be used by sigreturn and libgcc unwind.
196 	 */
197 	frame.sf_uc.uc_stack.ss_sp = PTROUT(td->td_sigstk.ss_sp);
198 	frame.sf_uc.uc_stack.ss_size = td->td_sigstk.ss_size;
199 	frame.sf_uc.uc_stack.ss_flags = (td->td_pflags & TDP_ALTSTACK)
200 	    ? ((oonstack) ? LINUX_SS_ONSTACK : 0) : LINUX_SS_DISABLE;
201 	PROC_UNLOCK(p);
202 
203 	bsd_to_linux_sigset(mask, &frame.sf_uc.uc_sigmask);
204 
205 	frame.sf_uc.uc_mcontext.sc_mask   = frame.sf_uc.uc_sigmask.__mask;
206 	frame.sf_uc.uc_mcontext.sc_edi    = regs->tf_rdi;
207 	frame.sf_uc.uc_mcontext.sc_esi    = regs->tf_rsi;
208 	frame.sf_uc.uc_mcontext.sc_ebp    = regs->tf_rbp;
209 	frame.sf_uc.uc_mcontext.sc_ebx    = regs->tf_rbx;
210 	frame.sf_uc.uc_mcontext.sc_esp    = regs->tf_rsp;
211 	frame.sf_uc.uc_mcontext.sc_edx    = regs->tf_rdx;
212 	frame.sf_uc.uc_mcontext.sc_ecx    = regs->tf_rcx;
213 	frame.sf_uc.uc_mcontext.sc_eax    = regs->tf_rax;
214 	frame.sf_uc.uc_mcontext.sc_eip    = regs->tf_rip;
215 	frame.sf_uc.uc_mcontext.sc_cs     = regs->tf_cs;
216 	frame.sf_uc.uc_mcontext.sc_gs     = regs->tf_gs;
217 	frame.sf_uc.uc_mcontext.sc_fs     = regs->tf_fs;
218 	frame.sf_uc.uc_mcontext.sc_es     = regs->tf_es;
219 	frame.sf_uc.uc_mcontext.sc_ds     = regs->tf_ds;
220 	frame.sf_uc.uc_mcontext.sc_eflags = regs->tf_rflags;
221 	frame.sf_uc.uc_mcontext.sc_esp_at_signal = regs->tf_rsp;
222 	frame.sf_uc.uc_mcontext.sc_ss     = regs->tf_ss;
223 	frame.sf_uc.uc_mcontext.sc_err    = regs->tf_err;
224 	frame.sf_uc.uc_mcontext.sc_cr2    = (u_int32_t)(uintptr_t)ksi->ksi_addr;
225 	frame.sf_uc.uc_mcontext.sc_trapno = bsd_to_linux_trapcode(code);
226 
227 	if (copyout(&frame, fp, sizeof(frame)) != 0) {
228 		/*
229 		 * Process has trashed its stack; give it an illegal
230 		 * instruction to halt it in its tracks.
231 		 */
232 		PROC_LOCK(p);
233 		sigexit(td, SIGILL);
234 	}
235 
236 	/* Build context to run handler in. */
237 	regs->tf_rsp = PTROUT(fp);
238 	regs->tf_rip = linux32_vdso_rt_sigcode;
239 	regs->tf_rdi = PTROUT(catcher);
240 	regs->tf_rflags &= ~(PSL_T | PSL_D);
241 	regs->tf_cs = _ucode32sel;
242 	regs->tf_ss = _udatasel;
243 	regs->tf_ds = _udatasel;
244 	regs->tf_es = _udatasel;
245 	regs->tf_fs = _ufssel;
246 	regs->tf_gs = _ugssel;
247 	regs->tf_flags = TF_HASSEGS;
248 	set_pcb_flags(td->td_pcb, PCB_FULL_IRET);
249 	PROC_LOCK(p);
250 	mtx_lock(&psp->ps_mtx);
251 }
252 
253 /*
254  * Send an interrupt to process.
255  *
256  * Stack is set up to allow sigcode stored
257  * in u. to call routine, followed by kcall
258  * to sigreturn routine below.  After sigreturn
259  * resets the signal mask, the stack, and the
260  * frame pointer, it returns to the user
261  * specified pc, psl.
262  */
263 static void
264 linux_sendsig(sig_t catcher, ksiginfo_t *ksi, sigset_t *mask)
265 {
266 	struct thread *td = curthread;
267 	struct proc *p = td->td_proc;
268 	struct sigacts *psp;
269 	struct trapframe *regs;
270 	struct l_sigframe *fp, frame;
271 	l_sigset_t lmask;
272 	int oonstack;
273 	int sig, code;
274 
275 	sig = linux_translate_traps(ksi->ksi_signo, ksi->ksi_trapno);
276 	code = ksi->ksi_code;
277 	PROC_LOCK_ASSERT(p, MA_OWNED);
278 	psp = p->p_sigacts;
279 	mtx_assert(&psp->ps_mtx, MA_OWNED);
280 	if (SIGISMEMBER(psp->ps_siginfo, sig)) {
281 		/* Signal handler installed with SA_SIGINFO. */
282 		linux_rt_sendsig(catcher, ksi, mask);
283 		return;
284 	}
285 
286 	regs = td->td_frame;
287 	oonstack = sigonstack(regs->tf_rsp);
288 
289 	/* Allocate space for the signal handler context. */
290 	if ((td->td_pflags & TDP_ALTSTACK) && !oonstack &&
291 	    SIGISMEMBER(psp->ps_sigonstack, sig)) {
292 		fp = (struct l_sigframe *)((uintptr_t)td->td_sigstk.ss_sp +
293 		    td->td_sigstk.ss_size - sizeof(struct l_sigframe));
294 	} else
295 		fp = (struct l_sigframe *)regs->tf_rsp - 1;
296 	mtx_unlock(&psp->ps_mtx);
297 	PROC_UNLOCK(p);
298 
299 	/* Build the argument list for the signal handler. */
300 	sig = bsd_to_linux_signal(sig);
301 
302 	bzero(&frame, sizeof(frame));
303 
304 	frame.sf_sig = sig;
305 	frame.sf_sigmask = *mask;
306 	bsd_to_linux_sigset(mask, &lmask);
307 
308 	/* Build the signal context to be used by sigreturn. */
309 	frame.sf_sc.sc_mask   = lmask.__mask;
310 	frame.sf_sc.sc_gs     = regs->tf_gs;
311 	frame.sf_sc.sc_fs     = regs->tf_fs;
312 	frame.sf_sc.sc_es     = regs->tf_es;
313 	frame.sf_sc.sc_ds     = regs->tf_ds;
314 	frame.sf_sc.sc_edi    = regs->tf_rdi;
315 	frame.sf_sc.sc_esi    = regs->tf_rsi;
316 	frame.sf_sc.sc_ebp    = regs->tf_rbp;
317 	frame.sf_sc.sc_ebx    = regs->tf_rbx;
318 	frame.sf_sc.sc_esp    = regs->tf_rsp;
319 	frame.sf_sc.sc_edx    = regs->tf_rdx;
320 	frame.sf_sc.sc_ecx    = regs->tf_rcx;
321 	frame.sf_sc.sc_eax    = regs->tf_rax;
322 	frame.sf_sc.sc_eip    = regs->tf_rip;
323 	frame.sf_sc.sc_cs     = regs->tf_cs;
324 	frame.sf_sc.sc_eflags = regs->tf_rflags;
325 	frame.sf_sc.sc_esp_at_signal = regs->tf_rsp;
326 	frame.sf_sc.sc_ss     = regs->tf_ss;
327 	frame.sf_sc.sc_err    = regs->tf_err;
328 	frame.sf_sc.sc_cr2    = (u_int32_t)(uintptr_t)ksi->ksi_addr;
329 	frame.sf_sc.sc_trapno = bsd_to_linux_trapcode(code);
330 
331 	if (copyout(&frame, fp, sizeof(frame)) != 0) {
332 		/*
333 		 * Process has trashed its stack; give it an illegal
334 		 * instruction to halt it in its tracks.
335 		 */
336 		PROC_LOCK(p);
337 		sigexit(td, SIGILL);
338 	}
339 
340 	/* Build context to run handler in. */
341 	regs->tf_rsp = PTROUT(fp);
342 	regs->tf_rip = linux32_vdso_sigcode;
343 	regs->tf_rdi = PTROUT(catcher);
344 	regs->tf_rflags &= ~(PSL_T | PSL_D);
345 	regs->tf_cs = _ucode32sel;
346 	regs->tf_ss = _udatasel;
347 	regs->tf_ds = _udatasel;
348 	regs->tf_es = _udatasel;
349 	regs->tf_fs = _ufssel;
350 	regs->tf_gs = _ugssel;
351 	regs->tf_flags = TF_HASSEGS;
352 	set_pcb_flags(td->td_pcb, PCB_FULL_IRET);
353 	PROC_LOCK(p);
354 	mtx_lock(&psp->ps_mtx);
355 }
356 
357 /*
358  * System call to cleanup state after a signal
359  * has been taken.  Reset signal mask and
360  * stack state from context left by sendsig (above).
361  * Return to previous pc and psl as specified by
362  * context left by sendsig. Check carefully to
363  * make sure that the user has not modified the
364  * psl to gain improper privileges or to cause
365  * a machine fault.
366  */
367 int
368 linux_sigreturn(struct thread *td, struct linux_sigreturn_args *args)
369 {
370 	struct l_sigframe frame;
371 	struct trapframe *regs;
372 	int eflags;
373 	ksiginfo_t ksi;
374 
375 	regs = td->td_frame;
376 
377 	/*
378 	 * The trampoline code hands us the sigframe.
379 	 * It is unsafe to keep track of it ourselves, in the event that a
380 	 * program jumps out of a signal handler.
381 	 */
382 	if (copyin(args->sfp, &frame, sizeof(frame)) != 0)
383 		return (EFAULT);
384 
385 	/* Check for security violations. */
386 	eflags = frame.sf_sc.sc_eflags;
387 	if (!EFL_SECURE(eflags, regs->tf_rflags))
388 		return(EINVAL);
389 
390 	/*
391 	 * Don't allow users to load a valid privileged %cs.  Let the
392 	 * hardware check for invalid selectors, excess privilege in
393 	 * other selectors, invalid %eip's and invalid %esp's.
394 	 */
395 	if (!CS_SECURE(frame.sf_sc.sc_cs)) {
396 		ksiginfo_init_trap(&ksi);
397 		ksi.ksi_signo = SIGBUS;
398 		ksi.ksi_code = BUS_OBJERR;
399 		ksi.ksi_trapno = T_PROTFLT;
400 		ksi.ksi_addr = (void *)regs->tf_rip;
401 		trapsignal(td, &ksi);
402 		return(EINVAL);
403 	}
404 
405 	kern_sigprocmask(td, SIG_SETMASK, &frame.sf_sigmask, NULL, 0);
406 
407 	/* Restore signal context. */
408 	regs->tf_rdi    = frame.sf_sc.sc_edi;
409 	regs->tf_rsi    = frame.sf_sc.sc_esi;
410 	regs->tf_rbp    = frame.sf_sc.sc_ebp;
411 	regs->tf_rbx    = frame.sf_sc.sc_ebx;
412 	regs->tf_rdx    = frame.sf_sc.sc_edx;
413 	regs->tf_rcx    = frame.sf_sc.sc_ecx;
414 	regs->tf_rax    = frame.sf_sc.sc_eax;
415 	regs->tf_rip    = frame.sf_sc.sc_eip;
416 	regs->tf_cs     = frame.sf_sc.sc_cs;
417 	regs->tf_ds     = frame.sf_sc.sc_ds;
418 	regs->tf_es     = frame.sf_sc.sc_es;
419 	regs->tf_fs     = frame.sf_sc.sc_fs;
420 	regs->tf_gs     = frame.sf_sc.sc_gs;
421 	regs->tf_rflags = eflags;
422 	regs->tf_rsp    = frame.sf_sc.sc_esp_at_signal;
423 	regs->tf_ss     = frame.sf_sc.sc_ss;
424 	set_pcb_flags(td->td_pcb, PCB_FULL_IRET);
425 
426 	return (EJUSTRETURN);
427 }
428 
429 /*
430  * System call to cleanup state after a signal
431  * has been taken.  Reset signal mask and
432  * stack state from context left by rt_sendsig (above).
433  * Return to previous pc and psl as specified by
434  * context left by sendsig. Check carefully to
435  * make sure that the user has not modified the
436  * psl to gain improper privileges or to cause
437  * a machine fault.
438  */
439 int
440 linux_rt_sigreturn(struct thread *td, struct linux_rt_sigreturn_args *args)
441 {
442 	struct l_ucontext uc;
443 	struct l_sigcontext *context;
444 	sigset_t bmask;
445 	l_stack_t *lss;
446 	stack_t ss;
447 	struct trapframe *regs;
448 	int eflags;
449 	ksiginfo_t ksi;
450 
451 	regs = td->td_frame;
452 
453 	/*
454 	 * The trampoline code hands us the ucontext.
455 	 * It is unsafe to keep track of it ourselves, in the event that a
456 	 * program jumps out of a signal handler.
457 	 */
458 	if (copyin(args->ucp, &uc, sizeof(uc)) != 0)
459 		return (EFAULT);
460 
461 	context = &uc.uc_mcontext;
462 
463 	/* Check for security violations. */
464 	eflags = context->sc_eflags;
465 	if (!EFL_SECURE(eflags, regs->tf_rflags))
466 		return(EINVAL);
467 
468 	/*
469 	 * Don't allow users to load a valid privileged %cs.  Let the
470 	 * hardware check for invalid selectors, excess privilege in
471 	 * other selectors, invalid %eip's and invalid %esp's.
472 	 */
473 	if (!CS_SECURE(context->sc_cs)) {
474 		ksiginfo_init_trap(&ksi);
475 		ksi.ksi_signo = SIGBUS;
476 		ksi.ksi_code = BUS_OBJERR;
477 		ksi.ksi_trapno = T_PROTFLT;
478 		ksi.ksi_addr = (void *)regs->tf_rip;
479 		trapsignal(td, &ksi);
480 		return(EINVAL);
481 	}
482 
483 	linux_to_bsd_sigset(&uc.uc_sigmask, &bmask);
484 	kern_sigprocmask(td, SIG_SETMASK, &bmask, NULL, 0);
485 
486 	/*
487 	 * Restore signal context
488 	 */
489 	regs->tf_gs	= context->sc_gs;
490 	regs->tf_fs	= context->sc_fs;
491 	regs->tf_es	= context->sc_es;
492 	regs->tf_ds	= context->sc_ds;
493 	regs->tf_rdi    = context->sc_edi;
494 	regs->tf_rsi    = context->sc_esi;
495 	regs->tf_rbp    = context->sc_ebp;
496 	regs->tf_rbx    = context->sc_ebx;
497 	regs->tf_rdx    = context->sc_edx;
498 	regs->tf_rcx    = context->sc_ecx;
499 	regs->tf_rax    = context->sc_eax;
500 	regs->tf_rip    = context->sc_eip;
501 	regs->tf_cs     = context->sc_cs;
502 	regs->tf_rflags = eflags;
503 	regs->tf_rsp    = context->sc_esp_at_signal;
504 	regs->tf_ss     = context->sc_ss;
505 	set_pcb_flags(td->td_pcb, PCB_FULL_IRET);
506 
507 	/*
508 	 * call sigaltstack & ignore results..
509 	 */
510 	lss = &uc.uc_stack;
511 	ss.ss_sp = PTRIN(lss->ss_sp);
512 	ss.ss_size = lss->ss_size;
513 	ss.ss_flags = linux_to_bsd_sigaltstack(lss->ss_flags);
514 
515 	(void)kern_sigaltstack(td, &ss, NULL);
516 
517 	return (EJUSTRETURN);
518 }
519 
520 static int
521 linux32_fetch_syscall_args(struct thread *td)
522 {
523 	struct proc *p;
524 	struct trapframe *frame;
525 	struct syscall_args *sa;
526 
527 	p = td->td_proc;
528 	frame = td->td_frame;
529 	sa = &td->td_sa;
530 
531 	sa->args[0] = frame->tf_rbx;
532 	sa->args[1] = frame->tf_rcx;
533 	sa->args[2] = frame->tf_rdx;
534 	sa->args[3] = frame->tf_rsi;
535 	sa->args[4] = frame->tf_rdi;
536 	sa->args[5] = frame->tf_rbp;	/* Unconfirmed */
537 	sa->code = frame->tf_rax;
538 	sa->original_code = sa->code;
539 
540 	if (sa->code >= p->p_sysent->sv_size)
541 		/* nosys */
542 		sa->callp = &p->p_sysent->sv_table[p->p_sysent->sv_size - 1];
543 	else
544 		sa->callp = &p->p_sysent->sv_table[sa->code];
545 
546 	td->td_retval[0] = 0;
547 	td->td_retval[1] = frame->tf_rdx;
548 
549 	return (0);
550 }
551 
552 static void
553 linux32_set_syscall_retval(struct thread *td, int error)
554 {
555 	struct trapframe *frame = td->td_frame;
556 
557 	cpu_set_syscall_retval(td, error);
558 
559 	if (__predict_false(error != 0)) {
560 		if (error != ERESTART && error != EJUSTRETURN)
561 			frame->tf_rax = bsd_to_linux_errno(error);
562 	}
563 }
564 
565 static void
566 linux32_set_fork_retval(struct thread *td)
567 {
568 	struct trapframe *frame = td->td_frame;
569 
570 	frame->tf_rax = 0;
571 }
572 
573 /*
574  * Clear registers on exec
575  * XXX copied from ia32_signal.c.
576  */
577 static void
578 linux_exec_setregs(struct thread *td, struct image_params *imgp,
579     uintptr_t stack)
580 {
581 	struct trapframe *regs = td->td_frame;
582 	struct pcb *pcb = td->td_pcb;
583 	register_t saved_rflags;
584 
585 	regs = td->td_frame;
586 	pcb = td->td_pcb;
587 
588 	if (td->td_proc->p_md.md_ldt != NULL)
589 		user_ldt_free(td);
590 
591 	critical_enter();
592 	wrmsr(MSR_FSBASE, 0);
593 	wrmsr(MSR_KGSBASE, 0);	/* User value while we're in the kernel */
594 	pcb->pcb_fsbase = 0;
595 	pcb->pcb_gsbase = 0;
596 	critical_exit();
597 	pcb->pcb_initial_fpucw = __LINUX_NPXCW__;
598 
599 	saved_rflags = regs->tf_rflags & PSL_T;
600 	bzero((char *)regs, sizeof(struct trapframe));
601 	regs->tf_rip = imgp->entry_addr;
602 	regs->tf_rsp = stack;
603 	regs->tf_rflags = PSL_USER | saved_rflags;
604 	regs->tf_gs = _ugssel;
605 	regs->tf_fs = _ufssel;
606 	regs->tf_es = _udatasel;
607 	regs->tf_ds = _udatasel;
608 	regs->tf_ss = _udatasel;
609 	regs->tf_flags = TF_HASSEGS;
610 	regs->tf_cs = _ucode32sel;
611 	regs->tf_rbx = (register_t)imgp->ps_strings;
612 
613 	x86_clear_dbregs(pcb);
614 
615 	fpstate_drop(td);
616 
617 	/* Do full restore on return so that we can change to a different %cs */
618 	set_pcb_flags(pcb, PCB_32BIT | PCB_FULL_IRET);
619 }
620 
621 /*
622  * XXX copied from ia32_sysvec.c.
623  */
624 static int
625 linux_copyout_strings(struct image_params *imgp, uintptr_t *stack_base)
626 {
627 	int argc, envc, error;
628 	u_int32_t *vectp;
629 	char *stringp;
630 	uintptr_t destp, ustringp;
631 	struct linux32_ps_strings *arginfo;
632 	char canary[LINUX_AT_RANDOM_LEN];
633 	size_t execpath_len;
634 
635 	arginfo = (struct linux32_ps_strings *)PROC_PS_STRINGS(imgp->proc);
636 	destp = (uintptr_t)arginfo;
637 
638 	if (imgp->execpath != NULL && imgp->auxargs != NULL) {
639 		execpath_len = strlen(imgp->execpath) + 1;
640 		destp -= execpath_len;
641 		destp = rounddown2(destp, sizeof(uint32_t));
642 		imgp->execpathp = (void *)destp;
643 		error = copyout(imgp->execpath, imgp->execpathp, execpath_len);
644 		if (error != 0)
645 			return (error);
646 	}
647 
648 	/* Prepare the canary for SSP. */
649 	arc4rand(canary, sizeof(canary), 0);
650 	destp -= roundup(sizeof(canary), sizeof(uint32_t));
651 	imgp->canary = (void *)destp;
652 	error = copyout(canary, imgp->canary, sizeof(canary));
653 	if (error != 0)
654 		return (error);
655 
656 	/* Allocate room for the argument and environment strings. */
657 	destp -= ARG_MAX - imgp->args->stringspace;
658 	destp = rounddown2(destp, sizeof(uint32_t));
659 	ustringp = destp;
660 
661 	if (imgp->auxargs) {
662 		/*
663 		 * Allocate room on the stack for the ELF auxargs
664 		 * array.  It has LINUX_AT_COUNT entries.
665 		 */
666 		destp -= LINUX_AT_COUNT * sizeof(Elf32_Auxinfo);
667 		destp = rounddown2(destp, sizeof(uint32_t));
668 	}
669 
670 	vectp = (uint32_t *)destp;
671 
672 	/*
673 	 * Allocate room for the argv[] and env vectors including the
674 	 * terminating NULL pointers.
675 	 */
676 	vectp -= imgp->args->argc + 1 + imgp->args->envc + 1;
677 
678 	/* vectp also becomes our initial stack base. */
679 	*stack_base = (uintptr_t)vectp;
680 
681 	stringp = imgp->args->begin_argv;
682 	argc = imgp->args->argc;
683 	envc = imgp->args->envc;
684 
685 	/* Copy out strings - arguments and environment. */
686 	error = copyout(stringp, (void *)ustringp,
687 	    ARG_MAX - imgp->args->stringspace);
688 	if (error != 0)
689 		return (error);
690 
691 	/* Fill in "ps_strings" struct for ps, w, etc. */
692 	if (suword32(&arginfo->ps_argvstr, (uint32_t)(intptr_t)vectp) != 0 ||
693 	    suword32(&arginfo->ps_nargvstr, argc) != 0)
694 		return (EFAULT);
695 
696 	/* Fill in argument portion of vector table. */
697 	for (; argc > 0; --argc) {
698 		if (suword32(vectp++, ustringp) != 0)
699 			return (EFAULT);
700 		while (*stringp++ != 0)
701 			ustringp++;
702 		ustringp++;
703 	}
704 
705 	/* A null vector table pointer separates the argp's from the envp's. */
706 	if (suword32(vectp++, 0) != 0)
707 		return (EFAULT);
708 
709 	if (suword32(&arginfo->ps_envstr, (uint32_t)(intptr_t)vectp) != 0 ||
710 	    suword32(&arginfo->ps_nenvstr, envc) != 0)
711 		return (EFAULT);
712 
713 	/* Fill in environment portion of vector table. */
714 	for (; envc > 0; --envc) {
715 		if (suword32(vectp++, ustringp) != 0)
716 			return (EFAULT);
717 		while (*stringp++ != 0)
718 			ustringp++;
719 		ustringp++;
720 	}
721 
722 	/* The end of the vector table is a null pointer. */
723 	if (suword32(vectp, 0) != 0)
724 		return (EFAULT);
725 
726 	if (imgp->auxargs) {
727 		vectp++;
728 		error = imgp->sysent->sv_copyout_auxargs(imgp,
729 		    (uintptr_t)vectp);
730 		if (error != 0)
731 			return (error);
732 	}
733 
734 	return (0);
735 }
736 
737 static SYSCTL_NODE(_compat, OID_AUTO, linux32, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
738     "32-bit Linux emulation");
739 
740 static u_long	linux32_maxdsiz = LINUX32_MAXDSIZ;
741 SYSCTL_ULONG(_compat_linux32, OID_AUTO, maxdsiz, CTLFLAG_RW,
742     &linux32_maxdsiz, 0, "");
743 static u_long	linux32_maxssiz = LINUX32_MAXSSIZ;
744 SYSCTL_ULONG(_compat_linux32, OID_AUTO, maxssiz, CTLFLAG_RW,
745     &linux32_maxssiz, 0, "");
746 static u_long	linux32_maxvmem = LINUX32_MAXVMEM;
747 SYSCTL_ULONG(_compat_linux32, OID_AUTO, maxvmem, CTLFLAG_RW,
748     &linux32_maxvmem, 0, "");
749 bool linux32_emulate_i386 = false;
750 SYSCTL_BOOL(_compat_linux32, OID_AUTO, emulate_i386, CTLFLAG_RWTUN,
751     &linux32_emulate_i386, 0, "Emulate the real i386");
752 
753 static void
754 linux32_fixlimit(struct rlimit *rl, int which)
755 {
756 
757 	switch (which) {
758 	case RLIMIT_DATA:
759 		if (linux32_maxdsiz != 0) {
760 			if (rl->rlim_cur > linux32_maxdsiz)
761 				rl->rlim_cur = linux32_maxdsiz;
762 			if (rl->rlim_max > linux32_maxdsiz)
763 				rl->rlim_max = linux32_maxdsiz;
764 		}
765 		break;
766 	case RLIMIT_STACK:
767 		if (linux32_maxssiz != 0) {
768 			if (rl->rlim_cur > linux32_maxssiz)
769 				rl->rlim_cur = linux32_maxssiz;
770 			if (rl->rlim_max > linux32_maxssiz)
771 				rl->rlim_max = linux32_maxssiz;
772 		}
773 		break;
774 	case RLIMIT_VMEM:
775 		if (linux32_maxvmem != 0) {
776 			if (rl->rlim_cur > linux32_maxvmem)
777 				rl->rlim_cur = linux32_maxvmem;
778 			if (rl->rlim_max > linux32_maxvmem)
779 				rl->rlim_max = linux32_maxvmem;
780 		}
781 		break;
782 	}
783 }
784 
785 struct sysentvec elf_linux_sysvec = {
786 	.sv_size	= LINUX32_SYS_MAXSYSCALL,
787 	.sv_table	= linux32_sysent,
788 	.sv_fixup	= elf32_freebsd_fixup,
789 	.sv_sendsig	= linux_sendsig,
790 	.sv_sigcode	= &_binary_linux32_vdso_so_o_start,
791 	.sv_szsigcode	= &linux_szsigcode,
792 	.sv_name	= "Linux ELF32",
793 	.sv_coredump	= elf32_coredump,
794 	.sv_elf_core_osabi = ELFOSABI_NONE,
795 	.sv_elf_core_abi_vendor = LINUX_ABI_VENDOR,
796 	.sv_elf_core_prepare_notes = linux32_prepare_notes,
797 	.sv_minsigstksz	= LINUX_MINSIGSTKSZ,
798 	.sv_minuser	= VM_MIN_ADDRESS,
799 	.sv_maxuser	= LINUX32_MAXUSER,
800 	.sv_usrstack	= LINUX32_USRSTACK,
801 	.sv_psstrings	= LINUX32_PS_STRINGS,
802 	.sv_psstringssz	= sizeof(struct linux32_ps_strings),
803 	.sv_stackprot	= VM_PROT_ALL,
804 	.sv_copyout_auxargs = __linuxN(copyout_auxargs),
805 	.sv_copyout_strings = linux_copyout_strings,
806 	.sv_setregs	= linux_exec_setregs,
807 	.sv_fixlimit	= linux32_fixlimit,
808 	.sv_maxssiz	= &linux32_maxssiz,
809 	.sv_flags	= SV_ABI_LINUX | SV_ILP32 | SV_IA32 | SV_SHP |
810 	    SV_SIG_DISCIGN | SV_SIG_WAITNDQ | SV_TIMEKEEP,
811 	.sv_set_syscall_retval = linux32_set_syscall_retval,
812 	.sv_fetch_syscall_args = linux32_fetch_syscall_args,
813 	.sv_syscallnames = linux32_syscallnames,
814 	.sv_shared_page_base = LINUX32_SHAREDPAGE,
815 	.sv_shared_page_len = PAGE_SIZE,
816 	.sv_schedtail	= linux_schedtail,
817 	.sv_thread_detach = linux_thread_detach,
818 	.sv_trap	= NULL,
819 	.sv_hwcap	= NULL,
820 	.sv_hwcap2	= NULL,
821 	.sv_onexec	= linux_on_exec_vmspace,
822 	.sv_onexit	= linux_on_exit,
823 	.sv_ontdexit	= linux_thread_dtor,
824 	.sv_setid_allowed = &linux_setid_allowed_query,
825 	.sv_set_fork_retval = linux32_set_fork_retval,
826 };
827 
828 static int
829 linux_on_exec_vmspace(struct proc *p, struct image_params *imgp)
830 {
831 	int error;
832 
833 	error = linux_map_vdso(p, linux_vdso_obj, linux_vdso_base,
834 	    LINUX32_VDSOPAGE_SIZE, imgp);
835 	if (error == 0)
836 		error = linux_on_exec(p, imgp);
837 	return (error);
838 }
839 
840 /*
841  * linux_vdso_install() and linux_exec_sysvec_init() must be called
842  * after exec_sysvec_init() which is SI_SUB_EXEC (SI_ORDER_ANY).
843  */
844 static void
845 linux_exec_sysvec_init(void *param)
846 {
847 	l_uintptr_t *ktimekeep_base, *ktsc_selector;
848 	struct sysentvec *sv;
849 	ptrdiff_t tkoff;
850 
851 	sv = param;
852 	/* Fill timekeep_base */
853 	exec_sysvec_init(sv);
854 
855 	tkoff = kern_timekeep_base - linux_vdso_base;
856 	ktimekeep_base = (l_uintptr_t *)(linux_vdso_mapping + tkoff);
857 	*ktimekeep_base = sv->sv_shared_page_base + sv->sv_timekeep_offset;
858 
859 	tkoff = kern_tsc_selector - linux_vdso_base;
860 	ktsc_selector = (l_uintptr_t *)(linux_vdso_mapping + tkoff);
861 	*ktsc_selector = linux_vdso_tsc_selector_idx();
862 	if (bootverbose)
863 		printf("Linux i386 vDSO tsc_selector: %u\n", *ktsc_selector);
864 
865 	tkoff = kern_cpu_selector - linux_vdso_base;
866 	ktsc_selector = (l_uintptr_t *)(linux_vdso_mapping + tkoff);
867 	*ktsc_selector = linux_vdso_cpu_selector_idx();
868 	if (bootverbose)
869 		printf("Linux i386 vDSO cpu_selector: %u\n", *ktsc_selector);
870 }
871 SYSINIT(elf_linux_exec_sysvec_init, SI_SUB_EXEC + 1, SI_ORDER_ANY,
872     linux_exec_sysvec_init, &elf_linux_sysvec);
873 
874 static void
875 linux_vdso_install(const void *param)
876 {
877 	char *vdso_start = &_binary_linux32_vdso_so_o_start;
878 	char *vdso_end = &_binary_linux32_vdso_so_o_end;
879 
880 	linux_szsigcode = vdso_end - vdso_start;
881 	MPASS(linux_szsigcode <= LINUX32_VDSOPAGE_SIZE);
882 
883 	linux_vdso_base = LINUX32_VDSOPAGE;
884 
885 	__elfN(linux_vdso_fixup)(vdso_start, linux_vdso_base);
886 
887 	linux_vdso_obj = __elfN(linux_shared_page_init)
888 	    (&linux_vdso_mapping, LINUX32_VDSOPAGE_SIZE);
889 	bcopy(vdso_start, linux_vdso_mapping, linux_szsigcode);
890 
891 	linux_vdso_reloc(linux_vdso_mapping, linux_vdso_base);
892 }
893 SYSINIT(elf_linux_vdso_init, SI_SUB_EXEC + 1, SI_ORDER_FIRST,
894     linux_vdso_install, NULL);
895 
896 static void
897 linux_vdso_deinstall(const void *param)
898 {
899 
900 	__elfN(linux_shared_page_fini)(linux_vdso_obj,
901 	    linux_vdso_mapping, LINUX32_VDSOPAGE_SIZE);
902 }
903 SYSUNINIT(elf_linux_vdso_uninit, SI_SUB_EXEC, SI_ORDER_FIRST,
904     linux_vdso_deinstall, NULL);
905 
906 static void
907 linux_vdso_reloc(char *mapping, Elf_Addr offset)
908 {
909 	const Elf_Shdr *shdr;
910 	const Elf_Rel *rel;
911 	const Elf_Ehdr *ehdr;
912 	Elf32_Addr *where;
913 	Elf_Size rtype, symidx;
914 	Elf32_Addr addr, addend;
915 	int i, relcnt;
916 
917 	MPASS(offset != 0);
918 
919 	relcnt = 0;
920 	ehdr = (const Elf_Ehdr *)mapping;
921 	shdr = (const Elf_Shdr *)(mapping + ehdr->e_shoff);
922 	for (i = 0; i < ehdr->e_shnum; i++)
923 	{
924 		switch (shdr[i].sh_type) {
925 		case SHT_REL:
926 			rel = (const Elf_Rel *)(mapping + shdr[i].sh_offset);
927 			relcnt = shdr[i].sh_size / sizeof(*rel);
928 			break;
929 		case SHT_RELA:
930 			printf("Linux i386 vDSO: unexpected Rela section\n");
931 			break;
932 		}
933 	}
934 
935 	for (i = 0; i < relcnt; i++, rel++) {
936 		where = (Elf32_Addr *)(mapping + rel->r_offset);
937 		addend = *where;
938 		rtype = ELF_R_TYPE(rel->r_info);
939 		symidx = ELF_R_SYM(rel->r_info);
940 
941 		switch (rtype) {
942 		case R_386_NONE:	/* none */
943 			break;
944 
945 		case R_386_RELATIVE:	/* B + A */
946 			addr = (Elf32_Addr)PTROUT(offset + addend);
947 			if (*where != addr)
948 				*where = addr;
949 			break;
950 
951 		case R_386_IRELATIVE:
952 			printf("Linux i386 vDSO: unexpected ifunc relocation, "
953 			    "symbol index %ld\n", (intmax_t)symidx);
954 			break;
955 		default:
956 			printf("Linux i386 vDSO: unexpected relocation type %ld, "
957 			    "symbol index %ld\n", (intmax_t)rtype, (intmax_t)symidx);
958 		}
959 	}
960 }
961 
962 static Elf_Brandnote linux32_brandnote = {
963 	.hdr.n_namesz	= sizeof(GNU_ABI_VENDOR),
964 	.hdr.n_descsz	= 16,	/* XXX at least 16 */
965 	.hdr.n_type	= 1,
966 	.vendor		= GNU_ABI_VENDOR,
967 	.flags		= BN_TRANSLATE_OSREL,
968 	.trans_osrel	= linux_trans_osrel
969 };
970 
971 static Elf32_Brandinfo linux_brand = {
972 	.brand		= ELFOSABI_LINUX,
973 	.machine	= EM_386,
974 	.compat_3_brand	= "Linux",
975 	.interp_path	= "/lib/ld-linux.so.1",
976 	.sysvec		= &elf_linux_sysvec,
977 	.interp_newpath	= NULL,
978 	.brand_note	= &linux32_brandnote,
979 	.flags		= BI_CAN_EXEC_DYN | BI_BRAND_NOTE
980 };
981 
982 static Elf32_Brandinfo linux_glibc2brand = {
983 	.brand		= ELFOSABI_LINUX,
984 	.machine	= EM_386,
985 	.compat_3_brand	= "Linux",
986 	.interp_path	= "/lib/ld-linux.so.2",
987 	.sysvec		= &elf_linux_sysvec,
988 	.interp_newpath	= NULL,
989 	.brand_note	= &linux32_brandnote,
990 	.flags		= BI_CAN_EXEC_DYN | BI_BRAND_NOTE
991 };
992 
993 static Elf32_Brandinfo linux_muslbrand = {
994 	.brand		= ELFOSABI_LINUX,
995 	.machine	= EM_386,
996 	.compat_3_brand	= "Linux",
997 	.interp_path	= "/lib/ld-musl-i386.so.1",
998 	.sysvec		= &elf_linux_sysvec,
999 	.interp_newpath	= NULL,
1000 	.brand_note	= &linux32_brandnote,
1001 	.flags		= BI_CAN_EXEC_DYN | BI_BRAND_NOTE |
1002 			    LINUX_BI_FUTEX_REQUEUE
1003 };
1004 
1005 Elf32_Brandinfo *linux_brandlist[] = {
1006 	&linux_brand,
1007 	&linux_glibc2brand,
1008 	&linux_muslbrand,
1009 	NULL
1010 };
1011 
1012 static int
1013 linux_elf_modevent(module_t mod, int type, void *data)
1014 {
1015 	Elf32_Brandinfo **brandinfo;
1016 	int error;
1017 	struct linux_ioctl_handler **lihp;
1018 
1019 	error = 0;
1020 
1021 	switch(type) {
1022 	case MOD_LOAD:
1023 		for (brandinfo = &linux_brandlist[0]; *brandinfo != NULL;
1024 		     ++brandinfo)
1025 			if (elf32_insert_brand_entry(*brandinfo) < 0)
1026 				error = EINVAL;
1027 		if (error == 0) {
1028 			SET_FOREACH(lihp, linux_ioctl_handler_set)
1029 				linux32_ioctl_register_handler(*lihp);
1030 			stclohz = (stathz ? stathz : hz);
1031 			if (bootverbose)
1032 				printf("Linux i386 ELF exec handler installed\n");
1033 		} else
1034 			printf("cannot insert Linux i386 ELF brand handler\n");
1035 		break;
1036 	case MOD_UNLOAD:
1037 		for (brandinfo = &linux_brandlist[0]; *brandinfo != NULL;
1038 		     ++brandinfo)
1039 			if (elf32_brand_inuse(*brandinfo))
1040 				error = EBUSY;
1041 		if (error == 0) {
1042 			for (brandinfo = &linux_brandlist[0];
1043 			     *brandinfo != NULL; ++brandinfo)
1044 				if (elf32_remove_brand_entry(*brandinfo) < 0)
1045 					error = EINVAL;
1046 		}
1047 		if (error == 0) {
1048 			SET_FOREACH(lihp, linux_ioctl_handler_set)
1049 				linux32_ioctl_unregister_handler(*lihp);
1050 			if (bootverbose)
1051 				printf("Linux i386 ELF exec handler removed\n");
1052 		} else
1053 			printf("Could not deinstall Linux i386 ELF interpreter entry\n");
1054 		break;
1055 	default:
1056 		return (EOPNOTSUPP);
1057 	}
1058 	return (error);
1059 }
1060 
1061 static moduledata_t linux_elf_mod = {
1062 	"linuxelf",
1063 	linux_elf_modevent,
1064 	0
1065 };
1066 
1067 DECLARE_MODULE_TIED(linuxelf, linux_elf_mod, SI_SUB_EXEC, SI_ORDER_ANY);
1068 MODULE_DEPEND(linuxelf, linux_common, 1, 1, 1);
1069 FEATURE(linux, "Linux 32bit support");
1070