1 /*	$NetBSD: kern_exec.c,v 1.435 2016/07/07 06:55:43 msaitoh 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.435 2016/07/07 06:55:43 msaitoh 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 *
exec_pool_alloc(struct pool * pp,int flags)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
exec_pool_free(struct pool * pp,void * addr)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*/
check_exec(struct lwp * l,struct exec_package * epp,struct pathbuf * pb)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
execve_fetch_element(char * const * array,size_t index,char ** value)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
sys_execve(struct lwp * l,const struct sys_execve_args * uap,register_t * retval)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
sys_fexecve(struct lwp * l,const struct sys_fexecve_args * uap,register_t * retval)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
exec_autoload(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
makepathbuf(struct lwp * l,const char * upath,struct pathbuf ** pbp,size_t * offs)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
execve_loadvm(struct lwp * l,const char * path,char * const * args,char * const * envs,execve_fetch_element_t fetch_element,struct execve_data * restrict data)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 && error != EACCES) {
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
execve_dovmcmds(struct lwp * l,struct execve_data * restrict data)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
execve_free_data(struct execve_data * data)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
pathexec(struct exec_package * epp,struct lwp * l,const char * pathstring)919 pathexec(struct exec_package *epp, struct lwp *l, const char *pathstring)
920 {
921 	const char		*commandname;
922 	size_t			commandlen;
923 	char			*path;
924 	struct proc 		*p = l->l_proc;
925 
926 	/* set command name & other accounting info */
927 	commandname = strrchr(epp->ep_resolvedname, '/');
928 	if (commandname != NULL) {
929 		commandname++;
930 	} else {
931 		commandname = epp->ep_resolvedname;
932 	}
933 	commandlen = min(strlen(commandname), MAXCOMLEN);
934 	(void)memcpy(p->p_comm, commandname, commandlen);
935 	p->p_comm[commandlen] = '\0';
936 
937 
938 	/*
939 	 * If the path starts with /, we don't need to do any work.
940 	 * This handles the majority of the cases.
941 	 * In the future perhaps we could canonicalize it?
942 	 */
943 	path = PNBUF_GET();
944 	if (pathstring[0] == '/') {
945 		(void)strlcpy(path, pathstring, MAXPATHLEN);
946 		epp->ep_path = path;
947 	}
948 #ifdef notyet
949 	/*
950 	 * Although this works most of the time [since the entry was just
951 	 * entered in the cache] we don't use it because it will fail for
952 	 * entries that are not placed in the cache because their name is
953 	 * longer than NCHNAMLEN and it is not the cleanest interface,
954 	 * because there could be races. When the namei cache is re-written,
955 	 * this can be changed to use the appropriate function.
956 	 */
957 	else if (!(error = vnode_to_path(path, MAXPATHLEN, p->p_textvp, l, p)))
958 		epp->ep_path = path;
959 #endif
960 	else {
961 #ifdef notyet
962 		printf("Cannot get path for pid %d [%s] (error %d)\n",
963 		    (int)p->p_pid, p->p_comm, error);
964 #endif
965 		PNBUF_PUT(path);
966  		epp->ep_path = NULL;
967 	}
968 }
969 
970 /* XXX elsewhere */
971 static int
credexec(struct lwp * l,struct vattr * attr)972 credexec(struct lwp *l, struct vattr *attr)
973 {
974 	struct proc *p = l->l_proc;
975 	int error;
976 
977 	/*
978 	 * Deal with set[ug]id.  MNT_NOSUID has already been used to disable
979 	 * s[ug]id.  It's OK to check for PSL_TRACED here as we have blocked
980 	 * out additional references on the process for the moment.
981 	 */
982 	if ((p->p_slflag & PSL_TRACED) == 0 &&
983 
984 	    (((attr->va_mode & S_ISUID) != 0 &&
985 	      kauth_cred_geteuid(l->l_cred) != attr->va_uid) ||
986 
987 	     ((attr->va_mode & S_ISGID) != 0 &&
988 	      kauth_cred_getegid(l->l_cred) != attr->va_gid))) {
989 		/*
990 		 * Mark the process as SUGID before we do
991 		 * anything that might block.
992 		 */
993 		proc_crmod_enter();
994 		proc_crmod_leave(NULL, NULL, true);
995 
996 		/* Make sure file descriptors 0..2 are in use. */
997 		if ((error = fd_checkstd()) != 0) {
998 			DPRINTF(("%s: fdcheckstd failed %d\n",
999 			    __func__, error));
1000 			return error;
1001 		}
1002 
1003 		/*
1004 		 * Copy the credential so other references don't see our
1005 		 * changes.
1006 		 */
1007 		l->l_cred = kauth_cred_copy(l->l_cred);
1008 #ifdef KTRACE
1009 		/*
1010 		 * If the persistent trace flag isn't set, turn off.
1011 		 */
1012 		if (p->p_tracep) {
1013 			mutex_enter(&ktrace_lock);
1014 			if (!(p->p_traceflag & KTRFAC_PERSISTENT))
1015 				ktrderef(p);
1016 			mutex_exit(&ktrace_lock);
1017 		}
1018 #endif
1019 		if (attr->va_mode & S_ISUID)
1020 			kauth_cred_seteuid(l->l_cred, attr->va_uid);
1021 		if (attr->va_mode & S_ISGID)
1022 			kauth_cred_setegid(l->l_cred, attr->va_gid);
1023 	} else {
1024 		if (kauth_cred_geteuid(l->l_cred) ==
1025 		    kauth_cred_getuid(l->l_cred) &&
1026 		    kauth_cred_getegid(l->l_cred) ==
1027 		    kauth_cred_getgid(l->l_cred))
1028 			p->p_flag &= ~PK_SUGID;
1029 	}
1030 
1031 	/*
1032 	 * Copy the credential so other references don't see our changes.
1033 	 * Test to see if this is necessary first, since in the common case
1034 	 * we won't need a private reference.
1035 	 */
1036 	if (kauth_cred_geteuid(l->l_cred) != kauth_cred_getsvuid(l->l_cred) ||
1037 	    kauth_cred_getegid(l->l_cred) != kauth_cred_getsvgid(l->l_cred)) {
1038 		l->l_cred = kauth_cred_copy(l->l_cred);
1039 		kauth_cred_setsvuid(l->l_cred, kauth_cred_geteuid(l->l_cred));
1040 		kauth_cred_setsvgid(l->l_cred, kauth_cred_getegid(l->l_cred));
1041 	}
1042 
1043 	/* Update the master credentials. */
1044 	if (l->l_cred != p->p_cred) {
1045 		kauth_cred_t ocred;
1046 
1047 		kauth_cred_hold(l->l_cred);
1048 		mutex_enter(p->p_lock);
1049 		ocred = p->p_cred;
1050 		p->p_cred = l->l_cred;
1051 		mutex_exit(p->p_lock);
1052 		kauth_cred_free(ocred);
1053 	}
1054 
1055 	return 0;
1056 }
1057 
1058 static void
emulexec(struct lwp * l,struct exec_package * epp)1059 emulexec(struct lwp *l, struct exec_package *epp)
1060 {
1061 	struct proc		*p = l->l_proc;
1062 
1063 	/* The emulation root will usually have been found when we looked
1064 	 * for the elf interpreter (or similar), if not look now. */
1065 	if (epp->ep_esch->es_emul->e_path != NULL &&
1066 	    epp->ep_emul_root == NULL)
1067 		emul_find_root(l, epp);
1068 
1069 	/* Any old emulation root got removed by fdcloseexec */
1070 	rw_enter(&p->p_cwdi->cwdi_lock, RW_WRITER);
1071 	p->p_cwdi->cwdi_edir = epp->ep_emul_root;
1072 	rw_exit(&p->p_cwdi->cwdi_lock);
1073 	epp->ep_emul_root = NULL;
1074 	if (epp->ep_interp != NULL)
1075 		vrele(epp->ep_interp);
1076 
1077 	/*
1078 	 * Call emulation specific exec hook. This can setup per-process
1079 	 * p->p_emuldata or do any other per-process stuff an emulation needs.
1080 	 *
1081 	 * If we are executing process of different emulation than the
1082 	 * original forked process, call e_proc_exit() of the old emulation
1083 	 * first, then e_proc_exec() of new emulation. If the emulation is
1084 	 * same, the exec hook code should deallocate any old emulation
1085 	 * resources held previously by this process.
1086 	 */
1087 	if (p->p_emul && p->p_emul->e_proc_exit
1088 	    && p->p_emul != epp->ep_esch->es_emul)
1089 		(*p->p_emul->e_proc_exit)(p);
1090 
1091 	/*
1092 	 * This is now LWP 1.
1093 	 */
1094 	/* XXX elsewhere */
1095 	mutex_enter(p->p_lock);
1096 	p->p_nlwpid = 1;
1097 	l->l_lid = 1;
1098 	mutex_exit(p->p_lock);
1099 
1100 	/*
1101 	 * Call exec hook. Emulation code may NOT store reference to anything
1102 	 * from &pack.
1103 	 */
1104 	if (epp->ep_esch->es_emul->e_proc_exec)
1105 		(*epp->ep_esch->es_emul->e_proc_exec)(p, epp);
1106 
1107 	/* update p_emul, the old value is no longer needed */
1108 	p->p_emul = epp->ep_esch->es_emul;
1109 
1110 	/* ...and the same for p_execsw */
1111 	p->p_execsw = epp->ep_esch;
1112 
1113 #ifdef __HAVE_SYSCALL_INTERN
1114 	(*p->p_emul->e_syscall_intern)(p);
1115 #endif
1116 	ktremul();
1117 }
1118 
1119 static int
execve_runproc(struct lwp * l,struct execve_data * restrict data,bool no_local_exec_lock,bool is_spawn)1120 execve_runproc(struct lwp *l, struct execve_data * restrict data,
1121 	bool no_local_exec_lock, bool is_spawn)
1122 {
1123 	struct exec_package	* const epp = &data->ed_pack;
1124 	int error = 0;
1125 	struct proc		*p;
1126 
1127 	/*
1128 	 * In case of a posix_spawn operation, the child doing the exec
1129 	 * might not hold the reader lock on exec_lock, but the parent
1130 	 * will do this instead.
1131 	 */
1132 	KASSERT(no_local_exec_lock || rw_lock_held(&exec_lock));
1133 	KASSERT(!no_local_exec_lock || is_spawn);
1134 	KASSERT(data != NULL);
1135 
1136 	p = l->l_proc;
1137 
1138 	/* Get rid of other LWPs. */
1139 	if (p->p_nlwps > 1) {
1140 		mutex_enter(p->p_lock);
1141 		exit_lwps(l);
1142 		mutex_exit(p->p_lock);
1143 	}
1144 	KDASSERT(p->p_nlwps == 1);
1145 
1146 	/* Destroy any lwpctl info. */
1147 	if (p->p_lwpctl != NULL)
1148 		lwp_ctl_exit();
1149 
1150 	/* Remove POSIX timers */
1151 	timers_free(p, TIMERS_POSIX);
1152 
1153 	/* Set the PaX flags. */
1154 	pax_set_flags(epp, p);
1155 
1156 	/*
1157 	 * Do whatever is necessary to prepare the address space
1158 	 * for remapping.  Note that this might replace the current
1159 	 * vmspace with another!
1160 	 */
1161 	if (is_spawn)
1162 		uvmspace_spawn(l, epp->ep_vm_minaddr,
1163 		    epp->ep_vm_maxaddr,
1164 		    epp->ep_flags & EXEC_TOPDOWN_VM);
1165 	else
1166 		uvmspace_exec(l, epp->ep_vm_minaddr,
1167 		    epp->ep_vm_maxaddr,
1168 		    epp->ep_flags & EXEC_TOPDOWN_VM);
1169 
1170 	struct vmspace		*vm;
1171 	vm = p->p_vmspace;
1172 	vm->vm_taddr = (void *)epp->ep_taddr;
1173 	vm->vm_tsize = btoc(epp->ep_tsize);
1174 	vm->vm_daddr = (void*)epp->ep_daddr;
1175 	vm->vm_dsize = btoc(epp->ep_dsize);
1176 	vm->vm_ssize = btoc(epp->ep_ssize);
1177 	vm->vm_issize = 0;
1178 	vm->vm_maxsaddr = (void *)epp->ep_maxsaddr;
1179 	vm->vm_minsaddr = (void *)epp->ep_minsaddr;
1180 
1181 	pax_aslr_init_vm(l, vm, epp);
1182 
1183 	/* Now map address space. */
1184 	error = execve_dovmcmds(l, data);
1185 	if (error != 0)
1186 		goto exec_abort;
1187 
1188 	pathexec(epp, l, data->ed_pathstring);
1189 
1190 	char * const newstack = STACK_GROW(vm->vm_minsaddr, epp->ep_ssize);
1191 
1192 	error = copyoutargs(data, l, newstack);
1193 	if (error != 0)
1194 		goto exec_abort;
1195 
1196 	cwdexec(p);
1197 	fd_closeexec();		/* handle close on exec */
1198 
1199 	if (__predict_false(ktrace_on))
1200 		fd_ktrexecfd();
1201 
1202 	execsigs(p);		/* reset catched signals */
1203 
1204 	mutex_enter(p->p_lock);
1205 	l->l_ctxlink = NULL;	/* reset ucontext link */
1206 	p->p_acflag &= ~AFORK;
1207 	p->p_flag |= PK_EXEC;
1208 	mutex_exit(p->p_lock);
1209 
1210 	/*
1211 	 * Stop profiling.
1212 	 */
1213 	if ((p->p_stflag & PST_PROFIL) != 0) {
1214 		mutex_spin_enter(&p->p_stmutex);
1215 		stopprofclock(p);
1216 		mutex_spin_exit(&p->p_stmutex);
1217 	}
1218 
1219 	/*
1220 	 * It's OK to test PL_PPWAIT unlocked here, as other LWPs have
1221 	 * exited and exec()/exit() are the only places it will be cleared.
1222 	 */
1223 	if ((p->p_lflag & PL_PPWAIT) != 0) {
1224 #if 0
1225 		lwp_t *lp;
1226 
1227 		mutex_enter(proc_lock);
1228 		lp = p->p_vforklwp;
1229 		p->p_vforklwp = NULL;
1230 
1231 		l->l_lwpctl = NULL; /* was on loan from blocked parent */
1232 		p->p_lflag &= ~PL_PPWAIT;
1233 
1234 		lp->l_pflag &= ~LP_VFORKWAIT; /* XXX */
1235 		cv_broadcast(&lp->l_waitcv);
1236 		mutex_exit(proc_lock);
1237 #else
1238 		mutex_enter(proc_lock);
1239 		l->l_lwpctl = NULL; /* was on loan from blocked parent */
1240 		p->p_lflag &= ~PL_PPWAIT;
1241 		cv_broadcast(&p->p_pptr->p_waitcv);
1242 		mutex_exit(proc_lock);
1243 #endif
1244 	}
1245 
1246 	error = credexec(l, &data->ed_attr);
1247 	if (error)
1248 		goto exec_abort;
1249 
1250 #if defined(__HAVE_RAS)
1251 	/*
1252 	 * Remove all RASs from the address space.
1253 	 */
1254 	ras_purgeall();
1255 #endif
1256 
1257 	doexechooks(p);
1258 
1259 	/*
1260 	 * Set initial SP at the top of the stack.
1261 	 *
1262 	 * Note that on machines where stack grows up (e.g. hppa), SP points to
1263 	 * the end of arg/env strings.  Userland guesses the address of argc
1264 	 * via ps_strings::ps_argvstr.
1265 	 */
1266 
1267 	/* Setup new registers and do misc. setup. */
1268 	(*epp->ep_esch->es_emul->e_setregs)(l, epp, (vaddr_t)newstack);
1269 	if (epp->ep_esch->es_setregs)
1270 		(*epp->ep_esch->es_setregs)(l, epp, (vaddr_t)newstack);
1271 
1272 	/* Provide a consistent LWP private setting */
1273 	(void)lwp_setprivate(l, NULL);
1274 
1275 	/* Discard all PCU state; need to start fresh */
1276 	pcu_discard_all(l);
1277 
1278 	/* map the process's signal trampoline code */
1279 	if ((error = exec_sigcode_map(p, epp->ep_esch->es_emul)) != 0) {
1280 		DPRINTF(("%s: map sigcode failed %d\n", __func__, error));
1281 		goto exec_abort;
1282 	}
1283 
1284 	pool_put(&exec_pool, data->ed_argp);
1285 
1286 	/* notify others that we exec'd */
1287 	KNOTE(&p->p_klist, NOTE_EXEC);
1288 
1289 	kmem_free(epp->ep_hdr, epp->ep_hdrlen);
1290 
1291 	SDT_PROBE(proc, kernel, , exec__success, epp->ep_kname, 0, 0, 0, 0);
1292 
1293 	emulexec(l, epp);
1294 
1295 	/* Allow new references from the debugger/procfs. */
1296 	rw_exit(&p->p_reflock);
1297 	if (!no_local_exec_lock)
1298 		rw_exit(&exec_lock);
1299 
1300 	mutex_enter(proc_lock);
1301 
1302 	if ((p->p_slflag & (PSL_TRACED|PSL_SYSCALL)) == PSL_TRACED) {
1303 		ksiginfo_t ksi;
1304 
1305 		KSI_INIT_EMPTY(&ksi);
1306 		ksi.ksi_signo = SIGTRAP;
1307 		ksi.ksi_lid = l->l_lid;
1308 		kpsignal(p, &ksi, NULL);
1309 	}
1310 
1311 	if (p->p_sflag & PS_STOPEXEC) {
1312 		ksiginfoq_t kq;
1313 
1314 		KERNEL_UNLOCK_ALL(l, &l->l_biglocks);
1315 		p->p_pptr->p_nstopchild++;
1316 		p->p_waited = 0;
1317 		mutex_enter(p->p_lock);
1318 		ksiginfo_queue_init(&kq);
1319 		sigclearall(p, &contsigmask, &kq);
1320 		lwp_lock(l);
1321 		l->l_stat = LSSTOP;
1322 		p->p_stat = SSTOP;
1323 		p->p_nrlwps--;
1324 		lwp_unlock(l);
1325 		mutex_exit(p->p_lock);
1326 		mutex_exit(proc_lock);
1327 		lwp_lock(l);
1328 		mi_switch(l);
1329 		ksiginfo_queue_drain(&kq);
1330 		KERNEL_LOCK(l->l_biglocks, l);
1331 	} else {
1332 		mutex_exit(proc_lock);
1333 	}
1334 
1335 	pathbuf_stringcopy_put(data->ed_pathbuf, data->ed_pathstring);
1336 	pathbuf_destroy(data->ed_pathbuf);
1337 	PNBUF_PUT(data->ed_resolvedpathbuf);
1338 #ifdef TRACE_EXEC
1339 	DPRINTF(("%s finished\n", __func__));
1340 #endif
1341 	return EJUSTRETURN;
1342 
1343  exec_abort:
1344 	SDT_PROBE(proc, kernel, , exec__failure, error, 0, 0, 0, 0);
1345 	rw_exit(&p->p_reflock);
1346 	if (!no_local_exec_lock)
1347 		rw_exit(&exec_lock);
1348 
1349 	pathbuf_stringcopy_put(data->ed_pathbuf, data->ed_pathstring);
1350 	pathbuf_destroy(data->ed_pathbuf);
1351 	PNBUF_PUT(data->ed_resolvedpathbuf);
1352 
1353 	/*
1354 	 * the old process doesn't exist anymore.  exit gracefully.
1355 	 * get rid of the (new) address space we have created, if any, get rid
1356 	 * of our namei data and vnode, and exit noting failure
1357 	 */
1358 	uvm_deallocate(&vm->vm_map, VM_MIN_ADDRESS,
1359 		VM_MAXUSER_ADDRESS - VM_MIN_ADDRESS);
1360 
1361 	exec_free_emul_arg(epp);
1362 	pool_put(&exec_pool, data->ed_argp);
1363 	kmem_free(epp->ep_hdr, epp->ep_hdrlen);
1364 	if (epp->ep_emul_root != NULL)
1365 		vrele(epp->ep_emul_root);
1366 	if (epp->ep_interp != NULL)
1367 		vrele(epp->ep_interp);
1368 
1369 	/* Acquire the sched-state mutex (exit1() will release it). */
1370 	if (!is_spawn) {
1371 		mutex_enter(p->p_lock);
1372 		exit1(l, error, SIGABRT);
1373 	}
1374 
1375 	return error;
1376 }
1377 
1378 int
execve1(struct lwp * l,const char * path,char * const * args,char * const * envs,execve_fetch_element_t fetch_element)1379 execve1(struct lwp *l, const char *path, char * const *args,
1380     char * const *envs, execve_fetch_element_t fetch_element)
1381 {
1382 	struct execve_data data;
1383 	int error;
1384 
1385 	error = execve_loadvm(l, path, args, envs, fetch_element, &data);
1386 	if (error)
1387 		return error;
1388 	error = execve_runproc(l, &data, false, false);
1389 	return error;
1390 }
1391 
1392 static size_t
fromptrsz(const struct exec_package * epp)1393 fromptrsz(const struct exec_package *epp)
1394 {
1395 	return (epp->ep_flags & EXEC_FROM32) ? sizeof(int) : sizeof(char *);
1396 }
1397 
1398 static size_t
ptrsz(const struct exec_package * epp)1399 ptrsz(const struct exec_package *epp)
1400 {
1401 	return (epp->ep_flags & EXEC_32) ? sizeof(int) : sizeof(char *);
1402 }
1403 
1404 static size_t
calcargs(struct execve_data * restrict data,const size_t argenvstrlen)1405 calcargs(struct execve_data * restrict data, const size_t argenvstrlen)
1406 {
1407 	struct exec_package	* const epp = &data->ed_pack;
1408 
1409 	const size_t nargenvptrs =
1410 	    1 +				/* long argc */
1411 	    data->ed_argc +		/* char *argv[] */
1412 	    1 +				/* \0 */
1413 	    data->ed_envc +		/* char *env[] */
1414 	    1 +				/* \0 */
1415 	    epp->ep_esch->es_arglen;	/* auxinfo */
1416 
1417 	return (nargenvptrs * ptrsz(epp)) + argenvstrlen;
1418 }
1419 
1420 static size_t
calcstack(struct execve_data * restrict data,const size_t gaplen)1421 calcstack(struct execve_data * restrict data, const size_t gaplen)
1422 {
1423 	struct exec_package	* const epp = &data->ed_pack;
1424 
1425 	data->ed_szsigcode = epp->ep_esch->es_emul->e_esigcode -
1426 	    epp->ep_esch->es_emul->e_sigcode;
1427 
1428 	data->ed_ps_strings_sz = (epp->ep_flags & EXEC_32) ?
1429 	    sizeof(struct ps_strings32) : sizeof(struct ps_strings);
1430 
1431 	const size_t sigcode_psstr_sz =
1432 	    data->ed_szsigcode +	/* sigcode */
1433 	    data->ed_ps_strings_sz +	/* ps_strings */
1434 	    STACK_PTHREADSPACE;		/* pthread space */
1435 
1436 	const size_t stacklen =
1437 	    data->ed_argslen +
1438 	    gaplen +
1439 	    sigcode_psstr_sz;
1440 
1441 	/* make the stack "safely" aligned */
1442 	return STACK_LEN_ALIGN(stacklen, STACK_ALIGNBYTES);
1443 }
1444 
1445 static int
copyoutargs(struct execve_data * restrict data,struct lwp * l,char * const newstack)1446 copyoutargs(struct execve_data * restrict data, struct lwp *l,
1447     char * const newstack)
1448 {
1449 	struct exec_package	* const epp = &data->ed_pack;
1450 	struct proc		*p = l->l_proc;
1451 	int			error;
1452 
1453 	/* remember information about the process */
1454 	data->ed_arginfo.ps_nargvstr = data->ed_argc;
1455 	data->ed_arginfo.ps_nenvstr = data->ed_envc;
1456 
1457 	/*
1458 	 * Allocate the stack address passed to the newly execve()'ed process.
1459 	 *
1460 	 * The new stack address will be set to the SP (stack pointer) register
1461 	 * in setregs().
1462 	 */
1463 
1464 	char *newargs = STACK_ALLOC(
1465 	    STACK_SHRINK(newstack, data->ed_argslen), data->ed_argslen);
1466 
1467 	error = (*epp->ep_esch->es_copyargs)(l, epp,
1468 	    &data->ed_arginfo, &newargs, data->ed_argp);
1469 
1470 	if (epp->ep_path) {
1471 		PNBUF_PUT(epp->ep_path);
1472 		epp->ep_path = NULL;
1473 	}
1474 	if (error) {
1475 		DPRINTF(("%s: copyargs failed %d\n", __func__, error));
1476 		return error;
1477 	}
1478 
1479 	error = copyoutpsstrs(data, p);
1480 	if (error != 0)
1481 		return error;
1482 
1483 	return 0;
1484 }
1485 
1486 static int
copyoutpsstrs(struct execve_data * restrict data,struct proc * p)1487 copyoutpsstrs(struct execve_data * restrict data, struct proc *p)
1488 {
1489 	struct exec_package	* const epp = &data->ed_pack;
1490 	struct ps_strings32	arginfo32;
1491 	void			*aip;
1492 	int			error;
1493 
1494 	/* fill process ps_strings info */
1495 	p->p_psstrp = (vaddr_t)STACK_ALLOC(STACK_GROW(epp->ep_minsaddr,
1496 	    STACK_PTHREADSPACE), data->ed_ps_strings_sz);
1497 
1498 	if (epp->ep_flags & EXEC_32) {
1499 		aip = &arginfo32;
1500 		arginfo32.ps_argvstr = (vaddr_t)data->ed_arginfo.ps_argvstr;
1501 		arginfo32.ps_nargvstr = data->ed_arginfo.ps_nargvstr;
1502 		arginfo32.ps_envstr = (vaddr_t)data->ed_arginfo.ps_envstr;
1503 		arginfo32.ps_nenvstr = data->ed_arginfo.ps_nenvstr;
1504 	} else
1505 		aip = &data->ed_arginfo;
1506 
1507 	/* copy out the process's ps_strings structure */
1508 	if ((error = copyout(aip, (void *)p->p_psstrp, data->ed_ps_strings_sz))
1509 	    != 0) {
1510 		DPRINTF(("%s: ps_strings copyout %p->%p size %zu failed\n",
1511 		    __func__, aip, (void *)p->p_psstrp, data->ed_ps_strings_sz));
1512 		return error;
1513 	}
1514 
1515 	return 0;
1516 }
1517 
1518 static int
copyinargs(struct execve_data * restrict data,char * const * args,char * const * envs,execve_fetch_element_t fetch_element,char ** dpp)1519 copyinargs(struct execve_data * restrict data, char * const *args,
1520     char * const *envs, execve_fetch_element_t fetch_element, char **dpp)
1521 {
1522 	struct exec_package	* const epp = &data->ed_pack;
1523 	char			*dp;
1524 	size_t			i;
1525 	int			error;
1526 
1527 	dp = *dpp;
1528 
1529 	data->ed_argc = 0;
1530 
1531 	/* copy the fake args list, if there's one, freeing it as we go */
1532 	if (epp->ep_flags & EXEC_HASARGL) {
1533 		struct exec_fakearg	*fa = epp->ep_fa;
1534 
1535 		while (fa->fa_arg != NULL) {
1536 			const size_t maxlen = ARG_MAX - (dp - data->ed_argp);
1537 			size_t len;
1538 
1539 			len = strlcpy(dp, fa->fa_arg, maxlen);
1540 			/* Count NUL into len. */
1541 			if (len < maxlen)
1542 				len++;
1543 			else {
1544 				while (fa->fa_arg != NULL) {
1545 					kmem_free(fa->fa_arg, fa->fa_len);
1546 					fa++;
1547 				}
1548 				kmem_free(epp->ep_fa, epp->ep_fa_len);
1549 				epp->ep_flags &= ~EXEC_HASARGL;
1550 				return E2BIG;
1551 			}
1552 			ktrexecarg(fa->fa_arg, len - 1);
1553 			dp += len;
1554 
1555 			kmem_free(fa->fa_arg, fa->fa_len);
1556 			fa++;
1557 			data->ed_argc++;
1558 		}
1559 		kmem_free(epp->ep_fa, epp->ep_fa_len);
1560 		epp->ep_flags &= ~EXEC_HASARGL;
1561 	}
1562 
1563 	/*
1564 	 * Read and count argument strings from user.
1565 	 */
1566 
1567 	if (args == NULL) {
1568 		DPRINTF(("%s: null args\n", __func__));
1569 		return EINVAL;
1570 	}
1571 	if (epp->ep_flags & EXEC_SKIPARG)
1572 		args = (const void *)((const char *)args + fromptrsz(epp));
1573 	i = 0;
1574 	error = copyinargstrs(data, args, fetch_element, &dp, &i, ktr_execarg);
1575 	if (error != 0) {
1576 		DPRINTF(("%s: copyin arg %d\n", __func__, error));
1577 		return error;
1578 	}
1579 	data->ed_argc += i;
1580 
1581 	/*
1582 	 * Read and count environment strings from user.
1583 	 */
1584 
1585 	data->ed_envc = 0;
1586 	/* environment need not be there */
1587 	if (envs == NULL)
1588 		goto done;
1589 	i = 0;
1590 	error = copyinargstrs(data, envs, fetch_element, &dp, &i, ktr_execenv);
1591 	if (error != 0) {
1592 		DPRINTF(("%s: copyin env %d\n", __func__, error));
1593 		return error;
1594 	}
1595 	data->ed_envc += i;
1596 
1597 done:
1598 	*dpp = dp;
1599 
1600 	return 0;
1601 }
1602 
1603 static int
copyinargstrs(struct execve_data * restrict data,char * const * strs,execve_fetch_element_t fetch_element,char ** dpp,size_t * ip,void (* ktr)(const void *,size_t))1604 copyinargstrs(struct execve_data * restrict data, char * const *strs,
1605     execve_fetch_element_t fetch_element, char **dpp, size_t *ip,
1606     void (*ktr)(const void *, size_t))
1607 {
1608 	char			*dp, *sp;
1609 	size_t			i;
1610 	int			error;
1611 
1612 	dp = *dpp;
1613 
1614 	i = 0;
1615 	while (1) {
1616 		const size_t maxlen = ARG_MAX - (dp - data->ed_argp);
1617 		size_t len;
1618 
1619 		if ((error = (*fetch_element)(strs, i, &sp)) != 0) {
1620 			return error;
1621 		}
1622 		if (!sp)
1623 			break;
1624 		if ((error = copyinstr(sp, dp, maxlen, &len)) != 0) {
1625 			if (error == ENAMETOOLONG)
1626 				error = E2BIG;
1627 			return error;
1628 		}
1629 		if (__predict_false(ktrace_on))
1630 			(*ktr)(dp, len - 1);
1631 		dp += len;
1632 		i++;
1633 	}
1634 
1635 	*dpp = dp;
1636 	*ip = i;
1637 
1638 	return 0;
1639 }
1640 
1641 /*
1642  * Copy argv and env strings from kernel buffer (argp) to the new stack.
1643  * Those strings are located just after auxinfo.
1644  */
1645 int
copyargs(struct lwp * l,struct exec_package * pack,struct ps_strings * arginfo,char ** stackp,void * argp)1646 copyargs(struct lwp *l, struct exec_package *pack, struct ps_strings *arginfo,
1647     char **stackp, void *argp)
1648 {
1649 	char	**cpp, *dp, *sp;
1650 	size_t	len;
1651 	void	*nullp;
1652 	long	argc, envc;
1653 	int	error;
1654 
1655 	cpp = (char **)*stackp;
1656 	nullp = NULL;
1657 	argc = arginfo->ps_nargvstr;
1658 	envc = arginfo->ps_nenvstr;
1659 
1660 	/* argc on stack is long */
1661 	CTASSERT(sizeof(*cpp) == sizeof(argc));
1662 
1663 	dp = (char *)(cpp +
1664 	    1 +				/* long argc */
1665 	    argc +			/* char *argv[] */
1666 	    1 +				/* \0 */
1667 	    envc +			/* char *env[] */
1668 	    1 +				/* \0 */
1669 	    /* XXX auxinfo multiplied by ptr size? */
1670 	    pack->ep_esch->es_arglen);	/* auxinfo */
1671 	sp = argp;
1672 
1673 	if ((error = copyout(&argc, cpp++, sizeof(argc))) != 0) {
1674 		COPYPRINTF("", cpp - 1, sizeof(argc));
1675 		return error;
1676 	}
1677 
1678 	/* XXX don't copy them out, remap them! */
1679 	arginfo->ps_argvstr = cpp; /* remember location of argv for later */
1680 
1681 	for (; --argc >= 0; sp += len, dp += len) {
1682 		if ((error = copyout(&dp, cpp++, sizeof(dp))) != 0) {
1683 			COPYPRINTF("", cpp - 1, sizeof(dp));
1684 			return error;
1685 		}
1686 		if ((error = copyoutstr(sp, dp, ARG_MAX, &len)) != 0) {
1687 			COPYPRINTF("str", dp, (size_t)ARG_MAX);
1688 			return error;
1689 		}
1690 	}
1691 
1692 	if ((error = copyout(&nullp, cpp++, sizeof(nullp))) != 0) {
1693 		COPYPRINTF("", cpp - 1, sizeof(nullp));
1694 		return error;
1695 	}
1696 
1697 	arginfo->ps_envstr = cpp; /* remember location of envp for later */
1698 
1699 	for (; --envc >= 0; sp += len, dp += len) {
1700 		if ((error = copyout(&dp, cpp++, sizeof(dp))) != 0) {
1701 			COPYPRINTF("", cpp - 1, sizeof(dp));
1702 			return error;
1703 		}
1704 		if ((error = copyoutstr(sp, dp, ARG_MAX, &len)) != 0) {
1705 			COPYPRINTF("str", dp, (size_t)ARG_MAX);
1706 			return error;
1707 		}
1708 
1709 	}
1710 
1711 	if ((error = copyout(&nullp, cpp++, sizeof(nullp))) != 0) {
1712 		COPYPRINTF("", cpp - 1, sizeof(nullp));
1713 		return error;
1714 	}
1715 
1716 	*stackp = (char *)cpp;
1717 	return 0;
1718 }
1719 
1720 
1721 /*
1722  * Add execsw[] entries.
1723  */
1724 int
exec_add(struct execsw * esp,int count)1725 exec_add(struct execsw *esp, int count)
1726 {
1727 	struct exec_entry	*it;
1728 	int			i;
1729 
1730 	if (count == 0) {
1731 		return 0;
1732 	}
1733 
1734 	/* Check for duplicates. */
1735 	rw_enter(&exec_lock, RW_WRITER);
1736 	for (i = 0; i < count; i++) {
1737 		LIST_FOREACH(it, &ex_head, ex_list) {
1738 			/* assume unique (makecmds, probe_func, emulation) */
1739 			if (it->ex_sw->es_makecmds == esp[i].es_makecmds &&
1740 			    it->ex_sw->u.elf_probe_func ==
1741 			    esp[i].u.elf_probe_func &&
1742 			    it->ex_sw->es_emul == esp[i].es_emul) {
1743 				rw_exit(&exec_lock);
1744 				return EEXIST;
1745 			}
1746 		}
1747 	}
1748 
1749 	/* Allocate new entries. */
1750 	for (i = 0; i < count; i++) {
1751 		it = kmem_alloc(sizeof(*it), KM_SLEEP);
1752 		it->ex_sw = &esp[i];
1753 		LIST_INSERT_HEAD(&ex_head, it, ex_list);
1754 	}
1755 
1756 	/* update execsw[] */
1757 	exec_init(0);
1758 	rw_exit(&exec_lock);
1759 	return 0;
1760 }
1761 
1762 /*
1763  * Remove execsw[] entry.
1764  */
1765 int
exec_remove(struct execsw * esp,int count)1766 exec_remove(struct execsw *esp, int count)
1767 {
1768 	struct exec_entry	*it, *next;
1769 	int			i;
1770 	const struct proclist_desc *pd;
1771 	proc_t			*p;
1772 
1773 	if (count == 0) {
1774 		return 0;
1775 	}
1776 
1777 	/* Abort if any are busy. */
1778 	rw_enter(&exec_lock, RW_WRITER);
1779 	for (i = 0; i < count; i++) {
1780 		mutex_enter(proc_lock);
1781 		for (pd = proclists; pd->pd_list != NULL; pd++) {
1782 			PROCLIST_FOREACH(p, pd->pd_list) {
1783 				if (p->p_execsw == &esp[i]) {
1784 					mutex_exit(proc_lock);
1785 					rw_exit(&exec_lock);
1786 					return EBUSY;
1787 				}
1788 			}
1789 		}
1790 		mutex_exit(proc_lock);
1791 	}
1792 
1793 	/* None are busy, so remove them all. */
1794 	for (i = 0; i < count; i++) {
1795 		for (it = LIST_FIRST(&ex_head); it != NULL; it = next) {
1796 			next = LIST_NEXT(it, ex_list);
1797 			if (it->ex_sw == &esp[i]) {
1798 				LIST_REMOVE(it, ex_list);
1799 				kmem_free(it, sizeof(*it));
1800 				break;
1801 			}
1802 		}
1803 	}
1804 
1805 	/* update execsw[] */
1806 	exec_init(0);
1807 	rw_exit(&exec_lock);
1808 	return 0;
1809 }
1810 
1811 /*
1812  * Initialize exec structures. If init_boot is true, also does necessary
1813  * one-time initialization (it's called from main() that way).
1814  * Once system is multiuser, this should be called with exec_lock held,
1815  * i.e. via exec_{add|remove}().
1816  */
1817 int
exec_init(int init_boot)1818 exec_init(int init_boot)
1819 {
1820 	const struct execsw 	**sw;
1821 	struct exec_entry	*ex;
1822 	SLIST_HEAD(,exec_entry)	first;
1823 	SLIST_HEAD(,exec_entry)	any;
1824 	SLIST_HEAD(,exec_entry)	last;
1825 	int			i, sz;
1826 
1827 	if (init_boot) {
1828 		/* do one-time initializations */
1829 		rw_init(&exec_lock);
1830 		mutex_init(&sigobject_lock, MUTEX_DEFAULT, IPL_NONE);
1831 		pool_init(&exec_pool, NCARGS, 0, 0, PR_NOALIGN|PR_NOTOUCH,
1832 		    "execargs", &exec_palloc, IPL_NONE);
1833 		pool_sethardlimit(&exec_pool, maxexec, "should not happen", 0);
1834 	} else {
1835 		KASSERT(rw_write_held(&exec_lock));
1836 	}
1837 
1838 	/* Sort each entry onto the appropriate queue. */
1839 	SLIST_INIT(&first);
1840 	SLIST_INIT(&any);
1841 	SLIST_INIT(&last);
1842 	sz = 0;
1843 	LIST_FOREACH(ex, &ex_head, ex_list) {
1844 		switch(ex->ex_sw->es_prio) {
1845 		case EXECSW_PRIO_FIRST:
1846 			SLIST_INSERT_HEAD(&first, ex, ex_slist);
1847 			break;
1848 		case EXECSW_PRIO_ANY:
1849 			SLIST_INSERT_HEAD(&any, ex, ex_slist);
1850 			break;
1851 		case EXECSW_PRIO_LAST:
1852 			SLIST_INSERT_HEAD(&last, ex, ex_slist);
1853 			break;
1854 		default:
1855 			panic("%s", __func__);
1856 			break;
1857 		}
1858 		sz++;
1859 	}
1860 
1861 	/*
1862 	 * Create new execsw[].  Ensure we do not try a zero-sized
1863 	 * allocation.
1864 	 */
1865 	sw = kmem_alloc(sz * sizeof(struct execsw *) + 1, KM_SLEEP);
1866 	i = 0;
1867 	SLIST_FOREACH(ex, &first, ex_slist) {
1868 		sw[i++] = ex->ex_sw;
1869 	}
1870 	SLIST_FOREACH(ex, &any, ex_slist) {
1871 		sw[i++] = ex->ex_sw;
1872 	}
1873 	SLIST_FOREACH(ex, &last, ex_slist) {
1874 		sw[i++] = ex->ex_sw;
1875 	}
1876 
1877 	/* Replace old execsw[] and free used memory. */
1878 	if (execsw != NULL) {
1879 		kmem_free(__UNCONST(execsw),
1880 		    nexecs * sizeof(struct execsw *) + 1);
1881 	}
1882 	execsw = sw;
1883 	nexecs = sz;
1884 
1885 	/* Figure out the maximum size of an exec header. */
1886 	exec_maxhdrsz = sizeof(int);
1887 	for (i = 0; i < nexecs; i++) {
1888 		if (execsw[i]->es_hdrsz > exec_maxhdrsz)
1889 			exec_maxhdrsz = execsw[i]->es_hdrsz;
1890 	}
1891 
1892 	return 0;
1893 }
1894 
1895 static int
exec_sigcode_map(struct proc * p,const struct emul * e)1896 exec_sigcode_map(struct proc *p, const struct emul *e)
1897 {
1898 	vaddr_t va;
1899 	vsize_t sz;
1900 	int error;
1901 	struct uvm_object *uobj;
1902 
1903 	sz = (vaddr_t)e->e_esigcode - (vaddr_t)e->e_sigcode;
1904 
1905 	if (e->e_sigobject == NULL || sz == 0) {
1906 		return 0;
1907 	}
1908 
1909 	/*
1910 	 * If we don't have a sigobject for this emulation, create one.
1911 	 *
1912 	 * sigobject is an anonymous memory object (just like SYSV shared
1913 	 * memory) that we keep a permanent reference to and that we map
1914 	 * in all processes that need this sigcode. The creation is simple,
1915 	 * we create an object, add a permanent reference to it, map it in
1916 	 * kernel space, copy out the sigcode to it and unmap it.
1917 	 * We map it with PROT_READ|PROT_EXEC into the process just
1918 	 * the way sys_mmap() would map it.
1919 	 */
1920 
1921 	uobj = *e->e_sigobject;
1922 	if (uobj == NULL) {
1923 		mutex_enter(&sigobject_lock);
1924 		if ((uobj = *e->e_sigobject) == NULL) {
1925 			uobj = uao_create(sz, 0);
1926 			(*uobj->pgops->pgo_reference)(uobj);
1927 			va = vm_map_min(kernel_map);
1928 			if ((error = uvm_map(kernel_map, &va, round_page(sz),
1929 			    uobj, 0, 0,
1930 			    UVM_MAPFLAG(UVM_PROT_RW, UVM_PROT_RW,
1931 			    UVM_INH_SHARE, UVM_ADV_RANDOM, 0)))) {
1932 				printf("kernel mapping failed %d\n", error);
1933 				(*uobj->pgops->pgo_detach)(uobj);
1934 				mutex_exit(&sigobject_lock);
1935 				return error;
1936 			}
1937 			memcpy((void *)va, e->e_sigcode, sz);
1938 #ifdef PMAP_NEED_PROCWR
1939 			pmap_procwr(&proc0, va, sz);
1940 #endif
1941 			uvm_unmap(kernel_map, va, va + round_page(sz));
1942 			*e->e_sigobject = uobj;
1943 		}
1944 		mutex_exit(&sigobject_lock);
1945 	}
1946 
1947 	/* Just a hint to uvm_map where to put it. */
1948 	va = e->e_vm_default_addr(p, (vaddr_t)p->p_vmspace->vm_daddr,
1949 	    round_page(sz), p->p_vmspace->vm_map.flags & VM_MAP_TOPDOWN);
1950 
1951 #ifdef __alpha__
1952 	/*
1953 	 * Tru64 puts /sbin/loader at the end of user virtual memory,
1954 	 * which causes the above calculation to put the sigcode at
1955 	 * an invalid address.  Put it just below the text instead.
1956 	 */
1957 	if (va == (vaddr_t)vm_map_max(&p->p_vmspace->vm_map)) {
1958 		va = (vaddr_t)p->p_vmspace->vm_taddr - round_page(sz);
1959 	}
1960 #endif
1961 
1962 	(*uobj->pgops->pgo_reference)(uobj);
1963 	error = uvm_map(&p->p_vmspace->vm_map, &va, round_page(sz),
1964 			uobj, 0, 0,
1965 			UVM_MAPFLAG(UVM_PROT_RX, UVM_PROT_RX, UVM_INH_SHARE,
1966 				    UVM_ADV_RANDOM, 0));
1967 	if (error) {
1968 		DPRINTF(("%s, %d: map %p "
1969 		    "uvm_map %#"PRIxVSIZE"@%#"PRIxVADDR" failed %d\n",
1970 		    __func__, __LINE__, &p->p_vmspace->vm_map, round_page(sz),
1971 		    va, error));
1972 		(*uobj->pgops->pgo_detach)(uobj);
1973 		return error;
1974 	}
1975 	p->p_sigctx.ps_sigcode = (void *)va;
1976 	return 0;
1977 }
1978 
1979 /*
1980  * Release a refcount on spawn_exec_data and destroy memory, if this
1981  * was the last one.
1982  */
1983 static void
spawn_exec_data_release(struct spawn_exec_data * data)1984 spawn_exec_data_release(struct spawn_exec_data *data)
1985 {
1986 	if (atomic_dec_32_nv(&data->sed_refcnt) != 0)
1987 		return;
1988 
1989 	cv_destroy(&data->sed_cv_child_ready);
1990 	mutex_destroy(&data->sed_mtx_child);
1991 
1992 	if (data->sed_actions)
1993 		posix_spawn_fa_free(data->sed_actions,
1994 		    data->sed_actions->len);
1995 	if (data->sed_attrs)
1996 		kmem_free(data->sed_attrs,
1997 		    sizeof(*data->sed_attrs));
1998 	kmem_free(data, sizeof(*data));
1999 }
2000 
2001 /*
2002  * A child lwp of a posix_spawn operation starts here and ends up in
2003  * cpu_spawn_return, dealing with all filedescriptor and scheduler
2004  * manipulations in between.
2005  * The parent waits for the child, as it is not clear whether the child
2006  * will be able to acquire its own exec_lock. If it can, the parent can
2007  * be released early and continue running in parallel. If not (or if the
2008  * magic debug flag is passed in the scheduler attribute struct), the
2009  * child rides on the parent's exec lock until it is ready to return to
2010  * to userland - and only then releases the parent. This method loses
2011  * concurrency, but improves error reporting.
2012  */
2013 static void
spawn_return(void * arg)2014 spawn_return(void *arg)
2015 {
2016 	struct spawn_exec_data *spawn_data = arg;
2017 	struct lwp *l = curlwp;
2018 	int error, newfd;
2019 	int ostat;
2020 	size_t i;
2021 	const struct posix_spawn_file_actions_entry *fae;
2022 	pid_t ppid;
2023 	register_t retval;
2024 	bool have_reflock;
2025 	bool parent_is_waiting = true;
2026 
2027 	/*
2028 	 * Check if we can release parent early.
2029 	 * We either need to have no sed_attrs, or sed_attrs does not
2030 	 * have POSIX_SPAWN_RETURNERROR or one of the flags, that require
2031 	 * safe access to the parent proc (passed in sed_parent).
2032 	 * We then try to get the exec_lock, and only if that works, we can
2033 	 * release the parent here already.
2034 	 */
2035 	ppid = spawn_data->sed_parent->p_pid;
2036 	if ((!spawn_data->sed_attrs
2037 	    || (spawn_data->sed_attrs->sa_flags
2038 	        & (POSIX_SPAWN_RETURNERROR|POSIX_SPAWN_SETPGROUP)) == 0)
2039 	    && rw_tryenter(&exec_lock, RW_READER)) {
2040 		parent_is_waiting = false;
2041 		mutex_enter(&spawn_data->sed_mtx_child);
2042 		cv_signal(&spawn_data->sed_cv_child_ready);
2043 		mutex_exit(&spawn_data->sed_mtx_child);
2044 	}
2045 
2046 	/* don't allow debugger access yet */
2047 	rw_enter(&l->l_proc->p_reflock, RW_WRITER);
2048 	have_reflock = true;
2049 
2050 	error = 0;
2051 	/* handle posix_spawn_file_actions */
2052 	if (spawn_data->sed_actions != NULL) {
2053 		for (i = 0; i < spawn_data->sed_actions->len; i++) {
2054 			fae = &spawn_data->sed_actions->fae[i];
2055 			switch (fae->fae_action) {
2056 			case FAE_OPEN:
2057 				if (fd_getfile(fae->fae_fildes) != NULL) {
2058 					error = fd_close(fae->fae_fildes);
2059 					if (error)
2060 						break;
2061 				}
2062 				error = fd_open(fae->fae_path, fae->fae_oflag,
2063 				    fae->fae_mode, &newfd);
2064 				if (error)
2065 					break;
2066 				if (newfd != fae->fae_fildes) {
2067 					error = dodup(l, newfd,
2068 					    fae->fae_fildes, 0, &retval);
2069 					if (fd_getfile(newfd) != NULL)
2070 						fd_close(newfd);
2071 				}
2072 				break;
2073 			case FAE_DUP2:
2074 				error = dodup(l, fae->fae_fildes,
2075 				    fae->fae_newfildes, 0, &retval);
2076 				break;
2077 			case FAE_CLOSE:
2078 				if (fd_getfile(fae->fae_fildes) == NULL) {
2079 					error = EBADF;
2080 					break;
2081 				}
2082 				error = fd_close(fae->fae_fildes);
2083 				break;
2084 			}
2085 			if (error)
2086 				goto report_error;
2087 		}
2088 	}
2089 
2090 	/* handle posix_spawnattr */
2091 	if (spawn_data->sed_attrs != NULL) {
2092 		struct sigaction sigact;
2093 		sigact._sa_u._sa_handler = SIG_DFL;
2094 		sigact.sa_flags = 0;
2095 
2096 		/*
2097 		 * set state to SSTOP so that this proc can be found by pid.
2098 		 * see proc_enterprp, do_sched_setparam below
2099 		 */
2100 		mutex_enter(proc_lock);
2101 		/*
2102 		 * p_stat should be SACTIVE, so we need to adjust the
2103 		 * parent's p_nstopchild here.  For safety, just make
2104 		 * we're on the good side of SDEAD before we adjust.
2105 		 */
2106 		ostat = l->l_proc->p_stat;
2107 		KASSERT(ostat < SSTOP);
2108 		l->l_proc->p_stat = SSTOP;
2109 		l->l_proc->p_waited = 0;
2110 		l->l_proc->p_pptr->p_nstopchild++;
2111 		mutex_exit(proc_lock);
2112 
2113 		/* Set process group */
2114 		if (spawn_data->sed_attrs->sa_flags & POSIX_SPAWN_SETPGROUP) {
2115 			pid_t mypid = l->l_proc->p_pid,
2116 			     pgrp = spawn_data->sed_attrs->sa_pgroup;
2117 
2118 			if (pgrp == 0)
2119 				pgrp = mypid;
2120 
2121 			error = proc_enterpgrp(spawn_data->sed_parent,
2122 			    mypid, pgrp, false);
2123 			if (error)
2124 				goto report_error_stopped;
2125 		}
2126 
2127 		/* Set scheduler policy */
2128 		if (spawn_data->sed_attrs->sa_flags & POSIX_SPAWN_SETSCHEDULER)
2129 			error = do_sched_setparam(l->l_proc->p_pid, 0,
2130 			    spawn_data->sed_attrs->sa_schedpolicy,
2131 			    &spawn_data->sed_attrs->sa_schedparam);
2132 		else if (spawn_data->sed_attrs->sa_flags
2133 		    & POSIX_SPAWN_SETSCHEDPARAM) {
2134 			error = do_sched_setparam(ppid, 0,
2135 			    SCHED_NONE, &spawn_data->sed_attrs->sa_schedparam);
2136 		}
2137 		if (error)
2138 			goto report_error_stopped;
2139 
2140 		/* Reset user ID's */
2141 		if (spawn_data->sed_attrs->sa_flags & POSIX_SPAWN_RESETIDS) {
2142 			error = do_setresuid(l, -1,
2143 			     kauth_cred_getgid(l->l_cred), -1,
2144 			     ID_E_EQ_R | ID_E_EQ_S);
2145 			if (error)
2146 				goto report_error_stopped;
2147 			error = do_setresuid(l, -1,
2148 			    kauth_cred_getuid(l->l_cred), -1,
2149 			    ID_E_EQ_R | ID_E_EQ_S);
2150 			if (error)
2151 				goto report_error_stopped;
2152 		}
2153 
2154 		/* Set signal masks/defaults */
2155 		if (spawn_data->sed_attrs->sa_flags & POSIX_SPAWN_SETSIGMASK) {
2156 			mutex_enter(l->l_proc->p_lock);
2157 			error = sigprocmask1(l, SIG_SETMASK,
2158 			    &spawn_data->sed_attrs->sa_sigmask, NULL);
2159 			mutex_exit(l->l_proc->p_lock);
2160 			if (error)
2161 				goto report_error_stopped;
2162 		}
2163 
2164 		if (spawn_data->sed_attrs->sa_flags & POSIX_SPAWN_SETSIGDEF) {
2165 			/*
2166 			 * The following sigaction call is using a sigaction
2167 			 * version 0 trampoline which is in the compatibility
2168 			 * code only. This is not a problem because for SIG_DFL
2169 			 * and SIG_IGN, the trampolines are now ignored. If they
2170 			 * were not, this would be a problem because we are
2171 			 * holding the exec_lock, and the compat code needs
2172 			 * to do the same in order to replace the trampoline
2173 			 * code of the process.
2174 			 */
2175 			for (i = 1; i <= NSIG; i++) {
2176 				if (sigismember(
2177 				    &spawn_data->sed_attrs->sa_sigdefault, i))
2178 					sigaction1(l, i, &sigact, NULL, NULL,
2179 					    0);
2180 			}
2181 		}
2182 		mutex_enter(proc_lock);
2183 		l->l_proc->p_stat = ostat;
2184 		l->l_proc->p_pptr->p_nstopchild--;
2185 		mutex_exit(proc_lock);
2186 	}
2187 
2188 	/* now do the real exec */
2189 	error = execve_runproc(l, &spawn_data->sed_exec, parent_is_waiting,
2190 	    true);
2191 	have_reflock = false;
2192 	if (error == EJUSTRETURN)
2193 		error = 0;
2194 	else if (error)
2195 		goto report_error;
2196 
2197 	if (parent_is_waiting) {
2198 		mutex_enter(&spawn_data->sed_mtx_child);
2199 		cv_signal(&spawn_data->sed_cv_child_ready);
2200 		mutex_exit(&spawn_data->sed_mtx_child);
2201 	}
2202 
2203 	/* release our refcount on the data */
2204 	spawn_exec_data_release(spawn_data);
2205 
2206 	/* and finally: leave to userland for the first time */
2207 	cpu_spawn_return(l);
2208 
2209 	/* NOTREACHED */
2210 	return;
2211 
2212  report_error_stopped:
2213 	mutex_enter(proc_lock);
2214 	l->l_proc->p_stat = ostat;
2215 	l->l_proc->p_pptr->p_nstopchild--;
2216 	mutex_exit(proc_lock);
2217  report_error:
2218 	if (have_reflock) {
2219 		/*
2220 		 * We have not passed through execve_runproc(),
2221 		 * which would have released the p_reflock and also
2222 		 * taken ownership of the sed_exec part of spawn_data,
2223 		 * so release/free both here.
2224 		 */
2225 		rw_exit(&l->l_proc->p_reflock);
2226 		execve_free_data(&spawn_data->sed_exec);
2227 	}
2228 
2229 	if (parent_is_waiting) {
2230 		/* pass error to parent */
2231 		mutex_enter(&spawn_data->sed_mtx_child);
2232 		spawn_data->sed_error = error;
2233 		cv_signal(&spawn_data->sed_cv_child_ready);
2234 		mutex_exit(&spawn_data->sed_mtx_child);
2235 	} else {
2236 		rw_exit(&exec_lock);
2237 	}
2238 
2239 	/* release our refcount on the data */
2240 	spawn_exec_data_release(spawn_data);
2241 
2242 	/* done, exit */
2243 	mutex_enter(l->l_proc->p_lock);
2244 	/*
2245 	 * Posix explicitly asks for an exit code of 127 if we report
2246 	 * errors from the child process - so, unfortunately, there
2247 	 * is no way to report a more exact error code.
2248 	 * A NetBSD specific workaround is POSIX_SPAWN_RETURNERROR as
2249 	 * flag bit in the attrp argument to posix_spawn(2), see above.
2250 	 */
2251 	exit1(l, 127, 0);
2252 }
2253 
2254 void
posix_spawn_fa_free(struct posix_spawn_file_actions * fa,size_t len)2255 posix_spawn_fa_free(struct posix_spawn_file_actions *fa, size_t len)
2256 {
2257 
2258 	for (size_t i = 0; i < len; i++) {
2259 		struct posix_spawn_file_actions_entry *fae = &fa->fae[i];
2260 		if (fae->fae_action != FAE_OPEN)
2261 			continue;
2262 		kmem_free(fae->fae_path, strlen(fae->fae_path) + 1);
2263 	}
2264 	if (fa->len > 0)
2265 		kmem_free(fa->fae, sizeof(*fa->fae) * fa->len);
2266 	kmem_free(fa, sizeof(*fa));
2267 }
2268 
2269 static int
posix_spawn_fa_alloc(struct posix_spawn_file_actions ** fap,const struct posix_spawn_file_actions * ufa,rlim_t lim)2270 posix_spawn_fa_alloc(struct posix_spawn_file_actions **fap,
2271     const struct posix_spawn_file_actions *ufa, rlim_t lim)
2272 {
2273 	struct posix_spawn_file_actions *fa;
2274 	struct posix_spawn_file_actions_entry *fae;
2275 	char *pbuf = NULL;
2276 	int error;
2277 	size_t i = 0;
2278 
2279 	fa = kmem_alloc(sizeof(*fa), KM_SLEEP);
2280 	error = copyin(ufa, fa, sizeof(*fa));
2281 	if (error || fa->len == 0) {
2282 		kmem_free(fa, sizeof(*fa));
2283 		return error;	/* 0 if not an error, and len == 0 */
2284 	}
2285 
2286 	if (fa->len > lim) {
2287 		kmem_free(fa, sizeof(*fa));
2288 		return EINVAL;
2289 	}
2290 
2291 	fa->size = fa->len;
2292 	size_t fal = fa->len * sizeof(*fae);
2293 	fae = fa->fae;
2294 	fa->fae = kmem_alloc(fal, KM_SLEEP);
2295 	error = copyin(fae, fa->fae, fal);
2296 	if (error)
2297 		goto out;
2298 
2299 	pbuf = PNBUF_GET();
2300 	for (; i < fa->len; i++) {
2301 		fae = &fa->fae[i];
2302 		if (fae->fae_action != FAE_OPEN)
2303 			continue;
2304 		error = copyinstr(fae->fae_path, pbuf, MAXPATHLEN, &fal);
2305 		if (error)
2306 			goto out;
2307 		fae->fae_path = kmem_alloc(fal, KM_SLEEP);
2308 		memcpy(fae->fae_path, pbuf, fal);
2309 	}
2310 	PNBUF_PUT(pbuf);
2311 
2312 	*fap = fa;
2313 	return 0;
2314 out:
2315 	if (pbuf)
2316 		PNBUF_PUT(pbuf);
2317 	posix_spawn_fa_free(fa, i);
2318 	return error;
2319 }
2320 
2321 int
check_posix_spawn(struct lwp * l1)2322 check_posix_spawn(struct lwp *l1)
2323 {
2324 	int error, tnprocs, count;
2325 	uid_t uid;
2326 	struct proc *p1;
2327 
2328 	p1 = l1->l_proc;
2329 	uid = kauth_cred_getuid(l1->l_cred);
2330 	tnprocs = atomic_inc_uint_nv(&nprocs);
2331 
2332 	/*
2333 	 * Although process entries are dynamically created, we still keep
2334 	 * a global limit on the maximum number we will create.
2335 	 */
2336 	if (__predict_false(tnprocs >= maxproc))
2337 		error = -1;
2338 	else
2339 		error = kauth_authorize_process(l1->l_cred,
2340 		    KAUTH_PROCESS_FORK, p1, KAUTH_ARG(tnprocs), NULL, NULL);
2341 
2342 	if (error) {
2343 		atomic_dec_uint(&nprocs);
2344 		return EAGAIN;
2345 	}
2346 
2347 	/*
2348 	 * Enforce limits.
2349 	 */
2350 	count = chgproccnt(uid, 1);
2351 	if (kauth_authorize_process(l1->l_cred, KAUTH_PROCESS_RLIMIT,
2352 	     p1, KAUTH_ARG(KAUTH_REQ_PROCESS_RLIMIT_BYPASS),
2353 	     &p1->p_rlimit[RLIMIT_NPROC], KAUTH_ARG(RLIMIT_NPROC)) != 0 &&
2354 	    __predict_false(count > p1->p_rlimit[RLIMIT_NPROC].rlim_cur)) {
2355 		(void)chgproccnt(uid, -1);
2356 		atomic_dec_uint(&nprocs);
2357 		return EAGAIN;
2358 	}
2359 
2360 	return 0;
2361 }
2362 
2363 int
do_posix_spawn(struct lwp * l1,pid_t * pid_res,bool * child_ok,const char * path,struct posix_spawn_file_actions * fa,struct posix_spawnattr * sa,char * const * argv,char * const * envp,execve_fetch_element_t fetch)2364 do_posix_spawn(struct lwp *l1, pid_t *pid_res, bool *child_ok, const char *path,
2365 	struct posix_spawn_file_actions *fa,
2366 	struct posix_spawnattr *sa,
2367 	char *const *argv, char *const *envp,
2368 	execve_fetch_element_t fetch)
2369 {
2370 
2371 	struct proc *p1, *p2;
2372 	struct lwp *l2;
2373 	int error;
2374 	struct spawn_exec_data *spawn_data;
2375 	vaddr_t uaddr;
2376 	pid_t pid;
2377 	bool have_exec_lock = false;
2378 
2379 	p1 = l1->l_proc;
2380 
2381 	/* Allocate and init spawn_data */
2382 	spawn_data = kmem_zalloc(sizeof(*spawn_data), KM_SLEEP);
2383 	spawn_data->sed_refcnt = 1; /* only parent so far */
2384 	cv_init(&spawn_data->sed_cv_child_ready, "pspawn");
2385 	mutex_init(&spawn_data->sed_mtx_child, MUTEX_DEFAULT, IPL_NONE);
2386 	mutex_enter(&spawn_data->sed_mtx_child);
2387 
2388 	/*
2389 	 * Do the first part of the exec now, collect state
2390 	 * in spawn_data.
2391 	 */
2392 	error = execve_loadvm(l1, path, argv,
2393 	    envp, fetch, &spawn_data->sed_exec);
2394 	if (error == EJUSTRETURN)
2395 		error = 0;
2396 	else if (error)
2397 		goto error_exit;
2398 
2399 	have_exec_lock = true;
2400 
2401 	/*
2402 	 * Allocate virtual address space for the U-area now, while it
2403 	 * is still easy to abort the fork operation if we're out of
2404 	 * kernel virtual address space.
2405 	 */
2406 	uaddr = uvm_uarea_alloc();
2407 	if (__predict_false(uaddr == 0)) {
2408 		error = ENOMEM;
2409 		goto error_exit;
2410 	}
2411 
2412 	/*
2413 	 * Allocate new proc. Borrow proc0 vmspace for it, we will
2414 	 * replace it with its own before returning to userland
2415 	 * in the child.
2416 	 * This is a point of no return, we will have to go through
2417 	 * the child proc to properly clean it up past this point.
2418 	 */
2419 	p2 = proc_alloc();
2420 	pid = p2->p_pid;
2421 
2422 	/*
2423 	 * Make a proc table entry for the new process.
2424 	 * Start by zeroing the section of proc that is zero-initialized,
2425 	 * then copy the section that is copied directly from the parent.
2426 	 */
2427 	memset(&p2->p_startzero, 0,
2428 	    (unsigned) ((char *)&p2->p_endzero - (char *)&p2->p_startzero));
2429 	memcpy(&p2->p_startcopy, &p1->p_startcopy,
2430 	    (unsigned) ((char *)&p2->p_endcopy - (char *)&p2->p_startcopy));
2431 	p2->p_vmspace = proc0.p_vmspace;
2432 
2433 	TAILQ_INIT(&p2->p_sigpend.sp_info);
2434 
2435 	LIST_INIT(&p2->p_lwps);
2436 	LIST_INIT(&p2->p_sigwaiters);
2437 
2438 	/*
2439 	 * Duplicate sub-structures as needed.
2440 	 * Increase reference counts on shared objects.
2441 	 * Inherit flags we want to keep.  The flags related to SIGCHLD
2442 	 * handling are important in order to keep a consistent behaviour
2443 	 * for the child after the fork.  If we are a 32-bit process, the
2444 	 * child will be too.
2445 	 */
2446 	p2->p_flag =
2447 	    p1->p_flag & (PK_SUGID | PK_NOCLDWAIT | PK_CLDSIGIGN | PK_32);
2448 	p2->p_emul = p1->p_emul;
2449 	p2->p_execsw = p1->p_execsw;
2450 
2451 	mutex_init(&p2->p_stmutex, MUTEX_DEFAULT, IPL_HIGH);
2452 	mutex_init(&p2->p_auxlock, MUTEX_DEFAULT, IPL_NONE);
2453 	rw_init(&p2->p_reflock);
2454 	cv_init(&p2->p_waitcv, "wait");
2455 	cv_init(&p2->p_lwpcv, "lwpwait");
2456 
2457 	p2->p_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
2458 
2459 	kauth_proc_fork(p1, p2);
2460 
2461 	p2->p_raslist = NULL;
2462 	p2->p_fd = fd_copy();
2463 
2464 	/* XXX racy */
2465 	p2->p_mqueue_cnt = p1->p_mqueue_cnt;
2466 
2467 	p2->p_cwdi = cwdinit();
2468 
2469 	/*
2470 	 * Note: p_limit (rlimit stuff) is copy-on-write, so normally
2471 	 * we just need increase pl_refcnt.
2472 	 */
2473 	if (!p1->p_limit->pl_writeable) {
2474 		lim_addref(p1->p_limit);
2475 		p2->p_limit = p1->p_limit;
2476 	} else {
2477 		p2->p_limit = lim_copy(p1->p_limit);
2478 	}
2479 
2480 	p2->p_lflag = 0;
2481 	p2->p_sflag = 0;
2482 	p2->p_slflag = 0;
2483 	p2->p_pptr = p1;
2484 	p2->p_ppid = p1->p_pid;
2485 	LIST_INIT(&p2->p_children);
2486 
2487 	p2->p_aio = NULL;
2488 
2489 #ifdef KTRACE
2490 	/*
2491 	 * Copy traceflag and tracefile if enabled.
2492 	 * If not inherited, these were zeroed above.
2493 	 */
2494 	if (p1->p_traceflag & KTRFAC_INHERIT) {
2495 		mutex_enter(&ktrace_lock);
2496 		p2->p_traceflag = p1->p_traceflag;
2497 		if ((p2->p_tracep = p1->p_tracep) != NULL)
2498 			ktradref(p2);
2499 		mutex_exit(&ktrace_lock);
2500 	}
2501 #endif
2502 
2503 	/*
2504 	 * Create signal actions for the child process.
2505 	 */
2506 	p2->p_sigacts = sigactsinit(p1, 0);
2507 	mutex_enter(p1->p_lock);
2508 	p2->p_sflag |=
2509 	    (p1->p_sflag & (PS_STOPFORK | PS_STOPEXEC | PS_NOCLDSTOP));
2510 	sched_proc_fork(p1, p2);
2511 	mutex_exit(p1->p_lock);
2512 
2513 	p2->p_stflag = p1->p_stflag;
2514 
2515 	/*
2516 	 * p_stats.
2517 	 * Copy parts of p_stats, and zero out the rest.
2518 	 */
2519 	p2->p_stats = pstatscopy(p1->p_stats);
2520 
2521 	/* copy over machdep flags to the new proc */
2522 	cpu_proc_fork(p1, p2);
2523 
2524 	/*
2525 	 * Prepare remaining parts of spawn data
2526 	 */
2527 	spawn_data->sed_actions = fa;
2528 	spawn_data->sed_attrs = sa;
2529 
2530 	spawn_data->sed_parent = p1;
2531 
2532 	/* create LWP */
2533 	lwp_create(l1, p2, uaddr, 0, NULL, 0, spawn_return, spawn_data,
2534 	    &l2, l1->l_class);
2535 	l2->l_ctxlink = NULL;	/* reset ucontext link */
2536 
2537 	/*
2538 	 * Copy the credential so other references don't see our changes.
2539 	 * Test to see if this is necessary first, since in the common case
2540 	 * we won't need a private reference.
2541 	 */
2542 	if (kauth_cred_geteuid(l2->l_cred) != kauth_cred_getsvuid(l2->l_cred) ||
2543 	    kauth_cred_getegid(l2->l_cred) != kauth_cred_getsvgid(l2->l_cred)) {
2544 		l2->l_cred = kauth_cred_copy(l2->l_cred);
2545 		kauth_cred_setsvuid(l2->l_cred, kauth_cred_geteuid(l2->l_cred));
2546 		kauth_cred_setsvgid(l2->l_cred, kauth_cred_getegid(l2->l_cred));
2547 	}
2548 
2549 	/* Update the master credentials. */
2550 	if (l2->l_cred != p2->p_cred) {
2551 		kauth_cred_t ocred;
2552 
2553 		kauth_cred_hold(l2->l_cred);
2554 		mutex_enter(p2->p_lock);
2555 		ocred = p2->p_cred;
2556 		p2->p_cred = l2->l_cred;
2557 		mutex_exit(p2->p_lock);
2558 		kauth_cred_free(ocred);
2559 	}
2560 
2561 	*child_ok = true;
2562 	spawn_data->sed_refcnt = 2;	/* child gets it as well */
2563 #if 0
2564 	l2->l_nopreempt = 1; /* start it non-preemptable */
2565 #endif
2566 
2567 	/*
2568 	 * It's now safe for the scheduler and other processes to see the
2569 	 * child process.
2570 	 */
2571 	mutex_enter(proc_lock);
2572 
2573 	if (p1->p_session->s_ttyvp != NULL && p1->p_lflag & PL_CONTROLT)
2574 		p2->p_lflag |= PL_CONTROLT;
2575 
2576 	LIST_INSERT_HEAD(&p1->p_children, p2, p_sibling);
2577 	p2->p_exitsig = SIGCHLD;	/* signal for parent on exit */
2578 
2579 	LIST_INSERT_AFTER(p1, p2, p_pglist);
2580 	LIST_INSERT_HEAD(&allproc, p2, p_list);
2581 
2582 	p2->p_trace_enabled = trace_is_enabled(p2);
2583 #ifdef __HAVE_SYSCALL_INTERN
2584 	(*p2->p_emul->e_syscall_intern)(p2);
2585 #endif
2586 
2587 	/*
2588 	 * Make child runnable, set start time, and add to run queue except
2589 	 * if the parent requested the child to start in SSTOP state.
2590 	 */
2591 	mutex_enter(p2->p_lock);
2592 
2593 	getmicrotime(&p2->p_stats->p_start);
2594 
2595 	lwp_lock(l2);
2596 	KASSERT(p2->p_nrlwps == 1);
2597 	p2->p_nrlwps = 1;
2598 	p2->p_stat = SACTIVE;
2599 	l2->l_stat = LSRUN;
2600 	sched_enqueue(l2, false);
2601 	lwp_unlock(l2);
2602 
2603 	mutex_exit(p2->p_lock);
2604 	mutex_exit(proc_lock);
2605 
2606 	cv_wait(&spawn_data->sed_cv_child_ready, &spawn_data->sed_mtx_child);
2607 	error = spawn_data->sed_error;
2608 	mutex_exit(&spawn_data->sed_mtx_child);
2609 	spawn_exec_data_release(spawn_data);
2610 
2611 	rw_exit(&p1->p_reflock);
2612 	rw_exit(&exec_lock);
2613 	have_exec_lock = false;
2614 
2615 	*pid_res = pid;
2616 	return error;
2617 
2618  error_exit:
2619 	if (have_exec_lock) {
2620 		execve_free_data(&spawn_data->sed_exec);
2621 		rw_exit(&p1->p_reflock);
2622 		rw_exit(&exec_lock);
2623 	}
2624 	mutex_exit(&spawn_data->sed_mtx_child);
2625 	spawn_exec_data_release(spawn_data);
2626 
2627 	return error;
2628 }
2629 
2630 int
sys_posix_spawn(struct lwp * l1,const struct sys_posix_spawn_args * uap,register_t * retval)2631 sys_posix_spawn(struct lwp *l1, const struct sys_posix_spawn_args *uap,
2632     register_t *retval)
2633 {
2634 	/* {
2635 		syscallarg(pid_t *) pid;
2636 		syscallarg(const char *) path;
2637 		syscallarg(const struct posix_spawn_file_actions *) file_actions;
2638 		syscallarg(const struct posix_spawnattr *) attrp;
2639 		syscallarg(char *const *) argv;
2640 		syscallarg(char *const *) envp;
2641 	} */
2642 
2643 	int error;
2644 	struct posix_spawn_file_actions *fa = NULL;
2645 	struct posix_spawnattr *sa = NULL;
2646 	pid_t pid;
2647 	bool child_ok = false;
2648 	rlim_t max_fileactions;
2649 	proc_t *p = l1->l_proc;
2650 
2651 	error = check_posix_spawn(l1);
2652 	if (error) {
2653 		*retval = error;
2654 		return 0;
2655 	}
2656 
2657 	/* copy in file_actions struct */
2658 	if (SCARG(uap, file_actions) != NULL) {
2659 		max_fileactions = 2 * min(p->p_rlimit[RLIMIT_NOFILE].rlim_cur,
2660 		    maxfiles);
2661 		error = posix_spawn_fa_alloc(&fa, SCARG(uap, file_actions),
2662 		    max_fileactions);
2663 		if (error)
2664 			goto error_exit;
2665 	}
2666 
2667 	/* copyin posix_spawnattr struct */
2668 	if (SCARG(uap, attrp) != NULL) {
2669 		sa = kmem_alloc(sizeof(*sa), KM_SLEEP);
2670 		error = copyin(SCARG(uap, attrp), sa, sizeof(*sa));
2671 		if (error)
2672 			goto error_exit;
2673 	}
2674 
2675 	/*
2676 	 * Do the spawn
2677 	 */
2678 	error = do_posix_spawn(l1, &pid, &child_ok, SCARG(uap, path), fa, sa,
2679 	    SCARG(uap, argv), SCARG(uap, envp), execve_fetch_element);
2680 	if (error)
2681 		goto error_exit;
2682 
2683 	if (error == 0 && SCARG(uap, pid) != NULL)
2684 		error = copyout(&pid, SCARG(uap, pid), sizeof(pid));
2685 
2686 	*retval = error;
2687 	return 0;
2688 
2689  error_exit:
2690 	if (!child_ok) {
2691 		(void)chgproccnt(kauth_cred_getuid(l1->l_cred), -1);
2692 		atomic_dec_uint(&nprocs);
2693 
2694 		if (sa)
2695 			kmem_free(sa, sizeof(*sa));
2696 		if (fa)
2697 			posix_spawn_fa_free(fa, fa->len);
2698 	}
2699 
2700 	*retval = error;
2701 	return 0;
2702 }
2703 
2704 void
exec_free_emul_arg(struct exec_package * epp)2705 exec_free_emul_arg(struct exec_package *epp)
2706 {
2707 	if (epp->ep_emul_arg_free != NULL) {
2708 		KASSERT(epp->ep_emul_arg != NULL);
2709 		(*epp->ep_emul_arg_free)(epp->ep_emul_arg);
2710 		epp->ep_emul_arg_free = NULL;
2711 		epp->ep_emul_arg = NULL;
2712 	} else {
2713 		KASSERT(epp->ep_emul_arg == NULL);
2714 	}
2715 }
2716 
2717 #ifdef DEBUG_EXEC
2718 static void
dump_vmcmds(const struct exec_package * const epp,size_t x,int error)2719 dump_vmcmds(const struct exec_package * const epp, size_t x, int error)
2720 {
2721 	struct exec_vmcmd *vp = &epp->ep_vmcmds.evs_cmds[0];
2722 	size_t j;
2723 
2724 	if (error == 0)
2725 		DPRINTF(("vmcmds %u\n", epp->ep_vmcmds.evs_used));
2726 	else
2727 		DPRINTF(("vmcmds %zu/%u, error %d\n", x,
2728 		    epp->ep_vmcmds.evs_used, error));
2729 
2730 	for (j = 0; j < epp->ep_vmcmds.evs_used; j++) {
2731 		DPRINTF(("vmcmd[%zu] = vmcmd_map_%s %#"
2732 		    PRIxVADDR"/%#"PRIxVSIZE" fd@%#"
2733 		    PRIxVSIZE" prot=0%o flags=%d\n", j,
2734 		    vp[j].ev_proc == vmcmd_map_pagedvn ?
2735 		    "pagedvn" :
2736 		    vp[j].ev_proc == vmcmd_map_readvn ?
2737 		    "readvn" :
2738 		    vp[j].ev_proc == vmcmd_map_zero ?
2739 		    "zero" : "*unknown*",
2740 		    vp[j].ev_addr, vp[j].ev_len,
2741 		    vp[j].ev_offset, vp[j].ev_prot,
2742 		    vp[j].ev_flags));
2743 		if (error != 0 && j == x)
2744 			DPRINTF(("     ^--- failed\n"));
2745 	}
2746 }
2747 #endif
2748