xref: /freebsd/sys/kern/imgact_elf.c (revision 20e1174a00801f2425419be793e10185df9ddf36)
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,
91cefb93f2SKonstantin Belousov     const char *interp, int interp_name_len, 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 
1593ebc1248SPeter Wemm static Elf_Brandinfo *elf_brand_list[MAX_BRANDS];
160e1743d02SSøren Schmidt 
161545517f1SEdward Tomasz Napierala #define	aligned(a, t)	(rounddown2((u_long)(a), sizeof(t)) == (u_long)(a))
16293d1c728SKonstantin Belousov 
16332c01de2SDmitry Chagin static const char FREEBSD_ABI_VENDOR[] = "FreeBSD";
16432c01de2SDmitry Chagin 
16532c01de2SDmitry Chagin Elf_Brandnote __elfN(freebsd_brandnote) = {
16632c01de2SDmitry Chagin 	.hdr.n_namesz	= sizeof(FREEBSD_ABI_VENDOR),
16732c01de2SDmitry Chagin 	.hdr.n_descsz	= sizeof(int32_t),
1684c22b468SEd Maste 	.hdr.n_type	= NT_FREEBSD_ABI_TAG,
16932c01de2SDmitry Chagin 	.vendor		= FREEBSD_ABI_VENDOR,
17089ffc202SBjoern A. Zeeb 	.flags		= BN_TRANSLATE_OSREL,
17189ffc202SBjoern A. Zeeb 	.trans_osrel	= __elfN(freebsd_trans_osrel)
17232c01de2SDmitry Chagin };
17332c01de2SDmitry Chagin 
174a95659f7SEd Maste static bool
17589ffc202SBjoern A. Zeeb __elfN(freebsd_trans_osrel)(const Elf_Note *note, int32_t *osrel)
17689ffc202SBjoern A. Zeeb {
17789ffc202SBjoern A. Zeeb 	uintptr_t p;
17889ffc202SBjoern A. Zeeb 
17989ffc202SBjoern A. Zeeb 	p = (uintptr_t)(note + 1);
1801b8388cdSMikolaj Golub 	p += roundup2(note->n_namesz, ELF_NOTE_ROUNDSIZE);
18189ffc202SBjoern A. Zeeb 	*osrel = *(const int32_t *)(p);
18289ffc202SBjoern A. Zeeb 
183a95659f7SEd Maste 	return (true);
18489ffc202SBjoern A. Zeeb }
18589ffc202SBjoern A. Zeeb 
18689ffc202SBjoern A. Zeeb static const char GNU_ABI_VENDOR[] = "GNU";
18789ffc202SBjoern A. Zeeb static int GNU_KFREEBSD_ABI_DESC = 3;
18889ffc202SBjoern A. Zeeb 
18989ffc202SBjoern A. Zeeb Elf_Brandnote __elfN(kfreebsd_brandnote) = {
19089ffc202SBjoern A. Zeeb 	.hdr.n_namesz	= sizeof(GNU_ABI_VENDOR),
19189ffc202SBjoern A. Zeeb 	.hdr.n_descsz	= 16,	/* XXX at least 16 */
19289ffc202SBjoern A. Zeeb 	.hdr.n_type	= 1,
19389ffc202SBjoern A. Zeeb 	.vendor		= GNU_ABI_VENDOR,
19489ffc202SBjoern A. Zeeb 	.flags		= BN_TRANSLATE_OSREL,
19589ffc202SBjoern A. Zeeb 	.trans_osrel	= kfreebsd_trans_osrel
19689ffc202SBjoern A. Zeeb };
19789ffc202SBjoern A. Zeeb 
198a95659f7SEd Maste static bool
19989ffc202SBjoern A. Zeeb kfreebsd_trans_osrel(const Elf_Note *note, int32_t *osrel)
20089ffc202SBjoern A. Zeeb {
20189ffc202SBjoern A. Zeeb 	const Elf32_Word *desc;
20289ffc202SBjoern A. Zeeb 	uintptr_t p;
20389ffc202SBjoern A. Zeeb 
20489ffc202SBjoern A. Zeeb 	p = (uintptr_t)(note + 1);
2051b8388cdSMikolaj Golub 	p += roundup2(note->n_namesz, ELF_NOTE_ROUNDSIZE);
20689ffc202SBjoern A. Zeeb 
20789ffc202SBjoern A. Zeeb 	desc = (const Elf32_Word *)p;
20889ffc202SBjoern A. Zeeb 	if (desc[0] != GNU_KFREEBSD_ABI_DESC)
209a95659f7SEd Maste 		return (false);
21089ffc202SBjoern A. Zeeb 
21189ffc202SBjoern A. Zeeb 	/*
21289ffc202SBjoern A. Zeeb 	 * Debian GNU/kFreeBSD embed the earliest compatible kernel version
21389ffc202SBjoern A. Zeeb 	 * (__FreeBSD_version: <major><two digit minor>Rxx) in the LSB way.
21489ffc202SBjoern A. Zeeb 	 */
21589ffc202SBjoern A. Zeeb 	*osrel = desc[1] * 100000 + desc[2] * 1000 + desc[3];
21689ffc202SBjoern A. Zeeb 
217a95659f7SEd Maste 	return (true);
21889ffc202SBjoern A. Zeeb }
21989ffc202SBjoern A. Zeeb 
220e1743d02SSøren Schmidt int
2213ebc1248SPeter Wemm __elfN(insert_brand_entry)(Elf_Brandinfo *entry)
222e1743d02SSøren Schmidt {
223e1743d02SSøren Schmidt 	int i;
224e1743d02SSøren Schmidt 
2253ebc1248SPeter Wemm 	for (i = 0; i < MAX_BRANDS; i++) {
226ea5a2b2eSSøren Schmidt 		if (elf_brand_list[i] == NULL) {
227ea5a2b2eSSøren Schmidt 			elf_brand_list[i] = entry;
228e1743d02SSøren Schmidt 			break;
229e1743d02SSøren Schmidt 		}
230e1743d02SSøren Schmidt 	}
231925c8b5bSBjoern A. Zeeb 	if (i == MAX_BRANDS) {
232925c8b5bSBjoern A. Zeeb 		printf("WARNING: %s: could not insert brandinfo entry: %p\n",
233925c8b5bSBjoern A. Zeeb 			__func__, entry);
234a7cddfedSJake Burkholder 		return (-1);
235925c8b5bSBjoern A. Zeeb 	}
236a7cddfedSJake Burkholder 	return (0);
237e1743d02SSøren Schmidt }
238e1743d02SSøren Schmidt 
239e1743d02SSøren Schmidt int
2403ebc1248SPeter Wemm __elfN(remove_brand_entry)(Elf_Brandinfo *entry)
241e1743d02SSøren Schmidt {
242e1743d02SSøren Schmidt 	int i;
243e1743d02SSøren Schmidt 
2443ebc1248SPeter Wemm 	for (i = 0; i < MAX_BRANDS; i++) {
245ea5a2b2eSSøren Schmidt 		if (elf_brand_list[i] == entry) {
246ea5a2b2eSSøren Schmidt 			elf_brand_list[i] = NULL;
247e1743d02SSøren Schmidt 			break;
248e1743d02SSøren Schmidt 		}
249e1743d02SSøren Schmidt 	}
250ea5a2b2eSSøren Schmidt 	if (i == MAX_BRANDS)
251a7cddfedSJake Burkholder 		return (-1);
252a7cddfedSJake Burkholder 	return (0);
253e1743d02SSøren Schmidt }
254e1743d02SSøren Schmidt 
255096977faSMark Newton int
2563ebc1248SPeter Wemm __elfN(brand_inuse)(Elf_Brandinfo *entry)
257096977faSMark Newton {
258096977faSMark Newton 	struct proc *p;
259553629ebSJake Burkholder 	int rval = FALSE;
260096977faSMark Newton 
2611005a129SJohn Baldwin 	sx_slock(&allproc_lock);
2624f506694SXin LI 	FOREACH_PROC_IN_SYSTEM(p) {
263553629ebSJake Burkholder 		if (p->p_sysent == entry->sysvec) {
264553629ebSJake Burkholder 			rval = TRUE;
265553629ebSJake Burkholder 			break;
266096977faSMark Newton 		}
267553629ebSJake Burkholder 	}
2681005a129SJohn Baldwin 	sx_sunlock(&allproc_lock);
269096977faSMark Newton 
270553629ebSJake Burkholder 	return (rval);
271096977faSMark Newton }
272096977faSMark Newton 
2735fe3ed62SJake Burkholder static Elf_Brandinfo *
27432c01de2SDmitry Chagin __elfN(get_brandinfo)(struct image_params *imgp, const char *interp,
275cefb93f2SKonstantin Belousov     int interp_name_len, int32_t *osrel, uint32_t *fctl0)
2765fe3ed62SJake Burkholder {
27732c01de2SDmitry Chagin 	const Elf_Ehdr *hdr = (const Elf_Ehdr *)imgp->image_header;
278af582aaeSKonstantin Belousov 	Elf_Brandinfo *bi, *bi_m;
27932c01de2SDmitry Chagin 	boolean_t ret;
2805fe3ed62SJake Burkholder 	int i;
2815fe3ed62SJake Burkholder 
2825fe3ed62SJake Burkholder 	/*
28332c01de2SDmitry Chagin 	 * We support four types of branding -- (1) the ELF EI_OSABI field
2845fe3ed62SJake Burkholder 	 * that SCO added to the ELF spec, (2) FreeBSD 3.x's traditional string
28532c01de2SDmitry Chagin 	 * branding w/in the ELF header, (3) path of the `interp_path'
28632c01de2SDmitry Chagin 	 * field, and (4) the ".note.ABI-tag" ELF section.
2875fe3ed62SJake Burkholder 	 */
2885fe3ed62SJake Burkholder 
28932c01de2SDmitry Chagin 	/* Look for an ".note.ABI-tag" ELF section */
290af582aaeSKonstantin Belousov 	bi_m = NULL;
29132c01de2SDmitry Chagin 	for (i = 0; i < MAX_BRANDS; i++) {
29232c01de2SDmitry Chagin 		bi = elf_brand_list[i];
293ecc2fda8SBjoern A. Zeeb 		if (bi == NULL)
294ecc2fda8SBjoern A. Zeeb 			continue;
2952274ab3dSKonstantin Belousov 		if (interp != NULL && (bi->flags & BI_BRAND_ONLY_STATIC) != 0)
2961438fe3cSKonstantin Belousov 			continue;
297ecc2fda8SBjoern A. Zeeb 		if (hdr->e_machine == bi->machine && (bi->flags &
298ecc2fda8SBjoern A. Zeeb 		    (BI_BRAND_NOTE|BI_BRAND_NOTE_MANDATORY)) != 0) {
299cefb93f2SKonstantin Belousov 			ret = __elfN(check_note)(imgp, bi->brand_note, osrel,
300cefb93f2SKonstantin Belousov 			    fctl0);
301f19d421aSNathan Whitehorn 			/* Give brand a chance to veto check_note's guess */
302f19d421aSNathan Whitehorn 			if (ret && bi->header_supported)
303f19d421aSNathan Whitehorn 				ret = bi->header_supported(imgp);
304af582aaeSKonstantin Belousov 			/*
305af582aaeSKonstantin Belousov 			 * If note checker claimed the binary, but the
306af582aaeSKonstantin Belousov 			 * interpreter path in the image does not
307af582aaeSKonstantin Belousov 			 * match default one for the brand, try to
308af582aaeSKonstantin Belousov 			 * search for other brands with the same
309af582aaeSKonstantin Belousov 			 * interpreter.  Either there is better brand
310af582aaeSKonstantin Belousov 			 * with the right interpreter, or, failing
311af582aaeSKonstantin Belousov 			 * this, we return first brand which accepted
312af582aaeSKonstantin Belousov 			 * our note and, optionally, header.
313af582aaeSKonstantin Belousov 			 */
3143aeacc55SKonstantin Belousov 			if (ret && bi_m == NULL && interp != NULL &&
3153aeacc55SKonstantin Belousov 			    (bi->interp_path == NULL ||
3163aeacc55SKonstantin Belousov 			    (strlen(bi->interp_path) + 1 != interp_name_len ||
3173aeacc55SKonstantin Belousov 			    strncmp(interp, bi->interp_path, interp_name_len)
3183aeacc55SKonstantin Belousov 			    != 0))) {
319af582aaeSKonstantin Belousov 				bi_m = bi;
320af582aaeSKonstantin Belousov 				ret = 0;
321af582aaeSKonstantin Belousov 			}
32232c01de2SDmitry Chagin 			if (ret)
32332c01de2SDmitry Chagin 				return (bi);
32432c01de2SDmitry Chagin 		}
32532c01de2SDmitry Chagin 	}
326af582aaeSKonstantin Belousov 	if (bi_m != NULL)
327af582aaeSKonstantin Belousov 		return (bi_m);
32832c01de2SDmitry Chagin 
3295fe3ed62SJake Burkholder 	/* If the executable has a brand, search for it in the brand list. */
3305fe3ed62SJake Burkholder 	for (i = 0; i < MAX_BRANDS; i++) {
3315fe3ed62SJake Burkholder 		bi = elf_brand_list[i];
3321438fe3cSKonstantin Belousov 		if (bi == NULL || (bi->flags & BI_BRAND_NOTE_MANDATORY) != 0 ||
3332274ab3dSKonstantin Belousov 		    (interp != NULL && (bi->flags & BI_BRAND_ONLY_STATIC) != 0))
334ecc2fda8SBjoern A. Zeeb 			continue;
335ecc2fda8SBjoern A. Zeeb 		if (hdr->e_machine == bi->machine &&
3365fe3ed62SJake Burkholder 		    (hdr->e_ident[EI_OSABI] == bi->brand ||
3370fe98320SEd Schouten 		    (bi->compat_3_brand != NULL &&
3383d560b4bSKonstantin Belousov 		    strcmp((const char *)&hdr->e_ident[OLD_EI_BRAND],
3390fe98320SEd Schouten 		    bi->compat_3_brand) == 0))) {
340686d2f31SNathan Whitehorn 			/* Looks good, but give brand a chance to veto */
341d722231bSJohn Baldwin 			if (bi->header_supported == NULL ||
34215a9aedfSKonstantin Belousov 			    bi->header_supported(imgp)) {
34315a9aedfSKonstantin Belousov 				/*
34415a9aedfSKonstantin Belousov 				 * Again, prefer strictly matching
34515a9aedfSKonstantin Belousov 				 * interpreter path.
34615a9aedfSKonstantin Belousov 				 */
3477aab7a80SKonstantin Belousov 				if (interp_name_len == 0 &&
3487aab7a80SKonstantin Belousov 				    bi->interp_path == NULL)
3497aab7a80SKonstantin Belousov 					return (bi);
3507aab7a80SKonstantin Belousov 				if (bi->interp_path != NULL &&
3517aab7a80SKonstantin Belousov 				    strlen(bi->interp_path) + 1 ==
35215a9aedfSKonstantin Belousov 				    interp_name_len && strncmp(interp,
35315a9aedfSKonstantin Belousov 				    bi->interp_path, interp_name_len) == 0)
3545fe3ed62SJake Burkholder 					return (bi);
35515a9aedfSKonstantin Belousov 				if (bi_m == NULL)
35615a9aedfSKonstantin Belousov 					bi_m = bi;
3575fe3ed62SJake Burkholder 			}
358686d2f31SNathan Whitehorn 		}
35915a9aedfSKonstantin Belousov 	}
36015a9aedfSKonstantin Belousov 	if (bi_m != NULL)
36115a9aedfSKonstantin Belousov 		return (bi_m);
3625fe3ed62SJake Burkholder 
363817dc004SWarner Losh 	/* No known brand, see if the header is recognized by any brand */
364817dc004SWarner Losh 	for (i = 0; i < MAX_BRANDS; i++) {
365817dc004SWarner Losh 		bi = elf_brand_list[i];
366817dc004SWarner Losh 		if (bi == NULL || bi->flags & BI_BRAND_NOTE_MANDATORY ||
367817dc004SWarner Losh 		    bi->header_supported == NULL)
368817dc004SWarner Losh 			continue;
369817dc004SWarner Losh 		if (hdr->e_machine == bi->machine) {
370817dc004SWarner Losh 			ret = bi->header_supported(imgp);
371817dc004SWarner Losh 			if (ret)
372817dc004SWarner Losh 				return (bi);
373817dc004SWarner Losh 		}
374817dc004SWarner Losh 	}
375817dc004SWarner Losh 
3765fe3ed62SJake Burkholder 	/* Lacking a known brand, search for a recognized interpreter. */
3775fe3ed62SJake Burkholder 	if (interp != NULL) {
3785fe3ed62SJake Burkholder 		for (i = 0; i < MAX_BRANDS; i++) {
3795fe3ed62SJake Burkholder 			bi = elf_brand_list[i];
3802274ab3dSKonstantin Belousov 			if (bi == NULL || (bi->flags &
3812274ab3dSKonstantin Belousov 			    (BI_BRAND_NOTE_MANDATORY | BI_BRAND_ONLY_STATIC))
3822274ab3dSKonstantin Belousov 			    != 0)
383ecc2fda8SBjoern A. Zeeb 				continue;
384ecc2fda8SBjoern A. Zeeb 			if (hdr->e_machine == bi->machine &&
3853aeacc55SKonstantin Belousov 			    bi->interp_path != NULL &&
386d1ae5c83SKonstantin Belousov 			    /* ELF image p_filesz includes terminating zero */
387d1ae5c83SKonstantin Belousov 			    strlen(bi->interp_path) + 1 == interp_name_len &&
388d1ae5c83SKonstantin Belousov 			    strncmp(interp, bi->interp_path, interp_name_len)
389d722231bSJohn Baldwin 			    == 0 && (bi->header_supported == NULL ||
390d722231bSJohn Baldwin 			    bi->header_supported(imgp)))
3915fe3ed62SJake Burkholder 				return (bi);
3925fe3ed62SJake Burkholder 		}
3935fe3ed62SJake Burkholder 	}
3945fe3ed62SJake Burkholder 
3955fe3ed62SJake Burkholder 	/* Lacking a recognized interpreter, try the default brand */
3965fe3ed62SJake Burkholder 	for (i = 0; i < MAX_BRANDS; i++) {
3975fe3ed62SJake Burkholder 		bi = elf_brand_list[i];
3981438fe3cSKonstantin Belousov 		if (bi == NULL || (bi->flags & BI_BRAND_NOTE_MANDATORY) != 0 ||
3992274ab3dSKonstantin Belousov 		    (interp != NULL && (bi->flags & BI_BRAND_ONLY_STATIC) != 0))
400ecc2fda8SBjoern A. Zeeb 			continue;
401ecc2fda8SBjoern A. Zeeb 		if (hdr->e_machine == bi->machine &&
402d722231bSJohn Baldwin 		    __elfN(fallback_brand) == bi->brand &&
403d722231bSJohn Baldwin 		    (bi->header_supported == NULL ||
404d722231bSJohn Baldwin 		    bi->header_supported(imgp)))
4055fe3ed62SJake Burkholder 			return (bi);
4065fe3ed62SJake Burkholder 	}
4075fe3ed62SJake Burkholder 	return (NULL);
4085fe3ed62SJake Burkholder }
4095fe3ed62SJake Burkholder 
410e1743d02SSøren Schmidt static int
4113ebc1248SPeter Wemm __elfN(check_header)(const Elf_Ehdr *hdr)
412e1743d02SSøren Schmidt {
413d0ca7c29SPeter Wemm 	Elf_Brandinfo *bi;
4143ebc1248SPeter Wemm 	int i;
4153ebc1248SPeter Wemm 
41652c24af7SPeter Wemm 	if (!IS_ELF(*hdr) ||
41752c24af7SPeter Wemm 	    hdr->e_ident[EI_CLASS] != ELF_TARG_CLASS ||
41852c24af7SPeter Wemm 	    hdr->e_ident[EI_DATA] != ELF_TARG_DATA ||
4193dc19c46SJacques Vidrine 	    hdr->e_ident[EI_VERSION] != EV_CURRENT ||
4203dc19c46SJacques Vidrine 	    hdr->e_phentsize != sizeof(Elf_Phdr) ||
4213dc19c46SJacques Vidrine 	    hdr->e_version != ELF_TARG_VER)
422a7cddfedSJake Burkholder 		return (ENOEXEC);
423e1743d02SSøren Schmidt 
4243ebc1248SPeter Wemm 	/*
4253ebc1248SPeter Wemm 	 * Make sure we have at least one brand for this machine.
4263ebc1248SPeter Wemm 	 */
4273ebc1248SPeter Wemm 
4283ebc1248SPeter Wemm 	for (i = 0; i < MAX_BRANDS; i++) {
429d0ca7c29SPeter Wemm 		bi = elf_brand_list[i];
430d0ca7c29SPeter Wemm 		if (bi != NULL && bi->machine == hdr->e_machine)
4313ebc1248SPeter Wemm 			break;
4323ebc1248SPeter Wemm 	}
4333ebc1248SPeter Wemm 	if (i == MAX_BRANDS)
434a7cddfedSJake Burkholder 		return (ENOEXEC);
435e1743d02SSøren Schmidt 
436a7cddfedSJake Burkholder 	return (0);
437e1743d02SSøren Schmidt }
438e1743d02SSøren Schmidt 
439e1743d02SSøren Schmidt static int
4403ebc1248SPeter Wemm __elfN(map_partial)(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
441ff6f03c7SAlan Cox     vm_offset_t start, vm_offset_t end, vm_prot_t prot)
4423ebc1248SPeter Wemm {
443da61b9a6SAlan Cox 	struct sf_buf *sf;
444da61b9a6SAlan Cox 	int error;
4453ebc1248SPeter Wemm 	vm_offset_t off;
4463ebc1248SPeter Wemm 
4473ebc1248SPeter Wemm 	/*
4483ebc1248SPeter Wemm 	 * Create the page if it doesn't exist yet. Ignore errors.
4493ebc1248SPeter Wemm 	 */
450aaadc41fSKonstantin Belousov 	vm_map_fixed(map, NULL, 0, trunc_page(start), round_page(end) -
451aaadc41fSKonstantin Belousov 	    trunc_page(start), VM_PROT_ALL, VM_PROT_ALL, MAP_CHECK_EXCL);
4523ebc1248SPeter Wemm 
4533ebc1248SPeter Wemm 	/*
4543ebc1248SPeter Wemm 	 * Find the page from the underlying object.
4553ebc1248SPeter Wemm 	 */
45628e8da65SAlan Cox 	if (object != NULL) {
457da61b9a6SAlan Cox 		sf = vm_imgact_map_page(object, offset);
458da61b9a6SAlan Cox 		if (sf == NULL)
459da61b9a6SAlan Cox 			return (KERN_FAILURE);
4603ebc1248SPeter Wemm 		off = offset - trunc_page(offset);
461da61b9a6SAlan Cox 		error = copyout((caddr_t)sf_buf_kva(sf) + off, (caddr_t)start,
462ca0387efSJake Burkholder 		    end - start);
463be996836SAttilio Rao 		vm_imgact_unmap_page(sf);
464fe0a8a39SKonstantin Belousov 		if (error != 0)
465a7cddfedSJake Burkholder 			return (KERN_FAILURE);
4663ebc1248SPeter Wemm 	}
4673ebc1248SPeter Wemm 
468a7cddfedSJake Burkholder 	return (KERN_SUCCESS);
4693ebc1248SPeter Wemm }
4703ebc1248SPeter Wemm 
4713ebc1248SPeter Wemm static int
472e3d8f8feSKonstantin Belousov __elfN(map_insert)(struct image_params *imgp, vm_map_t map, vm_object_t object,
473e3d8f8feSKonstantin Belousov     vm_ooffset_t offset, vm_offset_t start, vm_offset_t end, vm_prot_t prot,
474e3d8f8feSKonstantin Belousov     int cow)
4753ebc1248SPeter Wemm {
476da61b9a6SAlan Cox 	struct sf_buf *sf;
477da61b9a6SAlan Cox 	vm_offset_t off;
478a063facbSMarcel Moolenaar 	vm_size_t sz;
479e3d8f8feSKonstantin Belousov 	int error, locked, rv;
4803ebc1248SPeter Wemm 
4813ebc1248SPeter Wemm 	if (start != trunc_page(start)) {
48281f223caSJake Burkholder 		rv = __elfN(map_partial)(map, object, offset, start,
483ff6f03c7SAlan Cox 		    round_page(start), prot);
48428e8da65SAlan Cox 		if (rv != KERN_SUCCESS)
485a7cddfedSJake Burkholder 			return (rv);
4863ebc1248SPeter Wemm 		offset += round_page(start) - start;
4873ebc1248SPeter Wemm 		start = round_page(start);
4883ebc1248SPeter Wemm 	}
4893ebc1248SPeter Wemm 	if (end != round_page(end)) {
49081f223caSJake Burkholder 		rv = __elfN(map_partial)(map, object, offset +
491ff6f03c7SAlan Cox 		    trunc_page(end) - start, trunc_page(end), end, prot);
49228e8da65SAlan Cox 		if (rv != KERN_SUCCESS)
493a7cddfedSJake Burkholder 			return (rv);
4943ebc1248SPeter Wemm 		end = trunc_page(end);
4953ebc1248SPeter Wemm 	}
496e383e820SAlan Cox 	if (start >= end)
497e383e820SAlan Cox 		return (KERN_SUCCESS);
498e383e820SAlan Cox 	if ((offset & PAGE_MASK) != 0) {
4993ebc1248SPeter Wemm 		/*
500e383e820SAlan Cox 		 * The mapping is not page aligned.  This means that we have
501e383e820SAlan Cox 		 * to copy the data.
5023ebc1248SPeter Wemm 		 */
503aaadc41fSKonstantin Belousov 		rv = vm_map_fixed(map, NULL, 0, start, end - start,
504aaadc41fSKonstantin Belousov 		    prot | VM_PROT_WRITE, VM_PROT_ALL, MAP_CHECK_EXCL);
5055420f76bSKonstantin Belousov 		if (rv != KERN_SUCCESS)
506a7cddfedSJake Burkholder 			return (rv);
507da61b9a6SAlan Cox 		if (object == NULL)
508da61b9a6SAlan Cox 			return (KERN_SUCCESS);
509da61b9a6SAlan Cox 		for (; start < end; start += sz) {
510da61b9a6SAlan Cox 			sf = vm_imgact_map_page(object, offset);
511da61b9a6SAlan Cox 			if (sf == NULL)
512da61b9a6SAlan Cox 				return (KERN_FAILURE);
5133ebc1248SPeter Wemm 			off = offset - trunc_page(offset);
5143ebc1248SPeter Wemm 			sz = end - start;
515da61b9a6SAlan Cox 			if (sz > PAGE_SIZE - off)
516da61b9a6SAlan Cox 				sz = PAGE_SIZE - off;
517da61b9a6SAlan Cox 			error = copyout((caddr_t)sf_buf_kva(sf) + off,
5183ebc1248SPeter Wemm 			    (caddr_t)start, sz);
519be996836SAttilio Rao 			vm_imgact_unmap_page(sf);
5205420f76bSKonstantin Belousov 			if (error != 0)
521a7cddfedSJake Burkholder 				return (KERN_FAILURE);
522da61b9a6SAlan Cox 			offset += sz;
5233ebc1248SPeter Wemm 		}
5243ebc1248SPeter Wemm 	} else {
525e5e6093bSAlan Cox 		vm_object_reference(object);
526e383e820SAlan Cox 		rv = vm_map_fixed(map, object, offset, start, end - start,
527e383e820SAlan Cox 		    prot, VM_PROT_ALL, cow | MAP_CHECK_EXCL);
528e3d8f8feSKonstantin Belousov 		if (rv != KERN_SUCCESS) {
529e3d8f8feSKonstantin Belousov 			locked = VOP_ISLOCKED(imgp->vp);
530e3d8f8feSKonstantin Belousov 			VOP_UNLOCK(imgp->vp, 0);
531e5e6093bSAlan Cox 			vm_object_deallocate(object);
532e3d8f8feSKonstantin Belousov 			vn_lock(imgp->vp, locked | LK_RETRY);
533a7cddfedSJake Burkholder 			return (rv);
5343ebc1248SPeter Wemm 		}
5353ebc1248SPeter Wemm 	}
536e383e820SAlan Cox 	return (KERN_SUCCESS);
537e383e820SAlan Cox }
5383ebc1248SPeter Wemm 
5393ebc1248SPeter Wemm static int
5400bbee4cdSKonstantin Belousov __elfN(load_section)(struct image_params *imgp, vm_ooffset_t offset,
5411699546dSEdward Tomasz Napierala     caddr_t vmaddr, size_t memsz, size_t filsz, vm_prot_t prot)
542e1743d02SSøren Schmidt {
543da61b9a6SAlan Cox 	struct sf_buf *sf;
544e1743d02SSøren Schmidt 	size_t map_len;
545292177e6SAlan Cox 	vm_map_t map;
546292177e6SAlan Cox 	vm_object_t object;
547973d67c4SKonstantin Belousov 	vm_offset_t off, map_addr;
548fa7dd9c5SMatthew Dillon 	int error, rv, cow;
549e1743d02SSøren Schmidt 	size_t copy_len;
5500bbee4cdSKonstantin Belousov 	vm_ooffset_t file_addr;
55152c24af7SPeter Wemm 
55225ead034SBrian Feldman 	/*
55325ead034SBrian Feldman 	 * It's necessary to fail if the filsz + offset taken from the
55425ead034SBrian Feldman 	 * header is greater than the actual file pager object's size.
55525ead034SBrian Feldman 	 * If we were to allow this, then the vm_map_find() below would
55625ead034SBrian Feldman 	 * walk right off the end of the file object and into the ether.
55725ead034SBrian Feldman 	 *
55825ead034SBrian Feldman 	 * While I'm here, might as well check for something else that
55925ead034SBrian Feldman 	 * is invalid: filsz cannot be greater than memsz.
56025ead034SBrian Feldman 	 */
5619bcf2f2dSKonstantin Belousov 	if ((filsz != 0 && (off_t)filsz + offset > imgp->attr->va_size) ||
5629bcf2f2dSKonstantin Belousov 	    filsz > memsz) {
56325ead034SBrian Feldman 		uprintf("elf_load_section: truncated ELF file\n");
56425ead034SBrian Feldman 		return (ENOEXEC);
56525ead034SBrian Feldman 	}
56625ead034SBrian Feldman 
567292177e6SAlan Cox 	object = imgp->object;
568292177e6SAlan Cox 	map = &imgp->proc->p_vmspace->vm_map;
569545517f1SEdward Tomasz Napierala 	map_addr = trunc_page((vm_offset_t)vmaddr);
570545517f1SEdward Tomasz Napierala 	file_addr = trunc_page(offset);
571e1743d02SSøren Schmidt 
572e1743d02SSøren Schmidt 	/*
57352c24af7SPeter Wemm 	 * We have two choices.  We can either clear the data in the last page
57452c24af7SPeter Wemm 	 * of an oversized mapping, or we can start the anon mapping a page
57552c24af7SPeter Wemm 	 * early and copy the initialized data into that first page.  We
57628e8da65SAlan Cox 	 * choose the second.
57752c24af7SPeter Wemm 	 */
5789bcf2f2dSKonstantin Belousov 	if (filsz == 0)
5799bcf2f2dSKonstantin Belousov 		map_len = 0;
5809bcf2f2dSKonstantin Belousov 	else if (memsz > filsz)
581545517f1SEdward Tomasz Napierala 		map_len = trunc_page(offset + filsz) - file_addr;
58252c24af7SPeter Wemm 	else
583545517f1SEdward Tomasz Napierala 		map_len = round_page(offset + filsz) - file_addr;
58452c24af7SPeter Wemm 
58552c24af7SPeter Wemm 	if (map_len != 0) {
586fa7dd9c5SMatthew Dillon 		/* cow flags: don't dump readonly sections in core */
587fa7dd9c5SMatthew Dillon 		cow = MAP_COPY_ON_WRITE | MAP_PREFAULT |
588fa7dd9c5SMatthew Dillon 		    (prot & VM_PROT_WRITE ? 0 : MAP_DISABLE_COREDUMP);
589fa7dd9c5SMatthew Dillon 
590e3d8f8feSKonstantin Belousov 		rv = __elfN(map_insert)(imgp, map,
59152c24af7SPeter Wemm 				      object,
59252c24af7SPeter Wemm 				      file_addr,	/* file offset */
59352c24af7SPeter Wemm 				      map_addr,		/* virtual start */
59452c24af7SPeter Wemm 				      map_addr + map_len,/* virtual end */
59552c24af7SPeter Wemm 				      prot,
596fa7dd9c5SMatthew Dillon 				      cow);
597e5e6093bSAlan Cox 		if (rv != KERN_SUCCESS)
598a7cddfedSJake Burkholder 			return (EINVAL);
59952c24af7SPeter Wemm 
60052c24af7SPeter Wemm 		/* we can stop now if we've covered it all */
601973d67c4SKonstantin Belousov 		if (memsz == filsz)
602a7cddfedSJake Burkholder 			return (0);
60352c24af7SPeter Wemm 	}
60452c24af7SPeter Wemm 
60552c24af7SPeter Wemm 
60652c24af7SPeter Wemm 	/*
60752c24af7SPeter Wemm 	 * We have to get the remaining bit of the file into the first part
60852c24af7SPeter Wemm 	 * of the oversized map segment.  This is normally because the .data
60952c24af7SPeter Wemm 	 * segment in the file is extended to provide bss.  It's a neat idea
61052c24af7SPeter Wemm 	 * to try and save a page, but it's a pain in the behind to implement.
611e1743d02SSøren Schmidt 	 */
612545517f1SEdward Tomasz Napierala 	copy_len = filsz == 0 ? 0 : (offset + filsz) - trunc_page(offset +
613545517f1SEdward Tomasz Napierala 	    filsz);
614545517f1SEdward Tomasz Napierala 	map_addr = trunc_page((vm_offset_t)vmaddr + filsz);
615545517f1SEdward Tomasz Napierala 	map_len = round_page((vm_offset_t)vmaddr + memsz) - map_addr;
616e1743d02SSøren Schmidt 
61752c24af7SPeter Wemm 	/* This had damn well better be true! */
6188191d577SPeter Wemm 	if (map_len != 0) {
619e3d8f8feSKonstantin Belousov 		rv = __elfN(map_insert)(imgp, map, NULL, 0, map_addr,
620c547cbb4SAlan Cox 		    map_addr + map_len, prot, 0);
621973d67c4SKonstantin Belousov 		if (rv != KERN_SUCCESS)
622a7cddfedSJake Burkholder 			return (EINVAL);
6238191d577SPeter Wemm 	}
624e1743d02SSøren Schmidt 
62552c24af7SPeter Wemm 	if (copy_len != 0) {
626da61b9a6SAlan Cox 		sf = vm_imgact_map_page(object, offset + filsz);
627da61b9a6SAlan Cox 		if (sf == NULL)
628da61b9a6SAlan Cox 			return (EIO);
629e1743d02SSøren Schmidt 
63052c24af7SPeter Wemm 		/* send the page fragment to user space */
631545517f1SEdward Tomasz Napierala 		off = trunc_page(offset + filsz) - trunc_page(offset + filsz);
632da61b9a6SAlan Cox 		error = copyout((caddr_t)sf_buf_kva(sf) + off,
633da61b9a6SAlan Cox 		    (caddr_t)map_addr, copy_len);
634be996836SAttilio Rao 		vm_imgact_unmap_page(sf);
635973d67c4SKonstantin Belousov 		if (error != 0)
63652c24af7SPeter Wemm 			return (error);
63752c24af7SPeter Wemm 	}
638e1743d02SSøren Schmidt 
639e1743d02SSøren Schmidt 	/*
640c547cbb4SAlan Cox 	 * Remove write access to the page if it was only granted by map_insert
641c547cbb4SAlan Cox 	 * to allow copyout.
642e1743d02SSøren Schmidt 	 */
643c547cbb4SAlan Cox 	if ((prot & VM_PROT_WRITE) == 0)
644292177e6SAlan Cox 		vm_map_protect(map, trunc_page(map_addr), round_page(map_addr +
645292177e6SAlan Cox 		    map_len), prot, FALSE);
6468191d577SPeter Wemm 
647ff6f03c7SAlan Cox 	return (0);
648e1743d02SSøren Schmidt }
649e1743d02SSøren Schmidt 
650c33fe779SJohn Polstra /*
651c33fe779SJohn Polstra  * Load the file "file" into memory.  It may be either a shared object
652c33fe779SJohn Polstra  * or an executable.
653c33fe779SJohn Polstra  *
654c33fe779SJohn Polstra  * The "addr" reference parameter is in/out.  On entry, it specifies
655c33fe779SJohn Polstra  * the address where a shared object should be loaded.  If the file is
656c33fe779SJohn Polstra  * an executable, this value is ignored.  On exit, "addr" specifies
657c33fe779SJohn Polstra  * where the file was actually loaded.
658c33fe779SJohn Polstra  *
659c33fe779SJohn Polstra  * The "entry" reference parameter is out only.  On exit, it specifies
660c33fe779SJohn Polstra  * the entry point for the loaded file.
661c33fe779SJohn Polstra  */
662e1743d02SSøren Schmidt static int
6633ebc1248SPeter Wemm __elfN(load_file)(struct proc *p, const char *file, u_long *addr,
6641699546dSEdward Tomasz Napierala 	u_long *entry)
665e1743d02SSøren Schmidt {
666911c2be0SMark Peek 	struct {
667911c2be0SMark Peek 		struct nameidata nd;
668911c2be0SMark Peek 		struct vattr attr;
669911c2be0SMark Peek 		struct image_params image_params;
670911c2be0SMark Peek 	} *tempdata;
671d254af07SMatthew Dillon 	const Elf_Ehdr *hdr = NULL;
672d254af07SMatthew Dillon 	const Elf_Phdr *phdr = NULL;
673911c2be0SMark Peek 	struct nameidata *nd;
674911c2be0SMark Peek 	struct vattr *attr;
675911c2be0SMark Peek 	struct image_params *imgp;
67652c24af7SPeter Wemm 	vm_prot_t prot;
677c33fe779SJohn Polstra 	u_long rbase;
678c33fe779SJohn Polstra 	u_long base_addr = 0;
6795050aa86SKonstantin Belousov 	int error, i, numsegs;
680e1743d02SSøren Schmidt 
68112bc222eSJonathan Anderson #ifdef CAPABILITY_MODE
68212bc222eSJonathan Anderson 	/*
68312bc222eSJonathan Anderson 	 * XXXJA: This check can go away once we are sufficiently confident
68412bc222eSJonathan Anderson 	 * that the checks in namei() are correct.
68512bc222eSJonathan Anderson 	 */
68612bc222eSJonathan Anderson 	if (IN_CAPABILITY_MODE(curthread))
68712bc222eSJonathan Anderson 		return (ECAPMODE);
68812bc222eSJonathan Anderson #endif
68912bc222eSJonathan Anderson 
690a163d034SWarner Losh 	tempdata = malloc(sizeof(*tempdata), M_TEMP, M_WAITOK);
691911c2be0SMark Peek 	nd = &tempdata->nd;
692911c2be0SMark Peek 	attr = &tempdata->attr;
693911c2be0SMark Peek 	imgp = &tempdata->image_params;
694911c2be0SMark Peek 
695c8a79999SPeter Wemm 	/*
696c8a79999SPeter Wemm 	 * Initialize part of the common data
697c8a79999SPeter Wemm 	 */
698c8a79999SPeter Wemm 	imgp->proc = p;
699911c2be0SMark Peek 	imgp->attr = attr;
700c8a79999SPeter Wemm 	imgp->firstpage = NULL;
70159c8bc40SAlan Cox 	imgp->image_header = NULL;
7020b2ed1aeSJeff Roberson 	imgp->object = NULL;
7036d7bdc8dSRobert Watson 	imgp->execlabel = NULL;
704c8a79999SPeter Wemm 
7055050aa86SKonstantin Belousov 	NDINIT(nd, LOOKUP, LOCKLEAF | FOLLOW, UIO_SYSSPACE, file, curthread);
706911c2be0SMark Peek 	if ((error = namei(nd)) != 0) {
707911c2be0SMark Peek 		nd->ni_vp = NULL;
708e1743d02SSøren Schmidt 		goto fail;
709e1743d02SSøren Schmidt 	}
710911c2be0SMark Peek 	NDFREE(nd, NDF_ONLY_PNBUF);
711911c2be0SMark Peek 	imgp->vp = nd->ni_vp;
712c8a79999SPeter Wemm 
713e1743d02SSøren Schmidt 	/*
714e1743d02SSøren Schmidt 	 * Check permissions, modes, uid, etc on the file, and "open" it.
715e1743d02SSøren Schmidt 	 */
716c8a79999SPeter Wemm 	error = exec_check_permissions(imgp);
717373d1a3fSAlan Cox 	if (error)
718c8a79999SPeter Wemm 		goto fail;
719e1743d02SSøren Schmidt 
720c8a79999SPeter Wemm 	error = exec_map_first_page(imgp);
721373d1a3fSAlan Cox 	if (error)
722373d1a3fSAlan Cox 		goto fail;
723373d1a3fSAlan Cox 
72425ead034SBrian Feldman 	/*
72525ead034SBrian Feldman 	 * Also make certain that the interpreter stays the same, so set
726e6e370a7SJeff Roberson 	 * its VV_TEXT flag, too.
72725ead034SBrian Feldman 	 */
728877d24acSKonstantin Belousov 	VOP_SET_TEXT(nd->ni_vp);
729e6e370a7SJeff Roberson 
7308516dd18SPoul-Henning Kamp 	imgp->object = nd->ni_vp->v_object;
731e1743d02SSøren Schmidt 
732d254af07SMatthew Dillon 	hdr = (const Elf_Ehdr *)imgp->image_header;
7333ebc1248SPeter Wemm 	if ((error = __elfN(check_header)(hdr)) != 0)
734e1743d02SSøren Schmidt 		goto fail;
735c33fe779SJohn Polstra 	if (hdr->e_type == ET_DYN)
736c33fe779SJohn Polstra 		rbase = *addr;
737c33fe779SJohn Polstra 	else if (hdr->e_type == ET_EXEC)
738c33fe779SJohn Polstra 		rbase = 0;
739c33fe779SJohn Polstra 	else {
740c33fe779SJohn Polstra 		error = ENOEXEC;
741c33fe779SJohn Polstra 		goto fail;
742c33fe779SJohn Polstra 	}
743e1743d02SSøren Schmidt 
744c8a79999SPeter Wemm 	/* Only support headers that fit within first page for now      */
74552c24af7SPeter Wemm 	if ((hdr->e_phoff > PAGE_SIZE) ||
746d19d5bf4STijl Coosemans 	    (u_int)hdr->e_phentsize * hdr->e_phnum > PAGE_SIZE - hdr->e_phoff) {
747c8a79999SPeter Wemm 		error = ENOEXEC;
748e1743d02SSøren Schmidt 		goto fail;
749c8a79999SPeter Wemm 	}
750c8a79999SPeter Wemm 
751d254af07SMatthew Dillon 	phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
75293d1c728SKonstantin Belousov 	if (!aligned(phdr, Elf_Addr)) {
75393d1c728SKonstantin Belousov 		error = ENOEXEC;
75493d1c728SKonstantin Belousov 		goto fail;
75593d1c728SKonstantin Belousov 	}
756e1743d02SSøren Schmidt 
757c33fe779SJohn Polstra 	for (i = 0, numsegs = 0; i < hdr->e_phnum; i++) {
7585b33842aSKonstantin Belousov 		if (phdr[i].p_type == PT_LOAD && phdr[i].p_memsz != 0) {
7595b33842aSKonstantin Belousov 			/* Loadable segment */
760ed167eaaSKonstantin Belousov 			prot = __elfN(trans_prot)(phdr[i].p_flags);
761292177e6SAlan Cox 			error = __elfN(load_section)(imgp, phdr[i].p_offset,
76281f223caSJake Burkholder 			    (caddr_t)(uintptr_t)phdr[i].p_vaddr + rbase,
7631699546dSEdward Tomasz Napierala 			    phdr[i].p_memsz, phdr[i].p_filesz, prot);
764292177e6SAlan Cox 			if (error != 0)
765e1743d02SSøren Schmidt 				goto fail;
766e1743d02SSøren Schmidt 			/*
767c33fe779SJohn Polstra 			 * Establish the base address if this is the
768c33fe779SJohn Polstra 			 * first segment.
769e1743d02SSøren Schmidt 			 */
770c33fe779SJohn Polstra 			if (numsegs == 0)
771ca0387efSJake Burkholder   				base_addr = trunc_page(phdr[i].p_vaddr +
772ca0387efSJake Burkholder 				    rbase);
773c33fe779SJohn Polstra 			numsegs++;
774e1743d02SSøren Schmidt 		}
775e1743d02SSøren Schmidt 	}
776c33fe779SJohn Polstra 	*addr = base_addr;
777c33fe779SJohn Polstra 	*entry = (unsigned long)hdr->e_entry + rbase;
778e1743d02SSøren Schmidt 
779e1743d02SSøren Schmidt fail:
780c8a79999SPeter Wemm 	if (imgp->firstpage)
781c8a79999SPeter Wemm 		exec_unmap_first_page(imgp);
7820b2ed1aeSJeff Roberson 
783911c2be0SMark Peek 	if (nd->ni_vp)
784373d1a3fSAlan Cox 		vput(nd->ni_vp);
785911c2be0SMark Peek 
786911c2be0SMark Peek 	free(tempdata, M_TEMP);
787e1743d02SSøren Schmidt 
788a7cddfedSJake Burkholder 	return (error);
789e1743d02SSøren Schmidt }
790e1743d02SSøren Schmidt 
791fa50a355SKonstantin Belousov static u_long
792fa50a355SKonstantin Belousov __CONCAT(rnd_, __elfN(base))(vm_map_t map __unused, u_long minv, u_long maxv,
793fa50a355SKonstantin Belousov     u_int align)
794fa50a355SKonstantin Belousov {
795fa50a355SKonstantin Belousov 	u_long rbase, res;
796fa50a355SKonstantin Belousov 
797fa50a355SKonstantin Belousov 	MPASS(vm_map_min(map) <= minv);
798fa50a355SKonstantin Belousov 	MPASS(maxv <= vm_map_max(map));
799fa50a355SKonstantin Belousov 	MPASS(minv < maxv);
800fa50a355SKonstantin Belousov 	MPASS(minv + align < maxv);
801fa50a355SKonstantin Belousov 	arc4rand(&rbase, sizeof(rbase), 0);
802fa50a355SKonstantin Belousov 	res = roundup(minv, (u_long)align) + rbase % (maxv - minv);
803fa50a355SKonstantin Belousov 	res &= ~((u_long)align - 1);
804fa50a355SKonstantin Belousov 	if (res >= maxv)
805fa50a355SKonstantin Belousov 		res -= align;
806fa50a355SKonstantin Belousov 	KASSERT(res >= minv,
807fa50a355SKonstantin Belousov 	    ("res %#lx < minv %#lx, maxv %#lx rbase %#lx",
808fa50a355SKonstantin Belousov 	    res, minv, maxv, rbase));
809fa50a355SKonstantin Belousov 	KASSERT(res < maxv,
810fa50a355SKonstantin Belousov 	    ("res %#lx > maxv %#lx, minv %#lx rbase %#lx",
811fa50a355SKonstantin Belousov 	    res, maxv, minv, rbase));
812fa50a355SKonstantin Belousov 	return (res);
813fa50a355SKonstantin Belousov }
814fa50a355SKonstantin Belousov 
815*20e1174aSEdward Tomasz Napierala static int
816*20e1174aSEdward Tomasz Napierala __elfN(enforce_limits)(struct image_params *imgp, const Elf_Ehdr *hdr,
817*20e1174aSEdward Tomasz Napierala     const Elf_Phdr *phdr, u_long et_dyn_addr)
818*20e1174aSEdward Tomasz Napierala {
819*20e1174aSEdward Tomasz Napierala 	struct vmspace *vmspace;
820*20e1174aSEdward Tomasz Napierala 	const char *err_str;
821*20e1174aSEdward Tomasz Napierala 	u_long text_size, data_size, total_size, text_addr, data_addr;
822*20e1174aSEdward Tomasz Napierala 	u_long seg_size, seg_addr;
823*20e1174aSEdward Tomasz Napierala 	int i;
824*20e1174aSEdward Tomasz Napierala 
825*20e1174aSEdward Tomasz Napierala 	err_str = NULL;
826*20e1174aSEdward Tomasz Napierala 	text_size = data_size = total_size = text_addr = data_addr = 0;
827*20e1174aSEdward Tomasz Napierala 
828*20e1174aSEdward Tomasz Napierala 	for (i = 0; i < hdr->e_phnum; i++) {
829*20e1174aSEdward Tomasz Napierala 		if (phdr[i].p_type != PT_LOAD || phdr[i].p_memsz == 0)
830*20e1174aSEdward Tomasz Napierala 			continue;
831*20e1174aSEdward Tomasz Napierala 
832*20e1174aSEdward Tomasz Napierala 		seg_addr = trunc_page(phdr[i].p_vaddr + et_dyn_addr);
833*20e1174aSEdward Tomasz Napierala 		seg_size = round_page(phdr[i].p_memsz +
834*20e1174aSEdward Tomasz Napierala 		    phdr[i].p_vaddr + et_dyn_addr - seg_addr);
835*20e1174aSEdward Tomasz Napierala 
836*20e1174aSEdward Tomasz Napierala 		/*
837*20e1174aSEdward Tomasz Napierala 		 * Make the largest executable segment the official
838*20e1174aSEdward Tomasz Napierala 		 * text segment and all others data.
839*20e1174aSEdward Tomasz Napierala 		 *
840*20e1174aSEdward Tomasz Napierala 		 * Note that obreak() assumes that data_addr + data_size == end
841*20e1174aSEdward Tomasz Napierala 		 * of data load area, and the ELF file format expects segments
842*20e1174aSEdward Tomasz Napierala 		 * to be sorted by address.  If multiple data segments exist,
843*20e1174aSEdward Tomasz Napierala 		 * the last one will be used.
844*20e1174aSEdward Tomasz Napierala 		 */
845*20e1174aSEdward Tomasz Napierala 
846*20e1174aSEdward Tomasz Napierala 		if ((phdr[i].p_flags & PF_X) != 0 && text_size < seg_size) {
847*20e1174aSEdward Tomasz Napierala 			text_size = seg_size;
848*20e1174aSEdward Tomasz Napierala 			text_addr = seg_addr;
849*20e1174aSEdward Tomasz Napierala 		} else {
850*20e1174aSEdward Tomasz Napierala 			data_size = seg_size;
851*20e1174aSEdward Tomasz Napierala 			data_addr = seg_addr;
852*20e1174aSEdward Tomasz Napierala 		}
853*20e1174aSEdward Tomasz Napierala 		total_size += seg_size;
854*20e1174aSEdward Tomasz Napierala 	}
855*20e1174aSEdward Tomasz Napierala 
856*20e1174aSEdward Tomasz Napierala 	if (data_addr == 0 && data_size == 0) {
857*20e1174aSEdward Tomasz Napierala 		data_addr = text_addr;
858*20e1174aSEdward Tomasz Napierala 		data_size = text_size;
859*20e1174aSEdward Tomasz Napierala 	}
860*20e1174aSEdward Tomasz Napierala 
861*20e1174aSEdward Tomasz Napierala 	/*
862*20e1174aSEdward Tomasz Napierala 	 * Check limits.  It should be safe to check the
863*20e1174aSEdward Tomasz Napierala 	 * limits after loading the segments since we do
864*20e1174aSEdward Tomasz Napierala 	 * not actually fault in all the segments pages.
865*20e1174aSEdward Tomasz Napierala 	 */
866*20e1174aSEdward Tomasz Napierala 	PROC_LOCK(imgp->proc);
867*20e1174aSEdward Tomasz Napierala 	if (data_size > lim_cur_proc(imgp->proc, RLIMIT_DATA))
868*20e1174aSEdward Tomasz Napierala 		err_str = "Data segment size exceeds process limit";
869*20e1174aSEdward Tomasz Napierala 	else if (text_size > maxtsiz)
870*20e1174aSEdward Tomasz Napierala 		err_str = "Text segment size exceeds system limit";
871*20e1174aSEdward Tomasz Napierala 	else if (total_size > lim_cur_proc(imgp->proc, RLIMIT_VMEM))
872*20e1174aSEdward Tomasz Napierala 		err_str = "Total segment size exceeds process limit";
873*20e1174aSEdward Tomasz Napierala 	else if (racct_set(imgp->proc, RACCT_DATA, data_size) != 0)
874*20e1174aSEdward Tomasz Napierala 		err_str = "Data segment size exceeds resource limit";
875*20e1174aSEdward Tomasz Napierala 	else if (racct_set(imgp->proc, RACCT_VMEM, total_size) != 0)
876*20e1174aSEdward Tomasz Napierala 		err_str = "Total segment size exceeds resource limit";
877*20e1174aSEdward Tomasz Napierala 	PROC_UNLOCK(imgp->proc);
878*20e1174aSEdward Tomasz Napierala 	if (err_str != NULL) {
879*20e1174aSEdward Tomasz Napierala 		uprintf("%s\n", err_str);
880*20e1174aSEdward Tomasz Napierala 		return (ENOMEM);
881*20e1174aSEdward Tomasz Napierala 	}
882*20e1174aSEdward Tomasz Napierala 
883*20e1174aSEdward Tomasz Napierala 	vmspace = imgp->proc->p_vmspace;
884*20e1174aSEdward Tomasz Napierala 	vmspace->vm_tsize = text_size >> PAGE_SHIFT;
885*20e1174aSEdward Tomasz Napierala 	vmspace->vm_taddr = (caddr_t)(uintptr_t)text_addr;
886*20e1174aSEdward Tomasz Napierala 	vmspace->vm_dsize = data_size >> PAGE_SHIFT;
887*20e1174aSEdward Tomasz Napierala 	vmspace->vm_daddr = (caddr_t)(uintptr_t)data_addr;
888*20e1174aSEdward Tomasz Napierala 
889*20e1174aSEdward Tomasz Napierala 	return (0);
890*20e1174aSEdward Tomasz Napierala }
891*20e1174aSEdward Tomasz Napierala 
892fa50a355SKonstantin Belousov /*
893fa50a355SKonstantin Belousov  * Impossible et_dyn_addr initial value indicating that the real base
894fa50a355SKonstantin Belousov  * must be calculated later with some randomization applied.
895fa50a355SKonstantin Belousov  */
896fa50a355SKonstantin Belousov #define	ET_DYN_ADDR_RAND	1
897fa50a355SKonstantin Belousov 
898303b270bSEivind Eklund static int
8993ebc1248SPeter Wemm __CONCAT(exec_, __elfN(imgact))(struct image_params *imgp)
900e1743d02SSøren Schmidt {
9016c775eb6SKonstantin Belousov 	struct thread *td;
9026c775eb6SKonstantin Belousov 	const Elf_Ehdr *hdr;
90332c01de2SDmitry Chagin 	const Elf_Phdr *phdr;
904e5e6093bSAlan Cox 	Elf_Auxargs *elf_auxargs;
9055856e12eSJohn Dyson 	struct vmspace *vmspace;
906fa50a355SKonstantin Belousov 	vm_map_t map;
907*20e1174aSEdward Tomasz Napierala 	const char *newinterp;
9086c775eb6SKonstantin Belousov 	char *interp, *interp_buf, *path;
909d1dbc694SJohn Polstra 	Elf_Brandinfo *brand_info;
9105fe3ed62SJake Burkholder 	struct sysentvec *sv;
9116c775eb6SKonstantin Belousov 	vm_prot_t prot;
912*20e1174aSEdward Tomasz Napierala 	u_long addr, baddr, et_dyn_addr, entry, proghdr;
913fa50a355SKonstantin Belousov 	u_long maxalign, mapsz, maxv, maxv1;
914cefb93f2SKonstantin Belousov 	uint32_t fctl0;
9156c775eb6SKonstantin Belousov 	int32_t osrel;
9166c775eb6SKonstantin Belousov 	int error, i, n, interp_name_len, have_interp;
9176c775eb6SKonstantin Belousov 
9186c775eb6SKonstantin Belousov 	hdr = (const Elf_Ehdr *)imgp->image_header;
919e1743d02SSøren Schmidt 
920e1743d02SSøren Schmidt 	/*
921e1743d02SSøren Schmidt 	 * Do we have a valid ELF header ?
922900b28f9SMaxim Sobolev 	 *
923900b28f9SMaxim Sobolev 	 * Only allow ET_EXEC & ET_DYN here, reject ET_DYN later
924900b28f9SMaxim Sobolev 	 * if particular brand doesn't support it.
925e1743d02SSøren Schmidt 	 */
926900b28f9SMaxim Sobolev 	if (__elfN(check_header)(hdr) != 0 ||
927900b28f9SMaxim Sobolev 	    (hdr->e_type != ET_EXEC && hdr->e_type != ET_DYN))
928a7cddfedSJake Burkholder 		return (-1);
929e1743d02SSøren Schmidt 
930e1743d02SSøren Schmidt 	/*
931e1743d02SSøren Schmidt 	 * From here on down, we return an errno, not -1, as we've
932e1743d02SSøren Schmidt 	 * detected an ELF file.
933e1743d02SSøren Schmidt 	 */
934e1743d02SSøren Schmidt 
935e1743d02SSøren Schmidt 	if ((hdr->e_phoff > PAGE_SIZE) ||
936d19d5bf4STijl Coosemans 	    (u_int)hdr->e_phentsize * hdr->e_phnum > PAGE_SIZE - hdr->e_phoff) {
937c8a79999SPeter Wemm 		/* Only support headers in first page for now */
9386b16d664SEd Maste 		uprintf("Program headers not in the first page\n");
939a7cddfedSJake Burkholder 		return (ENOEXEC);
940e1743d02SSøren Schmidt 	}
94152c24af7SPeter Wemm 	phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
9426b16d664SEd Maste 	if (!aligned(phdr, Elf_Addr)) {
9436b16d664SEd Maste 		uprintf("Unaligned program headers\n");
94493d1c728SKonstantin Belousov 		return (ENOEXEC);
9456b16d664SEd Maste 	}
9466c775eb6SKonstantin Belousov 
9476c775eb6SKonstantin Belousov 	n = error = 0;
9487564c4adSKonstantin Belousov 	baddr = 0;
9496c775eb6SKonstantin Belousov 	osrel = 0;
950cefb93f2SKonstantin Belousov 	fctl0 = 0;
9516c775eb6SKonstantin Belousov 	entry = proghdr = 0;
9526c775eb6SKonstantin Belousov 	interp_name_len = 0;
953*20e1174aSEdward Tomasz Napierala 	newinterp = NULL;
9546c775eb6SKonstantin Belousov 	interp = interp_buf = NULL;
9556c775eb6SKonstantin Belousov 	td = curthread;
956fa50a355SKonstantin Belousov 	maxalign = PAGE_SIZE;
957fa50a355SKonstantin Belousov 	mapsz = 0;
9586c775eb6SKonstantin Belousov 
9595fe3ed62SJake Burkholder 	for (i = 0; i < hdr->e_phnum; i++) {
960291c06a1SKonstantin Belousov 		switch (phdr[i].p_type) {
961291c06a1SKonstantin Belousov 		case PT_LOAD:
9627564c4adSKonstantin Belousov 			if (n == 0)
9637564c4adSKonstantin Belousov 				baddr = phdr[i].p_vaddr;
964fa50a355SKonstantin Belousov 			if (phdr[i].p_align > maxalign)
965fa50a355SKonstantin Belousov 				maxalign = phdr[i].p_align;
966fa50a355SKonstantin Belousov 			mapsz += phdr[i].p_memsz;
9677564c4adSKonstantin Belousov 			n++;
968291c06a1SKonstantin Belousov 			break;
969291c06a1SKonstantin Belousov 		case PT_INTERP:
970e5e6093bSAlan Cox 			/* Path to interpreter */
971c9e562b1SGordon Tetlow 			if (phdr[i].p_filesz < 2 ||
972c9e562b1SGordon Tetlow 			    phdr[i].p_filesz > MAXPATHLEN) {
9736b16d664SEd Maste 				uprintf("Invalid PT_INTERP\n");
9746c775eb6SKonstantin Belousov 				error = ENOEXEC;
9756c775eb6SKonstantin Belousov 				goto ret;
9766b16d664SEd Maste 			}
977d3ee0a15SJonathan T. Looney 			if (interp != NULL) {
978d3ee0a15SJonathan T. Looney 				uprintf("Multiple PT_INTERP headers\n");
979d3ee0a15SJonathan T. Looney 				error = ENOEXEC;
980d3ee0a15SJonathan T. Looney 				goto ret;
981d3ee0a15SJonathan T. Looney 			}
982d1ae5c83SKonstantin Belousov 			interp_name_len = phdr[i].p_filesz;
9836c775eb6SKonstantin Belousov 			if (phdr[i].p_offset > PAGE_SIZE ||
9846c775eb6SKonstantin Belousov 			    interp_name_len > PAGE_SIZE - phdr[i].p_offset) {
9856c775eb6SKonstantin Belousov 				VOP_UNLOCK(imgp->vp, 0);
9866c775eb6SKonstantin Belousov 				interp_buf = malloc(interp_name_len + 1, M_TEMP,
9876c775eb6SKonstantin Belousov 				    M_WAITOK);
9886c775eb6SKonstantin Belousov 				vn_lock(imgp->vp, LK_EXCLUSIVE | LK_RETRY);
9896c775eb6SKonstantin Belousov 				error = vn_rdwr(UIO_READ, imgp->vp, interp_buf,
9906c775eb6SKonstantin Belousov 				    interp_name_len, phdr[i].p_offset,
9916c775eb6SKonstantin Belousov 				    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred,
9926c775eb6SKonstantin Belousov 				    NOCRED, NULL, td);
9936c775eb6SKonstantin Belousov 				if (error != 0) {
99453e20b27SKonstantin Belousov 					uprintf("i/o error PT_INTERP %d\n",
99553e20b27SKonstantin Belousov 					    error);
9966c775eb6SKonstantin Belousov 					goto ret;
9976c775eb6SKonstantin Belousov 				}
9986c775eb6SKonstantin Belousov 				interp_buf[interp_name_len] = '\0';
9996c775eb6SKonstantin Belousov 				interp = interp_buf;
10006c775eb6SKonstantin Belousov 			} else {
10016c775eb6SKonstantin Belousov 				interp = __DECONST(char *, imgp->image_header) +
10026c775eb6SKonstantin Belousov 				    phdr[i].p_offset;
1003c9e562b1SGordon Tetlow 				if (interp[interp_name_len - 1] != '\0') {
1004c9e562b1SGordon Tetlow 					uprintf("Invalid PT_INTERP\n");
1005c9e562b1SGordon Tetlow 					error = ENOEXEC;
1006c9e562b1SGordon Tetlow 					goto ret;
1007c9e562b1SGordon Tetlow 				}
10086c775eb6SKonstantin Belousov 			}
1009291c06a1SKonstantin Belousov 			break;
1010291c06a1SKonstantin Belousov 		case PT_GNU_STACK:
1011291c06a1SKonstantin Belousov 			if (__elfN(nxstack))
1012291c06a1SKonstantin Belousov 				imgp->stack_prot =
1013291c06a1SKonstantin Belousov 				    __elfN(trans_prot)(phdr[i].p_flags);
1014316b3843SKonstantin Belousov 			imgp->stack_sz = phdr[i].p_memsz;
1015291c06a1SKonstantin Belousov 			break;
10163ebc1248SPeter Wemm 		}
10173ebc1248SPeter Wemm 	}
10183ebc1248SPeter Wemm 
1019d1ae5c83SKonstantin Belousov 	brand_info = __elfN(get_brandinfo)(imgp, interp, interp_name_len,
1020cefb93f2SKonstantin Belousov 	    &osrel, &fctl0);
10215fe3ed62SJake Burkholder 	if (brand_info == NULL) {
10225fe3ed62SJake Burkholder 		uprintf("ELF binary type \"%u\" not known.\n",
10235fe3ed62SJake Burkholder 		    hdr->e_ident[EI_OSABI]);
10246c775eb6SKonstantin Belousov 		error = ENOEXEC;
10256c775eb6SKonstantin Belousov 		goto ret;
10263ebc1248SPeter Wemm 	}
1027fa50a355SKonstantin Belousov 	sv = brand_info->sysvec;
102877ebe276SEd Maste 	et_dyn_addr = 0;
1029ab02d85fSKonstantin Belousov 	if (hdr->e_type == ET_DYN) {
10306b16d664SEd Maste 		if ((brand_info->flags & BI_CAN_EXEC_DYN) == 0) {
10316b16d664SEd Maste 			uprintf("Cannot execute shared object\n");
10326c775eb6SKonstantin Belousov 			error = ENOEXEC;
10336c775eb6SKonstantin Belousov 			goto ret;
10346b16d664SEd Maste 		}
10357564c4adSKonstantin Belousov 		/*
10367564c4adSKonstantin Belousov 		 * Honour the base load address from the dso if it is
10377564c4adSKonstantin Belousov 		 * non-zero for some reason.
10387564c4adSKonstantin Belousov 		 */
1039fa50a355SKonstantin Belousov 		if (baddr == 0) {
1040fa50a355SKonstantin Belousov 			if ((sv->sv_flags & SV_ASLR) == 0 ||
1041fa50a355SKonstantin Belousov 			    (fctl0 & NT_FREEBSD_FCTL_ASLR_DISABLE) != 0)
1042fa50a355SKonstantin Belousov 				et_dyn_addr = ET_DYN_LOAD_ADDR;
1043fa50a355SKonstantin Belousov 			else if ((__elfN(pie_aslr_enabled) &&
1044fa50a355SKonstantin Belousov 			    (imgp->proc->p_flag2 & P2_ASLR_DISABLE) == 0) ||
1045fa50a355SKonstantin Belousov 			    (imgp->proc->p_flag2 & P2_ASLR_ENABLE) != 0)
1046fa50a355SKonstantin Belousov 				et_dyn_addr = ET_DYN_ADDR_RAND;
1047fa50a355SKonstantin Belousov 			else
1048ab02d85fSKonstantin Belousov 				et_dyn_addr = ET_DYN_LOAD_ADDR;
104977ebe276SEd Maste 		}
1050fa50a355SKonstantin Belousov 	}
10519b68618dSPeter Wemm 	if (interp != NULL && brand_info->interp_newpath != NULL)
10524113f8d7SPeter Wemm 		newinterp = brand_info->interp_newpath;
10533ebc1248SPeter Wemm 
105460bb3943SAlan Cox 	/*
105560bb3943SAlan Cox 	 * Avoid a possible deadlock if the current address space is destroyed
105660bb3943SAlan Cox 	 * and that address space maps the locked vnode.  In the common case,
105760bb3943SAlan Cox 	 * the locked vnode's v_usecount is decremented but remains greater
105860bb3943SAlan Cox 	 * than zero.  Consequently, the vnode lock is not needed by vrele().
105960bb3943SAlan Cox 	 * However, in cases where the vnode lock is external, such as nullfs,
106060bb3943SAlan Cox 	 * v_usecount may become zero.
10611dfab802SAlan Cox 	 *
10621dfab802SAlan Cox 	 * The VV_TEXT flag prevents modifications to the executable while
10631dfab802SAlan Cox 	 * the vnode is unlocked.
106460bb3943SAlan Cox 	 */
106522db15c0SAttilio Rao 	VOP_UNLOCK(imgp->vp, 0);
106660bb3943SAlan Cox 
1067fa50a355SKonstantin Belousov 	/*
1068fa50a355SKonstantin Belousov 	 * Decide whether to enable randomization of user mappings.
1069fa50a355SKonstantin Belousov 	 * First, reset user preferences for the setid binaries.
1070fa50a355SKonstantin Belousov 	 * Then, account for the support of the randomization by the
1071fa50a355SKonstantin Belousov 	 * ABI, by user preferences, and make special treatment for
1072fa50a355SKonstantin Belousov 	 * PIE binaries.
1073fa50a355SKonstantin Belousov 	 */
1074fa50a355SKonstantin Belousov 	if (imgp->credential_setid) {
1075fa50a355SKonstantin Belousov 		PROC_LOCK(imgp->proc);
1076fa50a355SKonstantin Belousov 		imgp->proc->p_flag2 &= ~(P2_ASLR_ENABLE | P2_ASLR_DISABLE);
1077fa50a355SKonstantin Belousov 		PROC_UNLOCK(imgp->proc);
1078fa50a355SKonstantin Belousov 	}
1079fa50a355SKonstantin Belousov 	if ((sv->sv_flags & SV_ASLR) == 0 ||
1080fa50a355SKonstantin Belousov 	    (imgp->proc->p_flag2 & P2_ASLR_DISABLE) != 0 ||
1081fa50a355SKonstantin Belousov 	    (fctl0 & NT_FREEBSD_FCTL_ASLR_DISABLE) != 0) {
1082fa50a355SKonstantin Belousov 		KASSERT(et_dyn_addr != ET_DYN_ADDR_RAND,
1083fa50a355SKonstantin Belousov 		    ("et_dyn_addr == RAND and !ASLR"));
1084fa50a355SKonstantin Belousov 	} else if ((imgp->proc->p_flag2 & P2_ASLR_ENABLE) != 0 ||
1085fa50a355SKonstantin Belousov 	    (__elfN(aslr_enabled) && hdr->e_type == ET_EXEC) ||
1086fa50a355SKonstantin Belousov 	    et_dyn_addr == ET_DYN_ADDR_RAND) {
1087fa50a355SKonstantin Belousov 		imgp->map_flags |= MAP_ASLR;
1088fa50a355SKonstantin Belousov 		/*
1089fa50a355SKonstantin Belousov 		 * If user does not care about sbrk, utilize the bss
1090fa50a355SKonstantin Belousov 		 * grow region for mappings as well.  We can select
1091fa50a355SKonstantin Belousov 		 * the base for the image anywere and still not suffer
1092fa50a355SKonstantin Belousov 		 * from the fragmentation.
1093fa50a355SKonstantin Belousov 		 */
1094fa50a355SKonstantin Belousov 		if (!__elfN(aslr_honor_sbrk) ||
1095fa50a355SKonstantin Belousov 		    (imgp->proc->p_flag2 & P2_ASLR_IGNSTART) != 0)
1096fa50a355SKonstantin Belousov 			imgp->map_flags |= MAP_ASLR_IGNSTART;
1097fa50a355SKonstantin Belousov 	}
1098fa50a355SKonstantin Belousov 
109989b57fcfSKonstantin Belousov 	error = exec_new_vmspace(imgp, sv);
1100fa50a355SKonstantin Belousov 	vmspace = imgp->proc->p_vmspace;
1101fa50a355SKonstantin Belousov 	map = &vmspace->vm_map;
1102fa50a355SKonstantin Belousov 
110319059a13SJohn Baldwin 	imgp->proc->p_sysent = sv;
1104e1743d02SSøren Schmidt 
1105fa50a355SKonstantin Belousov 	maxv = vm_map_max(map) - lim_max(td, RLIMIT_STACK);
1106fa50a355SKonstantin Belousov 	if (et_dyn_addr == ET_DYN_ADDR_RAND) {
1107fa50a355SKonstantin Belousov 		KASSERT((map->flags & MAP_ASLR) != 0,
1108fa50a355SKonstantin Belousov 		    ("ET_DYN_ADDR_RAND but !MAP_ASLR"));
1109fa50a355SKonstantin Belousov 		et_dyn_addr = __CONCAT(rnd_, __elfN(base))(map,
1110fa50a355SKonstantin Belousov 		    vm_map_min(map) + mapsz + lim_max(td, RLIMIT_DATA),
1111fa50a355SKonstantin Belousov 		    /* reserve half of the address space to interpreter */
1112fa50a355SKonstantin Belousov 		    maxv / 2, 1UL << flsl(maxalign));
1113fa50a355SKonstantin Belousov 	}
1114fa50a355SKonstantin Belousov 
1115cb05b60aSAttilio Rao 	vn_lock(imgp->vp, LK_EXCLUSIVE | LK_RETRY);
11166c775eb6SKonstantin Belousov 	if (error != 0)
11176c775eb6SKonstantin Belousov 		goto ret;
111860bb3943SAlan Cox 
1119e1743d02SSøren Schmidt 	for (i = 0; i < hdr->e_phnum; i++) {
1120e1743d02SSøren Schmidt 		switch (phdr[i].p_type) {
1121e1743d02SSøren Schmidt 		case PT_LOAD:	/* Loadable segment */
11225b33842aSKonstantin Belousov 			if (phdr[i].p_memsz == 0)
11235b33842aSKonstantin Belousov 				break;
1124ed167eaaSKonstantin Belousov 			prot = __elfN(trans_prot)(phdr[i].p_flags);
1125292177e6SAlan Cox 			error = __elfN(load_section)(imgp, phdr[i].p_offset,
1126ab02d85fSKonstantin Belousov 			    (caddr_t)(uintptr_t)phdr[i].p_vaddr + et_dyn_addr,
11271699546dSEdward Tomasz Napierala 			    phdr[i].p_memsz, phdr[i].p_filesz, prot);
1128292177e6SAlan Cox 			if (error != 0)
11296c775eb6SKonstantin Belousov 				goto ret;
1130e1743d02SSøren Schmidt 
1131cfaf7e60SDoug Rabson 			/*
1132cfaf7e60SDoug Rabson 			 * If this segment contains the program headers,
1133cfaf7e60SDoug Rabson 			 * remember their virtual address for the AT_PHDR
1134cfaf7e60SDoug Rabson 			 * aux entry. Static binaries don't usually include
1135cfaf7e60SDoug Rabson 			 * a PT_PHDR entry.
1136cfaf7e60SDoug Rabson 			 */
1137cfaf7e60SDoug Rabson 			if (phdr[i].p_offset == 0 &&
1138cfaf7e60SDoug Rabson 			    hdr->e_phoff + hdr->e_phnum * hdr->e_phentsize
1139cfaf7e60SDoug Rabson 				<= phdr[i].p_filesz)
1140ab02d85fSKonstantin Belousov 				proghdr = phdr[i].p_vaddr + hdr->e_phoff +
1141ab02d85fSKonstantin Belousov 				    et_dyn_addr;
114296725dd0SAlexander Kabaev 			break;
114396725dd0SAlexander Kabaev 		case PT_PHDR: 	/* Program header table info */
1144ab02d85fSKonstantin Belousov 			proghdr = phdr[i].p_vaddr + et_dyn_addr;
114596725dd0SAlexander Kabaev 			break;
114696725dd0SAlexander Kabaev 		default:
114796725dd0SAlexander Kabaev 			break;
114896725dd0SAlexander Kabaev 		}
114996725dd0SAlexander Kabaev 	}
115096725dd0SAlexander Kabaev 
1151*20e1174aSEdward Tomasz Napierala 	error = __elfN(enforce_limits)(imgp, hdr, phdr, et_dyn_addr);
1152*20e1174aSEdward Tomasz Napierala 	if (error != 0)
1153*20e1174aSEdward Tomasz Napierala 		goto ret;
1154cac45152SMatthew Dillon 
1155920acedbSNathan Whitehorn 	entry = (u_long)hdr->e_entry + et_dyn_addr;
1156920acedbSNathan Whitehorn 
1157cac45152SMatthew Dillon 	/*
1158c460ac3aSPeter Wemm 	 * We load the dynamic linker where a userland call
1159c460ac3aSPeter Wemm 	 * to mmap(0, ...) would put it.  The rationale behind this
1160c460ac3aSPeter Wemm 	 * calculation is that it leaves room for the heap to grow to
1161c460ac3aSPeter Wemm 	 * its maximum allowed size.
1162c460ac3aSPeter Wemm 	 */
11636c775eb6SKonstantin Belousov 	addr = round_page((vm_offset_t)vmspace->vm_daddr + lim_max(td,
1164292177e6SAlan Cox 	    RLIMIT_DATA));
1165fa50a355SKonstantin Belousov 	if ((map->flags & MAP_ASLR) != 0) {
1166fa50a355SKonstantin Belousov 		maxv1 = maxv / 2 + addr / 2;
1167fa50a355SKonstantin Belousov 		MPASS(maxv1 >= addr);	/* No overflow */
1168fa50a355SKonstantin Belousov 		map->anon_loc = __CONCAT(rnd_, __elfN(base))(map, addr, maxv1,
1169fa50a355SKonstantin Belousov 		    MAXPAGESIZES > 1 ? pagesizes[1] : pagesizes[0]);
1170fa50a355SKonstantin Belousov 	} else {
1171fa50a355SKonstantin Belousov 		map->anon_loc = addr;
1172fa50a355SKonstantin Belousov 	}
1173e1743d02SSøren Schmidt 
1174ea5a2b2eSSøren Schmidt 	imgp->entry_addr = entry;
1175ea5a2b2eSSøren Schmidt 
117660bb3943SAlan Cox 	if (interp != NULL) {
11776c775eb6SKonstantin Belousov 		have_interp = FALSE;
117822db15c0SAttilio Rao 		VOP_UNLOCK(imgp->vp, 0);
1179fa50a355SKonstantin Belousov 		if ((map->flags & MAP_ASLR) != 0) {
1180fa50a355SKonstantin Belousov 			/* Assume that interpeter fits into 1/4 of AS */
1181fa50a355SKonstantin Belousov 			maxv1 = maxv / 2 + addr / 2;
1182fa50a355SKonstantin Belousov 			MPASS(maxv1 >= addr);	/* No overflow */
1183fa50a355SKonstantin Belousov 			addr = __CONCAT(rnd_, __elfN(base))(map, addr,
1184fa50a355SKonstantin Belousov 			    maxv1, PAGE_SIZE);
1185fa50a355SKonstantin Belousov 		}
118660bb3943SAlan Cox 		if (brand_info->emul_path != NULL &&
11879b68618dSPeter Wemm 		    brand_info->emul_path[0] != '\0') {
1188a163d034SWarner Losh 			path = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
118960bb3943SAlan Cox 			snprintf(path, MAXPATHLEN, "%s%s",
119060bb3943SAlan Cox 			    brand_info->emul_path, interp);
11919b68618dSPeter Wemm 			error = __elfN(load_file)(imgp->proc, path, &addr,
11921699546dSEdward Tomasz Napierala 			    &imgp->entry_addr);
1193911c2be0SMark Peek 			free(path, M_TEMP);
11949b68618dSPeter Wemm 			if (error == 0)
11954113f8d7SPeter Wemm 				have_interp = TRUE;
11969b68618dSPeter Wemm 		}
119718995077SKonstantin Belousov 		if (!have_interp && newinterp != NULL &&
119818995077SKonstantin Belousov 		    (brand_info->interp_path == NULL ||
119918995077SKonstantin Belousov 		    strcmp(interp, brand_info->interp_path) == 0)) {
12004113f8d7SPeter Wemm 			error = __elfN(load_file)(imgp->proc, newinterp, &addr,
12011699546dSEdward Tomasz Napierala 			    &imgp->entry_addr);
1202387ad998SKonstantin Belousov 			if (error == 0)
12034113f8d7SPeter Wemm 				have_interp = TRUE;
12044113f8d7SPeter Wemm 		}
12054113f8d7SPeter Wemm 		if (!have_interp) {
12069b68618dSPeter Wemm 			error = __elfN(load_file)(imgp->proc, interp, &addr,
12071699546dSEdward Tomasz Napierala 			    &imgp->entry_addr);
120860bb3943SAlan Cox 		}
1209cb05b60aSAttilio Rao 		vn_lock(imgp->vp, LK_EXCLUSIVE | LK_RETRY);
12109b68618dSPeter Wemm 		if (error != 0) {
1211d943fa35SKonstantin Belousov 			uprintf("ELF interpreter %s not found, error %d\n",
1212d943fa35SKonstantin Belousov 			    interp, error);
12136c775eb6SKonstantin Belousov 			goto ret;
1214e1743d02SSøren Schmidt 		}
121595c807cfSRobert Watson 	} else
12167564c4adSKonstantin Belousov 		addr = et_dyn_addr;
1217ea5a2b2eSSøren Schmidt 
1218e1743d02SSøren Schmidt 	/*
1219e1743d02SSøren Schmidt 	 * Construct auxargs table (used by the fixup routine)
1220e1743d02SSøren Schmidt 	 */
1221a163d034SWarner Losh 	elf_auxargs = malloc(sizeof(Elf_Auxargs), M_TEMP, M_WAITOK);
1222e1743d02SSøren Schmidt 	elf_auxargs->execfd = -1;
1223e1743d02SSøren Schmidt 	elf_auxargs->phdr = proghdr;
1224e1743d02SSøren Schmidt 	elf_auxargs->phent = hdr->e_phentsize;
1225e1743d02SSøren Schmidt 	elf_auxargs->phnum = hdr->e_phnum;
1226e1743d02SSøren Schmidt 	elf_auxargs->pagesz = PAGE_SIZE;
1227e1743d02SSøren Schmidt 	elf_auxargs->base = addr;
1228e1743d02SSøren Schmidt 	elf_auxargs->flags = 0;
1229e1743d02SSøren Schmidt 	elf_auxargs->entry = entry;
1230d36eec69SWarner Losh 	elf_auxargs->hdr_eflags = hdr->e_flags;
1231e1743d02SSøren Schmidt 
1232e1743d02SSøren Schmidt 	imgp->auxargs = elf_auxargs;
1233e1743d02SSøren Schmidt 	imgp->interpreted = 0;
1234a0ea661fSNathan Whitehorn 	imgp->reloc_base = addr;
123532c01de2SDmitry Chagin 	imgp->proc->p_osrel = osrel;
1236cefb93f2SKonstantin Belousov 	imgp->proc->p_fctl0 = fctl0;
1237885f13dcSJohn Baldwin 	imgp->proc->p_elf_machine = hdr->e_machine;
1238885f13dcSJohn Baldwin 	imgp->proc->p_elf_flags = hdr->e_flags;
1239f231de47SKonstantin Belousov 
12406c775eb6SKonstantin Belousov ret:
12416c775eb6SKonstantin Belousov 	free(interp_buf, M_TEMP);
1242a7cddfedSJake Burkholder 	return (error);
1243e1743d02SSøren Schmidt }
1244e1743d02SSøren Schmidt 
1245a360a43dSJake Burkholder #define	suword __CONCAT(suword, __ELF_WORD_SIZE)
12463ebc1248SPeter Wemm 
12473ebc1248SPeter Wemm int
12483ebc1248SPeter Wemm __elfN(freebsd_fixup)(register_t **stack_base, struct image_params *imgp)
1249e1743d02SSøren Schmidt {
1250ecbb00a2SDoug Rabson 	Elf_Auxargs *args = (Elf_Auxargs *)imgp->auxargs;
12515f77b8a8SBrooks Davis 	Elf_Auxinfo *argarray, *pos;
12525f77b8a8SBrooks Davis 	Elf_Addr *base, *auxbase;
12535f77b8a8SBrooks Davis 	int error;
1254e1743d02SSøren Schmidt 
1255a360a43dSJake Burkholder 	base = (Elf_Addr *)*stack_base;
12565f77b8a8SBrooks Davis 	auxbase = base + imgp->args->argc + 1 + imgp->args->envc + 1;
12575f77b8a8SBrooks Davis 	argarray = pos = malloc(AT_COUNT * sizeof(*pos), M_TEMP,
12585f77b8a8SBrooks Davis 	    M_WAITOK | M_ZERO);
1259e1743d02SSøren Schmidt 
126035c2a5a8SWarner Losh 	if (args->execfd != -1)
1261e1743d02SSøren Schmidt 		AUXARGS_ENTRY(pos, AT_EXECFD, args->execfd);
1262e1743d02SSøren Schmidt 	AUXARGS_ENTRY(pos, AT_PHDR, args->phdr);
1263e1743d02SSøren Schmidt 	AUXARGS_ENTRY(pos, AT_PHENT, args->phent);
1264e1743d02SSøren Schmidt 	AUXARGS_ENTRY(pos, AT_PHNUM, args->phnum);
1265e1743d02SSøren Schmidt 	AUXARGS_ENTRY(pos, AT_PAGESZ, args->pagesz);
1266e1743d02SSøren Schmidt 	AUXARGS_ENTRY(pos, AT_FLAGS, args->flags);
1267e1743d02SSøren Schmidt 	AUXARGS_ENTRY(pos, AT_ENTRY, args->entry);
1268e1743d02SSøren Schmidt 	AUXARGS_ENTRY(pos, AT_BASE, args->base);
1269d36eec69SWarner Losh 	AUXARGS_ENTRY(pos, AT_EHDRFLAGS, args->hdr_eflags);
12703ff06357SKonstantin Belousov 	if (imgp->execpathp != 0)
12713ff06357SKonstantin Belousov 		AUXARGS_ENTRY(pos, AT_EXECPATH, imgp->execpathp);
1272b96bd95bSIan Lepore 	AUXARGS_ENTRY(pos, AT_OSRELDATE,
1273b96bd95bSIan Lepore 	    imgp->proc->p_ucred->cr_prison->pr_osreldate);
1274ee235befSKonstantin Belousov 	if (imgp->canary != 0) {
1275ee235befSKonstantin Belousov 		AUXARGS_ENTRY(pos, AT_CANARY, imgp->canary);
1276ee235befSKonstantin Belousov 		AUXARGS_ENTRY(pos, AT_CANARYLEN, imgp->canarylen);
1277ee235befSKonstantin Belousov 	}
1278ee235befSKonstantin Belousov 	AUXARGS_ENTRY(pos, AT_NCPUS, mp_ncpus);
1279ee235befSKonstantin Belousov 	if (imgp->pagesizes != 0) {
1280ee235befSKonstantin Belousov 		AUXARGS_ENTRY(pos, AT_PAGESIZES, imgp->pagesizes);
1281ee235befSKonstantin Belousov 		AUXARGS_ENTRY(pos, AT_PAGESIZESLEN, imgp->pagesizeslen);
1282ee235befSKonstantin Belousov 	}
1283aea81038SKonstantin Belousov 	if (imgp->sysent->sv_timekeep_base != 0) {
1284aea81038SKonstantin Belousov 		AUXARGS_ENTRY(pos, AT_TIMEKEEP,
1285aea81038SKonstantin Belousov 		    imgp->sysent->sv_timekeep_base);
1286aea81038SKonstantin Belousov 	}
128726d8f3e1SKonstantin Belousov 	AUXARGS_ENTRY(pos, AT_STACKPROT, imgp->sysent->sv_shared_page_obj
128826d8f3e1SKonstantin Belousov 	    != NULL && imgp->stack_prot != 0 ? imgp->stack_prot :
128926d8f3e1SKonstantin Belousov 	    imgp->sysent->sv_stackprot);
1290c2f37b92SJohn Baldwin 	if (imgp->sysent->sv_hwcap != NULL)
1291c2f37b92SJohn Baldwin 		AUXARGS_ENTRY(pos, AT_HWCAP, *imgp->sysent->sv_hwcap);
1292904d8c49SMichal Meloun 	if (imgp->sysent->sv_hwcap2 != NULL)
1293904d8c49SMichal Meloun 		AUXARGS_ENTRY(pos, AT_HWCAP2, *imgp->sysent->sv_hwcap2);
1294e1743d02SSøren Schmidt 	AUXARGS_ENTRY(pos, AT_NULL, 0);
1295e1743d02SSøren Schmidt 
1296e1743d02SSøren Schmidt 	free(imgp->auxargs, M_TEMP);
1297e1743d02SSøren Schmidt 	imgp->auxargs = NULL;
1298d8b2f079SBrooks Davis 	KASSERT(pos - argarray <= AT_COUNT, ("Too many auxargs"));
12995f77b8a8SBrooks Davis 
13005f77b8a8SBrooks Davis 	error = copyout(argarray, auxbase, sizeof(*argarray) * AT_COUNT);
13015f77b8a8SBrooks Davis 	free(argarray, M_TEMP);
13025f77b8a8SBrooks Davis 	if (error != 0)
13035f77b8a8SBrooks Davis 		return (error);
1304e1743d02SSøren Schmidt 
13053ebc1248SPeter Wemm 	base--;
13065f77b8a8SBrooks Davis 	if (suword(base, imgp->args->argc) == -1)
13075f77b8a8SBrooks Davis 		return (EFAULT);
13083ebc1248SPeter Wemm 	*stack_base = (register_t *)base;
1309a7cddfedSJake Burkholder 	return (0);
1310e1743d02SSøren Schmidt }
1311e1743d02SSøren Schmidt 
1312e1743d02SSøren Schmidt /*
13138c64af4fSJohn Polstra  * Code for generating ELF core dumps.
13148c64af4fSJohn Polstra  */
13158c64af4fSJohn Polstra 
13164d77a549SAlfred Perlstein typedef void (*segment_callback)(vm_map_entry_t, void *);
13170ff27d31SJohn Polstra 
13180ff27d31SJohn Polstra /* Closure for cb_put_phdr(). */
13190ff27d31SJohn Polstra struct phdr_closure {
13200ff27d31SJohn Polstra 	Elf_Phdr *phdr;		/* Program header to fill in */
13210ff27d31SJohn Polstra 	Elf_Off offset;		/* Offset of segment in core file */
13220ff27d31SJohn Polstra };
13230ff27d31SJohn Polstra 
13240ff27d31SJohn Polstra /* Closure for cb_size_segment(). */
13250ff27d31SJohn Polstra struct sseg_closure {
13260ff27d31SJohn Polstra 	int count;		/* Count of writable segments. */
13270ff27d31SJohn Polstra 	size_t size;		/* Total size of all writable segments. */
13280ff27d31SJohn Polstra };
13290ff27d31SJohn Polstra 
1330bd390213SMikolaj Golub typedef void (*outfunc_t)(void *, struct sbuf *, size_t *);
1331bd390213SMikolaj Golub 
1332bd390213SMikolaj Golub struct note_info {
1333bd390213SMikolaj Golub 	int		type;		/* Note type. */
1334bd390213SMikolaj Golub 	outfunc_t 	outfunc; 	/* Output function. */
1335bd390213SMikolaj Golub 	void		*outarg;	/* Argument for the output function. */
1336bd390213SMikolaj Golub 	size_t		outsize;	/* Output size. */
1337bd390213SMikolaj Golub 	TAILQ_ENTRY(note_info) link;	/* Link to the next note info. */
1338bd390213SMikolaj Golub };
1339bd390213SMikolaj Golub 
1340bd390213SMikolaj Golub TAILQ_HEAD(note_info_list, note_info);
1341bd390213SMikolaj Golub 
1342aa14e9b7SMark Johnston /* Coredump output parameters. */
1343aa14e9b7SMark Johnston struct coredump_params {
1344aa14e9b7SMark Johnston 	off_t		offset;
1345aa14e9b7SMark Johnston 	struct ucred	*active_cred;
1346aa14e9b7SMark Johnston 	struct ucred	*file_cred;
1347aa14e9b7SMark Johnston 	struct thread	*td;
1348aa14e9b7SMark Johnston 	struct vnode	*vp;
134978f57a9cSMark Johnston 	struct compressor *comp;
1350aa14e9b7SMark Johnston };
1351aa14e9b7SMark Johnston 
135278f57a9cSMark Johnston extern int compress_user_cores;
135378f57a9cSMark Johnston extern int compress_user_cores_level;
135478f57a9cSMark Johnston 
13554d77a549SAlfred Perlstein static void cb_put_phdr(vm_map_entry_t, void *);
13564d77a549SAlfred Perlstein static void cb_size_segment(vm_map_entry_t, void *);
1357c468ff88SAndriy Gapon static int core_write(struct coredump_params *, const void *, size_t, off_t,
1358aa14e9b7SMark Johnston     enum uio_seg);
13591005d8afSConrad Meyer static void each_dumpable_segment(struct thread *, segment_callback, void *);
1360aa14e9b7SMark Johnston static int __elfN(corehdr)(struct coredump_params *, int, void *, size_t,
1361aa14e9b7SMark Johnston     struct note_info_list *, size_t);
1362bd390213SMikolaj Golub static void __elfN(prepare_notes)(struct thread *, struct note_info_list *,
1363bd390213SMikolaj Golub     size_t *);
1364bd390213SMikolaj Golub static void __elfN(puthdr)(struct thread *, void *, size_t, int, size_t);
1365bd390213SMikolaj Golub static void __elfN(putnote)(struct note_info *, struct sbuf *);
1366bd390213SMikolaj Golub static size_t register_note(struct note_info_list *, int, outfunc_t, void *);
1367bd390213SMikolaj Golub static int sbuf_drain_core_output(void *, const char *, int);
1368f1fca82eSMikolaj Golub static int sbuf_drain_count(void *arg, const char *data, int len);
1369bd390213SMikolaj Golub 
1370bd390213SMikolaj Golub static void __elfN(note_fpregset)(void *, struct sbuf *, size_t *);
1371bd390213SMikolaj Golub static void __elfN(note_prpsinfo)(void *, struct sbuf *, size_t *);
1372bd390213SMikolaj Golub static void __elfN(note_prstatus)(void *, struct sbuf *, size_t *);
1373bd390213SMikolaj Golub static void __elfN(note_threadmd)(void *, struct sbuf *, size_t *);
1374bd390213SMikolaj Golub static void __elfN(note_thrmisc)(void *, struct sbuf *, size_t *);
137586be94fcSTycho Nightingale static void __elfN(note_ptlwpinfo)(void *, struct sbuf *, size_t *);
1376f1fca82eSMikolaj Golub static void __elfN(note_procstat_auxv)(void *, struct sbuf *, size_t *);
1377f1fca82eSMikolaj Golub static void __elfN(note_procstat_proc)(void *, struct sbuf *, size_t *);
1378f1fca82eSMikolaj Golub static void __elfN(note_procstat_psstrings)(void *, struct sbuf *, size_t *);
1379f1fca82eSMikolaj Golub static void note_procstat_files(void *, struct sbuf *, size_t *);
1380f1fca82eSMikolaj Golub static void note_procstat_groups(void *, struct sbuf *, size_t *);
1381f1fca82eSMikolaj Golub static void note_procstat_osrel(void *, struct sbuf *, size_t *);
1382f1fca82eSMikolaj Golub static void note_procstat_rlimit(void *, struct sbuf *, size_t *);
1383f1fca82eSMikolaj Golub static void note_procstat_umask(void *, struct sbuf *, size_t *);
1384f1fca82eSMikolaj Golub static void note_procstat_vmmap(void *, struct sbuf *, size_t *);
13858c64af4fSJohn Polstra 
1386aa14e9b7SMark Johnston /*
1387aa14e9b7SMark Johnston  * Write out a core segment to the compression stream.
1388aa14e9b7SMark Johnston  */
1389e7228204SAlfred Perlstein static int
1390aa14e9b7SMark Johnston compress_chunk(struct coredump_params *p, char *base, char *buf, u_int len)
1391aa14e9b7SMark Johnston {
1392aa14e9b7SMark Johnston 	u_int chunk_len;
1393e7228204SAlfred Perlstein 	int error;
1394aa14e9b7SMark Johnston 
1395aa14e9b7SMark Johnston 	while (len > 0) {
1396aa14e9b7SMark Johnston 		chunk_len = MIN(len, CORE_BUF_SIZE);
1397c468ff88SAndriy Gapon 
1398c468ff88SAndriy Gapon 		/*
1399c468ff88SAndriy Gapon 		 * We can get EFAULT error here.
1400c468ff88SAndriy Gapon 		 * In that case zero out the current chunk of the segment.
1401c468ff88SAndriy Gapon 		 */
1402c468ff88SAndriy Gapon 		error = copyin(base, buf, chunk_len);
1403c468ff88SAndriy Gapon 		if (error != 0)
1404c468ff88SAndriy Gapon 			bzero(buf, chunk_len);
140578f57a9cSMark Johnston 		error = compressor_write(p->comp, buf, chunk_len);
1406aa14e9b7SMark Johnston 		if (error != 0)
1407aa14e9b7SMark Johnston 			break;
1408aa14e9b7SMark Johnston 		base += chunk_len;
1409aa14e9b7SMark Johnston 		len -= chunk_len;
1410e7228204SAlfred Perlstein 	}
1411e7228204SAlfred Perlstein 	return (error);
1412e7228204SAlfred Perlstein }
1413e7228204SAlfred Perlstein 
1414aa14e9b7SMark Johnston static int
141578f57a9cSMark Johnston core_compressed_write(void *base, size_t len, off_t offset, void *arg)
1416aa14e9b7SMark Johnston {
1417aa14e9b7SMark Johnston 
1418aa14e9b7SMark Johnston 	return (core_write((struct coredump_params *)arg, base, len, offset,
1419aa14e9b7SMark Johnston 	    UIO_SYSSPACE));
1420aa14e9b7SMark Johnston }
1421aa14e9b7SMark Johnston 
1422aa14e9b7SMark Johnston static int
1423c468ff88SAndriy Gapon core_write(struct coredump_params *p, const void *base, size_t len,
1424c468ff88SAndriy Gapon     off_t offset, enum uio_seg seg)
1425aa14e9b7SMark Johnston {
1426aa14e9b7SMark Johnston 
1427c468ff88SAndriy Gapon 	return (vn_rdwr_inchunks(UIO_WRITE, p->vp, __DECONST(void *, base),
1428c468ff88SAndriy Gapon 	    len, offset, seg, IO_UNIT | IO_DIRECT | IO_RANGELOCKED,
1429aa14e9b7SMark Johnston 	    p->active_cred, p->file_cred, NULL, p->td));
1430aa14e9b7SMark Johnston }
1431aa14e9b7SMark Johnston 
1432aa14e9b7SMark Johnston static int
1433aa14e9b7SMark Johnston core_output(void *base, size_t len, off_t offset, struct coredump_params *p,
1434aa14e9b7SMark Johnston     void *tmpbuf)
1435aa14e9b7SMark Johnston {
1436c468ff88SAndriy Gapon 	int error;
1437aa14e9b7SMark Johnston 
143878f57a9cSMark Johnston 	if (p->comp != NULL)
1439aa14e9b7SMark Johnston 		return (compress_chunk(p, base, tmpbuf, len));
144078f57a9cSMark Johnston 
1441c468ff88SAndriy Gapon 	/*
1442c468ff88SAndriy Gapon 	 * EFAULT is a non-fatal error that we can get, for example,
1443c468ff88SAndriy Gapon 	 * if the segment is backed by a file but extends beyond its
1444c468ff88SAndriy Gapon 	 * end.
1445c468ff88SAndriy Gapon 	 */
1446c468ff88SAndriy Gapon 	error = core_write(p, base, len, offset, UIO_USERSPACE);
1447c468ff88SAndriy Gapon 	if (error == EFAULT) {
1448c468ff88SAndriy Gapon 		log(LOG_WARNING, "Failed to fully fault in a core file segment "
1449c468ff88SAndriy Gapon 		    "at VA %p with size 0x%zx to be written at offset 0x%jx "
1450c468ff88SAndriy Gapon 		    "for process %s\n", base, len, offset, curproc->p_comm);
1451c468ff88SAndriy Gapon 
1452c468ff88SAndriy Gapon 		/*
1453c468ff88SAndriy Gapon 		 * Write a "real" zero byte at the end of the target region
1454c468ff88SAndriy Gapon 		 * in the case this is the last segment.
1455c468ff88SAndriy Gapon 		 * The intermediate space will be implicitly zero-filled.
1456c468ff88SAndriy Gapon 		 */
1457c468ff88SAndriy Gapon 		error = core_write(p, zero_region, 1, offset + len - 1,
1458c468ff88SAndriy Gapon 		    UIO_SYSSPACE);
1459c468ff88SAndriy Gapon 	}
1460c468ff88SAndriy Gapon 	return (error);
1461aa14e9b7SMark Johnston }
1462bd390213SMikolaj Golub 
1463bd390213SMikolaj Golub /*
1464bd390213SMikolaj Golub  * Drain into a core file.
1465bd390213SMikolaj Golub  */
1466bd390213SMikolaj Golub static int
1467bd390213SMikolaj Golub sbuf_drain_core_output(void *arg, const char *data, int len)
1468bd390213SMikolaj Golub {
1469aa14e9b7SMark Johnston 	struct coredump_params *p;
1470f1fca82eSMikolaj Golub 	int error, locked;
1471bd390213SMikolaj Golub 
1472aa14e9b7SMark Johnston 	p = (struct coredump_params *)arg;
1473f1fca82eSMikolaj Golub 
1474f1fca82eSMikolaj Golub 	/*
1475f1fca82eSMikolaj Golub 	 * Some kern_proc out routines that print to this sbuf may
1476f1fca82eSMikolaj Golub 	 * call us with the process lock held. Draining with the
1477f1fca82eSMikolaj Golub 	 * non-sleepable lock held is unsafe. The lock is needed for
1478f1fca82eSMikolaj Golub 	 * those routines when dumping a live process. In our case we
1479f1fca82eSMikolaj Golub 	 * can safely release the lock before draining and acquire
1480f1fca82eSMikolaj Golub 	 * again after.
1481f1fca82eSMikolaj Golub 	 */
1482f1fca82eSMikolaj Golub 	locked = PROC_LOCKED(p->td->td_proc);
1483f1fca82eSMikolaj Golub 	if (locked)
1484f1fca82eSMikolaj Golub 		PROC_UNLOCK(p->td->td_proc);
148578f57a9cSMark Johnston 	if (p->comp != NULL)
148678f57a9cSMark Johnston 		error = compressor_write(p->comp, __DECONST(char *, data), len);
1487bd390213SMikolaj Golub 	else
1488aa14e9b7SMark Johnston 		error = core_write(p, __DECONST(void *, data), len, p->offset,
1489aa14e9b7SMark Johnston 		    UIO_SYSSPACE);
1490f1fca82eSMikolaj Golub 	if (locked)
1491f1fca82eSMikolaj Golub 		PROC_LOCK(p->td->td_proc);
1492bd390213SMikolaj Golub 	if (error != 0)
1493bd390213SMikolaj Golub 		return (-error);
1494bd390213SMikolaj Golub 	p->offset += len;
1495bd390213SMikolaj Golub 	return (len);
1496bd390213SMikolaj Golub }
1497bd390213SMikolaj Golub 
1498f1fca82eSMikolaj Golub /*
1499f1fca82eSMikolaj Golub  * Drain into a counter.
1500f1fca82eSMikolaj Golub  */
1501f1fca82eSMikolaj Golub static int
1502f1fca82eSMikolaj Golub sbuf_drain_count(void *arg, const char *data __unused, int len)
1503f1fca82eSMikolaj Golub {
1504f1fca82eSMikolaj Golub 	size_t *sizep;
1505f1fca82eSMikolaj Golub 
1506f1fca82eSMikolaj Golub 	sizep = (size_t *)arg;
1507f1fca82eSMikolaj Golub 	*sizep += len;
1508f1fca82eSMikolaj Golub 	return (len);
1509f1fca82eSMikolaj Golub }
1510f1fca82eSMikolaj Golub 
15118c64af4fSJohn Polstra int
1512e7228204SAlfred Perlstein __elfN(coredump)(struct thread *td, struct vnode *vp, off_t limit, int flags)
1513fca666a1SJulian Elischer {
1514247aba24SMarcel Moolenaar 	struct ucred *cred = td->td_ucred;
1515fca666a1SJulian Elischer 	int error = 0;
15160ff27d31SJohn Polstra 	struct sseg_closure seginfo;
1517bd390213SMikolaj Golub 	struct note_info_list notelst;
1518aa14e9b7SMark Johnston 	struct coredump_params params;
1519bd390213SMikolaj Golub 	struct note_info *ninfo;
1520aa14e9b7SMark Johnston 	void *hdr, *tmpbuf;
1521bd390213SMikolaj Golub 	size_t hdrsize, notesz, coresize;
15228c64af4fSJohn Polstra 
1523e7228204SAlfred Perlstein 	hdr = NULL;
152402d131adSMark Johnston 	tmpbuf = NULL;
1525bd390213SMikolaj Golub 	TAILQ_INIT(&notelst);
1526e7228204SAlfred Perlstein 
15270ff27d31SJohn Polstra 	/* Size the program segments. */
15280ff27d31SJohn Polstra 	seginfo.count = 0;
15290ff27d31SJohn Polstra 	seginfo.size = 0;
15301005d8afSConrad Meyer 	each_dumpable_segment(td, cb_size_segment, &seginfo);
15310ff27d31SJohn Polstra 
15320ff27d31SJohn Polstra 	/*
1533bd390213SMikolaj Golub 	 * Collect info about the core file header area.
15340ff27d31SJohn Polstra 	 */
1535bd390213SMikolaj Golub 	hdrsize = sizeof(Elf_Ehdr) + sizeof(Elf_Phdr) * (1 + seginfo.count);
1536c17b0bd2SConrad Meyer 	if (seginfo.count + 1 >= PN_XNUM)
1537c17b0bd2SConrad Meyer 		hdrsize += sizeof(Elf_Shdr);
1538bd390213SMikolaj Golub 	__elfN(prepare_notes)(td, &notelst, &notesz);
1539bd390213SMikolaj Golub 	coresize = round_page(hdrsize + notesz) + seginfo.size;
15400ff27d31SJohn Polstra 
154102d131adSMark Johnston 	/* Set up core dump parameters. */
154202d131adSMark Johnston 	params.offset = 0;
154302d131adSMark Johnston 	params.active_cred = cred;
154402d131adSMark Johnston 	params.file_cred = NOCRED;
154502d131adSMark Johnston 	params.td = td;
154602d131adSMark Johnston 	params.vp = vp;
154778f57a9cSMark Johnston 	params.comp = NULL;
154802d131adSMark Johnston 
1549afcc55f3SEdward Tomasz Napierala #ifdef RACCT
15504b5c9cf6SEdward Tomasz Napierala 	if (racct_enable) {
15511ba5ad42SEdward Tomasz Napierala 		PROC_LOCK(td->td_proc);
1552bd390213SMikolaj Golub 		error = racct_add(td->td_proc, RACCT_CORE, coresize);
15531ba5ad42SEdward Tomasz Napierala 		PROC_UNLOCK(td->td_proc);
15541ba5ad42SEdward Tomasz Napierala 		if (error != 0) {
15551ba5ad42SEdward Tomasz Napierala 			error = EFAULT;
15561ba5ad42SEdward Tomasz Napierala 			goto done;
15571ba5ad42SEdward Tomasz Napierala 		}
15584b5c9cf6SEdward Tomasz Napierala 	}
1559afcc55f3SEdward Tomasz Napierala #endif
1560bd390213SMikolaj Golub 	if (coresize >= limit) {
1561fba6b1afSAlfred Perlstein 		error = EFAULT;
1562fba6b1afSAlfred Perlstein 		goto done;
1563fba6b1afSAlfred Perlstein 	}
15640ff27d31SJohn Polstra 
1565aa14e9b7SMark Johnston 	/* Create a compression stream if necessary. */
156678f57a9cSMark Johnston 	if (compress_user_cores != 0) {
156778f57a9cSMark Johnston 		params.comp = compressor_init(core_compressed_write,
156878f57a9cSMark Johnston 		    compress_user_cores, CORE_BUF_SIZE,
156978f57a9cSMark Johnston 		    compress_user_cores_level, &params);
157078f57a9cSMark Johnston 		if (params.comp == NULL) {
1571aa14e9b7SMark Johnston 			error = EFAULT;
1572aa14e9b7SMark Johnston 			goto done;
1573aa14e9b7SMark Johnston 		}
1574aa14e9b7SMark Johnston 		tmpbuf = malloc(CORE_BUF_SIZE, M_TEMP, M_WAITOK | M_ZERO);
1575aa14e9b7SMark Johnston         }
1576aa14e9b7SMark Johnston 
15770ff27d31SJohn Polstra 	/*
15780ff27d31SJohn Polstra 	 * Allocate memory for building the header, fill it up,
1579bd390213SMikolaj Golub 	 * and write it out following the notes.
15800ff27d31SJohn Polstra 	 */
1581a163d034SWarner Losh 	hdr = malloc(hdrsize, M_TEMP, M_WAITOK);
1582aa14e9b7SMark Johnston 	error = __elfN(corehdr)(&params, seginfo.count, hdr, hdrsize, &notelst,
1583aa14e9b7SMark Johnston 	    notesz);
15840ff27d31SJohn Polstra 
15850ff27d31SJohn Polstra 	/* Write the contents of all of the writable segments. */
15860ff27d31SJohn Polstra 	if (error == 0) {
15870ff27d31SJohn Polstra 		Elf_Phdr *php;
15882b471bc6STim J. Robbins 		off_t offset;
15890ff27d31SJohn Polstra 		int i;
15900ff27d31SJohn Polstra 
15910ff27d31SJohn Polstra 		php = (Elf_Phdr *)((char *)hdr + sizeof(Elf_Ehdr)) + 1;
1592bd390213SMikolaj Golub 		offset = round_page(hdrsize + notesz);
15930ff27d31SJohn Polstra 		for (i = 0; i < seginfo.count; i++) {
1594aa14e9b7SMark Johnston 			error = core_output((caddr_t)(uintptr_t)php->p_vaddr,
1595aa14e9b7SMark Johnston 			    php->p_filesz, offset, &params, tmpbuf);
15960ff27d31SJohn Polstra 			if (error != 0)
15972b471bc6STim J. Robbins 				break;
15980ff27d31SJohn Polstra 			offset += php->p_filesz;
15990ff27d31SJohn Polstra 			php++;
16000ff27d31SJohn Polstra 		}
160178f57a9cSMark Johnston 		if (error == 0 && params.comp != NULL)
160278f57a9cSMark Johnston 			error = compressor_flush(params.comp);
16030ff27d31SJohn Polstra 	}
1604e7228204SAlfred Perlstein 	if (error) {
1605e7228204SAlfred Perlstein 		log(LOG_WARNING,
1606e7228204SAlfred Perlstein 		    "Failed to write core file for process %s (error %d)\n",
1607e7228204SAlfred Perlstein 		    curproc->p_comm, error);
1608e7228204SAlfred Perlstein 	}
1609e7228204SAlfred Perlstein 
1610e7228204SAlfred Perlstein done:
1611aa14e9b7SMark Johnston 	free(tmpbuf, M_TEMP);
161278f57a9cSMark Johnston 	if (params.comp != NULL)
161378f57a9cSMark Johnston 		compressor_fini(params.comp);
1614bd390213SMikolaj Golub 	while ((ninfo = TAILQ_FIRST(&notelst)) != NULL) {
1615bd390213SMikolaj Golub 		TAILQ_REMOVE(&notelst, ninfo, link);
1616bd390213SMikolaj Golub 		free(ninfo, M_TEMP);
1617bd390213SMikolaj Golub 	}
1618bd390213SMikolaj Golub 	if (hdr != NULL)
16190ff27d31SJohn Polstra 		free(hdr, M_TEMP);
16200ff27d31SJohn Polstra 
1621a7cddfedSJake Burkholder 	return (error);
16228c64af4fSJohn Polstra }
16238c64af4fSJohn Polstra 
16240ff27d31SJohn Polstra /*
16251005d8afSConrad Meyer  * A callback for each_dumpable_segment() to write out the segment's
16260ff27d31SJohn Polstra  * program header entry.
16270ff27d31SJohn Polstra  */
16280ff27d31SJohn Polstra static void
16295cc6d253SEd Maste cb_put_phdr(vm_map_entry_t entry, void *closure)
16300ff27d31SJohn Polstra {
16310ff27d31SJohn Polstra 	struct phdr_closure *phc = (struct phdr_closure *)closure;
16320ff27d31SJohn Polstra 	Elf_Phdr *phdr = phc->phdr;
16330ff27d31SJohn Polstra 
16340ff27d31SJohn Polstra 	phc->offset = round_page(phc->offset);
16350ff27d31SJohn Polstra 
16360ff27d31SJohn Polstra 	phdr->p_type = PT_LOAD;
16370ff27d31SJohn Polstra 	phdr->p_offset = phc->offset;
16380ff27d31SJohn Polstra 	phdr->p_vaddr = entry->start;
16390ff27d31SJohn Polstra 	phdr->p_paddr = 0;
16400ff27d31SJohn Polstra 	phdr->p_filesz = phdr->p_memsz = entry->end - entry->start;
16410ff27d31SJohn Polstra 	phdr->p_align = PAGE_SIZE;
1642ed167eaaSKonstantin Belousov 	phdr->p_flags = __elfN(untrans_prot)(entry->protection);
16430ff27d31SJohn Polstra 
16440ff27d31SJohn Polstra 	phc->offset += phdr->p_filesz;
16450ff27d31SJohn Polstra 	phc->phdr++;
16460ff27d31SJohn Polstra }
16470ff27d31SJohn Polstra 
16480ff27d31SJohn Polstra /*
16491005d8afSConrad Meyer  * A callback for each_dumpable_segment() to gather information about
16500ff27d31SJohn Polstra  * the number of segments and their total size.
16510ff27d31SJohn Polstra  */
16520ff27d31SJohn Polstra static void
1653f3325003SConrad Meyer cb_size_segment(vm_map_entry_t entry, void *closure)
16540ff27d31SJohn Polstra {
16550ff27d31SJohn Polstra 	struct sseg_closure *ssc = (struct sseg_closure *)closure;
16560ff27d31SJohn Polstra 
16570ff27d31SJohn Polstra 	ssc->count++;
16580ff27d31SJohn Polstra 	ssc->size += entry->end - entry->start;
16590ff27d31SJohn Polstra }
16600ff27d31SJohn Polstra 
16610ff27d31SJohn Polstra /*
16620ff27d31SJohn Polstra  * For each writable segment in the process's memory map, call the given
16630ff27d31SJohn Polstra  * function with a pointer to the map entry and some arbitrary
16640ff27d31SJohn Polstra  * caller-supplied data.
16650ff27d31SJohn Polstra  */
16660ff27d31SJohn Polstra static void
16671005d8afSConrad Meyer each_dumpable_segment(struct thread *td, segment_callback func, void *closure)
16680ff27d31SJohn Polstra {
1669247aba24SMarcel Moolenaar 	struct proc *p = td->td_proc;
16700ff27d31SJohn Polstra 	vm_map_t map = &p->p_vmspace->vm_map;
16710ff27d31SJohn Polstra 	vm_map_entry_t entry;
1672976a87a2SAlan Cox 	vm_object_t backing_object, object;
1673976a87a2SAlan Cox 	boolean_t ignore_entry;
16740ff27d31SJohn Polstra 
1675976a87a2SAlan Cox 	vm_map_lock_read(map);
16760ff27d31SJohn Polstra 	for (entry = map->header.next; entry != &map->header;
16770ff27d31SJohn Polstra 	    entry = entry->next) {
1678fa7dd9c5SMatthew Dillon 		/*
1679fa7dd9c5SMatthew Dillon 		 * Don't dump inaccessible mappings, deal with legacy
1680fa7dd9c5SMatthew Dillon 		 * coredump mode.
1681fa7dd9c5SMatthew Dillon 		 *
1682fa7dd9c5SMatthew Dillon 		 * Note that read-only segments related to the elf binary
1683fa7dd9c5SMatthew Dillon 		 * are marked MAP_ENTRY_NOCOREDUMP now so we no longer
1684fa7dd9c5SMatthew Dillon 		 * need to arbitrarily ignore such segments.
1685fa7dd9c5SMatthew Dillon 		 */
1686fa7dd9c5SMatthew Dillon 		if (elf_legacy_coredump) {
1687fa7dd9c5SMatthew Dillon 			if ((entry->protection & VM_PROT_RW) != VM_PROT_RW)
16880ff27d31SJohn Polstra 				continue;
1689fa7dd9c5SMatthew Dillon 		} else {
1690fa7dd9c5SMatthew Dillon 			if ((entry->protection & VM_PROT_ALL) == 0)
1691fa7dd9c5SMatthew Dillon 				continue;
1692fa7dd9c5SMatthew Dillon 		}
16930ff27d31SJohn Polstra 
16949730a5daSPaul Saab 		/*
1695fa7dd9c5SMatthew Dillon 		 * Dont include memory segment in the coredump if
1696fa7dd9c5SMatthew Dillon 		 * MAP_NOCORE is set in mmap(2) or MADV_NOCORE in
1697fa7dd9c5SMatthew Dillon 		 * madvise(2).  Do not dump submaps (i.e. parts of the
1698fa7dd9c5SMatthew Dillon 		 * kernel map).
16999730a5daSPaul Saab 		 */
1700fa7dd9c5SMatthew Dillon 		if (entry->eflags & (MAP_ENTRY_NOCOREDUMP|MAP_ENTRY_IS_SUB_MAP))
17019730a5daSPaul Saab 			continue;
17029730a5daSPaul Saab 
1703976a87a2SAlan Cox 		if ((object = entry->object.vm_object) == NULL)
17040ff27d31SJohn Polstra 			continue;
17050ff27d31SJohn Polstra 
17060ff27d31SJohn Polstra 		/* Ignore memory-mapped devices and such things. */
1707bc403f03SAttilio Rao 		VM_OBJECT_RLOCK(object);
1708976a87a2SAlan Cox 		while ((backing_object = object->backing_object) != NULL) {
1709bc403f03SAttilio Rao 			VM_OBJECT_RLOCK(backing_object);
1710bc403f03SAttilio Rao 			VM_OBJECT_RUNLOCK(object);
1711976a87a2SAlan Cox 			object = backing_object;
1712976a87a2SAlan Cox 		}
1713976a87a2SAlan Cox 		ignore_entry = object->type != OBJT_DEFAULT &&
1714bc411bc2SJohn Baldwin 		    object->type != OBJT_SWAP && object->type != OBJT_VNODE &&
1715bc411bc2SJohn Baldwin 		    object->type != OBJT_PHYS;
1716bc403f03SAttilio Rao 		VM_OBJECT_RUNLOCK(object);
1717976a87a2SAlan Cox 		if (ignore_entry)
17180ff27d31SJohn Polstra 			continue;
17190ff27d31SJohn Polstra 
17200ff27d31SJohn Polstra 		(*func)(entry, closure);
17210ff27d31SJohn Polstra 	}
1722976a87a2SAlan Cox 	vm_map_unlock_read(map);
17230ff27d31SJohn Polstra }
17240ff27d31SJohn Polstra 
17250ff27d31SJohn Polstra /*
17260ff27d31SJohn Polstra  * Write the core file header to the file, including padding up to
17270ff27d31SJohn Polstra  * the page boundary.
17280ff27d31SJohn Polstra  */
17298c64af4fSJohn Polstra static int
1730aa14e9b7SMark Johnston __elfN(corehdr)(struct coredump_params *p, int numsegs, void *hdr,
1731aa14e9b7SMark Johnston     size_t hdrsize, struct note_info_list *notelst, size_t notesz)
17328c64af4fSJohn Polstra {
1733bd390213SMikolaj Golub 	struct note_info *ninfo;
1734bd390213SMikolaj Golub 	struct sbuf *sb;
1735bd390213SMikolaj Golub 	int error;
17368c64af4fSJohn Polstra 
17378c64af4fSJohn Polstra 	/* Fill in the header. */
17380ff27d31SJohn Polstra 	bzero(hdr, hdrsize);
1739aa14e9b7SMark Johnston 	__elfN(puthdr)(p->td, hdr, hdrsize, numsegs, notesz);
17408c64af4fSJohn Polstra 
1741bd390213SMikolaj Golub 	sb = sbuf_new(NULL, NULL, CORE_BUF_SIZE, SBUF_FIXEDLEN);
1742aa14e9b7SMark Johnston 	sbuf_set_drain(sb, sbuf_drain_core_output, p);
1743bd390213SMikolaj Golub 	sbuf_start_section(sb, NULL);
1744bd390213SMikolaj Golub 	sbuf_bcat(sb, hdr, hdrsize);
1745bd390213SMikolaj Golub 	TAILQ_FOREACH(ninfo, notelst, link)
1746bd390213SMikolaj Golub 	    __elfN(putnote)(ninfo, sb);
1747bd390213SMikolaj Golub 	/* Align up to a page boundary for the program segments. */
1748bd390213SMikolaj Golub 	sbuf_end_section(sb, -1, PAGE_SIZE, 0);
1749bd390213SMikolaj Golub 	error = sbuf_finish(sb);
1750bd390213SMikolaj Golub 	sbuf_delete(sb);
1751bd390213SMikolaj Golub 
1752bd390213SMikolaj Golub 	return (error);
1753e7228204SAlfred Perlstein }
1754bd390213SMikolaj Golub 
1755bd390213SMikolaj Golub static void
1756bd390213SMikolaj Golub __elfN(prepare_notes)(struct thread *td, struct note_info_list *list,
1757bd390213SMikolaj Golub     size_t *sizep)
1758bd390213SMikolaj Golub {
1759bd390213SMikolaj Golub 	struct proc *p;
1760bd390213SMikolaj Golub 	struct thread *thr;
1761bd390213SMikolaj Golub 	size_t size;
1762bd390213SMikolaj Golub 
1763bd390213SMikolaj Golub 	p = td->td_proc;
1764bd390213SMikolaj Golub 	size = 0;
1765bd390213SMikolaj Golub 
1766bd390213SMikolaj Golub 	size += register_note(list, NT_PRPSINFO, __elfN(note_prpsinfo), p);
1767bd390213SMikolaj Golub 
1768bd390213SMikolaj Golub 	/*
1769bd390213SMikolaj Golub 	 * To have the debugger select the right thread (LWP) as the initial
1770bd390213SMikolaj Golub 	 * thread, we dump the state of the thread passed to us in td first.
1771bd390213SMikolaj Golub 	 * This is the thread that causes the core dump and thus likely to
1772bd390213SMikolaj Golub 	 * be the right thread one wants to have selected in the debugger.
1773bd390213SMikolaj Golub 	 */
1774bd390213SMikolaj Golub 	thr = td;
1775bd390213SMikolaj Golub 	while (thr != NULL) {
1776bd390213SMikolaj Golub 		size += register_note(list, NT_PRSTATUS,
1777bd390213SMikolaj Golub 		    __elfN(note_prstatus), thr);
1778bd390213SMikolaj Golub 		size += register_note(list, NT_FPREGSET,
1779bd390213SMikolaj Golub 		    __elfN(note_fpregset), thr);
1780bd390213SMikolaj Golub 		size += register_note(list, NT_THRMISC,
1781bd390213SMikolaj Golub 		    __elfN(note_thrmisc), thr);
178286be94fcSTycho Nightingale 		size += register_note(list, NT_PTLWPINFO,
178386be94fcSTycho Nightingale 		    __elfN(note_ptlwpinfo), thr);
1784bd390213SMikolaj Golub 		size += register_note(list, -1,
1785bd390213SMikolaj Golub 		    __elfN(note_threadmd), thr);
1786bd390213SMikolaj Golub 
1787bd390213SMikolaj Golub 		thr = (thr == td) ? TAILQ_FIRST(&p->p_threads) :
1788bd390213SMikolaj Golub 		    TAILQ_NEXT(thr, td_plist);
1789bd390213SMikolaj Golub 		if (thr == td)
1790bd390213SMikolaj Golub 			thr = TAILQ_NEXT(thr, td_plist);
1791dada0278SJohn Polstra 	}
1792dada0278SJohn Polstra 
1793f1fca82eSMikolaj Golub 	size += register_note(list, NT_PROCSTAT_PROC,
1794f1fca82eSMikolaj Golub 	    __elfN(note_procstat_proc), p);
1795f1fca82eSMikolaj Golub 	size += register_note(list, NT_PROCSTAT_FILES,
1796f1fca82eSMikolaj Golub 	    note_procstat_files, p);
1797f1fca82eSMikolaj Golub 	size += register_note(list, NT_PROCSTAT_VMMAP,
1798f1fca82eSMikolaj Golub 	    note_procstat_vmmap, p);
1799f1fca82eSMikolaj Golub 	size += register_note(list, NT_PROCSTAT_GROUPS,
1800f1fca82eSMikolaj Golub 	    note_procstat_groups, p);
1801f1fca82eSMikolaj Golub 	size += register_note(list, NT_PROCSTAT_UMASK,
1802f1fca82eSMikolaj Golub 	    note_procstat_umask, p);
1803f1fca82eSMikolaj Golub 	size += register_note(list, NT_PROCSTAT_RLIMIT,
1804f1fca82eSMikolaj Golub 	    note_procstat_rlimit, p);
1805f1fca82eSMikolaj Golub 	size += register_note(list, NT_PROCSTAT_OSREL,
1806f1fca82eSMikolaj Golub 	    note_procstat_osrel, p);
1807f1fca82eSMikolaj Golub 	size += register_note(list, NT_PROCSTAT_PSSTRINGS,
1808f1fca82eSMikolaj Golub 	    __elfN(note_procstat_psstrings), p);
1809f1fca82eSMikolaj Golub 	size += register_note(list, NT_PROCSTAT_AUXV,
1810f1fca82eSMikolaj Golub 	    __elfN(note_procstat_auxv), p);
1811f1fca82eSMikolaj Golub 
1812bd390213SMikolaj Golub 	*sizep = size;
1813bd390213SMikolaj Golub }
1814bd390213SMikolaj Golub 
1815bd390213SMikolaj Golub static void
1816bd390213SMikolaj Golub __elfN(puthdr)(struct thread *td, void *hdr, size_t hdrsize, int numsegs,
1817bd390213SMikolaj Golub     size_t notesz)
1818bd390213SMikolaj Golub {
1819bd390213SMikolaj Golub 	Elf_Ehdr *ehdr;
1820bd390213SMikolaj Golub 	Elf_Phdr *phdr;
1821c17b0bd2SConrad Meyer 	Elf_Shdr *shdr;
1822bd390213SMikolaj Golub 	struct phdr_closure phc;
1823bd390213SMikolaj Golub 
1824bd390213SMikolaj Golub 	ehdr = (Elf_Ehdr *)hdr;
1825bd390213SMikolaj Golub 
1826bd390213SMikolaj Golub 	ehdr->e_ident[EI_MAG0] = ELFMAG0;
1827bd390213SMikolaj Golub 	ehdr->e_ident[EI_MAG1] = ELFMAG1;
1828bd390213SMikolaj Golub 	ehdr->e_ident[EI_MAG2] = ELFMAG2;
1829bd390213SMikolaj Golub 	ehdr->e_ident[EI_MAG3] = ELFMAG3;
1830bd390213SMikolaj Golub 	ehdr->e_ident[EI_CLASS] = ELF_CLASS;
1831bd390213SMikolaj Golub 	ehdr->e_ident[EI_DATA] = ELF_DATA;
1832bd390213SMikolaj Golub 	ehdr->e_ident[EI_VERSION] = EV_CURRENT;
1833bd390213SMikolaj Golub 	ehdr->e_ident[EI_OSABI] = ELFOSABI_FREEBSD;
1834bd390213SMikolaj Golub 	ehdr->e_ident[EI_ABIVERSION] = 0;
1835bd390213SMikolaj Golub 	ehdr->e_ident[EI_PAD] = 0;
1836bd390213SMikolaj Golub 	ehdr->e_type = ET_CORE;
1837885f13dcSJohn Baldwin 	ehdr->e_machine = td->td_proc->p_elf_machine;
1838bd390213SMikolaj Golub 	ehdr->e_version = EV_CURRENT;
1839bd390213SMikolaj Golub 	ehdr->e_entry = 0;
1840bd390213SMikolaj Golub 	ehdr->e_phoff = sizeof(Elf_Ehdr);
1841885f13dcSJohn Baldwin 	ehdr->e_flags = td->td_proc->p_elf_flags;
1842bd390213SMikolaj Golub 	ehdr->e_ehsize = sizeof(Elf_Ehdr);
1843bd390213SMikolaj Golub 	ehdr->e_phentsize = sizeof(Elf_Phdr);
1844bd390213SMikolaj Golub 	ehdr->e_shentsize = sizeof(Elf_Shdr);
1845bd390213SMikolaj Golub 	ehdr->e_shstrndx = SHN_UNDEF;
1846c17b0bd2SConrad Meyer 	if (numsegs + 1 < PN_XNUM) {
1847c17b0bd2SConrad Meyer 		ehdr->e_phnum = numsegs + 1;
1848c17b0bd2SConrad Meyer 		ehdr->e_shnum = 0;
1849c17b0bd2SConrad Meyer 	} else {
1850c17b0bd2SConrad Meyer 		ehdr->e_phnum = PN_XNUM;
1851c17b0bd2SConrad Meyer 		ehdr->e_shnum = 1;
1852c17b0bd2SConrad Meyer 
1853c17b0bd2SConrad Meyer 		ehdr->e_shoff = ehdr->e_phoff +
1854c17b0bd2SConrad Meyer 		    (numsegs + 1) * ehdr->e_phentsize;
1855c17b0bd2SConrad Meyer 		KASSERT(ehdr->e_shoff == hdrsize - sizeof(Elf_Shdr),
1856c17b0bd2SConrad Meyer 		    ("e_shoff: %zu, hdrsize - shdr: %zu",
185707f825e8SConrad Meyer 		     (size_t)ehdr->e_shoff, hdrsize - sizeof(Elf_Shdr)));
1858c17b0bd2SConrad Meyer 
1859c17b0bd2SConrad Meyer 		shdr = (Elf_Shdr *)((char *)hdr + ehdr->e_shoff);
1860c17b0bd2SConrad Meyer 		memset(shdr, 0, sizeof(*shdr));
1861c17b0bd2SConrad Meyer 		/*
1862c17b0bd2SConrad Meyer 		 * A special first section is used to hold large segment and
1863c17b0bd2SConrad Meyer 		 * section counts.  This was proposed by Sun Microsystems in
1864c17b0bd2SConrad Meyer 		 * Solaris and has been adopted by Linux; the standard ELF
1865c17b0bd2SConrad Meyer 		 * tools are already familiar with the technique.
1866c17b0bd2SConrad Meyer 		 *
1867c17b0bd2SConrad Meyer 		 * See table 7-7 of the Solaris "Linker and Libraries Guide"
1868c17b0bd2SConrad Meyer 		 * (or 12-7 depending on the version of the document) for more
1869c17b0bd2SConrad Meyer 		 * details.
1870c17b0bd2SConrad Meyer 		 */
1871c17b0bd2SConrad Meyer 		shdr->sh_type = SHT_NULL;
1872c17b0bd2SConrad Meyer 		shdr->sh_size = ehdr->e_shnum;
1873c17b0bd2SConrad Meyer 		shdr->sh_link = ehdr->e_shstrndx;
1874c17b0bd2SConrad Meyer 		shdr->sh_info = numsegs + 1;
1875c17b0bd2SConrad Meyer 	}
1876bd390213SMikolaj Golub 
1877bd390213SMikolaj Golub 	/*
1878bd390213SMikolaj Golub 	 * Fill in the program header entries.
1879bd390213SMikolaj Golub 	 */
1880c17b0bd2SConrad Meyer 	phdr = (Elf_Phdr *)((char *)hdr + ehdr->e_phoff);
1881bd390213SMikolaj Golub 
1882bd390213SMikolaj Golub 	/* The note segement. */
1883bd390213SMikolaj Golub 	phdr->p_type = PT_NOTE;
1884bd390213SMikolaj Golub 	phdr->p_offset = hdrsize;
1885bd390213SMikolaj Golub 	phdr->p_vaddr = 0;
1886bd390213SMikolaj Golub 	phdr->p_paddr = 0;
1887bd390213SMikolaj Golub 	phdr->p_filesz = notesz;
1888bd390213SMikolaj Golub 	phdr->p_memsz = 0;
1889bd390213SMikolaj Golub 	phdr->p_flags = PF_R;
18901b8388cdSMikolaj Golub 	phdr->p_align = ELF_NOTE_ROUNDSIZE;
1891bd390213SMikolaj Golub 	phdr++;
1892bd390213SMikolaj Golub 
1893bd390213SMikolaj Golub 	/* All the writable segments from the program. */
1894bd390213SMikolaj Golub 	phc.phdr = phdr;
1895bd390213SMikolaj Golub 	phc.offset = round_page(hdrsize + notesz);
18961005d8afSConrad Meyer 	each_dumpable_segment(td, cb_put_phdr, &phc);
1897bd390213SMikolaj Golub }
1898bd390213SMikolaj Golub 
1899bd390213SMikolaj Golub static size_t
1900bd390213SMikolaj Golub register_note(struct note_info_list *list, int type, outfunc_t out, void *arg)
1901bd390213SMikolaj Golub {
1902bd390213SMikolaj Golub 	struct note_info *ninfo;
1903bd390213SMikolaj Golub 	size_t size, notesize;
1904bd390213SMikolaj Golub 
1905bd390213SMikolaj Golub 	size = 0;
1906bd390213SMikolaj Golub 	out(arg, NULL, &size);
1907bd390213SMikolaj Golub 	ninfo = malloc(sizeof(*ninfo), M_TEMP, M_ZERO | M_WAITOK);
1908bd390213SMikolaj Golub 	ninfo->type = type;
1909bd390213SMikolaj Golub 	ninfo->outfunc = out;
1910bd390213SMikolaj Golub 	ninfo->outarg = arg;
1911bd390213SMikolaj Golub 	ninfo->outsize = size;
1912bd390213SMikolaj Golub 	TAILQ_INSERT_TAIL(list, ninfo, link);
1913bd390213SMikolaj Golub 
1914bd390213SMikolaj Golub 	if (type == -1)
1915bd390213SMikolaj Golub 		return (size);
1916bd390213SMikolaj Golub 
1917bd390213SMikolaj Golub 	notesize = sizeof(Elf_Note) +		/* note header */
1918180e57e5SJohn Baldwin 	    roundup2(sizeof(FREEBSD_ABI_VENDOR), ELF_NOTE_ROUNDSIZE) +
1919180e57e5SJohn Baldwin 						/* note name */
1920180e57e5SJohn Baldwin 	    roundup2(size, ELF_NOTE_ROUNDSIZE);	/* note description */
1921180e57e5SJohn Baldwin 
1922180e57e5SJohn Baldwin 	return (notesize);
1923180e57e5SJohn Baldwin }
1924180e57e5SJohn Baldwin 
1925180e57e5SJohn Baldwin static size_t
1926180e57e5SJohn Baldwin append_note_data(const void *src, void *dst, size_t len)
1927180e57e5SJohn Baldwin {
1928180e57e5SJohn Baldwin 	size_t padded_len;
1929180e57e5SJohn Baldwin 
1930180e57e5SJohn Baldwin 	padded_len = roundup2(len, ELF_NOTE_ROUNDSIZE);
1931180e57e5SJohn Baldwin 	if (dst != NULL) {
1932180e57e5SJohn Baldwin 		bcopy(src, dst, len);
1933180e57e5SJohn Baldwin 		bzero((char *)dst + len, padded_len - len);
1934180e57e5SJohn Baldwin 	}
1935180e57e5SJohn Baldwin 	return (padded_len);
1936180e57e5SJohn Baldwin }
1937180e57e5SJohn Baldwin 
1938180e57e5SJohn Baldwin size_t
1939180e57e5SJohn Baldwin __elfN(populate_note)(int type, void *src, void *dst, size_t size, void **descp)
1940180e57e5SJohn Baldwin {
1941180e57e5SJohn Baldwin 	Elf_Note *note;
1942180e57e5SJohn Baldwin 	char *buf;
1943180e57e5SJohn Baldwin 	size_t notesize;
1944180e57e5SJohn Baldwin 
1945180e57e5SJohn Baldwin 	buf = dst;
1946180e57e5SJohn Baldwin 	if (buf != NULL) {
1947180e57e5SJohn Baldwin 		note = (Elf_Note *)buf;
1948180e57e5SJohn Baldwin 		note->n_namesz = sizeof(FREEBSD_ABI_VENDOR);
1949180e57e5SJohn Baldwin 		note->n_descsz = size;
1950180e57e5SJohn Baldwin 		note->n_type = type;
1951180e57e5SJohn Baldwin 		buf += sizeof(*note);
1952180e57e5SJohn Baldwin 		buf += append_note_data(FREEBSD_ABI_VENDOR, buf,
1953180e57e5SJohn Baldwin 		    sizeof(FREEBSD_ABI_VENDOR));
1954180e57e5SJohn Baldwin 		append_note_data(src, buf, size);
1955180e57e5SJohn Baldwin 		if (descp != NULL)
1956180e57e5SJohn Baldwin 			*descp = buf;
1957180e57e5SJohn Baldwin 	}
1958180e57e5SJohn Baldwin 
1959180e57e5SJohn Baldwin 	notesize = sizeof(Elf_Note) +		/* note header */
1960180e57e5SJohn Baldwin 	    roundup2(sizeof(FREEBSD_ABI_VENDOR), ELF_NOTE_ROUNDSIZE) +
1961180e57e5SJohn Baldwin 						/* note name */
19621b8388cdSMikolaj Golub 	    roundup2(size, ELF_NOTE_ROUNDSIZE);	/* note description */
1963bd390213SMikolaj Golub 
1964bd390213SMikolaj Golub 	return (notesize);
1965bd390213SMikolaj Golub }
1966bd390213SMikolaj Golub 
1967bd390213SMikolaj Golub static void
1968bd390213SMikolaj Golub __elfN(putnote)(struct note_info *ninfo, struct sbuf *sb)
1969bd390213SMikolaj Golub {
1970bd390213SMikolaj Golub 	Elf_Note note;
197114bdbaf2SConrad Meyer 	ssize_t old_len, sect_len;
197214bdbaf2SConrad Meyer 	size_t new_len, descsz, i;
1973bd390213SMikolaj Golub 
1974bd390213SMikolaj Golub 	if (ninfo->type == -1) {
1975bd390213SMikolaj Golub 		ninfo->outfunc(ninfo->outarg, sb, &ninfo->outsize);
1976bd390213SMikolaj Golub 		return;
1977bd390213SMikolaj Golub 	}
1978bd390213SMikolaj Golub 
1979180e57e5SJohn Baldwin 	note.n_namesz = sizeof(FREEBSD_ABI_VENDOR);
1980bd390213SMikolaj Golub 	note.n_descsz = ninfo->outsize;
1981bd390213SMikolaj Golub 	note.n_type = ninfo->type;
1982bd390213SMikolaj Golub 
1983bd390213SMikolaj Golub 	sbuf_bcat(sb, &note, sizeof(note));
1984bd390213SMikolaj Golub 	sbuf_start_section(sb, &old_len);
1985180e57e5SJohn Baldwin 	sbuf_bcat(sb, FREEBSD_ABI_VENDOR, sizeof(FREEBSD_ABI_VENDOR));
19861b8388cdSMikolaj Golub 	sbuf_end_section(sb, old_len, ELF_NOTE_ROUNDSIZE, 0);
1987bd390213SMikolaj Golub 	if (note.n_descsz == 0)
1988bd390213SMikolaj Golub 		return;
1989bd390213SMikolaj Golub 	sbuf_start_section(sb, &old_len);
1990bd390213SMikolaj Golub 	ninfo->outfunc(ninfo->outarg, sb, &ninfo->outsize);
199114bdbaf2SConrad Meyer 	sect_len = sbuf_end_section(sb, old_len, ELF_NOTE_ROUNDSIZE, 0);
199214bdbaf2SConrad Meyer 	if (sect_len < 0)
199314bdbaf2SConrad Meyer 		return;
199414bdbaf2SConrad Meyer 
199514bdbaf2SConrad Meyer 	new_len = (size_t)sect_len;
199614bdbaf2SConrad Meyer 	descsz = roundup(note.n_descsz, ELF_NOTE_ROUNDSIZE);
199714bdbaf2SConrad Meyer 	if (new_len < descsz) {
199814bdbaf2SConrad Meyer 		/*
199914bdbaf2SConrad Meyer 		 * It is expected that individual note emitters will correctly
200014bdbaf2SConrad Meyer 		 * predict their expected output size and fill up to that size
200114bdbaf2SConrad Meyer 		 * themselves, padding in a format-specific way if needed.
200214bdbaf2SConrad Meyer 		 * However, in case they don't, just do it here with zeros.
200314bdbaf2SConrad Meyer 		 */
200414bdbaf2SConrad Meyer 		for (i = 0; i < descsz - new_len; i++)
200514bdbaf2SConrad Meyer 			sbuf_putc(sb, 0);
200614bdbaf2SConrad Meyer 	} else if (new_len > descsz) {
200714bdbaf2SConrad Meyer 		/*
200814bdbaf2SConrad Meyer 		 * We can't always truncate sb -- we may have drained some
200914bdbaf2SConrad Meyer 		 * of it already.
201014bdbaf2SConrad Meyer 		 */
201114bdbaf2SConrad Meyer 		KASSERT(new_len == descsz, ("%s: Note type %u changed as we "
201214bdbaf2SConrad Meyer 		    "read it (%zu > %zu).  Since it is longer than "
201314bdbaf2SConrad Meyer 		    "expected, this coredump's notes are corrupt.  THIS "
201414bdbaf2SConrad Meyer 		    "IS A BUG in the note_procstat routine for type %u.\n",
201514bdbaf2SConrad Meyer 		    __func__, (unsigned)note.n_type, new_len, descsz,
201614bdbaf2SConrad Meyer 		    (unsigned)note.n_type));
201714bdbaf2SConrad Meyer 	}
2018bd390213SMikolaj Golub }
2019bd390213SMikolaj Golub 
2020bd390213SMikolaj Golub /*
2021bd390213SMikolaj Golub  * Miscellaneous note out functions.
2022bd390213SMikolaj Golub  */
2023bd390213SMikolaj Golub 
2024841c0c7eSNathan Whitehorn #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
2025841c0c7eSNathan Whitehorn #include <compat/freebsd32/freebsd32.h>
202651645e83SJohn Baldwin #include <compat/freebsd32/freebsd32_signal.h>
2027841c0c7eSNathan Whitehorn 
202862919d78SPeter Wemm typedef struct prstatus32 elf_prstatus_t;
202962919d78SPeter Wemm typedef struct prpsinfo32 elf_prpsinfo_t;
203062919d78SPeter Wemm typedef struct fpreg32 elf_prfpregset_t;
203162919d78SPeter Wemm typedef struct fpreg32 elf_fpregset_t;
203262919d78SPeter Wemm typedef struct reg32 elf_gregset_t;
20337f08176eSAttilio Rao typedef struct thrmisc32 elf_thrmisc_t;
2034f1fca82eSMikolaj Golub #define ELF_KERN_PROC_MASK	KERN_PROC_MASK32
2035f1fca82eSMikolaj Golub typedef struct kinfo_proc32 elf_kinfo_proc_t;
2036f1fca82eSMikolaj Golub typedef uint32_t elf_ps_strings_t;
203762919d78SPeter Wemm #else
203862919d78SPeter Wemm typedef prstatus_t elf_prstatus_t;
203962919d78SPeter Wemm typedef prpsinfo_t elf_prpsinfo_t;
204062919d78SPeter Wemm typedef prfpregset_t elf_prfpregset_t;
204162919d78SPeter Wemm typedef prfpregset_t elf_fpregset_t;
204262919d78SPeter Wemm typedef gregset_t elf_gregset_t;
20437f08176eSAttilio Rao typedef thrmisc_t elf_thrmisc_t;
2044f1fca82eSMikolaj Golub #define ELF_KERN_PROC_MASK	0
2045f1fca82eSMikolaj Golub typedef struct kinfo_proc elf_kinfo_proc_t;
2046f1fca82eSMikolaj Golub typedef vm_offset_t elf_ps_strings_t;
204762919d78SPeter Wemm #endif
204862919d78SPeter Wemm 
20498c64af4fSJohn Polstra static void
2050bd390213SMikolaj Golub __elfN(note_prpsinfo)(void *arg, struct sbuf *sb, size_t *sizep)
20518c64af4fSJohn Polstra {
2052c77547d2SJohn Baldwin 	struct sbuf sbarg;
2053c77547d2SJohn Baldwin 	size_t len;
2054c77547d2SJohn Baldwin 	char *cp, *end;
2055247aba24SMarcel Moolenaar 	struct proc *p;
2056bd390213SMikolaj Golub 	elf_prpsinfo_t *psinfo;
2057c77547d2SJohn Baldwin 	int error;
20588c64af4fSJohn Polstra 
2059bd390213SMikolaj Golub 	p = (struct proc *)arg;
2060bd390213SMikolaj Golub 	if (sb != NULL) {
2061bd390213SMikolaj Golub 		KASSERT(*sizep == sizeof(*psinfo), ("invalid size"));
2062bd390213SMikolaj Golub 		psinfo = malloc(sizeof(*psinfo), M_TEMP, M_ZERO | M_WAITOK);
20638c9b7b2cSMarcel Moolenaar 		psinfo->pr_version = PRPSINFO_VERSION;
206462919d78SPeter Wemm 		psinfo->pr_psinfosz = sizeof(elf_prpsinfo_t);
2065ccd3953eSJohn Baldwin 		strlcpy(psinfo->pr_fname, p->p_comm, sizeof(psinfo->pr_fname));
2066c77547d2SJohn Baldwin 		PROC_LOCK(p);
2067c77547d2SJohn Baldwin 		if (p->p_args != NULL) {
2068c77547d2SJohn Baldwin 			len = sizeof(psinfo->pr_psargs) - 1;
2069c77547d2SJohn Baldwin 			if (len > p->p_args->ar_length)
2070c77547d2SJohn Baldwin 				len = p->p_args->ar_length;
2071c77547d2SJohn Baldwin 			memcpy(psinfo->pr_psargs, p->p_args->ar_args, len);
2072c77547d2SJohn Baldwin 			PROC_UNLOCK(p);
2073c77547d2SJohn Baldwin 			error = 0;
2074c77547d2SJohn Baldwin 		} else {
2075c77547d2SJohn Baldwin 			_PHOLD(p);
2076c77547d2SJohn Baldwin 			PROC_UNLOCK(p);
2077c77547d2SJohn Baldwin 			sbuf_new(&sbarg, psinfo->pr_psargs,
2078c77547d2SJohn Baldwin 			    sizeof(psinfo->pr_psargs), SBUF_FIXEDLEN);
2079c77547d2SJohn Baldwin 			error = proc_getargv(curthread, p, &sbarg);
2080c77547d2SJohn Baldwin 			PRELE(p);
2081c77547d2SJohn Baldwin 			if (sbuf_finish(&sbarg) == 0)
2082c77547d2SJohn Baldwin 				len = sbuf_len(&sbarg) - 1;
2083c77547d2SJohn Baldwin 			else
2084c77547d2SJohn Baldwin 				len = sizeof(psinfo->pr_psargs) - 1;
2085c77547d2SJohn Baldwin 			sbuf_delete(&sbarg);
2086c77547d2SJohn Baldwin 		}
2087c77547d2SJohn Baldwin 		if (error || len == 0)
2088ccd3953eSJohn Baldwin 			strlcpy(psinfo->pr_psargs, p->p_comm,
20898c9b7b2cSMarcel Moolenaar 			    sizeof(psinfo->pr_psargs));
2090c77547d2SJohn Baldwin 		else {
2091c77547d2SJohn Baldwin 			KASSERT(len < sizeof(psinfo->pr_psargs),
2092c77547d2SJohn Baldwin 			    ("len is too long: %zu vs %zu", len,
2093c77547d2SJohn Baldwin 			    sizeof(psinfo->pr_psargs)));
2094c77547d2SJohn Baldwin 			cp = psinfo->pr_psargs;
2095c77547d2SJohn Baldwin 			end = cp + len - 1;
2096c77547d2SJohn Baldwin 			for (;;) {
2097c77547d2SJohn Baldwin 				cp = memchr(cp, '\0', end - cp);
2098c77547d2SJohn Baldwin 				if (cp == NULL)
2099c77547d2SJohn Baldwin 					break;
2100c77547d2SJohn Baldwin 				*cp = ' ';
2101c77547d2SJohn Baldwin 			}
2102c77547d2SJohn Baldwin 		}
2103ccb83afdSJohn Baldwin 		psinfo->pr_pid = p->p_pid;
2104bd390213SMikolaj Golub 		sbuf_bcat(sb, psinfo, sizeof(*psinfo));
2105bd390213SMikolaj Golub 		free(psinfo, M_TEMP);
2106bd390213SMikolaj Golub 	}
2107bd390213SMikolaj Golub 	*sizep = sizeof(*psinfo);
2108bd390213SMikolaj Golub }
2109bd390213SMikolaj Golub 
2110bd390213SMikolaj Golub static void
2111bd390213SMikolaj Golub __elfN(note_prstatus)(void *arg, struct sbuf *sb, size_t *sizep)
2112bd390213SMikolaj Golub {
2113bd390213SMikolaj Golub 	struct thread *td;
2114bd390213SMikolaj Golub 	elf_prstatus_t *status;
2115bd390213SMikolaj Golub 
2116bd390213SMikolaj Golub 	td = (struct thread *)arg;
2117bd390213SMikolaj Golub 	if (sb != NULL) {
2118bd390213SMikolaj Golub 		KASSERT(*sizep == sizeof(*status), ("invalid size"));
2119bd390213SMikolaj Golub 		status = malloc(sizeof(*status), M_TEMP, M_ZERO | M_WAITOK);
21208c9b7b2cSMarcel Moolenaar 		status->pr_version = PRSTATUS_VERSION;
212162919d78SPeter Wemm 		status->pr_statussz = sizeof(elf_prstatus_t);
212262919d78SPeter Wemm 		status->pr_gregsetsz = sizeof(elf_gregset_t);
212362919d78SPeter Wemm 		status->pr_fpregsetsz = sizeof(elf_fpregset_t);
21248c9b7b2cSMarcel Moolenaar 		status->pr_osreldate = osreldate;
2125bd390213SMikolaj Golub 		status->pr_cursig = td->td_proc->p_sig;
2126bd390213SMikolaj Golub 		status->pr_pid = td->td_tid;
2127841c0c7eSNathan Whitehorn #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
2128bd390213SMikolaj Golub 		fill_regs32(td, &status->pr_reg);
212962919d78SPeter Wemm #else
2130bd390213SMikolaj Golub 		fill_regs(td, &status->pr_reg);
213162919d78SPeter Wemm #endif
2132bd390213SMikolaj Golub 		sbuf_bcat(sb, status, sizeof(*status));
2133bd390213SMikolaj Golub 		free(status, M_TEMP);
21348c9b7b2cSMarcel Moolenaar 	}
2135bd390213SMikolaj Golub 	*sizep = sizeof(*status);
2136bd390213SMikolaj Golub }
2137bd390213SMikolaj Golub 
2138bd390213SMikolaj Golub static void
2139bd390213SMikolaj Golub __elfN(note_fpregset)(void *arg, struct sbuf *sb, size_t *sizep)
2140bd390213SMikolaj Golub {
2141bd390213SMikolaj Golub 	struct thread *td;
2142bd390213SMikolaj Golub 	elf_prfpregset_t *fpregset;
2143bd390213SMikolaj Golub 
2144bd390213SMikolaj Golub 	td = (struct thread *)arg;
2145bd390213SMikolaj Golub 	if (sb != NULL) {
2146bd390213SMikolaj Golub 		KASSERT(*sizep == sizeof(*fpregset), ("invalid size"));
2147bd390213SMikolaj Golub 		fpregset = malloc(sizeof(*fpregset), M_TEMP, M_ZERO | M_WAITOK);
2148bd390213SMikolaj Golub #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
2149bd390213SMikolaj Golub 		fill_fpregs32(td, fpregset);
2150bd390213SMikolaj Golub #else
2151bd390213SMikolaj Golub 		fill_fpregs(td, fpregset);
2152bd390213SMikolaj Golub #endif
2153bd390213SMikolaj Golub 		sbuf_bcat(sb, fpregset, sizeof(*fpregset));
2154bd390213SMikolaj Golub 		free(fpregset, M_TEMP);
2155bd390213SMikolaj Golub 	}
2156bd390213SMikolaj Golub 	*sizep = sizeof(*fpregset);
2157bd390213SMikolaj Golub }
2158bd390213SMikolaj Golub 
2159bd390213SMikolaj Golub static void
2160bd390213SMikolaj Golub __elfN(note_thrmisc)(void *arg, struct sbuf *sb, size_t *sizep)
2161bd390213SMikolaj Golub {
2162bd390213SMikolaj Golub 	struct thread *td;
2163bd390213SMikolaj Golub 	elf_thrmisc_t thrmisc;
2164bd390213SMikolaj Golub 
2165bd390213SMikolaj Golub 	td = (struct thread *)arg;
2166bd390213SMikolaj Golub 	if (sb != NULL) {
2167bd390213SMikolaj Golub 		KASSERT(*sizep == sizeof(thrmisc), ("invalid size"));
2168bd390213SMikolaj Golub 		bzero(&thrmisc._pad, sizeof(thrmisc._pad));
2169bd390213SMikolaj Golub 		strcpy(thrmisc.pr_tname, td->td_name);
2170bd390213SMikolaj Golub 		sbuf_bcat(sb, &thrmisc, sizeof(thrmisc));
2171bd390213SMikolaj Golub 	}
2172bd390213SMikolaj Golub 	*sizep = sizeof(thrmisc);
2173bd390213SMikolaj Golub }
2174bd390213SMikolaj Golub 
217586be94fcSTycho Nightingale static void
217686be94fcSTycho Nightingale __elfN(note_ptlwpinfo)(void *arg, struct sbuf *sb, size_t *sizep)
217786be94fcSTycho Nightingale {
217886be94fcSTycho Nightingale 	struct thread *td;
217986be94fcSTycho Nightingale 	size_t size;
218086be94fcSTycho Nightingale 	int structsize;
218151645e83SJohn Baldwin #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
218251645e83SJohn Baldwin 	struct ptrace_lwpinfo32 pl;
218351645e83SJohn Baldwin #else
218486be94fcSTycho Nightingale 	struct ptrace_lwpinfo pl;
218551645e83SJohn Baldwin #endif
218686be94fcSTycho Nightingale 
218786be94fcSTycho Nightingale 	td = (struct thread *)arg;
218851645e83SJohn Baldwin 	size = sizeof(structsize) + sizeof(pl);
218986be94fcSTycho Nightingale 	if (sb != NULL) {
219086be94fcSTycho Nightingale 		KASSERT(*sizep == size, ("invalid size"));
219151645e83SJohn Baldwin 		structsize = sizeof(pl);
219286be94fcSTycho Nightingale 		sbuf_bcat(sb, &structsize, sizeof(structsize));
219386be94fcSTycho Nightingale 		bzero(&pl, sizeof(pl));
219486be94fcSTycho Nightingale 		pl.pl_lwpid = td->td_tid;
219586be94fcSTycho Nightingale 		pl.pl_event = PL_EVENT_NONE;
219686be94fcSTycho Nightingale 		pl.pl_sigmask = td->td_sigmask;
219786be94fcSTycho Nightingale 		pl.pl_siglist = td->td_siglist;
219886be94fcSTycho Nightingale 		if (td->td_si.si_signo != 0) {
219986be94fcSTycho Nightingale 			pl.pl_event = PL_EVENT_SIGNAL;
220086be94fcSTycho Nightingale 			pl.pl_flags |= PL_FLAG_SI;
220151645e83SJohn Baldwin #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
220251645e83SJohn Baldwin 			siginfo_to_siginfo32(&td->td_si, &pl.pl_siginfo);
220351645e83SJohn Baldwin #else
220486be94fcSTycho Nightingale 			pl.pl_siginfo = td->td_si;
220551645e83SJohn Baldwin #endif
220686be94fcSTycho Nightingale 		}
220786be94fcSTycho Nightingale 		strcpy(pl.pl_tdname, td->td_name);
220886be94fcSTycho Nightingale 		/* XXX TODO: supply more information in struct ptrace_lwpinfo*/
220951645e83SJohn Baldwin 		sbuf_bcat(sb, &pl, sizeof(pl));
221086be94fcSTycho Nightingale 	}
221186be94fcSTycho Nightingale 	*sizep = size;
221286be94fcSTycho Nightingale }
221386be94fcSTycho Nightingale 
22144da47b2fSMarcel Moolenaar /*
22154da47b2fSMarcel Moolenaar  * Allow for MD specific notes, as well as any MD
22164da47b2fSMarcel Moolenaar  * specific preparations for writing MI notes.
22174da47b2fSMarcel Moolenaar  */
22188c64af4fSJohn Polstra static void
2219bd390213SMikolaj Golub __elfN(note_threadmd)(void *arg, struct sbuf *sb, size_t *sizep)
22208c64af4fSJohn Polstra {
2221bd390213SMikolaj Golub 	struct thread *td;
2222bd390213SMikolaj Golub 	void *buf;
2223bd390213SMikolaj Golub 	size_t size;
22248c64af4fSJohn Polstra 
2225bd390213SMikolaj Golub 	td = (struct thread *)arg;
2226bd390213SMikolaj Golub 	size = *sizep;
2227bd390213SMikolaj Golub 	if (size != 0 && sb != NULL)
2228bd390213SMikolaj Golub 		buf = malloc(size, M_TEMP, M_ZERO | M_WAITOK);
222983a396ceSChristian Brueffer 	else
223083a396ceSChristian Brueffer 		buf = NULL;
2231bd390213SMikolaj Golub 	size = 0;
2232bd390213SMikolaj Golub 	__elfN(dump_thread)(td, buf, &size);
223364779280SKonstantin Belousov 	KASSERT(sb == NULL || *sizep == size, ("invalid size"));
223483a396ceSChristian Brueffer 	if (size != 0 && sb != NULL)
2235bd390213SMikolaj Golub 		sbuf_bcat(sb, buf, size);
2236a1761d73SChristian Brueffer 	free(buf, M_TEMP);
2237bd390213SMikolaj Golub 	*sizep = size;
22388c64af4fSJohn Polstra }
22398c64af4fSJohn Polstra 
2240f1fca82eSMikolaj Golub #ifdef KINFO_PROC_SIZE
2241f1fca82eSMikolaj Golub CTASSERT(sizeof(struct kinfo_proc) == KINFO_PROC_SIZE);
2242f1fca82eSMikolaj Golub #endif
2243f1fca82eSMikolaj Golub 
2244f1fca82eSMikolaj Golub static void
2245f1fca82eSMikolaj Golub __elfN(note_procstat_proc)(void *arg, struct sbuf *sb, size_t *sizep)
2246f1fca82eSMikolaj Golub {
2247f1fca82eSMikolaj Golub 	struct proc *p;
2248f1fca82eSMikolaj Golub 	size_t size;
2249f1fca82eSMikolaj Golub 	int structsize;
2250f1fca82eSMikolaj Golub 
2251f1fca82eSMikolaj Golub 	p = (struct proc *)arg;
2252f1fca82eSMikolaj Golub 	size = sizeof(structsize) + p->p_numthreads *
2253f1fca82eSMikolaj Golub 	    sizeof(elf_kinfo_proc_t);
2254f1fca82eSMikolaj Golub 
2255f1fca82eSMikolaj Golub 	if (sb != NULL) {
2256f1fca82eSMikolaj Golub 		KASSERT(*sizep == size, ("invalid size"));
2257f1fca82eSMikolaj Golub 		structsize = sizeof(elf_kinfo_proc_t);
2258f1fca82eSMikolaj Golub 		sbuf_bcat(sb, &structsize, sizeof(structsize));
2259f1fca82eSMikolaj Golub 		PROC_LOCK(p);
2260f1fca82eSMikolaj Golub 		kern_proc_out(p, sb, ELF_KERN_PROC_MASK);
2261f1fca82eSMikolaj Golub 	}
2262f1fca82eSMikolaj Golub 	*sizep = size;
2263f1fca82eSMikolaj Golub }
2264f1fca82eSMikolaj Golub 
2265f1fca82eSMikolaj Golub #ifdef KINFO_FILE_SIZE
2266f1fca82eSMikolaj Golub CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
2267f1fca82eSMikolaj Golub #endif
2268f1fca82eSMikolaj Golub 
2269f1fca82eSMikolaj Golub static void
2270f1fca82eSMikolaj Golub note_procstat_files(void *arg, struct sbuf *sb, size_t *sizep)
2271f1fca82eSMikolaj Golub {
2272f1fca82eSMikolaj Golub 	struct proc *p;
227314bdbaf2SConrad Meyer 	size_t size, sect_sz, i;
227414bdbaf2SConrad Meyer 	ssize_t start_len, sect_len;
227514bdbaf2SConrad Meyer 	int structsize, filedesc_flags;
227614bdbaf2SConrad Meyer 
2277bcb60d52SConrad Meyer 	if (coredump_pack_fileinfo)
227814bdbaf2SConrad Meyer 		filedesc_flags = KERN_FILEDESC_PACK_KINFO;
227914bdbaf2SConrad Meyer 	else
228014bdbaf2SConrad Meyer 		filedesc_flags = 0;
2281f1fca82eSMikolaj Golub 
2282f1fca82eSMikolaj Golub 	p = (struct proc *)arg;
228314bdbaf2SConrad Meyer 	structsize = sizeof(struct kinfo_file);
2284f1fca82eSMikolaj Golub 	if (sb == NULL) {
2285f1fca82eSMikolaj Golub 		size = 0;
2286f1fca82eSMikolaj Golub 		sb = sbuf_new(NULL, NULL, 128, SBUF_FIXEDLEN);
2287f1fca82eSMikolaj Golub 		sbuf_set_drain(sb, sbuf_drain_count, &size);
2288f1fca82eSMikolaj Golub 		sbuf_bcat(sb, &structsize, sizeof(structsize));
2289f1fca82eSMikolaj Golub 		PROC_LOCK(p);
229014bdbaf2SConrad Meyer 		kern_proc_filedesc_out(p, sb, -1, filedesc_flags);
2291f1fca82eSMikolaj Golub 		sbuf_finish(sb);
2292f1fca82eSMikolaj Golub 		sbuf_delete(sb);
2293f1fca82eSMikolaj Golub 		*sizep = size;
2294f1fca82eSMikolaj Golub 	} else {
229514bdbaf2SConrad Meyer 		sbuf_start_section(sb, &start_len);
229614bdbaf2SConrad Meyer 
2297f1fca82eSMikolaj Golub 		sbuf_bcat(sb, &structsize, sizeof(structsize));
2298f1fca82eSMikolaj Golub 		PROC_LOCK(p);
229914bdbaf2SConrad Meyer 		kern_proc_filedesc_out(p, sb, *sizep - sizeof(structsize),
230014bdbaf2SConrad Meyer 		    filedesc_flags);
230114bdbaf2SConrad Meyer 
230214bdbaf2SConrad Meyer 		sect_len = sbuf_end_section(sb, start_len, 0, 0);
230314bdbaf2SConrad Meyer 		if (sect_len < 0)
230414bdbaf2SConrad Meyer 			return;
230514bdbaf2SConrad Meyer 		sect_sz = sect_len;
230614bdbaf2SConrad Meyer 
230714bdbaf2SConrad Meyer 		KASSERT(sect_sz <= *sizep,
230814bdbaf2SConrad Meyer 		    ("kern_proc_filedesc_out did not respect maxlen; "
230914bdbaf2SConrad Meyer 		     "requested %zu, got %zu", *sizep - sizeof(structsize),
231014bdbaf2SConrad Meyer 		     sect_sz - sizeof(structsize)));
231114bdbaf2SConrad Meyer 
231214bdbaf2SConrad Meyer 		for (i = 0; i < *sizep - sect_sz && sb->s_error == 0; i++)
231314bdbaf2SConrad Meyer 			sbuf_putc(sb, 0);
2314f1fca82eSMikolaj Golub 	}
2315f1fca82eSMikolaj Golub }
2316f1fca82eSMikolaj Golub 
2317f1fca82eSMikolaj Golub #ifdef KINFO_VMENTRY_SIZE
2318f1fca82eSMikolaj Golub CTASSERT(sizeof(struct kinfo_vmentry) == KINFO_VMENTRY_SIZE);
2319f1fca82eSMikolaj Golub #endif
2320f1fca82eSMikolaj Golub 
2321f1fca82eSMikolaj Golub static void
2322f1fca82eSMikolaj Golub note_procstat_vmmap(void *arg, struct sbuf *sb, size_t *sizep)
2323f1fca82eSMikolaj Golub {
2324f1fca82eSMikolaj Golub 	struct proc *p;
2325f1fca82eSMikolaj Golub 	size_t size;
2326e6b95927SConrad Meyer 	int structsize, vmmap_flags;
2327e6b95927SConrad Meyer 
2328e6b95927SConrad Meyer 	if (coredump_pack_vmmapinfo)
2329e6b95927SConrad Meyer 		vmmap_flags = KERN_VMMAP_PACK_KINFO;
2330e6b95927SConrad Meyer 	else
2331e6b95927SConrad Meyer 		vmmap_flags = 0;
2332f1fca82eSMikolaj Golub 
2333f1fca82eSMikolaj Golub 	p = (struct proc *)arg;
2334e6b95927SConrad Meyer 	structsize = sizeof(struct kinfo_vmentry);
2335f1fca82eSMikolaj Golub 	if (sb == NULL) {
2336f1fca82eSMikolaj Golub 		size = 0;
2337f1fca82eSMikolaj Golub 		sb = sbuf_new(NULL, NULL, 128, SBUF_FIXEDLEN);
2338f1fca82eSMikolaj Golub 		sbuf_set_drain(sb, sbuf_drain_count, &size);
2339f1fca82eSMikolaj Golub 		sbuf_bcat(sb, &structsize, sizeof(structsize));
2340f1fca82eSMikolaj Golub 		PROC_LOCK(p);
2341e6b95927SConrad Meyer 		kern_proc_vmmap_out(p, sb, -1, vmmap_flags);
2342f1fca82eSMikolaj Golub 		sbuf_finish(sb);
2343f1fca82eSMikolaj Golub 		sbuf_delete(sb);
2344f1fca82eSMikolaj Golub 		*sizep = size;
2345f1fca82eSMikolaj Golub 	} else {
2346f1fca82eSMikolaj Golub 		sbuf_bcat(sb, &structsize, sizeof(structsize));
2347f1fca82eSMikolaj Golub 		PROC_LOCK(p);
2348e6b95927SConrad Meyer 		kern_proc_vmmap_out(p, sb, *sizep - sizeof(structsize),
2349e6b95927SConrad Meyer 		    vmmap_flags);
2350f1fca82eSMikolaj Golub 	}
2351f1fca82eSMikolaj Golub }
2352f1fca82eSMikolaj Golub 
2353f1fca82eSMikolaj Golub static void
2354f1fca82eSMikolaj Golub note_procstat_groups(void *arg, struct sbuf *sb, size_t *sizep)
2355f1fca82eSMikolaj Golub {
2356f1fca82eSMikolaj Golub 	struct proc *p;
2357f1fca82eSMikolaj Golub 	size_t size;
2358f1fca82eSMikolaj Golub 	int structsize;
2359f1fca82eSMikolaj Golub 
2360f1fca82eSMikolaj Golub 	p = (struct proc *)arg;
2361f1fca82eSMikolaj Golub 	size = sizeof(structsize) + p->p_ucred->cr_ngroups * sizeof(gid_t);
2362f1fca82eSMikolaj Golub 	if (sb != NULL) {
2363f1fca82eSMikolaj Golub 		KASSERT(*sizep == size, ("invalid size"));
2364f1fca82eSMikolaj Golub 		structsize = sizeof(gid_t);
2365f1fca82eSMikolaj Golub 		sbuf_bcat(sb, &structsize, sizeof(structsize));
2366f1fca82eSMikolaj Golub 		sbuf_bcat(sb, p->p_ucred->cr_groups, p->p_ucred->cr_ngroups *
2367f1fca82eSMikolaj Golub 		    sizeof(gid_t));
2368f1fca82eSMikolaj Golub 	}
2369f1fca82eSMikolaj Golub 	*sizep = size;
2370f1fca82eSMikolaj Golub }
2371f1fca82eSMikolaj Golub 
2372f1fca82eSMikolaj Golub static void
2373f1fca82eSMikolaj Golub note_procstat_umask(void *arg, struct sbuf *sb, size_t *sizep)
2374f1fca82eSMikolaj Golub {
2375f1fca82eSMikolaj Golub 	struct proc *p;
2376f1fca82eSMikolaj Golub 	size_t size;
2377f1fca82eSMikolaj Golub 	int structsize;
2378f1fca82eSMikolaj Golub 
2379f1fca82eSMikolaj Golub 	p = (struct proc *)arg;
2380f1fca82eSMikolaj Golub 	size = sizeof(structsize) + sizeof(p->p_fd->fd_cmask);
2381f1fca82eSMikolaj Golub 	if (sb != NULL) {
2382f1fca82eSMikolaj Golub 		KASSERT(*sizep == size, ("invalid size"));
2383f1fca82eSMikolaj Golub 		structsize = sizeof(p->p_fd->fd_cmask);
2384f1fca82eSMikolaj Golub 		sbuf_bcat(sb, &structsize, sizeof(structsize));
2385f1fca82eSMikolaj Golub 		sbuf_bcat(sb, &p->p_fd->fd_cmask, sizeof(p->p_fd->fd_cmask));
2386f1fca82eSMikolaj Golub 	}
2387f1fca82eSMikolaj Golub 	*sizep = size;
2388f1fca82eSMikolaj Golub }
2389f1fca82eSMikolaj Golub 
2390f1fca82eSMikolaj Golub static void
2391f1fca82eSMikolaj Golub note_procstat_rlimit(void *arg, struct sbuf *sb, size_t *sizep)
2392f1fca82eSMikolaj Golub {
2393f1fca82eSMikolaj Golub 	struct proc *p;
2394f1fca82eSMikolaj Golub 	struct rlimit rlim[RLIM_NLIMITS];
2395f1fca82eSMikolaj Golub 	size_t size;
2396f1fca82eSMikolaj Golub 	int structsize, i;
2397f1fca82eSMikolaj Golub 
2398f1fca82eSMikolaj Golub 	p = (struct proc *)arg;
2399f1fca82eSMikolaj Golub 	size = sizeof(structsize) + sizeof(rlim);
2400f1fca82eSMikolaj Golub 	if (sb != NULL) {
2401f1fca82eSMikolaj Golub 		KASSERT(*sizep == size, ("invalid size"));
2402f1fca82eSMikolaj Golub 		structsize = sizeof(rlim);
2403f1fca82eSMikolaj Golub 		sbuf_bcat(sb, &structsize, sizeof(structsize));
2404f1fca82eSMikolaj Golub 		PROC_LOCK(p);
2405f1fca82eSMikolaj Golub 		for (i = 0; i < RLIM_NLIMITS; i++)
2406f6f6d240SMateusz Guzik 			lim_rlimit_proc(p, i, &rlim[i]);
2407f1fca82eSMikolaj Golub 		PROC_UNLOCK(p);
2408f1fca82eSMikolaj Golub 		sbuf_bcat(sb, rlim, sizeof(rlim));
2409f1fca82eSMikolaj Golub 	}
2410f1fca82eSMikolaj Golub 	*sizep = size;
2411f1fca82eSMikolaj Golub }
2412f1fca82eSMikolaj Golub 
2413f1fca82eSMikolaj Golub static void
2414f1fca82eSMikolaj Golub note_procstat_osrel(void *arg, struct sbuf *sb, size_t *sizep)
2415f1fca82eSMikolaj Golub {
2416f1fca82eSMikolaj Golub 	struct proc *p;
2417f1fca82eSMikolaj Golub 	size_t size;
2418f1fca82eSMikolaj Golub 	int structsize;
2419f1fca82eSMikolaj Golub 
2420f1fca82eSMikolaj Golub 	p = (struct proc *)arg;
2421f1fca82eSMikolaj Golub 	size = sizeof(structsize) + sizeof(p->p_osrel);
2422f1fca82eSMikolaj Golub 	if (sb != NULL) {
2423f1fca82eSMikolaj Golub 		KASSERT(*sizep == size, ("invalid size"));
2424f1fca82eSMikolaj Golub 		structsize = sizeof(p->p_osrel);
2425f1fca82eSMikolaj Golub 		sbuf_bcat(sb, &structsize, sizeof(structsize));
2426f1fca82eSMikolaj Golub 		sbuf_bcat(sb, &p->p_osrel, sizeof(p->p_osrel));
2427f1fca82eSMikolaj Golub 	}
2428f1fca82eSMikolaj Golub 	*sizep = size;
2429f1fca82eSMikolaj Golub }
2430f1fca82eSMikolaj Golub 
2431f1fca82eSMikolaj Golub static void
2432f1fca82eSMikolaj Golub __elfN(note_procstat_psstrings)(void *arg, struct sbuf *sb, size_t *sizep)
2433f1fca82eSMikolaj Golub {
2434f1fca82eSMikolaj Golub 	struct proc *p;
2435f1fca82eSMikolaj Golub 	elf_ps_strings_t ps_strings;
2436f1fca82eSMikolaj Golub 	size_t size;
2437f1fca82eSMikolaj Golub 	int structsize;
2438f1fca82eSMikolaj Golub 
2439f1fca82eSMikolaj Golub 	p = (struct proc *)arg;
2440f1fca82eSMikolaj Golub 	size = sizeof(structsize) + sizeof(ps_strings);
2441f1fca82eSMikolaj Golub 	if (sb != NULL) {
2442f1fca82eSMikolaj Golub 		KASSERT(*sizep == size, ("invalid size"));
2443f1fca82eSMikolaj Golub 		structsize = sizeof(ps_strings);
2444f1fca82eSMikolaj Golub #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
2445f1fca82eSMikolaj Golub 		ps_strings = PTROUT(p->p_sysent->sv_psstrings);
2446f1fca82eSMikolaj Golub #else
2447f1fca82eSMikolaj Golub 		ps_strings = p->p_sysent->sv_psstrings;
2448f1fca82eSMikolaj Golub #endif
2449f1fca82eSMikolaj Golub 		sbuf_bcat(sb, &structsize, sizeof(structsize));
2450f1fca82eSMikolaj Golub 		sbuf_bcat(sb, &ps_strings, sizeof(ps_strings));
2451f1fca82eSMikolaj Golub 	}
2452f1fca82eSMikolaj Golub 	*sizep = size;
2453f1fca82eSMikolaj Golub }
2454f1fca82eSMikolaj Golub 
2455f1fca82eSMikolaj Golub static void
2456f1fca82eSMikolaj Golub __elfN(note_procstat_auxv)(void *arg, struct sbuf *sb, size_t *sizep)
2457f1fca82eSMikolaj Golub {
2458f1fca82eSMikolaj Golub 	struct proc *p;
2459f1fca82eSMikolaj Golub 	size_t size;
2460f1fca82eSMikolaj Golub 	int structsize;
2461f1fca82eSMikolaj Golub 
2462f1fca82eSMikolaj Golub 	p = (struct proc *)arg;
2463f1fca82eSMikolaj Golub 	if (sb == NULL) {
2464f1fca82eSMikolaj Golub 		size = 0;
2465f1fca82eSMikolaj Golub 		sb = sbuf_new(NULL, NULL, 128, SBUF_FIXEDLEN);
2466f1fca82eSMikolaj Golub 		sbuf_set_drain(sb, sbuf_drain_count, &size);
2467f1fca82eSMikolaj Golub 		sbuf_bcat(sb, &structsize, sizeof(structsize));
2468f1fca82eSMikolaj Golub 		PHOLD(p);
2469f1fca82eSMikolaj Golub 		proc_getauxv(curthread, p, sb);
2470f1fca82eSMikolaj Golub 		PRELE(p);
2471f1fca82eSMikolaj Golub 		sbuf_finish(sb);
2472f1fca82eSMikolaj Golub 		sbuf_delete(sb);
2473f1fca82eSMikolaj Golub 		*sizep = size;
2474f1fca82eSMikolaj Golub 	} else {
2475f1fca82eSMikolaj Golub 		structsize = sizeof(Elf_Auxinfo);
2476f1fca82eSMikolaj Golub 		sbuf_bcat(sb, &structsize, sizeof(structsize));
2477f1fca82eSMikolaj Golub 		PHOLD(p);
2478f1fca82eSMikolaj Golub 		proc_getauxv(curthread, p, sb);
2479f1fca82eSMikolaj Golub 		PRELE(p);
2480f1fca82eSMikolaj Golub 	}
2481f1fca82eSMikolaj Golub }
2482f1fca82eSMikolaj Golub 
248332c01de2SDmitry Chagin static boolean_t
248492328a32SKonstantin Belousov __elfN(parse_notes)(struct image_params *imgp, Elf_Note *checknote,
248592328a32SKonstantin Belousov     const char *note_vendor, const Elf_Phdr *pnote,
248692328a32SKonstantin Belousov     boolean_t (*cb)(const Elf_Note *, void *, boolean_t *), void *cb_arg)
248732c01de2SDmitry Chagin {
2488267c52fcSKonstantin Belousov 	const Elf_Note *note, *note0, *note_end;
248932c01de2SDmitry Chagin 	const char *note_name;
24906c775eb6SKonstantin Belousov 	char *buf;
24916c775eb6SKonstantin Belousov 	int i, error;
24926c775eb6SKonstantin Belousov 	boolean_t res;
249332c01de2SDmitry Chagin 
24946c775eb6SKonstantin Belousov 	/* We need some limit, might as well use PAGE_SIZE. */
24956c775eb6SKonstantin Belousov 	if (pnote == NULL || pnote->p_filesz > PAGE_SIZE)
249632c01de2SDmitry Chagin 		return (FALSE);
24976c775eb6SKonstantin Belousov 	ASSERT_VOP_LOCKED(imgp->vp, "parse_notes");
24986c775eb6SKonstantin Belousov 	if (pnote->p_offset > PAGE_SIZE ||
24996c775eb6SKonstantin Belousov 	    pnote->p_filesz > PAGE_SIZE - pnote->p_offset) {
25006c775eb6SKonstantin Belousov 		VOP_UNLOCK(imgp->vp, 0);
25016c775eb6SKonstantin Belousov 		buf = malloc(pnote->p_filesz, M_TEMP, M_WAITOK);
25026c775eb6SKonstantin Belousov 		vn_lock(imgp->vp, LK_EXCLUSIVE | LK_RETRY);
25036c775eb6SKonstantin Belousov 		error = vn_rdwr(UIO_READ, imgp->vp, buf, pnote->p_filesz,
25046c775eb6SKonstantin Belousov 		    pnote->p_offset, UIO_SYSSPACE, IO_NODELOCKED,
25056c775eb6SKonstantin Belousov 		    curthread->td_ucred, NOCRED, NULL, curthread);
25066c775eb6SKonstantin Belousov 		if (error != 0) {
25076c775eb6SKonstantin Belousov 			uprintf("i/o error PT_NOTE\n");
2508eda8fe63SKonstantin Belousov 			goto retf;
25096c775eb6SKonstantin Belousov 		}
25106c775eb6SKonstantin Belousov 		note = note0 = (const Elf_Note *)buf;
25116c775eb6SKonstantin Belousov 		note_end = (const Elf_Note *)(buf + pnote->p_filesz);
25126c775eb6SKonstantin Belousov 	} else {
25136c775eb6SKonstantin Belousov 		note = note0 = (const Elf_Note *)(imgp->image_header +
25146c775eb6SKonstantin Belousov 		    pnote->p_offset);
251532c01de2SDmitry Chagin 		note_end = (const Elf_Note *)(imgp->image_header +
251632c01de2SDmitry Chagin 		    pnote->p_offset + pnote->p_filesz);
25176c775eb6SKonstantin Belousov 		buf = NULL;
25186c775eb6SKonstantin Belousov 	}
2519267c52fcSKonstantin Belousov 	for (i = 0; i < 100 && note >= note0 && note < note_end; i++) {
2520d1ae5c83SKonstantin Belousov 		if (!aligned(note, Elf32_Addr) || (const char *)note_end -
25216c775eb6SKonstantin Belousov 		    (const char *)note < sizeof(Elf_Note)) {
2522eda8fe63SKonstantin Belousov 			goto retf;
25236c775eb6SKonstantin Belousov 		}
252492328a32SKonstantin Belousov 		if (note->n_namesz != checknote->n_namesz ||
252592328a32SKonstantin Belousov 		    note->n_descsz != checknote->n_descsz ||
252692328a32SKonstantin Belousov 		    note->n_type != checknote->n_type)
252732c01de2SDmitry Chagin 			goto nextnote;
252832c01de2SDmitry Chagin 		note_name = (const char *)(note + 1);
252992328a32SKonstantin Belousov 		if (note_name + checknote->n_namesz >=
253092328a32SKonstantin Belousov 		    (const char *)note_end || strncmp(note_vendor,
253192328a32SKonstantin Belousov 		    note_name, checknote->n_namesz) != 0)
253232c01de2SDmitry Chagin 			goto nextnote;
253332c01de2SDmitry Chagin 
253492328a32SKonstantin Belousov 		if (cb(note, cb_arg, &res))
25356c775eb6SKonstantin Belousov 			goto ret;
253632c01de2SDmitry Chagin nextnote:
253732c01de2SDmitry Chagin 		note = (const Elf_Note *)((const char *)(note + 1) +
25381b8388cdSMikolaj Golub 		    roundup2(note->n_namesz, ELF_NOTE_ROUNDSIZE) +
25391b8388cdSMikolaj Golub 		    roundup2(note->n_descsz, ELF_NOTE_ROUNDSIZE));
254032c01de2SDmitry Chagin 	}
2541eda8fe63SKonstantin Belousov retf:
25426c775eb6SKonstantin Belousov 	res = FALSE;
25436c775eb6SKonstantin Belousov ret:
25446c775eb6SKonstantin Belousov 	free(buf, M_TEMP);
25456c775eb6SKonstantin Belousov 	return (res);
254632c01de2SDmitry Chagin }
254732c01de2SDmitry Chagin 
254892328a32SKonstantin Belousov struct brandnote_cb_arg {
254992328a32SKonstantin Belousov 	Elf_Brandnote *brandnote;
255092328a32SKonstantin Belousov 	int32_t *osrel;
255192328a32SKonstantin Belousov };
255292328a32SKonstantin Belousov 
255392328a32SKonstantin Belousov static boolean_t
255492328a32SKonstantin Belousov brandnote_cb(const Elf_Note *note, void *arg0, boolean_t *res)
255592328a32SKonstantin Belousov {
255692328a32SKonstantin Belousov 	struct brandnote_cb_arg *arg;
255792328a32SKonstantin Belousov 
255892328a32SKonstantin Belousov 	arg = arg0;
255992328a32SKonstantin Belousov 
256092328a32SKonstantin Belousov 	/*
256192328a32SKonstantin Belousov 	 * Fetch the osreldate for binary from the ELF OSABI-note if
256292328a32SKonstantin Belousov 	 * necessary.
256392328a32SKonstantin Belousov 	 */
256492328a32SKonstantin Belousov 	*res = (arg->brandnote->flags & BN_TRANSLATE_OSREL) != 0 &&
256592328a32SKonstantin Belousov 	    arg->brandnote->trans_osrel != NULL ?
256692328a32SKonstantin Belousov 	    arg->brandnote->trans_osrel(note, arg->osrel) : TRUE;
256792328a32SKonstantin Belousov 
256892328a32SKonstantin Belousov 	return (TRUE);
256992328a32SKonstantin Belousov }
257092328a32SKonstantin Belousov 
2571cefb93f2SKonstantin Belousov static Elf_Note fctl_note = {
2572cefb93f2SKonstantin Belousov 	.n_namesz = sizeof(FREEBSD_ABI_VENDOR),
2573cefb93f2SKonstantin Belousov 	.n_descsz = sizeof(uint32_t),
2574cefb93f2SKonstantin Belousov 	.n_type = NT_FREEBSD_FEATURE_CTL,
2575cefb93f2SKonstantin Belousov };
2576cefb93f2SKonstantin Belousov 
2577cefb93f2SKonstantin Belousov struct fctl_cb_arg {
2578cefb93f2SKonstantin Belousov 	uint32_t *fctl0;
2579cefb93f2SKonstantin Belousov };
2580cefb93f2SKonstantin Belousov 
2581cefb93f2SKonstantin Belousov static boolean_t
2582cefb93f2SKonstantin Belousov note_fctl_cb(const Elf_Note *note, void *arg0, boolean_t *res)
2583cefb93f2SKonstantin Belousov {
2584cefb93f2SKonstantin Belousov 	struct fctl_cb_arg *arg;
2585cefb93f2SKonstantin Belousov 	const Elf32_Word *desc;
2586cefb93f2SKonstantin Belousov 	uintptr_t p;
2587cefb93f2SKonstantin Belousov 
2588cefb93f2SKonstantin Belousov 	arg = arg0;
2589cefb93f2SKonstantin Belousov 	p = (uintptr_t)(note + 1);
2590cefb93f2SKonstantin Belousov 	p += roundup2(note->n_namesz, ELF_NOTE_ROUNDSIZE);
2591cefb93f2SKonstantin Belousov 	desc = (const Elf32_Word *)p;
2592cefb93f2SKonstantin Belousov 	*arg->fctl0 = desc[0];
2593cefb93f2SKonstantin Belousov 	return (TRUE);
2594cefb93f2SKonstantin Belousov }
2595cefb93f2SKonstantin Belousov 
259632c01de2SDmitry Chagin /*
2597cefb93f2SKonstantin Belousov  * Try to find the appropriate ABI-note section for checknote, fetch
2598cefb93f2SKonstantin Belousov  * the osreldate and feature control flags for binary from the ELF
2599cefb93f2SKonstantin Belousov  * OSABI-note.  Only the first page of the image is searched, the same
2600cefb93f2SKonstantin Belousov  * as for headers.
26011a9c7decSKonstantin Belousov  */
26021a9c7decSKonstantin Belousov static boolean_t
260392328a32SKonstantin Belousov __elfN(check_note)(struct image_params *imgp, Elf_Brandnote *brandnote,
2604cefb93f2SKonstantin Belousov     int32_t *osrel, uint32_t *fctl0)
26051a9c7decSKonstantin Belousov {
26061a9c7decSKonstantin Belousov 	const Elf_Phdr *phdr;
26071a9c7decSKonstantin Belousov 	const Elf_Ehdr *hdr;
260892328a32SKonstantin Belousov 	struct brandnote_cb_arg b_arg;
2609cefb93f2SKonstantin Belousov 	struct fctl_cb_arg f_arg;
2610cefb93f2SKonstantin Belousov 	int i, j;
26111a9c7decSKonstantin Belousov 
26121a9c7decSKonstantin Belousov 	hdr = (const Elf_Ehdr *)imgp->image_header;
26131a9c7decSKonstantin Belousov 	phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
261492328a32SKonstantin Belousov 	b_arg.brandnote = brandnote;
261592328a32SKonstantin Belousov 	b_arg.osrel = osrel;
2616cefb93f2SKonstantin Belousov 	f_arg.fctl0 = fctl0;
26171a9c7decSKonstantin Belousov 
26181a9c7decSKonstantin Belousov 	for (i = 0; i < hdr->e_phnum; i++) {
261992328a32SKonstantin Belousov 		if (phdr[i].p_type == PT_NOTE && __elfN(parse_notes)(imgp,
262092328a32SKonstantin Belousov 		    &brandnote->hdr, brandnote->vendor, &phdr[i], brandnote_cb,
262192328a32SKonstantin Belousov 		    &b_arg)) {
2622cefb93f2SKonstantin Belousov 			for (j = 0; j < hdr->e_phnum; j++) {
2623cefb93f2SKonstantin Belousov 				if (phdr[j].p_type == PT_NOTE &&
2624cefb93f2SKonstantin Belousov 				    __elfN(parse_notes)(imgp, &fctl_note,
2625cefb93f2SKonstantin Belousov 				    FREEBSD_ABI_VENDOR, &phdr[j],
2626cefb93f2SKonstantin Belousov 				    note_fctl_cb, &f_arg))
2627cefb93f2SKonstantin Belousov 					break;
2628cefb93f2SKonstantin Belousov 			}
26291a9c7decSKonstantin Belousov 			return (TRUE);
26301a9c7decSKonstantin Belousov 		}
263192328a32SKonstantin Belousov 	}
26321a9c7decSKonstantin Belousov 	return (FALSE);
26331a9c7decSKonstantin Belousov 
26341a9c7decSKonstantin Belousov }
26351a9c7decSKonstantin Belousov 
26361a9c7decSKonstantin Belousov /*
2637e1743d02SSøren Schmidt  * Tell kern_execve.c about it, with a little help from the linker.
2638e1743d02SSøren Schmidt  */
2639a360a43dSJake Burkholder static struct execsw __elfN(execsw) = {
2640b7feabf9SEd Maste 	.ex_imgact = __CONCAT(exec_, __elfN(imgact)),
2641b7feabf9SEd Maste 	.ex_name = __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE))
2642a360a43dSJake Burkholder };
2643a360a43dSJake Burkholder EXEC_SET(__CONCAT(elf, __ELF_WORD_SIZE), __elfN(execsw));
2644e7228204SAlfred Perlstein 
2645ed167eaaSKonstantin Belousov static vm_prot_t
2646ed167eaaSKonstantin Belousov __elfN(trans_prot)(Elf_Word flags)
2647ed167eaaSKonstantin Belousov {
2648ed167eaaSKonstantin Belousov 	vm_prot_t prot;
2649ed167eaaSKonstantin Belousov 
2650ed167eaaSKonstantin Belousov 	prot = 0;
2651ed167eaaSKonstantin Belousov 	if (flags & PF_X)
2652ed167eaaSKonstantin Belousov 		prot |= VM_PROT_EXECUTE;
2653ed167eaaSKonstantin Belousov 	if (flags & PF_W)
2654ed167eaaSKonstantin Belousov 		prot |= VM_PROT_WRITE;
2655ed167eaaSKonstantin Belousov 	if (flags & PF_R)
2656ed167eaaSKonstantin Belousov 		prot |= VM_PROT_READ;
2657eb785fabSKonstantin Belousov #if __ELF_WORD_SIZE == 32 && (defined(__amd64__) || defined(__i386__))
2658126b36a2SKonstantin Belousov 	if (i386_read_exec && (flags & PF_R))
2659676eda08SMarcel Moolenaar 		prot |= VM_PROT_EXECUTE;
2660676eda08SMarcel Moolenaar #endif
2661ed167eaaSKonstantin Belousov 	return (prot);
2662ed167eaaSKonstantin Belousov }
2663ed167eaaSKonstantin Belousov 
2664ed167eaaSKonstantin Belousov static Elf_Word
2665ed167eaaSKonstantin Belousov __elfN(untrans_prot)(vm_prot_t prot)
2666ed167eaaSKonstantin Belousov {
2667ed167eaaSKonstantin Belousov 	Elf_Word flags;
2668ed167eaaSKonstantin Belousov 
2669ed167eaaSKonstantin Belousov 	flags = 0;
2670ed167eaaSKonstantin Belousov 	if (prot & VM_PROT_EXECUTE)
2671ed167eaaSKonstantin Belousov 		flags |= PF_X;
2672ed167eaaSKonstantin Belousov 	if (prot & VM_PROT_READ)
2673ed167eaaSKonstantin Belousov 		flags |= PF_R;
2674ed167eaaSKonstantin Belousov 	if (prot & VM_PROT_WRITE)
2675ed167eaaSKonstantin Belousov 		flags |= PF_W;
2676ed167eaaSKonstantin Belousov 	return (flags);
2677ed167eaaSKonstantin Belousov }
2678