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