1 /*	$NetBSD: netbsd32_execve.c,v 1.9 2002/03/22 21:36:46 jdolecek Exp $	*/
2 
3 /*
4  * Copyright (c) 1998, 2001 Matthew R. Green
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. The name of the author may not be used to endorse or promote products
16  *    derived from this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
23  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
25  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  */
30 
31 #include <sys/cdefs.h>
32 __KERNEL_RCSID(0, "$NetBSD: netbsd32_execve.c,v 1.9 2002/03/22 21:36:46 jdolecek Exp $");
33 
34 #if defined(_KERNEL_OPT)
35 #include "opt_ktrace.h"
36 #endif
37 
38 #include <sys/param.h>
39 #include <sys/systm.h>
40 #include <sys/malloc.h>
41 #include <sys/mount.h>
42 #include <sys/stat.h>
43 #include <sys/wait.h>
44 #include <sys/ktrace.h>
45 #include <sys/vnode.h>
46 #include <sys/file.h>
47 #include <sys/filedesc.h>
48 #include <sys/namei.h>
49 
50 #include <uvm/uvm_extern.h>
51 
52 #include <sys/syscallargs.h>
53 #include <sys/proc.h>
54 #include <sys/acct.h>
55 #include <sys/exec.h>
56 
57 #include <compat/netbsd32/netbsd32.h>
58 #include <compat/netbsd32/netbsd32_syscall.h>
59 #include <compat/netbsd32/netbsd32_syscallargs.h>
60 
61 /* this is provided by kern/kern_exec.c */
62 extern int exec_maxhdrsz;
63 #if defined(LKM) || defined(_LKM)
64 extern struct lock exec_lock;
65 #endif
66 
67 /*
68  * Need to completly reimplement this syscall due to argument copying.
69  */
70 /* ARGSUSED */
71 int
72 netbsd32_execve(p, v, retval)
73 	struct proc *p;
74 	void *v;
75 	register_t *retval;
76 {
77 	struct netbsd32_execve_args /* {
78 		syscallarg(const netbsd32_charp) path;
79 		syscallarg(netbsd32_charpp) argp;
80 		syscallarg(netbsd32_charpp) envp;
81 	} */ *uap = v;
82 	struct sys_execve_args ua;
83 	caddr_t sg;
84 
85 	NETBSD32TOP_UAP(path, const char);
86 	NETBSD32TOP_UAP(argp, char *);
87 	NETBSD32TOP_UAP(envp, char *);
88 	sg = stackgap_init(p, 0);
89 	CHECK_ALT_EXIST(p, &sg, SCARG(&ua, path));
90 
91 	return netbsd32_execve2(p, &ua, retval);
92 }
93 
94 int
95 netbsd32_execve2(p, uap, retval)
96 	struct proc *p;
97 	struct sys_execve_args *uap;
98 	register_t *retval;
99 {
100 	/* Function args */
101 	int error, i;
102 	struct exec_package pack;
103 	struct nameidata nid;
104 	struct vattr attr;
105 	struct ucred *cred = p->p_ucred;
106 	char *argp;
107 	netbsd32_charp const *cpp;
108 	char *dp;
109 	netbsd32_charp sp;
110 	long argc, envc;
111 	size_t len;
112 	char *stack;
113 	struct ps_strings arginfo;
114 	struct vmspace *vm;
115 	char **tmpfap;
116 	int szsigcode;
117 	struct exec_vmcmd *base_vcp = NULL;
118 
119 	/*
120 	 * Init the namei data to point the file user's program name.
121 	 * This is done here rather than in check_exec(), so that it's
122 	 * possible to override this settings if any of makecmd/probe
123 	 * functions call check_exec() recursively - for example,
124 	 * see exec_script_makecmds().
125 	 */
126 	NDINIT(&nid, LOOKUP, NOFOLLOW, UIO_USERSPACE, SCARG(uap, path), p);
127 
128 	/*
129 	 * initialize the fields of the exec package.
130 	 */
131 	pack.ep_name = SCARG(uap, path);
132 	pack.ep_hdr = malloc(exec_maxhdrsz, M_EXEC, M_WAITOK);
133 	pack.ep_hdrlen = exec_maxhdrsz;
134 	pack.ep_hdrvalid = 0;
135 	pack.ep_ndp = &nid;
136 	pack.ep_emul_arg = NULL;
137 	pack.ep_vmcmds.evs_cnt = 0;
138 	pack.ep_vmcmds.evs_used = 0;
139 	pack.ep_vap = &attr;
140 	pack.ep_flags = 0;
141 
142 #if defined(LKM) || defined(_LKM)
143 	lockmgr(&exec_lock, LK_SHARED, NULL);
144 #endif
145 
146 	/* see if we can run it. */
147 	if ((error = check_exec(p, &pack)) != 0)
148 		goto freehdr;
149 
150 	/* XXX -- THE FOLLOWING SECTION NEEDS MAJOR CLEANUP */
151 
152 	/* allocate an argument buffer */
153 	argp = (char *) uvm_km_valloc_wait(exec_map, NCARGS);
154 #ifdef DIAGNOSTIC
155 	if (argp == (vaddr_t) 0)
156 		panic("netbsd32_execve: argp == NULL");
157 #endif
158 	dp = argp;
159 	argc = 0;
160 
161 	/* copy the fake args list, if there's one, freeing it as we go */
162 	if (pack.ep_flags & EXEC_HASARGL) {
163 		tmpfap = pack.ep_fa;
164 		while (*tmpfap != NULL) {
165 			char *cp;
166 
167 			cp = *tmpfap;
168 			while (*cp)
169 				*dp++ = *cp++;
170 			dp++;
171 
172 			FREE(*tmpfap, M_EXEC);
173 			tmpfap++; argc++;
174 		}
175 		FREE(pack.ep_fa, M_EXEC);
176 		pack.ep_flags &= ~EXEC_HASARGL;
177 	}
178 
179 	/* Now get argv & environment */
180 	if (!(cpp = (netbsd32_charp *)SCARG(uap, argp))) {
181 		error = EINVAL;
182 		goto bad;
183 	}
184 
185 	if (pack.ep_flags & EXEC_SKIPARG)
186 		cpp++;
187 
188 	while (1) {
189 		len = argp + ARG_MAX - dp;
190 		if ((error = copyin(cpp, &sp, sizeof(sp))) != 0)
191 			goto bad;
192 		if (!sp)
193 			break;
194 		if ((error = copyinstr((char *)(u_long)sp, dp,
195 				       len, &len)) != 0) {
196 			if (error == ENAMETOOLONG)
197 				error = E2BIG;
198 			goto bad;
199 		}
200 		dp += len;
201 		cpp++;
202 		argc++;
203 	}
204 
205 	envc = 0;
206 	/* environment need not be there */
207 	if ((cpp = (netbsd32_charp *)SCARG(uap, envp)) != NULL ) {
208 		while (1) {
209 			len = argp + ARG_MAX - dp;
210 			if ((error = copyin(cpp, &sp, sizeof(sp))) != 0)
211 				goto bad;
212 			if (!sp)
213 				break;
214 			if ((error = copyinstr((char *)(u_long)sp,
215 					       dp, len, &len)) != 0) {
216 				if (error == ENAMETOOLONG)
217 					error = E2BIG;
218 				goto bad;
219 			}
220 			dp += len;
221 			cpp++;
222 			envc++;
223 		}
224 	}
225 
226 	dp = (char *) ALIGN(dp);
227 
228 	szsigcode = pack.ep_es->es_emul->e_esigcode -
229 	    pack.ep_es->es_emul->e_sigcode;
230 
231 	/* Now check if args & environ fit into new stack */
232 	if (pack.ep_flags & EXEC_32)
233 		len = ((argc + envc + 2 + pack.ep_es->es_arglen) *
234 		    sizeof(int) + sizeof(int) + dp + STACKGAPLEN +
235 		    szsigcode + sizeof(struct ps_strings)) - argp;
236 	else
237 		len = ((argc + envc + 2 + pack.ep_es->es_arglen) *
238 		    sizeof(char *) + sizeof(int) + dp + STACKGAPLEN +
239 		    szsigcode + sizeof(struct ps_strings)) - argp;
240 
241 	len = ALIGN(len);	/* make the stack "safely" aligned */
242 
243 	if (len > pack.ep_ssize) { /* in effect, compare to initial limit */
244 		error = ENOMEM;
245 		goto bad;
246 	}
247 
248 	/* adjust "active stack depth" for process VSZ */
249 	pack.ep_ssize = len;	/* maybe should go elsewhere, but... */
250 
251 	/*
252 	 * Do whatever is necessary to prepare the address space
253 	 * for remapping.  Note that this might replace the current
254 	 * vmspace with another!
255 	 */
256 	uvmspace_exec(p, VM_MIN_ADDRESS, (vaddr_t)pack.ep_minsaddr);
257 
258 	/* Now map address space */
259 	vm = p->p_vmspace;
260 	vm->vm_taddr = (char *) pack.ep_taddr;
261 	vm->vm_tsize = btoc(pack.ep_tsize);
262 	vm->vm_daddr = (char *) pack.ep_daddr;
263 	vm->vm_dsize = btoc(pack.ep_dsize);
264 	vm->vm_ssize = btoc(pack.ep_ssize);
265 	vm->vm_maxsaddr = (char *) pack.ep_maxsaddr;
266 	vm->vm_minsaddr = (char *) pack.ep_minsaddr;
267 
268 	/* create the new process's VM space by running the vmcmds */
269 #ifdef DIAGNOSTIC
270 	if (pack.ep_vmcmds.evs_used == 0)
271 		panic("netbsd32_execve: no vmcmds");
272 #endif
273 	for (i = 0; i < pack.ep_vmcmds.evs_used && !error; i++) {
274 		struct exec_vmcmd *vcp;
275 
276 		vcp = &pack.ep_vmcmds.evs_cmds[i];
277 		if (vcp->ev_flags & VMCMD_RELATIVE) {
278 #ifdef DIAGNOSTIC
279 			if (base_vcp == NULL)
280 				panic("netbsd32_execve: relative vmcmd with no base");
281 			if (vcp->ev_flags & VMCMD_BASE)
282 				panic("netbsd32_execve: illegal base & relative vmcmd");
283 #endif
284 			vcp->ev_addr += base_vcp->ev_addr;
285 		}
286 		error = (*vcp->ev_proc)(p, vcp);
287 #ifdef DEBUG
288 		if (error) {
289 			int j;
290 
291 			for (j = 0; j <= i; j++)
292 				printf("vmcmd[%d] = %#lx/%#lx @ %#lx\n", j,
293 				       vcp[j-i].ev_addr, vcp[j-i].ev_len,
294 				       vcp[j-i].ev_offset);
295 		}
296 #endif
297 		if (vcp->ev_flags & VMCMD_BASE)
298 			base_vcp = vcp;
299 	}
300 
301 	/* free the vmspace-creation commands, and release their references */
302 	kill_vmcmds(&pack.ep_vmcmds);
303 
304 	/* if an error happened, deallocate and punt */
305 	if (error) {
306 #ifdef DEBUG
307 		printf("netbsd32_execve: vmcmd %i failed: %d\n", i-1, error);
308 #endif
309 		goto exec_abort;
310 	}
311 
312 	/* remember information about the process */
313 	arginfo.ps_nargvstr = argc;
314 	arginfo.ps_nenvstr = envc;
315 
316 	stack = (char *) (vm->vm_minsaddr - len);
317 	/* Now copy argc, args & environ to new stack */
318 	error = (*pack.ep_es->es_copyargs)(&pack, &arginfo,
319 	    &stack, argp);
320 	if (error) {
321 #ifdef DEBUG
322 		printf("netbsd32_execve: copyargs failed\n");
323 #endif
324 		goto exec_abort;
325 	}
326 	/* restore the stack back to its original point */
327 	stack = (char *) (vm->vm_minsaddr - len);
328 
329 	/* fill process ps_strings info */
330 	p->p_psstr = (struct ps_strings *)(stack - sizeof(struct ps_strings));
331 	p->p_psargv = offsetof(struct ps_strings, ps_argvstr);
332 	p->p_psnargv = offsetof(struct ps_strings, ps_nargvstr);
333 	p->p_psenv = offsetof(struct ps_strings, ps_envstr);
334 	p->p_psnenv = offsetof(struct ps_strings, ps_nenvstr);
335 
336 	/* copy out the process's ps_strings structure */
337 	if (copyout(&arginfo, (char *)p->p_psstr, sizeof(arginfo))) {
338 #ifdef DEBUG
339 		printf("netbsd32_execve: ps_strings copyout failed\n");
340 #endif
341 		goto exec_abort;
342 	}
343 
344 	/* copy out the process's signal trapoline code */
345 	if (szsigcode) {
346 		if (copyout((char *)pack.ep_es->es_emul->e_sigcode,
347 		    p->p_sigctx.ps_sigcode = (char *)p->p_psstr - szsigcode,
348 		    szsigcode)) {
349 #ifdef DEBUG
350 			printf("netbsd32_execve: sig trampoline copyout failed\n");
351 #endif
352 			goto exec_abort;
353 		}
354 #ifdef PMAP_NEED_PROCWR
355 		/* This is code. Let the pmap do what is needed. */
356 		pmap_procwr(p, (vaddr_t)p->p_sigacts->ps_sigcode, szsigcode);
357 #endif
358 	}
359 
360 	stopprofclock(p);	/* stop profiling */
361 	fdcloseexec(p);		/* handle close on exec */
362 	execsigs(p);		/* reset catched signals */
363 	p->p_ctxlink = NULL;	/* reset ucontext link */
364 
365 	/* set command name & other accounting info */
366 	len = min(nid.ni_cnd.cn_namelen, MAXCOMLEN);
367 	memcpy(p->p_comm, nid.ni_cnd.cn_nameptr, len);
368 	p->p_comm[len] = 0;
369 	p->p_acflag &= ~AFORK;
370 
371 	/* record proc's vnode, for use by procfs and others */
372         if (p->p_textvp)
373                 vrele(p->p_textvp);
374 	VREF(pack.ep_vp);
375 	p->p_textvp = pack.ep_vp;
376 
377 	p->p_flag |= P_EXEC;
378 	if (p->p_flag & P_PPWAIT) {
379 		p->p_flag &= ~P_PPWAIT;
380 		wakeup((caddr_t) p->p_pptr);
381 	}
382 
383 	/*
384 	 * deal with set[ug]id.
385 	 * MNT_NOSUID has already been used to disable s[ug]id.
386 	 */
387 	if ((p->p_flag & P_TRACED) == 0 &&
388 
389 	    (((attr.va_mode & S_ISUID) != 0 &&
390 	      p->p_ucred->cr_uid != attr.va_uid) ||
391 
392 	     ((attr.va_mode & S_ISGID) != 0 &&
393 	      p->p_ucred->cr_gid != attr.va_gid))) {
394 		/*
395 		 * Mark the process as SUGID before we do
396 		 * anything that might block.
397 		 */
398 		p_sugid(p);
399 
400 		p->p_ucred = crcopy(cred);
401 #ifdef KTRACE
402 		/*
403 		 * If process is being ktraced, turn off - unless
404 		 * root set it.
405 		 */
406 		if (p->p_tracep && !(p->p_traceflag & KTRFAC_ROOT))
407 			ktrderef(p);
408 #endif
409 		if (attr.va_mode & S_ISUID)
410 			p->p_ucred->cr_uid = attr.va_uid;
411 		if (attr.va_mode & S_ISGID)
412 			p->p_ucred->cr_gid = attr.va_gid;
413 	} else
414 		p->p_flag &= ~P_SUGID;
415 	p->p_cred->p_svuid = p->p_ucred->cr_uid;
416 	p->p_cred->p_svgid = p->p_ucred->cr_gid;
417 
418 	doexechooks(p);
419 
420 	uvm_km_free_wakeup(exec_map, (vaddr_t) argp, NCARGS);
421 
422 	PNBUF_PUT(nid.ni_cnd.cn_pnbuf);
423 	vn_lock(pack.ep_vp, LK_EXCLUSIVE | LK_RETRY);
424 	VOP_CLOSE(pack.ep_vp, FREAD, cred, p);
425 	vput(pack.ep_vp);
426 
427 	/* setup new registers and do misc. setup. */
428 	(*pack.ep_es->es_emul->e_setregs)(p, &pack, (u_long) stack);
429 	if (pack.ep_es->es_setregs)
430 		(*pack.ep_es->es_setregs)(p, &pack, (u_long) stack);
431 
432 	if (p->p_flag & P_TRACED)
433 		psignal(p, SIGTRAP);
434 
435 	free(pack.ep_hdr, M_EXEC);
436 
437 	/*
438 	 * Call emulation specific exec hook. This can setup setup per-process
439 	 * p->p_emuldata or do any other per-process stuff an emulation needs.
440 	 *
441 	 * If we are executing process of different emulation than the
442 	 * original forked process, call e_proc_exit() of the old emulation
443 	 * first, then e_proc_exec() of new emulation. If the emulation is
444 	 * same, the exec hook code should deallocate any old emulation
445 	 * resources held previously by this process.
446 	 */
447 	if (p->p_emul && p->p_emul->e_proc_exit
448 	    && p->p_emul != pack.ep_es->es_emul)
449 		(*p->p_emul->e_proc_exit)(p);
450 
451 	/*
452 	 * Call exec hook. Emulation code may NOT store reference to anything
453 	 * from &pack.
454 	 */
455         if (pack.ep_es->es_emul->e_proc_exec)
456                 (*pack.ep_es->es_emul->e_proc_exec)(p, &pack);
457 
458 	/* update p_emul, the old value is no longer needed */
459 	p->p_emul = pack.ep_es->es_emul;
460 
461 #ifdef KTRACE
462 	if (KTRPOINT(p, KTR_EMUL))
463 		ktremul(p);
464 #endif
465 
466 #if defined(LKM) || defined(_LKM)
467 	lockmgr(&exec_lock, LK_RELEASE, NULL);
468 #endif
469 
470 	return (EJUSTRETURN);
471 
472 bad:
473 	/* free the vmspace-creation commands, and release their references */
474 	kill_vmcmds(&pack.ep_vmcmds);
475 	/* kill any opened file descriptor, if necessary */
476 	if (pack.ep_flags & EXEC_HASFD) {
477 		pack.ep_flags &= ~EXEC_HASFD;
478 		(void) fdrelease(p, pack.ep_fd);
479 	}
480 	/* close and put the exec'd file */
481 	vn_lock(pack.ep_vp, LK_EXCLUSIVE | LK_RETRY);
482 	VOP_CLOSE(pack.ep_vp, FREAD, cred, p);
483 	vput(pack.ep_vp);
484 	PNBUF_PUT(nid.ni_cnd.cn_pnbuf);
485 	uvm_km_free_wakeup(exec_map, (vaddr_t) argp, NCARGS);
486 
487 freehdr:
488 #if defined(LKM) || defined(_LKM)
489 	lockmgr(&exec_lock, LK_RELEASE, NULL);
490 #endif
491 
492 	free(pack.ep_hdr, M_EXEC);
493 	return error;
494 
495 exec_abort:
496 #if defined(LKM) || defined(_LKM)
497 	lockmgr(&exec_lock, LK_RELEASE, NULL);
498 #endif
499 
500 	/*
501 	 * the old process doesn't exist anymore.  exit gracefully.
502 	 * get rid of the (new) address space we have created, if any, get rid
503 	 * of our namei data and vnode, and exit noting failure
504 	 */
505 	uvm_deallocate(&vm->vm_map, VM_MIN_ADDRESS,
506 		VM_MAXUSER_ADDRESS - VM_MIN_ADDRESS);
507 	if (pack.ep_emul_arg)
508 		FREE(pack.ep_emul_arg, M_TEMP);
509 	PNBUF_PUT(nid.ni_cnd.cn_pnbuf);
510 	vn_lock(pack.ep_vp, LK_EXCLUSIVE | LK_RETRY);
511 	VOP_CLOSE(pack.ep_vp, FREAD, cred, p);
512 	vput(pack.ep_vp);
513 	uvm_km_free_wakeup(exec_map, (vaddr_t) argp, NCARGS);
514 	free(pack.ep_hdr, M_EXEC);
515 	exit1(p, W_EXITCODE(error, SIGABRT));
516 
517 	/* NOTREACHED */
518 	return 0;
519 }
520