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