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