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