xref: /openbsd-src/sys/kern/exec_elf.c (revision b0cba4039f65e653a771c9a6dfc4de23413eec17)
1 /*	$OpenBSD: exec_elf.c,v 1.137 2017/02/08 21:04:44 guenther 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/kernel.h>
72 #include <sys/proc.h>
73 #include <sys/malloc.h>
74 #include <sys/pool.h>
75 #include <sys/mount.h>
76 #include <sys/namei.h>
77 #include <sys/vnode.h>
78 #include <sys/core.h>
79 #include <sys/syslog.h>
80 #include <sys/exec.h>
81 #include <sys/exec_elf.h>
82 #include <sys/file.h>
83 #include <sys/ptrace.h>
84 #include <sys/syscall.h>
85 #include <sys/signalvar.h>
86 #include <sys/stat.h>
87 #include <sys/pledge.h>
88 
89 #include <sys/mman.h>
90 
91 #include <uvm/uvm_extern.h>
92 
93 #include <machine/reg.h>
94 #include <machine/exec.h>
95 
96 int	elf_load_file(struct proc *, char *, struct exec_package *,
97 	    struct elf_args *);
98 int	elf_check_header(Elf_Ehdr *);
99 int	elf_read_from(struct proc *, struct vnode *, u_long, void *, int);
100 void	elf_load_psection(struct exec_vmcmd_set *, struct vnode *,
101 	    Elf_Phdr *, Elf_Addr *, Elf_Addr *, int *, int);
102 int	coredump_elf(struct proc *, void *);
103 void	*elf_copyargs(struct exec_package *, struct ps_strings *, void *,
104 	    void *);
105 int	exec_elf_fixup(struct proc *, struct exec_package *);
106 int	elf_os_pt_note(struct proc *, struct exec_package *, Elf_Ehdr *,
107 	    char *, size_t, size_t);
108 
109 extern char sigcode[], esigcode[], sigcoderet[];
110 #ifdef SYSCALL_DEBUG
111 extern char *syscallnames[];
112 #endif
113 
114 /* round up and down to page boundaries. */
115 #define ELF_ROUND(a, b)		(((a) + (b) - 1) & ~((b) - 1))
116 #define ELF_TRUNC(a, b)		((a) & ~((b) - 1))
117 
118 /*
119  * We limit the number of program headers to 32, this should
120  * be a reasonable limit for ELF, the most we have seen so far is 12
121  */
122 #define ELF_MAX_VALID_PHDR 32
123 
124 /*
125  * How many entries are in the AuxInfo array we pass to the process?
126  */
127 #define ELF_AUX_ENTRIES	8
128 
129 /*
130  * This is the OpenBSD ELF emul
131  */
132 struct emul emul_elf = {
133 	"native",
134 	NULL,
135 	sendsig,
136 	SYS_syscall,
137 	SYS_MAXSYSCALL,
138 	sysent,
139 #ifdef SYSCALL_DEBUG
140 	syscallnames,
141 #else
142 	NULL,
143 #endif
144 	(sizeof(AuxInfo) * ELF_AUX_ENTRIES / sizeof(char *)),
145 	elf_copyargs,
146 	setregs,
147 	exec_elf_fixup,
148 	coredump_elf,
149 	sigcode,
150 	esigcode,
151 	sigcoderet,
152 	EMUL_ENABLED | EMUL_NATIVE,
153 };
154 
155 /*
156  * Copy arguments onto the stack in the normal way, but add some
157  * space for extra information in case of dynamic binding.
158  */
159 void *
160 elf_copyargs(struct exec_package *pack, struct ps_strings *arginfo,
161 		void *stack, void *argp)
162 {
163 	stack = copyargs(pack, arginfo, stack, argp);
164 	if (!stack)
165 		return (NULL);
166 
167 	/*
168 	 * Push space for extra arguments on the stack needed by
169 	 * dynamically linked binaries.
170 	 */
171 	if (pack->ep_emul_arg != NULL) {
172 		pack->ep_emul_argp = stack;
173 		stack = (char *)stack + ELF_AUX_ENTRIES * sizeof (AuxInfo);
174 	}
175 	return (stack);
176 }
177 
178 /*
179  * Check header for validity; return 0 for ok, ENOEXEC if error
180  */
181 int
182 elf_check_header(Elf_Ehdr *ehdr)
183 {
184 	/*
185 	 * We need to check magic, class size, endianess, and version before
186 	 * we look at the rest of the Elf_Ehdr structure. These few elements
187 	 * are represented in a machine independent fashion.
188 	 */
189 	if (!IS_ELF(*ehdr) ||
190 	    ehdr->e_ident[EI_CLASS] != ELF_TARG_CLASS ||
191 	    ehdr->e_ident[EI_DATA] != ELF_TARG_DATA ||
192 	    ehdr->e_ident[EI_VERSION] != ELF_TARG_VER)
193 		return (ENOEXEC);
194 
195 	/* Now check the machine dependent header */
196 	if (ehdr->e_machine != ELF_TARG_MACH ||
197 	    ehdr->e_version != ELF_TARG_VER)
198 		return (ENOEXEC);
199 
200 	/* Don't allow an insane amount of sections. */
201 	if (ehdr->e_phnum > ELF_MAX_VALID_PHDR)
202 		return (ENOEXEC);
203 
204 	return (0);
205 }
206 
207 /*
208  * Load a psection at the appropriate address
209  */
210 void
211 elf_load_psection(struct exec_vmcmd_set *vcset, struct vnode *vp,
212     Elf_Phdr *ph, Elf_Addr *addr, Elf_Addr *size, int *prot, int flags)
213 {
214 	u_long msize, lsize, psize, rm, rf;
215 	long diff, offset, bdiff;
216 	Elf_Addr base;
217 
218 	/*
219 	 * If the user specified an address, then we load there.
220 	 */
221 	if (*addr != ELF_NO_ADDR) {
222 		if (ph->p_align > 1) {
223 			*addr = ELF_TRUNC(*addr, ph->p_align);
224 			diff = ph->p_vaddr - ELF_TRUNC(ph->p_vaddr, ph->p_align);
225 			/* page align vaddr */
226 			base = *addr + trunc_page(ph->p_vaddr)
227 			    - ELF_TRUNC(ph->p_vaddr, ph->p_align);
228 		} else {
229 			diff = 0;
230 			base = *addr + trunc_page(ph->p_vaddr) - ph->p_vaddr;
231 		}
232 	} else {
233 		*addr = ph->p_vaddr;
234 		if (ph->p_align > 1)
235 			*addr = ELF_TRUNC(*addr, ph->p_align);
236 		base = trunc_page(ph->p_vaddr);
237 		diff = ph->p_vaddr - *addr;
238 	}
239 	bdiff = ph->p_vaddr - trunc_page(ph->p_vaddr);
240 
241 	/*
242 	 * Enforce W^X and map W|X segments without X permission
243 	 * initially.  The dynamic linker will make these read-only
244 	 * and add back X permission after relocation processing.
245 	 * Static executables with W|X segments will probably crash.
246 	 */
247 	*prot |= (ph->p_flags & PF_R) ? PROT_READ : 0;
248 	*prot |= (ph->p_flags & PF_W) ? PROT_WRITE : 0;
249 	if ((ph->p_flags & PF_W) == 0)
250 		*prot |= (ph->p_flags & PF_X) ? PROT_EXEC : 0;
251 
252 	msize = ph->p_memsz + diff;
253 	offset = ph->p_offset - bdiff;
254 	lsize = ph->p_filesz + bdiff;
255 	psize = round_page(lsize);
256 
257 	/*
258 	 * Because the pagedvn pager can't handle zero fill of the last
259 	 * data page if it's not page aligned we map the last page readvn.
260 	 */
261 	if (ph->p_flags & PF_W) {
262 		psize = trunc_page(lsize);
263 		if (psize > 0)
264 			NEW_VMCMD2(vcset, vmcmd_map_pagedvn, psize, base, vp,
265 			    offset, *prot, flags);
266 		if (psize != lsize) {
267 			NEW_VMCMD2(vcset, vmcmd_map_readvn, lsize - psize,
268 			    base + psize, vp, offset + psize, *prot, flags);
269 		}
270 	} else {
271 		NEW_VMCMD2(vcset, vmcmd_map_pagedvn, psize, base, vp, offset,
272 		    *prot, flags);
273 	}
274 
275 	/*
276 	 * Check if we need to extend the size of the segment
277 	 */
278 	rm = round_page(*addr + ph->p_memsz + diff);
279 	rf = round_page(*addr + ph->p_filesz + diff);
280 
281 	if (rm != rf) {
282 		NEW_VMCMD2(vcset, vmcmd_map_zero, rm - rf, rf, NULLVP, 0,
283 		    *prot, flags);
284 	}
285 	*size = msize;
286 }
287 
288 /*
289  * Read from vnode into buffer at offset.
290  */
291 int
292 elf_read_from(struct proc *p, struct vnode *vp, u_long off, void *buf,
293     int size)
294 {
295 	int error;
296 	size_t resid;
297 
298 	if ((error = vn_rdwr(UIO_READ, vp, buf, size, off, UIO_SYSSPACE,
299 	    0, p->p_ucred, &resid, p)) != 0)
300 		return error;
301 	/*
302 	 * See if we got all of it
303 	 */
304 	if (resid != 0)
305 		return (ENOEXEC);
306 	return (0);
307 }
308 
309 /*
310  * Load a file (interpreter/library) pointed to by path [stolen from
311  * coff_load_shlib()]. Made slightly generic so it might be used externally.
312  */
313 int
314 elf_load_file(struct proc *p, char *path, struct exec_package *epp,
315     struct elf_args *ap)
316 {
317 	int error, i;
318 	struct nameidata nd;
319 	Elf_Ehdr eh;
320 	Elf_Phdr *ph = NULL;
321 	u_long phsize;
322 	Elf_Addr addr;
323 	struct vnode *vp;
324 	Elf_Phdr *base_ph = NULL;
325 	struct interp_ld_sec {
326 		Elf_Addr vaddr;
327 		u_long memsz;
328 	} loadmap[ELF_MAX_VALID_PHDR];
329 	int nload, idx = 0;
330 	Elf_Addr pos;
331 	int file_align;
332 	int loop;
333 	size_t randomizequota = ELF_RANDOMIZE_LIMIT;
334 
335 	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE, path, p);
336 	nd.ni_pledge = PLEDGE_RPATH;
337 	if ((error = namei(&nd)) != 0) {
338 		return (error);
339 	}
340 	vp = nd.ni_vp;
341 	if (vp->v_type != VREG) {
342 		error = EACCES;
343 		goto bad;
344 	}
345 	if ((error = VOP_GETATTR(vp, epp->ep_vap, p->p_ucred, p)) != 0)
346 		goto bad;
347 	if (vp->v_mount->mnt_flag & MNT_NOEXEC) {
348 		error = EACCES;
349 		goto bad;
350 	}
351 	if ((error = VOP_ACCESS(vp, VREAD, p->p_ucred, p)) != 0)
352 		goto bad1;
353 	if ((error = elf_read_from(p, nd.ni_vp, 0, &eh, sizeof(eh))) != 0)
354 		goto bad1;
355 
356 	if (elf_check_header(&eh) || eh.e_type != ET_DYN) {
357 		error = ENOEXEC;
358 		goto bad1;
359 	}
360 
361 	ph = mallocarray(eh.e_phnum, sizeof(Elf_Phdr), M_TEMP, M_WAITOK);
362 	phsize = eh.e_phnum * sizeof(Elf_Phdr);
363 
364 	if ((error = elf_read_from(p, nd.ni_vp, eh.e_phoff, ph, phsize)) != 0)
365 		goto bad1;
366 
367 	for (i = 0; i < eh.e_phnum; i++) {
368 		if (ph[i].p_type == PT_LOAD) {
369 			if (ph[i].p_filesz > ph[i].p_memsz)
370 				goto bad1;
371 			loadmap[idx].vaddr = trunc_page(ph[i].p_vaddr);
372 			loadmap[idx].memsz = round_page (ph[i].p_vaddr +
373 			    ph[i].p_memsz - loadmap[idx].vaddr);
374 			file_align = ph[i].p_align;
375 			idx++;
376 		}
377 	}
378 	nload = idx;
379 
380 	/*
381 	 * Load the interpreter where a non-fixed mmap(NULL, ...)
382 	 * would (i.e. something safely out of the way).
383 	 */
384 	pos = uvm_map_hint(p->p_vmspace, PROT_EXEC, VM_MIN_ADDRESS,
385 	    VM_MAXUSER_ADDRESS);
386 	pos = ELF_ROUND(pos, file_align);
387 
388 	loop = 0;
389 	for (i = 0; i < nload;/**/) {
390 		vaddr_t	addr;
391 		struct	uvm_object *uobj;
392 		off_t	uoff;
393 		size_t	size;
394 
395 #ifdef this_needs_fixing
396 		if (i == 0) {
397 			uobj = &vp->v_uvm.u_obj;
398 			/* need to fix uoff */
399 		} else {
400 #endif
401 			uobj = NULL;
402 			uoff = 0;
403 #ifdef this_needs_fixing
404 		}
405 #endif
406 
407 		addr = trunc_page(pos + loadmap[i].vaddr);
408 		size =  round_page(addr + loadmap[i].memsz) - addr;
409 
410 		/* CRAP - map_findspace does not avoid daddr+BRKSIZ */
411 		if ((addr + size > (vaddr_t)p->p_vmspace->vm_daddr) &&
412 		    (addr < (vaddr_t)p->p_vmspace->vm_daddr + BRKSIZ))
413 			addr = round_page((vaddr_t)p->p_vmspace->vm_daddr +
414 			    BRKSIZ);
415 
416 		if (uvm_map_mquery(&p->p_vmspace->vm_map, &addr, size,
417 		    (i == 0 ? uoff : UVM_UNKNOWN_OFFSET), 0) != 0) {
418 			if (loop == 0) {
419 				loop = 1;
420 				i = 0;
421 				pos = 0;
422 				continue;
423 			}
424 			error = ENOMEM;
425 			goto bad1;
426 		}
427 		if (addr != pos + loadmap[i].vaddr) {
428 			/* base changed. */
429 			pos = addr - trunc_page(loadmap[i].vaddr);
430 			pos = ELF_ROUND(pos,file_align);
431 			i = 0;
432 			continue;
433 		}
434 
435 		i++;
436 	}
437 
438 	/*
439 	 * Load all the necessary sections
440 	 */
441 	for (i = 0; i < eh.e_phnum; i++) {
442 		Elf_Addr size = 0;
443 		int prot = 0;
444 		int flags;
445 
446 		switch (ph[i].p_type) {
447 		case PT_LOAD:
448 			if (base_ph == NULL) {
449 				flags = VMCMD_BASE;
450 				addr = pos;
451 				base_ph = &ph[i];
452 			} else {
453 				flags = VMCMD_RELATIVE;
454 				addr = ph[i].p_vaddr - base_ph->p_vaddr;
455 			}
456 			elf_load_psection(&epp->ep_vmcmds, nd.ni_vp,
457 			    &ph[i], &addr, &size, &prot, flags);
458 			/* If entry is within this section it must be text */
459 			if (eh.e_entry >= ph[i].p_vaddr &&
460 			    eh.e_entry < (ph[i].p_vaddr + size)) {
461  				epp->ep_entry = addr + eh.e_entry -
462 				    ELF_TRUNC(ph[i].p_vaddr,ph[i].p_align);
463 				ap->arg_interp = addr;
464 			}
465 			addr += size;
466 			break;
467 
468 		case PT_DYNAMIC:
469 		case PT_PHDR:
470 		case PT_NOTE:
471 			break;
472 
473 		case PT_OPENBSD_RANDOMIZE:
474 			if (ph[i].p_memsz > randomizequota) {
475 				error = ENOMEM;
476 				goto bad1;
477 			}
478 			randomizequota -= ph[i].p_memsz;
479 			NEW_VMCMD(&epp->ep_vmcmds, vmcmd_randomize,
480 			    ph[i].p_memsz, ph[i].p_vaddr + pos, NULLVP, 0, 0);
481 			break;
482 
483 		default:
484 			break;
485 		}
486 	}
487 
488 	vn_marktext(nd.ni_vp);
489 
490 bad1:
491 	VOP_CLOSE(nd.ni_vp, FREAD, p->p_ucred, p);
492 bad:
493 	free(ph, M_TEMP, phsize);
494 
495 	vput(nd.ni_vp);
496 	return (error);
497 }
498 
499 /*
500  * Prepare an Elf binary's exec package
501  *
502  * First, set of the various offsets/lengths in the exec package.
503  *
504  * Then, mark the text image busy (so it can be demand paged) or error out if
505  * this is not possible.  Finally, set up vmcmds for the text, data, bss, and
506  * stack segments.
507  */
508 int
509 exec_elf_makecmds(struct proc *p, struct exec_package *epp)
510 {
511 	Elf_Ehdr *eh = epp->ep_hdr;
512 	Elf_Phdr *ph, *pp, *base_ph = NULL;
513 	Elf_Addr phdr = 0, exe_base = 0;
514 	int error, i, has_phdr = 0;
515 	char *interp = NULL;
516 	u_long phsize;
517 	size_t randomizequota = ELF_RANDOMIZE_LIMIT;
518 
519 	if (epp->ep_hdrvalid < sizeof(Elf_Ehdr))
520 		return (ENOEXEC);
521 
522 	if (elf_check_header(eh) ||
523 	   (eh->e_type != ET_EXEC && eh->e_type != ET_DYN))
524 		return (ENOEXEC);
525 
526 	/*
527 	 * check if vnode is in open for writing, because we want to demand-
528 	 * page out of it.  if it is, don't do it, for various reasons.
529 	 */
530 	if (epp->ep_vp->v_writecount != 0) {
531 #ifdef DIAGNOSTIC
532 		if (epp->ep_vp->v_flag & VTEXT)
533 			panic("exec: a VTEXT vnode has writecount != 0");
534 #endif
535 		return (ETXTBSY);
536 	}
537 	/*
538 	 * Allocate space to hold all the program headers, and read them
539 	 * from the file
540 	 */
541 	ph = mallocarray(eh->e_phnum, sizeof(Elf_Phdr), M_TEMP, M_WAITOK);
542 	phsize = eh->e_phnum * sizeof(Elf_Phdr);
543 
544 	if ((error = elf_read_from(p, epp->ep_vp, eh->e_phoff, ph,
545 	    phsize)) != 0)
546 		goto bad;
547 
548 	epp->ep_tsize = ELF_NO_ADDR;
549 	epp->ep_dsize = ELF_NO_ADDR;
550 
551 	for (i = 0, pp = ph; i < eh->e_phnum; i++, pp++) {
552 		if (pp->p_type == PT_INTERP && !interp) {
553 			if (pp->p_filesz < 2 || pp->p_filesz > MAXPATHLEN)
554 				goto bad;
555 			interp = pool_get(&namei_pool, PR_WAITOK);
556 			if ((error = elf_read_from(p, epp->ep_vp,
557 			    pp->p_offset, interp, pp->p_filesz)) != 0) {
558 				goto bad;
559 			}
560 			if (interp[pp->p_filesz - 1] != '\0')
561 				goto bad;
562 		} else if (pp->p_type == PT_LOAD) {
563 			if (pp->p_filesz > pp->p_memsz) {
564 				error = EINVAL;
565 				goto bad;
566 			}
567 			if (base_ph == NULL)
568 				base_ph = pp;
569 		} else if (pp->p_type == PT_PHDR) {
570 			has_phdr = 1;
571 		}
572 	}
573 
574 	if (eh->e_type == ET_DYN) {
575 		/* need phdr and load sections for PIE */
576 		if (!has_phdr || base_ph == NULL) {
577 			error = EINVAL;
578 			goto bad;
579 		}
580 		/* randomize exe_base for PIE */
581 		exe_base = uvm_map_pie(base_ph->p_align);
582 	}
583 
584 	/*
585 	 * OK, we want a slightly different twist of the
586 	 * standard emulation package for "real" elf.
587 	 */
588 	epp->ep_emul = &emul_elf;
589 
590 	/*
591 	 * Verify this is an OpenBSD executable.  If it's marked that way
592 	 * via a PT_NOTE then also check for a PT_OPENBSD_WXNEEDED segment.
593 	 */
594 	if (eh->e_ident[EI_OSABI] != ELFOSABI_OPENBSD && (error =
595 	    elf_os_pt_note(p, epp, epp->ep_hdr, "OpenBSD", 8, 4)) != 0) {
596 		goto bad;
597 	}
598 
599 	/*
600 	 * Load all the necessary sections
601 	 */
602 	for (i = 0, pp = ph; i < eh->e_phnum; i++, pp++) {
603 		Elf_Addr addr, size = 0;
604 		int prot = 0;
605 		int flags = 0;
606 
607 		switch (pp->p_type) {
608 		case PT_LOAD:
609 			if (exe_base != 0) {
610 				if (pp == base_ph) {
611 					flags = VMCMD_BASE;
612 					addr = exe_base;
613 				} else {
614 					flags = VMCMD_RELATIVE;
615 					addr = pp->p_vaddr - base_ph->p_vaddr;
616 				}
617 			} else
618 				addr = ELF_NO_ADDR;
619 
620 			/*
621 			 * Calculates size of text and data segments
622 			 * by starting at first and going to end of last.
623 			 * 'rwx' sections are treated as data.
624 			 * this is correct for BSS_PLT, but may not be
625 			 * for DATA_PLT, is fine for TEXT_PLT.
626 			 */
627 			elf_load_psection(&epp->ep_vmcmds, epp->ep_vp,
628 			    pp, &addr, &size, &prot, flags);
629 
630 			/*
631 			 * Update exe_base in case alignment was off.
632 			 * For PIE, addr is relative to exe_base so
633 			 * adjust it (non PIE exe_base is 0 so no change).
634 			 */
635 			if (flags == VMCMD_BASE)
636 				exe_base = addr;
637 			else
638 				addr += exe_base;
639 
640 			/*
641 			 * Decide whether it's text or data by looking
642 			 * at the protection of the section
643 			 */
644 			if (prot & PROT_WRITE) {
645 				/* data section */
646 				if (epp->ep_dsize == ELF_NO_ADDR) {
647 					epp->ep_daddr = addr;
648 					epp->ep_dsize = size;
649 				} else {
650 					if (addr < epp->ep_daddr) {
651 						epp->ep_dsize =
652 						    epp->ep_dsize +
653 						    epp->ep_daddr -
654 						    addr;
655 						epp->ep_daddr = addr;
656 					} else
657 						epp->ep_dsize = addr+size -
658 						    epp->ep_daddr;
659 				}
660 			} else if (prot & PROT_EXEC) {
661 				/* text section */
662 				if (epp->ep_tsize == ELF_NO_ADDR) {
663 					epp->ep_taddr = addr;
664 					epp->ep_tsize = size;
665 				} else {
666 					if (addr < epp->ep_taddr) {
667 						epp->ep_tsize =
668 						    epp->ep_tsize +
669 						    epp->ep_taddr -
670 						    addr;
671 						epp->ep_taddr = addr;
672 					} else
673 						epp->ep_tsize = addr+size -
674 						    epp->ep_taddr;
675 				}
676 			}
677 			break;
678 
679 		case PT_SHLIB:
680 			error = ENOEXEC;
681 			goto bad;
682 
683 		case PT_INTERP:
684 			/* Already did this one */
685 		case PT_DYNAMIC:
686 		case PT_NOTE:
687 			break;
688 
689 		case PT_PHDR:
690 			/* Note address of program headers (in text segment) */
691 			phdr = pp->p_vaddr;
692 			break;
693 
694 		case PT_OPENBSD_RANDOMIZE:
695 			if (ph[i].p_memsz > randomizequota) {
696 				error = ENOMEM;
697 				goto bad;
698 			}
699 			randomizequota -= ph[i].p_memsz;
700 			NEW_VMCMD(&epp->ep_vmcmds, vmcmd_randomize,
701 			    ph[i].p_memsz, ph[i].p_vaddr + exe_base, NULLVP, 0, 0);
702 			break;
703 
704 		default:
705 			/*
706 			 * Not fatal, we don't need to understand everything
707 			 * :-)
708 			 */
709 			break;
710 		}
711 	}
712 
713 	phdr += exe_base;
714 
715 	/*
716 	 * Strangely some linux programs may have all load sections marked
717 	 * writeable, in this case, textsize is not -1, but rather 0;
718 	 */
719 	if (epp->ep_tsize == ELF_NO_ADDR)
720 		epp->ep_tsize = 0;
721 	/*
722 	 * Another possibility is that it has all load sections marked
723 	 * read-only.  Fake a zero-sized data segment right after the
724 	 * text segment.
725 	 */
726 	if (epp->ep_dsize == ELF_NO_ADDR) {
727 		epp->ep_daddr = round_page(epp->ep_taddr + epp->ep_tsize);
728 		epp->ep_dsize = 0;
729 	}
730 
731 	epp->ep_interp = interp;
732 	epp->ep_entry = eh->e_entry + exe_base;
733 
734 	/*
735 	 * Check if we found a dynamically linked binary and arrange to load
736 	 * its interpreter when the exec file is released.
737 	 */
738 	if (interp || eh->e_type == ET_DYN) {
739 		struct elf_args *ap;
740 
741 		ap = malloc(sizeof(*ap), M_TEMP, M_WAITOK);
742 
743 		ap->arg_phaddr = phdr;
744 		ap->arg_phentsize = eh->e_phentsize;
745 		ap->arg_phnum = eh->e_phnum;
746 		ap->arg_entry = eh->e_entry + exe_base;
747 		ap->arg_interp = exe_base;
748 
749 		epp->ep_emul_arg = ap;
750 		epp->ep_emul_argsize = sizeof *ap;
751 	}
752 
753 	free(ph, M_TEMP, phsize);
754 	vn_marktext(epp->ep_vp);
755 	return (exec_setup_stack(p, epp));
756 
757 bad:
758 	if (interp)
759 		pool_put(&namei_pool, interp);
760 	free(ph, M_TEMP, phsize);
761 	kill_vmcmds(&epp->ep_vmcmds);
762 	if (error == 0)
763 		return (ENOEXEC);
764 	return (error);
765 }
766 
767 /*
768  * Phase II of load. It is now safe to load the interpreter. Info collected
769  * when loading the program is available for setup of the interpreter.
770  */
771 int
772 exec_elf_fixup(struct proc *p, struct exec_package *epp)
773 {
774 	char	*interp;
775 	int	error = 0;
776 	struct	elf_args *ap;
777 	AuxInfo ai[ELF_AUX_ENTRIES], *a;
778 
779 	if (epp->ep_emul_arg == NULL) {
780 		return (0);
781 	}
782 
783 	interp = epp->ep_interp;
784 	ap = epp->ep_emul_arg;
785 
786 	if (interp &&
787 	    (error = elf_load_file(p, interp, epp, ap)) != 0) {
788 		free(ap, M_TEMP, epp->ep_emul_argsize);
789 		pool_put(&namei_pool, interp);
790 		kill_vmcmds(&epp->ep_vmcmds);
791 		return (error);
792 	}
793 	/*
794 	 * We have to do this ourselves...
795 	 */
796 	error = exec_process_vmcmds(p, epp);
797 
798 	/*
799 	 * Push extra arguments on the stack needed by dynamically
800 	 * linked binaries
801 	 */
802 	if (error == 0) {
803 		a = ai;
804 
805 		a->au_id = AUX_phdr;
806 		a->au_v = ap->arg_phaddr;
807 		a++;
808 
809 		a->au_id = AUX_phent;
810 		a->au_v = ap->arg_phentsize;
811 		a++;
812 
813 		a->au_id = AUX_phnum;
814 		a->au_v = ap->arg_phnum;
815 		a++;
816 
817 		a->au_id = AUX_pagesz;
818 		a->au_v = PAGE_SIZE;
819 		a++;
820 
821 		a->au_id = AUX_base;
822 		a->au_v = ap->arg_interp;
823 		a++;
824 
825 		a->au_id = AUX_flags;
826 		a->au_v = 0;
827 		a++;
828 
829 		a->au_id = AUX_entry;
830 		a->au_v = ap->arg_entry;
831 		a++;
832 
833 		a->au_id = AUX_null;
834 		a->au_v = 0;
835 		a++;
836 
837 		error = copyout(ai, epp->ep_emul_argp, sizeof ai);
838 	}
839 	free(ap, M_TEMP, epp->ep_emul_argsize);
840 	if (interp)
841 		pool_put(&namei_pool, interp);
842 	return (error);
843 }
844 
845 int
846 elf_os_pt_note(struct proc *p, struct exec_package *epp, Elf_Ehdr *eh,
847     char *os_name, size_t name_size, size_t desc_size)
848 {
849 	char pathbuf[MAXPATHLEN];
850 	Elf_Phdr *hph, *ph;
851 	Elf_Note *np = NULL;
852 	size_t phsize;
853 	int error;
854 
855 	hph = mallocarray(eh->e_phnum, sizeof(Elf_Phdr), M_TEMP, M_WAITOK);
856 	phsize = eh->e_phnum * sizeof(Elf_Phdr);
857 	if ((error = elf_read_from(p, epp->ep_vp, eh->e_phoff,
858 	    hph, phsize)) != 0)
859 		goto out1;
860 
861 	for (ph = hph;  ph < &hph[eh->e_phnum]; ph++) {
862 		if (ph->p_type == PT_OPENBSD_WXNEEDED) {
863 			int wxallowed = (epp->ep_vp->v_mount &&
864 			    (epp->ep_vp->v_mount->mnt_flag & MNT_WXALLOWED));
865 
866 			if (!wxallowed) {
867 				error = copyinstr(epp->ep_name, &pathbuf,
868 				    sizeof(pathbuf), NULL);
869 				log(LOG_NOTICE,
870 				    "%s(%d): W^X binary outside wxallowed mountpoint\n",
871 				    error ? "" : pathbuf, p->p_p->ps_pid);
872 				error = EACCES;
873 				goto out1;
874 			}
875 			epp->ep_flags |= EXEC_WXNEEDED;
876 			break;
877 		}
878 	}
879 
880 	for (ph = hph;  ph < &hph[eh->e_phnum]; ph++) {
881 		if (ph->p_type != PT_NOTE ||
882 		    ph->p_filesz > 1024 ||
883 		    ph->p_filesz < sizeof(Elf_Note) + name_size)
884 			continue;
885 
886 		np = malloc(ph->p_filesz, M_TEMP, M_WAITOK);
887 		if ((error = elf_read_from(p, epp->ep_vp, ph->p_offset,
888 		    np, ph->p_filesz)) != 0)
889 			goto out2;
890 
891 #if 0
892 		if (np->type != ELF_NOTE_TYPE_OSVERSION) {
893 			free(np, M_TEMP, ph->p_filesz);
894 			np = NULL;
895 			continue;
896 		}
897 #endif
898 
899 		/* Check the name and description sizes. */
900 		if (np->namesz != name_size ||
901 		    np->descsz != desc_size)
902 			goto out3;
903 
904 		if (memcmp((np + 1), os_name, name_size))
905 			goto out3;
906 
907 		/* XXX: We could check for the specific emulation here */
908 		/* All checks succeeded. */
909 		error = 0;
910 		goto out2;
911 	}
912 
913 out3:
914 	error = ENOEXEC;
915 out2:
916 	free(np, M_TEMP, ph->p_filesz);
917 out1:
918 	free(hph, M_TEMP, phsize);
919 	return error;
920 }
921 
922 /*
923  * Start of routines related to dumping core
924  */
925 
926 #ifdef SMALL_KERNEL
927 int
928 coredump_elf(struct proc *p, void *cookie)
929 {
930 	return EPERM;
931 }
932 #else /* !SMALL_KERNEL */
933 
934 
935 struct countsegs_state {
936 	int	npsections;
937 };
938 
939 int	coredump_countsegs_elf(struct proc *, void *,
940 	    struct uvm_coredump_state *);
941 
942 struct writesegs_state {
943 	Elf_Phdr *psections;
944 	off_t	secoff;
945 };
946 
947 int	coredump_writeseghdrs_elf(struct proc *, void *,
948 	    struct uvm_coredump_state *);
949 
950 int	coredump_notes_elf(struct proc *, void *, size_t *);
951 int	coredump_note_elf(struct proc *, void *, size_t *);
952 int	coredump_writenote_elf(struct proc *, void *, Elf_Note *,
953 	    const char *, void *);
954 
955 #define	ELFROUNDSIZE	4	/* XXX Should it be sizeof(Elf_Word)? */
956 #define	elfround(x)	roundup((x), ELFROUNDSIZE)
957 
958 int
959 coredump_elf(struct proc *p, void *cookie)
960 {
961 	Elf_Ehdr ehdr;
962 	Elf_Phdr *psections = NULL;
963 	struct countsegs_state cs;
964 	struct writesegs_state ws;
965 	off_t notestart, secstart, offset;
966 	size_t notesize, psectionslen;
967 	int error, i;
968 
969 	/*
970 	 * We have to make a total of 3 passes across the map:
971 	 *
972 	 *	1. Count the number of map entries (the number of
973 	 *	   PT_LOAD sections).
974 	 *
975 	 *	2. Write the P-section headers.
976 	 *
977 	 *	3. Write the P-sections.
978 	 */
979 
980 	/* Pass 1: count the entries. */
981 	cs.npsections = 0;
982 	error = uvm_coredump_walkmap(p, NULL, coredump_countsegs_elf, &cs);
983 	if (error)
984 		goto out;
985 
986 	/* Count the PT_NOTE section. */
987 	cs.npsections++;
988 
989 	/* Get the size of the notes. */
990 	error = coredump_notes_elf(p, NULL, &notesize);
991 	if (error)
992 		goto out;
993 
994 	memset(&ehdr, 0, sizeof(ehdr));
995 	memcpy(ehdr.e_ident, ELFMAG, SELFMAG);
996 	ehdr.e_ident[EI_CLASS] = ELF_TARG_CLASS;
997 	ehdr.e_ident[EI_DATA] = ELF_TARG_DATA;
998 	ehdr.e_ident[EI_VERSION] = EV_CURRENT;
999 	/* XXX Should be the OSABI/ABI version of the executable. */
1000 	ehdr.e_ident[EI_OSABI] = ELFOSABI_SYSV;
1001 	ehdr.e_ident[EI_ABIVERSION] = 0;
1002 	ehdr.e_type = ET_CORE;
1003 	/* XXX This should be the e_machine of the executable. */
1004 	ehdr.e_machine = ELF_TARG_MACH;
1005 	ehdr.e_version = EV_CURRENT;
1006 	ehdr.e_entry = 0;
1007 	ehdr.e_phoff = sizeof(ehdr);
1008 	ehdr.e_shoff = 0;
1009 	ehdr.e_flags = 0;
1010 	ehdr.e_ehsize = sizeof(ehdr);
1011 	ehdr.e_phentsize = sizeof(Elf_Phdr);
1012 	ehdr.e_phnum = cs.npsections;
1013 	ehdr.e_shentsize = 0;
1014 	ehdr.e_shnum = 0;
1015 	ehdr.e_shstrndx = 0;
1016 
1017 	/* Write out the ELF header. */
1018 	error = coredump_write(cookie, UIO_SYSSPACE, &ehdr, sizeof(ehdr));
1019 	if (error)
1020 		goto out;
1021 
1022 	psections = mallocarray(cs.npsections, sizeof(Elf_Phdr),
1023 	    M_TEMP, M_WAITOK|M_ZERO);
1024 	psectionslen = cs.npsections * sizeof(Elf_Phdr);
1025 
1026 	offset = sizeof(ehdr);
1027 	notestart = offset + psectionslen;
1028 	secstart = notestart + notesize;
1029 
1030 	/* Pass 2: now write the P-section headers. */
1031 	ws.secoff = secstart;
1032 	ws.psections = psections;
1033 	error = uvm_coredump_walkmap(p, cookie, coredump_writeseghdrs_elf, &ws);
1034 	if (error)
1035 		goto out;
1036 
1037 	/* Write out the PT_NOTE header. */
1038 	ws.psections->p_type = PT_NOTE;
1039 	ws.psections->p_offset = notestart;
1040 	ws.psections->p_vaddr = 0;
1041 	ws.psections->p_paddr = 0;
1042 	ws.psections->p_filesz = notesize;
1043 	ws.psections->p_memsz = 0;
1044 	ws.psections->p_flags = PF_R;
1045 	ws.psections->p_align = ELFROUNDSIZE;
1046 
1047 	error = coredump_write(cookie, UIO_SYSSPACE, psections, psectionslen);
1048 	if (error)
1049 		goto out;
1050 
1051 #ifdef DIAGNOSTIC
1052 	offset += psectionslen;
1053 	if (offset != notestart)
1054 		panic("coredump: offset %lld != notestart %lld",
1055 		    (long long) offset, (long long) notestart);
1056 #endif
1057 
1058 	/* Write out the notes. */
1059 	error = coredump_notes_elf(p, cookie, &notesize);
1060 	if (error)
1061 		goto out;
1062 
1063 #ifdef DIAGNOSTIC
1064 	offset += notesize;
1065 	if (offset != secstart)
1066 		panic("coredump: offset %lld != secstart %lld",
1067 		    (long long) offset, (long long) secstart);
1068 #endif
1069 
1070 	/* Pass 3: finally, write the sections themselves. */
1071 	for (i = 0; i < cs.npsections - 1; i++) {
1072 		if (psections[i].p_filesz == 0)
1073 			continue;
1074 
1075 #ifdef DIAGNOSTIC
1076 		if (offset != psections[i].p_offset)
1077 			panic("coredump: offset %lld != p_offset[%d] %lld",
1078 			    (long long) offset, i,
1079 			    (long long) psections[i].p_filesz);
1080 #endif
1081 
1082 		error = coredump_write(cookie, UIO_USERSPACE,
1083 		    (void *)(vaddr_t)psections[i].p_vaddr,
1084 		    psections[i].p_filesz);
1085 		if (error)
1086 			goto out;
1087 
1088 		coredump_unmap(cookie, (vaddr_t)psections[i].p_vaddr,
1089 		    (vaddr_t)psections[i].p_vaddr + psections[i].p_filesz);
1090 
1091 #ifdef DIAGNOSTIC
1092 		offset += psections[i].p_filesz;
1093 #endif
1094 	}
1095 
1096 out:
1097 	free(psections, M_TEMP, psectionslen);
1098 	return (error);
1099 }
1100 
1101 int
1102 coredump_countsegs_elf(struct proc *p, void *iocookie,
1103     struct uvm_coredump_state *us)
1104 {
1105 	struct countsegs_state *cs = us->cookie;
1106 
1107 	cs->npsections++;
1108 	return (0);
1109 }
1110 
1111 int
1112 coredump_writeseghdrs_elf(struct proc *p, void *iocookie,
1113     struct uvm_coredump_state *us)
1114 {
1115 	struct writesegs_state *ws = us->cookie;
1116 	Elf_Phdr phdr;
1117 	vsize_t size, realsize;
1118 
1119 	size = us->end - us->start;
1120 	realsize = us->realend - us->start;
1121 
1122 	phdr.p_type = PT_LOAD;
1123 	phdr.p_offset = ws->secoff;
1124 	phdr.p_vaddr = us->start;
1125 	phdr.p_paddr = 0;
1126 	phdr.p_filesz = realsize;
1127 	phdr.p_memsz = size;
1128 	phdr.p_flags = 0;
1129 	if (us->prot & PROT_READ)
1130 		phdr.p_flags |= PF_R;
1131 	if (us->prot & PROT_WRITE)
1132 		phdr.p_flags |= PF_W;
1133 	if (us->prot & PROT_EXEC)
1134 		phdr.p_flags |= PF_X;
1135 	phdr.p_align = PAGE_SIZE;
1136 
1137 	ws->secoff += phdr.p_filesz;
1138 	*ws->psections++ = phdr;
1139 
1140 	return (0);
1141 }
1142 
1143 int
1144 coredump_notes_elf(struct proc *p, void *iocookie, size_t *sizep)
1145 {
1146 	struct ps_strings pss;
1147 	struct iovec iov;
1148 	struct uio uio;
1149 	struct elfcore_procinfo cpi;
1150 	Elf_Note nhdr;
1151 	struct process *pr = p->p_p;
1152 	struct proc *q;
1153 	size_t size, notesize;
1154 	int error;
1155 
1156 	size = 0;
1157 
1158 	/* First, write an elfcore_procinfo. */
1159 	notesize = sizeof(nhdr) + elfround(sizeof("OpenBSD")) +
1160 	    elfround(sizeof(cpi));
1161 	if (iocookie) {
1162 		memset(&cpi, 0, sizeof(cpi));
1163 
1164 		cpi.cpi_version = ELFCORE_PROCINFO_VERSION;
1165 		cpi.cpi_cpisize = sizeof(cpi);
1166 		cpi.cpi_signo = p->p_sisig;
1167 		cpi.cpi_sigcode = p->p_sicode;
1168 
1169 		cpi.cpi_sigpend = p->p_siglist;
1170 		cpi.cpi_sigmask = p->p_sigmask;
1171 		cpi.cpi_sigignore = pr->ps_sigacts->ps_sigignore;
1172 		cpi.cpi_sigcatch = pr->ps_sigacts->ps_sigcatch;
1173 
1174 		cpi.cpi_pid = pr->ps_pid;
1175 		cpi.cpi_ppid = pr->ps_pptr->ps_pid;
1176 		cpi.cpi_pgrp = pr->ps_pgid;
1177 		if (pr->ps_session->s_leader)
1178 			cpi.cpi_sid = pr->ps_session->s_leader->ps_pid;
1179 		else
1180 			cpi.cpi_sid = 0;
1181 
1182 		cpi.cpi_ruid = p->p_ucred->cr_ruid;
1183 		cpi.cpi_euid = p->p_ucred->cr_uid;
1184 		cpi.cpi_svuid = p->p_ucred->cr_svuid;
1185 
1186 		cpi.cpi_rgid = p->p_ucred->cr_rgid;
1187 		cpi.cpi_egid = p->p_ucred->cr_gid;
1188 		cpi.cpi_svgid = p->p_ucred->cr_svgid;
1189 
1190 		(void)strlcpy(cpi.cpi_name, pr->ps_comm, sizeof(cpi.cpi_name));
1191 
1192 		nhdr.namesz = sizeof("OpenBSD");
1193 		nhdr.descsz = sizeof(cpi);
1194 		nhdr.type = NT_OPENBSD_PROCINFO;
1195 
1196 		error = coredump_writenote_elf(p, iocookie, &nhdr,
1197 		    "OpenBSD", &cpi);
1198 		if (error)
1199 			return (error);
1200 	}
1201 	size += notesize;
1202 
1203 	/* Second, write an NT_OPENBSD_AUXV note. */
1204 	notesize = sizeof(nhdr) + elfround(sizeof("OpenBSD")) +
1205 	    elfround(pr->ps_emul->e_arglen * sizeof(char *));
1206 	if (iocookie) {
1207 		iov.iov_base = &pss;
1208 		iov.iov_len = sizeof(pss);
1209 		uio.uio_iov = &iov;
1210 		uio.uio_iovcnt = 1;
1211 		uio.uio_offset = (off_t)pr->ps_strings;
1212 		uio.uio_resid = sizeof(pss);
1213 		uio.uio_segflg = UIO_SYSSPACE;
1214 		uio.uio_rw = UIO_READ;
1215 		uio.uio_procp = NULL;
1216 
1217 		error = uvm_io(&p->p_vmspace->vm_map, &uio, 0);
1218 		if (error)
1219 			return (error);
1220 
1221 		if (pss.ps_envstr == NULL)
1222 			return (EIO);
1223 
1224 		nhdr.namesz = sizeof("OpenBSD");
1225 		nhdr.descsz = pr->ps_emul->e_arglen * sizeof(char *);
1226 		nhdr.type = NT_OPENBSD_AUXV;
1227 
1228 		error = coredump_write(iocookie, UIO_SYSSPACE,
1229 		    &nhdr, sizeof(nhdr));
1230 		if (error)
1231 			return (error);
1232 
1233 		error = coredump_write(iocookie, UIO_SYSSPACE,
1234 		    "OpenBSD", elfround(nhdr.namesz));
1235 		if (error)
1236 			return (error);
1237 
1238 		error = coredump_write(iocookie, UIO_USERSPACE,
1239 		    pss.ps_envstr + pss.ps_nenvstr + 1, nhdr.descsz);
1240 		if (error)
1241 			return (error);
1242 	}
1243 	size += notesize;
1244 
1245 #ifdef PT_WCOOKIE
1246 	notesize = sizeof(nhdr) + elfround(sizeof("OpenBSD")) +
1247 	    elfround(sizeof(register_t));
1248 	if (iocookie) {
1249 		register_t wcookie;
1250 
1251 		nhdr.namesz = sizeof("OpenBSD");
1252 		nhdr.descsz = sizeof(register_t);
1253 		nhdr.type = NT_OPENBSD_WCOOKIE;
1254 
1255 		wcookie = process_get_wcookie(p);
1256 		error = coredump_writenote_elf(p, iocookie, &nhdr,
1257 		    "OpenBSD", &wcookie);
1258 		if (error)
1259 			return (error);
1260 	}
1261 	size += notesize;
1262 #endif
1263 
1264 	/*
1265 	 * Now write the register info for the thread that caused the
1266 	 * coredump.
1267 	 */
1268 	error = coredump_note_elf(p, iocookie, &notesize);
1269 	if (error)
1270 		return (error);
1271 	size += notesize;
1272 
1273 	/*
1274 	 * Now, for each thread, write the register info and any other
1275 	 * per-thread notes.  Since we're dumping core, all the other
1276 	 * threads in the process have been stopped and the list can't
1277 	 * change.
1278 	 */
1279 	TAILQ_FOREACH(q, &pr->ps_threads, p_thr_link) {
1280 		if (q == p)		/* we've taken care of this thread */
1281 			continue;
1282 		error = coredump_note_elf(q, iocookie, &notesize);
1283 		if (error)
1284 			return (error);
1285 		size += notesize;
1286 	}
1287 
1288 	*sizep = size;
1289 	return (0);
1290 }
1291 
1292 int
1293 coredump_note_elf(struct proc *p, void *iocookie, size_t *sizep)
1294 {
1295 	Elf_Note nhdr;
1296 	int size, notesize, error;
1297 	int namesize;
1298 	char name[64+ELFROUNDSIZE];
1299 	struct reg intreg;
1300 #ifdef PT_GETFPREGS
1301 	struct fpreg freg;
1302 #endif
1303 
1304 	size = 0;
1305 
1306 	snprintf(name, sizeof(name)-ELFROUNDSIZE, "%s@%d",
1307 	    "OpenBSD", p->p_tid + THREAD_PID_OFFSET);
1308 	namesize = strlen(name) + 1;
1309 	memset(name + namesize, 0, elfround(namesize) - namesize);
1310 
1311 	notesize = sizeof(nhdr) + elfround(namesize) + elfround(sizeof(intreg));
1312 	if (iocookie) {
1313 		error = process_read_regs(p, &intreg);
1314 		if (error)
1315 			return (error);
1316 
1317 		nhdr.namesz = namesize;
1318 		nhdr.descsz = sizeof(intreg);
1319 		nhdr.type = NT_OPENBSD_REGS;
1320 
1321 		error = coredump_writenote_elf(p, iocookie, &nhdr,
1322 		    name, &intreg);
1323 		if (error)
1324 			return (error);
1325 
1326 	}
1327 	size += notesize;
1328 
1329 #ifdef PT_GETFPREGS
1330 	notesize = sizeof(nhdr) + elfround(namesize) + elfround(sizeof(freg));
1331 	if (iocookie) {
1332 		error = process_read_fpregs(p, &freg);
1333 		if (error)
1334 			return (error);
1335 
1336 		nhdr.namesz = namesize;
1337 		nhdr.descsz = sizeof(freg);
1338 		nhdr.type = NT_OPENBSD_FPREGS;
1339 
1340 		error = coredump_writenote_elf(p, iocookie, &nhdr, name, &freg);
1341 		if (error)
1342 			return (error);
1343 	}
1344 	size += notesize;
1345 #endif
1346 
1347 	*sizep = size;
1348 	/* XXX Add hook for machdep per-LWP notes. */
1349 	return (0);
1350 }
1351 
1352 int
1353 coredump_writenote_elf(struct proc *p, void *cookie, Elf_Note *nhdr,
1354     const char *name, void *data)
1355 {
1356 	int error;
1357 
1358 	error = coredump_write(cookie, UIO_SYSSPACE, nhdr, sizeof(*nhdr));
1359 	if (error)
1360 		return error;
1361 
1362 	error = coredump_write(cookie, UIO_SYSSPACE, name,
1363 	    elfround(nhdr->namesz));
1364 	if (error)
1365 		return error;
1366 
1367 	return coredump_write(cookie, UIO_SYSSPACE, data, nhdr->descsz);
1368 }
1369 #endif /* !SMALL_KERNEL */
1370