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