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