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