xref: /netbsd-src/sys/kern/kern_exec.c (revision 4472dbe5e3bd91ef2540bada7a7ca7384627ff9b)
1 /*	$NetBSD: kern_exec.c,v 1.110 2000/05/27 00:40:45 sommerfeld Exp $	*/
2 
3 /*-
4  * Copyright (C) 1993, 1994, 1996 Christopher G. Demetriou
5  * Copyright (C) 1992 Wolfgang Solfrank.
6  * Copyright (C) 1992 TooLs GmbH.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. All advertising materials mentioning features or use of this software
18  *    must display the following acknowledgement:
19  *	This product includes software developed by TooLs GmbH.
20  * 4. The name of TooLs GmbH may not be used to endorse or promote products
21  *    derived from this software without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``AS IS'' AND ANY EXPRESS OR
24  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
26  * IN NO EVENT SHALL TOOLS GMBH BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
27  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
28  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
29  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
30  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
31  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
32  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33  */
34 
35 #include "opt_ktrace.h"
36 
37 #include <sys/param.h>
38 #include <sys/systm.h>
39 #include <sys/filedesc.h>
40 #include <sys/kernel.h>
41 #include <sys/proc.h>
42 #include <sys/mount.h>
43 #include <sys/malloc.h>
44 #include <sys/namei.h>
45 #include <sys/vnode.h>
46 #include <sys/file.h>
47 #include <sys/acct.h>
48 #include <sys/exec.h>
49 #include <sys/ktrace.h>
50 #include <sys/resourcevar.h>
51 #include <sys/wait.h>
52 #include <sys/mman.h>
53 #include <sys/signalvar.h>
54 #include <sys/stat.h>
55 
56 #include <sys/syscallargs.h>
57 
58 #include <vm/vm.h>
59 #include <vm/vm_kern.h>
60 
61 #include <uvm/uvm_extern.h>
62 
63 #include <machine/cpu.h>
64 #include <machine/reg.h>
65 
66 /*
67  * check exec:
68  * given an "executable" described in the exec package's namei info,
69  * see what we can do with it.
70  *
71  * ON ENTRY:
72  *	exec package with appropriate namei info
73  *	proc pointer of exec'ing proc
74  *	NO SELF-LOCKED VNODES
75  *
76  * ON EXIT:
77  *	error:	nothing held, etc.  exec header still allocated.
78  *	ok:	filled exec package, executable's vnode (unlocked).
79  *
80  * EXEC SWITCH ENTRY:
81  * 	Locked vnode to check, exec package, proc.
82  *
83  * EXEC SWITCH EXIT:
84  *	ok:	return 0, filled exec package, executable's vnode (unlocked).
85  *	error:	destructive:
86  *			everything deallocated execept exec header.
87  *		non-destructive:
88  *			error code, executable's vnode (unlocked),
89  *			exec header unmodified.
90  */
91 int
92 check_exec(p, epp)
93 	struct proc *p;
94 	struct exec_package *epp;
95 {
96 	int error, i;
97 	struct vnode *vp;
98 	struct nameidata *ndp;
99 	size_t resid;
100 
101 	ndp = epp->ep_ndp;
102 	ndp->ni_cnd.cn_nameiop = LOOKUP;
103 	ndp->ni_cnd.cn_flags = FOLLOW | LOCKLEAF | SAVENAME;
104 	/* first get the vnode */
105 	if ((error = namei(ndp)) != 0)
106 		return error;
107 	epp->ep_vp = vp = ndp->ni_vp;
108 
109 	/* check access and type */
110 	if (vp->v_type != VREG) {
111 		error = EACCES;
112 		goto bad1;
113 	}
114 	if ((error = VOP_ACCESS(vp, VEXEC, p->p_ucred, p)) != 0)
115 		goto bad1;
116 
117 	/* get attributes */
118 	if ((error = VOP_GETATTR(vp, epp->ep_vap, p->p_ucred, p)) != 0)
119 		goto bad1;
120 
121 	/* Check mount point */
122 	if (vp->v_mount->mnt_flag & MNT_NOEXEC) {
123 		error = EACCES;
124 		goto bad1;
125 	}
126 	if ((vp->v_mount->mnt_flag & MNT_NOSUID) || (p->p_flag & P_TRACED))
127 		epp->ep_vap->va_mode &= ~(S_ISUID | S_ISGID);
128 
129 	/* try to open it */
130 	if ((error = VOP_OPEN(vp, FREAD, p->p_ucred, p)) != 0)
131 		goto bad1;
132 
133 	/* unlock vp, since we need it unlocked from here on out. */
134 	VOP_UNLOCK(vp, 0);
135 
136 	/* now we have the file, get the exec header */
137 	error = vn_rdwr(UIO_READ, vp, epp->ep_hdr, epp->ep_hdrlen, 0,
138 			UIO_SYSSPACE, 0, p->p_ucred, &resid, p);
139 	if (error)
140 		goto bad2;
141 	epp->ep_hdrvalid = epp->ep_hdrlen - resid;
142 
143 	/*
144 	 * set up the vmcmds for creation of the process
145 	 * address space
146 	 */
147 	error = ENOEXEC;
148 	for (i = 0; i < nexecs && error != 0; i++) {
149 		int newerror;
150 
151 		if (execsw[i].es_check == NULL)
152 			continue;
153 
154 		newerror = (*execsw[i].es_check)(p, epp);
155 		/* make sure the first "interesting" error code is saved. */
156 		if (!newerror || error == ENOEXEC)
157 			error = newerror;
158 		if (epp->ep_flags & EXEC_DESTR && error != 0)
159 			return error;
160 	}
161 	if (!error) {
162 		/* check that entry point is sane */
163 		if (epp->ep_entry > VM_MAXUSER_ADDRESS)
164 			error = ENOEXEC;
165 
166 		/* check limits */
167 		if ((epp->ep_tsize > MAXTSIZ) ||
168 		    (epp->ep_dsize > p->p_rlimit[RLIMIT_DATA].rlim_cur))
169 			error = ENOMEM;
170 
171 		if (!error)
172 			return (0);
173 	}
174 
175 	/*
176 	 * free any vmspace-creation commands,
177 	 * and release their references
178 	 */
179 	kill_vmcmds(&epp->ep_vmcmds);
180 
181 bad2:
182 	/*
183 	 * close and release the vnode, restore the old one, free the
184 	 * pathname buf, and punt.
185 	 */
186 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
187 	VOP_CLOSE(vp, FREAD, p->p_ucred, p);
188 	vput(vp);
189 	FREE(ndp->ni_cnd.cn_pnbuf, M_NAMEI);
190 	return error;
191 
192 bad1:
193 	/*
194 	 * free the namei pathname buffer, and put the vnode
195 	 * (which we don't yet have open).
196 	 */
197 	vput(vp);				/* was still locked */
198 	FREE(ndp->ni_cnd.cn_pnbuf, M_NAMEI);
199 	return error;
200 }
201 
202 /*
203  * exec system call
204  */
205 /* ARGSUSED */
206 int
207 sys_execve(p, v, retval)
208 	struct proc *p;
209 	void *v;
210 	register_t *retval;
211 {
212 	struct sys_execve_args /* {
213 		syscallarg(const char *) path;
214 		syscallarg(char * const *) argp;
215 		syscallarg(char * const *) envp;
216 	} */ *uap = v;
217 	int error, i;
218 	struct exec_package pack;
219 	struct nameidata nid;
220 	struct vattr attr;
221 	struct ucred *cred = p->p_ucred;
222 	char *argp;
223 	char * const *cpp;
224 	char *dp, *sp;
225 	long argc, envc;
226 	size_t len;
227 	char *stack;
228 	struct ps_strings arginfo;
229 	struct vmspace *vm;
230 	char **tmpfap;
231 	int szsigcode;
232 	extern struct emul emul_netbsd;
233 
234 	/*
235 	 * figure out the maximum size of an exec header, if necessary.
236 	 * XXX should be able to keep LKM code from modifying exec switch
237 	 * when we're still using it, but...
238 	 */
239 	if (exec_maxhdrsz == 0) {
240 		for (i = 0; i < nexecs; i++)
241 			if (execsw[i].es_check != NULL
242 			    && execsw[i].es_hdrsz > exec_maxhdrsz)
243 				exec_maxhdrsz = execsw[i].es_hdrsz;
244 	}
245 
246 	/* init the namei data to point the file user's program name */
247 	/* XXX cgd 960926: why do this here?  most will be clobbered. */
248 	NDINIT(&nid, LOOKUP, NOFOLLOW, UIO_USERSPACE, SCARG(uap, path), p);
249 
250 	/*
251 	 * initialize the fields of the exec package.
252 	 */
253 	pack.ep_name = SCARG(uap, path);
254 	MALLOC(pack.ep_hdr, void *, exec_maxhdrsz, M_EXEC, M_WAITOK);
255 	pack.ep_hdrlen = exec_maxhdrsz;
256 	pack.ep_hdrvalid = 0;
257 	pack.ep_ndp = &nid;
258 	pack.ep_emul_arg = NULL;
259 	pack.ep_vmcmds.evs_cnt = 0;
260 	pack.ep_vmcmds.evs_used = 0;
261 	pack.ep_vap = &attr;
262 	pack.ep_emul = &emul_netbsd;
263 	pack.ep_flags = 0;
264 
265 	/* see if we can run it. */
266 	if ((error = check_exec(p, &pack)) != 0)
267 		goto freehdr;
268 
269 	/* XXX -- THE FOLLOWING SECTION NEEDS MAJOR CLEANUP */
270 
271 	/* allocate an argument buffer */
272 	argp = (char *) uvm_km_valloc_wait(exec_map, NCARGS);
273 #ifdef DIAGNOSTIC
274 	if (argp == (vaddr_t) 0)
275 		panic("execve: argp == NULL");
276 #endif
277 	dp = argp;
278 	argc = 0;
279 
280 	/* copy the fake args list, if there's one, freeing it as we go */
281 	if (pack.ep_flags & EXEC_HASARGL) {
282 		tmpfap = pack.ep_fa;
283 		while (*tmpfap != NULL) {
284 			char *cp;
285 
286 			cp = *tmpfap;
287 			while (*cp)
288 				*dp++ = *cp++;
289 			dp++;
290 
291 			FREE(*tmpfap, M_EXEC);
292 			tmpfap++; argc++;
293 		}
294 		FREE(pack.ep_fa, M_EXEC);
295 		pack.ep_flags &= ~EXEC_HASARGL;
296 	}
297 
298 	/* Now get argv & environment */
299 	if (!(cpp = SCARG(uap, argp))) {
300 		error = EINVAL;
301 		goto bad;
302 	}
303 
304 	if (pack.ep_flags & EXEC_SKIPARG)
305 		cpp++;
306 
307 	while (1) {
308 		len = argp + ARG_MAX - dp;
309 		if ((error = copyin(cpp, &sp, sizeof(sp))) != 0)
310 			goto bad;
311 		if (!sp)
312 			break;
313 		if ((error = copyinstr(sp, dp, len, &len)) != 0) {
314 			if (error == ENAMETOOLONG)
315 				error = E2BIG;
316 			goto bad;
317 		}
318 		dp += len;
319 		cpp++;
320 		argc++;
321 	}
322 
323 	envc = 0;
324 	/* environment need not be there */
325 	if ((cpp = SCARG(uap, envp)) != NULL ) {
326 		while (1) {
327 			len = argp + ARG_MAX - dp;
328 			if ((error = copyin(cpp, &sp, sizeof(sp))) != 0)
329 				goto bad;
330 			if (!sp)
331 				break;
332 			if ((error = copyinstr(sp, dp, len, &len)) != 0) {
333 				if (error == ENAMETOOLONG)
334 					error = E2BIG;
335 				goto bad;
336 			}
337 			dp += len;
338 			cpp++;
339 			envc++;
340 		}
341 	}
342 
343 	dp = (char *) ALIGN(dp);
344 
345 	szsigcode = pack.ep_emul->e_esigcode - pack.ep_emul->e_sigcode;
346 
347 	/* Now check if args & environ fit into new stack */
348 	if (pack.ep_flags & EXEC_32)
349 		len = ((argc + envc + 2 + pack.ep_emul->e_arglen) * sizeof(int) +
350 		       sizeof(int) + dp + STACKGAPLEN + szsigcode +
351 		       sizeof(struct ps_strings)) - argp;
352 	else
353 		len = ((argc + envc + 2 + pack.ep_emul->e_arglen) * sizeof(char *) +
354 		       sizeof(int) + dp + STACKGAPLEN + szsigcode +
355 		       sizeof(struct ps_strings)) - argp;
356 
357 	len = ALIGN(len);	/* make the stack "safely" aligned */
358 
359 	if (len > pack.ep_ssize) { /* in effect, compare to initial limit */
360 		error = ENOMEM;
361 		goto bad;
362 	}
363 
364 	/* adjust "active stack depth" for process VSZ */
365 	pack.ep_ssize = len;	/* maybe should go elsewhere, but... */
366 
367 	/*
368 	 * Do whatever is necessary to prepare the address space
369 	 * for remapping.  Note that this might replace the current
370 	 * vmspace with another!
371 	 */
372 	uvmspace_exec(p);
373 
374 	/* Now map address space */
375 	vm = p->p_vmspace;
376 	vm->vm_taddr = (char *) pack.ep_taddr;
377 	vm->vm_tsize = btoc(pack.ep_tsize);
378 	vm->vm_daddr = (char *) pack.ep_daddr;
379 	vm->vm_dsize = btoc(pack.ep_dsize);
380 	vm->vm_ssize = btoc(pack.ep_ssize);
381 	vm->vm_maxsaddr = (char *) pack.ep_maxsaddr;
382 
383 	/* create the new process's VM space by running the vmcmds */
384 #ifdef DIAGNOSTIC
385 	if (pack.ep_vmcmds.evs_used == 0)
386 		panic("execve: no vmcmds");
387 #endif
388 	for (i = 0; i < pack.ep_vmcmds.evs_used && !error; i++) {
389 		struct exec_vmcmd *vcp;
390 
391 		vcp = &pack.ep_vmcmds.evs_cmds[i];
392 		error = (*vcp->ev_proc)(p, vcp);
393 	}
394 
395 	/* free the vmspace-creation commands, and release their references */
396 	kill_vmcmds(&pack.ep_vmcmds);
397 
398 	/* if an error happened, deallocate and punt */
399 	if (error)
400 		goto exec_abort;
401 
402 	/* remember information about the process */
403 	arginfo.ps_nargvstr = argc;
404 	arginfo.ps_nenvstr = envc;
405 
406 	stack = (char *) (USRSTACK - len);
407 	/* Now copy argc, args & environ to new stack */
408 	if (!(*pack.ep_emul->e_copyargs)(&pack, &arginfo, stack, argp))
409 		goto exec_abort;
410 
411 	/* copy out the process's ps_strings structure */
412 	if (copyout(&arginfo, (char *) PS_STRINGS, sizeof(arginfo)))
413 		goto exec_abort;
414 
415 	/* fill process ps_strings info */
416 	p->p_psstr = PS_STRINGS;
417 	p->p_psargv = offsetof(struct ps_strings, ps_argvstr);
418 	p->p_psnargv = offsetof(struct ps_strings, ps_nargvstr);
419 	p->p_psenv = offsetof(struct ps_strings, ps_envstr);
420 	p->p_psnenv = offsetof(struct ps_strings, ps_nenvstr);
421 
422 	/* copy out the process's signal trapoline code */
423 	if (szsigcode) {
424 		if (copyout((char *)pack.ep_emul->e_sigcode,
425 		    p->p_sigacts->ps_sigcode = (char *)PS_STRINGS - szsigcode,
426 		    szsigcode))
427 			goto exec_abort;
428 #ifdef PMAP_NEED_PROCWR
429 		/* This is code. Let the pmap do what is needed. */
430 		pmap_procwr(p, (vaddr_t)p->p_sigacts->ps_sigcode, szsigcode);
431 #endif
432 	}
433 
434 	stopprofclock(p);	/* stop profiling */
435 	fdcloseexec(p);		/* handle close on exec */
436 	execsigs(p);		/* reset catched signals */
437 	p->p_ctxlink = NULL;	/* reset ucontext link */
438 
439 	/* set command name & other accounting info */
440 	len = min(nid.ni_cnd.cn_namelen, MAXCOMLEN);
441 	memcpy(p->p_comm, nid.ni_cnd.cn_nameptr, len);
442 	p->p_comm[len] = 0;
443 	p->p_acflag &= ~AFORK;
444 
445 	/* record proc's vnode, for use by procfs and others */
446         if (p->p_textvp)
447                 vrele(p->p_textvp);
448 	VREF(pack.ep_vp);
449 	p->p_textvp = pack.ep_vp;
450 
451 	p->p_flag |= P_EXEC;
452 	if (p->p_flag & P_PPWAIT) {
453 		p->p_flag &= ~P_PPWAIT;
454 		wakeup((caddr_t) p->p_pptr);
455 	}
456 
457 	/*
458 	 * deal with set[ug]id.
459 	 * MNT_NOSUID and P_TRACED have already been used to disable s[ug]id.
460 	 */
461 	if (((attr.va_mode & S_ISUID) != 0 && p->p_ucred->cr_uid != attr.va_uid)
462 	 || ((attr.va_mode & S_ISGID) != 0 && p->p_ucred->cr_gid != attr.va_gid)){
463 		p->p_ucred = crcopy(cred);
464 #ifdef KTRACE
465 		/*
466 		 * If process is being ktraced, turn off - unless
467 		 * root set it.
468 		 */
469 		if (p->p_tracep && !(p->p_traceflag & KTRFAC_ROOT))
470 			ktrderef(p);
471 #endif
472 		if (attr.va_mode & S_ISUID)
473 			p->p_ucred->cr_uid = attr.va_uid;
474 		if (attr.va_mode & S_ISGID)
475 			p->p_ucred->cr_gid = attr.va_gid;
476 		p_sugid(p);
477 	} else
478 		p->p_flag &= ~P_SUGID;
479 	p->p_cred->p_svuid = p->p_ucred->cr_uid;
480 	p->p_cred->p_svgid = p->p_ucred->cr_gid;
481 
482 	doexechooks(p);
483 
484 	uvm_km_free_wakeup(exec_map, (vaddr_t) argp, NCARGS);
485 
486 	FREE(nid.ni_cnd.cn_pnbuf, M_NAMEI);
487 	vn_lock(pack.ep_vp, LK_EXCLUSIVE | LK_RETRY);
488 	VOP_CLOSE(pack.ep_vp, FREAD, cred, p);
489 	vput(pack.ep_vp);
490 
491 	/* setup new registers and do misc. setup. */
492 	(*pack.ep_emul->e_setregs)(p, &pack, (u_long) stack);
493 
494 	if (p->p_flag & P_TRACED)
495 		psignal(p, SIGTRAP);
496 
497 	p->p_emul = pack.ep_emul;
498 	FREE(pack.ep_hdr, M_EXEC);
499 
500 #ifdef KTRACE
501 	if (KTRPOINT(p, KTR_EMUL))
502 		ktremul(p);
503 #endif
504 
505 	return (EJUSTRETURN);
506 
507 bad:
508 	/* free the vmspace-creation commands, and release their references */
509 	kill_vmcmds(&pack.ep_vmcmds);
510 	/* kill any opened file descriptor, if necessary */
511 	if (pack.ep_flags & EXEC_HASFD) {
512 		pack.ep_flags &= ~EXEC_HASFD;
513 		(void) fdrelease(p, pack.ep_fd);
514 	}
515 	/* close and put the exec'd file */
516 	vn_lock(pack.ep_vp, LK_EXCLUSIVE | LK_RETRY);
517 	VOP_CLOSE(pack.ep_vp, FREAD, cred, p);
518 	vput(pack.ep_vp);
519 	FREE(nid.ni_cnd.cn_pnbuf, M_NAMEI);
520 	uvm_km_free_wakeup(exec_map, (vaddr_t) argp, NCARGS);
521 
522 freehdr:
523 	FREE(pack.ep_hdr, M_EXEC);
524 	return error;
525 
526 exec_abort:
527 	/*
528 	 * the old process doesn't exist anymore.  exit gracefully.
529 	 * get rid of the (new) address space we have created, if any, get rid
530 	 * of our namei data and vnode, and exit noting failure
531 	 */
532 	uvm_deallocate(&vm->vm_map, VM_MIN_ADDRESS,
533 		VM_MAXUSER_ADDRESS - VM_MIN_ADDRESS);
534 	if (pack.ep_emul_arg)
535 		FREE(pack.ep_emul_arg, M_TEMP);
536 	FREE(nid.ni_cnd.cn_pnbuf, M_NAMEI);
537 	vn_lock(pack.ep_vp, LK_EXCLUSIVE | LK_RETRY);
538 	VOP_CLOSE(pack.ep_vp, FREAD, cred, p);
539 	vput(pack.ep_vp);
540 	uvm_km_free_wakeup(exec_map, (vaddr_t) argp, NCARGS);
541 	FREE(pack.ep_hdr, M_EXEC);
542 	exit1(p, W_EXITCODE(0, SIGABRT));
543 	exit1(p, -1);
544 
545 	/* NOTREACHED */
546 	return 0;
547 }
548 
549 
550 void *
551 copyargs(pack, arginfo, stack, argp)
552 	struct exec_package *pack;
553 	struct ps_strings *arginfo;
554 	void *stack;
555 	void *argp;
556 {
557 	char **cpp = stack;
558 	char *dp, *sp;
559 	size_t len;
560 	void *nullp = NULL;
561 	int argc = arginfo->ps_nargvstr;
562 	int envc = arginfo->ps_nenvstr;
563 
564 	if (copyout(&argc, cpp++, sizeof(argc)))
565 		return NULL;
566 
567 	dp = (char *) (cpp + argc + envc + 2 + pack->ep_emul->e_arglen);
568 	sp = argp;
569 
570 	/* XXX don't copy them out, remap them! */
571 	arginfo->ps_argvstr = cpp; /* remember location of argv for later */
572 
573 	for (; --argc >= 0; sp += len, dp += len)
574 		if (copyout(&dp, cpp++, sizeof(dp)) ||
575 		    copyoutstr(sp, dp, ARG_MAX, &len))
576 			return NULL;
577 
578 	if (copyout(&nullp, cpp++, sizeof(nullp)))
579 		return NULL;
580 
581 	arginfo->ps_envstr = cpp; /* remember location of envp for later */
582 
583 	for (; --envc >= 0; sp += len, dp += len)
584 		if (copyout(&dp, cpp++, sizeof(dp)) ||
585 		    copyoutstr(sp, dp, ARG_MAX, &len))
586 			return NULL;
587 
588 	if (copyout(&nullp, cpp++, sizeof(nullp)))
589 		return NULL;
590 
591 	return cpp;
592 }
593