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