xref: /openbsd-src/sys/kern/kern_exec.c (revision 6f05df2d9be0954bec42d51d943d77bd250fb664)
1 /*	$OpenBSD: kern_exec.c,v 1.149 2014/11/18 02:37:31 tedu Exp $	*/
2 /*	$NetBSD: kern_exec.c,v 1.75 1996/02/09 18:59:28 christos Exp $	*/
3 
4 /*-
5  * Copyright (C) 1993, 1994 Christopher G. Demetriou
6  * Copyright (C) 1992 Wolfgang Solfrank.
7  * Copyright (C) 1992 TooLs GmbH.
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by TooLs GmbH.
21  * 4. The name of TooLs GmbH may not be used to endorse or promote products
22  *    derived from this software without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``AS IS'' AND ANY EXPRESS OR
25  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27  * IN NO EVENT SHALL TOOLS GMBH BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
29  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
30  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
31  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
32  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
33  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34  */
35 
36 #include <sys/param.h>
37 #include <sys/systm.h>
38 #include <sys/filedesc.h>
39 #include <sys/kernel.h>
40 #include <sys/proc.h>
41 #include <sys/mount.h>
42 #include <sys/malloc.h>
43 #include <sys/pool.h>
44 #include <sys/namei.h>
45 #include <sys/vnode.h>
46 #include <sys/file.h>
47 #include <sys/acct.h>
48 #include <sys/exec.h>
49 #include <sys/ktrace.h>
50 #include <sys/resourcevar.h>
51 #include <sys/wait.h>
52 #include <sys/mman.h>
53 #include <sys/signalvar.h>
54 #include <sys/stat.h>
55 #include <sys/conf.h>
56 #ifdef SYSVSHM
57 #include <sys/shm.h>
58 #endif
59 
60 #include <sys/syscallargs.h>
61 
62 #include <machine/reg.h>
63 
64 #ifdef __HAVE_MD_TCB
65 # include <machine/tcb.h>
66 #endif
67 
68 #include "systrace.h"
69 
70 #if NSYSTRACE > 0
71 #include <dev/systrace.h>
72 #endif
73 
74 const struct kmem_va_mode kv_exec = {
75 	.kv_wait = 1,
76 	.kv_map = &exec_map
77 };
78 
79 /*
80  * Map the shared signal code.
81  */
82 int exec_sigcode_map(struct process *, struct emul *);
83 
84 /*
85  * If non-zero, stackgap_random specifies the upper limit of the random gap size
86  * added to the fixed stack gap. Must be n^2.
87  */
88 int stackgap_random = STACKGAP_RANDOM;
89 
90 /*
91  * check exec:
92  * given an "executable" described in the exec package's namei info,
93  * see what we can do with it.
94  *
95  * ON ENTRY:
96  *	exec package with appropriate namei info
97  *	proc pointer of exec'ing proc
98  *	NO SELF-LOCKED VNODES
99  *
100  * ON EXIT:
101  *	error:	nothing held, etc.  exec header still allocated.
102  *	ok:	filled exec package, one locked vnode.
103  *
104  * EXEC SWITCH ENTRY:
105  * 	Locked vnode to check, exec package, proc.
106  *
107  * EXEC SWITCH EXIT:
108  *	ok:	return 0, filled exec package, one locked vnode.
109  *	error:	destructive:
110  *			everything deallocated except exec header.
111  *		non-destructive:
112  *			error code, locked vnode, exec header unmodified
113  */
114 int
115 check_exec(struct proc *p, struct exec_package *epp)
116 {
117 	int error, i;
118 	struct vnode *vp;
119 	struct nameidata *ndp;
120 	size_t resid;
121 
122 	ndp = epp->ep_ndp;
123 	ndp->ni_cnd.cn_nameiop = LOOKUP;
124 	ndp->ni_cnd.cn_flags = FOLLOW | LOCKLEAF | SAVENAME;
125 	/* first get the vnode */
126 	if ((error = namei(ndp)) != 0)
127 		return (error);
128 	epp->ep_vp = vp = ndp->ni_vp;
129 
130 	/* check for regular file */
131 	if (vp->v_type == VDIR) {
132 		error = EISDIR;
133 		goto bad1;
134 	}
135 	if (vp->v_type != VREG) {
136 		error = EACCES;
137 		goto bad1;
138 	}
139 
140 	/* get attributes */
141 	if ((error = VOP_GETATTR(vp, epp->ep_vap, p->p_ucred, p)) != 0)
142 		goto bad1;
143 
144 	/* Check mount point */
145 	if (vp->v_mount->mnt_flag & MNT_NOEXEC) {
146 		error = EACCES;
147 		goto bad1;
148 	}
149 
150 	if ((vp->v_mount->mnt_flag & MNT_NOSUID))
151 		epp->ep_vap->va_mode &= ~(VSUID | VSGID);
152 
153 	/* check access.  for root we have to see if any exec bit on */
154 	if ((error = VOP_ACCESS(vp, VEXEC, p->p_ucred, p)) != 0)
155 		goto bad1;
156 	if ((epp->ep_vap->va_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) == 0) {
157 		error = EACCES;
158 		goto bad1;
159 	}
160 
161 	/* try to open it */
162 	if ((error = VOP_OPEN(vp, FREAD, p->p_ucred, p)) != 0)
163 		goto bad1;
164 
165 	/* unlock vp, we need it unlocked from here */
166 	VOP_UNLOCK(vp, 0, p);
167 
168 	/* now we have the file, get the exec header */
169 	error = vn_rdwr(UIO_READ, vp, epp->ep_hdr, epp->ep_hdrlen, 0,
170 	    UIO_SYSSPACE, 0, p->p_ucred, &resid, p);
171 	if (error)
172 		goto bad2;
173 	epp->ep_hdrvalid = epp->ep_hdrlen - resid;
174 
175 	/*
176 	 * set up the vmcmds for creation of the process
177 	 * address space
178 	 */
179 	error = ENOEXEC;
180 	for (i = 0; i < nexecs && error != 0; i++) {
181 		int newerror;
182 
183 		if (execsw[i].es_check == NULL)
184 			continue;
185 		newerror = (*execsw[i].es_check)(p, epp);
186 		if (!newerror && !(epp->ep_emul->e_flags & EMUL_ENABLED))
187 			newerror = EPERM;
188 		/* make sure the first "interesting" error code is saved. */
189 		if (!newerror || error == ENOEXEC)
190 			error = newerror;
191 		if (epp->ep_flags & EXEC_DESTR && error != 0)
192 			return (error);
193 	}
194 	if (!error) {
195 		/* check that entry point is sane */
196 		if (epp->ep_entry > VM_MAXUSER_ADDRESS) {
197 			error = ENOEXEC;
198 		}
199 
200 		/* check limits */
201 		if ((epp->ep_tsize > MAXTSIZ) ||
202 		    (epp->ep_dsize > p->p_rlimit[RLIMIT_DATA].rlim_cur))
203 			error = ENOMEM;
204 
205 		if (!error)
206 			return (0);
207 	}
208 
209 	/*
210 	 * free any vmspace-creation commands,
211 	 * and release their references
212 	 */
213 	kill_vmcmds(&epp->ep_vmcmds);
214 
215 bad2:
216 	/*
217 	 * close the vnode, free the pathname buf, and punt.
218 	 */
219 	vn_close(vp, FREAD, p->p_ucred, p);
220 	pool_put(&namei_pool, ndp->ni_cnd.cn_pnbuf);
221 	return (error);
222 
223 bad1:
224 	/*
225 	 * free the namei pathname buffer, and put the vnode
226 	 * (which we don't yet have open).
227 	 */
228 	pool_put(&namei_pool, ndp->ni_cnd.cn_pnbuf);
229 	vput(vp);
230 	return (error);
231 }
232 
233 /*
234  * exec system call
235  */
236 /* ARGSUSED */
237 int
238 sys_execve(struct proc *p, void *v, register_t *retval)
239 {
240 	struct sys_execve_args /* {
241 		syscallarg(const char *) path;
242 		syscallarg(char *const *) argp;
243 		syscallarg(char *const *) envp;
244 	} */ *uap = v;
245 	int error;
246 	struct exec_package pack;
247 	struct nameidata nid;
248 	struct vattr attr;
249 	struct ucred *cred = p->p_ucred;
250 	char *argp;
251 	char * const *cpp, *dp, *sp;
252 	struct process *pr = p->p_p;
253 	long argc, envc;
254 	size_t len, sgap;
255 #ifdef MACHINE_STACK_GROWS_UP
256 	size_t slen;
257 #endif
258 	char *stack;
259 	struct ps_strings arginfo;
260 	struct vmspace *vm = pr->ps_vmspace;
261 	char **tmpfap;
262 	extern struct emul emul_native;
263 #if NSYSTRACE > 0
264 	int wassugid = ISSET(pr->ps_flags, PS_SUGID | PS_SUGIDEXEC);
265 	size_t pathbuflen;
266 #endif
267 	char *pathbuf = NULL;
268 	struct vnode *otvp;
269 
270 	/* get other threads to stop */
271 	if ((error = single_thread_set(p, SINGLE_UNWIND, 1)))
272 		return (error);
273 
274 	/*
275 	 * Cheap solution to complicated problems.
276 	 * Mark this process as "leave me alone, I'm execing".
277 	 */
278 	atomic_setbits_int(&pr->ps_flags, PS_INEXEC);
279 
280 #if NSYSTRACE > 0
281 	if (ISSET(p->p_flag, P_SYSTRACE)) {
282 		systrace_execve0(p);
283 		pathbuf = pool_get(&namei_pool, PR_WAITOK);
284 		error = copyinstr(SCARG(uap, path), pathbuf, MAXPATHLEN,
285 		    &pathbuflen);
286 		if (error != 0)
287 			goto clrflag;
288 	}
289 #endif
290 	if (pathbuf != NULL) {
291 		NDINIT(&nid, LOOKUP, NOFOLLOW, UIO_SYSSPACE, pathbuf, p);
292 	} else {
293 		NDINIT(&nid, LOOKUP, NOFOLLOW, UIO_USERSPACE,
294 		    SCARG(uap, path), p);
295 	}
296 
297 	/*
298 	 * initialize the fields of the exec package.
299 	 */
300 	if (pathbuf != NULL)
301 		pack.ep_name = pathbuf;
302 	else
303 		pack.ep_name = (char *)SCARG(uap, path);
304 	pack.ep_hdr = malloc(exec_maxhdrsz, M_EXEC, M_WAITOK);
305 	pack.ep_hdrlen = exec_maxhdrsz;
306 	pack.ep_hdrvalid = 0;
307 	pack.ep_ndp = &nid;
308 	pack.ep_interp = NULL;
309 	pack.ep_emul_arg = NULL;
310 	VMCMDSET_INIT(&pack.ep_vmcmds);
311 	pack.ep_vap = &attr;
312 	pack.ep_emul = &emul_native;
313 	pack.ep_flags = 0;
314 
315 	/* see if we can run it. */
316 	if ((error = check_exec(p, &pack)) != 0) {
317 		goto freehdr;
318 	}
319 
320 	/* XXX -- THE FOLLOWING SECTION NEEDS MAJOR CLEANUP */
321 
322 	/* allocate an argument buffer */
323 	argp = km_alloc(NCARGS, &kv_exec, &kp_pageable, &kd_waitok);
324 #ifdef DIAGNOSTIC
325 	if (argp == NULL)
326 		panic("execve: argp == NULL");
327 #endif
328 	dp = argp;
329 	argc = 0;
330 
331 	/* copy the fake args list, if there's one, freeing it as we go */
332 	if (pack.ep_flags & EXEC_HASARGL) {
333 		tmpfap = pack.ep_fa;
334 		while (*tmpfap != NULL) {
335 			char *cp;
336 
337 			cp = *tmpfap;
338 			while (*cp)
339 				*dp++ = *cp++;
340 			*dp++ = '\0';
341 
342 			free(*tmpfap, M_EXEC, 0);
343 			tmpfap++; argc++;
344 		}
345 		free(pack.ep_fa, M_EXEC, 0);
346 		pack.ep_flags &= ~EXEC_HASARGL;
347 	}
348 
349 	/* Now get argv & environment */
350 	if (!(cpp = SCARG(uap, argp))) {
351 		error = EFAULT;
352 		goto bad;
353 	}
354 
355 	if (pack.ep_flags & EXEC_SKIPARG)
356 		cpp++;
357 
358 	while (1) {
359 		len = argp + ARG_MAX - dp;
360 		if ((error = copyin(cpp, &sp, sizeof(sp))) != 0)
361 			goto bad;
362 		if (!sp)
363 			break;
364 		if ((error = copyinstr(sp, dp, len, &len)) != 0) {
365 			if (error == ENAMETOOLONG)
366 				error = E2BIG;
367 			goto bad;
368 		}
369 		dp += len;
370 		cpp++;
371 		argc++;
372 	}
373 
374 	envc = 0;
375 	/* environment does not need to be there */
376 	if ((cpp = SCARG(uap, envp)) != NULL ) {
377 		while (1) {
378 			len = argp + ARG_MAX - dp;
379 			if ((error = copyin(cpp, &sp, sizeof(sp))) != 0)
380 				goto bad;
381 			if (!sp)
382 				break;
383 			if ((error = copyinstr(sp, dp, len, &len)) != 0) {
384 				if (error == ENAMETOOLONG)
385 					error = E2BIG;
386 				goto bad;
387 			}
388 			dp += len;
389 			cpp++;
390 			envc++;
391 		}
392 	}
393 
394 	dp = (char *)(((long)dp + _STACKALIGNBYTES) & ~_STACKALIGNBYTES);
395 
396 	sgap = STACKGAPLEN;
397 	if (stackgap_random != 0) {
398 		sgap += arc4random() & (stackgap_random - 1);
399 		sgap = (sgap + _STACKALIGNBYTES) & ~_STACKALIGNBYTES;
400 	}
401 
402 	/* Now check if args & environ fit into new stack */
403 	len = ((argc + envc + 2 + pack.ep_emul->e_arglen) * sizeof(char *) +
404 	    sizeof(long) + dp + sgap + sizeof(struct ps_strings)) - argp;
405 
406 	len = (len + _STACKALIGNBYTES) &~ _STACKALIGNBYTES;
407 
408 	if (len > pack.ep_ssize) { /* in effect, compare to initial limit */
409 		error = ENOMEM;
410 		goto bad;
411 	}
412 
413 	/* adjust "active stack depth" for process VSZ */
414 	pack.ep_ssize = len;	/* maybe should go elsewhere, but... */
415 
416 	/*
417 	 * we're committed: any further errors will kill the process, so
418 	 * kill the other threads now.
419 	 */
420 	single_thread_set(p, SINGLE_EXIT, 0);
421 
422 	/*
423 	 * Prepare vmspace for remapping. Note that uvmspace_exec can replace
424 	 * pr_vmspace!
425 	 */
426 	uvmspace_exec(p, VM_MIN_ADDRESS, VM_MAXUSER_ADDRESS);
427 
428 	vm = pr->ps_vmspace;
429 	/* Now map address space */
430 	vm->vm_taddr = (char *)trunc_page(pack.ep_taddr);
431 	vm->vm_tsize = atop(round_page(pack.ep_taddr + pack.ep_tsize) -
432 	    trunc_page(pack.ep_taddr));
433 	vm->vm_daddr = (char *)trunc_page(pack.ep_daddr);
434 	vm->vm_dsize = atop(round_page(pack.ep_daddr + pack.ep_dsize) -
435 	    trunc_page(pack.ep_daddr));
436 	vm->vm_dused = 0;
437 	vm->vm_ssize = atop(round_page(pack.ep_ssize));
438 	vm->vm_maxsaddr = (char *)pack.ep_maxsaddr;
439 	vm->vm_minsaddr = (char *)pack.ep_minsaddr;
440 
441 	/* create the new process's VM space by running the vmcmds */
442 #ifdef DIAGNOSTIC
443 	if (pack.ep_vmcmds.evs_used == 0)
444 		panic("execve: no vmcmds");
445 #endif
446 	error = exec_process_vmcmds(p, &pack);
447 
448 	/* if an error happened, deallocate and punt */
449 	if (error)
450 		goto exec_abort;
451 
452 	/* remember information about the process */
453 	arginfo.ps_nargvstr = argc;
454 	arginfo.ps_nenvstr = envc;
455 
456 #ifdef MACHINE_STACK_GROWS_UP
457 	stack = (char *)USRSTACK + sizeof(arginfo) + sgap;
458 	slen = len - sizeof(arginfo) - sgap;
459 #else
460 	stack = (char *)(USRSTACK - len);
461 #endif
462 	/* Now copy argc, args & environ to new stack */
463 	if (!(*pack.ep_emul->e_copyargs)(&pack, &arginfo, stack, argp))
464 		goto exec_abort;
465 
466 	/* copy out the process's ps_strings structure */
467 	if (copyout(&arginfo, (char *)PS_STRINGS, sizeof(arginfo)))
468 		goto exec_abort;
469 
470 	stopprofclock(pr);	/* stop profiling */
471 	fdcloseexec(p);		/* handle close on exec */
472 	execsigs(p);		/* reset caught signals */
473 	TCB_SET(p, NULL);	/* reset the TCB address */
474 
475 	/* set command name & other accounting info */
476 	memset(p->p_comm, 0, sizeof(p->p_comm));
477 	len = min(nid.ni_cnd.cn_namelen, MAXCOMLEN);
478 	bcopy(nid.ni_cnd.cn_nameptr, p->p_comm, len);
479 	pr->ps_acflag &= ~AFORK;
480 
481 	/* record proc's vnode, for use by sysctl */
482 	otvp = pr->ps_textvp;
483 	vref(pack.ep_vp);
484 	pr->ps_textvp = pack.ep_vp;
485 	if (otvp)
486 		vrele(otvp);
487 
488 	atomic_setbits_int(&pr->ps_flags, PS_EXEC);
489 	if (pr->ps_flags & PS_PPWAIT) {
490 		atomic_clearbits_int(&pr->ps_flags, PS_PPWAIT);
491 		atomic_clearbits_int(&pr->ps_pptr->ps_flags, PS_ISPWAIT);
492 		wakeup(pr->ps_pptr);
493 	}
494 
495 	/*
496 	 * If process does execve() while it has a mismatched real,
497 	 * effective, or saved uid/gid, we set PS_SUGIDEXEC.
498 	 */
499 	if (cred->cr_uid != cred->cr_ruid ||
500 	    cred->cr_uid != cred->cr_svuid ||
501 	    cred->cr_gid != cred->cr_rgid ||
502 	    cred->cr_gid != cred->cr_svgid)
503 		atomic_setbits_int(&pr->ps_flags, PS_SUGIDEXEC);
504 	else
505 		atomic_clearbits_int(&pr->ps_flags, PS_SUGIDEXEC);
506 
507 	/*
508 	 * deal with set[ug]id.
509 	 * MNT_NOEXEC has already been used to disable s[ug]id.
510 	 */
511 	if ((attr.va_mode & (VSUID | VSGID)) && proc_cansugid(p)) {
512 		int i;
513 
514 		atomic_setbits_int(&pr->ps_flags, PS_SUGID|PS_SUGIDEXEC);
515 
516 #ifdef KTRACE
517 		/*
518 		 * If process is being ktraced, turn off - unless
519 		 * root set it.
520 		 */
521 		if (pr->ps_tracevp && !(pr->ps_traceflag & KTRFAC_ROOT))
522 			ktrcleartrace(pr);
523 #endif
524 		p->p_ucred = cred = crcopy(cred);
525 		if (attr.va_mode & VSUID)
526 			cred->cr_uid = attr.va_uid;
527 		if (attr.va_mode & VSGID)
528 			cred->cr_gid = attr.va_gid;
529 
530 		/*
531 		 * For set[ug]id processes, a few caveats apply to
532 		 * stdin, stdout, and stderr.
533 		 */
534 		error = 0;
535 		fdplock(p->p_fd);
536 		for (i = 0; i < 3; i++) {
537 			struct file *fp = NULL;
538 
539 			/*
540 			 * NOTE - This will never return NULL because of
541 			 * immature fds. The file descriptor table is not
542 			 * shared because we're suid.
543 			 */
544 			fp = fd_getfile(p->p_fd, i);
545 
546 			/*
547 			 * Ensure that stdin, stdout, and stderr are already
548 			 * allocated.  We do not want userland to accidentally
549 			 * allocate descriptors in this range which has implied
550 			 * meaning to libc.
551 			 */
552 			if (fp == NULL) {
553 				short flags = FREAD | (i == 0 ? 0 : FWRITE);
554 				struct vnode *vp;
555 				int indx;
556 
557 				if ((error = falloc(p, &fp, &indx)) != 0)
558 					break;
559 #ifdef DIAGNOSTIC
560 				if (indx != i)
561 					panic("sys_execve: falloc indx != i");
562 #endif
563 				if ((error = cdevvp(getnulldev(), &vp)) != 0) {
564 					fdremove(p->p_fd, indx);
565 					closef(fp, p);
566 					break;
567 				}
568 				if ((error = VOP_OPEN(vp, flags, cred, p)) != 0) {
569 					fdremove(p->p_fd, indx);
570 					closef(fp, p);
571 					vrele(vp);
572 					break;
573 				}
574 				if (flags & FWRITE)
575 					vp->v_writecount++;
576 				fp->f_flag = flags;
577 				fp->f_type = DTYPE_VNODE;
578 				fp->f_ops = &vnops;
579 				fp->f_data = (caddr_t)vp;
580 				FILE_SET_MATURE(fp, p);
581 			}
582 		}
583 		fdpunlock(p->p_fd);
584 		if (error)
585 			goto exec_abort;
586 	} else
587 		atomic_clearbits_int(&pr->ps_flags, PS_SUGID);
588 
589 	/*
590 	 * Reset the saved ugids and update the process's copy of the
591 	 * creds if the creds have been changed
592 	 */
593 	if (cred->cr_uid != cred->cr_svuid ||
594 	    cred->cr_gid != cred->cr_svgid) {
595 		/* make sure we have unshared ucreds */
596 		p->p_ucred = cred = crcopy(cred);
597 		cred->cr_svuid = cred->cr_uid;
598 		cred->cr_svgid = cred->cr_gid;
599 	}
600 
601 	if (pr->ps_ucred != cred) {
602 		struct ucred *ocred;
603 
604 		ocred = pr->ps_ucred;
605 		crhold(cred);
606 		pr->ps_ucred = cred;
607 		crfree(ocred);
608 	}
609 
610 	if (pr->ps_flags & PS_SUGIDEXEC) {
611 		int i, s = splclock();
612 
613 		timeout_del(&pr->ps_realit_to);
614 		for (i = 0; i < nitems(pr->ps_timer); i++) {
615 			timerclear(&pr->ps_timer[i].it_interval);
616 			timerclear(&pr->ps_timer[i].it_value);
617 		}
618 		splx(s);
619 	}
620 
621 	/* reset CPU time usage for the thread, but not the process */
622 	timespecclear(&p->p_tu.tu_runtime);
623 	p->p_tu.tu_uticks = p->p_tu.tu_sticks = p->p_tu.tu_iticks = 0;
624 
625 	km_free(argp, NCARGS, &kv_exec, &kp_pageable);
626 
627 	pool_put(&namei_pool, nid.ni_cnd.cn_pnbuf);
628 	vn_close(pack.ep_vp, FREAD, cred, p);
629 
630 	/*
631 	 * notify others that we exec'd
632 	 */
633 	KNOTE(&pr->ps_klist, NOTE_EXEC);
634 
635 	/* setup new registers and do misc. setup. */
636 	if (pack.ep_emul->e_fixup != NULL) {
637 		if ((*pack.ep_emul->e_fixup)(p, &pack) != 0)
638 			goto free_pack_abort;
639 	}
640 #ifdef MACHINE_STACK_GROWS_UP
641 	(*pack.ep_emul->e_setregs)(p, &pack, (u_long)stack + slen, retval);
642 #else
643 	(*pack.ep_emul->e_setregs)(p, &pack, (u_long)stack, retval);
644 #endif
645 
646 	/* map the process's signal trampoline code */
647 	if (exec_sigcode_map(pr, pack.ep_emul))
648 		goto free_pack_abort;
649 
650 #ifdef __HAVE_EXEC_MD_MAP
651 	/* perform md specific mappings that process might need */
652 	if (exec_md_map(p, &pack))
653 		goto free_pack_abort;
654 #endif
655 
656 	if (pr->ps_flags & PS_TRACED)
657 		psignal(p, SIGTRAP);
658 
659 	free(pack.ep_hdr, M_EXEC, 0);
660 
661 	/*
662 	 * Call emulation specific exec hook. This can setup per-process
663 	 * p->p_emuldata or do any other per-process stuff an emulation needs.
664 	 *
665 	 * If we are executing process of different emulation than the
666 	 * original forked process, call e_proc_exit() of the old emulation
667 	 * first, then e_proc_exec() of new emulation. If the emulation is
668 	 * same, the exec hook code should deallocate any old emulation
669 	 * resources held previously by this process.
670 	 */
671 	if (pr->ps_emul && pr->ps_emul->e_proc_exit &&
672 	    pr->ps_emul != pack.ep_emul)
673 		(*pr->ps_emul->e_proc_exit)(p);
674 
675 	p->p_descfd = 255;
676 	if ((pack.ep_flags & EXEC_HASFD) && pack.ep_fd < 255)
677 		p->p_descfd = pack.ep_fd;
678 
679 	/*
680 	 * Call exec hook. Emulation code may NOT store reference to anything
681 	 * from &pack.
682 	 */
683 	if (pack.ep_emul->e_proc_exec)
684 		(*pack.ep_emul->e_proc_exec)(p, &pack);
685 
686 	/* update ps_emul, the old value is no longer needed */
687 	pr->ps_emul = pack.ep_emul;
688 
689 #ifdef KTRACE
690 	if (KTRPOINT(p, KTR_EMUL))
691 		ktremul(p);
692 #endif
693 
694 	atomic_clearbits_int(&pr->ps_flags, PS_INEXEC);
695 	single_thread_clear(p, P_SUSPSIG);
696 
697 #if NSYSTRACE > 0
698 	if (ISSET(p->p_flag, P_SYSTRACE) &&
699 	    wassugid && !ISSET(pr->ps_flags, PS_SUGID | PS_SUGIDEXEC))
700 		systrace_execve1(pathbuf, p);
701 #endif
702 
703 	if (pathbuf != NULL)
704 		pool_put(&namei_pool, pathbuf);
705 
706 	return (0);
707 
708 bad:
709 	/* free the vmspace-creation commands, and release their references */
710 	kill_vmcmds(&pack.ep_vmcmds);
711 	/* kill any opened file descriptor, if necessary */
712 	if (pack.ep_flags & EXEC_HASFD) {
713 		pack.ep_flags &= ~EXEC_HASFD;
714 		fdplock(p->p_fd);
715 		(void) fdrelease(p, pack.ep_fd);
716 		fdpunlock(p->p_fd);
717 	}
718 	if (pack.ep_interp != NULL)
719 		pool_put(&namei_pool, pack.ep_interp);
720 	if (pack.ep_emul_arg != NULL)
721 		free(pack.ep_emul_arg, M_TEMP, 0);
722 	/* close and put the exec'd file */
723 	vn_close(pack.ep_vp, FREAD, cred, p);
724 	pool_put(&namei_pool, nid.ni_cnd.cn_pnbuf);
725 	km_free(argp, NCARGS, &kv_exec, &kp_pageable);
726 
727  freehdr:
728 	free(pack.ep_hdr, M_EXEC, 0);
729 #if NSYSTRACE > 0
730  clrflag:
731 #endif
732 	atomic_clearbits_int(&pr->ps_flags, PS_INEXEC);
733 	single_thread_clear(p, P_SUSPSIG);
734 
735 	if (pathbuf != NULL)
736 		pool_put(&namei_pool, pathbuf);
737 
738 	return (error);
739 
740 exec_abort:
741 	/*
742 	 * the old process doesn't exist anymore.  exit gracefully.
743 	 * get rid of the (new) address space we have created, if any, get rid
744 	 * of our namei data and vnode, and exit noting failure
745 	 */
746 	uvm_deallocate(&vm->vm_map, VM_MIN_ADDRESS,
747 		VM_MAXUSER_ADDRESS - VM_MIN_ADDRESS);
748 	if (pack.ep_interp != NULL)
749 		pool_put(&namei_pool, pack.ep_interp);
750 	if (pack.ep_emul_arg != NULL)
751 		free(pack.ep_emul_arg, M_TEMP, 0);
752 	pool_put(&namei_pool, nid.ni_cnd.cn_pnbuf);
753 	vn_close(pack.ep_vp, FREAD, cred, p);
754 	km_free(argp, NCARGS, &kv_exec, &kp_pageable);
755 
756 free_pack_abort:
757 	free(pack.ep_hdr, M_EXEC, 0);
758 	exit1(p, W_EXITCODE(0, SIGABRT), EXIT_NORMAL);
759 
760 	/* NOTREACHED */
761 	atomic_clearbits_int(&pr->ps_flags, PS_INEXEC);
762 	if (pathbuf != NULL)
763 		pool_put(&namei_pool, pathbuf);
764 
765 	return (0);
766 }
767 
768 
769 void *
770 copyargs(struct exec_package *pack, struct ps_strings *arginfo, void *stack,
771     void *argp)
772 {
773 	char **cpp = stack;
774 	char *dp, *sp;
775 	size_t len;
776 	void *nullp = NULL;
777 	long argc = arginfo->ps_nargvstr;
778 	int envc = arginfo->ps_nenvstr;
779 
780 	if (copyout(&argc, cpp++, sizeof(argc)))
781 		return (NULL);
782 
783 	dp = (char *) (cpp + argc + envc + 2 + pack->ep_emul->e_arglen);
784 	sp = argp;
785 
786 	/* XXX don't copy them out, remap them! */
787 	arginfo->ps_argvstr = cpp; /* remember location of argv for later */
788 
789 	for (; --argc >= 0; sp += len, dp += len)
790 		if (copyout(&dp, cpp++, sizeof(dp)) ||
791 		    copyoutstr(sp, dp, ARG_MAX, &len))
792 			return (NULL);
793 
794 	if (copyout(&nullp, cpp++, sizeof(nullp)))
795 		return (NULL);
796 
797 	arginfo->ps_envstr = cpp; /* remember location of envp for later */
798 
799 	for (; --envc >= 0; sp += len, dp += len)
800 		if (copyout(&dp, cpp++, sizeof(dp)) ||
801 		    copyoutstr(sp, dp, ARG_MAX, &len))
802 			return (NULL);
803 
804 	if (copyout(&nullp, cpp++, sizeof(nullp)))
805 		return (NULL);
806 
807 	return (cpp);
808 }
809 
810 int
811 exec_sigcode_map(struct process *pr, struct emul *e)
812 {
813 	vsize_t sz;
814 
815 	sz = (vaddr_t)e->e_esigcode - (vaddr_t)e->e_sigcode;
816 
817 	/*
818 	 * If we don't have a sigobject for this emulation, create one.
819 	 *
820 	 * sigobject is an anonymous memory object (just like SYSV shared
821 	 * memory) that we keep a permanent reference to and that we map
822 	 * in all processes that need this sigcode. The creation is simple,
823 	 * we create an object, add a permanent reference to it, map it in
824 	 * kernel space, copy out the sigcode to it and unmap it.
825 	 * Then we map it with PROT_READ|PROT_EXEC into the process just
826 	 * the way sys_mmap would map it.
827 	 */
828 	if (e->e_sigobject == NULL) {
829 		vaddr_t va;
830 		int r;
831 
832 		e->e_sigobject = uao_create(sz, 0);
833 		uao_reference(e->e_sigobject);	/* permanent reference */
834 
835 		if ((r = uvm_map(kernel_map, &va, round_page(sz), e->e_sigobject,
836 		    0, 0, UVM_MAPFLAG(PROT_READ | PROT_WRITE, PROT_READ | PROT_WRITE,
837 		    UVM_INH_SHARE, POSIX_MADV_RANDOM, 0)))) {
838 			uao_detach(e->e_sigobject);
839 			return (ENOMEM);
840 		}
841 		memcpy((void *)va, e->e_sigcode, sz);
842 		uvm_unmap(kernel_map, va, va + round_page(sz));
843 	}
844 
845 	pr->ps_sigcode = 0; /* no hint */
846 	uao_reference(e->e_sigobject);
847 	if (uvm_map(&pr->ps_vmspace->vm_map, &pr->ps_sigcode, round_page(sz),
848 	    e->e_sigobject, 0, 0, UVM_MAPFLAG(PROT_READ | PROT_EXEC,
849 	    PROT_READ | PROT_EXEC, UVM_INH_SHARE, POSIX_MADV_RANDOM, 0))) {
850 		uao_detach(e->e_sigobject);
851 		return (ENOMEM);
852 	}
853 
854 	return (0);
855 }
856