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