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