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