xref: /openbsd-src/sys/kern/exec_elf.c (revision 242b8fde7751fdd8f82a116bcc742baadaf520f0)
1 /*	$OpenBSD: exec_elf.c,v 1.187 2024/07/14 11:14:29 jca Exp $	*/
2 
3 /*
4  * Copyright (c) 1996 Per Fogelstrom
5  * All rights reserved.
6  *
7  * Copyright (c) 1994 Christos Zoulas
8  * All rights reserved.
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  * 3. The name of the author may not be used to endorse or promote products
19  *    derived from this software without specific prior written permission
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
22  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
23  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
24  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
26  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
30  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  *
32  */
33 
34 /*
35  * Copyright (c) 2001 Wasabi Systems, Inc.
36  * All rights reserved.
37  *
38  * Written by Jason R. Thorpe for Wasabi Systems, Inc.
39  *
40  * Redistribution and use in source and binary forms, with or without
41  * modification, are permitted provided that the following conditions
42  * are met:
43  * 1. Redistributions of source code must retain the above copyright
44  *    notice, this list of conditions and the following disclaimer.
45  * 2. Redistributions in binary form must reproduce the above copyright
46  *    notice, this list of conditions and the following disclaimer in the
47  *    documentation and/or other materials provided with the distribution.
48  * 3. All advertising materials mentioning features or use of this software
49  *    must display the following acknowledgement:
50  *	This product includes software developed for the NetBSD Project by
51  *	Wasabi Systems, Inc.
52  * 4. The name of Wasabi Systems, Inc. may not be used to endorse
53  *    or promote products derived from this software without specific prior
54  *    written permission.
55  *
56  * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``AS IS'' AND
57  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
58  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
59  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL WASABI SYSTEMS, INC
60  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
61  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
62  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
63  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
64  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
65  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
66  * POSSIBILITY OF SUCH DAMAGE.
67  */
68 
69 #include <sys/param.h>
70 #include <sys/systm.h>
71 #include <sys/proc.h>
72 #include <sys/malloc.h>
73 #include <sys/pool.h>
74 #include <sys/mount.h>
75 #include <sys/namei.h>
76 #include <sys/vnode.h>
77 #include <sys/core.h>
78 #include <sys/exec.h>
79 #include <sys/exec_elf.h>
80 #include <sys/fcntl.h>
81 #include <sys/ptrace.h>
82 #include <sys/signalvar.h>
83 #include <sys/pledge.h>
84 #include <sys/syscall.h>
85 
86 #include <sys/mman.h>
87 
88 #include <uvm/uvm_extern.h>
89 
90 #include <machine/reg.h>
91 #include <machine/exec.h>
92 #include <machine/elf.h>
93 
94 int	elf_load_file(struct proc *, char *, struct exec_package *,
95 	    struct elf_args *);
96 int	elf_check_header(Elf_Ehdr *);
97 int	elf_read_from(struct proc *, struct vnode *, u_long, void *, int);
98 void	elf_load_psection(struct exec_vmcmd_set *, struct vnode *,
99 	    Elf_Phdr *, Elf_Addr *, Elf_Addr *, int *, int);
100 int	elf_os_pt_note_name(Elf_Note *);
101 int	elf_os_pt_note(struct proc *, struct exec_package *, Elf_Ehdr *, int *);
102 int	elf_read_pintable(struct proc *p, struct vnode *vp, Elf_Phdr *pp,
103 	    u_int **pinp, int is_ldso, size_t len);
104 
105 /* round up and down to page boundaries. */
106 #define ELF_ROUND(a, b)		(((a) + (b) - 1) & ~((b) - 1))
107 #define ELF_TRUNC(a, b)		((a) & ~((b) - 1))
108 
109 /*
110  * We limit the number of program headers to 32, this should
111  * be a reasonable limit for ELF, the most we have seen so far is 12
112  */
113 #define ELF_MAX_VALID_PHDR 32
114 
115 #define ELF_NOTE_NAME_OPENBSD	0x01
116 
117 struct elf_note_name {
118 	char *name;
119 	int id;
120 } elf_note_names[] = {
121 	{ "OpenBSD",	ELF_NOTE_NAME_OPENBSD },
122 };
123 
124 #define	ELFROUNDSIZE	sizeof(Elf_Word)
125 #define	elfround(x)	roundup((x), ELFROUNDSIZE)
126 
127 
128 /*
129  * Check header for validity; return 0 for ok, ENOEXEC if error
130  */
131 int
132 elf_check_header(Elf_Ehdr *ehdr)
133 {
134 	/*
135 	 * We need to check magic, class size, endianness, and version before
136 	 * we look at the rest of the Elf_Ehdr structure. These few elements
137 	 * are represented in a machine independent fashion.
138 	 */
139 	if (!IS_ELF(*ehdr) ||
140 	    ehdr->e_ident[EI_CLASS] != ELF_TARG_CLASS ||
141 	    ehdr->e_ident[EI_DATA] != ELF_TARG_DATA ||
142 	    ehdr->e_ident[EI_VERSION] != ELF_TARG_VER)
143 		return (ENOEXEC);
144 
145 	/* Now check the machine dependent header */
146 	if (ehdr->e_machine != ELF_TARG_MACH ||
147 	    ehdr->e_version != ELF_TARG_VER)
148 		return (ENOEXEC);
149 
150 	/* Don't allow an insane amount of sections. */
151 	if (ehdr->e_phnum > ELF_MAX_VALID_PHDR)
152 		return (ENOEXEC);
153 
154 	return (0);
155 }
156 
157 /*
158  * Load a psection at the appropriate address
159  */
160 void
161 elf_load_psection(struct exec_vmcmd_set *vcset, struct vnode *vp,
162     Elf_Phdr *ph, Elf_Addr *addr, Elf_Addr *size, int *prot, int flags)
163 {
164 	u_long msize, lsize, psize, rm, rf;
165 	long diff, offset, bdiff;
166 	Elf_Addr base;
167 
168 	/*
169 	 * If the user specified an address, then we load there.
170 	 */
171 	if (*addr != ELF_NO_ADDR) {
172 		if (ph->p_align > 1) {
173 			*addr = ELF_TRUNC(*addr, ph->p_align);
174 			diff = ph->p_vaddr - ELF_TRUNC(ph->p_vaddr, ph->p_align);
175 			/* page align vaddr */
176 			base = *addr + trunc_page(ph->p_vaddr)
177 			    - ELF_TRUNC(ph->p_vaddr, ph->p_align);
178 		} else {
179 			diff = 0;
180 			base = *addr + trunc_page(ph->p_vaddr) - ph->p_vaddr;
181 		}
182 	} else {
183 		*addr = ph->p_vaddr;
184 		if (ph->p_align > 1)
185 			*addr = ELF_TRUNC(*addr, ph->p_align);
186 		base = trunc_page(ph->p_vaddr);
187 		diff = ph->p_vaddr - *addr;
188 	}
189 	bdiff = ph->p_vaddr - trunc_page(ph->p_vaddr);
190 
191 	/*
192 	 * Enforce W^X and map W|X segments without X permission
193 	 * initially.  The dynamic linker will make these read-only
194 	 * and add back X permission after relocation processing.
195 	 * Static executables with W|X segments will probably crash.
196 	 */
197 	*prot |= (ph->p_flags & PF_R) ? PROT_READ : 0;
198 	*prot |= (ph->p_flags & PF_W) ? PROT_WRITE : 0;
199 	if ((ph->p_flags & PF_W) == 0)
200 		*prot |= (ph->p_flags & PF_X) ? PROT_EXEC : 0;
201 
202 	/*
203 	 * Apply immutability as much as possible, but not text/rodata
204 	 * segments of textrel binaries, or RELRO or PT_OPENBSD_MUTABLE
205 	 * sections, or LOADS marked PF_OPENBSD_MUTABLE, or LOADS which
206 	 * violate W^X.
207 	 * Userland (meaning crt0 or ld.so) will repair those regions.
208 	 */
209 	if ((ph->p_flags & (PF_X | PF_W)) != (PF_X | PF_W) &&
210 	    ((ph->p_flags & PF_OPENBSD_MUTABLE) == 0))
211 		flags |= VMCMD_IMMUTABLE;
212 	if ((flags & VMCMD_TEXTREL) && (ph->p_flags & PF_W) == 0)
213 		flags &= ~VMCMD_IMMUTABLE;
214 
215 	msize = ph->p_memsz + diff;
216 	offset = ph->p_offset - bdiff;
217 	lsize = ph->p_filesz + bdiff;
218 	psize = round_page(lsize);
219 
220 	/*
221 	 * Because the pagedvn pager can't handle zero fill of the last
222 	 * data page if it's not page aligned we map the last page readvn.
223 	 */
224 	if (ph->p_flags & PF_W) {
225 		psize = trunc_page(lsize);
226 		if (psize > 0)
227 			NEW_VMCMD2(vcset, vmcmd_map_pagedvn, psize, base, vp,
228 			    offset, *prot, flags);
229 		if (psize != lsize) {
230 			NEW_VMCMD2(vcset, vmcmd_map_readvn, lsize - psize,
231 			    base + psize, vp, offset + psize, *prot, flags);
232 		}
233 	} else {
234 		NEW_VMCMD2(vcset, vmcmd_map_pagedvn, psize, base, vp, offset,
235 		    *prot, flags);
236 	}
237 
238 	/*
239 	 * Check if we need to extend the size of the segment
240 	 */
241 	rm = round_page(*addr + ph->p_memsz + diff);
242 	rf = round_page(*addr + ph->p_filesz + diff);
243 
244 	if (rm != rf) {
245 		NEW_VMCMD2(vcset, vmcmd_map_zero, rm - rf, rf, NULLVP, 0,
246 		    *prot, flags);
247 	}
248 	*size = msize;
249 }
250 
251 /*
252  * Read from vnode into buffer at offset.
253  */
254 int
255 elf_read_from(struct proc *p, struct vnode *vp, u_long off, void *buf,
256     int size)
257 {
258 	int error;
259 	size_t resid;
260 
261 	if ((error = vn_rdwr(UIO_READ, vp, buf, size, off, UIO_SYSSPACE,
262 	    0, p->p_ucred, &resid, p)) != 0)
263 		return error;
264 	/*
265 	 * See if we got all of it
266 	 */
267 	if (resid != 0)
268 		return (ENOEXEC);
269 	return (0);
270 }
271 
272 /*
273  * rebase the pin offsets inside a base,len window for the text segment only.
274  */
275 void
276 elf_adjustpins(vaddr_t *basep, size_t *lenp, u_int *pins, int npins, u_int offset)
277 {
278 	int i;
279 
280 	/* Adjust offsets, base, len */
281 	for (i = 0; i < npins; i++) {
282 		if (pins[i] == -1 || pins[i] == 0)
283 			continue;
284 		pins[i] -= offset;
285 	}
286 	*basep += offset;
287 	*lenp -= offset;
288 }
289 
290 int
291 elf_read_pintable(struct proc *p, struct vnode *vp, Elf_Phdr *pp,
292     u_int **pinp, int is_ldso, size_t len)
293 {
294 	struct pinsyscalls {
295 		u_int offset;
296 		u_int sysno;
297 	} *syscalls = NULL;
298 	int i, nsyscalls = 0, npins = 0;
299 	u_int *pins = NULL;
300 
301 	if (pp->p_filesz > SYS_MAXSYSCALL * 2 * sizeof(*syscalls) ||
302 	    pp->p_filesz % sizeof(*syscalls) != 0)
303 		goto bad;
304 	nsyscalls = pp->p_filesz / sizeof(*syscalls);
305 	syscalls = malloc(pp->p_filesz, M_PINSYSCALL, M_WAITOK);
306 	if (elf_read_from(p, vp, pp->p_offset, syscalls,
307 	    pp->p_filesz) != 0)
308 		goto bad;
309 
310 	/* Validate, and calculate pintable size */
311 	for (i = 0; i < nsyscalls; i++) {
312 		if (syscalls[i].sysno <= 0 ||
313 		    syscalls[i].sysno >= SYS_MAXSYSCALL ||
314 		    syscalls[i].offset > len)
315 			goto bad;
316 		npins = MAX(npins, syscalls[i].sysno);
317 	}
318 	if (is_ldso)
319 		npins = MAX(npins, SYS_kbind);	/* XXX see ld.so/loader.c */
320 	npins++;
321 
322 	/* Fill pintable: 0 = invalid, -1 = allowed, else offset from base */
323 	pins = mallocarray(npins, sizeof(u_int), M_PINSYSCALL, M_WAITOK|M_ZERO);
324 	for (i = 0; i < nsyscalls; i++) {
325 		if (pins[syscalls[i].sysno])
326 			pins[syscalls[i].sysno] = -1;	/* duplicated */
327 		else
328 			pins[syscalls[i].sysno] = syscalls[i].offset;
329 	}
330 	if (is_ldso)
331 		pins[SYS_kbind] = -1;	/* XXX see ld.so/loader.c */
332 	*pinp = pins;
333 	pins = NULL;
334 bad:
335 	free(syscalls, M_PINSYSCALL, nsyscalls * sizeof(*syscalls));
336 	free(pins, M_PINSYSCALL, npins * sizeof(u_int));
337 	return npins;
338 }
339 
340 /*
341  * Load a file (interpreter/library) pointed to by path [stolen from
342  * coff_load_shlib()]. Made slightly generic so it might be used externally.
343  */
344 int
345 elf_load_file(struct proc *p, char *path, struct exec_package *epp,
346     struct elf_args *ap)
347 {
348 	int error, i;
349 	struct nameidata nd;
350 	Elf_Ehdr eh;
351 	Elf_Phdr *ph = NULL, *syscall_ph = NULL;
352 	u_long phsize = 0;
353 	Elf_Addr addr;
354 	struct vnode *vp;
355 	Elf_Phdr *base_ph = NULL;
356 	struct interp_ld_sec {
357 		Elf_Addr vaddr;
358 		u_long memsz;
359 	} loadmap[ELF_MAX_VALID_PHDR];
360 	int nload, idx = 0;
361 	Elf_Addr pos;
362 	int file_align;
363 	int loop;
364 	size_t randomizequota = ELF_RANDOMIZE_LIMIT;
365 	vaddr_t text_start = -1, text_end = 0;
366 
367 	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE, path, p);
368 	nd.ni_pledge = PLEDGE_RPATH;
369 	nd.ni_unveil = UNVEIL_READ;
370 	if ((error = namei(&nd)) != 0) {
371 		return (error);
372 	}
373 	vp = nd.ni_vp;
374 	if (vp->v_type != VREG) {
375 		error = EACCES;
376 		goto bad;
377 	}
378 	if ((error = VOP_GETATTR(vp, epp->ep_vap, p->p_ucred, p)) != 0)
379 		goto bad;
380 	if (vp->v_mount->mnt_flag & MNT_NOEXEC) {
381 		error = EACCES;
382 		goto bad;
383 	}
384 	if ((error = VOP_ACCESS(vp, VREAD, p->p_ucred, p)) != 0)
385 		goto bad1;
386 	if ((error = elf_read_from(p, nd.ni_vp, 0, &eh, sizeof(eh))) != 0)
387 		goto bad1;
388 
389 	if (elf_check_header(&eh) || eh.e_type != ET_DYN) {
390 		error = ENOEXEC;
391 		goto bad1;
392 	}
393 
394 	ph = mallocarray(eh.e_phnum, sizeof(Elf_Phdr), M_TEMP, M_WAITOK);
395 	phsize = eh.e_phnum * sizeof(Elf_Phdr);
396 
397 	if ((error = elf_read_from(p, nd.ni_vp, eh.e_phoff, ph, phsize)) != 0)
398 		goto bad1;
399 
400 	for (i = 0; i < eh.e_phnum; i++) {
401 		if ((ph[i].p_align > 1) && !powerof2(ph[i].p_align)) {
402 			error = EINVAL;
403 			goto bad1;
404 		}
405 
406 		if (ph[i].p_type == PT_LOAD) {
407 			if (ph[i].p_filesz > ph[i].p_memsz ||
408 			    ph[i].p_memsz == 0) {
409 				error = EINVAL;
410 				goto bad1;
411 			}
412 			loadmap[idx].vaddr = trunc_page(ph[i].p_vaddr);
413 			loadmap[idx].memsz = round_page (ph[i].p_vaddr +
414 			    ph[i].p_memsz - loadmap[idx].vaddr);
415 			file_align = ph[i].p_align;
416 			idx++;
417 		}
418 	}
419 	nload = idx;
420 
421 	/*
422 	 * Load the interpreter where a non-fixed mmap(NULL, ...)
423 	 * would (i.e. something safely out of the way).
424 	 */
425 	pos = uvm_map_hint(p->p_vmspace, PROT_EXEC, VM_MIN_ADDRESS,
426 	    VM_MAXUSER_ADDRESS);
427 	pos = ELF_ROUND(pos, file_align);
428 
429 	loop = 0;
430 	for (i = 0; i < nload;/**/) {
431 		vaddr_t	addr;
432 		struct	uvm_object *uobj;
433 		off_t	uoff;
434 		size_t	size;
435 
436 #ifdef this_needs_fixing
437 		if (i == 0) {
438 			uobj = &vp->v_uvm.u_obj;
439 			/* need to fix uoff */
440 		} else {
441 #endif
442 			uobj = NULL;
443 			uoff = 0;
444 #ifdef this_needs_fixing
445 		}
446 #endif
447 
448 		addr = trunc_page(pos + loadmap[i].vaddr);
449 		size =  round_page(addr + loadmap[i].memsz) - addr;
450 
451 		/* CRAP - map_findspace does not avoid daddr+BRKSIZ */
452 		if ((addr + size > (vaddr_t)p->p_vmspace->vm_daddr) &&
453 		    (addr < (vaddr_t)p->p_vmspace->vm_daddr + BRKSIZ))
454 			addr = round_page((vaddr_t)p->p_vmspace->vm_daddr +
455 			    BRKSIZ);
456 
457 		if (uvm_map_mquery(&p->p_vmspace->vm_map, &addr, size,
458 		    (i == 0 ? uoff : UVM_UNKNOWN_OFFSET), 0) != 0) {
459 			if (loop == 0) {
460 				loop = 1;
461 				i = 0;
462 				pos = 0;
463 				continue;
464 			}
465 			error = ENOMEM;
466 			goto bad1;
467 		}
468 		if (addr != pos + loadmap[i].vaddr) {
469 			/* base changed. */
470 			pos = addr - trunc_page(loadmap[i].vaddr);
471 			pos = ELF_ROUND(pos,file_align);
472 			i = 0;
473 			continue;
474 		}
475 
476 		i++;
477 	}
478 
479 	/*
480 	 * Load all the necessary sections
481 	 */
482 	for (i = 0; i < eh.e_phnum; i++) {
483 		Elf_Addr size = 0;
484 		int prot = 0;
485 		int flags;
486 
487 		switch (ph[i].p_type) {
488 		case PT_LOAD:
489 			if (base_ph == NULL) {
490 				flags = VMCMD_BASE;
491 				addr = pos;
492 				base_ph = &ph[i];
493 			} else {
494 				flags = VMCMD_RELATIVE;
495 				addr = ph[i].p_vaddr - base_ph->p_vaddr;
496 			}
497 			elf_load_psection(&epp->ep_vmcmds, nd.ni_vp,
498 			    &ph[i], &addr, &size, &prot, flags);
499 			/* If entry is within this section it must be text */
500 			if (eh.e_entry >= ph[i].p_vaddr &&
501 			    eh.e_entry < (ph[i].p_vaddr + size)) {
502 				/* LOAD containing e_entry may not be writable */
503 				if (prot & PROT_WRITE) {
504 					error = ENOEXEC;
505 					goto bad1;
506 				}
507  				epp->ep_entry = addr + eh.e_entry -
508 				    ELF_TRUNC(ph[i].p_vaddr,ph[i].p_align);
509 				if (flags == VMCMD_RELATIVE)
510 					epp->ep_entry += pos;
511 				ap->arg_interp = pos;
512 			}
513 			if (prot & PROT_EXEC) {
514 				if (addr < text_start)
515 					text_start = addr;
516 				if (addr+size >= text_end)
517 					text_end = addr + size;
518 			}
519 			addr += size;
520 			break;
521 
522 		case PT_PHDR:
523 		case PT_NOTE:
524 			break;
525 
526 		case PT_OPENBSD_RANDOMIZE:
527 			if (ph[i].p_memsz > randomizequota) {
528 				error = ENOMEM;
529 				goto bad1;
530 			}
531 			randomizequota -= ph[i].p_memsz;
532 			NEW_VMCMD(&epp->ep_vmcmds, vmcmd_randomize,
533 			    ph[i].p_memsz, ph[i].p_vaddr + pos, NULLVP, 0, 0);
534 			break;
535 
536 		case PT_DYNAMIC:
537 #if defined (__mips__)
538 			/* DT_DEBUG is not ready on mips */
539 			NEW_VMCMD(&epp->ep_vmcmds, vmcmd_mutable,
540 			    ph[i].p_memsz, ph[i].p_vaddr + pos, NULLVP, 0, 0);
541 #endif
542 			break;
543 		case PT_GNU_RELRO:
544 		case PT_OPENBSD_MUTABLE:
545 			NEW_VMCMD(&epp->ep_vmcmds, vmcmd_mutable,
546 			    ph[i].p_memsz, ph[i].p_vaddr + pos, NULLVP, 0, 0);
547 			break;
548 		case PT_OPENBSD_SYSCALLS:
549 			syscall_ph = &ph[i];
550 			break;
551 		default:
552 			break;
553 		}
554 	}
555 
556 	if (syscall_ph) {
557 		struct process *pr = p->p_p;
558 		vaddr_t base = pos;
559 		size_t len = text_end;
560 		u_int *pins;
561 		int npins;
562 
563 		npins = elf_read_pintable(p, nd.ni_vp, syscall_ph,
564 		    &pins, 1, len);
565 		if (npins) {
566 			elf_adjustpins(&base, &len, pins, npins,
567 			    text_start);
568 			pr->ps_pin.pn_start = base;
569 			pr->ps_pin.pn_end = base + len;
570 			pr->ps_pin.pn_pins = pins;
571 			pr->ps_pin.pn_npins = npins;
572 			pr->ps_flags |= PS_PIN;
573 		}
574 	}
575 
576 	vn_marktext(nd.ni_vp);
577 
578 bad1:
579 	VOP_CLOSE(nd.ni_vp, FREAD, p->p_ucred, p);
580 bad:
581 	free(ph, M_TEMP, phsize);
582 
583 	vput(nd.ni_vp);
584 	return (error);
585 }
586 
587 /*
588  * Prepare an Elf binary's exec package
589  *
590  * First, set of the various offsets/lengths in the exec package.
591  *
592  * Then, mark the text image busy (so it can be demand paged) or error out if
593  * this is not possible.  Finally, set up vmcmds for the text, data, bss, and
594  * stack segments.
595  */
596 int
597 exec_elf_makecmds(struct proc *p, struct exec_package *epp)
598 {
599 	Elf_Ehdr *eh = epp->ep_hdr;
600 	Elf_Phdr *ph, *pp, *base_ph = NULL, *syscall_ph = NULL;
601 	Elf_Addr phdr = 0, exe_base = 0, exe_end = 0;
602 	int error, i, has_phdr = 0, names = 0, textrel = 0;
603 	char *interp = NULL;
604 	u_long phsize;
605 	size_t randomizequota = ELF_RANDOMIZE_LIMIT;
606 
607 	if (epp->ep_hdrvalid < sizeof(Elf_Ehdr))
608 		return (ENOEXEC);
609 
610 	if (elf_check_header(eh) ||
611 	   (eh->e_type != ET_EXEC && eh->e_type != ET_DYN))
612 		return (ENOEXEC);
613 
614 	/*
615 	 * check if vnode is in open for writing, because we want to demand-
616 	 * page out of it.  if it is, don't do it, for various reasons.
617 	 */
618 	if (epp->ep_vp->v_writecount != 0) {
619 #ifdef DIAGNOSTIC
620 		if (epp->ep_vp->v_flag & VTEXT)
621 			panic("exec: a VTEXT vnode has writecount != 0");
622 #endif
623 		return (ETXTBSY);
624 	}
625 	/*
626 	 * Allocate space to hold all the program headers, and read them
627 	 * from the file
628 	 */
629 	ph = mallocarray(eh->e_phnum, sizeof(Elf_Phdr), M_TEMP, M_WAITOK);
630 	phsize = eh->e_phnum * sizeof(Elf_Phdr);
631 
632 	if ((error = elf_read_from(p, epp->ep_vp, eh->e_phoff, ph,
633 	    phsize)) != 0)
634 		goto bad;
635 
636 	epp->ep_tsize = ELF_NO_ADDR;
637 	epp->ep_dsize = ELF_NO_ADDR;
638 
639 	for (i = 0, pp = ph; i < eh->e_phnum; i++, pp++) {
640 		if ((pp->p_align > 1) && !powerof2(pp->p_align)) {
641 			error = EINVAL;
642 			goto bad;
643 		}
644 
645 		if (pp->p_type == PT_INTERP && !interp) {
646 			if (pp->p_filesz < 2 || pp->p_filesz > MAXPATHLEN)
647 				goto bad;
648 			interp = pool_get(&namei_pool, PR_WAITOK);
649 			if ((error = elf_read_from(p, epp->ep_vp,
650 			    pp->p_offset, interp, pp->p_filesz)) != 0) {
651 				goto bad;
652 			}
653 			if (interp[pp->p_filesz - 1] != '\0')
654 				goto bad;
655 		} else if (pp->p_type == PT_LOAD) {
656 			if (pp->p_filesz > pp->p_memsz ||
657 			    pp->p_memsz == 0) {
658 				error = EINVAL;
659 				goto bad;
660 			}
661 			if (base_ph == NULL)
662 				base_ph = pp;
663 		} else if (pp->p_type == PT_PHDR) {
664 			has_phdr = 1;
665 		}
666 	}
667 
668 	/*
669 	 * Verify this is an OpenBSD executable.  If it's marked that way
670 	 * via a PT_NOTE then also check for a PT_OPENBSD_WXNEEDED segment.
671 	 */
672 	if ((error = elf_os_pt_note(p, epp, epp->ep_hdr, &names)) != 0)
673 		goto bad;
674 	if (eh->e_ident[EI_OSABI] == ELFOSABI_OPENBSD)
675 		names |= ELF_NOTE_NAME_OPENBSD;
676 
677 	if (eh->e_type == ET_DYN) {
678 		/* need phdr and load sections for PIE */
679 		if (!has_phdr || base_ph == NULL || base_ph->p_vaddr != 0) {
680 			error = EINVAL;
681 			goto bad;
682 		}
683 		/* randomize exe_base for PIE */
684 		exe_base = uvm_map_pie(base_ph->p_align);
685 
686 		/*
687 		 * Check if DYNAMIC contains DT_TEXTREL
688 		 */
689 		for (i = 0, pp = ph; i < eh->e_phnum; i++, pp++) {
690 			Elf_Dyn *dt;
691 			int j;
692 
693 			switch (pp->p_type) {
694 			case PT_DYNAMIC:
695 				if (pp->p_filesz > 64*1024)
696 					break;
697 				dt = malloc(pp->p_filesz, M_TEMP, M_WAITOK);
698 				error = vn_rdwr(UIO_READ, epp->ep_vp,
699 				    (caddr_t)dt, pp->p_filesz, pp->p_offset,
700 				    UIO_SYSSPACE, IO_UNIT, p->p_ucred, NULL, p);
701 				if (error) {
702 					free(dt, M_TEMP, pp->p_filesz);
703 					break;
704 				}
705 				for (j = 0; j < pp->p_filesz / sizeof(*dt); j++) {
706 					if (dt[j].d_tag == DT_TEXTREL) {
707 						textrel = VMCMD_TEXTREL;
708 						break;
709 					}
710 				}
711 				free(dt, M_TEMP, pp->p_filesz);
712 				break;
713 			default:
714 				break;
715 			}
716 		}
717 	}
718 
719 	/*
720 	 * Load all the necessary sections
721 	 */
722 	for (i = 0, pp = ph; i < eh->e_phnum; i++, pp++) {
723 		Elf_Addr addr, size = 0;
724 		int prot = 0;
725 		int flags = 0;
726 
727 		switch (pp->p_type) {
728 		case PT_LOAD:
729 			if (exe_base != 0) {
730 				if (pp == base_ph) {
731 					flags = VMCMD_BASE;
732 					addr = exe_base;
733 				} else {
734 					flags = VMCMD_RELATIVE;
735 					addr = pp->p_vaddr - base_ph->p_vaddr;
736 				}
737 			} else
738 				addr = ELF_NO_ADDR;
739 
740 			/* Static binaries may not call pinsyscalls() */
741 			if (interp == NULL)
742 				p->p_vmspace->vm_map.flags |= VM_MAP_PINSYSCALL_ONCE;
743 
744 			/*
745 			 * Calculates size of text and data segments
746 			 * by starting at first and going to end of last.
747 			 * 'rwx' sections are treated as data.
748 			 * this is correct for BSS_PLT, but may not be
749 			 * for DATA_PLT, is fine for TEXT_PLT.
750 			 */
751 			elf_load_psection(&epp->ep_vmcmds, epp->ep_vp,
752 			    pp, &addr, &size, &prot, flags | textrel);
753 
754 			/*
755 			 * Update exe_base in case alignment was off.
756 			 * For PIE, addr is relative to exe_base so
757 			 * adjust it (non PIE exe_base is 0 so no change).
758 			 */
759 			if (flags == VMCMD_BASE)
760 				exe_base = addr;
761 			else
762 				addr += exe_base;
763 
764 			/*
765 			 * Decide whether it's text or data by looking
766 			 * at the protection of the section
767 			 */
768 			if (prot & PROT_WRITE) {
769 				/* data section */
770 				if (epp->ep_dsize == ELF_NO_ADDR) {
771 					epp->ep_daddr = addr;
772 					epp->ep_dsize = size;
773 				} else {
774 					if (addr < epp->ep_daddr) {
775 						epp->ep_dsize =
776 						    epp->ep_dsize +
777 						    epp->ep_daddr -
778 						    addr;
779 						epp->ep_daddr = addr;
780 					} else
781 						epp->ep_dsize = addr+size -
782 						    epp->ep_daddr;
783 				}
784 			} else if (prot & PROT_EXEC) {
785 				/* text section */
786 				if (epp->ep_tsize == ELF_NO_ADDR) {
787 					epp->ep_taddr = addr;
788 					epp->ep_tsize = size;
789 				} else {
790 					if (addr < epp->ep_taddr) {
791 						epp->ep_tsize =
792 						    epp->ep_tsize +
793 						    epp->ep_taddr -
794 						    addr;
795 						epp->ep_taddr = addr;
796 					} else
797 						epp->ep_tsize = addr+size -
798 						    epp->ep_taddr;
799 				}
800 				if (interp == NULL)
801 					exe_end = epp->ep_taddr +
802 					    epp->ep_tsize;	/* end of TEXT */
803 			}
804 			break;
805 
806 		case PT_SHLIB:
807 			error = ENOEXEC;
808 			goto bad;
809 
810 		case PT_INTERP:
811 			/* Already did this one */
812 		case PT_NOTE:
813 			break;
814 
815 		case PT_PHDR:
816 			/* Note address of program headers (in text segment) */
817 			phdr = pp->p_vaddr;
818 			break;
819 
820 		case PT_OPENBSD_RANDOMIZE:
821 			if (ph[i].p_memsz > randomizequota) {
822 				error = ENOMEM;
823 				goto bad;
824 			}
825 			randomizequota -= ph[i].p_memsz;
826 			NEW_VMCMD(&epp->ep_vmcmds, vmcmd_randomize,
827 			    ph[i].p_memsz, ph[i].p_vaddr + exe_base, NULLVP, 0, 0);
828 			break;
829 
830 		case PT_DYNAMIC:
831 #if defined (__mips__)
832 			/* DT_DEBUG is not ready on mips */
833 			NEW_VMCMD(&epp->ep_vmcmds, vmcmd_mutable,
834 			    ph[i].p_memsz, ph[i].p_vaddr + exe_base, NULLVP, 0, 0);
835 #endif
836 			break;
837 		case PT_GNU_RELRO:
838 		case PT_OPENBSD_MUTABLE:
839 			NEW_VMCMD(&epp->ep_vmcmds, vmcmd_mutable,
840 			    ph[i].p_memsz, ph[i].p_vaddr + exe_base, NULLVP, 0, 0);
841 			break;
842 		case PT_OPENBSD_SYSCALLS:
843 			if (interp == NULL)
844 				syscall_ph = &ph[i];
845 			break;
846 		default:
847 			/*
848 			 * Not fatal, we don't need to understand everything
849 			 * :-)
850 			 */
851 			break;
852 		}
853 	}
854 
855 	if (syscall_ph) {
856 		vaddr_t base = exe_base;
857 		size_t len = exe_end - exe_base;
858 		u_int *pins;
859 		int npins;
860 
861 		npins = elf_read_pintable(p, epp->ep_vp, syscall_ph,
862 		    &pins, 0, len);
863 		if (npins) {
864 			elf_adjustpins(&base, &len, pins, npins,
865 			    epp->ep_taddr - exe_base);
866 			epp->ep_pinstart = base;
867 			epp->ep_pinend = base + len;
868 			epp->ep_pins = pins;
869 			epp->ep_npins = npins;
870 			p->p_p->ps_flags |= PS_PIN;
871 		}
872 	}
873 
874 	phdr += exe_base;
875 
876 	/*
877 	 * Strangely some linux programs may have all load sections marked
878 	 * writeable, in this case, textsize is not -1, but rather 0;
879 	 */
880 	if (epp->ep_tsize == ELF_NO_ADDR)
881 		epp->ep_tsize = 0;
882 	/*
883 	 * Another possibility is that it has all load sections marked
884 	 * read-only.  Fake a zero-sized data segment right after the
885 	 * text segment.
886 	 */
887 	if (epp->ep_dsize == ELF_NO_ADDR) {
888 		epp->ep_daddr = round_page(epp->ep_taddr + epp->ep_tsize);
889 		epp->ep_dsize = 0;
890 	}
891 
892 	epp->ep_interp = interp;
893 	epp->ep_entry = eh->e_entry + exe_base;
894 
895 	/*
896 	 * Check if we found a dynamically linked binary and arrange to load
897 	 * its interpreter when the exec file is released.
898 	 */
899 	if (interp || eh->e_type == ET_DYN) {
900 		struct elf_args *ap;
901 
902 		ap = malloc(sizeof(*ap), M_TEMP, M_WAITOK);
903 
904 		ap->arg_phaddr = phdr;
905 		ap->arg_phentsize = eh->e_phentsize;
906 		ap->arg_phnum = eh->e_phnum;
907 		ap->arg_entry = eh->e_entry + exe_base;
908 		ap->arg_interp = exe_base;
909 
910 		epp->ep_args = ap;
911 	}
912 
913 	free(ph, M_TEMP, phsize);
914 	vn_marktext(epp->ep_vp);
915 	return (exec_setup_stack(p, epp));
916 
917 bad:
918 	if (interp)
919 		pool_put(&namei_pool, interp);
920 	free(ph, M_TEMP, phsize);
921 	kill_vmcmds(&epp->ep_vmcmds);
922 	if (error == 0)
923 		return (ENOEXEC);
924 	return (error);
925 }
926 
927 /*
928  * Phase II of load. It is now safe to load the interpreter. Info collected
929  * when loading the program is available for setup of the interpreter.
930  */
931 int
932 exec_elf_fixup(struct proc *p, struct exec_package *epp)
933 {
934 	char	*interp;
935 	int	error = 0;
936 	struct	elf_args *ap;
937 	AuxInfo ai[ELF_AUX_ENTRIES], *a;
938 
939 	ap = epp->ep_args;
940 	if (ap == NULL) {
941 		return (0);
942 	}
943 
944 	interp = epp->ep_interp;
945 
946 	/* disable kbind in programs that don't use ld.so */
947 	if (interp == NULL)
948 		p->p_p->ps_kbind_addr = BOGO_PC;
949 
950 	if (interp &&
951 	    (error = elf_load_file(p, interp, epp, ap)) != 0) {
952 		uprintf("execve: cannot load %s\n", interp);
953 		free(ap, M_TEMP, sizeof *ap);
954 		pool_put(&namei_pool, interp);
955 		kill_vmcmds(&epp->ep_vmcmds);
956 		return (error);
957 	}
958 	/*
959 	 * We have to do this ourselves...
960 	 */
961 	error = exec_process_vmcmds(p, epp);
962 
963 	/*
964 	 * Push extra arguments on the stack needed by dynamically
965 	 * linked binaries
966 	 */
967 	if (error == 0) {
968 		memset(&ai, 0, sizeof ai);
969 		a = ai;
970 
971 		a->au_id = AUX_phdr;
972 		a->au_v = ap->arg_phaddr;
973 		a++;
974 
975 		a->au_id = AUX_phent;
976 		a->au_v = ap->arg_phentsize;
977 		a++;
978 
979 		a->au_id = AUX_phnum;
980 		a->au_v = ap->arg_phnum;
981 		a++;
982 
983 		a->au_id = AUX_pagesz;
984 		a->au_v = PAGE_SIZE;
985 		a++;
986 
987 		a->au_id = AUX_base;
988 		a->au_v = ap->arg_interp;
989 		a++;
990 
991 		a->au_id = AUX_flags;
992 		a->au_v = 0;
993 		a++;
994 
995 		a->au_id = AUX_entry;
996 		a->au_v = ap->arg_entry;
997 		a++;
998 
999 #ifdef __HAVE_CPU_HWCAP
1000 		a->au_id = AUX_hwcap;
1001 		a->au_v = hwcap;
1002 		a++;
1003 #endif /* __HAVE_CPU_HWCAP */
1004 
1005 #ifdef __HAVE_CPU_HWCAP2
1006 		a->au_id = AUX_hwcap2;
1007 		a->au_v = hwcap2;
1008 		a++;
1009 #endif /* __HAVE_CPU_HWCAP2 */
1010 
1011 		a->au_id = AUX_openbsd_timekeep;
1012 		a->au_v = p->p_p->ps_timekeep;
1013 		a++;
1014 
1015 		a->au_id = AUX_null;
1016 		a->au_v = 0;
1017 		a++;
1018 
1019 		error = copyout(ai, epp->ep_auxinfo, sizeof ai);
1020 	}
1021 	free(ap, M_TEMP, sizeof *ap);
1022 	if (interp)
1023 		pool_put(&namei_pool, interp);
1024 	return (error);
1025 }
1026 
1027 int
1028 elf_os_pt_note_name(Elf_Note *np)
1029 {
1030 	int i, j;
1031 
1032 	for (i = 0; i < nitems(elf_note_names); i++) {
1033 		size_t namlen = strlen(elf_note_names[i].name);
1034 		if (np->namesz < namlen)
1035 			continue;
1036 		/* verify name padding (after the NUL) is NUL */
1037 		for (j = namlen + 1; j < elfround(np->namesz); j++)
1038 			if (((char *)(np + 1))[j] != '\0')
1039 				continue;
1040 		/* verify desc padding is NUL */
1041 		for (j = np->descsz; j < elfround(np->descsz); j++)
1042 			if (((char *)(np + 1))[j] != '\0')
1043 				continue;
1044 		if (strcmp((char *)(np + 1), elf_note_names[i].name) == 0)
1045 			return elf_note_names[i].id;
1046 	}
1047 	return (0);
1048 }
1049 
1050 int
1051 elf_os_pt_note(struct proc *p, struct exec_package *epp, Elf_Ehdr *eh, int *namesp)
1052 {
1053 	Elf_Phdr *hph, *ph;
1054 	Elf_Note *np = NULL;
1055 	size_t phsize, offset, pfilesz = 0, total;
1056 	int error, names = 0;
1057 
1058 	hph = mallocarray(eh->e_phnum, sizeof(Elf_Phdr), M_TEMP, M_WAITOK);
1059 	phsize = eh->e_phnum * sizeof(Elf_Phdr);
1060 	if ((error = elf_read_from(p, epp->ep_vp, eh->e_phoff,
1061 	    hph, phsize)) != 0)
1062 		goto out1;
1063 
1064 	for (ph = hph;  ph < &hph[eh->e_phnum]; ph++) {
1065 		if (ph->p_type == PT_OPENBSD_WXNEEDED) {
1066 			epp->ep_flags |= EXEC_WXNEEDED;
1067 			continue;
1068 		}
1069 		if (ph->p_type == PT_OPENBSD_NOBTCFI) {
1070 			epp->ep_flags |= EXEC_NOBTCFI;
1071 			continue;
1072 		}
1073 
1074 		if (ph->p_type != PT_NOTE || ph->p_filesz > 1024)
1075 			continue;
1076 
1077 		if (np && ph->p_filesz != pfilesz) {
1078 			free(np, M_TEMP, pfilesz);
1079 			np = NULL;
1080 		}
1081 		if (!np)
1082 			np = malloc(ph->p_filesz, M_TEMP, M_WAITOK);
1083 		pfilesz = ph->p_filesz;
1084 		if ((error = elf_read_from(p, epp->ep_vp, ph->p_offset,
1085 		    np, ph->p_filesz)) != 0)
1086 			goto out2;
1087 
1088 		for (offset = 0; offset < ph->p_filesz; offset += total) {
1089 			Elf_Note *np2 = (Elf_Note *)((char *)np + offset);
1090 
1091 			if (offset + sizeof(Elf_Note) > ph->p_filesz)
1092 				break;
1093 			total = sizeof(Elf_Note) + elfround(np2->namesz) +
1094 			    elfround(np2->descsz);
1095 			if (offset + total > ph->p_filesz)
1096 				break;
1097 			names |= elf_os_pt_note_name(np2);
1098 		}
1099 	}
1100 
1101 out2:
1102 	free(np, M_TEMP, pfilesz);
1103 out1:
1104 	free(hph, M_TEMP, phsize);
1105 	*namesp = names;
1106 	return ((names & ELF_NOTE_NAME_OPENBSD) ? 0 : ENOEXEC);
1107 }
1108 
1109 /*
1110  * Start of routines related to dumping core
1111  */
1112 
1113 #ifdef SMALL_KERNEL
1114 int
1115 coredump_elf(struct proc *p, void *cookie)
1116 {
1117 	return EPERM;
1118 }
1119 #else /* !SMALL_KERNEL */
1120 
1121 struct writesegs_state {
1122 	off_t	notestart;
1123 	off_t	secstart;
1124 	off_t	secoff;
1125 	struct	proc *p;
1126 	void	*iocookie;
1127 	Elf_Phdr *psections;
1128 	size_t	psectionslen;
1129 	size_t	notesize;
1130 	int	npsections;
1131 };
1132 
1133 uvm_coredump_setup_cb	coredump_setup_elf;
1134 uvm_coredump_walk_cb	coredump_walk_elf;
1135 
1136 int	coredump_notes_elf(struct proc *, void *, size_t *);
1137 int	coredump_note_elf(struct proc *, void *, size_t *);
1138 int	coredump_writenote_elf(struct proc *, void *, Elf_Note *,
1139 	    const char *, void *);
1140 
1141 extern vaddr_t sigcode_va;
1142 extern vsize_t sigcode_sz;
1143 
1144 int
1145 coredump_elf(struct proc *p, void *cookie)
1146 {
1147 #ifdef DIAGNOSTIC
1148 	off_t offset;
1149 #endif
1150 	struct writesegs_state ws;
1151 	size_t notesize;
1152 	int error, i;
1153 
1154 	ws.p = p;
1155 	ws.iocookie = cookie;
1156 	ws.psections = NULL;
1157 
1158 	/*
1159 	 * Walk the map to get all the segment offsets and lengths,
1160 	 * write out the ELF header.
1161 	 */
1162 	error = uvm_coredump_walkmap(p, coredump_setup_elf,
1163 	    coredump_walk_elf, &ws);
1164 	if (error)
1165 		goto out;
1166 
1167 	error = coredump_write(cookie, UIO_SYSSPACE, ws.psections,
1168 	    ws.psectionslen, 0);
1169 	if (error)
1170 		goto out;
1171 
1172 	/* Write out the notes. */
1173 	error = coredump_notes_elf(p, cookie, &notesize);
1174 	if (error)
1175 		goto out;
1176 
1177 #ifdef DIAGNOSTIC
1178 	if (notesize != ws.notesize)
1179 		panic("coredump: notesize changed: %zu != %zu",
1180 		    ws.notesize, notesize);
1181 	offset = ws.notestart + notesize;
1182 	if (offset != ws.secstart)
1183 		panic("coredump: offset %lld != secstart %lld",
1184 		    (long long) offset, (long long) ws.secstart);
1185 #endif
1186 
1187 	/* Pass 3: finally, write the sections themselves. */
1188 	for (i = 0; i < ws.npsections - 1; i++) {
1189 		Elf_Phdr *pent = &ws.psections[i];
1190 		if (pent->p_filesz == 0)
1191 			continue;
1192 
1193 #ifdef DIAGNOSTIC
1194 		if (offset != pent->p_offset)
1195 			panic("coredump: offset %lld != p_offset[%d] %lld",
1196 			    (long long) offset, i,
1197 			    (long long) pent->p_filesz);
1198 #endif
1199 
1200 		/*
1201 		 * Since the sigcode is mapped execute-only, we can't
1202 		 * read it.  So use the kernel mapping for it instead.
1203 		 */
1204 		if (pent->p_vaddr == p->p_p->ps_sigcode &&
1205 		    pent->p_filesz == sigcode_sz) {
1206 			error = coredump_write(cookie, UIO_SYSSPACE,
1207 			    (void *)sigcode_va, sigcode_sz, 0);
1208 		} else {
1209 			error = coredump_write(cookie, UIO_USERSPACE,
1210 			    (void *)(vaddr_t)pent->p_vaddr, pent->p_filesz,
1211 			    (pent->p_flags & PF_ISVNODE));
1212 		}
1213 		if (error)
1214 			goto out;
1215 
1216 		coredump_unmap(cookie, (vaddr_t)pent->p_vaddr,
1217 		    (vaddr_t)pent->p_vaddr + pent->p_filesz);
1218 
1219 #ifdef DIAGNOSTIC
1220 		offset += ws.psections[i].p_filesz;
1221 #endif
1222 	}
1223 
1224 out:
1225 	free(ws.psections, M_TEMP, ws.psectionslen);
1226 	return (error);
1227 }
1228 
1229 
1230 /*
1231  * Normally we lay out core files like this:
1232  *	[ELF Header] [Program headers] [Notes] [data for PT_LOAD segments]
1233  *
1234  * However, if there's >= 65535 segments then it overflows the field
1235  * in the ELF header, so the standard specifies putting a magic
1236  * number there and saving the real count in the .sh_info field of
1237  * the first *section* header...which requires generating a section
1238  * header.  To avoid confusing tools, we include an .shstrtab section
1239  * as well so all the indexes look valid.  So in this case we lay
1240  * out the core file like this:
1241  *	[ELF Header] [Section Headers] [.shstrtab] [Program headers] \
1242  *	[Notes] [data for PT_LOAD segments]
1243  *
1244  * The 'shstrtab' structure below is data for the second of the two
1245  * section headers, plus the .shstrtab itself, in one const buffer.
1246  */
1247 static const struct {
1248     Elf_Shdr	shdr;
1249     char	shstrtab[sizeof(ELF_SHSTRTAB) + 1];
1250 } shstrtab = {
1251     .shdr = {
1252 	.sh_name = 1,			/* offset in .shstrtab below */
1253 	.sh_type = SHT_STRTAB,
1254 	.sh_offset = sizeof(Elf_Ehdr) + 2*sizeof(Elf_Shdr),
1255 	.sh_size = sizeof(ELF_SHSTRTAB) + 1,
1256 	.sh_addralign = 1,
1257     },
1258     .shstrtab = "\0" ELF_SHSTRTAB,
1259 };
1260 
1261 int
1262 coredump_setup_elf(int segment_count, void *cookie)
1263 {
1264 	Elf_Ehdr ehdr;
1265 	struct writesegs_state *ws = cookie;
1266 	Elf_Phdr *note;
1267 	int error;
1268 
1269 	/* Get the count of segments, plus one for the PT_NOTE */
1270 	ws->npsections = segment_count + 1;
1271 
1272 	/* Get the size of the notes. */
1273 	error = coredump_notes_elf(ws->p, NULL, &ws->notesize);
1274 	if (error)
1275 		return error;
1276 
1277 	/* Setup the ELF header */
1278 	memset(&ehdr, 0, sizeof(ehdr));
1279 	memcpy(ehdr.e_ident, ELFMAG, SELFMAG);
1280 	ehdr.e_ident[EI_CLASS] = ELF_TARG_CLASS;
1281 	ehdr.e_ident[EI_DATA] = ELF_TARG_DATA;
1282 	ehdr.e_ident[EI_VERSION] = EV_CURRENT;
1283 	/* XXX Should be the OSABI/ABI version of the executable. */
1284 	ehdr.e_ident[EI_OSABI] = ELFOSABI_SYSV;
1285 	ehdr.e_ident[EI_ABIVERSION] = 0;
1286 	ehdr.e_type = ET_CORE;
1287 	/* XXX This should be the e_machine of the executable. */
1288 	ehdr.e_machine = ELF_TARG_MACH;
1289 	ehdr.e_version = EV_CURRENT;
1290 	ehdr.e_entry = 0;
1291 	ehdr.e_flags = 0;
1292 	ehdr.e_ehsize = sizeof(ehdr);
1293 	ehdr.e_phentsize = sizeof(Elf_Phdr);
1294 
1295 	if (ws->npsections < PN_XNUM) {
1296 		ehdr.e_phoff = sizeof(ehdr);
1297 		ehdr.e_shoff = 0;
1298 		ehdr.e_phnum = ws->npsections;
1299 		ehdr.e_shentsize = 0;
1300 		ehdr.e_shnum = 0;
1301 		ehdr.e_shstrndx = 0;
1302 	} else {
1303 		/* too many segments, use extension setup */
1304 		ehdr.e_shoff = sizeof(ehdr);
1305 		ehdr.e_phnum = PN_XNUM;
1306 		ehdr.e_shentsize = sizeof(Elf_Shdr);
1307 		ehdr.e_shnum = 2;
1308 		ehdr.e_shstrndx = 1;
1309 		ehdr.e_phoff = shstrtab.shdr.sh_offset + shstrtab.shdr.sh_size;
1310 	}
1311 
1312 	/* Write out the ELF header. */
1313 	error = coredump_write(ws->iocookie, UIO_SYSSPACE, &ehdr, sizeof(ehdr), 0);
1314 	if (error)
1315 		return error;
1316 
1317 	/*
1318 	 * If an section header is needed to store extension info, write
1319 	 * it out after the ELF header and before the program header.
1320 	 */
1321 	if (ehdr.e_shnum != 0) {
1322 		Elf_Shdr shdr = { .sh_info = ws->npsections };
1323 		error = coredump_write(ws->iocookie, UIO_SYSSPACE, &shdr,
1324 		    sizeof shdr, 0);
1325 		if (error)
1326 			return error;
1327 		error = coredump_write(ws->iocookie, UIO_SYSSPACE, &shstrtab,
1328 		    sizeof(shstrtab.shdr) + sizeof(shstrtab.shstrtab), 0);
1329 		if (error)
1330 			return error;
1331 	}
1332 
1333 	/*
1334 	 * Allocate the segment header array and setup to collect
1335 	 * the section sizes and offsets
1336 	 */
1337 	ws->psections = mallocarray(ws->npsections, sizeof(Elf_Phdr),
1338 	    M_TEMP, M_WAITOK|M_CANFAIL|M_ZERO);
1339 	if (ws->psections == NULL)
1340 		return ENOMEM;
1341 	ws->psectionslen = ws->npsections * sizeof(Elf_Phdr);
1342 
1343 	ws->notestart = ehdr.e_phoff + ws->psectionslen;
1344 	ws->secstart = ws->notestart + ws->notesize;
1345 	ws->secoff = ws->secstart;
1346 
1347 	/* Fill in the PT_NOTE segment header in the last slot */
1348 	note = &ws->psections[ws->npsections - 1];
1349 	note->p_type = PT_NOTE;
1350 	note->p_offset = ws->notestart;
1351 	note->p_vaddr = 0;
1352 	note->p_paddr = 0;
1353 	note->p_filesz = ws->notesize;
1354 	note->p_memsz = 0;
1355 	note->p_flags = PF_R;
1356 	note->p_align = ELFROUNDSIZE;
1357 
1358 	return (0);
1359 }
1360 
1361 int
1362 coredump_walk_elf(vaddr_t start, vaddr_t realend, vaddr_t end, vm_prot_t prot,
1363     int isvnode, int nsegment, void *cookie)
1364 {
1365 	struct writesegs_state *ws = cookie;
1366 	Elf_Phdr phdr;
1367 	vsize_t size, realsize;
1368 
1369 	size = end - start;
1370 	realsize = realend - start;
1371 
1372 	phdr.p_type = PT_LOAD;
1373 	phdr.p_offset = ws->secoff;
1374 	phdr.p_vaddr = start;
1375 	phdr.p_paddr = 0;
1376 	phdr.p_filesz = realsize;
1377 	phdr.p_memsz = size;
1378 	phdr.p_flags = 0;
1379 	if (prot & PROT_READ)
1380 		phdr.p_flags |= PF_R;
1381 	if (prot & PROT_WRITE)
1382 		phdr.p_flags |= PF_W;
1383 	if (prot & PROT_EXEC)
1384 		phdr.p_flags |= PF_X;
1385 	if (isvnode)
1386 		phdr.p_flags |= PF_ISVNODE;
1387 	phdr.p_align = PAGE_SIZE;
1388 
1389 	ws->secoff += phdr.p_filesz;
1390 	ws->psections[nsegment] = phdr;
1391 
1392 	return (0);
1393 }
1394 
1395 int
1396 coredump_notes_elf(struct proc *p, void *iocookie, size_t *sizep)
1397 {
1398 	struct elfcore_procinfo cpi;
1399 	Elf_Note nhdr;
1400 	struct process *pr = p->p_p;
1401 	struct proc *q;
1402 	size_t size, notesize;
1403 	int error;
1404 
1405 	KASSERT(!P_HASSIBLING(p) || pr->ps_single != NULL);
1406 	size = 0;
1407 
1408 	/* First, write an elfcore_procinfo. */
1409 	notesize = sizeof(nhdr) + elfround(sizeof("OpenBSD")) +
1410 	    elfround(sizeof(cpi));
1411 	if (iocookie) {
1412 		memset(&cpi, 0, sizeof(cpi));
1413 
1414 		cpi.cpi_version = ELFCORE_PROCINFO_VERSION;
1415 		cpi.cpi_cpisize = sizeof(cpi);
1416 		cpi.cpi_signo = p->p_sisig;
1417 		cpi.cpi_sigcode = p->p_sicode;
1418 
1419 		cpi.cpi_sigpend = p->p_siglist | pr->ps_siglist;
1420 		cpi.cpi_sigmask = p->p_sigmask;
1421 		cpi.cpi_sigignore = pr->ps_sigacts->ps_sigignore;
1422 		cpi.cpi_sigcatch = pr->ps_sigacts->ps_sigcatch;
1423 
1424 		cpi.cpi_pid = pr->ps_pid;
1425 		cpi.cpi_ppid = pr->ps_ppid;
1426 		cpi.cpi_pgrp = pr->ps_pgid;
1427 		if (pr->ps_session->s_leader)
1428 			cpi.cpi_sid = pr->ps_session->s_leader->ps_pid;
1429 		else
1430 			cpi.cpi_sid = 0;
1431 
1432 		cpi.cpi_ruid = p->p_ucred->cr_ruid;
1433 		cpi.cpi_euid = p->p_ucred->cr_uid;
1434 		cpi.cpi_svuid = p->p_ucred->cr_svuid;
1435 
1436 		cpi.cpi_rgid = p->p_ucred->cr_rgid;
1437 		cpi.cpi_egid = p->p_ucred->cr_gid;
1438 		cpi.cpi_svgid = p->p_ucred->cr_svgid;
1439 
1440 		(void)strlcpy(cpi.cpi_name, pr->ps_comm, sizeof(cpi.cpi_name));
1441 
1442 		nhdr.namesz = sizeof("OpenBSD");
1443 		nhdr.descsz = sizeof(cpi);
1444 		nhdr.type = NT_OPENBSD_PROCINFO;
1445 
1446 		error = coredump_writenote_elf(p, iocookie, &nhdr,
1447 		    "OpenBSD", &cpi);
1448 		if (error)
1449 			return (error);
1450 	}
1451 	size += notesize;
1452 
1453 	/* Second, write an NT_OPENBSD_AUXV note. */
1454 	notesize = sizeof(nhdr) + elfround(sizeof("OpenBSD")) +
1455 	    elfround(ELF_AUX_WORDS * sizeof(char *));
1456 	if (iocookie && pr->ps_auxinfo) {
1457 
1458 		nhdr.namesz = sizeof("OpenBSD");
1459 		nhdr.descsz = ELF_AUX_WORDS * sizeof(char *);
1460 		nhdr.type = NT_OPENBSD_AUXV;
1461 
1462 		error = coredump_write(iocookie, UIO_SYSSPACE,
1463 		    &nhdr, sizeof(nhdr), 0);
1464 		if (error)
1465 			return (error);
1466 
1467 		error = coredump_write(iocookie, UIO_SYSSPACE,
1468 		    "OpenBSD", elfround(nhdr.namesz), 0);
1469 		if (error)
1470 			return (error);
1471 
1472 		error = coredump_write(iocookie, UIO_USERSPACE,
1473 		    (caddr_t)pr->ps_auxinfo, nhdr.descsz, 0);
1474 		if (error)
1475 			return (error);
1476 	}
1477 	size += notesize;
1478 
1479 #ifdef PT_WCOOKIE
1480 	notesize = sizeof(nhdr) + elfround(sizeof("OpenBSD")) +
1481 	    elfround(sizeof(register_t));
1482 	if (iocookie) {
1483 		register_t wcookie;
1484 
1485 		nhdr.namesz = sizeof("OpenBSD");
1486 		nhdr.descsz = sizeof(register_t);
1487 		nhdr.type = NT_OPENBSD_WCOOKIE;
1488 
1489 		wcookie = process_get_wcookie(p);
1490 		error = coredump_writenote_elf(p, iocookie, &nhdr,
1491 		    "OpenBSD", &wcookie);
1492 		if (error)
1493 			return (error);
1494 	}
1495 	size += notesize;
1496 #endif
1497 
1498 	/*
1499 	 * Now write the register info for the thread that caused the
1500 	 * coredump.
1501 	 */
1502 	error = coredump_note_elf(p, iocookie, &notesize);
1503 	if (error)
1504 		return (error);
1505 	size += notesize;
1506 
1507 	/*
1508 	 * Now, for each thread, write the register info and any other
1509 	 * per-thread notes.  Since we're dumping core, all the other
1510 	 * threads in the process have been stopped and the list can't
1511 	 * change.
1512 	 */
1513 	TAILQ_FOREACH(q, &pr->ps_threads, p_thr_link) {
1514 		if (q == p)		/* we've taken care of this thread */
1515 			continue;
1516 		error = coredump_note_elf(q, iocookie, &notesize);
1517 		if (error)
1518 			return (error);
1519 		size += notesize;
1520 	}
1521 
1522 	*sizep = size;
1523 	return (0);
1524 }
1525 
1526 int
1527 coredump_note_elf(struct proc *p, void *iocookie, size_t *sizep)
1528 {
1529 	Elf_Note nhdr;
1530 	int size, notesize, error;
1531 	int namesize;
1532 	char name[64+ELFROUNDSIZE];
1533 	struct reg intreg;
1534 #ifdef PT_GETFPREGS
1535 	struct fpreg freg;
1536 #endif
1537 #ifdef PT_PACMASK
1538 	register_t pacmask[2];
1539 #endif
1540 
1541 	size = 0;
1542 
1543 	snprintf(name, sizeof(name)-ELFROUNDSIZE, "%s@%d",
1544 	    "OpenBSD", p->p_tid + THREAD_PID_OFFSET);
1545 	namesize = strlen(name) + 1;
1546 	memset(name + namesize, 0, elfround(namesize) - namesize);
1547 
1548 	notesize = sizeof(nhdr) + elfround(namesize) + elfround(sizeof(intreg));
1549 	if (iocookie) {
1550 		error = process_read_regs(p, &intreg);
1551 		if (error)
1552 			return (error);
1553 
1554 		nhdr.namesz = namesize;
1555 		nhdr.descsz = sizeof(intreg);
1556 		nhdr.type = NT_OPENBSD_REGS;
1557 
1558 		error = coredump_writenote_elf(p, iocookie, &nhdr,
1559 		    name, &intreg);
1560 		if (error)
1561 			return (error);
1562 
1563 	}
1564 	size += notesize;
1565 
1566 #ifdef PT_GETFPREGS
1567 	notesize = sizeof(nhdr) + elfround(namesize) + elfround(sizeof(freg));
1568 	if (iocookie) {
1569 		error = process_read_fpregs(p, &freg);
1570 		if (error)
1571 			return (error);
1572 
1573 		nhdr.namesz = namesize;
1574 		nhdr.descsz = sizeof(freg);
1575 		nhdr.type = NT_OPENBSD_FPREGS;
1576 
1577 		error = coredump_writenote_elf(p, iocookie, &nhdr, name, &freg);
1578 		if (error)
1579 			return (error);
1580 	}
1581 	size += notesize;
1582 #endif
1583 
1584 #ifdef PT_PACMASK
1585 	notesize = sizeof(nhdr) + elfround(namesize) +
1586 	    elfround(sizeof(pacmask));
1587 	if (iocookie) {
1588 		pacmask[0] = pacmask[1] = process_get_pacmask(p);
1589 
1590 		nhdr.namesz = namesize;
1591 		nhdr.descsz = sizeof(pacmask);
1592 		nhdr.type = NT_OPENBSD_PACMASK;
1593 
1594 		error = coredump_writenote_elf(p, iocookie, &nhdr,
1595 		    name, &pacmask);
1596 		if (error)
1597 			return (error);
1598 	}
1599 	size += notesize;
1600 #endif
1601 
1602 	*sizep = size;
1603 	/* XXX Add hook for machdep per-LWP notes. */
1604 	return (0);
1605 }
1606 
1607 int
1608 coredump_writenote_elf(struct proc *p, void *cookie, Elf_Note *nhdr,
1609     const char *name, void *data)
1610 {
1611 	int error;
1612 
1613 	error = coredump_write(cookie, UIO_SYSSPACE, nhdr, sizeof(*nhdr), 0);
1614 	if (error)
1615 		return error;
1616 
1617 	error = coredump_write(cookie, UIO_SYSSPACE, name,
1618 	    elfround(nhdr->namesz), 0);
1619 	if (error)
1620 		return error;
1621 
1622 	return coredump_write(cookie, UIO_SYSSPACE, data, nhdr->descsz, 0);
1623 }
1624 #endif /* !SMALL_KERNEL */
1625