]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/kern_exec.c
Merge ^/head r287527 through r287679.
[FreeBSD/FreeBSD.git] / sys / kern / kern_exec.c
1 /*-
2  * Copyright (c) 1993, David Greenman
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29
30 #include "opt_capsicum.h"
31 #include "opt_hwpmc_hooks.h"
32 #include "opt_ktrace.h"
33 #include "opt_vm.h"
34
35 #include <sys/param.h>
36 #include <sys/capsicum.h>
37 #include <sys/systm.h>
38 #include <sys/eventhandler.h>
39 #include <sys/lock.h>
40 #include <sys/mutex.h>
41 #include <sys/sysproto.h>
42 #include <sys/signalvar.h>
43 #include <sys/kernel.h>
44 #include <sys/mount.h>
45 #include <sys/filedesc.h>
46 #include <sys/fcntl.h>
47 #include <sys/acct.h>
48 #include <sys/exec.h>
49 #include <sys/imgact.h>
50 #include <sys/imgact_elf.h>
51 #include <sys/wait.h>
52 #include <sys/malloc.h>
53 #include <sys/priv.h>
54 #include <sys/proc.h>
55 #include <sys/pioctl.h>
56 #include <sys/namei.h>
57 #include <sys/resourcevar.h>
58 #include <sys/rwlock.h>
59 #include <sys/sched.h>
60 #include <sys/sdt.h>
61 #include <sys/sf_buf.h>
62 #include <sys/syscallsubr.h>
63 #include <sys/sysent.h>
64 #include <sys/shm.h>
65 #include <sys/sysctl.h>
66 #include <sys/vnode.h>
67 #include <sys/stat.h>
68 #ifdef KTRACE
69 #include <sys/ktrace.h>
70 #endif
71
72 #include <vm/vm.h>
73 #include <vm/vm_param.h>
74 #include <vm/pmap.h>
75 #include <vm/vm_page.h>
76 #include <vm/vm_map.h>
77 #include <vm/vm_kern.h>
78 #include <vm/vm_extern.h>
79 #include <vm/vm_object.h>
80 #include <vm/vm_pager.h>
81
82 #ifdef  HWPMC_HOOKS
83 #include <sys/pmckern.h>
84 #endif
85
86 #include <machine/reg.h>
87
88 #include <security/audit/audit.h>
89 #include <security/mac/mac_framework.h>
90
91 #ifdef KDTRACE_HOOKS
92 #include <sys/dtrace_bsd.h>
93 dtrace_execexit_func_t  dtrace_fasttrap_exec;
94 #endif
95
96 SDT_PROVIDER_DECLARE(proc);
97 SDT_PROBE_DEFINE1(proc, kernel, , exec, "char *");
98 SDT_PROBE_DEFINE1(proc, kernel, , exec__failure, "int");
99 SDT_PROBE_DEFINE1(proc, kernel, , exec__success, "char *");
100
101 MALLOC_DEFINE(M_PARGS, "proc-args", "Process arguments");
102
103 int coredump_pack_fileinfo = 1;
104 SYSCTL_INT(_kern, OID_AUTO, coredump_pack_fileinfo, CTLFLAG_RWTUN,
105     &coredump_pack_fileinfo, 0,
106     "Enable file path packing in 'procstat -f' coredump notes");
107
108 static int sysctl_kern_ps_strings(SYSCTL_HANDLER_ARGS);
109 static int sysctl_kern_usrstack(SYSCTL_HANDLER_ARGS);
110 static int sysctl_kern_stackprot(SYSCTL_HANDLER_ARGS);
111 static int do_execve(struct thread *td, struct image_args *args,
112     struct mac *mac_p);
113
114 /* XXX This should be vm_size_t. */
115 SYSCTL_PROC(_kern, KERN_PS_STRINGS, ps_strings, CTLTYPE_ULONG|CTLFLAG_RD,
116     NULL, 0, sysctl_kern_ps_strings, "LU", "");
117
118 /* XXX This should be vm_size_t. */
119 SYSCTL_PROC(_kern, KERN_USRSTACK, usrstack, CTLTYPE_ULONG|CTLFLAG_RD|
120     CTLFLAG_CAPRD, NULL, 0, sysctl_kern_usrstack, "LU", "");
121
122 SYSCTL_PROC(_kern, OID_AUTO, stackprot, CTLTYPE_INT|CTLFLAG_RD,
123     NULL, 0, sysctl_kern_stackprot, "I", "");
124
125 u_long ps_arg_cache_limit = PAGE_SIZE / 16;
126 SYSCTL_ULONG(_kern, OID_AUTO, ps_arg_cache_limit, CTLFLAG_RW, 
127     &ps_arg_cache_limit, 0, "");
128
129 static int disallow_high_osrel;
130 SYSCTL_INT(_kern, OID_AUTO, disallow_high_osrel, CTLFLAG_RW,
131     &disallow_high_osrel, 0,
132     "Disallow execution of binaries built for higher version of the world");
133
134 static int map_at_zero = 0;
135 SYSCTL_INT(_security_bsd, OID_AUTO, map_at_zero, CTLFLAG_RWTUN, &map_at_zero, 0,
136     "Permit processes to map an object at virtual address 0.");
137
138 static int
139 sysctl_kern_ps_strings(SYSCTL_HANDLER_ARGS)
140 {
141         struct proc *p;
142         int error;
143
144         p = curproc;
145 #ifdef SCTL_MASK32
146         if (req->flags & SCTL_MASK32) {
147                 unsigned int val;
148                 val = (unsigned int)p->p_sysent->sv_psstrings;
149                 error = SYSCTL_OUT(req, &val, sizeof(val));
150         } else
151 #endif
152                 error = SYSCTL_OUT(req, &p->p_sysent->sv_psstrings,
153                    sizeof(p->p_sysent->sv_psstrings));
154         return error;
155 }
156
157 static int
158 sysctl_kern_usrstack(SYSCTL_HANDLER_ARGS)
159 {
160         struct proc *p;
161         int error;
162
163         p = curproc;
164 #ifdef SCTL_MASK32
165         if (req->flags & SCTL_MASK32) {
166                 unsigned int val;
167                 val = (unsigned int)p->p_sysent->sv_usrstack;
168                 error = SYSCTL_OUT(req, &val, sizeof(val));
169         } else
170 #endif
171                 error = SYSCTL_OUT(req, &p->p_sysent->sv_usrstack,
172                     sizeof(p->p_sysent->sv_usrstack));
173         return error;
174 }
175
176 static int
177 sysctl_kern_stackprot(SYSCTL_HANDLER_ARGS)
178 {
179         struct proc *p;
180
181         p = curproc;
182         return (SYSCTL_OUT(req, &p->p_sysent->sv_stackprot,
183             sizeof(p->p_sysent->sv_stackprot)));
184 }
185
186 /*
187  * Each of the items is a pointer to a `const struct execsw', hence the
188  * double pointer here.
189  */
190 static const struct execsw **execsw;
191
192 #ifndef _SYS_SYSPROTO_H_
193 struct execve_args {
194         char    *fname; 
195         char    **argv;
196         char    **envv; 
197 };
198 #endif
199
200 int
201 sys_execve(struct thread *td, struct execve_args *uap)
202 {
203         struct image_args args;
204         struct vmspace *oldvmspace;
205         int error;
206
207         error = pre_execve(td, &oldvmspace);
208         if (error != 0)
209                 return (error);
210         error = exec_copyin_args(&args, uap->fname, UIO_USERSPACE,
211             uap->argv, uap->envv);
212         if (error == 0)
213                 error = kern_execve(td, &args, NULL);
214         post_execve(td, error, oldvmspace);
215         return (error);
216 }
217
218 #ifndef _SYS_SYSPROTO_H_
219 struct fexecve_args {
220         int     fd;
221         char    **argv;
222         char    **envv;
223 }
224 #endif
225 int
226 sys_fexecve(struct thread *td, struct fexecve_args *uap)
227 {
228         struct image_args args;
229         struct vmspace *oldvmspace;
230         int error;
231
232         error = pre_execve(td, &oldvmspace);
233         if (error != 0)
234                 return (error);
235         error = exec_copyin_args(&args, NULL, UIO_SYSSPACE,
236             uap->argv, uap->envv);
237         if (error == 0) {
238                 args.fd = uap->fd;
239                 error = kern_execve(td, &args, NULL);
240         }
241         post_execve(td, error, oldvmspace);
242         return (error);
243 }
244
245 #ifndef _SYS_SYSPROTO_H_
246 struct __mac_execve_args {
247         char    *fname;
248         char    **argv;
249         char    **envv;
250         struct mac      *mac_p;
251 };
252 #endif
253
254 int
255 sys___mac_execve(struct thread *td, struct __mac_execve_args *uap)
256 {
257 #ifdef MAC
258         struct image_args args;
259         struct vmspace *oldvmspace;
260         int error;
261
262         error = pre_execve(td, &oldvmspace);
263         if (error != 0)
264                 return (error);
265         error = exec_copyin_args(&args, uap->fname, UIO_USERSPACE,
266             uap->argv, uap->envv);
267         if (error == 0)
268                 error = kern_execve(td, &args, uap->mac_p);
269         post_execve(td, error, oldvmspace);
270         return (error);
271 #else
272         return (ENOSYS);
273 #endif
274 }
275
276 int
277 pre_execve(struct thread *td, struct vmspace **oldvmspace)
278 {
279         struct proc *p;
280         int error;
281
282         KASSERT(td == curthread, ("non-current thread %p", td));
283         error = 0;
284         p = td->td_proc;
285         if ((p->p_flag & P_HADTHREADS) != 0) {
286                 PROC_LOCK(p);
287                 if (thread_single(p, SINGLE_BOUNDARY) != 0)
288                         error = ERESTART;
289                 PROC_UNLOCK(p);
290         }
291         KASSERT(error != 0 || (td->td_pflags & TDP_EXECVMSPC) == 0,
292             ("nested execve"));
293         *oldvmspace = p->p_vmspace;
294         return (error);
295 }
296
297 void
298 post_execve(struct thread *td, int error, struct vmspace *oldvmspace)
299 {
300         struct proc *p;
301
302         KASSERT(td == curthread, ("non-current thread %p", td));
303         p = td->td_proc;
304         if ((p->p_flag & P_HADTHREADS) != 0) {
305                 PROC_LOCK(p);
306                 /*
307                  * If success, we upgrade to SINGLE_EXIT state to
308                  * force other threads to suicide.
309                  */
310                 if (error == 0)
311                         thread_single(p, SINGLE_EXIT);
312                 else
313                         thread_single_end(p, SINGLE_BOUNDARY);
314                 PROC_UNLOCK(p);
315         }
316         if ((td->td_pflags & TDP_EXECVMSPC) != 0) {
317                 KASSERT(p->p_vmspace != oldvmspace,
318                     ("oldvmspace still used"));
319                 vmspace_free(oldvmspace);
320                 td->td_pflags &= ~TDP_EXECVMSPC;
321         }
322 }
323
324 /*
325  * XXX: kern_execve has the astonishing property of not always returning to
326  * the caller.  If sufficiently bad things happen during the call to
327  * do_execve(), it can end up calling exit1(); as a result, callers must
328  * avoid doing anything which they might need to undo (e.g., allocating
329  * memory).
330  */
331 int
332 kern_execve(struct thread *td, struct image_args *args, struct mac *mac_p)
333 {
334
335         AUDIT_ARG_ARGV(args->begin_argv, args->argc,
336             args->begin_envv - args->begin_argv);
337         AUDIT_ARG_ENVV(args->begin_envv, args->envc,
338             args->endp - args->begin_envv);
339         return (do_execve(td, args, mac_p));
340 }
341
342 /*
343  * In-kernel implementation of execve().  All arguments are assumed to be
344  * userspace pointers from the passed thread.
345  */
346 static int
347 do_execve(td, args, mac_p)
348         struct thread *td;
349         struct image_args *args;
350         struct mac *mac_p;
351 {
352         struct proc *p = td->td_proc;
353         struct nameidata nd;
354         struct ucred *newcred = NULL, *oldcred;
355         struct uidinfo *euip = NULL;
356         register_t *stack_base;
357         int error, i;
358         struct image_params image_params, *imgp;
359         struct vattr attr;
360         int (*img_first)(struct image_params *);
361         struct pargs *oldargs = NULL, *newargs = NULL;
362         struct sigacts *oldsigacts, *newsigacts;
363 #ifdef KTRACE
364         struct vnode *tracevp = NULL;
365         struct ucred *tracecred = NULL;
366 #endif
367         struct vnode *oldtextvp = NULL, *newtextvp;
368         cap_rights_t rights;
369         int credential_changing;
370         int textset;
371 #ifdef MAC
372         struct label *interpvplabel = NULL;
373         int will_transition;
374 #endif
375 #ifdef HWPMC_HOOKS
376         struct pmckern_procexec pe;
377 #endif
378         static const char fexecv_proc_title[] = "(fexecv)";
379
380         imgp = &image_params;
381
382         /*
383          * Lock the process and set the P_INEXEC flag to indicate that
384          * it should be left alone until we're done here.  This is
385          * necessary to avoid race conditions - e.g. in ptrace() -
386          * that might allow a local user to illicitly obtain elevated
387          * privileges.
388          */
389         PROC_LOCK(p);
390         KASSERT((p->p_flag & P_INEXEC) == 0,
391             ("%s(): process already has P_INEXEC flag", __func__));
392         p->p_flag |= P_INEXEC;
393         PROC_UNLOCK(p);
394
395         /*
396          * Initialize part of the common data
397          */
398         bzero(imgp, sizeof(*imgp));
399         imgp->proc = p;
400         imgp->attr = &attr;
401         imgp->args = args;
402
403 #ifdef MAC
404         error = mac_execve_enter(imgp, mac_p);
405         if (error)
406                 goto exec_fail;
407 #endif
408
409         /*
410          * Translate the file name. namei() returns a vnode pointer
411          *      in ni_vp amoung other things.
412          *
413          * XXXAUDIT: It would be desirable to also audit the name of the
414          * interpreter if this is an interpreted binary.
415          */
416         if (args->fname != NULL) {
417                 NDINIT(&nd, LOOKUP, ISOPEN | LOCKLEAF | FOLLOW | SAVENAME
418                     | AUDITVNODE1, UIO_SYSSPACE, args->fname, td);
419         }
420
421         SDT_PROBE(proc, kernel, , exec, args->fname, 0, 0, 0, 0 );
422
423 interpret:
424         if (args->fname != NULL) {
425 #ifdef CAPABILITY_MODE
426                 /*
427                  * While capability mode can't reach this point via direct
428                  * path arguments to execve(), we also don't allow
429                  * interpreters to be used in capability mode (for now).
430                  * Catch indirect lookups and return a permissions error.
431                  */
432                 if (IN_CAPABILITY_MODE(td)) {
433                         error = ECAPMODE;
434                         goto exec_fail;
435                 }
436 #endif
437                 error = namei(&nd);
438                 if (error)
439                         goto exec_fail;
440
441                 newtextvp = nd.ni_vp;
442                 imgp->vp = newtextvp;
443         } else {
444                 AUDIT_ARG_FD(args->fd);
445                 /*
446                  * Descriptors opened only with O_EXEC or O_RDONLY are allowed.
447                  */
448                 error = fgetvp_exec(td, args->fd,
449                     cap_rights_init(&rights, CAP_FEXECVE), &newtextvp);
450                 if (error)
451                         goto exec_fail;
452                 vn_lock(newtextvp, LK_EXCLUSIVE | LK_RETRY);
453                 AUDIT_ARG_VNODE1(newtextvp);
454                 imgp->vp = newtextvp;
455         }
456
457         /*
458          * Check file permissions (also 'opens' file)
459          */
460         error = exec_check_permissions(imgp);
461         if (error)
462                 goto exec_fail_dealloc;
463
464         imgp->object = imgp->vp->v_object;
465         if (imgp->object != NULL)
466                 vm_object_reference(imgp->object);
467
468         /*
469          * Set VV_TEXT now so no one can write to the executable while we're
470          * activating it.
471          *
472          * Remember if this was set before and unset it in case this is not
473          * actually an executable image.
474          */
475         textset = VOP_IS_TEXT(imgp->vp);
476         VOP_SET_TEXT(imgp->vp);
477
478         error = exec_map_first_page(imgp);
479         if (error)
480                 goto exec_fail_dealloc;
481
482         imgp->proc->p_osrel = 0;
483         /*
484          *      If the current process has a special image activator it
485          *      wants to try first, call it.   For example, emulating shell
486          *      scripts differently.
487          */
488         error = -1;
489         if ((img_first = imgp->proc->p_sysent->sv_imgact_try) != NULL)
490                 error = img_first(imgp);
491
492         /*
493          *      Loop through the list of image activators, calling each one.
494          *      An activator returns -1 if there is no match, 0 on success,
495          *      and an error otherwise.
496          */
497         for (i = 0; error == -1 && execsw[i]; ++i) {
498                 if (execsw[i]->ex_imgact == NULL ||
499                     execsw[i]->ex_imgact == img_first) {
500                         continue;
501                 }
502                 error = (*execsw[i]->ex_imgact)(imgp);
503         }
504
505         if (error) {
506                 if (error == -1) {
507                         if (textset == 0)
508                                 VOP_UNSET_TEXT(imgp->vp);
509                         error = ENOEXEC;
510                 }
511                 goto exec_fail_dealloc;
512         }
513
514         /*
515          * Special interpreter operation, cleanup and loop up to try to
516          * activate the interpreter.
517          */
518         if (imgp->interpreted) {
519                 exec_unmap_first_page(imgp);
520                 /*
521                  * VV_TEXT needs to be unset for scripts.  There is a short
522                  * period before we determine that something is a script where
523                  * VV_TEXT will be set. The vnode lock is held over this
524                  * entire period so nothing should illegitimately be blocked.
525                  */
526                 VOP_UNSET_TEXT(imgp->vp);
527                 /* free name buffer and old vnode */
528                 if (args->fname != NULL)
529                         NDFREE(&nd, NDF_ONLY_PNBUF);
530 #ifdef MAC
531                 mac_execve_interpreter_enter(newtextvp, &interpvplabel);
532 #endif
533                 if (imgp->opened) {
534                         VOP_CLOSE(newtextvp, FREAD, td->td_ucred, td);
535                         imgp->opened = 0;
536                 }
537                 vput(newtextvp);
538                 vm_object_deallocate(imgp->object);
539                 imgp->object = NULL;
540                 /* set new name to that of the interpreter */
541                 NDINIT(&nd, LOOKUP, LOCKLEAF | FOLLOW | SAVENAME,
542                     UIO_SYSSPACE, imgp->interpreter_name, td);
543                 args->fname = imgp->interpreter_name;
544                 goto interpret;
545         }
546
547         /*
548          * NB: We unlock the vnode here because it is believed that none
549          * of the sv_copyout_strings/sv_fixup operations require the vnode.
550          */
551         VOP_UNLOCK(imgp->vp, 0);
552
553         /*
554          * Do the best to calculate the full path to the image file.
555          */
556         if (imgp->auxargs != NULL &&
557             ((args->fname != NULL && args->fname[0] == '/') ||
558              vn_fullpath(td, imgp->vp, &imgp->execpath, &imgp->freepath) != 0))
559                 imgp->execpath = args->fname;
560
561         if (disallow_high_osrel &&
562             P_OSREL_MAJOR(p->p_osrel) > P_OSREL_MAJOR(__FreeBSD_version)) {
563                 error = ENOEXEC;
564                 uprintf("Osrel %d for image %s too high\n", p->p_osrel,
565                     imgp->execpath != NULL ? imgp->execpath : "<unresolved>");
566                 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
567                 goto exec_fail_dealloc;
568         }
569
570         /* ABI enforces the use of Capsicum. Switch into capabilities mode. */
571         if (SV_PROC_FLAG(p, SV_CAPSICUM))
572                 sys_cap_enter(td, NULL);
573
574         /*
575          * Copy out strings (args and env) and initialize stack base
576          */
577         if (p->p_sysent->sv_copyout_strings)
578                 stack_base = (*p->p_sysent->sv_copyout_strings)(imgp);
579         else
580                 stack_base = exec_copyout_strings(imgp);
581
582         /*
583          * If custom stack fixup routine present for this process
584          * let it do the stack setup.
585          * Else stuff argument count as first item on stack
586          */
587         if (p->p_sysent->sv_fixup != NULL)
588                 (*p->p_sysent->sv_fixup)(&stack_base, imgp);
589         else
590                 suword(--stack_base, imgp->args->argc);
591
592         if (args->fdp != NULL) {
593                 /* Install a brand new file descriptor table. */
594                 fdinstall_remapped(td, args->fdp);
595                 args->fdp = NULL;
596         } else {
597                 /*
598                  * Keep on using the existing file descriptor table. For
599                  * security and other reasons, the file descriptor table
600                  * cannot be shared after an exec.
601                  */
602                 fdunshare(td);
603                 /* close files on exec */
604                 fdcloseexec(td);
605         }
606
607         /*
608          * Malloc things before we need locks.
609          */
610         i = imgp->args->begin_envv - imgp->args->begin_argv;
611         /* Cache arguments if they fit inside our allowance */
612         if (ps_arg_cache_limit >= i + sizeof(struct pargs)) {
613                 newargs = pargs_alloc(i);
614                 bcopy(imgp->args->begin_argv, newargs->ar_args, i);
615         }
616
617         vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
618
619         /*
620          * For security and other reasons, signal handlers cannot
621          * be shared after an exec. The new process gets a copy of the old
622          * handlers. In execsigs(), the new process will have its signals
623          * reset.
624          */
625         if (sigacts_shared(p->p_sigacts)) {
626                 oldsigacts = p->p_sigacts;
627                 newsigacts = sigacts_alloc();
628                 sigacts_copy(newsigacts, oldsigacts);
629         } else {
630                 oldsigacts = NULL;
631                 newsigacts = NULL; /* satisfy gcc */
632         }
633
634         PROC_LOCK(p);
635         if (oldsigacts)
636                 p->p_sigacts = newsigacts;
637         oldcred = p->p_ucred;
638         /* Stop profiling */
639         stopprofclock(p);
640
641         /* reset caught signals */
642         execsigs(p);
643
644         /* name this process - nameiexec(p, ndp) */
645         bzero(p->p_comm, sizeof(p->p_comm));
646         if (args->fname)
647                 bcopy(nd.ni_cnd.cn_nameptr, p->p_comm,
648                     min(nd.ni_cnd.cn_namelen, MAXCOMLEN));
649         else if (vn_commname(newtextvp, p->p_comm, sizeof(p->p_comm)) != 0)
650                 bcopy(fexecv_proc_title, p->p_comm, sizeof(fexecv_proc_title));
651         bcopy(p->p_comm, td->td_name, sizeof(td->td_name));
652 #ifdef KTR
653         sched_clear_tdname(td);
654 #endif
655
656         /*
657          * mark as execed, wakeup the process that vforked (if any) and tell
658          * it that it now has its own resources back
659          */
660         p->p_flag |= P_EXEC;
661         if ((p->p_flag2 & P2_NOTRACE_EXEC) == 0)
662                 p->p_flag2 &= ~P2_NOTRACE;
663         if (p->p_flag & P_PPWAIT) {
664                 p->p_flag &= ~(P_PPWAIT | P_PPTRACE);
665                 cv_broadcast(&p->p_pwait);
666         }
667
668         /*
669          * Implement image setuid/setgid.
670          *
671          * Don't honor setuid/setgid if the filesystem prohibits it or if
672          * the process is being traced.
673          *
674          * We disable setuid/setgid/etc in compatibility mode on the basis
675          * that most setugid applications are not written with that
676          * environment in mind, and will therefore almost certainly operate
677          * incorrectly. In principle there's no reason that setugid
678          * applications might not be useful in capability mode, so we may want
679          * to reconsider this conservative design choice in the future.
680          *
681          * XXXMAC: For the time being, use NOSUID to also prohibit
682          * transitions on the file system.
683          */
684         credential_changing = 0;
685         credential_changing |= (attr.va_mode & S_ISUID) && oldcred->cr_uid !=
686             attr.va_uid;
687         credential_changing |= (attr.va_mode & S_ISGID) && oldcred->cr_gid !=
688             attr.va_gid;
689 #ifdef MAC
690         will_transition = mac_vnode_execve_will_transition(oldcred, imgp->vp,
691             interpvplabel, imgp);
692         credential_changing |= will_transition;
693 #endif
694
695         if (credential_changing &&
696 #ifdef CAPABILITY_MODE
697             ((oldcred->cr_flags & CRED_FLAG_CAPMODE) == 0) &&
698 #endif
699             (imgp->vp->v_mount->mnt_flag & MNT_NOSUID) == 0 &&
700             (p->p_flag & P_TRACED) == 0) {
701                 /*
702                  * Turn off syscall tracing for set-id programs, except for
703                  * root.  Record any set-id flags first to make sure that
704                  * we do not regain any tracing during a possible block.
705                  */
706                 setsugid(p);
707
708 #ifdef KTRACE
709                 if (p->p_tracecred != NULL &&
710                     priv_check_cred(p->p_tracecred, PRIV_DEBUG_DIFFCRED, 0))
711                         ktrprocexec(p, &tracecred, &tracevp);
712 #endif
713                 /*
714                  * Close any file descriptors 0..2 that reference procfs,
715                  * then make sure file descriptors 0..2 are in use.
716                  *
717                  * Both fdsetugidsafety() and fdcheckstd() may call functions
718                  * taking sleepable locks, so temporarily drop our locks.
719                  */
720                 PROC_UNLOCK(p);
721                 VOP_UNLOCK(imgp->vp, 0);
722                 fdsetugidsafety(td);
723                 error = fdcheckstd(td);
724                 if (error != 0)
725                         goto done1;
726                 newcred = crdup(oldcred);
727                 euip = uifind(attr.va_uid);
728                 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
729                 PROC_LOCK(p);
730                 /*
731                  * Set the new credentials.
732                  */
733                 if (attr.va_mode & S_ISUID)
734                         change_euid(newcred, euip);
735                 if (attr.va_mode & S_ISGID)
736                         change_egid(newcred, attr.va_gid);
737 #ifdef MAC
738                 if (will_transition) {
739                         mac_vnode_execve_transition(oldcred, newcred, imgp->vp,
740                             interpvplabel, imgp);
741                 }
742 #endif
743                 /*
744                  * Implement correct POSIX saved-id behavior.
745                  *
746                  * XXXMAC: Note that the current logic will save the
747                  * uid and gid if a MAC domain transition occurs, even
748                  * though maybe it shouldn't.
749                  */
750                 change_svuid(newcred, newcred->cr_uid);
751                 change_svgid(newcred, newcred->cr_gid);
752                 proc_set_cred(p, newcred);
753         } else {
754                 if (oldcred->cr_uid == oldcred->cr_ruid &&
755                     oldcred->cr_gid == oldcred->cr_rgid)
756                         p->p_flag &= ~P_SUGID;
757                 /*
758                  * Implement correct POSIX saved-id behavior.
759                  *
760                  * XXX: It's not clear that the existing behavior is
761                  * POSIX-compliant.  A number of sources indicate that the
762                  * saved uid/gid should only be updated if the new ruid is
763                  * not equal to the old ruid, or the new euid is not equal
764                  * to the old euid and the new euid is not equal to the old
765                  * ruid.  The FreeBSD code always updates the saved uid/gid.
766                  * Also, this code uses the new (replaced) euid and egid as
767                  * the source, which may or may not be the right ones to use.
768                  */
769                 if (oldcred->cr_svuid != oldcred->cr_uid ||
770                     oldcred->cr_svgid != oldcred->cr_gid) {
771                         PROC_UNLOCK(p);
772                         VOP_UNLOCK(imgp->vp, 0);
773                         newcred = crdup(oldcred);
774                         vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
775                         PROC_LOCK(p);
776                         change_svuid(newcred, newcred->cr_uid);
777                         change_svgid(newcred, newcred->cr_gid);
778                         proc_set_cred(p, newcred);
779                 }
780         }
781
782         /*
783          * Store the vp for use in procfs.  This vnode was referenced by namei
784          * or fgetvp_exec.
785          */
786         oldtextvp = p->p_textvp;
787         p->p_textvp = newtextvp;
788
789 #ifdef KDTRACE_HOOKS
790         /*
791          * Tell the DTrace fasttrap provider about the exec if it
792          * has declared an interest.
793          */
794         if (dtrace_fasttrap_exec)
795                 dtrace_fasttrap_exec(p);
796 #endif
797
798         /*
799          * Notify others that we exec'd, and clear the P_INEXEC flag
800          * as we're now a bona fide freshly-execed process.
801          */
802         KNOTE_LOCKED(&p->p_klist, NOTE_EXEC);
803         p->p_flag &= ~P_INEXEC;
804
805         /* clear "fork but no exec" flag, as we _are_ execing */
806         p->p_acflag &= ~AFORK;
807
808         /*
809          * Free any previous argument cache and replace it with
810          * the new argument cache, if any.
811          */
812         oldargs = p->p_args;
813         p->p_args = newargs;
814         newargs = NULL;
815
816 #ifdef  HWPMC_HOOKS
817         /*
818          * Check if system-wide sampling is in effect or if the
819          * current process is using PMCs.  If so, do exec() time
820          * processing.  This processing needs to happen AFTER the
821          * P_INEXEC flag is cleared.
822          *
823          * The proc lock needs to be released before taking the PMC
824          * SX.
825          */
826         if (PMC_SYSTEM_SAMPLING_ACTIVE() || PMC_PROC_IS_USING_PMCS(p)) {
827                 PROC_UNLOCK(p);
828                 VOP_UNLOCK(imgp->vp, 0);
829                 pe.pm_credentialschanged = credential_changing;
830                 pe.pm_entryaddr = imgp->entry_addr;
831
832                 PMC_CALL_HOOK_X(td, PMC_FN_PROCESS_EXEC, (void *) &pe);
833                 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
834         } else
835                 PROC_UNLOCK(p);
836 #else  /* !HWPMC_HOOKS */
837         PROC_UNLOCK(p);
838 #endif
839
840         /* Set values passed into the program in registers. */
841         if (p->p_sysent->sv_setregs)
842                 (*p->p_sysent->sv_setregs)(td, imgp, 
843                     (u_long)(uintptr_t)stack_base);
844         else
845                 exec_setregs(td, imgp, (u_long)(uintptr_t)stack_base);
846
847         vfs_mark_atime(imgp->vp, td->td_ucred);
848
849         SDT_PROBE(proc, kernel, , exec__success, args->fname, 0, 0, 0, 0);
850
851         VOP_UNLOCK(imgp->vp, 0);
852 done1:
853         /*
854          * Free any resources malloc'd earlier that we didn't use.
855          */
856         if (euip != NULL)
857                 uifree(euip);
858         if (newcred != NULL)
859                 crfree(oldcred);
860
861         /*
862          * Handle deferred decrement of ref counts.
863          */
864         if (oldtextvp != NULL)
865                 vrele(oldtextvp);
866 #ifdef KTRACE
867         if (tracevp != NULL)
868                 vrele(tracevp);
869         if (tracecred != NULL)
870                 crfree(tracecred);
871 #endif
872         vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
873         pargs_drop(oldargs);
874         pargs_drop(newargs);
875         if (oldsigacts != NULL)
876                 sigacts_free(oldsigacts);
877
878 exec_fail_dealloc:
879
880         /*
881          * free various allocated resources
882          */
883         if (imgp->firstpage != NULL)
884                 exec_unmap_first_page(imgp);
885
886         if (imgp->vp != NULL) {
887                 if (args->fname)
888                         NDFREE(&nd, NDF_ONLY_PNBUF);
889                 if (imgp->opened)
890                         VOP_CLOSE(imgp->vp, FREAD, td->td_ucred, td);
891                 if (error != 0)
892                         vput(imgp->vp);
893                 else
894                         VOP_UNLOCK(imgp->vp, 0);
895         }
896
897         if (imgp->object != NULL)
898                 vm_object_deallocate(imgp->object);
899
900         free(imgp->freepath, M_TEMP);
901
902         if (error == 0) {
903                 PROC_LOCK(p);
904                 td->td_dbgflags |= TDB_EXEC;
905                 PROC_UNLOCK(p);
906
907                 /*
908                  * Stop the process here if its stop event mask has
909                  * the S_EXEC bit set.
910                  */
911                 STOPEVENT(p, S_EXEC, 0);
912                 goto done2;
913         }
914
915 exec_fail:
916         /* we're done here, clear P_INEXEC */
917         PROC_LOCK(p);
918         p->p_flag &= ~P_INEXEC;
919         PROC_UNLOCK(p);
920
921         SDT_PROBE(proc, kernel, , exec__failure, error, 0, 0, 0, 0);
922
923 done2:
924 #ifdef MAC
925         mac_execve_exit(imgp);
926         mac_execve_interpreter_exit(interpvplabel);
927 #endif
928         exec_free_args(args);
929
930         if (error && imgp->vmspace_destroyed) {
931                 /* sorry, no more process anymore. exit gracefully */
932                 exit1(td, 0, SIGABRT);
933                 /* NOT REACHED */
934         }
935
936 #ifdef KTRACE
937         if (error == 0)
938                 ktrprocctor(p);
939 #endif
940
941         return (error);
942 }
943
944 int
945 exec_map_first_page(imgp)
946         struct image_params *imgp;
947 {
948         int rv, i;
949         int initial_pagein;
950         vm_page_t ma[VM_INITIAL_PAGEIN];
951         vm_object_t object;
952
953         if (imgp->firstpage != NULL)
954                 exec_unmap_first_page(imgp);
955
956         object = imgp->vp->v_object;
957         if (object == NULL)
958                 return (EACCES);
959         VM_OBJECT_WLOCK(object);
960 #if VM_NRESERVLEVEL > 0
961         vm_object_color(object, 0);
962 #endif
963         ma[0] = vm_page_grab(object, 0, VM_ALLOC_NORMAL);
964         if (ma[0]->valid != VM_PAGE_BITS_ALL) {
965                 initial_pagein = VM_INITIAL_PAGEIN;
966                 if (initial_pagein > object->size)
967                         initial_pagein = object->size;
968                 for (i = 1; i < initial_pagein; i++) {
969                         if ((ma[i] = vm_page_next(ma[i - 1])) != NULL) {
970                                 if (ma[i]->valid)
971                                         break;
972                                 if (vm_page_tryxbusy(ma[i]))
973                                         break;
974                         } else {
975                                 ma[i] = vm_page_alloc(object, i,
976                                     VM_ALLOC_NORMAL | VM_ALLOC_IFNOTCACHED);
977                                 if (ma[i] == NULL)
978                                         break;
979                         }
980                 }
981                 initial_pagein = i;
982                 rv = vm_pager_get_pages(object, ma, initial_pagein, 0);
983                 if (rv != VM_PAGER_OK) {
984                         vm_page_lock(ma[0]);
985                         vm_page_free(ma[0]);
986                         vm_page_unlock(ma[0]);
987                         VM_OBJECT_WUNLOCK(object);
988                         return (EIO);
989                 }
990         }
991         vm_page_xunbusy(ma[0]);
992         vm_page_lock(ma[0]);
993         vm_page_hold(ma[0]);
994         vm_page_activate(ma[0]);
995         vm_page_unlock(ma[0]);
996         VM_OBJECT_WUNLOCK(object);
997
998         imgp->firstpage = sf_buf_alloc(ma[0], 0);
999         imgp->image_header = (char *)sf_buf_kva(imgp->firstpage);
1000
1001         return (0);
1002 }
1003
1004 void
1005 exec_unmap_first_page(imgp)
1006         struct image_params *imgp;
1007 {
1008         vm_page_t m;
1009
1010         if (imgp->firstpage != NULL) {
1011                 m = sf_buf_page(imgp->firstpage);
1012                 sf_buf_free(imgp->firstpage);
1013                 imgp->firstpage = NULL;
1014                 vm_page_lock(m);
1015                 vm_page_unhold(m);
1016                 vm_page_unlock(m);
1017         }
1018 }
1019
1020 /*
1021  * Destroy old address space, and allocate a new stack
1022  *      The new stack is only SGROWSIZ large because it is grown
1023  *      automatically in trap.c.
1024  */
1025 int
1026 exec_new_vmspace(imgp, sv)
1027         struct image_params *imgp;
1028         struct sysentvec *sv;
1029 {
1030         int error;
1031         struct proc *p = imgp->proc;
1032         struct vmspace *vmspace = p->p_vmspace;
1033         vm_object_t obj;
1034         struct rlimit rlim_stack;
1035         vm_offset_t sv_minuser, stack_addr;
1036         vm_map_t map;
1037         u_long ssiz;
1038
1039         imgp->vmspace_destroyed = 1;
1040         imgp->sysent = sv;
1041
1042         /* May be called with Giant held */
1043         EVENTHANDLER_INVOKE(process_exec, p, imgp);
1044
1045         /*
1046          * Blow away entire process VM, if address space not shared,
1047          * otherwise, create a new VM space so that other threads are
1048          * not disrupted
1049          */
1050         map = &vmspace->vm_map;
1051         if (map_at_zero)
1052                 sv_minuser = sv->sv_minuser;
1053         else
1054                 sv_minuser = MAX(sv->sv_minuser, PAGE_SIZE);
1055         if (vmspace->vm_refcnt == 1 && vm_map_min(map) == sv_minuser &&
1056             vm_map_max(map) == sv->sv_maxuser) {
1057                 shmexit(vmspace);
1058                 pmap_remove_pages(vmspace_pmap(vmspace));
1059                 vm_map_remove(map, vm_map_min(map), vm_map_max(map));
1060         } else {
1061                 error = vmspace_exec(p, sv_minuser, sv->sv_maxuser);
1062                 if (error)
1063                         return (error);
1064                 vmspace = p->p_vmspace;
1065                 map = &vmspace->vm_map;
1066         }
1067
1068         /* Map a shared page */
1069         obj = sv->sv_shared_page_obj;
1070         if (obj != NULL) {
1071                 vm_object_reference(obj);
1072                 error = vm_map_fixed(map, obj, 0,
1073                     sv->sv_shared_page_base, sv->sv_shared_page_len,
1074                     VM_PROT_READ | VM_PROT_EXECUTE,
1075                     VM_PROT_READ | VM_PROT_EXECUTE,
1076                     MAP_INHERIT_SHARE | MAP_ACC_NO_CHARGE);
1077                 if (error) {
1078                         vm_object_deallocate(obj);
1079                         return (error);
1080                 }
1081         }
1082
1083         /* Allocate a new stack */
1084         if (imgp->stack_sz != 0) {
1085                 ssiz = trunc_page(imgp->stack_sz);
1086                 PROC_LOCK(p);
1087                 lim_rlimit_proc(p, RLIMIT_STACK, &rlim_stack);
1088                 PROC_UNLOCK(p);
1089                 if (ssiz > rlim_stack.rlim_max)
1090                         ssiz = rlim_stack.rlim_max;
1091                 if (ssiz > rlim_stack.rlim_cur) {
1092                         rlim_stack.rlim_cur = ssiz;
1093                         kern_setrlimit(curthread, RLIMIT_STACK, &rlim_stack);
1094                 }
1095         } else if (sv->sv_maxssiz != NULL) {
1096                 ssiz = *sv->sv_maxssiz;
1097         } else {
1098                 ssiz = maxssiz;
1099         }
1100         stack_addr = sv->sv_usrstack - ssiz;
1101         error = vm_map_stack(map, stack_addr, (vm_size_t)ssiz,
1102             obj != NULL && imgp->stack_prot != 0 ? imgp->stack_prot :
1103                 sv->sv_stackprot,
1104             VM_PROT_ALL, MAP_STACK_GROWS_DOWN);
1105         if (error)
1106                 return (error);
1107
1108         /*
1109          * vm_ssize and vm_maxsaddr are somewhat antiquated concepts, but they
1110          * are still used to enforce the stack rlimit on the process stack.
1111          */
1112         vmspace->vm_ssize = sgrowsiz >> PAGE_SHIFT;
1113         vmspace->vm_maxsaddr = (char *)stack_addr;
1114
1115         return (0);
1116 }
1117
1118 /*
1119  * Copy out argument and environment strings from the old process address
1120  * space into the temporary string buffer.
1121  */
1122 int
1123 exec_copyin_args(struct image_args *args, char *fname,
1124     enum uio_seg segflg, char **argv, char **envv)
1125 {
1126         u_long argp, envp;
1127         int error;
1128         size_t length;
1129
1130         bzero(args, sizeof(*args));
1131         if (argv == NULL)
1132                 return (EFAULT);
1133
1134         /*
1135          * Allocate demand-paged memory for the file name, argument, and
1136          * environment strings.
1137          */
1138         error = exec_alloc_args(args);
1139         if (error != 0)
1140                 return (error);
1141
1142         /*
1143          * Copy the file name.
1144          */
1145         if (fname != NULL) {
1146                 args->fname = args->buf;
1147                 error = (segflg == UIO_SYSSPACE) ?
1148                     copystr(fname, args->fname, PATH_MAX, &length) :
1149                     copyinstr(fname, args->fname, PATH_MAX, &length);
1150                 if (error != 0)
1151                         goto err_exit;
1152         } else
1153                 length = 0;
1154
1155         args->begin_argv = args->buf + length;
1156         args->endp = args->begin_argv;
1157         args->stringspace = ARG_MAX;
1158
1159         /*
1160          * extract arguments first
1161          */
1162         for (;;) {
1163                 error = fueword(argv++, &argp);
1164                 if (error == -1) {
1165                         error = EFAULT;
1166                         goto err_exit;
1167                 }
1168                 if (argp == 0)
1169                         break;
1170                 error = copyinstr((void *)(uintptr_t)argp, args->endp,
1171                     args->stringspace, &length);
1172                 if (error != 0) {
1173                         if (error == ENAMETOOLONG) 
1174                                 error = E2BIG;
1175                         goto err_exit;
1176                 }
1177                 args->stringspace -= length;
1178                 args->endp += length;
1179                 args->argc++;
1180         }
1181
1182         args->begin_envv = args->endp;
1183
1184         /*
1185          * extract environment strings
1186          */
1187         if (envv) {
1188                 for (;;) {
1189                         error = fueword(envv++, &envp);
1190                         if (error == -1) {
1191                                 error = EFAULT;
1192                                 goto err_exit;
1193                         }
1194                         if (envp == 0)
1195                                 break;
1196                         error = copyinstr((void *)(uintptr_t)envp,
1197                             args->endp, args->stringspace, &length);
1198                         if (error != 0) {
1199                                 if (error == ENAMETOOLONG)
1200                                         error = E2BIG;
1201                                 goto err_exit;
1202                         }
1203                         args->stringspace -= length;
1204                         args->endp += length;
1205                         args->envc++;
1206                 }
1207         }
1208
1209         return (0);
1210
1211 err_exit:
1212         exec_free_args(args);
1213         return (error);
1214 }
1215
1216 int
1217 exec_copyin_data_fds(struct thread *td, struct image_args *args,
1218     const void *data, size_t datalen, const int *fds, size_t fdslen)
1219 {
1220         struct filedesc *ofdp;
1221         const char *p;
1222         int *kfds;
1223         int error;
1224
1225         memset(args, '\0', sizeof(*args));
1226         ofdp = td->td_proc->p_fd;
1227         if (datalen >= ARG_MAX || fdslen > ofdp->fd_lastfile + 1)
1228                 return (E2BIG);
1229         error = exec_alloc_args(args);
1230         if (error != 0)
1231                 return (error);
1232
1233         args->begin_argv = args->buf;
1234         args->stringspace = ARG_MAX;
1235
1236         if (datalen > 0) {
1237                 /*
1238                  * Argument buffer has been provided. Copy it into the
1239                  * kernel as a single string and add a terminating null
1240                  * byte.
1241                  */
1242                 error = copyin(data, args->begin_argv, datalen);
1243                 if (error != 0)
1244                         goto err_exit;
1245                 args->begin_argv[datalen] = '\0';
1246                 args->endp = args->begin_argv + datalen + 1;
1247                 args->stringspace -= datalen + 1;
1248
1249                 /*
1250                  * Traditional argument counting. Count the number of
1251                  * null bytes.
1252                  */
1253                 for (p = args->begin_argv; p < args->endp; ++p)
1254                         if (*p == '\0')
1255                                 ++args->argc;
1256         } else {
1257                 /* No argument buffer provided. */
1258                 args->endp = args->begin_argv;
1259         }
1260         /* There are no environment variables. */
1261         args->begin_envv = args->endp;
1262
1263         /* Create new file descriptor table. */
1264         kfds = malloc(fdslen * sizeof(int), M_TEMP, M_WAITOK);
1265         error = copyin(fds, kfds, fdslen * sizeof(int));
1266         if (error != 0) {
1267                 free(kfds, M_TEMP);
1268                 goto err_exit;
1269         }
1270         error = fdcopy_remapped(ofdp, kfds, fdslen, &args->fdp);
1271         free(kfds, M_TEMP);
1272         if (error != 0)
1273                 goto err_exit;
1274
1275         return (0);
1276 err_exit:
1277         exec_free_args(args);
1278         return (error);
1279 }
1280
1281 /*
1282  * Allocate temporary demand-paged, zero-filled memory for the file name,
1283  * argument, and environment strings.  Returns zero if the allocation succeeds
1284  * and ENOMEM otherwise.
1285  */
1286 int
1287 exec_alloc_args(struct image_args *args)
1288 {
1289
1290         args->buf = (char *)kmap_alloc_wait(exec_map, PATH_MAX + ARG_MAX);
1291         return (args->buf != NULL ? 0 : ENOMEM);
1292 }
1293
1294 void
1295 exec_free_args(struct image_args *args)
1296 {
1297
1298         if (args->buf != NULL) {
1299                 kmap_free_wakeup(exec_map, (vm_offset_t)args->buf,
1300                     PATH_MAX + ARG_MAX);
1301                 args->buf = NULL;
1302         }
1303         if (args->fname_buf != NULL) {
1304                 free(args->fname_buf, M_TEMP);
1305                 args->fname_buf = NULL;
1306         }
1307         if (args->fdp != NULL)
1308                 fdescfree_remapped(args->fdp);
1309 }
1310
1311 /*
1312  * Copy strings out to the new process address space, constructing new arg
1313  * and env vector tables. Return a pointer to the base so that it can be used
1314  * as the initial stack pointer.
1315  */
1316 register_t *
1317 exec_copyout_strings(imgp)
1318         struct image_params *imgp;
1319 {
1320         int argc, envc;
1321         char **vectp;
1322         char *stringp;
1323         uintptr_t destp;
1324         register_t *stack_base;
1325         struct ps_strings *arginfo;
1326         struct proc *p;
1327         size_t execpath_len;
1328         int szsigcode, szps;
1329         char canary[sizeof(long) * 8];
1330
1331         szps = sizeof(pagesizes[0]) * MAXPAGESIZES;
1332         /*
1333          * Calculate string base and vector table pointers.
1334          * Also deal with signal trampoline code for this exec type.
1335          */
1336         if (imgp->execpath != NULL && imgp->auxargs != NULL)
1337                 execpath_len = strlen(imgp->execpath) + 1;
1338         else
1339                 execpath_len = 0;
1340         p = imgp->proc;
1341         szsigcode = 0;
1342         arginfo = (struct ps_strings *)p->p_sysent->sv_psstrings;
1343         if (p->p_sysent->sv_sigcode_base == 0) {
1344                 if (p->p_sysent->sv_szsigcode != NULL)
1345                         szsigcode = *(p->p_sysent->sv_szsigcode);
1346         }
1347         destp = (uintptr_t)arginfo;
1348
1349         /*
1350          * install sigcode
1351          */
1352         if (szsigcode != 0) {
1353                 destp -= szsigcode;
1354                 destp = rounddown2(destp, sizeof(void *));
1355                 copyout(p->p_sysent->sv_sigcode, (void *)destp, szsigcode);
1356         }
1357
1358         /*
1359          * Copy the image path for the rtld.
1360          */
1361         if (execpath_len != 0) {
1362                 destp -= execpath_len;
1363                 imgp->execpathp = destp;
1364                 copyout(imgp->execpath, (void *)destp, execpath_len);
1365         }
1366
1367         /*
1368          * Prepare the canary for SSP.
1369          */
1370         arc4rand(canary, sizeof(canary), 0);
1371         destp -= sizeof(canary);
1372         imgp->canary = destp;
1373         copyout(canary, (void *)destp, sizeof(canary));
1374         imgp->canarylen = sizeof(canary);
1375
1376         /*
1377          * Prepare the pagesizes array.
1378          */
1379         destp -= szps;
1380         destp = rounddown2(destp, sizeof(void *));
1381         imgp->pagesizes = destp;
1382         copyout(pagesizes, (void *)destp, szps);
1383         imgp->pagesizeslen = szps;
1384
1385         destp -= ARG_MAX - imgp->args->stringspace;
1386         destp = rounddown2(destp, sizeof(void *));
1387
1388         /*
1389          * If we have a valid auxargs ptr, prepare some room
1390          * on the stack.
1391          */
1392         if (imgp->auxargs) {
1393                 /*
1394                  * 'AT_COUNT*2' is size for the ELF Auxargs data. This is for
1395                  * lower compatibility.
1396                  */
1397                 imgp->auxarg_size = (imgp->auxarg_size) ? imgp->auxarg_size :
1398                     (AT_COUNT * 2);
1399                 /*
1400                  * The '+ 2' is for the null pointers at the end of each of
1401                  * the arg and env vector sets,and imgp->auxarg_size is room
1402                  * for argument of Runtime loader.
1403                  */
1404                 vectp = (char **)(destp - (imgp->args->argc +
1405                     imgp->args->envc + 2 + imgp->auxarg_size)
1406                     * sizeof(char *));
1407         } else {
1408                 /*
1409                  * The '+ 2' is for the null pointers at the end of each of
1410                  * the arg and env vector sets
1411                  */
1412                 vectp = (char **)(destp - (imgp->args->argc + imgp->args->envc
1413                     + 2) * sizeof(char *));
1414         }
1415
1416         /*
1417          * vectp also becomes our initial stack base
1418          */
1419         stack_base = (register_t *)vectp;
1420
1421         stringp = imgp->args->begin_argv;
1422         argc = imgp->args->argc;
1423         envc = imgp->args->envc;
1424
1425         /*
1426          * Copy out strings - arguments and environment.
1427          */
1428         copyout(stringp, (void *)destp, ARG_MAX - imgp->args->stringspace);
1429
1430         /*
1431          * Fill in "ps_strings" struct for ps, w, etc.
1432          */
1433         suword(&arginfo->ps_argvstr, (long)(intptr_t)vectp);
1434         suword32(&arginfo->ps_nargvstr, argc);
1435
1436         /*
1437          * Fill in argument portion of vector table.
1438          */
1439         for (; argc > 0; --argc) {
1440                 suword(vectp++, (long)(intptr_t)destp);
1441                 while (*stringp++ != 0)
1442                         destp++;
1443                 destp++;
1444         }
1445
1446         /* a null vector table pointer separates the argp's from the envp's */
1447         suword(vectp++, 0);
1448
1449         suword(&arginfo->ps_envstr, (long)(intptr_t)vectp);
1450         suword32(&arginfo->ps_nenvstr, envc);
1451
1452         /*
1453          * Fill in environment portion of vector table.
1454          */
1455         for (; envc > 0; --envc) {
1456                 suword(vectp++, (long)(intptr_t)destp);
1457                 while (*stringp++ != 0)
1458                         destp++;
1459                 destp++;
1460         }
1461
1462         /* end of vector table is a null pointer */
1463         suword(vectp, 0);
1464
1465         return (stack_base);
1466 }
1467
1468 /*
1469  * Check permissions of file to execute.
1470  *      Called with imgp->vp locked.
1471  *      Return 0 for success or error code on failure.
1472  */
1473 int
1474 exec_check_permissions(imgp)
1475         struct image_params *imgp;
1476 {
1477         struct vnode *vp = imgp->vp;
1478         struct vattr *attr = imgp->attr;
1479         struct thread *td;
1480         int error, writecount;
1481
1482         td = curthread;
1483
1484         /* Get file attributes */
1485         error = VOP_GETATTR(vp, attr, td->td_ucred);
1486         if (error)
1487                 return (error);
1488
1489 #ifdef MAC
1490         error = mac_vnode_check_exec(td->td_ucred, imgp->vp, imgp);
1491         if (error)
1492                 return (error);
1493 #endif
1494
1495         /*
1496          * 1) Check if file execution is disabled for the filesystem that
1497          *    this file resides on.
1498          * 2) Ensure that at least one execute bit is on. Otherwise, a
1499          *    privileged user will always succeed, and we don't want this
1500          *    to happen unless the file really is executable.
1501          * 3) Ensure that the file is a regular file.
1502          */
1503         if ((vp->v_mount->mnt_flag & MNT_NOEXEC) ||
1504             (attr->va_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) == 0 ||
1505             (attr->va_type != VREG))
1506                 return (EACCES);
1507
1508         /*
1509          * Zero length files can't be exec'd
1510          */
1511         if (attr->va_size == 0)
1512                 return (ENOEXEC);
1513
1514         /*
1515          *  Check for execute permission to file based on current credentials.
1516          */
1517         error = VOP_ACCESS(vp, VEXEC, td->td_ucred, td);
1518         if (error)
1519                 return (error);
1520
1521         /*
1522          * Check number of open-for-writes on the file and deny execution
1523          * if there are any.
1524          */
1525         error = VOP_GET_WRITECOUNT(vp, &writecount);
1526         if (error != 0)
1527                 return (error);
1528         if (writecount != 0)
1529                 return (ETXTBSY);
1530
1531         /*
1532          * Call filesystem specific open routine (which does nothing in the
1533          * general case).
1534          */
1535         error = VOP_OPEN(vp, FREAD, td->td_ucred, td, NULL);
1536         if (error == 0)
1537                 imgp->opened = 1;
1538         return (error);
1539 }
1540
1541 /*
1542  * Exec handler registration
1543  */
1544 int
1545 exec_register(execsw_arg)
1546         const struct execsw *execsw_arg;
1547 {
1548         const struct execsw **es, **xs, **newexecsw;
1549         int count = 2;  /* New slot and trailing NULL */
1550
1551         if (execsw)
1552                 for (es = execsw; *es; es++)
1553                         count++;
1554         newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
1555         if (newexecsw == NULL)
1556                 return (ENOMEM);
1557         xs = newexecsw;
1558         if (execsw)
1559                 for (es = execsw; *es; es++)
1560                         *xs++ = *es;
1561         *xs++ = execsw_arg;
1562         *xs = NULL;
1563         if (execsw)
1564                 free(execsw, M_TEMP);
1565         execsw = newexecsw;
1566         return (0);
1567 }
1568
1569 int
1570 exec_unregister(execsw_arg)
1571         const struct execsw *execsw_arg;
1572 {
1573         const struct execsw **es, **xs, **newexecsw;
1574         int count = 1;
1575
1576         if (execsw == NULL)
1577                 panic("unregister with no handlers left?\n");
1578
1579         for (es = execsw; *es; es++) {
1580                 if (*es == execsw_arg)
1581                         break;
1582         }
1583         if (*es == NULL)
1584                 return (ENOENT);
1585         for (es = execsw; *es; es++)
1586                 if (*es != execsw_arg)
1587                         count++;
1588         newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
1589         if (newexecsw == NULL)
1590                 return (ENOMEM);
1591         xs = newexecsw;
1592         for (es = execsw; *es; es++)
1593                 if (*es != execsw_arg)
1594                         *xs++ = *es;
1595         *xs = NULL;
1596         if (execsw)
1597                 free(execsw, M_TEMP);
1598         execsw = newexecsw;
1599         return (0);
1600 }