xref: /netbsd-src/sys/kern/exec_elf32.c (revision 2a399c6883d870daece976daec6ffa7bb7f934ce)
1 /*	$NetBSD: exec_elf32.c,v 1.26 1997/05/08 16:20:05 mycroft Exp $	*/
2 
3 /*
4  * Copyright (c) 1996 Christopher G. Demetriou
5  * Copyright (c) 1994 Christos Zoulas
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. The name of the author may not be used to endorse or promote products
17  *    derived from this software without specific prior written permission
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30 
31 /* If not included by exec_elf64.c, ELFSIZE won't be defined. */
32 #ifndef ELFSIZE
33 #define	ELFSIZE		32
34 #endif
35 
36 #include <sys/param.h>
37 #include <sys/systm.h>
38 #include <sys/kernel.h>
39 #include <sys/proc.h>
40 #include <sys/malloc.h>
41 #include <sys/namei.h>
42 #include <sys/vnode.h>
43 #include <sys/exec.h>
44 #include <sys/exec_elf.h>
45 #include <sys/fcntl.h>
46 #include <sys/syscall.h>
47 #include <sys/signalvar.h>
48 #include <sys/mount.h>
49 #include <sys/stat.h>
50 
51 #include <sys/mman.h>
52 #include <vm/vm.h>
53 #include <vm/vm_param.h>
54 #include <vm/vm_map.h>
55 
56 #include <machine/cpu.h>
57 #include <machine/reg.h>
58 
59 #ifdef COMPAT_LINUX
60 #include <compat/linux/linux_exec.h>
61 #endif
62 
63 #ifdef COMPAT_SVR4
64 #include <compat/svr4/svr4_exec.h>
65 #endif
66 
67 #define	CONCAT(x,y)	__CONCAT(x,y)
68 #define	ELFNAME(x)	CONCAT(elf,CONCAT(ELFSIZE,CONCAT(_,x)))
69 #define	ELFNAME2(x,y)	CONCAT(x,CONCAT(_elf,CONCAT(ELFSIZE,CONCAT(_,y))))
70 #define	ELFNAMEEND(x)	CONCAT(x,CONCAT(_elf,ELFSIZE))
71 #define	ELFDEFNNAME(x)	CONCAT(ELF,CONCAT(ELFSIZE,CONCAT(_,x)))
72 
73 int	ELFNAME(check_header) __P((Elf_Ehdr *, int));
74 int	ELFNAME(load_file) __P((struct proc *, struct exec_package *, char *,
75 	    struct exec_vmcmd_set *, u_long *, struct elf_args *, Elf_Addr *));
76 void	ELFNAME(load_psection) __P((struct exec_vmcmd_set *, struct vnode *,
77 	    Elf_Phdr *, Elf_Addr *, u_long *, int *));
78 
79 extern char sigcode[], esigcode[];
80 #ifdef SYSCALL_DEBUG
81 extern char *syscallnames[];
82 #endif
83 
84 struct emul ELFNAMEEND(emul_netbsd) = {
85 	"netbsd",
86 	NULL,
87 	sendsig,
88 	SYS_syscall,
89 	SYS_MAXSYSCALL,
90 	sysent,
91 #ifdef SYSCALL_DEBUG
92 	syscallnames,
93 #else
94 	NULL,
95 #endif
96 	ELF_AUX_ENTRIES * sizeof(AuxInfo),
97 	ELFNAME(copyargs),
98 	setregs,
99 	sigcode,
100 	esigcode,
101 };
102 
103 int (*ELFNAME(probe_funcs)[]) __P((struct proc *, struct exec_package *,
104     Elf_Ehdr *, char *, Elf_Addr *)) = {
105 #if defined(COMPAT_LINUX) && (ELFSIZE == 32)
106 	ELFNAME2(linux,probe),			/* XXX not 64-bit safe */
107 #endif
108 #if defined(COMPAT_SVR4) && (ELFSIZE == 32)
109 	ELFNAME2(svr4,probe),			/* XXX not 64-bit safe */
110 #endif
111 };
112 
113 /* round up and down to page boundaries. */
114 #define	ELF_ROUND(a, b)		(((a) + (b) - 1) & ~((b) - 1))
115 #define	ELF_TRUNC(a, b)		((a) & ~((b) - 1))
116 
117 /*
118  * Copy arguments onto the stack in the normal way, but add some
119  * extra information in case of dynamic binding.
120  */
121 void *
122 ELFNAME(copyargs)(pack, arginfo, stack, argp)
123 	struct exec_package *pack;
124 	struct ps_strings *arginfo;
125 	void *stack;
126 	void *argp;
127 {
128 	size_t len;
129 	AuxInfo ai[ELF_AUX_ENTRIES], *a;
130 	struct elf_args *ap;
131 
132 	stack = copyargs(pack, arginfo, stack, argp);
133 	if (!stack)
134 		return NULL;
135 
136 	a = ai;
137 
138 	/*
139 	 * Push extra arguments on the stack needed by dynamically
140 	 * linked binaries
141 	 */
142 	if ((ap = (struct elf_args *)pack->ep_emul_arg)) {
143 
144 		a->au_id = AUX_phdr;
145 		a->au_v = ap->arg_phaddr;
146 		a++;
147 
148 		a->au_id = AUX_phent;
149 		a->au_v = ap->arg_phentsize;
150 		a++;
151 
152 		a->au_id = AUX_phnum;
153 		a->au_v = ap->arg_phnum;
154 		a++;
155 
156 		a->au_id = AUX_pagesz;
157 		a->au_v = NBPG;
158 		a++;
159 
160 		a->au_id = AUX_base;
161 		a->au_v = ap->arg_interp;
162 		a++;
163 
164 		a->au_id = AUX_flags;
165 		a->au_v = 0;
166 		a++;
167 
168 		a->au_id = AUX_entry;
169 		a->au_v = ap->arg_entry;
170 		a++;
171 
172 		free((char *)ap, M_TEMP);
173 		pack->ep_emul_arg = NULL;
174 	}
175 
176 	a->au_id = AUX_null;
177 	a->au_v = 0;
178 	a++;
179 
180 	len = (a - ai) * sizeof (AuxInfo);
181 	if (copyout(ai, stack, len))
182 		return NULL;
183 	stack += len;
184 
185 	return stack;
186 }
187 
188 /*
189  * elf_check_header():
190  *
191  * Check header for validity; return 0 of ok ENOEXEC if error
192  */
193 int
194 ELFNAME(check_header)(eh, type)
195 	Elf_Ehdr *eh;
196 	int type;
197 {
198 
199 	if (bcmp(eh->e_ident, Elf_e_ident, Elf_e_siz) != 0)
200 		return ENOEXEC;
201 
202 	switch (eh->e_machine) {
203 
204 	ELFDEFNNAME(MACHDEP_ID_CASES)
205 
206 	default:
207 		return ENOEXEC;
208 	}
209 
210 	if (eh->e_type != type)
211 		return ENOEXEC;
212 
213 	return 0;
214 }
215 
216 /*
217  * elf_load_psection():
218  *
219  * Load a psection at the appropriate address
220  */
221 void
222 ELFNAME(load_psection)(vcset, vp, ph, addr, size, prot)
223 	struct exec_vmcmd_set *vcset;
224 	struct vnode *vp;
225 	Elf_Phdr *ph;
226 	Elf_Addr *addr;
227 	u_long *size;
228 	int *prot;
229 {
230 	u_long uaddr, msize, psize, rm, rf;
231 	long diff, offset;
232 
233 	/*
234 	 * If the user specified an address, then we load there.
235 	 */
236 	if (*addr != ELFDEFNNAME(NO_ADDR)) {
237 		if (ph->p_align > 1) {
238 			*addr = ELF_ROUND(*addr, ph->p_align);
239 			uaddr = ELF_TRUNC(ph->p_vaddr, ph->p_align);
240 		} else
241 			uaddr = ph->p_vaddr;
242 		diff = ph->p_vaddr - uaddr;
243 	} else {
244 		*addr = uaddr = ph->p_vaddr;
245 		if (ph->p_align > 1)
246 			*addr = ELF_TRUNC(uaddr, ph->p_align);
247 		diff = uaddr - *addr;
248 	}
249 
250 	*prot |= (ph->p_flags & Elf_pf_r) ? VM_PROT_READ : 0;
251 	*prot |= (ph->p_flags & Elf_pf_w) ? VM_PROT_WRITE : 0;
252 	*prot |= (ph->p_flags & Elf_pf_x) ? VM_PROT_EXECUTE : 0;
253 
254 	offset = ph->p_offset - diff;
255 	*size = ph->p_filesz + diff;
256 	msize = ph->p_memsz + diff;
257 	psize = round_page(*size);
258 
259 	if ((ph->p_flags & Elf_pf_w) != 0) {
260 		/*
261 		 * Because the pagedvn pager can't handle zero fill of the last
262 		 * data page if it's not page aligned we map the last page
263 		 * readvn.
264 		 */
265 		psize = trunc_page(*size);
266 		NEW_VMCMD(vcset, vmcmd_map_pagedvn, psize, *addr, vp,
267 		    offset, *prot);
268 		if(psize != *size)
269 			NEW_VMCMD(vcset, vmcmd_map_readvn, *size - psize,
270 			    *addr + psize, vp, offset + psize, *prot);
271 	} else
272 		NEW_VMCMD(vcset, vmcmd_map_pagedvn, psize, *addr, vp,
273 		    offset, *prot);
274 
275 	/*
276 	 * Check if we need to extend the size of the segment
277 	 */
278 	rm = round_page(*addr + msize);
279 	rf = round_page(*addr + *size);
280 
281 	if (rm != rf) {
282 		NEW_VMCMD(vcset, vmcmd_map_zero, rm - rf, rf, NULLVP,
283 		    0, *prot);
284 		*size = msize;
285 	}
286 }
287 
288 /*
289  * elf_read_from():
290  *
291  *	Read from vnode into buffer at offset.
292  */
293 int
294 ELFNAME(read_from)(p, vp, off, buf, size)
295 	struct vnode *vp;
296 	u_long off;
297 	struct proc *p;
298 	caddr_t buf;
299 	int size;
300 {
301 	int error;
302 	int resid;
303 
304 	if ((error = vn_rdwr(UIO_READ, vp, buf, size, off, UIO_SYSSPACE,
305 	    0, p->p_ucred, &resid, p)) != 0)
306 		return error;
307 	/*
308 	 * See if we got all of it
309 	 */
310 	if (resid != 0)
311 		return ENOEXEC;
312 	return 0;
313 }
314 
315 /*
316  * elf_load_file():
317  *
318  * Load a file (interpreter/library) pointed to by path
319  * [stolen from coff_load_shlib()]. Made slightly generic
320  * so it might be used externally.
321  */
322 int
323 ELFNAME(load_file)(p, epp, path, vcset, entry, ap, last)
324 	struct proc *p;
325 	struct exec_package *epp;
326 	char *path;
327 	struct exec_vmcmd_set *vcset;
328 	u_long *entry;
329 	struct elf_args	*ap;
330 	Elf_Addr *last;
331 {
332 	int error, i;
333 	struct nameidata nd;
334 	struct vnode *vp;
335 	struct vattr attr;
336 	Elf_Ehdr eh;
337 	Elf_Phdr *ph = NULL;
338 	u_long phsize;
339 	char *bp = NULL;
340 	Elf_Addr addr = *last;
341 
342 	bp = path;
343 	/*
344 	 * 1. open file
345 	 * 2. read filehdr
346 	 * 3. map text, data, and bss out of it using VM_*
347 	 */
348 	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE, path, p);
349 	if ((error = namei(&nd)) != 0)
350 		return error;
351 	vp = nd.ni_vp;
352 
353 	/*
354 	 * Similarly, if it's not marked as executable, or it's not a regular
355 	 * file, we don't allow it to be used.
356 	 */
357 	if (vp->v_type != VREG) {
358 		error = EACCES;
359 		goto badunlock;
360 	}
361 	if ((error = VOP_ACCESS(vp, VEXEC, p->p_ucred, p)) != 0)
362 		goto badunlock;
363 
364 	/* get attributes */
365 	if ((error = VOP_GETATTR(vp, &attr, p->p_ucred, p)) != 0)
366 		goto badunlock;
367 
368 	/*
369 	 * Check mount point.  Though we're not trying to exec this binary,
370 	 * we will be executing code from it, so if the mount point
371 	 * disallows execution or set-id-ness, we punt or kill the set-id.
372 	 */
373 	if (vp->v_mount->mnt_flag & MNT_NOEXEC) {
374 		error = EACCES;
375 		goto badunlock;
376 	}
377 	if (vp->v_mount->mnt_flag & MNT_NOSUID)
378 		epp->ep_vap->va_mode &= ~(S_ISUID | S_ISGID);
379 
380 #ifdef notyet /* XXX cgd 960926 */
381 	XXX cgd 960926: (maybe) VOP_OPEN it (and VOP_CLOSE in copyargs?)
382 #endif
383 	VOP_UNLOCK(vp);
384 
385 	if ((error = ELFNAME(read_from)(p, vp, 0, (caddr_t) &eh,
386 	    sizeof(eh))) != 0)
387 		goto bad;
388 
389 	if ((error = ELFNAME(check_header)(&eh, Elf_et_dyn)) != 0)
390 		goto bad;
391 
392 	phsize = eh.e_phnum * sizeof(Elf_Phdr);
393 	ph = (Elf_Phdr *)malloc(phsize, M_TEMP, M_WAITOK);
394 
395 	if ((error = ELFNAME(read_from)(p, vp, eh.e_phoff,
396 	    (caddr_t) ph, phsize)) != 0)
397 		goto bad;
398 
399 	/*
400 	 * Load all the necessary sections
401 	 */
402 	for (i = 0; i < eh.e_phnum; i++) {
403 		u_long size = 0;
404 		int prot = 0;
405 
406 		switch (ph[i].p_type) {
407 		case Elf_pt_load:
408 			ELFNAME(load_psection)(vcset, vp, &ph[i], &addr,
409 			    &size, &prot);
410 			/* If entry is within this section it must be text */
411 			if (eh.e_entry >= ph[i].p_vaddr &&
412 			    eh.e_entry < (ph[i].p_vaddr + size)) {
413 				/* XXX */
414 				*entry = addr + eh.e_entry;
415 #ifdef mips
416 				*entry -= ph[i].p_vaddr;
417 #endif
418 				ap->arg_interp = addr;
419 			}
420 			addr += size;
421 			break;
422 
423 		case Elf_pt_dynamic:
424 		case Elf_pt_phdr:
425 		case Elf_pt_note:
426 			break;
427 
428 		default:
429 			break;
430 		}
431 	}
432 
433 	free((char *)ph, M_TEMP);
434 	*last = addr;
435 	vrele(vp);
436 	return 0;
437 
438 badunlock:
439 	VOP_UNLOCK(vp);
440 
441 bad:
442 	if (ph != NULL)
443 		free((char *)ph, M_TEMP);
444 #ifdef notyet /* XXX cgd 960926 */
445 	(maybe) VOP_CLOSE it
446 #endif
447 	vrele(vp);
448 	return error;
449 }
450 
451 /*
452  * exec_elf_makecmds(): Prepare an Elf binary's exec package
453  *
454  * First, set of the various offsets/lengths in the exec package.
455  *
456  * Then, mark the text image busy (so it can be demand paged) or error
457  * out if this is not possible.  Finally, set up vmcmds for the
458  * text, data, bss, and stack segments.
459  */
460 int
461 ELFNAME2(exec,makecmds)(p, epp)
462 	struct proc *p;
463 	struct exec_package *epp;
464 {
465 	Elf_Ehdr *eh = epp->ep_hdr;
466 	Elf_Phdr *ph, *pp;
467 	Elf_Addr phdr = 0, pos = 0;
468 	int error, i, n, nload;
469 	char interp[MAXPATHLEN];
470 	u_long phsize;
471 
472 	if (epp->ep_hdrvalid < sizeof(Elf_Ehdr))
473 		return ENOEXEC;
474 
475 	if (ELFNAME(check_header)(eh, Elf_et_exec))
476 		return ENOEXEC;
477 
478 	/*
479 	 * check if vnode is in open for writing, because we want to
480 	 * demand-page out of it.  if it is, don't do it, for various
481 	 * reasons
482 	 */
483 	if (epp->ep_vp->v_writecount != 0) {
484 #ifdef DIAGNOSTIC
485 		if (epp->ep_vp->v_flag & VTEXT)
486 			panic("exec: a VTEXT vnode has writecount != 0\n");
487 #endif
488 		return ETXTBSY;
489 	}
490 	/*
491 	 * Allocate space to hold all the program headers, and read them
492 	 * from the file
493 	 */
494 	phsize = eh->e_phnum * sizeof(Elf_Phdr);
495 	ph = (Elf_Phdr *)malloc(phsize, M_TEMP, M_WAITOK);
496 
497 	if ((error = ELFNAME(read_from)(p, epp->ep_vp, eh->e_phoff,
498 	    (caddr_t) ph, phsize)) != 0)
499 		goto bad;
500 
501 	epp->ep_taddr = epp->ep_tsize = ELFDEFNNAME(NO_ADDR);
502 	epp->ep_daddr = epp->ep_dsize = ELFDEFNNAME(NO_ADDR);
503 
504 	interp[0] = '\0';
505 
506 	for (i = 0; i < eh->e_phnum; i++) {
507 		pp = &ph[i];
508 		if (pp->p_type == Elf_pt_interp) {
509 			if (pp->p_filesz >= sizeof(interp))
510 				goto bad;
511 			if ((error = ELFNAME(read_from)(p, epp->ep_vp,
512 			    pp->p_offset, (caddr_t) interp,
513 			    pp->p_filesz)) != 0)
514 				goto bad;
515 			break;
516 		}
517 	}
518 
519 	/*
520 	 * Setup things for native emulation.
521 	 */
522 	epp->ep_emul = &ELFNAMEEND(emul_netbsd);
523 	pos = ELFDEFNNAME(NO_ADDR);
524 
525 	/*
526 	 * On the same architecture, we may be emulating different systems.
527 	 * See which one will accept this executable. This currently only
528 	 * applies to Linux and SVR4 on the i386.
529 	 *
530 	 * Probe functions would normally see if the interpreter (if any)
531 	 * exists. Emulation packages may possibly replace the interpreter in
532 	 * interp[] with a changed path (/emul/xxx/<path>), and also
533 	 * set the ep_emul field in the exec package structure.
534 	 */
535 	n = sizeof ELFNAME(probe_funcs) / sizeof ELFNAME(probe_funcs)[0];
536 	if (n != 0) {
537 		error = ENOEXEC;
538 		for (i = 0; i < n && error; i++)
539 			error = ELFNAME(probe_funcs)[i](p, epp, eh,
540 			    interp, &pos);
541 
542 #ifdef notyet
543 		/*
544 		 * We should really use a signature in our native binaries
545 		 * and have our own probe function for matching binaries,
546 		 * before trying the emulations. For now, if the emulation
547 		 * probes failed we default to native.
548 		 */
549 		if (error)
550 			goto bad;
551 #endif
552 	}
553 
554 	/*
555 	 * Load all the necessary sections
556 	 */
557 	for (i = nload = 0; i < eh->e_phnum; i++) {
558 		Elf_Addr  addr = ELFDEFNNAME(NO_ADDR);
559 		u_long size = 0;
560 		int prot = 0;
561 
562 		pp = &ph[i];
563 
564 		switch (ph[i].p_type) {
565 		case Elf_pt_load:
566 			/*
567 			 * XXX
568 			 * Can handle only 2 sections: text and data
569 			 */
570 			if (nload++ == 2)
571 				goto bad;
572 			ELFNAME(load_psection)(&epp->ep_vmcmds, epp->ep_vp,
573 			    &ph[i], &addr, &size, &prot);
574 
575 			/*
576 			 * Decide whether it's text or data by looking
577 			 * at the entry point.
578 			 */
579 			if (eh->e_entry >= addr &&
580 			    eh->e_entry < (addr + size)) {
581 				epp->ep_taddr = addr;
582 				epp->ep_tsize = size;
583 				if (epp->ep_daddr == ELFDEFNNAME(NO_ADDR)) {
584 					epp->ep_daddr = addr;
585 					epp->ep_dsize = size;
586 				}
587 			} else {
588 				epp->ep_daddr = addr;
589 				epp->ep_dsize = size;
590 			}
591 			break;
592 
593 		case Elf_pt_shlib:
594 			error = ENOEXEC;
595 			goto bad;
596 
597 		case Elf_pt_interp:
598 			/* Already did this one */
599 		case Elf_pt_dynamic:
600 		case Elf_pt_note:
601 			break;
602 
603 		case Elf_pt_phdr:
604 			/* Note address of program headers (in text segment) */
605 			phdr = pp->p_vaddr;
606 			break;
607 
608 		default:
609 			/*
610 			 * Not fatal; we don't need to understand everything.
611 			 */
612 			break;
613 		}
614 	}
615 
616 	/* this breaks on, e.g., OpenBSD-compatible mips shared binaries. */
617 #ifndef ELF_INTERP_NON_RELOCATABLE
618 	/*
619 	 * If no position to load the interpreter was set by a probe
620 	 * function, pick the same address that a non-fixed mmap(0, ..)
621 	 * would (i.e. something safely out of the way).
622 	 */
623 	if (pos == ELFDEFNNAME(NO_ADDR))
624 		pos = round_page(epp->ep_daddr + MAXDSIZ);
625 #endif	/* !ELF_INTERP_NON_RELOCATABLE */
626 
627 	/*
628 	 * Check if we found a dynamically linked binary and arrange to load
629 	 * it's interpreter
630 	 */
631 	if (interp[0]) {
632 		struct elf_args *ap;
633 
634 		ap = (struct elf_args *)malloc(sizeof(struct elf_args),
635 		    M_TEMP, M_WAITOK);
636 		if ((error = ELFNAME(load_file)(p, epp, interp,
637 		    &epp->ep_vmcmds, &epp->ep_entry, ap, &pos)) != 0) {
638 			free((char *)ap, M_TEMP);
639 			goto bad;
640 		}
641 		pos += phsize;
642 		ap->arg_phaddr = phdr;
643 
644 		ap->arg_phentsize = eh->e_phentsize;
645 		ap->arg_phnum = eh->e_phnum;
646 		ap->arg_entry = eh->e_entry;
647 
648 		epp->ep_emul_arg = ap;
649 	} else
650 		epp->ep_entry = eh->e_entry;
651 
652 #ifdef ELF_MAP_PAGE_ZERO
653 	/* Dell SVR4 maps page zero, yeuch! */
654 	NEW_VMCMD(&epp->ep_vmcmds, vmcmd_map_readvn, NBPG, 0, epp->ep_vp, 0,
655 	    VM_PROT_READ);
656 #endif
657 	free((char *)ph, M_TEMP);
658 	epp->ep_vp->v_flag |= VTEXT;
659 	return exec_elf_setup_stack(p, epp);
660 
661 bad:
662 	free((char *)ph, M_TEMP);
663 	kill_vmcmds(&epp->ep_vmcmds);
664 	return ENOEXEC;
665 }
666