xref: /freebsd/sys/kern/imgact_elf.c (revision a4bcd20486f8c20cc875b39bc75aa0d5a047373f)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 2017 Dell EMC
5  * Copyright (c) 2000-2001, 2003 David O'Brien
6  * Copyright (c) 1995-1996 Søren Schmidt
7  * Copyright (c) 1996 Peter Wemm
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer
15  *    in this position and unchanged.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. The name of the author may not be used to endorse or promote products
20  *    derived from this software without specific prior written permission
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
23  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
24  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
25  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
27  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
31  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33 
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36 
37 #include "opt_capsicum.h"
38 
39 #include <sys/param.h>
40 #include <sys/capsicum.h>
41 #include <sys/compressor.h>
42 #include <sys/exec.h>
43 #include <sys/fcntl.h>
44 #include <sys/imgact.h>
45 #include <sys/imgact_elf.h>
46 #include <sys/jail.h>
47 #include <sys/kernel.h>
48 #include <sys/lock.h>
49 #include <sys/malloc.h>
50 #include <sys/mount.h>
51 #include <sys/mman.h>
52 #include <sys/namei.h>
53 #include <sys/proc.h>
54 #include <sys/procfs.h>
55 #include <sys/ptrace.h>
56 #include <sys/racct.h>
57 #include <sys/resourcevar.h>
58 #include <sys/rwlock.h>
59 #include <sys/sbuf.h>
60 #include <sys/sf_buf.h>
61 #include <sys/smp.h>
62 #include <sys/systm.h>
63 #include <sys/signalvar.h>
64 #include <sys/stat.h>
65 #include <sys/sx.h>
66 #include <sys/syscall.h>
67 #include <sys/sysctl.h>
68 #include <sys/sysent.h>
69 #include <sys/vnode.h>
70 #include <sys/syslog.h>
71 #include <sys/eventhandler.h>
72 #include <sys/user.h>
73 
74 #include <vm/vm.h>
75 #include <vm/vm_kern.h>
76 #include <vm/vm_param.h>
77 #include <vm/pmap.h>
78 #include <vm/vm_map.h>
79 #include <vm/vm_object.h>
80 #include <vm/vm_extern.h>
81 
82 #include <machine/elf.h>
83 #include <machine/md_var.h>
84 
85 #define ELF_NOTE_ROUNDSIZE	4
86 #define OLD_EI_BRAND	8
87 
88 static int __elfN(check_header)(const Elf_Ehdr *hdr);
89 static Elf_Brandinfo *__elfN(get_brandinfo)(struct image_params *imgp,
90     const char *interp, int32_t *osrel, uint32_t *fctl0);
91 static int __elfN(load_file)(struct proc *p, const char *file, u_long *addr,
92     u_long *entry);
93 static int __elfN(load_section)(struct image_params *imgp, vm_ooffset_t offset,
94     caddr_t vmaddr, size_t memsz, size_t filsz, vm_prot_t prot);
95 static int __CONCAT(exec_, __elfN(imgact))(struct image_params *imgp);
96 static bool __elfN(freebsd_trans_osrel)(const Elf_Note *note,
97     int32_t *osrel);
98 static bool kfreebsd_trans_osrel(const Elf_Note *note, int32_t *osrel);
99 static boolean_t __elfN(check_note)(struct image_params *imgp,
100     Elf_Brandnote *checknote, int32_t *osrel, boolean_t *has_fctl0,
101     uint32_t *fctl0);
102 static vm_prot_t __elfN(trans_prot)(Elf_Word);
103 static Elf_Word __elfN(untrans_prot)(vm_prot_t);
104 
105 SYSCTL_NODE(_kern, OID_AUTO, __CONCAT(elf, __ELF_WORD_SIZE),
106     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
107     "");
108 
109 #define	CORE_BUF_SIZE	(16 * 1024)
110 
111 int __elfN(fallback_brand) = -1;
112 SYSCTL_INT(__CONCAT(_kern_elf, __ELF_WORD_SIZE), OID_AUTO,
113     fallback_brand, CTLFLAG_RWTUN, &__elfN(fallback_brand), 0,
114     __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE)) " brand of last resort");
115 
116 static int elf_legacy_coredump = 0;
117 SYSCTL_INT(_debug, OID_AUTO, __elfN(legacy_coredump), CTLFLAG_RW,
118     &elf_legacy_coredump, 0,
119     "include all and only RW pages in core dumps");
120 
121 int __elfN(nxstack) =
122 #if defined(__amd64__) || defined(__powerpc64__) /* both 64 and 32 bit */ || \
123     (defined(__arm__) && __ARM_ARCH >= 7) || defined(__aarch64__) || \
124     defined(__riscv)
125 	1;
126 #else
127 	0;
128 #endif
129 SYSCTL_INT(__CONCAT(_kern_elf, __ELF_WORD_SIZE), OID_AUTO,
130     nxstack, CTLFLAG_RW, &__elfN(nxstack), 0,
131     __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE)) ": enable non-executable stack");
132 
133 #if __ELF_WORD_SIZE == 32 && (defined(__amd64__) || defined(__i386__))
134 int i386_read_exec = 0;
135 SYSCTL_INT(_kern_elf32, OID_AUTO, read_exec, CTLFLAG_RW, &i386_read_exec, 0,
136     "enable execution from readable segments");
137 #endif
138 
139 static u_long __elfN(pie_base) = ET_DYN_LOAD_ADDR;
140 static int
141 sysctl_pie_base(SYSCTL_HANDLER_ARGS)
142 {
143 	u_long val;
144 	int error;
145 
146 	val = __elfN(pie_base);
147 	error = sysctl_handle_long(oidp, &val, 0, req);
148 	if (error != 0 || req->newptr == NULL)
149 		return (error);
150 	if ((val & PAGE_MASK) != 0)
151 		return (EINVAL);
152 	__elfN(pie_base) = val;
153 	return (0);
154 }
155 SYSCTL_PROC(__CONCAT(_kern_elf, __ELF_WORD_SIZE), OID_AUTO, pie_base,
156     CTLTYPE_ULONG | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0,
157     sysctl_pie_base, "LU",
158     "PIE load base without randomization");
159 
160 SYSCTL_NODE(__CONCAT(_kern_elf, __ELF_WORD_SIZE), OID_AUTO, aslr,
161     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
162     "");
163 #define	ASLR_NODE_OID	__CONCAT(__CONCAT(_kern_elf, __ELF_WORD_SIZE), _aslr)
164 
165 static int __elfN(aslr_enabled) = 0;
166 SYSCTL_INT(ASLR_NODE_OID, OID_AUTO, enable, CTLFLAG_RWTUN,
167     &__elfN(aslr_enabled), 0,
168     __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE))
169     ": enable address map randomization");
170 
171 static int __elfN(pie_aslr_enabled) = 0;
172 SYSCTL_INT(ASLR_NODE_OID, OID_AUTO, pie_enable, CTLFLAG_RWTUN,
173     &__elfN(pie_aslr_enabled), 0,
174     __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE))
175     ": enable address map randomization for PIE binaries");
176 
177 static int __elfN(aslr_honor_sbrk) = 1;
178 SYSCTL_INT(ASLR_NODE_OID, OID_AUTO, honor_sbrk, CTLFLAG_RW,
179     &__elfN(aslr_honor_sbrk), 0,
180     __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE)) ": assume sbrk is used");
181 
182 static int __elfN(aslr_stack_gap) = 3;
183 SYSCTL_INT(ASLR_NODE_OID, OID_AUTO, stack_gap, CTLFLAG_RW,
184     &__elfN(aslr_stack_gap), 0,
185     __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE))
186     ": maximum percentage of main stack to waste on a random gap");
187 
188 static int __elfN(sigfastblock) = 1;
189 SYSCTL_INT(__CONCAT(_kern_elf, __ELF_WORD_SIZE), OID_AUTO, sigfastblock,
190     CTLFLAG_RWTUN, &__elfN(sigfastblock), 0,
191     "enable sigfastblock for new processes");
192 
193 static Elf_Brandinfo *elf_brand_list[MAX_BRANDS];
194 
195 #define	aligned(a, t)	(rounddown2((u_long)(a), sizeof(t)) == (u_long)(a))
196 
197 static const char FREEBSD_ABI_VENDOR[] = "FreeBSD";
198 
199 Elf_Brandnote __elfN(freebsd_brandnote) = {
200 	.hdr.n_namesz	= sizeof(FREEBSD_ABI_VENDOR),
201 	.hdr.n_descsz	= sizeof(int32_t),
202 	.hdr.n_type	= NT_FREEBSD_ABI_TAG,
203 	.vendor		= FREEBSD_ABI_VENDOR,
204 	.flags		= BN_TRANSLATE_OSREL,
205 	.trans_osrel	= __elfN(freebsd_trans_osrel)
206 };
207 
208 static bool
209 __elfN(freebsd_trans_osrel)(const Elf_Note *note, int32_t *osrel)
210 {
211 	uintptr_t p;
212 
213 	p = (uintptr_t)(note + 1);
214 	p += roundup2(note->n_namesz, ELF_NOTE_ROUNDSIZE);
215 	*osrel = *(const int32_t *)(p);
216 
217 	return (true);
218 }
219 
220 static const char GNU_ABI_VENDOR[] = "GNU";
221 static int GNU_KFREEBSD_ABI_DESC = 3;
222 
223 Elf_Brandnote __elfN(kfreebsd_brandnote) = {
224 	.hdr.n_namesz	= sizeof(GNU_ABI_VENDOR),
225 	.hdr.n_descsz	= 16,	/* XXX at least 16 */
226 	.hdr.n_type	= 1,
227 	.vendor		= GNU_ABI_VENDOR,
228 	.flags		= BN_TRANSLATE_OSREL,
229 	.trans_osrel	= kfreebsd_trans_osrel
230 };
231 
232 static bool
233 kfreebsd_trans_osrel(const Elf_Note *note, int32_t *osrel)
234 {
235 	const Elf32_Word *desc;
236 	uintptr_t p;
237 
238 	p = (uintptr_t)(note + 1);
239 	p += roundup2(note->n_namesz, ELF_NOTE_ROUNDSIZE);
240 
241 	desc = (const Elf32_Word *)p;
242 	if (desc[0] != GNU_KFREEBSD_ABI_DESC)
243 		return (false);
244 
245 	/*
246 	 * Debian GNU/kFreeBSD embed the earliest compatible kernel version
247 	 * (__FreeBSD_version: <major><two digit minor>Rxx) in the LSB way.
248 	 */
249 	*osrel = desc[1] * 100000 + desc[2] * 1000 + desc[3];
250 
251 	return (true);
252 }
253 
254 int
255 __elfN(insert_brand_entry)(Elf_Brandinfo *entry)
256 {
257 	int i;
258 
259 	for (i = 0; i < MAX_BRANDS; i++) {
260 		if (elf_brand_list[i] == NULL) {
261 			elf_brand_list[i] = entry;
262 			break;
263 		}
264 	}
265 	if (i == MAX_BRANDS) {
266 		printf("WARNING: %s: could not insert brandinfo entry: %p\n",
267 			__func__, entry);
268 		return (-1);
269 	}
270 	return (0);
271 }
272 
273 int
274 __elfN(remove_brand_entry)(Elf_Brandinfo *entry)
275 {
276 	int i;
277 
278 	for (i = 0; i < MAX_BRANDS; i++) {
279 		if (elf_brand_list[i] == entry) {
280 			elf_brand_list[i] = NULL;
281 			break;
282 		}
283 	}
284 	if (i == MAX_BRANDS)
285 		return (-1);
286 	return (0);
287 }
288 
289 int
290 __elfN(brand_inuse)(Elf_Brandinfo *entry)
291 {
292 	struct proc *p;
293 	int rval = FALSE;
294 
295 	sx_slock(&allproc_lock);
296 	FOREACH_PROC_IN_SYSTEM(p) {
297 		if (p->p_sysent == entry->sysvec) {
298 			rval = TRUE;
299 			break;
300 		}
301 	}
302 	sx_sunlock(&allproc_lock);
303 
304 	return (rval);
305 }
306 
307 static Elf_Brandinfo *
308 __elfN(get_brandinfo)(struct image_params *imgp, const char *interp,
309     int32_t *osrel, uint32_t *fctl0)
310 {
311 	const Elf_Ehdr *hdr = (const Elf_Ehdr *)imgp->image_header;
312 	Elf_Brandinfo *bi, *bi_m;
313 	boolean_t ret, has_fctl0;
314 	int i, interp_name_len;
315 
316 	interp_name_len = interp != NULL ? strlen(interp) + 1 : 0;
317 
318 	/*
319 	 * We support four types of branding -- (1) the ELF EI_OSABI field
320 	 * that SCO added to the ELF spec, (2) FreeBSD 3.x's traditional string
321 	 * branding w/in the ELF header, (3) path of the `interp_path'
322 	 * field, and (4) the ".note.ABI-tag" ELF section.
323 	 */
324 
325 	/* Look for an ".note.ABI-tag" ELF section */
326 	bi_m = NULL;
327 	for (i = 0; i < MAX_BRANDS; i++) {
328 		bi = elf_brand_list[i];
329 		if (bi == NULL)
330 			continue;
331 		if (interp != NULL && (bi->flags & BI_BRAND_ONLY_STATIC) != 0)
332 			continue;
333 		if (hdr->e_machine == bi->machine && (bi->flags &
334 		    (BI_BRAND_NOTE|BI_BRAND_NOTE_MANDATORY)) != 0) {
335 			has_fctl0 = false;
336 			*fctl0 = 0;
337 			*osrel = 0;
338 			ret = __elfN(check_note)(imgp, bi->brand_note, osrel,
339 			    &has_fctl0, fctl0);
340 			/* Give brand a chance to veto check_note's guess */
341 			if (ret && bi->header_supported) {
342 				ret = bi->header_supported(imgp, osrel,
343 				    has_fctl0 ? fctl0 : NULL);
344 			}
345 			/*
346 			 * If note checker claimed the binary, but the
347 			 * interpreter path in the image does not
348 			 * match default one for the brand, try to
349 			 * search for other brands with the same
350 			 * interpreter.  Either there is better brand
351 			 * with the right interpreter, or, failing
352 			 * this, we return first brand which accepted
353 			 * our note and, optionally, header.
354 			 */
355 			if (ret && bi_m == NULL && interp != NULL &&
356 			    (bi->interp_path == NULL ||
357 			    (strlen(bi->interp_path) + 1 != interp_name_len ||
358 			    strncmp(interp, bi->interp_path, interp_name_len)
359 			    != 0))) {
360 				bi_m = bi;
361 				ret = 0;
362 			}
363 			if (ret)
364 				return (bi);
365 		}
366 	}
367 	if (bi_m != NULL)
368 		return (bi_m);
369 
370 	/* If the executable has a brand, search for it in the brand list. */
371 	for (i = 0; i < MAX_BRANDS; i++) {
372 		bi = elf_brand_list[i];
373 		if (bi == NULL || (bi->flags & BI_BRAND_NOTE_MANDATORY) != 0 ||
374 		    (interp != NULL && (bi->flags & BI_BRAND_ONLY_STATIC) != 0))
375 			continue;
376 		if (hdr->e_machine == bi->machine &&
377 		    (hdr->e_ident[EI_OSABI] == bi->brand ||
378 		    (bi->compat_3_brand != NULL &&
379 		    strcmp((const char *)&hdr->e_ident[OLD_EI_BRAND],
380 		    bi->compat_3_brand) == 0))) {
381 			/* Looks good, but give brand a chance to veto */
382 			if (bi->header_supported == NULL ||
383 			    bi->header_supported(imgp, NULL, NULL)) {
384 				/*
385 				 * Again, prefer strictly matching
386 				 * interpreter path.
387 				 */
388 				if (interp_name_len == 0 &&
389 				    bi->interp_path == NULL)
390 					return (bi);
391 				if (bi->interp_path != NULL &&
392 				    strlen(bi->interp_path) + 1 ==
393 				    interp_name_len && strncmp(interp,
394 				    bi->interp_path, interp_name_len) == 0)
395 					return (bi);
396 				if (bi_m == NULL)
397 					bi_m = bi;
398 			}
399 		}
400 	}
401 	if (bi_m != NULL)
402 		return (bi_m);
403 
404 	/* No known brand, see if the header is recognized by any brand */
405 	for (i = 0; i < MAX_BRANDS; i++) {
406 		bi = elf_brand_list[i];
407 		if (bi == NULL || bi->flags & BI_BRAND_NOTE_MANDATORY ||
408 		    bi->header_supported == NULL)
409 			continue;
410 		if (hdr->e_machine == bi->machine) {
411 			ret = bi->header_supported(imgp, NULL, NULL);
412 			if (ret)
413 				return (bi);
414 		}
415 	}
416 
417 	/* Lacking a known brand, search for a recognized interpreter. */
418 	if (interp != NULL) {
419 		for (i = 0; i < MAX_BRANDS; i++) {
420 			bi = elf_brand_list[i];
421 			if (bi == NULL || (bi->flags &
422 			    (BI_BRAND_NOTE_MANDATORY | BI_BRAND_ONLY_STATIC))
423 			    != 0)
424 				continue;
425 			if (hdr->e_machine == bi->machine &&
426 			    bi->interp_path != NULL &&
427 			    /* ELF image p_filesz includes terminating zero */
428 			    strlen(bi->interp_path) + 1 == interp_name_len &&
429 			    strncmp(interp, bi->interp_path, interp_name_len)
430 			    == 0 && (bi->header_supported == NULL ||
431 			    bi->header_supported(imgp, NULL, NULL)))
432 				return (bi);
433 		}
434 	}
435 
436 	/* Lacking a recognized interpreter, try the default brand */
437 	for (i = 0; i < MAX_BRANDS; i++) {
438 		bi = elf_brand_list[i];
439 		if (bi == NULL || (bi->flags & BI_BRAND_NOTE_MANDATORY) != 0 ||
440 		    (interp != NULL && (bi->flags & BI_BRAND_ONLY_STATIC) != 0))
441 			continue;
442 		if (hdr->e_machine == bi->machine &&
443 		    __elfN(fallback_brand) == bi->brand &&
444 		    (bi->header_supported == NULL ||
445 		    bi->header_supported(imgp, NULL, NULL)))
446 			return (bi);
447 	}
448 	return (NULL);
449 }
450 
451 static bool
452 __elfN(phdr_in_zero_page)(const Elf_Ehdr *hdr)
453 {
454 	return (hdr->e_phoff <= PAGE_SIZE &&
455 	    (u_int)hdr->e_phentsize * hdr->e_phnum <= PAGE_SIZE - hdr->e_phoff);
456 }
457 
458 static int
459 __elfN(check_header)(const Elf_Ehdr *hdr)
460 {
461 	Elf_Brandinfo *bi;
462 	int i;
463 
464 	if (!IS_ELF(*hdr) ||
465 	    hdr->e_ident[EI_CLASS] != ELF_TARG_CLASS ||
466 	    hdr->e_ident[EI_DATA] != ELF_TARG_DATA ||
467 	    hdr->e_ident[EI_VERSION] != EV_CURRENT ||
468 	    hdr->e_phentsize != sizeof(Elf_Phdr) ||
469 	    hdr->e_version != ELF_TARG_VER)
470 		return (ENOEXEC);
471 
472 	/*
473 	 * Make sure we have at least one brand for this machine.
474 	 */
475 
476 	for (i = 0; i < MAX_BRANDS; i++) {
477 		bi = elf_brand_list[i];
478 		if (bi != NULL && bi->machine == hdr->e_machine)
479 			break;
480 	}
481 	if (i == MAX_BRANDS)
482 		return (ENOEXEC);
483 
484 	return (0);
485 }
486 
487 static int
488 __elfN(map_partial)(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
489     vm_offset_t start, vm_offset_t end, vm_prot_t prot)
490 {
491 	struct sf_buf *sf;
492 	int error;
493 	vm_offset_t off;
494 
495 	/*
496 	 * Create the page if it doesn't exist yet. Ignore errors.
497 	 */
498 	vm_map_fixed(map, NULL, 0, trunc_page(start), round_page(end) -
499 	    trunc_page(start), VM_PROT_ALL, VM_PROT_ALL, MAP_CHECK_EXCL);
500 
501 	/*
502 	 * Find the page from the underlying object.
503 	 */
504 	if (object != NULL) {
505 		sf = vm_imgact_map_page(object, offset);
506 		if (sf == NULL)
507 			return (KERN_FAILURE);
508 		off = offset - trunc_page(offset);
509 		error = copyout((caddr_t)sf_buf_kva(sf) + off, (caddr_t)start,
510 		    end - start);
511 		vm_imgact_unmap_page(sf);
512 		if (error != 0)
513 			return (KERN_FAILURE);
514 	}
515 
516 	return (KERN_SUCCESS);
517 }
518 
519 static int
520 __elfN(map_insert)(struct image_params *imgp, vm_map_t map, vm_object_t object,
521     vm_ooffset_t offset, vm_offset_t start, vm_offset_t end, vm_prot_t prot,
522     int cow)
523 {
524 	struct sf_buf *sf;
525 	vm_offset_t off;
526 	vm_size_t sz;
527 	int error, locked, rv;
528 
529 	if (start != trunc_page(start)) {
530 		rv = __elfN(map_partial)(map, object, offset, start,
531 		    round_page(start), prot);
532 		if (rv != KERN_SUCCESS)
533 			return (rv);
534 		offset += round_page(start) - start;
535 		start = round_page(start);
536 	}
537 	if (end != round_page(end)) {
538 		rv = __elfN(map_partial)(map, object, offset +
539 		    trunc_page(end) - start, trunc_page(end), end, prot);
540 		if (rv != KERN_SUCCESS)
541 			return (rv);
542 		end = trunc_page(end);
543 	}
544 	if (start >= end)
545 		return (KERN_SUCCESS);
546 	if ((offset & PAGE_MASK) != 0) {
547 		/*
548 		 * The mapping is not page aligned.  This means that we have
549 		 * to copy the data.
550 		 */
551 		rv = vm_map_fixed(map, NULL, 0, start, end - start,
552 		    prot | VM_PROT_WRITE, VM_PROT_ALL, MAP_CHECK_EXCL);
553 		if (rv != KERN_SUCCESS)
554 			return (rv);
555 		if (object == NULL)
556 			return (KERN_SUCCESS);
557 		for (; start < end; start += sz) {
558 			sf = vm_imgact_map_page(object, offset);
559 			if (sf == NULL)
560 				return (KERN_FAILURE);
561 			off = offset - trunc_page(offset);
562 			sz = end - start;
563 			if (sz > PAGE_SIZE - off)
564 				sz = PAGE_SIZE - off;
565 			error = copyout((caddr_t)sf_buf_kva(sf) + off,
566 			    (caddr_t)start, sz);
567 			vm_imgact_unmap_page(sf);
568 			if (error != 0)
569 				return (KERN_FAILURE);
570 			offset += sz;
571 		}
572 	} else {
573 		vm_object_reference(object);
574 		rv = vm_map_fixed(map, object, offset, start, end - start,
575 		    prot, VM_PROT_ALL, cow | MAP_CHECK_EXCL |
576 		    (object != NULL ? MAP_VN_EXEC : 0));
577 		if (rv != KERN_SUCCESS) {
578 			locked = VOP_ISLOCKED(imgp->vp);
579 			VOP_UNLOCK(imgp->vp);
580 			vm_object_deallocate(object);
581 			vn_lock(imgp->vp, locked | LK_RETRY);
582 			return (rv);
583 		} else if (object != NULL) {
584 			MPASS(imgp->vp->v_object == object);
585 			VOP_SET_TEXT_CHECKED(imgp->vp);
586 		}
587 	}
588 	return (KERN_SUCCESS);
589 }
590 
591 static int
592 __elfN(load_section)(struct image_params *imgp, vm_ooffset_t offset,
593     caddr_t vmaddr, size_t memsz, size_t filsz, vm_prot_t prot)
594 {
595 	struct sf_buf *sf;
596 	size_t map_len;
597 	vm_map_t map;
598 	vm_object_t object;
599 	vm_offset_t map_addr;
600 	int error, rv, cow;
601 	size_t copy_len;
602 	vm_ooffset_t file_addr;
603 
604 	/*
605 	 * It's necessary to fail if the filsz + offset taken from the
606 	 * header is greater than the actual file pager object's size.
607 	 * If we were to allow this, then the vm_map_find() below would
608 	 * walk right off the end of the file object and into the ether.
609 	 *
610 	 * While I'm here, might as well check for something else that
611 	 * is invalid: filsz cannot be greater than memsz.
612 	 */
613 	if ((filsz != 0 && (off_t)filsz + offset > imgp->attr->va_size) ||
614 	    filsz > memsz) {
615 		uprintf("elf_load_section: truncated ELF file\n");
616 		return (ENOEXEC);
617 	}
618 
619 	object = imgp->object;
620 	map = &imgp->proc->p_vmspace->vm_map;
621 	map_addr = trunc_page((vm_offset_t)vmaddr);
622 	file_addr = trunc_page(offset);
623 
624 	/*
625 	 * We have two choices.  We can either clear the data in the last page
626 	 * of an oversized mapping, or we can start the anon mapping a page
627 	 * early and copy the initialized data into that first page.  We
628 	 * choose the second.
629 	 */
630 	if (filsz == 0)
631 		map_len = 0;
632 	else if (memsz > filsz)
633 		map_len = trunc_page(offset + filsz) - file_addr;
634 	else
635 		map_len = round_page(offset + filsz) - file_addr;
636 
637 	if (map_len != 0) {
638 		/* cow flags: don't dump readonly sections in core */
639 		cow = MAP_COPY_ON_WRITE | MAP_PREFAULT |
640 		    (prot & VM_PROT_WRITE ? 0 : MAP_DISABLE_COREDUMP);
641 
642 		rv = __elfN(map_insert)(imgp, map, object, file_addr,
643 		    map_addr, map_addr + map_len, prot, cow);
644 		if (rv != KERN_SUCCESS)
645 			return (EINVAL);
646 
647 		/* we can stop now if we've covered it all */
648 		if (memsz == filsz)
649 			return (0);
650 	}
651 
652 	/*
653 	 * We have to get the remaining bit of the file into the first part
654 	 * of the oversized map segment.  This is normally because the .data
655 	 * segment in the file is extended to provide bss.  It's a neat idea
656 	 * to try and save a page, but it's a pain in the behind to implement.
657 	 */
658 	copy_len = filsz == 0 ? 0 : (offset + filsz) - trunc_page(offset +
659 	    filsz);
660 	map_addr = trunc_page((vm_offset_t)vmaddr + filsz);
661 	map_len = round_page((vm_offset_t)vmaddr + memsz) - map_addr;
662 
663 	/* This had damn well better be true! */
664 	if (map_len != 0) {
665 		rv = __elfN(map_insert)(imgp, map, NULL, 0, map_addr,
666 		    map_addr + map_len, prot, 0);
667 		if (rv != KERN_SUCCESS)
668 			return (EINVAL);
669 	}
670 
671 	if (copy_len != 0) {
672 		sf = vm_imgact_map_page(object, offset + filsz);
673 		if (sf == NULL)
674 			return (EIO);
675 
676 		/* send the page fragment to user space */
677 		error = copyout((caddr_t)sf_buf_kva(sf), (caddr_t)map_addr,
678 		    copy_len);
679 		vm_imgact_unmap_page(sf);
680 		if (error != 0)
681 			return (error);
682 	}
683 
684 	/*
685 	 * Remove write access to the page if it was only granted by map_insert
686 	 * to allow copyout.
687 	 */
688 	if ((prot & VM_PROT_WRITE) == 0)
689 		vm_map_protect(map, trunc_page(map_addr), round_page(map_addr +
690 		    map_len), prot, FALSE);
691 
692 	return (0);
693 }
694 
695 static int
696 __elfN(load_sections)(struct image_params *imgp, const Elf_Ehdr *hdr,
697     const Elf_Phdr *phdr, u_long rbase, u_long *base_addrp)
698 {
699 	vm_prot_t prot;
700 	u_long base_addr;
701 	bool first;
702 	int error, i;
703 
704 	ASSERT_VOP_LOCKED(imgp->vp, __func__);
705 
706 	base_addr = 0;
707 	first = true;
708 
709 	for (i = 0; i < hdr->e_phnum; i++) {
710 		if (phdr[i].p_type != PT_LOAD || phdr[i].p_memsz == 0)
711 			continue;
712 
713 		/* Loadable segment */
714 		prot = __elfN(trans_prot)(phdr[i].p_flags);
715 		error = __elfN(load_section)(imgp, phdr[i].p_offset,
716 		    (caddr_t)(uintptr_t)phdr[i].p_vaddr + rbase,
717 		    phdr[i].p_memsz, phdr[i].p_filesz, prot);
718 		if (error != 0)
719 			return (error);
720 
721 		/*
722 		 * Establish the base address if this is the first segment.
723 		 */
724 		if (first) {
725   			base_addr = trunc_page(phdr[i].p_vaddr + rbase);
726 			first = false;
727 		}
728 	}
729 
730 	if (base_addrp != NULL)
731 		*base_addrp = base_addr;
732 
733 	return (0);
734 }
735 
736 /*
737  * Load the file "file" into memory.  It may be either a shared object
738  * or an executable.
739  *
740  * The "addr" reference parameter is in/out.  On entry, it specifies
741  * the address where a shared object should be loaded.  If the file is
742  * an executable, this value is ignored.  On exit, "addr" specifies
743  * where the file was actually loaded.
744  *
745  * The "entry" reference parameter is out only.  On exit, it specifies
746  * the entry point for the loaded file.
747  */
748 static int
749 __elfN(load_file)(struct proc *p, const char *file, u_long *addr,
750 	u_long *entry)
751 {
752 	struct {
753 		struct nameidata nd;
754 		struct vattr attr;
755 		struct image_params image_params;
756 	} *tempdata;
757 	const Elf_Ehdr *hdr = NULL;
758 	const Elf_Phdr *phdr = NULL;
759 	struct nameidata *nd;
760 	struct vattr *attr;
761 	struct image_params *imgp;
762 	u_long rbase;
763 	u_long base_addr = 0;
764 	int error;
765 
766 #ifdef CAPABILITY_MODE
767 	/*
768 	 * XXXJA: This check can go away once we are sufficiently confident
769 	 * that the checks in namei() are correct.
770 	 */
771 	if (IN_CAPABILITY_MODE(curthread))
772 		return (ECAPMODE);
773 #endif
774 
775 	tempdata = malloc(sizeof(*tempdata), M_TEMP, M_WAITOK | M_ZERO);
776 	nd = &tempdata->nd;
777 	attr = &tempdata->attr;
778 	imgp = &tempdata->image_params;
779 
780 	/*
781 	 * Initialize part of the common data
782 	 */
783 	imgp->proc = p;
784 	imgp->attr = attr;
785 
786 	NDINIT(nd, LOOKUP, ISOPEN | FOLLOW | LOCKSHARED | LOCKLEAF,
787 	    UIO_SYSSPACE, file, curthread);
788 	if ((error = namei(nd)) != 0) {
789 		nd->ni_vp = NULL;
790 		goto fail;
791 	}
792 	NDFREE(nd, NDF_ONLY_PNBUF);
793 	imgp->vp = nd->ni_vp;
794 
795 	/*
796 	 * Check permissions, modes, uid, etc on the file, and "open" it.
797 	 */
798 	error = exec_check_permissions(imgp);
799 	if (error)
800 		goto fail;
801 
802 	error = exec_map_first_page(imgp);
803 	if (error)
804 		goto fail;
805 
806 	imgp->object = nd->ni_vp->v_object;
807 
808 	hdr = (const Elf_Ehdr *)imgp->image_header;
809 	if ((error = __elfN(check_header)(hdr)) != 0)
810 		goto fail;
811 	if (hdr->e_type == ET_DYN)
812 		rbase = *addr;
813 	else if (hdr->e_type == ET_EXEC)
814 		rbase = 0;
815 	else {
816 		error = ENOEXEC;
817 		goto fail;
818 	}
819 
820 	/* Only support headers that fit within first page for now      */
821 	if (!__elfN(phdr_in_zero_page)(hdr)) {
822 		error = ENOEXEC;
823 		goto fail;
824 	}
825 
826 	phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
827 	if (!aligned(phdr, Elf_Addr)) {
828 		error = ENOEXEC;
829 		goto fail;
830 	}
831 
832 	error = __elfN(load_sections)(imgp, hdr, phdr, rbase, &base_addr);
833 	if (error != 0)
834 		goto fail;
835 
836 	*addr = base_addr;
837 	*entry = (unsigned long)hdr->e_entry + rbase;
838 
839 fail:
840 	if (imgp->firstpage)
841 		exec_unmap_first_page(imgp);
842 
843 	if (nd->ni_vp) {
844 		if (imgp->textset)
845 			VOP_UNSET_TEXT_CHECKED(nd->ni_vp);
846 		vput(nd->ni_vp);
847 	}
848 	free(tempdata, M_TEMP);
849 
850 	return (error);
851 }
852 
853 static u_long
854 __CONCAT(rnd_, __elfN(base))(vm_map_t map __unused, u_long minv, u_long maxv,
855     u_int align)
856 {
857 	u_long rbase, res;
858 
859 	MPASS(vm_map_min(map) <= minv);
860 	MPASS(maxv <= vm_map_max(map));
861 	MPASS(minv < maxv);
862 	MPASS(minv + align < maxv);
863 	arc4rand(&rbase, sizeof(rbase), 0);
864 	res = roundup(minv, (u_long)align) + rbase % (maxv - minv);
865 	res &= ~((u_long)align - 1);
866 	if (res >= maxv)
867 		res -= align;
868 	KASSERT(res >= minv,
869 	    ("res %#lx < minv %#lx, maxv %#lx rbase %#lx",
870 	    res, minv, maxv, rbase));
871 	KASSERT(res < maxv,
872 	    ("res %#lx > maxv %#lx, minv %#lx rbase %#lx",
873 	    res, maxv, minv, rbase));
874 	return (res);
875 }
876 
877 static int
878 __elfN(enforce_limits)(struct image_params *imgp, const Elf_Ehdr *hdr,
879     const Elf_Phdr *phdr, u_long et_dyn_addr)
880 {
881 	struct vmspace *vmspace;
882 	const char *err_str;
883 	u_long text_size, data_size, total_size, text_addr, data_addr;
884 	u_long seg_size, seg_addr;
885 	int i;
886 
887 	err_str = NULL;
888 	text_size = data_size = total_size = text_addr = data_addr = 0;
889 
890 	for (i = 0; i < hdr->e_phnum; i++) {
891 		if (phdr[i].p_type != PT_LOAD || phdr[i].p_memsz == 0)
892 			continue;
893 
894 		seg_addr = trunc_page(phdr[i].p_vaddr + et_dyn_addr);
895 		seg_size = round_page(phdr[i].p_memsz +
896 		    phdr[i].p_vaddr + et_dyn_addr - seg_addr);
897 
898 		/*
899 		 * Make the largest executable segment the official
900 		 * text segment and all others data.
901 		 *
902 		 * Note that obreak() assumes that data_addr + data_size == end
903 		 * of data load area, and the ELF file format expects segments
904 		 * to be sorted by address.  If multiple data segments exist,
905 		 * the last one will be used.
906 		 */
907 
908 		if ((phdr[i].p_flags & PF_X) != 0 && text_size < seg_size) {
909 			text_size = seg_size;
910 			text_addr = seg_addr;
911 		} else {
912 			data_size = seg_size;
913 			data_addr = seg_addr;
914 		}
915 		total_size += seg_size;
916 	}
917 
918 	if (data_addr == 0 && data_size == 0) {
919 		data_addr = text_addr;
920 		data_size = text_size;
921 	}
922 
923 	/*
924 	 * Check limits.  It should be safe to check the
925 	 * limits after loading the segments since we do
926 	 * not actually fault in all the segments pages.
927 	 */
928 	PROC_LOCK(imgp->proc);
929 	if (data_size > lim_cur_proc(imgp->proc, RLIMIT_DATA))
930 		err_str = "Data segment size exceeds process limit";
931 	else if (text_size > maxtsiz)
932 		err_str = "Text segment size exceeds system limit";
933 	else if (total_size > lim_cur_proc(imgp->proc, RLIMIT_VMEM))
934 		err_str = "Total segment size exceeds process limit";
935 	else if (racct_set(imgp->proc, RACCT_DATA, data_size) != 0)
936 		err_str = "Data segment size exceeds resource limit";
937 	else if (racct_set(imgp->proc, RACCT_VMEM, total_size) != 0)
938 		err_str = "Total segment size exceeds resource limit";
939 	PROC_UNLOCK(imgp->proc);
940 	if (err_str != NULL) {
941 		uprintf("%s\n", err_str);
942 		return (ENOMEM);
943 	}
944 
945 	vmspace = imgp->proc->p_vmspace;
946 	vmspace->vm_tsize = text_size >> PAGE_SHIFT;
947 	vmspace->vm_taddr = (caddr_t)(uintptr_t)text_addr;
948 	vmspace->vm_dsize = data_size >> PAGE_SHIFT;
949 	vmspace->vm_daddr = (caddr_t)(uintptr_t)data_addr;
950 
951 	return (0);
952 }
953 
954 static int
955 __elfN(get_interp)(struct image_params *imgp, const Elf_Phdr *phdr,
956     char **interpp, bool *free_interpp)
957 {
958 	struct thread *td;
959 	char *interp;
960 	int error, interp_name_len;
961 
962 	KASSERT(phdr->p_type == PT_INTERP,
963 	    ("%s: p_type %u != PT_INTERP", __func__, phdr->p_type));
964 	ASSERT_VOP_LOCKED(imgp->vp, __func__);
965 
966 	td = curthread;
967 
968 	/* Path to interpreter */
969 	if (phdr->p_filesz < 2 || phdr->p_filesz > MAXPATHLEN) {
970 		uprintf("Invalid PT_INTERP\n");
971 		return (ENOEXEC);
972 	}
973 
974 	interp_name_len = phdr->p_filesz;
975 	if (phdr->p_offset > PAGE_SIZE ||
976 	    interp_name_len > PAGE_SIZE - phdr->p_offset) {
977 		/*
978 		 * The vnode lock might be needed by the pagedaemon to
979 		 * clean pages owned by the vnode.  Do not allow sleep
980 		 * waiting for memory with the vnode locked, instead
981 		 * try non-sleepable allocation first, and if it
982 		 * fails, go to the slow path were we drop the lock
983 		 * and do M_WAITOK.  A text reference prevents
984 		 * modifications to the vnode content.
985 		 */
986 		interp = malloc(interp_name_len + 1, M_TEMP, M_NOWAIT);
987 		if (interp == NULL) {
988 			VOP_UNLOCK(imgp->vp);
989 			interp = malloc(interp_name_len + 1, M_TEMP, M_WAITOK);
990 			vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
991 		}
992 
993 		error = vn_rdwr(UIO_READ, imgp->vp, interp,
994 		    interp_name_len, phdr->p_offset,
995 		    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred,
996 		    NOCRED, NULL, td);
997 		if (error != 0) {
998 			free(interp, M_TEMP);
999 			uprintf("i/o error PT_INTERP %d\n", error);
1000 			return (error);
1001 		}
1002 		interp[interp_name_len] = '\0';
1003 
1004 		*interpp = interp;
1005 		*free_interpp = true;
1006 		return (0);
1007 	}
1008 
1009 	interp = __DECONST(char *, imgp->image_header) + phdr->p_offset;
1010 	if (interp[interp_name_len - 1] != '\0') {
1011 		uprintf("Invalid PT_INTERP\n");
1012 		return (ENOEXEC);
1013 	}
1014 
1015 	*interpp = interp;
1016 	*free_interpp = false;
1017 	return (0);
1018 }
1019 
1020 static int
1021 __elfN(load_interp)(struct image_params *imgp, const Elf_Brandinfo *brand_info,
1022     const char *interp, u_long *addr, u_long *entry)
1023 {
1024 	char *path;
1025 	int error;
1026 
1027 	if (brand_info->emul_path != NULL &&
1028 	    brand_info->emul_path[0] != '\0') {
1029 		path = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1030 		snprintf(path, MAXPATHLEN, "%s%s",
1031 		    brand_info->emul_path, interp);
1032 		error = __elfN(load_file)(imgp->proc, path, addr, entry);
1033 		free(path, M_TEMP);
1034 		if (error == 0)
1035 			return (0);
1036 	}
1037 
1038 	if (brand_info->interp_newpath != NULL &&
1039 	    (brand_info->interp_path == NULL ||
1040 	    strcmp(interp, brand_info->interp_path) == 0)) {
1041 		error = __elfN(load_file)(imgp->proc,
1042 		    brand_info->interp_newpath, addr, entry);
1043 		if (error == 0)
1044 			return (0);
1045 	}
1046 
1047 	error = __elfN(load_file)(imgp->proc, interp, addr, entry);
1048 	if (error == 0)
1049 		return (0);
1050 
1051 	uprintf("ELF interpreter %s not found, error %d\n", interp, error);
1052 	return (error);
1053 }
1054 
1055 /*
1056  * Impossible et_dyn_addr initial value indicating that the real base
1057  * must be calculated later with some randomization applied.
1058  */
1059 #define	ET_DYN_ADDR_RAND	1
1060 
1061 static int
1062 __CONCAT(exec_, __elfN(imgact))(struct image_params *imgp)
1063 {
1064 	struct thread *td;
1065 	const Elf_Ehdr *hdr;
1066 	const Elf_Phdr *phdr;
1067 	Elf_Auxargs *elf_auxargs;
1068 	struct vmspace *vmspace;
1069 	vm_map_t map;
1070 	char *interp;
1071 	Elf_Brandinfo *brand_info;
1072 	struct sysentvec *sv;
1073 	u_long addr, baddr, et_dyn_addr, entry, proghdr;
1074 	u_long maxalign, mapsz, maxv, maxv1;
1075 	uint32_t fctl0;
1076 	int32_t osrel;
1077 	bool free_interp;
1078 	int error, i, n;
1079 
1080 	hdr = (const Elf_Ehdr *)imgp->image_header;
1081 
1082 	/*
1083 	 * Do we have a valid ELF header ?
1084 	 *
1085 	 * Only allow ET_EXEC & ET_DYN here, reject ET_DYN later
1086 	 * if particular brand doesn't support it.
1087 	 */
1088 	if (__elfN(check_header)(hdr) != 0 ||
1089 	    (hdr->e_type != ET_EXEC && hdr->e_type != ET_DYN))
1090 		return (-1);
1091 
1092 	/*
1093 	 * From here on down, we return an errno, not -1, as we've
1094 	 * detected an ELF file.
1095 	 */
1096 
1097 	if (!__elfN(phdr_in_zero_page)(hdr)) {
1098 		uprintf("Program headers not in the first page\n");
1099 		return (ENOEXEC);
1100 	}
1101 	phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
1102 	if (!aligned(phdr, Elf_Addr)) {
1103 		uprintf("Unaligned program headers\n");
1104 		return (ENOEXEC);
1105 	}
1106 
1107 	n = error = 0;
1108 	baddr = 0;
1109 	osrel = 0;
1110 	fctl0 = 0;
1111 	entry = proghdr = 0;
1112 	interp = NULL;
1113 	free_interp = false;
1114 	td = curthread;
1115 	maxalign = PAGE_SIZE;
1116 	mapsz = 0;
1117 
1118 	for (i = 0; i < hdr->e_phnum; i++) {
1119 		switch (phdr[i].p_type) {
1120 		case PT_LOAD:
1121 			if (n == 0)
1122 				baddr = phdr[i].p_vaddr;
1123 			if (phdr[i].p_align > maxalign)
1124 				maxalign = phdr[i].p_align;
1125 			mapsz += phdr[i].p_memsz;
1126 			n++;
1127 
1128 			/*
1129 			 * If this segment contains the program headers,
1130 			 * remember their virtual address for the AT_PHDR
1131 			 * aux entry. Static binaries don't usually include
1132 			 * a PT_PHDR entry.
1133 			 */
1134 			if (phdr[i].p_offset == 0 &&
1135 			    hdr->e_phoff + hdr->e_phnum * hdr->e_phentsize
1136 				<= phdr[i].p_filesz)
1137 				proghdr = phdr[i].p_vaddr + hdr->e_phoff;
1138 			break;
1139 		case PT_INTERP:
1140 			/* Path to interpreter */
1141 			if (interp != NULL) {
1142 				uprintf("Multiple PT_INTERP headers\n");
1143 				error = ENOEXEC;
1144 				goto ret;
1145 			}
1146 			error = __elfN(get_interp)(imgp, &phdr[i], &interp,
1147 			    &free_interp);
1148 			if (error != 0)
1149 				goto ret;
1150 			break;
1151 		case PT_GNU_STACK:
1152 			if (__elfN(nxstack))
1153 				imgp->stack_prot =
1154 				    __elfN(trans_prot)(phdr[i].p_flags);
1155 			imgp->stack_sz = phdr[i].p_memsz;
1156 			break;
1157 		case PT_PHDR: 	/* Program header table info */
1158 			proghdr = phdr[i].p_vaddr;
1159 			break;
1160 		}
1161 	}
1162 
1163 	brand_info = __elfN(get_brandinfo)(imgp, interp, &osrel, &fctl0);
1164 	if (brand_info == NULL) {
1165 		uprintf("ELF binary type \"%u\" not known.\n",
1166 		    hdr->e_ident[EI_OSABI]);
1167 		error = ENOEXEC;
1168 		goto ret;
1169 	}
1170 	sv = brand_info->sysvec;
1171 	et_dyn_addr = 0;
1172 	if (hdr->e_type == ET_DYN) {
1173 		if ((brand_info->flags & BI_CAN_EXEC_DYN) == 0) {
1174 			uprintf("Cannot execute shared object\n");
1175 			error = ENOEXEC;
1176 			goto ret;
1177 		}
1178 		/*
1179 		 * Honour the base load address from the dso if it is
1180 		 * non-zero for some reason.
1181 		 */
1182 		if (baddr == 0) {
1183 			if ((sv->sv_flags & SV_ASLR) == 0 ||
1184 			    (fctl0 & NT_FREEBSD_FCTL_ASLR_DISABLE) != 0)
1185 				et_dyn_addr = __elfN(pie_base);
1186 			else if ((__elfN(pie_aslr_enabled) &&
1187 			    (imgp->proc->p_flag2 & P2_ASLR_DISABLE) == 0) ||
1188 			    (imgp->proc->p_flag2 & P2_ASLR_ENABLE) != 0)
1189 				et_dyn_addr = ET_DYN_ADDR_RAND;
1190 			else
1191 				et_dyn_addr = __elfN(pie_base);
1192 		}
1193 	}
1194 
1195 	/*
1196 	 * Avoid a possible deadlock if the current address space is destroyed
1197 	 * and that address space maps the locked vnode.  In the common case,
1198 	 * the locked vnode's v_usecount is decremented but remains greater
1199 	 * than zero.  Consequently, the vnode lock is not needed by vrele().
1200 	 * However, in cases where the vnode lock is external, such as nullfs,
1201 	 * v_usecount may become zero.
1202 	 *
1203 	 * The VV_TEXT flag prevents modifications to the executable while
1204 	 * the vnode is unlocked.
1205 	 */
1206 	VOP_UNLOCK(imgp->vp);
1207 
1208 	/*
1209 	 * Decide whether to enable randomization of user mappings.
1210 	 * First, reset user preferences for the setid binaries.
1211 	 * Then, account for the support of the randomization by the
1212 	 * ABI, by user preferences, and make special treatment for
1213 	 * PIE binaries.
1214 	 */
1215 	if (imgp->credential_setid) {
1216 		PROC_LOCK(imgp->proc);
1217 		imgp->proc->p_flag2 &= ~(P2_ASLR_ENABLE | P2_ASLR_DISABLE);
1218 		PROC_UNLOCK(imgp->proc);
1219 	}
1220 	if ((sv->sv_flags & SV_ASLR) == 0 ||
1221 	    (imgp->proc->p_flag2 & P2_ASLR_DISABLE) != 0 ||
1222 	    (fctl0 & NT_FREEBSD_FCTL_ASLR_DISABLE) != 0) {
1223 		KASSERT(et_dyn_addr != ET_DYN_ADDR_RAND,
1224 		    ("et_dyn_addr == RAND and !ASLR"));
1225 	} else if ((imgp->proc->p_flag2 & P2_ASLR_ENABLE) != 0 ||
1226 	    (__elfN(aslr_enabled) && hdr->e_type == ET_EXEC) ||
1227 	    et_dyn_addr == ET_DYN_ADDR_RAND) {
1228 		imgp->map_flags |= MAP_ASLR;
1229 		/*
1230 		 * If user does not care about sbrk, utilize the bss
1231 		 * grow region for mappings as well.  We can select
1232 		 * the base for the image anywere and still not suffer
1233 		 * from the fragmentation.
1234 		 */
1235 		if (!__elfN(aslr_honor_sbrk) ||
1236 		    (imgp->proc->p_flag2 & P2_ASLR_IGNSTART) != 0)
1237 			imgp->map_flags |= MAP_ASLR_IGNSTART;
1238 	}
1239 
1240 	error = exec_new_vmspace(imgp, sv);
1241 	vmspace = imgp->proc->p_vmspace;
1242 	map = &vmspace->vm_map;
1243 
1244 	imgp->proc->p_sysent = sv;
1245 
1246 	maxv = vm_map_max(map) - lim_max(td, RLIMIT_STACK);
1247 	if (et_dyn_addr == ET_DYN_ADDR_RAND) {
1248 		KASSERT((map->flags & MAP_ASLR) != 0,
1249 		    ("ET_DYN_ADDR_RAND but !MAP_ASLR"));
1250 		et_dyn_addr = __CONCAT(rnd_, __elfN(base))(map,
1251 		    vm_map_min(map) + mapsz + lim_max(td, RLIMIT_DATA),
1252 		    /* reserve half of the address space to interpreter */
1253 		    maxv / 2, 1UL << flsl(maxalign));
1254 	}
1255 
1256 	vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
1257 	if (error != 0)
1258 		goto ret;
1259 
1260 	error = __elfN(load_sections)(imgp, hdr, phdr, et_dyn_addr, NULL);
1261 	if (error != 0)
1262 		goto ret;
1263 
1264 	error = __elfN(enforce_limits)(imgp, hdr, phdr, et_dyn_addr);
1265 	if (error != 0)
1266 		goto ret;
1267 
1268 	entry = (u_long)hdr->e_entry + et_dyn_addr;
1269 
1270 	/*
1271 	 * We load the dynamic linker where a userland call
1272 	 * to mmap(0, ...) would put it.  The rationale behind this
1273 	 * calculation is that it leaves room for the heap to grow to
1274 	 * its maximum allowed size.
1275 	 */
1276 	addr = round_page((vm_offset_t)vmspace->vm_daddr + lim_max(td,
1277 	    RLIMIT_DATA));
1278 	if ((map->flags & MAP_ASLR) != 0) {
1279 		maxv1 = maxv / 2 + addr / 2;
1280 		MPASS(maxv1 >= addr);	/* No overflow */
1281 		map->anon_loc = __CONCAT(rnd_, __elfN(base))(map, addr, maxv1,
1282 		    MAXPAGESIZES > 1 ? pagesizes[1] : pagesizes[0]);
1283 	} else {
1284 		map->anon_loc = addr;
1285 	}
1286 
1287 	imgp->entry_addr = entry;
1288 
1289 	if (interp != NULL) {
1290 		VOP_UNLOCK(imgp->vp);
1291 		if ((map->flags & MAP_ASLR) != 0) {
1292 			/* Assume that interpeter fits into 1/4 of AS */
1293 			maxv1 = maxv / 2 + addr / 2;
1294 			MPASS(maxv1 >= addr);	/* No overflow */
1295 			addr = __CONCAT(rnd_, __elfN(base))(map, addr,
1296 			    maxv1, PAGE_SIZE);
1297 		}
1298 		error = __elfN(load_interp)(imgp, brand_info, interp, &addr,
1299 		    &imgp->entry_addr);
1300 		vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
1301 		if (error != 0)
1302 			goto ret;
1303 	} else
1304 		addr = et_dyn_addr;
1305 
1306 	/*
1307 	 * Construct auxargs table (used by the copyout_auxargs routine)
1308 	 */
1309 	elf_auxargs = malloc(sizeof(Elf_Auxargs), M_TEMP, M_NOWAIT);
1310 	if (elf_auxargs == NULL) {
1311 		VOP_UNLOCK(imgp->vp);
1312 		elf_auxargs = malloc(sizeof(Elf_Auxargs), M_TEMP, M_WAITOK);
1313 		vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
1314 	}
1315 	elf_auxargs->execfd = -1;
1316 	elf_auxargs->phdr = proghdr + et_dyn_addr;
1317 	elf_auxargs->phent = hdr->e_phentsize;
1318 	elf_auxargs->phnum = hdr->e_phnum;
1319 	elf_auxargs->pagesz = PAGE_SIZE;
1320 	elf_auxargs->base = addr;
1321 	elf_auxargs->flags = 0;
1322 	elf_auxargs->entry = entry;
1323 	elf_auxargs->hdr_eflags = hdr->e_flags;
1324 
1325 	imgp->auxargs = elf_auxargs;
1326 	imgp->interpreted = 0;
1327 	imgp->reloc_base = addr;
1328 	imgp->proc->p_osrel = osrel;
1329 	imgp->proc->p_fctl0 = fctl0;
1330 	imgp->proc->p_elf_machine = hdr->e_machine;
1331 	imgp->proc->p_elf_flags = hdr->e_flags;
1332 
1333 ret:
1334 	if (free_interp)
1335 		free(interp, M_TEMP);
1336 	return (error);
1337 }
1338 
1339 #define	suword __CONCAT(suword, __ELF_WORD_SIZE)
1340 
1341 int
1342 __elfN(freebsd_copyout_auxargs)(struct image_params *imgp, uintptr_t base)
1343 {
1344 	Elf_Auxargs *args = (Elf_Auxargs *)imgp->auxargs;
1345 	Elf_Auxinfo *argarray, *pos;
1346 	int error;
1347 
1348 	argarray = pos = malloc(AT_COUNT * sizeof(*pos), M_TEMP,
1349 	    M_WAITOK | M_ZERO);
1350 
1351 	if (args->execfd != -1)
1352 		AUXARGS_ENTRY(pos, AT_EXECFD, args->execfd);
1353 	AUXARGS_ENTRY(pos, AT_PHDR, args->phdr);
1354 	AUXARGS_ENTRY(pos, AT_PHENT, args->phent);
1355 	AUXARGS_ENTRY(pos, AT_PHNUM, args->phnum);
1356 	AUXARGS_ENTRY(pos, AT_PAGESZ, args->pagesz);
1357 	AUXARGS_ENTRY(pos, AT_FLAGS, args->flags);
1358 	AUXARGS_ENTRY(pos, AT_ENTRY, args->entry);
1359 	AUXARGS_ENTRY(pos, AT_BASE, args->base);
1360 	AUXARGS_ENTRY(pos, AT_EHDRFLAGS, args->hdr_eflags);
1361 	if (imgp->execpathp != 0)
1362 		AUXARGS_ENTRY_PTR(pos, AT_EXECPATH, imgp->execpathp);
1363 	AUXARGS_ENTRY(pos, AT_OSRELDATE,
1364 	    imgp->proc->p_ucred->cr_prison->pr_osreldate);
1365 	if (imgp->canary != 0) {
1366 		AUXARGS_ENTRY_PTR(pos, AT_CANARY, imgp->canary);
1367 		AUXARGS_ENTRY(pos, AT_CANARYLEN, imgp->canarylen);
1368 	}
1369 	AUXARGS_ENTRY(pos, AT_NCPUS, mp_ncpus);
1370 	if (imgp->pagesizes != 0) {
1371 		AUXARGS_ENTRY_PTR(pos, AT_PAGESIZES, imgp->pagesizes);
1372 		AUXARGS_ENTRY(pos, AT_PAGESIZESLEN, imgp->pagesizeslen);
1373 	}
1374 	if (imgp->sysent->sv_timekeep_base != 0) {
1375 		AUXARGS_ENTRY(pos, AT_TIMEKEEP,
1376 		    imgp->sysent->sv_timekeep_base);
1377 	}
1378 	AUXARGS_ENTRY(pos, AT_STACKPROT, imgp->sysent->sv_shared_page_obj
1379 	    != NULL && imgp->stack_prot != 0 ? imgp->stack_prot :
1380 	    imgp->sysent->sv_stackprot);
1381 	if (imgp->sysent->sv_hwcap != NULL)
1382 		AUXARGS_ENTRY(pos, AT_HWCAP, *imgp->sysent->sv_hwcap);
1383 	if (imgp->sysent->sv_hwcap2 != NULL)
1384 		AUXARGS_ENTRY(pos, AT_HWCAP2, *imgp->sysent->sv_hwcap2);
1385 	AUXARGS_ENTRY(pos, AT_BSDFLAGS, __elfN(sigfastblock) ?
1386 	    ELF_BSDF_SIGFASTBLK : 0);
1387 	AUXARGS_ENTRY(pos, AT_ARGC, imgp->args->argc);
1388 	AUXARGS_ENTRY_PTR(pos, AT_ARGV, imgp->argv);
1389 	AUXARGS_ENTRY(pos, AT_ENVC, imgp->args->envc);
1390 	AUXARGS_ENTRY_PTR(pos, AT_ENVV, imgp->envv);
1391 	AUXARGS_ENTRY_PTR(pos, AT_PS_STRINGS, imgp->ps_strings);
1392 	AUXARGS_ENTRY(pos, AT_NULL, 0);
1393 
1394 	free(imgp->auxargs, M_TEMP);
1395 	imgp->auxargs = NULL;
1396 	KASSERT(pos - argarray <= AT_COUNT, ("Too many auxargs"));
1397 
1398 	error = copyout(argarray, (void *)base, sizeof(*argarray) * AT_COUNT);
1399 	free(argarray, M_TEMP);
1400 	return (error);
1401 }
1402 
1403 int
1404 __elfN(freebsd_fixup)(uintptr_t *stack_base, struct image_params *imgp)
1405 {
1406 	Elf_Addr *base;
1407 
1408 	base = (Elf_Addr *)*stack_base;
1409 	base--;
1410 	if (suword(base, imgp->args->argc) == -1)
1411 		return (EFAULT);
1412 	*stack_base = (uintptr_t)base;
1413 	return (0);
1414 }
1415 
1416 /*
1417  * Code for generating ELF core dumps.
1418  */
1419 
1420 typedef void (*segment_callback)(vm_map_entry_t, void *);
1421 
1422 /* Closure for cb_put_phdr(). */
1423 struct phdr_closure {
1424 	Elf_Phdr *phdr;		/* Program header to fill in */
1425 	Elf_Off offset;		/* Offset of segment in core file */
1426 };
1427 
1428 /* Closure for cb_size_segment(). */
1429 struct sseg_closure {
1430 	int count;		/* Count of writable segments. */
1431 	size_t size;		/* Total size of all writable segments. */
1432 };
1433 
1434 typedef void (*outfunc_t)(void *, struct sbuf *, size_t *);
1435 
1436 struct note_info {
1437 	int		type;		/* Note type. */
1438 	outfunc_t 	outfunc; 	/* Output function. */
1439 	void		*outarg;	/* Argument for the output function. */
1440 	size_t		outsize;	/* Output size. */
1441 	TAILQ_ENTRY(note_info) link;	/* Link to the next note info. */
1442 };
1443 
1444 TAILQ_HEAD(note_info_list, note_info);
1445 
1446 /* Coredump output parameters. */
1447 struct coredump_params {
1448 	off_t		offset;
1449 	struct ucred	*active_cred;
1450 	struct ucred	*file_cred;
1451 	struct thread	*td;
1452 	struct vnode	*vp;
1453 	struct compressor *comp;
1454 };
1455 
1456 extern int compress_user_cores;
1457 extern int compress_user_cores_level;
1458 
1459 static void cb_put_phdr(vm_map_entry_t, void *);
1460 static void cb_size_segment(vm_map_entry_t, void *);
1461 static int core_write(struct coredump_params *, const void *, size_t, off_t,
1462     enum uio_seg, size_t *);
1463 static void each_dumpable_segment(struct thread *, segment_callback, void *);
1464 static int __elfN(corehdr)(struct coredump_params *, int, void *, size_t,
1465     struct note_info_list *, size_t);
1466 static void __elfN(prepare_notes)(struct thread *, struct note_info_list *,
1467     size_t *);
1468 static void __elfN(puthdr)(struct thread *, void *, size_t, int, size_t);
1469 static void __elfN(putnote)(struct note_info *, struct sbuf *);
1470 static size_t register_note(struct note_info_list *, int, outfunc_t, void *);
1471 static int sbuf_drain_core_output(void *, const char *, int);
1472 
1473 static void __elfN(note_fpregset)(void *, struct sbuf *, size_t *);
1474 static void __elfN(note_prpsinfo)(void *, struct sbuf *, size_t *);
1475 static void __elfN(note_prstatus)(void *, struct sbuf *, size_t *);
1476 static void __elfN(note_threadmd)(void *, struct sbuf *, size_t *);
1477 static void __elfN(note_thrmisc)(void *, struct sbuf *, size_t *);
1478 static void __elfN(note_ptlwpinfo)(void *, struct sbuf *, size_t *);
1479 static void __elfN(note_procstat_auxv)(void *, struct sbuf *, size_t *);
1480 static void __elfN(note_procstat_proc)(void *, struct sbuf *, size_t *);
1481 static void __elfN(note_procstat_psstrings)(void *, struct sbuf *, size_t *);
1482 static void note_procstat_files(void *, struct sbuf *, size_t *);
1483 static void note_procstat_groups(void *, struct sbuf *, size_t *);
1484 static void note_procstat_osrel(void *, struct sbuf *, size_t *);
1485 static void note_procstat_rlimit(void *, struct sbuf *, size_t *);
1486 static void note_procstat_umask(void *, struct sbuf *, size_t *);
1487 static void note_procstat_vmmap(void *, struct sbuf *, size_t *);
1488 
1489 /*
1490  * Write out a core segment to the compression stream.
1491  */
1492 static int
1493 compress_chunk(struct coredump_params *p, char *base, char *buf, u_int len)
1494 {
1495 	u_int chunk_len;
1496 	int error;
1497 
1498 	while (len > 0) {
1499 		chunk_len = MIN(len, CORE_BUF_SIZE);
1500 
1501 		/*
1502 		 * We can get EFAULT error here.
1503 		 * In that case zero out the current chunk of the segment.
1504 		 */
1505 		error = copyin(base, buf, chunk_len);
1506 		if (error != 0)
1507 			bzero(buf, chunk_len);
1508 		error = compressor_write(p->comp, buf, chunk_len);
1509 		if (error != 0)
1510 			break;
1511 		base += chunk_len;
1512 		len -= chunk_len;
1513 	}
1514 	return (error);
1515 }
1516 
1517 static int
1518 core_compressed_write(void *base, size_t len, off_t offset, void *arg)
1519 {
1520 
1521 	return (core_write((struct coredump_params *)arg, base, len, offset,
1522 	    UIO_SYSSPACE, NULL));
1523 }
1524 
1525 static int
1526 core_write(struct coredump_params *p, const void *base, size_t len,
1527     off_t offset, enum uio_seg seg, size_t *resid)
1528 {
1529 
1530 	return (vn_rdwr_inchunks(UIO_WRITE, p->vp, __DECONST(void *, base),
1531 	    len, offset, seg, IO_UNIT | IO_DIRECT | IO_RANGELOCKED,
1532 	    p->active_cred, p->file_cred, resid, p->td));
1533 }
1534 
1535 static int
1536 core_output(char *base, size_t len, off_t offset, struct coredump_params *p,
1537     void *tmpbuf)
1538 {
1539 	vm_map_t map;
1540 	struct mount *mp;
1541 	size_t resid, runlen;
1542 	int error;
1543 	bool success;
1544 
1545 	KASSERT((uintptr_t)base % PAGE_SIZE == 0,
1546 	    ("%s: user address %p is not page-aligned", __func__, base));
1547 
1548 	if (p->comp != NULL)
1549 		return (compress_chunk(p, base, tmpbuf, len));
1550 
1551 	map = &p->td->td_proc->p_vmspace->vm_map;
1552 	for (; len > 0; base += runlen, offset += runlen, len -= runlen) {
1553 		/*
1554 		 * Attempt to page in all virtual pages in the range.  If a
1555 		 * virtual page is not backed by the pager, it is represented as
1556 		 * a hole in the file.  This can occur with zero-filled
1557 		 * anonymous memory or truncated files, for example.
1558 		 */
1559 		for (runlen = 0; runlen < len; runlen += PAGE_SIZE) {
1560 			error = vm_fault(map, (uintptr_t)base + runlen,
1561 			    VM_PROT_READ, VM_FAULT_NOFILL, NULL);
1562 			if (runlen == 0)
1563 				success = error == KERN_SUCCESS;
1564 			else if ((error == KERN_SUCCESS) != success)
1565 				break;
1566 		}
1567 
1568 		if (success) {
1569 			error = core_write(p, base, runlen, offset,
1570 			    UIO_USERSPACE, &resid);
1571 			if (error != 0) {
1572 				if (error != EFAULT)
1573 					break;
1574 
1575 				/*
1576 				 * EFAULT may be returned if the user mapping
1577 				 * could not be accessed, e.g., because a mapped
1578 				 * file has been truncated.  Skip the page if no
1579 				 * progress was made, to protect against a
1580 				 * hypothetical scenario where vm_fault() was
1581 				 * successful but core_write() returns EFAULT
1582 				 * anyway.
1583 				 */
1584 				runlen -= resid;
1585 				if (runlen == 0) {
1586 					success = false;
1587 					runlen = PAGE_SIZE;
1588 				}
1589 			}
1590 		}
1591 		if (!success) {
1592 			error = vn_start_write(p->vp, &mp, V_WAIT);
1593 			if (error != 0)
1594 				break;
1595 			vn_lock(p->vp, LK_EXCLUSIVE | LK_RETRY);
1596 			error = vn_truncate_locked(p->vp, offset + runlen,
1597 			    false, p->td->td_ucred);
1598 			VOP_UNLOCK(p->vp);
1599 			vn_finished_write(mp);
1600 			if (error != 0)
1601 				break;
1602 		}
1603 	}
1604 	return (error);
1605 }
1606 
1607 /*
1608  * Drain into a core file.
1609  */
1610 static int
1611 sbuf_drain_core_output(void *arg, const char *data, int len)
1612 {
1613 	struct coredump_params *p;
1614 	int error, locked;
1615 
1616 	p = (struct coredump_params *)arg;
1617 
1618 	/*
1619 	 * Some kern_proc out routines that print to this sbuf may
1620 	 * call us with the process lock held. Draining with the
1621 	 * non-sleepable lock held is unsafe. The lock is needed for
1622 	 * those routines when dumping a live process. In our case we
1623 	 * can safely release the lock before draining and acquire
1624 	 * again after.
1625 	 */
1626 	locked = PROC_LOCKED(p->td->td_proc);
1627 	if (locked)
1628 		PROC_UNLOCK(p->td->td_proc);
1629 	if (p->comp != NULL)
1630 		error = compressor_write(p->comp, __DECONST(char *, data), len);
1631 	else
1632 		error = core_write(p, __DECONST(void *, data), len, p->offset,
1633 		    UIO_SYSSPACE, NULL);
1634 	if (locked)
1635 		PROC_LOCK(p->td->td_proc);
1636 	if (error != 0)
1637 		return (-error);
1638 	p->offset += len;
1639 	return (len);
1640 }
1641 
1642 int
1643 __elfN(coredump)(struct thread *td, struct vnode *vp, off_t limit, int flags)
1644 {
1645 	struct ucred *cred = td->td_ucred;
1646 	int error = 0;
1647 	struct sseg_closure seginfo;
1648 	struct note_info_list notelst;
1649 	struct coredump_params params;
1650 	struct note_info *ninfo;
1651 	void *hdr, *tmpbuf;
1652 	size_t hdrsize, notesz, coresize;
1653 
1654 	hdr = NULL;
1655 	tmpbuf = NULL;
1656 	TAILQ_INIT(&notelst);
1657 
1658 	/* Size the program segments. */
1659 	seginfo.count = 0;
1660 	seginfo.size = 0;
1661 	each_dumpable_segment(td, cb_size_segment, &seginfo);
1662 
1663 	/*
1664 	 * Collect info about the core file header area.
1665 	 */
1666 	hdrsize = sizeof(Elf_Ehdr) + sizeof(Elf_Phdr) * (1 + seginfo.count);
1667 	if (seginfo.count + 1 >= PN_XNUM)
1668 		hdrsize += sizeof(Elf_Shdr);
1669 	__elfN(prepare_notes)(td, &notelst, &notesz);
1670 	coresize = round_page(hdrsize + notesz) + seginfo.size;
1671 
1672 	/* Set up core dump parameters. */
1673 	params.offset = 0;
1674 	params.active_cred = cred;
1675 	params.file_cred = NOCRED;
1676 	params.td = td;
1677 	params.vp = vp;
1678 	params.comp = NULL;
1679 
1680 #ifdef RACCT
1681 	if (racct_enable) {
1682 		PROC_LOCK(td->td_proc);
1683 		error = racct_add(td->td_proc, RACCT_CORE, coresize);
1684 		PROC_UNLOCK(td->td_proc);
1685 		if (error != 0) {
1686 			error = EFAULT;
1687 			goto done;
1688 		}
1689 	}
1690 #endif
1691 	if (coresize >= limit) {
1692 		error = EFAULT;
1693 		goto done;
1694 	}
1695 
1696 	/* Create a compression stream if necessary. */
1697 	if (compress_user_cores != 0) {
1698 		params.comp = compressor_init(core_compressed_write,
1699 		    compress_user_cores, CORE_BUF_SIZE,
1700 		    compress_user_cores_level, &params);
1701 		if (params.comp == NULL) {
1702 			error = EFAULT;
1703 			goto done;
1704 		}
1705 		tmpbuf = malloc(CORE_BUF_SIZE, M_TEMP, M_WAITOK | M_ZERO);
1706         }
1707 
1708 	/*
1709 	 * Allocate memory for building the header, fill it up,
1710 	 * and write it out following the notes.
1711 	 */
1712 	hdr = malloc(hdrsize, M_TEMP, M_WAITOK);
1713 	error = __elfN(corehdr)(&params, seginfo.count, hdr, hdrsize, &notelst,
1714 	    notesz);
1715 
1716 	/* Write the contents of all of the writable segments. */
1717 	if (error == 0) {
1718 		Elf_Phdr *php;
1719 		off_t offset;
1720 		int i;
1721 
1722 		php = (Elf_Phdr *)((char *)hdr + sizeof(Elf_Ehdr)) + 1;
1723 		offset = round_page(hdrsize + notesz);
1724 		for (i = 0; i < seginfo.count; i++) {
1725 			error = core_output((char *)(uintptr_t)php->p_vaddr,
1726 			    php->p_filesz, offset, &params, tmpbuf);
1727 			if (error != 0)
1728 				break;
1729 			offset += php->p_filesz;
1730 			php++;
1731 		}
1732 		if (error == 0 && params.comp != NULL)
1733 			error = compressor_flush(params.comp);
1734 	}
1735 	if (error) {
1736 		log(LOG_WARNING,
1737 		    "Failed to write core file for process %s (error %d)\n",
1738 		    curproc->p_comm, error);
1739 	}
1740 
1741 done:
1742 	free(tmpbuf, M_TEMP);
1743 	if (params.comp != NULL)
1744 		compressor_fini(params.comp);
1745 	while ((ninfo = TAILQ_FIRST(&notelst)) != NULL) {
1746 		TAILQ_REMOVE(&notelst, ninfo, link);
1747 		free(ninfo, M_TEMP);
1748 	}
1749 	if (hdr != NULL)
1750 		free(hdr, M_TEMP);
1751 
1752 	return (error);
1753 }
1754 
1755 /*
1756  * A callback for each_dumpable_segment() to write out the segment's
1757  * program header entry.
1758  */
1759 static void
1760 cb_put_phdr(vm_map_entry_t entry, void *closure)
1761 {
1762 	struct phdr_closure *phc = (struct phdr_closure *)closure;
1763 	Elf_Phdr *phdr = phc->phdr;
1764 
1765 	phc->offset = round_page(phc->offset);
1766 
1767 	phdr->p_type = PT_LOAD;
1768 	phdr->p_offset = phc->offset;
1769 	phdr->p_vaddr = entry->start;
1770 	phdr->p_paddr = 0;
1771 	phdr->p_filesz = phdr->p_memsz = entry->end - entry->start;
1772 	phdr->p_align = PAGE_SIZE;
1773 	phdr->p_flags = __elfN(untrans_prot)(entry->protection);
1774 
1775 	phc->offset += phdr->p_filesz;
1776 	phc->phdr++;
1777 }
1778 
1779 /*
1780  * A callback for each_dumpable_segment() to gather information about
1781  * the number of segments and their total size.
1782  */
1783 static void
1784 cb_size_segment(vm_map_entry_t entry, void *closure)
1785 {
1786 	struct sseg_closure *ssc = (struct sseg_closure *)closure;
1787 
1788 	ssc->count++;
1789 	ssc->size += entry->end - entry->start;
1790 }
1791 
1792 /*
1793  * For each writable segment in the process's memory map, call the given
1794  * function with a pointer to the map entry and some arbitrary
1795  * caller-supplied data.
1796  */
1797 static void
1798 each_dumpable_segment(struct thread *td, segment_callback func, void *closure)
1799 {
1800 	struct proc *p = td->td_proc;
1801 	vm_map_t map = &p->p_vmspace->vm_map;
1802 	vm_map_entry_t entry;
1803 	vm_object_t backing_object, object;
1804 	bool ignore_entry;
1805 
1806 	vm_map_lock_read(map);
1807 	VM_MAP_ENTRY_FOREACH(entry, map) {
1808 		/*
1809 		 * Don't dump inaccessible mappings, deal with legacy
1810 		 * coredump mode.
1811 		 *
1812 		 * Note that read-only segments related to the elf binary
1813 		 * are marked MAP_ENTRY_NOCOREDUMP now so we no longer
1814 		 * need to arbitrarily ignore such segments.
1815 		 */
1816 		if (elf_legacy_coredump) {
1817 			if ((entry->protection & VM_PROT_RW) != VM_PROT_RW)
1818 				continue;
1819 		} else {
1820 			if ((entry->protection & VM_PROT_ALL) == 0)
1821 				continue;
1822 		}
1823 
1824 		/*
1825 		 * Dont include memory segment in the coredump if
1826 		 * MAP_NOCORE is set in mmap(2) or MADV_NOCORE in
1827 		 * madvise(2).  Do not dump submaps (i.e. parts of the
1828 		 * kernel map).
1829 		 */
1830 		if (entry->eflags & (MAP_ENTRY_NOCOREDUMP|MAP_ENTRY_IS_SUB_MAP))
1831 			continue;
1832 
1833 		if ((object = entry->object.vm_object) == NULL)
1834 			continue;
1835 
1836 		/* Ignore memory-mapped devices and such things. */
1837 		VM_OBJECT_RLOCK(object);
1838 		while ((backing_object = object->backing_object) != NULL) {
1839 			VM_OBJECT_RLOCK(backing_object);
1840 			VM_OBJECT_RUNLOCK(object);
1841 			object = backing_object;
1842 		}
1843 		ignore_entry = (object->flags & OBJ_FICTITIOUS) != 0;
1844 		VM_OBJECT_RUNLOCK(object);
1845 		if (ignore_entry)
1846 			continue;
1847 
1848 		(*func)(entry, closure);
1849 	}
1850 	vm_map_unlock_read(map);
1851 }
1852 
1853 /*
1854  * Write the core file header to the file, including padding up to
1855  * the page boundary.
1856  */
1857 static int
1858 __elfN(corehdr)(struct coredump_params *p, int numsegs, void *hdr,
1859     size_t hdrsize, struct note_info_list *notelst, size_t notesz)
1860 {
1861 	struct note_info *ninfo;
1862 	struct sbuf *sb;
1863 	int error;
1864 
1865 	/* Fill in the header. */
1866 	bzero(hdr, hdrsize);
1867 	__elfN(puthdr)(p->td, hdr, hdrsize, numsegs, notesz);
1868 
1869 	sb = sbuf_new(NULL, NULL, CORE_BUF_SIZE, SBUF_FIXEDLEN);
1870 	sbuf_set_drain(sb, sbuf_drain_core_output, p);
1871 	sbuf_start_section(sb, NULL);
1872 	sbuf_bcat(sb, hdr, hdrsize);
1873 	TAILQ_FOREACH(ninfo, notelst, link)
1874 	    __elfN(putnote)(ninfo, sb);
1875 	/* Align up to a page boundary for the program segments. */
1876 	sbuf_end_section(sb, -1, PAGE_SIZE, 0);
1877 	error = sbuf_finish(sb);
1878 	sbuf_delete(sb);
1879 
1880 	return (error);
1881 }
1882 
1883 static void
1884 __elfN(prepare_notes)(struct thread *td, struct note_info_list *list,
1885     size_t *sizep)
1886 {
1887 	struct proc *p;
1888 	struct thread *thr;
1889 	size_t size;
1890 
1891 	p = td->td_proc;
1892 	size = 0;
1893 
1894 	size += register_note(list, NT_PRPSINFO, __elfN(note_prpsinfo), p);
1895 
1896 	/*
1897 	 * To have the debugger select the right thread (LWP) as the initial
1898 	 * thread, we dump the state of the thread passed to us in td first.
1899 	 * This is the thread that causes the core dump and thus likely to
1900 	 * be the right thread one wants to have selected in the debugger.
1901 	 */
1902 	thr = td;
1903 	while (thr != NULL) {
1904 		size += register_note(list, NT_PRSTATUS,
1905 		    __elfN(note_prstatus), thr);
1906 		size += register_note(list, NT_FPREGSET,
1907 		    __elfN(note_fpregset), thr);
1908 		size += register_note(list, NT_THRMISC,
1909 		    __elfN(note_thrmisc), thr);
1910 		size += register_note(list, NT_PTLWPINFO,
1911 		    __elfN(note_ptlwpinfo), thr);
1912 		size += register_note(list, -1,
1913 		    __elfN(note_threadmd), thr);
1914 
1915 		thr = (thr == td) ? TAILQ_FIRST(&p->p_threads) :
1916 		    TAILQ_NEXT(thr, td_plist);
1917 		if (thr == td)
1918 			thr = TAILQ_NEXT(thr, td_plist);
1919 	}
1920 
1921 	size += register_note(list, NT_PROCSTAT_PROC,
1922 	    __elfN(note_procstat_proc), p);
1923 	size += register_note(list, NT_PROCSTAT_FILES,
1924 	    note_procstat_files, p);
1925 	size += register_note(list, NT_PROCSTAT_VMMAP,
1926 	    note_procstat_vmmap, p);
1927 	size += register_note(list, NT_PROCSTAT_GROUPS,
1928 	    note_procstat_groups, p);
1929 	size += register_note(list, NT_PROCSTAT_UMASK,
1930 	    note_procstat_umask, p);
1931 	size += register_note(list, NT_PROCSTAT_RLIMIT,
1932 	    note_procstat_rlimit, p);
1933 	size += register_note(list, NT_PROCSTAT_OSREL,
1934 	    note_procstat_osrel, p);
1935 	size += register_note(list, NT_PROCSTAT_PSSTRINGS,
1936 	    __elfN(note_procstat_psstrings), p);
1937 	size += register_note(list, NT_PROCSTAT_AUXV,
1938 	    __elfN(note_procstat_auxv), p);
1939 
1940 	*sizep = size;
1941 }
1942 
1943 static void
1944 __elfN(puthdr)(struct thread *td, void *hdr, size_t hdrsize, int numsegs,
1945     size_t notesz)
1946 {
1947 	Elf_Ehdr *ehdr;
1948 	Elf_Phdr *phdr;
1949 	Elf_Shdr *shdr;
1950 	struct phdr_closure phc;
1951 
1952 	ehdr = (Elf_Ehdr *)hdr;
1953 
1954 	ehdr->e_ident[EI_MAG0] = ELFMAG0;
1955 	ehdr->e_ident[EI_MAG1] = ELFMAG1;
1956 	ehdr->e_ident[EI_MAG2] = ELFMAG2;
1957 	ehdr->e_ident[EI_MAG3] = ELFMAG3;
1958 	ehdr->e_ident[EI_CLASS] = ELF_CLASS;
1959 	ehdr->e_ident[EI_DATA] = ELF_DATA;
1960 	ehdr->e_ident[EI_VERSION] = EV_CURRENT;
1961 	ehdr->e_ident[EI_OSABI] = ELFOSABI_FREEBSD;
1962 	ehdr->e_ident[EI_ABIVERSION] = 0;
1963 	ehdr->e_ident[EI_PAD] = 0;
1964 	ehdr->e_type = ET_CORE;
1965 	ehdr->e_machine = td->td_proc->p_elf_machine;
1966 	ehdr->e_version = EV_CURRENT;
1967 	ehdr->e_entry = 0;
1968 	ehdr->e_phoff = sizeof(Elf_Ehdr);
1969 	ehdr->e_flags = td->td_proc->p_elf_flags;
1970 	ehdr->e_ehsize = sizeof(Elf_Ehdr);
1971 	ehdr->e_phentsize = sizeof(Elf_Phdr);
1972 	ehdr->e_shentsize = sizeof(Elf_Shdr);
1973 	ehdr->e_shstrndx = SHN_UNDEF;
1974 	if (numsegs + 1 < PN_XNUM) {
1975 		ehdr->e_phnum = numsegs + 1;
1976 		ehdr->e_shnum = 0;
1977 	} else {
1978 		ehdr->e_phnum = PN_XNUM;
1979 		ehdr->e_shnum = 1;
1980 
1981 		ehdr->e_shoff = ehdr->e_phoff +
1982 		    (numsegs + 1) * ehdr->e_phentsize;
1983 		KASSERT(ehdr->e_shoff == hdrsize - sizeof(Elf_Shdr),
1984 		    ("e_shoff: %zu, hdrsize - shdr: %zu",
1985 		     (size_t)ehdr->e_shoff, hdrsize - sizeof(Elf_Shdr)));
1986 
1987 		shdr = (Elf_Shdr *)((char *)hdr + ehdr->e_shoff);
1988 		memset(shdr, 0, sizeof(*shdr));
1989 		/*
1990 		 * A special first section is used to hold large segment and
1991 		 * section counts.  This was proposed by Sun Microsystems in
1992 		 * Solaris and has been adopted by Linux; the standard ELF
1993 		 * tools are already familiar with the technique.
1994 		 *
1995 		 * See table 7-7 of the Solaris "Linker and Libraries Guide"
1996 		 * (or 12-7 depending on the version of the document) for more
1997 		 * details.
1998 		 */
1999 		shdr->sh_type = SHT_NULL;
2000 		shdr->sh_size = ehdr->e_shnum;
2001 		shdr->sh_link = ehdr->e_shstrndx;
2002 		shdr->sh_info = numsegs + 1;
2003 	}
2004 
2005 	/*
2006 	 * Fill in the program header entries.
2007 	 */
2008 	phdr = (Elf_Phdr *)((char *)hdr + ehdr->e_phoff);
2009 
2010 	/* The note segement. */
2011 	phdr->p_type = PT_NOTE;
2012 	phdr->p_offset = hdrsize;
2013 	phdr->p_vaddr = 0;
2014 	phdr->p_paddr = 0;
2015 	phdr->p_filesz = notesz;
2016 	phdr->p_memsz = 0;
2017 	phdr->p_flags = PF_R;
2018 	phdr->p_align = ELF_NOTE_ROUNDSIZE;
2019 	phdr++;
2020 
2021 	/* All the writable segments from the program. */
2022 	phc.phdr = phdr;
2023 	phc.offset = round_page(hdrsize + notesz);
2024 	each_dumpable_segment(td, cb_put_phdr, &phc);
2025 }
2026 
2027 static size_t
2028 register_note(struct note_info_list *list, int type, outfunc_t out, void *arg)
2029 {
2030 	struct note_info *ninfo;
2031 	size_t size, notesize;
2032 
2033 	size = 0;
2034 	out(arg, NULL, &size);
2035 	ninfo = malloc(sizeof(*ninfo), M_TEMP, M_ZERO | M_WAITOK);
2036 	ninfo->type = type;
2037 	ninfo->outfunc = out;
2038 	ninfo->outarg = arg;
2039 	ninfo->outsize = size;
2040 	TAILQ_INSERT_TAIL(list, ninfo, link);
2041 
2042 	if (type == -1)
2043 		return (size);
2044 
2045 	notesize = sizeof(Elf_Note) +		/* note header */
2046 	    roundup2(sizeof(FREEBSD_ABI_VENDOR), ELF_NOTE_ROUNDSIZE) +
2047 						/* note name */
2048 	    roundup2(size, ELF_NOTE_ROUNDSIZE);	/* note description */
2049 
2050 	return (notesize);
2051 }
2052 
2053 static size_t
2054 append_note_data(const void *src, void *dst, size_t len)
2055 {
2056 	size_t padded_len;
2057 
2058 	padded_len = roundup2(len, ELF_NOTE_ROUNDSIZE);
2059 	if (dst != NULL) {
2060 		bcopy(src, dst, len);
2061 		bzero((char *)dst + len, padded_len - len);
2062 	}
2063 	return (padded_len);
2064 }
2065 
2066 size_t
2067 __elfN(populate_note)(int type, void *src, void *dst, size_t size, void **descp)
2068 {
2069 	Elf_Note *note;
2070 	char *buf;
2071 	size_t notesize;
2072 
2073 	buf = dst;
2074 	if (buf != NULL) {
2075 		note = (Elf_Note *)buf;
2076 		note->n_namesz = sizeof(FREEBSD_ABI_VENDOR);
2077 		note->n_descsz = size;
2078 		note->n_type = type;
2079 		buf += sizeof(*note);
2080 		buf += append_note_data(FREEBSD_ABI_VENDOR, buf,
2081 		    sizeof(FREEBSD_ABI_VENDOR));
2082 		append_note_data(src, buf, size);
2083 		if (descp != NULL)
2084 			*descp = buf;
2085 	}
2086 
2087 	notesize = sizeof(Elf_Note) +		/* note header */
2088 	    roundup2(sizeof(FREEBSD_ABI_VENDOR), ELF_NOTE_ROUNDSIZE) +
2089 						/* note name */
2090 	    roundup2(size, ELF_NOTE_ROUNDSIZE);	/* note description */
2091 
2092 	return (notesize);
2093 }
2094 
2095 static void
2096 __elfN(putnote)(struct note_info *ninfo, struct sbuf *sb)
2097 {
2098 	Elf_Note note;
2099 	ssize_t old_len, sect_len;
2100 	size_t new_len, descsz, i;
2101 
2102 	if (ninfo->type == -1) {
2103 		ninfo->outfunc(ninfo->outarg, sb, &ninfo->outsize);
2104 		return;
2105 	}
2106 
2107 	note.n_namesz = sizeof(FREEBSD_ABI_VENDOR);
2108 	note.n_descsz = ninfo->outsize;
2109 	note.n_type = ninfo->type;
2110 
2111 	sbuf_bcat(sb, &note, sizeof(note));
2112 	sbuf_start_section(sb, &old_len);
2113 	sbuf_bcat(sb, FREEBSD_ABI_VENDOR, sizeof(FREEBSD_ABI_VENDOR));
2114 	sbuf_end_section(sb, old_len, ELF_NOTE_ROUNDSIZE, 0);
2115 	if (note.n_descsz == 0)
2116 		return;
2117 	sbuf_start_section(sb, &old_len);
2118 	ninfo->outfunc(ninfo->outarg, sb, &ninfo->outsize);
2119 	sect_len = sbuf_end_section(sb, old_len, ELF_NOTE_ROUNDSIZE, 0);
2120 	if (sect_len < 0)
2121 		return;
2122 
2123 	new_len = (size_t)sect_len;
2124 	descsz = roundup(note.n_descsz, ELF_NOTE_ROUNDSIZE);
2125 	if (new_len < descsz) {
2126 		/*
2127 		 * It is expected that individual note emitters will correctly
2128 		 * predict their expected output size and fill up to that size
2129 		 * themselves, padding in a format-specific way if needed.
2130 		 * However, in case they don't, just do it here with zeros.
2131 		 */
2132 		for (i = 0; i < descsz - new_len; i++)
2133 			sbuf_putc(sb, 0);
2134 	} else if (new_len > descsz) {
2135 		/*
2136 		 * We can't always truncate sb -- we may have drained some
2137 		 * of it already.
2138 		 */
2139 		KASSERT(new_len == descsz, ("%s: Note type %u changed as we "
2140 		    "read it (%zu > %zu).  Since it is longer than "
2141 		    "expected, this coredump's notes are corrupt.  THIS "
2142 		    "IS A BUG in the note_procstat routine for type %u.\n",
2143 		    __func__, (unsigned)note.n_type, new_len, descsz,
2144 		    (unsigned)note.n_type));
2145 	}
2146 }
2147 
2148 /*
2149  * Miscellaneous note out functions.
2150  */
2151 
2152 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
2153 #include <compat/freebsd32/freebsd32.h>
2154 #include <compat/freebsd32/freebsd32_signal.h>
2155 
2156 typedef struct prstatus32 elf_prstatus_t;
2157 typedef struct prpsinfo32 elf_prpsinfo_t;
2158 typedef struct fpreg32 elf_prfpregset_t;
2159 typedef struct fpreg32 elf_fpregset_t;
2160 typedef struct reg32 elf_gregset_t;
2161 typedef struct thrmisc32 elf_thrmisc_t;
2162 #define ELF_KERN_PROC_MASK	KERN_PROC_MASK32
2163 typedef struct kinfo_proc32 elf_kinfo_proc_t;
2164 typedef uint32_t elf_ps_strings_t;
2165 #else
2166 typedef prstatus_t elf_prstatus_t;
2167 typedef prpsinfo_t elf_prpsinfo_t;
2168 typedef prfpregset_t elf_prfpregset_t;
2169 typedef prfpregset_t elf_fpregset_t;
2170 typedef gregset_t elf_gregset_t;
2171 typedef thrmisc_t elf_thrmisc_t;
2172 #define ELF_KERN_PROC_MASK	0
2173 typedef struct kinfo_proc elf_kinfo_proc_t;
2174 typedef vm_offset_t elf_ps_strings_t;
2175 #endif
2176 
2177 static void
2178 __elfN(note_prpsinfo)(void *arg, struct sbuf *sb, size_t *sizep)
2179 {
2180 	struct sbuf sbarg;
2181 	size_t len;
2182 	char *cp, *end;
2183 	struct proc *p;
2184 	elf_prpsinfo_t *psinfo;
2185 	int error;
2186 
2187 	p = (struct proc *)arg;
2188 	if (sb != NULL) {
2189 		KASSERT(*sizep == sizeof(*psinfo), ("invalid size"));
2190 		psinfo = malloc(sizeof(*psinfo), M_TEMP, M_ZERO | M_WAITOK);
2191 		psinfo->pr_version = PRPSINFO_VERSION;
2192 		psinfo->pr_psinfosz = sizeof(elf_prpsinfo_t);
2193 		strlcpy(psinfo->pr_fname, p->p_comm, sizeof(psinfo->pr_fname));
2194 		PROC_LOCK(p);
2195 		if (p->p_args != NULL) {
2196 			len = sizeof(psinfo->pr_psargs) - 1;
2197 			if (len > p->p_args->ar_length)
2198 				len = p->p_args->ar_length;
2199 			memcpy(psinfo->pr_psargs, p->p_args->ar_args, len);
2200 			PROC_UNLOCK(p);
2201 			error = 0;
2202 		} else {
2203 			_PHOLD(p);
2204 			PROC_UNLOCK(p);
2205 			sbuf_new(&sbarg, psinfo->pr_psargs,
2206 			    sizeof(psinfo->pr_psargs), SBUF_FIXEDLEN);
2207 			error = proc_getargv(curthread, p, &sbarg);
2208 			PRELE(p);
2209 			if (sbuf_finish(&sbarg) == 0)
2210 				len = sbuf_len(&sbarg) - 1;
2211 			else
2212 				len = sizeof(psinfo->pr_psargs) - 1;
2213 			sbuf_delete(&sbarg);
2214 		}
2215 		if (error || len == 0)
2216 			strlcpy(psinfo->pr_psargs, p->p_comm,
2217 			    sizeof(psinfo->pr_psargs));
2218 		else {
2219 			KASSERT(len < sizeof(psinfo->pr_psargs),
2220 			    ("len is too long: %zu vs %zu", len,
2221 			    sizeof(psinfo->pr_psargs)));
2222 			cp = psinfo->pr_psargs;
2223 			end = cp + len - 1;
2224 			for (;;) {
2225 				cp = memchr(cp, '\0', end - cp);
2226 				if (cp == NULL)
2227 					break;
2228 				*cp = ' ';
2229 			}
2230 		}
2231 		psinfo->pr_pid = p->p_pid;
2232 		sbuf_bcat(sb, psinfo, sizeof(*psinfo));
2233 		free(psinfo, M_TEMP);
2234 	}
2235 	*sizep = sizeof(*psinfo);
2236 }
2237 
2238 static void
2239 __elfN(note_prstatus)(void *arg, struct sbuf *sb, size_t *sizep)
2240 {
2241 	struct thread *td;
2242 	elf_prstatus_t *status;
2243 
2244 	td = (struct thread *)arg;
2245 	if (sb != NULL) {
2246 		KASSERT(*sizep == sizeof(*status), ("invalid size"));
2247 		status = malloc(sizeof(*status), M_TEMP, M_ZERO | M_WAITOK);
2248 		status->pr_version = PRSTATUS_VERSION;
2249 		status->pr_statussz = sizeof(elf_prstatus_t);
2250 		status->pr_gregsetsz = sizeof(elf_gregset_t);
2251 		status->pr_fpregsetsz = sizeof(elf_fpregset_t);
2252 		status->pr_osreldate = osreldate;
2253 		status->pr_cursig = td->td_proc->p_sig;
2254 		status->pr_pid = td->td_tid;
2255 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
2256 		fill_regs32(td, &status->pr_reg);
2257 #else
2258 		fill_regs(td, &status->pr_reg);
2259 #endif
2260 		sbuf_bcat(sb, status, sizeof(*status));
2261 		free(status, M_TEMP);
2262 	}
2263 	*sizep = sizeof(*status);
2264 }
2265 
2266 static void
2267 __elfN(note_fpregset)(void *arg, struct sbuf *sb, size_t *sizep)
2268 {
2269 	struct thread *td;
2270 	elf_prfpregset_t *fpregset;
2271 
2272 	td = (struct thread *)arg;
2273 	if (sb != NULL) {
2274 		KASSERT(*sizep == sizeof(*fpregset), ("invalid size"));
2275 		fpregset = malloc(sizeof(*fpregset), M_TEMP, M_ZERO | M_WAITOK);
2276 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
2277 		fill_fpregs32(td, fpregset);
2278 #else
2279 		fill_fpregs(td, fpregset);
2280 #endif
2281 		sbuf_bcat(sb, fpregset, sizeof(*fpregset));
2282 		free(fpregset, M_TEMP);
2283 	}
2284 	*sizep = sizeof(*fpregset);
2285 }
2286 
2287 static void
2288 __elfN(note_thrmisc)(void *arg, struct sbuf *sb, size_t *sizep)
2289 {
2290 	struct thread *td;
2291 	elf_thrmisc_t thrmisc;
2292 
2293 	td = (struct thread *)arg;
2294 	if (sb != NULL) {
2295 		KASSERT(*sizep == sizeof(thrmisc), ("invalid size"));
2296 		bzero(&thrmisc, sizeof(thrmisc));
2297 		strcpy(thrmisc.pr_tname, td->td_name);
2298 		sbuf_bcat(sb, &thrmisc, sizeof(thrmisc));
2299 	}
2300 	*sizep = sizeof(thrmisc);
2301 }
2302 
2303 static void
2304 __elfN(note_ptlwpinfo)(void *arg, struct sbuf *sb, size_t *sizep)
2305 {
2306 	struct thread *td;
2307 	size_t size;
2308 	int structsize;
2309 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
2310 	struct ptrace_lwpinfo32 pl;
2311 #else
2312 	struct ptrace_lwpinfo pl;
2313 #endif
2314 
2315 	td = (struct thread *)arg;
2316 	size = sizeof(structsize) + sizeof(pl);
2317 	if (sb != NULL) {
2318 		KASSERT(*sizep == size, ("invalid size"));
2319 		structsize = sizeof(pl);
2320 		sbuf_bcat(sb, &structsize, sizeof(structsize));
2321 		bzero(&pl, sizeof(pl));
2322 		pl.pl_lwpid = td->td_tid;
2323 		pl.pl_event = PL_EVENT_NONE;
2324 		pl.pl_sigmask = td->td_sigmask;
2325 		pl.pl_siglist = td->td_siglist;
2326 		if (td->td_si.si_signo != 0) {
2327 			pl.pl_event = PL_EVENT_SIGNAL;
2328 			pl.pl_flags |= PL_FLAG_SI;
2329 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
2330 			siginfo_to_siginfo32(&td->td_si, &pl.pl_siginfo);
2331 #else
2332 			pl.pl_siginfo = td->td_si;
2333 #endif
2334 		}
2335 		strcpy(pl.pl_tdname, td->td_name);
2336 		/* XXX TODO: supply more information in struct ptrace_lwpinfo*/
2337 		sbuf_bcat(sb, &pl, sizeof(pl));
2338 	}
2339 	*sizep = size;
2340 }
2341 
2342 /*
2343  * Allow for MD specific notes, as well as any MD
2344  * specific preparations for writing MI notes.
2345  */
2346 static void
2347 __elfN(note_threadmd)(void *arg, struct sbuf *sb, size_t *sizep)
2348 {
2349 	struct thread *td;
2350 	void *buf;
2351 	size_t size;
2352 
2353 	td = (struct thread *)arg;
2354 	size = *sizep;
2355 	if (size != 0 && sb != NULL)
2356 		buf = malloc(size, M_TEMP, M_ZERO | M_WAITOK);
2357 	else
2358 		buf = NULL;
2359 	size = 0;
2360 	__elfN(dump_thread)(td, buf, &size);
2361 	KASSERT(sb == NULL || *sizep == size, ("invalid size"));
2362 	if (size != 0 && sb != NULL)
2363 		sbuf_bcat(sb, buf, size);
2364 	free(buf, M_TEMP);
2365 	*sizep = size;
2366 }
2367 
2368 #ifdef KINFO_PROC_SIZE
2369 CTASSERT(sizeof(struct kinfo_proc) == KINFO_PROC_SIZE);
2370 #endif
2371 
2372 static void
2373 __elfN(note_procstat_proc)(void *arg, struct sbuf *sb, size_t *sizep)
2374 {
2375 	struct proc *p;
2376 	size_t size;
2377 	int structsize;
2378 
2379 	p = (struct proc *)arg;
2380 	size = sizeof(structsize) + p->p_numthreads *
2381 	    sizeof(elf_kinfo_proc_t);
2382 
2383 	if (sb != NULL) {
2384 		KASSERT(*sizep == size, ("invalid size"));
2385 		structsize = sizeof(elf_kinfo_proc_t);
2386 		sbuf_bcat(sb, &structsize, sizeof(structsize));
2387 		PROC_LOCK(p);
2388 		kern_proc_out(p, sb, ELF_KERN_PROC_MASK);
2389 	}
2390 	*sizep = size;
2391 }
2392 
2393 #ifdef KINFO_FILE_SIZE
2394 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
2395 #endif
2396 
2397 static void
2398 note_procstat_files(void *arg, struct sbuf *sb, size_t *sizep)
2399 {
2400 	struct proc *p;
2401 	size_t size, sect_sz, i;
2402 	ssize_t start_len, sect_len;
2403 	int structsize, filedesc_flags;
2404 
2405 	if (coredump_pack_fileinfo)
2406 		filedesc_flags = KERN_FILEDESC_PACK_KINFO;
2407 	else
2408 		filedesc_flags = 0;
2409 
2410 	p = (struct proc *)arg;
2411 	structsize = sizeof(struct kinfo_file);
2412 	if (sb == NULL) {
2413 		size = 0;
2414 		sb = sbuf_new(NULL, NULL, 128, SBUF_FIXEDLEN);
2415 		sbuf_set_drain(sb, sbuf_count_drain, &size);
2416 		sbuf_bcat(sb, &structsize, sizeof(structsize));
2417 		PROC_LOCK(p);
2418 		kern_proc_filedesc_out(p, sb, -1, filedesc_flags);
2419 		sbuf_finish(sb);
2420 		sbuf_delete(sb);
2421 		*sizep = size;
2422 	} else {
2423 		sbuf_start_section(sb, &start_len);
2424 
2425 		sbuf_bcat(sb, &structsize, sizeof(structsize));
2426 		PROC_LOCK(p);
2427 		kern_proc_filedesc_out(p, sb, *sizep - sizeof(structsize),
2428 		    filedesc_flags);
2429 
2430 		sect_len = sbuf_end_section(sb, start_len, 0, 0);
2431 		if (sect_len < 0)
2432 			return;
2433 		sect_sz = sect_len;
2434 
2435 		KASSERT(sect_sz <= *sizep,
2436 		    ("kern_proc_filedesc_out did not respect maxlen; "
2437 		     "requested %zu, got %zu", *sizep - sizeof(structsize),
2438 		     sect_sz - sizeof(structsize)));
2439 
2440 		for (i = 0; i < *sizep - sect_sz && sb->s_error == 0; i++)
2441 			sbuf_putc(sb, 0);
2442 	}
2443 }
2444 
2445 #ifdef KINFO_VMENTRY_SIZE
2446 CTASSERT(sizeof(struct kinfo_vmentry) == KINFO_VMENTRY_SIZE);
2447 #endif
2448 
2449 static void
2450 note_procstat_vmmap(void *arg, struct sbuf *sb, size_t *sizep)
2451 {
2452 	struct proc *p;
2453 	size_t size;
2454 	int structsize, vmmap_flags;
2455 
2456 	if (coredump_pack_vmmapinfo)
2457 		vmmap_flags = KERN_VMMAP_PACK_KINFO;
2458 	else
2459 		vmmap_flags = 0;
2460 
2461 	p = (struct proc *)arg;
2462 	structsize = sizeof(struct kinfo_vmentry);
2463 	if (sb == NULL) {
2464 		size = 0;
2465 		sb = sbuf_new(NULL, NULL, 128, SBUF_FIXEDLEN);
2466 		sbuf_set_drain(sb, sbuf_count_drain, &size);
2467 		sbuf_bcat(sb, &structsize, sizeof(structsize));
2468 		PROC_LOCK(p);
2469 		kern_proc_vmmap_out(p, sb, -1, vmmap_flags);
2470 		sbuf_finish(sb);
2471 		sbuf_delete(sb);
2472 		*sizep = size;
2473 	} else {
2474 		sbuf_bcat(sb, &structsize, sizeof(structsize));
2475 		PROC_LOCK(p);
2476 		kern_proc_vmmap_out(p, sb, *sizep - sizeof(structsize),
2477 		    vmmap_flags);
2478 	}
2479 }
2480 
2481 static void
2482 note_procstat_groups(void *arg, struct sbuf *sb, size_t *sizep)
2483 {
2484 	struct proc *p;
2485 	size_t size;
2486 	int structsize;
2487 
2488 	p = (struct proc *)arg;
2489 	size = sizeof(structsize) + p->p_ucred->cr_ngroups * sizeof(gid_t);
2490 	if (sb != NULL) {
2491 		KASSERT(*sizep == size, ("invalid size"));
2492 		structsize = sizeof(gid_t);
2493 		sbuf_bcat(sb, &structsize, sizeof(structsize));
2494 		sbuf_bcat(sb, p->p_ucred->cr_groups, p->p_ucred->cr_ngroups *
2495 		    sizeof(gid_t));
2496 	}
2497 	*sizep = size;
2498 }
2499 
2500 static void
2501 note_procstat_umask(void *arg, struct sbuf *sb, size_t *sizep)
2502 {
2503 	struct proc *p;
2504 	size_t size;
2505 	int structsize;
2506 
2507 	p = (struct proc *)arg;
2508 	size = sizeof(structsize) + sizeof(p->p_fd->fd_cmask);
2509 	if (sb != NULL) {
2510 		KASSERT(*sizep == size, ("invalid size"));
2511 		structsize = sizeof(p->p_fd->fd_cmask);
2512 		sbuf_bcat(sb, &structsize, sizeof(structsize));
2513 		sbuf_bcat(sb, &p->p_fd->fd_cmask, sizeof(p->p_fd->fd_cmask));
2514 	}
2515 	*sizep = size;
2516 }
2517 
2518 static void
2519 note_procstat_rlimit(void *arg, struct sbuf *sb, size_t *sizep)
2520 {
2521 	struct proc *p;
2522 	struct rlimit rlim[RLIM_NLIMITS];
2523 	size_t size;
2524 	int structsize, i;
2525 
2526 	p = (struct proc *)arg;
2527 	size = sizeof(structsize) + sizeof(rlim);
2528 	if (sb != NULL) {
2529 		KASSERT(*sizep == size, ("invalid size"));
2530 		structsize = sizeof(rlim);
2531 		sbuf_bcat(sb, &structsize, sizeof(structsize));
2532 		PROC_LOCK(p);
2533 		for (i = 0; i < RLIM_NLIMITS; i++)
2534 			lim_rlimit_proc(p, i, &rlim[i]);
2535 		PROC_UNLOCK(p);
2536 		sbuf_bcat(sb, rlim, sizeof(rlim));
2537 	}
2538 	*sizep = size;
2539 }
2540 
2541 static void
2542 note_procstat_osrel(void *arg, struct sbuf *sb, size_t *sizep)
2543 {
2544 	struct proc *p;
2545 	size_t size;
2546 	int structsize;
2547 
2548 	p = (struct proc *)arg;
2549 	size = sizeof(structsize) + sizeof(p->p_osrel);
2550 	if (sb != NULL) {
2551 		KASSERT(*sizep == size, ("invalid size"));
2552 		structsize = sizeof(p->p_osrel);
2553 		sbuf_bcat(sb, &structsize, sizeof(structsize));
2554 		sbuf_bcat(sb, &p->p_osrel, sizeof(p->p_osrel));
2555 	}
2556 	*sizep = size;
2557 }
2558 
2559 static void
2560 __elfN(note_procstat_psstrings)(void *arg, struct sbuf *sb, size_t *sizep)
2561 {
2562 	struct proc *p;
2563 	elf_ps_strings_t ps_strings;
2564 	size_t size;
2565 	int structsize;
2566 
2567 	p = (struct proc *)arg;
2568 	size = sizeof(structsize) + sizeof(ps_strings);
2569 	if (sb != NULL) {
2570 		KASSERT(*sizep == size, ("invalid size"));
2571 		structsize = sizeof(ps_strings);
2572 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
2573 		ps_strings = PTROUT(p->p_sysent->sv_psstrings);
2574 #else
2575 		ps_strings = p->p_sysent->sv_psstrings;
2576 #endif
2577 		sbuf_bcat(sb, &structsize, sizeof(structsize));
2578 		sbuf_bcat(sb, &ps_strings, sizeof(ps_strings));
2579 	}
2580 	*sizep = size;
2581 }
2582 
2583 static void
2584 __elfN(note_procstat_auxv)(void *arg, struct sbuf *sb, size_t *sizep)
2585 {
2586 	struct proc *p;
2587 	size_t size;
2588 	int structsize;
2589 
2590 	p = (struct proc *)arg;
2591 	if (sb == NULL) {
2592 		size = 0;
2593 		sb = sbuf_new(NULL, NULL, 128, SBUF_FIXEDLEN);
2594 		sbuf_set_drain(sb, sbuf_count_drain, &size);
2595 		sbuf_bcat(sb, &structsize, sizeof(structsize));
2596 		PHOLD(p);
2597 		proc_getauxv(curthread, p, sb);
2598 		PRELE(p);
2599 		sbuf_finish(sb);
2600 		sbuf_delete(sb);
2601 		*sizep = size;
2602 	} else {
2603 		structsize = sizeof(Elf_Auxinfo);
2604 		sbuf_bcat(sb, &structsize, sizeof(structsize));
2605 		PHOLD(p);
2606 		proc_getauxv(curthread, p, sb);
2607 		PRELE(p);
2608 	}
2609 }
2610 
2611 static boolean_t
2612 __elfN(parse_notes)(struct image_params *imgp, Elf_Note *checknote,
2613     const char *note_vendor, const Elf_Phdr *pnote,
2614     boolean_t (*cb)(const Elf_Note *, void *, boolean_t *), void *cb_arg)
2615 {
2616 	const Elf_Note *note, *note0, *note_end;
2617 	const char *note_name;
2618 	char *buf;
2619 	int i, error;
2620 	boolean_t res;
2621 
2622 	/* We need some limit, might as well use PAGE_SIZE. */
2623 	if (pnote == NULL || pnote->p_filesz > PAGE_SIZE)
2624 		return (FALSE);
2625 	ASSERT_VOP_LOCKED(imgp->vp, "parse_notes");
2626 	if (pnote->p_offset > PAGE_SIZE ||
2627 	    pnote->p_filesz > PAGE_SIZE - pnote->p_offset) {
2628 		buf = malloc(pnote->p_filesz, M_TEMP, M_NOWAIT);
2629 		if (buf == NULL) {
2630 			VOP_UNLOCK(imgp->vp);
2631 			buf = malloc(pnote->p_filesz, M_TEMP, M_WAITOK);
2632 			vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
2633 		}
2634 		error = vn_rdwr(UIO_READ, imgp->vp, buf, pnote->p_filesz,
2635 		    pnote->p_offset, UIO_SYSSPACE, IO_NODELOCKED,
2636 		    curthread->td_ucred, NOCRED, NULL, curthread);
2637 		if (error != 0) {
2638 			uprintf("i/o error PT_NOTE\n");
2639 			goto retf;
2640 		}
2641 		note = note0 = (const Elf_Note *)buf;
2642 		note_end = (const Elf_Note *)(buf + pnote->p_filesz);
2643 	} else {
2644 		note = note0 = (const Elf_Note *)(imgp->image_header +
2645 		    pnote->p_offset);
2646 		note_end = (const Elf_Note *)(imgp->image_header +
2647 		    pnote->p_offset + pnote->p_filesz);
2648 		buf = NULL;
2649 	}
2650 	for (i = 0; i < 100 && note >= note0 && note < note_end; i++) {
2651 		if (!aligned(note, Elf32_Addr) || (const char *)note_end -
2652 		    (const char *)note < sizeof(Elf_Note)) {
2653 			goto retf;
2654 		}
2655 		if (note->n_namesz != checknote->n_namesz ||
2656 		    note->n_descsz != checknote->n_descsz ||
2657 		    note->n_type != checknote->n_type)
2658 			goto nextnote;
2659 		note_name = (const char *)(note + 1);
2660 		if (note_name + checknote->n_namesz >=
2661 		    (const char *)note_end || strncmp(note_vendor,
2662 		    note_name, checknote->n_namesz) != 0)
2663 			goto nextnote;
2664 
2665 		if (cb(note, cb_arg, &res))
2666 			goto ret;
2667 nextnote:
2668 		note = (const Elf_Note *)((const char *)(note + 1) +
2669 		    roundup2(note->n_namesz, ELF_NOTE_ROUNDSIZE) +
2670 		    roundup2(note->n_descsz, ELF_NOTE_ROUNDSIZE));
2671 	}
2672 retf:
2673 	res = FALSE;
2674 ret:
2675 	free(buf, M_TEMP);
2676 	return (res);
2677 }
2678 
2679 struct brandnote_cb_arg {
2680 	Elf_Brandnote *brandnote;
2681 	int32_t *osrel;
2682 };
2683 
2684 static boolean_t
2685 brandnote_cb(const Elf_Note *note, void *arg0, boolean_t *res)
2686 {
2687 	struct brandnote_cb_arg *arg;
2688 
2689 	arg = arg0;
2690 
2691 	/*
2692 	 * Fetch the osreldate for binary from the ELF OSABI-note if
2693 	 * necessary.
2694 	 */
2695 	*res = (arg->brandnote->flags & BN_TRANSLATE_OSREL) != 0 &&
2696 	    arg->brandnote->trans_osrel != NULL ?
2697 	    arg->brandnote->trans_osrel(note, arg->osrel) : TRUE;
2698 
2699 	return (TRUE);
2700 }
2701 
2702 static Elf_Note fctl_note = {
2703 	.n_namesz = sizeof(FREEBSD_ABI_VENDOR),
2704 	.n_descsz = sizeof(uint32_t),
2705 	.n_type = NT_FREEBSD_FEATURE_CTL,
2706 };
2707 
2708 struct fctl_cb_arg {
2709 	boolean_t *has_fctl0;
2710 	uint32_t *fctl0;
2711 };
2712 
2713 static boolean_t
2714 note_fctl_cb(const Elf_Note *note, void *arg0, boolean_t *res)
2715 {
2716 	struct fctl_cb_arg *arg;
2717 	const Elf32_Word *desc;
2718 	uintptr_t p;
2719 
2720 	arg = arg0;
2721 	p = (uintptr_t)(note + 1);
2722 	p += roundup2(note->n_namesz, ELF_NOTE_ROUNDSIZE);
2723 	desc = (const Elf32_Word *)p;
2724 	*arg->has_fctl0 = TRUE;
2725 	*arg->fctl0 = desc[0];
2726 	return (TRUE);
2727 }
2728 
2729 /*
2730  * Try to find the appropriate ABI-note section for checknote, fetch
2731  * the osreldate and feature control flags for binary from the ELF
2732  * OSABI-note.  Only the first page of the image is searched, the same
2733  * as for headers.
2734  */
2735 static boolean_t
2736 __elfN(check_note)(struct image_params *imgp, Elf_Brandnote *brandnote,
2737     int32_t *osrel, boolean_t *has_fctl0, uint32_t *fctl0)
2738 {
2739 	const Elf_Phdr *phdr;
2740 	const Elf_Ehdr *hdr;
2741 	struct brandnote_cb_arg b_arg;
2742 	struct fctl_cb_arg f_arg;
2743 	int i, j;
2744 
2745 	hdr = (const Elf_Ehdr *)imgp->image_header;
2746 	phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
2747 	b_arg.brandnote = brandnote;
2748 	b_arg.osrel = osrel;
2749 	f_arg.has_fctl0 = has_fctl0;
2750 	f_arg.fctl0 = fctl0;
2751 
2752 	for (i = 0; i < hdr->e_phnum; i++) {
2753 		if (phdr[i].p_type == PT_NOTE && __elfN(parse_notes)(imgp,
2754 		    &brandnote->hdr, brandnote->vendor, &phdr[i], brandnote_cb,
2755 		    &b_arg)) {
2756 			for (j = 0; j < hdr->e_phnum; j++) {
2757 				if (phdr[j].p_type == PT_NOTE &&
2758 				    __elfN(parse_notes)(imgp, &fctl_note,
2759 				    FREEBSD_ABI_VENDOR, &phdr[j],
2760 				    note_fctl_cb, &f_arg))
2761 					break;
2762 			}
2763 			return (TRUE);
2764 		}
2765 	}
2766 	return (FALSE);
2767 
2768 }
2769 
2770 /*
2771  * Tell kern_execve.c about it, with a little help from the linker.
2772  */
2773 static struct execsw __elfN(execsw) = {
2774 	.ex_imgact = __CONCAT(exec_, __elfN(imgact)),
2775 	.ex_name = __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE))
2776 };
2777 EXEC_SET(__CONCAT(elf, __ELF_WORD_SIZE), __elfN(execsw));
2778 
2779 static vm_prot_t
2780 __elfN(trans_prot)(Elf_Word flags)
2781 {
2782 	vm_prot_t prot;
2783 
2784 	prot = 0;
2785 	if (flags & PF_X)
2786 		prot |= VM_PROT_EXECUTE;
2787 	if (flags & PF_W)
2788 		prot |= VM_PROT_WRITE;
2789 	if (flags & PF_R)
2790 		prot |= VM_PROT_READ;
2791 #if __ELF_WORD_SIZE == 32 && (defined(__amd64__) || defined(__i386__))
2792 	if (i386_read_exec && (flags & PF_R))
2793 		prot |= VM_PROT_EXECUTE;
2794 #endif
2795 	return (prot);
2796 }
2797 
2798 static Elf_Word
2799 __elfN(untrans_prot)(vm_prot_t prot)
2800 {
2801 	Elf_Word flags;
2802 
2803 	flags = 0;
2804 	if (prot & VM_PROT_EXECUTE)
2805 		flags |= PF_X;
2806 	if (prot & VM_PROT_READ)
2807 		flags |= PF_R;
2808 	if (prot & VM_PROT_WRITE)
2809 		flags |= PF_W;
2810 	return (flags);
2811 }
2812 
2813 void
2814 __elfN(stackgap)(struct image_params *imgp, uintptr_t *stack_base)
2815 {
2816 	uintptr_t range, rbase, gap;
2817 	int pct;
2818 
2819 	if ((imgp->map_flags & MAP_ASLR) == 0)
2820 		return;
2821 	pct = __elfN(aslr_stack_gap);
2822 	if (pct == 0)
2823 		return;
2824 	if (pct > 50)
2825 		pct = 50;
2826 	range = imgp->eff_stack_sz * pct / 100;
2827 	arc4rand(&rbase, sizeof(rbase), 0);
2828 	gap = rbase % range;
2829 	gap &= ~(sizeof(u_long) - 1);
2830 	*stack_base -= gap;
2831 }
2832