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