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