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