xref: /freebsd/sys/amd64/linux/linux_sysvec.c (revision 77013d11e6483b970af25e13c9b892075742f7e5)
1 /*-
2  * Copyright (c) 2004 Tim J. Robbins
3  * Copyright (c) 2003 Peter Wemm
4  * Copyright (c) 2002 Doug Rabson
5  * Copyright (c) 1998-1999 Andrew Gallatin
6  * Copyright (c) 1994-1996 Søren Schmidt
7  * All rights reserved.
8  * Copyright (c) 2013, 2021 Dmitry Chagin <dchagin@FreeBSD.org>
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer
15  *    in this position and unchanged.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. The name of the author may not be used to endorse or promote products
20  *    derived from this software without specific prior written permission
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
23  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
24  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
25  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
27  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
31  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33 
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36 
37 #define	__ELF_WORD_SIZE	64
38 
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/exec.h>
42 #include <sys/fcntl.h>
43 #include <sys/imgact.h>
44 #include <sys/imgact_elf.h>
45 #include <sys/kernel.h>
46 #include <sys/ktr.h>
47 #include <sys/lock.h>
48 #include <sys/malloc.h>
49 #include <sys/module.h>
50 #include <sys/mutex.h>
51 #include <sys/proc.h>
52 #include <sys/resourcevar.h>
53 #include <sys/stddef.h>
54 #include <sys/signalvar.h>
55 #include <sys/syscallsubr.h>
56 #include <sys/sysctl.h>
57 #include <sys/sysent.h>
58 #include <sys/sysproto.h>
59 #include <sys/vnode.h>
60 #include <sys/eventhandler.h>
61 
62 #include <vm/vm.h>
63 #include <vm/pmap.h>
64 #include <vm/vm_extern.h>
65 #include <vm/vm_map.h>
66 #include <vm/vm_object.h>
67 #include <vm/vm_page.h>
68 #include <vm/vm_param.h>
69 
70 #include <machine/cpu.h>
71 #include <machine/md_var.h>
72 #include <machine/pcb.h>
73 #include <machine/specialreg.h>
74 #include <machine/trap.h>
75 
76 #include <x86/linux/linux_x86.h>
77 #include <amd64/linux/linux.h>
78 #include <amd64/linux/linux_proto.h>
79 #include <compat/linux/linux_emul.h>
80 #include <compat/linux/linux_ioctl.h>
81 #include <compat/linux/linux_mib.h>
82 #include <compat/linux/linux_misc.h>
83 #include <compat/linux/linux_signal.h>
84 #include <compat/linux/linux_sysproto.h>
85 #include <compat/linux/linux_util.h>
86 #include <compat/linux/linux_vdso.h>
87 
88 MODULE_VERSION(linux64, 1);
89 
90 #define	LINUX_VDSOPAGE_SIZE	PAGE_SIZE * 2
91 #define	LINUX_VDSOPAGE_LA48	(VM_MAXUSER_ADDRESS_LA48 - \
92 				    LINUX_VDSOPAGE_SIZE)
93 #define	LINUX_SHAREDPAGE_LA48	(LINUX_VDSOPAGE_LA48 - PAGE_SIZE)
94 				/*
95 				 * PAGE_SIZE - the size
96 				 * of the native SHAREDPAGE
97 				 */
98 #define	LINUX_USRSTACK_LA48	LINUX_SHAREDPAGE_LA48
99 #define	LINUX_PS_STRINGS_LA48	(LINUX_USRSTACK_LA48 - \
100 				    sizeof(struct ps_strings))
101 
102 static int linux_szsigcode;
103 static vm_object_t linux_vdso_obj;
104 static char *linux_vdso_mapping;
105 extern char _binary_linux_vdso_so_o_start;
106 extern char _binary_linux_vdso_so_o_end;
107 static vm_offset_t linux_vdso_base;
108 
109 extern struct sysent linux_sysent[LINUX_SYS_MAXSYSCALL];
110 
111 SET_DECLARE(linux_ioctl_handler_set, struct linux_ioctl_handler);
112 
113 static int	linux_copyout_strings(struct image_params *imgp,
114 		    uintptr_t *stack_base);
115 static int	linux_fixup_elf(uintptr_t *stack_base,
116 		    struct image_params *iparams);
117 static bool	linux_trans_osrel(const Elf_Note *note, int32_t *osrel);
118 static void	linux_vdso_install(const void *param);
119 static void	linux_vdso_deinstall(const void *param);
120 static void	linux_vdso_reloc(char *mapping, Elf_Addr offset);
121 static void	linux_set_syscall_retval(struct thread *td, int error);
122 static int	linux_fetch_syscall_args(struct thread *td);
123 static void	linux_exec_setregs(struct thread *td, struct image_params *imgp,
124 		    uintptr_t stack);
125 static void	linux_exec_sysvec_init(void *param);
126 static int	linux_on_exec_vmspace(struct proc *p,
127 		    struct image_params *imgp);
128 static int	linux_vsyscall(struct thread *td);
129 
130 #define LINUX_T_UNKNOWN  255
131 static int _bsd_to_linux_trapcode[] = {
132 	LINUX_T_UNKNOWN,	/* 0 */
133 	6,			/* 1  T_PRIVINFLT */
134 	LINUX_T_UNKNOWN,	/* 2 */
135 	3,			/* 3  T_BPTFLT */
136 	LINUX_T_UNKNOWN,	/* 4 */
137 	LINUX_T_UNKNOWN,	/* 5 */
138 	16,			/* 6  T_ARITHTRAP */
139 	254,			/* 7  T_ASTFLT */
140 	LINUX_T_UNKNOWN,	/* 8 */
141 	13,			/* 9  T_PROTFLT */
142 	1,			/* 10 T_TRCTRAP */
143 	LINUX_T_UNKNOWN,	/* 11 */
144 	14,			/* 12 T_PAGEFLT */
145 	LINUX_T_UNKNOWN,	/* 13 */
146 	17,			/* 14 T_ALIGNFLT */
147 	LINUX_T_UNKNOWN,	/* 15 */
148 	LINUX_T_UNKNOWN,	/* 16 */
149 	LINUX_T_UNKNOWN,	/* 17 */
150 	0,			/* 18 T_DIVIDE */
151 	2,			/* 19 T_NMI */
152 	4,			/* 20 T_OFLOW */
153 	5,			/* 21 T_BOUND */
154 	7,			/* 22 T_DNA */
155 	8,			/* 23 T_DOUBLEFLT */
156 	9,			/* 24 T_FPOPFLT */
157 	10,			/* 25 T_TSSFLT */
158 	11,			/* 26 T_SEGNPFLT */
159 	12,			/* 27 T_STKFLT */
160 	18,			/* 28 T_MCHK */
161 	19,			/* 29 T_XMMFLT */
162 	15			/* 30 T_RESERVED */
163 };
164 #define bsd_to_linux_trapcode(code) \
165     ((code)<nitems(_bsd_to_linux_trapcode)? \
166      _bsd_to_linux_trapcode[(code)]: \
167      LINUX_T_UNKNOWN)
168 
169 LINUX_VDSO_SYM_INTPTR(linux_rt_sigcode);
170 LINUX_VDSO_SYM_CHAR(linux_platform);
171 LINUX_VDSO_SYM_INTPTR(kern_timekeep_base);
172 LINUX_VDSO_SYM_INTPTR(kern_tsc_selector);
173 
174 /*
175  * If FreeBSD & Linux have a difference of opinion about what a trap
176  * means, deal with it here.
177  *
178  * MPSAFE
179  */
180 static int
181 linux_translate_traps(int signal, int trap_code)
182 {
183 
184 	if (signal != SIGBUS)
185 		return (signal);
186 	switch (trap_code) {
187 	case T_PROTFLT:
188 	case T_TSSFLT:
189 	case T_DOUBLEFLT:
190 	case T_PAGEFLT:
191 		return (SIGSEGV);
192 	default:
193 		return (signal);
194 	}
195 }
196 
197 static int
198 linux_fetch_syscall_args(struct thread *td)
199 {
200 	struct proc *p;
201 	struct trapframe *frame;
202 	struct syscall_args *sa;
203 
204 	p = td->td_proc;
205 	frame = td->td_frame;
206 	sa = &td->td_sa;
207 
208 	sa->args[0] = frame->tf_rdi;
209 	sa->args[1] = frame->tf_rsi;
210 	sa->args[2] = frame->tf_rdx;
211 	sa->args[3] = frame->tf_rcx;
212 	sa->args[4] = frame->tf_r8;
213 	sa->args[5] = frame->tf_r9;
214 	sa->code = frame->tf_rax;
215 	sa->original_code = sa->code;
216 
217 	if (sa->code >= p->p_sysent->sv_size)
218 		/* nosys */
219 		sa->callp = &p->p_sysent->sv_table[p->p_sysent->sv_size - 1];
220 	else
221 		sa->callp = &p->p_sysent->sv_table[sa->code];
222 
223 	td->td_retval[0] = 0;
224 	return (0);
225 }
226 
227 static void
228 linux_set_syscall_retval(struct thread *td, int error)
229 {
230 	struct trapframe *frame;
231 
232 	frame = td->td_frame;
233 
234 	switch (error) {
235 	case 0:
236 		frame->tf_rax = td->td_retval[0];
237  		frame->tf_r10 = frame->tf_rcx;
238 		break;
239 
240 	case ERESTART:
241 		/*
242 		 * Reconstruct pc, we know that 'syscall' is 2 bytes,
243 		 * lcall $X,y is 7 bytes, int 0x80 is 2 bytes.
244 		 * We saved this in tf_err.
245 		 *
246 		 */
247 		frame->tf_rip -= frame->tf_err;
248 		frame->tf_r10 = frame->tf_rcx;
249 		break;
250 
251 	case EJUSTRETURN:
252 		break;
253 
254 	default:
255 		frame->tf_rax = bsd_to_linux_errno(error);
256 		frame->tf_r10 = frame->tf_rcx;
257 		break;
258 	}
259 
260 	/*
261 	 * Differently from FreeBSD native ABI, on Linux only %rcx
262 	 * and %r11 values are not preserved across the syscall.
263 	 * Require full context restore to get all registers except
264 	 * those two restored at return to usermode.
265 	 *
266 	 * XXX: Would be great to be able to avoid PCB_FULL_IRET
267 	 *      for the error == 0 case.
268 	 */
269 	set_pcb_flags(td->td_pcb, PCB_FULL_IRET);
270 }
271 
272 static int
273 linux_copyout_auxargs(struct image_params *imgp, uintptr_t base)
274 {
275 	Elf_Auxargs *args;
276 	Elf_Auxinfo *argarray, *pos;
277 	struct proc *p;
278 	int error, issetugid;
279 
280 	p = imgp->proc;
281 	args = (Elf64_Auxargs *)imgp->auxargs;
282 	argarray = pos = malloc(LINUX_AT_COUNT * sizeof(*pos), M_TEMP,
283 	    M_WAITOK | M_ZERO);
284 
285 	issetugid = p->p_flag & P_SUGID ? 1 : 0;
286 	AUXARGS_ENTRY(pos, LINUX_AT_SYSINFO_EHDR, linux_vdso_base);
287 	AUXARGS_ENTRY(pos, LINUX_AT_HWCAP, cpu_feature);
288 	AUXARGS_ENTRY(pos, AT_PAGESZ, args->pagesz);
289 	AUXARGS_ENTRY(pos, LINUX_AT_CLKTCK, stclohz);
290 	AUXARGS_ENTRY(pos, AT_PHDR, args->phdr);
291 	AUXARGS_ENTRY(pos, AT_PHENT, args->phent);
292 	AUXARGS_ENTRY(pos, AT_PHNUM, args->phnum);
293 	AUXARGS_ENTRY(pos, AT_BASE, args->base);
294 	AUXARGS_ENTRY(pos, AT_FLAGS, args->flags);
295 	AUXARGS_ENTRY(pos, AT_ENTRY, args->entry);
296 	AUXARGS_ENTRY(pos, AT_UID, imgp->proc->p_ucred->cr_ruid);
297 	AUXARGS_ENTRY(pos, AT_EUID, imgp->proc->p_ucred->cr_svuid);
298 	AUXARGS_ENTRY(pos, AT_GID, imgp->proc->p_ucred->cr_rgid);
299 	AUXARGS_ENTRY(pos, AT_EGID, imgp->proc->p_ucred->cr_svgid);
300 	AUXARGS_ENTRY(pos, LINUX_AT_SECURE, issetugid);
301 	AUXARGS_ENTRY_PTR(pos, LINUX_AT_RANDOM, imgp->canary);
302 	AUXARGS_ENTRY(pos, LINUX_AT_HWCAP2, 0);
303 	if (imgp->execpathp != 0)
304 		AUXARGS_ENTRY_PTR(pos, LINUX_AT_EXECFN, imgp->execpathp);
305 	if (args->execfd != -1)
306 		AUXARGS_ENTRY(pos, AT_EXECFD, args->execfd);
307 	AUXARGS_ENTRY(pos, LINUX_AT_PLATFORM, PTROUT(linux_platform));
308 	AUXARGS_ENTRY(pos, AT_NULL, 0);
309 
310 	free(imgp->auxargs, M_TEMP);
311 	imgp->auxargs = NULL;
312 	KASSERT(pos - argarray <= LINUX_AT_COUNT, ("Too many auxargs"));
313 
314 	error = copyout(argarray, (void *)base,
315 	    sizeof(*argarray) * LINUX_AT_COUNT);
316 	free(argarray, M_TEMP);
317 	return (error);
318 }
319 
320 static int
321 linux_fixup_elf(uintptr_t *stack_base, struct image_params *imgp)
322 {
323 	Elf_Addr *base;
324 
325 	base = (Elf64_Addr *)*stack_base;
326 	base--;
327 	if (suword(base, (uint64_t)imgp->args->argc) == -1)
328 		return (EFAULT);
329 
330 	*stack_base = (uintptr_t)base;
331 	return (0);
332 }
333 
334 /*
335  * Copy strings out to the new process address space, constructing new arg
336  * and env vector tables. Return a pointer to the base so that it can be used
337  * as the initial stack pointer.
338  */
339 static int
340 linux_copyout_strings(struct image_params *imgp, uintptr_t *stack_base)
341 {
342 	int argc, envc, error;
343 	char **vectp;
344 	char *stringp;
345 	uintptr_t destp, ustringp;
346 	struct ps_strings *arginfo;
347 	char canary[LINUX_AT_RANDOM_LEN];
348 	size_t execpath_len;
349 	struct proc *p;
350 
351 	/* Calculate string base and vector table pointers. */
352 	if (imgp->execpath != NULL && imgp->auxargs != NULL)
353 		execpath_len = strlen(imgp->execpath) + 1;
354 	else
355 		execpath_len = 0;
356 
357 	p = imgp->proc;
358 	arginfo = (struct ps_strings *)p->p_sysent->sv_psstrings;
359 	destp = (uintptr_t)arginfo;
360 
361 	if (execpath_len != 0) {
362 		destp -= execpath_len;
363 		destp = rounddown2(destp, sizeof(void *));
364 		imgp->execpathp = (void *)destp;
365 		error = copyout(imgp->execpath, imgp->execpathp, execpath_len);
366 		if (error != 0)
367 			return (error);
368 	}
369 
370 	/* Prepare the canary for SSP. */
371 	arc4rand(canary, sizeof(canary), 0);
372 	destp -= roundup(sizeof(canary), sizeof(void *));
373 	imgp->canary = (void *)destp;
374 	error = copyout(canary, imgp->canary, sizeof(canary));
375 	if (error != 0)
376 		return (error);
377 
378 	/* Allocate room for the argument and environment strings. */
379 	destp -= ARG_MAX - imgp->args->stringspace;
380 	destp = rounddown2(destp, sizeof(void *));
381 	ustringp = destp;
382 
383 	if (imgp->auxargs) {
384 		/*
385 		 * Allocate room on the stack for the ELF auxargs
386 		 * array.  It has LINUX_AT_COUNT entries.
387 		 */
388 		destp -= LINUX_AT_COUNT * sizeof(Elf64_Auxinfo);
389 		destp = rounddown2(destp, sizeof(void *));
390 	}
391 
392 	vectp = (char **)destp;
393 
394 	/*
395 	 * Allocate room for the argv[] and env vectors including the
396 	 * terminating NULL pointers.
397 	 */
398 	vectp -= imgp->args->argc + 1 + imgp->args->envc + 1;
399 
400 	/*
401 	 * Starting with 2.24, glibc depends on a 16-byte stack alignment.
402 	 * One "long argc" will be prepended later.
403 	 */
404 	vectp = (char **)((((uintptr_t)vectp + 8) & ~0xF) - 8);
405 
406 	/* vectp also becomes our initial stack base. */
407 	*stack_base = (uintptr_t)vectp;
408 
409 	stringp = imgp->args->begin_argv;
410 	argc = imgp->args->argc;
411 	envc = imgp->args->envc;
412 
413 	/* Copy out strings - arguments and environment. */
414 	error = copyout(stringp, (void *)ustringp,
415 	    ARG_MAX - imgp->args->stringspace);
416 	if (error != 0)
417 		return (error);
418 
419 	/* Fill in "ps_strings" struct for ps, w, etc. */
420 	if (suword(&arginfo->ps_argvstr, (long)(intptr_t)vectp) != 0 ||
421 	    suword(&arginfo->ps_nargvstr, argc) != 0)
422 		return (EFAULT);
423 
424 	/* Fill in argument portion of vector table. */
425 	for (; argc > 0; --argc) {
426 		if (suword(vectp++, ustringp) != 0)
427 			return (EFAULT);
428 		while (*stringp++ != 0)
429 			ustringp++;
430 		ustringp++;
431 	}
432 
433 	/* A null vector table pointer separates the argp's from the envp's. */
434 	if (suword(vectp++, 0) != 0)
435 		return (EFAULT);
436 
437 	if (suword(&arginfo->ps_envstr, (long)(intptr_t)vectp) != 0 ||
438 	    suword(&arginfo->ps_nenvstr, envc) != 0)
439 		return (EFAULT);
440 
441 	/* Fill in environment portion of vector table. */
442 	for (; envc > 0; --envc) {
443 		if (suword(vectp++, ustringp) != 0)
444 			return (EFAULT);
445 		while (*stringp++ != 0)
446 			ustringp++;
447 		ustringp++;
448 	}
449 
450 	/* The end of the vector table is a null pointer. */
451 	if (suword(vectp, 0) != 0)
452 		return (EFAULT);
453 
454 	if (imgp->auxargs) {
455 		vectp++;
456 		error = imgp->sysent->sv_copyout_auxargs(imgp,
457 		    (uintptr_t)vectp);
458 		if (error != 0)
459 			return (error);
460 	}
461 
462 	return (0);
463 }
464 
465 /*
466  * Reset registers to default values on exec.
467  */
468 static void
469 linux_exec_setregs(struct thread *td, struct image_params *imgp,
470     uintptr_t stack)
471 {
472 	struct trapframe *regs;
473 	struct pcb *pcb;
474 	register_t saved_rflags;
475 
476 	regs = td->td_frame;
477 	pcb = td->td_pcb;
478 
479 	if (td->td_proc->p_md.md_ldt != NULL)
480 		user_ldt_free(td);
481 
482 	pcb->pcb_fsbase = 0;
483 	pcb->pcb_gsbase = 0;
484 	clear_pcb_flags(pcb, PCB_32BIT);
485 	pcb->pcb_initial_fpucw = __LINUX_NPXCW__;
486 	set_pcb_flags(pcb, PCB_FULL_IRET);
487 
488 	saved_rflags = regs->tf_rflags & PSL_T;
489 	bzero((char *)regs, sizeof(struct trapframe));
490 	regs->tf_rip = imgp->entry_addr;
491 	regs->tf_rsp = stack;
492 	regs->tf_rflags = PSL_USER | saved_rflags;
493 	regs->tf_ss = _udatasel;
494 	regs->tf_cs = _ucodesel;
495 	regs->tf_ds = _udatasel;
496 	regs->tf_es = _udatasel;
497 	regs->tf_fs = _ufssel;
498 	regs->tf_gs = _ugssel;
499 	regs->tf_flags = TF_HASSEGS;
500 
501 	x86_clear_dbregs(pcb);
502 
503 	/*
504 	 * Drop the FP state if we hold it, so that the process gets a
505 	 * clean FP state if it uses the FPU again.
506 	 */
507 	fpstate_drop(td);
508 }
509 
510 /*
511  * Copied from amd64/amd64/machdep.c
512  *
513  * XXX fpu state need? don't think so
514  */
515 int
516 linux_rt_sigreturn(struct thread *td, struct linux_rt_sigreturn_args *args)
517 {
518 	struct proc *p;
519 	struct l_ucontext uc;
520 	struct l_sigcontext *context;
521 	struct trapframe *regs;
522 	unsigned long rflags;
523 	int error;
524 	ksiginfo_t ksi;
525 
526 	regs = td->td_frame;
527 	error = copyin((void *)regs->tf_rbx, &uc, sizeof(uc));
528 	if (error != 0)
529 		return (error);
530 
531 	p = td->td_proc;
532 	context = &uc.uc_mcontext;
533 	rflags = context->sc_rflags;
534 
535 	/*
536 	 * Don't allow users to change privileged or reserved flags.
537 	 */
538 	/*
539 	 * XXX do allow users to change the privileged flag PSL_RF.
540 	 * The cpu sets PSL_RF in tf_rflags for faults.  Debuggers
541 	 * should sometimes set it there too.  tf_rflags is kept in
542 	 * the signal context during signal handling and there is no
543 	 * other place to remember it, so the PSL_RF bit may be
544 	 * corrupted by the signal handler without us knowing.
545 	 * Corruption of the PSL_RF bit at worst causes one more or
546 	 * one less debugger trap, so allowing it is fairly harmless.
547 	 */
548 
549 #define RFLAG_SECURE(ef, oef)     ((((ef) ^ (oef)) & ~PSL_USERCHANGE) == 0)
550 	if (!RFLAG_SECURE(rflags & ~PSL_RF, regs->tf_rflags & ~PSL_RF)) {
551 		printf("linux_rt_sigreturn: rflags = 0x%lx\n", rflags);
552 		return (EINVAL);
553 	}
554 
555 	/*
556 	 * Don't allow users to load a valid privileged %cs.  Let the
557 	 * hardware check for invalid selectors, excess privilege in
558 	 * other selectors, invalid %eip's and invalid %esp's.
559 	 */
560 #define CS_SECURE(cs)           (ISPL(cs) == SEL_UPL)
561 	if (!CS_SECURE(context->sc_cs)) {
562 		printf("linux_rt_sigreturn: cs = 0x%x\n", context->sc_cs);
563 		ksiginfo_init_trap(&ksi);
564 		ksi.ksi_signo = SIGBUS;
565 		ksi.ksi_code = BUS_OBJERR;
566 		ksi.ksi_trapno = T_PROTFLT;
567 		ksi.ksi_addr = (void *)regs->tf_rip;
568 		trapsignal(td, &ksi);
569 		return (EINVAL);
570 	}
571 
572 	PROC_LOCK(p);
573 	linux_to_bsd_sigset(&uc.uc_sigmask, &td->td_sigmask);
574 	SIG_CANTMASK(td->td_sigmask);
575 	signotify(td);
576 	PROC_UNLOCK(p);
577 
578 	regs->tf_rdi    = context->sc_rdi;
579 	regs->tf_rsi    = context->sc_rsi;
580 	regs->tf_rdx    = context->sc_rdx;
581 	regs->tf_rbp    = context->sc_rbp;
582 	regs->tf_rbx    = context->sc_rbx;
583 	regs->tf_rcx    = context->sc_rcx;
584 	regs->tf_rax    = context->sc_rax;
585 	regs->tf_rip    = context->sc_rip;
586 	regs->tf_rsp    = context->sc_rsp;
587 	regs->tf_r8     = context->sc_r8;
588 	regs->tf_r9     = context->sc_r9;
589 	regs->tf_r10    = context->sc_r10;
590 	regs->tf_r11    = context->sc_r11;
591 	regs->tf_r12    = context->sc_r12;
592 	regs->tf_r13    = context->sc_r13;
593 	regs->tf_r14    = context->sc_r14;
594 	regs->tf_r15    = context->sc_r15;
595 	regs->tf_cs     = context->sc_cs;
596 	regs->tf_err    = context->sc_err;
597 	regs->tf_rflags = rflags;
598 
599 	set_pcb_flags(td->td_pcb, PCB_FULL_IRET);
600 	return (EJUSTRETURN);
601 }
602 
603 /*
604  * copied from amd64/amd64/machdep.c
605  *
606  * Send an interrupt to process.
607  */
608 static void
609 linux_rt_sendsig(sig_t catcher, ksiginfo_t *ksi, sigset_t *mask)
610 {
611 	struct l_rt_sigframe sf, *sfp;
612 	struct proc *p;
613 	struct thread *td;
614 	struct sigacts *psp;
615 	caddr_t sp;
616 	struct trapframe *regs;
617 	int sig, code;
618 	int oonstack;
619 
620 	td = curthread;
621 	p = td->td_proc;
622 	PROC_LOCK_ASSERT(p, MA_OWNED);
623 	sig = ksi->ksi_signo;
624 	psp = p->p_sigacts;
625 	code = ksi->ksi_code;
626 	mtx_assert(&psp->ps_mtx, MA_OWNED);
627 	regs = td->td_frame;
628 	oonstack = sigonstack(regs->tf_rsp);
629 
630 	LINUX_CTR4(rt_sendsig, "%p, %d, %p, %u",
631 	    catcher, sig, mask, code);
632 
633 	/* Save user context. */
634 	bzero(&sf, sizeof(sf));
635 	bsd_to_linux_sigset(mask, &sf.sf_sc.uc_sigmask);
636 	bsd_to_linux_sigset(mask, &sf.sf_sc.uc_mcontext.sc_mask);
637 
638 	sf.sf_sc.uc_stack.ss_sp = PTROUT(td->td_sigstk.ss_sp);
639 	sf.sf_sc.uc_stack.ss_size = td->td_sigstk.ss_size;
640 	sf.sf_sc.uc_stack.ss_flags = (td->td_pflags & TDP_ALTSTACK)
641 	    ? ((oonstack) ? LINUX_SS_ONSTACK : 0) : LINUX_SS_DISABLE;
642 
643 	sf.sf_sc.uc_mcontext.sc_rdi    = regs->tf_rdi;
644 	sf.sf_sc.uc_mcontext.sc_rsi    = regs->tf_rsi;
645 	sf.sf_sc.uc_mcontext.sc_rdx    = regs->tf_rdx;
646 	sf.sf_sc.uc_mcontext.sc_rbp    = regs->tf_rbp;
647 	sf.sf_sc.uc_mcontext.sc_rbx    = regs->tf_rbx;
648 	sf.sf_sc.uc_mcontext.sc_rcx    = regs->tf_rcx;
649 	sf.sf_sc.uc_mcontext.sc_rax    = regs->tf_rax;
650 	sf.sf_sc.uc_mcontext.sc_rip    = regs->tf_rip;
651 	sf.sf_sc.uc_mcontext.sc_rsp    = regs->tf_rsp;
652 	sf.sf_sc.uc_mcontext.sc_r8     = regs->tf_r8;
653 	sf.sf_sc.uc_mcontext.sc_r9     = regs->tf_r9;
654 	sf.sf_sc.uc_mcontext.sc_r10    = regs->tf_r10;
655 	sf.sf_sc.uc_mcontext.sc_r11    = regs->tf_r11;
656 	sf.sf_sc.uc_mcontext.sc_r12    = regs->tf_r12;
657 	sf.sf_sc.uc_mcontext.sc_r13    = regs->tf_r13;
658 	sf.sf_sc.uc_mcontext.sc_r14    = regs->tf_r14;
659 	sf.sf_sc.uc_mcontext.sc_r15    = regs->tf_r15;
660 	sf.sf_sc.uc_mcontext.sc_cs     = regs->tf_cs;
661 	sf.sf_sc.uc_mcontext.sc_rflags = regs->tf_rflags;
662 	sf.sf_sc.uc_mcontext.sc_err    = regs->tf_err;
663 	sf.sf_sc.uc_mcontext.sc_trapno = bsd_to_linux_trapcode(code);
664 	sf.sf_sc.uc_mcontext.sc_cr2    = (register_t)ksi->ksi_addr;
665 
666 	/* Allocate space for the signal handler context. */
667 	if ((td->td_pflags & TDP_ALTSTACK) != 0 && !oonstack &&
668 	    SIGISMEMBER(psp->ps_sigonstack, sig)) {
669 		sp = (caddr_t)td->td_sigstk.ss_sp + td->td_sigstk.ss_size -
670 		    sizeof(struct l_rt_sigframe);
671 	} else
672 		sp = (caddr_t)regs->tf_rsp - sizeof(struct l_rt_sigframe) - 128;
673 	/* Align to 16 bytes. */
674 	sfp = (struct l_rt_sigframe *)((unsigned long)sp & ~0xFul);
675 
676 	/* Translate the signal. */
677 	sig = bsd_to_linux_signal(sig);
678 
679 	/* Build the argument list for the signal handler. */
680 	regs->tf_rdi = sig;			/* arg 1 in %rdi */
681 	regs->tf_rax = 0;
682 	regs->tf_rsi = (register_t)&sfp->sf_si;	/* arg 2 in %rsi */
683 	regs->tf_rdx = (register_t)&sfp->sf_sc;	/* arg 3 in %rdx */
684 
685 	/* Fill in POSIX parts. */
686 	siginfo_to_lsiginfo(&ksi->ksi_info, &sf.sf_si, sig);
687 	sf.sf_handler = catcher;
688 
689 	mtx_unlock(&psp->ps_mtx);
690 	PROC_UNLOCK(p);
691 
692 	/* Copy the sigframe out to the user's stack. */
693 	if (copyout(&sf, sfp, sizeof(*sfp)) != 0) {
694 		PROC_LOCK(p);
695 		sigexit(td, SIGILL);
696 	}
697 
698 	regs->tf_rsp = (long)sfp;
699 	regs->tf_rip = linux_rt_sigcode;
700 	regs->tf_rflags &= ~(PSL_T | PSL_D);
701 	regs->tf_cs = _ucodesel;
702 	set_pcb_flags(td->td_pcb, PCB_FULL_IRET);
703 	PROC_LOCK(p);
704 	mtx_lock(&psp->ps_mtx);
705 }
706 
707 #define	LINUX_VSYSCALL_START		(-10UL << 20)
708 #define	LINUX_VSYSCALL_SZ		1024
709 
710 const unsigned long linux_vsyscall_vector[] = {
711 	LINUX_SYS_gettimeofday,
712 	LINUX_SYS_linux_time,
713 	LINUX_SYS_linux_getcpu,
714 };
715 
716 static int
717 linux_vsyscall(struct thread *td)
718 {
719 	struct trapframe *frame;
720 	uint64_t retqaddr;
721 	int code, traced;
722 	int error;
723 
724 	frame = td->td_frame;
725 
726 	/* Check %rip for vsyscall area. */
727 	if (__predict_true(frame->tf_rip < LINUX_VSYSCALL_START))
728 		return (EINVAL);
729 	if ((frame->tf_rip & (LINUX_VSYSCALL_SZ - 1)) != 0)
730 		return (EINVAL);
731 	code = (frame->tf_rip - LINUX_VSYSCALL_START) / LINUX_VSYSCALL_SZ;
732 	if (code >= nitems(linux_vsyscall_vector))
733 		return (EINVAL);
734 
735 	/*
736 	 * vsyscall called as callq *(%rax), so we must
737 	 * use return address from %rsp and also fixup %rsp.
738 	 */
739 	error = copyin((void *)frame->tf_rsp, &retqaddr, sizeof(retqaddr));
740 	if (error)
741 		return (error);
742 
743 	frame->tf_rip = retqaddr;
744 	frame->tf_rax = linux_vsyscall_vector[code];
745 	frame->tf_rsp += 8;
746 
747 	traced = (frame->tf_flags & PSL_T);
748 
749 	amd64_syscall(td, traced);
750 
751 	return (0);
752 }
753 
754 struct sysentvec elf_linux_sysvec = {
755 	.sv_size	= LINUX_SYS_MAXSYSCALL,
756 	.sv_table	= linux_sysent,
757 	.sv_transtrap	= linux_translate_traps,
758 	.sv_fixup	= linux_fixup_elf,
759 	.sv_sendsig	= linux_rt_sendsig,
760 	.sv_sigcode	= &_binary_linux_vdso_so_o_start,
761 	.sv_szsigcode	= &linux_szsigcode,
762 	.sv_name	= "Linux ELF64",
763 	.sv_coredump	= elf64_coredump,
764 	.sv_elf_core_osabi = ELFOSABI_NONE,
765 	.sv_elf_core_abi_vendor = LINUX_ABI_VENDOR,
766 	.sv_elf_core_prepare_notes = linux64_prepare_notes,
767 	.sv_imgact_try	= linux_exec_imgact_try,
768 	.sv_minsigstksz	= LINUX_MINSIGSTKSZ,
769 	.sv_minuser	= VM_MIN_ADDRESS,
770 	.sv_maxuser	= VM_MAXUSER_ADDRESS_LA48,
771 	.sv_usrstack	= LINUX_USRSTACK_LA48,
772 	.sv_psstrings	= LINUX_PS_STRINGS_LA48,
773 	.sv_stackprot	= VM_PROT_ALL,
774 	.sv_copyout_auxargs = linux_copyout_auxargs,
775 	.sv_copyout_strings = linux_copyout_strings,
776 	.sv_setregs	= linux_exec_setregs,
777 	.sv_fixlimit	= NULL,
778 	.sv_maxssiz	= NULL,
779 	.sv_flags	= SV_ABI_LINUX | SV_LP64 | SV_SHP | SV_SIG_DISCIGN |
780 	    SV_SIG_WAITNDQ | SV_TIMEKEEP,
781 	.sv_set_syscall_retval = linux_set_syscall_retval,
782 	.sv_fetch_syscall_args = linux_fetch_syscall_args,
783 	.sv_syscallnames = NULL,
784 	.sv_shared_page_base = LINUX_SHAREDPAGE_LA48,
785 	.sv_shared_page_len = PAGE_SIZE,
786 	.sv_schedtail	= linux_schedtail,
787 	.sv_thread_detach = linux_thread_detach,
788 	.sv_trap	= linux_vsyscall,
789 	.sv_onexec	= linux_on_exec_vmspace,
790 	.sv_onexit	= linux_on_exit,
791 	.sv_ontdexit	= linux_thread_dtor,
792 	.sv_setid_allowed = &linux_setid_allowed_query,
793 };
794 
795 static int
796 linux_on_exec_vmspace(struct proc *p, struct image_params *imgp)
797 {
798 	int error;
799 
800 	error = linux_map_vdso(p, linux_vdso_obj, linux_vdso_base,
801 	    LINUX_VDSOPAGE_SIZE, imgp);
802 	if (error == 0)
803 		linux_on_exec(p, imgp);
804 	return (error);
805 }
806 
807 /*
808  * linux_vdso_install() and linux_exec_sysvec_init() must be called
809  * after exec_sysvec_init() which is SI_SUB_EXEC (SI_ORDER_ANY).
810  */
811 static void
812 linux_exec_sysvec_init(void *param)
813 {
814 	l_uintptr_t *ktimekeep_base, *ktsc_selector;
815 	struct sysentvec *sv;
816 	ptrdiff_t tkoff;
817 
818 	sv = param;
819 	amd64_lower_shared_page(sv);
820 	/* Fill timekeep_base */
821 	exec_sysvec_init(sv);
822 
823 	tkoff = kern_timekeep_base - linux_vdso_base;
824 	ktimekeep_base = (l_uintptr_t *)(linux_vdso_mapping + tkoff);
825 	*ktimekeep_base = sv->sv_timekeep_base;
826 
827 	tkoff = kern_tsc_selector - linux_vdso_base;
828 	ktsc_selector = (l_uintptr_t *)(linux_vdso_mapping + tkoff);
829 	*ktsc_selector = linux_vdso_tsc_selector_idx();
830 	if (bootverbose)
831 		printf("Linux x86-64 vDSO tsc_selector: %lu\n", *ktsc_selector);
832 }
833 SYSINIT(elf_linux_exec_sysvec_init, SI_SUB_EXEC + 1, SI_ORDER_ANY,
834     linux_exec_sysvec_init, &elf_linux_sysvec);
835 
836 static void
837 linux_vdso_install(const void *param)
838 {
839 	char *vdso_start = &_binary_linux_vdso_so_o_start;
840 	char *vdso_end = &_binary_linux_vdso_so_o_end;
841 
842 	linux_szsigcode = vdso_end - vdso_start;
843 	MPASS(linux_szsigcode <= LINUX_VDSOPAGE_SIZE);
844 
845 	linux_vdso_base = LINUX_VDSOPAGE_LA48;
846 	if (hw_lower_amd64_sharedpage != 0)
847 		linux_vdso_base -= PAGE_SIZE;
848 
849 	__elfN(linux_vdso_fixup)(vdso_start, linux_vdso_base);
850 
851 	linux_vdso_obj = __elfN(linux_shared_page_init)
852 	    (&linux_vdso_mapping, LINUX_VDSOPAGE_SIZE);
853 	bcopy(vdso_start, linux_vdso_mapping, linux_szsigcode);
854 
855 	linux_vdso_reloc(linux_vdso_mapping, linux_vdso_base);
856 }
857 SYSINIT(elf_linux_vdso_init, SI_SUB_EXEC + 1, SI_ORDER_FIRST,
858     linux_vdso_install, NULL);
859 
860 static void
861 linux_vdso_deinstall(const void *param)
862 {
863 
864 	__elfN(linux_shared_page_fini)(linux_vdso_obj,
865 	    linux_vdso_mapping, LINUX_VDSOPAGE_SIZE);
866 }
867 SYSUNINIT(elf_linux_vdso_uninit, SI_SUB_EXEC, SI_ORDER_FIRST,
868     linux_vdso_deinstall, NULL);
869 
870 static void
871 linux_vdso_reloc(char *mapping, Elf_Addr offset)
872 {
873 	const Elf_Ehdr *ehdr;
874 	const Elf_Shdr *shdr;
875 	Elf64_Addr *where, val;
876 	Elf_Size rtype, symidx;
877 	const Elf_Rela *rela;
878 	Elf_Addr addr, addend;
879 	int relacnt;
880 	int i, j;
881 
882 	MPASS(offset != 0);
883 
884 	relacnt = 0;
885 	ehdr = (const Elf_Ehdr *)mapping;
886 	shdr = (const Elf_Shdr *)(mapping + ehdr->e_shoff);
887 	for (i = 0; i < ehdr->e_shnum; i++)
888 	{
889 		switch (shdr[i].sh_type) {
890 		case SHT_REL:
891 			printf("Linux x86_64 vDSO: unexpected Rel section\n");
892 			break;
893 		case SHT_RELA:
894 			rela = (const Elf_Rela *)(mapping + shdr[i].sh_offset);
895 			relacnt = shdr[i].sh_size / sizeof(*rela);
896 		}
897 	}
898 
899 	for (j = 0; j < relacnt; j++, rela++) {
900 		where = (Elf_Addr *)(mapping + rela->r_offset);
901 		addend = rela->r_addend;
902 		rtype = ELF_R_TYPE(rela->r_info);
903 		symidx = ELF_R_SYM(rela->r_info);
904 
905 		switch (rtype) {
906 		case R_X86_64_NONE:	/* none */
907 			break;
908 
909 		case R_X86_64_RELATIVE:	/* B + A */
910 			addr = (Elf_Addr)(offset + addend);
911 			val = addr;
912 			if (*where != val)
913 				*where = val;
914 			break;
915 		case R_X86_64_IRELATIVE:
916 			printf("Linux x86_64 vDSO: unexpected ifunc relocation, "
917 			    "symbol index %ld\n", symidx);
918 			break;
919 		default:
920 			printf("Linux x86_64 vDSO: unexpected relocation type %ld, "
921 			    "symbol index %ld\n", rtype, symidx);
922 		}
923 	}
924 }
925 
926 static char GNULINUX_ABI_VENDOR[] = "GNU";
927 static int GNULINUX_ABI_DESC = 0;
928 
929 static bool
930 linux_trans_osrel(const Elf_Note *note, int32_t *osrel)
931 {
932 	const Elf32_Word *desc;
933 	uintptr_t p;
934 
935 	p = (uintptr_t)(note + 1);
936 	p += roundup2(note->n_namesz, sizeof(Elf32_Addr));
937 
938 	desc = (const Elf32_Word *)p;
939 	if (desc[0] != GNULINUX_ABI_DESC)
940 		return (false);
941 
942 	/*
943 	 * For Linux we encode osrel using the Linux convention of
944 	 * 	(version << 16) | (major << 8) | (minor)
945 	 * See macro in linux_mib.h
946 	 */
947 	*osrel = LINUX_KERNVER(desc[1], desc[2], desc[3]);
948 
949 	return (true);
950 }
951 
952 static Elf_Brandnote linux64_brandnote = {
953 	.hdr.n_namesz	= sizeof(GNULINUX_ABI_VENDOR),
954 	.hdr.n_descsz	= 16,
955 	.hdr.n_type	= 1,
956 	.vendor		= GNULINUX_ABI_VENDOR,
957 	.flags		= BN_TRANSLATE_OSREL,
958 	.trans_osrel	= linux_trans_osrel
959 };
960 
961 static Elf64_Brandinfo linux_glibc2brand = {
962 	.brand		= ELFOSABI_LINUX,
963 	.machine	= EM_X86_64,
964 	.compat_3_brand	= "Linux",
965 	.emul_path	= linux_emul_path,
966 	.interp_path	= "/lib64/ld-linux-x86-64.so.2",
967 	.sysvec		= &elf_linux_sysvec,
968 	.interp_newpath	= NULL,
969 	.brand_note	= &linux64_brandnote,
970 	.flags		= BI_CAN_EXEC_DYN | BI_BRAND_NOTE
971 };
972 
973 static Elf64_Brandinfo linux_glibc2brandshort = {
974 	.brand		= ELFOSABI_LINUX,
975 	.machine	= EM_X86_64,
976 	.compat_3_brand	= "Linux",
977 	.emul_path	= linux_emul_path,
978 	.interp_path	= "/lib64/ld-linux.so.2",
979 	.sysvec		= &elf_linux_sysvec,
980 	.interp_newpath	= NULL,
981 	.brand_note	= &linux64_brandnote,
982 	.flags		= BI_CAN_EXEC_DYN | BI_BRAND_NOTE
983 };
984 
985 static Elf64_Brandinfo linux_muslbrand = {
986 	.brand		= ELFOSABI_LINUX,
987 	.machine	= EM_X86_64,
988 	.compat_3_brand	= "Linux",
989 	.emul_path	= linux_emul_path,
990 	.interp_path	= "/lib/ld-musl-x86_64.so.1",
991 	.sysvec		= &elf_linux_sysvec,
992 	.interp_newpath	= NULL,
993 	.brand_note	= &linux64_brandnote,
994 	.flags		= BI_CAN_EXEC_DYN | BI_BRAND_NOTE |
995 			    LINUX_BI_FUTEX_REQUEUE
996 };
997 
998 Elf64_Brandinfo *linux_brandlist[] = {
999 	&linux_glibc2brand,
1000 	&linux_glibc2brandshort,
1001 	&linux_muslbrand,
1002 	NULL
1003 };
1004 
1005 static int
1006 linux64_elf_modevent(module_t mod, int type, void *data)
1007 {
1008 	Elf64_Brandinfo **brandinfo;
1009 	int error;
1010 	struct linux_ioctl_handler **lihp;
1011 
1012 	error = 0;
1013 
1014 	switch(type) {
1015 	case MOD_LOAD:
1016 		for (brandinfo = &linux_brandlist[0]; *brandinfo != NULL;
1017 		     ++brandinfo)
1018 			if (elf64_insert_brand_entry(*brandinfo) < 0)
1019 				error = EINVAL;
1020 		if (error == 0) {
1021 			SET_FOREACH(lihp, linux_ioctl_handler_set)
1022 				linux_ioctl_register_handler(*lihp);
1023 			stclohz = (stathz ? stathz : hz);
1024 			if (bootverbose)
1025 				printf("Linux x86-64 ELF exec handler installed\n");
1026 		} else
1027 			printf("cannot insert Linux x86-64 ELF brand handler\n");
1028 		break;
1029 	case MOD_UNLOAD:
1030 		for (brandinfo = &linux_brandlist[0]; *brandinfo != NULL;
1031 		     ++brandinfo)
1032 			if (elf64_brand_inuse(*brandinfo))
1033 				error = EBUSY;
1034 		if (error == 0) {
1035 			for (brandinfo = &linux_brandlist[0];
1036 			     *brandinfo != NULL; ++brandinfo)
1037 				if (elf64_remove_brand_entry(*brandinfo) < 0)
1038 					error = EINVAL;
1039 		}
1040 		if (error == 0) {
1041 			SET_FOREACH(lihp, linux_ioctl_handler_set)
1042 				linux_ioctl_unregister_handler(*lihp);
1043 			if (bootverbose)
1044 				printf("Linux x86_64 ELF exec handler removed\n");
1045 		} else
1046 			printf("Could not deinstall Linux x86_64 ELF interpreter entry\n");
1047 		break;
1048 	default:
1049 		return (EOPNOTSUPP);
1050 	}
1051 	return (error);
1052 }
1053 
1054 static moduledata_t linux64_elf_mod = {
1055 	"linux64elf",
1056 	linux64_elf_modevent,
1057 	0
1058 };
1059 
1060 DECLARE_MODULE_TIED(linux64elf, linux64_elf_mod, SI_SUB_EXEC, SI_ORDER_ANY);
1061 MODULE_DEPEND(linux64elf, linux_common, 1, 1, 1);
1062 FEATURE(linux64, "Linux 64bit support");
1063