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