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