xref: /freebsd/sys/kern/imgact_elf.c (revision 1073d17eeb31811958a928d7768df13f19ce1338)
1e1743d02SSøren Schmidt /*-
28a36da99SPedro F. Giffuni  * SPDX-License-Identifier: BSD-3-Clause
38a36da99SPedro F. Giffuni  *
486be94fcSTycho Nightingale  * Copyright (c) 2017 Dell EMC
5455d3589SDavid E. O'Brien  * Copyright (c) 2000-2001, 2003 David O'Brien
69a14aa01SUlrich Spörlein  * Copyright (c) 1995-1996 Søren Schmidt
7e1743d02SSøren Schmidt  * Copyright (c) 1996 Peter Wemm
8e1743d02SSøren Schmidt  * All rights reserved.
9e1743d02SSøren Schmidt  *
10e1743d02SSøren Schmidt  * Redistribution and use in source and binary forms, with or without
11e1743d02SSøren Schmidt  * modification, are permitted provided that the following conditions
12e1743d02SSøren Schmidt  * are met:
13e1743d02SSøren Schmidt  * 1. Redistributions of source code must retain the above copyright
14e1743d02SSøren Schmidt  *    notice, this list of conditions and the following disclaimer
15e1743d02SSøren Schmidt  *    in this position and unchanged.
16e1743d02SSøren Schmidt  * 2. Redistributions in binary form must reproduce the above copyright
17e1743d02SSøren Schmidt  *    notice, this list of conditions and the following disclaimer in the
18e1743d02SSøren Schmidt  *    documentation and/or other materials provided with the distribution.
19e1743d02SSøren Schmidt  * 3. The name of the author may not be used to endorse or promote products
2021dc7d4fSJens Schweikhardt  *    derived from this software without specific prior written permission
21e1743d02SSøren Schmidt  *
22e1743d02SSøren Schmidt  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
23e1743d02SSøren Schmidt  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
24e1743d02SSøren Schmidt  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
25e1743d02SSøren Schmidt  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
26e1743d02SSøren Schmidt  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
27e1743d02SSøren Schmidt  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28e1743d02SSøren Schmidt  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29e1743d02SSøren Schmidt  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30e1743d02SSøren Schmidt  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
31e1743d02SSøren Schmidt  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32e1743d02SSøren Schmidt  */
33e1743d02SSøren Schmidt 
34677b542eSDavid E. O'Brien #include <sys/cdefs.h>
35677b542eSDavid E. O'Brien __FBSDID("$FreeBSD$");
36677b542eSDavid E. O'Brien 
3712bc222eSJonathan Anderson #include "opt_capsicum.h"
3862919d78SPeter Wemm 
39e1743d02SSøren Schmidt #include <sys/param.h>
404a144410SRobert Watson #include <sys/capsicum.h>
4178f57a9cSMark Johnston #include <sys/compressor.h>
42e1743d02SSøren Schmidt #include <sys/exec.h>
438c64af4fSJohn Polstra #include <sys/fcntl.h>
44e1743d02SSøren Schmidt #include <sys/imgact.h>
45e1743d02SSøren Schmidt #include <sys/imgact_elf.h>
46b96bd95bSIan Lepore #include <sys/jail.h>
47e1743d02SSøren Schmidt #include <sys/kernel.h>
48f34fa851SJohn Baldwin #include <sys/lock.h>
49e1743d02SSøren Schmidt #include <sys/malloc.h>
5068ff2a43SChristian S.J. Peron #include <sys/mount.h>
518c64af4fSJohn Polstra #include <sys/mman.h>
52a794e791SBruce Evans #include <sys/namei.h>
538c64af4fSJohn Polstra #include <sys/pioctl.h>
54a794e791SBruce Evans #include <sys/proc.h>
558c64af4fSJohn Polstra #include <sys/procfs.h>
5686be94fcSTycho Nightingale #include <sys/ptrace.h>
571ba5ad42SEdward Tomasz Napierala #include <sys/racct.h>
588c64af4fSJohn Polstra #include <sys/resourcevar.h>
5989f6b863SAttilio Rao #include <sys/rwlock.h>
60bd390213SMikolaj Golub #include <sys/sbuf.h>
61da61b9a6SAlan Cox #include <sys/sf_buf.h>
62ee235befSKonstantin Belousov #include <sys/smp.h>
6336240ea5SDoug Rabson #include <sys/systm.h>
64e1743d02SSøren Schmidt #include <sys/signalvar.h>
658c64af4fSJohn Polstra #include <sys/stat.h>
661005a129SJohn Baldwin #include <sys/sx.h>
678c64af4fSJohn Polstra #include <sys/syscall.h>
68e1743d02SSøren Schmidt #include <sys/sysctl.h>
698c64af4fSJohn Polstra #include <sys/sysent.h>
70a794e791SBruce Evans #include <sys/vnode.h>
71e7228204SAlfred Perlstein #include <sys/syslog.h>
72e7228204SAlfred Perlstein #include <sys/eventhandler.h>
73f1fca82eSMikolaj Golub #include <sys/user.h>
74e7228204SAlfred Perlstein 
75e1743d02SSøren Schmidt #include <vm/vm.h>
76e1743d02SSøren Schmidt #include <vm/vm_kern.h>
77e1743d02SSøren Schmidt #include <vm/vm_param.h>
78e1743d02SSøren Schmidt #include <vm/pmap.h>
79e1743d02SSøren Schmidt #include <vm/vm_map.h>
800ff27d31SJohn Polstra #include <vm/vm_object.h>
81e1743d02SSøren Schmidt #include <vm/vm_extern.h>
82e1743d02SSøren Schmidt 
8352c24af7SPeter Wemm #include <machine/elf.h>
84e1743d02SSøren Schmidt #include <machine/md_var.h>
85e1743d02SSøren Schmidt 
861b8388cdSMikolaj Golub #define ELF_NOTE_ROUNDSIZE	4
87c815a20cSDavid E. O'Brien #define OLD_EI_BRAND	8
88c815a20cSDavid E. O'Brien 
893ebc1248SPeter Wemm static int __elfN(check_header)(const Elf_Ehdr *hdr);
9032c01de2SDmitry Chagin static Elf_Brandinfo *__elfN(get_brandinfo)(struct image_params *imgp,
9109c78d53SEdward Tomasz Napierala     const char *interp, int32_t *osrel, uint32_t *fctl0);
923ebc1248SPeter Wemm static int __elfN(load_file)(struct proc *p, const char *file, u_long *addr,
931699546dSEdward Tomasz Napierala     u_long *entry);
940bbee4cdSKonstantin Belousov static int __elfN(load_section)(struct image_params *imgp, vm_ooffset_t offset,
951699546dSEdward Tomasz Napierala     caddr_t vmaddr, size_t memsz, size_t filsz, vm_prot_t prot);
963ebc1248SPeter Wemm static int __CONCAT(exec_, __elfN(imgact))(struct image_params *imgp);
97a95659f7SEd Maste static bool __elfN(freebsd_trans_osrel)(const Elf_Note *note,
9889ffc202SBjoern A. Zeeb     int32_t *osrel);
99a95659f7SEd Maste static bool kfreebsd_trans_osrel(const Elf_Note *note, int32_t *osrel);
10032c01de2SDmitry Chagin static boolean_t __elfN(check_note)(struct image_params *imgp,
101cefb93f2SKonstantin Belousov     Elf_Brandnote *checknote, int32_t *osrel, uint32_t *fctl0);
102ed167eaaSKonstantin Belousov static vm_prot_t __elfN(trans_prot)(Elf_Word);
103ed167eaaSKonstantin Belousov static Elf_Word __elfN(untrans_prot)(vm_prot_t);
104e1743d02SSøren Schmidt 
105a360a43dSJake Burkholder SYSCTL_NODE(_kern, OID_AUTO, __CONCAT(elf, __ELF_WORD_SIZE), CTLFLAG_RW, 0,
106a360a43dSJake Burkholder     "");
107a360a43dSJake Burkholder 
108bd390213SMikolaj Golub #define	CORE_BUF_SIZE	(16 * 1024)
109e7228204SAlfred Perlstein 
110e548a1d4SJake Burkholder int __elfN(fallback_brand) = -1;
111e548a1d4SJake Burkholder SYSCTL_INT(__CONCAT(_kern_elf, __ELF_WORD_SIZE), OID_AUTO,
112af3b2549SHans Petter Selasky     fallback_brand, CTLFLAG_RWTUN, &__elfN(fallback_brand), 0,
113a360a43dSJake Burkholder     __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE)) " brand of last resort");
114a360a43dSJake Burkholder 
115551d79e1SMarcel Moolenaar static int elf_legacy_coredump = 0;
116a360a43dSJake Burkholder SYSCTL_INT(_debug, OID_AUTO, __elfN(legacy_coredump), CTLFLAG_RW,
1171cbb879dSEd Maste     &elf_legacy_coredump, 0,
1181cbb879dSEd Maste     "include all and only RW pages in core dumps");
119e1743d02SSøren Schmidt 
12062c625fdSKonstantin Belousov int __elfN(nxstack) =
1214d22d07aSKonstantin Belousov #if defined(__amd64__) || defined(__powerpc64__) /* both 64 and 32 bit */ || \
1224bf4b0f1SJohn Baldwin     (defined(__arm__) && __ARM_ARCH >= 7) || defined(__aarch64__) || \
1234bf4b0f1SJohn Baldwin     defined(__riscv)
12462c625fdSKonstantin Belousov 	1;
12562c625fdSKonstantin Belousov #else
12662c625fdSKonstantin Belousov 	0;
12762c625fdSKonstantin Belousov #endif
128291c06a1SKonstantin Belousov SYSCTL_INT(__CONCAT(_kern_elf, __ELF_WORD_SIZE), OID_AUTO,
129291c06a1SKonstantin Belousov     nxstack, CTLFLAG_RW, &__elfN(nxstack), 0,
130291c06a1SKonstantin Belousov     __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE)) ": enable non-executable stack");
131291c06a1SKonstantin Belousov 
132eb785fabSKonstantin Belousov #if __ELF_WORD_SIZE == 32 && (defined(__amd64__) || defined(__i386__))
133126b36a2SKonstantin Belousov int i386_read_exec = 0;
134126b36a2SKonstantin Belousov SYSCTL_INT(_kern_elf32, OID_AUTO, read_exec, CTLFLAG_RW, &i386_read_exec, 0,
135126b36a2SKonstantin Belousov     "enable execution from readable segments");
136126b36a2SKonstantin Belousov #endif
137126b36a2SKonstantin Belousov 
138fa50a355SKonstantin Belousov SYSCTL_NODE(__CONCAT(_kern_elf, __ELF_WORD_SIZE), OID_AUTO, aslr, CTLFLAG_RW, 0,
139fa50a355SKonstantin Belousov     "");
140fa50a355SKonstantin Belousov #define	ASLR_NODE_OID	__CONCAT(__CONCAT(_kern_elf, __ELF_WORD_SIZE), _aslr)
141fa50a355SKonstantin Belousov 
142fa50a355SKonstantin Belousov static int __elfN(aslr_enabled) = 0;
143fa50a355SKonstantin Belousov SYSCTL_INT(ASLR_NODE_OID, OID_AUTO, enable, CTLFLAG_RWTUN,
144fa50a355SKonstantin Belousov     &__elfN(aslr_enabled), 0,
145fa50a355SKonstantin Belousov     __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE))
146fa50a355SKonstantin Belousov     ": enable address map randomization");
147fa50a355SKonstantin Belousov 
148fa50a355SKonstantin Belousov static int __elfN(pie_aslr_enabled) = 0;
149fa50a355SKonstantin Belousov SYSCTL_INT(ASLR_NODE_OID, OID_AUTO, pie_enable, CTLFLAG_RWTUN,
150fa50a355SKonstantin Belousov     &__elfN(pie_aslr_enabled), 0,
151fa50a355SKonstantin Belousov     __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE))
152fa50a355SKonstantin Belousov     ": enable address map randomization for PIE binaries");
153fa50a355SKonstantin Belousov 
154fa50a355SKonstantin Belousov static int __elfN(aslr_honor_sbrk) = 1;
155fa50a355SKonstantin Belousov SYSCTL_INT(ASLR_NODE_OID, OID_AUTO, honor_sbrk, CTLFLAG_RW,
156fa50a355SKonstantin Belousov     &__elfN(aslr_honor_sbrk), 0,
157fa50a355SKonstantin Belousov     __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE)) ": assume sbrk is used");
158fa50a355SKonstantin Belousov 
159fc83c5a7SKonstantin Belousov static int __elfN(aslr_stack_gap) = 3;
160fc83c5a7SKonstantin Belousov SYSCTL_INT(ASLR_NODE_OID, OID_AUTO, stack_gap, CTLFLAG_RW,
161fc83c5a7SKonstantin Belousov     &__elfN(aslr_stack_gap), 0,
162fc83c5a7SKonstantin Belousov     __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE))
163fc83c5a7SKonstantin Belousov     ": maximum percentage of main stack to waste on a random gap");
164fc83c5a7SKonstantin Belousov 
1653ebc1248SPeter Wemm static Elf_Brandinfo *elf_brand_list[MAX_BRANDS];
166e1743d02SSøren Schmidt 
167545517f1SEdward Tomasz Napierala #define	aligned(a, t)	(rounddown2((u_long)(a), sizeof(t)) == (u_long)(a))
16893d1c728SKonstantin Belousov 
16932c01de2SDmitry Chagin static const char FREEBSD_ABI_VENDOR[] = "FreeBSD";
17032c01de2SDmitry Chagin 
17132c01de2SDmitry Chagin Elf_Brandnote __elfN(freebsd_brandnote) = {
17232c01de2SDmitry Chagin 	.hdr.n_namesz	= sizeof(FREEBSD_ABI_VENDOR),
17332c01de2SDmitry Chagin 	.hdr.n_descsz	= sizeof(int32_t),
1744c22b468SEd Maste 	.hdr.n_type	= NT_FREEBSD_ABI_TAG,
17532c01de2SDmitry Chagin 	.vendor		= FREEBSD_ABI_VENDOR,
17689ffc202SBjoern A. Zeeb 	.flags		= BN_TRANSLATE_OSREL,
17789ffc202SBjoern A. Zeeb 	.trans_osrel	= __elfN(freebsd_trans_osrel)
17832c01de2SDmitry Chagin };
17932c01de2SDmitry Chagin 
180a95659f7SEd Maste static bool
18189ffc202SBjoern A. Zeeb __elfN(freebsd_trans_osrel)(const Elf_Note *note, int32_t *osrel)
18289ffc202SBjoern A. Zeeb {
18389ffc202SBjoern A. Zeeb 	uintptr_t p;
18489ffc202SBjoern A. Zeeb 
18589ffc202SBjoern A. Zeeb 	p = (uintptr_t)(note + 1);
1861b8388cdSMikolaj Golub 	p += roundup2(note->n_namesz, ELF_NOTE_ROUNDSIZE);
18789ffc202SBjoern A. Zeeb 	*osrel = *(const int32_t *)(p);
18889ffc202SBjoern A. Zeeb 
189a95659f7SEd Maste 	return (true);
19089ffc202SBjoern A. Zeeb }
19189ffc202SBjoern A. Zeeb 
19289ffc202SBjoern A. Zeeb static const char GNU_ABI_VENDOR[] = "GNU";
19389ffc202SBjoern A. Zeeb static int GNU_KFREEBSD_ABI_DESC = 3;
19489ffc202SBjoern A. Zeeb 
19589ffc202SBjoern A. Zeeb Elf_Brandnote __elfN(kfreebsd_brandnote) = {
19689ffc202SBjoern A. Zeeb 	.hdr.n_namesz	= sizeof(GNU_ABI_VENDOR),
19789ffc202SBjoern A. Zeeb 	.hdr.n_descsz	= 16,	/* XXX at least 16 */
19889ffc202SBjoern A. Zeeb 	.hdr.n_type	= 1,
19989ffc202SBjoern A. Zeeb 	.vendor		= GNU_ABI_VENDOR,
20089ffc202SBjoern A. Zeeb 	.flags		= BN_TRANSLATE_OSREL,
20189ffc202SBjoern A. Zeeb 	.trans_osrel	= kfreebsd_trans_osrel
20289ffc202SBjoern A. Zeeb };
20389ffc202SBjoern A. Zeeb 
204a95659f7SEd Maste static bool
20589ffc202SBjoern A. Zeeb kfreebsd_trans_osrel(const Elf_Note *note, int32_t *osrel)
20689ffc202SBjoern A. Zeeb {
20789ffc202SBjoern A. Zeeb 	const Elf32_Word *desc;
20889ffc202SBjoern A. Zeeb 	uintptr_t p;
20989ffc202SBjoern A. Zeeb 
21089ffc202SBjoern A. Zeeb 	p = (uintptr_t)(note + 1);
2111b8388cdSMikolaj Golub 	p += roundup2(note->n_namesz, ELF_NOTE_ROUNDSIZE);
21289ffc202SBjoern A. Zeeb 
21389ffc202SBjoern A. Zeeb 	desc = (const Elf32_Word *)p;
21489ffc202SBjoern A. Zeeb 	if (desc[0] != GNU_KFREEBSD_ABI_DESC)
215a95659f7SEd Maste 		return (false);
21689ffc202SBjoern A. Zeeb 
21789ffc202SBjoern A. Zeeb 	/*
21889ffc202SBjoern A. Zeeb 	 * Debian GNU/kFreeBSD embed the earliest compatible kernel version
21989ffc202SBjoern A. Zeeb 	 * (__FreeBSD_version: <major><two digit minor>Rxx) in the LSB way.
22089ffc202SBjoern A. Zeeb 	 */
22189ffc202SBjoern A. Zeeb 	*osrel = desc[1] * 100000 + desc[2] * 1000 + desc[3];
22289ffc202SBjoern A. Zeeb 
223a95659f7SEd Maste 	return (true);
22489ffc202SBjoern A. Zeeb }
22589ffc202SBjoern A. Zeeb 
226e1743d02SSøren Schmidt int
2273ebc1248SPeter Wemm __elfN(insert_brand_entry)(Elf_Brandinfo *entry)
228e1743d02SSøren Schmidt {
229e1743d02SSøren Schmidt 	int i;
230e1743d02SSøren Schmidt 
2313ebc1248SPeter Wemm 	for (i = 0; i < MAX_BRANDS; i++) {
232ea5a2b2eSSøren Schmidt 		if (elf_brand_list[i] == NULL) {
233ea5a2b2eSSøren Schmidt 			elf_brand_list[i] = entry;
234e1743d02SSøren Schmidt 			break;
235e1743d02SSøren Schmidt 		}
236e1743d02SSøren Schmidt 	}
237925c8b5bSBjoern A. Zeeb 	if (i == MAX_BRANDS) {
238925c8b5bSBjoern A. Zeeb 		printf("WARNING: %s: could not insert brandinfo entry: %p\n",
239925c8b5bSBjoern A. Zeeb 			__func__, entry);
240a7cddfedSJake Burkholder 		return (-1);
241925c8b5bSBjoern A. Zeeb 	}
242a7cddfedSJake Burkholder 	return (0);
243e1743d02SSøren Schmidt }
244e1743d02SSøren Schmidt 
245e1743d02SSøren Schmidt int
2463ebc1248SPeter Wemm __elfN(remove_brand_entry)(Elf_Brandinfo *entry)
247e1743d02SSøren Schmidt {
248e1743d02SSøren Schmidt 	int i;
249e1743d02SSøren Schmidt 
2503ebc1248SPeter Wemm 	for (i = 0; i < MAX_BRANDS; i++) {
251ea5a2b2eSSøren Schmidt 		if (elf_brand_list[i] == entry) {
252ea5a2b2eSSøren Schmidt 			elf_brand_list[i] = NULL;
253e1743d02SSøren Schmidt 			break;
254e1743d02SSøren Schmidt 		}
255e1743d02SSøren Schmidt 	}
256ea5a2b2eSSøren Schmidt 	if (i == MAX_BRANDS)
257a7cddfedSJake Burkholder 		return (-1);
258a7cddfedSJake Burkholder 	return (0);
259e1743d02SSøren Schmidt }
260e1743d02SSøren Schmidt 
261096977faSMark Newton int
2623ebc1248SPeter Wemm __elfN(brand_inuse)(Elf_Brandinfo *entry)
263096977faSMark Newton {
264096977faSMark Newton 	struct proc *p;
265553629ebSJake Burkholder 	int rval = FALSE;
266096977faSMark Newton 
2671005a129SJohn Baldwin 	sx_slock(&allproc_lock);
2684f506694SXin LI 	FOREACH_PROC_IN_SYSTEM(p) {
269553629ebSJake Burkholder 		if (p->p_sysent == entry->sysvec) {
270553629ebSJake Burkholder 			rval = TRUE;
271553629ebSJake Burkholder 			break;
272096977faSMark Newton 		}
273553629ebSJake Burkholder 	}
2741005a129SJohn Baldwin 	sx_sunlock(&allproc_lock);
275096977faSMark Newton 
276553629ebSJake Burkholder 	return (rval);
277096977faSMark Newton }
278096977faSMark Newton 
2795fe3ed62SJake Burkholder static Elf_Brandinfo *
28032c01de2SDmitry Chagin __elfN(get_brandinfo)(struct image_params *imgp, const char *interp,
28109c78d53SEdward Tomasz Napierala     int32_t *osrel, uint32_t *fctl0)
2825fe3ed62SJake Burkholder {
28332c01de2SDmitry Chagin 	const Elf_Ehdr *hdr = (const Elf_Ehdr *)imgp->image_header;
284af582aaeSKonstantin Belousov 	Elf_Brandinfo *bi, *bi_m;
28532c01de2SDmitry Chagin 	boolean_t ret;
28609c78d53SEdward Tomasz Napierala 	int i, interp_name_len;
28709c78d53SEdward Tomasz Napierala 
288be7808dcSKonstantin Belousov 	interp_name_len = interp != NULL ? strlen(interp) + 1 : 0;
2895fe3ed62SJake Burkholder 
2905fe3ed62SJake Burkholder 	/*
29132c01de2SDmitry Chagin 	 * We support four types of branding -- (1) the ELF EI_OSABI field
2925fe3ed62SJake Burkholder 	 * that SCO added to the ELF spec, (2) FreeBSD 3.x's traditional string
29332c01de2SDmitry Chagin 	 * branding w/in the ELF header, (3) path of the `interp_path'
29432c01de2SDmitry Chagin 	 * field, and (4) the ".note.ABI-tag" ELF section.
2955fe3ed62SJake Burkholder 	 */
2965fe3ed62SJake Burkholder 
29732c01de2SDmitry Chagin 	/* Look for an ".note.ABI-tag" ELF section */
298af582aaeSKonstantin Belousov 	bi_m = NULL;
29932c01de2SDmitry Chagin 	for (i = 0; i < MAX_BRANDS; i++) {
30032c01de2SDmitry Chagin 		bi = elf_brand_list[i];
301ecc2fda8SBjoern A. Zeeb 		if (bi == NULL)
302ecc2fda8SBjoern A. Zeeb 			continue;
3032274ab3dSKonstantin Belousov 		if (interp != NULL && (bi->flags & BI_BRAND_ONLY_STATIC) != 0)
3041438fe3cSKonstantin Belousov 			continue;
305ecc2fda8SBjoern A. Zeeb 		if (hdr->e_machine == bi->machine && (bi->flags &
306ecc2fda8SBjoern A. Zeeb 		    (BI_BRAND_NOTE|BI_BRAND_NOTE_MANDATORY)) != 0) {
307cefb93f2SKonstantin Belousov 			ret = __elfN(check_note)(imgp, bi->brand_note, osrel,
308cefb93f2SKonstantin Belousov 			    fctl0);
309f19d421aSNathan Whitehorn 			/* Give brand a chance to veto check_note's guess */
310f19d421aSNathan Whitehorn 			if (ret && bi->header_supported)
311f19d421aSNathan Whitehorn 				ret = bi->header_supported(imgp);
312af582aaeSKonstantin Belousov 			/*
313af582aaeSKonstantin Belousov 			 * If note checker claimed the binary, but the
314af582aaeSKonstantin Belousov 			 * interpreter path in the image does not
315af582aaeSKonstantin Belousov 			 * match default one for the brand, try to
316af582aaeSKonstantin Belousov 			 * search for other brands with the same
317af582aaeSKonstantin Belousov 			 * interpreter.  Either there is better brand
318af582aaeSKonstantin Belousov 			 * with the right interpreter, or, failing
319af582aaeSKonstantin Belousov 			 * this, we return first brand which accepted
320af582aaeSKonstantin Belousov 			 * our note and, optionally, header.
321af582aaeSKonstantin Belousov 			 */
3223aeacc55SKonstantin Belousov 			if (ret && bi_m == NULL && interp != NULL &&
3233aeacc55SKonstantin Belousov 			    (bi->interp_path == NULL ||
3243aeacc55SKonstantin Belousov 			    (strlen(bi->interp_path) + 1 != interp_name_len ||
3253aeacc55SKonstantin Belousov 			    strncmp(interp, bi->interp_path, interp_name_len)
3263aeacc55SKonstantin Belousov 			    != 0))) {
327af582aaeSKonstantin Belousov 				bi_m = bi;
328af582aaeSKonstantin Belousov 				ret = 0;
329af582aaeSKonstantin Belousov 			}
33032c01de2SDmitry Chagin 			if (ret)
33132c01de2SDmitry Chagin 				return (bi);
33232c01de2SDmitry Chagin 		}
33332c01de2SDmitry Chagin 	}
334af582aaeSKonstantin Belousov 	if (bi_m != NULL)
335af582aaeSKonstantin Belousov 		return (bi_m);
33632c01de2SDmitry Chagin 
3375fe3ed62SJake Burkholder 	/* If the executable has a brand, search for it in the brand list. */
3385fe3ed62SJake Burkholder 	for (i = 0; i < MAX_BRANDS; i++) {
3395fe3ed62SJake Burkholder 		bi = elf_brand_list[i];
3401438fe3cSKonstantin Belousov 		if (bi == NULL || (bi->flags & BI_BRAND_NOTE_MANDATORY) != 0 ||
3412274ab3dSKonstantin Belousov 		    (interp != NULL && (bi->flags & BI_BRAND_ONLY_STATIC) != 0))
342ecc2fda8SBjoern A. Zeeb 			continue;
343ecc2fda8SBjoern A. Zeeb 		if (hdr->e_machine == bi->machine &&
3445fe3ed62SJake Burkholder 		    (hdr->e_ident[EI_OSABI] == bi->brand ||
3450fe98320SEd Schouten 		    (bi->compat_3_brand != NULL &&
3463d560b4bSKonstantin Belousov 		    strcmp((const char *)&hdr->e_ident[OLD_EI_BRAND],
3470fe98320SEd Schouten 		    bi->compat_3_brand) == 0))) {
348686d2f31SNathan Whitehorn 			/* Looks good, but give brand a chance to veto */
349d722231bSJohn Baldwin 			if (bi->header_supported == NULL ||
35015a9aedfSKonstantin Belousov 			    bi->header_supported(imgp)) {
35115a9aedfSKonstantin Belousov 				/*
35215a9aedfSKonstantin Belousov 				 * Again, prefer strictly matching
35315a9aedfSKonstantin Belousov 				 * interpreter path.
35415a9aedfSKonstantin Belousov 				 */
3557aab7a80SKonstantin Belousov 				if (interp_name_len == 0 &&
3567aab7a80SKonstantin Belousov 				    bi->interp_path == NULL)
3577aab7a80SKonstantin Belousov 					return (bi);
3587aab7a80SKonstantin Belousov 				if (bi->interp_path != NULL &&
3597aab7a80SKonstantin Belousov 				    strlen(bi->interp_path) + 1 ==
36015a9aedfSKonstantin Belousov 				    interp_name_len && strncmp(interp,
36115a9aedfSKonstantin Belousov 				    bi->interp_path, interp_name_len) == 0)
3625fe3ed62SJake Burkholder 					return (bi);
36315a9aedfSKonstantin Belousov 				if (bi_m == NULL)
36415a9aedfSKonstantin Belousov 					bi_m = bi;
3655fe3ed62SJake Burkholder 			}
366686d2f31SNathan Whitehorn 		}
36715a9aedfSKonstantin Belousov 	}
36815a9aedfSKonstantin Belousov 	if (bi_m != NULL)
36915a9aedfSKonstantin Belousov 		return (bi_m);
3705fe3ed62SJake Burkholder 
371817dc004SWarner Losh 	/* No known brand, see if the header is recognized by any brand */
372817dc004SWarner Losh 	for (i = 0; i < MAX_BRANDS; i++) {
373817dc004SWarner Losh 		bi = elf_brand_list[i];
374817dc004SWarner Losh 		if (bi == NULL || bi->flags & BI_BRAND_NOTE_MANDATORY ||
375817dc004SWarner Losh 		    bi->header_supported == NULL)
376817dc004SWarner Losh 			continue;
377817dc004SWarner Losh 		if (hdr->e_machine == bi->machine) {
378817dc004SWarner Losh 			ret = bi->header_supported(imgp);
379817dc004SWarner Losh 			if (ret)
380817dc004SWarner Losh 				return (bi);
381817dc004SWarner Losh 		}
382817dc004SWarner Losh 	}
383817dc004SWarner Losh 
3845fe3ed62SJake Burkholder 	/* Lacking a known brand, search for a recognized interpreter. */
3855fe3ed62SJake Burkholder 	if (interp != NULL) {
3865fe3ed62SJake Burkholder 		for (i = 0; i < MAX_BRANDS; i++) {
3875fe3ed62SJake Burkholder 			bi = elf_brand_list[i];
3882274ab3dSKonstantin Belousov 			if (bi == NULL || (bi->flags &
3892274ab3dSKonstantin Belousov 			    (BI_BRAND_NOTE_MANDATORY | BI_BRAND_ONLY_STATIC))
3902274ab3dSKonstantin Belousov 			    != 0)
391ecc2fda8SBjoern A. Zeeb 				continue;
392ecc2fda8SBjoern A. Zeeb 			if (hdr->e_machine == bi->machine &&
3933aeacc55SKonstantin Belousov 			    bi->interp_path != NULL &&
394d1ae5c83SKonstantin Belousov 			    /* ELF image p_filesz includes terminating zero */
395d1ae5c83SKonstantin Belousov 			    strlen(bi->interp_path) + 1 == interp_name_len &&
396d1ae5c83SKonstantin Belousov 			    strncmp(interp, bi->interp_path, interp_name_len)
397d722231bSJohn Baldwin 			    == 0 && (bi->header_supported == NULL ||
398d722231bSJohn Baldwin 			    bi->header_supported(imgp)))
3995fe3ed62SJake Burkholder 				return (bi);
4005fe3ed62SJake Burkholder 		}
4015fe3ed62SJake Burkholder 	}
4025fe3ed62SJake Burkholder 
4035fe3ed62SJake Burkholder 	/* Lacking a recognized interpreter, try the default brand */
4045fe3ed62SJake Burkholder 	for (i = 0; i < MAX_BRANDS; i++) {
4055fe3ed62SJake Burkholder 		bi = elf_brand_list[i];
4061438fe3cSKonstantin Belousov 		if (bi == NULL || (bi->flags & BI_BRAND_NOTE_MANDATORY) != 0 ||
4072274ab3dSKonstantin Belousov 		    (interp != NULL && (bi->flags & BI_BRAND_ONLY_STATIC) != 0))
408ecc2fda8SBjoern A. Zeeb 			continue;
409ecc2fda8SBjoern A. Zeeb 		if (hdr->e_machine == bi->machine &&
410d722231bSJohn Baldwin 		    __elfN(fallback_brand) == bi->brand &&
411d722231bSJohn Baldwin 		    (bi->header_supported == NULL ||
412d722231bSJohn Baldwin 		    bi->header_supported(imgp)))
4135fe3ed62SJake Burkholder 			return (bi);
4145fe3ed62SJake Burkholder 	}
4155fe3ed62SJake Burkholder 	return (NULL);
4165fe3ed62SJake Burkholder }
4175fe3ed62SJake Burkholder 
418e1743d02SSøren Schmidt static int
4193ebc1248SPeter Wemm __elfN(check_header)(const Elf_Ehdr *hdr)
420e1743d02SSøren Schmidt {
421d0ca7c29SPeter Wemm 	Elf_Brandinfo *bi;
4223ebc1248SPeter Wemm 	int i;
4233ebc1248SPeter Wemm 
42452c24af7SPeter Wemm 	if (!IS_ELF(*hdr) ||
42552c24af7SPeter Wemm 	    hdr->e_ident[EI_CLASS] != ELF_TARG_CLASS ||
42652c24af7SPeter Wemm 	    hdr->e_ident[EI_DATA] != ELF_TARG_DATA ||
4273dc19c46SJacques Vidrine 	    hdr->e_ident[EI_VERSION] != EV_CURRENT ||
4283dc19c46SJacques Vidrine 	    hdr->e_phentsize != sizeof(Elf_Phdr) ||
4293dc19c46SJacques Vidrine 	    hdr->e_version != ELF_TARG_VER)
430a7cddfedSJake Burkholder 		return (ENOEXEC);
431e1743d02SSøren Schmidt 
4323ebc1248SPeter Wemm 	/*
4333ebc1248SPeter Wemm 	 * Make sure we have at least one brand for this machine.
4343ebc1248SPeter Wemm 	 */
4353ebc1248SPeter Wemm 
4363ebc1248SPeter Wemm 	for (i = 0; i < MAX_BRANDS; i++) {
437d0ca7c29SPeter Wemm 		bi = elf_brand_list[i];
438d0ca7c29SPeter Wemm 		if (bi != NULL && bi->machine == hdr->e_machine)
4393ebc1248SPeter Wemm 			break;
4403ebc1248SPeter Wemm 	}
4413ebc1248SPeter Wemm 	if (i == MAX_BRANDS)
442a7cddfedSJake Burkholder 		return (ENOEXEC);
443e1743d02SSøren Schmidt 
444a7cddfedSJake Burkholder 	return (0);
445e1743d02SSøren Schmidt }
446e1743d02SSøren Schmidt 
447e1743d02SSøren Schmidt static int
4483ebc1248SPeter Wemm __elfN(map_partial)(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
449ff6f03c7SAlan Cox     vm_offset_t start, vm_offset_t end, vm_prot_t prot)
4503ebc1248SPeter Wemm {
451da61b9a6SAlan Cox 	struct sf_buf *sf;
452da61b9a6SAlan Cox 	int error;
4533ebc1248SPeter Wemm 	vm_offset_t off;
4543ebc1248SPeter Wemm 
4553ebc1248SPeter Wemm 	/*
4563ebc1248SPeter Wemm 	 * Create the page if it doesn't exist yet. Ignore errors.
4573ebc1248SPeter Wemm 	 */
458aaadc41fSKonstantin Belousov 	vm_map_fixed(map, NULL, 0, trunc_page(start), round_page(end) -
459aaadc41fSKonstantin Belousov 	    trunc_page(start), VM_PROT_ALL, VM_PROT_ALL, MAP_CHECK_EXCL);
4603ebc1248SPeter Wemm 
4613ebc1248SPeter Wemm 	/*
4623ebc1248SPeter Wemm 	 * Find the page from the underlying object.
4633ebc1248SPeter Wemm 	 */
46428e8da65SAlan Cox 	if (object != NULL) {
465da61b9a6SAlan Cox 		sf = vm_imgact_map_page(object, offset);
466da61b9a6SAlan Cox 		if (sf == NULL)
467da61b9a6SAlan Cox 			return (KERN_FAILURE);
4683ebc1248SPeter Wemm 		off = offset - trunc_page(offset);
469da61b9a6SAlan Cox 		error = copyout((caddr_t)sf_buf_kva(sf) + off, (caddr_t)start,
470ca0387efSJake Burkholder 		    end - start);
471be996836SAttilio Rao 		vm_imgact_unmap_page(sf);
472fe0a8a39SKonstantin Belousov 		if (error != 0)
473a7cddfedSJake Burkholder 			return (KERN_FAILURE);
4743ebc1248SPeter Wemm 	}
4753ebc1248SPeter Wemm 
476a7cddfedSJake Burkholder 	return (KERN_SUCCESS);
4773ebc1248SPeter Wemm }
4783ebc1248SPeter Wemm 
4793ebc1248SPeter Wemm static int
480e3d8f8feSKonstantin Belousov __elfN(map_insert)(struct image_params *imgp, vm_map_t map, vm_object_t object,
481e3d8f8feSKonstantin Belousov     vm_ooffset_t offset, vm_offset_t start, vm_offset_t end, vm_prot_t prot,
482e3d8f8feSKonstantin Belousov     int cow)
4833ebc1248SPeter Wemm {
484da61b9a6SAlan Cox 	struct sf_buf *sf;
485da61b9a6SAlan Cox 	vm_offset_t off;
486a063facbSMarcel Moolenaar 	vm_size_t sz;
487e3d8f8feSKonstantin Belousov 	int error, locked, rv;
4883ebc1248SPeter Wemm 
4893ebc1248SPeter Wemm 	if (start != trunc_page(start)) {
49081f223caSJake Burkholder 		rv = __elfN(map_partial)(map, object, offset, start,
491ff6f03c7SAlan Cox 		    round_page(start), prot);
49228e8da65SAlan Cox 		if (rv != KERN_SUCCESS)
493a7cddfedSJake Burkholder 			return (rv);
4943ebc1248SPeter Wemm 		offset += round_page(start) - start;
4953ebc1248SPeter Wemm 		start = round_page(start);
4963ebc1248SPeter Wemm 	}
4973ebc1248SPeter Wemm 	if (end != round_page(end)) {
49881f223caSJake Burkholder 		rv = __elfN(map_partial)(map, object, offset +
499ff6f03c7SAlan Cox 		    trunc_page(end) - start, trunc_page(end), end, prot);
50028e8da65SAlan Cox 		if (rv != KERN_SUCCESS)
501a7cddfedSJake Burkholder 			return (rv);
5023ebc1248SPeter Wemm 		end = trunc_page(end);
5033ebc1248SPeter Wemm 	}
504e383e820SAlan Cox 	if (start >= end)
505e383e820SAlan Cox 		return (KERN_SUCCESS);
506e383e820SAlan Cox 	if ((offset & PAGE_MASK) != 0) {
5073ebc1248SPeter Wemm 		/*
508e383e820SAlan Cox 		 * The mapping is not page aligned.  This means that we have
509e383e820SAlan Cox 		 * to copy the data.
5103ebc1248SPeter Wemm 		 */
511aaadc41fSKonstantin Belousov 		rv = vm_map_fixed(map, NULL, 0, start, end - start,
512aaadc41fSKonstantin Belousov 		    prot | VM_PROT_WRITE, VM_PROT_ALL, MAP_CHECK_EXCL);
5135420f76bSKonstantin Belousov 		if (rv != KERN_SUCCESS)
514a7cddfedSJake Burkholder 			return (rv);
515da61b9a6SAlan Cox 		if (object == NULL)
516da61b9a6SAlan Cox 			return (KERN_SUCCESS);
517da61b9a6SAlan Cox 		for (; start < end; start += sz) {
518da61b9a6SAlan Cox 			sf = vm_imgact_map_page(object, offset);
519da61b9a6SAlan Cox 			if (sf == NULL)
520da61b9a6SAlan Cox 				return (KERN_FAILURE);
5213ebc1248SPeter Wemm 			off = offset - trunc_page(offset);
5223ebc1248SPeter Wemm 			sz = end - start;
523da61b9a6SAlan Cox 			if (sz > PAGE_SIZE - off)
524da61b9a6SAlan Cox 				sz = PAGE_SIZE - off;
525da61b9a6SAlan Cox 			error = copyout((caddr_t)sf_buf_kva(sf) + off,
5263ebc1248SPeter Wemm 			    (caddr_t)start, sz);
527be996836SAttilio Rao 			vm_imgact_unmap_page(sf);
5285420f76bSKonstantin Belousov 			if (error != 0)
529a7cddfedSJake Burkholder 				return (KERN_FAILURE);
530da61b9a6SAlan Cox 			offset += sz;
5313ebc1248SPeter Wemm 		}
5323ebc1248SPeter Wemm 	} else {
533e5e6093bSAlan Cox 		vm_object_reference(object);
534e383e820SAlan Cox 		rv = vm_map_fixed(map, object, offset, start, end - start,
53578022527SKonstantin Belousov 		    prot, VM_PROT_ALL, cow | MAP_CHECK_EXCL |
53678022527SKonstantin Belousov 		    (object != NULL ? MAP_VN_EXEC : 0));
537e3d8f8feSKonstantin Belousov 		if (rv != KERN_SUCCESS) {
538e3d8f8feSKonstantin Belousov 			locked = VOP_ISLOCKED(imgp->vp);
539e3d8f8feSKonstantin Belousov 			VOP_UNLOCK(imgp->vp, 0);
540e5e6093bSAlan Cox 			vm_object_deallocate(object);
541e3d8f8feSKonstantin Belousov 			vn_lock(imgp->vp, locked | LK_RETRY);
542a7cddfedSJake Burkholder 			return (rv);
54378022527SKonstantin Belousov 		} else if (object != NULL) {
54478022527SKonstantin Belousov 			MPASS(imgp->vp->v_object == object);
54578022527SKonstantin Belousov 			VOP_SET_TEXT_CHECKED(imgp->vp);
5463ebc1248SPeter Wemm 		}
5473ebc1248SPeter Wemm 	}
548e383e820SAlan Cox 	return (KERN_SUCCESS);
549e383e820SAlan Cox }
5503ebc1248SPeter Wemm 
5513ebc1248SPeter Wemm static int
5520bbee4cdSKonstantin Belousov __elfN(load_section)(struct image_params *imgp, vm_ooffset_t offset,
5531699546dSEdward Tomasz Napierala     caddr_t vmaddr, size_t memsz, size_t filsz, vm_prot_t prot)
554e1743d02SSøren Schmidt {
555da61b9a6SAlan Cox 	struct sf_buf *sf;
556e1743d02SSøren Schmidt 	size_t map_len;
557292177e6SAlan Cox 	vm_map_t map;
558292177e6SAlan Cox 	vm_object_t object;
559e020a35fSMark Johnston 	vm_offset_t map_addr;
560fa7dd9c5SMatthew Dillon 	int error, rv, cow;
561e1743d02SSøren Schmidt 	size_t copy_len;
5620bbee4cdSKonstantin Belousov 	vm_ooffset_t file_addr;
56352c24af7SPeter Wemm 
56425ead034SBrian Feldman 	/*
56525ead034SBrian Feldman 	 * It's necessary to fail if the filsz + offset taken from the
56625ead034SBrian Feldman 	 * header is greater than the actual file pager object's size.
56725ead034SBrian Feldman 	 * If we were to allow this, then the vm_map_find() below would
56825ead034SBrian Feldman 	 * walk right off the end of the file object and into the ether.
56925ead034SBrian Feldman 	 *
57025ead034SBrian Feldman 	 * While I'm here, might as well check for something else that
57125ead034SBrian Feldman 	 * is invalid: filsz cannot be greater than memsz.
57225ead034SBrian Feldman 	 */
5739bcf2f2dSKonstantin Belousov 	if ((filsz != 0 && (off_t)filsz + offset > imgp->attr->va_size) ||
5749bcf2f2dSKonstantin Belousov 	    filsz > memsz) {
57525ead034SBrian Feldman 		uprintf("elf_load_section: truncated ELF file\n");
57625ead034SBrian Feldman 		return (ENOEXEC);
57725ead034SBrian Feldman 	}
57825ead034SBrian Feldman 
579292177e6SAlan Cox 	object = imgp->object;
580292177e6SAlan Cox 	map = &imgp->proc->p_vmspace->vm_map;
581545517f1SEdward Tomasz Napierala 	map_addr = trunc_page((vm_offset_t)vmaddr);
582545517f1SEdward Tomasz Napierala 	file_addr = trunc_page(offset);
583e1743d02SSøren Schmidt 
584e1743d02SSøren Schmidt 	/*
58552c24af7SPeter Wemm 	 * We have two choices.  We can either clear the data in the last page
58652c24af7SPeter Wemm 	 * of an oversized mapping, or we can start the anon mapping a page
58752c24af7SPeter Wemm 	 * early and copy the initialized data into that first page.  We
58828e8da65SAlan Cox 	 * choose the second.
58952c24af7SPeter Wemm 	 */
5909bcf2f2dSKonstantin Belousov 	if (filsz == 0)
5919bcf2f2dSKonstantin Belousov 		map_len = 0;
5929bcf2f2dSKonstantin Belousov 	else if (memsz > filsz)
593545517f1SEdward Tomasz Napierala 		map_len = trunc_page(offset + filsz) - file_addr;
59452c24af7SPeter Wemm 	else
595545517f1SEdward Tomasz Napierala 		map_len = round_page(offset + filsz) - file_addr;
59652c24af7SPeter Wemm 
59752c24af7SPeter Wemm 	if (map_len != 0) {
598fa7dd9c5SMatthew Dillon 		/* cow flags: don't dump readonly sections in core */
599fa7dd9c5SMatthew Dillon 		cow = MAP_COPY_ON_WRITE | MAP_PREFAULT |
600fa7dd9c5SMatthew Dillon 		    (prot & VM_PROT_WRITE ? 0 : MAP_DISABLE_COREDUMP);
601fa7dd9c5SMatthew Dillon 
60278022527SKonstantin Belousov 		rv = __elfN(map_insert)(imgp, map, object, file_addr,
60378022527SKonstantin Belousov 		    map_addr, map_addr + map_len, prot, cow);
604e5e6093bSAlan Cox 		if (rv != KERN_SUCCESS)
605a7cddfedSJake Burkholder 			return (EINVAL);
60652c24af7SPeter Wemm 
60752c24af7SPeter Wemm 		/* we can stop now if we've covered it all */
608973d67c4SKonstantin Belousov 		if (memsz == filsz)
609a7cddfedSJake Burkholder 			return (0);
61052c24af7SPeter Wemm 	}
61152c24af7SPeter Wemm 
61252c24af7SPeter Wemm 
61352c24af7SPeter Wemm 	/*
61452c24af7SPeter Wemm 	 * We have to get the remaining bit of the file into the first part
61552c24af7SPeter Wemm 	 * of the oversized map segment.  This is normally because the .data
61652c24af7SPeter Wemm 	 * segment in the file is extended to provide bss.  It's a neat idea
61752c24af7SPeter Wemm 	 * to try and save a page, but it's a pain in the behind to implement.
618e1743d02SSøren Schmidt 	 */
619545517f1SEdward Tomasz Napierala 	copy_len = filsz == 0 ? 0 : (offset + filsz) - trunc_page(offset +
620545517f1SEdward Tomasz Napierala 	    filsz);
621545517f1SEdward Tomasz Napierala 	map_addr = trunc_page((vm_offset_t)vmaddr + filsz);
622545517f1SEdward Tomasz Napierala 	map_len = round_page((vm_offset_t)vmaddr + memsz) - map_addr;
623e1743d02SSøren Schmidt 
62452c24af7SPeter Wemm 	/* This had damn well better be true! */
6258191d577SPeter Wemm 	if (map_len != 0) {
626e3d8f8feSKonstantin Belousov 		rv = __elfN(map_insert)(imgp, map, NULL, 0, map_addr,
627c547cbb4SAlan Cox 		    map_addr + map_len, prot, 0);
628973d67c4SKonstantin Belousov 		if (rv != KERN_SUCCESS)
629a7cddfedSJake Burkholder 			return (EINVAL);
6308191d577SPeter Wemm 	}
631e1743d02SSøren Schmidt 
63252c24af7SPeter Wemm 	if (copy_len != 0) {
633da61b9a6SAlan Cox 		sf = vm_imgact_map_page(object, offset + filsz);
634da61b9a6SAlan Cox 		if (sf == NULL)
635da61b9a6SAlan Cox 			return (EIO);
636e1743d02SSøren Schmidt 
63752c24af7SPeter Wemm 		/* send the page fragment to user space */
638e020a35fSMark Johnston 		error = copyout((caddr_t)sf_buf_kva(sf), (caddr_t)map_addr,
639e020a35fSMark Johnston 		    copy_len);
640be996836SAttilio Rao 		vm_imgact_unmap_page(sf);
641973d67c4SKonstantin Belousov 		if (error != 0)
64252c24af7SPeter Wemm 			return (error);
64352c24af7SPeter Wemm 	}
644e1743d02SSøren Schmidt 
645e1743d02SSøren Schmidt 	/*
646c547cbb4SAlan Cox 	 * Remove write access to the page if it was only granted by map_insert
647c547cbb4SAlan Cox 	 * to allow copyout.
648e1743d02SSøren Schmidt 	 */
649c547cbb4SAlan Cox 	if ((prot & VM_PROT_WRITE) == 0)
650292177e6SAlan Cox 		vm_map_protect(map, trunc_page(map_addr), round_page(map_addr +
651292177e6SAlan Cox 		    map_len), prot, FALSE);
6528191d577SPeter Wemm 
653ff6f03c7SAlan Cox 	return (0);
654e1743d02SSøren Schmidt }
655e1743d02SSøren Schmidt 
6569bcd7482SEdward Tomasz Napierala static int
6579bcd7482SEdward Tomasz Napierala __elfN(load_sections)(struct image_params *imgp, const Elf_Ehdr *hdr,
6589bcd7482SEdward Tomasz Napierala     const Elf_Phdr *phdr, u_long rbase, u_long *base_addrp)
6599bcd7482SEdward Tomasz Napierala {
6609bcd7482SEdward Tomasz Napierala 	vm_prot_t prot;
6619bcd7482SEdward Tomasz Napierala 	u_long base_addr;
6629bcd7482SEdward Tomasz Napierala 	bool first;
6639bcd7482SEdward Tomasz Napierala 	int error, i;
6649bcd7482SEdward Tomasz Napierala 
665b65ca345SEdward Tomasz Napierala 	ASSERT_VOP_LOCKED(imgp->vp, __func__);
666b65ca345SEdward Tomasz Napierala 
6679bcd7482SEdward Tomasz Napierala 	base_addr = 0;
6689bcd7482SEdward Tomasz Napierala 	first = true;
6699bcd7482SEdward Tomasz Napierala 
6709bcd7482SEdward Tomasz Napierala 	for (i = 0; i < hdr->e_phnum; i++) {
6719bcd7482SEdward Tomasz Napierala 		if (phdr[i].p_type != PT_LOAD || phdr[i].p_memsz == 0)
6729bcd7482SEdward Tomasz Napierala 			continue;
6739bcd7482SEdward Tomasz Napierala 
6749bcd7482SEdward Tomasz Napierala 		/* Loadable segment */
6759bcd7482SEdward Tomasz Napierala 		prot = __elfN(trans_prot)(phdr[i].p_flags);
6769bcd7482SEdward Tomasz Napierala 		error = __elfN(load_section)(imgp, phdr[i].p_offset,
6779bcd7482SEdward Tomasz Napierala 		    (caddr_t)(uintptr_t)phdr[i].p_vaddr + rbase,
6789bcd7482SEdward Tomasz Napierala 		    phdr[i].p_memsz, phdr[i].p_filesz, prot);
6799bcd7482SEdward Tomasz Napierala 		if (error != 0)
6809bcd7482SEdward Tomasz Napierala 			return (error);
6819bcd7482SEdward Tomasz Napierala 
6829bcd7482SEdward Tomasz Napierala 		/*
6839bcd7482SEdward Tomasz Napierala 		 * Establish the base address if this is the first segment.
6849bcd7482SEdward Tomasz Napierala 		 */
6859bcd7482SEdward Tomasz Napierala 		if (first) {
6869bcd7482SEdward Tomasz Napierala   			base_addr = trunc_page(phdr[i].p_vaddr + rbase);
6879bcd7482SEdward Tomasz Napierala 			first = false;
6889bcd7482SEdward Tomasz Napierala 		}
6899bcd7482SEdward Tomasz Napierala 	}
6909bcd7482SEdward Tomasz Napierala 
6919bcd7482SEdward Tomasz Napierala 	if (base_addrp != NULL)
6929bcd7482SEdward Tomasz Napierala 		*base_addrp = base_addr;
6939bcd7482SEdward Tomasz Napierala 
6949bcd7482SEdward Tomasz Napierala 	return (0);
6959bcd7482SEdward Tomasz Napierala }
6969bcd7482SEdward Tomasz Napierala 
697c33fe779SJohn Polstra /*
698c33fe779SJohn Polstra  * Load the file "file" into memory.  It may be either a shared object
699c33fe779SJohn Polstra  * or an executable.
700c33fe779SJohn Polstra  *
701c33fe779SJohn Polstra  * The "addr" reference parameter is in/out.  On entry, it specifies
702c33fe779SJohn Polstra  * the address where a shared object should be loaded.  If the file is
703c33fe779SJohn Polstra  * an executable, this value is ignored.  On exit, "addr" specifies
704c33fe779SJohn Polstra  * where the file was actually loaded.
705c33fe779SJohn Polstra  *
706c33fe779SJohn Polstra  * The "entry" reference parameter is out only.  On exit, it specifies
707c33fe779SJohn Polstra  * the entry point for the loaded file.
708c33fe779SJohn Polstra  */
709e1743d02SSøren Schmidt static int
7103ebc1248SPeter Wemm __elfN(load_file)(struct proc *p, const char *file, u_long *addr,
7111699546dSEdward Tomasz Napierala 	u_long *entry)
712e1743d02SSøren Schmidt {
713911c2be0SMark Peek 	struct {
714911c2be0SMark Peek 		struct nameidata nd;
715911c2be0SMark Peek 		struct vattr attr;
716911c2be0SMark Peek 		struct image_params image_params;
717911c2be0SMark Peek 	} *tempdata;
718d254af07SMatthew Dillon 	const Elf_Ehdr *hdr = NULL;
719d254af07SMatthew Dillon 	const Elf_Phdr *phdr = NULL;
720911c2be0SMark Peek 	struct nameidata *nd;
721911c2be0SMark Peek 	struct vattr *attr;
722911c2be0SMark Peek 	struct image_params *imgp;
72378022527SKonstantin Belousov 	u_long rbase;
724c33fe779SJohn Polstra 	u_long base_addr = 0;
7259bcd7482SEdward Tomasz Napierala 	int error;
726e1743d02SSøren Schmidt 
72712bc222eSJonathan Anderson #ifdef CAPABILITY_MODE
72812bc222eSJonathan Anderson 	/*
72912bc222eSJonathan Anderson 	 * XXXJA: This check can go away once we are sufficiently confident
73012bc222eSJonathan Anderson 	 * that the checks in namei() are correct.
73112bc222eSJonathan Anderson 	 */
73212bc222eSJonathan Anderson 	if (IN_CAPABILITY_MODE(curthread))
73312bc222eSJonathan Anderson 		return (ECAPMODE);
73412bc222eSJonathan Anderson #endif
73512bc222eSJonathan Anderson 
736*1073d17eSKonstantin Belousov 	tempdata = malloc(sizeof(*tempdata), M_TEMP, M_WAITOK | M_ZERO);
737911c2be0SMark Peek 	nd = &tempdata->nd;
738911c2be0SMark Peek 	attr = &tempdata->attr;
739911c2be0SMark Peek 	imgp = &tempdata->image_params;
740911c2be0SMark Peek 
741c8a79999SPeter Wemm 	/*
742c8a79999SPeter Wemm 	 * Initialize part of the common data
743c8a79999SPeter Wemm 	 */
744c8a79999SPeter Wemm 	imgp->proc = p;
745911c2be0SMark Peek 	imgp->attr = attr;
746c8a79999SPeter Wemm 
747f422bc30SJohn Baldwin 	NDINIT(nd, LOOKUP, ISOPEN | FOLLOW | LOCKSHARED | LOCKLEAF,
748f422bc30SJohn Baldwin 	    UIO_SYSSPACE, file, curthread);
749911c2be0SMark Peek 	if ((error = namei(nd)) != 0) {
750911c2be0SMark Peek 		nd->ni_vp = NULL;
751e1743d02SSøren Schmidt 		goto fail;
752e1743d02SSøren Schmidt 	}
753911c2be0SMark Peek 	NDFREE(nd, NDF_ONLY_PNBUF);
754911c2be0SMark Peek 	imgp->vp = nd->ni_vp;
755c8a79999SPeter Wemm 
756e1743d02SSøren Schmidt 	/*
757e1743d02SSøren Schmidt 	 * Check permissions, modes, uid, etc on the file, and "open" it.
758e1743d02SSøren Schmidt 	 */
759c8a79999SPeter Wemm 	error = exec_check_permissions(imgp);
760373d1a3fSAlan Cox 	if (error)
761c8a79999SPeter Wemm 		goto fail;
762e1743d02SSøren Schmidt 
763c8a79999SPeter Wemm 	error = exec_map_first_page(imgp);
764373d1a3fSAlan Cox 	if (error)
765373d1a3fSAlan Cox 		goto fail;
766373d1a3fSAlan Cox 
7678516dd18SPoul-Henning Kamp 	imgp->object = nd->ni_vp->v_object;
768e1743d02SSøren Schmidt 
769d254af07SMatthew Dillon 	hdr = (const Elf_Ehdr *)imgp->image_header;
7703ebc1248SPeter Wemm 	if ((error = __elfN(check_header)(hdr)) != 0)
771e1743d02SSøren Schmidt 		goto fail;
772c33fe779SJohn Polstra 	if (hdr->e_type == ET_DYN)
773c33fe779SJohn Polstra 		rbase = *addr;
774c33fe779SJohn Polstra 	else if (hdr->e_type == ET_EXEC)
775c33fe779SJohn Polstra 		rbase = 0;
776c33fe779SJohn Polstra 	else {
777c33fe779SJohn Polstra 		error = ENOEXEC;
778c33fe779SJohn Polstra 		goto fail;
779c33fe779SJohn Polstra 	}
780e1743d02SSøren Schmidt 
781c8a79999SPeter Wemm 	/* Only support headers that fit within first page for now      */
78252c24af7SPeter Wemm 	if ((hdr->e_phoff > PAGE_SIZE) ||
783d19d5bf4STijl Coosemans 	    (u_int)hdr->e_phentsize * hdr->e_phnum > PAGE_SIZE - hdr->e_phoff) {
784c8a79999SPeter Wemm 		error = ENOEXEC;
785e1743d02SSøren Schmidt 		goto fail;
786c8a79999SPeter Wemm 	}
787c8a79999SPeter Wemm 
788d254af07SMatthew Dillon 	phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
78993d1c728SKonstantin Belousov 	if (!aligned(phdr, Elf_Addr)) {
79093d1c728SKonstantin Belousov 		error = ENOEXEC;
79193d1c728SKonstantin Belousov 		goto fail;
79293d1c728SKonstantin Belousov 	}
793e1743d02SSøren Schmidt 
7949bcd7482SEdward Tomasz Napierala 	error = __elfN(load_sections)(imgp, hdr, phdr, rbase, &base_addr);
795292177e6SAlan Cox 	if (error != 0)
796e1743d02SSøren Schmidt 		goto fail;
7979bcd7482SEdward Tomasz Napierala 
798c33fe779SJohn Polstra 	*addr = base_addr;
799c33fe779SJohn Polstra 	*entry = (unsigned long)hdr->e_entry + rbase;
800e1743d02SSøren Schmidt 
801e1743d02SSøren Schmidt fail:
802c8a79999SPeter Wemm 	if (imgp->firstpage)
803c8a79999SPeter Wemm 		exec_unmap_first_page(imgp);
8040b2ed1aeSJeff Roberson 
80578022527SKonstantin Belousov 	if (nd->ni_vp) {
80678022527SKonstantin Belousov 		if (imgp->textset)
80778022527SKonstantin Belousov 			VOP_UNSET_TEXT_CHECKED(nd->ni_vp);
808373d1a3fSAlan Cox 		vput(nd->ni_vp);
80978022527SKonstantin Belousov 	}
810911c2be0SMark Peek 	free(tempdata, M_TEMP);
811e1743d02SSøren Schmidt 
812a7cddfedSJake Burkholder 	return (error);
813e1743d02SSøren Schmidt }
814e1743d02SSøren Schmidt 
815fa50a355SKonstantin Belousov static u_long
816fa50a355SKonstantin Belousov __CONCAT(rnd_, __elfN(base))(vm_map_t map __unused, u_long minv, u_long maxv,
817fa50a355SKonstantin Belousov     u_int align)
818fa50a355SKonstantin Belousov {
819fa50a355SKonstantin Belousov 	u_long rbase, res;
820fa50a355SKonstantin Belousov 
821fa50a355SKonstantin Belousov 	MPASS(vm_map_min(map) <= minv);
822fa50a355SKonstantin Belousov 	MPASS(maxv <= vm_map_max(map));
823fa50a355SKonstantin Belousov 	MPASS(minv < maxv);
824fa50a355SKonstantin Belousov 	MPASS(minv + align < maxv);
825fa50a355SKonstantin Belousov 	arc4rand(&rbase, sizeof(rbase), 0);
826fa50a355SKonstantin Belousov 	res = roundup(minv, (u_long)align) + rbase % (maxv - minv);
827fa50a355SKonstantin Belousov 	res &= ~((u_long)align - 1);
828fa50a355SKonstantin Belousov 	if (res >= maxv)
829fa50a355SKonstantin Belousov 		res -= align;
830fa50a355SKonstantin Belousov 	KASSERT(res >= minv,
831fa50a355SKonstantin Belousov 	    ("res %#lx < minv %#lx, maxv %#lx rbase %#lx",
832fa50a355SKonstantin Belousov 	    res, minv, maxv, rbase));
833fa50a355SKonstantin Belousov 	KASSERT(res < maxv,
834fa50a355SKonstantin Belousov 	    ("res %#lx > maxv %#lx, minv %#lx rbase %#lx",
835fa50a355SKonstantin Belousov 	    res, maxv, minv, rbase));
836fa50a355SKonstantin Belousov 	return (res);
837fa50a355SKonstantin Belousov }
838fa50a355SKonstantin Belousov 
83920e1174aSEdward Tomasz Napierala static int
84020e1174aSEdward Tomasz Napierala __elfN(enforce_limits)(struct image_params *imgp, const Elf_Ehdr *hdr,
84120e1174aSEdward Tomasz Napierala     const Elf_Phdr *phdr, u_long et_dyn_addr)
84220e1174aSEdward Tomasz Napierala {
84320e1174aSEdward Tomasz Napierala 	struct vmspace *vmspace;
84420e1174aSEdward Tomasz Napierala 	const char *err_str;
84520e1174aSEdward Tomasz Napierala 	u_long text_size, data_size, total_size, text_addr, data_addr;
84620e1174aSEdward Tomasz Napierala 	u_long seg_size, seg_addr;
84720e1174aSEdward Tomasz Napierala 	int i;
84820e1174aSEdward Tomasz Napierala 
84920e1174aSEdward Tomasz Napierala 	err_str = NULL;
85020e1174aSEdward Tomasz Napierala 	text_size = data_size = total_size = text_addr = data_addr = 0;
85120e1174aSEdward Tomasz Napierala 
85220e1174aSEdward Tomasz Napierala 	for (i = 0; i < hdr->e_phnum; i++) {
85320e1174aSEdward Tomasz Napierala 		if (phdr[i].p_type != PT_LOAD || phdr[i].p_memsz == 0)
85420e1174aSEdward Tomasz Napierala 			continue;
85520e1174aSEdward Tomasz Napierala 
85620e1174aSEdward Tomasz Napierala 		seg_addr = trunc_page(phdr[i].p_vaddr + et_dyn_addr);
85720e1174aSEdward Tomasz Napierala 		seg_size = round_page(phdr[i].p_memsz +
85820e1174aSEdward Tomasz Napierala 		    phdr[i].p_vaddr + et_dyn_addr - seg_addr);
85920e1174aSEdward Tomasz Napierala 
86020e1174aSEdward Tomasz Napierala 		/*
86120e1174aSEdward Tomasz Napierala 		 * Make the largest executable segment the official
86220e1174aSEdward Tomasz Napierala 		 * text segment and all others data.
86320e1174aSEdward Tomasz Napierala 		 *
86420e1174aSEdward Tomasz Napierala 		 * Note that obreak() assumes that data_addr + data_size == end
86520e1174aSEdward Tomasz Napierala 		 * of data load area, and the ELF file format expects segments
86620e1174aSEdward Tomasz Napierala 		 * to be sorted by address.  If multiple data segments exist,
86720e1174aSEdward Tomasz Napierala 		 * the last one will be used.
86820e1174aSEdward Tomasz Napierala 		 */
86920e1174aSEdward Tomasz Napierala 
87020e1174aSEdward Tomasz Napierala 		if ((phdr[i].p_flags & PF_X) != 0 && text_size < seg_size) {
87120e1174aSEdward Tomasz Napierala 			text_size = seg_size;
87220e1174aSEdward Tomasz Napierala 			text_addr = seg_addr;
87320e1174aSEdward Tomasz Napierala 		} else {
87420e1174aSEdward Tomasz Napierala 			data_size = seg_size;
87520e1174aSEdward Tomasz Napierala 			data_addr = seg_addr;
87620e1174aSEdward Tomasz Napierala 		}
87720e1174aSEdward Tomasz Napierala 		total_size += seg_size;
87820e1174aSEdward Tomasz Napierala 	}
87920e1174aSEdward Tomasz Napierala 
88020e1174aSEdward Tomasz Napierala 	if (data_addr == 0 && data_size == 0) {
88120e1174aSEdward Tomasz Napierala 		data_addr = text_addr;
88220e1174aSEdward Tomasz Napierala 		data_size = text_size;
88320e1174aSEdward Tomasz Napierala 	}
88420e1174aSEdward Tomasz Napierala 
88520e1174aSEdward Tomasz Napierala 	/*
88620e1174aSEdward Tomasz Napierala 	 * Check limits.  It should be safe to check the
88720e1174aSEdward Tomasz Napierala 	 * limits after loading the segments since we do
88820e1174aSEdward Tomasz Napierala 	 * not actually fault in all the segments pages.
88920e1174aSEdward Tomasz Napierala 	 */
89020e1174aSEdward Tomasz Napierala 	PROC_LOCK(imgp->proc);
89120e1174aSEdward Tomasz Napierala 	if (data_size > lim_cur_proc(imgp->proc, RLIMIT_DATA))
89220e1174aSEdward Tomasz Napierala 		err_str = "Data segment size exceeds process limit";
89320e1174aSEdward Tomasz Napierala 	else if (text_size > maxtsiz)
89420e1174aSEdward Tomasz Napierala 		err_str = "Text segment size exceeds system limit";
89520e1174aSEdward Tomasz Napierala 	else if (total_size > lim_cur_proc(imgp->proc, RLIMIT_VMEM))
89620e1174aSEdward Tomasz Napierala 		err_str = "Total segment size exceeds process limit";
89720e1174aSEdward Tomasz Napierala 	else if (racct_set(imgp->proc, RACCT_DATA, data_size) != 0)
89820e1174aSEdward Tomasz Napierala 		err_str = "Data segment size exceeds resource limit";
89920e1174aSEdward Tomasz Napierala 	else if (racct_set(imgp->proc, RACCT_VMEM, total_size) != 0)
90020e1174aSEdward Tomasz Napierala 		err_str = "Total segment size exceeds resource limit";
90120e1174aSEdward Tomasz Napierala 	PROC_UNLOCK(imgp->proc);
90220e1174aSEdward Tomasz Napierala 	if (err_str != NULL) {
90320e1174aSEdward Tomasz Napierala 		uprintf("%s\n", err_str);
90420e1174aSEdward Tomasz Napierala 		return (ENOMEM);
90520e1174aSEdward Tomasz Napierala 	}
90620e1174aSEdward Tomasz Napierala 
90720e1174aSEdward Tomasz Napierala 	vmspace = imgp->proc->p_vmspace;
90820e1174aSEdward Tomasz Napierala 	vmspace->vm_tsize = text_size >> PAGE_SHIFT;
90920e1174aSEdward Tomasz Napierala 	vmspace->vm_taddr = (caddr_t)(uintptr_t)text_addr;
91020e1174aSEdward Tomasz Napierala 	vmspace->vm_dsize = data_size >> PAGE_SHIFT;
91120e1174aSEdward Tomasz Napierala 	vmspace->vm_daddr = (caddr_t)(uintptr_t)data_addr;
91220e1174aSEdward Tomasz Napierala 
91320e1174aSEdward Tomasz Napierala 	return (0);
91420e1174aSEdward Tomasz Napierala }
91520e1174aSEdward Tomasz Napierala 
91609c78d53SEdward Tomasz Napierala static int
91709c78d53SEdward Tomasz Napierala __elfN(get_interp)(struct image_params *imgp, const Elf_Phdr *phdr,
91809c78d53SEdward Tomasz Napierala     char **interpp, bool *free_interpp)
91909c78d53SEdward Tomasz Napierala {
92009c78d53SEdward Tomasz Napierala 	struct thread *td;
92109c78d53SEdward Tomasz Napierala 	char *interp;
92209c78d53SEdward Tomasz Napierala 	int error, interp_name_len;
92309c78d53SEdward Tomasz Napierala 
92409c78d53SEdward Tomasz Napierala 	KASSERT(phdr->p_type == PT_INTERP,
92509c78d53SEdward Tomasz Napierala 	    ("%s: p_type %u != PT_INTERP", __func__, phdr->p_type));
926b65ca345SEdward Tomasz Napierala 	ASSERT_VOP_LOCKED(imgp->vp, __func__);
92709c78d53SEdward Tomasz Napierala 
92809c78d53SEdward Tomasz Napierala 	td = curthread;
92909c78d53SEdward Tomasz Napierala 
93009c78d53SEdward Tomasz Napierala 	/* Path to interpreter */
93109c78d53SEdward Tomasz Napierala 	if (phdr->p_filesz < 2 || phdr->p_filesz > MAXPATHLEN) {
93209c78d53SEdward Tomasz Napierala 		uprintf("Invalid PT_INTERP\n");
93309c78d53SEdward Tomasz Napierala 		return (ENOEXEC);
93409c78d53SEdward Tomasz Napierala 	}
93509c78d53SEdward Tomasz Napierala 
93609c78d53SEdward Tomasz Napierala 	interp_name_len = phdr->p_filesz;
93709c78d53SEdward Tomasz Napierala 	if (phdr->p_offset > PAGE_SIZE ||
93809c78d53SEdward Tomasz Napierala 	    interp_name_len > PAGE_SIZE - phdr->p_offset) {
9390ddfdc60SKonstantin Belousov 		/*
940f1f81d3bSKonstantin Belousov 		 * The vnode lock might be needed by the pagedaemon to
9410ddfdc60SKonstantin Belousov 		 * clean pages owned by the vnode.  Do not allow sleep
9420ddfdc60SKonstantin Belousov 		 * waiting for memory with the vnode locked, instead
9430ddfdc60SKonstantin Belousov 		 * try non-sleepable allocation first, and if it
9440ddfdc60SKonstantin Belousov 		 * fails, go to the slow path were we drop the lock
945f1f81d3bSKonstantin Belousov 		 * and do M_WAITOK.  A text reference prevents
946f1f81d3bSKonstantin Belousov 		 * modifications to the vnode content.
9470ddfdc60SKonstantin Belousov 		 */
9482d6b8546SKonstantin Belousov 		interp = malloc(interp_name_len + 1, M_TEMP, M_NOWAIT);
9492d6b8546SKonstantin Belousov 		if (interp == NULL) {
95009c78d53SEdward Tomasz Napierala 			VOP_UNLOCK(imgp->vp, 0);
95109c78d53SEdward Tomasz Napierala 			interp = malloc(interp_name_len + 1, M_TEMP, M_WAITOK);
95278022527SKonstantin Belousov 			vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
9532d6b8546SKonstantin Belousov 		}
9540ddfdc60SKonstantin Belousov 
95509c78d53SEdward Tomasz Napierala 		error = vn_rdwr(UIO_READ, imgp->vp, interp,
95609c78d53SEdward Tomasz Napierala 		    interp_name_len, phdr->p_offset,
95709c78d53SEdward Tomasz Napierala 		    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred,
95809c78d53SEdward Tomasz Napierala 		    NOCRED, NULL, td);
95909c78d53SEdward Tomasz Napierala 		if (error != 0) {
96009c78d53SEdward Tomasz Napierala 			free(interp, M_TEMP);
96109c78d53SEdward Tomasz Napierala 			uprintf("i/o error PT_INTERP %d\n", error);
96209c78d53SEdward Tomasz Napierala 			return (error);
96309c78d53SEdward Tomasz Napierala 		}
96409c78d53SEdward Tomasz Napierala 		interp[interp_name_len] = '\0';
96509c78d53SEdward Tomasz Napierala 
96609c78d53SEdward Tomasz Napierala 		*interpp = interp;
96709c78d53SEdward Tomasz Napierala 		*free_interpp = true;
96809c78d53SEdward Tomasz Napierala 		return (0);
96909c78d53SEdward Tomasz Napierala 	}
97009c78d53SEdward Tomasz Napierala 
97109c78d53SEdward Tomasz Napierala 	interp = __DECONST(char *, imgp->image_header) + phdr->p_offset;
97209c78d53SEdward Tomasz Napierala 	if (interp[interp_name_len - 1] != '\0') {
97309c78d53SEdward Tomasz Napierala 		uprintf("Invalid PT_INTERP\n");
97409c78d53SEdward Tomasz Napierala 		return (ENOEXEC);
97509c78d53SEdward Tomasz Napierala 	}
97609c78d53SEdward Tomasz Napierala 
97709c78d53SEdward Tomasz Napierala 	*interpp = interp;
97809c78d53SEdward Tomasz Napierala 	*free_interpp = false;
97909c78d53SEdward Tomasz Napierala 	return (0);
98009c78d53SEdward Tomasz Napierala }
98109c78d53SEdward Tomasz Napierala 
9829274fb35SEdward Tomasz Napierala static int
9839274fb35SEdward Tomasz Napierala __elfN(load_interp)(struct image_params *imgp, const Elf_Brandinfo *brand_info,
9849274fb35SEdward Tomasz Napierala     const char *interp, u_long *addr, u_long *entry)
9859274fb35SEdward Tomasz Napierala {
9869274fb35SEdward Tomasz Napierala 	char *path;
9879274fb35SEdward Tomasz Napierala 	int error;
9889274fb35SEdward Tomasz Napierala 
9899274fb35SEdward Tomasz Napierala 	if (brand_info->emul_path != NULL &&
9909274fb35SEdward Tomasz Napierala 	    brand_info->emul_path[0] != '\0') {
9919274fb35SEdward Tomasz Napierala 		path = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
9929274fb35SEdward Tomasz Napierala 		snprintf(path, MAXPATHLEN, "%s%s",
9939274fb35SEdward Tomasz Napierala 		    brand_info->emul_path, interp);
9949274fb35SEdward Tomasz Napierala 		error = __elfN(load_file)(imgp->proc, path, addr, entry);
9959274fb35SEdward Tomasz Napierala 		free(path, M_TEMP);
9969274fb35SEdward Tomasz Napierala 		if (error == 0)
9979274fb35SEdward Tomasz Napierala 			return (0);
9989274fb35SEdward Tomasz Napierala 	}
9999274fb35SEdward Tomasz Napierala 
10009274fb35SEdward Tomasz Napierala 	if (brand_info->interp_newpath != NULL &&
10019274fb35SEdward Tomasz Napierala 	    (brand_info->interp_path == NULL ||
10029274fb35SEdward Tomasz Napierala 	    strcmp(interp, brand_info->interp_path) == 0)) {
10039274fb35SEdward Tomasz Napierala 		error = __elfN(load_file)(imgp->proc,
10049274fb35SEdward Tomasz Napierala 		    brand_info->interp_newpath, addr, entry);
10059274fb35SEdward Tomasz Napierala 		if (error == 0)
10069274fb35SEdward Tomasz Napierala 			return (0);
10079274fb35SEdward Tomasz Napierala 	}
10089274fb35SEdward Tomasz Napierala 
10099274fb35SEdward Tomasz Napierala 	error = __elfN(load_file)(imgp->proc, interp, addr, entry);
10109274fb35SEdward Tomasz Napierala 	if (error == 0)
10119274fb35SEdward Tomasz Napierala 		return (0);
10129274fb35SEdward Tomasz Napierala 
10139274fb35SEdward Tomasz Napierala 	uprintf("ELF interpreter %s not found, error %d\n", interp, error);
10149274fb35SEdward Tomasz Napierala 	return (error);
10159274fb35SEdward Tomasz Napierala }
10169274fb35SEdward Tomasz Napierala 
1017fa50a355SKonstantin Belousov /*
1018fa50a355SKonstantin Belousov  * Impossible et_dyn_addr initial value indicating that the real base
1019fa50a355SKonstantin Belousov  * must be calculated later with some randomization applied.
1020fa50a355SKonstantin Belousov  */
1021fa50a355SKonstantin Belousov #define	ET_DYN_ADDR_RAND	1
1022fa50a355SKonstantin Belousov 
1023303b270bSEivind Eklund static int
10243ebc1248SPeter Wemm __CONCAT(exec_, __elfN(imgact))(struct image_params *imgp)
1025e1743d02SSøren Schmidt {
10266c775eb6SKonstantin Belousov 	struct thread *td;
10276c775eb6SKonstantin Belousov 	const Elf_Ehdr *hdr;
102832c01de2SDmitry Chagin 	const Elf_Phdr *phdr;
1029e5e6093bSAlan Cox 	Elf_Auxargs *elf_auxargs;
10305856e12eSJohn Dyson 	struct vmspace *vmspace;
1031fa50a355SKonstantin Belousov 	vm_map_t map;
10329274fb35SEdward Tomasz Napierala 	char *interp;
1033d1dbc694SJohn Polstra 	Elf_Brandinfo *brand_info;
10345fe3ed62SJake Burkholder 	struct sysentvec *sv;
103520e1174aSEdward Tomasz Napierala 	u_long addr, baddr, et_dyn_addr, entry, proghdr;
1036fa50a355SKonstantin Belousov 	u_long maxalign, mapsz, maxv, maxv1;
1037cefb93f2SKonstantin Belousov 	uint32_t fctl0;
10386c775eb6SKonstantin Belousov 	int32_t osrel;
103909c78d53SEdward Tomasz Napierala 	bool free_interp;
10409274fb35SEdward Tomasz Napierala 	int error, i, n;
10416c775eb6SKonstantin Belousov 
10426c775eb6SKonstantin Belousov 	hdr = (const Elf_Ehdr *)imgp->image_header;
1043e1743d02SSøren Schmidt 
1044e1743d02SSøren Schmidt 	/*
1045e1743d02SSøren Schmidt 	 * Do we have a valid ELF header ?
1046900b28f9SMaxim Sobolev 	 *
1047900b28f9SMaxim Sobolev 	 * Only allow ET_EXEC & ET_DYN here, reject ET_DYN later
1048900b28f9SMaxim Sobolev 	 * if particular brand doesn't support it.
1049e1743d02SSøren Schmidt 	 */
1050900b28f9SMaxim Sobolev 	if (__elfN(check_header)(hdr) != 0 ||
1051900b28f9SMaxim Sobolev 	    (hdr->e_type != ET_EXEC && hdr->e_type != ET_DYN))
1052a7cddfedSJake Burkholder 		return (-1);
1053e1743d02SSøren Schmidt 
1054e1743d02SSøren Schmidt 	/*
1055e1743d02SSøren Schmidt 	 * From here on down, we return an errno, not -1, as we've
1056e1743d02SSøren Schmidt 	 * detected an ELF file.
1057e1743d02SSøren Schmidt 	 */
1058e1743d02SSøren Schmidt 
1059e1743d02SSøren Schmidt 	if ((hdr->e_phoff > PAGE_SIZE) ||
1060d19d5bf4STijl Coosemans 	    (u_int)hdr->e_phentsize * hdr->e_phnum > PAGE_SIZE - hdr->e_phoff) {
1061c8a79999SPeter Wemm 		/* Only support headers in first page for now */
10626b16d664SEd Maste 		uprintf("Program headers not in the first page\n");
1063a7cddfedSJake Burkholder 		return (ENOEXEC);
1064e1743d02SSøren Schmidt 	}
106552c24af7SPeter Wemm 	phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
10666b16d664SEd Maste 	if (!aligned(phdr, Elf_Addr)) {
10676b16d664SEd Maste 		uprintf("Unaligned program headers\n");
106893d1c728SKonstantin Belousov 		return (ENOEXEC);
10696b16d664SEd Maste 	}
10706c775eb6SKonstantin Belousov 
10716c775eb6SKonstantin Belousov 	n = error = 0;
10727564c4adSKonstantin Belousov 	baddr = 0;
10736c775eb6SKonstantin Belousov 	osrel = 0;
1074cefb93f2SKonstantin Belousov 	fctl0 = 0;
10756c775eb6SKonstantin Belousov 	entry = proghdr = 0;
10769274fb35SEdward Tomasz Napierala 	interp = NULL;
107709c78d53SEdward Tomasz Napierala 	free_interp = false;
10786c775eb6SKonstantin Belousov 	td = curthread;
1079fa50a355SKonstantin Belousov 	maxalign = PAGE_SIZE;
1080fa50a355SKonstantin Belousov 	mapsz = 0;
10816c775eb6SKonstantin Belousov 
10825fe3ed62SJake Burkholder 	for (i = 0; i < hdr->e_phnum; i++) {
1083291c06a1SKonstantin Belousov 		switch (phdr[i].p_type) {
1084291c06a1SKonstantin Belousov 		case PT_LOAD:
10857564c4adSKonstantin Belousov 			if (n == 0)
10867564c4adSKonstantin Belousov 				baddr = phdr[i].p_vaddr;
1087fa50a355SKonstantin Belousov 			if (phdr[i].p_align > maxalign)
1088fa50a355SKonstantin Belousov 				maxalign = phdr[i].p_align;
1089fa50a355SKonstantin Belousov 			mapsz += phdr[i].p_memsz;
10907564c4adSKonstantin Belousov 			n++;
10919bcd7482SEdward Tomasz Napierala 
10929bcd7482SEdward Tomasz Napierala 			/*
10939bcd7482SEdward Tomasz Napierala 			 * If this segment contains the program headers,
10949bcd7482SEdward Tomasz Napierala 			 * remember their virtual address for the AT_PHDR
10959bcd7482SEdward Tomasz Napierala 			 * aux entry. Static binaries don't usually include
10969bcd7482SEdward Tomasz Napierala 			 * a PT_PHDR entry.
10979bcd7482SEdward Tomasz Napierala 			 */
10989bcd7482SEdward Tomasz Napierala 			if (phdr[i].p_offset == 0 &&
10999bcd7482SEdward Tomasz Napierala 			    hdr->e_phoff + hdr->e_phnum * hdr->e_phentsize
11009bcd7482SEdward Tomasz Napierala 				<= phdr[i].p_filesz)
11019bcd7482SEdward Tomasz Napierala 				proghdr = phdr[i].p_vaddr + hdr->e_phoff;
1102291c06a1SKonstantin Belousov 			break;
1103291c06a1SKonstantin Belousov 		case PT_INTERP:
1104e5e6093bSAlan Cox 			/* Path to interpreter */
1105d3ee0a15SJonathan T. Looney 			if (interp != NULL) {
1106d3ee0a15SJonathan T. Looney 				uprintf("Multiple PT_INTERP headers\n");
1107d3ee0a15SJonathan T. Looney 				error = ENOEXEC;
1108d3ee0a15SJonathan T. Looney 				goto ret;
1109d3ee0a15SJonathan T. Looney 			}
111009c78d53SEdward Tomasz Napierala 			error = __elfN(get_interp)(imgp, &phdr[i], &interp,
111109c78d53SEdward Tomasz Napierala 			    &free_interp);
111209c78d53SEdward Tomasz Napierala 			if (error != 0)
11136c775eb6SKonstantin Belousov 				goto ret;
1114291c06a1SKonstantin Belousov 			break;
1115291c06a1SKonstantin Belousov 		case PT_GNU_STACK:
1116291c06a1SKonstantin Belousov 			if (__elfN(nxstack))
1117291c06a1SKonstantin Belousov 				imgp->stack_prot =
1118291c06a1SKonstantin Belousov 				    __elfN(trans_prot)(phdr[i].p_flags);
1119316b3843SKonstantin Belousov 			imgp->stack_sz = phdr[i].p_memsz;
1120291c06a1SKonstantin Belousov 			break;
11219bcd7482SEdward Tomasz Napierala 		case PT_PHDR: 	/* Program header table info */
11229bcd7482SEdward Tomasz Napierala 			proghdr = phdr[i].p_vaddr;
11239bcd7482SEdward Tomasz Napierala 			break;
11243ebc1248SPeter Wemm 		}
11253ebc1248SPeter Wemm 	}
11263ebc1248SPeter Wemm 
112709c78d53SEdward Tomasz Napierala 	brand_info = __elfN(get_brandinfo)(imgp, interp, &osrel, &fctl0);
11285fe3ed62SJake Burkholder 	if (brand_info == NULL) {
11295fe3ed62SJake Burkholder 		uprintf("ELF binary type \"%u\" not known.\n",
11305fe3ed62SJake Burkholder 		    hdr->e_ident[EI_OSABI]);
11316c775eb6SKonstantin Belousov 		error = ENOEXEC;
11326c775eb6SKonstantin Belousov 		goto ret;
11333ebc1248SPeter Wemm 	}
1134fa50a355SKonstantin Belousov 	sv = brand_info->sysvec;
113577ebe276SEd Maste 	et_dyn_addr = 0;
1136ab02d85fSKonstantin Belousov 	if (hdr->e_type == ET_DYN) {
11376b16d664SEd Maste 		if ((brand_info->flags & BI_CAN_EXEC_DYN) == 0) {
11386b16d664SEd Maste 			uprintf("Cannot execute shared object\n");
11396c775eb6SKonstantin Belousov 			error = ENOEXEC;
11406c775eb6SKonstantin Belousov 			goto ret;
11416b16d664SEd Maste 		}
11427564c4adSKonstantin Belousov 		/*
11437564c4adSKonstantin Belousov 		 * Honour the base load address from the dso if it is
11447564c4adSKonstantin Belousov 		 * non-zero for some reason.
11457564c4adSKonstantin Belousov 		 */
1146fa50a355SKonstantin Belousov 		if (baddr == 0) {
1147fa50a355SKonstantin Belousov 			if ((sv->sv_flags & SV_ASLR) == 0 ||
1148fa50a355SKonstantin Belousov 			    (fctl0 & NT_FREEBSD_FCTL_ASLR_DISABLE) != 0)
1149fa50a355SKonstantin Belousov 				et_dyn_addr = ET_DYN_LOAD_ADDR;
1150fa50a355SKonstantin Belousov 			else if ((__elfN(pie_aslr_enabled) &&
1151fa50a355SKonstantin Belousov 			    (imgp->proc->p_flag2 & P2_ASLR_DISABLE) == 0) ||
1152fa50a355SKonstantin Belousov 			    (imgp->proc->p_flag2 & P2_ASLR_ENABLE) != 0)
1153fa50a355SKonstantin Belousov 				et_dyn_addr = ET_DYN_ADDR_RAND;
1154fa50a355SKonstantin Belousov 			else
1155ab02d85fSKonstantin Belousov 				et_dyn_addr = ET_DYN_LOAD_ADDR;
115677ebe276SEd Maste 		}
1157fa50a355SKonstantin Belousov 	}
11583ebc1248SPeter Wemm 
115960bb3943SAlan Cox 	/*
116060bb3943SAlan Cox 	 * Avoid a possible deadlock if the current address space is destroyed
116160bb3943SAlan Cox 	 * and that address space maps the locked vnode.  In the common case,
116260bb3943SAlan Cox 	 * the locked vnode's v_usecount is decremented but remains greater
116360bb3943SAlan Cox 	 * than zero.  Consequently, the vnode lock is not needed by vrele().
116460bb3943SAlan Cox 	 * However, in cases where the vnode lock is external, such as nullfs,
116560bb3943SAlan Cox 	 * v_usecount may become zero.
11661dfab802SAlan Cox 	 *
11671dfab802SAlan Cox 	 * The VV_TEXT flag prevents modifications to the executable while
11681dfab802SAlan Cox 	 * the vnode is unlocked.
116960bb3943SAlan Cox 	 */
117022db15c0SAttilio Rao 	VOP_UNLOCK(imgp->vp, 0);
117160bb3943SAlan Cox 
1172fa50a355SKonstantin Belousov 	/*
1173fa50a355SKonstantin Belousov 	 * Decide whether to enable randomization of user mappings.
1174fa50a355SKonstantin Belousov 	 * First, reset user preferences for the setid binaries.
1175fa50a355SKonstantin Belousov 	 * Then, account for the support of the randomization by the
1176fa50a355SKonstantin Belousov 	 * ABI, by user preferences, and make special treatment for
1177fa50a355SKonstantin Belousov 	 * PIE binaries.
1178fa50a355SKonstantin Belousov 	 */
1179fa50a355SKonstantin Belousov 	if (imgp->credential_setid) {
1180fa50a355SKonstantin Belousov 		PROC_LOCK(imgp->proc);
1181fa50a355SKonstantin Belousov 		imgp->proc->p_flag2 &= ~(P2_ASLR_ENABLE | P2_ASLR_DISABLE);
1182fa50a355SKonstantin Belousov 		PROC_UNLOCK(imgp->proc);
1183fa50a355SKonstantin Belousov 	}
1184fa50a355SKonstantin Belousov 	if ((sv->sv_flags & SV_ASLR) == 0 ||
1185fa50a355SKonstantin Belousov 	    (imgp->proc->p_flag2 & P2_ASLR_DISABLE) != 0 ||
1186fa50a355SKonstantin Belousov 	    (fctl0 & NT_FREEBSD_FCTL_ASLR_DISABLE) != 0) {
1187fa50a355SKonstantin Belousov 		KASSERT(et_dyn_addr != ET_DYN_ADDR_RAND,
1188fa50a355SKonstantin Belousov 		    ("et_dyn_addr == RAND and !ASLR"));
1189fa50a355SKonstantin Belousov 	} else if ((imgp->proc->p_flag2 & P2_ASLR_ENABLE) != 0 ||
1190fa50a355SKonstantin Belousov 	    (__elfN(aslr_enabled) && hdr->e_type == ET_EXEC) ||
1191fa50a355SKonstantin Belousov 	    et_dyn_addr == ET_DYN_ADDR_RAND) {
1192fa50a355SKonstantin Belousov 		imgp->map_flags |= MAP_ASLR;
1193fa50a355SKonstantin Belousov 		/*
1194fa50a355SKonstantin Belousov 		 * If user does not care about sbrk, utilize the bss
1195fa50a355SKonstantin Belousov 		 * grow region for mappings as well.  We can select
1196fa50a355SKonstantin Belousov 		 * the base for the image anywere and still not suffer
1197fa50a355SKonstantin Belousov 		 * from the fragmentation.
1198fa50a355SKonstantin Belousov 		 */
1199fa50a355SKonstantin Belousov 		if (!__elfN(aslr_honor_sbrk) ||
1200fa50a355SKonstantin Belousov 		    (imgp->proc->p_flag2 & P2_ASLR_IGNSTART) != 0)
1201fa50a355SKonstantin Belousov 			imgp->map_flags |= MAP_ASLR_IGNSTART;
1202fa50a355SKonstantin Belousov 	}
1203fa50a355SKonstantin Belousov 
120489b57fcfSKonstantin Belousov 	error = exec_new_vmspace(imgp, sv);
1205fa50a355SKonstantin Belousov 	vmspace = imgp->proc->p_vmspace;
1206fa50a355SKonstantin Belousov 	map = &vmspace->vm_map;
1207fa50a355SKonstantin Belousov 
120819059a13SJohn Baldwin 	imgp->proc->p_sysent = sv;
1209e1743d02SSøren Schmidt 
1210fa50a355SKonstantin Belousov 	maxv = vm_map_max(map) - lim_max(td, RLIMIT_STACK);
1211fa50a355SKonstantin Belousov 	if (et_dyn_addr == ET_DYN_ADDR_RAND) {
1212fa50a355SKonstantin Belousov 		KASSERT((map->flags & MAP_ASLR) != 0,
1213fa50a355SKonstantin Belousov 		    ("ET_DYN_ADDR_RAND but !MAP_ASLR"));
1214fa50a355SKonstantin Belousov 		et_dyn_addr = __CONCAT(rnd_, __elfN(base))(map,
1215fa50a355SKonstantin Belousov 		    vm_map_min(map) + mapsz + lim_max(td, RLIMIT_DATA),
1216fa50a355SKonstantin Belousov 		    /* reserve half of the address space to interpreter */
1217fa50a355SKonstantin Belousov 		    maxv / 2, 1UL << flsl(maxalign));
1218fa50a355SKonstantin Belousov 	}
1219fa50a355SKonstantin Belousov 
122078022527SKonstantin Belousov 	vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
12216c775eb6SKonstantin Belousov 	if (error != 0)
12226c775eb6SKonstantin Belousov 		goto ret;
122360bb3943SAlan Cox 
12249bcd7482SEdward Tomasz Napierala 	error = __elfN(load_sections)(imgp, hdr, phdr, et_dyn_addr, NULL);
1225292177e6SAlan Cox 	if (error != 0)
12266c775eb6SKonstantin Belousov 		goto ret;
1227e1743d02SSøren Schmidt 
122820e1174aSEdward Tomasz Napierala 	error = __elfN(enforce_limits)(imgp, hdr, phdr, et_dyn_addr);
122920e1174aSEdward Tomasz Napierala 	if (error != 0)
123020e1174aSEdward Tomasz Napierala 		goto ret;
1231cac45152SMatthew Dillon 
1232920acedbSNathan Whitehorn 	entry = (u_long)hdr->e_entry + et_dyn_addr;
1233920acedbSNathan Whitehorn 
1234cac45152SMatthew Dillon 	/*
1235c460ac3aSPeter Wemm 	 * We load the dynamic linker where a userland call
1236c460ac3aSPeter Wemm 	 * to mmap(0, ...) would put it.  The rationale behind this
1237c460ac3aSPeter Wemm 	 * calculation is that it leaves room for the heap to grow to
1238c460ac3aSPeter Wemm 	 * its maximum allowed size.
1239c460ac3aSPeter Wemm 	 */
12406c775eb6SKonstantin Belousov 	addr = round_page((vm_offset_t)vmspace->vm_daddr + lim_max(td,
1241292177e6SAlan Cox 	    RLIMIT_DATA));
1242fa50a355SKonstantin Belousov 	if ((map->flags & MAP_ASLR) != 0) {
1243fa50a355SKonstantin Belousov 		maxv1 = maxv / 2 + addr / 2;
1244fa50a355SKonstantin Belousov 		MPASS(maxv1 >= addr);	/* No overflow */
1245fa50a355SKonstantin Belousov 		map->anon_loc = __CONCAT(rnd_, __elfN(base))(map, addr, maxv1,
1246fa50a355SKonstantin Belousov 		    MAXPAGESIZES > 1 ? pagesizes[1] : pagesizes[0]);
1247fa50a355SKonstantin Belousov 	} else {
1248fa50a355SKonstantin Belousov 		map->anon_loc = addr;
1249fa50a355SKonstantin Belousov 	}
1250e1743d02SSøren Schmidt 
1251ea5a2b2eSSøren Schmidt 	imgp->entry_addr = entry;
1252ea5a2b2eSSøren Schmidt 
125360bb3943SAlan Cox 	if (interp != NULL) {
125422db15c0SAttilio Rao 		VOP_UNLOCK(imgp->vp, 0);
1255fa50a355SKonstantin Belousov 		if ((map->flags & MAP_ASLR) != 0) {
1256fa50a355SKonstantin Belousov 			/* Assume that interpeter fits into 1/4 of AS */
1257fa50a355SKonstantin Belousov 			maxv1 = maxv / 2 + addr / 2;
1258fa50a355SKonstantin Belousov 			MPASS(maxv1 >= addr);	/* No overflow */
1259fa50a355SKonstantin Belousov 			addr = __CONCAT(rnd_, __elfN(base))(map, addr,
1260fa50a355SKonstantin Belousov 			    maxv1, PAGE_SIZE);
1261fa50a355SKonstantin Belousov 		}
12629274fb35SEdward Tomasz Napierala 		error = __elfN(load_interp)(imgp, brand_info, interp, &addr,
12631699546dSEdward Tomasz Napierala 		    &imgp->entry_addr);
126478022527SKonstantin Belousov 		vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
12659274fb35SEdward Tomasz Napierala 		if (error != 0)
12666c775eb6SKonstantin Belousov 			goto ret;
126795c807cfSRobert Watson 	} else
12687564c4adSKonstantin Belousov 		addr = et_dyn_addr;
1269ea5a2b2eSSøren Schmidt 
1270e1743d02SSøren Schmidt 	/*
1271e1743d02SSøren Schmidt 	 * Construct auxargs table (used by the fixup routine)
1272e1743d02SSøren Schmidt 	 */
12732d6b8546SKonstantin Belousov 	elf_auxargs = malloc(sizeof(Elf_Auxargs), M_TEMP, M_NOWAIT);
12742d6b8546SKonstantin Belousov 	if (elf_auxargs == NULL) {
12752d6b8546SKonstantin Belousov 		VOP_UNLOCK(imgp->vp, 0);
1276a163d034SWarner Losh 		elf_auxargs = malloc(sizeof(Elf_Auxargs), M_TEMP, M_WAITOK);
127778022527SKonstantin Belousov 		vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
12782d6b8546SKonstantin Belousov 	}
1279e1743d02SSøren Schmidt 	elf_auxargs->execfd = -1;
12809bcd7482SEdward Tomasz Napierala 	elf_auxargs->phdr = proghdr + et_dyn_addr;
1281e1743d02SSøren Schmidt 	elf_auxargs->phent = hdr->e_phentsize;
1282e1743d02SSøren Schmidt 	elf_auxargs->phnum = hdr->e_phnum;
1283e1743d02SSøren Schmidt 	elf_auxargs->pagesz = PAGE_SIZE;
1284e1743d02SSøren Schmidt 	elf_auxargs->base = addr;
1285e1743d02SSøren Schmidt 	elf_auxargs->flags = 0;
1286e1743d02SSøren Schmidt 	elf_auxargs->entry = entry;
1287d36eec69SWarner Losh 	elf_auxargs->hdr_eflags = hdr->e_flags;
1288e1743d02SSøren Schmidt 
1289e1743d02SSøren Schmidt 	imgp->auxargs = elf_auxargs;
1290e1743d02SSøren Schmidt 	imgp->interpreted = 0;
1291a0ea661fSNathan Whitehorn 	imgp->reloc_base = addr;
129232c01de2SDmitry Chagin 	imgp->proc->p_osrel = osrel;
1293cefb93f2SKonstantin Belousov 	imgp->proc->p_fctl0 = fctl0;
1294885f13dcSJohn Baldwin 	imgp->proc->p_elf_machine = hdr->e_machine;
1295885f13dcSJohn Baldwin 	imgp->proc->p_elf_flags = hdr->e_flags;
1296f231de47SKonstantin Belousov 
12976c775eb6SKonstantin Belousov ret:
129809c78d53SEdward Tomasz Napierala 	if (free_interp)
129909c78d53SEdward Tomasz Napierala 		free(interp, M_TEMP);
1300a7cddfedSJake Burkholder 	return (error);
1301e1743d02SSøren Schmidt }
1302e1743d02SSøren Schmidt 
1303a360a43dSJake Burkholder #define	suword __CONCAT(suword, __ELF_WORD_SIZE)
13043ebc1248SPeter Wemm 
13053ebc1248SPeter Wemm int
13063ebc1248SPeter Wemm __elfN(freebsd_fixup)(register_t **stack_base, struct image_params *imgp)
1307e1743d02SSøren Schmidt {
1308ecbb00a2SDoug Rabson 	Elf_Auxargs *args = (Elf_Auxargs *)imgp->auxargs;
13095f77b8a8SBrooks Davis 	Elf_Auxinfo *argarray, *pos;
13105f77b8a8SBrooks Davis 	Elf_Addr *base, *auxbase;
13115f77b8a8SBrooks Davis 	int error;
1312e1743d02SSøren Schmidt 
1313a360a43dSJake Burkholder 	base = (Elf_Addr *)*stack_base;
13145f77b8a8SBrooks Davis 	auxbase = base + imgp->args->argc + 1 + imgp->args->envc + 1;
13155f77b8a8SBrooks Davis 	argarray = pos = malloc(AT_COUNT * sizeof(*pos), M_TEMP,
13165f77b8a8SBrooks Davis 	    M_WAITOK | M_ZERO);
1317e1743d02SSøren Schmidt 
131835c2a5a8SWarner Losh 	if (args->execfd != -1)
1319e1743d02SSøren Schmidt 		AUXARGS_ENTRY(pos, AT_EXECFD, args->execfd);
1320e1743d02SSøren Schmidt 	AUXARGS_ENTRY(pos, AT_PHDR, args->phdr);
1321e1743d02SSøren Schmidt 	AUXARGS_ENTRY(pos, AT_PHENT, args->phent);
1322e1743d02SSøren Schmidt 	AUXARGS_ENTRY(pos, AT_PHNUM, args->phnum);
1323e1743d02SSøren Schmidt 	AUXARGS_ENTRY(pos, AT_PAGESZ, args->pagesz);
1324e1743d02SSøren Schmidt 	AUXARGS_ENTRY(pos, AT_FLAGS, args->flags);
1325e1743d02SSøren Schmidt 	AUXARGS_ENTRY(pos, AT_ENTRY, args->entry);
1326e1743d02SSøren Schmidt 	AUXARGS_ENTRY(pos, AT_BASE, args->base);
1327d36eec69SWarner Losh 	AUXARGS_ENTRY(pos, AT_EHDRFLAGS, args->hdr_eflags);
13283ff06357SKonstantin Belousov 	if (imgp->execpathp != 0)
13293ff06357SKonstantin Belousov 		AUXARGS_ENTRY(pos, AT_EXECPATH, imgp->execpathp);
1330b96bd95bSIan Lepore 	AUXARGS_ENTRY(pos, AT_OSRELDATE,
1331b96bd95bSIan Lepore 	    imgp->proc->p_ucred->cr_prison->pr_osreldate);
1332ee235befSKonstantin Belousov 	if (imgp->canary != 0) {
1333ee235befSKonstantin Belousov 		AUXARGS_ENTRY(pos, AT_CANARY, imgp->canary);
1334ee235befSKonstantin Belousov 		AUXARGS_ENTRY(pos, AT_CANARYLEN, imgp->canarylen);
1335ee235befSKonstantin Belousov 	}
1336ee235befSKonstantin Belousov 	AUXARGS_ENTRY(pos, AT_NCPUS, mp_ncpus);
1337ee235befSKonstantin Belousov 	if (imgp->pagesizes != 0) {
1338ee235befSKonstantin Belousov 		AUXARGS_ENTRY(pos, AT_PAGESIZES, imgp->pagesizes);
1339ee235befSKonstantin Belousov 		AUXARGS_ENTRY(pos, AT_PAGESIZESLEN, imgp->pagesizeslen);
1340ee235befSKonstantin Belousov 	}
1341aea81038SKonstantin Belousov 	if (imgp->sysent->sv_timekeep_base != 0) {
1342aea81038SKonstantin Belousov 		AUXARGS_ENTRY(pos, AT_TIMEKEEP,
1343aea81038SKonstantin Belousov 		    imgp->sysent->sv_timekeep_base);
1344aea81038SKonstantin Belousov 	}
134526d8f3e1SKonstantin Belousov 	AUXARGS_ENTRY(pos, AT_STACKPROT, imgp->sysent->sv_shared_page_obj
134626d8f3e1SKonstantin Belousov 	    != NULL && imgp->stack_prot != 0 ? imgp->stack_prot :
134726d8f3e1SKonstantin Belousov 	    imgp->sysent->sv_stackprot);
1348c2f37b92SJohn Baldwin 	if (imgp->sysent->sv_hwcap != NULL)
1349c2f37b92SJohn Baldwin 		AUXARGS_ENTRY(pos, AT_HWCAP, *imgp->sysent->sv_hwcap);
1350904d8c49SMichal Meloun 	if (imgp->sysent->sv_hwcap2 != NULL)
1351904d8c49SMichal Meloun 		AUXARGS_ENTRY(pos, AT_HWCAP2, *imgp->sysent->sv_hwcap2);
1352e1743d02SSøren Schmidt 	AUXARGS_ENTRY(pos, AT_NULL, 0);
1353e1743d02SSøren Schmidt 
1354e1743d02SSøren Schmidt 	free(imgp->auxargs, M_TEMP);
1355e1743d02SSøren Schmidt 	imgp->auxargs = NULL;
1356d8b2f079SBrooks Davis 	KASSERT(pos - argarray <= AT_COUNT, ("Too many auxargs"));
13575f77b8a8SBrooks Davis 
13585f77b8a8SBrooks Davis 	error = copyout(argarray, auxbase, sizeof(*argarray) * AT_COUNT);
13595f77b8a8SBrooks Davis 	free(argarray, M_TEMP);
13605f77b8a8SBrooks Davis 	if (error != 0)
13615f77b8a8SBrooks Davis 		return (error);
1362e1743d02SSøren Schmidt 
13633ebc1248SPeter Wemm 	base--;
13645f77b8a8SBrooks Davis 	if (suword(base, imgp->args->argc) == -1)
13655f77b8a8SBrooks Davis 		return (EFAULT);
13663ebc1248SPeter Wemm 	*stack_base = (register_t *)base;
1367a7cddfedSJake Burkholder 	return (0);
1368e1743d02SSøren Schmidt }
1369e1743d02SSøren Schmidt 
1370e1743d02SSøren Schmidt /*
13718c64af4fSJohn Polstra  * Code for generating ELF core dumps.
13728c64af4fSJohn Polstra  */
13738c64af4fSJohn Polstra 
13744d77a549SAlfred Perlstein typedef void (*segment_callback)(vm_map_entry_t, void *);
13750ff27d31SJohn Polstra 
13760ff27d31SJohn Polstra /* Closure for cb_put_phdr(). */
13770ff27d31SJohn Polstra struct phdr_closure {
13780ff27d31SJohn Polstra 	Elf_Phdr *phdr;		/* Program header to fill in */
13790ff27d31SJohn Polstra 	Elf_Off offset;		/* Offset of segment in core file */
13800ff27d31SJohn Polstra };
13810ff27d31SJohn Polstra 
13820ff27d31SJohn Polstra /* Closure for cb_size_segment(). */
13830ff27d31SJohn Polstra struct sseg_closure {
13840ff27d31SJohn Polstra 	int count;		/* Count of writable segments. */
13850ff27d31SJohn Polstra 	size_t size;		/* Total size of all writable segments. */
13860ff27d31SJohn Polstra };
13870ff27d31SJohn Polstra 
1388bd390213SMikolaj Golub typedef void (*outfunc_t)(void *, struct sbuf *, size_t *);
1389bd390213SMikolaj Golub 
1390bd390213SMikolaj Golub struct note_info {
1391bd390213SMikolaj Golub 	int		type;		/* Note type. */
1392bd390213SMikolaj Golub 	outfunc_t 	outfunc; 	/* Output function. */
1393bd390213SMikolaj Golub 	void		*outarg;	/* Argument for the output function. */
1394bd390213SMikolaj Golub 	size_t		outsize;	/* Output size. */
1395bd390213SMikolaj Golub 	TAILQ_ENTRY(note_info) link;	/* Link to the next note info. */
1396bd390213SMikolaj Golub };
1397bd390213SMikolaj Golub 
1398bd390213SMikolaj Golub TAILQ_HEAD(note_info_list, note_info);
1399bd390213SMikolaj Golub 
1400aa14e9b7SMark Johnston /* Coredump output parameters. */
1401aa14e9b7SMark Johnston struct coredump_params {
1402aa14e9b7SMark Johnston 	off_t		offset;
1403aa14e9b7SMark Johnston 	struct ucred	*active_cred;
1404aa14e9b7SMark Johnston 	struct ucred	*file_cred;
1405aa14e9b7SMark Johnston 	struct thread	*td;
1406aa14e9b7SMark Johnston 	struct vnode	*vp;
140778f57a9cSMark Johnston 	struct compressor *comp;
1408aa14e9b7SMark Johnston };
1409aa14e9b7SMark Johnston 
141078f57a9cSMark Johnston extern int compress_user_cores;
141178f57a9cSMark Johnston extern int compress_user_cores_level;
141278f57a9cSMark Johnston 
14134d77a549SAlfred Perlstein static void cb_put_phdr(vm_map_entry_t, void *);
14144d77a549SAlfred Perlstein static void cb_size_segment(vm_map_entry_t, void *);
1415c468ff88SAndriy Gapon static int core_write(struct coredump_params *, const void *, size_t, off_t,
1416aa14e9b7SMark Johnston     enum uio_seg);
14171005d8afSConrad Meyer static void each_dumpable_segment(struct thread *, segment_callback, void *);
1418aa14e9b7SMark Johnston static int __elfN(corehdr)(struct coredump_params *, int, void *, size_t,
1419aa14e9b7SMark Johnston     struct note_info_list *, size_t);
1420bd390213SMikolaj Golub static void __elfN(prepare_notes)(struct thread *, struct note_info_list *,
1421bd390213SMikolaj Golub     size_t *);
1422bd390213SMikolaj Golub static void __elfN(puthdr)(struct thread *, void *, size_t, int, size_t);
1423bd390213SMikolaj Golub static void __elfN(putnote)(struct note_info *, struct sbuf *);
1424bd390213SMikolaj Golub static size_t register_note(struct note_info_list *, int, outfunc_t, void *);
1425bd390213SMikolaj Golub static int sbuf_drain_core_output(void *, const char *, int);
1426bd390213SMikolaj Golub 
1427bd390213SMikolaj Golub static void __elfN(note_fpregset)(void *, struct sbuf *, size_t *);
1428bd390213SMikolaj Golub static void __elfN(note_prpsinfo)(void *, struct sbuf *, size_t *);
1429bd390213SMikolaj Golub static void __elfN(note_prstatus)(void *, struct sbuf *, size_t *);
1430bd390213SMikolaj Golub static void __elfN(note_threadmd)(void *, struct sbuf *, size_t *);
1431bd390213SMikolaj Golub static void __elfN(note_thrmisc)(void *, struct sbuf *, size_t *);
143286be94fcSTycho Nightingale static void __elfN(note_ptlwpinfo)(void *, struct sbuf *, size_t *);
1433f1fca82eSMikolaj Golub static void __elfN(note_procstat_auxv)(void *, struct sbuf *, size_t *);
1434f1fca82eSMikolaj Golub static void __elfN(note_procstat_proc)(void *, struct sbuf *, size_t *);
1435f1fca82eSMikolaj Golub static void __elfN(note_procstat_psstrings)(void *, struct sbuf *, size_t *);
1436f1fca82eSMikolaj Golub static void note_procstat_files(void *, struct sbuf *, size_t *);
1437f1fca82eSMikolaj Golub static void note_procstat_groups(void *, struct sbuf *, size_t *);
1438f1fca82eSMikolaj Golub static void note_procstat_osrel(void *, struct sbuf *, size_t *);
1439f1fca82eSMikolaj Golub static void note_procstat_rlimit(void *, struct sbuf *, size_t *);
1440f1fca82eSMikolaj Golub static void note_procstat_umask(void *, struct sbuf *, size_t *);
1441f1fca82eSMikolaj Golub static void note_procstat_vmmap(void *, struct sbuf *, size_t *);
14428c64af4fSJohn Polstra 
1443aa14e9b7SMark Johnston /*
1444aa14e9b7SMark Johnston  * Write out a core segment to the compression stream.
1445aa14e9b7SMark Johnston  */
1446e7228204SAlfred Perlstein static int
1447aa14e9b7SMark Johnston compress_chunk(struct coredump_params *p, char *base, char *buf, u_int len)
1448aa14e9b7SMark Johnston {
1449aa14e9b7SMark Johnston 	u_int chunk_len;
1450e7228204SAlfred Perlstein 	int error;
1451aa14e9b7SMark Johnston 
1452aa14e9b7SMark Johnston 	while (len > 0) {
1453aa14e9b7SMark Johnston 		chunk_len = MIN(len, CORE_BUF_SIZE);
1454c468ff88SAndriy Gapon 
1455c468ff88SAndriy Gapon 		/*
1456c468ff88SAndriy Gapon 		 * We can get EFAULT error here.
1457c468ff88SAndriy Gapon 		 * In that case zero out the current chunk of the segment.
1458c468ff88SAndriy Gapon 		 */
1459c468ff88SAndriy Gapon 		error = copyin(base, buf, chunk_len);
1460c468ff88SAndriy Gapon 		if (error != 0)
1461c468ff88SAndriy Gapon 			bzero(buf, chunk_len);
146278f57a9cSMark Johnston 		error = compressor_write(p->comp, buf, chunk_len);
1463aa14e9b7SMark Johnston 		if (error != 0)
1464aa14e9b7SMark Johnston 			break;
1465aa14e9b7SMark Johnston 		base += chunk_len;
1466aa14e9b7SMark Johnston 		len -= chunk_len;
1467e7228204SAlfred Perlstein 	}
1468e7228204SAlfred Perlstein 	return (error);
1469e7228204SAlfred Perlstein }
1470e7228204SAlfred Perlstein 
1471aa14e9b7SMark Johnston static int
147278f57a9cSMark Johnston core_compressed_write(void *base, size_t len, off_t offset, void *arg)
1473aa14e9b7SMark Johnston {
1474aa14e9b7SMark Johnston 
1475aa14e9b7SMark Johnston 	return (core_write((struct coredump_params *)arg, base, len, offset,
1476aa14e9b7SMark Johnston 	    UIO_SYSSPACE));
1477aa14e9b7SMark Johnston }
1478aa14e9b7SMark Johnston 
1479aa14e9b7SMark Johnston static int
1480c468ff88SAndriy Gapon core_write(struct coredump_params *p, const void *base, size_t len,
1481c468ff88SAndriy Gapon     off_t offset, enum uio_seg seg)
1482aa14e9b7SMark Johnston {
1483aa14e9b7SMark Johnston 
1484c468ff88SAndriy Gapon 	return (vn_rdwr_inchunks(UIO_WRITE, p->vp, __DECONST(void *, base),
1485c468ff88SAndriy Gapon 	    len, offset, seg, IO_UNIT | IO_DIRECT | IO_RANGELOCKED,
1486aa14e9b7SMark Johnston 	    p->active_cred, p->file_cred, NULL, p->td));
1487aa14e9b7SMark Johnston }
1488aa14e9b7SMark Johnston 
1489aa14e9b7SMark Johnston static int
1490aa14e9b7SMark Johnston core_output(void *base, size_t len, off_t offset, struct coredump_params *p,
1491aa14e9b7SMark Johnston     void *tmpbuf)
1492aa14e9b7SMark Johnston {
1493c468ff88SAndriy Gapon 	int error;
1494aa14e9b7SMark Johnston 
149578f57a9cSMark Johnston 	if (p->comp != NULL)
1496aa14e9b7SMark Johnston 		return (compress_chunk(p, base, tmpbuf, len));
149778f57a9cSMark Johnston 
1498c468ff88SAndriy Gapon 	/*
1499c468ff88SAndriy Gapon 	 * EFAULT is a non-fatal error that we can get, for example,
1500c468ff88SAndriy Gapon 	 * if the segment is backed by a file but extends beyond its
1501c468ff88SAndriy Gapon 	 * end.
1502c468ff88SAndriy Gapon 	 */
1503c468ff88SAndriy Gapon 	error = core_write(p, base, len, offset, UIO_USERSPACE);
1504c468ff88SAndriy Gapon 	if (error == EFAULT) {
1505c468ff88SAndriy Gapon 		log(LOG_WARNING, "Failed to fully fault in a core file segment "
1506c468ff88SAndriy Gapon 		    "at VA %p with size 0x%zx to be written at offset 0x%jx "
1507c468ff88SAndriy Gapon 		    "for process %s\n", base, len, offset, curproc->p_comm);
1508c468ff88SAndriy Gapon 
1509c468ff88SAndriy Gapon 		/*
1510c468ff88SAndriy Gapon 		 * Write a "real" zero byte at the end of the target region
1511c468ff88SAndriy Gapon 		 * in the case this is the last segment.
1512c468ff88SAndriy Gapon 		 * The intermediate space will be implicitly zero-filled.
1513c468ff88SAndriy Gapon 		 */
1514c468ff88SAndriy Gapon 		error = core_write(p, zero_region, 1, offset + len - 1,
1515c468ff88SAndriy Gapon 		    UIO_SYSSPACE);
1516c468ff88SAndriy Gapon 	}
1517c468ff88SAndriy Gapon 	return (error);
1518aa14e9b7SMark Johnston }
1519bd390213SMikolaj Golub 
1520bd390213SMikolaj Golub /*
1521bd390213SMikolaj Golub  * Drain into a core file.
1522bd390213SMikolaj Golub  */
1523bd390213SMikolaj Golub static int
1524bd390213SMikolaj Golub sbuf_drain_core_output(void *arg, const char *data, int len)
1525bd390213SMikolaj Golub {
1526aa14e9b7SMark Johnston 	struct coredump_params *p;
1527f1fca82eSMikolaj Golub 	int error, locked;
1528bd390213SMikolaj Golub 
1529aa14e9b7SMark Johnston 	p = (struct coredump_params *)arg;
1530f1fca82eSMikolaj Golub 
1531f1fca82eSMikolaj Golub 	/*
1532f1fca82eSMikolaj Golub 	 * Some kern_proc out routines that print to this sbuf may
1533f1fca82eSMikolaj Golub 	 * call us with the process lock held. Draining with the
1534f1fca82eSMikolaj Golub 	 * non-sleepable lock held is unsafe. The lock is needed for
1535f1fca82eSMikolaj Golub 	 * those routines when dumping a live process. In our case we
1536f1fca82eSMikolaj Golub 	 * can safely release the lock before draining and acquire
1537f1fca82eSMikolaj Golub 	 * again after.
1538f1fca82eSMikolaj Golub 	 */
1539f1fca82eSMikolaj Golub 	locked = PROC_LOCKED(p->td->td_proc);
1540f1fca82eSMikolaj Golub 	if (locked)
1541f1fca82eSMikolaj Golub 		PROC_UNLOCK(p->td->td_proc);
154278f57a9cSMark Johnston 	if (p->comp != NULL)
154378f57a9cSMark Johnston 		error = compressor_write(p->comp, __DECONST(char *, data), len);
1544bd390213SMikolaj Golub 	else
1545aa14e9b7SMark Johnston 		error = core_write(p, __DECONST(void *, data), len, p->offset,
1546aa14e9b7SMark Johnston 		    UIO_SYSSPACE);
1547f1fca82eSMikolaj Golub 	if (locked)
1548f1fca82eSMikolaj Golub 		PROC_LOCK(p->td->td_proc);
1549bd390213SMikolaj Golub 	if (error != 0)
1550bd390213SMikolaj Golub 		return (-error);
1551bd390213SMikolaj Golub 	p->offset += len;
1552bd390213SMikolaj Golub 	return (len);
1553bd390213SMikolaj Golub }
1554bd390213SMikolaj Golub 
15558c64af4fSJohn Polstra int
1556e7228204SAlfred Perlstein __elfN(coredump)(struct thread *td, struct vnode *vp, off_t limit, int flags)
1557fca666a1SJulian Elischer {
1558247aba24SMarcel Moolenaar 	struct ucred *cred = td->td_ucred;
1559fca666a1SJulian Elischer 	int error = 0;
15600ff27d31SJohn Polstra 	struct sseg_closure seginfo;
1561bd390213SMikolaj Golub 	struct note_info_list notelst;
1562aa14e9b7SMark Johnston 	struct coredump_params params;
1563bd390213SMikolaj Golub 	struct note_info *ninfo;
1564aa14e9b7SMark Johnston 	void *hdr, *tmpbuf;
1565bd390213SMikolaj Golub 	size_t hdrsize, notesz, coresize;
15668c64af4fSJohn Polstra 
1567e7228204SAlfred Perlstein 	hdr = NULL;
156802d131adSMark Johnston 	tmpbuf = NULL;
1569bd390213SMikolaj Golub 	TAILQ_INIT(&notelst);
1570e7228204SAlfred Perlstein 
15710ff27d31SJohn Polstra 	/* Size the program segments. */
15720ff27d31SJohn Polstra 	seginfo.count = 0;
15730ff27d31SJohn Polstra 	seginfo.size = 0;
15741005d8afSConrad Meyer 	each_dumpable_segment(td, cb_size_segment, &seginfo);
15750ff27d31SJohn Polstra 
15760ff27d31SJohn Polstra 	/*
1577bd390213SMikolaj Golub 	 * Collect info about the core file header area.
15780ff27d31SJohn Polstra 	 */
1579bd390213SMikolaj Golub 	hdrsize = sizeof(Elf_Ehdr) + sizeof(Elf_Phdr) * (1 + seginfo.count);
1580c17b0bd2SConrad Meyer 	if (seginfo.count + 1 >= PN_XNUM)
1581c17b0bd2SConrad Meyer 		hdrsize += sizeof(Elf_Shdr);
1582bd390213SMikolaj Golub 	__elfN(prepare_notes)(td, &notelst, &notesz);
1583bd390213SMikolaj Golub 	coresize = round_page(hdrsize + notesz) + seginfo.size;
15840ff27d31SJohn Polstra 
158502d131adSMark Johnston 	/* Set up core dump parameters. */
158602d131adSMark Johnston 	params.offset = 0;
158702d131adSMark Johnston 	params.active_cred = cred;
158802d131adSMark Johnston 	params.file_cred = NOCRED;
158902d131adSMark Johnston 	params.td = td;
159002d131adSMark Johnston 	params.vp = vp;
159178f57a9cSMark Johnston 	params.comp = NULL;
159202d131adSMark Johnston 
1593afcc55f3SEdward Tomasz Napierala #ifdef RACCT
15944b5c9cf6SEdward Tomasz Napierala 	if (racct_enable) {
15951ba5ad42SEdward Tomasz Napierala 		PROC_LOCK(td->td_proc);
1596bd390213SMikolaj Golub 		error = racct_add(td->td_proc, RACCT_CORE, coresize);
15971ba5ad42SEdward Tomasz Napierala 		PROC_UNLOCK(td->td_proc);
15981ba5ad42SEdward Tomasz Napierala 		if (error != 0) {
15991ba5ad42SEdward Tomasz Napierala 			error = EFAULT;
16001ba5ad42SEdward Tomasz Napierala 			goto done;
16011ba5ad42SEdward Tomasz Napierala 		}
16024b5c9cf6SEdward Tomasz Napierala 	}
1603afcc55f3SEdward Tomasz Napierala #endif
1604bd390213SMikolaj Golub 	if (coresize >= limit) {
1605fba6b1afSAlfred Perlstein 		error = EFAULT;
1606fba6b1afSAlfred Perlstein 		goto done;
1607fba6b1afSAlfred Perlstein 	}
16080ff27d31SJohn Polstra 
1609aa14e9b7SMark Johnston 	/* Create a compression stream if necessary. */
161078f57a9cSMark Johnston 	if (compress_user_cores != 0) {
161178f57a9cSMark Johnston 		params.comp = compressor_init(core_compressed_write,
161278f57a9cSMark Johnston 		    compress_user_cores, CORE_BUF_SIZE,
161378f57a9cSMark Johnston 		    compress_user_cores_level, &params);
161478f57a9cSMark Johnston 		if (params.comp == NULL) {
1615aa14e9b7SMark Johnston 			error = EFAULT;
1616aa14e9b7SMark Johnston 			goto done;
1617aa14e9b7SMark Johnston 		}
1618aa14e9b7SMark Johnston 		tmpbuf = malloc(CORE_BUF_SIZE, M_TEMP, M_WAITOK | M_ZERO);
1619aa14e9b7SMark Johnston         }
1620aa14e9b7SMark Johnston 
16210ff27d31SJohn Polstra 	/*
16220ff27d31SJohn Polstra 	 * Allocate memory for building the header, fill it up,
1623bd390213SMikolaj Golub 	 * and write it out following the notes.
16240ff27d31SJohn Polstra 	 */
1625a163d034SWarner Losh 	hdr = malloc(hdrsize, M_TEMP, M_WAITOK);
1626aa14e9b7SMark Johnston 	error = __elfN(corehdr)(&params, seginfo.count, hdr, hdrsize, &notelst,
1627aa14e9b7SMark Johnston 	    notesz);
16280ff27d31SJohn Polstra 
16290ff27d31SJohn Polstra 	/* Write the contents of all of the writable segments. */
16300ff27d31SJohn Polstra 	if (error == 0) {
16310ff27d31SJohn Polstra 		Elf_Phdr *php;
16322b471bc6STim J. Robbins 		off_t offset;
16330ff27d31SJohn Polstra 		int i;
16340ff27d31SJohn Polstra 
16350ff27d31SJohn Polstra 		php = (Elf_Phdr *)((char *)hdr + sizeof(Elf_Ehdr)) + 1;
1636bd390213SMikolaj Golub 		offset = round_page(hdrsize + notesz);
16370ff27d31SJohn Polstra 		for (i = 0; i < seginfo.count; i++) {
1638aa14e9b7SMark Johnston 			error = core_output((caddr_t)(uintptr_t)php->p_vaddr,
1639aa14e9b7SMark Johnston 			    php->p_filesz, offset, &params, tmpbuf);
16400ff27d31SJohn Polstra 			if (error != 0)
16412b471bc6STim J. Robbins 				break;
16420ff27d31SJohn Polstra 			offset += php->p_filesz;
16430ff27d31SJohn Polstra 			php++;
16440ff27d31SJohn Polstra 		}
164578f57a9cSMark Johnston 		if (error == 0 && params.comp != NULL)
164678f57a9cSMark Johnston 			error = compressor_flush(params.comp);
16470ff27d31SJohn Polstra 	}
1648e7228204SAlfred Perlstein 	if (error) {
1649e7228204SAlfred Perlstein 		log(LOG_WARNING,
1650e7228204SAlfred Perlstein 		    "Failed to write core file for process %s (error %d)\n",
1651e7228204SAlfred Perlstein 		    curproc->p_comm, error);
1652e7228204SAlfred Perlstein 	}
1653e7228204SAlfred Perlstein 
1654e7228204SAlfred Perlstein done:
1655aa14e9b7SMark Johnston 	free(tmpbuf, M_TEMP);
165678f57a9cSMark Johnston 	if (params.comp != NULL)
165778f57a9cSMark Johnston 		compressor_fini(params.comp);
1658bd390213SMikolaj Golub 	while ((ninfo = TAILQ_FIRST(&notelst)) != NULL) {
1659bd390213SMikolaj Golub 		TAILQ_REMOVE(&notelst, ninfo, link);
1660bd390213SMikolaj Golub 		free(ninfo, M_TEMP);
1661bd390213SMikolaj Golub 	}
1662bd390213SMikolaj Golub 	if (hdr != NULL)
16630ff27d31SJohn Polstra 		free(hdr, M_TEMP);
16640ff27d31SJohn Polstra 
1665a7cddfedSJake Burkholder 	return (error);
16668c64af4fSJohn Polstra }
16678c64af4fSJohn Polstra 
16680ff27d31SJohn Polstra /*
16691005d8afSConrad Meyer  * A callback for each_dumpable_segment() to write out the segment's
16700ff27d31SJohn Polstra  * program header entry.
16710ff27d31SJohn Polstra  */
16720ff27d31SJohn Polstra static void
16735cc6d253SEd Maste cb_put_phdr(vm_map_entry_t entry, void *closure)
16740ff27d31SJohn Polstra {
16750ff27d31SJohn Polstra 	struct phdr_closure *phc = (struct phdr_closure *)closure;
16760ff27d31SJohn Polstra 	Elf_Phdr *phdr = phc->phdr;
16770ff27d31SJohn Polstra 
16780ff27d31SJohn Polstra 	phc->offset = round_page(phc->offset);
16790ff27d31SJohn Polstra 
16800ff27d31SJohn Polstra 	phdr->p_type = PT_LOAD;
16810ff27d31SJohn Polstra 	phdr->p_offset = phc->offset;
16820ff27d31SJohn Polstra 	phdr->p_vaddr = entry->start;
16830ff27d31SJohn Polstra 	phdr->p_paddr = 0;
16840ff27d31SJohn Polstra 	phdr->p_filesz = phdr->p_memsz = entry->end - entry->start;
16850ff27d31SJohn Polstra 	phdr->p_align = PAGE_SIZE;
1686ed167eaaSKonstantin Belousov 	phdr->p_flags = __elfN(untrans_prot)(entry->protection);
16870ff27d31SJohn Polstra 
16880ff27d31SJohn Polstra 	phc->offset += phdr->p_filesz;
16890ff27d31SJohn Polstra 	phc->phdr++;
16900ff27d31SJohn Polstra }
16910ff27d31SJohn Polstra 
16920ff27d31SJohn Polstra /*
16931005d8afSConrad Meyer  * A callback for each_dumpable_segment() to gather information about
16940ff27d31SJohn Polstra  * the number of segments and their total size.
16950ff27d31SJohn Polstra  */
16960ff27d31SJohn Polstra static void
1697f3325003SConrad Meyer cb_size_segment(vm_map_entry_t entry, void *closure)
16980ff27d31SJohn Polstra {
16990ff27d31SJohn Polstra 	struct sseg_closure *ssc = (struct sseg_closure *)closure;
17000ff27d31SJohn Polstra 
17010ff27d31SJohn Polstra 	ssc->count++;
17020ff27d31SJohn Polstra 	ssc->size += entry->end - entry->start;
17030ff27d31SJohn Polstra }
17040ff27d31SJohn Polstra 
17050ff27d31SJohn Polstra /*
17060ff27d31SJohn Polstra  * For each writable segment in the process's memory map, call the given
17070ff27d31SJohn Polstra  * function with a pointer to the map entry and some arbitrary
17080ff27d31SJohn Polstra  * caller-supplied data.
17090ff27d31SJohn Polstra  */
17100ff27d31SJohn Polstra static void
17111005d8afSConrad Meyer each_dumpable_segment(struct thread *td, segment_callback func, void *closure)
17120ff27d31SJohn Polstra {
1713247aba24SMarcel Moolenaar 	struct proc *p = td->td_proc;
17140ff27d31SJohn Polstra 	vm_map_t map = &p->p_vmspace->vm_map;
17150ff27d31SJohn Polstra 	vm_map_entry_t entry;
1716976a87a2SAlan Cox 	vm_object_t backing_object, object;
1717976a87a2SAlan Cox 	boolean_t ignore_entry;
17180ff27d31SJohn Polstra 
1719976a87a2SAlan Cox 	vm_map_lock_read(map);
17200ff27d31SJohn Polstra 	for (entry = map->header.next; entry != &map->header;
17210ff27d31SJohn Polstra 	    entry = entry->next) {
1722fa7dd9c5SMatthew Dillon 		/*
1723fa7dd9c5SMatthew Dillon 		 * Don't dump inaccessible mappings, deal with legacy
1724fa7dd9c5SMatthew Dillon 		 * coredump mode.
1725fa7dd9c5SMatthew Dillon 		 *
1726fa7dd9c5SMatthew Dillon 		 * Note that read-only segments related to the elf binary
1727fa7dd9c5SMatthew Dillon 		 * are marked MAP_ENTRY_NOCOREDUMP now so we no longer
1728fa7dd9c5SMatthew Dillon 		 * need to arbitrarily ignore such segments.
1729fa7dd9c5SMatthew Dillon 		 */
1730fa7dd9c5SMatthew Dillon 		if (elf_legacy_coredump) {
1731fa7dd9c5SMatthew Dillon 			if ((entry->protection & VM_PROT_RW) != VM_PROT_RW)
17320ff27d31SJohn Polstra 				continue;
1733fa7dd9c5SMatthew Dillon 		} else {
1734fa7dd9c5SMatthew Dillon 			if ((entry->protection & VM_PROT_ALL) == 0)
1735fa7dd9c5SMatthew Dillon 				continue;
1736fa7dd9c5SMatthew Dillon 		}
17370ff27d31SJohn Polstra 
17389730a5daSPaul Saab 		/*
1739fa7dd9c5SMatthew Dillon 		 * Dont include memory segment in the coredump if
1740fa7dd9c5SMatthew Dillon 		 * MAP_NOCORE is set in mmap(2) or MADV_NOCORE in
1741fa7dd9c5SMatthew Dillon 		 * madvise(2).  Do not dump submaps (i.e. parts of the
1742fa7dd9c5SMatthew Dillon 		 * kernel map).
17439730a5daSPaul Saab 		 */
1744fa7dd9c5SMatthew Dillon 		if (entry->eflags & (MAP_ENTRY_NOCOREDUMP|MAP_ENTRY_IS_SUB_MAP))
17459730a5daSPaul Saab 			continue;
17469730a5daSPaul Saab 
1747976a87a2SAlan Cox 		if ((object = entry->object.vm_object) == NULL)
17480ff27d31SJohn Polstra 			continue;
17490ff27d31SJohn Polstra 
17500ff27d31SJohn Polstra 		/* Ignore memory-mapped devices and such things. */
1751bc403f03SAttilio Rao 		VM_OBJECT_RLOCK(object);
1752976a87a2SAlan Cox 		while ((backing_object = object->backing_object) != NULL) {
1753bc403f03SAttilio Rao 			VM_OBJECT_RLOCK(backing_object);
1754bc403f03SAttilio Rao 			VM_OBJECT_RUNLOCK(object);
1755976a87a2SAlan Cox 			object = backing_object;
1756976a87a2SAlan Cox 		}
1757976a87a2SAlan Cox 		ignore_entry = object->type != OBJT_DEFAULT &&
1758bc411bc2SJohn Baldwin 		    object->type != OBJT_SWAP && object->type != OBJT_VNODE &&
1759bc411bc2SJohn Baldwin 		    object->type != OBJT_PHYS;
1760bc403f03SAttilio Rao 		VM_OBJECT_RUNLOCK(object);
1761976a87a2SAlan Cox 		if (ignore_entry)
17620ff27d31SJohn Polstra 			continue;
17630ff27d31SJohn Polstra 
17640ff27d31SJohn Polstra 		(*func)(entry, closure);
17650ff27d31SJohn Polstra 	}
1766976a87a2SAlan Cox 	vm_map_unlock_read(map);
17670ff27d31SJohn Polstra }
17680ff27d31SJohn Polstra 
17690ff27d31SJohn Polstra /*
17700ff27d31SJohn Polstra  * Write the core file header to the file, including padding up to
17710ff27d31SJohn Polstra  * the page boundary.
17720ff27d31SJohn Polstra  */
17738c64af4fSJohn Polstra static int
1774aa14e9b7SMark Johnston __elfN(corehdr)(struct coredump_params *p, int numsegs, void *hdr,
1775aa14e9b7SMark Johnston     size_t hdrsize, struct note_info_list *notelst, size_t notesz)
17768c64af4fSJohn Polstra {
1777bd390213SMikolaj Golub 	struct note_info *ninfo;
1778bd390213SMikolaj Golub 	struct sbuf *sb;
1779bd390213SMikolaj Golub 	int error;
17808c64af4fSJohn Polstra 
17818c64af4fSJohn Polstra 	/* Fill in the header. */
17820ff27d31SJohn Polstra 	bzero(hdr, hdrsize);
1783aa14e9b7SMark Johnston 	__elfN(puthdr)(p->td, hdr, hdrsize, numsegs, notesz);
17848c64af4fSJohn Polstra 
1785bd390213SMikolaj Golub 	sb = sbuf_new(NULL, NULL, CORE_BUF_SIZE, SBUF_FIXEDLEN);
1786aa14e9b7SMark Johnston 	sbuf_set_drain(sb, sbuf_drain_core_output, p);
1787bd390213SMikolaj Golub 	sbuf_start_section(sb, NULL);
1788bd390213SMikolaj Golub 	sbuf_bcat(sb, hdr, hdrsize);
1789bd390213SMikolaj Golub 	TAILQ_FOREACH(ninfo, notelst, link)
1790bd390213SMikolaj Golub 	    __elfN(putnote)(ninfo, sb);
1791bd390213SMikolaj Golub 	/* Align up to a page boundary for the program segments. */
1792bd390213SMikolaj Golub 	sbuf_end_section(sb, -1, PAGE_SIZE, 0);
1793bd390213SMikolaj Golub 	error = sbuf_finish(sb);
1794bd390213SMikolaj Golub 	sbuf_delete(sb);
1795bd390213SMikolaj Golub 
1796bd390213SMikolaj Golub 	return (error);
1797e7228204SAlfred Perlstein }
1798bd390213SMikolaj Golub 
1799bd390213SMikolaj Golub static void
1800bd390213SMikolaj Golub __elfN(prepare_notes)(struct thread *td, struct note_info_list *list,
1801bd390213SMikolaj Golub     size_t *sizep)
1802bd390213SMikolaj Golub {
1803bd390213SMikolaj Golub 	struct proc *p;
1804bd390213SMikolaj Golub 	struct thread *thr;
1805bd390213SMikolaj Golub 	size_t size;
1806bd390213SMikolaj Golub 
1807bd390213SMikolaj Golub 	p = td->td_proc;
1808bd390213SMikolaj Golub 	size = 0;
1809bd390213SMikolaj Golub 
1810bd390213SMikolaj Golub 	size += register_note(list, NT_PRPSINFO, __elfN(note_prpsinfo), p);
1811bd390213SMikolaj Golub 
1812bd390213SMikolaj Golub 	/*
1813bd390213SMikolaj Golub 	 * To have the debugger select the right thread (LWP) as the initial
1814bd390213SMikolaj Golub 	 * thread, we dump the state of the thread passed to us in td first.
1815bd390213SMikolaj Golub 	 * This is the thread that causes the core dump and thus likely to
1816bd390213SMikolaj Golub 	 * be the right thread one wants to have selected in the debugger.
1817bd390213SMikolaj Golub 	 */
1818bd390213SMikolaj Golub 	thr = td;
1819bd390213SMikolaj Golub 	while (thr != NULL) {
1820bd390213SMikolaj Golub 		size += register_note(list, NT_PRSTATUS,
1821bd390213SMikolaj Golub 		    __elfN(note_prstatus), thr);
1822bd390213SMikolaj Golub 		size += register_note(list, NT_FPREGSET,
1823bd390213SMikolaj Golub 		    __elfN(note_fpregset), thr);
1824bd390213SMikolaj Golub 		size += register_note(list, NT_THRMISC,
1825bd390213SMikolaj Golub 		    __elfN(note_thrmisc), thr);
182686be94fcSTycho Nightingale 		size += register_note(list, NT_PTLWPINFO,
182786be94fcSTycho Nightingale 		    __elfN(note_ptlwpinfo), thr);
1828bd390213SMikolaj Golub 		size += register_note(list, -1,
1829bd390213SMikolaj Golub 		    __elfN(note_threadmd), thr);
1830bd390213SMikolaj Golub 
1831bd390213SMikolaj Golub 		thr = (thr == td) ? TAILQ_FIRST(&p->p_threads) :
1832bd390213SMikolaj Golub 		    TAILQ_NEXT(thr, td_plist);
1833bd390213SMikolaj Golub 		if (thr == td)
1834bd390213SMikolaj Golub 			thr = TAILQ_NEXT(thr, td_plist);
1835dada0278SJohn Polstra 	}
1836dada0278SJohn Polstra 
1837f1fca82eSMikolaj Golub 	size += register_note(list, NT_PROCSTAT_PROC,
1838f1fca82eSMikolaj Golub 	    __elfN(note_procstat_proc), p);
1839f1fca82eSMikolaj Golub 	size += register_note(list, NT_PROCSTAT_FILES,
1840f1fca82eSMikolaj Golub 	    note_procstat_files, p);
1841f1fca82eSMikolaj Golub 	size += register_note(list, NT_PROCSTAT_VMMAP,
1842f1fca82eSMikolaj Golub 	    note_procstat_vmmap, p);
1843f1fca82eSMikolaj Golub 	size += register_note(list, NT_PROCSTAT_GROUPS,
1844f1fca82eSMikolaj Golub 	    note_procstat_groups, p);
1845f1fca82eSMikolaj Golub 	size += register_note(list, NT_PROCSTAT_UMASK,
1846f1fca82eSMikolaj Golub 	    note_procstat_umask, p);
1847f1fca82eSMikolaj Golub 	size += register_note(list, NT_PROCSTAT_RLIMIT,
1848f1fca82eSMikolaj Golub 	    note_procstat_rlimit, p);
1849f1fca82eSMikolaj Golub 	size += register_note(list, NT_PROCSTAT_OSREL,
1850f1fca82eSMikolaj Golub 	    note_procstat_osrel, p);
1851f1fca82eSMikolaj Golub 	size += register_note(list, NT_PROCSTAT_PSSTRINGS,
1852f1fca82eSMikolaj Golub 	    __elfN(note_procstat_psstrings), p);
1853f1fca82eSMikolaj Golub 	size += register_note(list, NT_PROCSTAT_AUXV,
1854f1fca82eSMikolaj Golub 	    __elfN(note_procstat_auxv), p);
1855f1fca82eSMikolaj Golub 
1856bd390213SMikolaj Golub 	*sizep = size;
1857bd390213SMikolaj Golub }
1858bd390213SMikolaj Golub 
1859bd390213SMikolaj Golub static void
1860bd390213SMikolaj Golub __elfN(puthdr)(struct thread *td, void *hdr, size_t hdrsize, int numsegs,
1861bd390213SMikolaj Golub     size_t notesz)
1862bd390213SMikolaj Golub {
1863bd390213SMikolaj Golub 	Elf_Ehdr *ehdr;
1864bd390213SMikolaj Golub 	Elf_Phdr *phdr;
1865c17b0bd2SConrad Meyer 	Elf_Shdr *shdr;
1866bd390213SMikolaj Golub 	struct phdr_closure phc;
1867bd390213SMikolaj Golub 
1868bd390213SMikolaj Golub 	ehdr = (Elf_Ehdr *)hdr;
1869bd390213SMikolaj Golub 
1870bd390213SMikolaj Golub 	ehdr->e_ident[EI_MAG0] = ELFMAG0;
1871bd390213SMikolaj Golub 	ehdr->e_ident[EI_MAG1] = ELFMAG1;
1872bd390213SMikolaj Golub 	ehdr->e_ident[EI_MAG2] = ELFMAG2;
1873bd390213SMikolaj Golub 	ehdr->e_ident[EI_MAG3] = ELFMAG3;
1874bd390213SMikolaj Golub 	ehdr->e_ident[EI_CLASS] = ELF_CLASS;
1875bd390213SMikolaj Golub 	ehdr->e_ident[EI_DATA] = ELF_DATA;
1876bd390213SMikolaj Golub 	ehdr->e_ident[EI_VERSION] = EV_CURRENT;
1877bd390213SMikolaj Golub 	ehdr->e_ident[EI_OSABI] = ELFOSABI_FREEBSD;
1878bd390213SMikolaj Golub 	ehdr->e_ident[EI_ABIVERSION] = 0;
1879bd390213SMikolaj Golub 	ehdr->e_ident[EI_PAD] = 0;
1880bd390213SMikolaj Golub 	ehdr->e_type = ET_CORE;
1881885f13dcSJohn Baldwin 	ehdr->e_machine = td->td_proc->p_elf_machine;
1882bd390213SMikolaj Golub 	ehdr->e_version = EV_CURRENT;
1883bd390213SMikolaj Golub 	ehdr->e_entry = 0;
1884bd390213SMikolaj Golub 	ehdr->e_phoff = sizeof(Elf_Ehdr);
1885885f13dcSJohn Baldwin 	ehdr->e_flags = td->td_proc->p_elf_flags;
1886bd390213SMikolaj Golub 	ehdr->e_ehsize = sizeof(Elf_Ehdr);
1887bd390213SMikolaj Golub 	ehdr->e_phentsize = sizeof(Elf_Phdr);
1888bd390213SMikolaj Golub 	ehdr->e_shentsize = sizeof(Elf_Shdr);
1889bd390213SMikolaj Golub 	ehdr->e_shstrndx = SHN_UNDEF;
1890c17b0bd2SConrad Meyer 	if (numsegs + 1 < PN_XNUM) {
1891c17b0bd2SConrad Meyer 		ehdr->e_phnum = numsegs + 1;
1892c17b0bd2SConrad Meyer 		ehdr->e_shnum = 0;
1893c17b0bd2SConrad Meyer 	} else {
1894c17b0bd2SConrad Meyer 		ehdr->e_phnum = PN_XNUM;
1895c17b0bd2SConrad Meyer 		ehdr->e_shnum = 1;
1896c17b0bd2SConrad Meyer 
1897c17b0bd2SConrad Meyer 		ehdr->e_shoff = ehdr->e_phoff +
1898c17b0bd2SConrad Meyer 		    (numsegs + 1) * ehdr->e_phentsize;
1899c17b0bd2SConrad Meyer 		KASSERT(ehdr->e_shoff == hdrsize - sizeof(Elf_Shdr),
1900c17b0bd2SConrad Meyer 		    ("e_shoff: %zu, hdrsize - shdr: %zu",
190107f825e8SConrad Meyer 		     (size_t)ehdr->e_shoff, hdrsize - sizeof(Elf_Shdr)));
1902c17b0bd2SConrad Meyer 
1903c17b0bd2SConrad Meyer 		shdr = (Elf_Shdr *)((char *)hdr + ehdr->e_shoff);
1904c17b0bd2SConrad Meyer 		memset(shdr, 0, sizeof(*shdr));
1905c17b0bd2SConrad Meyer 		/*
1906c17b0bd2SConrad Meyer 		 * A special first section is used to hold large segment and
1907c17b0bd2SConrad Meyer 		 * section counts.  This was proposed by Sun Microsystems in
1908c17b0bd2SConrad Meyer 		 * Solaris and has been adopted by Linux; the standard ELF
1909c17b0bd2SConrad Meyer 		 * tools are already familiar with the technique.
1910c17b0bd2SConrad Meyer 		 *
1911c17b0bd2SConrad Meyer 		 * See table 7-7 of the Solaris "Linker and Libraries Guide"
1912c17b0bd2SConrad Meyer 		 * (or 12-7 depending on the version of the document) for more
1913c17b0bd2SConrad Meyer 		 * details.
1914c17b0bd2SConrad Meyer 		 */
1915c17b0bd2SConrad Meyer 		shdr->sh_type = SHT_NULL;
1916c17b0bd2SConrad Meyer 		shdr->sh_size = ehdr->e_shnum;
1917c17b0bd2SConrad Meyer 		shdr->sh_link = ehdr->e_shstrndx;
1918c17b0bd2SConrad Meyer 		shdr->sh_info = numsegs + 1;
1919c17b0bd2SConrad Meyer 	}
1920bd390213SMikolaj Golub 
1921bd390213SMikolaj Golub 	/*
1922bd390213SMikolaj Golub 	 * Fill in the program header entries.
1923bd390213SMikolaj Golub 	 */
1924c17b0bd2SConrad Meyer 	phdr = (Elf_Phdr *)((char *)hdr + ehdr->e_phoff);
1925bd390213SMikolaj Golub 
1926bd390213SMikolaj Golub 	/* The note segement. */
1927bd390213SMikolaj Golub 	phdr->p_type = PT_NOTE;
1928bd390213SMikolaj Golub 	phdr->p_offset = hdrsize;
1929bd390213SMikolaj Golub 	phdr->p_vaddr = 0;
1930bd390213SMikolaj Golub 	phdr->p_paddr = 0;
1931bd390213SMikolaj Golub 	phdr->p_filesz = notesz;
1932bd390213SMikolaj Golub 	phdr->p_memsz = 0;
1933bd390213SMikolaj Golub 	phdr->p_flags = PF_R;
19341b8388cdSMikolaj Golub 	phdr->p_align = ELF_NOTE_ROUNDSIZE;
1935bd390213SMikolaj Golub 	phdr++;
1936bd390213SMikolaj Golub 
1937bd390213SMikolaj Golub 	/* All the writable segments from the program. */
1938bd390213SMikolaj Golub 	phc.phdr = phdr;
1939bd390213SMikolaj Golub 	phc.offset = round_page(hdrsize + notesz);
19401005d8afSConrad Meyer 	each_dumpable_segment(td, cb_put_phdr, &phc);
1941bd390213SMikolaj Golub }
1942bd390213SMikolaj Golub 
1943bd390213SMikolaj Golub static size_t
1944bd390213SMikolaj Golub register_note(struct note_info_list *list, int type, outfunc_t out, void *arg)
1945bd390213SMikolaj Golub {
1946bd390213SMikolaj Golub 	struct note_info *ninfo;
1947bd390213SMikolaj Golub 	size_t size, notesize;
1948bd390213SMikolaj Golub 
1949bd390213SMikolaj Golub 	size = 0;
1950bd390213SMikolaj Golub 	out(arg, NULL, &size);
1951bd390213SMikolaj Golub 	ninfo = malloc(sizeof(*ninfo), M_TEMP, M_ZERO | M_WAITOK);
1952bd390213SMikolaj Golub 	ninfo->type = type;
1953bd390213SMikolaj Golub 	ninfo->outfunc = out;
1954bd390213SMikolaj Golub 	ninfo->outarg = arg;
1955bd390213SMikolaj Golub 	ninfo->outsize = size;
1956bd390213SMikolaj Golub 	TAILQ_INSERT_TAIL(list, ninfo, link);
1957bd390213SMikolaj Golub 
1958bd390213SMikolaj Golub 	if (type == -1)
1959bd390213SMikolaj Golub 		return (size);
1960bd390213SMikolaj Golub 
1961bd390213SMikolaj Golub 	notesize = sizeof(Elf_Note) +		/* note header */
1962180e57e5SJohn Baldwin 	    roundup2(sizeof(FREEBSD_ABI_VENDOR), ELF_NOTE_ROUNDSIZE) +
1963180e57e5SJohn Baldwin 						/* note name */
1964180e57e5SJohn Baldwin 	    roundup2(size, ELF_NOTE_ROUNDSIZE);	/* note description */
1965180e57e5SJohn Baldwin 
1966180e57e5SJohn Baldwin 	return (notesize);
1967180e57e5SJohn Baldwin }
1968180e57e5SJohn Baldwin 
1969180e57e5SJohn Baldwin static size_t
1970180e57e5SJohn Baldwin append_note_data(const void *src, void *dst, size_t len)
1971180e57e5SJohn Baldwin {
1972180e57e5SJohn Baldwin 	size_t padded_len;
1973180e57e5SJohn Baldwin 
1974180e57e5SJohn Baldwin 	padded_len = roundup2(len, ELF_NOTE_ROUNDSIZE);
1975180e57e5SJohn Baldwin 	if (dst != NULL) {
1976180e57e5SJohn Baldwin 		bcopy(src, dst, len);
1977180e57e5SJohn Baldwin 		bzero((char *)dst + len, padded_len - len);
1978180e57e5SJohn Baldwin 	}
1979180e57e5SJohn Baldwin 	return (padded_len);
1980180e57e5SJohn Baldwin }
1981180e57e5SJohn Baldwin 
1982180e57e5SJohn Baldwin size_t
1983180e57e5SJohn Baldwin __elfN(populate_note)(int type, void *src, void *dst, size_t size, void **descp)
1984180e57e5SJohn Baldwin {
1985180e57e5SJohn Baldwin 	Elf_Note *note;
1986180e57e5SJohn Baldwin 	char *buf;
1987180e57e5SJohn Baldwin 	size_t notesize;
1988180e57e5SJohn Baldwin 
1989180e57e5SJohn Baldwin 	buf = dst;
1990180e57e5SJohn Baldwin 	if (buf != NULL) {
1991180e57e5SJohn Baldwin 		note = (Elf_Note *)buf;
1992180e57e5SJohn Baldwin 		note->n_namesz = sizeof(FREEBSD_ABI_VENDOR);
1993180e57e5SJohn Baldwin 		note->n_descsz = size;
1994180e57e5SJohn Baldwin 		note->n_type = type;
1995180e57e5SJohn Baldwin 		buf += sizeof(*note);
1996180e57e5SJohn Baldwin 		buf += append_note_data(FREEBSD_ABI_VENDOR, buf,
1997180e57e5SJohn Baldwin 		    sizeof(FREEBSD_ABI_VENDOR));
1998180e57e5SJohn Baldwin 		append_note_data(src, buf, size);
1999180e57e5SJohn Baldwin 		if (descp != NULL)
2000180e57e5SJohn Baldwin 			*descp = buf;
2001180e57e5SJohn Baldwin 	}
2002180e57e5SJohn Baldwin 
2003180e57e5SJohn Baldwin 	notesize = sizeof(Elf_Note) +		/* note header */
2004180e57e5SJohn Baldwin 	    roundup2(sizeof(FREEBSD_ABI_VENDOR), ELF_NOTE_ROUNDSIZE) +
2005180e57e5SJohn Baldwin 						/* note name */
20061b8388cdSMikolaj Golub 	    roundup2(size, ELF_NOTE_ROUNDSIZE);	/* note description */
2007bd390213SMikolaj Golub 
2008bd390213SMikolaj Golub 	return (notesize);
2009bd390213SMikolaj Golub }
2010bd390213SMikolaj Golub 
2011bd390213SMikolaj Golub static void
2012bd390213SMikolaj Golub __elfN(putnote)(struct note_info *ninfo, struct sbuf *sb)
2013bd390213SMikolaj Golub {
2014bd390213SMikolaj Golub 	Elf_Note note;
201514bdbaf2SConrad Meyer 	ssize_t old_len, sect_len;
201614bdbaf2SConrad Meyer 	size_t new_len, descsz, i;
2017bd390213SMikolaj Golub 
2018bd390213SMikolaj Golub 	if (ninfo->type == -1) {
2019bd390213SMikolaj Golub 		ninfo->outfunc(ninfo->outarg, sb, &ninfo->outsize);
2020bd390213SMikolaj Golub 		return;
2021bd390213SMikolaj Golub 	}
2022bd390213SMikolaj Golub 
2023180e57e5SJohn Baldwin 	note.n_namesz = sizeof(FREEBSD_ABI_VENDOR);
2024bd390213SMikolaj Golub 	note.n_descsz = ninfo->outsize;
2025bd390213SMikolaj Golub 	note.n_type = ninfo->type;
2026bd390213SMikolaj Golub 
2027bd390213SMikolaj Golub 	sbuf_bcat(sb, &note, sizeof(note));
2028bd390213SMikolaj Golub 	sbuf_start_section(sb, &old_len);
2029180e57e5SJohn Baldwin 	sbuf_bcat(sb, FREEBSD_ABI_VENDOR, sizeof(FREEBSD_ABI_VENDOR));
20301b8388cdSMikolaj Golub 	sbuf_end_section(sb, old_len, ELF_NOTE_ROUNDSIZE, 0);
2031bd390213SMikolaj Golub 	if (note.n_descsz == 0)
2032bd390213SMikolaj Golub 		return;
2033bd390213SMikolaj Golub 	sbuf_start_section(sb, &old_len);
2034bd390213SMikolaj Golub 	ninfo->outfunc(ninfo->outarg, sb, &ninfo->outsize);
203514bdbaf2SConrad Meyer 	sect_len = sbuf_end_section(sb, old_len, ELF_NOTE_ROUNDSIZE, 0);
203614bdbaf2SConrad Meyer 	if (sect_len < 0)
203714bdbaf2SConrad Meyer 		return;
203814bdbaf2SConrad Meyer 
203914bdbaf2SConrad Meyer 	new_len = (size_t)sect_len;
204014bdbaf2SConrad Meyer 	descsz = roundup(note.n_descsz, ELF_NOTE_ROUNDSIZE);
204114bdbaf2SConrad Meyer 	if (new_len < descsz) {
204214bdbaf2SConrad Meyer 		/*
204314bdbaf2SConrad Meyer 		 * It is expected that individual note emitters will correctly
204414bdbaf2SConrad Meyer 		 * predict their expected output size and fill up to that size
204514bdbaf2SConrad Meyer 		 * themselves, padding in a format-specific way if needed.
204614bdbaf2SConrad Meyer 		 * However, in case they don't, just do it here with zeros.
204714bdbaf2SConrad Meyer 		 */
204814bdbaf2SConrad Meyer 		for (i = 0; i < descsz - new_len; i++)
204914bdbaf2SConrad Meyer 			sbuf_putc(sb, 0);
205014bdbaf2SConrad Meyer 	} else if (new_len > descsz) {
205114bdbaf2SConrad Meyer 		/*
205214bdbaf2SConrad Meyer 		 * We can't always truncate sb -- we may have drained some
205314bdbaf2SConrad Meyer 		 * of it already.
205414bdbaf2SConrad Meyer 		 */
205514bdbaf2SConrad Meyer 		KASSERT(new_len == descsz, ("%s: Note type %u changed as we "
205614bdbaf2SConrad Meyer 		    "read it (%zu > %zu).  Since it is longer than "
205714bdbaf2SConrad Meyer 		    "expected, this coredump's notes are corrupt.  THIS "
205814bdbaf2SConrad Meyer 		    "IS A BUG in the note_procstat routine for type %u.\n",
205914bdbaf2SConrad Meyer 		    __func__, (unsigned)note.n_type, new_len, descsz,
206014bdbaf2SConrad Meyer 		    (unsigned)note.n_type));
206114bdbaf2SConrad Meyer 	}
2062bd390213SMikolaj Golub }
2063bd390213SMikolaj Golub 
2064bd390213SMikolaj Golub /*
2065bd390213SMikolaj Golub  * Miscellaneous note out functions.
2066bd390213SMikolaj Golub  */
2067bd390213SMikolaj Golub 
2068841c0c7eSNathan Whitehorn #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
2069841c0c7eSNathan Whitehorn #include <compat/freebsd32/freebsd32.h>
207051645e83SJohn Baldwin #include <compat/freebsd32/freebsd32_signal.h>
2071841c0c7eSNathan Whitehorn 
207262919d78SPeter Wemm typedef struct prstatus32 elf_prstatus_t;
207362919d78SPeter Wemm typedef struct prpsinfo32 elf_prpsinfo_t;
207462919d78SPeter Wemm typedef struct fpreg32 elf_prfpregset_t;
207562919d78SPeter Wemm typedef struct fpreg32 elf_fpregset_t;
207662919d78SPeter Wemm typedef struct reg32 elf_gregset_t;
20777f08176eSAttilio Rao typedef struct thrmisc32 elf_thrmisc_t;
2078f1fca82eSMikolaj Golub #define ELF_KERN_PROC_MASK	KERN_PROC_MASK32
2079f1fca82eSMikolaj Golub typedef struct kinfo_proc32 elf_kinfo_proc_t;
2080f1fca82eSMikolaj Golub typedef uint32_t elf_ps_strings_t;
208162919d78SPeter Wemm #else
208262919d78SPeter Wemm typedef prstatus_t elf_prstatus_t;
208362919d78SPeter Wemm typedef prpsinfo_t elf_prpsinfo_t;
208462919d78SPeter Wemm typedef prfpregset_t elf_prfpregset_t;
208562919d78SPeter Wemm typedef prfpregset_t elf_fpregset_t;
208662919d78SPeter Wemm typedef gregset_t elf_gregset_t;
20877f08176eSAttilio Rao typedef thrmisc_t elf_thrmisc_t;
2088f1fca82eSMikolaj Golub #define ELF_KERN_PROC_MASK	0
2089f1fca82eSMikolaj Golub typedef struct kinfo_proc elf_kinfo_proc_t;
2090f1fca82eSMikolaj Golub typedef vm_offset_t elf_ps_strings_t;
209162919d78SPeter Wemm #endif
209262919d78SPeter Wemm 
20938c64af4fSJohn Polstra static void
2094bd390213SMikolaj Golub __elfN(note_prpsinfo)(void *arg, struct sbuf *sb, size_t *sizep)
20958c64af4fSJohn Polstra {
2096c77547d2SJohn Baldwin 	struct sbuf sbarg;
2097c77547d2SJohn Baldwin 	size_t len;
2098c77547d2SJohn Baldwin 	char *cp, *end;
2099247aba24SMarcel Moolenaar 	struct proc *p;
2100bd390213SMikolaj Golub 	elf_prpsinfo_t *psinfo;
2101c77547d2SJohn Baldwin 	int error;
21028c64af4fSJohn Polstra 
2103bd390213SMikolaj Golub 	p = (struct proc *)arg;
2104bd390213SMikolaj Golub 	if (sb != NULL) {
2105bd390213SMikolaj Golub 		KASSERT(*sizep == sizeof(*psinfo), ("invalid size"));
2106bd390213SMikolaj Golub 		psinfo = malloc(sizeof(*psinfo), M_TEMP, M_ZERO | M_WAITOK);
21078c9b7b2cSMarcel Moolenaar 		psinfo->pr_version = PRPSINFO_VERSION;
210862919d78SPeter Wemm 		psinfo->pr_psinfosz = sizeof(elf_prpsinfo_t);
2109ccd3953eSJohn Baldwin 		strlcpy(psinfo->pr_fname, p->p_comm, sizeof(psinfo->pr_fname));
2110c77547d2SJohn Baldwin 		PROC_LOCK(p);
2111c77547d2SJohn Baldwin 		if (p->p_args != NULL) {
2112c77547d2SJohn Baldwin 			len = sizeof(psinfo->pr_psargs) - 1;
2113c77547d2SJohn Baldwin 			if (len > p->p_args->ar_length)
2114c77547d2SJohn Baldwin 				len = p->p_args->ar_length;
2115c77547d2SJohn Baldwin 			memcpy(psinfo->pr_psargs, p->p_args->ar_args, len);
2116c77547d2SJohn Baldwin 			PROC_UNLOCK(p);
2117c77547d2SJohn Baldwin 			error = 0;
2118c77547d2SJohn Baldwin 		} else {
2119c77547d2SJohn Baldwin 			_PHOLD(p);
2120c77547d2SJohn Baldwin 			PROC_UNLOCK(p);
2121c77547d2SJohn Baldwin 			sbuf_new(&sbarg, psinfo->pr_psargs,
2122c77547d2SJohn Baldwin 			    sizeof(psinfo->pr_psargs), SBUF_FIXEDLEN);
2123c77547d2SJohn Baldwin 			error = proc_getargv(curthread, p, &sbarg);
2124c77547d2SJohn Baldwin 			PRELE(p);
2125c77547d2SJohn Baldwin 			if (sbuf_finish(&sbarg) == 0)
2126c77547d2SJohn Baldwin 				len = sbuf_len(&sbarg) - 1;
2127c77547d2SJohn Baldwin 			else
2128c77547d2SJohn Baldwin 				len = sizeof(psinfo->pr_psargs) - 1;
2129c77547d2SJohn Baldwin 			sbuf_delete(&sbarg);
2130c77547d2SJohn Baldwin 		}
2131c77547d2SJohn Baldwin 		if (error || len == 0)
2132ccd3953eSJohn Baldwin 			strlcpy(psinfo->pr_psargs, p->p_comm,
21338c9b7b2cSMarcel Moolenaar 			    sizeof(psinfo->pr_psargs));
2134c77547d2SJohn Baldwin 		else {
2135c77547d2SJohn Baldwin 			KASSERT(len < sizeof(psinfo->pr_psargs),
2136c77547d2SJohn Baldwin 			    ("len is too long: %zu vs %zu", len,
2137c77547d2SJohn Baldwin 			    sizeof(psinfo->pr_psargs)));
2138c77547d2SJohn Baldwin 			cp = psinfo->pr_psargs;
2139c77547d2SJohn Baldwin 			end = cp + len - 1;
2140c77547d2SJohn Baldwin 			for (;;) {
2141c77547d2SJohn Baldwin 				cp = memchr(cp, '\0', end - cp);
2142c77547d2SJohn Baldwin 				if (cp == NULL)
2143c77547d2SJohn Baldwin 					break;
2144c77547d2SJohn Baldwin 				*cp = ' ';
2145c77547d2SJohn Baldwin 			}
2146c77547d2SJohn Baldwin 		}
2147ccb83afdSJohn Baldwin 		psinfo->pr_pid = p->p_pid;
2148bd390213SMikolaj Golub 		sbuf_bcat(sb, psinfo, sizeof(*psinfo));
2149bd390213SMikolaj Golub 		free(psinfo, M_TEMP);
2150bd390213SMikolaj Golub 	}
2151bd390213SMikolaj Golub 	*sizep = sizeof(*psinfo);
2152bd390213SMikolaj Golub }
2153bd390213SMikolaj Golub 
2154bd390213SMikolaj Golub static void
2155bd390213SMikolaj Golub __elfN(note_prstatus)(void *arg, struct sbuf *sb, size_t *sizep)
2156bd390213SMikolaj Golub {
2157bd390213SMikolaj Golub 	struct thread *td;
2158bd390213SMikolaj Golub 	elf_prstatus_t *status;
2159bd390213SMikolaj Golub 
2160bd390213SMikolaj Golub 	td = (struct thread *)arg;
2161bd390213SMikolaj Golub 	if (sb != NULL) {
2162bd390213SMikolaj Golub 		KASSERT(*sizep == sizeof(*status), ("invalid size"));
2163bd390213SMikolaj Golub 		status = malloc(sizeof(*status), M_TEMP, M_ZERO | M_WAITOK);
21648c9b7b2cSMarcel Moolenaar 		status->pr_version = PRSTATUS_VERSION;
216562919d78SPeter Wemm 		status->pr_statussz = sizeof(elf_prstatus_t);
216662919d78SPeter Wemm 		status->pr_gregsetsz = sizeof(elf_gregset_t);
216762919d78SPeter Wemm 		status->pr_fpregsetsz = sizeof(elf_fpregset_t);
21688c9b7b2cSMarcel Moolenaar 		status->pr_osreldate = osreldate;
2169bd390213SMikolaj Golub 		status->pr_cursig = td->td_proc->p_sig;
2170bd390213SMikolaj Golub 		status->pr_pid = td->td_tid;
2171841c0c7eSNathan Whitehorn #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
2172bd390213SMikolaj Golub 		fill_regs32(td, &status->pr_reg);
217362919d78SPeter Wemm #else
2174bd390213SMikolaj Golub 		fill_regs(td, &status->pr_reg);
217562919d78SPeter Wemm #endif
2176bd390213SMikolaj Golub 		sbuf_bcat(sb, status, sizeof(*status));
2177bd390213SMikolaj Golub 		free(status, M_TEMP);
21788c9b7b2cSMarcel Moolenaar 	}
2179bd390213SMikolaj Golub 	*sizep = sizeof(*status);
2180bd390213SMikolaj Golub }
2181bd390213SMikolaj Golub 
2182bd390213SMikolaj Golub static void
2183bd390213SMikolaj Golub __elfN(note_fpregset)(void *arg, struct sbuf *sb, size_t *sizep)
2184bd390213SMikolaj Golub {
2185bd390213SMikolaj Golub 	struct thread *td;
2186bd390213SMikolaj Golub 	elf_prfpregset_t *fpregset;
2187bd390213SMikolaj Golub 
2188bd390213SMikolaj Golub 	td = (struct thread *)arg;
2189bd390213SMikolaj Golub 	if (sb != NULL) {
2190bd390213SMikolaj Golub 		KASSERT(*sizep == sizeof(*fpregset), ("invalid size"));
2191bd390213SMikolaj Golub 		fpregset = malloc(sizeof(*fpregset), M_TEMP, M_ZERO | M_WAITOK);
2192bd390213SMikolaj Golub #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
2193bd390213SMikolaj Golub 		fill_fpregs32(td, fpregset);
2194bd390213SMikolaj Golub #else
2195bd390213SMikolaj Golub 		fill_fpregs(td, fpregset);
2196bd390213SMikolaj Golub #endif
2197bd390213SMikolaj Golub 		sbuf_bcat(sb, fpregset, sizeof(*fpregset));
2198bd390213SMikolaj Golub 		free(fpregset, M_TEMP);
2199bd390213SMikolaj Golub 	}
2200bd390213SMikolaj Golub 	*sizep = sizeof(*fpregset);
2201bd390213SMikolaj Golub }
2202bd390213SMikolaj Golub 
2203bd390213SMikolaj Golub static void
2204bd390213SMikolaj Golub __elfN(note_thrmisc)(void *arg, struct sbuf *sb, size_t *sizep)
2205bd390213SMikolaj Golub {
2206bd390213SMikolaj Golub 	struct thread *td;
2207bd390213SMikolaj Golub 	elf_thrmisc_t thrmisc;
2208bd390213SMikolaj Golub 
2209bd390213SMikolaj Golub 	td = (struct thread *)arg;
2210bd390213SMikolaj Golub 	if (sb != NULL) {
2211bd390213SMikolaj Golub 		KASSERT(*sizep == sizeof(thrmisc), ("invalid size"));
2212bd390213SMikolaj Golub 		bzero(&thrmisc._pad, sizeof(thrmisc._pad));
2213bd390213SMikolaj Golub 		strcpy(thrmisc.pr_tname, td->td_name);
2214bd390213SMikolaj Golub 		sbuf_bcat(sb, &thrmisc, sizeof(thrmisc));
2215bd390213SMikolaj Golub 	}
2216bd390213SMikolaj Golub 	*sizep = sizeof(thrmisc);
2217bd390213SMikolaj Golub }
2218bd390213SMikolaj Golub 
221986be94fcSTycho Nightingale static void
222086be94fcSTycho Nightingale __elfN(note_ptlwpinfo)(void *arg, struct sbuf *sb, size_t *sizep)
222186be94fcSTycho Nightingale {
222286be94fcSTycho Nightingale 	struct thread *td;
222386be94fcSTycho Nightingale 	size_t size;
222486be94fcSTycho Nightingale 	int structsize;
222551645e83SJohn Baldwin #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
222651645e83SJohn Baldwin 	struct ptrace_lwpinfo32 pl;
222751645e83SJohn Baldwin #else
222886be94fcSTycho Nightingale 	struct ptrace_lwpinfo pl;
222951645e83SJohn Baldwin #endif
223086be94fcSTycho Nightingale 
223186be94fcSTycho Nightingale 	td = (struct thread *)arg;
223251645e83SJohn Baldwin 	size = sizeof(structsize) + sizeof(pl);
223386be94fcSTycho Nightingale 	if (sb != NULL) {
223486be94fcSTycho Nightingale 		KASSERT(*sizep == size, ("invalid size"));
223551645e83SJohn Baldwin 		structsize = sizeof(pl);
223686be94fcSTycho Nightingale 		sbuf_bcat(sb, &structsize, sizeof(structsize));
223786be94fcSTycho Nightingale 		bzero(&pl, sizeof(pl));
223886be94fcSTycho Nightingale 		pl.pl_lwpid = td->td_tid;
223986be94fcSTycho Nightingale 		pl.pl_event = PL_EVENT_NONE;
224086be94fcSTycho Nightingale 		pl.pl_sigmask = td->td_sigmask;
224186be94fcSTycho Nightingale 		pl.pl_siglist = td->td_siglist;
224286be94fcSTycho Nightingale 		if (td->td_si.si_signo != 0) {
224386be94fcSTycho Nightingale 			pl.pl_event = PL_EVENT_SIGNAL;
224486be94fcSTycho Nightingale 			pl.pl_flags |= PL_FLAG_SI;
224551645e83SJohn Baldwin #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
224651645e83SJohn Baldwin 			siginfo_to_siginfo32(&td->td_si, &pl.pl_siginfo);
224751645e83SJohn Baldwin #else
224886be94fcSTycho Nightingale 			pl.pl_siginfo = td->td_si;
224951645e83SJohn Baldwin #endif
225086be94fcSTycho Nightingale 		}
225186be94fcSTycho Nightingale 		strcpy(pl.pl_tdname, td->td_name);
225286be94fcSTycho Nightingale 		/* XXX TODO: supply more information in struct ptrace_lwpinfo*/
225351645e83SJohn Baldwin 		sbuf_bcat(sb, &pl, sizeof(pl));
225486be94fcSTycho Nightingale 	}
225586be94fcSTycho Nightingale 	*sizep = size;
225686be94fcSTycho Nightingale }
225786be94fcSTycho Nightingale 
22584da47b2fSMarcel Moolenaar /*
22594da47b2fSMarcel Moolenaar  * Allow for MD specific notes, as well as any MD
22604da47b2fSMarcel Moolenaar  * specific preparations for writing MI notes.
22614da47b2fSMarcel Moolenaar  */
22628c64af4fSJohn Polstra static void
2263bd390213SMikolaj Golub __elfN(note_threadmd)(void *arg, struct sbuf *sb, size_t *sizep)
22648c64af4fSJohn Polstra {
2265bd390213SMikolaj Golub 	struct thread *td;
2266bd390213SMikolaj Golub 	void *buf;
2267bd390213SMikolaj Golub 	size_t size;
22688c64af4fSJohn Polstra 
2269bd390213SMikolaj Golub 	td = (struct thread *)arg;
2270bd390213SMikolaj Golub 	size = *sizep;
2271bd390213SMikolaj Golub 	if (size != 0 && sb != NULL)
2272bd390213SMikolaj Golub 		buf = malloc(size, M_TEMP, M_ZERO | M_WAITOK);
227383a396ceSChristian Brueffer 	else
227483a396ceSChristian Brueffer 		buf = NULL;
2275bd390213SMikolaj Golub 	size = 0;
2276bd390213SMikolaj Golub 	__elfN(dump_thread)(td, buf, &size);
227764779280SKonstantin Belousov 	KASSERT(sb == NULL || *sizep == size, ("invalid size"));
227883a396ceSChristian Brueffer 	if (size != 0 && sb != NULL)
2279bd390213SMikolaj Golub 		sbuf_bcat(sb, buf, size);
2280a1761d73SChristian Brueffer 	free(buf, M_TEMP);
2281bd390213SMikolaj Golub 	*sizep = size;
22828c64af4fSJohn Polstra }
22838c64af4fSJohn Polstra 
2284f1fca82eSMikolaj Golub #ifdef KINFO_PROC_SIZE
2285f1fca82eSMikolaj Golub CTASSERT(sizeof(struct kinfo_proc) == KINFO_PROC_SIZE);
2286f1fca82eSMikolaj Golub #endif
2287f1fca82eSMikolaj Golub 
2288f1fca82eSMikolaj Golub static void
2289f1fca82eSMikolaj Golub __elfN(note_procstat_proc)(void *arg, struct sbuf *sb, size_t *sizep)
2290f1fca82eSMikolaj Golub {
2291f1fca82eSMikolaj Golub 	struct proc *p;
2292f1fca82eSMikolaj Golub 	size_t size;
2293f1fca82eSMikolaj Golub 	int structsize;
2294f1fca82eSMikolaj Golub 
2295f1fca82eSMikolaj Golub 	p = (struct proc *)arg;
2296f1fca82eSMikolaj Golub 	size = sizeof(structsize) + p->p_numthreads *
2297f1fca82eSMikolaj Golub 	    sizeof(elf_kinfo_proc_t);
2298f1fca82eSMikolaj Golub 
2299f1fca82eSMikolaj Golub 	if (sb != NULL) {
2300f1fca82eSMikolaj Golub 		KASSERT(*sizep == size, ("invalid size"));
2301f1fca82eSMikolaj Golub 		structsize = sizeof(elf_kinfo_proc_t);
2302f1fca82eSMikolaj Golub 		sbuf_bcat(sb, &structsize, sizeof(structsize));
2303f1fca82eSMikolaj Golub 		PROC_LOCK(p);
2304f1fca82eSMikolaj Golub 		kern_proc_out(p, sb, ELF_KERN_PROC_MASK);
2305f1fca82eSMikolaj Golub 	}
2306f1fca82eSMikolaj Golub 	*sizep = size;
2307f1fca82eSMikolaj Golub }
2308f1fca82eSMikolaj Golub 
2309f1fca82eSMikolaj Golub #ifdef KINFO_FILE_SIZE
2310f1fca82eSMikolaj Golub CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
2311f1fca82eSMikolaj Golub #endif
2312f1fca82eSMikolaj Golub 
2313f1fca82eSMikolaj Golub static void
2314f1fca82eSMikolaj Golub note_procstat_files(void *arg, struct sbuf *sb, size_t *sizep)
2315f1fca82eSMikolaj Golub {
2316f1fca82eSMikolaj Golub 	struct proc *p;
231714bdbaf2SConrad Meyer 	size_t size, sect_sz, i;
231814bdbaf2SConrad Meyer 	ssize_t start_len, sect_len;
231914bdbaf2SConrad Meyer 	int structsize, filedesc_flags;
232014bdbaf2SConrad Meyer 
2321bcb60d52SConrad Meyer 	if (coredump_pack_fileinfo)
232214bdbaf2SConrad Meyer 		filedesc_flags = KERN_FILEDESC_PACK_KINFO;
232314bdbaf2SConrad Meyer 	else
232414bdbaf2SConrad Meyer 		filedesc_flags = 0;
2325f1fca82eSMikolaj Golub 
2326f1fca82eSMikolaj Golub 	p = (struct proc *)arg;
232714bdbaf2SConrad Meyer 	structsize = sizeof(struct kinfo_file);
2328f1fca82eSMikolaj Golub 	if (sb == NULL) {
2329f1fca82eSMikolaj Golub 		size = 0;
2330f1fca82eSMikolaj Golub 		sb = sbuf_new(NULL, NULL, 128, SBUF_FIXEDLEN);
23315c32e9fcSAlexander Motin 		sbuf_set_drain(sb, sbuf_count_drain, &size);
2332f1fca82eSMikolaj Golub 		sbuf_bcat(sb, &structsize, sizeof(structsize));
2333f1fca82eSMikolaj Golub 		PROC_LOCK(p);
233414bdbaf2SConrad Meyer 		kern_proc_filedesc_out(p, sb, -1, filedesc_flags);
2335f1fca82eSMikolaj Golub 		sbuf_finish(sb);
2336f1fca82eSMikolaj Golub 		sbuf_delete(sb);
2337f1fca82eSMikolaj Golub 		*sizep = size;
2338f1fca82eSMikolaj Golub 	} else {
233914bdbaf2SConrad Meyer 		sbuf_start_section(sb, &start_len);
234014bdbaf2SConrad Meyer 
2341f1fca82eSMikolaj Golub 		sbuf_bcat(sb, &structsize, sizeof(structsize));
2342f1fca82eSMikolaj Golub 		PROC_LOCK(p);
234314bdbaf2SConrad Meyer 		kern_proc_filedesc_out(p, sb, *sizep - sizeof(structsize),
234414bdbaf2SConrad Meyer 		    filedesc_flags);
234514bdbaf2SConrad Meyer 
234614bdbaf2SConrad Meyer 		sect_len = sbuf_end_section(sb, start_len, 0, 0);
234714bdbaf2SConrad Meyer 		if (sect_len < 0)
234814bdbaf2SConrad Meyer 			return;
234914bdbaf2SConrad Meyer 		sect_sz = sect_len;
235014bdbaf2SConrad Meyer 
235114bdbaf2SConrad Meyer 		KASSERT(sect_sz <= *sizep,
235214bdbaf2SConrad Meyer 		    ("kern_proc_filedesc_out did not respect maxlen; "
235314bdbaf2SConrad Meyer 		     "requested %zu, got %zu", *sizep - sizeof(structsize),
235414bdbaf2SConrad Meyer 		     sect_sz - sizeof(structsize)));
235514bdbaf2SConrad Meyer 
235614bdbaf2SConrad Meyer 		for (i = 0; i < *sizep - sect_sz && sb->s_error == 0; i++)
235714bdbaf2SConrad Meyer 			sbuf_putc(sb, 0);
2358f1fca82eSMikolaj Golub 	}
2359f1fca82eSMikolaj Golub }
2360f1fca82eSMikolaj Golub 
2361f1fca82eSMikolaj Golub #ifdef KINFO_VMENTRY_SIZE
2362f1fca82eSMikolaj Golub CTASSERT(sizeof(struct kinfo_vmentry) == KINFO_VMENTRY_SIZE);
2363f1fca82eSMikolaj Golub #endif
2364f1fca82eSMikolaj Golub 
2365f1fca82eSMikolaj Golub static void
2366f1fca82eSMikolaj Golub note_procstat_vmmap(void *arg, struct sbuf *sb, size_t *sizep)
2367f1fca82eSMikolaj Golub {
2368f1fca82eSMikolaj Golub 	struct proc *p;
2369f1fca82eSMikolaj Golub 	size_t size;
2370e6b95927SConrad Meyer 	int structsize, vmmap_flags;
2371e6b95927SConrad Meyer 
2372e6b95927SConrad Meyer 	if (coredump_pack_vmmapinfo)
2373e6b95927SConrad Meyer 		vmmap_flags = KERN_VMMAP_PACK_KINFO;
2374e6b95927SConrad Meyer 	else
2375e6b95927SConrad Meyer 		vmmap_flags = 0;
2376f1fca82eSMikolaj Golub 
2377f1fca82eSMikolaj Golub 	p = (struct proc *)arg;
2378e6b95927SConrad Meyer 	structsize = sizeof(struct kinfo_vmentry);
2379f1fca82eSMikolaj Golub 	if (sb == NULL) {
2380f1fca82eSMikolaj Golub 		size = 0;
2381f1fca82eSMikolaj Golub 		sb = sbuf_new(NULL, NULL, 128, SBUF_FIXEDLEN);
23825c32e9fcSAlexander Motin 		sbuf_set_drain(sb, sbuf_count_drain, &size);
2383f1fca82eSMikolaj Golub 		sbuf_bcat(sb, &structsize, sizeof(structsize));
2384f1fca82eSMikolaj Golub 		PROC_LOCK(p);
2385e6b95927SConrad Meyer 		kern_proc_vmmap_out(p, sb, -1, vmmap_flags);
2386f1fca82eSMikolaj Golub 		sbuf_finish(sb);
2387f1fca82eSMikolaj Golub 		sbuf_delete(sb);
2388f1fca82eSMikolaj Golub 		*sizep = size;
2389f1fca82eSMikolaj Golub 	} else {
2390f1fca82eSMikolaj Golub 		sbuf_bcat(sb, &structsize, sizeof(structsize));
2391f1fca82eSMikolaj Golub 		PROC_LOCK(p);
2392e6b95927SConrad Meyer 		kern_proc_vmmap_out(p, sb, *sizep - sizeof(structsize),
2393e6b95927SConrad Meyer 		    vmmap_flags);
2394f1fca82eSMikolaj Golub 	}
2395f1fca82eSMikolaj Golub }
2396f1fca82eSMikolaj Golub 
2397f1fca82eSMikolaj Golub static void
2398f1fca82eSMikolaj Golub note_procstat_groups(void *arg, struct sbuf *sb, size_t *sizep)
2399f1fca82eSMikolaj Golub {
2400f1fca82eSMikolaj Golub 	struct proc *p;
2401f1fca82eSMikolaj Golub 	size_t size;
2402f1fca82eSMikolaj Golub 	int structsize;
2403f1fca82eSMikolaj Golub 
2404f1fca82eSMikolaj Golub 	p = (struct proc *)arg;
2405f1fca82eSMikolaj Golub 	size = sizeof(structsize) + p->p_ucred->cr_ngroups * sizeof(gid_t);
2406f1fca82eSMikolaj Golub 	if (sb != NULL) {
2407f1fca82eSMikolaj Golub 		KASSERT(*sizep == size, ("invalid size"));
2408f1fca82eSMikolaj Golub 		structsize = sizeof(gid_t);
2409f1fca82eSMikolaj Golub 		sbuf_bcat(sb, &structsize, sizeof(structsize));
2410f1fca82eSMikolaj Golub 		sbuf_bcat(sb, p->p_ucred->cr_groups, p->p_ucred->cr_ngroups *
2411f1fca82eSMikolaj Golub 		    sizeof(gid_t));
2412f1fca82eSMikolaj Golub 	}
2413f1fca82eSMikolaj Golub 	*sizep = size;
2414f1fca82eSMikolaj Golub }
2415f1fca82eSMikolaj Golub 
2416f1fca82eSMikolaj Golub static void
2417f1fca82eSMikolaj Golub note_procstat_umask(void *arg, struct sbuf *sb, size_t *sizep)
2418f1fca82eSMikolaj Golub {
2419f1fca82eSMikolaj Golub 	struct proc *p;
2420f1fca82eSMikolaj Golub 	size_t size;
2421f1fca82eSMikolaj Golub 	int structsize;
2422f1fca82eSMikolaj Golub 
2423f1fca82eSMikolaj Golub 	p = (struct proc *)arg;
2424f1fca82eSMikolaj Golub 	size = sizeof(structsize) + sizeof(p->p_fd->fd_cmask);
2425f1fca82eSMikolaj Golub 	if (sb != NULL) {
2426f1fca82eSMikolaj Golub 		KASSERT(*sizep == size, ("invalid size"));
2427f1fca82eSMikolaj Golub 		structsize = sizeof(p->p_fd->fd_cmask);
2428f1fca82eSMikolaj Golub 		sbuf_bcat(sb, &structsize, sizeof(structsize));
2429f1fca82eSMikolaj Golub 		sbuf_bcat(sb, &p->p_fd->fd_cmask, sizeof(p->p_fd->fd_cmask));
2430f1fca82eSMikolaj Golub 	}
2431f1fca82eSMikolaj Golub 	*sizep = size;
2432f1fca82eSMikolaj Golub }
2433f1fca82eSMikolaj Golub 
2434f1fca82eSMikolaj Golub static void
2435f1fca82eSMikolaj Golub note_procstat_rlimit(void *arg, struct sbuf *sb, size_t *sizep)
2436f1fca82eSMikolaj Golub {
2437f1fca82eSMikolaj Golub 	struct proc *p;
2438f1fca82eSMikolaj Golub 	struct rlimit rlim[RLIM_NLIMITS];
2439f1fca82eSMikolaj Golub 	size_t size;
2440f1fca82eSMikolaj Golub 	int structsize, i;
2441f1fca82eSMikolaj Golub 
2442f1fca82eSMikolaj Golub 	p = (struct proc *)arg;
2443f1fca82eSMikolaj Golub 	size = sizeof(structsize) + sizeof(rlim);
2444f1fca82eSMikolaj Golub 	if (sb != NULL) {
2445f1fca82eSMikolaj Golub 		KASSERT(*sizep == size, ("invalid size"));
2446f1fca82eSMikolaj Golub 		structsize = sizeof(rlim);
2447f1fca82eSMikolaj Golub 		sbuf_bcat(sb, &structsize, sizeof(structsize));
2448f1fca82eSMikolaj Golub 		PROC_LOCK(p);
2449f1fca82eSMikolaj Golub 		for (i = 0; i < RLIM_NLIMITS; i++)
2450f6f6d240SMateusz Guzik 			lim_rlimit_proc(p, i, &rlim[i]);
2451f1fca82eSMikolaj Golub 		PROC_UNLOCK(p);
2452f1fca82eSMikolaj Golub 		sbuf_bcat(sb, rlim, sizeof(rlim));
2453f1fca82eSMikolaj Golub 	}
2454f1fca82eSMikolaj Golub 	*sizep = size;
2455f1fca82eSMikolaj Golub }
2456f1fca82eSMikolaj Golub 
2457f1fca82eSMikolaj Golub static void
2458f1fca82eSMikolaj Golub note_procstat_osrel(void *arg, struct sbuf *sb, size_t *sizep)
2459f1fca82eSMikolaj Golub {
2460f1fca82eSMikolaj Golub 	struct proc *p;
2461f1fca82eSMikolaj Golub 	size_t size;
2462f1fca82eSMikolaj Golub 	int structsize;
2463f1fca82eSMikolaj Golub 
2464f1fca82eSMikolaj Golub 	p = (struct proc *)arg;
2465f1fca82eSMikolaj Golub 	size = sizeof(structsize) + sizeof(p->p_osrel);
2466f1fca82eSMikolaj Golub 	if (sb != NULL) {
2467f1fca82eSMikolaj Golub 		KASSERT(*sizep == size, ("invalid size"));
2468f1fca82eSMikolaj Golub 		structsize = sizeof(p->p_osrel);
2469f1fca82eSMikolaj Golub 		sbuf_bcat(sb, &structsize, sizeof(structsize));
2470f1fca82eSMikolaj Golub 		sbuf_bcat(sb, &p->p_osrel, sizeof(p->p_osrel));
2471f1fca82eSMikolaj Golub 	}
2472f1fca82eSMikolaj Golub 	*sizep = size;
2473f1fca82eSMikolaj Golub }
2474f1fca82eSMikolaj Golub 
2475f1fca82eSMikolaj Golub static void
2476f1fca82eSMikolaj Golub __elfN(note_procstat_psstrings)(void *arg, struct sbuf *sb, size_t *sizep)
2477f1fca82eSMikolaj Golub {
2478f1fca82eSMikolaj Golub 	struct proc *p;
2479f1fca82eSMikolaj Golub 	elf_ps_strings_t ps_strings;
2480f1fca82eSMikolaj Golub 	size_t size;
2481f1fca82eSMikolaj Golub 	int structsize;
2482f1fca82eSMikolaj Golub 
2483f1fca82eSMikolaj Golub 	p = (struct proc *)arg;
2484f1fca82eSMikolaj Golub 	size = sizeof(structsize) + sizeof(ps_strings);
2485f1fca82eSMikolaj Golub 	if (sb != NULL) {
2486f1fca82eSMikolaj Golub 		KASSERT(*sizep == size, ("invalid size"));
2487f1fca82eSMikolaj Golub 		structsize = sizeof(ps_strings);
2488f1fca82eSMikolaj Golub #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
2489f1fca82eSMikolaj Golub 		ps_strings = PTROUT(p->p_sysent->sv_psstrings);
2490f1fca82eSMikolaj Golub #else
2491f1fca82eSMikolaj Golub 		ps_strings = p->p_sysent->sv_psstrings;
2492f1fca82eSMikolaj Golub #endif
2493f1fca82eSMikolaj Golub 		sbuf_bcat(sb, &structsize, sizeof(structsize));
2494f1fca82eSMikolaj Golub 		sbuf_bcat(sb, &ps_strings, sizeof(ps_strings));
2495f1fca82eSMikolaj Golub 	}
2496f1fca82eSMikolaj Golub 	*sizep = size;
2497f1fca82eSMikolaj Golub }
2498f1fca82eSMikolaj Golub 
2499f1fca82eSMikolaj Golub static void
2500f1fca82eSMikolaj Golub __elfN(note_procstat_auxv)(void *arg, struct sbuf *sb, size_t *sizep)
2501f1fca82eSMikolaj Golub {
2502f1fca82eSMikolaj Golub 	struct proc *p;
2503f1fca82eSMikolaj Golub 	size_t size;
2504f1fca82eSMikolaj Golub 	int structsize;
2505f1fca82eSMikolaj Golub 
2506f1fca82eSMikolaj Golub 	p = (struct proc *)arg;
2507f1fca82eSMikolaj Golub 	if (sb == NULL) {
2508f1fca82eSMikolaj Golub 		size = 0;
2509f1fca82eSMikolaj Golub 		sb = sbuf_new(NULL, NULL, 128, SBUF_FIXEDLEN);
25105c32e9fcSAlexander Motin 		sbuf_set_drain(sb, sbuf_count_drain, &size);
2511f1fca82eSMikolaj Golub 		sbuf_bcat(sb, &structsize, sizeof(structsize));
2512f1fca82eSMikolaj Golub 		PHOLD(p);
2513f1fca82eSMikolaj Golub 		proc_getauxv(curthread, p, sb);
2514f1fca82eSMikolaj Golub 		PRELE(p);
2515f1fca82eSMikolaj Golub 		sbuf_finish(sb);
2516f1fca82eSMikolaj Golub 		sbuf_delete(sb);
2517f1fca82eSMikolaj Golub 		*sizep = size;
2518f1fca82eSMikolaj Golub 	} else {
2519f1fca82eSMikolaj Golub 		structsize = sizeof(Elf_Auxinfo);
2520f1fca82eSMikolaj Golub 		sbuf_bcat(sb, &structsize, sizeof(structsize));
2521f1fca82eSMikolaj Golub 		PHOLD(p);
2522f1fca82eSMikolaj Golub 		proc_getauxv(curthread, p, sb);
2523f1fca82eSMikolaj Golub 		PRELE(p);
2524f1fca82eSMikolaj Golub 	}
2525f1fca82eSMikolaj Golub }
2526f1fca82eSMikolaj Golub 
252732c01de2SDmitry Chagin static boolean_t
252892328a32SKonstantin Belousov __elfN(parse_notes)(struct image_params *imgp, Elf_Note *checknote,
252992328a32SKonstantin Belousov     const char *note_vendor, const Elf_Phdr *pnote,
253092328a32SKonstantin Belousov     boolean_t (*cb)(const Elf_Note *, void *, boolean_t *), void *cb_arg)
253132c01de2SDmitry Chagin {
2532267c52fcSKonstantin Belousov 	const Elf_Note *note, *note0, *note_end;
253332c01de2SDmitry Chagin 	const char *note_name;
25346c775eb6SKonstantin Belousov 	char *buf;
25356c775eb6SKonstantin Belousov 	int i, error;
25366c775eb6SKonstantin Belousov 	boolean_t res;
253732c01de2SDmitry Chagin 
25386c775eb6SKonstantin Belousov 	/* We need some limit, might as well use PAGE_SIZE. */
25396c775eb6SKonstantin Belousov 	if (pnote == NULL || pnote->p_filesz > PAGE_SIZE)
254032c01de2SDmitry Chagin 		return (FALSE);
25416c775eb6SKonstantin Belousov 	ASSERT_VOP_LOCKED(imgp->vp, "parse_notes");
25426c775eb6SKonstantin Belousov 	if (pnote->p_offset > PAGE_SIZE ||
25436c775eb6SKonstantin Belousov 	    pnote->p_filesz > PAGE_SIZE - pnote->p_offset) {
25442d6b8546SKonstantin Belousov 		buf = malloc(pnote->p_filesz, M_TEMP, M_NOWAIT);
25452d6b8546SKonstantin Belousov 		if (buf == NULL) {
25466c775eb6SKonstantin Belousov 			VOP_UNLOCK(imgp->vp, 0);
25476c775eb6SKonstantin Belousov 			buf = malloc(pnote->p_filesz, M_TEMP, M_WAITOK);
254878022527SKonstantin Belousov 			vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
25492d6b8546SKonstantin Belousov 		}
25506c775eb6SKonstantin Belousov 		error = vn_rdwr(UIO_READ, imgp->vp, buf, pnote->p_filesz,
25516c775eb6SKonstantin Belousov 		    pnote->p_offset, UIO_SYSSPACE, IO_NODELOCKED,
25526c775eb6SKonstantin Belousov 		    curthread->td_ucred, NOCRED, NULL, curthread);
25536c775eb6SKonstantin Belousov 		if (error != 0) {
25546c775eb6SKonstantin Belousov 			uprintf("i/o error PT_NOTE\n");
2555eda8fe63SKonstantin Belousov 			goto retf;
25566c775eb6SKonstantin Belousov 		}
25576c775eb6SKonstantin Belousov 		note = note0 = (const Elf_Note *)buf;
25586c775eb6SKonstantin Belousov 		note_end = (const Elf_Note *)(buf + pnote->p_filesz);
25596c775eb6SKonstantin Belousov 	} else {
25606c775eb6SKonstantin Belousov 		note = note0 = (const Elf_Note *)(imgp->image_header +
25616c775eb6SKonstantin Belousov 		    pnote->p_offset);
256232c01de2SDmitry Chagin 		note_end = (const Elf_Note *)(imgp->image_header +
256332c01de2SDmitry Chagin 		    pnote->p_offset + pnote->p_filesz);
25646c775eb6SKonstantin Belousov 		buf = NULL;
25656c775eb6SKonstantin Belousov 	}
2566267c52fcSKonstantin Belousov 	for (i = 0; i < 100 && note >= note0 && note < note_end; i++) {
2567d1ae5c83SKonstantin Belousov 		if (!aligned(note, Elf32_Addr) || (const char *)note_end -
25686c775eb6SKonstantin Belousov 		    (const char *)note < sizeof(Elf_Note)) {
2569eda8fe63SKonstantin Belousov 			goto retf;
25706c775eb6SKonstantin Belousov 		}
257192328a32SKonstantin Belousov 		if (note->n_namesz != checknote->n_namesz ||
257292328a32SKonstantin Belousov 		    note->n_descsz != checknote->n_descsz ||
257392328a32SKonstantin Belousov 		    note->n_type != checknote->n_type)
257432c01de2SDmitry Chagin 			goto nextnote;
257532c01de2SDmitry Chagin 		note_name = (const char *)(note + 1);
257692328a32SKonstantin Belousov 		if (note_name + checknote->n_namesz >=
257792328a32SKonstantin Belousov 		    (const char *)note_end || strncmp(note_vendor,
257892328a32SKonstantin Belousov 		    note_name, checknote->n_namesz) != 0)
257932c01de2SDmitry Chagin 			goto nextnote;
258032c01de2SDmitry Chagin 
258192328a32SKonstantin Belousov 		if (cb(note, cb_arg, &res))
25826c775eb6SKonstantin Belousov 			goto ret;
258332c01de2SDmitry Chagin nextnote:
258432c01de2SDmitry Chagin 		note = (const Elf_Note *)((const char *)(note + 1) +
25851b8388cdSMikolaj Golub 		    roundup2(note->n_namesz, ELF_NOTE_ROUNDSIZE) +
25861b8388cdSMikolaj Golub 		    roundup2(note->n_descsz, ELF_NOTE_ROUNDSIZE));
258732c01de2SDmitry Chagin 	}
2588eda8fe63SKonstantin Belousov retf:
25896c775eb6SKonstantin Belousov 	res = FALSE;
25906c775eb6SKonstantin Belousov ret:
25916c775eb6SKonstantin Belousov 	free(buf, M_TEMP);
25926c775eb6SKonstantin Belousov 	return (res);
259332c01de2SDmitry Chagin }
259432c01de2SDmitry Chagin 
259592328a32SKonstantin Belousov struct brandnote_cb_arg {
259692328a32SKonstantin Belousov 	Elf_Brandnote *brandnote;
259792328a32SKonstantin Belousov 	int32_t *osrel;
259892328a32SKonstantin Belousov };
259992328a32SKonstantin Belousov 
260092328a32SKonstantin Belousov static boolean_t
260192328a32SKonstantin Belousov brandnote_cb(const Elf_Note *note, void *arg0, boolean_t *res)
260292328a32SKonstantin Belousov {
260392328a32SKonstantin Belousov 	struct brandnote_cb_arg *arg;
260492328a32SKonstantin Belousov 
260592328a32SKonstantin Belousov 	arg = arg0;
260692328a32SKonstantin Belousov 
260792328a32SKonstantin Belousov 	/*
260892328a32SKonstantin Belousov 	 * Fetch the osreldate for binary from the ELF OSABI-note if
260992328a32SKonstantin Belousov 	 * necessary.
261092328a32SKonstantin Belousov 	 */
261192328a32SKonstantin Belousov 	*res = (arg->brandnote->flags & BN_TRANSLATE_OSREL) != 0 &&
261292328a32SKonstantin Belousov 	    arg->brandnote->trans_osrel != NULL ?
261392328a32SKonstantin Belousov 	    arg->brandnote->trans_osrel(note, arg->osrel) : TRUE;
261492328a32SKonstantin Belousov 
261592328a32SKonstantin Belousov 	return (TRUE);
261692328a32SKonstantin Belousov }
261792328a32SKonstantin Belousov 
2618cefb93f2SKonstantin Belousov static Elf_Note fctl_note = {
2619cefb93f2SKonstantin Belousov 	.n_namesz = sizeof(FREEBSD_ABI_VENDOR),
2620cefb93f2SKonstantin Belousov 	.n_descsz = sizeof(uint32_t),
2621cefb93f2SKonstantin Belousov 	.n_type = NT_FREEBSD_FEATURE_CTL,
2622cefb93f2SKonstantin Belousov };
2623cefb93f2SKonstantin Belousov 
2624cefb93f2SKonstantin Belousov struct fctl_cb_arg {
2625cefb93f2SKonstantin Belousov 	uint32_t *fctl0;
2626cefb93f2SKonstantin Belousov };
2627cefb93f2SKonstantin Belousov 
2628cefb93f2SKonstantin Belousov static boolean_t
2629cefb93f2SKonstantin Belousov note_fctl_cb(const Elf_Note *note, void *arg0, boolean_t *res)
2630cefb93f2SKonstantin Belousov {
2631cefb93f2SKonstantin Belousov 	struct fctl_cb_arg *arg;
2632cefb93f2SKonstantin Belousov 	const Elf32_Word *desc;
2633cefb93f2SKonstantin Belousov 	uintptr_t p;
2634cefb93f2SKonstantin Belousov 
2635cefb93f2SKonstantin Belousov 	arg = arg0;
2636cefb93f2SKonstantin Belousov 	p = (uintptr_t)(note + 1);
2637cefb93f2SKonstantin Belousov 	p += roundup2(note->n_namesz, ELF_NOTE_ROUNDSIZE);
2638cefb93f2SKonstantin Belousov 	desc = (const Elf32_Word *)p;
2639cefb93f2SKonstantin Belousov 	*arg->fctl0 = desc[0];
2640cefb93f2SKonstantin Belousov 	return (TRUE);
2641cefb93f2SKonstantin Belousov }
2642cefb93f2SKonstantin Belousov 
264332c01de2SDmitry Chagin /*
2644cefb93f2SKonstantin Belousov  * Try to find the appropriate ABI-note section for checknote, fetch
2645cefb93f2SKonstantin Belousov  * the osreldate and feature control flags for binary from the ELF
2646cefb93f2SKonstantin Belousov  * OSABI-note.  Only the first page of the image is searched, the same
2647cefb93f2SKonstantin Belousov  * as for headers.
26481a9c7decSKonstantin Belousov  */
26491a9c7decSKonstantin Belousov static boolean_t
265092328a32SKonstantin Belousov __elfN(check_note)(struct image_params *imgp, Elf_Brandnote *brandnote,
2651cefb93f2SKonstantin Belousov     int32_t *osrel, uint32_t *fctl0)
26521a9c7decSKonstantin Belousov {
26531a9c7decSKonstantin Belousov 	const Elf_Phdr *phdr;
26541a9c7decSKonstantin Belousov 	const Elf_Ehdr *hdr;
265592328a32SKonstantin Belousov 	struct brandnote_cb_arg b_arg;
2656cefb93f2SKonstantin Belousov 	struct fctl_cb_arg f_arg;
2657cefb93f2SKonstantin Belousov 	int i, j;
26581a9c7decSKonstantin Belousov 
26591a9c7decSKonstantin Belousov 	hdr = (const Elf_Ehdr *)imgp->image_header;
26601a9c7decSKonstantin Belousov 	phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
266192328a32SKonstantin Belousov 	b_arg.brandnote = brandnote;
266292328a32SKonstantin Belousov 	b_arg.osrel = osrel;
2663cefb93f2SKonstantin Belousov 	f_arg.fctl0 = fctl0;
26641a9c7decSKonstantin Belousov 
26651a9c7decSKonstantin Belousov 	for (i = 0; i < hdr->e_phnum; i++) {
266692328a32SKonstantin Belousov 		if (phdr[i].p_type == PT_NOTE && __elfN(parse_notes)(imgp,
266792328a32SKonstantin Belousov 		    &brandnote->hdr, brandnote->vendor, &phdr[i], brandnote_cb,
266892328a32SKonstantin Belousov 		    &b_arg)) {
2669cefb93f2SKonstantin Belousov 			for (j = 0; j < hdr->e_phnum; j++) {
2670cefb93f2SKonstantin Belousov 				if (phdr[j].p_type == PT_NOTE &&
2671cefb93f2SKonstantin Belousov 				    __elfN(parse_notes)(imgp, &fctl_note,
2672cefb93f2SKonstantin Belousov 				    FREEBSD_ABI_VENDOR, &phdr[j],
2673cefb93f2SKonstantin Belousov 				    note_fctl_cb, &f_arg))
2674cefb93f2SKonstantin Belousov 					break;
2675cefb93f2SKonstantin Belousov 			}
26761a9c7decSKonstantin Belousov 			return (TRUE);
26771a9c7decSKonstantin Belousov 		}
267892328a32SKonstantin Belousov 	}
26791a9c7decSKonstantin Belousov 	return (FALSE);
26801a9c7decSKonstantin Belousov 
26811a9c7decSKonstantin Belousov }
26821a9c7decSKonstantin Belousov 
26831a9c7decSKonstantin Belousov /*
2684e1743d02SSøren Schmidt  * Tell kern_execve.c about it, with a little help from the linker.
2685e1743d02SSøren Schmidt  */
2686a360a43dSJake Burkholder static struct execsw __elfN(execsw) = {
2687b7feabf9SEd Maste 	.ex_imgact = __CONCAT(exec_, __elfN(imgact)),
2688b7feabf9SEd Maste 	.ex_name = __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE))
2689a360a43dSJake Burkholder };
2690a360a43dSJake Burkholder EXEC_SET(__CONCAT(elf, __ELF_WORD_SIZE), __elfN(execsw));
2691e7228204SAlfred Perlstein 
2692ed167eaaSKonstantin Belousov static vm_prot_t
2693ed167eaaSKonstantin Belousov __elfN(trans_prot)(Elf_Word flags)
2694ed167eaaSKonstantin Belousov {
2695ed167eaaSKonstantin Belousov 	vm_prot_t prot;
2696ed167eaaSKonstantin Belousov 
2697ed167eaaSKonstantin Belousov 	prot = 0;
2698ed167eaaSKonstantin Belousov 	if (flags & PF_X)
2699ed167eaaSKonstantin Belousov 		prot |= VM_PROT_EXECUTE;
2700ed167eaaSKonstantin Belousov 	if (flags & PF_W)
2701ed167eaaSKonstantin Belousov 		prot |= VM_PROT_WRITE;
2702ed167eaaSKonstantin Belousov 	if (flags & PF_R)
2703ed167eaaSKonstantin Belousov 		prot |= VM_PROT_READ;
2704eb785fabSKonstantin Belousov #if __ELF_WORD_SIZE == 32 && (defined(__amd64__) || defined(__i386__))
2705126b36a2SKonstantin Belousov 	if (i386_read_exec && (flags & PF_R))
2706676eda08SMarcel Moolenaar 		prot |= VM_PROT_EXECUTE;
2707676eda08SMarcel Moolenaar #endif
2708ed167eaaSKonstantin Belousov 	return (prot);
2709ed167eaaSKonstantin Belousov }
2710ed167eaaSKonstantin Belousov 
2711ed167eaaSKonstantin Belousov static Elf_Word
2712ed167eaaSKonstantin Belousov __elfN(untrans_prot)(vm_prot_t prot)
2713ed167eaaSKonstantin Belousov {
2714ed167eaaSKonstantin Belousov 	Elf_Word flags;
2715ed167eaaSKonstantin Belousov 
2716ed167eaaSKonstantin Belousov 	flags = 0;
2717ed167eaaSKonstantin Belousov 	if (prot & VM_PROT_EXECUTE)
2718ed167eaaSKonstantin Belousov 		flags |= PF_X;
2719ed167eaaSKonstantin Belousov 	if (prot & VM_PROT_READ)
2720ed167eaaSKonstantin Belousov 		flags |= PF_R;
2721ed167eaaSKonstantin Belousov 	if (prot & VM_PROT_WRITE)
2722ed167eaaSKonstantin Belousov 		flags |= PF_W;
2723ed167eaaSKonstantin Belousov 	return (flags);
2724ed167eaaSKonstantin Belousov }
2725fc83c5a7SKonstantin Belousov 
2726fc83c5a7SKonstantin Belousov void
2727fc83c5a7SKonstantin Belousov __elfN(stackgap)(struct image_params *imgp, u_long *stack_base)
2728fc83c5a7SKonstantin Belousov {
2729fc83c5a7SKonstantin Belousov 	u_long range, rbase, gap;
2730fc83c5a7SKonstantin Belousov 	int pct;
2731fc83c5a7SKonstantin Belousov 
2732fc83c5a7SKonstantin Belousov 	if ((imgp->map_flags & MAP_ASLR) == 0)
2733fc83c5a7SKonstantin Belousov 		return;
2734fc83c5a7SKonstantin Belousov 	pct = __elfN(aslr_stack_gap);
2735fc83c5a7SKonstantin Belousov 	if (pct == 0)
2736fc83c5a7SKonstantin Belousov 		return;
2737fc83c5a7SKonstantin Belousov 	if (pct > 50)
2738fc83c5a7SKonstantin Belousov 		pct = 50;
2739fc83c5a7SKonstantin Belousov 	range = imgp->eff_stack_sz * pct / 100;
2740fc83c5a7SKonstantin Belousov 	arc4rand(&rbase, sizeof(rbase), 0);
2741fc83c5a7SKonstantin Belousov 	gap = rbase % range;
2742fc83c5a7SKonstantin Belousov 	gap &= ~(sizeof(u_long) - 1);
2743fc83c5a7SKonstantin Belousov 	*stack_base -= gap;
2744fc83c5a7SKonstantin Belousov }
2745