xref: /openbsd-src/sys/kern/exec_elf.c (revision 8334acbae9ccc2f5a5e3e93e22561560a5a6b346)
1 /*	$OpenBSD: exec_elf.c,v 1.11 1996/06/15 07:30:05 etheisen Exp $	*/
2 /*	$NetBSD: exec_elf.c,v 1.6 1996/02/09 18:59:18 christos Exp $	*/
3 
4 /*
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 
32 #include <sys/param.h>
33 #include <sys/systm.h>
34 #include <sys/kernel.h>
35 #include <sys/proc.h>
36 #include <sys/malloc.h>
37 #include <sys/namei.h>
38 #include <sys/vnode.h>
39 #include <sys/exec.h>
40 #include <sys/exec_elf.h>
41 #include <sys/syscall.h>
42 #include <sys/signalvar.h>
43 
44 #if defined(COMPAT_LINUX) || defined(COMPAT_SVR4)	/*XXX should be */
45 #undef EXEC_ELF						/*XXX defined in */
46 #define EXEC_ELF					/*XXX machine/exec.h */
47 #endif							/*XXX instead ? */
48 
49 #if defined(NATIVE_EXEC_ELF) || defined(EXEC_ELF)
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 #include <machine/exec.h>
59 
60 #ifdef COMPAT_LINUX
61 #include <compat/linux/linux_exec.h>
62 #endif
63 
64 #ifdef COMPAT_SVR4
65 #include <compat/svr4/svr4_exec.h>
66 #endif
67 
68 int (*elf_probe_funcs[]) __P((struct proc *, struct exec_package *,
69 			      char *, u_long *)) = {
70 #ifdef COMPAT_SVR4
71 	svr4_elf_probe,
72 #endif
73 #ifdef COMPAT_LINUX
74 	linux_elf_probe
75 #endif
76 };
77 
78 int elf_check_header __P((Elf32_Ehdr *, int));
79 int elf_load_file __P((struct proc *, char *, struct exec_vmcmd_set *,
80 		       u_long *, struct elf_args *, u_long *));
81 
82 static int elf_read_from __P((struct proc *, struct vnode *, u_long,
83 	caddr_t, int));
84 static void elf_load_psection __P((struct exec_vmcmd_set *,
85 	struct vnode *, Elf32_Phdr *, u_long *, u_long *, int *));
86 
87 #define ELF_ALIGN(a, b) ((a) & ~((b) - 1))
88 
89 /*
90  * This is the basic elf emul. elf_probe_funcs may change to other emuls.
91  */
92 
93 extern char sigcode[], esigcode[];
94 #ifdef SYSCALL_DEBUG
95 extern char *syscallnames[];
96 #endif
97 
98 struct emul emul_elf = {
99 	"native",
100 	NULL,
101 	sendsig,
102 	SYS_syscall,
103 	SYS_MAXSYSCALL,
104 	sysent,
105 #ifdef SYSCALL_DEBUG
106 	syscallnames,
107 #else
108 	NULL,
109 #endif
110 	sizeof(AuxInfo) * ELF_AUX_ENTRIES,
111 	elf_copyargs,
112 	setregs,
113 	sigcode,
114 	esigcode,
115 };
116 
117 
118 /*
119  * Copy arguments onto the stack in the normal way, but add some
120  * extra information in case of dynamic binding.
121  */
122 void *
123 elf_copyargs(pack, arginfo, stack, argp)
124 	struct exec_package *pack;
125 	struct ps_strings *arginfo;
126 	void *stack;
127 	void *argp;
128 {
129 	size_t len;
130 	AuxInfo ai[ELF_AUX_ENTRIES], *a;
131 	struct elf_args *ap;
132 
133 	stack = copyargs(pack, arginfo, stack, argp);
134 	if (!stack)
135 		return NULL;
136 
137 	/*
138 	 * Push extra arguments on the stack needed by dynamically
139 	 * linked binaries
140 	 */
141 	if ((ap = (struct elf_args *) pack->ep_emul_arg)) {
142 		a = ai;
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 		a->au_id = AUX_null;
173 		a->au_v = 0;
174 		a++;
175 
176 		free((char *) ap, M_TEMP);
177 		len = ELF_AUX_ENTRIES * sizeof (AuxInfo);
178 		if (copyout(ai, stack, len))
179 			return NULL;
180 		stack += len;
181 	}
182 	return stack;
183 }
184 
185 /*
186  * elf_check_header():
187  *
188  * Check header for validity; return 0 for ok, ENOEXEC if error
189  */
190 int
191 elf_check_header(ehdr, type)
192 	Elf32_Ehdr *ehdr;
193 	int type;
194 {
195         /*
196 	 * We need to check magic, class size, endianess,
197 	 * and version before we look at the rest of the
198 	 * Elf32_Ehdr structure.  These few elements are
199 	 * represented in a machine independant fashion.
200 	 */
201 	if (!IS_ELF(*ehdr) ||
202 	    ehdr->e_ident[EI_CLASS] != ELF_TARG_CLASS ||
203 	    ehdr->e_ident[EI_DATA] != ELF_TARG_DATA ||
204 	    ehdr->e_ident[EI_VERSION] != ELF_TARG_VER)
205                 return ENOEXEC;
206 
207         /* Now check the machine dependant header */
208 	if (ehdr->e_machine != ELF_TARG_MACH ||
209 	    ehdr->e_version != ELF_TARG_VER)
210                 return ENOEXEC;
211 
212         /* Check the type */
213 	if (ehdr->e_type != type)
214 		return ENOEXEC;
215 
216 	return 0;
217 }
218 
219 /*
220  * elf_load_psection():
221  *
222  * Load a psection at the appropriate address
223  */
224 static void
225 elf_load_psection(vcset, vp, ph, addr, size, prot)
226 	struct exec_vmcmd_set *vcset;
227 	struct vnode *vp;
228 	Elf32_Phdr *ph;
229 	u_long *addr;
230 	u_long *size;
231 	int *prot;
232 {
233 	u_long uaddr, msize, psize, rm, rf;
234 	long diff, offset;
235 
236 	/*
237 	 * If the user specified an address, then we load there.
238 	 */
239 	if (*addr != ELF32_NO_ADDR) {
240 		if (ph->p_align > 1) {
241 			*addr = ELF_ALIGN(*addr + ph->p_align, ph->p_align);
242 			uaddr = ELF_ALIGN(ph->p_vaddr, ph->p_align);
243 		} else
244 			uaddr = ph->p_vaddr;
245 		diff = ph->p_vaddr - uaddr;
246 	} else {
247 		*addr = uaddr = ph->p_vaddr;
248 		if (ph->p_align > 1)
249 			*addr = ELF_ALIGN(uaddr, ph->p_align);
250 		diff = uaddr - *addr;
251 	}
252 
253 	*prot |= (ph->p_flags & PF_R) ? VM_PROT_READ : 0;
254 	*prot |= (ph->p_flags & PF_W) ? VM_PROT_WRITE : 0;
255 	*prot |= (ph->p_flags & PF_X) ? VM_PROT_EXECUTE : 0;
256 
257 	offset = ph->p_offset - diff;
258 	*size = ph->p_filesz + diff;
259 	msize = ph->p_memsz + diff;
260 	psize = round_page(*size);
261 
262 	/*
263 	 * Because the pagedvn pager can't handle zero fill of the last
264 	 * data page if it's not page aligned we map the las page readvn.
265 	 */
266 	if(ph->p_flags & PF_W) {
267 		psize = trunc_page(*size);
268 		NEW_VMCMD(vcset, vmcmd_map_pagedvn, psize, *addr, vp, offset, *prot);
269 		if(psize != *size) {
270 			NEW_VMCMD(vcset, vmcmd_map_readvn, *size - psize, *addr
271 + psize, vp, offset + psize, *prot);
272 		}
273 	}
274 	else {
275 		 NEW_VMCMD(vcset, vmcmd_map_pagedvn, psize, *addr, vp, offset, *prot);
276 	}
277 
278 	/*
279 	 * Check if we need to extend the size of the segment
280 	 */
281 	rm = round_page(*addr + msize);
282 	rf = round_page(*addr + *size);
283 
284 	if (rm != rf) {
285 		NEW_VMCMD(vcset, vmcmd_map_zero, rm - rf, rf, NULLVP, 0, *prot);
286 		*size = msize;
287 	}
288 }
289 
290 /*
291  * elf_read_from():
292  *
293  *	Read from vnode into buffer at offset.
294  */
295 static int
296 elf_read_from(p, vp, off, buf, size)
297 	struct vnode *vp;
298 	u_long off;
299 	struct proc *p;
300 	caddr_t buf;
301 	int size;
302 {
303 	int error;
304 	int resid;
305 
306 	if ((error = vn_rdwr(UIO_READ, vp, buf, size,
307 			     off, UIO_SYSSPACE, IO_NODELOCKED, p->p_ucred,
308 			     &resid, p)) != 0)
309 		return error;
310 	/*
311 	 * See if we got all of it
312 	 */
313 	if (resid != 0)
314 		return ENOEXEC;
315 	return 0;
316 }
317 
318 /*
319  * elf_load_file():
320  *
321  * Load a file (interpreter/library) pointed to by path
322  * [stolen from coff_load_shlib()]. Made slightly generic
323  * so it might be used externally.
324  */
325 int
326 elf_load_file(p, path, vcset, entry, ap, last)
327 	struct proc *p;
328 	char *path;
329 	struct exec_vmcmd_set *vcset;
330 	u_long *entry;
331 	struct elf_args	*ap;
332 	u_long *last;
333 {
334 	int error, i;
335 	struct nameidata nd;
336 	Elf32_Ehdr eh;
337 	Elf32_Phdr *ph = NULL;
338 	u_long phsize;
339 	char *bp = NULL;
340 	u_long 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, UIO_SYSSPACE, path, p);
349 	if ((error = namei(&nd)) != 0) {
350 		return error;
351 	}
352 	if ((error = elf_read_from(p, nd.ni_vp, 0, (caddr_t) &eh,
353 				    sizeof(eh))) != 0)
354 		goto bad;
355 
356 	if ((error = elf_check_header(&eh, ET_DYN)) != 0)
357 		goto bad;
358 
359 	phsize = eh.e_phnum * sizeof(Elf32_Phdr);
360 	ph = (Elf32_Phdr *) malloc(phsize, M_TEMP, M_WAITOK);
361 
362 	if ((error = elf_read_from(p, nd.ni_vp, eh.e_phoff,
363 				    (caddr_t) ph, phsize)) != 0)
364 		goto bad;
365 
366 	/*
367 	 * Load all the necessary sections
368 	 */
369 	for (i = 0; i < eh.e_phnum; i++) {
370 		u_long size = 0;
371 		int prot = 0;
372 
373 		switch (ph[i].p_type) {
374 		case PT_LOAD:
375 			elf_load_psection(vcset, nd.ni_vp, &ph[i], &addr,
376 						&size, &prot);
377 			/* If entry is within this section it must be text */
378 			if (eh.e_entry >= ph[i].p_vaddr &&
379 			    eh.e_entry < (ph[i].p_vaddr + size)) {
380 				*entry = addr + eh.e_entry - ph[i].p_vaddr;
381 				ap->arg_interp = addr;
382 			}
383 			addr += size;
384 			break;
385 
386 		case PT_DYNAMIC:
387 		case PT_PHDR:
388 		case PT_NOTE:
389 			break;
390 
391 		default:
392 			break;
393 		}
394 	}
395 
396 bad:
397 	if (ph != NULL)
398 		free((char *) ph, M_TEMP);
399 
400 	*last = addr;
401 	vrele(nd.ni_vp);
402 	return error;
403 }
404 
405 /*
406  * exec_elf_makecmds(): Prepare an Elf binary's exec package
407  *
408  * First, set of the various offsets/lengths in the exec package.
409  *
410  * Then, mark the text image busy (so it can be demand paged) or error
411  * out if this is not possible.  Finally, set up vmcmds for the
412  * text, data, bss, and stack segments.
413  *
414  */
415 int
416 exec_elf_makecmds(p, epp)
417 	struct proc *p;
418 	struct exec_package *epp;
419 {
420 	Elf32_Ehdr *eh = epp->ep_hdr;
421 	Elf32_Phdr *ph, *pp;
422 	Elf32_Addr phdr = 0;
423 	int error, i, n, nload;
424 	char interp[MAXPATHLEN];
425 	u_long pos = 0, phsize;
426 
427 	if (epp->ep_hdrvalid < sizeof(Elf32_Ehdr))
428 		return ENOEXEC;
429 
430 	if (elf_check_header(eh, ET_EXEC))
431 		return ENOEXEC;
432 
433 	/*
434 	 * check if vnode is in open for writing, because we want to
435 	 * demand-page out of it.  if it is, don't do it, for various
436 	 * reasons
437 	 */
438 	if (epp->ep_vp->v_writecount != 0) {
439 #ifdef DIAGNOSTIC
440 		if (epp->ep_vp->v_flag & VTEXT)
441 			panic("exec: a VTEXT vnode has writecount != 0\n");
442 #endif
443 		return ETXTBSY;
444 	}
445 	/*
446 	 * Allocate space to hold all the program headers, and read them
447 	 * from the file
448 	 */
449 	phsize = eh->e_phnum * sizeof(Elf32_Phdr);
450 	ph = (Elf32_Phdr *) malloc(phsize, M_TEMP, M_WAITOK);
451 
452 	if ((error = elf_read_from(p, epp->ep_vp, eh->e_phoff,
453 				    (caddr_t) ph, phsize)) != 0)
454 		goto bad;
455 
456 	epp->ep_tsize = ELF32_NO_ADDR;
457 	epp->ep_dsize = ELF32_NO_ADDR;
458 
459 	interp[0] = '\0';
460 
461 	for (i = 0; i < eh->e_phnum; i++) {
462 		pp = &ph[i];
463 		if (pp->p_type == PT_INTERP) {
464 			if (pp->p_filesz >= sizeof(interp))
465 				goto bad;
466 			if ((error = elf_read_from(p, epp->ep_vp, pp->p_offset,
467 			    (caddr_t) interp, pp->p_filesz)) != 0)
468 				goto bad;
469 			break;
470 		}
471 	}
472 
473 	/*
474 	 * OK, we want a slightly different twist of the
475 	 * standard emulation package for "real" elf.
476 	 */
477 	epp->ep_emul = &emul_elf;
478 	pos = ELF32_NO_ADDR;
479 
480 	/*
481 	 * On the same architecture, we may be emulating different systems.
482 	 * See which one will accept this executable. This currently only
483 	 * applies to Linux and SVR4 on the i386.
484 	 *
485 	 * Probe functions would normally see if the interpreter (if any)
486 	 * exists. Emulation packages may possibly replace the interpreter in
487 	 * interp[] with a changed path (/emul/xxx/<path>), and also
488 	 * set the ep_emul field in the exec package structure.
489 	 */
490 	if ((n = sizeof elf_probe_funcs / sizeof elf_probe_funcs[0])) {
491 		error = ENOEXEC;
492 		for (i = 0; i < n && error; i++)
493 			error = elf_probe_funcs[i](p, epp, interp, &pos);
494 
495 		if (error)
496 			goto bad;
497 	}
498 
499 	/*
500 	 * Load all the necessary sections
501 	 */
502 	for (i = nload = 0; i < eh->e_phnum; i++) {
503 		u_long  addr = ELF32_NO_ADDR, size = 0;
504 		int prot = 0;
505 
506 		pp = &ph[i];
507 
508 		switch (ph[i].p_type) {
509 		case PT_LOAD:
510 			/*
511 			 * XXX
512 			 * Can handle only 2 sections: text and data
513 			 */
514 			if (nload++ == 2)
515 				goto bad;
516 			elf_load_psection(&epp->ep_vmcmds, epp->ep_vp,
517 				&ph[i], &addr, &size, &prot);
518 			/*
519 			 * Decide whether it's text or data by looking
520 			 * at the entry point.
521 			 */
522 			if (eh->e_entry >= addr && eh->e_entry < (addr + size)){
523 				epp->ep_taddr = addr;
524 				epp->ep_tsize = size;
525 			} else {
526 				epp->ep_daddr = addr;
527 				epp->ep_dsize = size;
528 			}
529 			break;
530 
531 		case PT_SHLIB:
532 			error = ENOEXEC;
533 			goto bad;
534 
535 		case PT_INTERP:
536 			/* Already did this one */
537 		case PT_DYNAMIC:
538 		case PT_NOTE:
539 			break;
540 
541 		case PT_PHDR:
542 			/* Note address of program headers (in text segment) */
543 			phdr = pp->p_vaddr;
544 		break;
545 
546 		default:
547 			/*
548 			 * Not fatal, we don't need to understand everything
549 			 * :-)
550 			 */
551 			break;
552 		}
553 	}
554 
555 #if !defined(mips)
556 	/*
557 	 * If no position to load the interpreter was set by a probe
558 	 * function, pick the same address that a non-fixed mmap(0, ..)
559 	 * would (i.e. something safely out of the way).
560 	 */
561 	if (pos == ELF32_NO_ADDR)
562 		pos = round_page(epp->ep_daddr + MAXDSIZ);
563 #endif
564 
565 	/*
566 	 * Check if we found a dynamically linked binary and arrange to load
567 	 * it's interpreter
568 	 */
569 	if (interp[0]) {
570 		struct elf_args *ap;
571 
572 		ap = (struct elf_args *) malloc(sizeof(struct elf_args),
573 						 M_TEMP, M_WAITOK);
574 		if ((error = elf_load_file(p, interp, &epp->ep_vmcmds,
575 				&epp->ep_entry, ap, &pos)) != 0) {
576 			free((char *) ap, M_TEMP);
577 			goto bad;
578 		}
579 		pos += phsize;
580 		ap->arg_phaddr = phdr;
581 
582 		ap->arg_phentsize = eh->e_phentsize;
583 		ap->arg_phnum = eh->e_phnum;
584 		ap->arg_entry = eh->e_entry;
585 
586 		epp->ep_emul_arg = ap;
587 	} else
588 		epp->ep_entry = eh->e_entry;
589 
590 #ifdef ELF_MAP_PAGE_ZERO
591 	/* Dell SVR4 maps page zero, yeuch! */
592 	NEW_VMCMD(&epp->ep_vmcmds, vmcmd_map_readvn, NBPG, 0, epp->ep_vp, 0,
593 	    VM_PROT_READ);
594 #endif
595 
596 	free((char *) ph, M_TEMP);
597 	epp->ep_vp->v_flag |= VTEXT;
598 	return exec_aout_setup_stack(p, epp);
599 
600 bad:
601 	free((char *) ph, M_TEMP);
602 	kill_vmcmds(&epp->ep_vmcmds);
603 	return ENOEXEC;
604 }
605 #endif /* NATIVE_EXEC_ELF || EXEC_ELF */
606