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