xref: /netbsd-src/sys/kern/kern_exec.c (revision 7c7c171d130af9949261bc7dce2150a03c3d239c)
1 /*	$NetBSD: kern_exec.c,v 1.90 1998/03/01 02:22:28 fvdl 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_uvm.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 #if defined(UVM)
62 #include <uvm/uvm_extern.h>
63 #endif
64 
65 #include <machine/cpu.h>
66 #include <machine/reg.h>
67 
68 /*
69  * check exec:
70  * given an "executable" described in the exec package's namei info,
71  * see what we can do with it.
72  *
73  * ON ENTRY:
74  *	exec package with appropriate namei info
75  *	proc pointer of exec'ing proc
76  *	NO SELF-LOCKED VNODES
77  *
78  * ON EXIT:
79  *	error:	nothing held, etc.  exec header still allocated.
80  *	ok:	filled exec package, executable's vnode (unlocked).
81  *
82  * EXEC SWITCH ENTRY:
83  * 	Locked vnode to check, exec package, proc.
84  *
85  * EXEC SWITCH EXIT:
86  *	ok:	return 0, filled exec package, executable's vnode (unlocked).
87  *	error:	destructive:
88  *			everything deallocated execept exec header.
89  *		non-destructive:
90  *			error code, executable's vnode (unlocked),
91  *			exec header unmodified.
92  */
93 int
94 check_exec(p, epp)
95 	struct proc *p;
96 	struct exec_package *epp;
97 {
98 	int error, i;
99 	struct vnode *vp;
100 	struct nameidata *ndp;
101 	int resid;
102 
103 	ndp = epp->ep_ndp;
104 	ndp->ni_cnd.cn_nameiop = LOOKUP;
105 	ndp->ni_cnd.cn_flags = FOLLOW | LOCKLEAF | SAVENAME;
106 	/* first get the vnode */
107 	if ((error = namei(ndp)) != 0)
108 		return error;
109 	epp->ep_vp = vp = ndp->ni_vp;
110 
111 	/* check access and type */
112 	if (vp->v_type != VREG) {
113 		error = EACCES;
114 		goto bad1;
115 	}
116 	if ((error = VOP_ACCESS(vp, VEXEC, p->p_ucred, p)) != 0)
117 		goto bad1;
118 
119 	/* get attributes */
120 	if ((error = VOP_GETATTR(vp, epp->ep_vap, p->p_ucred, p)) != 0)
121 		goto bad1;
122 
123 	/* Check mount point */
124 	if (vp->v_mount->mnt_flag & MNT_NOEXEC) {
125 		error = EACCES;
126 		goto bad1;
127 	}
128 	if ((vp->v_mount->mnt_flag & MNT_NOSUID) || (p->p_flag & P_TRACED))
129 		epp->ep_vap->va_mode &= ~(S_ISUID | S_ISGID);
130 
131 	/* try to open it */
132 	if ((error = VOP_OPEN(vp, FREAD, p->p_ucred, p)) != 0)
133 		goto bad1;
134 
135 	/* unlock vp, since we don't need it locked from here on out. */
136 	VOP_UNLOCK(vp, 0);
137 
138 	/* now we have the file, get the exec header */
139 	error = vn_rdwr(UIO_READ, vp, epp->ep_hdr, epp->ep_hdrlen, 0,
140 			UIO_SYSSPACE, 0, p->p_ucred, &resid, p);
141 	if (error)
142 		goto bad2;
143 	epp->ep_hdrvalid = epp->ep_hdrlen - resid;
144 
145 	/*
146 	 * set up the vmcmds for creation of the process
147 	 * address space
148 	 */
149 	error = ENOEXEC;
150 	for (i = 0; i < nexecs && error != 0; i++) {
151 		int newerror;
152 
153 		if (execsw[i].es_check == NULL)
154 			continue;
155 
156 		newerror = (*execsw[i].es_check)(p, epp);
157 		/* make sure the first "interesting" error code is saved. */
158 		if (!newerror || error == ENOEXEC)
159 			error = newerror;
160 		if (epp->ep_flags & EXEC_DESTR && error != 0)
161 			return error;
162 	}
163 	if (!error) {
164 		/* check that entry point is sane */
165 		if (epp->ep_entry > VM_MAXUSER_ADDRESS)
166 			error = ENOEXEC;
167 
168 		/* check limits */
169 		if ((epp->ep_tsize > MAXTSIZ) ||
170 		    (epp->ep_dsize > p->p_rlimit[RLIMIT_DATA].rlim_cur))
171 			error = ENOMEM;
172 
173 		if (!error)
174 			return (0);
175 	}
176 
177 	/*
178 	 * free any vmspace-creation commands,
179 	 * and release their references
180 	 */
181 	kill_vmcmds(&epp->ep_vmcmds);
182 
183 bad2:
184 	/*
185 	 * unlock and close the vnode, restore the old one, free the
186 	 * pathname buf, and punt.
187 	 */
188 	VOP_CLOSE(vp, FREAD, p->p_ucred, p);
189 	vrele(vp);
190 	FREE(ndp->ni_cnd.cn_pnbuf, M_NAMEI);
191 	return error;
192 
193 bad1:
194 	/*
195 	 * free the namei pathname buffer, and put the vnode
196 	 * (which we don't yet have open).
197 	 */
198 	vput(vp);				/* was still locked */
199 	FREE(ndp->ni_cnd.cn_pnbuf, M_NAMEI);
200 	return error;
201 }
202 
203 /*
204  * exec system call
205  */
206 /* ARGSUSED */
207 int
208 sys_execve(p, v, retval)
209 	register struct proc *p;
210 	void *v;
211 	register_t *retval;
212 {
213 	register struct sys_execve_args /* {
214 		syscallarg(const char *) path;
215 		syscallarg(char * const *) argp;
216 		syscallarg(char * const *) envp;
217 	} */ *uap = v;
218 	int error, i;
219 	struct exec_package pack;
220 	struct nameidata nid;
221 	struct vattr attr;
222 	struct ucred *cred = p->p_ucred;
223 	char *argp;
224 	char * const *cpp;
225 	char *dp, *sp;
226 	long argc, envc;
227 	size_t len;
228 	char *stack;
229 	struct ps_strings arginfo;
230 	struct vmspace *vm;
231 	char **tmpfap;
232 	int szsigcode;
233 	extern struct emul emul_netbsd;
234 
235 	/*
236 	 * figure out the maximum size of an exec header, if necessary.
237 	 * XXX should be able to keep LKM code from modifying exec switch
238 	 * when we're still using it, but...
239 	 */
240 	if (exec_maxhdrsz == 0) {
241 		for (i = 0; i < nexecs; i++)
242 			if (execsw[i].es_check != NULL
243 			    && execsw[i].es_hdrsz > exec_maxhdrsz)
244 				exec_maxhdrsz = execsw[i].es_hdrsz;
245 	}
246 
247 	/* init the namei data to point the file user's program name */
248 	/* XXX cgd 960926: why do this here?  most will be clobbered. */
249 	NDINIT(&nid, LOOKUP, NOFOLLOW, UIO_USERSPACE, SCARG(uap, path), p);
250 
251 	/*
252 	 * initialize the fields of the exec package.
253 	 */
254 	pack.ep_name = SCARG(uap, path);
255 	MALLOC(pack.ep_hdr, void *, exec_maxhdrsz, M_EXEC, M_WAITOK);
256 	pack.ep_hdrlen = exec_maxhdrsz;
257 	pack.ep_hdrvalid = 0;
258 	pack.ep_ndp = &nid;
259 	pack.ep_emul_arg = NULL;
260 	pack.ep_vmcmds.evs_cnt = 0;
261 	pack.ep_vmcmds.evs_used = 0;
262 	pack.ep_vap = &attr;
263 	pack.ep_emul = &emul_netbsd;
264 	pack.ep_flags = 0;
265 
266 	/* see if we can run it. */
267 	if ((error = check_exec(p, &pack)) != 0)
268 		goto freehdr;
269 
270 	/* XXX -- THE FOLLOWING SECTION NEEDS MAJOR CLEANUP */
271 
272 	/* allocate an argument buffer */
273 #if defined(UVM)
274 	argp = (char *) uvm_km_valloc_wait(exec_map, NCARGS);
275 #else
276 	argp = (char *) kmem_alloc_wait(exec_map, NCARGS);
277 #endif
278 #ifdef DIAGNOSTIC
279 	if (argp == (vm_offset_t) 0)
280 		panic("execve: argp == NULL");
281 #endif
282 	dp = argp;
283 	argc = 0;
284 
285 	/* copy the fake args list, if there's one, freeing it as we go */
286 	if (pack.ep_flags & EXEC_HASARGL) {
287 		tmpfap = pack.ep_fa;
288 		while (*tmpfap != NULL) {
289 			char *cp;
290 
291 			cp = *tmpfap;
292 			while (*cp)
293 				*dp++ = *cp++;
294 			dp++;
295 
296 			FREE(*tmpfap, M_EXEC);
297 			tmpfap++; argc++;
298 		}
299 		FREE(pack.ep_fa, M_EXEC);
300 		pack.ep_flags &= ~EXEC_HASARGL;
301 	}
302 
303 	/* Now get argv & environment */
304 	if (!(cpp = SCARG(uap, argp))) {
305 		error = EINVAL;
306 		goto bad;
307 	}
308 
309 	if (pack.ep_flags & EXEC_SKIPARG)
310 		cpp++;
311 
312 	while (1) {
313 		len = argp + ARG_MAX - dp;
314 		if ((error = copyin(cpp, &sp, sizeof(sp))) != 0)
315 			goto bad;
316 		if (!sp)
317 			break;
318 		if ((error = copyinstr(sp, dp, len, &len)) != 0) {
319 			if (error == ENAMETOOLONG)
320 				error = E2BIG;
321 			goto bad;
322 		}
323 		dp += len;
324 		cpp++;
325 		argc++;
326 	}
327 
328 	envc = 0;
329 	/* environment need not be there */
330 	if ((cpp = SCARG(uap, envp)) != NULL ) {
331 		while (1) {
332 			len = argp + ARG_MAX - dp;
333 			if ((error = copyin(cpp, &sp, sizeof(sp))) != 0)
334 				goto bad;
335 			if (!sp)
336 				break;
337 			if ((error = copyinstr(sp, dp, len, &len)) != 0) {
338 				if (error == ENAMETOOLONG)
339 					error = E2BIG;
340 				goto bad;
341 			}
342 			dp += len;
343 			cpp++;
344 			envc++;
345 		}
346 	}
347 
348 	dp = (char *) ALIGN(dp);
349 
350 	szsigcode = pack.ep_emul->e_esigcode - pack.ep_emul->e_sigcode;
351 
352 	/* Now check if args & environ fit into new stack */
353 	len = ((argc + envc + 2 + pack.ep_emul->e_arglen) * sizeof(char *) +
354 	    sizeof(long) + 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 #if defined(UVM)
373 	uvmspace_exec(p);
374 #else
375 	vmspace_exec(p);
376 #endif
377 
378 	/* Now map address space */
379 	vm = p->p_vmspace;
380 	vm->vm_taddr = (char *) pack.ep_taddr;
381 	vm->vm_tsize = btoc(pack.ep_tsize);
382 	vm->vm_daddr = (char *) pack.ep_daddr;
383 	vm->vm_dsize = btoc(pack.ep_dsize);
384 	vm->vm_ssize = btoc(pack.ep_ssize);
385 	vm->vm_maxsaddr = (char *) pack.ep_maxsaddr;
386 
387 	/* create the new process's VM space by running the vmcmds */
388 #ifdef DIAGNOSTIC
389 	if (pack.ep_vmcmds.evs_used == 0)
390 		panic("execve: no vmcmds");
391 #endif
392 	for (i = 0; i < pack.ep_vmcmds.evs_used && !error; i++) {
393 		struct exec_vmcmd *vcp;
394 
395 		vcp = &pack.ep_vmcmds.evs_cmds[i];
396 		error = (*vcp->ev_proc)(p, vcp);
397 	}
398 
399 	/* free the vmspace-creation commands, and release their references */
400 	kill_vmcmds(&pack.ep_vmcmds);
401 
402 	/* if an error happened, deallocate and punt */
403 	if (error)
404 		goto exec_abort;
405 
406 	/* remember information about the process */
407 	arginfo.ps_nargvstr = argc;
408 	arginfo.ps_nenvstr = envc;
409 
410 	stack = (char *) (USRSTACK - len);
411 	/* Now copy argc, args & environ to new stack */
412 	if (!(*pack.ep_emul->e_copyargs)(&pack, &arginfo, stack, argp))
413 		goto exec_abort;
414 
415 	/* copy out the process's ps_strings structure */
416 	if (copyout(&arginfo, (char *) PS_STRINGS, sizeof(arginfo)))
417 		goto exec_abort;
418 
419 	/* copy out the process's signal trapoline code */
420 	if (szsigcode && copyout((char *) pack.ep_emul->e_sigcode,
421 				 ((char *) PS_STRINGS) - szsigcode,
422 				 szsigcode))
423 		goto exec_abort;
424 
425 	fdcloseexec(p);		/* handle close on exec */
426 	execsigs(p);		/* reset catched signals */
427 
428 	/* set command name & other accounting info */
429 	len = min(nid.ni_cnd.cn_namelen, MAXCOMLEN);
430 	bcopy(nid.ni_cnd.cn_nameptr, p->p_comm, len);
431 	p->p_comm[len] = 0;
432 	p->p_acflag &= ~AFORK;
433 
434 	/* record proc's vnode, for use by procfs and others */
435         if (p->p_textvp)
436                 vrele(p->p_textvp);
437 	VREF(pack.ep_vp);
438 	p->p_textvp = pack.ep_vp;
439 
440 	p->p_flag |= P_EXEC;
441 	if (p->p_flag & P_PPWAIT) {
442 		p->p_flag &= ~P_PPWAIT;
443 		wakeup((caddr_t) p->p_pptr);
444 	}
445 
446 	/*
447 	 * deal with set[ug]id.
448 	 * MNT_NOEXEC and P_TRACED have already been used to disable s[ug]id.
449 	 */
450 	if (((attr.va_mode & S_ISUID) != 0 && p->p_ucred->cr_uid != attr.va_uid)
451 	 || ((attr.va_mode & S_ISGID) != 0 && p->p_ucred->cr_gid != attr.va_gid)){
452 		p->p_ucred = crcopy(cred);
453 #ifdef KTRACE
454 		/*
455 		 * If process is being ktraced, turn off - unless
456 		 * root set it.
457 		 */
458 		if (p->p_tracep && !(p->p_traceflag & KTRFAC_ROOT)) {
459 			vrele(p->p_tracep);
460 			p->p_tracep = NULL;
461 			p->p_traceflag = 0;
462 		}
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, (vm_offset_t) argp, NCARGS);
476 #else
477 	kmem_free_wakeup(exec_map, (vm_offset_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_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, (vm_offset_t) argp, NCARGS);
514 #else
515 	kmem_free_wakeup(exec_map, (vm_offset_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, (vm_offset_t) argp, NCARGS);
542 #else
543 	kmem_free_wakeup(exec_map, (vm_offset_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