xref: /netbsd-src/sys/kern/exec_elf.c (revision 7c192b2a5e1093666e67801684f930ef49b3b363)
1 /*	$NetBSD: exec_elf.c,v 1.90 2017/04/21 13:17:42 kamil 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.90 2017/04/21 13:17:42 kamil 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 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_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 void
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 = 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 	KASSERT((offset & (align - 1)) == 0);
140 
141 	for (i = 0; i < eh->e_phnum; i++)
142 		ph[i].p_vaddr += offset;
143 	epp->ep_entryoffset = offset;
144 	eh->e_entry += offset;
145 }
146 
147 /*
148  * Copy arguments onto the stack in the normal way, but add some
149  * extra information in case of dynamic binding.
150  */
151 int
152 elf_copyargs(struct lwp *l, struct exec_package *pack,
153     struct ps_strings *arginfo, char **stackp, void *argp)
154 {
155 	size_t len, vlen;
156 	AuxInfo ai[ELF_AUX_ENTRIES], *a, *execname;
157 	struct elf_args *ap;
158 	int error;
159 
160 	if ((error = copyargs(l, pack, arginfo, stackp, argp)) != 0)
161 		return error;
162 
163 	a = ai;
164 	execname = NULL;
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 		if (pack->ep_path) {
230 			execname = a;
231 			a->a_type = AT_SUN_EXECNAME;
232 			a++;
233 		}
234 
235 		exec_free_emul_arg(pack);
236 	}
237 
238 	a->a_type = AT_NULL;
239 	a->a_v = 0;
240 	a++;
241 
242 	vlen = (a - ai) * sizeof(ai[0]);
243 
244 	KASSERT(vlen <= sizeof(ai));
245 
246 	if (execname) {
247 		char *path = pack->ep_path;
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 	if ((error = copyout(ai, *stackp, vlen)) != 0)
257 		return error;
258 	*stackp += vlen + len;
259 
260 	return 0;
261 }
262 
263 /*
264  * elf_check_header():
265  *
266  * Check header for validity; return 0 if ok, ENOEXEC if error
267  */
268 int
269 elf_check_header(Elf_Ehdr *eh)
270 {
271 
272 	if (memcmp(eh->e_ident, ELFMAG, SELFMAG) != 0 ||
273 	    eh->e_ident[EI_CLASS] != ELFCLASS) {
274 		DPRINTF("bad magic e_ident[EI_MAG0,EI_MAG3] %#x%x%x%x, "
275 		    "e_ident[EI_CLASS] %#x", eh->e_ident[EI_MAG0],
276 		    eh->e_ident[EI_MAG1], eh->e_ident[EI_MAG2],
277 		    eh->e_ident[EI_MAG3], eh->e_ident[EI_CLASS]);
278 		return ENOEXEC;
279 	}
280 
281 	switch (eh->e_machine) {
282 
283 	ELFDEFNNAME(MACHDEP_ID_CASES)
284 
285 	default:
286 		DPRINTF("bad machine %#x", eh->e_machine);
287 		return ENOEXEC;
288 	}
289 
290 	if (ELF_EHDR_FLAGS_OK(eh) == 0) {
291 		DPRINTF("bad flags %#x", eh->e_flags);
292 		return ENOEXEC;
293 	}
294 
295 	if (eh->e_shnum > ELF_MAXSHNUM || eh->e_phnum > ELF_MAXPHNUM) {
296 		DPRINTF("bad shnum/phnum %#x/%#x", eh->e_shnum, eh->e_phnum);
297 		return ENOEXEC;
298 	}
299 
300 	return 0;
301 }
302 
303 /*
304  * elf_load_psection():
305  *
306  * Load a psection at the appropriate address
307  */
308 static void
309 elf_load_psection(struct exec_vmcmd_set *vcset, struct vnode *vp,
310     const Elf_Phdr *ph, Elf_Addr *addr, u_long *size, int flags)
311 {
312 	u_long msize, psize, rm, rf;
313 	long diff, offset;
314 	int vmprot = 0;
315 
316 	/*
317 	 * If the user specified an address, then we load there.
318 	 */
319 	if (*addr == ELFDEFNNAME(NO_ADDR))
320 		*addr = ph->p_vaddr;
321 
322 	if (ph->p_align > 1) {
323 		/*
324 		 * Make sure we are virtually aligned as we are supposed to be.
325 		 */
326 		diff = ph->p_vaddr - ELF_TRUNC(ph->p_vaddr, ph->p_align);
327 		KASSERT(*addr - diff == ELF_TRUNC(*addr, ph->p_align));
328 		/*
329 		 * But make sure to not map any pages before the start of the
330 		 * psection by limiting the difference to within a page.
331 		 */
332 		diff &= PAGE_MASK;
333 	} else
334 		diff = 0;
335 
336 	vmprot |= (ph->p_flags & PF_R) ? VM_PROT_READ : 0;
337 	vmprot |= (ph->p_flags & PF_W) ? VM_PROT_WRITE : 0;
338 	vmprot |= (ph->p_flags & PF_X) ? VM_PROT_EXECUTE : 0;
339 
340 	/*
341 	 * Adjust everything so it all starts on a page boundary.
342 	 */
343 	*addr -= diff;
344 	offset = ph->p_offset - diff;
345 	*size = ph->p_filesz + diff;
346 	msize = ph->p_memsz + diff;
347 
348 	if (ph->p_align >= PAGE_SIZE) {
349 		if ((ph->p_flags & PF_W) != 0) {
350 			/*
351 			 * Because the pagedvn pager can't handle zero fill
352 			 * of the last data page if it's not page aligned we
353 			 * map the last page readvn.
354 			 */
355 			psize = trunc_page(*size);
356 		} else {
357 			psize = round_page(*size);
358 		}
359 	} else {
360 		psize = *size;
361 	}
362 
363 	if (psize > 0) {
364 		NEW_VMCMD2(vcset, ph->p_align < PAGE_SIZE ?
365 		    vmcmd_map_readvn : vmcmd_map_pagedvn, psize, *addr, vp,
366 		    offset, vmprot, flags);
367 		flags &= VMCMD_RELATIVE;
368 	}
369 	if (psize < *size) {
370 		NEW_VMCMD2(vcset, vmcmd_map_readvn, *size - psize,
371 		    *addr + psize, vp, offset + psize, vmprot, flags);
372 	}
373 
374 	/*
375 	 * Check if we need to extend the size of the segment (does
376 	 * bss extend page the next page boundary)?
377 	 */
378 	rm = round_page(*addr + msize);
379 	rf = round_page(*addr + *size);
380 
381 	if (rm != rf) {
382 		NEW_VMCMD2(vcset, vmcmd_map_zero, rm - rf, rf, NULLVP,
383 		    0, vmprot, flags & VMCMD_RELATIVE);
384 		*size = msize;
385 	}
386 }
387 
388 /*
389  * elf_load_interp():
390  *
391  * Load an interpreter pointed to by path.
392  */
393 static int
394 elf_load_interp(struct lwp *l, struct exec_package *epp, char *path,
395     struct exec_vmcmd_set *vcset, u_long *entryoff, Elf_Addr *last)
396 {
397 	int error, i;
398 	struct vnode *vp;
399 	struct vattr attr;
400 	Elf_Ehdr eh;
401 	Elf_Phdr *ph = NULL;
402 	const Elf_Phdr *base_ph;
403 	const Elf_Phdr *last_ph;
404 	u_long phsize;
405 	Elf_Addr addr = *last;
406 	struct proc *p;
407 	bool use_topdown;
408 
409 	p = l->l_proc;
410 
411 	KASSERT(p->p_vmspace);
412 	KASSERT(p->p_vmspace != proc0.p_vmspace);
413 
414 #ifdef __USE_TOPDOWN_VM
415 	use_topdown = epp->ep_flags & EXEC_TOPDOWN_VM;
416 #else
417 	use_topdown = false;
418 #endif
419 
420 	/*
421 	 * 1. open file
422 	 * 2. read filehdr
423 	 * 3. map text, data, and bss out of it using VM_*
424 	 */
425 	vp = epp->ep_interp;
426 	if (vp == NULL) {
427 		error = emul_find_interp(l, epp, path);
428 		if (error != 0)
429 			return error;
430 		vp = epp->ep_interp;
431 	}
432 	/* We'll tidy this ourselves - otherwise we have locking issues */
433 	epp->ep_interp = NULL;
434 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
435 
436 	/*
437 	 * Similarly, if it's not marked as executable, or it's not a regular
438 	 * file, we don't allow it to be used.
439 	 */
440 	if (vp->v_type != VREG) {
441 		error = EACCES;
442 		goto badunlock;
443 	}
444 	if ((error = VOP_ACCESS(vp, VEXEC, l->l_cred)) != 0)
445 		goto badunlock;
446 
447 	/* get attributes */
448 	if ((error = VOP_GETATTR(vp, &attr, l->l_cred)) != 0)
449 		goto badunlock;
450 
451 	/*
452 	 * Check mount point.  Though we're not trying to exec this binary,
453 	 * we will be executing code from it, so if the mount point
454 	 * disallows execution or set-id-ness, we punt or kill the set-id.
455 	 */
456 	if (vp->v_mount->mnt_flag & MNT_NOEXEC) {
457 		error = EACCES;
458 		goto badunlock;
459 	}
460 	if (vp->v_mount->mnt_flag & MNT_NOSUID)
461 		epp->ep_vap->va_mode &= ~(S_ISUID | S_ISGID);
462 
463 	error = vn_marktext(vp);
464 	if (error)
465 		goto badunlock;
466 
467 	VOP_UNLOCK(vp);
468 
469 	if ((error = exec_read_from(l, vp, 0, &eh, sizeof(eh))) != 0)
470 		goto bad;
471 
472 	if ((error = elf_check_header(&eh)) != 0)
473 		goto bad;
474 	if (eh.e_type != ET_DYN || eh.e_phnum == 0) {
475 		DPRINTF("bad interpreter type %#x", eh.e_type);
476 		error = ENOEXEC;
477 		goto bad;
478 	}
479 
480 	phsize = eh.e_phnum * sizeof(Elf_Phdr);
481 	ph = kmem_alloc(phsize, KM_SLEEP);
482 
483 	if ((error = exec_read_from(l, vp, eh.e_phoff, ph, phsize)) != 0)
484 		goto bad;
485 
486 #ifdef ELF_INTERP_NON_RELOCATABLE
487 	/*
488 	 * Evil hack:  Only MIPS should be non-relocatable, and the
489 	 * psections should have a high address (typically 0x5ffe0000).
490 	 * If it's now relocatable, it should be linked at 0 and the
491 	 * psections should have zeros in the upper part of the address.
492 	 * Otherwise, force the load at the linked address.
493 	 */
494 	if (*last == ELF_LINK_ADDR && (ph->p_vaddr & 0xffff0000) == 0)
495 		*last = ELFDEFNNAME(NO_ADDR);
496 #endif
497 
498 	/*
499 	 * If no position to load the interpreter was set by a probe
500 	 * function, pick the same address that a non-fixed mmap(0, ..)
501 	 * would (i.e. something safely out of the way).
502 	 */
503 	if (*last == ELFDEFNNAME(NO_ADDR)) {
504 		u_long limit = 0;
505 		/*
506 		 * Find the start and ending addresses of the psections to
507 		 * be loaded.  This will give us the size.
508 		 */
509 		for (i = 0, base_ph = NULL; i < eh.e_phnum; i++) {
510 			if (ph[i].p_type == PT_LOAD) {
511 				u_long psize = ph[i].p_vaddr + ph[i].p_memsz;
512 				if (base_ph == NULL)
513 					base_ph = &ph[i];
514 				if (psize > limit)
515 					limit = psize;
516 			}
517 		}
518 
519 		if (base_ph == NULL) {
520 			DPRINTF("no interpreter loadable sections");
521 			error = ENOEXEC;
522 			goto bad;
523 		}
524 
525 		/*
526 		 * Now compute the size and load address.
527 		 */
528 		addr = (*epp->ep_esch->es_emul->e_vm_default_addr)(p,
529 		    epp->ep_daddr,
530 		    round_page(limit) - trunc_page(base_ph->p_vaddr),
531 		    use_topdown);
532 		addr += (Elf_Addr)pax_aslr_rtld_offset(epp, base_ph->p_align,
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 		DPRINTF("small header %#x", epp->ep_hdrvalid);
644 		return ENOEXEC;
645 	}
646 	if ((error = elf_check_header(eh)) != 0)
647 		return error;
648 
649 	if (eh->e_type == ET_DYN)
650 		/* PIE, and some libs have an entry point */
651 		is_dyn = true;
652 	else if (eh->e_type != ET_EXEC) {
653 		DPRINTF("bad type %#x", eh->e_type);
654 		return ENOEXEC;
655 	}
656 
657 	if (eh->e_phnum == 0) {
658 		DPRINTF("no program headers");
659 		return ENOEXEC;
660 	}
661 
662 	error = vn_marktext(epp->ep_vp);
663 	if (error)
664 		return error;
665 
666 	/*
667 	 * Allocate space to hold all the program headers, and read them
668 	 * from the file
669 	 */
670 	phsize = eh->e_phnum * sizeof(Elf_Phdr);
671 	ph = kmem_alloc(phsize, KM_SLEEP);
672 
673 	if ((error = exec_read_from(l, epp->ep_vp, eh->e_phoff, ph, phsize)) !=
674 	    0)
675 		goto bad;
676 
677 	epp->ep_taddr = epp->ep_tsize = ELFDEFNNAME(NO_ADDR);
678 	epp->ep_daddr = epp->ep_dsize = ELFDEFNNAME(NO_ADDR);
679 
680 	for (i = 0; i < eh->e_phnum; i++) {
681 		pp = &ph[i];
682 		if (pp->p_type == PT_INTERP) {
683 			if (pp->p_filesz < 2 || pp->p_filesz > MAXPATHLEN) {
684 				DPRINTF("bad interpreter namelen %#jx",
685 				    (uintmax_t)pp->p_filesz);
686 				error = ENOEXEC;
687 				goto bad;
688 			}
689 			interp = PNBUF_GET();
690 			if ((error = exec_read_from(l, epp->ep_vp,
691 			    pp->p_offset, interp, pp->p_filesz)) != 0)
692 				goto bad;
693 			/* Ensure interp is NUL-terminated and of the expected length */
694 			if (strnlen(interp, pp->p_filesz) != pp->p_filesz - 1) {
695 				DPRINTF("bad interpreter name");
696 				error = ENOEXEC;
697 				goto bad;
698 			}
699 			break;
700 		}
701 	}
702 
703 	/*
704 	 * On the same architecture, we may be emulating different systems.
705 	 * See which one will accept this executable.
706 	 *
707 	 * Probe functions would normally see if the interpreter (if any)
708 	 * exists. Emulation packages may possibly replace the interpreter in
709 	 * interp with a changed path (/emul/xxx/<path>).
710 	 */
711 	pos = ELFDEFNNAME(NO_ADDR);
712 	if (epp->ep_esch->u.elf_probe_func) {
713 		vaddr_t startp = (vaddr_t)pos;
714 
715 		error = (*epp->ep_esch->u.elf_probe_func)(l, epp, eh, interp,
716 							  &startp);
717 		if (error)
718 			goto bad;
719 		pos = (Elf_Addr)startp;
720 	}
721 
722 	if (is_dyn)
723 		elf_placedynexec(epp, eh, ph);
724 
725 	/*
726 	 * Load all the necessary sections
727 	 */
728 	for (i = 0; i < eh->e_phnum; i++) {
729 		Elf_Addr addr = ELFDEFNNAME(NO_ADDR);
730 		u_long size = 0;
731 
732 		switch (ph[i].p_type) {
733 		case PT_LOAD:
734 			elf_load_psection(&epp->ep_vmcmds, epp->ep_vp,
735 			    &ph[i], &addr, &size, VMCMD_FIXED);
736 
737 			/*
738 			 * Consider this as text segment, if it is executable.
739 			 * If there is more than one text segment, pick the
740 			 * largest.
741 			 */
742 			if (ph[i].p_flags & PF_X) {
743 				if (epp->ep_taddr == ELFDEFNNAME(NO_ADDR) ||
744 				    size > epp->ep_tsize) {
745 					epp->ep_taddr = addr;
746 					epp->ep_tsize = size;
747 				}
748 				end_text = addr + size;
749 			} else {
750 				epp->ep_daddr = addr;
751 				epp->ep_dsize = size;
752 			}
753 			if (ph[i].p_offset == 0) {
754 				computed_phdr = ph[i].p_vaddr + eh->e_phoff;
755 			}
756 			break;
757 
758 		case PT_SHLIB:
759 			/* SCO has these sections. */
760 		case PT_INTERP:
761 			/* Already did this one. */
762 		case PT_DYNAMIC:
763 		case PT_NOTE:
764 			break;
765 		case PT_PHDR:
766 			/* Note address of program headers (in text segment) */
767 			phdr = ph[i].p_vaddr;
768 			break;
769 
770 		default:
771 			/*
772 			 * Not fatal; we don't need to understand everything.
773 			 */
774 			break;
775 		}
776 	}
777 
778 	if (epp->ep_vmcmds.evs_used == 0) {
779 		/* No VMCMD; there was no PT_LOAD section, or those
780 		 * sections were empty */
781 		DPRINTF("no vmcommands");
782 		error = ENOEXEC;
783 		goto bad;
784 	}
785 
786 	if (epp->ep_daddr == ELFDEFNNAME(NO_ADDR)) {
787 		epp->ep_daddr = round_page(end_text);
788 		epp->ep_dsize = 0;
789 	}
790 
791 	/*
792 	 * Check if we found a dynamically linked binary and arrange to load
793 	 * its interpreter
794 	 */
795 	if (interp) {
796 		u_int nused = epp->ep_vmcmds.evs_used;
797 		u_long interp_offset = 0;
798 
799 		if ((error = elf_load_interp(l, epp, interp,
800 		    &epp->ep_vmcmds, &interp_offset, &pos)) != 0) {
801 			goto bad;
802 		}
803 		if (epp->ep_vmcmds.evs_used == nused) {
804 			/* elf_load_interp() has not set up any new VMCMD */
805 			DPRINTF("no vmcommands for interpreter");
806 			error = ENOEXEC;
807 			goto bad;
808 		}
809 
810 		ap = kmem_alloc(sizeof(*ap), KM_SLEEP);
811 		ap->arg_interp = epp->ep_vmcmds.evs_cmds[nused].ev_addr;
812 		epp->ep_entryoffset = interp_offset;
813 		epp->ep_entry = ap->arg_interp + interp_offset;
814 		PNBUF_PUT(interp);
815 		interp = NULL;
816 	} else {
817 		epp->ep_entry = eh->e_entry;
818 		if (epp->ep_flags & EXEC_FORCEAUX) {
819 			ap = kmem_alloc(sizeof(*ap), KM_SLEEP);
820 			ap->arg_interp = (vaddr_t)NULL;
821 		} else
822 			ap = NULL;
823 	}
824 
825 	if (ap) {
826 		ap->arg_phaddr = phdr ? phdr : computed_phdr;
827 		ap->arg_phentsize = eh->e_phentsize;
828 		ap->arg_phnum = eh->e_phnum;
829 		ap->arg_entry = eh->e_entry;
830 		epp->ep_emul_arg = ap;
831 		epp->ep_emul_arg_free = elf_free_emul_arg;
832 	}
833 
834 #ifdef ELF_MAP_PAGE_ZERO
835 	/* Dell SVR4 maps page zero, yeuch! */
836 	NEW_VMCMD(&epp->ep_vmcmds, vmcmd_map_readvn, PAGE_SIZE, 0,
837 	    epp->ep_vp, 0, VM_PROT_READ);
838 #endif
839 
840 	error = (*epp->ep_esch->es_setup_stack)(l, epp);
841 	if (error)
842 		goto bad;
843 
844 	kmem_free(ph, phsize);
845 	return 0;
846 
847 bad:
848 	if (interp)
849 		PNBUF_PUT(interp);
850 	exec_free_emul_arg(epp);
851 	kmem_free(ph, phsize);
852 	kill_vmcmds(&epp->ep_vmcmds);
853 	return error;
854 }
855 
856 int
857 netbsd_elf_signature(struct lwp *l, struct exec_package *epp,
858     Elf_Ehdr *eh)
859 {
860 	size_t i;
861 	Elf_Phdr *ph;
862 	size_t phsize;
863 	char *nbuf;
864 	int error;
865 	int isnetbsd = 0;
866 
867 	epp->ep_pax_flags = 0;
868 
869 	if (eh->e_phnum > ELF_MAXPHNUM || eh->e_phnum == 0) {
870 		DPRINTF("no signature %#x", eh->e_phnum);
871 		return ENOEXEC;
872 	}
873 
874 	phsize = eh->e_phnum * sizeof(Elf_Phdr);
875 	ph = kmem_alloc(phsize, KM_SLEEP);
876 	error = exec_read_from(l, epp->ep_vp, eh->e_phoff, ph, phsize);
877 	if (error)
878 		goto out;
879 
880 	nbuf = kmem_alloc(ELF_MAXNOTESIZE, KM_SLEEP);
881 	for (i = 0; i < eh->e_phnum; i++) {
882 		const char *nptr;
883 		size_t nlen;
884 
885 		if (ph[i].p_type != PT_NOTE ||
886 		    ph[i].p_filesz > ELF_MAXNOTESIZE)
887 			continue;
888 
889 		nlen = ph[i].p_filesz;
890 		error = exec_read_from(l, epp->ep_vp, ph[i].p_offset,
891 				       nbuf, nlen);
892 		if (error)
893 			continue;
894 
895 		nptr = nbuf;
896 		while (nlen > 0) {
897 			const Elf_Nhdr *np;
898 			const char *ndata, *ndesc;
899 
900 			/* note header */
901 			np = (const Elf_Nhdr *)nptr;
902 			if (nlen < sizeof(*np)) {
903 				break;
904 			}
905 			nptr += sizeof(*np);
906 			nlen -= sizeof(*np);
907 
908 			/* note name */
909 			ndata = nptr;
910 			if (nlen < roundup(np->n_namesz, 4)) {
911 				break;
912 			}
913 			nptr += roundup(np->n_namesz, 4);
914 			nlen -= roundup(np->n_namesz, 4);
915 
916 			/* note description */
917 			ndesc = nptr;
918 			if (nlen < roundup(np->n_descsz, 4)) {
919 				break;
920 			}
921 			nptr += roundup(np->n_descsz, 4);
922 			nlen -= roundup(np->n_descsz, 4);
923 
924 			isnetbsd |= netbsd_elf_note(epp, np, ndata, ndesc);
925 		}
926 	}
927 	kmem_free(nbuf, ELF_MAXNOTESIZE);
928 
929 	error = isnetbsd ? 0 : ENOEXEC;
930 #ifdef DEBUG_ELF
931 	if (error)
932 		DPRINTF("not netbsd");
933 #endif
934 out:
935 	kmem_free(ph, phsize);
936 	return error;
937 }
938 
939 int
940 netbsd_elf_note(struct exec_package *epp,
941 		const Elf_Nhdr *np, const char *ndata, const char *ndesc)
942 {
943 	int isnetbsd = 0;
944 
945 #ifdef DIAGNOSTIC
946 	const char *badnote;
947 #define BADNOTE(n) badnote = (n)
948 #else
949 #define BADNOTE(n)
950 #endif
951 
952 	switch (np->n_type) {
953 	case ELF_NOTE_TYPE_NETBSD_TAG:
954 		/* It is us */
955 		if (np->n_namesz == ELF_NOTE_NETBSD_NAMESZ &&
956 		    np->n_descsz == ELF_NOTE_NETBSD_DESCSZ &&
957 		    memcmp(ndata, ELF_NOTE_NETBSD_NAME,
958 		    ELF_NOTE_NETBSD_NAMESZ) == 0) {
959 			memcpy(&epp->ep_osversion, ndesc,
960 			    ELF_NOTE_NETBSD_DESCSZ);
961 			isnetbsd = 1;
962 			break;
963 		}
964 
965 		/*
966 		 * Ignore SuSE tags; SuSE's n_type is the same the
967 		 * NetBSD one.
968 		 */
969 		if (np->n_namesz == ELF_NOTE_SUSE_NAMESZ &&
970 		    memcmp(ndata, ELF_NOTE_SUSE_NAME,
971 		    ELF_NOTE_SUSE_NAMESZ) == 0)
972 			break;
973 		/*
974 		 * Ignore old GCC
975 		 */
976 		if (np->n_namesz == ELF_NOTE_OGCC_NAMESZ &&
977 		    memcmp(ndata, ELF_NOTE_OGCC_NAME,
978 		    ELF_NOTE_OGCC_NAMESZ) == 0)
979 			break;
980 		BADNOTE("NetBSD tag");
981 		goto bad;
982 
983 	case ELF_NOTE_TYPE_PAX_TAG:
984 		if (np->n_namesz == ELF_NOTE_PAX_NAMESZ &&
985 		    np->n_descsz == ELF_NOTE_PAX_DESCSZ &&
986 		    memcmp(ndata, ELF_NOTE_PAX_NAME,
987 		    ELF_NOTE_PAX_NAMESZ) == 0) {
988 			uint32_t flags;
989 			memcpy(&flags, ndesc, sizeof(flags));
990 			/* Convert the flags and insert them into
991 			 * the exec package. */
992 			pax_setup_elf_flags(epp, flags);
993 			break;
994 		}
995 		BADNOTE("PaX tag");
996 		goto bad;
997 
998 	case ELF_NOTE_TYPE_MARCH_TAG:
999 		/* Copy the machine arch into the package. */
1000 		if (np->n_namesz == ELF_NOTE_MARCH_NAMESZ
1001 		    && memcmp(ndata, ELF_NOTE_MARCH_NAME,
1002 			    ELF_NOTE_MARCH_NAMESZ) == 0) {
1003 			/* Do not truncate the buffer */
1004 			if (np->n_descsz > sizeof(epp->ep_machine_arch)) {
1005 				BADNOTE("description size limit");
1006 				goto bad;
1007 			}
1008 			/*
1009 			 * Ensure ndesc is NUL-terminated and of the
1010 			 * expected length.
1011 			 */
1012 			if (strnlen(ndesc, np->n_descsz) + 1 !=
1013 			    np->n_descsz) {
1014 				BADNOTE("description size");
1015 				goto bad;
1016 			}
1017 			strlcpy(epp->ep_machine_arch, ndesc,
1018 			    sizeof(epp->ep_machine_arch));
1019 			break;
1020 		}
1021 		BADNOTE("march tag");
1022 		goto bad;
1023 
1024 	case ELF_NOTE_TYPE_MCMODEL_TAG:
1025 		/* arch specific check for code model */
1026 #ifdef ELF_MD_MCMODEL_CHECK
1027 		if (np->n_namesz == ELF_NOTE_MCMODEL_NAMESZ
1028 		    && memcmp(ndata, ELF_NOTE_MCMODEL_NAME,
1029 			    ELF_NOTE_MCMODEL_NAMESZ) == 0) {
1030 			ELF_MD_MCMODEL_CHECK(epp, ndesc, np->n_descsz);
1031 			break;
1032 		}
1033 		BADNOTE("mcmodel tag");
1034 		goto bad;
1035 #endif
1036 		break;
1037 
1038 	case ELF_NOTE_TYPE_SUSE_VERSION_TAG:
1039 		break;
1040 
1041 	case ELF_NOTE_TYPE_GO_BUILDID_TAG:
1042 		break;
1043 
1044 	default:
1045 		BADNOTE("unknown tag");
1046 bad:
1047 #ifdef DIAGNOSTIC
1048 		/* Ignore GNU tags */
1049 		if (np->n_namesz == ELF_NOTE_GNU_NAMESZ &&
1050 		    memcmp(ndata, ELF_NOTE_GNU_NAME,
1051 		    ELF_NOTE_GNU_NAMESZ) == 0)
1052 		    break;
1053 
1054 		int ns = (int)np->n_namesz;
1055 		printf("%s: Unknown elf note type %d (%s): "
1056 		    "[namesz=%d, descsz=%d name=%-*.*s]\n",
1057 		    epp->ep_kname, np->n_type, badnote, np->n_namesz,
1058 		    np->n_descsz, ns, ns, ndata);
1059 #endif
1060 		break;
1061 	}
1062 
1063 	return isnetbsd;
1064 }
1065 
1066 int
1067 netbsd_elf_probe(struct lwp *l, struct exec_package *epp, void *eh, char *itp,
1068     vaddr_t *pos)
1069 {
1070 	int error;
1071 
1072 	if ((error = netbsd_elf_signature(l, epp, eh)) != 0)
1073 		return error;
1074 #ifdef ELF_MD_PROBE_FUNC
1075 	if ((error = ELF_MD_PROBE_FUNC(l, epp, eh, itp, pos)) != 0)
1076 		return error;
1077 #elif defined(ELF_INTERP_NON_RELOCATABLE)
1078 	*pos = ELF_LINK_ADDR;
1079 #endif
1080 	epp->ep_flags |= EXEC_FORCEAUX;
1081 	return 0;
1082 }
1083 
1084 void
1085 elf_free_emul_arg(void *arg)
1086 {
1087 	struct elf_args *ap = arg;
1088 	KASSERT(ap != NULL);
1089 	kmem_free(ap, sizeof(*ap));
1090 }
1091