xref: /netbsd-src/sys/kern/exec_elf.c (revision a7e090f70e491979434963c9a27df4020fe0a18b)
1 /*	$NetBSD: exec_elf.c,v 1.19 2010/03/22 22:10:10 drochner 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.19 2010/03/22 22:10:10 drochner 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/malloc.h>
69 #include <sys/kmem.h>
70 #include <sys/namei.h>
71 #include <sys/vnode.h>
72 #include <sys/exec.h>
73 #include <sys/exec_elf.h>
74 #include <sys/syscall.h>
75 #include <sys/signalvar.h>
76 #include <sys/mount.h>
77 #include <sys/stat.h>
78 #include <sys/kauth.h>
79 #include <sys/bitops.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 
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_file		ELFNAME(load_file)
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_probe	ELFNAME2(netbsd,probe)
97 #define	coredump		ELFNAMEEND(coredump)
98 
99 int	elf_load_file(struct lwp *, struct exec_package *, char *,
100 	    struct exec_vmcmd_set *, u_long *, struct elf_args *, Elf_Addr *);
101 void	elf_load_psection(struct exec_vmcmd_set *, struct vnode *,
102 	    const Elf_Phdr *, Elf_Addr *, u_long *, int *, int);
103 
104 int	netbsd_elf_signature(struct lwp *, struct exec_package *, Elf_Ehdr *);
105 int	netbsd_elf_probe(struct lwp *, struct exec_package *, void *, char *,
106 	    vaddr_t *);
107 
108 /* round up and down to page boundaries. */
109 #define	ELF_ROUND(a, b)		(((a) + (b) - 1) & ~((b) - 1))
110 #define	ELF_TRUNC(a, b)		((a) & ~((b) - 1))
111 
112 /*
113  * Arbitrary limits to avoid DoS for excessive memory allocation.
114  */
115 #define MAXPHNUM	128
116 #define MAXSHNUM	32768
117 #define MAXNOTESIZE	1024
118 
119 static void
120 elf_placedynexec(struct lwp *l, struct exec_package *epp, Elf_Ehdr *eh,
121     Elf_Phdr *ph)
122 {
123 	Elf_Addr align, offset;
124 	int i;
125 
126 	for (align = i = 0; i < eh->e_phnum; i++)
127 		if (ph[i].p_type == PT_LOAD && ph[i].p_align > align)
128 			align = ph[i].p_align;
129 
130 #ifdef PAX_ASLR
131 	if (pax_aslr_active(l)) {
132 		size_t pax_align, l2, delta;
133 		uint32_t r;
134 
135 		pax_align = align;
136 
137 		r = arc4random();
138 
139 		if (pax_align == 0)
140 			pax_align = PGSHIFT;
141 		l2 = ilog2(pax_align);
142 		delta = PAX_ASLR_DELTA(r, l2, PAX_ASLR_DELTA_EXEC_LEN);
143 		offset = ELF_TRUNC(delta, pax_align) + PAGE_SIZE;
144 #ifdef PAX_ASLR_DEBUG
145 		uprintf("r=0x%x l2=0x%zx PGSHIFT=0x%x Delta=0x%zx\n", r, l2,
146 		    PGSHIFT, delta);
147 		uprintf("pax offset=0x%zx entry=0x%llx\n",
148 		    offset, (unsigned long long)eh->e_entry);
149 #endif /* PAX_ASLR_DEBUG */
150 	} else
151 #endif /* PAX_ASLR */
152 		offset = MAX(align, PAGE_SIZE);
153 
154 	for (i = 0; i < eh->e_phnum; i++)
155 		ph[i].p_vaddr += offset;
156 	eh->e_entry += offset;
157 }
158 
159 /*
160  * Copy arguments onto the stack in the normal way, but add some
161  * extra information in case of dynamic binding.
162  */
163 int
164 elf_copyargs(struct lwp *l, struct exec_package *pack,
165     struct ps_strings *arginfo, char **stackp, void *argp)
166 {
167 	size_t len, vlen;
168 	AuxInfo ai[ELF_AUX_ENTRIES], *a, *execname;
169 	struct elf_args *ap;
170 	int error;
171 
172 	if ((error = copyargs(l, pack, arginfo, stackp, argp)) != 0)
173 		return error;
174 
175 	a = ai;
176 	execname = NULL;
177 
178 	/*
179 	 * Push extra arguments on the stack needed by dynamically
180 	 * linked binaries
181 	 */
182 	if ((ap = (struct elf_args *)pack->ep_emul_arg)) {
183 		struct vattr *vap = pack->ep_vap;
184 
185 		a->a_type = AT_PHDR;
186 		a->a_v = ap->arg_phaddr;
187 		a++;
188 
189 		a->a_type = AT_PHENT;
190 		a->a_v = ap->arg_phentsize;
191 		a++;
192 
193 		a->a_type = AT_PHNUM;
194 		a->a_v = ap->arg_phnum;
195 		a++;
196 
197 		a->a_type = AT_PAGESZ;
198 		a->a_v = PAGE_SIZE;
199 		a++;
200 
201 		a->a_type = AT_BASE;
202 		a->a_v = ap->arg_interp;
203 		a++;
204 
205 		a->a_type = AT_FLAGS;
206 		a->a_v = 0;
207 		a++;
208 
209 		a->a_type = AT_ENTRY;
210 		a->a_v = ap->arg_entry;
211 		a++;
212 
213 		a->a_type = AT_EUID;
214 		if (vap->va_mode & S_ISUID)
215 			a->a_v = vap->va_uid;
216 		else
217 			a->a_v = kauth_cred_geteuid(l->l_cred);
218 		a++;
219 
220 		a->a_type = AT_RUID;
221 		a->a_v = kauth_cred_getuid(l->l_cred);
222 		a++;
223 
224 		a->a_type = AT_EGID;
225 		if (vap->va_mode & S_ISGID)
226 			a->a_v = vap->va_gid;
227 		else
228 			a->a_v = kauth_cred_getegid(l->l_cred);
229 		a++;
230 
231 		a->a_type = AT_RGID;
232 		a->a_v = kauth_cred_getgid(l->l_cred);
233 		a++;
234 
235 		if (pack->ep_path) {
236 			execname = a;
237 			a->a_type = AT_SUN_EXECNAME;
238 			a++;
239 		}
240 
241 		free(ap, M_TEMP);
242 		pack->ep_emul_arg = NULL;
243 	}
244 
245 	a->a_type = AT_NULL;
246 	a->a_v = 0;
247 	a++;
248 
249 	vlen = (a - ai) * sizeof(AuxInfo);
250 
251 	if (execname) {
252 		char *path = pack->ep_path;
253 		execname->a_v = (uintptr_t)(*stackp + vlen);
254 		len = strlen(path) + 1;
255 		if ((error = copyout(path, (*stackp + vlen), len)) != 0)
256 			return error;
257 		len = ALIGN(len);
258 	} else
259 		len = 0;
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 of ok ENOEXEC if error
272  */
273 int
274 elf_check_header(Elf_Ehdr *eh, int type)
275 {
276 
277 	if (memcmp(eh->e_ident, ELFMAG, SELFMAG) != 0 ||
278 	    eh->e_ident[EI_CLASS] != ELFCLASS)
279 		return ENOEXEC;
280 
281 	switch (eh->e_machine) {
282 
283 	ELFDEFNNAME(MACHDEP_ID_CASES)
284 
285 	default:
286 		return ENOEXEC;
287 	}
288 
289 	if (ELF_EHDR_FLAGS_OK(eh) == 0)
290 		return ENOEXEC;
291 
292 	if (eh->e_type != type)
293 		return ENOEXEC;
294 
295 	if (eh->e_shnum > MAXSHNUM || eh->e_phnum > MAXPHNUM)
296 		return ENOEXEC;
297 
298 	return 0;
299 }
300 
301 /*
302  * elf_load_psection():
303  *
304  * Load a psection at the appropriate address
305  */
306 void
307 elf_load_psection(struct exec_vmcmd_set *vcset, struct vnode *vp,
308     const Elf_Phdr *ph, Elf_Addr *addr, u_long *size, int *prot, int flags)
309 {
310 	u_long msize, psize, rm, rf;
311 	long diff, offset;
312 
313 	/*
314 	 * If the user specified an address, then we load there.
315 	 */
316 	if (*addr == ELFDEFNNAME(NO_ADDR))
317 		*addr = ph->p_vaddr;
318 
319 	if (ph->p_align > 1) {
320 		/*
321 		 * Make sure we are virtually aligned as we are supposed to be.
322 		 */
323 		diff = ph->p_vaddr - ELF_TRUNC(ph->p_vaddr, ph->p_align);
324 		KASSERT(*addr - diff == ELF_TRUNC(*addr, ph->p_align));
325 		/*
326 		 * But make sure to not map any pages before the start of the
327 		 * psection by limiting the difference to within a page.
328 		 */
329 		diff &= PAGE_MASK;
330 	} else
331 		diff = 0;
332 
333 	*prot |= (ph->p_flags & PF_R) ? VM_PROT_READ : 0;
334 	*prot |= (ph->p_flags & PF_W) ? VM_PROT_WRITE : 0;
335 	*prot |= (ph->p_flags & PF_X) ? VM_PROT_EXECUTE : 0;
336 
337 	/*
338 	 * Adjust everything so it all starts on a page boundary.
339 	 */
340 	*addr -= diff;
341 	offset = ph->p_offset - diff;
342 	*size = ph->p_filesz + diff;
343 	msize = ph->p_memsz + diff;
344 
345 	if (ph->p_align >= PAGE_SIZE) {
346 		if ((ph->p_flags & PF_W) != 0) {
347 			/*
348 			 * Because the pagedvn pager can't handle zero fill
349 			 * of the last data page if it's not page aligned we
350 			 * map the last page readvn.
351 			 */
352 			psize = trunc_page(*size);
353 		} else {
354 			psize = round_page(*size);
355 		}
356 	} else {
357 		psize = *size;
358 	}
359 
360 	if (psize > 0) {
361 		NEW_VMCMD2(vcset, ph->p_align < PAGE_SIZE ?
362 		    vmcmd_map_readvn : vmcmd_map_pagedvn, psize, *addr, vp,
363 		    offset, *prot, flags);
364 		flags &= VMCMD_RELATIVE;
365 	}
366 	if (psize < *size) {
367 		NEW_VMCMD2(vcset, vmcmd_map_readvn, *size - psize,
368 		    *addr + psize, vp, offset + psize, *prot, flags);
369 	}
370 
371 	/*
372 	 * Check if we need to extend the size of the segment (does
373 	 * bss extend page the next page boundary)?
374 	 */
375 	rm = round_page(*addr + msize);
376 	rf = round_page(*addr + *size);
377 
378 	if (rm != rf) {
379 		NEW_VMCMD2(vcset, vmcmd_map_zero, rm - rf, rf, NULLVP,
380 		    0, *prot, flags & VMCMD_RELATIVE);
381 		*size = msize;
382 	}
383 }
384 
385 /*
386  * elf_load_file():
387  *
388  * Load a file (interpreter/library) pointed to by path
389  * [stolen from coff_load_shlib()]. Made slightly generic
390  * so it might be used externally.
391  */
392 int
393 elf_load_file(struct lwp *l, struct exec_package *epp, char *path,
394     struct exec_vmcmd_set *vcset, u_long *entryoff, struct elf_args *ap,
395     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 *ph0;
403 	const Elf_Phdr *base_ph;
404 	const Elf_Phdr *last_ph;
405 	u_long phsize;
406 	Elf_Addr addr = *last;
407 	struct proc *p;
408 
409 	p = l->l_proc;
410 
411 	/*
412 	 * 1. open file
413 	 * 2. read filehdr
414 	 * 3. map text, data, and bss out of it using VM_*
415 	 */
416 	vp = epp->ep_interp;
417 	if (vp == NULL) {
418 		error = emul_find_interp(l, epp, path);
419 		if (error != 0)
420 			return error;
421 		vp = epp->ep_interp;
422 	}
423 	/* We'll tidy this ourselves - otherwise we have locking issues */
424 	epp->ep_interp = NULL;
425 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
426 
427 	/*
428 	 * Similarly, if it's not marked as executable, or it's not a regular
429 	 * file, we don't allow it to be used.
430 	 */
431 	if (vp->v_type != VREG) {
432 		error = EACCES;
433 		goto badunlock;
434 	}
435 	if ((error = VOP_ACCESS(vp, VEXEC, l->l_cred)) != 0)
436 		goto badunlock;
437 
438 	/* get attributes */
439 	if ((error = VOP_GETATTR(vp, &attr, l->l_cred)) != 0)
440 		goto badunlock;
441 
442 	/*
443 	 * Check mount point.  Though we're not trying to exec this binary,
444 	 * we will be executing code from it, so if the mount point
445 	 * disallows execution or set-id-ness, we punt or kill the set-id.
446 	 */
447 	if (vp->v_mount->mnt_flag & MNT_NOEXEC) {
448 		error = EACCES;
449 		goto badunlock;
450 	}
451 	if (vp->v_mount->mnt_flag & MNT_NOSUID)
452 		epp->ep_vap->va_mode &= ~(S_ISUID | S_ISGID);
453 
454 #ifdef notyet /* XXX cgd 960926 */
455 	XXX cgd 960926: (maybe) VOP_OPEN it (and VOP_CLOSE in copyargs?)
456 #endif
457 
458 	error = vn_marktext(vp);
459 	if (error)
460 		goto badunlock;
461 
462 	VOP_UNLOCK(vp, 0);
463 
464 	if ((error = exec_read_from(l, vp, 0, &eh, sizeof(eh))) != 0)
465 		goto bad;
466 
467 	if ((error = elf_check_header(&eh, ET_DYN)) != 0)
468 		goto bad;
469 
470 	if (eh.e_phnum > MAXPHNUM || eh.e_phnum == 0) {
471 		error = ENOEXEC;
472 		goto bad;
473 	}
474 
475 	phsize = eh.e_phnum * sizeof(Elf_Phdr);
476 	ph = kmem_alloc(phsize, KM_SLEEP);
477 
478 	if ((error = exec_read_from(l, vp, eh.e_phoff, ph, phsize)) != 0)
479 		goto bad;
480 
481 #ifdef ELF_INTERP_NON_RELOCATABLE
482 	/*
483 	 * Evil hack:  Only MIPS should be non-relocatable, and the
484 	 * psections should have a high address (typically 0x5ffe0000).
485 	 * If it's now relocatable, it should be linked at 0 and the
486 	 * psections should have zeros in the upper part of the address.
487 	 * Otherwise, force the load at the linked address.
488 	 */
489 	if (*last == ELF_LINK_ADDR && (ph->p_vaddr & 0xffff0000) == 0)
490 		*last = ELFDEFNNAME(NO_ADDR);
491 #endif
492 
493 	/*
494 	 * If no position to load the interpreter was set by a probe
495 	 * function, pick the same address that a non-fixed mmap(0, ..)
496 	 * would (i.e. something safely out of the way).
497 	 */
498 	if (*last == ELFDEFNNAME(NO_ADDR)) {
499 		u_long limit = 0;
500 		/*
501 		 * Find the start and ending addresses of the psections to
502 		 * be loaded.  This will give us the size.
503 		 */
504 		for (i = 0, ph0 = ph, base_ph = NULL; i < eh.e_phnum;
505 		     i++, ph0++) {
506 			if (ph0->p_type == PT_LOAD) {
507 				u_long psize = ph0->p_vaddr + ph0->p_memsz;
508 				if (base_ph == NULL)
509 					base_ph = ph0;
510 				if (psize > limit)
511 					limit = psize;
512 			}
513 		}
514 
515 		if (base_ph == NULL) {
516 			error = ENOEXEC;
517 			goto bad;
518 		}
519 
520 		/*
521 		 * Now compute the size and load address.
522 		 */
523 		addr = (*epp->ep_esch->es_emul->e_vm_default_addr)(p,
524 		    epp->ep_daddr,
525 		    round_page(limit) - trunc_page(base_ph->p_vaddr));
526 	} else
527 		addr = *last; /* may be ELF_LINK_ADDR */
528 
529 	/*
530 	 * Load all the necessary sections
531 	 */
532 	for (i = 0, ph0 = ph, base_ph = NULL, last_ph = NULL;
533 	     i < eh.e_phnum; i++, ph0++) {
534 		switch (ph0->p_type) {
535 		case PT_LOAD: {
536 			u_long size;
537 			int prot = 0;
538 			int flags;
539 
540 			if (base_ph == NULL) {
541 				/*
542 				 * First encountered psection is always the
543 				 * base psection.  Make sure it's aligned
544 				 * properly (align down for topdown and align
545 				 * upwards for not topdown).
546 				 */
547 				base_ph = ph0;
548 				flags = VMCMD_BASE;
549 				if (addr == ELF_LINK_ADDR)
550 					addr = ph0->p_vaddr;
551 				if (p->p_vmspace->vm_map.flags & VM_MAP_TOPDOWN)
552 					addr = ELF_TRUNC(addr, ph0->p_align);
553 				else
554 					addr = ELF_ROUND(addr, ph0->p_align);
555 			} else {
556 				u_long limit = round_page(last_ph->p_vaddr
557 				    + last_ph->p_memsz);
558 				u_long base = trunc_page(ph0->p_vaddr);
559 
560 				/*
561 				 * If there is a gap in between the psections,
562 				 * map it as inaccessible so nothing else
563 				 * mmap'ed will be placed there.
564 				 */
565 				if (limit != base) {
566 					NEW_VMCMD2(vcset, vmcmd_map_zero,
567 					    base - limit,
568 					    limit - base_ph->p_vaddr, NULLVP,
569 					    0, VM_PROT_NONE, VMCMD_RELATIVE);
570 				}
571 
572 				addr = ph0->p_vaddr - base_ph->p_vaddr;
573 				flags = VMCMD_RELATIVE;
574 			}
575 			last_ph = ph0;
576 			elf_load_psection(vcset, vp, &ph[i], &addr,
577 			    &size, &prot, flags);
578 			/*
579 			 * If entry is within this psection then this
580 			 * must contain the .text section.  *entryoff is
581 			 * relative to the base psection.
582 			 */
583 			if (eh.e_entry >= ph0->p_vaddr &&
584 			    eh.e_entry < (ph0->p_vaddr + size)) {
585 				*entryoff = eh.e_entry - base_ph->p_vaddr;
586 			}
587 			addr += size;
588 			break;
589 		}
590 
591 		case PT_DYNAMIC:
592 		case PT_PHDR:
593 			break;
594 
595 		case PT_NOTE:
596 			break;
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, 0);
613 
614 bad:
615 	if (ph != NULL)
616 		kmem_free(ph, phsize);
617 #ifdef notyet /* XXX cgd 960926 */
618 	(maybe) VOP_CLOSE it
619 #endif
620 	vrele(vp);
621 	return error;
622 }
623 
624 /*
625  * exec_elf_makecmds(): Prepare an Elf binary's exec package
626  *
627  * First, set of the various offsets/lengths in the exec package.
628  *
629  * Then, mark the text image busy (so it can be demand paged) or error
630  * out if this is not possible.  Finally, set up vmcmds for the
631  * text, data, bss, and stack segments.
632  */
633 int
634 exec_elf_makecmds(struct lwp *l, struct exec_package *epp)
635 {
636 	Elf_Ehdr *eh = epp->ep_hdr;
637 	Elf_Phdr *ph, *pp;
638 	Elf_Addr phdr = 0, pos = 0;
639 	int error, i, nload;
640 	char *interp = NULL;
641 	u_long phsize;
642 	struct proc *p;
643 	bool is_dyn;
644 
645 	if (epp->ep_hdrvalid < sizeof(Elf_Ehdr))
646 		return ENOEXEC;
647 
648 	is_dyn = elf_check_header(eh, ET_DYN) == 0;
649 	/*
650 	 * XXX allow for executing shared objects. It seems silly
651 	 * but other ELF-based systems allow it as well.
652 	 */
653 	if (elf_check_header(eh, ET_EXEC) != 0 && !is_dyn)
654 		return ENOEXEC;
655 
656 	if (eh->e_phnum > MAXPHNUM || eh->e_phnum == 0)
657 		return ENOEXEC;
658 
659 	error = vn_marktext(epp->ep_vp);
660 	if (error)
661 		return error;
662 
663 	/*
664 	 * Allocate space to hold all the program headers, and read them
665 	 * from the file
666 	 */
667 	p = l->l_proc;
668 	phsize = eh->e_phnum * sizeof(Elf_Phdr);
669 	ph = kmem_alloc(phsize, KM_SLEEP);
670 
671 	if ((error = exec_read_from(l, epp->ep_vp, eh->e_phoff, ph, phsize)) !=
672 	    0)
673 		goto bad;
674 
675 	epp->ep_taddr = epp->ep_tsize = ELFDEFNNAME(NO_ADDR);
676 	epp->ep_daddr = epp->ep_dsize = ELFDEFNNAME(NO_ADDR);
677 
678 	for (i = 0; i < eh->e_phnum; i++) {
679 		pp = &ph[i];
680 		if (pp->p_type == PT_INTERP) {
681 			if (pp->p_filesz >= MAXPATHLEN) {
682 				error = ENOEXEC;
683 				goto bad;
684 			}
685 			interp = PNBUF_GET();
686 			interp[0] = '\0';
687 			if ((error = exec_read_from(l, epp->ep_vp,
688 			    pp->p_offset, interp, pp->p_filesz)) != 0)
689 				goto bad;
690 			break;
691 		}
692 	}
693 
694 	/*
695 	 * On the same architecture, we may be emulating different systems.
696 	 * See which one will accept this executable.
697 	 *
698 	 * Probe functions would normally see if the interpreter (if any)
699 	 * exists. Emulation packages may possibly replace the interpreter in
700 	 * interp[] with a changed path (/emul/xxx/<path>).
701 	 */
702 	pos = ELFDEFNNAME(NO_ADDR);
703 	if (epp->ep_esch->u.elf_probe_func) {
704 		vaddr_t startp = (vaddr_t)pos;
705 
706 		error = (*epp->ep_esch->u.elf_probe_func)(l, epp, eh, interp,
707 							  &startp);
708 		if (error)
709 			goto bad;
710 		pos = (Elf_Addr)startp;
711 	}
712 
713 #if defined(PAX_MPROTECT) || defined(PAX_SEGVGUARD) || defined(PAX_ASLR)
714 	p->p_pax = epp->ep_pax_flags;
715 #endif /* PAX_MPROTECT || PAX_SEGVGUARD || PAX_ASLR */
716 
717 	if (is_dyn)
718 		elf_placedynexec(l, epp, eh, ph);
719 
720 	/*
721 	 * Load all the necessary sections
722 	 */
723 	for (i = nload = 0; i < eh->e_phnum; i++) {
724 		Elf_Addr  addr = ELFDEFNNAME(NO_ADDR);
725 		u_long size = 0;
726 		int prot = 0;
727 
728 		pp = &ph[i];
729 
730 		switch (ph[i].p_type) {
731 		case PT_LOAD:
732 			/*
733 			 * XXX
734 			 * Can handle only 2 sections: text and data
735 			 */
736 			if (nload++ == 2) {
737 				error = ENOEXEC;
738 				goto bad;
739 			}
740 			elf_load_psection(&epp->ep_vmcmds, epp->ep_vp,
741 			    &ph[i], &addr, &size, &prot, VMCMD_FIXED);
742 
743 			/*
744 			 * Decide whether it's text or data by looking
745 			 * at the entry point.
746 			 */
747 			if (eh->e_entry >= addr &&
748 			    eh->e_entry < (addr + size)) {
749 				epp->ep_taddr = addr;
750 				epp->ep_tsize = size;
751 				if (epp->ep_daddr == ELFDEFNNAME(NO_ADDR)) {
752 					epp->ep_daddr = addr;
753 					epp->ep_dsize = size;
754 				}
755 			} else {
756 				epp->ep_daddr = addr;
757 				epp->ep_dsize = size;
758 			}
759 			break;
760 
761 		case PT_SHLIB:
762 			/* SCO has these sections. */
763 		case PT_INTERP:
764 			/* Already did this one. */
765 		case PT_DYNAMIC:
766 			break;
767 		case PT_NOTE:
768 			break;
769 		case PT_PHDR:
770 			/* Note address of program headers (in text segment) */
771 			phdr = pp->p_vaddr;
772 			break;
773 
774 		default:
775 			/*
776 			 * Not fatal; we don't need to understand everything.
777 			 */
778 			break;
779 		}
780 	}
781 
782 	/*
783 	 * Check if we found a dynamically linked binary and arrange to load
784 	 * its interpreter
785 	 */
786 	if (interp) {
787 		struct elf_args *ap;
788 		int j = epp->ep_vmcmds.evs_used;
789 		u_long interp_offset;
790 
791 		ap = (struct elf_args *)malloc(sizeof(struct elf_args),
792 		    M_TEMP, M_WAITOK);
793 		if ((error = elf_load_file(l, epp, interp,
794 		    &epp->ep_vmcmds, &interp_offset, ap, &pos)) != 0) {
795 			free(ap, M_TEMP);
796 			goto bad;
797 		}
798 		ap->arg_interp = epp->ep_vmcmds.evs_cmds[j].ev_addr;
799 		epp->ep_entry = ap->arg_interp + interp_offset;
800 		ap->arg_phaddr = phdr;
801 
802 		ap->arg_phentsize = eh->e_phentsize;
803 		ap->arg_phnum = eh->e_phnum;
804 		ap->arg_entry = eh->e_entry;
805 
806 		epp->ep_emul_arg = ap;
807 
808 		PNBUF_PUT(interp);
809 	} else
810 		epp->ep_entry = eh->e_entry;
811 
812 #ifdef ELF_MAP_PAGE_ZERO
813 	/* Dell SVR4 maps page zero, yeuch! */
814 	NEW_VMCMD(&epp->ep_vmcmds, vmcmd_map_readvn, PAGE_SIZE, 0,
815 	    epp->ep_vp, 0, VM_PROT_READ);
816 #endif
817 	kmem_free(ph, phsize);
818 	return (*epp->ep_esch->es_setup_stack)(l, epp);
819 
820 bad:
821 	if (interp)
822 		PNBUF_PUT(interp);
823 	kmem_free(ph, phsize);
824 	kill_vmcmds(&epp->ep_vmcmds);
825 	return error;
826 }
827 
828 int
829 netbsd_elf_signature(struct lwp *l, struct exec_package *epp,
830     Elf_Ehdr *eh)
831 {
832 	size_t i;
833 	Elf_Shdr *sh;
834 	Elf_Nhdr *np;
835 	size_t shsize;
836 	int error;
837 	int isnetbsd = 0;
838 	char *ndata;
839 
840 	epp->ep_pax_flags = 0;
841 	if (eh->e_shnum > MAXSHNUM || eh->e_shnum == 0)
842 		return ENOEXEC;
843 
844 	shsize = eh->e_shnum * sizeof(Elf_Shdr);
845 	sh = kmem_alloc(shsize, KM_SLEEP);
846 	error = exec_read_from(l, epp->ep_vp, eh->e_shoff, sh, shsize);
847 	if (error)
848 		goto out;
849 
850 	np = kmem_alloc(MAXNOTESIZE, KM_SLEEP);
851 	for (i = 0; i < eh->e_shnum; i++) {
852 		Elf_Shdr *shp = &sh[i];
853 
854 		if (shp->sh_type != SHT_NOTE ||
855 		    shp->sh_size > MAXNOTESIZE ||
856 		    shp->sh_size < sizeof(Elf_Nhdr) + ELF_NOTE_NETBSD_NAMESZ)
857 			continue;
858 
859 		error = exec_read_from(l, epp->ep_vp, shp->sh_offset, np,
860 		    shp->sh_size);
861 		if (error)
862 			continue;
863 
864 		ndata = (char *)(np + 1);
865 		switch (np->n_type) {
866 		case ELF_NOTE_TYPE_NETBSD_TAG:
867 			if (np->n_namesz != ELF_NOTE_NETBSD_NAMESZ ||
868 			    np->n_descsz != ELF_NOTE_NETBSD_DESCSZ ||
869 			    memcmp(ndata, ELF_NOTE_NETBSD_NAME,
870 			    ELF_NOTE_NETBSD_NAMESZ))
871 				goto bad;
872 			isnetbsd = 1;
873 			break;
874 
875 		case ELF_NOTE_TYPE_PAX_TAG:
876 			if (np->n_namesz != ELF_NOTE_PAX_NAMESZ ||
877 			    np->n_descsz != ELF_NOTE_PAX_DESCSZ ||
878 			    memcmp(ndata, ELF_NOTE_PAX_NAME,
879 			    ELF_NOTE_PAX_NAMESZ)) {
880 bad:
881 #ifdef DIAGNOSTIC
882 				printf("%s: bad tag %d: "
883 				    "[%d %d, %d %d, %*.*s %*.*s]\n",
884 				    epp->ep_name,
885 				    np->n_type,
886 				    np->n_namesz, ELF_NOTE_PAX_NAMESZ,
887 				    np->n_descsz, ELF_NOTE_PAX_DESCSZ,
888 				    ELF_NOTE_PAX_NAMESZ,
889 				    ELF_NOTE_PAX_NAMESZ,
890 				    ndata,
891 				    ELF_NOTE_PAX_NAMESZ,
892 				    ELF_NOTE_PAX_NAMESZ,
893 				    ELF_NOTE_PAX_NAME);
894 #endif
895 				continue;
896 			}
897 			(void)memcpy(&epp->ep_pax_flags,
898 			    ndata + ELF_NOTE_PAX_NAMESZ,
899 			    sizeof(epp->ep_pax_flags));
900 			break;
901 
902 		default:
903 #ifdef DIAGNOSTIC
904 			printf("%s: unknown note type %d\n", epp->ep_name,
905 			    np->n_type);
906 #endif
907 			break;
908 		}
909 	}
910 	kmem_free(np, MAXNOTESIZE);
911 
912 	error = isnetbsd ? 0 : ENOEXEC;
913 out:
914 	kmem_free(sh, shsize);
915 	return error;
916 }
917 
918 int
919 netbsd_elf_probe(struct lwp *l, struct exec_package *epp, void *eh, char *itp,
920     vaddr_t *pos)
921 {
922 	int error;
923 
924 	if ((error = netbsd_elf_signature(l, epp, eh)) != 0)
925 		return error;
926 #ifdef ELF_MD_PROBE_FUNC
927 	if ((error = ELF_MD_PROBE_FUNC(l, epp, eh, itp, pos)) != 0)
928 		return error;
929 #elif defined(ELF_INTERP_NON_RELOCATABLE)
930 	*pos = ELF_LINK_ADDR;
931 #endif
932 	return 0;
933 }
934