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