exec_elf32.c revision 1.131
1/*	$NetBSD: exec_elf32.c,v 1.131 2008/01/02 22:04:56 yamt Exp $	*/
2
3/*-
4 * Copyright (c) 1994, 2000, 2005 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Christos Zoulas.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 *    notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 *    notice, this list of conditions and the following disclaimer in the
17 *    documentation and/or other materials provided with the distribution.
18 * 3. All advertising materials mentioning features or use of this software
19 *    must display the following acknowledgement:
20 *	This product includes software developed by the NetBSD
21 *	Foundation, Inc. and its contributors.
22 * 4. Neither the name of The NetBSD Foundation nor the names of its
23 *    contributors may be used to endorse or promote products derived
24 *    from this software without specific prior written permission.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36 * POSSIBILITY OF SUCH DAMAGE.
37 */
38
39/*
40 * Copyright (c) 1996 Christopher G. Demetriou
41 * All rights reserved.
42 *
43 * Redistribution and use in source and binary forms, with or without
44 * modification, are permitted provided that the following conditions
45 * are met:
46 * 1. Redistributions of source code must retain the above copyright
47 *    notice, this list of conditions and the following disclaimer.
48 * 2. Redistributions in binary form must reproduce the above copyright
49 *    notice, this list of conditions and the following disclaimer in the
50 *    documentation and/or other materials provided with the distribution.
51 * 3. The name of the author may not be used to endorse or promote products
52 *    derived from this software without specific prior written permission
53 *
54 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
55 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
56 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
57 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
58 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
59 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
60 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
61 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
62 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
63 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
64 */
65
66#include <sys/cdefs.h>
67__KERNEL_RCSID(1, "$NetBSD: exec_elf32.c,v 1.131 2008/01/02 22:04:56 yamt Exp $");
68
69/* If not included by exec_elf64.c, ELFSIZE won't be defined. */
70#ifndef ELFSIZE
71#define	ELFSIZE		32
72#endif
73
74#ifdef _KERNEL_OPT
75#include "opt_pax.h"
76#endif /* _KERNEL_OPT */
77
78#include <sys/param.h>
79#include <sys/proc.h>
80#include <sys/malloc.h>
81#include <sys/namei.h>
82#include <sys/vnode.h>
83#include <sys/exec.h>
84#include <sys/exec_elf.h>
85#include <sys/syscall.h>
86#include <sys/signalvar.h>
87#include <sys/mount.h>
88#include <sys/stat.h>
89#include <sys/kauth.h>
90#include <sys/bitops.h>
91
92#include <sys/cpu.h>
93#include <machine/reg.h>
94
95#include <compat/common/compat_util.h>
96
97#include <sys/pax.h>
98
99extern const struct emul emul_netbsd;
100
101#define elf_check_header	ELFNAME(check_header)
102#define elf_copyargs		ELFNAME(copyargs)
103#define elf_load_file		ELFNAME(load_file)
104#define elf_load_psection	ELFNAME(load_psection)
105#define exec_elf_makecmds	ELFNAME2(exec,makecmds)
106#define netbsd_elf_signature	ELFNAME2(netbsd,signature)
107#define netbsd_elf_probe	ELFNAME2(netbsd,probe)
108
109int	elf_load_file(struct lwp *, struct exec_package *, char *,
110	    struct exec_vmcmd_set *, u_long *, struct elf_args *, Elf_Addr *);
111void	elf_load_psection(struct exec_vmcmd_set *, struct vnode *,
112	    const Elf_Phdr *, Elf_Addr *, u_long *, int *, int);
113
114int	netbsd_elf_signature(struct lwp *, struct exec_package *, Elf_Ehdr *);
115int	netbsd_elf_probe(struct lwp *, struct exec_package *, void *, char *,
116	    vaddr_t *);
117
118/* round up and down to page boundaries. */
119#define	ELF_ROUND(a, b)		(((a) + (b) - 1) & ~((b) - 1))
120#define	ELF_TRUNC(a, b)		((a) & ~((b) - 1))
121
122#define MAXPHNUM	50
123
124#ifdef PAX_ASLR
125/*
126 * We don't move this code in kern_pax.c because it is compiled twice.
127 */
128static void
129pax_aslr_elf(struct lwp *l, struct exec_package *epp, Elf_Ehdr *eh,
130    Elf_Phdr *ph)
131{
132	size_t pax_align = 0, pax_offset, i;
133	uint32_t r;
134
135	if (!pax_aslr_active(l))
136		return;
137
138	/*
139	 * find align XXX: not all sections might have the same
140	 * alignment
141	 */
142	for (i = 0; i < eh->e_phnum; i++)
143		if (ph[i].p_type == PT_LOAD) {
144			pax_align = ph[i].p_align;
145			break;
146		}
147
148	r = arc4random();
149
150	if (pax_align == 0)
151		pax_align = PGSHIFT;
152#ifdef DEBUG_ASLR
153	uprintf("r=0x%x a=0x%x p=0x%x Delta=0x%lx\n", r,
154	    ilog2(pax_align), PGSHIFT, PAX_ASLR_DELTA(r,
155		ilog2(pax_align), PAX_ASLR_DELTA_EXEC_LEN));
156#endif
157	pax_offset = ELF_TRUNC(PAX_ASLR_DELTA(r,
158	    ilog2(pax_align), PAX_ASLR_DELTA_EXEC_LEN), pax_align);
159
160	for (i = 0; i < eh->e_phnum; i++)
161		ph[i].p_vaddr += pax_offset;
162	eh->e_entry += pax_offset;
163#ifdef DEBUG_ASLR
164	uprintf("pax offset=0x%x entry=0x%x\n",
165	    pax_offset, eh->e_entry);
166#endif
167}
168#endif /* PAX_ASLR */
169
170/*
171 * Copy arguments onto the stack in the normal way, but add some
172 * extra information in case of dynamic binding.
173 */
174int
175elf_copyargs(struct lwp *l, struct exec_package *pack,
176    struct ps_strings *arginfo, char **stackp, void *argp)
177{
178	size_t len, vlen;
179	AuxInfo ai[ELF_AUX_ENTRIES], *a, *execname;
180	struct elf_args *ap;
181	int error;
182
183	if ((error = copyargs(l, pack, arginfo, stackp, argp)) != 0)
184		return error;
185
186	a = ai;
187	execname = NULL;
188
189	/*
190	 * Push extra arguments on the stack needed by dynamically
191	 * linked binaries
192	 */
193	if ((ap = (struct elf_args *)pack->ep_emul_arg)) {
194		struct vattr *vap = pack->ep_vap;
195
196		a->a_type = AT_PHDR;
197		a->a_v = ap->arg_phaddr;
198		a++;
199
200		a->a_type = AT_PHENT;
201		a->a_v = ap->arg_phentsize;
202		a++;
203
204		a->a_type = AT_PHNUM;
205		a->a_v = ap->arg_phnum;
206		a++;
207
208		a->a_type = AT_PAGESZ;
209		a->a_v = PAGE_SIZE;
210		a++;
211
212		a->a_type = AT_BASE;
213		a->a_v = ap->arg_interp;
214		a++;
215
216		a->a_type = AT_FLAGS;
217		a->a_v = 0;
218		a++;
219
220		a->a_type = AT_ENTRY;
221		a->a_v = ap->arg_entry;
222		a++;
223
224		a->a_type = AT_EUID;
225		if (vap->va_mode & S_ISUID)
226			a->a_v = vap->va_uid;
227		else
228			a->a_v = kauth_cred_geteuid(l->l_cred);
229		a++;
230
231		a->a_type = AT_RUID;
232		a->a_v = kauth_cred_getuid(l->l_cred);
233		a++;
234
235		a->a_type = AT_EGID;
236		if (vap->va_mode & S_ISGID)
237			a->a_v = vap->va_gid;
238		else
239			a->a_v = kauth_cred_getegid(l->l_cred);
240		a++;
241
242		a->a_type = AT_RGID;
243		a->a_v = kauth_cred_getgid(l->l_cred);
244		a++;
245
246		if (pack->ep_path) {
247			execname = a;
248			a->a_type = AT_SUN_EXECNAME;
249			a++;
250		}
251
252		free(ap, M_TEMP);
253		pack->ep_emul_arg = NULL;
254	}
255
256	a->a_type = AT_NULL;
257	a->a_v = 0;
258	a++;
259
260	vlen = (a - ai) * sizeof(AuxInfo);
261
262	if (execname) {
263		char *path = pack->ep_path;
264		execname->a_v = (intptr_t)(*stackp + vlen);
265		len = strlen(path) + 1;
266		if ((error = copyout(path, (*stackp + vlen), len)) != 0)
267			return error;
268		len = ALIGN(len);
269	} else
270		len = 0;
271
272	if ((error = copyout(ai, *stackp, vlen)) != 0)
273		return error;
274	*stackp += vlen + len;
275
276	return 0;
277}
278
279/*
280 * elf_check_header():
281 *
282 * Check header for validity; return 0 of ok ENOEXEC if error
283 */
284int
285elf_check_header(Elf_Ehdr *eh, int type)
286{
287
288	if (memcmp(eh->e_ident, ELFMAG, SELFMAG) != 0 ||
289	    eh->e_ident[EI_CLASS] != ELFCLASS)
290		return ENOEXEC;
291
292	switch (eh->e_machine) {
293
294	ELFDEFNNAME(MACHDEP_ID_CASES)
295
296	default:
297		return ENOEXEC;
298	}
299
300	if (ELF_EHDR_FLAGS_OK(eh) == 0)
301		return ENOEXEC;
302
303	if (eh->e_type != type)
304		return ENOEXEC;
305
306	if (eh->e_shnum > 32768 || eh->e_phnum > 128)
307		return ENOEXEC;
308
309	return 0;
310}
311
312/*
313 * elf_load_psection():
314 *
315 * Load a psection at the appropriate address
316 */
317void
318elf_load_psection(struct exec_vmcmd_set *vcset, struct vnode *vp,
319    const Elf_Phdr *ph, Elf_Addr *addr, u_long *size, int *prot, int flags)
320{
321	u_long msize, psize, rm, rf;
322	long diff, offset;
323
324	/*
325	 * If the user specified an address, then we load there.
326	 */
327	if (*addr == ELFDEFNNAME(NO_ADDR))
328		*addr = ph->p_vaddr;
329
330	if (ph->p_align > 1) {
331		/*
332		 * Make sure we are virtually aligned as we are supposed to be.
333		 */
334		diff = ph->p_vaddr - ELF_TRUNC(ph->p_vaddr, ph->p_align);
335		KASSERT(*addr - diff == ELF_TRUNC(*addr, ph->p_align));
336		/*
337		 * But make sure to not map any pages before the start of the
338		 * psection by limiting the difference to within a page.
339		 */
340		diff &= PAGE_MASK;
341	} else
342		diff = 0;
343
344	*prot |= (ph->p_flags & PF_R) ? VM_PROT_READ : 0;
345	*prot |= (ph->p_flags & PF_W) ? VM_PROT_WRITE : 0;
346	*prot |= (ph->p_flags & PF_X) ? VM_PROT_EXECUTE : 0;
347
348	/*
349	 * Adjust everything so it all starts on a page boundary.
350	 */
351	*addr -= diff;
352	offset = ph->p_offset - diff;
353	*size = ph->p_filesz + diff;
354	msize = ph->p_memsz + diff;
355
356	if (ph->p_align >= PAGE_SIZE) {
357		if ((ph->p_flags & PF_W) != 0) {
358			/*
359			 * Because the pagedvn pager can't handle zero fill
360			 * of the last data page if it's not page aligned we
361			 * map the last page readvn.
362			 */
363			psize = trunc_page(*size);
364		} else {
365			psize = round_page(*size);
366		}
367	} else {
368		psize = *size;
369	}
370
371	if (psize > 0) {
372		NEW_VMCMD2(vcset, ph->p_align < PAGE_SIZE ?
373		    vmcmd_map_readvn : vmcmd_map_pagedvn, psize, *addr, vp,
374		    offset, *prot, flags);
375		flags &= VMCMD_RELATIVE;
376	}
377	if (psize < *size) {
378		NEW_VMCMD2(vcset, vmcmd_map_readvn, *size - psize,
379		    *addr + psize, vp, offset + psize, *prot, flags);
380	}
381
382	/*
383	 * Check if we need to extend the size of the segment (does
384	 * bss extend page the next page boundary)?
385	 */
386	rm = round_page(*addr + msize);
387	rf = round_page(*addr + *size);
388
389	if (rm != rf) {
390		NEW_VMCMD2(vcset, vmcmd_map_zero, rm - rf, rf, NULLVP,
391		    0, *prot, flags & VMCMD_RELATIVE);
392		*size = msize;
393	}
394}
395
396/*
397 * elf_load_file():
398 *
399 * Load a file (interpreter/library) pointed to by path
400 * [stolen from coff_load_shlib()]. Made slightly generic
401 * so it might be used externally.
402 */
403int
404elf_load_file(struct lwp *l, struct exec_package *epp, char *path,
405    struct exec_vmcmd_set *vcset, u_long *entryoff, struct elf_args *ap,
406    Elf_Addr *last)
407{
408	int error, i;
409	struct vnode *vp;
410	struct vattr attr;
411	Elf_Ehdr eh;
412	Elf_Phdr *ph = NULL;
413	const Elf_Phdr *ph0;
414	const Elf_Phdr *base_ph;
415	const Elf_Phdr *last_ph;
416	u_long phsize;
417	Elf_Addr addr = *last;
418	struct proc *p;
419
420	p = l->l_proc;
421
422	/*
423	 * 1. open file
424	 * 2. read filehdr
425	 * 3. map text, data, and bss out of it using VM_*
426	 */
427	vp = epp->ep_interp;
428	if (vp == NULL) {
429		error = emul_find_interp(l, epp, path);
430		if (error != 0)
431			return error;
432		vp = epp->ep_interp;
433	}
434	/* We'll tidy this ourselves - otherwise we have locking issues */
435	epp->ep_interp = NULL;
436	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
437
438	/*
439	 * Similarly, if it's not marked as executable, or it's not a regular
440	 * file, we don't allow it to be used.
441	 */
442	if (vp->v_type != VREG) {
443		error = EACCES;
444		goto badunlock;
445	}
446	if ((error = VOP_ACCESS(vp, VEXEC, l->l_cred)) != 0)
447		goto badunlock;
448
449	/* get attributes */
450	if ((error = VOP_GETATTR(vp, &attr, l->l_cred)) != 0)
451		goto badunlock;
452
453	/*
454	 * Check mount point.  Though we're not trying to exec this binary,
455	 * we will be executing code from it, so if the mount point
456	 * disallows execution or set-id-ness, we punt or kill the set-id.
457	 */
458	if (vp->v_mount->mnt_flag & MNT_NOEXEC) {
459		error = EACCES;
460		goto badunlock;
461	}
462	if (vp->v_mount->mnt_flag & MNT_NOSUID)
463		epp->ep_vap->va_mode &= ~(S_ISUID | S_ISGID);
464
465#ifdef notyet /* XXX cgd 960926 */
466	XXX cgd 960926: (maybe) VOP_OPEN it (and VOP_CLOSE in copyargs?)
467#endif
468
469	error = vn_marktext(vp);
470	if (error)
471		goto badunlock;
472
473	VOP_UNLOCK(vp, 0);
474
475	if ((error = exec_read_from(l, vp, 0, &eh, sizeof(eh))) != 0)
476		goto bad;
477
478	if ((error = elf_check_header(&eh, ET_DYN)) != 0)
479		goto bad;
480
481	if (eh.e_phnum > MAXPHNUM || eh.e_phnum == 0) {
482		error = ENOEXEC;
483		goto bad;
484	}
485
486	phsize = eh.e_phnum * sizeof(Elf_Phdr);
487	ph = (Elf_Phdr *)malloc(phsize, M_TEMP, M_WAITOK);
488
489	if ((error = exec_read_from(l, vp, eh.e_phoff, ph, phsize)) != 0)
490		goto bad;
491
492#ifdef ELF_INTERP_NON_RELOCATABLE
493	/*
494	 * Evil hack:  Only MIPS should be non-relocatable, and the
495	 * psections should have a high address (typically 0x5ffe0000).
496	 * If it's now relocatable, it should be linked at 0 and the
497	 * psections should have zeros in the upper part of the address.
498	 * Otherwise, force the load at the linked address.
499	 */
500	if (*last == ELF_LINK_ADDR && (ph->p_vaddr & 0xffff0000) == 0)
501		*last = ELFDEFNNAME(NO_ADDR);
502#endif
503
504	/*
505	 * If no position to load the interpreter was set by a probe
506	 * function, pick the same address that a non-fixed mmap(0, ..)
507	 * would (i.e. something safely out of the way).
508	 */
509	if (*last == ELFDEFNNAME(NO_ADDR)) {
510		u_long limit = 0;
511		/*
512		 * Find the start and ending addresses of the psections to
513		 * be loaded.  This will give us the size.
514		 */
515		for (i = 0, ph0 = ph, base_ph = NULL; i < eh.e_phnum;
516		     i++, ph0++) {
517			if (ph0->p_type == PT_LOAD) {
518				u_long psize = ph0->p_vaddr + ph0->p_memsz;
519				if (base_ph == NULL)
520					base_ph = ph0;
521				if (psize > limit)
522					limit = psize;
523			}
524		}
525
526		if (base_ph == NULL) {
527			error = ENOEXEC;
528			goto bad;
529		}
530
531		/*
532		 * Now compute the size and load address.
533		 */
534		addr = (*epp->ep_esch->es_emul->e_vm_default_addr)(p,
535		    epp->ep_daddr,
536		    round_page(limit) - trunc_page(base_ph->p_vaddr));
537	} else
538		addr = *last; /* may be ELF_LINK_ADDR */
539
540	/*
541	 * Load all the necessary sections
542	 */
543	for (i = 0, ph0 = ph, base_ph = NULL, last_ph = NULL;
544	     i < eh.e_phnum; i++, ph0++) {
545		switch (ph0->p_type) {
546		case PT_LOAD: {
547			u_long size;
548			int prot = 0;
549			int flags;
550
551			if (base_ph == NULL) {
552				/*
553				 * First encountered psection is always the
554				 * base psection.  Make sure it's aligned
555				 * properly (align down for topdown and align
556				 * upwards for not topdown).
557				 */
558				base_ph = ph0;
559				flags = VMCMD_BASE;
560				if (addr == ELF_LINK_ADDR)
561					addr = ph0->p_vaddr;
562				if (p->p_vmspace->vm_map.flags & VM_MAP_TOPDOWN)
563					addr = ELF_TRUNC(addr, ph0->p_align);
564				else
565					addr = ELF_ROUND(addr, ph0->p_align);
566			} else {
567				u_long limit = round_page(last_ph->p_vaddr
568				    + last_ph->p_memsz);
569				u_long base = trunc_page(ph0->p_vaddr);
570
571				/*
572				 * If there is a gap in between the psections,
573				 * map it as inaccessible so nothing else
574				 * mmap'ed will be placed there.
575				 */
576				if (limit != base) {
577					NEW_VMCMD2(vcset, vmcmd_map_zero,
578					    base - limit,
579					    limit - base_ph->p_vaddr, NULLVP,
580					    0, VM_PROT_NONE, VMCMD_RELATIVE);
581				}
582
583				addr = ph0->p_vaddr - base_ph->p_vaddr;
584				flags = VMCMD_RELATIVE;
585			}
586			last_ph = ph0;
587			elf_load_psection(vcset, vp, &ph[i], &addr,
588			    &size, &prot, flags);
589			/*
590			 * If entry is within this psection then this
591			 * must contain the .text section.  *entryoff is
592			 * relative to the base psection.
593			 */
594			if (eh.e_entry >= ph0->p_vaddr &&
595			    eh.e_entry < (ph0->p_vaddr + size)) {
596				*entryoff = eh.e_entry - base_ph->p_vaddr;
597			}
598			addr += size;
599			break;
600		}
601
602		case PT_DYNAMIC:
603		case PT_PHDR:
604			break;
605
606		case PT_NOTE:
607			break;
608
609		default:
610			break;
611		}
612	}
613
614	free(ph, M_TEMP);
615	/*
616	 * This value is ignored if TOPDOWN.
617	 */
618	*last = addr;
619	vrele(vp);
620	return 0;
621
622badunlock:
623	VOP_UNLOCK(vp, 0);
624
625bad:
626	if (ph != NULL)
627		free(ph, M_TEMP);
628#ifdef notyet /* XXX cgd 960926 */
629	(maybe) VOP_CLOSE it
630#endif
631	vrele(vp);
632	return error;
633}
634
635/*
636 * exec_elf_makecmds(): Prepare an Elf binary's exec package
637 *
638 * First, set of the various offsets/lengths in the exec package.
639 *
640 * Then, mark the text image busy (so it can be demand paged) or error
641 * out if this is not possible.  Finally, set up vmcmds for the
642 * text, data, bss, and stack segments.
643 */
644int
645exec_elf_makecmds(struct lwp *l, struct exec_package *epp)
646{
647	Elf_Ehdr *eh = epp->ep_hdr;
648	Elf_Phdr *ph, *pp;
649	Elf_Addr phdr = 0, pos = 0;
650	int error, i, nload;
651	char *interp = NULL;
652	u_long phsize;
653	struct proc *p;
654	bool is_dyn;
655
656	if (epp->ep_hdrvalid < sizeof(Elf_Ehdr))
657		return ENOEXEC;
658
659	is_dyn = elf_check_header(eh, ET_DYN) == 0;
660	/*
661	 * XXX allow for executing shared objects. It seems silly
662	 * but other ELF-based systems allow it as well.
663	 */
664	if (elf_check_header(eh, ET_EXEC) != 0 && !is_dyn)
665		return ENOEXEC;
666
667	if (eh->e_phnum > MAXPHNUM || eh->e_phnum == 0)
668		return ENOEXEC;
669
670	error = vn_marktext(epp->ep_vp);
671	if (error)
672		return error;
673
674	/*
675	 * Allocate space to hold all the program headers, and read them
676	 * from the file
677	 */
678	p = l->l_proc;
679	phsize = eh->e_phnum * sizeof(Elf_Phdr);
680	ph = (Elf_Phdr *)malloc(phsize, M_TEMP, M_WAITOK);
681
682	if ((error = exec_read_from(l, epp->ep_vp, eh->e_phoff, ph, phsize)) !=
683	    0)
684		goto bad;
685
686	epp->ep_taddr = epp->ep_tsize = ELFDEFNNAME(NO_ADDR);
687	epp->ep_daddr = epp->ep_dsize = ELFDEFNNAME(NO_ADDR);
688
689	for (i = 0; i < eh->e_phnum; i++) {
690		pp = &ph[i];
691		if (pp->p_type == PT_INTERP) {
692			if (pp->p_filesz >= MAXPATHLEN) {
693				error = ENOEXEC;
694				goto bad;
695			}
696			interp = PNBUF_GET();
697			interp[0] = '\0';
698			if ((error = exec_read_from(l, epp->ep_vp,
699			    pp->p_offset, interp, pp->p_filesz)) != 0)
700				goto bad;
701			break;
702		}
703	}
704
705	/*
706	 * On the same architecture, we may be emulating different systems.
707	 * See which one will accept this executable.
708	 *
709	 * Probe functions would normally see if the interpreter (if any)
710	 * exists. Emulation packages may possibly replace the interpreter in
711	 * interp[] with a changed path (/emul/xxx/<path>).
712	 */
713	pos = ELFDEFNNAME(NO_ADDR);
714	if (epp->ep_esch->u.elf_probe_func) {
715		vaddr_t startp = (vaddr_t)pos;
716
717		error = (*epp->ep_esch->u.elf_probe_func)(l, epp, eh, interp,
718							  &startp);
719		if (error)
720			goto bad;
721		pos = (Elf_Addr)startp;
722	}
723
724#if defined(PAX_MPROTECT) || defined(PAX_SEGVGUARD) || defined(PAX_ASLR)
725	if (epp->ep_pax_flags)
726		pax_adjust(l, epp->ep_pax_flags);
727#endif /* PAX_MPROTECT || PAX_SEGVGUARD || PAX_ASLR */
728
729#ifdef PAX_ASLR
730	if (is_dyn)
731		pax_aslr_elf(l, epp, eh, ph);
732#endif /* PAX_ASLR */
733
734	/*
735	 * Load all the necessary sections
736	 */
737	for (i = nload = 0; i < eh->e_phnum; i++) {
738		Elf_Addr  addr = ELFDEFNNAME(NO_ADDR);
739		u_long size = 0;
740		int prot = 0;
741
742		pp = &ph[i];
743
744		switch (ph[i].p_type) {
745		case PT_LOAD:
746			/*
747			 * XXX
748			 * Can handle only 2 sections: text and data
749			 */
750			if (nload++ == 2) {
751				error = ENOEXEC;
752				goto bad;
753			}
754			elf_load_psection(&epp->ep_vmcmds, epp->ep_vp,
755			    &ph[i], &addr, &size, &prot, VMCMD_FIXED);
756
757			/*
758			 * Decide whether it's text or data by looking
759			 * at the entry point.
760			 */
761			if (eh->e_entry >= addr &&
762			    eh->e_entry < (addr + size)) {
763				epp->ep_taddr = addr;
764				epp->ep_tsize = size;
765				if (epp->ep_daddr == ELFDEFNNAME(NO_ADDR)) {
766					epp->ep_daddr = addr;
767					epp->ep_dsize = size;
768				}
769			} else {
770				epp->ep_daddr = addr;
771				epp->ep_dsize = size;
772			}
773			break;
774
775		case PT_SHLIB:
776			/* SCO has these sections. */
777		case PT_INTERP:
778			/* Already did this one. */
779		case PT_DYNAMIC:
780			break;
781		case PT_NOTE:
782			break;
783		case PT_PHDR:
784			/* Note address of program headers (in text segment) */
785			phdr = pp->p_vaddr;
786			break;
787
788		default:
789			/*
790			 * Not fatal; we don't need to understand everything.
791			 */
792			break;
793		}
794	}
795
796	/*
797	 * Check if we found a dynamically linked binary and arrange to load
798	 * its interpreter
799	 */
800	if (interp) {
801		struct elf_args *ap;
802		int j = epp->ep_vmcmds.evs_used;
803		u_long interp_offset;
804
805		MALLOC(ap, struct elf_args *, sizeof(struct elf_args),
806		    M_TEMP, M_WAITOK);
807		if ((error = elf_load_file(l, epp, interp,
808		    &epp->ep_vmcmds, &interp_offset, ap, &pos)) != 0) {
809			FREE(ap, M_TEMP);
810			goto bad;
811		}
812		ap->arg_interp = epp->ep_vmcmds.evs_cmds[j].ev_addr;
813		epp->ep_entry = ap->arg_interp + interp_offset;
814		ap->arg_phaddr = phdr;
815
816		ap->arg_phentsize = eh->e_phentsize;
817		ap->arg_phnum = eh->e_phnum;
818		ap->arg_entry = eh->e_entry;
819
820		epp->ep_emul_arg = ap;
821
822		PNBUF_PUT(interp);
823	} else
824		epp->ep_entry = eh->e_entry;
825
826#ifdef ELF_MAP_PAGE_ZERO
827	/* Dell SVR4 maps page zero, yeuch! */
828	NEW_VMCMD(&epp->ep_vmcmds, vmcmd_map_readvn, PAGE_SIZE, 0,
829	    epp->ep_vp, 0, VM_PROT_READ);
830#endif
831	free(ph, M_TEMP);
832	return (*epp->ep_esch->es_setup_stack)(l, epp);
833
834bad:
835	if (interp)
836		PNBUF_PUT(interp);
837	free(ph, M_TEMP);
838	kill_vmcmds(&epp->ep_vmcmds);
839	return error;
840}
841
842int
843netbsd_elf_signature(struct lwp *l, struct exec_package *epp,
844    Elf_Ehdr *eh)
845{
846	size_t i;
847	Elf_Phdr *ph;
848	size_t phsize;
849	int error;
850	int isnetbsd = 0;
851	char *ndata;
852
853	epp->ep_pax_flags = 0;
854	if (eh->e_phnum > MAXPHNUM || eh->e_phnum == 0)
855		return ENOEXEC;
856
857	phsize = eh->e_phnum * sizeof(Elf_Phdr);
858	ph = (Elf_Phdr *)malloc(phsize, M_TEMP, M_WAITOK);
859	error = exec_read_from(l, epp->ep_vp, eh->e_phoff, ph, phsize);
860	if (error)
861		goto out;
862
863	for (i = 0; i < eh->e_phnum; i++) {
864		Elf_Phdr *ephp = &ph[i];
865		Elf_Nhdr *np;
866
867		if (ephp->p_type != PT_NOTE ||
868		    ephp->p_filesz > 1024 ||
869		    ephp->p_filesz < sizeof(Elf_Nhdr) + ELF_NOTE_NETBSD_NAMESZ)
870			continue;
871
872		np = (Elf_Nhdr *)malloc(ephp->p_filesz, M_TEMP, M_WAITOK);
873		error = exec_read_from(l, epp->ep_vp, ephp->p_offset, np,
874		    ephp->p_filesz);
875		if (error)
876			goto next;
877
878		ndata = (char *)(np + 1);
879		switch (np->n_type) {
880		case ELF_NOTE_TYPE_NETBSD_TAG:
881			if (np->n_namesz != ELF_NOTE_NETBSD_NAMESZ ||
882			    np->n_descsz != ELF_NOTE_NETBSD_DESCSZ ||
883			    memcmp(ndata, ELF_NOTE_NETBSD_NAME,
884			    ELF_NOTE_NETBSD_NAMESZ))
885				goto next;
886			isnetbsd = 1;
887			break;
888
889		case ELF_NOTE_TYPE_PAX_TAG:
890			if (np->n_namesz != ELF_NOTE_PAX_NAMESZ ||
891			    np->n_descsz != ELF_NOTE_PAX_DESCSZ ||
892			    memcmp(ndata, ELF_NOTE_PAX_NAME,
893			    ELF_NOTE_PAX_NAMESZ))
894				goto next;
895			(void)memcpy(&epp->ep_pax_flags,
896			    ndata + ELF_NOTE_PAX_NAMESZ,
897			    sizeof(epp->ep_pax_flags));
898			break;
899
900		default:
901			break;
902		}
903
904next:
905		free(np, M_TEMP);
906		continue;
907	}
908
909	error = isnetbsd ? 0 : ENOEXEC;
910out:
911	free(ph, M_TEMP);
912	return error;
913}
914
915int
916netbsd_elf_probe(struct lwp *l, struct exec_package *epp, void *eh, char *itp,
917    vaddr_t *pos)
918{
919	int error;
920
921	if ((error = netbsd_elf_signature(l, epp, eh)) != 0)
922		return error;
923#ifdef ELF_INTERP_NON_RELOCATABLE
924	*pos = ELF_LINK_ADDR;
925#endif
926	return 0;
927}
928