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