xref: /dragonfly/sys/kern/kern_exec.c (revision 509221ae)
1 /*
2  * Copyright (c) 1993, David Greenman
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $FreeBSD: src/sys/kern/kern_exec.c,v 1.107.2.15 2002/07/30 15:40:46 nectar Exp $
27  * $DragonFly: src/sys/kern/kern_exec.c,v 1.33 2005/06/22 19:40:35 dillon Exp $
28  */
29 
30 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/sysproto.h>
33 #include <sys/kernel.h>
34 #include <sys/mount.h>
35 #include <sys/filedesc.h>
36 #include <sys/fcntl.h>
37 #include <sys/acct.h>
38 #include <sys/exec.h>
39 #include <sys/imgact.h>
40 #include <sys/imgact_elf.h>
41 #include <sys/kern_syscall.h>
42 #include <sys/wait.h>
43 #include <sys/malloc.h>
44 #include <sys/proc.h>
45 #include <sys/signalvar.h>
46 #include <sys/pioctl.h>
47 #include <sys/nlookup.h>
48 #include <sys/sfbuf.h>
49 #include <sys/sysent.h>
50 #include <sys/shm.h>
51 #include <sys/sysctl.h>
52 #include <sys/vnode.h>
53 #include <sys/vmmeter.h>
54 #include <sys/aio.h>
55 #include <sys/libkern.h>
56 
57 #include <vm/vm.h>
58 #include <vm/vm_param.h>
59 #include <sys/lock.h>
60 #include <vm/pmap.h>
61 #include <vm/vm_page.h>
62 #include <vm/vm_map.h>
63 #include <vm/vm_kern.h>
64 #include <vm/vm_extern.h>
65 #include <vm/vm_object.h>
66 #include <vm/vm_pager.h>
67 
68 #include <sys/user.h>
69 #include <machine/reg.h>
70 
71 #include <sys/thread2.h>
72 
73 MALLOC_DEFINE(M_PARGS, "proc-args", "Process arguments");
74 
75 static register_t *exec_copyout_strings (struct image_params *);
76 
77 /* XXX This should be vm_size_t. */
78 static u_long ps_strings = PS_STRINGS;
79 SYSCTL_ULONG(_kern, KERN_PS_STRINGS, ps_strings, CTLFLAG_RD, &ps_strings, 0, "");
80 
81 /* XXX This should be vm_size_t. */
82 static u_long usrstack = USRSTACK;
83 SYSCTL_ULONG(_kern, KERN_USRSTACK, usrstack, CTLFLAG_RD, &usrstack, 0, "");
84 
85 u_long ps_arg_cache_limit = PAGE_SIZE / 16;
86 SYSCTL_LONG(_kern, OID_AUTO, ps_arg_cache_limit, CTLFLAG_RW,
87     &ps_arg_cache_limit, 0, "");
88 
89 int ps_argsopen = 1;
90 SYSCTL_INT(_kern, OID_AUTO, ps_argsopen, CTLFLAG_RW, &ps_argsopen, 0, "");
91 
92 void print_execve_args(struct image_args *args);
93 int debug_execve_args = 0;
94 SYSCTL_INT(_kern, OID_AUTO, debug_execve_args, CTLFLAG_RW, &debug_execve_args,
95     0, "");
96 
97 /*
98  * stackgap_random specifies if the stackgap should have a random size added
99  * to it.  It must be a power of 2.  If non-zero, the stack gap will be
100  * calculated as: ALIGN(arc4random() & (stackgap_random - 1)).
101  */
102 static int stackgap_random = 1024;
103 static int
104 sysctl_kern_stackgap(SYSCTL_HANDLER_ARGS)
105 {
106 	int error, new_val;
107 	new_val = stackgap_random;
108 	error = sysctl_handle_int(oidp, &new_val, 0, req);
109 	if (error != 0 || req->newptr == NULL)
110 		return (error);
111 	if ((new_val < 0) || (new_val > 16 * PAGE_SIZE) || ! powerof2(new_val))
112 		return (EINVAL);
113 	stackgap_random = new_val;
114 
115 	return(0);
116 }
117 
118 SYSCTL_PROC(_kern, OID_AUTO, stackgap_random, CTLFLAG_RW|CTLTYPE_UINT,
119 	0, 0, sysctl_kern_stackgap, "IU", "Max random stack gap (power of 2)");
120 
121 void
122 print_execve_args(struct image_args *args)
123 {
124 	char *cp;
125 	int ndx;
126 
127 	cp = args->begin_argv;
128 	for (ndx = 0; ndx < args->argc; ndx++) {
129 		printf("\targv[%d]: %s\n", ndx, cp);
130 		while (*cp++ != '\0');
131 	}
132 	for (ndx = 0; ndx < args->envc; ndx++) {
133 		printf("\tenvv[%d]: %s\n", ndx, cp);
134 		while (*cp++ != '\0');
135 	}
136 }
137 
138 /*
139  * Each of the items is a pointer to a `const struct execsw', hence the
140  * double pointer here.
141  */
142 static const struct execsw **execsw;
143 
144 int
145 kern_execve(struct nlookupdata *nd, struct image_args *args)
146 {
147 	struct thread *td = curthread;
148 	struct proc *p = td->td_proc;
149 	register_t *stack_base;
150 	int error, len, i;
151 	struct image_params image_params, *imgp;
152 	struct vattr attr;
153 	int (*img_first) (struct image_params *);
154 
155 	if (debug_execve_args) {
156 		printf("%s()\n", __func__);
157 		print_execve_args(args);
158 	}
159 
160 	KKASSERT(p);
161 	imgp = &image_params;
162 
163 	/*
164 	 * Lock the process and set the P_INEXEC flag to indicate that
165 	 * it should be left alone until we're done here.  This is
166 	 * necessary to avoid race conditions - e.g. in ptrace() -
167 	 * that might allow a local user to illicitly obtain elevated
168 	 * privileges.
169 	 */
170 	p->p_flag |= P_INEXEC;
171 
172 	/*
173 	 * Initialize part of the common data
174 	 */
175 	imgp->proc = p;
176 	imgp->args = args;
177 	imgp->attr = &attr;
178 	imgp->entry_addr = 0;
179 	imgp->resident = 0;
180 	imgp->vmspace_destroyed = 0;
181 	imgp->interpreted = 0;
182 	imgp->interpreter_name[0] = 0;
183 	imgp->auxargs = NULL;
184 	imgp->vp = NULL;
185 	imgp->firstpage = NULL;
186 	imgp->ps_strings = 0;
187 	imgp->image_header = NULL;
188 
189 interpret:
190 
191 	/*
192 	 * Translate the file name to a vnode.  Unlock the cache entry to
193 	 * improve parallelism for programs exec'd in parallel.
194 	 */
195 	if ((error = nlookup(nd)) != 0)
196 		goto exec_fail;
197 	error = cache_vget(nd->nl_ncp, nd->nl_cred, LK_EXCLUSIVE, &imgp->vp);
198 	KKASSERT(nd->nl_flags & NLC_NCPISLOCKED);
199 	nd->nl_flags &= ~NLC_NCPISLOCKED;
200 	cache_unlock(nd->nl_ncp);
201 	if (error)
202 		goto exec_fail;
203 
204 	/*
205 	 * Check file permissions (also 'opens' file)
206 	 */
207 	error = exec_check_permissions(imgp);
208 	if (error) {
209 		VOP_UNLOCK(imgp->vp, 0, td);
210 		goto exec_fail_dealloc;
211 	}
212 
213 	error = exec_map_first_page(imgp);
214 	VOP_UNLOCK(imgp->vp, 0, td);
215 	if (error)
216 		goto exec_fail_dealloc;
217 
218 	if (debug_execve_args && imgp->interpreted) {
219 		printf("    target is interpreted -- recursive pass\n");
220 		printf("    interpreter: %s\n", imgp->interpreter_name);
221 		print_execve_args(args);
222 	}
223 
224 	/*
225 	 *	If the current process has a special image activator it
226 	 *	wants to try first, call it.   For example, emulating shell
227 	 *	scripts differently.
228 	 */
229 	error = -1;
230 	if ((img_first = imgp->proc->p_sysent->sv_imgact_try) != NULL)
231 		error = img_first(imgp);
232 
233 	/*
234 	 *	If the vnode has a registered vmspace, exec the vmspace
235 	 */
236 	if (error == -1 && imgp->vp->v_resident) {
237 		error = exec_resident_imgact(imgp);
238 	}
239 
240 	/*
241 	 *	Loop through the list of image activators, calling each one.
242 	 *	An activator returns -1 if there is no match, 0 on success,
243 	 *	and an error otherwise.
244 	 */
245 	for (i = 0; error == -1 && execsw[i]; ++i) {
246 		if (execsw[i]->ex_imgact == NULL ||
247 		    execsw[i]->ex_imgact == img_first) {
248 			continue;
249 		}
250 		error = (*execsw[i]->ex_imgact)(imgp);
251 	}
252 
253 	if (error) {
254 		if (error == -1)
255 			error = ENOEXEC;
256 		goto exec_fail_dealloc;
257 	}
258 
259 	/*
260 	 * Special interpreter operation, cleanup and loop up to try to
261 	 * activate the interpreter.
262 	 */
263 	if (imgp->interpreted) {
264 		exec_unmap_first_page(imgp);
265 		nlookup_done(nd);
266 		vrele(imgp->vp);
267 		imgp->vp = NULL;
268 		error = nlookup_init(nd, imgp->interpreter_name, UIO_SYSSPACE,
269 					NLC_FOLLOW);
270 		if (error)
271 			goto exec_fail;
272 		goto interpret;
273 	}
274 
275 	/*
276 	 * Copy out strings (args and env) and initialize stack base
277 	 */
278 	stack_base = exec_copyout_strings(imgp);
279 	p->p_vmspace->vm_minsaddr = (char *)stack_base;
280 
281 	/*
282 	 * If custom stack fixup routine present for this process
283 	 * let it do the stack setup.  If we are running a resident
284 	 * image there is no auxinfo or other image activator context
285 	 * so don't try to add fixups to the stack.
286 	 *
287 	 * Else stuff argument count as first item on stack
288 	 */
289 	if (p->p_sysent->sv_fixup && imgp->resident == 0)
290 		(*p->p_sysent->sv_fixup)(&stack_base, imgp);
291 	else
292 		suword(--stack_base, imgp->args->argc);
293 
294 	/*
295 	 * For security and other reasons, the file descriptor table cannot
296 	 * be shared after an exec.
297 	 */
298 	if (p->p_fd->fd_refcnt > 1) {
299 		struct filedesc *tmp;
300 
301 		tmp = fdcopy(p);
302 		fdfree(p);
303 		p->p_fd = tmp;
304 	}
305 
306 	/*
307 	 * For security and other reasons, signal handlers cannot
308 	 * be shared after an exec. The new proces gets a copy of the old
309 	 * handlers. In execsigs(), the new process will have its signals
310 	 * reset.
311 	 */
312 	if (p->p_procsig->ps_refcnt > 1) {
313 		struct procsig *newprocsig;
314 
315 		MALLOC(newprocsig, struct procsig *, sizeof(struct procsig),
316 		       M_SUBPROC, M_WAITOK);
317 		bcopy(p->p_procsig, newprocsig, sizeof(*newprocsig));
318 		p->p_procsig->ps_refcnt--;
319 		p->p_procsig = newprocsig;
320 		p->p_procsig->ps_refcnt = 1;
321 		if (p->p_sigacts == &p->p_addr->u_sigacts)
322 			panic("shared procsig but private sigacts?");
323 
324 		p->p_addr->u_sigacts = *p->p_sigacts;
325 		p->p_sigacts = &p->p_addr->u_sigacts;
326 	}
327 
328 	/* Stop profiling */
329 	stopprofclock(p);
330 
331 	/* close files on exec */
332 	fdcloseexec(p);
333 
334 	/* reset caught signals */
335 	execsigs(p);
336 
337 	/* name this process - nameiexec(p, ndp) */
338 	len = min(nd->nl_ncp->nc_nlen, MAXCOMLEN);
339 	bcopy(nd->nl_ncp->nc_name, p->p_comm, len);
340 	p->p_comm[len] = 0;
341 
342 	/*
343 	 * mark as execed, wakeup the process that vforked (if any) and tell
344 	 * it that it now has its own resources back
345 	 */
346 	p->p_flag |= P_EXEC;
347 	if (p->p_pptr && (p->p_flag & P_PPWAIT)) {
348 		p->p_flag &= ~P_PPWAIT;
349 		wakeup((caddr_t)p->p_pptr);
350 	}
351 
352 	/*
353 	 * Implement image setuid/setgid.
354 	 *
355 	 * Don't honor setuid/setgid if the filesystem prohibits it or if
356 	 * the process is being traced.
357 	 */
358 	if ((((attr.va_mode & VSUID) && p->p_ucred->cr_uid != attr.va_uid) ||
359 	     ((attr.va_mode & VSGID) && p->p_ucred->cr_gid != attr.va_gid)) &&
360 	    (imgp->vp->v_mount->mnt_flag & MNT_NOSUID) == 0 &&
361 	    (p->p_flag & P_TRACED) == 0) {
362 		/*
363 		 * Turn off syscall tracing for set-id programs, except for
364 		 * root.  Record any set-id flags first to make sure that
365 		 * we do not regain any tracing during a possible block.
366 		 */
367 		setsugid();
368 		if (p->p_tracep && suser(td)) {
369 			struct vnode *vtmp;
370 
371 			if ((vtmp = p->p_tracep) != NULL) {
372 				p->p_tracep = NULL;
373 				p->p_traceflag = 0;
374 				vrele(vtmp);
375 			}
376 		}
377 		/* Close any file descriptors 0..2 that reference procfs */
378 		setugidsafety(p);
379 		/* Make sure file descriptors 0..2 are in use. */
380 		error = fdcheckstd(p);
381 		if (error != 0)
382 			goto exec_fail_dealloc;
383 		/*
384 		 * Set the new credentials.
385 		 */
386 		cratom(&p->p_ucred);
387 		if (attr.va_mode & VSUID)
388 			change_euid(attr.va_uid);
389 		if (attr.va_mode & VSGID)
390 			p->p_ucred->cr_gid = attr.va_gid;
391 
392 		/*
393 		 * Clear local varsym variables
394 		 */
395 		varsymset_clean(&p->p_varsymset);
396 	} else {
397 		if (p->p_ucred->cr_uid == p->p_ucred->cr_ruid &&
398 		    p->p_ucred->cr_gid == p->p_ucred->cr_rgid)
399 			p->p_flag &= ~P_SUGID;
400 	}
401 
402 	/*
403 	 * Implement correct POSIX saved-id behavior.
404 	 */
405 	if (p->p_ucred->cr_svuid != p->p_ucred->cr_uid ||
406 	    p->p_ucred->cr_svgid != p->p_ucred->cr_gid) {
407 		cratom(&p->p_ucred);
408 		p->p_ucred->cr_svuid = p->p_ucred->cr_uid;
409 		p->p_ucred->cr_svgid = p->p_ucred->cr_gid;
410 	}
411 
412 	/*
413 	 * Store the vp for use in procfs
414 	 */
415 	if (p->p_textvp)		/* release old reference */
416 		vrele(p->p_textvp);
417 	p->p_textvp = imgp->vp;
418 	vref(p->p_textvp);
419 
420         /*
421          * Notify others that we exec'd, and clear the P_INEXEC flag
422          * as we're now a bona fide freshly-execed process.
423          */
424 	KNOTE(&p->p_klist, NOTE_EXEC);
425 	p->p_flag &= ~P_INEXEC;
426 
427 	/*
428 	 * If tracing the process, trap to debugger so breakpoints
429 	 * 	can be set before the program executes.
430 	 */
431 	STOPEVENT(p, S_EXEC, 0);
432 
433 	if (p->p_flag & P_TRACED)
434 		psignal(p, SIGTRAP);
435 
436 	/* clear "fork but no exec" flag, as we _are_ execing */
437 	p->p_acflag &= ~AFORK;
438 
439 	/* Set values passed into the program in registers. */
440 	setregs(p, imgp->entry_addr, (u_long)(uintptr_t)stack_base,
441 	    imgp->ps_strings);
442 
443 	/* Free any previous argument cache */
444 	if (p->p_args && --p->p_args->ar_ref == 0)
445 		FREE(p->p_args, M_PARGS);
446 	p->p_args = NULL;
447 
448 	/* Cache arguments if they fit inside our allowance */
449 	i = imgp->args->begin_envv - imgp->args->begin_argv;
450 	if (ps_arg_cache_limit >= i + sizeof(struct pargs)) {
451 		MALLOC(p->p_args, struct pargs *, sizeof(struct pargs) + i,
452 		    M_PARGS, M_WAITOK);
453 		p->p_args->ar_ref = 1;
454 		p->p_args->ar_length = i;
455 		bcopy(imgp->args->begin_argv, p->p_args->ar_args, i);
456 	}
457 
458 exec_fail_dealloc:
459 
460 	/*
461 	 * free various allocated resources
462 	 */
463 	if (imgp->firstpage)
464 		exec_unmap_first_page(imgp);
465 
466 	if (imgp->vp) {
467 		vrele(imgp->vp);
468 		imgp->vp = NULL;
469 	}
470 
471 	if (error == 0) {
472 		++mycpu->gd_cnt.v_exec;
473 		return (0);
474 	}
475 
476 exec_fail:
477 	/* we're done here, clear P_INEXEC */
478 	p->p_flag &= ~P_INEXEC;
479 	if (imgp->vmspace_destroyed) {
480 		/* sorry, no more process anymore. exit gracefully */
481 		exit1(W_EXITCODE(0, SIGABRT));
482 		/* NOT REACHED */
483 		return(0);
484 	} else {
485 		return(error);
486 	}
487 }
488 
489 /*
490  * execve() system call.
491  */
492 int
493 execve(struct execve_args *uap)
494 {
495 	struct nlookupdata nd;
496 	struct image_args args;
497 	int error;
498 
499 	error = nlookup_init(&nd, uap->fname, UIO_USERSPACE, NLC_FOLLOW);
500 	if (error == 0) {
501 		error = exec_copyin_args(&args, uap->fname, PATH_USERSPACE,
502 					uap->argv, uap->envv);
503 	}
504 	if (error == 0)
505 		error = kern_execve(&nd, &args);
506 	nlookup_done(&nd);
507 	exec_free_args(&args);
508 
509 	/*
510 	 * The syscall result is returned in registers to the new program.
511 	 * Linux will register %edx as an atexit function and we must be
512 	 * sure to set it to 0.  XXX
513 	 */
514 	if (error == 0)
515 		uap->sysmsg_result64 = 0;
516 
517 	return (error);
518 }
519 
520 int
521 exec_map_first_page(struct image_params *imgp)
522 {
523 	int rv, i;
524 	int initial_pagein;
525 	vm_page_t ma[VM_INITIAL_PAGEIN];
526 	vm_page_t m;
527 	vm_object_t object;
528 	int error;
529 
530 	if (imgp->firstpage)
531 		exec_unmap_first_page(imgp);
532 
533 	/*
534 	 * XXX the callers should really use vn_open so we don't have to
535 	 * do this junk.
536 	 */
537 	if ((error = VOP_GETVOBJECT(imgp->vp, &object)) != 0) {
538 		if (vn_canvmio(imgp->vp) == TRUE) {
539 			error = vfs_object_create(imgp->vp, curthread);
540 			if (error == 0)
541 				error = VOP_GETVOBJECT(imgp->vp, &object);
542 		}
543 	}
544 	if (error)
545 		return (EIO);
546 
547 	/*
548 	 * We shouldn't need protection for vm_page_grab() but we certainly
549 	 * need it for the lookup loop below (lookup/busy race), since
550 	 * an interrupt can unbusy and free the page before our busy check.
551 	 */
552 	crit_enter();
553 	m = vm_page_grab(object, 0, VM_ALLOC_NORMAL | VM_ALLOC_RETRY);
554 
555 	if ((m->valid & VM_PAGE_BITS_ALL) != VM_PAGE_BITS_ALL) {
556 		ma[0] = m;
557 		initial_pagein = VM_INITIAL_PAGEIN;
558 		if (initial_pagein > object->size)
559 			initial_pagein = object->size;
560 		for (i = 1; i < initial_pagein; i++) {
561 			if ((m = vm_page_lookup(object, i)) != NULL) {
562 				if ((m->flags & PG_BUSY) || m->busy)
563 					break;
564 				if (m->valid)
565 					break;
566 				vm_page_busy(m);
567 			} else {
568 				m = vm_page_alloc(object, i, VM_ALLOC_NORMAL);
569 				if (m == NULL)
570 					break;
571 			}
572 			ma[i] = m;
573 		}
574 		initial_pagein = i;
575 
576 		/*
577 		 * get_pages unbusies all the requested pages except the
578 		 * primary page (at index 0 in this case).
579 		 */
580 		rv = vm_pager_get_pages(object, ma, initial_pagein, 0);
581 		m = vm_page_lookup(object, 0);
582 
583 		if (rv != VM_PAGER_OK || m == NULL || m->valid == 0) {
584 			if (m) {
585 				vm_page_protect(m, VM_PROT_NONE);
586 				vm_page_free(m);
587 			}
588 			crit_exit();
589 			return EIO;
590 		}
591 	}
592 	vm_page_hold(m);
593 	vm_page_wakeup(m);	/* unbusy the page */
594 	crit_exit();
595 
596 	imgp->firstpage = sf_buf_alloc(m, SFB_CPUPRIVATE);
597 	imgp->image_header = (void *)sf_buf_kva(imgp->firstpage);
598 
599 	return 0;
600 }
601 
602 void
603 exec_unmap_first_page(struct image_params *imgp)
604 {
605 	vm_page_t m;
606 
607 	crit_enter();
608 	if (imgp->firstpage != NULL) {
609 		m = sf_buf_page(imgp->firstpage);
610 		sf_buf_free(imgp->firstpage);
611 		imgp->firstpage = NULL;
612 		imgp->image_header = NULL;
613 		vm_page_unhold(m);
614 	}
615 	crit_exit();
616 }
617 
618 /*
619  * Destroy old address space, and allocate a new stack
620  *	The new stack is only SGROWSIZ large because it is grown
621  *	automatically in trap.c.
622  */
623 int
624 exec_new_vmspace(struct image_params *imgp, struct vmspace *vmcopy)
625 {
626 	int error;
627 	struct vmspace *vmspace = imgp->proc->p_vmspace;
628 	vm_offset_t stack_addr = USRSTACK - maxssiz;
629 	vm_map_t map;
630 
631 	imgp->vmspace_destroyed = 1;
632 
633 	/*
634 	 * Prevent a pending AIO from modifying the new address space.
635 	 */
636 	aio_proc_rundown(imgp->proc);
637 
638 	/*
639 	 * Blow away entire process VM, if address space not shared,
640 	 * otherwise, create a new VM space so that other threads are
641 	 * not disrupted.  If we are execing a resident vmspace we
642 	 * create a duplicate of it and remap the stack.
643 	 *
644 	 * The exitingcnt test is not strictly necessary but has been
645 	 * included for code sanity (to make the code more deterministic).
646 	 */
647 	map = &vmspace->vm_map;
648 	if (vmcopy) {
649 		vmspace_exec(imgp->proc, vmcopy);
650 		vmspace = imgp->proc->p_vmspace;
651 		pmap_remove_pages(vmspace_pmap(vmspace), stack_addr, USRSTACK);
652 		map = &vmspace->vm_map;
653 	} else if (vmspace->vm_refcnt == 1 && vmspace->vm_exitingcnt == 0) {
654 		shmexit(vmspace);
655 		if (vmspace->vm_upcalls)
656 			upc_release(vmspace, imgp->proc);
657 		pmap_remove_pages(vmspace_pmap(vmspace), 0, VM_MAXUSER_ADDRESS);
658 		vm_map_remove(map, 0, VM_MAXUSER_ADDRESS);
659 	} else {
660 		vmspace_exec(imgp->proc, NULL);
661 		vmspace = imgp->proc->p_vmspace;
662 		map = &vmspace->vm_map;
663 	}
664 
665 	/* Allocate a new stack */
666 	error = vm_map_stack(&vmspace->vm_map, stack_addr, (vm_size_t)maxssiz,
667 	    VM_PROT_ALL, VM_PROT_ALL, 0);
668 	if (error)
669 		return (error);
670 
671 	/* vm_ssize and vm_maxsaddr are somewhat antiquated concepts in the
672 	 * VM_STACK case, but they are still used to monitor the size of the
673 	 * process stack so we can check the stack rlimit.
674 	 */
675 	vmspace->vm_ssize = sgrowsiz >> PAGE_SHIFT;
676 	vmspace->vm_maxsaddr = (char *)USRSTACK - maxssiz;
677 
678 	return(0);
679 }
680 
681 /*
682  * Copy out argument and environment strings from the old process
683  *	address space into the temporary string buffer.
684  */
685 int
686 exec_copyin_args(struct image_args *args, char *fname,
687 		enum exec_path_segflg segflg, char **argv, char **envv)
688 {
689 	char	*argp, *envp;
690 	int	error = 0;
691 	size_t	length;
692 
693 	bzero(args, sizeof(*args));
694 	args->buf = (char *) kmem_alloc_wait(exec_map, PATH_MAX + ARG_MAX);
695 	if (args->buf == NULL)
696 		return (ENOMEM);
697 	args->begin_argv = args->buf;
698 	args->endp = args->begin_argv;
699 	args->space = ARG_MAX;
700 
701 	args->fname = args->buf + ARG_MAX;
702 
703 	/*
704 	 * Copy the file name.
705 	 */
706 	if (segflg == PATH_SYSSPACE) {
707 		error = copystr(fname, args->fname, PATH_MAX, &length);
708 	} else if (segflg == PATH_USERSPACE) {
709 		error = copyinstr(fname, args->fname, PATH_MAX, &length);
710 	}
711 
712 	/*
713 	 * Extract argument strings.  argv may not be NULL.  The argv
714 	 * array is terminated by a NULL entry.  We special-case the
715 	 * situation where argv[0] is NULL by passing { filename, NULL }
716 	 * to the new program to guarentee that the interpreter knows what
717 	 * file to open in case we exec an interpreted file.   Note that
718 	 * a NULL argv[0] terminates the argv[] array.
719 	 *
720 	 * XXX the special-casing of argv[0] is historical and needs to be
721 	 * revisited.
722 	 */
723 	if (argv == NULL)
724 		error = EFAULT;
725 	if (error == 0) {
726 		while ((argp = (caddr_t)(intptr_t)fuword(argv++)) != NULL) {
727 			if (argp == (caddr_t)-1) {
728 				error = EFAULT;
729 				break;
730 			}
731 			error = copyinstr(argp, args->endp,
732 					    args->space, &length);
733 			if (error) {
734 				if (error == ENAMETOOLONG)
735 					error = E2BIG;
736 				break;
737 			}
738 			args->space -= length;
739 			args->endp += length;
740 			args->argc++;
741 		}
742 		if (args->argc == 0 && error == 0) {
743 			length = strlen(args->fname) + 1;
744 			if (length > args->space) {
745 				error = E2BIG;
746 			} else {
747 				bcopy(args->fname, args->endp, length);
748 				args->space -= length;
749 				args->endp += length;
750 				args->argc++;
751 			}
752 		}
753 	}
754 
755 	args->begin_envv = args->endp;
756 
757 	/*
758 	 * extract environment strings.  envv may be NULL.
759 	 */
760 	if (envv && error == 0) {
761 		while ((envp = (caddr_t) (intptr_t) fuword(envv++))) {
762 			if (envp == (caddr_t) -1) {
763 				error = EFAULT;
764 				break;
765 			}
766 			error = copyinstr(envp, args->endp, args->space,
767 			    &length);
768 			if (error) {
769 				if (error == ENAMETOOLONG)
770 					error = E2BIG;
771 				break;
772 			}
773 			args->space -= length;
774 			args->endp += length;
775 			args->envc++;
776 		}
777 	}
778 	return (error);
779 }
780 
781 void
782 exec_free_args(struct image_args *args)
783 {
784 	if (args->buf) {
785 		kmem_free_wakeup(exec_map,
786 				(vm_offset_t)args->buf, PATH_MAX + ARG_MAX);
787 		args->buf = NULL;
788 	}
789 }
790 
791 /*
792  * Copy strings out to the new process address space, constructing
793  *	new arg and env vector tables. Return a pointer to the base
794  *	so that it can be used as the initial stack pointer.
795  */
796 register_t *
797 exec_copyout_strings(struct image_params *imgp)
798 {
799 	int argc, envc, sgap;
800 	char **vectp;
801 	char *stringp, *destp;
802 	register_t *stack_base;
803 	struct ps_strings *arginfo;
804 	int szsigcode;
805 
806 	/*
807 	 * Calculate string base and vector table pointers.
808 	 * Also deal with signal trampoline code for this exec type.
809 	 */
810 	arginfo = (struct ps_strings *)PS_STRINGS;
811 	szsigcode = *(imgp->proc->p_sysent->sv_szsigcode);
812 	if (stackgap_random != 0)
813 		sgap = ALIGN(arc4random() & (stackgap_random - 1));
814 	else
815 		sgap = 0;
816 	destp =	(caddr_t)arginfo - szsigcode - SPARE_USRSPACE - sgap -
817 	    roundup((ARG_MAX - imgp->args->space), sizeof(char *));
818 
819 	/*
820 	 * install sigcode
821 	 */
822 	if (szsigcode)
823 		copyout(imgp->proc->p_sysent->sv_sigcode,
824 		    ((caddr_t)arginfo - szsigcode), szsigcode);
825 
826 	/*
827 	 * If we have a valid auxargs ptr, prepare some room
828 	 * on the stack.
829 	 *
830 	 * The '+ 2' is for the null pointers at the end of each of the
831 	 * arg and env vector sets, and 'AT_COUNT*2' is room for the
832 	 * ELF Auxargs data.
833 	 */
834 	if (imgp->auxargs) {
835 		vectp = (char **)(destp - (imgp->args->argc +
836 			imgp->args->envc + 2 + AT_COUNT * 2) * sizeof(char*));
837 	} else {
838 		vectp = (char **)(destp - (imgp->args->argc +
839 			imgp->args->envc + 2) * sizeof(char*));
840 	}
841 
842 	/*
843 	 * NOTE: don't bother aligning the stack here for GCC 2.x, it will
844 	 * be done in crt1.o.  Note that GCC 3.x aligns the stack in main.
845 	 */
846 
847 	/*
848 	 * vectp also becomes our initial stack base
849 	 */
850 	stack_base = (register_t *)vectp;
851 
852 	stringp = imgp->args->begin_argv;
853 	argc = imgp->args->argc;
854 	envc = imgp->args->envc;
855 
856 	/*
857 	 * Copy out strings - arguments and environment.
858 	 */
859 	copyout(stringp, destp, ARG_MAX - imgp->args->space);
860 
861 	/*
862 	 * Fill in "ps_strings" struct for ps, w, etc.
863 	 */
864 	suword(&arginfo->ps_argvstr, (long)(intptr_t)vectp);
865 	suword(&arginfo->ps_nargvstr, argc);
866 
867 	/*
868 	 * Fill in argument portion of vector table.
869 	 */
870 	for (; argc > 0; --argc) {
871 		suword(vectp++, (long)(intptr_t)destp);
872 		while (*stringp++ != 0)
873 			destp++;
874 		destp++;
875 	}
876 
877 	/* a null vector table pointer separates the argp's from the envp's */
878 	suword(vectp++, 0);
879 
880 	suword(&arginfo->ps_envstr, (long)(intptr_t)vectp);
881 	suword(&arginfo->ps_nenvstr, envc);
882 
883 	/*
884 	 * Fill in environment portion of vector table.
885 	 */
886 	for (; envc > 0; --envc) {
887 		suword(vectp++, (long)(intptr_t)destp);
888 		while (*stringp++ != 0)
889 			destp++;
890 		destp++;
891 	}
892 
893 	/* end of vector table is a null pointer */
894 	suword(vectp, 0);
895 
896 	return (stack_base);
897 }
898 
899 /*
900  * Check permissions of file to execute.
901  *	Return 0 for success or error code on failure.
902  */
903 int
904 exec_check_permissions(struct image_params *imgp)
905 {
906 	struct proc *p = imgp->proc;
907 	struct vnode *vp = imgp->vp;
908 	struct vattr *attr = imgp->attr;
909 	struct thread *td = p->p_thread;
910 	int error;
911 
912 	/* Get file attributes */
913 	error = VOP_GETATTR(vp, attr, td);
914 	if (error)
915 		return (error);
916 
917 	/*
918 	 * 1) Check if file execution is disabled for the filesystem that this
919 	 *	file resides on.
920 	 * 2) Insure that at least one execute bit is on - otherwise root
921 	 *	will always succeed, and we don't want to happen unless the
922 	 *	file really is executable.
923 	 * 3) Insure that the file is a regular file.
924 	 */
925 	if ((vp->v_mount->mnt_flag & MNT_NOEXEC) ||
926 	    ((attr->va_mode & 0111) == 0) ||
927 	    (attr->va_type != VREG)) {
928 		return (EACCES);
929 	}
930 
931 	/*
932 	 * Zero length files can't be exec'd
933 	 */
934 	if (attr->va_size == 0)
935 		return (ENOEXEC);
936 
937 	/*
938 	 *  Check for execute permission to file based on current credentials.
939 	 */
940 	error = VOP_ACCESS(vp, VEXEC, p->p_ucred, td);
941 	if (error)
942 		return (error);
943 
944 	/*
945 	 * Check number of open-for-writes on the file and deny execution
946 	 * if there are any.
947 	 */
948 	if (vp->v_writecount)
949 		return (ETXTBSY);
950 
951 	/*
952 	 * Call filesystem specific open routine (which does nothing in the
953 	 * general case).
954 	 */
955 	error = VOP_OPEN(vp, FREAD, p->p_ucred, NULL, td);
956 	if (error)
957 		return (error);
958 
959 	return (0);
960 }
961 
962 /*
963  * Exec handler registration
964  */
965 int
966 exec_register(const struct execsw *execsw_arg)
967 {
968 	const struct execsw **es, **xs, **newexecsw;
969 	int count = 2;	/* New slot and trailing NULL */
970 
971 	if (execsw)
972 		for (es = execsw; *es; es++)
973 			count++;
974 	newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
975 	if (newexecsw == NULL)
976 		return ENOMEM;
977 	xs = newexecsw;
978 	if (execsw)
979 		for (es = execsw; *es; es++)
980 			*xs++ = *es;
981 	*xs++ = execsw_arg;
982 	*xs = NULL;
983 	if (execsw)
984 		free(execsw, M_TEMP);
985 	execsw = newexecsw;
986 	return 0;
987 }
988 
989 int
990 exec_unregister(const struct execsw *execsw_arg)
991 {
992 	const struct execsw **es, **xs, **newexecsw;
993 	int count = 1;
994 
995 	if (execsw == NULL)
996 		panic("unregister with no handlers left?");
997 
998 	for (es = execsw; *es; es++) {
999 		if (*es == execsw_arg)
1000 			break;
1001 	}
1002 	if (*es == NULL)
1003 		return ENOENT;
1004 	for (es = execsw; *es; es++)
1005 		if (*es != execsw_arg)
1006 			count++;
1007 	newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
1008 	if (newexecsw == NULL)
1009 		return ENOMEM;
1010 	xs = newexecsw;
1011 	for (es = execsw; *es; es++)
1012 		if (*es != execsw_arg)
1013 			*xs++ = *es;
1014 	*xs = NULL;
1015 	if (execsw)
1016 		free(execsw, M_TEMP);
1017 	execsw = newexecsw;
1018 	return 0;
1019 }
1020