xref: /freebsd/sys/kern/kern_exec.c (revision 884a2a699669ec61e2366e3e358342dbc94be24a)
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 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include "opt_hwpmc_hooks.h"
31 #include "opt_kdtrace.h"
32 #include "opt_ktrace.h"
33 #include "opt_vm.h"
34 
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/eventhandler.h>
38 #include <sys/lock.h>
39 #include <sys/mutex.h>
40 #include <sys/sysproto.h>
41 #include <sys/signalvar.h>
42 #include <sys/kernel.h>
43 #include <sys/mount.h>
44 #include <sys/filedesc.h>
45 #include <sys/fcntl.h>
46 #include <sys/acct.h>
47 #include <sys/exec.h>
48 #include <sys/imgact.h>
49 #include <sys/imgact_elf.h>
50 #include <sys/wait.h>
51 #include <sys/malloc.h>
52 #include <sys/priv.h>
53 #include <sys/proc.h>
54 #include <sys/pioctl.h>
55 #include <sys/namei.h>
56 #include <sys/resourcevar.h>
57 #include <sys/sdt.h>
58 #include <sys/sf_buf.h>
59 #include <sys/syscallsubr.h>
60 #include <sys/sysent.h>
61 #include <sys/shm.h>
62 #include <sys/sysctl.h>
63 #include <sys/vnode.h>
64 #include <sys/stat.h>
65 #ifdef KTRACE
66 #include <sys/ktrace.h>
67 #endif
68 
69 #include <vm/vm.h>
70 #include <vm/vm_param.h>
71 #include <vm/pmap.h>
72 #include <vm/vm_page.h>
73 #include <vm/vm_map.h>
74 #include <vm/vm_kern.h>
75 #include <vm/vm_extern.h>
76 #include <vm/vm_object.h>
77 #include <vm/vm_pager.h>
78 
79 #ifdef	HWPMC_HOOKS
80 #include <sys/pmckern.h>
81 #endif
82 
83 #include <machine/reg.h>
84 
85 #include <security/audit/audit.h>
86 #include <security/mac/mac_framework.h>
87 
88 #ifdef KDTRACE_HOOKS
89 #include <sys/dtrace_bsd.h>
90 dtrace_execexit_func_t	dtrace_fasttrap_exec;
91 #endif
92 
93 SDT_PROVIDER_DECLARE(proc);
94 SDT_PROBE_DEFINE(proc, kernel, , exec, exec);
95 SDT_PROBE_ARGTYPE(proc, kernel, , exec, 0, "char *");
96 SDT_PROBE_DEFINE(proc, kernel, , exec_failure, exec-failure);
97 SDT_PROBE_ARGTYPE(proc, kernel, , exec_failure, 0, "int");
98 SDT_PROBE_DEFINE(proc, kernel, , exec_success, exec-success);
99 SDT_PROBE_ARGTYPE(proc, kernel, , exec_success, 0, "char *");
100 
101 MALLOC_DEFINE(M_PARGS, "proc-args", "Process arguments");
102 
103 static int sysctl_kern_ps_strings(SYSCTL_HANDLER_ARGS);
104 static int sysctl_kern_usrstack(SYSCTL_HANDLER_ARGS);
105 static int sysctl_kern_stackprot(SYSCTL_HANDLER_ARGS);
106 static int do_execve(struct thread *td, struct image_args *args,
107     struct mac *mac_p);
108 
109 /* XXX This should be vm_size_t. */
110 SYSCTL_PROC(_kern, KERN_PS_STRINGS, ps_strings, CTLTYPE_ULONG|CTLFLAG_RD,
111     NULL, 0, sysctl_kern_ps_strings, "LU", "");
112 
113 /* XXX This should be vm_size_t. */
114 SYSCTL_PROC(_kern, KERN_USRSTACK, usrstack, CTLTYPE_ULONG|CTLFLAG_RD,
115     NULL, 0, sysctl_kern_usrstack, "LU", "");
116 
117 SYSCTL_PROC(_kern, OID_AUTO, stackprot, CTLTYPE_INT|CTLFLAG_RD,
118     NULL, 0, sysctl_kern_stackprot, "I", "");
119 
120 u_long ps_arg_cache_limit = PAGE_SIZE / 16;
121 SYSCTL_ULONG(_kern, OID_AUTO, ps_arg_cache_limit, CTLFLAG_RW,
122     &ps_arg_cache_limit, 0, "");
123 
124 static int map_at_zero = 0;
125 TUNABLE_INT("security.bsd.map_at_zero", &map_at_zero);
126 SYSCTL_INT(_security_bsd, OID_AUTO, map_at_zero, CTLFLAG_RW, &map_at_zero, 0,
127     "Permit processes to map an object at virtual address 0.");
128 
129 static int
130 sysctl_kern_ps_strings(SYSCTL_HANDLER_ARGS)
131 {
132 	struct proc *p;
133 	int error;
134 
135 	p = curproc;
136 #ifdef SCTL_MASK32
137 	if (req->flags & SCTL_MASK32) {
138 		unsigned int val;
139 		val = (unsigned int)p->p_sysent->sv_psstrings;
140 		error = SYSCTL_OUT(req, &val, sizeof(val));
141 	} else
142 #endif
143 		error = SYSCTL_OUT(req, &p->p_sysent->sv_psstrings,
144 		   sizeof(p->p_sysent->sv_psstrings));
145 	return error;
146 }
147 
148 static int
149 sysctl_kern_usrstack(SYSCTL_HANDLER_ARGS)
150 {
151 	struct proc *p;
152 	int error;
153 
154 	p = curproc;
155 #ifdef SCTL_MASK32
156 	if (req->flags & SCTL_MASK32) {
157 		unsigned int val;
158 		val = (unsigned int)p->p_sysent->sv_usrstack;
159 		error = SYSCTL_OUT(req, &val, sizeof(val));
160 	} else
161 #endif
162 		error = SYSCTL_OUT(req, &p->p_sysent->sv_usrstack,
163 		    sizeof(p->p_sysent->sv_usrstack));
164 	return error;
165 }
166 
167 static int
168 sysctl_kern_stackprot(SYSCTL_HANDLER_ARGS)
169 {
170 	struct proc *p;
171 
172 	p = curproc;
173 	return (SYSCTL_OUT(req, &p->p_sysent->sv_stackprot,
174 	    sizeof(p->p_sysent->sv_stackprot)));
175 }
176 
177 /*
178  * Each of the items is a pointer to a `const struct execsw', hence the
179  * double pointer here.
180  */
181 static const struct execsw **execsw;
182 
183 #ifndef _SYS_SYSPROTO_H_
184 struct execve_args {
185 	char    *fname;
186 	char    **argv;
187 	char    **envv;
188 };
189 #endif
190 
191 int
192 execve(td, uap)
193 	struct thread *td;
194 	struct execve_args /* {
195 		char *fname;
196 		char **argv;
197 		char **envv;
198 	} */ *uap;
199 {
200 	int error;
201 	struct image_args args;
202 
203 	error = exec_copyin_args(&args, uap->fname, UIO_USERSPACE,
204 	    uap->argv, uap->envv);
205 	if (error == 0)
206 		error = kern_execve(td, &args, NULL);
207 	return (error);
208 }
209 
210 #ifndef _SYS_SYSPROTO_H_
211 struct fexecve_args {
212 	int	fd;
213 	char	**argv;
214 	char	**envv;
215 }
216 #endif
217 int
218 fexecve(struct thread *td, struct fexecve_args *uap)
219 {
220 	int error;
221 	struct image_args args;
222 
223 	error = exec_copyin_args(&args, NULL, UIO_SYSSPACE,
224 	    uap->argv, uap->envv);
225 	if (error == 0) {
226 		args.fd = uap->fd;
227 		error = kern_execve(td, &args, NULL);
228 	}
229 	return (error);
230 }
231 
232 #ifndef _SYS_SYSPROTO_H_
233 struct __mac_execve_args {
234 	char	*fname;
235 	char	**argv;
236 	char	**envv;
237 	struct mac	*mac_p;
238 };
239 #endif
240 
241 int
242 __mac_execve(td, uap)
243 	struct thread *td;
244 	struct __mac_execve_args /* {
245 		char *fname;
246 		char **argv;
247 		char **envv;
248 		struct mac *mac_p;
249 	} */ *uap;
250 {
251 #ifdef MAC
252 	int error;
253 	struct image_args args;
254 
255 	error = exec_copyin_args(&args, uap->fname, UIO_USERSPACE,
256 	    uap->argv, uap->envv);
257 	if (error == 0)
258 		error = kern_execve(td, &args, uap->mac_p);
259 	return (error);
260 #else
261 	return (ENOSYS);
262 #endif
263 }
264 
265 /*
266  * XXX: kern_execve has the astonishing property of not always returning to
267  * the caller.  If sufficiently bad things happen during the call to
268  * do_execve(), it can end up calling exit1(); as a result, callers must
269  * avoid doing anything which they might need to undo (e.g., allocating
270  * memory).
271  */
272 int
273 kern_execve(td, args, mac_p)
274 	struct thread *td;
275 	struct image_args *args;
276 	struct mac *mac_p;
277 {
278 	struct proc *p = td->td_proc;
279 	int error;
280 
281 	AUDIT_ARG_ARGV(args->begin_argv, args->argc,
282 	    args->begin_envv - args->begin_argv);
283 	AUDIT_ARG_ENVV(args->begin_envv, args->envc,
284 	    args->endp - args->begin_envv);
285 	if (p->p_flag & P_HADTHREADS) {
286 		PROC_LOCK(p);
287 		if (thread_single(SINGLE_BOUNDARY)) {
288 			PROC_UNLOCK(p);
289 	       		exec_free_args(args);
290 			return (ERESTART);	/* Try again later. */
291 		}
292 		PROC_UNLOCK(p);
293 	}
294 
295 	error = do_execve(td, args, mac_p);
296 
297 	if (p->p_flag & P_HADTHREADS) {
298 		PROC_LOCK(p);
299 		/*
300 		 * If success, we upgrade to SINGLE_EXIT state to
301 		 * force other threads to suicide.
302 		 */
303 		if (error == 0)
304 			thread_single(SINGLE_EXIT);
305 		else
306 			thread_single_end();
307 		PROC_UNLOCK(p);
308 	}
309 
310 	return (error);
311 }
312 
313 /*
314  * In-kernel implementation of execve().  All arguments are assumed to be
315  * userspace pointers from the passed thread.
316  */
317 static int
318 do_execve(td, args, mac_p)
319 	struct thread *td;
320 	struct image_args *args;
321 	struct mac *mac_p;
322 {
323 	struct proc *p = td->td_proc;
324 	struct nameidata nd;
325 	struct ucred *newcred = NULL, *oldcred;
326 	struct uidinfo *euip;
327 	register_t *stack_base;
328 	int error, i;
329 	struct image_params image_params, *imgp;
330 	struct vattr attr;
331 	int (*img_first)(struct image_params *);
332 	struct pargs *oldargs = NULL, *newargs = NULL;
333 	struct sigacts *oldsigacts, *newsigacts;
334 #ifdef KTRACE
335 	struct vnode *tracevp = NULL;
336 	struct ucred *tracecred = NULL;
337 #endif
338 	struct vnode *textvp = NULL, *binvp = NULL;
339 	int credential_changing;
340 	int vfslocked;
341 	int textset;
342 #ifdef MAC
343 	struct label *interpvplabel = NULL;
344 	int will_transition;
345 #endif
346 #ifdef HWPMC_HOOKS
347 	struct pmckern_procexec pe;
348 #endif
349 	static const char fexecv_proc_title[] = "(fexecv)";
350 
351 	vfslocked = 0;
352 	imgp = &image_params;
353 
354 	/*
355 	 * Lock the process and set the P_INEXEC flag to indicate that
356 	 * it should be left alone until we're done here.  This is
357 	 * necessary to avoid race conditions - e.g. in ptrace() -
358 	 * that might allow a local user to illicitly obtain elevated
359 	 * privileges.
360 	 */
361 	PROC_LOCK(p);
362 	KASSERT((p->p_flag & P_INEXEC) == 0,
363 	    ("%s(): process already has P_INEXEC flag", __func__));
364 	p->p_flag |= P_INEXEC;
365 	PROC_UNLOCK(p);
366 
367 	/*
368 	 * Initialize part of the common data
369 	 */
370 	imgp->proc = p;
371 	imgp->execlabel = NULL;
372 	imgp->attr = &attr;
373 	imgp->entry_addr = 0;
374 	imgp->reloc_base = 0;
375 	imgp->vmspace_destroyed = 0;
376 	imgp->interpreted = 0;
377 	imgp->opened = 0;
378 	imgp->interpreter_name = NULL;
379 	imgp->auxargs = NULL;
380 	imgp->vp = NULL;
381 	imgp->object = NULL;
382 	imgp->firstpage = NULL;
383 	imgp->ps_strings = 0;
384 	imgp->auxarg_size = 0;
385 	imgp->args = args;
386 	imgp->execpath = imgp->freepath = NULL;
387 	imgp->execpathp = 0;
388 	imgp->canary = 0;
389 	imgp->canarylen = 0;
390 	imgp->pagesizes = 0;
391 	imgp->pagesizeslen = 0;
392 	imgp->stack_prot = 0;
393 
394 #ifdef MAC
395 	error = mac_execve_enter(imgp, mac_p);
396 	if (error)
397 		goto exec_fail;
398 #endif
399 
400 	imgp->image_header = NULL;
401 
402 	/*
403 	 * Translate the file name. namei() returns a vnode pointer
404 	 *	in ni_vp amoung other things.
405 	 *
406 	 * XXXAUDIT: It would be desirable to also audit the name of the
407 	 * interpreter if this is an interpreted binary.
408 	 */
409 	if (args->fname != NULL) {
410 		NDINIT(&nd, LOOKUP, ISOPEN | LOCKLEAF | FOLLOW | SAVENAME
411 		    | MPSAFE | AUDITVNODE1, UIO_SYSSPACE, args->fname, td);
412 	}
413 
414 	SDT_PROBE(proc, kernel, , exec, args->fname, 0, 0, 0, 0 );
415 
416 interpret:
417 	if (args->fname != NULL) {
418 		error = namei(&nd);
419 		if (error)
420 			goto exec_fail;
421 
422 		vfslocked = NDHASGIANT(&nd);
423 		binvp  = nd.ni_vp;
424 		imgp->vp = binvp;
425 	} else {
426 		AUDIT_ARG_FD(args->fd);
427 		error = fgetvp(td, args->fd, &binvp);
428 		if (error)
429 			goto exec_fail;
430 		vfslocked = VFS_LOCK_GIANT(binvp->v_mount);
431 		vn_lock(binvp, LK_EXCLUSIVE | LK_RETRY);
432 		AUDIT_ARG_VNODE1(binvp);
433 		imgp->vp = binvp;
434 	}
435 
436 	/*
437 	 * Check file permissions (also 'opens' file)
438 	 */
439 	error = exec_check_permissions(imgp);
440 	if (error)
441 		goto exec_fail_dealloc;
442 
443 	imgp->object = imgp->vp->v_object;
444 	if (imgp->object != NULL)
445 		vm_object_reference(imgp->object);
446 
447 	/*
448 	 * Set VV_TEXT now so no one can write to the executable while we're
449 	 * activating it.
450 	 *
451 	 * Remember if this was set before and unset it in case this is not
452 	 * actually an executable image.
453 	 */
454 	textset = imgp->vp->v_vflag & VV_TEXT;
455 	imgp->vp->v_vflag |= VV_TEXT;
456 
457 	error = exec_map_first_page(imgp);
458 	if (error)
459 		goto exec_fail_dealloc;
460 
461 	imgp->proc->p_osrel = 0;
462 	/*
463 	 *	If the current process has a special image activator it
464 	 *	wants to try first, call it.   For example, emulating shell
465 	 *	scripts differently.
466 	 */
467 	error = -1;
468 	if ((img_first = imgp->proc->p_sysent->sv_imgact_try) != NULL)
469 		error = img_first(imgp);
470 
471 	/*
472 	 *	Loop through the list of image activators, calling each one.
473 	 *	An activator returns -1 if there is no match, 0 on success,
474 	 *	and an error otherwise.
475 	 */
476 	for (i = 0; error == -1 && execsw[i]; ++i) {
477 		if (execsw[i]->ex_imgact == NULL ||
478 		    execsw[i]->ex_imgact == img_first) {
479 			continue;
480 		}
481 		error = (*execsw[i]->ex_imgact)(imgp);
482 	}
483 
484 	if (error) {
485 		if (error == -1) {
486 			if (textset == 0)
487 				imgp->vp->v_vflag &= ~VV_TEXT;
488 			error = ENOEXEC;
489 		}
490 		goto exec_fail_dealloc;
491 	}
492 
493 	/*
494 	 * Special interpreter operation, cleanup and loop up to try to
495 	 * activate the interpreter.
496 	 */
497 	if (imgp->interpreted) {
498 		exec_unmap_first_page(imgp);
499 		/*
500 		 * VV_TEXT needs to be unset for scripts.  There is a short
501 		 * period before we determine that something is a script where
502 		 * VV_TEXT will be set. The vnode lock is held over this
503 		 * entire period so nothing should illegitimately be blocked.
504 		 */
505 		imgp->vp->v_vflag &= ~VV_TEXT;
506 		/* free name buffer and old vnode */
507 		if (args->fname != NULL)
508 			NDFREE(&nd, NDF_ONLY_PNBUF);
509 #ifdef MAC
510 		mac_execve_interpreter_enter(binvp, &interpvplabel);
511 #endif
512 		if (imgp->opened) {
513 			VOP_CLOSE(binvp, FREAD, td->td_ucred, td);
514 			imgp->opened = 0;
515 		}
516 		vput(binvp);
517 		vm_object_deallocate(imgp->object);
518 		imgp->object = NULL;
519 		VFS_UNLOCK_GIANT(vfslocked);
520 		vfslocked = 0;
521 		/* set new name to that of the interpreter */
522 		NDINIT(&nd, LOOKUP, LOCKLEAF | FOLLOW | SAVENAME | MPSAFE,
523 		    UIO_SYSSPACE, imgp->interpreter_name, td);
524 		args->fname = imgp->interpreter_name;
525 		goto interpret;
526 	}
527 
528 	/*
529 	 * NB: We unlock the vnode here because it is believed that none
530 	 * of the sv_copyout_strings/sv_fixup operations require the vnode.
531 	 */
532 	VOP_UNLOCK(imgp->vp, 0);
533 
534 	/*
535 	 * Do the best to calculate the full path to the image file.
536 	 */
537 	if (imgp->auxargs != NULL &&
538 	    ((args->fname != NULL && args->fname[0] == '/') ||
539 	     vn_fullpath(td, imgp->vp, &imgp->execpath, &imgp->freepath) != 0))
540 		imgp->execpath = args->fname;
541 
542 	/*
543 	 * Copy out strings (args and env) and initialize stack base
544 	 */
545 	if (p->p_sysent->sv_copyout_strings)
546 		stack_base = (*p->p_sysent->sv_copyout_strings)(imgp);
547 	else
548 		stack_base = exec_copyout_strings(imgp);
549 
550 	/*
551 	 * If custom stack fixup routine present for this process
552 	 * let it do the stack setup.
553 	 * Else stuff argument count as first item on stack
554 	 */
555 	if (p->p_sysent->sv_fixup != NULL)
556 		(*p->p_sysent->sv_fixup)(&stack_base, imgp);
557 	else
558 		suword(--stack_base, imgp->args->argc);
559 
560 	/*
561 	 * For security and other reasons, the file descriptor table cannot
562 	 * be shared after an exec.
563 	 */
564 	fdunshare(p, td);
565 
566 	/*
567 	 * Malloc things before we need locks.
568 	 */
569 	newcred = crget();
570 	euip = uifind(attr.va_uid);
571 	i = imgp->args->begin_envv - imgp->args->begin_argv;
572 	/* Cache arguments if they fit inside our allowance */
573 	if (ps_arg_cache_limit >= i + sizeof(struct pargs)) {
574 		newargs = pargs_alloc(i);
575 		bcopy(imgp->args->begin_argv, newargs->ar_args, i);
576 	}
577 
578 	/* close files on exec */
579 	fdcloseexec(td);
580 	vn_lock(imgp->vp, LK_EXCLUSIVE | LK_RETRY);
581 
582 	/* Get a reference to the vnode prior to locking the proc */
583 	VREF(binvp);
584 
585 	/*
586 	 * For security and other reasons, signal handlers cannot
587 	 * be shared after an exec. The new process gets a copy of the old
588 	 * handlers. In execsigs(), the new process will have its signals
589 	 * reset.
590 	 */
591 	PROC_LOCK(p);
592 	oldcred = crcopysafe(p, newcred);
593 	if (sigacts_shared(p->p_sigacts)) {
594 		oldsigacts = p->p_sigacts;
595 		PROC_UNLOCK(p);
596 		newsigacts = sigacts_alloc();
597 		sigacts_copy(newsigacts, oldsigacts);
598 		PROC_LOCK(p);
599 		p->p_sigacts = newsigacts;
600 	} else
601 		oldsigacts = NULL;
602 
603 	/* Stop profiling */
604 	stopprofclock(p);
605 
606 	/* reset caught signals */
607 	execsigs(p);
608 
609 	/* name this process - nameiexec(p, ndp) */
610 	bzero(p->p_comm, sizeof(p->p_comm));
611 	if (args->fname)
612 		bcopy(nd.ni_cnd.cn_nameptr, p->p_comm,
613 		    min(nd.ni_cnd.cn_namelen, MAXCOMLEN));
614 	else if (vn_commname(binvp, p->p_comm, sizeof(p->p_comm)) != 0)
615 		bcopy(fexecv_proc_title, p->p_comm, sizeof(fexecv_proc_title));
616 	bcopy(p->p_comm, td->td_name, sizeof(td->td_name));
617 
618 	/*
619 	 * mark as execed, wakeup the process that vforked (if any) and tell
620 	 * it that it now has its own resources back
621 	 */
622 	p->p_flag |= P_EXEC;
623 	if (p->p_pptr && (p->p_flag & P_PPWAIT)) {
624 		p->p_flag &= ~P_PPWAIT;
625 		cv_broadcast(&p->p_pwait);
626 	}
627 
628 	/*
629 	 * Implement image setuid/setgid.
630 	 *
631 	 * Don't honor setuid/setgid if the filesystem prohibits it or if
632 	 * the process is being traced.
633 	 *
634 	 * XXXMAC: For the time being, use NOSUID to also prohibit
635 	 * transitions on the file system.
636 	 */
637 	credential_changing = 0;
638 	credential_changing |= (attr.va_mode & S_ISUID) && oldcred->cr_uid !=
639 	    attr.va_uid;
640 	credential_changing |= (attr.va_mode & S_ISGID) && oldcred->cr_gid !=
641 	    attr.va_gid;
642 #ifdef MAC
643 	will_transition = mac_vnode_execve_will_transition(oldcred, imgp->vp,
644 	    interpvplabel, imgp);
645 	credential_changing |= will_transition;
646 #endif
647 
648 	if (credential_changing &&
649 	    (imgp->vp->v_mount->mnt_flag & MNT_NOSUID) == 0 &&
650 	    (p->p_flag & P_TRACED) == 0) {
651 		/*
652 		 * Turn off syscall tracing for set-id programs, except for
653 		 * root.  Record any set-id flags first to make sure that
654 		 * we do not regain any tracing during a possible block.
655 		 */
656 		setsugid(p);
657 
658 #ifdef KTRACE
659 		if (priv_check_cred(oldcred, PRIV_DEBUG_DIFFCRED, 0))
660 			ktrprocexec(p, &tracecred, &tracevp);
661 #endif
662 		/*
663 		 * Close any file descriptors 0..2 that reference procfs,
664 		 * then make sure file descriptors 0..2 are in use.
665 		 *
666 		 * setugidsafety() may call closef() and then pfind()
667 		 * which may grab the process lock.
668 		 * fdcheckstd() may call falloc() which may block to
669 		 * allocate memory, so temporarily drop the process lock.
670 		 */
671 		PROC_UNLOCK(p);
672 		VOP_UNLOCK(imgp->vp, 0);
673 		setugidsafety(td);
674 		error = fdcheckstd(td);
675 		vn_lock(imgp->vp, LK_EXCLUSIVE | LK_RETRY);
676 		if (error != 0)
677 			goto done1;
678 		PROC_LOCK(p);
679 		/*
680 		 * Set the new credentials.
681 		 */
682 		if (attr.va_mode & S_ISUID)
683 			change_euid(newcred, euip);
684 		if (attr.va_mode & S_ISGID)
685 			change_egid(newcred, attr.va_gid);
686 #ifdef MAC
687 		if (will_transition) {
688 			mac_vnode_execve_transition(oldcred, newcred, imgp->vp,
689 			    interpvplabel, imgp);
690 		}
691 #endif
692 		/*
693 		 * Implement correct POSIX saved-id behavior.
694 		 *
695 		 * XXXMAC: Note that the current logic will save the
696 		 * uid and gid if a MAC domain transition occurs, even
697 		 * though maybe it shouldn't.
698 		 */
699 		change_svuid(newcred, newcred->cr_uid);
700 		change_svgid(newcred, newcred->cr_gid);
701 		p->p_ucred = newcred;
702 		newcred = NULL;
703 	} else {
704 		if (oldcred->cr_uid == oldcred->cr_ruid &&
705 		    oldcred->cr_gid == oldcred->cr_rgid)
706 			p->p_flag &= ~P_SUGID;
707 		/*
708 		 * Implement correct POSIX saved-id behavior.
709 		 *
710 		 * XXX: It's not clear that the existing behavior is
711 		 * POSIX-compliant.  A number of sources indicate that the
712 		 * saved uid/gid should only be updated if the new ruid is
713 		 * not equal to the old ruid, or the new euid is not equal
714 		 * to the old euid and the new euid is not equal to the old
715 		 * ruid.  The FreeBSD code always updates the saved uid/gid.
716 		 * Also, this code uses the new (replaced) euid and egid as
717 		 * the source, which may or may not be the right ones to use.
718 		 */
719 		if (oldcred->cr_svuid != oldcred->cr_uid ||
720 		    oldcred->cr_svgid != oldcred->cr_gid) {
721 			change_svuid(newcred, newcred->cr_uid);
722 			change_svgid(newcred, newcred->cr_gid);
723 			p->p_ucred = newcred;
724 			newcred = NULL;
725 		}
726 	}
727 
728 	/*
729 	 * Store the vp for use in procfs.  This vnode was referenced prior
730 	 * to locking the proc lock.
731 	 */
732 	textvp = p->p_textvp;
733 	p->p_textvp = binvp;
734 
735 #ifdef KDTRACE_HOOKS
736 	/*
737 	 * Tell the DTrace fasttrap provider about the exec if it
738 	 * has declared an interest.
739 	 */
740 	if (dtrace_fasttrap_exec)
741 		dtrace_fasttrap_exec(p);
742 #endif
743 
744 	/*
745 	 * Notify others that we exec'd, and clear the P_INEXEC flag
746 	 * as we're now a bona fide freshly-execed process.
747 	 */
748 	KNOTE_LOCKED(&p->p_klist, NOTE_EXEC);
749 	p->p_flag &= ~P_INEXEC;
750 
751 	/*
752 	 * If tracing the process, trap to the debugger so that
753 	 * breakpoints can be set before the program executes.  We
754 	 * have to use tdsignal() to deliver the signal to the current
755 	 * thread since any other threads in this process will exit if
756 	 * execve() succeeds.
757 	 */
758 	if (p->p_flag & P_TRACED)
759 		tdsignal(td, SIGTRAP);
760 
761 	/* clear "fork but no exec" flag, as we _are_ execing */
762 	p->p_acflag &= ~AFORK;
763 
764 	/*
765 	 * Free any previous argument cache and replace it with
766 	 * the new argument cache, if any.
767 	 */
768 	oldargs = p->p_args;
769 	p->p_args = newargs;
770 	newargs = NULL;
771 
772 #ifdef	HWPMC_HOOKS
773 	/*
774 	 * Check if system-wide sampling is in effect or if the
775 	 * current process is using PMCs.  If so, do exec() time
776 	 * processing.  This processing needs to happen AFTER the
777 	 * P_INEXEC flag is cleared.
778 	 *
779 	 * The proc lock needs to be released before taking the PMC
780 	 * SX.
781 	 */
782 	if (PMC_SYSTEM_SAMPLING_ACTIVE() || PMC_PROC_IS_USING_PMCS(p)) {
783 		PROC_UNLOCK(p);
784 		VOP_UNLOCK(imgp->vp, 0);
785 		pe.pm_credentialschanged = credential_changing;
786 		pe.pm_entryaddr = imgp->entry_addr;
787 
788 		PMC_CALL_HOOK_X(td, PMC_FN_PROCESS_EXEC, (void *) &pe);
789 		vn_lock(imgp->vp, LK_EXCLUSIVE | LK_RETRY);
790 	} else
791 		PROC_UNLOCK(p);
792 #else  /* !HWPMC_HOOKS */
793 	PROC_UNLOCK(p);
794 #endif
795 
796 	/* Set values passed into the program in registers. */
797 	if (p->p_sysent->sv_setregs)
798 		(*p->p_sysent->sv_setregs)(td, imgp,
799 		    (u_long)(uintptr_t)stack_base);
800 	else
801 		exec_setregs(td, imgp, (u_long)(uintptr_t)stack_base);
802 
803 	vfs_mark_atime(imgp->vp, td->td_ucred);
804 
805 	SDT_PROBE(proc, kernel, , exec_success, args->fname, 0, 0, 0, 0);
806 
807 done1:
808 	/*
809 	 * Free any resources malloc'd earlier that we didn't use.
810 	 */
811 	uifree(euip);
812 	if (newcred == NULL)
813 		crfree(oldcred);
814 	else
815 		crfree(newcred);
816 	VOP_UNLOCK(imgp->vp, 0);
817 
818 	/*
819 	 * Handle deferred decrement of ref counts.
820 	 */
821 	if (textvp != NULL) {
822 		int tvfslocked;
823 
824 		tvfslocked = VFS_LOCK_GIANT(textvp->v_mount);
825 		vrele(textvp);
826 		VFS_UNLOCK_GIANT(tvfslocked);
827 	}
828 	if (binvp && error != 0)
829 		vrele(binvp);
830 #ifdef KTRACE
831 	if (tracevp != NULL) {
832 		int tvfslocked;
833 
834 		tvfslocked = VFS_LOCK_GIANT(tracevp->v_mount);
835 		vrele(tracevp);
836 		VFS_UNLOCK_GIANT(tvfslocked);
837 	}
838 	if (tracecred != NULL)
839 		crfree(tracecred);
840 #endif
841 	vn_lock(imgp->vp, LK_EXCLUSIVE | LK_RETRY);
842 	pargs_drop(oldargs);
843 	pargs_drop(newargs);
844 	if (oldsigacts != NULL)
845 		sigacts_free(oldsigacts);
846 
847 exec_fail_dealloc:
848 
849 	/*
850 	 * free various allocated resources
851 	 */
852 	if (imgp->firstpage != NULL)
853 		exec_unmap_first_page(imgp);
854 
855 	if (imgp->vp != NULL) {
856 		if (args->fname)
857 			NDFREE(&nd, NDF_ONLY_PNBUF);
858 		if (imgp->opened)
859 			VOP_CLOSE(imgp->vp, FREAD, td->td_ucred, td);
860 		vput(imgp->vp);
861 	}
862 
863 	if (imgp->object != NULL)
864 		vm_object_deallocate(imgp->object);
865 
866 	free(imgp->freepath, M_TEMP);
867 
868 	if (error == 0) {
869 		PROC_LOCK(p);
870 		td->td_dbgflags |= TDB_EXEC;
871 		PROC_UNLOCK(p);
872 
873 		/*
874 		 * Stop the process here if its stop event mask has
875 		 * the S_EXEC bit set.
876 		 */
877 		STOPEVENT(p, S_EXEC, 0);
878 		goto done2;
879 	}
880 
881 exec_fail:
882 	/* we're done here, clear P_INEXEC */
883 	PROC_LOCK(p);
884 	p->p_flag &= ~P_INEXEC;
885 	PROC_UNLOCK(p);
886 
887 	SDT_PROBE(proc, kernel, , exec_failure, error, 0, 0, 0, 0);
888 
889 done2:
890 #ifdef MAC
891 	mac_execve_exit(imgp);
892 	mac_execve_interpreter_exit(interpvplabel);
893 #endif
894 	VFS_UNLOCK_GIANT(vfslocked);
895 	exec_free_args(args);
896 
897 	if (error && imgp->vmspace_destroyed) {
898 		/* sorry, no more process anymore. exit gracefully */
899 		exit1(td, W_EXITCODE(0, SIGABRT));
900 		/* NOT REACHED */
901 	}
902 
903 #ifdef KTRACE
904 	if (error == 0)
905 		ktrprocctor(p);
906 #endif
907 
908 	return (error);
909 }
910 
911 int
912 exec_map_first_page(imgp)
913 	struct image_params *imgp;
914 {
915 	int rv, i;
916 	int initial_pagein;
917 	vm_page_t ma[VM_INITIAL_PAGEIN];
918 	vm_object_t object;
919 
920 	if (imgp->firstpage != NULL)
921 		exec_unmap_first_page(imgp);
922 
923 	object = imgp->vp->v_object;
924 	if (object == NULL)
925 		return (EACCES);
926 	VM_OBJECT_LOCK(object);
927 #if VM_NRESERVLEVEL > 0
928 	if ((object->flags & OBJ_COLORED) == 0) {
929 		object->flags |= OBJ_COLORED;
930 		object->pg_color = 0;
931 	}
932 #endif
933 	ma[0] = vm_page_grab(object, 0, VM_ALLOC_NORMAL | VM_ALLOC_RETRY);
934 	if (ma[0]->valid != VM_PAGE_BITS_ALL) {
935 		initial_pagein = VM_INITIAL_PAGEIN;
936 		if (initial_pagein > object->size)
937 			initial_pagein = object->size;
938 		for (i = 1; i < initial_pagein; i++) {
939 			if ((ma[i] = vm_page_next(ma[i - 1])) != NULL) {
940 				if (ma[i]->valid)
941 					break;
942 				if ((ma[i]->oflags & VPO_BUSY) || ma[i]->busy)
943 					break;
944 				vm_page_busy(ma[i]);
945 			} else {
946 				ma[i] = vm_page_alloc(object, i,
947 				    VM_ALLOC_NORMAL | VM_ALLOC_IFNOTCACHED);
948 				if (ma[i] == NULL)
949 					break;
950 			}
951 		}
952 		initial_pagein = i;
953 		rv = vm_pager_get_pages(object, ma, initial_pagein, 0);
954 		ma[0] = vm_page_lookup(object, 0);
955 		if ((rv != VM_PAGER_OK) || (ma[0] == NULL)) {
956 			if (ma[0] != NULL) {
957 				vm_page_lock(ma[0]);
958 				vm_page_free(ma[0]);
959 				vm_page_unlock(ma[0]);
960 			}
961 			VM_OBJECT_UNLOCK(object);
962 			return (EIO);
963 		}
964 	}
965 	vm_page_lock(ma[0]);
966 	vm_page_hold(ma[0]);
967 	vm_page_unlock(ma[0]);
968 	vm_page_wakeup(ma[0]);
969 	VM_OBJECT_UNLOCK(object);
970 
971 	imgp->firstpage = sf_buf_alloc(ma[0], 0);
972 	imgp->image_header = (char *)sf_buf_kva(imgp->firstpage);
973 
974 	return (0);
975 }
976 
977 void
978 exec_unmap_first_page(imgp)
979 	struct image_params *imgp;
980 {
981 	vm_page_t m;
982 
983 	if (imgp->firstpage != NULL) {
984 		m = sf_buf_page(imgp->firstpage);
985 		sf_buf_free(imgp->firstpage);
986 		imgp->firstpage = NULL;
987 		vm_page_lock(m);
988 		vm_page_unhold(m);
989 		vm_page_unlock(m);
990 	}
991 }
992 
993 /*
994  * Destroy old address space, and allocate a new stack
995  *	The new stack is only SGROWSIZ large because it is grown
996  *	automatically in trap.c.
997  */
998 int
999 exec_new_vmspace(imgp, sv)
1000 	struct image_params *imgp;
1001 	struct sysentvec *sv;
1002 {
1003 	int error;
1004 	struct proc *p = imgp->proc;
1005 	struct vmspace *vmspace = p->p_vmspace;
1006 	vm_object_t obj;
1007 	vm_offset_t sv_minuser, stack_addr;
1008 	vm_map_t map;
1009 	u_long ssiz;
1010 
1011 	imgp->vmspace_destroyed = 1;
1012 	imgp->sysent = sv;
1013 
1014 	/* May be called with Giant held */
1015 	EVENTHANDLER_INVOKE(process_exec, p, imgp);
1016 
1017 	/*
1018 	 * Blow away entire process VM, if address space not shared,
1019 	 * otherwise, create a new VM space so that other threads are
1020 	 * not disrupted
1021 	 */
1022 	map = &vmspace->vm_map;
1023 	if (map_at_zero)
1024 		sv_minuser = sv->sv_minuser;
1025 	else
1026 		sv_minuser = MAX(sv->sv_minuser, PAGE_SIZE);
1027 	if (vmspace->vm_refcnt == 1 && vm_map_min(map) == sv_minuser &&
1028 	    vm_map_max(map) == sv->sv_maxuser) {
1029 		shmexit(vmspace);
1030 		pmap_remove_pages(vmspace_pmap(vmspace));
1031 		vm_map_remove(map, vm_map_min(map), vm_map_max(map));
1032 	} else {
1033 		error = vmspace_exec(p, sv_minuser, sv->sv_maxuser);
1034 		if (error)
1035 			return (error);
1036 		vmspace = p->p_vmspace;
1037 		map = &vmspace->vm_map;
1038 	}
1039 
1040 	/* Map a shared page */
1041 	obj = sv->sv_shared_page_obj;
1042 	if (obj != NULL) {
1043 		vm_object_reference(obj);
1044 		error = vm_map_fixed(map, obj, 0,
1045 		    sv->sv_shared_page_base, sv->sv_shared_page_len,
1046 		    VM_PROT_READ | VM_PROT_EXECUTE, VM_PROT_ALL,
1047 		    MAP_COPY_ON_WRITE | MAP_ACC_NO_CHARGE);
1048 		if (error) {
1049 			vm_object_deallocate(obj);
1050 			return (error);
1051 		}
1052 	}
1053 
1054 	/* Allocate a new stack */
1055 	if (sv->sv_maxssiz != NULL)
1056 		ssiz = *sv->sv_maxssiz;
1057 	else
1058 		ssiz = maxssiz;
1059 	stack_addr = sv->sv_usrstack - ssiz;
1060 	error = vm_map_stack(map, stack_addr, (vm_size_t)ssiz,
1061 	    obj != NULL && imgp->stack_prot != 0 ? imgp->stack_prot :
1062 		sv->sv_stackprot,
1063 	    VM_PROT_ALL, MAP_STACK_GROWS_DOWN);
1064 	if (error)
1065 		return (error);
1066 
1067 #ifdef __ia64__
1068 	/* Allocate a new register stack */
1069 	stack_addr = IA64_BACKINGSTORE;
1070 	error = vm_map_stack(map, stack_addr, (vm_size_t)ssiz,
1071 	    sv->sv_stackprot, VM_PROT_ALL, MAP_STACK_GROWS_UP);
1072 	if (error)
1073 		return (error);
1074 #endif
1075 
1076 	/* vm_ssize and vm_maxsaddr are somewhat antiquated concepts in the
1077 	 * VM_STACK case, but they are still used to monitor the size of the
1078 	 * process stack so we can check the stack rlimit.
1079 	 */
1080 	vmspace->vm_ssize = sgrowsiz >> PAGE_SHIFT;
1081 	vmspace->vm_maxsaddr = (char *)sv->sv_usrstack - ssiz;
1082 
1083 	return (0);
1084 }
1085 
1086 /*
1087  * Copy out argument and environment strings from the old process address
1088  * space into the temporary string buffer.
1089  */
1090 int
1091 exec_copyin_args(struct image_args *args, char *fname,
1092     enum uio_seg segflg, char **argv, char **envv)
1093 {
1094 	char *argp, *envp;
1095 	int error;
1096 	size_t length;
1097 
1098 	bzero(args, sizeof(*args));
1099 	if (argv == NULL)
1100 		return (EFAULT);
1101 
1102 	/*
1103 	 * Allocate demand-paged memory for the file name, argument, and
1104 	 * environment strings.
1105 	 */
1106 	error = exec_alloc_args(args);
1107 	if (error != 0)
1108 		return (error);
1109 
1110 	/*
1111 	 * Copy the file name.
1112 	 */
1113 	if (fname != NULL) {
1114 		args->fname = args->buf;
1115 		error = (segflg == UIO_SYSSPACE) ?
1116 		    copystr(fname, args->fname, PATH_MAX, &length) :
1117 		    copyinstr(fname, args->fname, PATH_MAX, &length);
1118 		if (error != 0)
1119 			goto err_exit;
1120 	} else
1121 		length = 0;
1122 
1123 	args->begin_argv = args->buf + length;
1124 	args->endp = args->begin_argv;
1125 	args->stringspace = ARG_MAX;
1126 
1127 	/*
1128 	 * extract arguments first
1129 	 */
1130 	while ((argp = (caddr_t) (intptr_t) fuword(argv++))) {
1131 		if (argp == (caddr_t) -1) {
1132 			error = EFAULT;
1133 			goto err_exit;
1134 		}
1135 		if ((error = copyinstr(argp, args->endp,
1136 		    args->stringspace, &length))) {
1137 			if (error == ENAMETOOLONG)
1138 				error = E2BIG;
1139 			goto err_exit;
1140 		}
1141 		args->stringspace -= length;
1142 		args->endp += length;
1143 		args->argc++;
1144 	}
1145 
1146 	args->begin_envv = args->endp;
1147 
1148 	/*
1149 	 * extract environment strings
1150 	 */
1151 	if (envv) {
1152 		while ((envp = (caddr_t)(intptr_t)fuword(envv++))) {
1153 			if (envp == (caddr_t)-1) {
1154 				error = EFAULT;
1155 				goto err_exit;
1156 			}
1157 			if ((error = copyinstr(envp, args->endp,
1158 			    args->stringspace, &length))) {
1159 				if (error == ENAMETOOLONG)
1160 					error = E2BIG;
1161 				goto err_exit;
1162 			}
1163 			args->stringspace -= length;
1164 			args->endp += length;
1165 			args->envc++;
1166 		}
1167 	}
1168 
1169 	return (0);
1170 
1171 err_exit:
1172 	exec_free_args(args);
1173 	return (error);
1174 }
1175 
1176 /*
1177  * Allocate temporary demand-paged, zero-filled memory for the file name,
1178  * argument, and environment strings.  Returns zero if the allocation succeeds
1179  * and ENOMEM otherwise.
1180  */
1181 int
1182 exec_alloc_args(struct image_args *args)
1183 {
1184 
1185 	args->buf = (char *)kmem_alloc_wait(exec_map, PATH_MAX + ARG_MAX);
1186 	return (args->buf != NULL ? 0 : ENOMEM);
1187 }
1188 
1189 void
1190 exec_free_args(struct image_args *args)
1191 {
1192 
1193 	if (args->buf != NULL) {
1194 		kmem_free_wakeup(exec_map, (vm_offset_t)args->buf,
1195 		    PATH_MAX + ARG_MAX);
1196 		args->buf = NULL;
1197 	}
1198 	if (args->fname_buf != NULL) {
1199 		free(args->fname_buf, M_TEMP);
1200 		args->fname_buf = NULL;
1201 	}
1202 }
1203 
1204 /*
1205  * Copy strings out to the new process address space, constructing new arg
1206  * and env vector tables. Return a pointer to the base so that it can be used
1207  * as the initial stack pointer.
1208  */
1209 register_t *
1210 exec_copyout_strings(imgp)
1211 	struct image_params *imgp;
1212 {
1213 	int argc, envc;
1214 	char **vectp;
1215 	char *stringp, *destp;
1216 	register_t *stack_base;
1217 	struct ps_strings *arginfo;
1218 	struct proc *p;
1219 	size_t execpath_len;
1220 	int szsigcode, szps;
1221 	char canary[sizeof(long) * 8];
1222 
1223 	szps = sizeof(pagesizes[0]) * MAXPAGESIZES;
1224 	/*
1225 	 * Calculate string base and vector table pointers.
1226 	 * Also deal with signal trampoline code for this exec type.
1227 	 */
1228 	if (imgp->execpath != NULL && imgp->auxargs != NULL)
1229 		execpath_len = strlen(imgp->execpath) + 1;
1230 	else
1231 		execpath_len = 0;
1232 	p = imgp->proc;
1233 	szsigcode = 0;
1234 	arginfo = (struct ps_strings *)p->p_sysent->sv_psstrings;
1235 	if (p->p_sysent->sv_sigcode_base == 0) {
1236 		if (p->p_sysent->sv_szsigcode != NULL)
1237 			szsigcode = *(p->p_sysent->sv_szsigcode);
1238 	}
1239 	destp =	(caddr_t)arginfo - szsigcode - SPARE_USRSPACE -
1240 	    roundup(execpath_len, sizeof(char *)) -
1241 	    roundup(sizeof(canary), sizeof(char *)) -
1242 	    roundup(szps, sizeof(char *)) -
1243 	    roundup((ARG_MAX - imgp->args->stringspace), sizeof(char *));
1244 
1245 	/*
1246 	 * install sigcode
1247 	 */
1248 	if (szsigcode != 0)
1249 		copyout(p->p_sysent->sv_sigcode, ((caddr_t)arginfo -
1250 		    szsigcode), szsigcode);
1251 
1252 	/*
1253 	 * Copy the image path for the rtld.
1254 	 */
1255 	if (execpath_len != 0) {
1256 		imgp->execpathp = (uintptr_t)arginfo - szsigcode - execpath_len;
1257 		copyout(imgp->execpath, (void *)imgp->execpathp,
1258 		    execpath_len);
1259 	}
1260 
1261 	/*
1262 	 * Prepare the canary for SSP.
1263 	 */
1264 	arc4rand(canary, sizeof(canary), 0);
1265 	imgp->canary = (uintptr_t)arginfo - szsigcode - execpath_len -
1266 	    sizeof(canary);
1267 	copyout(canary, (void *)imgp->canary, sizeof(canary));
1268 	imgp->canarylen = sizeof(canary);
1269 
1270 	/*
1271 	 * Prepare the pagesizes array.
1272 	 */
1273 	imgp->pagesizes = (uintptr_t)arginfo - szsigcode - execpath_len -
1274 	    roundup(sizeof(canary), sizeof(char *)) - szps;
1275 	copyout(pagesizes, (void *)imgp->pagesizes, szps);
1276 	imgp->pagesizeslen = szps;
1277 
1278 	/*
1279 	 * If we have a valid auxargs ptr, prepare some room
1280 	 * on the stack.
1281 	 */
1282 	if (imgp->auxargs) {
1283 		/*
1284 		 * 'AT_COUNT*2' is size for the ELF Auxargs data. This is for
1285 		 * lower compatibility.
1286 		 */
1287 		imgp->auxarg_size = (imgp->auxarg_size) ? imgp->auxarg_size :
1288 		    (AT_COUNT * 2);
1289 		/*
1290 		 * The '+ 2' is for the null pointers at the end of each of
1291 		 * the arg and env vector sets,and imgp->auxarg_size is room
1292 		 * for argument of Runtime loader.
1293 		 */
1294 		vectp = (char **)(destp - (imgp->args->argc +
1295 		    imgp->args->envc + 2 + imgp->auxarg_size)
1296 		    * sizeof(char *));
1297 	} else {
1298 		/*
1299 		 * The '+ 2' is for the null pointers at the end of each of
1300 		 * the arg and env vector sets
1301 		 */
1302 		vectp = (char **)(destp - (imgp->args->argc + imgp->args->envc + 2) *
1303 		    sizeof(char *));
1304 	}
1305 
1306 	/*
1307 	 * vectp also becomes our initial stack base
1308 	 */
1309 	stack_base = (register_t *)vectp;
1310 
1311 	stringp = imgp->args->begin_argv;
1312 	argc = imgp->args->argc;
1313 	envc = imgp->args->envc;
1314 
1315 	/*
1316 	 * Copy out strings - arguments and environment.
1317 	 */
1318 	copyout(stringp, destp, ARG_MAX - imgp->args->stringspace);
1319 
1320 	/*
1321 	 * Fill in "ps_strings" struct for ps, w, etc.
1322 	 */
1323 	suword(&arginfo->ps_argvstr, (long)(intptr_t)vectp);
1324 	suword32(&arginfo->ps_nargvstr, argc);
1325 
1326 	/*
1327 	 * Fill in argument portion of vector table.
1328 	 */
1329 	for (; argc > 0; --argc) {
1330 		suword(vectp++, (long)(intptr_t)destp);
1331 		while (*stringp++ != 0)
1332 			destp++;
1333 		destp++;
1334 	}
1335 
1336 	/* a null vector table pointer separates the argp's from the envp's */
1337 	suword(vectp++, 0);
1338 
1339 	suword(&arginfo->ps_envstr, (long)(intptr_t)vectp);
1340 	suword32(&arginfo->ps_nenvstr, envc);
1341 
1342 	/*
1343 	 * Fill in environment portion of vector table.
1344 	 */
1345 	for (; envc > 0; --envc) {
1346 		suword(vectp++, (long)(intptr_t)destp);
1347 		while (*stringp++ != 0)
1348 			destp++;
1349 		destp++;
1350 	}
1351 
1352 	/* end of vector table is a null pointer */
1353 	suword(vectp, 0);
1354 
1355 	return (stack_base);
1356 }
1357 
1358 /*
1359  * Check permissions of file to execute.
1360  *	Called with imgp->vp locked.
1361  *	Return 0 for success or error code on failure.
1362  */
1363 int
1364 exec_check_permissions(imgp)
1365 	struct image_params *imgp;
1366 {
1367 	struct vnode *vp = imgp->vp;
1368 	struct vattr *attr = imgp->attr;
1369 	struct thread *td;
1370 	int error;
1371 
1372 	td = curthread;
1373 
1374 	/* Get file attributes */
1375 	error = VOP_GETATTR(vp, attr, td->td_ucred);
1376 	if (error)
1377 		return (error);
1378 
1379 #ifdef MAC
1380 	error = mac_vnode_check_exec(td->td_ucred, imgp->vp, imgp);
1381 	if (error)
1382 		return (error);
1383 #endif
1384 
1385 	/*
1386 	 * 1) Check if file execution is disabled for the filesystem that
1387 	 *    this file resides on.
1388 	 * 2) Ensure that at least one execute bit is on. Otherwise, a
1389 	 *    privileged user will always succeed, and we don't want this
1390 	 *    to happen unless the file really is executable.
1391 	 * 3) Ensure that the file is a regular file.
1392 	 */
1393 	if ((vp->v_mount->mnt_flag & MNT_NOEXEC) ||
1394 	    (attr->va_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) == 0 ||
1395 	    (attr->va_type != VREG))
1396 		return (EACCES);
1397 
1398 	/*
1399 	 * Zero length files can't be exec'd
1400 	 */
1401 	if (attr->va_size == 0)
1402 		return (ENOEXEC);
1403 
1404 	/*
1405 	 *  Check for execute permission to file based on current credentials.
1406 	 */
1407 	error = VOP_ACCESS(vp, VEXEC, td->td_ucred, td);
1408 	if (error)
1409 		return (error);
1410 
1411 	/*
1412 	 * Check number of open-for-writes on the file and deny execution
1413 	 * if there are any.
1414 	 */
1415 	if (vp->v_writecount)
1416 		return (ETXTBSY);
1417 
1418 	/*
1419 	 * Call filesystem specific open routine (which does nothing in the
1420 	 * general case).
1421 	 */
1422 	error = VOP_OPEN(vp, FREAD, td->td_ucred, td, NULL);
1423 	if (error == 0)
1424 		imgp->opened = 1;
1425 	return (error);
1426 }
1427 
1428 /*
1429  * Exec handler registration
1430  */
1431 int
1432 exec_register(execsw_arg)
1433 	const struct execsw *execsw_arg;
1434 {
1435 	const struct execsw **es, **xs, **newexecsw;
1436 	int count = 2;	/* New slot and trailing NULL */
1437 
1438 	if (execsw)
1439 		for (es = execsw; *es; es++)
1440 			count++;
1441 	newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
1442 	if (newexecsw == NULL)
1443 		return (ENOMEM);
1444 	xs = newexecsw;
1445 	if (execsw)
1446 		for (es = execsw; *es; es++)
1447 			*xs++ = *es;
1448 	*xs++ = execsw_arg;
1449 	*xs = NULL;
1450 	if (execsw)
1451 		free(execsw, M_TEMP);
1452 	execsw = newexecsw;
1453 	return (0);
1454 }
1455 
1456 int
1457 exec_unregister(execsw_arg)
1458 	const struct execsw *execsw_arg;
1459 {
1460 	const struct execsw **es, **xs, **newexecsw;
1461 	int count = 1;
1462 
1463 	if (execsw == NULL)
1464 		panic("unregister with no handlers left?\n");
1465 
1466 	for (es = execsw; *es; es++) {
1467 		if (*es == execsw_arg)
1468 			break;
1469 	}
1470 	if (*es == NULL)
1471 		return (ENOENT);
1472 	for (es = execsw; *es; es++)
1473 		if (*es != execsw_arg)
1474 			count++;
1475 	newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
1476 	if (newexecsw == NULL)
1477 		return (ENOMEM);
1478 	xs = newexecsw;
1479 	for (es = execsw; *es; es++)
1480 		if (*es != execsw_arg)
1481 			*xs++ = *es;
1482 	*xs = NULL;
1483 	if (execsw)
1484 		free(execsw, M_TEMP);
1485 	execsw = newexecsw;
1486 	return (0);
1487 }
1488 
1489 static vm_object_t shared_page_obj;
1490 static int shared_page_free;
1491 
1492 int
1493 shared_page_fill(int size, int align, const char *data)
1494 {
1495 	vm_page_t m;
1496 	struct sf_buf *s;
1497 	vm_offset_t sk;
1498 	int res;
1499 
1500 	VM_OBJECT_LOCK(shared_page_obj);
1501 	m = vm_page_grab(shared_page_obj, 0, VM_ALLOC_RETRY);
1502 	res = roundup(shared_page_free, align);
1503 	if (res + size >= IDX_TO_OFF(shared_page_obj->size))
1504 		res = -1;
1505 	else {
1506 		VM_OBJECT_UNLOCK(shared_page_obj);
1507 		s = sf_buf_alloc(m, SFB_DEFAULT);
1508 		sk = sf_buf_kva(s);
1509 		bcopy(data, (void *)(sk + res), size);
1510 		shared_page_free = res + size;
1511 		sf_buf_free(s);
1512 		VM_OBJECT_LOCK(shared_page_obj);
1513 	}
1514 	vm_page_wakeup(m);
1515 	VM_OBJECT_UNLOCK(shared_page_obj);
1516 	return (res);
1517 }
1518 
1519 static void
1520 shared_page_init(void *dummy __unused)
1521 {
1522 	vm_page_t m;
1523 
1524 	shared_page_obj = vm_pager_allocate(OBJT_PHYS, 0, PAGE_SIZE,
1525 	    VM_PROT_DEFAULT, 0, NULL);
1526 	VM_OBJECT_LOCK(shared_page_obj);
1527 	m = vm_page_grab(shared_page_obj, 0, VM_ALLOC_RETRY | VM_ALLOC_NOBUSY |
1528 	    VM_ALLOC_ZERO);
1529 	m->valid = VM_PAGE_BITS_ALL;
1530 	VM_OBJECT_UNLOCK(shared_page_obj);
1531 }
1532 
1533 SYSINIT(shp, SI_SUB_EXEC, SI_ORDER_FIRST, (sysinit_cfunc_t)shared_page_init,
1534     NULL);
1535 
1536 void
1537 exec_sysvec_init(void *param)
1538 {
1539 	struct sysentvec *sv;
1540 
1541 	sv = (struct sysentvec *)param;
1542 
1543 	if ((sv->sv_flags & SV_SHP) == 0)
1544 		return;
1545 	sv->sv_shared_page_obj = shared_page_obj;
1546 	sv->sv_sigcode_base = sv->sv_shared_page_base +
1547 	    shared_page_fill(*(sv->sv_szsigcode), 16, sv->sv_sigcode);
1548 }
1549