xref: /openbsd-src/sys/kern/exec_elf.c (revision ae3cb403620ab940fbaabb3055fac045a63d56b7)
1 /*	$OpenBSD: exec_elf.c,v 1.142 2017/12/30 23:08:29 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/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 	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 = 0;
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 				if (flags == VMCMD_RELATIVE)
464 					epp->ep_entry += pos;
465 				ap->arg_interp = pos;
466 			}
467 			addr += size;
468 			break;
469 
470 		case PT_DYNAMIC:
471 		case PT_PHDR:
472 		case PT_NOTE:
473 			break;
474 
475 		case PT_OPENBSD_RANDOMIZE:
476 			if (ph[i].p_memsz > randomizequota) {
477 				error = ENOMEM;
478 				goto bad1;
479 			}
480 			randomizequota -= ph[i].p_memsz;
481 			NEW_VMCMD(&epp->ep_vmcmds, vmcmd_randomize,
482 			    ph[i].p_memsz, ph[i].p_vaddr + pos, NULLVP, 0, 0);
483 			break;
484 
485 		default:
486 			break;
487 		}
488 	}
489 
490 	vn_marktext(nd.ni_vp);
491 
492 bad1:
493 	VOP_CLOSE(nd.ni_vp, FREAD, p->p_ucred, p);
494 bad:
495 	free(ph, M_TEMP, phsize);
496 
497 	vput(nd.ni_vp);
498 	return (error);
499 }
500 
501 /*
502  * Prepare an Elf binary's exec package
503  *
504  * First, set of the various offsets/lengths in the exec package.
505  *
506  * Then, mark the text image busy (so it can be demand paged) or error out if
507  * this is not possible.  Finally, set up vmcmds for the text, data, bss, and
508  * stack segments.
509  */
510 int
511 exec_elf_makecmds(struct proc *p, struct exec_package *epp)
512 {
513 	Elf_Ehdr *eh = epp->ep_hdr;
514 	Elf_Phdr *ph, *pp, *base_ph = NULL;
515 	Elf_Addr phdr = 0, exe_base = 0;
516 	int error, i, has_phdr = 0;
517 	char *interp = NULL;
518 	u_long phsize;
519 	size_t randomizequota = ELF_RANDOMIZE_LIMIT;
520 
521 	if (epp->ep_hdrvalid < sizeof(Elf_Ehdr))
522 		return (ENOEXEC);
523 
524 	if (elf_check_header(eh) ||
525 	   (eh->e_type != ET_EXEC && eh->e_type != ET_DYN))
526 		return (ENOEXEC);
527 
528 	/*
529 	 * check if vnode is in open for writing, because we want to demand-
530 	 * page out of it.  if it is, don't do it, for various reasons.
531 	 */
532 	if (epp->ep_vp->v_writecount != 0) {
533 #ifdef DIAGNOSTIC
534 		if (epp->ep_vp->v_flag & VTEXT)
535 			panic("exec: a VTEXT vnode has writecount != 0");
536 #endif
537 		return (ETXTBSY);
538 	}
539 	/*
540 	 * Allocate space to hold all the program headers, and read them
541 	 * from the file
542 	 */
543 	ph = mallocarray(eh->e_phnum, sizeof(Elf_Phdr), M_TEMP, M_WAITOK);
544 	phsize = eh->e_phnum * sizeof(Elf_Phdr);
545 
546 	if ((error = elf_read_from(p, epp->ep_vp, eh->e_phoff, ph,
547 	    phsize)) != 0)
548 		goto bad;
549 
550 	epp->ep_tsize = ELF_NO_ADDR;
551 	epp->ep_dsize = ELF_NO_ADDR;
552 
553 	for (i = 0, pp = ph; i < eh->e_phnum; i++, pp++) {
554 		if (pp->p_type == PT_INTERP && !interp) {
555 			if (pp->p_filesz < 2 || pp->p_filesz > MAXPATHLEN)
556 				goto bad;
557 			interp = pool_get(&namei_pool, PR_WAITOK);
558 			if ((error = elf_read_from(p, epp->ep_vp,
559 			    pp->p_offset, interp, pp->p_filesz)) != 0) {
560 				goto bad;
561 			}
562 			if (interp[pp->p_filesz - 1] != '\0')
563 				goto bad;
564 		} else if (pp->p_type == PT_LOAD) {
565 			if (pp->p_filesz > pp->p_memsz) {
566 				error = EINVAL;
567 				goto bad;
568 			}
569 			if (base_ph == NULL)
570 				base_ph = pp;
571 		} else if (pp->p_type == PT_PHDR) {
572 			has_phdr = 1;
573 		}
574 	}
575 
576 	if (eh->e_type == ET_DYN) {
577 		/* need phdr and load sections for PIE */
578 		if (!has_phdr || base_ph == NULL) {
579 			error = EINVAL;
580 			goto bad;
581 		}
582 		/* randomize exe_base for PIE */
583 		exe_base = uvm_map_pie(base_ph->p_align);
584 	}
585 
586 	/*
587 	 * OK, we want a slightly different twist of the
588 	 * standard emulation package for "real" elf.
589 	 */
590 	epp->ep_emul = &emul_elf;
591 
592 	/*
593 	 * Verify this is an OpenBSD executable.  If it's marked that way
594 	 * via a PT_NOTE then also check for a PT_OPENBSD_WXNEEDED segment.
595 	 */
596 	if (eh->e_ident[EI_OSABI] != ELFOSABI_OPENBSD && (error =
597 	    elf_os_pt_note(p, epp, epp->ep_hdr, "OpenBSD", 8, 4)) != 0) {
598 		goto bad;
599 	}
600 
601 	/*
602 	 * Load all the necessary sections
603 	 */
604 	for (i = 0, pp = ph; i < eh->e_phnum; i++, pp++) {
605 		Elf_Addr addr, size = 0;
606 		int prot = 0;
607 		int flags = 0;
608 
609 		switch (pp->p_type) {
610 		case PT_LOAD:
611 			if (exe_base != 0) {
612 				if (pp == base_ph) {
613 					flags = VMCMD_BASE;
614 					addr = exe_base;
615 				} else {
616 					flags = VMCMD_RELATIVE;
617 					addr = pp->p_vaddr - base_ph->p_vaddr;
618 				}
619 			} else
620 				addr = ELF_NO_ADDR;
621 
622 			/*
623 			 * Calculates size of text and data segments
624 			 * by starting at first and going to end of last.
625 			 * 'rwx' sections are treated as data.
626 			 * this is correct for BSS_PLT, but may not be
627 			 * for DATA_PLT, is fine for TEXT_PLT.
628 			 */
629 			elf_load_psection(&epp->ep_vmcmds, epp->ep_vp,
630 			    pp, &addr, &size, &prot, flags);
631 
632 			/*
633 			 * Update exe_base in case alignment was off.
634 			 * For PIE, addr is relative to exe_base so
635 			 * adjust it (non PIE exe_base is 0 so no change).
636 			 */
637 			if (flags == VMCMD_BASE)
638 				exe_base = addr;
639 			else
640 				addr += exe_base;
641 
642 			/*
643 			 * Decide whether it's text or data by looking
644 			 * at the protection of the section
645 			 */
646 			if (prot & PROT_WRITE) {
647 				/* data section */
648 				if (epp->ep_dsize == ELF_NO_ADDR) {
649 					epp->ep_daddr = addr;
650 					epp->ep_dsize = size;
651 				} else {
652 					if (addr < epp->ep_daddr) {
653 						epp->ep_dsize =
654 						    epp->ep_dsize +
655 						    epp->ep_daddr -
656 						    addr;
657 						epp->ep_daddr = addr;
658 					} else
659 						epp->ep_dsize = addr+size -
660 						    epp->ep_daddr;
661 				}
662 			} else if (prot & PROT_EXEC) {
663 				/* text section */
664 				if (epp->ep_tsize == ELF_NO_ADDR) {
665 					epp->ep_taddr = addr;
666 					epp->ep_tsize = size;
667 				} else {
668 					if (addr < epp->ep_taddr) {
669 						epp->ep_tsize =
670 						    epp->ep_tsize +
671 						    epp->ep_taddr -
672 						    addr;
673 						epp->ep_taddr = addr;
674 					} else
675 						epp->ep_tsize = addr+size -
676 						    epp->ep_taddr;
677 				}
678 			}
679 			break;
680 
681 		case PT_SHLIB:
682 			error = ENOEXEC;
683 			goto bad;
684 
685 		case PT_INTERP:
686 			/* Already did this one */
687 		case PT_DYNAMIC:
688 		case PT_NOTE:
689 			break;
690 
691 		case PT_PHDR:
692 			/* Note address of program headers (in text segment) */
693 			phdr = pp->p_vaddr;
694 			break;
695 
696 		case PT_OPENBSD_RANDOMIZE:
697 			if (ph[i].p_memsz > randomizequota) {
698 				error = ENOMEM;
699 				goto bad;
700 			}
701 			randomizequota -= ph[i].p_memsz;
702 			NEW_VMCMD(&epp->ep_vmcmds, vmcmd_randomize,
703 			    ph[i].p_memsz, ph[i].p_vaddr + exe_base, NULLVP, 0, 0);
704 			break;
705 
706 		default:
707 			/*
708 			 * Not fatal, we don't need to understand everything
709 			 * :-)
710 			 */
711 			break;
712 		}
713 	}
714 
715 	phdr += exe_base;
716 
717 	/*
718 	 * Strangely some linux programs may have all load sections marked
719 	 * writeable, in this case, textsize is not -1, but rather 0;
720 	 */
721 	if (epp->ep_tsize == ELF_NO_ADDR)
722 		epp->ep_tsize = 0;
723 	/*
724 	 * Another possibility is that it has all load sections marked
725 	 * read-only.  Fake a zero-sized data segment right after the
726 	 * text segment.
727 	 */
728 	if (epp->ep_dsize == ELF_NO_ADDR) {
729 		epp->ep_daddr = round_page(epp->ep_taddr + epp->ep_tsize);
730 		epp->ep_dsize = 0;
731 	}
732 
733 	epp->ep_interp = interp;
734 	epp->ep_entry = eh->e_entry + exe_base;
735 
736 	/*
737 	 * Check if we found a dynamically linked binary and arrange to load
738 	 * its interpreter when the exec file is released.
739 	 */
740 	if (interp || eh->e_type == ET_DYN) {
741 		struct elf_args *ap;
742 
743 		ap = malloc(sizeof(*ap), M_TEMP, M_WAITOK);
744 
745 		ap->arg_phaddr = phdr;
746 		ap->arg_phentsize = eh->e_phentsize;
747 		ap->arg_phnum = eh->e_phnum;
748 		ap->arg_entry = eh->e_entry + exe_base;
749 		ap->arg_interp = exe_base;
750 
751 		epp->ep_emul_arg = ap;
752 		epp->ep_emul_argsize = sizeof *ap;
753 	}
754 
755 	free(ph, M_TEMP, phsize);
756 	vn_marktext(epp->ep_vp);
757 	return (exec_setup_stack(p, epp));
758 
759 bad:
760 	if (interp)
761 		pool_put(&namei_pool, interp);
762 	free(ph, M_TEMP, phsize);
763 	kill_vmcmds(&epp->ep_vmcmds);
764 	if (error == 0)
765 		return (ENOEXEC);
766 	return (error);
767 }
768 
769 /*
770  * Phase II of load. It is now safe to load the interpreter. Info collected
771  * when loading the program is available for setup of the interpreter.
772  */
773 int
774 exec_elf_fixup(struct proc *p, struct exec_package *epp)
775 {
776 	char	*interp;
777 	int	error = 0;
778 	struct	elf_args *ap;
779 	AuxInfo ai[ELF_AUX_ENTRIES], *a;
780 
781 	if (epp->ep_emul_arg == NULL) {
782 		return (0);
783 	}
784 
785 	interp = epp->ep_interp;
786 	ap = epp->ep_emul_arg;
787 
788 	if (interp &&
789 	    (error = elf_load_file(p, interp, epp, ap)) != 0) {
790 		free(ap, M_TEMP, epp->ep_emul_argsize);
791 		pool_put(&namei_pool, interp);
792 		kill_vmcmds(&epp->ep_vmcmds);
793 		return (error);
794 	}
795 	/*
796 	 * We have to do this ourselves...
797 	 */
798 	error = exec_process_vmcmds(p, epp);
799 
800 	/*
801 	 * Push extra arguments on the stack needed by dynamically
802 	 * linked binaries
803 	 */
804 	if (error == 0) {
805 		memset(&ai, 0, sizeof ai);
806 		a = ai;
807 
808 		a->au_id = AUX_phdr;
809 		a->au_v = ap->arg_phaddr;
810 		a++;
811 
812 		a->au_id = AUX_phent;
813 		a->au_v = ap->arg_phentsize;
814 		a++;
815 
816 		a->au_id = AUX_phnum;
817 		a->au_v = ap->arg_phnum;
818 		a++;
819 
820 		a->au_id = AUX_pagesz;
821 		a->au_v = PAGE_SIZE;
822 		a++;
823 
824 		a->au_id = AUX_base;
825 		a->au_v = ap->arg_interp;
826 		a++;
827 
828 		a->au_id = AUX_flags;
829 		a->au_v = 0;
830 		a++;
831 
832 		a->au_id = AUX_entry;
833 		a->au_v = ap->arg_entry;
834 		a++;
835 
836 		a->au_id = AUX_null;
837 		a->au_v = 0;
838 		a++;
839 
840 		error = copyout(ai, epp->ep_emul_argp, sizeof ai);
841 	}
842 	free(ap, M_TEMP, epp->ep_emul_argsize);
843 	if (interp)
844 		pool_put(&namei_pool, interp);
845 	return (error);
846 }
847 
848 int
849 elf_os_pt_note(struct proc *p, struct exec_package *epp, Elf_Ehdr *eh,
850     char *os_name, size_t name_size, size_t desc_size)
851 {
852 	char pathbuf[MAXPATHLEN];
853 	Elf_Phdr *hph, *ph;
854 	Elf_Note *np = NULL;
855 	size_t phsize;
856 	int error;
857 
858 	hph = mallocarray(eh->e_phnum, sizeof(Elf_Phdr), M_TEMP, M_WAITOK);
859 	phsize = eh->e_phnum * sizeof(Elf_Phdr);
860 	if ((error = elf_read_from(p, epp->ep_vp, eh->e_phoff,
861 	    hph, phsize)) != 0)
862 		goto out1;
863 
864 	for (ph = hph;  ph < &hph[eh->e_phnum]; ph++) {
865 		if (ph->p_type == PT_OPENBSD_WXNEEDED) {
866 			int wxallowed = (epp->ep_vp->v_mount &&
867 			    (epp->ep_vp->v_mount->mnt_flag & MNT_WXALLOWED));
868 
869 			if (!wxallowed) {
870 				error = copyinstr(epp->ep_name, &pathbuf,
871 				    sizeof(pathbuf), NULL);
872 				log(LOG_NOTICE,
873 				    "%s(%d): W^X binary outside wxallowed mountpoint\n",
874 				    error ? "" : pathbuf, p->p_p->ps_pid);
875 				error = EACCES;
876 				goto out1;
877 			}
878 			epp->ep_flags |= EXEC_WXNEEDED;
879 			break;
880 		}
881 	}
882 
883 	for (ph = hph;  ph < &hph[eh->e_phnum]; ph++) {
884 		if (ph->p_type != PT_NOTE ||
885 		    ph->p_filesz > 1024 ||
886 		    ph->p_filesz < sizeof(Elf_Note) + name_size)
887 			continue;
888 
889 		np = malloc(ph->p_filesz, M_TEMP, M_WAITOK);
890 		if ((error = elf_read_from(p, epp->ep_vp, ph->p_offset,
891 		    np, ph->p_filesz)) != 0)
892 			goto out2;
893 
894 #if 0
895 		if (np->type != ELF_NOTE_TYPE_OSVERSION) {
896 			free(np, M_TEMP, ph->p_filesz);
897 			np = NULL;
898 			continue;
899 		}
900 #endif
901 
902 		/* Check the name and description sizes. */
903 		if (np->namesz != name_size ||
904 		    np->descsz != desc_size)
905 			goto out3;
906 
907 		if (memcmp((np + 1), os_name, name_size))
908 			goto out3;
909 
910 		/* XXX: We could check for the specific emulation here */
911 		/* All checks succeeded. */
912 		error = 0;
913 		goto out2;
914 	}
915 
916 out3:
917 	error = ENOEXEC;
918 out2:
919 	free(np, M_TEMP, ph->p_filesz);
920 out1:
921 	free(hph, M_TEMP, phsize);
922 	return error;
923 }
924 
925 /*
926  * Start of routines related to dumping core
927  */
928 
929 #ifdef SMALL_KERNEL
930 int
931 coredump_elf(struct proc *p, void *cookie)
932 {
933 	return EPERM;
934 }
935 #else /* !SMALL_KERNEL */
936 
937 struct writesegs_state {
938 	off_t	notestart;
939 	off_t	secstart;
940 	off_t	secoff;
941 	struct	proc *p;
942 	void	*iocookie;
943 	Elf_Phdr *psections;
944 	size_t	psectionslen;
945 	size_t	notesize;
946 	int	npsections;
947 };
948 
949 uvm_coredump_setup_cb	coredump_setup_elf;
950 uvm_coredump_walk_cb	coredump_walk_elf;
951 
952 int	coredump_notes_elf(struct proc *, void *, size_t *);
953 int	coredump_note_elf(struct proc *, void *, size_t *);
954 int	coredump_writenote_elf(struct proc *, void *, Elf_Note *,
955 	    const char *, void *);
956 
957 #define	ELFROUNDSIZE	4	/* XXX Should it be sizeof(Elf_Word)? */
958 #define	elfround(x)	roundup((x), ELFROUNDSIZE)
959 
960 int
961 coredump_elf(struct proc *p, void *cookie)
962 {
963 #ifdef DIAGNOSTIC
964 	off_t offset;
965 #endif
966 	struct writesegs_state ws;
967 	size_t notesize;
968 	int error, i;
969 
970 	ws.p = p;
971 	ws.iocookie = cookie;
972 	ws.psections = NULL;
973 
974 	/*
975 	 * Walk the map to get all the segment offsets and lengths,
976 	 * write out the ELF header.
977 	 */
978 	error = uvm_coredump_walkmap(p, coredump_setup_elf,
979 	    coredump_walk_elf, &ws);
980 	if (error)
981 		goto out;
982 
983 	error = coredump_write(cookie, UIO_SYSSPACE, ws.psections,
984 	    ws.psectionslen);
985 	if (error)
986 		goto out;
987 
988 	/* Write out the notes. */
989 	error = coredump_notes_elf(p, cookie, &notesize);
990 	if (error)
991 		goto out;
992 
993 #ifdef DIAGNOSTIC
994 	if (notesize != ws.notesize)
995 		panic("coredump: notesize changed: %zu != %zu",
996 		    ws.notesize, notesize);
997 	offset = ws.notestart + notesize;
998 	if (offset != ws.secstart)
999 		panic("coredump: offset %lld != secstart %lld",
1000 		    (long long) offset, (long long) ws.secstart);
1001 #endif
1002 
1003 	/* Pass 3: finally, write the sections themselves. */
1004 	for (i = 0; i < ws.npsections - 1; i++) {
1005 		Elf_Phdr *pent = &ws.psections[i];
1006 		if (pent->p_filesz == 0)
1007 			continue;
1008 
1009 #ifdef DIAGNOSTIC
1010 		if (offset != pent->p_offset)
1011 			panic("coredump: offset %lld != p_offset[%d] %lld",
1012 			    (long long) offset, i,
1013 			    (long long) pent->p_filesz);
1014 #endif
1015 
1016 		error = coredump_write(cookie, UIO_USERSPACE,
1017 		    (void *)(vaddr_t)pent->p_vaddr, pent->p_filesz);
1018 		if (error)
1019 			goto out;
1020 
1021 		coredump_unmap(cookie, (vaddr_t)pent->p_vaddr,
1022 		    (vaddr_t)pent->p_vaddr + pent->p_filesz);
1023 
1024 #ifdef DIAGNOSTIC
1025 		offset += ws.psections[i].p_filesz;
1026 #endif
1027 	}
1028 
1029 out:
1030 	free(ws.psections, M_TEMP, ws.psectionslen);
1031 	return (error);
1032 }
1033 
1034 
1035 
1036 int
1037 coredump_setup_elf(int segment_count, void *cookie)
1038 {
1039 	Elf_Ehdr ehdr;
1040 	struct writesegs_state *ws = cookie;
1041 	Elf_Phdr *note;
1042 	int error;
1043 
1044 	/* Get the count of segments, plus one for the PT_NOTE */
1045 	ws->npsections = segment_count + 1;
1046 
1047 	/* Get the size of the notes. */
1048 	error = coredump_notes_elf(ws->p, NULL, &ws->notesize);
1049 	if (error)
1050 		return error;
1051 
1052 	/* Setup the ELF header */
1053 	memset(&ehdr, 0, sizeof(ehdr));
1054 	memcpy(ehdr.e_ident, ELFMAG, SELFMAG);
1055 	ehdr.e_ident[EI_CLASS] = ELF_TARG_CLASS;
1056 	ehdr.e_ident[EI_DATA] = ELF_TARG_DATA;
1057 	ehdr.e_ident[EI_VERSION] = EV_CURRENT;
1058 	/* XXX Should be the OSABI/ABI version of the executable. */
1059 	ehdr.e_ident[EI_OSABI] = ELFOSABI_SYSV;
1060 	ehdr.e_ident[EI_ABIVERSION] = 0;
1061 	ehdr.e_type = ET_CORE;
1062 	/* XXX This should be the e_machine of the executable. */
1063 	ehdr.e_machine = ELF_TARG_MACH;
1064 	ehdr.e_version = EV_CURRENT;
1065 	ehdr.e_entry = 0;
1066 	ehdr.e_phoff = sizeof(ehdr);
1067 	ehdr.e_shoff = 0;
1068 	ehdr.e_flags = 0;
1069 	ehdr.e_ehsize = sizeof(ehdr);
1070 	ehdr.e_phentsize = sizeof(Elf_Phdr);
1071 	ehdr.e_phnum = ws->npsections;
1072 	ehdr.e_shentsize = 0;
1073 	ehdr.e_shnum = 0;
1074 	ehdr.e_shstrndx = 0;
1075 
1076 	/* Write out the ELF header. */
1077 	error = coredump_write(ws->iocookie, UIO_SYSSPACE, &ehdr, sizeof(ehdr));
1078 	if (error)
1079 		return error;
1080 
1081 	/*
1082 	 * Allocate the segment header array and setup to collect
1083 	 * the section sizes and offsets
1084 	 */
1085 	ws->psections = mallocarray(ws->npsections, sizeof(Elf_Phdr),
1086 	    M_TEMP, M_WAITOK|M_ZERO);
1087 	ws->psectionslen = ws->npsections * sizeof(Elf_Phdr);
1088 
1089 	ws->notestart = sizeof(ehdr) + ws->psectionslen;
1090 	ws->secstart = ws->notestart + ws->notesize;
1091 	ws->secoff = ws->secstart;
1092 
1093 	/* Fill in the PT_NOTE segment header in the last slot */
1094 	note = &ws->psections[ws->npsections - 1];
1095 	note->p_type = PT_NOTE;
1096 	note->p_offset = ws->notestart;
1097 	note->p_vaddr = 0;
1098 	note->p_paddr = 0;
1099 	note->p_filesz = ws->notesize;
1100 	note->p_memsz = 0;
1101 	note->p_flags = PF_R;
1102 	note->p_align = ELFROUNDSIZE;
1103 
1104 	return (0);
1105 }
1106 
1107 int
1108 coredump_walk_elf(vaddr_t start, vaddr_t realend, vaddr_t end, vm_prot_t prot,
1109     int nsegment, void *cookie)
1110 {
1111 	struct writesegs_state *ws = cookie;
1112 	Elf_Phdr phdr;
1113 	vsize_t size, realsize;
1114 
1115 	size = end - start;
1116 	realsize = realend - start;
1117 
1118 	phdr.p_type = PT_LOAD;
1119 	phdr.p_offset = ws->secoff;
1120 	phdr.p_vaddr = start;
1121 	phdr.p_paddr = 0;
1122 	phdr.p_filesz = realsize;
1123 	phdr.p_memsz = size;
1124 	phdr.p_flags = 0;
1125 	if (prot & PROT_READ)
1126 		phdr.p_flags |= PF_R;
1127 	if (prot & PROT_WRITE)
1128 		phdr.p_flags |= PF_W;
1129 	if (prot & PROT_EXEC)
1130 		phdr.p_flags |= PF_X;
1131 	phdr.p_align = PAGE_SIZE;
1132 
1133 	ws->secoff += phdr.p_filesz;
1134 	ws->psections[nsegment] = phdr;
1135 
1136 	return (0);
1137 }
1138 
1139 int
1140 coredump_notes_elf(struct proc *p, void *iocookie, size_t *sizep)
1141 {
1142 	struct ps_strings pss;
1143 	struct iovec iov;
1144 	struct uio uio;
1145 	struct elfcore_procinfo cpi;
1146 	Elf_Note nhdr;
1147 	struct process *pr = p->p_p;
1148 	struct proc *q;
1149 	size_t size, notesize;
1150 	int error;
1151 
1152 	size = 0;
1153 
1154 	/* First, write an elfcore_procinfo. */
1155 	notesize = sizeof(nhdr) + elfround(sizeof("OpenBSD")) +
1156 	    elfround(sizeof(cpi));
1157 	if (iocookie) {
1158 		memset(&cpi, 0, sizeof(cpi));
1159 
1160 		cpi.cpi_version = ELFCORE_PROCINFO_VERSION;
1161 		cpi.cpi_cpisize = sizeof(cpi);
1162 		cpi.cpi_signo = p->p_sisig;
1163 		cpi.cpi_sigcode = p->p_sicode;
1164 
1165 		cpi.cpi_sigpend = p->p_siglist;
1166 		cpi.cpi_sigmask = p->p_sigmask;
1167 		cpi.cpi_sigignore = pr->ps_sigacts->ps_sigignore;
1168 		cpi.cpi_sigcatch = pr->ps_sigacts->ps_sigcatch;
1169 
1170 		cpi.cpi_pid = pr->ps_pid;
1171 		cpi.cpi_ppid = pr->ps_pptr->ps_pid;
1172 		cpi.cpi_pgrp = pr->ps_pgid;
1173 		if (pr->ps_session->s_leader)
1174 			cpi.cpi_sid = pr->ps_session->s_leader->ps_pid;
1175 		else
1176 			cpi.cpi_sid = 0;
1177 
1178 		cpi.cpi_ruid = p->p_ucred->cr_ruid;
1179 		cpi.cpi_euid = p->p_ucred->cr_uid;
1180 		cpi.cpi_svuid = p->p_ucred->cr_svuid;
1181 
1182 		cpi.cpi_rgid = p->p_ucred->cr_rgid;
1183 		cpi.cpi_egid = p->p_ucred->cr_gid;
1184 		cpi.cpi_svgid = p->p_ucred->cr_svgid;
1185 
1186 		(void)strlcpy(cpi.cpi_name, pr->ps_comm, sizeof(cpi.cpi_name));
1187 
1188 		nhdr.namesz = sizeof("OpenBSD");
1189 		nhdr.descsz = sizeof(cpi);
1190 		nhdr.type = NT_OPENBSD_PROCINFO;
1191 
1192 		error = coredump_writenote_elf(p, iocookie, &nhdr,
1193 		    "OpenBSD", &cpi);
1194 		if (error)
1195 			return (error);
1196 	}
1197 	size += notesize;
1198 
1199 	/* Second, write an NT_OPENBSD_AUXV note. */
1200 	notesize = sizeof(nhdr) + elfround(sizeof("OpenBSD")) +
1201 	    elfround(pr->ps_emul->e_arglen * sizeof(char *));
1202 	if (iocookie) {
1203 		iov.iov_base = &pss;
1204 		iov.iov_len = sizeof(pss);
1205 		uio.uio_iov = &iov;
1206 		uio.uio_iovcnt = 1;
1207 		uio.uio_offset = (off_t)pr->ps_strings;
1208 		uio.uio_resid = sizeof(pss);
1209 		uio.uio_segflg = UIO_SYSSPACE;
1210 		uio.uio_rw = UIO_READ;
1211 		uio.uio_procp = NULL;
1212 
1213 		error = uvm_io(&p->p_vmspace->vm_map, &uio, 0);
1214 		if (error)
1215 			return (error);
1216 
1217 		if (pss.ps_envstr == NULL)
1218 			return (EIO);
1219 
1220 		nhdr.namesz = sizeof("OpenBSD");
1221 		nhdr.descsz = pr->ps_emul->e_arglen * sizeof(char *);
1222 		nhdr.type = NT_OPENBSD_AUXV;
1223 
1224 		error = coredump_write(iocookie, UIO_SYSSPACE,
1225 		    &nhdr, sizeof(nhdr));
1226 		if (error)
1227 			return (error);
1228 
1229 		error = coredump_write(iocookie, UIO_SYSSPACE,
1230 		    "OpenBSD", elfround(nhdr.namesz));
1231 		if (error)
1232 			return (error);
1233 
1234 		error = coredump_write(iocookie, UIO_USERSPACE,
1235 		    pss.ps_envstr + pss.ps_nenvstr + 1, nhdr.descsz);
1236 		if (error)
1237 			return (error);
1238 	}
1239 	size += notesize;
1240 
1241 #ifdef PT_WCOOKIE
1242 	notesize = sizeof(nhdr) + elfround(sizeof("OpenBSD")) +
1243 	    elfround(sizeof(register_t));
1244 	if (iocookie) {
1245 		register_t wcookie;
1246 
1247 		nhdr.namesz = sizeof("OpenBSD");
1248 		nhdr.descsz = sizeof(register_t);
1249 		nhdr.type = NT_OPENBSD_WCOOKIE;
1250 
1251 		wcookie = process_get_wcookie(p);
1252 		error = coredump_writenote_elf(p, iocookie, &nhdr,
1253 		    "OpenBSD", &wcookie);
1254 		if (error)
1255 			return (error);
1256 	}
1257 	size += notesize;
1258 #endif
1259 
1260 	/*
1261 	 * Now write the register info for the thread that caused the
1262 	 * coredump.
1263 	 */
1264 	error = coredump_note_elf(p, iocookie, &notesize);
1265 	if (error)
1266 		return (error);
1267 	size += notesize;
1268 
1269 	/*
1270 	 * Now, for each thread, write the register info and any other
1271 	 * per-thread notes.  Since we're dumping core, all the other
1272 	 * threads in the process have been stopped and the list can't
1273 	 * change.
1274 	 */
1275 	TAILQ_FOREACH(q, &pr->ps_threads, p_thr_link) {
1276 		if (q == p)		/* we've taken care of this thread */
1277 			continue;
1278 		error = coredump_note_elf(q, iocookie, &notesize);
1279 		if (error)
1280 			return (error);
1281 		size += notesize;
1282 	}
1283 
1284 	*sizep = size;
1285 	return (0);
1286 }
1287 
1288 int
1289 coredump_note_elf(struct proc *p, void *iocookie, size_t *sizep)
1290 {
1291 	Elf_Note nhdr;
1292 	int size, notesize, error;
1293 	int namesize;
1294 	char name[64+ELFROUNDSIZE];
1295 	struct reg intreg;
1296 #ifdef PT_GETFPREGS
1297 	struct fpreg freg;
1298 #endif
1299 
1300 	size = 0;
1301 
1302 	snprintf(name, sizeof(name)-ELFROUNDSIZE, "%s@%d",
1303 	    "OpenBSD", p->p_tid + THREAD_PID_OFFSET);
1304 	namesize = strlen(name) + 1;
1305 	memset(name + namesize, 0, elfround(namesize) - namesize);
1306 
1307 	notesize = sizeof(nhdr) + elfround(namesize) + elfround(sizeof(intreg));
1308 	if (iocookie) {
1309 		error = process_read_regs(p, &intreg);
1310 		if (error)
1311 			return (error);
1312 
1313 		nhdr.namesz = namesize;
1314 		nhdr.descsz = sizeof(intreg);
1315 		nhdr.type = NT_OPENBSD_REGS;
1316 
1317 		error = coredump_writenote_elf(p, iocookie, &nhdr,
1318 		    name, &intreg);
1319 		if (error)
1320 			return (error);
1321 
1322 	}
1323 	size += notesize;
1324 
1325 #ifdef PT_GETFPREGS
1326 	notesize = sizeof(nhdr) + elfround(namesize) + elfround(sizeof(freg));
1327 	if (iocookie) {
1328 		error = process_read_fpregs(p, &freg);
1329 		if (error)
1330 			return (error);
1331 
1332 		nhdr.namesz = namesize;
1333 		nhdr.descsz = sizeof(freg);
1334 		nhdr.type = NT_OPENBSD_FPREGS;
1335 
1336 		error = coredump_writenote_elf(p, iocookie, &nhdr, name, &freg);
1337 		if (error)
1338 			return (error);
1339 	}
1340 	size += notesize;
1341 #endif
1342 
1343 	*sizep = size;
1344 	/* XXX Add hook for machdep per-LWP notes. */
1345 	return (0);
1346 }
1347 
1348 int
1349 coredump_writenote_elf(struct proc *p, void *cookie, Elf_Note *nhdr,
1350     const char *name, void *data)
1351 {
1352 	int error;
1353 
1354 	error = coredump_write(cookie, UIO_SYSSPACE, nhdr, sizeof(*nhdr));
1355 	if (error)
1356 		return error;
1357 
1358 	error = coredump_write(cookie, UIO_SYSSPACE, name,
1359 	    elfround(nhdr->namesz));
1360 	if (error)
1361 		return error;
1362 
1363 	return coredump_write(cookie, UIO_SYSSPACE, data, nhdr->descsz);
1364 }
1365 #endif /* !SMALL_KERNEL */
1366