xref: /netbsd-src/sys/kern/exec_elf.c (revision 230b95665bbd3a9d1a53658a36b1053f8382a519)
1 /*	$NetBSD: exec_elf.c,v 1.70 2014/08/17 23:03:58 chs 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.70 2014/08/17 23:03:58 chs 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 static void
119 elf_placedynexec(struct lwp *l, struct exec_package *epp, Elf_Ehdr *eh,
120     Elf_Phdr *ph)
121 {
122 	Elf_Addr align, offset;
123 	int i;
124 
125 	for (align = i = 0; i < eh->e_phnum; i++)
126 		if (ph[i].p_type == PT_LOAD && ph[i].p_align > align)
127 			align = ph[i].p_align;
128 
129 #ifdef PAX_ASLR
130 	if (pax_aslr_active(l)) {
131 		size_t pax_align, l2, delta;
132 		uint32_t r;
133 
134 		pax_align = align;
135 
136 		r = cprng_fast32();
137 
138 		if (pax_align == 0)
139 			pax_align = PGSHIFT;
140 		l2 = ilog2(pax_align);
141 		delta = PAX_ASLR_DELTA(r, l2, PAX_ASLR_DELTA_EXEC_LEN);
142 		offset = ELF_TRUNC(delta, pax_align) + PAGE_SIZE;
143 #ifdef PAX_ASLR_DEBUG
144 		uprintf("r=0x%x l2=0x%zx PGSHIFT=0x%x Delta=0x%zx\n", r, l2,
145 		    PGSHIFT, delta);
146 		uprintf("pax offset=0x%llx entry=0x%llx\n",
147 		    (unsigned long long)offset,
148 		    (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 	offset += epp->ep_vm_minaddr;
155 
156 	for (i = 0; i < eh->e_phnum; i++)
157 		ph[i].p_vaddr += offset;
158 	epp->ep_entryoffset = offset;
159 	eh->e_entry += offset;
160 }
161 
162 /*
163  * Copy arguments onto the stack in the normal way, but add some
164  * extra information in case of dynamic binding.
165  */
166 int
167 elf_copyargs(struct lwp *l, struct exec_package *pack,
168     struct ps_strings *arginfo, char **stackp, void *argp)
169 {
170 	size_t len, vlen;
171 	AuxInfo ai[ELF_AUX_ENTRIES], *a, *execname;
172 	struct elf_args *ap;
173 	int error;
174 
175 	if ((error = copyargs(l, pack, arginfo, stackp, argp)) != 0)
176 		return error;
177 
178 	a = ai;
179 	execname = NULL;
180 
181 	/*
182 	 * Push extra arguments on the stack needed by dynamically
183 	 * linked binaries
184 	 */
185 	if ((ap = (struct elf_args *)pack->ep_emul_arg)) {
186 		struct vattr *vap = pack->ep_vap;
187 
188 		a->a_type = AT_PHDR;
189 		a->a_v = ap->arg_phaddr;
190 		a++;
191 
192 		a->a_type = AT_PHENT;
193 		a->a_v = ap->arg_phentsize;
194 		a++;
195 
196 		a->a_type = AT_PHNUM;
197 		a->a_v = ap->arg_phnum;
198 		a++;
199 
200 		a->a_type = AT_PAGESZ;
201 		a->a_v = PAGE_SIZE;
202 		a++;
203 
204 		a->a_type = AT_BASE;
205 		a->a_v = ap->arg_interp;
206 		a++;
207 
208 		a->a_type = AT_FLAGS;
209 		a->a_v = 0;
210 		a++;
211 
212 		a->a_type = AT_ENTRY;
213 		a->a_v = ap->arg_entry;
214 		a++;
215 
216 		a->a_type = AT_EUID;
217 		if (vap->va_mode & S_ISUID)
218 			a->a_v = vap->va_uid;
219 		else
220 			a->a_v = kauth_cred_geteuid(l->l_cred);
221 		a++;
222 
223 		a->a_type = AT_RUID;
224 		a->a_v = kauth_cred_getuid(l->l_cred);
225 		a++;
226 
227 		a->a_type = AT_EGID;
228 		if (vap->va_mode & S_ISGID)
229 			a->a_v = vap->va_gid;
230 		else
231 			a->a_v = kauth_cred_getegid(l->l_cred);
232 		a++;
233 
234 		a->a_type = AT_RGID;
235 		a->a_v = kauth_cred_getgid(l->l_cred);
236 		a++;
237 
238 		a->a_type = AT_STACKBASE;
239 		a->a_v = l->l_proc->p_stackbase;
240 		a++;
241 
242 		if (pack->ep_path) {
243 			execname = a;
244 			a->a_type = AT_SUN_EXECNAME;
245 			a++;
246 		}
247 
248 		exec_free_emul_arg(pack);
249 	}
250 
251 	a->a_type = AT_NULL;
252 	a->a_v = 0;
253 	a++;
254 
255 	vlen = (a - ai) * sizeof(ai[0]);
256 
257 	KASSERT(vlen <= sizeof(ai));
258 
259 	if (execname) {
260 		char *path = pack->ep_path;
261 		execname->a_v = (uintptr_t)(*stackp + vlen);
262 		len = strlen(path) + 1;
263 		if ((error = copyout(path, (*stackp + vlen), len)) != 0)
264 			return error;
265 		len = ALIGN(len);
266 	} else
267 		len = 0;
268 
269 	if ((error = copyout(ai, *stackp, vlen)) != 0)
270 		return error;
271 	*stackp += vlen + len;
272 
273 	return 0;
274 }
275 
276 /*
277  * elf_check_header():
278  *
279  * Check header for validity; return 0 if ok, ENOEXEC if error
280  */
281 int
282 elf_check_header(Elf_Ehdr *eh)
283 {
284 
285 	if (memcmp(eh->e_ident, ELFMAG, SELFMAG) != 0 ||
286 	    eh->e_ident[EI_CLASS] != ELFCLASS)
287 		return ENOEXEC;
288 
289 	switch (eh->e_machine) {
290 
291 	ELFDEFNNAME(MACHDEP_ID_CASES)
292 
293 	default:
294 		return ENOEXEC;
295 	}
296 
297 	if (ELF_EHDR_FLAGS_OK(eh) == 0)
298 		return ENOEXEC;
299 
300 	if (eh->e_shnum > ELF_MAXSHNUM || eh->e_phnum > ELF_MAXPHNUM)
301 		return ENOEXEC;
302 
303 	return 0;
304 }
305 
306 /*
307  * elf_load_psection():
308  *
309  * Load a psection at the appropriate address
310  */
311 static void
312 elf_load_psection(struct exec_vmcmd_set *vcset, struct vnode *vp,
313     const Elf_Phdr *ph, Elf_Addr *addr, u_long *size, int flags)
314 {
315 	u_long msize, psize, rm, rf;
316 	long diff, offset;
317 	int vmprot = 0;
318 
319 	/*
320 	 * If the user specified an address, then we load there.
321 	 */
322 	if (*addr == ELFDEFNNAME(NO_ADDR))
323 		*addr = ph->p_vaddr;
324 
325 	if (ph->p_align > 1) {
326 		/*
327 		 * Make sure we are virtually aligned as we are supposed to be.
328 		 */
329 		diff = ph->p_vaddr - ELF_TRUNC(ph->p_vaddr, ph->p_align);
330 		KASSERT(*addr - diff == ELF_TRUNC(*addr, ph->p_align));
331 		/*
332 		 * But make sure to not map any pages before the start of the
333 		 * psection by limiting the difference to within a page.
334 		 */
335 		diff &= PAGE_MASK;
336 	} else
337 		diff = 0;
338 
339 	vmprot |= (ph->p_flags & PF_R) ? VM_PROT_READ : 0;
340 	vmprot |= (ph->p_flags & PF_W) ? VM_PROT_WRITE : 0;
341 	vmprot |= (ph->p_flags & PF_X) ? VM_PROT_EXECUTE : 0;
342 
343 	/*
344 	 * Adjust everything so it all starts on a page boundary.
345 	 */
346 	*addr -= diff;
347 	offset = ph->p_offset - diff;
348 	*size = ph->p_filesz + diff;
349 	msize = ph->p_memsz + diff;
350 
351 	if (ph->p_align >= PAGE_SIZE) {
352 		if ((ph->p_flags & PF_W) != 0) {
353 			/*
354 			 * Because the pagedvn pager can't handle zero fill
355 			 * of the last data page if it's not page aligned we
356 			 * map the last page readvn.
357 			 */
358 			psize = trunc_page(*size);
359 		} else {
360 			psize = round_page(*size);
361 		}
362 	} else {
363 		psize = *size;
364 	}
365 
366 	if (psize > 0) {
367 		NEW_VMCMD2(vcset, ph->p_align < PAGE_SIZE ?
368 		    vmcmd_map_readvn : vmcmd_map_pagedvn, psize, *addr, vp,
369 		    offset, vmprot, flags);
370 		flags &= VMCMD_RELATIVE;
371 	}
372 	if (psize < *size) {
373 		NEW_VMCMD2(vcset, vmcmd_map_readvn, *size - psize,
374 		    *addr + psize, vp, offset + psize, vmprot, flags);
375 	}
376 
377 	/*
378 	 * Check if we need to extend the size of the segment (does
379 	 * bss extend page the next page boundary)?
380 	 */
381 	rm = round_page(*addr + msize);
382 	rf = round_page(*addr + *size);
383 
384 	if (rm != rf) {
385 		NEW_VMCMD2(vcset, vmcmd_map_zero, rm - rf, rf, NULLVP,
386 		    0, vmprot, flags & VMCMD_RELATIVE);
387 		*size = msize;
388 	}
389 }
390 
391 /*
392  * elf_load_interp():
393  *
394  * Load an interpreter pointed to by path.
395  */
396 static int
397 elf_load_interp(struct lwp *l, struct exec_package *epp, char *path,
398     struct exec_vmcmd_set *vcset, u_long *entryoff, Elf_Addr *last)
399 {
400 	int error, i;
401 	struct vnode *vp;
402 	struct vattr attr;
403 	Elf_Ehdr eh;
404 	Elf_Phdr *ph = NULL;
405 	const Elf_Phdr *base_ph;
406 	const Elf_Phdr *last_ph;
407 	u_long phsize;
408 	Elf_Addr addr = *last;
409 	struct proc *p;
410 	bool use_topdown;
411 
412 	p = l->l_proc;
413 
414 	KASSERT(p->p_vmspace);
415 	if (__predict_true(p->p_vmspace != proc0.p_vmspace)) {
416 		use_topdown = p->p_vmspace->vm_map.flags & VM_MAP_TOPDOWN;
417 	} else {
418 #ifdef __USE_TOPDOWN_VM
419 		use_topdown = epp->ep_flags & EXEC_TOPDOWN_VM;
420 #else
421 		use_topdown = false;
422 #endif
423 	}
424 
425 	/*
426 	 * 1. open file
427 	 * 2. read filehdr
428 	 * 3. map text, data, and bss out of it using VM_*
429 	 */
430 	vp = epp->ep_interp;
431 	if (vp == NULL) {
432 		error = emul_find_interp(l, epp, path);
433 		if (error != 0)
434 			return error;
435 		vp = epp->ep_interp;
436 	}
437 	/* We'll tidy this ourselves - otherwise we have locking issues */
438 	epp->ep_interp = NULL;
439 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
440 
441 	/*
442 	 * Similarly, if it's not marked as executable, or it's not a regular
443 	 * file, we don't allow it to be used.
444 	 */
445 	if (vp->v_type != VREG) {
446 		error = EACCES;
447 		goto badunlock;
448 	}
449 	if ((error = VOP_ACCESS(vp, VEXEC, l->l_cred)) != 0)
450 		goto badunlock;
451 
452 	/* get attributes */
453 	if ((error = VOP_GETATTR(vp, &attr, l->l_cred)) != 0)
454 		goto badunlock;
455 
456 	/*
457 	 * Check mount point.  Though we're not trying to exec this binary,
458 	 * we will be executing code from it, so if the mount point
459 	 * disallows execution or set-id-ness, we punt or kill the set-id.
460 	 */
461 	if (vp->v_mount->mnt_flag & MNT_NOEXEC) {
462 		error = EACCES;
463 		goto badunlock;
464 	}
465 	if (vp->v_mount->mnt_flag & MNT_NOSUID)
466 		epp->ep_vap->va_mode &= ~(S_ISUID | S_ISGID);
467 
468 #ifdef notyet /* XXX cgd 960926 */
469 	XXX cgd 960926: (maybe) VOP_OPEN it (and VOP_CLOSE in copyargs?)
470 
471 	XXXps: this problem will make it impossible to use an interpreter
472 	from a file system which actually does something in VOP_OPEN
473 #endif
474 
475 	error = vn_marktext(vp);
476 	if (error)
477 		goto badunlock;
478 
479 	VOP_UNLOCK(vp);
480 
481 	if ((error = exec_read_from(l, vp, 0, &eh, sizeof(eh))) != 0)
482 		goto bad;
483 
484 	if ((error = elf_check_header(&eh)) != 0)
485 		goto bad;
486 	if (eh.e_type != ET_DYN || eh.e_phnum == 0) {
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 			error = ENOEXEC;
532 			goto bad;
533 		}
534 
535 		/*
536 		 * Now compute the size and load address.
537 		 */
538 		addr = (*epp->ep_esch->es_emul->e_vm_default_addr)(p,
539 		    epp->ep_daddr,
540 		    round_page(limit) - trunc_page(base_ph->p_vaddr));
541 	} else
542 		addr = *last; /* may be ELF_LINK_ADDR */
543 
544 	/*
545 	 * Load all the necessary sections
546 	 */
547 	for (i = 0, base_ph = NULL, last_ph = NULL; i < eh.e_phnum; i++) {
548 		switch (ph[i].p_type) {
549 		case PT_LOAD: {
550 			u_long size;
551 			int flags;
552 
553 			if (base_ph == NULL) {
554 				/*
555 				 * First encountered psection is always the
556 				 * base psection.  Make sure it's aligned
557 				 * properly (align down for topdown and align
558 				 * upwards for not topdown).
559 				 */
560 				base_ph = &ph[i];
561 				flags = VMCMD_BASE;
562 				if (addr == ELF_LINK_ADDR)
563 					addr = ph[i].p_vaddr;
564 				if (use_topdown)
565 					addr = ELF_TRUNC(addr, ph[i].p_align);
566 				else
567 					addr = ELF_ROUND(addr, ph[i].p_align);
568 			} else {
569 				u_long limit = round_page(last_ph->p_vaddr
570 				    + last_ph->p_memsz);
571 				u_long base = trunc_page(ph[i].p_vaddr);
572 
573 				/*
574 				 * If there is a gap in between the psections,
575 				 * map it as inaccessible so nothing else
576 				 * mmap'ed will be placed there.
577 				 */
578 				if (limit != base) {
579 					NEW_VMCMD2(vcset, vmcmd_map_zero,
580 					    base - limit,
581 					    limit - base_ph->p_vaddr, NULLVP,
582 					    0, VM_PROT_NONE, VMCMD_RELATIVE);
583 				}
584 
585 				addr = ph[i].p_vaddr - base_ph->p_vaddr;
586 				flags = VMCMD_RELATIVE;
587 			}
588 			last_ph = &ph[i];
589 			elf_load_psection(vcset, vp, &ph[i], &addr,
590 			    &size, flags);
591 			/*
592 			 * If entry is within this psection then this
593 			 * must contain the .text section.  *entryoff is
594 			 * relative to the base psection.
595 			 */
596 			if (eh.e_entry >= ph[i].p_vaddr &&
597 			    eh.e_entry < (ph[i].p_vaddr + size)) {
598 				*entryoff = eh.e_entry - base_ph->p_vaddr;
599 			}
600 			addr += size;
601 			break;
602 		}
603 
604 		default:
605 			break;
606 		}
607 	}
608 
609 	kmem_free(ph, phsize);
610 	/*
611 	 * This value is ignored if TOPDOWN.
612 	 */
613 	*last = addr;
614 	vrele(vp);
615 	return 0;
616 
617 badunlock:
618 	VOP_UNLOCK(vp);
619 
620 bad:
621 	if (ph != NULL)
622 		kmem_free(ph, phsize);
623 #ifdef notyet /* XXX cgd 960926 */
624 	(maybe) VOP_CLOSE it
625 #endif
626 	vrele(vp);
627 	return error;
628 }
629 
630 /*
631  * exec_elf_makecmds(): Prepare an Elf binary's exec package
632  *
633  * First, set of the various offsets/lengths in the exec package.
634  *
635  * Then, mark the text image busy (so it can be demand paged) or error
636  * out if this is not possible.  Finally, set up vmcmds for the
637  * text, data, bss, and stack segments.
638  */
639 int
640 exec_elf_makecmds(struct lwp *l, struct exec_package *epp)
641 {
642 	Elf_Ehdr *eh = epp->ep_hdr;
643 	Elf_Phdr *ph, *pp;
644 	Elf_Addr phdr = 0, computed_phdr = 0, pos = 0, end_text = 0;
645 	int error, i;
646 	char *interp = NULL;
647 	u_long phsize;
648 	struct elf_args *ap;
649 	bool is_dyn = false;
650 
651 	if (epp->ep_hdrvalid < sizeof(Elf_Ehdr))
652 		return ENOEXEC;
653 	if ((error = elf_check_header(eh)) != 0)
654 		return error;
655 
656 	if (eh->e_type == ET_DYN)
657 		/*
658 		 * XXX allow for executing shared objects. It seems silly
659 		 * but other ELF-based systems allow it as well.
660 		 */
661 		is_dyn = true;
662 	else if (eh->e_type != ET_EXEC)
663 		return ENOEXEC;
664 
665 	if (eh->e_phnum == 0)
666 		return ENOEXEC;
667 
668 	error = vn_marktext(epp->ep_vp);
669 	if (error)
670 		return error;
671 
672 	/*
673 	 * Allocate space to hold all the program headers, and read them
674 	 * from the file
675 	 */
676 	phsize = eh->e_phnum * sizeof(Elf_Phdr);
677 	ph = kmem_alloc(phsize, KM_SLEEP);
678 
679 	if ((error = exec_read_from(l, epp->ep_vp, eh->e_phoff, ph, phsize)) !=
680 	    0)
681 		goto bad;
682 
683 	epp->ep_taddr = epp->ep_tsize = ELFDEFNNAME(NO_ADDR);
684 	epp->ep_daddr = epp->ep_dsize = ELFDEFNNAME(NO_ADDR);
685 
686 	for (i = 0; i < eh->e_phnum; i++) {
687 		pp = &ph[i];
688 		if (pp->p_type == PT_INTERP) {
689 			if (pp->p_filesz < 2 || pp->p_filesz > MAXPATHLEN) {
690 				error = ENOEXEC;
691 				goto bad;
692 			}
693 			interp = PNBUF_GET();
694 			if ((error = exec_read_from(l, epp->ep_vp,
695 			    pp->p_offset, interp, pp->p_filesz)) != 0)
696 				goto bad;
697 			/* Ensure interp is NUL-terminated and of the expected length */
698 			if (strnlen(interp, pp->p_filesz) != pp->p_filesz - 1) {
699 				error = ENOEXEC;
700 				goto bad;
701 			}
702 			break;
703 		}
704 	}
705 
706 	/*
707 	 * On the same architecture, we may be emulating different systems.
708 	 * See which one will accept this executable.
709 	 *
710 	 * Probe functions would normally see if the interpreter (if any)
711 	 * exists. Emulation packages may possibly replace the interpreter in
712 	 * interp[] with a changed path (/emul/xxx/<path>).
713 	 */
714 	pos = ELFDEFNNAME(NO_ADDR);
715 	if (epp->ep_esch->u.elf_probe_func) {
716 		vaddr_t startp = (vaddr_t)pos;
717 
718 		error = (*epp->ep_esch->u.elf_probe_func)(l, epp, eh, interp,
719 							  &startp);
720 		if (error)
721 			goto bad;
722 		pos = (Elf_Addr)startp;
723 	}
724 
725 #if defined(PAX_MPROTECT) || defined(PAX_SEGVGUARD) || defined(PAX_ASLR)
726 	l->l_proc->p_pax = epp->ep_pax_flags;
727 #endif /* PAX_MPROTECT || PAX_SEGVGUARD || PAX_ASLR */
728 
729 	if (is_dyn)
730 		elf_placedynexec(l, epp, eh, ph);
731 
732 	/*
733 	 * Load all the necessary sections
734 	 */
735 	for (i = 0; i < eh->e_phnum; i++) {
736 		Elf_Addr addr = ELFDEFNNAME(NO_ADDR);
737 		u_long size = 0;
738 
739 		switch (ph[i].p_type) {
740 		case PT_LOAD:
741 			elf_load_psection(&epp->ep_vmcmds, epp->ep_vp,
742 			    &ph[i], &addr, &size, VMCMD_FIXED);
743 
744 			/*
745 			 * Consider this as text segment, if it is executable.
746 			 * If there is more than one text segment, pick the
747 			 * largest.
748 			 */
749 			if (ph[i].p_flags & PF_X) {
750 				if (epp->ep_taddr == ELFDEFNNAME(NO_ADDR) ||
751 				    size > epp->ep_tsize) {
752 					epp->ep_taddr = addr;
753 					epp->ep_tsize = size;
754 				}
755 				end_text = addr + size;
756 			} else {
757 				epp->ep_daddr = addr;
758 				epp->ep_dsize = size;
759 			}
760 			if (ph[i].p_offset == 0) {
761 				computed_phdr = ph[i].p_vaddr + eh->e_phoff;
762 			}
763 			break;
764 
765 		case PT_SHLIB:
766 			/* SCO has these sections. */
767 		case PT_INTERP:
768 			/* Already did this one. */
769 		case PT_DYNAMIC:
770 		case PT_NOTE:
771 			break;
772 		case PT_PHDR:
773 			/* Note address of program headers (in text segment) */
774 			phdr = ph[i].p_vaddr;
775 			break;
776 
777 		default:
778 			/*
779 			 * Not fatal; we don't need to understand everything.
780 			 */
781 			break;
782 		}
783 	}
784 
785 	if (epp->ep_vmcmds.evs_used == 0) {
786 		/* No VMCMD; there was no PT_LOAD section, or those
787 		 * sections were empty */
788 		error = ENOEXEC;
789 		goto bad;
790 	}
791 
792 	if (epp->ep_daddr == ELFDEFNNAME(NO_ADDR)) {
793 		epp->ep_daddr = round_page(end_text);
794 		epp->ep_dsize = 0;
795 	}
796 
797 	/*
798 	 * Check if we found a dynamically linked binary and arrange to load
799 	 * its interpreter
800 	 */
801 	if (interp) {
802 		u_int nused = epp->ep_vmcmds.evs_used;
803 		u_long interp_offset = 0;
804 
805 		if ((error = elf_load_interp(l, epp, interp,
806 		    &epp->ep_vmcmds, &interp_offset, &pos)) != 0) {
807 			goto bad;
808 		}
809 		if (epp->ep_vmcmds.evs_used == nused) {
810 			/* elf_load_interp() has not set up any new VMCMD */
811 			error = ENOEXEC;
812 			goto bad;
813 		}
814 
815 		ap = kmem_alloc(sizeof(*ap), KM_SLEEP);
816 		ap->arg_interp = epp->ep_vmcmds.evs_cmds[nused].ev_addr;
817 		epp->ep_entryoffset = interp_offset;
818 		epp->ep_entry = ap->arg_interp + interp_offset;
819 		PNBUF_PUT(interp);
820 	} else {
821 		epp->ep_entry = eh->e_entry;
822 		if (epp->ep_flags & EXEC_FORCEAUX) {
823 			ap = kmem_alloc(sizeof(*ap), KM_SLEEP);
824 			ap->arg_interp = (vaddr_t)NULL;
825 		} else
826 			ap = NULL;
827 	}
828 
829 	if (ap) {
830 		ap->arg_phaddr = phdr ? phdr : computed_phdr;
831 		ap->arg_phentsize = eh->e_phentsize;
832 		ap->arg_phnum = eh->e_phnum;
833 		ap->arg_entry = eh->e_entry;
834 		epp->ep_emul_arg = ap;
835 		epp->ep_emul_arg_free = elf_free_emul_arg;
836 	}
837 
838 #ifdef ELF_MAP_PAGE_ZERO
839 	/* Dell SVR4 maps page zero, yeuch! */
840 	NEW_VMCMD(&epp->ep_vmcmds, vmcmd_map_readvn, PAGE_SIZE, 0,
841 	    epp->ep_vp, 0, VM_PROT_READ);
842 #endif
843 	kmem_free(ph, phsize);
844 	return (*epp->ep_esch->es_setup_stack)(l, epp);
845 
846 bad:
847 	if (interp)
848 		PNBUF_PUT(interp);
849 	exec_free_emul_arg(epp);
850 	kmem_free(ph, phsize);
851 	kill_vmcmds(&epp->ep_vmcmds);
852 	return error;
853 }
854 
855 int
856 netbsd_elf_signature(struct lwp *l, struct exec_package *epp,
857     Elf_Ehdr *eh)
858 {
859 	size_t i;
860 	Elf_Shdr *sh;
861 	Elf_Nhdr *np;
862 	size_t shsize, nsize;
863 	int error;
864 	int isnetbsd = 0;
865 	char *ndata, *ndesc;
866 
867 #ifdef DIAGNOSTIC
868 	const char *badnote;
869 #define BADNOTE(n) badnote = (n)
870 #else
871 #define BADNOTE(n)
872 #endif
873 
874 	epp->ep_pax_flags = 0;
875 	if (eh->e_shnum > ELF_MAXSHNUM || eh->e_shnum == 0)
876 		return ENOEXEC;
877 
878 	shsize = eh->e_shnum * sizeof(Elf_Shdr);
879 	sh = kmem_alloc(shsize, KM_SLEEP);
880 	error = exec_read_from(l, epp->ep_vp, eh->e_shoff, sh, shsize);
881 	if (error)
882 		goto out;
883 
884 	np = kmem_alloc(ELF_MAXNOTESIZE, KM_SLEEP);
885 	for (i = 0; i < eh->e_shnum; i++) {
886 		Elf_Shdr *shp = &sh[i];
887 
888 		if (shp->sh_type != SHT_NOTE ||
889 		    shp->sh_size > ELF_MAXNOTESIZE ||
890 		    shp->sh_size < sizeof(Elf_Nhdr) + ELF_NOTE_NETBSD_NAMESZ)
891 			continue;
892 
893 		error = exec_read_from(l, epp->ep_vp, shp->sh_offset, np,
894 		    shp->sh_size);
895 		if (error)
896 			continue;
897 
898 		/* Point to the note, skip the header */
899 		ndata = (char *)(np + 1);
900 
901 		/*
902 		 * Padding is present if necessary to ensure 4-byte alignment.
903 		 * The actual section size is therefore:
904 		 *    header size + 4-byte aligned name + 4-byte aligned desc
905 		 * Ensure this size is consistent with what is indicated
906 		 * in sh_size. The first check avoids integer overflows.
907 		 *
908 		 * Binaries from before NetBSD 1.6 have two notes in the same
909 		 * note section.  The second note was never used, so as long as
910 		 * the section is at least as big as it should be, it's ok.
911 		 * These binaries also have a second note section with a note of
912 		 * type ELF_NOTE_TYPE_NETBSD_TAG, which can be ignored as well.
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, ELF_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