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