xref: /netbsd-src/sys/kern/kern_exec.c (revision 6ea46cb5e46c49111a6ecf3bcbe3c7e2730fe9f6)
1 /*	$NetBSD: kern_exec.c,v 1.55 1994/06/29 06:32:24 cgd Exp $	*/
2 
3 /*-
4  * Copyright (C) 1993, 1994 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 
54 #include <vm/vm.h>
55 #include <vm/vm_kern.h>
56 
57 #include <machine/cpu.h>
58 #include <machine/reg.h>
59 
60 #ifdef COPY_SIGCODE
61 extern char sigcode[], esigcode[];
62 
63 #define	szsigcode	(esigcode - sigcode)
64 #else
65 #define	szsigcode	0
66 #endif
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, one locked vnode.
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, one locked vnode.
87  *	error:	destructive:
88  *			everything deallocated execept exec header.
89  *		non-descructive:
90  *			error code, locked vnode, exec header unmodified
91  */
92 int
93 check_exec(p, epp)
94 	struct proc *p;
95 	struct exec_package *epp;
96 {
97 	int error, i;
98 	struct vnode *vp;
99 	char *cp, *ep, *name;
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))
108 		return error;
109 	epp->ep_vp = vp = ndp->ni_vp;
110 
111 	/* check for regular file */
112 	if (vp->v_type != VREG) {
113 		error = EACCES;
114 		goto bad1;
115 	}
116 
117 	/* get attributes */
118 	if (error = VOP_GETATTR(vp, epp->ep_vap, p->p_ucred, p))
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 &= ~(VSUID | VSGID);
128 
129 	/* check access.  for root we have to see if any exec bit on */
130 	if (error = VOP_ACCESS(vp, VEXEC, p->p_ucred, p))
131 		goto bad1;
132 	if ((epp->ep_vap->va_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) == 0) {
133 		error = EACCES;
134 		goto bad1;
135 	}
136 
137 	/* try to open it */
138 	if (error = VOP_OPEN(vp, FREAD, p->p_ucred, p))
139 		goto bad1;
140 
141 	/* now we have the file, get the exec header */
142 	if (error = vn_rdwr(UIO_READ, vp, epp->ep_hdr, epp->ep_hdrlen, 0,
143 	    UIO_SYSSPACE, IO_NODELOCKED, p->p_ucred, &resid, p))
144 		goto bad2;
145 	epp->ep_hdrvalid = epp->ep_hdrlen - resid;
146 
147 	/*
148 	 * set up the vmcmds for creation of the process
149 	 * address space
150 	 */
151 	error = ENOEXEC;
152 	for (i = 0; i < nexecs && error != 0; i++) {
153 		if (execsw[i].es_check != NULL)
154 			error = (*execsw[i].es_check)(p, epp);
155 		if (epp->ep_flags & EXEC_DESTR && error != 0)
156 			return error;
157 	}
158 	if (!error) {
159 		/* check that entry point is sane */
160 		if (epp->ep_entry > VM_MAXUSER_ADDRESS)
161 			error = ENOEXEC;
162 
163 		/* check limits */
164 		if ((epp->ep_tsize > MAXTSIZ) ||
165 		    (epp->ep_dsize > p->p_rlimit[RLIMIT_DATA].rlim_cur))
166 			error = ENOMEM;
167 
168 		if (!error)
169 			return (0);
170 	}
171 
172 	/*
173 	 * free any vmspace-creation commands,
174 	 * and release their references
175 	 */
176 	kill_vmcmds(&epp->ep_vmcmds);
177 
178 bad2:
179 	/*
180 	 * unlock and close the vnode, restore the old one, free the
181 	 * pathname buf, and punt.
182 	 */
183 	VOP_UNLOCK(vp);
184 	vn_close(vp, FREAD, p->p_ucred, p);
185 	FREE(ndp->ni_cnd.cn_pnbuf, M_NAMEI);
186 	return error;
187 
188 bad1:
189 	/*
190 	 * free the namei pathname buffer, and put the vnode
191 	 * (which we don't yet have open).
192 	 */
193 	FREE(ndp->ni_cnd.cn_pnbuf, M_NAMEI);
194 	vput(vp);
195 	return error;
196 }
197 
198 /*
199  * exec system call
200  */
201 /* ARGSUSED */
202 execve(p, uap, retval)
203 	register struct proc *p;
204 	register struct execve_args *uap;
205 	int *retval;
206 {
207 	int error, i;
208 	struct exec_package pack;
209 	struct nameidata nid;
210 	struct vattr attr;
211 	struct ucred *cred = p->p_ucred;
212 	char *argp;
213 	char **cpp, *dp, *sp, *np;
214 	int argc, envc, len;
215 	char *stack;
216 	struct ps_strings arginfo;
217 	struct vmspace *vm = p->p_vmspace;
218 	char **tmpfap;
219 
220 	/*
221 	 * figure out the maximum size of an exec header, if necessary.
222 	 * XXX should be able to keep LKM code from modifying exec switch
223 	 * when we're still using it, but...
224 	 */
225 	if (exec_maxhdrsz == 0) {
226 		for (i = 0; i < nexecs; i++)
227 			if (execsw[i].es_check != NULL
228 			    && execsw[i].es_hdrsz > exec_maxhdrsz)
229 				exec_maxhdrsz = execsw[i].es_hdrsz;
230 	}
231 
232 	/* init the namei data to point the file user's program name */
233 	NDINIT(&nid, LOOKUP, NOFOLLOW, UIO_USERSPACE, uap->path, p);
234 
235 	/*
236 	 * initialize the fields of the exec package.
237 	 */
238 	pack.ep_name = uap->path;
239 	MALLOC(pack.ep_hdr, void *, exec_maxhdrsz, M_EXEC, M_WAITOK);
240 	pack.ep_hdrlen = exec_maxhdrsz;
241 	pack.ep_hdrvalid = 0;
242 	pack.ep_ndp = &nid;
243 	pack.ep_setup = NULL;	/* assume no setup function */
244 	pack.ep_vmcmds.evs_cnt = 0;
245 	pack.ep_vmcmds.evs_used = 0;
246 	pack.ep_vap = &attr;
247 	pack.ep_emul = EMUL_NETBSD;
248 	pack.ep_flags = 0;
249 
250 	/* see if we can run it. */
251 	if (error = check_exec(p, &pack))
252 		goto freehdr;
253 
254 	/* XXX -- THE FOLLOWING SECTION NEEDS MAJOR CLEANUP */
255 
256 	/* allocate an argument buffer */
257 	argp = (char *) kmem_alloc_wait(exec_map, NCARGS);
258 #ifdef DIAGNOSTIC
259 	if (argp == (vm_offset_t) 0)
260 		panic("execve: argp == NULL");
261 #endif
262 	dp = argp;
263 	argc = 0;
264 
265 	/* copy the fake args list, if there's one, freeing it as we go */
266 	if (pack.ep_flags & EXEC_HASARGL) {
267 		tmpfap = pack.ep_fa;
268 		while (*tmpfap != NULL) {
269 			char *cp;
270 
271 			cp = *tmpfap;
272 			while (*cp)
273 				*dp++ = *cp++;
274 			*dp++;
275 
276 			FREE(*tmpfap, M_EXEC);
277 			tmpfap++; argc++;
278 		}
279 		FREE(pack.ep_fa, M_EXEC);
280 		pack.ep_flags &= ~EXEC_HASARGL;
281 	}
282 
283 	/* Now get argv & environment */
284 	if (!(cpp = uap->argp)) {
285 		error = EINVAL;
286 		goto bad;
287 	}
288 
289 	if (pack.ep_flags & EXEC_SKIPARG)
290 		cpp++;
291 
292 	while (1) {
293 		len = argp + ARG_MAX - dp;
294 		if (error = copyin(cpp, &sp, sizeof(sp)))
295 			goto bad;
296 		if (!sp)
297 			break;
298 		if (error = copyinstr(sp, dp, len, (u_int *) & len)) {
299 			if (error == ENAMETOOLONG)
300 				error = E2BIG;
301 			goto bad;
302 		}
303 		dp += len;
304 		cpp++;
305 		argc++;
306 	}
307 
308 	envc = 0;
309 	if (cpp = uap->envp) {	/* environment need not be there */
310 		while (1) {
311 			len = argp + ARG_MAX - dp;
312 			if (error = copyin(cpp, &sp, sizeof(sp)))
313 				goto bad;
314 			if (!sp)
315 				break;
316 			if (error = copyinstr(sp, dp, len, (u_int *) & len)) {
317 				if (error == ENAMETOOLONG)
318 					error = E2BIG;
319 				goto bad;
320 			}
321 			dp += len;
322 			cpp++;
323 			envc++;
324 		}
325 		dp = (char *) ALIGN(dp);
326 	}
327 
328 	/* Now check if args & environ fit into new stack */
329 	len = ((argc + envc + 2) * sizeof(char *) + sizeof(int) +
330 	    dp + STACKGAPLEN + szsigcode + sizeof(struct ps_strings)) - argp;
331 	len = ALIGN(len);	/* make the stack "safely" aligned */
332 
333 	if (len > pack.ep_ssize) { /* in effect, compare to initial limit */
334 		error = ENOMEM;
335 		goto bad;
336 	}
337 
338 	/* adjust "active stack depth" for process VSZ */
339 	pack.ep_ssize = len;	/* maybe should go elsewhere, but... */
340 
341 	/* Unmap old program */
342 #ifdef sparc
343 	kill_user_windows(p);		/* before stack addresses go away */
344 #endif
345 	/* Kill shared memory and unmap old program */
346 #ifdef SYSVSHM
347 	if (vm->vm_shm)
348 		shmexit(p);
349 #endif
350 	vm_deallocate(&vm->vm_map, VM_MIN_ADDRESS,
351 		VM_MAXUSER_ADDRESS - VM_MIN_ADDRESS);
352 
353 	/* Now map address space */
354 	vm->vm_taddr = (char *) pack.ep_taddr;
355 	vm->vm_tsize = btoc(pack.ep_tsize);
356 	vm->vm_daddr = (char *) pack.ep_daddr;
357 	vm->vm_dsize = btoc(pack.ep_dsize);
358 	vm->vm_ssize = btoc(pack.ep_ssize);
359 	vm->vm_maxsaddr = (char *) pack.ep_maxsaddr;
360 
361 	/* create the new process's VM space by running the vmcmds */
362 #ifdef DIAGNOSTIC
363 	if (pack.ep_vmcmds.evs_used == 0)
364 		panic("execve: no vmcmds");
365 #endif
366 	for (i = 0; i < pack.ep_vmcmds.evs_used && !error; i++) {
367 		struct exec_vmcmd *vcp;
368 
369 		vcp = &pack.ep_vmcmds.evs_cmds[i];
370 		error = (*vcp->ev_proc)(p, vcp);
371 	}
372 
373 	/* free the vmspace-creation commands, and release their references */
374 	kill_vmcmds(&pack.ep_vmcmds);
375 
376 	/* if an error happened, deallocate and punt */
377 	if (error)
378 		goto exec_abort;
379 
380 	/* remember information about the process */
381 	arginfo.ps_nargvstr = argc;
382 	arginfo.ps_nenvstr = envc;
383 
384 	/* Now copy argc, args & environ to new stack */
385 	stack = (char *) (USRSTACK - len);
386 	cpp = (char **) stack;
387 
388 	if (copyout(&argc, cpp++, sizeof(argc)))
389 		goto exec_abort;
390 	dp = (char *) (cpp + argc + envc + 2);
391 
392 	/* XXX don't copy them out, remap them! */
393 	arginfo.ps_argvstr = dp; /* remember location of argv for later */
394 	for (sp = argp; --argc >= 0; sp += len, dp += len) {
395 		len = strlen(sp) + 1;
396 		if (copyout(&dp, cpp++, sizeof(dp))
397 		    || copyoutstr(sp, dp, len, 0))
398 			goto exec_abort;
399 	}
400 	np = 0;
401 	if (copyout(&np, cpp++, sizeof(np)))
402 		goto exec_abort;
403 
404 	arginfo.ps_envstr = dp;	/* remember location of env for later */
405 	for (; --envc >= 0; sp += len, dp += len) {
406 		len = strlen(sp) + 1;
407 		if (copyout(&dp, cpp++, sizeof(dp))
408 		    || copyoutstr(sp, dp, len, 0))
409 			goto exec_abort;
410 	}
411 	if (copyout(&np, cpp, sizeof(np)))
412 		goto exec_abort;
413 
414 	/* copy out the process's ps_strings structure */
415 	if (copyout(&arginfo, (char *) PS_STRINGS, sizeof(arginfo)))
416 		goto exec_abort;
417 
418 #ifdef COPY_SIGCODE
419 	/* copy out the process's signal trapoline code */
420 	if (copyout((char *) sigcode, ((char *) PS_STRINGS) - szsigcode,
421 		szsigcode)) {
422 		goto exec_abort;
423 	}
424 #endif
425 
426 	fdcloseexec(p);		/* handle close on exec */
427 	execsigs(p);		/* reset catched signals */
428 
429 	/* set command name & other accounting info */
430 	len = min(nid.ni_cnd.cn_namelen, MAXCOMLEN);
431 	bcopy(nid.ni_cnd.cn_nameptr, p->p_comm, len);
432 	p->p_comm[len] = 0;
433 	p->p_acflag &= ~AFORK;
434 
435 	/* record proc's vnode, for use by procfs and others */
436         if (p->p_textvp)
437                 vrele(p->p_textvp);
438 	VREF(pack.ep_vp);
439 	p->p_textvp = pack.ep_vp;
440 
441 	p->p_flag |= P_EXEC;
442 	if (p->p_flag & P_PPWAIT) {
443 		p->p_flag &= ~P_PPWAIT;
444 		wakeup((caddr_t) p->p_pptr);
445 	}
446 
447 	/*
448 	 * deal with set[ug]id.
449 	 * MNT_NOEXEC and P_TRACED have already been used to disable s[ug]id.
450 	 */
451 	p->p_flag &= ~P_SUGID;
452 	if (((attr.va_mode & VSUID) != 0 &&
453 	    p->p_ucred->cr_uid != attr.va_uid)
454 	    || (attr.va_mode & VSGID) != 0 &&
455 	    p->p_ucred->cr_gid != attr.va_gid) {
456 		p->p_ucred = crcopy(cred);
457 #ifdef KTRACE
458 		/*
459 		 * If process is being ktraced, turn off - unless
460 		 * root set it.
461 		 */
462 		if (p->p_tracep && !(p->p_traceflag & KTRFAC_ROOT)) {
463 			vrele(p->p_tracep);
464 			p->p_tracep = NULL;
465 			p->p_traceflag = 0;
466 		}
467 #endif
468 		if (attr.va_mode & VSUID)
469 			p->p_ucred->cr_uid = attr.va_uid;
470 		if (attr.va_mode & VSGID)
471 			p->p_ucred->cr_gid = attr.va_gid;
472 		p->p_flag |= P_SUGID;
473 	}
474 	p->p_cred->p_svuid = p->p_ucred->cr_uid;
475 	p->p_cred->p_svgid = p->p_ucred->cr_gid;
476 
477 	kmem_free_wakeup(exec_map, (vm_offset_t) argp, NCARGS);
478 
479 	FREE(nid.ni_cnd.cn_pnbuf, M_NAMEI);
480 	VOP_CLOSE(pack.ep_vp, FREAD, cred, p);
481 	vput(pack.ep_vp);
482 
483 	/* setup new registers and do misc. setup. */
484 	setregs(p, pack.ep_entry, (u_long) stack, retval);
485 	if (pack.ep_setup != NULL)
486 		 (*pack.ep_setup)(p, &pack);
487 
488 	if (p->p_flag & P_TRACED)
489 		psignal(p, SIGTRAP);
490 
491 	p->p_emul = pack.ep_emul;
492 	FREE(pack.ep_hdr, M_EXEC);
493 	return 0;
494 
495 bad:
496 	/* free the vmspace-creation commands, and release their references */
497 	kill_vmcmds(&pack.ep_vmcmds);
498 	/* kill any opened file descriptor, if necessary */
499 	if (pack.ep_flags & EXEC_HASFD) {
500 		pack.ep_flags &= ~EXEC_HASFD;
501 		exec_closefd(p, pack.ep_fd);
502 	}
503 	/* close and put the exec'd file */
504 	VOP_CLOSE(pack.ep_vp, FREAD, cred, p);
505 	vput(pack.ep_vp);
506 	FREE(nid.ni_cnd.cn_pnbuf, M_NAMEI);
507 	kmem_free_wakeup(exec_map, (vm_offset_t) argp, NCARGS);
508 
509 freehdr:
510 	FREE(pack.ep_hdr, M_EXEC);
511 	return error;
512 
513 exec_abort:
514 	/*
515 	 * the old process doesn't exist anymore.  exit gracefully.
516 	 * get rid of the (new) address space we have created, if any, get rid
517 	 * of our namei data and vnode, and exit noting failure
518 	 */
519 	vm_deallocate(&vm->vm_map, VM_MIN_ADDRESS,
520 		VM_MAXUSER_ADDRESS - VM_MIN_ADDRESS);
521 	FREE(nid.ni_cnd.cn_pnbuf, M_NAMEI);
522 	VOP_CLOSE(pack.ep_vp, FREAD, cred, p);
523 	vput(pack.ep_vp);
524 	kmem_free_wakeup(exec_map, (vm_offset_t) argp, NCARGS);
525 	FREE(pack.ep_hdr, M_EXEC);
526 	exit1(p, W_EXITCODE(0, SIGABRT));
527 	exit1(p, -1);
528 
529 	/* NOTREACHED */
530 	return 0;
531 }
532