kern_exec.c revision 1.360 1 /* $NetBSD: kern_exec.c,v 1.360 2013/04/20 22:28:58 christos Exp $ */
2
3 /*-
4 * Copyright (c) 2008 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
17 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
18 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
20 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 * POSSIBILITY OF SUCH DAMAGE.
27 */
28
29 /*-
30 * Copyright (C) 1993, 1994, 1996 Christopher G. Demetriou
31 * Copyright (C) 1992 Wolfgang Solfrank.
32 * Copyright (C) 1992 TooLs GmbH.
33 * All rights reserved.
34 *
35 * Redistribution and use in source and binary forms, with or without
36 * modification, are permitted provided that the following conditions
37 * are met:
38 * 1. Redistributions of source code must retain the above copyright
39 * notice, this list of conditions and the following disclaimer.
40 * 2. Redistributions in binary form must reproduce the above copyright
41 * notice, this list of conditions and the following disclaimer in the
42 * documentation and/or other materials provided with the distribution.
43 * 3. All advertising materials mentioning features or use of this software
44 * must display the following acknowledgement:
45 * This product includes software developed by TooLs GmbH.
46 * 4. The name of TooLs GmbH may not be used to endorse or promote products
47 * derived from this software without specific prior written permission.
48 *
49 * THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``AS IS'' AND ANY EXPRESS OR
50 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
51 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
52 * IN NO EVENT SHALL TOOLS GMBH BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
53 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
54 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
55 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
56 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
57 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
58 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
59 */
60
61 #include <sys/cdefs.h>
62 __KERNEL_RCSID(0, "$NetBSD: kern_exec.c,v 1.360 2013/04/20 22:28:58 christos Exp $");
63
64 #include "opt_exec.h"
65 #include "opt_execfmt.h"
66 #include "opt_ktrace.h"
67 #include "opt_modular.h"
68 #include "opt_syscall_debug.h"
69 #include "veriexec.h"
70 #include "opt_pax.h"
71
72 #include <sys/param.h>
73 #include <sys/systm.h>
74 #include <sys/filedesc.h>
75 #include <sys/kernel.h>
76 #include <sys/proc.h>
77 #include <sys/mount.h>
78 #include <sys/malloc.h>
79 #include <sys/kmem.h>
80 #include <sys/namei.h>
81 #include <sys/vnode.h>
82 #include <sys/file.h>
83 #include <sys/acct.h>
84 #include <sys/atomic.h>
85 #include <sys/exec.h>
86 #include <sys/ktrace.h>
87 #include <sys/uidinfo.h>
88 #include <sys/wait.h>
89 #include <sys/mman.h>
90 #include <sys/ras.h>
91 #include <sys/signalvar.h>
92 #include <sys/stat.h>
93 #include <sys/syscall.h>
94 #include <sys/kauth.h>
95 #include <sys/lwpctl.h>
96 #include <sys/pax.h>
97 #include <sys/cpu.h>
98 #include <sys/module.h>
99 #include <sys/syscallvar.h>
100 #include <sys/syscallargs.h>
101 #if NVERIEXEC > 0
102 #include <sys/verified_exec.h>
103 #endif /* NVERIEXEC > 0 */
104 #include <sys/sdt.h>
105 #include <sys/spawn.h>
106 #include <sys/prot.h>
107 #include <sys/cprng.h>
108
109 #include <uvm/uvm_extern.h>
110
111 #include <machine/reg.h>
112
113 #include <compat/common/compat_util.h>
114
115 static int exec_sigcode_map(struct proc *, const struct emul *);
116
117 #ifdef DEBUG_EXEC
118 #define DPRINTF(a) printf a
119 #define COPYPRINTF(s, a, b) printf("%s, %d: copyout%s @%p %zu\n", __func__, \
120 __LINE__, (s), (a), (b))
121 #else
122 #define DPRINTF(a)
123 #define COPYPRINTF(s, a, b)
124 #endif /* DEBUG_EXEC */
125
126 /*
127 * DTrace SDT provider definitions
128 */
129 SDT_PROBE_DEFINE(proc,,,exec,
130 "char *", NULL,
131 NULL, NULL, NULL, NULL,
132 NULL, NULL, NULL, NULL);
133 SDT_PROBE_DEFINE(proc,,,exec_success,
134 "char *", NULL,
135 NULL, NULL, NULL, NULL,
136 NULL, NULL, NULL, NULL);
137 SDT_PROBE_DEFINE(proc,,,exec_failure,
138 "int", NULL,
139 NULL, NULL, NULL, NULL,
140 NULL, NULL, NULL, NULL);
141
142 /*
143 * Exec function switch:
144 *
145 * Note that each makecmds function is responsible for loading the
146 * exec package with the necessary functions for any exec-type-specific
147 * handling.
148 *
149 * Functions for specific exec types should be defined in their own
150 * header file.
151 */
152 static const struct execsw **execsw = NULL;
153 static int nexecs;
154
155 u_int exec_maxhdrsz; /* must not be static - used by netbsd32 */
156
157 /* list of dynamically loaded execsw entries */
158 static LIST_HEAD(execlist_head, exec_entry) ex_head =
159 LIST_HEAD_INITIALIZER(ex_head);
160 struct exec_entry {
161 LIST_ENTRY(exec_entry) ex_list;
162 SLIST_ENTRY(exec_entry) ex_slist;
163 const struct execsw *ex_sw;
164 };
165
166 #ifndef __HAVE_SYSCALL_INTERN
167 void syscall(void);
168 #endif
169
170 /* NetBSD emul struct */
171 struct emul emul_netbsd = {
172 .e_name = "netbsd",
173 .e_path = NULL,
174 #ifndef __HAVE_MINIMAL_EMUL
175 .e_flags = EMUL_HAS_SYS___syscall,
176 .e_errno = NULL,
177 .e_nosys = SYS_syscall,
178 .e_nsysent = SYS_NSYSENT,
179 #endif
180 .e_sysent = sysent,
181 #ifdef SYSCALL_DEBUG
182 .e_syscallnames = syscallnames,
183 #else
184 .e_syscallnames = NULL,
185 #endif
186 .e_sendsig = sendsig,
187 .e_trapsignal = trapsignal,
188 .e_tracesig = NULL,
189 .e_sigcode = NULL,
190 .e_esigcode = NULL,
191 .e_sigobject = NULL,
192 .e_setregs = setregs,
193 .e_proc_exec = NULL,
194 .e_proc_fork = NULL,
195 .e_proc_exit = NULL,
196 .e_lwp_fork = NULL,
197 .e_lwp_exit = NULL,
198 #ifdef __HAVE_SYSCALL_INTERN
199 .e_syscall_intern = syscall_intern,
200 #else
201 .e_syscall = syscall,
202 #endif
203 .e_sysctlovly = NULL,
204 .e_fault = NULL,
205 .e_vm_default_addr = uvm_default_mapaddr,
206 .e_usertrap = NULL,
207 .e_ucsize = sizeof(ucontext_t),
208 .e_startlwp = startlwp
209 };
210
211 /*
212 * Exec lock. Used to control access to execsw[] structures.
213 * This must not be static so that netbsd32 can access it, too.
214 */
215 krwlock_t exec_lock;
216
217 static kmutex_t sigobject_lock;
218
219 /*
220 * Data used between a loadvm and execve part of an "exec" operation
221 */
222 struct execve_data {
223 struct exec_package ed_pack;
224 struct pathbuf *ed_pathbuf;
225 struct vattr ed_attr;
226 struct ps_strings ed_arginfo;
227 char *ed_argp;
228 const char *ed_pathstring;
229 char *ed_resolvedpathbuf;
230 size_t ed_ps_strings_sz;
231 int ed_szsigcode;
232 long ed_argc;
233 long ed_envc;
234 };
235
236 /*
237 * data passed from parent lwp to child during a posix_spawn()
238 */
239 struct spawn_exec_data {
240 struct execve_data sed_exec;
241 struct posix_spawn_file_actions
242 *sed_actions;
243 struct posix_spawnattr *sed_attrs;
244 struct proc *sed_parent;
245 kcondvar_t sed_cv_child_ready;
246 kmutex_t sed_mtx_child;
247 int sed_error;
248 volatile uint32_t sed_refcnt;
249 };
250
251 static void *
252 exec_pool_alloc(struct pool *pp, int flags)
253 {
254
255 return (void *)uvm_km_alloc(kernel_map, NCARGS, 0,
256 UVM_KMF_PAGEABLE | UVM_KMF_WAITVA);
257 }
258
259 static void
260 exec_pool_free(struct pool *pp, void *addr)
261 {
262
263 uvm_km_free(kernel_map, (vaddr_t)addr, NCARGS, UVM_KMF_PAGEABLE);
264 }
265
266 static struct pool exec_pool;
267
268 static struct pool_allocator exec_palloc = {
269 .pa_alloc = exec_pool_alloc,
270 .pa_free = exec_pool_free,
271 .pa_pagesz = NCARGS
272 };
273
274 /*
275 * check exec:
276 * given an "executable" described in the exec package's namei info,
277 * see what we can do with it.
278 *
279 * ON ENTRY:
280 * exec package with appropriate namei info
281 * lwp pointer of exec'ing lwp
282 * NO SELF-LOCKED VNODES
283 *
284 * ON EXIT:
285 * error: nothing held, etc. exec header still allocated.
286 * ok: filled exec package, executable's vnode (unlocked).
287 *
288 * EXEC SWITCH ENTRY:
289 * Locked vnode to check, exec package, proc.
290 *
291 * EXEC SWITCH EXIT:
292 * ok: return 0, filled exec package, executable's vnode (unlocked).
293 * error: destructive:
294 * everything deallocated execept exec header.
295 * non-destructive:
296 * error code, executable's vnode (unlocked),
297 * exec header unmodified.
298 */
299 int
300 /*ARGSUSED*/
301 check_exec(struct lwp *l, struct exec_package *epp, struct pathbuf *pb)
302 {
303 int error, i;
304 struct vnode *vp;
305 struct nameidata nd;
306 size_t resid;
307
308 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | TRYEMULROOT, pb);
309
310 /* first get the vnode */
311 if ((error = namei(&nd)) != 0)
312 return error;
313 epp->ep_vp = vp = nd.ni_vp;
314 /* this cannot overflow as both are size PATH_MAX */
315 strcpy(epp->ep_resolvedname, nd.ni_pnbuf);
316
317 #ifdef DIAGNOSTIC
318 /* paranoia (take this out once namei stuff stabilizes) */
319 memset(nd.ni_pnbuf, '~', PATH_MAX);
320 #endif
321
322 /* check access and type */
323 if (vp->v_type != VREG) {
324 error = EACCES;
325 goto bad1;
326 }
327 if ((error = VOP_ACCESS(vp, VEXEC, l->l_cred)) != 0)
328 goto bad1;
329
330 /* get attributes */
331 if ((error = VOP_GETATTR(vp, epp->ep_vap, l->l_cred)) != 0)
332 goto bad1;
333
334 /* Check mount point */
335 if (vp->v_mount->mnt_flag & MNT_NOEXEC) {
336 error = EACCES;
337 goto bad1;
338 }
339 if (vp->v_mount->mnt_flag & MNT_NOSUID)
340 epp->ep_vap->va_mode &= ~(S_ISUID | S_ISGID);
341
342 /* try to open it */
343 if ((error = VOP_OPEN(vp, FREAD, l->l_cred)) != 0)
344 goto bad1;
345
346 /* unlock vp, since we need it unlocked from here on out. */
347 VOP_UNLOCK(vp);
348
349 #if NVERIEXEC > 0
350 error = veriexec_verify(l, vp, epp->ep_resolvedname,
351 epp->ep_flags & EXEC_INDIR ? VERIEXEC_INDIRECT : VERIEXEC_DIRECT,
352 NULL);
353 if (error)
354 goto bad2;
355 #endif /* NVERIEXEC > 0 */
356
357 #ifdef PAX_SEGVGUARD
358 error = pax_segvguard(l, vp, epp->ep_resolvedname, false);
359 if (error)
360 goto bad2;
361 #endif /* PAX_SEGVGUARD */
362
363 /* now we have the file, get the exec header */
364 error = vn_rdwr(UIO_READ, vp, epp->ep_hdr, epp->ep_hdrlen, 0,
365 UIO_SYSSPACE, 0, l->l_cred, &resid, NULL);
366 if (error)
367 goto bad2;
368 epp->ep_hdrvalid = epp->ep_hdrlen - resid;
369
370 /*
371 * Set up default address space limits. Can be overridden
372 * by individual exec packages.
373 *
374 * XXX probably should be all done in the exec packages.
375 */
376 epp->ep_vm_minaddr = VM_MIN_ADDRESS;
377 epp->ep_vm_maxaddr = VM_MAXUSER_ADDRESS;
378 /*
379 * set up the vmcmds for creation of the process
380 * address space
381 */
382 error = ENOEXEC;
383 for (i = 0; i < nexecs; i++) {
384 int newerror;
385
386 epp->ep_esch = execsw[i];
387 newerror = (*execsw[i]->es_makecmds)(l, epp);
388
389 if (!newerror) {
390 /* Seems ok: check that entry point is not too high */
391 if (epp->ep_entry > epp->ep_vm_maxaddr) {
392 #ifdef DIAGNOSTIC
393 printf("%s: rejecting %p due to "
394 "too high entry address (> %p)\n",
395 __func__, (void *)epp->ep_entry,
396 (void *)epp->ep_vm_maxaddr);
397 #endif
398 error = ENOEXEC;
399 break;
400 }
401 /* Seems ok: check that entry point is not too low */
402 if (epp->ep_entry < epp->ep_vm_minaddr) {
403 #ifdef DIAGNOSTIC
404 printf("%s: rejecting %p due to "
405 "too low entry address (< %p)\n",
406 __func__, (void *)epp->ep_entry,
407 (void *)epp->ep_vm_minaddr);
408 #endif
409 error = ENOEXEC;
410 break;
411 }
412
413 /* check limits */
414 if ((epp->ep_tsize > MAXTSIZ) ||
415 (epp->ep_dsize > (u_quad_t)l->l_proc->p_rlimit
416 [RLIMIT_DATA].rlim_cur)) {
417 #ifdef DIAGNOSTIC
418 printf("%s: rejecting due to "
419 "limits (t=%llu > %llu || d=%llu > %llu)\n",
420 __func__,
421 (unsigned long long)epp->ep_tsize,
422 (unsigned long long)MAXTSIZ,
423 (unsigned long long)epp->ep_dsize,
424 (unsigned long long)
425 l->l_proc->p_rlimit[RLIMIT_DATA].rlim_cur);
426 #endif
427 error = ENOMEM;
428 break;
429 }
430 return 0;
431 }
432
433 if (epp->ep_emul_root != NULL) {
434 vrele(epp->ep_emul_root);
435 epp->ep_emul_root = NULL;
436 }
437 if (epp->ep_interp != NULL) {
438 vrele(epp->ep_interp);
439 epp->ep_interp = NULL;
440 }
441
442 /* make sure the first "interesting" error code is saved. */
443 if (error == ENOEXEC)
444 error = newerror;
445
446 if (epp->ep_flags & EXEC_DESTR)
447 /* Error from "#!" code, tidied up by recursive call */
448 return error;
449 }
450
451 /* not found, error */
452
453 /*
454 * free any vmspace-creation commands,
455 * and release their references
456 */
457 kill_vmcmds(&epp->ep_vmcmds);
458
459 bad2:
460 /*
461 * close and release the vnode, restore the old one, free the
462 * pathname buf, and punt.
463 */
464 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
465 VOP_CLOSE(vp, FREAD, l->l_cred);
466 vput(vp);
467 return error;
468
469 bad1:
470 /*
471 * free the namei pathname buffer, and put the vnode
472 * (which we don't yet have open).
473 */
474 vput(vp); /* was still locked */
475 return error;
476 }
477
478 #ifdef __MACHINE_STACK_GROWS_UP
479 #define STACK_PTHREADSPACE NBPG
480 #else
481 #define STACK_PTHREADSPACE 0
482 #endif
483
484 static int
485 execve_fetch_element(char * const *array, size_t index, char **value)
486 {
487 return copyin(array + index, value, sizeof(*value));
488 }
489
490 /*
491 * exec system call
492 */
493 int
494 sys_execve(struct lwp *l, const struct sys_execve_args *uap, register_t *retval)
495 {
496 /* {
497 syscallarg(const char *) path;
498 syscallarg(char * const *) argp;
499 syscallarg(char * const *) envp;
500 } */
501
502 return execve1(l, SCARG(uap, path), SCARG(uap, argp),
503 SCARG(uap, envp), execve_fetch_element);
504 }
505
506 int
507 sys_fexecve(struct lwp *l, const struct sys_fexecve_args *uap,
508 register_t *retval)
509 {
510 /* {
511 syscallarg(int) fd;
512 syscallarg(char * const *) argp;
513 syscallarg(char * const *) envp;
514 } */
515
516 return ENOSYS;
517 }
518
519 /*
520 * Load modules to try and execute an image that we do not understand.
521 * If no execsw entries are present, we load those likely to be needed
522 * in order to run native images only. Otherwise, we autoload all
523 * possible modules that could let us run the binary. XXX lame
524 */
525 static void
526 exec_autoload(void)
527 {
528 #ifdef MODULAR
529 static const char * const native[] = {
530 "exec_elf32",
531 "exec_elf64",
532 "exec_script",
533 NULL
534 };
535 static const char * const compat[] = {
536 "exec_elf32",
537 "exec_elf64",
538 "exec_script",
539 "exec_aout",
540 "exec_coff",
541 "exec_ecoff",
542 "compat_aoutm68k",
543 "compat_freebsd",
544 "compat_ibcs2",
545 "compat_linux",
546 "compat_linux32",
547 "compat_netbsd32",
548 "compat_sunos",
549 "compat_sunos32",
550 "compat_svr4",
551 "compat_svr4_32",
552 "compat_ultrix",
553 NULL
554 };
555 char const * const *list;
556 int i;
557
558 list = (nexecs == 0 ? native : compat);
559 for (i = 0; list[i] != NULL; i++) {
560 if (module_autoload(list[i], MODULE_CLASS_MISC) != 0) {
561 continue;
562 }
563 yield();
564 }
565 #endif
566 }
567
568 static int
569 execve_loadvm(struct lwp *l, const char *path, char * const *args,
570 char * const *envs, execve_fetch_element_t fetch_element,
571 struct execve_data * restrict data)
572 {
573 int error;
574 struct proc *p;
575 char *dp, *sp;
576 size_t i, len;
577 struct exec_fakearg *tmpfap;
578 u_int modgen;
579
580 KASSERT(data != NULL);
581
582 p = l->l_proc;
583 modgen = 0;
584
585 SDT_PROBE(proc,,,exec, path, 0, 0, 0, 0);
586
587 /*
588 * Check if we have exceeded our number of processes limit.
589 * This is so that we handle the case where a root daemon
590 * forked, ran setuid to become the desired user and is trying
591 * to exec. The obvious place to do the reference counting check
592 * is setuid(), but we don't do the reference counting check there
593 * like other OS's do because then all the programs that use setuid()
594 * must be modified to check the return code of setuid() and exit().
595 * It is dangerous to make setuid() fail, because it fails open and
596 * the program will continue to run as root. If we make it succeed
597 * and return an error code, again we are not enforcing the limit.
598 * The best place to enforce the limit is here, when the process tries
599 * to execute a new image, because eventually the process will need
600 * to call exec in order to do something useful.
601 */
602 retry:
603 if (p->p_flag & PK_SUGID) {
604 if (kauth_authorize_process(l->l_cred, KAUTH_PROCESS_RLIMIT,
605 p, KAUTH_ARG(KAUTH_REQ_PROCESS_RLIMIT_BYPASS),
606 &p->p_rlimit[RLIMIT_NPROC],
607 KAUTH_ARG(RLIMIT_NPROC)) != 0 &&
608 chgproccnt(kauth_cred_getuid(l->l_cred), 0) >
609 p->p_rlimit[RLIMIT_NPROC].rlim_cur)
610 return EAGAIN;
611 }
612
613 /*
614 * Drain existing references and forbid new ones. The process
615 * should be left alone until we're done here. This is necessary
616 * to avoid race conditions - e.g. in ptrace() - that might allow
617 * a local user to illicitly obtain elevated privileges.
618 */
619 rw_enter(&p->p_reflock, RW_WRITER);
620
621 /*
622 * Init the namei data to point the file user's program name.
623 * This is done here rather than in check_exec(), so that it's
624 * possible to override this settings if any of makecmd/probe
625 * functions call check_exec() recursively - for example,
626 * see exec_script_makecmds().
627 */
628 error = pathbuf_copyin(path, &data->ed_pathbuf);
629 if (error) {
630 DPRINTF(("%s: pathbuf_copyin path @%p %d\n", __func__,
631 path, error));
632 goto clrflg;
633 }
634 data->ed_pathstring = pathbuf_stringcopy_get(data->ed_pathbuf);
635
636 data->ed_resolvedpathbuf = PNBUF_GET();
637 #ifdef DIAGNOSTIC
638 strcpy(data->ed_resolvedpathbuf, "/wrong");
639 #endif
640
641 /*
642 * initialize the fields of the exec package.
643 */
644 data->ed_pack.ep_name = path;
645 data->ed_pack.ep_kname = data->ed_pathstring;
646 data->ed_pack.ep_resolvedname = data->ed_resolvedpathbuf;
647 data->ed_pack.ep_hdr = kmem_alloc(exec_maxhdrsz, KM_SLEEP);
648 data->ed_pack.ep_hdrlen = exec_maxhdrsz;
649 data->ed_pack.ep_hdrvalid = 0;
650 data->ed_pack.ep_emul_arg = NULL;
651 data->ed_pack.ep_emul_arg_free = NULL;
652 data->ed_pack.ep_vmcmds.evs_cnt = 0;
653 data->ed_pack.ep_vmcmds.evs_used = 0;
654 data->ed_pack.ep_vap = &data->ed_attr;
655 data->ed_pack.ep_flags = 0;
656 data->ed_pack.ep_emul_root = NULL;
657 data->ed_pack.ep_interp = NULL;
658 data->ed_pack.ep_esch = NULL;
659 data->ed_pack.ep_pax_flags = 0;
660
661 rw_enter(&exec_lock, RW_READER);
662
663 /* see if we can run it. */
664 if ((error = check_exec(l, &data->ed_pack, data->ed_pathbuf)) != 0) {
665 if (error != ENOENT) {
666 DPRINTF(("%s: check exec failed %d\n",
667 __func__, error));
668 }
669 goto freehdr;
670 }
671
672 /* XXX -- THE FOLLOWING SECTION NEEDS MAJOR CLEANUP */
673
674 /* allocate an argument buffer */
675 data->ed_argp = pool_get(&exec_pool, PR_WAITOK);
676 KASSERT(data->ed_argp != NULL);
677 dp = data->ed_argp;
678 data->ed_argc = 0;
679
680 /* copy the fake args list, if there's one, freeing it as we go */
681 if (data->ed_pack.ep_flags & EXEC_HASARGL) {
682 tmpfap = data->ed_pack.ep_fa;
683 while (tmpfap->fa_arg != NULL) {
684 const char *cp;
685
686 cp = tmpfap->fa_arg;
687 while (*cp)
688 *dp++ = *cp++;
689 *dp++ = '\0';
690 ktrexecarg(tmpfap->fa_arg, cp - tmpfap->fa_arg);
691
692 kmem_free(tmpfap->fa_arg, tmpfap->fa_len);
693 tmpfap++; data->ed_argc++;
694 }
695 kmem_free(data->ed_pack.ep_fa, data->ed_pack.ep_fa_len);
696 data->ed_pack.ep_flags &= ~EXEC_HASARGL;
697 }
698
699 /* Now get argv & environment */
700 if (args == NULL) {
701 DPRINTF(("%s: null args\n", __func__));
702 error = EINVAL;
703 goto bad;
704 }
705 /* 'i' will index the argp/envp element to be retrieved */
706 i = 0;
707 if (data->ed_pack.ep_flags & EXEC_SKIPARG)
708 i++;
709
710 while (1) {
711 len = data->ed_argp + ARG_MAX - dp;
712 if ((error = (*fetch_element)(args, i, &sp)) != 0) {
713 DPRINTF(("%s: fetch_element args %d\n",
714 __func__, error));
715 goto bad;
716 }
717 if (!sp)
718 break;
719 if ((error = copyinstr(sp, dp, len, &len)) != 0) {
720 DPRINTF(("%s: copyinstr args %d\n", __func__, error));
721 if (error == ENAMETOOLONG)
722 error = E2BIG;
723 goto bad;
724 }
725 ktrexecarg(dp, len - 1);
726 dp += len;
727 i++;
728 data->ed_argc++;
729 }
730
731 data->ed_envc = 0;
732 /* environment need not be there */
733 if (envs != NULL) {
734 i = 0;
735 while (1) {
736 len = data->ed_argp + ARG_MAX - dp;
737 if ((error = (*fetch_element)(envs, i, &sp)) != 0) {
738 DPRINTF(("%s: fetch_element env %d\n",
739 __func__, error));
740 goto bad;
741 }
742 if (!sp)
743 break;
744 if ((error = copyinstr(sp, dp, len, &len)) != 0) {
745 DPRINTF(("%s: copyinstr env %d\n",
746 __func__, error));
747 if (error == ENAMETOOLONG)
748 error = E2BIG;
749 goto bad;
750 }
751
752 ktrexecenv(dp, len - 1);
753 dp += len;
754 i++;
755 data->ed_envc++;
756 }
757 }
758
759 dp = (char *) ALIGN(dp);
760
761 data->ed_szsigcode = data->ed_pack.ep_esch->es_emul->e_esigcode -
762 data->ed_pack.ep_esch->es_emul->e_sigcode;
763
764 #ifdef __MACHINE_STACK_GROWS_UP
765 /* See big comment lower down */
766 #define RTLD_GAP 32
767 #else
768 #define RTLD_GAP 0
769 #endif
770
771 /* Now check if args & environ fit into new stack */
772 if (data->ed_pack.ep_flags & EXEC_32) {
773 data->ed_ps_strings_sz = sizeof(struct ps_strings32);
774 len = ((data->ed_argc + data->ed_envc + 2 +
775 data->ed_pack.ep_esch->es_arglen) *
776 sizeof(int) + sizeof(int) + dp + RTLD_GAP +
777 data->ed_szsigcode + data->ed_ps_strings_sz + STACK_PTHREADSPACE)
778 - data->ed_argp;
779 } else {
780 data->ed_ps_strings_sz = sizeof(struct ps_strings);
781 len = ((data->ed_argc + data->ed_envc + 2 +
782 data->ed_pack.ep_esch->es_arglen) *
783 sizeof(char *) + sizeof(int) + dp + RTLD_GAP +
784 data->ed_szsigcode + data->ed_ps_strings_sz + STACK_PTHREADSPACE)
785 - data->ed_argp;
786 }
787
788 #ifdef PAX_ASLR
789 if (pax_aslr_active(l))
790 len += (cprng_fast32() % PAGE_SIZE);
791 #endif /* PAX_ASLR */
792
793 /* make the stack "safely" aligned */
794 len = STACK_LEN_ALIGN(len, STACK_ALIGNBYTES);
795
796 if (len > data->ed_pack.ep_ssize) {
797 /* in effect, compare to initial limit */
798 DPRINTF(("%s: stack limit exceeded %zu\n", __func__, len));
799 goto bad;
800 }
801 /* adjust "active stack depth" for process VSZ */
802 data->ed_pack.ep_ssize = len;
803
804 return 0;
805
806 bad:
807 /* free the vmspace-creation commands, and release their references */
808 kill_vmcmds(&data->ed_pack.ep_vmcmds);
809 /* kill any opened file descriptor, if necessary */
810 if (data->ed_pack.ep_flags & EXEC_HASFD) {
811 data->ed_pack.ep_flags &= ~EXEC_HASFD;
812 fd_close(data->ed_pack.ep_fd);
813 }
814 /* close and put the exec'd file */
815 vn_lock(data->ed_pack.ep_vp, LK_EXCLUSIVE | LK_RETRY);
816 VOP_CLOSE(data->ed_pack.ep_vp, FREAD, l->l_cred);
817 vput(data->ed_pack.ep_vp);
818 pool_put(&exec_pool, data->ed_argp);
819
820 freehdr:
821 kmem_free(data->ed_pack.ep_hdr, data->ed_pack.ep_hdrlen);
822 if (data->ed_pack.ep_emul_root != NULL)
823 vrele(data->ed_pack.ep_emul_root);
824 if (data->ed_pack.ep_interp != NULL)
825 vrele(data->ed_pack.ep_interp);
826
827 rw_exit(&exec_lock);
828
829 pathbuf_stringcopy_put(data->ed_pathbuf, data->ed_pathstring);
830 pathbuf_destroy(data->ed_pathbuf);
831 PNBUF_PUT(data->ed_resolvedpathbuf);
832
833 clrflg:
834 rw_exit(&p->p_reflock);
835
836 if (modgen != module_gen && error == ENOEXEC) {
837 modgen = module_gen;
838 exec_autoload();
839 goto retry;
840 }
841
842 SDT_PROBE(proc,,,exec_failure, error, 0, 0, 0, 0);
843 return error;
844 }
845
846 static void
847 execve_free_data(struct execve_data *data)
848 {
849
850 /* free the vmspace-creation commands, and release their references */
851 kill_vmcmds(&data->ed_pack.ep_vmcmds);
852 /* kill any opened file descriptor, if necessary */
853 if (data->ed_pack.ep_flags & EXEC_HASFD) {
854 data->ed_pack.ep_flags &= ~EXEC_HASFD;
855 fd_close(data->ed_pack.ep_fd);
856 }
857
858 /* close and put the exec'd file */
859 vn_lock(data->ed_pack.ep_vp, LK_EXCLUSIVE | LK_RETRY);
860 VOP_CLOSE(data->ed_pack.ep_vp, FREAD, curlwp->l_cred);
861 vput(data->ed_pack.ep_vp);
862 pool_put(&exec_pool, data->ed_argp);
863
864 kmem_free(data->ed_pack.ep_hdr, data->ed_pack.ep_hdrlen);
865 if (data->ed_pack.ep_emul_root != NULL)
866 vrele(data->ed_pack.ep_emul_root);
867 if (data->ed_pack.ep_interp != NULL)
868 vrele(data->ed_pack.ep_interp);
869
870 pathbuf_stringcopy_put(data->ed_pathbuf, data->ed_pathstring);
871 pathbuf_destroy(data->ed_pathbuf);
872 PNBUF_PUT(data->ed_resolvedpathbuf);
873 }
874
875 static int
876 execve_runproc(struct lwp *l, struct execve_data * restrict data,
877 bool no_local_exec_lock, bool is_spawn)
878 {
879 int error = 0;
880 struct proc *p;
881 size_t i;
882 char *stack, *dp;
883 const char *commandname;
884 struct ps_strings32 arginfo32;
885 struct exec_vmcmd *base_vcp;
886 void *aip;
887 struct vmspace *vm;
888 ksiginfo_t ksi;
889 ksiginfoq_t kq;
890
891 /*
892 * In case of a posix_spawn operation, the child doing the exec
893 * might not hold the reader lock on exec_lock, but the parent
894 * will do this instead.
895 */
896 KASSERT(no_local_exec_lock || rw_lock_held(&exec_lock));
897 KASSERT(data != NULL);
898 if (data == NULL)
899 return (EINVAL);
900
901 p = l->l_proc;
902 if (no_local_exec_lock)
903 KASSERT(is_spawn);
904
905 base_vcp = NULL;
906
907 if (data->ed_pack.ep_flags & EXEC_32)
908 aip = &arginfo32;
909 else
910 aip = &data->ed_arginfo;
911
912 /* Get rid of other LWPs. */
913 if (p->p_nlwps > 1) {
914 mutex_enter(p->p_lock);
915 exit_lwps(l);
916 mutex_exit(p->p_lock);
917 }
918 KDASSERT(p->p_nlwps == 1);
919
920 /* Destroy any lwpctl info. */
921 if (p->p_lwpctl != NULL)
922 lwp_ctl_exit();
923
924 /* Remove POSIX timers */
925 timers_free(p, TIMERS_POSIX);
926
927 /*
928 * Do whatever is necessary to prepare the address space
929 * for remapping. Note that this might replace the current
930 * vmspace with another!
931 */
932 if (is_spawn)
933 uvmspace_spawn(l, data->ed_pack.ep_vm_minaddr,
934 data->ed_pack.ep_vm_maxaddr);
935 else
936 uvmspace_exec(l, data->ed_pack.ep_vm_minaddr,
937 data->ed_pack.ep_vm_maxaddr);
938
939 /* record proc's vnode, for use by procfs and others */
940 if (p->p_textvp)
941 vrele(p->p_textvp);
942 vref(data->ed_pack.ep_vp);
943 p->p_textvp = data->ed_pack.ep_vp;
944
945 /* Now map address space */
946 vm = p->p_vmspace;
947 vm->vm_taddr = (void *)data->ed_pack.ep_taddr;
948 vm->vm_tsize = btoc(data->ed_pack.ep_tsize);
949 vm->vm_daddr = (void*)data->ed_pack.ep_daddr;
950 vm->vm_dsize = btoc(data->ed_pack.ep_dsize);
951 vm->vm_ssize = btoc(data->ed_pack.ep_ssize);
952 vm->vm_issize = 0;
953 vm->vm_maxsaddr = (void *)data->ed_pack.ep_maxsaddr;
954 vm->vm_minsaddr = (void *)data->ed_pack.ep_minsaddr;
955
956 #ifdef PAX_ASLR
957 pax_aslr_init(l, vm);
958 #endif /* PAX_ASLR */
959
960 /* create the new process's VM space by running the vmcmds */
961 #ifdef DIAGNOSTIC
962 if (data->ed_pack.ep_vmcmds.evs_used == 0)
963 panic("%s: no vmcmds", __func__);
964 #endif
965
966 #ifdef DEBUG_EXEC
967 {
968 size_t j;
969 struct exec_vmcmd *vp = &data->ed_pack.ep_vmcmds.evs_cmds[0];
970 DPRINTF(("vmcmds %u\n", data->ed_pack.ep_vmcmds.evs_used));
971 for (j = 0; j < data->ed_pack.ep_vmcmds.evs_used; j++) {
972 DPRINTF(("vmcmd[%zu] = vmcmd_map_%s %#"
973 PRIxVADDR"/%#"PRIxVSIZE" fd@%#"
974 PRIxVSIZE" prot=0%o flags=%d\n", j,
975 vp[j].ev_proc == vmcmd_map_pagedvn ?
976 "pagedvn" :
977 vp[j].ev_proc == vmcmd_map_readvn ?
978 "readvn" :
979 vp[j].ev_proc == vmcmd_map_zero ?
980 "zero" : "*unknown*",
981 vp[j].ev_addr, vp[j].ev_len,
982 vp[j].ev_offset, vp[j].ev_prot,
983 vp[j].ev_flags));
984 }
985 }
986 #endif /* DEBUG_EXEC */
987
988 for (i = 0; i < data->ed_pack.ep_vmcmds.evs_used && !error; i++) {
989 struct exec_vmcmd *vcp;
990
991 vcp = &data->ed_pack.ep_vmcmds.evs_cmds[i];
992 if (vcp->ev_flags & VMCMD_RELATIVE) {
993 #ifdef DIAGNOSTIC
994 if (base_vcp == NULL)
995 panic("%s: relative vmcmd with no base",
996 __func__);
997 if (vcp->ev_flags & VMCMD_BASE)
998 panic("%s: illegal base & relative vmcmd",
999 __func__);
1000 #endif
1001 vcp->ev_addr += base_vcp->ev_addr;
1002 }
1003 error = (*vcp->ev_proc)(l, vcp);
1004 #ifdef DEBUG_EXEC
1005 if (error) {
1006 size_t j;
1007 struct exec_vmcmd *vp =
1008 &data->ed_pack.ep_vmcmds.evs_cmds[0];
1009 DPRINTF(("vmcmds %zu/%u, error %d\n", i,
1010 data->ed_pack.ep_vmcmds.evs_used, error));
1011 for (j = 0; j < data->ed_pack.ep_vmcmds.evs_used; j++) {
1012 DPRINTF(("vmcmd[%zu] = vmcmd_map_%s %#"
1013 PRIxVADDR"/%#"PRIxVSIZE" fd@%#"
1014 PRIxVSIZE" prot=0%o flags=%d\n", j,
1015 vp[j].ev_proc == vmcmd_map_pagedvn ?
1016 "pagedvn" :
1017 vp[j].ev_proc == vmcmd_map_readvn ?
1018 "readvn" :
1019 vp[j].ev_proc == vmcmd_map_zero ?
1020 "zero" : "*unknown*",
1021 vp[j].ev_addr, vp[j].ev_len,
1022 vp[j].ev_offset, vp[j].ev_prot,
1023 vp[j].ev_flags));
1024 if (j == i)
1025 DPRINTF((" ^--- failed\n"));
1026 }
1027 }
1028 #endif /* DEBUG_EXEC */
1029 if (vcp->ev_flags & VMCMD_BASE)
1030 base_vcp = vcp;
1031 }
1032
1033 /* free the vmspace-creation commands, and release their references */
1034 kill_vmcmds(&data->ed_pack.ep_vmcmds);
1035
1036 vn_lock(data->ed_pack.ep_vp, LK_EXCLUSIVE | LK_RETRY);
1037 VOP_CLOSE(data->ed_pack.ep_vp, FREAD, l->l_cred);
1038 vput(data->ed_pack.ep_vp);
1039
1040 /* if an error happened, deallocate and punt */
1041 if (error) {
1042 DPRINTF(("%s: vmcmd %zu failed: %d\n", __func__, i - 1, error));
1043 goto exec_abort;
1044 }
1045
1046 /* remember information about the process */
1047 data->ed_arginfo.ps_nargvstr = data->ed_argc;
1048 data->ed_arginfo.ps_nenvstr = data->ed_envc;
1049
1050 /* set command name & other accounting info */
1051 commandname = strrchr(data->ed_pack.ep_resolvedname, '/');
1052 if (commandname != NULL) {
1053 commandname++;
1054 } else {
1055 commandname = data->ed_pack.ep_resolvedname;
1056 }
1057 i = min(strlen(commandname), MAXCOMLEN);
1058 (void)memcpy(p->p_comm, commandname, i);
1059 p->p_comm[i] = '\0';
1060
1061 dp = PNBUF_GET();
1062 /*
1063 * If the path starts with /, we don't need to do any work.
1064 * This handles the majority of the cases.
1065 * In the future perhaps we could canonicalize it?
1066 */
1067 if (data->ed_pathstring[0] == '/')
1068 (void)strlcpy(data->ed_pack.ep_path = dp, data->ed_pathstring,
1069 MAXPATHLEN);
1070 #ifdef notyet
1071 /*
1072 * Although this works most of the time [since the entry was just
1073 * entered in the cache] we don't use it because it theoretically
1074 * can fail and it is not the cleanest interface, because there
1075 * could be races. When the namei cache is re-written, this can
1076 * be changed to use the appropriate function.
1077 */
1078 else if (!(error = vnode_to_path(dp, MAXPATHLEN, p->p_textvp, l, p)))
1079 data->ed_pack.ep_path = dp;
1080 #endif
1081 else {
1082 #ifdef notyet
1083 printf("Cannot get path for pid %d [%s] (error %d)\n",
1084 (int)p->p_pid, p->p_comm, error);
1085 #endif
1086 data->ed_pack.ep_path = NULL;
1087 PNBUF_PUT(dp);
1088 }
1089
1090 stack = (char *)STACK_ALLOC(STACK_GROW(vm->vm_minsaddr,
1091 STACK_PTHREADSPACE + data->ed_ps_strings_sz + data->ed_szsigcode),
1092 data->ed_pack.ep_ssize - (data->ed_ps_strings_sz + data->ed_szsigcode));
1093
1094 #ifdef __MACHINE_STACK_GROWS_UP
1095 /*
1096 * The copyargs call always copies into lower addresses
1097 * first, moving towards higher addresses, starting with
1098 * the stack pointer that we give. When the stack grows
1099 * down, this puts argc/argv/envp very shallow on the
1100 * stack, right at the first user stack pointer.
1101 * When the stack grows up, the situation is reversed.
1102 *
1103 * Normally, this is no big deal. But the ld_elf.so _rtld()
1104 * function expects to be called with a single pointer to
1105 * a region that has a few words it can stash values into,
1106 * followed by argc/argv/envp. When the stack grows down,
1107 * it's easy to decrement the stack pointer a little bit to
1108 * allocate the space for these few words and pass the new
1109 * stack pointer to _rtld. When the stack grows up, however,
1110 * a few words before argc is part of the signal trampoline, XXX
1111 * so we have a problem.
1112 *
1113 * Instead of changing how _rtld works, we take the easy way
1114 * out and steal 32 bytes before we call copyargs.
1115 * This extra space was allowed for when 'pack.ep_ssize' was calculated.
1116 */
1117 stack += RTLD_GAP;
1118 #endif /* __MACHINE_STACK_GROWS_UP */
1119
1120 /* Now copy argc, args & environ to new stack */
1121 error = (*data->ed_pack.ep_esch->es_copyargs)(l, &data->ed_pack,
1122 &data->ed_arginfo, &stack, data->ed_argp);
1123
1124 if (data->ed_pack.ep_path) {
1125 PNBUF_PUT(data->ed_pack.ep_path);
1126 data->ed_pack.ep_path = NULL;
1127 }
1128 if (error) {
1129 DPRINTF(("%s: copyargs failed %d\n", __func__, error));
1130 goto exec_abort;
1131 }
1132 /* Move the stack back to original point */
1133 stack = (char *)STACK_GROW(vm->vm_minsaddr, data->ed_pack.ep_ssize);
1134
1135 /* fill process ps_strings info */
1136 p->p_psstrp = (vaddr_t)STACK_ALLOC(STACK_GROW(vm->vm_minsaddr,
1137 STACK_PTHREADSPACE), data->ed_ps_strings_sz);
1138
1139 if (data->ed_pack.ep_flags & EXEC_32) {
1140 arginfo32.ps_argvstr = (vaddr_t)data->ed_arginfo.ps_argvstr;
1141 arginfo32.ps_nargvstr = data->ed_arginfo.ps_nargvstr;
1142 arginfo32.ps_envstr = (vaddr_t)data->ed_arginfo.ps_envstr;
1143 arginfo32.ps_nenvstr = data->ed_arginfo.ps_nenvstr;
1144 }
1145
1146 /* copy out the process's ps_strings structure */
1147 if ((error = copyout(aip, (void *)p->p_psstrp, data->ed_ps_strings_sz))
1148 != 0) {
1149 DPRINTF(("%s: ps_strings copyout %p->%p size %zu failed\n",
1150 __func__, aip, (void *)p->p_psstrp, data->ed_ps_strings_sz));
1151 goto exec_abort;
1152 }
1153
1154 cwdexec(p);
1155 fd_closeexec(); /* handle close on exec */
1156
1157 if (__predict_false(ktrace_on))
1158 fd_ktrexecfd();
1159
1160 execsigs(p); /* reset catched signals */
1161
1162 l->l_ctxlink = NULL; /* reset ucontext link */
1163
1164
1165 p->p_acflag &= ~AFORK;
1166 mutex_enter(p->p_lock);
1167 p->p_flag |= PK_EXEC;
1168 mutex_exit(p->p_lock);
1169
1170 /*
1171 * Stop profiling.
1172 */
1173 if ((p->p_stflag & PST_PROFIL) != 0) {
1174 mutex_spin_enter(&p->p_stmutex);
1175 stopprofclock(p);
1176 mutex_spin_exit(&p->p_stmutex);
1177 }
1178
1179 /*
1180 * It's OK to test PL_PPWAIT unlocked here, as other LWPs have
1181 * exited and exec()/exit() are the only places it will be cleared.
1182 */
1183 if ((p->p_lflag & PL_PPWAIT) != 0) {
1184 #if 0
1185 lwp_t *lp;
1186
1187 mutex_enter(proc_lock);
1188 lp = p->p_vforklwp;
1189 p->p_vforklwp = NULL;
1190
1191 l->l_lwpctl = NULL; /* was on loan from blocked parent */
1192 p->p_lflag &= ~PL_PPWAIT;
1193
1194 lp->l_pflag &= ~LP_VFORKWAIT; /* XXX */
1195 cv_broadcast(&lp->l_waitcv);
1196 mutex_exit(proc_lock);
1197 #else
1198 mutex_enter(proc_lock);
1199 l->l_lwpctl = NULL; /* was on loan from blocked parent */
1200 p->p_lflag &= ~PL_PPWAIT;
1201 cv_broadcast(&p->p_pptr->p_waitcv);
1202 mutex_exit(proc_lock);
1203 #endif
1204 }
1205
1206 /*
1207 * Deal with set[ug]id. MNT_NOSUID has already been used to disable
1208 * s[ug]id. It's OK to check for PSL_TRACED here as we have blocked
1209 * out additional references on the process for the moment.
1210 */
1211 if ((p->p_slflag & PSL_TRACED) == 0 &&
1212
1213 (((data->ed_attr.va_mode & S_ISUID) != 0 &&
1214 kauth_cred_geteuid(l->l_cred) != data->ed_attr.va_uid) ||
1215
1216 ((data->ed_attr.va_mode & S_ISGID) != 0 &&
1217 kauth_cred_getegid(l->l_cred) != data->ed_attr.va_gid))) {
1218 /*
1219 * Mark the process as SUGID before we do
1220 * anything that might block.
1221 */
1222 proc_crmod_enter();
1223 proc_crmod_leave(NULL, NULL, true);
1224
1225 /* Make sure file descriptors 0..2 are in use. */
1226 if ((error = fd_checkstd()) != 0) {
1227 DPRINTF(("%s: fdcheckstd failed %d\n",
1228 __func__, error));
1229 goto exec_abort;
1230 }
1231
1232 /*
1233 * Copy the credential so other references don't see our
1234 * changes.
1235 */
1236 l->l_cred = kauth_cred_copy(l->l_cred);
1237 #ifdef KTRACE
1238 /*
1239 * If the persistent trace flag isn't set, turn off.
1240 */
1241 if (p->p_tracep) {
1242 mutex_enter(&ktrace_lock);
1243 if (!(p->p_traceflag & KTRFAC_PERSISTENT))
1244 ktrderef(p);
1245 mutex_exit(&ktrace_lock);
1246 }
1247 #endif
1248 if (data->ed_attr.va_mode & S_ISUID)
1249 kauth_cred_seteuid(l->l_cred, data->ed_attr.va_uid);
1250 if (data->ed_attr.va_mode & S_ISGID)
1251 kauth_cred_setegid(l->l_cred, data->ed_attr.va_gid);
1252 } else {
1253 if (kauth_cred_geteuid(l->l_cred) ==
1254 kauth_cred_getuid(l->l_cred) &&
1255 kauth_cred_getegid(l->l_cred) ==
1256 kauth_cred_getgid(l->l_cred))
1257 p->p_flag &= ~PK_SUGID;
1258 }
1259
1260 /*
1261 * Copy the credential so other references don't see our changes.
1262 * Test to see if this is necessary first, since in the common case
1263 * we won't need a private reference.
1264 */
1265 if (kauth_cred_geteuid(l->l_cred) != kauth_cred_getsvuid(l->l_cred) ||
1266 kauth_cred_getegid(l->l_cred) != kauth_cred_getsvgid(l->l_cred)) {
1267 l->l_cred = kauth_cred_copy(l->l_cred);
1268 kauth_cred_setsvuid(l->l_cred, kauth_cred_geteuid(l->l_cred));
1269 kauth_cred_setsvgid(l->l_cred, kauth_cred_getegid(l->l_cred));
1270 }
1271
1272 /* Update the master credentials. */
1273 if (l->l_cred != p->p_cred) {
1274 kauth_cred_t ocred;
1275
1276 kauth_cred_hold(l->l_cred);
1277 mutex_enter(p->p_lock);
1278 ocred = p->p_cred;
1279 p->p_cred = l->l_cred;
1280 mutex_exit(p->p_lock);
1281 kauth_cred_free(ocred);
1282 }
1283
1284 #if defined(__HAVE_RAS)
1285 /*
1286 * Remove all RASs from the address space.
1287 */
1288 ras_purgeall();
1289 #endif
1290
1291 doexechooks(p);
1292
1293 /* setup new registers and do misc. setup. */
1294 (*data->ed_pack.ep_esch->es_emul->e_setregs)(l, &data->ed_pack,
1295 (vaddr_t)stack);
1296 if (data->ed_pack.ep_esch->es_setregs)
1297 (*data->ed_pack.ep_esch->es_setregs)(l, &data->ed_pack,
1298 (vaddr_t)stack);
1299
1300 /* Provide a consistent LWP private setting */
1301 (void)lwp_setprivate(l, NULL);
1302
1303 /* Discard all PCU state; need to start fresh */
1304 pcu_discard_all(l);
1305
1306 /* map the process's signal trampoline code */
1307 if ((error = exec_sigcode_map(p, data->ed_pack.ep_esch->es_emul)) != 0) {
1308 DPRINTF(("%s: map sigcode failed %d\n", __func__, error));
1309 goto exec_abort;
1310 }
1311
1312 pool_put(&exec_pool, data->ed_argp);
1313
1314 /* notify others that we exec'd */
1315 KNOTE(&p->p_klist, NOTE_EXEC);
1316
1317 kmem_free(data->ed_pack.ep_hdr, data->ed_pack.ep_hdrlen);
1318
1319 SDT_PROBE(proc,,,exec_success, data->ed_pack.ep_name, 0, 0, 0, 0);
1320
1321 /* The emulation root will usually have been found when we looked
1322 * for the elf interpreter (or similar), if not look now. */
1323 if (data->ed_pack.ep_esch->es_emul->e_path != NULL &&
1324 data->ed_pack.ep_emul_root == NULL)
1325 emul_find_root(l, &data->ed_pack);
1326
1327 /* Any old emulation root got removed by fdcloseexec */
1328 rw_enter(&p->p_cwdi->cwdi_lock, RW_WRITER);
1329 p->p_cwdi->cwdi_edir = data->ed_pack.ep_emul_root;
1330 rw_exit(&p->p_cwdi->cwdi_lock);
1331 data->ed_pack.ep_emul_root = NULL;
1332 if (data->ed_pack.ep_interp != NULL)
1333 vrele(data->ed_pack.ep_interp);
1334
1335 /*
1336 * Call emulation specific exec hook. This can setup per-process
1337 * p->p_emuldata or do any other per-process stuff an emulation needs.
1338 *
1339 * If we are executing process of different emulation than the
1340 * original forked process, call e_proc_exit() of the old emulation
1341 * first, then e_proc_exec() of new emulation. If the emulation is
1342 * same, the exec hook code should deallocate any old emulation
1343 * resources held previously by this process.
1344 */
1345 if (p->p_emul && p->p_emul->e_proc_exit
1346 && p->p_emul != data->ed_pack.ep_esch->es_emul)
1347 (*p->p_emul->e_proc_exit)(p);
1348
1349 /*
1350 * This is now LWP 1.
1351 */
1352 mutex_enter(p->p_lock);
1353 p->p_nlwpid = 1;
1354 l->l_lid = 1;
1355 mutex_exit(p->p_lock);
1356
1357 /*
1358 * Call exec hook. Emulation code may NOT store reference to anything
1359 * from &pack.
1360 */
1361 if (data->ed_pack.ep_esch->es_emul->e_proc_exec)
1362 (*data->ed_pack.ep_esch->es_emul->e_proc_exec)(p, &data->ed_pack);
1363
1364 /* update p_emul, the old value is no longer needed */
1365 p->p_emul = data->ed_pack.ep_esch->es_emul;
1366
1367 /* ...and the same for p_execsw */
1368 p->p_execsw = data->ed_pack.ep_esch;
1369
1370 #ifdef __HAVE_SYSCALL_INTERN
1371 (*p->p_emul->e_syscall_intern)(p);
1372 #endif
1373 ktremul();
1374
1375 /* Allow new references from the debugger/procfs. */
1376 rw_exit(&p->p_reflock);
1377 if (!no_local_exec_lock)
1378 rw_exit(&exec_lock);
1379
1380 mutex_enter(proc_lock);
1381
1382 if ((p->p_slflag & (PSL_TRACED|PSL_SYSCALL)) == PSL_TRACED) {
1383 KSI_INIT_EMPTY(&ksi);
1384 ksi.ksi_signo = SIGTRAP;
1385 ksi.ksi_lid = l->l_lid;
1386 kpsignal(p, &ksi, NULL);
1387 }
1388
1389 if (p->p_sflag & PS_STOPEXEC) {
1390 KERNEL_UNLOCK_ALL(l, &l->l_biglocks);
1391 p->p_pptr->p_nstopchild++;
1392 p->p_pptr->p_waited = 0;
1393 mutex_enter(p->p_lock);
1394 ksiginfo_queue_init(&kq);
1395 sigclearall(p, &contsigmask, &kq);
1396 lwp_lock(l);
1397 l->l_stat = LSSTOP;
1398 p->p_stat = SSTOP;
1399 p->p_nrlwps--;
1400 lwp_unlock(l);
1401 mutex_exit(p->p_lock);
1402 mutex_exit(proc_lock);
1403 lwp_lock(l);
1404 mi_switch(l);
1405 ksiginfo_queue_drain(&kq);
1406 KERNEL_LOCK(l->l_biglocks, l);
1407 } else {
1408 mutex_exit(proc_lock);
1409 }
1410
1411 pathbuf_stringcopy_put(data->ed_pathbuf, data->ed_pathstring);
1412 pathbuf_destroy(data->ed_pathbuf);
1413 PNBUF_PUT(data->ed_resolvedpathbuf);
1414 DPRINTF(("%s finished\n", __func__));
1415 return (EJUSTRETURN);
1416
1417 exec_abort:
1418 SDT_PROBE(proc,,,exec_failure, error, 0, 0, 0, 0);
1419 rw_exit(&p->p_reflock);
1420 if (!no_local_exec_lock)
1421 rw_exit(&exec_lock);
1422
1423 pathbuf_stringcopy_put(data->ed_pathbuf, data->ed_pathstring);
1424 pathbuf_destroy(data->ed_pathbuf);
1425 PNBUF_PUT(data->ed_resolvedpathbuf);
1426
1427 /*
1428 * the old process doesn't exist anymore. exit gracefully.
1429 * get rid of the (new) address space we have created, if any, get rid
1430 * of our namei data and vnode, and exit noting failure
1431 */
1432 uvm_deallocate(&vm->vm_map, VM_MIN_ADDRESS,
1433 VM_MAXUSER_ADDRESS - VM_MIN_ADDRESS);
1434
1435 exec_free_emul_arg(&data->ed_pack);
1436 pool_put(&exec_pool, data->ed_argp);
1437 kmem_free(data->ed_pack.ep_hdr, data->ed_pack.ep_hdrlen);
1438 if (data->ed_pack.ep_emul_root != NULL)
1439 vrele(data->ed_pack.ep_emul_root);
1440 if (data->ed_pack.ep_interp != NULL)
1441 vrele(data->ed_pack.ep_interp);
1442
1443 /* Acquire the sched-state mutex (exit1() will release it). */
1444 if (!is_spawn) {
1445 mutex_enter(p->p_lock);
1446 exit1(l, W_EXITCODE(error, SIGABRT));
1447 }
1448
1449 return error;
1450 }
1451
1452 int
1453 execve1(struct lwp *l, const char *path, char * const *args,
1454 char * const *envs, execve_fetch_element_t fetch_element)
1455 {
1456 struct execve_data data;
1457 int error;
1458
1459 error = execve_loadvm(l, path, args, envs, fetch_element, &data);
1460 if (error)
1461 return error;
1462 error = execve_runproc(l, &data, false, false);
1463 return error;
1464 }
1465
1466 int
1467 copyargs(struct lwp *l, struct exec_package *pack, struct ps_strings *arginfo,
1468 char **stackp, void *argp)
1469 {
1470 char **cpp, *dp, *sp;
1471 size_t len;
1472 void *nullp;
1473 long argc, envc;
1474 int error;
1475
1476 cpp = (char **)*stackp;
1477 nullp = NULL;
1478 argc = arginfo->ps_nargvstr;
1479 envc = arginfo->ps_nenvstr;
1480 if ((error = copyout(&argc, cpp++, sizeof(argc))) != 0) {
1481 COPYPRINTF("", cpp - 1, sizeof(argc));
1482 return error;
1483 }
1484
1485 dp = (char *) (cpp + argc + envc + 2 + pack->ep_esch->es_arglen);
1486 sp = argp;
1487
1488 /* XXX don't copy them out, remap them! */
1489 arginfo->ps_argvstr = cpp; /* remember location of argv for later */
1490
1491 for (; --argc >= 0; sp += len, dp += len) {
1492 if ((error = copyout(&dp, cpp++, sizeof(dp))) != 0) {
1493 COPYPRINTF("", cpp - 1, sizeof(dp));
1494 return error;
1495 }
1496 if ((error = copyoutstr(sp, dp, ARG_MAX, &len)) != 0) {
1497 COPYPRINTF("str", dp, (size_t)ARG_MAX);
1498 return error;
1499 }
1500 }
1501
1502 if ((error = copyout(&nullp, cpp++, sizeof(nullp))) != 0) {
1503 COPYPRINTF("", cpp - 1, sizeof(nullp));
1504 return error;
1505 }
1506
1507 arginfo->ps_envstr = cpp; /* remember location of envp for later */
1508
1509 for (; --envc >= 0; sp += len, dp += len) {
1510 if ((error = copyout(&dp, cpp++, sizeof(dp))) != 0) {
1511 COPYPRINTF("", cpp - 1, sizeof(dp));
1512 return error;
1513 }
1514 if ((error = copyoutstr(sp, dp, ARG_MAX, &len)) != 0) {
1515 COPYPRINTF("str", dp, (size_t)ARG_MAX);
1516 return error;
1517 }
1518
1519 }
1520
1521 if ((error = copyout(&nullp, cpp++, sizeof(nullp))) != 0) {
1522 COPYPRINTF("", cpp - 1, sizeof(nullp));
1523 return error;
1524 }
1525
1526 *stackp = (char *)cpp;
1527 return 0;
1528 }
1529
1530
1531 /*
1532 * Add execsw[] entries.
1533 */
1534 int
1535 exec_add(struct execsw *esp, int count)
1536 {
1537 struct exec_entry *it;
1538 int i;
1539
1540 if (count == 0) {
1541 return 0;
1542 }
1543
1544 /* Check for duplicates. */
1545 rw_enter(&exec_lock, RW_WRITER);
1546 for (i = 0; i < count; i++) {
1547 LIST_FOREACH(it, &ex_head, ex_list) {
1548 /* assume unique (makecmds, probe_func, emulation) */
1549 if (it->ex_sw->es_makecmds == esp[i].es_makecmds &&
1550 it->ex_sw->u.elf_probe_func ==
1551 esp[i].u.elf_probe_func &&
1552 it->ex_sw->es_emul == esp[i].es_emul) {
1553 rw_exit(&exec_lock);
1554 return EEXIST;
1555 }
1556 }
1557 }
1558
1559 /* Allocate new entries. */
1560 for (i = 0; i < count; i++) {
1561 it = kmem_alloc(sizeof(*it), KM_SLEEP);
1562 it->ex_sw = &esp[i];
1563 LIST_INSERT_HEAD(&ex_head, it, ex_list);
1564 }
1565
1566 /* update execsw[] */
1567 exec_init(0);
1568 rw_exit(&exec_lock);
1569 return 0;
1570 }
1571
1572 /*
1573 * Remove execsw[] entry.
1574 */
1575 int
1576 exec_remove(struct execsw *esp, int count)
1577 {
1578 struct exec_entry *it, *next;
1579 int i;
1580 const struct proclist_desc *pd;
1581 proc_t *p;
1582
1583 if (count == 0) {
1584 return 0;
1585 }
1586
1587 /* Abort if any are busy. */
1588 rw_enter(&exec_lock, RW_WRITER);
1589 for (i = 0; i < count; i++) {
1590 mutex_enter(proc_lock);
1591 for (pd = proclists; pd->pd_list != NULL; pd++) {
1592 PROCLIST_FOREACH(p, pd->pd_list) {
1593 if (p->p_execsw == &esp[i]) {
1594 mutex_exit(proc_lock);
1595 rw_exit(&exec_lock);
1596 return EBUSY;
1597 }
1598 }
1599 }
1600 mutex_exit(proc_lock);
1601 }
1602
1603 /* None are busy, so remove them all. */
1604 for (i = 0; i < count; i++) {
1605 for (it = LIST_FIRST(&ex_head); it != NULL; it = next) {
1606 next = LIST_NEXT(it, ex_list);
1607 if (it->ex_sw == &esp[i]) {
1608 LIST_REMOVE(it, ex_list);
1609 kmem_free(it, sizeof(*it));
1610 break;
1611 }
1612 }
1613 }
1614
1615 /* update execsw[] */
1616 exec_init(0);
1617 rw_exit(&exec_lock);
1618 return 0;
1619 }
1620
1621 /*
1622 * Initialize exec structures. If init_boot is true, also does necessary
1623 * one-time initialization (it's called from main() that way).
1624 * Once system is multiuser, this should be called with exec_lock held,
1625 * i.e. via exec_{add|remove}().
1626 */
1627 int
1628 exec_init(int init_boot)
1629 {
1630 const struct execsw **sw;
1631 struct exec_entry *ex;
1632 SLIST_HEAD(,exec_entry) first;
1633 SLIST_HEAD(,exec_entry) any;
1634 SLIST_HEAD(,exec_entry) last;
1635 int i, sz;
1636
1637 if (init_boot) {
1638 /* do one-time initializations */
1639 rw_init(&exec_lock);
1640 mutex_init(&sigobject_lock, MUTEX_DEFAULT, IPL_NONE);
1641 pool_init(&exec_pool, NCARGS, 0, 0, PR_NOALIGN|PR_NOTOUCH,
1642 "execargs", &exec_palloc, IPL_NONE);
1643 pool_sethardlimit(&exec_pool, maxexec, "should not happen", 0);
1644 } else {
1645 KASSERT(rw_write_held(&exec_lock));
1646 }
1647
1648 /* Sort each entry onto the appropriate queue. */
1649 SLIST_INIT(&first);
1650 SLIST_INIT(&any);
1651 SLIST_INIT(&last);
1652 sz = 0;
1653 LIST_FOREACH(ex, &ex_head, ex_list) {
1654 switch(ex->ex_sw->es_prio) {
1655 case EXECSW_PRIO_FIRST:
1656 SLIST_INSERT_HEAD(&first, ex, ex_slist);
1657 break;
1658 case EXECSW_PRIO_ANY:
1659 SLIST_INSERT_HEAD(&any, ex, ex_slist);
1660 break;
1661 case EXECSW_PRIO_LAST:
1662 SLIST_INSERT_HEAD(&last, ex, ex_slist);
1663 break;
1664 default:
1665 panic("%s", __func__);
1666 break;
1667 }
1668 sz++;
1669 }
1670
1671 /*
1672 * Create new execsw[]. Ensure we do not try a zero-sized
1673 * allocation.
1674 */
1675 sw = kmem_alloc(sz * sizeof(struct execsw *) + 1, KM_SLEEP);
1676 i = 0;
1677 SLIST_FOREACH(ex, &first, ex_slist) {
1678 sw[i++] = ex->ex_sw;
1679 }
1680 SLIST_FOREACH(ex, &any, ex_slist) {
1681 sw[i++] = ex->ex_sw;
1682 }
1683 SLIST_FOREACH(ex, &last, ex_slist) {
1684 sw[i++] = ex->ex_sw;
1685 }
1686
1687 /* Replace old execsw[] and free used memory. */
1688 if (execsw != NULL) {
1689 kmem_free(__UNCONST(execsw),
1690 nexecs * sizeof(struct execsw *) + 1);
1691 }
1692 execsw = sw;
1693 nexecs = sz;
1694
1695 /* Figure out the maximum size of an exec header. */
1696 exec_maxhdrsz = sizeof(int);
1697 for (i = 0; i < nexecs; i++) {
1698 if (execsw[i]->es_hdrsz > exec_maxhdrsz)
1699 exec_maxhdrsz = execsw[i]->es_hdrsz;
1700 }
1701
1702 return 0;
1703 }
1704
1705 static int
1706 exec_sigcode_map(struct proc *p, const struct emul *e)
1707 {
1708 vaddr_t va;
1709 vsize_t sz;
1710 int error;
1711 struct uvm_object *uobj;
1712
1713 sz = (vaddr_t)e->e_esigcode - (vaddr_t)e->e_sigcode;
1714
1715 if (e->e_sigobject == NULL || sz == 0) {
1716 return 0;
1717 }
1718
1719 /*
1720 * If we don't have a sigobject for this emulation, create one.
1721 *
1722 * sigobject is an anonymous memory object (just like SYSV shared
1723 * memory) that we keep a permanent reference to and that we map
1724 * in all processes that need this sigcode. The creation is simple,
1725 * we create an object, add a permanent reference to it, map it in
1726 * kernel space, copy out the sigcode to it and unmap it.
1727 * We map it with PROT_READ|PROT_EXEC into the process just
1728 * the way sys_mmap() would map it.
1729 */
1730
1731 uobj = *e->e_sigobject;
1732 if (uobj == NULL) {
1733 mutex_enter(&sigobject_lock);
1734 if ((uobj = *e->e_sigobject) == NULL) {
1735 uobj = uao_create(sz, 0);
1736 (*uobj->pgops->pgo_reference)(uobj);
1737 va = vm_map_min(kernel_map);
1738 if ((error = uvm_map(kernel_map, &va, round_page(sz),
1739 uobj, 0, 0,
1740 UVM_MAPFLAG(UVM_PROT_RW, UVM_PROT_RW,
1741 UVM_INH_SHARE, UVM_ADV_RANDOM, 0)))) {
1742 printf("kernel mapping failed %d\n", error);
1743 (*uobj->pgops->pgo_detach)(uobj);
1744 mutex_exit(&sigobject_lock);
1745 return (error);
1746 }
1747 memcpy((void *)va, e->e_sigcode, sz);
1748 #ifdef PMAP_NEED_PROCWR
1749 pmap_procwr(&proc0, va, sz);
1750 #endif
1751 uvm_unmap(kernel_map, va, va + round_page(sz));
1752 *e->e_sigobject = uobj;
1753 }
1754 mutex_exit(&sigobject_lock);
1755 }
1756
1757 /* Just a hint to uvm_map where to put it. */
1758 va = e->e_vm_default_addr(p, (vaddr_t)p->p_vmspace->vm_daddr,
1759 round_page(sz));
1760
1761 #ifdef __alpha__
1762 /*
1763 * Tru64 puts /sbin/loader at the end of user virtual memory,
1764 * which causes the above calculation to put the sigcode at
1765 * an invalid address. Put it just below the text instead.
1766 */
1767 if (va == (vaddr_t)vm_map_max(&p->p_vmspace->vm_map)) {
1768 va = (vaddr_t)p->p_vmspace->vm_taddr - round_page(sz);
1769 }
1770 #endif
1771
1772 (*uobj->pgops->pgo_reference)(uobj);
1773 error = uvm_map(&p->p_vmspace->vm_map, &va, round_page(sz),
1774 uobj, 0, 0,
1775 UVM_MAPFLAG(UVM_PROT_RX, UVM_PROT_RX, UVM_INH_SHARE,
1776 UVM_ADV_RANDOM, 0));
1777 if (error) {
1778 DPRINTF(("%s, %d: map %p "
1779 "uvm_map %#"PRIxVSIZE"@%#"PRIxVADDR" failed %d\n",
1780 __func__, __LINE__, &p->p_vmspace->vm_map, round_page(sz),
1781 va, error));
1782 (*uobj->pgops->pgo_detach)(uobj);
1783 return (error);
1784 }
1785 p->p_sigctx.ps_sigcode = (void *)va;
1786 return (0);
1787 }
1788
1789 /*
1790 * Release a refcount on spawn_exec_data and destroy memory, if this
1791 * was the last one.
1792 */
1793 static void
1794 spawn_exec_data_release(struct spawn_exec_data *data)
1795 {
1796 if (atomic_dec_32_nv(&data->sed_refcnt) != 0)
1797 return;
1798
1799 cv_destroy(&data->sed_cv_child_ready);
1800 mutex_destroy(&data->sed_mtx_child);
1801
1802 if (data->sed_actions)
1803 posix_spawn_fa_free(data->sed_actions,
1804 data->sed_actions->len);
1805 if (data->sed_attrs)
1806 kmem_free(data->sed_attrs,
1807 sizeof(*data->sed_attrs));
1808 kmem_free(data, sizeof(*data));
1809 }
1810
1811 /*
1812 * A child lwp of a posix_spawn operation starts here and ends up in
1813 * cpu_spawn_return, dealing with all filedescriptor and scheduler
1814 * manipulations in between.
1815 * The parent waits for the child, as it is not clear wether the child
1816 * will be able to aquire its own exec_lock. If it can, the parent can
1817 * be released early and continue running in parallel. If not (or if the
1818 * magic debug flag is passed in the scheduler attribute struct), the
1819 * child rides on the parent's exec lock untill it is ready to return to
1820 * to userland - and only then releases the parent. This method loses
1821 * concurrency, but improves error reporting.
1822 */
1823 static void
1824 spawn_return(void *arg)
1825 {
1826 struct spawn_exec_data *spawn_data = arg;
1827 struct lwp *l = curlwp;
1828 int error, newfd;
1829 size_t i;
1830 const struct posix_spawn_file_actions_entry *fae;
1831 pid_t ppid;
1832 register_t retval;
1833 bool have_reflock;
1834 bool parent_is_waiting = true;
1835
1836 /*
1837 * Check if we can release parent early.
1838 * We either need to have no sed_attrs, or sed_attrs does not
1839 * have POSIX_SPAWN_RETURNERROR or one of the flags, that require
1840 * safe access to the parent proc (passed in sed_parent).
1841 * We then try to get the exec_lock, and only if that works, we can
1842 * release the parent here already.
1843 */
1844 ppid = spawn_data->sed_parent->p_pid;
1845 if ((!spawn_data->sed_attrs
1846 || (spawn_data->sed_attrs->sa_flags
1847 & (POSIX_SPAWN_RETURNERROR|POSIX_SPAWN_SETPGROUP)) == 0)
1848 && rw_tryenter(&exec_lock, RW_READER)) {
1849 parent_is_waiting = false;
1850 mutex_enter(&spawn_data->sed_mtx_child);
1851 cv_signal(&spawn_data->sed_cv_child_ready);
1852 mutex_exit(&spawn_data->sed_mtx_child);
1853 }
1854
1855 /* don't allow debugger access yet */
1856 rw_enter(&l->l_proc->p_reflock, RW_WRITER);
1857 have_reflock = true;
1858
1859 error = 0;
1860 /* handle posix_spawn_file_actions */
1861 if (spawn_data->sed_actions != NULL) {
1862 for (i = 0; i < spawn_data->sed_actions->len; i++) {
1863 fae = &spawn_data->sed_actions->fae[i];
1864 switch (fae->fae_action) {
1865 case FAE_OPEN:
1866 if (fd_getfile(fae->fae_fildes) != NULL) {
1867 error = fd_close(fae->fae_fildes);
1868 if (error)
1869 break;
1870 }
1871 error = fd_open(fae->fae_path, fae->fae_oflag,
1872 fae->fae_mode, &newfd);
1873 if (error)
1874 break;
1875 if (newfd != fae->fae_fildes) {
1876 error = dodup(l, newfd,
1877 fae->fae_fildes, 0, &retval);
1878 if (fd_getfile(newfd) != NULL)
1879 fd_close(newfd);
1880 }
1881 break;
1882 case FAE_DUP2:
1883 error = dodup(l, fae->fae_fildes,
1884 fae->fae_newfildes, 0, &retval);
1885 break;
1886 case FAE_CLOSE:
1887 if (fd_getfile(fae->fae_fildes) == NULL) {
1888 error = EBADF;
1889 break;
1890 }
1891 error = fd_close(fae->fae_fildes);
1892 break;
1893 }
1894 if (error)
1895 goto report_error;
1896 }
1897 }
1898
1899 /* handle posix_spawnattr */
1900 if (spawn_data->sed_attrs != NULL) {
1901 int ostat;
1902 struct sigaction sigact;
1903 sigact._sa_u._sa_handler = SIG_DFL;
1904 sigact.sa_flags = 0;
1905
1906 /*
1907 * set state to SSTOP so that this proc can be found by pid.
1908 * see proc_enterprp, do_sched_setparam below
1909 */
1910 ostat = l->l_proc->p_stat;
1911 l->l_proc->p_stat = SSTOP;
1912
1913 /* Set process group */
1914 if (spawn_data->sed_attrs->sa_flags & POSIX_SPAWN_SETPGROUP) {
1915 pid_t mypid = l->l_proc->p_pid,
1916 pgrp = spawn_data->sed_attrs->sa_pgroup;
1917
1918 if (pgrp == 0)
1919 pgrp = mypid;
1920
1921 error = proc_enterpgrp(spawn_data->sed_parent,
1922 mypid, pgrp, false);
1923 if (error)
1924 goto report_error;
1925 }
1926
1927 /* Set scheduler policy */
1928 if (spawn_data->sed_attrs->sa_flags & POSIX_SPAWN_SETSCHEDULER)
1929 error = do_sched_setparam(l->l_proc->p_pid, 0,
1930 spawn_data->sed_attrs->sa_schedpolicy,
1931 &spawn_data->sed_attrs->sa_schedparam);
1932 else if (spawn_data->sed_attrs->sa_flags
1933 & POSIX_SPAWN_SETSCHEDPARAM) {
1934 error = do_sched_setparam(ppid, 0,
1935 SCHED_NONE, &spawn_data->sed_attrs->sa_schedparam);
1936 }
1937 if (error)
1938 goto report_error;
1939
1940 /* Reset user ID's */
1941 if (spawn_data->sed_attrs->sa_flags & POSIX_SPAWN_RESETIDS) {
1942 error = do_setresuid(l, -1,
1943 kauth_cred_getgid(l->l_cred), -1,
1944 ID_E_EQ_R | ID_E_EQ_S);
1945 if (error)
1946 goto report_error;
1947 error = do_setresuid(l, -1,
1948 kauth_cred_getuid(l->l_cred), -1,
1949 ID_E_EQ_R | ID_E_EQ_S);
1950 if (error)
1951 goto report_error;
1952 }
1953
1954 /* Set signal masks/defaults */
1955 if (spawn_data->sed_attrs->sa_flags & POSIX_SPAWN_SETSIGMASK) {
1956 mutex_enter(l->l_proc->p_lock);
1957 error = sigprocmask1(l, SIG_SETMASK,
1958 &spawn_data->sed_attrs->sa_sigmask, NULL);
1959 mutex_exit(l->l_proc->p_lock);
1960 if (error)
1961 goto report_error;
1962 }
1963
1964 if (spawn_data->sed_attrs->sa_flags & POSIX_SPAWN_SETSIGDEF) {
1965 for (i = 1; i <= NSIG; i++) {
1966 if (sigismember(
1967 &spawn_data->sed_attrs->sa_sigdefault, i))
1968 sigaction1(l, i, &sigact, NULL, NULL,
1969 0);
1970 }
1971 }
1972 l->l_proc->p_stat = ostat;
1973 }
1974
1975 /* now do the real exec */
1976 error = execve_runproc(l, &spawn_data->sed_exec, parent_is_waiting,
1977 true);
1978 have_reflock = false;
1979 if (error == EJUSTRETURN)
1980 error = 0;
1981 else if (error)
1982 goto report_error;
1983
1984 if (parent_is_waiting) {
1985 mutex_enter(&spawn_data->sed_mtx_child);
1986 cv_signal(&spawn_data->sed_cv_child_ready);
1987 mutex_exit(&spawn_data->sed_mtx_child);
1988 }
1989
1990 /* release our refcount on the data */
1991 spawn_exec_data_release(spawn_data);
1992
1993 /* and finaly: leave to userland for the first time */
1994 cpu_spawn_return(l);
1995
1996 /* NOTREACHED */
1997 return;
1998
1999 report_error:
2000 if (have_reflock) {
2001 /*
2002 * We have not passed through execve_runproc(),
2003 * which would have released the p_reflock and also
2004 * taken ownership of the sed_exec part of spawn_data,
2005 * so release/free both here.
2006 */
2007 rw_exit(&l->l_proc->p_reflock);
2008 execve_free_data(&spawn_data->sed_exec);
2009 }
2010
2011 if (parent_is_waiting) {
2012 /* pass error to parent */
2013 mutex_enter(&spawn_data->sed_mtx_child);
2014 spawn_data->sed_error = error;
2015 cv_signal(&spawn_data->sed_cv_child_ready);
2016 mutex_exit(&spawn_data->sed_mtx_child);
2017 } else {
2018 rw_exit(&exec_lock);
2019 }
2020
2021 /* release our refcount on the data */
2022 spawn_exec_data_release(spawn_data);
2023
2024 /* done, exit */
2025 mutex_enter(l->l_proc->p_lock);
2026 /*
2027 * Posix explicitly asks for an exit code of 127 if we report
2028 * errors from the child process - so, unfortunately, there
2029 * is no way to report a more exact error code.
2030 * A NetBSD specific workaround is POSIX_SPAWN_RETURNERROR as
2031 * flag bit in the attrp argument to posix_spawn(2), see above.
2032 */
2033 exit1(l, W_EXITCODE(127, 0));
2034 }
2035
2036 void
2037 posix_spawn_fa_free(struct posix_spawn_file_actions *fa, size_t len)
2038 {
2039
2040 for (size_t i = 0; i < len; i++) {
2041 struct posix_spawn_file_actions_entry *fae = &fa->fae[i];
2042 if (fae->fae_action != FAE_OPEN)
2043 continue;
2044 kmem_free(fae->fae_path, strlen(fae->fae_path) + 1);
2045 }
2046 if (fa->len > 0)
2047 kmem_free(fa->fae, sizeof(*fa->fae) * fa->len);
2048 kmem_free(fa, sizeof(*fa));
2049 }
2050
2051 static int
2052 posix_spawn_fa_alloc(struct posix_spawn_file_actions **fap,
2053 const struct posix_spawn_file_actions *ufa)
2054 {
2055 struct posix_spawn_file_actions *fa;
2056 struct posix_spawn_file_actions_entry *fae;
2057 char *pbuf = NULL;
2058 int error;
2059 size_t i = 0;
2060
2061 fa = kmem_alloc(sizeof(*fa), KM_SLEEP);
2062 error = copyin(ufa, fa, sizeof(*fa));
2063 if (error) {
2064 fa->fae = NULL;
2065 fa->len = 0;
2066 goto out;
2067 }
2068
2069 if (fa->len == 0) {
2070 kmem_free(fa, sizeof(*fa));
2071 return 0;
2072 }
2073
2074 fa->size = fa->len;
2075 size_t fal = fa->len * sizeof(*fae);
2076 fae = fa->fae;
2077 fa->fae = kmem_alloc(fal, KM_SLEEP);
2078 error = copyin(fae, fa->fae, fal);
2079 if (error)
2080 goto out;
2081
2082 pbuf = PNBUF_GET();
2083 for (; i < fa->len; i++) {
2084 fae = &fa->fae[i];
2085 if (fae->fae_action != FAE_OPEN)
2086 continue;
2087 error = copyinstr(fae->fae_path, pbuf, MAXPATHLEN, &fal);
2088 if (error)
2089 goto out;
2090 fae->fae_path = kmem_alloc(fal, KM_SLEEP);
2091 memcpy(fae->fae_path, pbuf, fal);
2092 }
2093 PNBUF_PUT(pbuf);
2094
2095 *fap = fa;
2096 return 0;
2097 out:
2098 if (pbuf)
2099 PNBUF_PUT(pbuf);
2100 posix_spawn_fa_free(fa, i);
2101 return error;
2102 }
2103
2104 int
2105 check_posix_spawn(struct lwp *l1)
2106 {
2107 int error, tnprocs, count;
2108 uid_t uid;
2109 struct proc *p1;
2110
2111 p1 = l1->l_proc;
2112 uid = kauth_cred_getuid(l1->l_cred);
2113 tnprocs = atomic_inc_uint_nv(&nprocs);
2114
2115 /*
2116 * Although process entries are dynamically created, we still keep
2117 * a global limit on the maximum number we will create.
2118 */
2119 if (__predict_false(tnprocs >= maxproc))
2120 error = -1;
2121 else
2122 error = kauth_authorize_process(l1->l_cred,
2123 KAUTH_PROCESS_FORK, p1, KAUTH_ARG(tnprocs), NULL, NULL);
2124
2125 if (error) {
2126 atomic_dec_uint(&nprocs);
2127 return EAGAIN;
2128 }
2129
2130 /*
2131 * Enforce limits.
2132 */
2133 count = chgproccnt(uid, 1);
2134 if (kauth_authorize_process(l1->l_cred, KAUTH_PROCESS_RLIMIT,
2135 p1, KAUTH_ARG(KAUTH_REQ_PROCESS_RLIMIT_BYPASS),
2136 &p1->p_rlimit[RLIMIT_NPROC], KAUTH_ARG(RLIMIT_NPROC)) != 0 &&
2137 __predict_false(count > p1->p_rlimit[RLIMIT_NPROC].rlim_cur)) {
2138 (void)chgproccnt(uid, -1);
2139 atomic_dec_uint(&nprocs);
2140 return EAGAIN;
2141 }
2142
2143 return 0;
2144 }
2145
2146 int
2147 do_posix_spawn(struct lwp *l1, pid_t *pid_res, bool *child_ok, const char *path,
2148 struct posix_spawn_file_actions *fa,
2149 struct posix_spawnattr *sa,
2150 char *const *argv, char *const *envp,
2151 execve_fetch_element_t fetch)
2152 {
2153
2154 struct proc *p1, *p2;
2155 struct lwp *l2;
2156 int error;
2157 struct spawn_exec_data *spawn_data;
2158 vaddr_t uaddr;
2159 pid_t pid;
2160 bool have_exec_lock = false;
2161
2162 p1 = l1->l_proc;
2163
2164 /* Allocate and init spawn_data */
2165 spawn_data = kmem_zalloc(sizeof(*spawn_data), KM_SLEEP);
2166 spawn_data->sed_refcnt = 1; /* only parent so far */
2167 cv_init(&spawn_data->sed_cv_child_ready, "pspawn");
2168 mutex_init(&spawn_data->sed_mtx_child, MUTEX_DEFAULT, IPL_NONE);
2169 mutex_enter(&spawn_data->sed_mtx_child);
2170
2171 /*
2172 * Do the first part of the exec now, collect state
2173 * in spawn_data.
2174 */
2175 error = execve_loadvm(l1, path, argv,
2176 envp, fetch, &spawn_data->sed_exec);
2177 if (error == EJUSTRETURN)
2178 error = 0;
2179 else if (error)
2180 goto error_exit;
2181
2182 have_exec_lock = true;
2183
2184 /*
2185 * Allocate virtual address space for the U-area now, while it
2186 * is still easy to abort the fork operation if we're out of
2187 * kernel virtual address space.
2188 */
2189 uaddr = uvm_uarea_alloc();
2190 if (__predict_false(uaddr == 0)) {
2191 error = ENOMEM;
2192 goto error_exit;
2193 }
2194
2195 /*
2196 * Allocate new proc. Borrow proc0 vmspace for it, we will
2197 * replace it with its own before returning to userland
2198 * in the child.
2199 * This is a point of no return, we will have to go through
2200 * the child proc to properly clean it up past this point.
2201 */
2202 p2 = proc_alloc();
2203 pid = p2->p_pid;
2204
2205 /*
2206 * Make a proc table entry for the new process.
2207 * Start by zeroing the section of proc that is zero-initialized,
2208 * then copy the section that is copied directly from the parent.
2209 */
2210 memset(&p2->p_startzero, 0,
2211 (unsigned) ((char *)&p2->p_endzero - (char *)&p2->p_startzero));
2212 memcpy(&p2->p_startcopy, &p1->p_startcopy,
2213 (unsigned) ((char *)&p2->p_endcopy - (char *)&p2->p_startcopy));
2214 p2->p_vmspace = proc0.p_vmspace;
2215
2216 CIRCLEQ_INIT(&p2->p_sigpend.sp_info);
2217
2218 LIST_INIT(&p2->p_lwps);
2219 LIST_INIT(&p2->p_sigwaiters);
2220
2221 /*
2222 * Duplicate sub-structures as needed.
2223 * Increase reference counts on shared objects.
2224 * Inherit flags we want to keep. The flags related to SIGCHLD
2225 * handling are important in order to keep a consistent behaviour
2226 * for the child after the fork. If we are a 32-bit process, the
2227 * child will be too.
2228 */
2229 p2->p_flag =
2230 p1->p_flag & (PK_SUGID | PK_NOCLDWAIT | PK_CLDSIGIGN | PK_32);
2231 p2->p_emul = p1->p_emul;
2232 p2->p_execsw = p1->p_execsw;
2233
2234 mutex_init(&p2->p_stmutex, MUTEX_DEFAULT, IPL_HIGH);
2235 mutex_init(&p2->p_auxlock, MUTEX_DEFAULT, IPL_NONE);
2236 rw_init(&p2->p_reflock);
2237 cv_init(&p2->p_waitcv, "wait");
2238 cv_init(&p2->p_lwpcv, "lwpwait");
2239
2240 p2->p_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
2241
2242 kauth_proc_fork(p1, p2);
2243
2244 p2->p_raslist = NULL;
2245 p2->p_fd = fd_copy();
2246
2247 /* XXX racy */
2248 p2->p_mqueue_cnt = p1->p_mqueue_cnt;
2249
2250 p2->p_cwdi = cwdinit();
2251
2252 /*
2253 * Note: p_limit (rlimit stuff) is copy-on-write, so normally
2254 * we just need increase pl_refcnt.
2255 */
2256 if (!p1->p_limit->pl_writeable) {
2257 lim_addref(p1->p_limit);
2258 p2->p_limit = p1->p_limit;
2259 } else {
2260 p2->p_limit = lim_copy(p1->p_limit);
2261 }
2262
2263 p2->p_lflag = 0;
2264 p2->p_sflag = 0;
2265 p2->p_slflag = 0;
2266 p2->p_pptr = p1;
2267 p2->p_ppid = p1->p_pid;
2268 LIST_INIT(&p2->p_children);
2269
2270 p2->p_aio = NULL;
2271
2272 #ifdef KTRACE
2273 /*
2274 * Copy traceflag and tracefile if enabled.
2275 * If not inherited, these were zeroed above.
2276 */
2277 if (p1->p_traceflag & KTRFAC_INHERIT) {
2278 mutex_enter(&ktrace_lock);
2279 p2->p_traceflag = p1->p_traceflag;
2280 if ((p2->p_tracep = p1->p_tracep) != NULL)
2281 ktradref(p2);
2282 mutex_exit(&ktrace_lock);
2283 }
2284 #endif
2285
2286 /*
2287 * Create signal actions for the child process.
2288 */
2289 p2->p_sigacts = sigactsinit(p1, 0);
2290 mutex_enter(p1->p_lock);
2291 p2->p_sflag |=
2292 (p1->p_sflag & (PS_STOPFORK | PS_STOPEXEC | PS_NOCLDSTOP));
2293 sched_proc_fork(p1, p2);
2294 mutex_exit(p1->p_lock);
2295
2296 p2->p_stflag = p1->p_stflag;
2297
2298 /*
2299 * p_stats.
2300 * Copy parts of p_stats, and zero out the rest.
2301 */
2302 p2->p_stats = pstatscopy(p1->p_stats);
2303
2304 /* copy over machdep flags to the new proc */
2305 cpu_proc_fork(p1, p2);
2306
2307 /*
2308 * Prepare remaining parts of spawn data
2309 */
2310 spawn_data->sed_actions = fa;
2311 spawn_data->sed_attrs = sa;
2312
2313 spawn_data->sed_parent = p1;
2314
2315 /* create LWP */
2316 lwp_create(l1, p2, uaddr, 0, NULL, 0, spawn_return, spawn_data,
2317 &l2, l1->l_class);
2318 l2->l_ctxlink = NULL; /* reset ucontext link */
2319
2320 /*
2321 * Copy the credential so other references don't see our changes.
2322 * Test to see if this is necessary first, since in the common case
2323 * we won't need a private reference.
2324 */
2325 if (kauth_cred_geteuid(l2->l_cred) != kauth_cred_getsvuid(l2->l_cred) ||
2326 kauth_cred_getegid(l2->l_cred) != kauth_cred_getsvgid(l2->l_cred)) {
2327 l2->l_cred = kauth_cred_copy(l2->l_cred);
2328 kauth_cred_setsvuid(l2->l_cred, kauth_cred_geteuid(l2->l_cred));
2329 kauth_cred_setsvgid(l2->l_cred, kauth_cred_getegid(l2->l_cred));
2330 }
2331
2332 /* Update the master credentials. */
2333 if (l2->l_cred != p2->p_cred) {
2334 kauth_cred_t ocred;
2335
2336 kauth_cred_hold(l2->l_cred);
2337 mutex_enter(p2->p_lock);
2338 ocred = p2->p_cred;
2339 p2->p_cred = l2->l_cred;
2340 mutex_exit(p2->p_lock);
2341 kauth_cred_free(ocred);
2342 }
2343
2344 *child_ok = true;
2345 spawn_data->sed_refcnt = 2; /* child gets it as well */
2346 #if 0
2347 l2->l_nopreempt = 1; /* start it non-preemptable */
2348 #endif
2349
2350 /*
2351 * It's now safe for the scheduler and other processes to see the
2352 * child process.
2353 */
2354 mutex_enter(proc_lock);
2355
2356 if (p1->p_session->s_ttyvp != NULL && p1->p_lflag & PL_CONTROLT)
2357 p2->p_lflag |= PL_CONTROLT;
2358
2359 LIST_INSERT_HEAD(&p1->p_children, p2, p_sibling);
2360 p2->p_exitsig = SIGCHLD; /* signal for parent on exit */
2361
2362 LIST_INSERT_AFTER(p1, p2, p_pglist);
2363 LIST_INSERT_HEAD(&allproc, p2, p_list);
2364
2365 p2->p_trace_enabled = trace_is_enabled(p2);
2366 #ifdef __HAVE_SYSCALL_INTERN
2367 (*p2->p_emul->e_syscall_intern)(p2);
2368 #endif
2369
2370 /*
2371 * Make child runnable, set start time, and add to run queue except
2372 * if the parent requested the child to start in SSTOP state.
2373 */
2374 mutex_enter(p2->p_lock);
2375
2376 getmicrotime(&p2->p_stats->p_start);
2377
2378 lwp_lock(l2);
2379 KASSERT(p2->p_nrlwps == 1);
2380 p2->p_nrlwps = 1;
2381 p2->p_stat = SACTIVE;
2382 l2->l_stat = LSRUN;
2383 sched_enqueue(l2, false);
2384 lwp_unlock(l2);
2385
2386 mutex_exit(p2->p_lock);
2387 mutex_exit(proc_lock);
2388
2389 cv_wait(&spawn_data->sed_cv_child_ready, &spawn_data->sed_mtx_child);
2390 error = spawn_data->sed_error;
2391 mutex_exit(&spawn_data->sed_mtx_child);
2392 spawn_exec_data_release(spawn_data);
2393
2394 rw_exit(&p1->p_reflock);
2395 rw_exit(&exec_lock);
2396 have_exec_lock = false;
2397
2398 *pid_res = pid;
2399 return error;
2400
2401 error_exit:
2402 if (have_exec_lock) {
2403 execve_free_data(&spawn_data->sed_exec);
2404 rw_exit(&p1->p_reflock);
2405 rw_exit(&exec_lock);
2406 }
2407 mutex_exit(&spawn_data->sed_mtx_child);
2408 spawn_exec_data_release(spawn_data);
2409
2410 return error;
2411 }
2412
2413 int
2414 sys_posix_spawn(struct lwp *l1, const struct sys_posix_spawn_args *uap,
2415 register_t *retval)
2416 {
2417 /* {
2418 syscallarg(pid_t *) pid;
2419 syscallarg(const char *) path;
2420 syscallarg(const struct posix_spawn_file_actions *) file_actions;
2421 syscallarg(const struct posix_spawnattr *) attrp;
2422 syscallarg(char *const *) argv;
2423 syscallarg(char *const *) envp;
2424 } */
2425
2426 int error;
2427 struct posix_spawn_file_actions *fa = NULL;
2428 struct posix_spawnattr *sa = NULL;
2429 pid_t pid;
2430 bool child_ok = false;
2431
2432 error = check_posix_spawn(l1);
2433 if (error) {
2434 *retval = error;
2435 return 0;
2436 }
2437
2438 /* copy in file_actions struct */
2439 if (SCARG(uap, file_actions) != NULL) {
2440 error = posix_spawn_fa_alloc(&fa, SCARG(uap, file_actions));
2441 if (error)
2442 goto error_exit;
2443 }
2444
2445 /* copyin posix_spawnattr struct */
2446 if (SCARG(uap, attrp) != NULL) {
2447 sa = kmem_alloc(sizeof(*sa), KM_SLEEP);
2448 error = copyin(SCARG(uap, attrp), sa, sizeof(*sa));
2449 if (error)
2450 goto error_exit;
2451 }
2452
2453 /*
2454 * Do the spawn
2455 */
2456 error = do_posix_spawn(l1, &pid, &child_ok, SCARG(uap, path), fa, sa,
2457 SCARG(uap, argv), SCARG(uap, envp), execve_fetch_element);
2458 if (error)
2459 goto error_exit;
2460
2461 if (error == 0 && SCARG(uap, pid) != NULL)
2462 error = copyout(&pid, SCARG(uap, pid), sizeof(pid));
2463
2464 *retval = error;
2465 return 0;
2466
2467 error_exit:
2468 if (!child_ok) {
2469 (void)chgproccnt(kauth_cred_getuid(l1->l_cred), -1);
2470 atomic_dec_uint(&nprocs);
2471
2472 if (sa)
2473 kmem_free(sa, sizeof(*sa));
2474 if (fa)
2475 posix_spawn_fa_free(fa, fa->len);
2476 }
2477
2478 *retval = error;
2479 return 0;
2480 }
2481
2482 void
2483 exec_free_emul_arg(struct exec_package *epp)
2484 {
2485 if (epp->ep_emul_arg_free != NULL) {
2486 KASSERT(epp->ep_emul_arg != NULL);
2487 (*epp->ep_emul_arg_free)(epp->ep_emul_arg);
2488 epp->ep_emul_arg_free = NULL;
2489 epp->ep_emul_arg = NULL;
2490 } else {
2491 KASSERT(epp->ep_emul_arg == NULL);
2492 }
2493 }
2494