xref: /freebsd/sys/kern/kern_exec.c (revision 3ff369fed2a08f32dda232c10470b949bef9489f)
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$
27  */
28 
29 #include <sys/param.h>
30 #include <sys/systm.h>
31 #include <sys/lock.h>
32 #include <sys/mutex.h>
33 #include <sys/sysproto.h>
34 #include <sys/signalvar.h>
35 #include <sys/kernel.h>
36 #include <sys/mount.h>
37 #include <sys/filedesc.h>
38 #include <sys/fcntl.h>
39 #include <sys/acct.h>
40 #include <sys/exec.h>
41 #include <sys/imgact.h>
42 #include <sys/imgact_elf.h>
43 #include <sys/wait.h>
44 #include <sys/malloc.h>
45 #include <sys/proc.h>
46 #include <sys/pioctl.h>
47 #include <sys/namei.h>
48 #include <sys/sysent.h>
49 #include <sys/shm.h>
50 #include <sys/sysctl.h>
51 #include <sys/user.h>
52 #include <sys/vnode.h>
53 
54 #include <vm/vm.h>
55 #include <vm/vm_param.h>
56 #include <vm/pmap.h>
57 #include <vm/vm_page.h>
58 #include <vm/vm_map.h>
59 #include <vm/vm_kern.h>
60 #include <vm/vm_extern.h>
61 #include <vm/vm_object.h>
62 #include <vm/vm_pager.h>
63 
64 #include <machine/reg.h>
65 
66 MALLOC_DEFINE(M_PARGS, "proc-args", "Process arguments");
67 
68 static MALLOC_DEFINE(M_ATEXEC, "atexec", "atexec callback");
69 
70 /*
71  * callout list for things to do at exec time
72  */
73 struct execlist {
74 	execlist_fn function;
75 	TAILQ_ENTRY(execlist) next;
76 };
77 
78 TAILQ_HEAD(exec_list_head, execlist);
79 static struct exec_list_head exec_list = TAILQ_HEAD_INITIALIZER(exec_list);
80 
81 static register_t *exec_copyout_strings(struct image_params *);
82 
83 /* XXX This should be vm_size_t. */
84 static u_long ps_strings = PS_STRINGS;
85 SYSCTL_ULONG(_kern, KERN_PS_STRINGS, ps_strings, CTLFLAG_RD, &ps_strings, 0, "");
86 
87 /* XXX This should be vm_size_t. */
88 static u_long usrstack = USRSTACK;
89 SYSCTL_ULONG(_kern, KERN_USRSTACK, usrstack, CTLFLAG_RD, &usrstack, 0, "");
90 
91 u_long ps_arg_cache_limit = PAGE_SIZE / 16;
92 SYSCTL_ULONG(_kern, OID_AUTO, ps_arg_cache_limit, CTLFLAG_RW,
93     &ps_arg_cache_limit, 0, "");
94 
95 int ps_argsopen = 1;
96 SYSCTL_INT(_kern, OID_AUTO, ps_argsopen, CTLFLAG_RW, &ps_argsopen, 0, "");
97 
98 #ifdef __ia64__
99 /* XXX HACK */
100 static int regstkpages = 256;
101 SYSCTL_INT(_machdep, OID_AUTO, regstkpages, CTLFLAG_RW, &regstkpages, 0, "");
102 #endif
103 
104 /*
105  * Each of the items is a pointer to a `const struct execsw', hence the
106  * double pointer here.
107  */
108 static const struct execsw **execsw;
109 
110 #ifndef _SYS_SYSPROTO_H_
111 struct execve_args {
112         char    *fname;
113         char    **argv;
114         char    **envv;
115 };
116 #endif
117 
118 /*
119  * execve() system call.
120  *
121  * MPSAFE
122  */
123 int
124 execve(td, uap)
125 	struct thread *td;
126 	register struct execve_args *uap;
127 {
128 	struct proc *p = td->td_proc;
129 	struct nameidata nd, *ndp;
130 	struct ucred *newcred = NULL, *oldcred;
131 	struct uidinfo *euip;
132 	register_t *stack_base;
133 	int error, len, i;
134 	struct image_params image_params, *imgp;
135 	struct vattr attr;
136 	int (*img_first)(struct image_params *);
137 	struct pargs *oldargs, *newargs = NULL;
138 	struct procsig *oldprocsig, *newprocsig;
139 #ifdef KTRACE
140 	struct vnode *tracevp = NULL;
141 #endif
142 	struct vnode *textvp = NULL;
143 
144 	imgp = &image_params;
145 
146 	/*
147 	 * Lock the process and set the P_INEXEC flag to indicate that
148 	 * it should be left alone until we're done here.  This is
149 	 * necessary to avoid race conditions - e.g. in ptrace() -
150 	 * that might allow a local user to illicitly obtain elevated
151 	 * privileges.
152 	 */
153 	mtx_lock(&Giant);
154 	PROC_LOCK(p);
155 	KASSERT((p->p_flag & P_INEXEC) == 0,
156 	    ("%s(): process already has P_INEXEC flag", __func__));
157 	p->p_flag |= P_INEXEC;
158 	PROC_UNLOCK(p);
159 
160 /* XXXKSE */
161 /* !!!!!!!! we need abort all the other threads of this process before we */
162 /* proceed beyond his point! */
163 
164 	/*
165 	 * Initialize part of the common data
166 	 */
167 	imgp->proc = p;
168 	imgp->uap = uap;
169 	imgp->attr = &attr;
170 	imgp->argc = imgp->envc = 0;
171 	imgp->argv0 = NULL;
172 	imgp->entry_addr = 0;
173 	imgp->vmspace_destroyed = 0;
174 	imgp->interpreted = 0;
175 	imgp->interpreter_name[0] = '\0';
176 	imgp->auxargs = NULL;
177 	imgp->vp = NULL;
178 	imgp->firstpage = NULL;
179 	imgp->ps_strings = 0;
180 	imgp->auxarg_size = 0;
181 
182 	/*
183 	 * Allocate temporary demand zeroed space for argument and
184 	 *	environment strings
185 	 */
186 	imgp->stringbase = (char *)kmem_alloc_wait(exec_map, ARG_MAX + PAGE_SIZE);
187 	if (imgp->stringbase == NULL) {
188 		error = ENOMEM;
189 		goto exec_fail;
190 	}
191 	imgp->stringp = imgp->stringbase;
192 	imgp->stringspace = ARG_MAX;
193 	imgp->image_header = imgp->stringbase + ARG_MAX;
194 
195 	/*
196 	 * Translate the file name. namei() returns a vnode pointer
197 	 *	in ni_vp amoung other things.
198 	 */
199 	ndp = &nd;
200 	NDINIT(ndp, LOOKUP, LOCKLEAF | FOLLOW | SAVENAME,
201 	    UIO_USERSPACE, uap->fname, td);
202 
203 interpret:
204 
205 	error = namei(ndp);
206 	if (error) {
207 		kmem_free_wakeup(exec_map, (vm_offset_t)imgp->stringbase,
208 			ARG_MAX + PAGE_SIZE);
209 		goto exec_fail;
210 	}
211 
212 	imgp->vp = ndp->ni_vp;
213 	imgp->fname = uap->fname;
214 
215 	/*
216 	 * Check file permissions (also 'opens' file)
217 	 */
218 	error = exec_check_permissions(imgp);
219 	if (error) {
220 		VOP_UNLOCK(imgp->vp, 0, td);
221 		goto exec_fail_dealloc;
222 	}
223 
224 	error = exec_map_first_page(imgp);
225 	VOP_UNLOCK(imgp->vp, 0, td);
226 	if (error)
227 		goto exec_fail_dealloc;
228 
229 	/*
230 	 *	If the current process has a special image activator it
231 	 *	wants to try first, call it.   For example, emulating shell
232 	 *	scripts differently.
233 	 */
234 	error = -1;
235 	if ((img_first = imgp->proc->p_sysent->sv_imgact_try) != NULL)
236 		error = img_first(imgp);
237 
238 	/*
239 	 *	Loop through the list of image activators, calling each one.
240 	 *	An activator returns -1 if there is no match, 0 on success,
241 	 *	and an error otherwise.
242 	 */
243 	for (i = 0; error == -1 && execsw[i]; ++i) {
244 		if (execsw[i]->ex_imgact == NULL ||
245 		    execsw[i]->ex_imgact == img_first) {
246 			continue;
247 		}
248 		error = (*execsw[i]->ex_imgact)(imgp);
249 	}
250 
251 	if (error) {
252 		if (error == -1)
253 			error = ENOEXEC;
254 		goto exec_fail_dealloc;
255 	}
256 
257 	/*
258 	 * Special interpreter operation, cleanup and loop up to try to
259 	 * activate the interpreter.
260 	 */
261 	if (imgp->interpreted) {
262 		exec_unmap_first_page(imgp);
263 		/* free name buffer and old vnode */
264 		NDFREE(ndp, NDF_ONLY_PNBUF);
265 		vrele(ndp->ni_vp);
266 		/* set new name to that of the interpreter */
267 		NDINIT(ndp, LOOKUP, LOCKLEAF | FOLLOW | SAVENAME,
268 		    UIO_SYSSPACE, imgp->interpreter_name, td);
269 		goto interpret;
270 	}
271 
272 	/*
273 	 * Copy out strings (args and env) and initialize stack base
274 	 */
275 	stack_base = exec_copyout_strings(imgp);
276 	p->p_vmspace->vm_minsaddr = (char *)stack_base;
277 
278 	/*
279 	 * If custom stack fixup routine present for this process
280 	 * let it do the stack setup.
281 	 * Else stuff argument count as first item on stack
282 	 */
283 	if (p->p_sysent->sv_fixup)
284 		(*p->p_sysent->sv_fixup)(&stack_base, imgp);
285 	else
286 		suword(--stack_base, imgp->argc);
287 
288 	/*
289 	 * For security and other reasons, the file descriptor table cannot
290 	 * be shared after an exec.
291 	 */
292 	FILEDESC_LOCK(p->p_fd);
293 	if (p->p_fd->fd_refcnt > 1) {
294 		struct filedesc *tmp;
295 
296 		tmp = fdcopy(td);
297 		FILEDESC_UNLOCK(p->p_fd);
298 		fdfree(td);
299 		p->p_fd = tmp;
300 	} else
301 		FILEDESC_UNLOCK(p->p_fd);
302 
303 	/*
304 	 * Malloc things before we need locks.
305 	 */
306 	newcred = crget();
307 	euip = uifind(attr.va_uid);
308 	i = imgp->endargs - imgp->stringbase;
309 	if (ps_arg_cache_limit >= i + sizeof(struct pargs))
310 		newargs = pargs_alloc(i);
311 
312 	/* close files on exec */
313 	fdcloseexec(td);
314 
315 	/*
316 	 * For security and other reasons, signal handlers cannot
317 	 * be shared after an exec. The new process gets a copy of the old
318 	 * handlers. In execsigs(), the new process will have its signals
319 	 * reset.
320 	 */
321 	PROC_LOCK(p);
322 	mp_fixme("procsig needs a lock");
323 	if (p->p_procsig->ps_refcnt > 1) {
324 		oldprocsig = p->p_procsig;
325 		PROC_UNLOCK(p);
326 		MALLOC(newprocsig, struct procsig *, sizeof(struct procsig),
327 		    M_SUBPROC, M_WAITOK);
328 		bcopy(oldprocsig, newprocsig, sizeof(*newprocsig));
329 		newprocsig->ps_refcnt = 1;
330 		oldprocsig->ps_refcnt--;
331 		PROC_LOCK(p);
332 		p->p_procsig = newprocsig;
333 		if (p->p_sigacts == &p->p_uarea->u_sigacts)
334 			panic("shared procsig but private sigacts?");
335 
336 		p->p_uarea->u_sigacts = *p->p_sigacts;
337 		p->p_sigacts = &p->p_uarea->u_sigacts;
338 	}
339 	/* Stop profiling */
340 	stopprofclock(p);
341 
342 	/* reset caught signals */
343 	execsigs(p);
344 
345 	/* name this process - nameiexec(p, ndp) */
346 	len = min(ndp->ni_cnd.cn_namelen,MAXCOMLEN);
347 	bcopy(ndp->ni_cnd.cn_nameptr, p->p_comm, len);
348 	p->p_comm[len] = 0;
349 
350 	/*
351 	 * mark as execed, wakeup the process that vforked (if any) and tell
352 	 * it that it now has its own resources back
353 	 */
354 	p->p_flag |= P_EXEC;
355 	if (p->p_pptr && (p->p_flag & P_PPWAIT)) {
356 		p->p_flag &= ~P_PPWAIT;
357 		wakeup((caddr_t)p->p_pptr);
358 	}
359 
360 	/*
361 	 * Implement image setuid/setgid.
362 	 *
363 	 * Don't honor setuid/setgid if the filesystem prohibits it or if
364 	 * the process is being traced.
365 	 */
366 	oldcred = p->p_ucred;
367 	if ((((attr.va_mode & VSUID) && oldcred->cr_uid != attr.va_uid) ||
368 	     ((attr.va_mode & VSGID) && oldcred->cr_gid != attr.va_gid)) &&
369 	    (imgp->vp->v_mount->mnt_flag & MNT_NOSUID) == 0 &&
370 	    (p->p_flag & P_TRACED) == 0) {
371 		/*
372 		 * Turn off syscall tracing for set-id programs, except for
373 		 * root.  Record any set-id flags first to make sure that
374 		 * we do not regain any tracing during a possible block.
375 		 */
376 		setsugid(p);
377 #ifdef KTRACE
378 		if (p->p_tracep && suser_cred(oldcred, PRISON_ROOT)) {
379 			mtx_lock(&ktrace_mtx);
380 			p->p_traceflag = 0;
381 			tracevp = p->p_tracep;
382 			p->p_tracep = NULL;
383 			mtx_unlock(&ktrace_mtx);
384 		}
385 #endif
386 		/* Make sure file descriptors 0..2 are in use.  */
387 		error = fdcheckstd(td);
388 		if (error != 0)
389 			goto exec_fail_dealloc;
390 		/*
391 		 * Set the new credentials.
392 		 */
393 		crcopy(newcred, oldcred);
394 		if (attr.va_mode & VSUID)
395 			change_euid(newcred, euip);
396 		if (attr.va_mode & VSGID)
397 			change_egid(newcred, attr.va_gid);
398 		setugidsafety(td);
399 		/*
400 		 * Implement correct POSIX saved-id behavior.
401 		 */
402 		change_svuid(newcred, newcred->cr_uid);
403 		change_svgid(newcred, newcred->cr_gid);
404 		p->p_ucred = newcred;
405 		newcred = NULL;
406 	} else {
407 		if (oldcred->cr_uid == oldcred->cr_ruid &&
408 		    oldcred->cr_gid == oldcred->cr_rgid)
409 			p->p_flag &= ~P_SUGID;
410 		/*
411 		 * Implement correct POSIX saved-id behavior.
412 		 *
413 		 * XXX: It's not clear that the existing behavior is
414 		 * POSIX-compliant.  A number of sources indicate that the
415 		 * saved uid/gid should only be updated if the new ruid is
416 		 * not equal to the old ruid, or the new euid is not equal
417 		 * to the old euid and the new euid is not equal to the old
418 		 * ruid.  The FreeBSD code always updates the saved uid/gid.
419 		 * Also, this code uses the new (replaced) euid and egid as
420 		 * the source, which may or may not be the right ones to use.
421 		 */
422 		if (oldcred->cr_svuid != oldcred->cr_uid ||
423 		    oldcred->cr_svgid != oldcred->cr_gid) {
424 			crcopy(newcred, oldcred);
425 			change_svuid(newcred, newcred->cr_uid);
426 			change_svgid(newcred, newcred->cr_gid);
427 			p->p_ucred = newcred;
428 			newcred = NULL;
429 		}
430 	}
431 
432 	/*
433 	 * Store the vp for use in procfs
434 	 */
435 	textvp = p->p_textvp;
436 	VREF(ndp->ni_vp);
437 	p->p_textvp = ndp->ni_vp;
438 
439 	/*
440 	 * Notify others that we exec'd, and clear the P_INEXEC flag
441 	 * as we're now a bona fide freshly-execed process.
442 	 */
443 	KNOTE(&p->p_klist, NOTE_EXEC);
444 	p->p_flag &= ~P_INEXEC;
445 
446 	/*
447 	 * If tracing the process, trap to debugger so breakpoints
448 	 * can be set before the program executes.
449 	 */
450 	_STOPEVENT(p, S_EXEC, 0);
451 
452 	if (p->p_flag & P_TRACED)
453 		psignal(p, SIGTRAP);
454 
455 	/* clear "fork but no exec" flag, as we _are_ execing */
456 	p->p_acflag &= ~AFORK;
457 
458 	/* Free any previous argument cache */
459 	oldargs = p->p_args;
460 	p->p_args = NULL;
461 
462 	/* Set values passed into the program in registers. */
463 	setregs(td, imgp->entry_addr, (u_long)(uintptr_t)stack_base,
464 	    imgp->ps_strings);
465 
466 	/* Cache arguments if they fit inside our allowance */
467 	if (ps_arg_cache_limit >= i + sizeof(struct pargs)) {
468 		bcopy(imgp->stringbase, newargs->ar_args, i);
469 		p->p_args = newargs;
470 		newargs = NULL;
471 	}
472 	PROC_UNLOCK(p);
473 
474 	/*
475 	 * Free any resources malloc'd earlier that we didn't use.
476 	 */
477 	uifree(euip);
478 	if (newcred == NULL)
479 		crfree(oldcred);
480 	else
481 		crfree(newcred);
482 	KASSERT(newargs == NULL, ("leaking p_args"));
483 	/*
484 	 * Handle deferred decrement of ref counts.
485 	 */
486 	if (textvp != NULL)
487 		vrele(textvp);
488 #ifdef KTRACE
489 	if (tracevp != NULL)
490 		vrele(tracevp);
491 #endif
492 	pargs_drop(oldargs);
493 
494 exec_fail_dealloc:
495 
496 	/*
497 	 * free various allocated resources
498 	 */
499 	if (imgp->firstpage)
500 		exec_unmap_first_page(imgp);
501 
502 	if (imgp->stringbase != NULL)
503 		kmem_free_wakeup(exec_map, (vm_offset_t)imgp->stringbase,
504 			ARG_MAX + PAGE_SIZE);
505 
506 	if (imgp->vp) {
507 		NDFREE(ndp, NDF_ONLY_PNBUF);
508 		vrele(imgp->vp);
509 	}
510 
511 	if (error == 0)
512 		goto done2;
513 
514 exec_fail:
515 	/* we're done here, clear P_INEXEC */
516 	PROC_LOCK(p);
517 	p->p_flag &= ~P_INEXEC;
518 	PROC_UNLOCK(p);
519 
520 	if (imgp->vmspace_destroyed) {
521 		/* sorry, no more process anymore. exit gracefully */
522 		exit1(td, W_EXITCODE(0, SIGABRT));
523 		/* NOT REACHED */
524 		error = 0;
525 	}
526 done2:
527 	mtx_unlock(&Giant);
528 	return (error);
529 }
530 
531 int
532 exec_map_first_page(imgp)
533 	struct image_params *imgp;
534 {
535 	int rv, i;
536 	int initial_pagein;
537 	vm_page_t ma[VM_INITIAL_PAGEIN];
538 	vm_object_t object;
539 
540 	GIANT_REQUIRED;
541 
542 	if (imgp->firstpage) {
543 		exec_unmap_first_page(imgp);
544 	}
545 
546 	VOP_GETVOBJECT(imgp->vp, &object);
547 
548 	ma[0] = vm_page_grab(object, 0, VM_ALLOC_NORMAL | VM_ALLOC_RETRY);
549 
550 	if ((ma[0]->valid & VM_PAGE_BITS_ALL) != VM_PAGE_BITS_ALL) {
551 		initial_pagein = VM_INITIAL_PAGEIN;
552 		if (initial_pagein > object->size)
553 			initial_pagein = object->size;
554 		for (i = 1; i < initial_pagein; i++) {
555 			if ((ma[i] = vm_page_lookup(object, i)) != NULL) {
556 				if ((ma[i]->flags & PG_BUSY) || ma[i]->busy)
557 					break;
558 				if (ma[i]->valid)
559 					break;
560 				vm_page_busy(ma[i]);
561 			} else {
562 				ma[i] = vm_page_alloc(object, i, VM_ALLOC_NORMAL);
563 				if (ma[i] == NULL)
564 					break;
565 			}
566 		}
567 		initial_pagein = i;
568 
569 		rv = vm_pager_get_pages(object, ma, initial_pagein, 0);
570 		ma[0] = vm_page_lookup(object, 0);
571 
572 		if ((rv != VM_PAGER_OK) || (ma[0] == NULL) || (ma[0]->valid == 0)) {
573 			if (ma[0]) {
574 				vm_page_protect(ma[0], VM_PROT_NONE);
575 				vm_page_free(ma[0]);
576 			}
577 			return EIO;
578 		}
579 	}
580 
581 	vm_page_wire(ma[0]);
582 	vm_page_wakeup(ma[0]);
583 
584 	pmap_qenter((vm_offset_t)imgp->image_header, ma, 1);
585 	imgp->firstpage = ma[0];
586 
587 	return 0;
588 }
589 
590 void
591 exec_unmap_first_page(imgp)
592 	struct image_params *imgp;
593 {
594 	GIANT_REQUIRED;
595 
596 	if (imgp->firstpage) {
597 		pmap_qremove((vm_offset_t)imgp->image_header, 1);
598 		vm_page_unwire(imgp->firstpage, 1);
599 		imgp->firstpage = NULL;
600 	}
601 }
602 
603 /*
604  * Destroy old address space, and allocate a new stack
605  *	The new stack is only SGROWSIZ large because it is grown
606  *	automatically in trap.c.
607  */
608 int
609 exec_new_vmspace(imgp)
610 	struct image_params *imgp;
611 {
612 	int error;
613 	struct execlist *ep;
614 	struct proc *p = imgp->proc;
615 	struct vmspace *vmspace = p->p_vmspace;
616 	vm_offset_t stack_addr = USRSTACK - maxssiz;
617 
618 	GIANT_REQUIRED;
619 
620 	imgp->vmspace_destroyed = 1;
621 
622 	/*
623 	 * Perform functions registered with at_exec().
624 	 */
625 	TAILQ_FOREACH(ep, &exec_list, next)
626 		(*ep->function)(p);
627 
628 	/*
629 	 * Blow away entire process VM, if address space not shared,
630 	 * otherwise, create a new VM space so that other threads are
631 	 * not disrupted
632 	 */
633 	if (vmspace->vm_refcnt == 1) {
634 		if (vmspace->vm_shm)
635 			shmexit(p);
636 		pmap_remove_pages(vmspace_pmap(vmspace), 0, VM_MAXUSER_ADDRESS);
637 		vm_map_remove(&vmspace->vm_map, 0, VM_MAXUSER_ADDRESS);
638 	} else {
639 		vmspace_exec(p);
640 		vmspace = p->p_vmspace;
641 	}
642 
643 	/* Allocate a new stack */
644 	error = vm_map_stack(&vmspace->vm_map, stack_addr, (vm_size_t)maxssiz,
645 	    VM_PROT_ALL, VM_PROT_ALL, 0);
646 	if (error)
647 		return (error);
648 
649 #ifdef __ia64__
650 	{
651 		/*
652 		 * Allocate backing store. We really need something
653 		 * similar to vm_map_stack which can allow the backing
654 		 * store to grow upwards. This will do for now.
655 		 */
656 		vm_offset_t bsaddr;
657 		bsaddr = USRSTACK - 2*maxssiz;
658 		error = vm_map_find(&vmspace->vm_map, 0, 0, &bsaddr,
659 				    regstkpages * PAGE_SIZE, 0,
660 				    VM_PROT_ALL, VM_PROT_ALL, 0);
661 		FIRST_THREAD_IN_PROC(p)->td_md.md_bspstore = bsaddr;
662 	}
663 #endif
664 
665 	/* vm_ssize and vm_maxsaddr are somewhat antiquated concepts in the
666 	 * VM_STACK case, but they are still used to monitor the size of the
667 	 * process stack so we can check the stack rlimit.
668 	 */
669 	vmspace->vm_ssize = sgrowsiz >> PAGE_SHIFT;
670 	vmspace->vm_maxsaddr = (char *)USRSTACK - maxssiz;
671 
672 	return(0);
673 }
674 
675 /*
676  * Copy out argument and environment strings from the old process
677  *	address space into the temporary string buffer.
678  */
679 int
680 exec_extract_strings(imgp)
681 	struct image_params *imgp;
682 {
683 	char	**argv, **envv;
684 	char	*argp, *envp;
685 	int	error;
686 	size_t	length;
687 
688 	/*
689 	 * extract arguments first
690 	 */
691 
692 	argv = imgp->uap->argv;
693 
694 	if (argv) {
695 		argp = (caddr_t) (intptr_t) fuword(argv);
696 		if (argp == (caddr_t) -1)
697 			return (EFAULT);
698 		if (argp)
699 			argv++;
700 		if (imgp->argv0)
701 			argp = imgp->argv0;
702 		if (argp) {
703 			do {
704 				if (argp == (caddr_t) -1)
705 					return (EFAULT);
706 				if ((error = copyinstr(argp, imgp->stringp,
707 				    imgp->stringspace, &length))) {
708 					if (error == ENAMETOOLONG)
709 						return(E2BIG);
710 					return (error);
711 				}
712 				imgp->stringspace -= length;
713 				imgp->stringp += length;
714 				imgp->argc++;
715 			} while ((argp = (caddr_t) (intptr_t) fuword(argv++)));
716 		}
717 	}
718 
719 	imgp->endargs = imgp->stringp;
720 
721 	/*
722 	 * extract environment strings
723 	 */
724 
725 	envv = imgp->uap->envv;
726 
727 	if (envv) {
728 		while ((envp = (caddr_t) (intptr_t) fuword(envv++))) {
729 			if (envp == (caddr_t) -1)
730 				return (EFAULT);
731 			if ((error = copyinstr(envp, imgp->stringp,
732 			    imgp->stringspace, &length))) {
733 				if (error == ENAMETOOLONG)
734 					return(E2BIG);
735 				return (error);
736 			}
737 			imgp->stringspace -= length;
738 			imgp->stringp += length;
739 			imgp->envc++;
740 		}
741 	}
742 
743 	return (0);
744 }
745 
746 /*
747  * Copy strings out to the new process address space, constructing
748  *	new arg and env vector tables. Return a pointer to the base
749  *	so that it can be used as the initial stack pointer.
750  */
751 register_t *
752 exec_copyout_strings(imgp)
753 	struct image_params *imgp;
754 {
755 	int argc, envc;
756 	char **vectp;
757 	char *stringp, *destp;
758 	register_t *stack_base;
759 	struct ps_strings *arginfo;
760 	int szsigcode;
761 
762 	/*
763 	 * Calculate string base and vector table pointers.
764 	 * Also deal with signal trampoline code for this exec type.
765 	 */
766 	arginfo = (struct ps_strings *)PS_STRINGS;
767 	szsigcode = *(imgp->proc->p_sysent->sv_szsigcode);
768 	destp =	(caddr_t)arginfo - szsigcode - SPARE_USRSPACE -
769 		roundup((ARG_MAX - imgp->stringspace), sizeof(char *));
770 
771 	/*
772 	 * install sigcode
773 	 */
774 	if (szsigcode)
775 		copyout(imgp->proc->p_sysent->sv_sigcode,
776 			((caddr_t)arginfo - szsigcode), szsigcode);
777 
778 	/*
779 	 * If we have a valid auxargs ptr, prepare some room
780 	 * on the stack.
781 	 */
782 	if (imgp->auxargs) {
783 		/*
784 		 * 'AT_COUNT*2' is size for the ELF Auxargs data. This is for
785 		 * lower compatibility.
786 		 */
787 		imgp->auxarg_size = (imgp->auxarg_size) ? imgp->auxarg_size
788 			: (AT_COUNT * 2);
789 		/*
790 		 * The '+ 2' is for the null pointers at the end of each of
791 		 * the arg and env vector sets,and imgp->auxarg_size is room
792 		 * for argument of Runtime loader.
793 		 */
794 		vectp = (char **) (destp - (imgp->argc + imgp->envc + 2 +
795 				       imgp->auxarg_size) * sizeof(char *));
796 
797 	} else
798 		/*
799 		 * The '+ 2' is for the null pointers at the end of each of
800 		 * the arg and env vector sets
801 		 */
802 		vectp = (char **)
803 			(destp - (imgp->argc + imgp->envc + 2) * sizeof(char *));
804 
805 	/*
806 	 * vectp also becomes our initial stack base
807 	 */
808 	stack_base = (register_t *)vectp;
809 
810 	stringp = imgp->stringbase;
811 	argc = imgp->argc;
812 	envc = imgp->envc;
813 
814 	/*
815 	 * Copy out strings - arguments and environment.
816 	 */
817 	copyout(stringp, destp, ARG_MAX - imgp->stringspace);
818 
819 	/*
820 	 * Fill in "ps_strings" struct for ps, w, etc.
821 	 */
822 	suword(&arginfo->ps_argvstr, (long)(intptr_t)vectp);
823 	suword(&arginfo->ps_nargvstr, argc);
824 
825 	/*
826 	 * Fill in argument portion of vector table.
827 	 */
828 	for (; argc > 0; --argc) {
829 		suword(vectp++, (long)(intptr_t)destp);
830 		while (*stringp++ != 0)
831 			destp++;
832 		destp++;
833 	}
834 
835 	/* a null vector table pointer separates the argp's from the envp's */
836 	suword(vectp++, 0);
837 
838 	suword(&arginfo->ps_envstr, (long)(intptr_t)vectp);
839 	suword(&arginfo->ps_nenvstr, envc);
840 
841 	/*
842 	 * Fill in environment portion of vector table.
843 	 */
844 	for (; envc > 0; --envc) {
845 		suword(vectp++, (long)(intptr_t)destp);
846 		while (*stringp++ != 0)
847 			destp++;
848 		destp++;
849 	}
850 
851 	/* end of vector table is a null pointer */
852 	suword(vectp, 0);
853 
854 	return (stack_base);
855 }
856 
857 /*
858  * Check permissions of file to execute.
859  *	Called with imgp->vp locked.
860  *	Return 0 for success or error code on failure.
861  */
862 int
863 exec_check_permissions(imgp)
864 	struct image_params *imgp;
865 {
866 	struct vnode *vp = imgp->vp;
867 	struct vattr *attr = imgp->attr;
868 	struct thread *td;
869 	int error;
870 
871 	td = curthread;			/* XXXKSE */
872 	/* Get file attributes */
873 	error = VOP_GETATTR(vp, attr, td->td_ucred, td);
874 	if (error)
875 		return (error);
876 
877 	/*
878 	 * 1) Check if file execution is disabled for the filesystem that this
879 	 *	file resides on.
880 	 * 2) Insure that at least one execute bit is on - otherwise root
881 	 *	will always succeed, and we don't want to happen unless the
882 	 *	file really is executable.
883 	 * 3) Insure that the file is a regular file.
884 	 */
885 	if ((vp->v_mount->mnt_flag & MNT_NOEXEC) ||
886 	    ((attr->va_mode & 0111) == 0) ||
887 	    (attr->va_type != VREG))
888 		return (EACCES);
889 
890 	/*
891 	 * Zero length files can't be exec'd
892 	 */
893 	if (attr->va_size == 0)
894 		return (ENOEXEC);
895 
896 	/*
897 	 *  Check for execute permission to file based on current credentials.
898 	 */
899 	error = VOP_ACCESS(vp, VEXEC, td->td_ucred, td);
900 	if (error)
901 		return (error);
902 
903 	/*
904 	 * Check number of open-for-writes on the file and deny execution
905 	 * if there are any.
906 	 */
907 	if (vp->v_writecount)
908 		return (ETXTBSY);
909 
910 	/*
911 	 * Call filesystem specific open routine (which does nothing in the
912 	 * general case).
913 	 */
914 	error = VOP_OPEN(vp, FREAD, td->td_ucred, td);
915 	return (error);
916 }
917 
918 /*
919  * Exec handler registration
920  */
921 int
922 exec_register(execsw_arg)
923 	const struct execsw *execsw_arg;
924 {
925 	const struct execsw **es, **xs, **newexecsw;
926 	int count = 2;	/* New slot and trailing NULL */
927 
928 	if (execsw)
929 		for (es = execsw; *es; es++)
930 			count++;
931 	newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
932 	if (newexecsw == NULL)
933 		return ENOMEM;
934 	xs = newexecsw;
935 	if (execsw)
936 		for (es = execsw; *es; es++)
937 			*xs++ = *es;
938 	*xs++ = execsw_arg;
939 	*xs = NULL;
940 	if (execsw)
941 		free(execsw, M_TEMP);
942 	execsw = newexecsw;
943 	return 0;
944 }
945 
946 int
947 exec_unregister(execsw_arg)
948 	const struct execsw *execsw_arg;
949 {
950 	const struct execsw **es, **xs, **newexecsw;
951 	int count = 1;
952 
953 	if (execsw == NULL)
954 		panic("unregister with no handlers left?\n");
955 
956 	for (es = execsw; *es; es++) {
957 		if (*es == execsw_arg)
958 			break;
959 	}
960 	if (*es == NULL)
961 		return ENOENT;
962 	for (es = execsw; *es; es++)
963 		if (*es != execsw_arg)
964 			count++;
965 	newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
966 	if (newexecsw == NULL)
967 		return ENOMEM;
968 	xs = newexecsw;
969 	for (es = execsw; *es; es++)
970 		if (*es != execsw_arg)
971 			*xs++ = *es;
972 	*xs = NULL;
973 	if (execsw)
974 		free(execsw, M_TEMP);
975 	execsw = newexecsw;
976 	return 0;
977 }
978 
979 int
980 at_exec(function)
981 	execlist_fn function;
982 {
983 	struct execlist *ep;
984 
985 #ifdef INVARIANTS
986 	/* Be noisy if the programmer has lost track of things */
987 	if (rm_at_exec(function))
988 		printf("WARNING: exec callout entry (%p) already present\n",
989 		    function);
990 #endif
991 	ep = malloc(sizeof(*ep), M_ATEXEC, M_NOWAIT);
992 	if (ep == NULL)
993 		return (ENOMEM);
994 	ep->function = function;
995 	TAILQ_INSERT_TAIL(&exec_list, ep, next);
996 	return (0);
997 }
998 
999 /*
1000  * Scan the exec callout list for the given item and remove it.
1001  * Returns the number of items removed (0 or 1)
1002  */
1003 int
1004 rm_at_exec(function)
1005 	execlist_fn function;
1006 {
1007 	struct execlist *ep;
1008 
1009 	TAILQ_FOREACH(ep, &exec_list, next) {
1010 		if (ep->function == function) {
1011 			TAILQ_REMOVE(&exec_list, ep, next);
1012 			free(ep, M_ATEXEC);
1013 			return(1);
1014 		}
1015 	}
1016 	return (0);
1017 }
1018 
1019