xref: /netbsd-src/sys/kern/exec_elf.c (revision 946379e7b37692fc43f68eb0d1c10daa0a7f3b6c)
1 /*	$NetBSD: exec_elf.c,v 1.81 2015/11/26 13:15:34 martin Exp $	*/
2 
3 /*-
4  * Copyright (c) 1994, 2000, 2005, 2015 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 and Maxime Villard.
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.81 2015/11/26 13:15:34 martin 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 static void
119 elf_placedynexec(struct exec_package *epp, Elf_Ehdr *eh, Elf_Phdr *ph)
120 {
121 	Elf_Addr align, offset;
122 	int i;
123 
124 	for (align = i = 0; i < eh->e_phnum; i++)
125 		if (ph[i].p_type == PT_LOAD && ph[i].p_align > align)
126 			align = ph[i].p_align;
127 
128 #ifdef PAX_ASLR
129 	if (pax_aslr_epp_active(epp)) {
130 		size_t pax_align, l2, delta;
131 		uint32_t r;
132 
133 		pax_align = align;
134 
135 		r = cprng_fast32();
136 
137 		if (pax_align == 0)
138 			pax_align = PGSHIFT;
139 		l2 = ilog2(pax_align);
140 		delta = PAX_ASLR_DELTA(r, l2, PAX_ASLR_DELTA_EXEC_LEN);
141 		offset = ELF_TRUNC(delta, pax_align) + PAGE_SIZE;
142 #ifdef PAX_ASLR_DEBUG
143 		uprintf("r=0x%x l2=0x%zx PGSHIFT=0x%x Delta=0x%zx\n", r, l2,
144 		    PGSHIFT, delta);
145 		uprintf("pax offset=0x%llx entry=0x%llx\n",
146 		    (unsigned long long)offset,
147 		    (unsigned long long)eh->e_entry);
148 #endif /* PAX_ASLR_DEBUG */
149 	} else
150 #endif /* PAX_ASLR */
151 		offset = MAX(align, PAGE_SIZE);
152 
153 	offset += epp->ep_vm_minaddr;
154 
155 	for (i = 0; i < eh->e_phnum; i++)
156 		ph[i].p_vaddr += offset;
157 	epp->ep_entryoffset = offset;
158 	eh->e_entry += offset;
159 }
160 
161 /*
162  * Copy arguments onto the stack in the normal way, but add some
163  * extra information in case of dynamic binding.
164  */
165 int
166 elf_copyargs(struct lwp *l, struct exec_package *pack,
167     struct ps_strings *arginfo, char **stackp, void *argp)
168 {
169 	size_t len, vlen;
170 	AuxInfo ai[ELF_AUX_ENTRIES], *a, *execname;
171 	struct elf_args *ap;
172 	int error;
173 
174 	if ((error = copyargs(l, pack, arginfo, stackp, argp)) != 0)
175 		return error;
176 
177 	a = ai;
178 	execname = NULL;
179 
180 	memset(ai, 0, sizeof(ai));
181 
182 	/*
183 	 * Push extra arguments on the stack needed by dynamically
184 	 * linked binaries
185 	 */
186 	if ((ap = (struct elf_args *)pack->ep_emul_arg)) {
187 		struct vattr *vap = pack->ep_vap;
188 
189 		a->a_type = AT_PHDR;
190 		a->a_v = ap->arg_phaddr;
191 		a++;
192 
193 		a->a_type = AT_PHENT;
194 		a->a_v = ap->arg_phentsize;
195 		a++;
196 
197 		a->a_type = AT_PHNUM;
198 		a->a_v = ap->arg_phnum;
199 		a++;
200 
201 		a->a_type = AT_PAGESZ;
202 		a->a_v = PAGE_SIZE;
203 		a++;
204 
205 		a->a_type = AT_BASE;
206 		a->a_v = ap->arg_interp;
207 		a++;
208 
209 		a->a_type = AT_FLAGS;
210 		a->a_v = 0;
211 		a++;
212 
213 		a->a_type = AT_ENTRY;
214 		a->a_v = ap->arg_entry;
215 		a++;
216 
217 		a->a_type = AT_EUID;
218 		if (vap->va_mode & S_ISUID)
219 			a->a_v = vap->va_uid;
220 		else
221 			a->a_v = kauth_cred_geteuid(l->l_cred);
222 		a++;
223 
224 		a->a_type = AT_RUID;
225 		a->a_v = kauth_cred_getuid(l->l_cred);
226 		a++;
227 
228 		a->a_type = AT_EGID;
229 		if (vap->va_mode & S_ISGID)
230 			a->a_v = vap->va_gid;
231 		else
232 			a->a_v = kauth_cred_getegid(l->l_cred);
233 		a++;
234 
235 		a->a_type = AT_RGID;
236 		a->a_v = kauth_cred_getgid(l->l_cred);
237 		a++;
238 
239 		a->a_type = AT_STACKBASE;
240 		a->a_v = l->l_proc->p_stackbase;
241 		a++;
242 
243 		if (pack->ep_path) {
244 			execname = a;
245 			a->a_type = AT_SUN_EXECNAME;
246 			a++;
247 		}
248 
249 		exec_free_emul_arg(pack);
250 	}
251 
252 	a->a_type = AT_NULL;
253 	a->a_v = 0;
254 	a++;
255 
256 	vlen = (a - ai) * sizeof(ai[0]);
257 
258 	KASSERT(vlen <= sizeof(ai));
259 
260 	if (execname) {
261 		char *path = pack->ep_path;
262 		execname->a_v = (uintptr_t)(*stackp + vlen);
263 		len = strlen(path) + 1;
264 		if ((error = copyout(path, (*stackp + vlen), len)) != 0)
265 			return error;
266 		len = ALIGN(len);
267 	} else
268 		len = 0;
269 
270 	if ((error = copyout(ai, *stackp, vlen)) != 0)
271 		return error;
272 	*stackp += vlen + len;
273 
274 	return 0;
275 }
276 
277 /*
278  * elf_check_header():
279  *
280  * Check header for validity; return 0 if ok, ENOEXEC if error
281  */
282 int
283 elf_check_header(Elf_Ehdr *eh)
284 {
285 
286 	if (memcmp(eh->e_ident, ELFMAG, SELFMAG) != 0 ||
287 	    eh->e_ident[EI_CLASS] != ELFCLASS)
288 		return ENOEXEC;
289 
290 	switch (eh->e_machine) {
291 
292 	ELFDEFNNAME(MACHDEP_ID_CASES)
293 
294 	default:
295 		return ENOEXEC;
296 	}
297 
298 	if (ELF_EHDR_FLAGS_OK(eh) == 0)
299 		return ENOEXEC;
300 
301 	if (eh->e_shnum > ELF_MAXSHNUM || eh->e_phnum > ELF_MAXPHNUM)
302 		return ENOEXEC;
303 
304 	return 0;
305 }
306 
307 /*
308  * elf_load_psection():
309  *
310  * Load a psection at the appropriate address
311  */
312 static void
313 elf_load_psection(struct exec_vmcmd_set *vcset, struct vnode *vp,
314     const Elf_Phdr *ph, Elf_Addr *addr, u_long *size, int flags)
315 {
316 	u_long msize, psize, rm, rf;
317 	long diff, offset;
318 	int vmprot = 0;
319 
320 	/*
321 	 * If the user specified an address, then we load there.
322 	 */
323 	if (*addr == ELFDEFNNAME(NO_ADDR))
324 		*addr = ph->p_vaddr;
325 
326 	if (ph->p_align > 1) {
327 		/*
328 		 * Make sure we are virtually aligned as we are supposed to be.
329 		 */
330 		diff = ph->p_vaddr - ELF_TRUNC(ph->p_vaddr, ph->p_align);
331 		KASSERT(*addr - diff == ELF_TRUNC(*addr, ph->p_align));
332 		/*
333 		 * But make sure to not map any pages before the start of the
334 		 * psection by limiting the difference to within a page.
335 		 */
336 		diff &= PAGE_MASK;
337 	} else
338 		diff = 0;
339 
340 	vmprot |= (ph->p_flags & PF_R) ? VM_PROT_READ : 0;
341 	vmprot |= (ph->p_flags & PF_W) ? VM_PROT_WRITE : 0;
342 	vmprot |= (ph->p_flags & PF_X) ? VM_PROT_EXECUTE : 0;
343 
344 	/*
345 	 * Adjust everything so it all starts on a page boundary.
346 	 */
347 	*addr -= diff;
348 	offset = ph->p_offset - diff;
349 	*size = ph->p_filesz + diff;
350 	msize = ph->p_memsz + diff;
351 
352 	if (ph->p_align >= PAGE_SIZE) {
353 		if ((ph->p_flags & PF_W) != 0) {
354 			/*
355 			 * Because the pagedvn pager can't handle zero fill
356 			 * of the last data page if it's not page aligned we
357 			 * map the last page readvn.
358 			 */
359 			psize = trunc_page(*size);
360 		} else {
361 			psize = round_page(*size);
362 		}
363 	} else {
364 		psize = *size;
365 	}
366 
367 	if (psize > 0) {
368 		NEW_VMCMD2(vcset, ph->p_align < PAGE_SIZE ?
369 		    vmcmd_map_readvn : vmcmd_map_pagedvn, psize, *addr, vp,
370 		    offset, vmprot, flags);
371 		flags &= VMCMD_RELATIVE;
372 	}
373 	if (psize < *size) {
374 		NEW_VMCMD2(vcset, vmcmd_map_readvn, *size - psize,
375 		    *addr + psize, vp, offset + psize, vmprot, flags);
376 	}
377 
378 	/*
379 	 * Check if we need to extend the size of the segment (does
380 	 * bss extend page the next page boundary)?
381 	 */
382 	rm = round_page(*addr + msize);
383 	rf = round_page(*addr + *size);
384 
385 	if (rm != rf) {
386 		NEW_VMCMD2(vcset, vmcmd_map_zero, rm - rf, rf, NULLVP,
387 		    0, vmprot, flags & VMCMD_RELATIVE);
388 		*size = msize;
389 	}
390 }
391 
392 /*
393  * elf_load_interp():
394  *
395  * Load an interpreter pointed to by path.
396  */
397 static int
398 elf_load_interp(struct lwp *l, struct exec_package *epp, char *path,
399     struct exec_vmcmd_set *vcset, u_long *entryoff, Elf_Addr *last)
400 {
401 	int error, i;
402 	struct vnode *vp;
403 	struct vattr attr;
404 	Elf_Ehdr eh;
405 	Elf_Phdr *ph = NULL;
406 	const Elf_Phdr *base_ph;
407 	const Elf_Phdr *last_ph;
408 	u_long phsize;
409 	Elf_Addr addr = *last;
410 	struct proc *p;
411 	bool use_topdown;
412 
413 	p = l->l_proc;
414 
415 	KASSERT(p->p_vmspace);
416 	KASSERT(p->p_vmspace != proc0.p_vmspace);
417 
418 #ifdef __USE_TOPDOWN_VM
419 	use_topdown = epp->ep_flags & EXEC_TOPDOWN_VM;
420 #else
421 	use_topdown = false;
422 #endif
423 
424 	/*
425 	 * 1. open file
426 	 * 2. read filehdr
427 	 * 3. map text, data, and bss out of it using VM_*
428 	 */
429 	vp = epp->ep_interp;
430 	if (vp == NULL) {
431 		error = emul_find_interp(l, epp, path);
432 		if (error != 0)
433 			return error;
434 		vp = epp->ep_interp;
435 	}
436 	/* We'll tidy this ourselves - otherwise we have locking issues */
437 	epp->ep_interp = NULL;
438 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
439 
440 	/*
441 	 * Similarly, if it's not marked as executable, or it's not a regular
442 	 * file, we don't allow it to be used.
443 	 */
444 	if (vp->v_type != VREG) {
445 		error = EACCES;
446 		goto badunlock;
447 	}
448 	if ((error = VOP_ACCESS(vp, VEXEC, l->l_cred)) != 0)
449 		goto badunlock;
450 
451 	/* get attributes */
452 	if ((error = VOP_GETATTR(vp, &attr, l->l_cred)) != 0)
453 		goto badunlock;
454 
455 	/*
456 	 * Check mount point.  Though we're not trying to exec this binary,
457 	 * we will be executing code from it, so if the mount point
458 	 * disallows execution or set-id-ness, we punt or kill the set-id.
459 	 */
460 	if (vp->v_mount->mnt_flag & MNT_NOEXEC) {
461 		error = EACCES;
462 		goto badunlock;
463 	}
464 	if (vp->v_mount->mnt_flag & MNT_NOSUID)
465 		epp->ep_vap->va_mode &= ~(S_ISUID | S_ISGID);
466 
467 	error = vn_marktext(vp);
468 	if (error)
469 		goto badunlock;
470 
471 	VOP_UNLOCK(vp);
472 
473 	if ((error = exec_read_from(l, vp, 0, &eh, sizeof(eh))) != 0)
474 		goto bad;
475 
476 	if ((error = elf_check_header(&eh)) != 0)
477 		goto bad;
478 	if (eh.e_type != ET_DYN || eh.e_phnum == 0) {
479 		error = ENOEXEC;
480 		goto bad;
481 	}
482 
483 	phsize = eh.e_phnum * sizeof(Elf_Phdr);
484 	ph = kmem_alloc(phsize, KM_SLEEP);
485 
486 	if ((error = exec_read_from(l, vp, eh.e_phoff, ph, phsize)) != 0)
487 		goto bad;
488 
489 #ifdef ELF_INTERP_NON_RELOCATABLE
490 	/*
491 	 * Evil hack:  Only MIPS should be non-relocatable, and the
492 	 * psections should have a high address (typically 0x5ffe0000).
493 	 * If it's now relocatable, it should be linked at 0 and the
494 	 * psections should have zeros in the upper part of the address.
495 	 * Otherwise, force the load at the linked address.
496 	 */
497 	if (*last == ELF_LINK_ADDR && (ph->p_vaddr & 0xffff0000) == 0)
498 		*last = ELFDEFNNAME(NO_ADDR);
499 #endif
500 
501 	/*
502 	 * If no position to load the interpreter was set by a probe
503 	 * function, pick the same address that a non-fixed mmap(0, ..)
504 	 * would (i.e. something safely out of the way).
505 	 */
506 	if (*last == ELFDEFNNAME(NO_ADDR)) {
507 		u_long limit = 0;
508 		/*
509 		 * Find the start and ending addresses of the psections to
510 		 * be loaded.  This will give us the size.
511 		 */
512 		for (i = 0, base_ph = NULL; i < eh.e_phnum; i++) {
513 			if (ph[i].p_type == PT_LOAD) {
514 				u_long psize = ph[i].p_vaddr + ph[i].p_memsz;
515 				if (base_ph == NULL)
516 					base_ph = &ph[i];
517 				if (psize > limit)
518 					limit = psize;
519 			}
520 		}
521 
522 		if (base_ph == NULL) {
523 			error = ENOEXEC;
524 			goto bad;
525 		}
526 
527 		/*
528 		 * Now compute the size and load address.
529 		 */
530 		addr = (*epp->ep_esch->es_emul->e_vm_default_addr)(p,
531 		    epp->ep_daddr,
532 		    round_page(limit) - trunc_page(base_ph->p_vaddr),
533 		    use_topdown);
534 	} else {
535 		addr = *last; /* may be ELF_LINK_ADDR */
536 	}
537 
538 	/*
539 	 * Load all the necessary sections
540 	 */
541 	for (i = 0, base_ph = NULL, last_ph = NULL; i < eh.e_phnum; i++) {
542 		switch (ph[i].p_type) {
543 		case PT_LOAD: {
544 			u_long size;
545 			int flags;
546 
547 			if (base_ph == NULL) {
548 				/*
549 				 * First encountered psection is always the
550 				 * base psection.  Make sure it's aligned
551 				 * properly (align down for topdown and align
552 				 * upwards for not topdown).
553 				 */
554 				base_ph = &ph[i];
555 				flags = VMCMD_BASE;
556 				if (addr == ELF_LINK_ADDR)
557 					addr = ph[i].p_vaddr;
558 				if (use_topdown)
559 					addr = ELF_TRUNC(addr, ph[i].p_align);
560 				else
561 					addr = ELF_ROUND(addr, ph[i].p_align);
562 			} else {
563 				u_long limit = round_page(last_ph->p_vaddr
564 				    + last_ph->p_memsz);
565 				u_long base = trunc_page(ph[i].p_vaddr);
566 
567 				/*
568 				 * If there is a gap in between the psections,
569 				 * map it as inaccessible so nothing else
570 				 * mmap'ed will be placed there.
571 				 */
572 				if (limit != base) {
573 					NEW_VMCMD2(vcset, vmcmd_map_zero,
574 					    base - limit,
575 					    limit - base_ph->p_vaddr, NULLVP,
576 					    0, VM_PROT_NONE, VMCMD_RELATIVE);
577 				}
578 
579 				addr = ph[i].p_vaddr - base_ph->p_vaddr;
580 				flags = VMCMD_RELATIVE;
581 			}
582 			last_ph = &ph[i];
583 			elf_load_psection(vcset, vp, &ph[i], &addr,
584 			    &size, flags);
585 			/*
586 			 * If entry is within this psection then this
587 			 * must contain the .text section.  *entryoff is
588 			 * relative to the base psection.
589 			 */
590 			if (eh.e_entry >= ph[i].p_vaddr &&
591 			    eh.e_entry < (ph[i].p_vaddr + size)) {
592 				*entryoff = eh.e_entry - base_ph->p_vaddr;
593 			}
594 			addr += size;
595 			break;
596 		}
597 
598 		default:
599 			break;
600 		}
601 	}
602 
603 	kmem_free(ph, phsize);
604 	/*
605 	 * This value is ignored if TOPDOWN.
606 	 */
607 	*last = addr;
608 	vrele(vp);
609 	return 0;
610 
611 badunlock:
612 	VOP_UNLOCK(vp);
613 
614 bad:
615 	if (ph != NULL)
616 		kmem_free(ph, phsize);
617 	vrele(vp);
618 	return error;
619 }
620 
621 /*
622  * exec_elf_makecmds(): Prepare an Elf binary's exec package
623  *
624  * First, set of the various offsets/lengths in the exec package.
625  *
626  * Then, mark the text image busy (so it can be demand paged) or error
627  * out if this is not possible.  Finally, set up vmcmds for the
628  * text, data, bss, and stack segments.
629  */
630 int
631 exec_elf_makecmds(struct lwp *l, struct exec_package *epp)
632 {
633 	Elf_Ehdr *eh = epp->ep_hdr;
634 	Elf_Phdr *ph, *pp;
635 	Elf_Addr phdr = 0, computed_phdr = 0, pos = 0, end_text = 0;
636 	int error, i;
637 	char *interp = NULL;
638 	u_long phsize;
639 	struct elf_args *ap;
640 	bool is_dyn = false;
641 
642 	if (epp->ep_hdrvalid < sizeof(Elf_Ehdr))
643 		return ENOEXEC;
644 	if ((error = elf_check_header(eh)) != 0)
645 		return error;
646 
647 	if (eh->e_type == ET_DYN)
648 		/* PIE, and some libs have an entry point */
649 		is_dyn = true;
650 	else if (eh->e_type != ET_EXEC)
651 		return ENOEXEC;
652 
653 	if (eh->e_phnum == 0)
654 		return ENOEXEC;
655 
656 	error = vn_marktext(epp->ep_vp);
657 	if (error)
658 		return error;
659 
660 	/*
661 	 * Allocate space to hold all the program headers, and read them
662 	 * from the file
663 	 */
664 	phsize = eh->e_phnum * sizeof(Elf_Phdr);
665 	ph = kmem_alloc(phsize, KM_SLEEP);
666 
667 	if ((error = exec_read_from(l, epp->ep_vp, eh->e_phoff, ph, phsize)) !=
668 	    0)
669 		goto bad;
670 
671 	epp->ep_taddr = epp->ep_tsize = ELFDEFNNAME(NO_ADDR);
672 	epp->ep_daddr = epp->ep_dsize = ELFDEFNNAME(NO_ADDR);
673 
674 	for (i = 0; i < eh->e_phnum; i++) {
675 		pp = &ph[i];
676 		if (pp->p_type == PT_INTERP) {
677 			if (pp->p_filesz < 2 || pp->p_filesz > MAXPATHLEN) {
678 				error = ENOEXEC;
679 				goto bad;
680 			}
681 			interp = PNBUF_GET();
682 			if ((error = exec_read_from(l, epp->ep_vp,
683 			    pp->p_offset, interp, pp->p_filesz)) != 0)
684 				goto bad;
685 			/* Ensure interp is NUL-terminated and of the expected length */
686 			if (strnlen(interp, pp->p_filesz) != pp->p_filesz - 1) {
687 				error = ENOEXEC;
688 				goto bad;
689 			}
690 			break;
691 		}
692 	}
693 
694 	/*
695 	 * On the same architecture, we may be emulating different systems.
696 	 * See which one will accept this executable.
697 	 *
698 	 * Probe functions would normally see if the interpreter (if any)
699 	 * exists. Emulation packages may possibly replace the interpreter in
700 	 * interp with a changed path (/emul/xxx/<path>).
701 	 */
702 	pos = ELFDEFNNAME(NO_ADDR);
703 	if (epp->ep_esch->u.elf_probe_func) {
704 		vaddr_t startp = (vaddr_t)pos;
705 
706 		error = (*epp->ep_esch->u.elf_probe_func)(l, epp, eh, interp,
707 							  &startp);
708 		if (error)
709 			goto bad;
710 		pos = (Elf_Addr)startp;
711 	}
712 
713 	if (is_dyn)
714 		elf_placedynexec(epp, eh, ph);
715 
716 	/*
717 	 * Load all the necessary sections
718 	 */
719 	for (i = 0; i < eh->e_phnum; i++) {
720 		Elf_Addr addr = ELFDEFNNAME(NO_ADDR);
721 		u_long size = 0;
722 
723 		switch (ph[i].p_type) {
724 		case PT_LOAD:
725 			elf_load_psection(&epp->ep_vmcmds, epp->ep_vp,
726 			    &ph[i], &addr, &size, VMCMD_FIXED);
727 
728 			/*
729 			 * Consider this as text segment, if it is executable.
730 			 * If there is more than one text segment, pick the
731 			 * largest.
732 			 */
733 			if (ph[i].p_flags & PF_X) {
734 				if (epp->ep_taddr == ELFDEFNNAME(NO_ADDR) ||
735 				    size > epp->ep_tsize) {
736 					epp->ep_taddr = addr;
737 					epp->ep_tsize = size;
738 				}
739 				end_text = addr + size;
740 			} else {
741 				epp->ep_daddr = addr;
742 				epp->ep_dsize = size;
743 			}
744 			if (ph[i].p_offset == 0) {
745 				computed_phdr = ph[i].p_vaddr + eh->e_phoff;
746 			}
747 			break;
748 
749 		case PT_SHLIB:
750 			/* SCO has these sections. */
751 		case PT_INTERP:
752 			/* Already did this one. */
753 		case PT_DYNAMIC:
754 		case PT_NOTE:
755 			break;
756 		case PT_PHDR:
757 			/* Note address of program headers (in text segment) */
758 			phdr = ph[i].p_vaddr;
759 			break;
760 
761 		default:
762 			/*
763 			 * Not fatal; we don't need to understand everything.
764 			 */
765 			break;
766 		}
767 	}
768 
769 	if (epp->ep_vmcmds.evs_used == 0) {
770 		/* No VMCMD; there was no PT_LOAD section, or those
771 		 * sections were empty */
772 		error = ENOEXEC;
773 		goto bad;
774 	}
775 
776 	if (epp->ep_daddr == ELFDEFNNAME(NO_ADDR)) {
777 		epp->ep_daddr = round_page(end_text);
778 		epp->ep_dsize = 0;
779 	}
780 
781 	/*
782 	 * Check if we found a dynamically linked binary and arrange to load
783 	 * its interpreter
784 	 */
785 	if (interp) {
786 		u_int nused = epp->ep_vmcmds.evs_used;
787 		u_long interp_offset = 0;
788 
789 		if ((error = elf_load_interp(l, epp, interp,
790 		    &epp->ep_vmcmds, &interp_offset, &pos)) != 0) {
791 			goto bad;
792 		}
793 		if (epp->ep_vmcmds.evs_used == nused) {
794 			/* elf_load_interp() has not set up any new VMCMD */
795 			error = ENOEXEC;
796 			goto bad;
797 		}
798 
799 		ap = kmem_alloc(sizeof(*ap), KM_SLEEP);
800 		ap->arg_interp = epp->ep_vmcmds.evs_cmds[nused].ev_addr;
801 		epp->ep_entryoffset = interp_offset;
802 		epp->ep_entry = ap->arg_interp + interp_offset;
803 		PNBUF_PUT(interp);
804 		interp = NULL;
805 	} else {
806 		epp->ep_entry = eh->e_entry;
807 		if (epp->ep_flags & EXEC_FORCEAUX) {
808 			ap = kmem_alloc(sizeof(*ap), KM_SLEEP);
809 			ap->arg_interp = (vaddr_t)NULL;
810 		} else
811 			ap = NULL;
812 	}
813 
814 	if (ap) {
815 		ap->arg_phaddr = phdr ? phdr : computed_phdr;
816 		ap->arg_phentsize = eh->e_phentsize;
817 		ap->arg_phnum = eh->e_phnum;
818 		ap->arg_entry = eh->e_entry;
819 		epp->ep_emul_arg = ap;
820 		epp->ep_emul_arg_free = elf_free_emul_arg;
821 	}
822 
823 #ifdef ELF_MAP_PAGE_ZERO
824 	/* Dell SVR4 maps page zero, yeuch! */
825 	NEW_VMCMD(&epp->ep_vmcmds, vmcmd_map_readvn, PAGE_SIZE, 0,
826 	    epp->ep_vp, 0, VM_PROT_READ);
827 #endif
828 
829 	error = (*epp->ep_esch->es_setup_stack)(l, epp);
830 	if (error)
831 		goto bad;
832 
833 	kmem_free(ph, phsize);
834 	return 0;
835 
836 bad:
837 	if (interp)
838 		PNBUF_PUT(interp);
839 	exec_free_emul_arg(epp);
840 	kmem_free(ph, phsize);
841 	kill_vmcmds(&epp->ep_vmcmds);
842 	return error;
843 }
844 
845 int
846 netbsd_elf_signature(struct lwp *l, struct exec_package *epp,
847     Elf_Ehdr *eh)
848 {
849 	size_t i;
850 	Elf_Shdr *sh;
851 	Elf_Nhdr *np;
852 	size_t shsize, nsize;
853 	int error;
854 	int isnetbsd = 0;
855 	char *ndata, *ndesc;
856 
857 #ifdef DIAGNOSTIC
858 	const char *badnote;
859 #define BADNOTE(n) badnote = (n)
860 #else
861 #define BADNOTE(n)
862 #endif
863 
864 	epp->ep_pax_flags = 0;
865 	if (eh->e_shnum > ELF_MAXSHNUM || eh->e_shnum == 0)
866 		return ENOEXEC;
867 
868 	shsize = eh->e_shnum * sizeof(Elf_Shdr);
869 	sh = kmem_alloc(shsize, KM_SLEEP);
870 	error = exec_read_from(l, epp->ep_vp, eh->e_shoff, sh, shsize);
871 	if (error)
872 		goto out;
873 
874 	np = kmem_alloc(ELF_MAXNOTESIZE, KM_SLEEP);
875 	for (i = 0; i < eh->e_shnum; i++) {
876 		Elf_Shdr *shp = &sh[i];
877 
878 		if (shp->sh_type != SHT_NOTE ||
879 		    shp->sh_size > ELF_MAXNOTESIZE ||
880 		    shp->sh_size < sizeof(Elf_Nhdr) + ELF_NOTE_NETBSD_NAMESZ)
881 			continue;
882 
883 		error = exec_read_from(l, epp->ep_vp, shp->sh_offset, np,
884 		    shp->sh_size);
885 		if (error)
886 			continue;
887 
888 		/* Point to the note, skip the header */
889 		ndata = (char *)(np + 1);
890 
891 		/*
892 		 * Padding is present if necessary to ensure 4-byte alignment.
893 		 * The actual section size is therefore:
894 		 *    header size + 4-byte aligned name + 4-byte aligned desc
895 		 * Ensure this size is consistent with what is indicated
896 		 * in sh_size. The first check avoids integer overflows.
897 		 *
898 		 * Binaries from before NetBSD 1.6 have two notes in the same
899 		 * note section.  The second note was never used, so as long as
900 		 * the section is at least as big as it should be, it's ok.
901 		 * These binaries also have a second note section with a note of
902 		 * type ELF_NOTE_TYPE_NETBSD_TAG, which can be ignored as well.
903 		 */
904 		if (np->n_namesz > shp->sh_size || np->n_descsz > shp->sh_size) {
905 			BADNOTE("note size limit");
906 			goto bad;
907 		}
908 		nsize = sizeof(*np) + roundup(np->n_namesz, 4) +
909 		    roundup(np->n_descsz, 4);
910 		if (nsize > shp->sh_size) {
911 			BADNOTE("note size");
912 			goto bad;
913 		}
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 the
931 			 * NetBSD 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 			 * Ignore old GCC
939 			 */
940 			if (np->n_namesz == ELF_NOTE_OGCC_NAMESZ &&
941 			    memcmp(ndata, ELF_NOTE_OGCC_NAME,
942 			    ELF_NOTE_OGCC_NAMESZ) == 0)
943 				break;
944 			BADNOTE("NetBSD tag");
945 			goto bad;
946 
947 		case ELF_NOTE_TYPE_PAX_TAG:
948 			if (np->n_namesz == ELF_NOTE_PAX_NAMESZ &&
949 			    np->n_descsz == ELF_NOTE_PAX_DESCSZ &&
950 			    memcmp(ndata, ELF_NOTE_PAX_NAME,
951 			    ELF_NOTE_PAX_NAMESZ) == 0) {
952 				uint32_t flags;
953 				memcpy(&flags, ndesc, sizeof(flags));
954 #if defined(PAX_MPROTECT) || defined(PAX_SEGVGUARD) || defined(PAX_ASLR)
955 				/* Convert the flags and insert them into
956 				 * the exec package. */
957 				pax_setup_elf_flags(epp, flags);
958 #else
959 				(void)flags; /* UNUSED */
960 #endif /* PAX_MPROTECT || PAX_SEGVGUARD || PAX_ASLR */
961 				break;
962 			}
963 			BADNOTE("PaX tag");
964 			goto bad;
965 
966 		case ELF_NOTE_TYPE_MARCH_TAG:
967 			/* Copy the machine arch into the package. */
968 			if (np->n_namesz == ELF_NOTE_MARCH_NAMESZ
969 			    && memcmp(ndata, ELF_NOTE_MARCH_NAME,
970 				    ELF_NOTE_MARCH_NAMESZ) == 0) {
971 				/* Do not truncate the buffer */
972 				if (np->n_descsz > sizeof(epp->ep_machine_arch)) {
973 					BADNOTE("description size limit");
974 					goto bad;
975 				}
976 				/*
977 				 * Ensure ndesc is NUL-terminated and of the
978 				 * expected length.
979 				 */
980 				if (strnlen(ndesc, np->n_descsz) + 1 !=
981 				    np->n_descsz) {
982 					BADNOTE("description size");
983 					goto bad;
984 				}
985 				strlcpy(epp->ep_machine_arch, ndesc,
986 				    sizeof(epp->ep_machine_arch));
987 				break;
988 			}
989 			BADNOTE("march tag");
990 			goto bad;
991 
992 		case ELF_NOTE_TYPE_MCMODEL_TAG:
993 			/* arch specific check for code model */
994 #ifdef ELF_MD_MCMODEL_CHECK
995 			if (np->n_namesz == ELF_NOTE_MCMODEL_NAMESZ
996 			    && memcmp(ndata, ELF_NOTE_MCMODEL_NAME,
997 				    ELF_NOTE_MCMODEL_NAMESZ) == 0) {
998 				ELF_MD_MCMODEL_CHECK(epp, ndesc, np->n_descsz);
999 				break;
1000 			}
1001 			BADNOTE("mcmodel tag");
1002 			goto bad;
1003 #endif
1004 			break;
1005 
1006 		case ELF_NOTE_TYPE_SUSE_VERSION_TAG:
1007 			break;
1008 
1009 		case ELF_NOTE_TYPE_GO_BUILDID_TAG:
1010 			break;
1011 
1012 		default:
1013 			BADNOTE("unknown tag");
1014 bad:
1015 #ifdef DIAGNOSTIC
1016 			/* Ignore GNU tags */
1017 			if (np->n_namesz == ELF_NOTE_GNU_NAMESZ &&
1018 			    memcmp(ndata, ELF_NOTE_GNU_NAME,
1019 			    ELF_NOTE_GNU_NAMESZ) == 0)
1020 			    break;
1021 
1022 			int ns = MIN(np->n_namesz, shp->sh_size - sizeof(*np));
1023 			printf("%s: Unknown elf note type %d (%s): "
1024 			    "[namesz=%d, descsz=%d name=%-*.*s]\n",
1025 			    epp->ep_kname, np->n_type, badnote, np->n_namesz,
1026 			    np->n_descsz, ns, ns, ndata);
1027 #endif
1028 			break;
1029 		}
1030 	}
1031 	kmem_free(np, ELF_MAXNOTESIZE);
1032 
1033 	error = isnetbsd ? 0 : ENOEXEC;
1034 out:
1035 	kmem_free(sh, shsize);
1036 	return error;
1037 }
1038 
1039 int
1040 netbsd_elf_probe(struct lwp *l, struct exec_package *epp, void *eh, char *itp,
1041     vaddr_t *pos)
1042 {
1043 	int error;
1044 
1045 	if ((error = netbsd_elf_signature(l, epp, eh)) != 0)
1046 		return error;
1047 #ifdef ELF_MD_PROBE_FUNC
1048 	if ((error = ELF_MD_PROBE_FUNC(l, epp, eh, itp, pos)) != 0)
1049 		return error;
1050 #elif defined(ELF_INTERP_NON_RELOCATABLE)
1051 	*pos = ELF_LINK_ADDR;
1052 #endif
1053 	epp->ep_flags |= EXEC_FORCEAUX;
1054 	return 0;
1055 }
1056 
1057 void
1058 elf_free_emul_arg(void *arg)
1059 {
1060 	struct elf_args *ap = arg;
1061 	KASSERT(ap != NULL);
1062 	kmem_free(ap, sizeof(*ap));
1063 }
1064