xref: /freebsd/sys/kern/imgact_elf.c (revision d22c735e033e47d58878a9c00aa09e90e6e83f06)
1 /*-
2  * Copyright (c) 2000 David O'Brien
3  * Copyright (c) 1995-1996 Søren Schmidt
4  * Copyright (c) 1996 Peter Wemm
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer
12  *    in this position and unchanged.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. The name of the author may not be used to endorse or promote products
17  *    derived from this software without specific prior written permission
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30 
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33 
34 #include "opt_capsicum.h"
35 #include "opt_compat.h"
36 #include "opt_core.h"
37 
38 #include <sys/param.h>
39 #include <sys/capsicum.h>
40 #include <sys/exec.h>
41 #include <sys/fcntl.h>
42 #include <sys/imgact.h>
43 #include <sys/imgact_elf.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/pioctl.h>
51 #include <sys/proc.h>
52 #include <sys/procfs.h>
53 #include <sys/racct.h>
54 #include <sys/resourcevar.h>
55 #include <sys/rwlock.h>
56 #include <sys/sbuf.h>
57 #include <sys/sf_buf.h>
58 #include <sys/smp.h>
59 #include <sys/systm.h>
60 #include <sys/signalvar.h>
61 #include <sys/stat.h>
62 #include <sys/sx.h>
63 #include <sys/syscall.h>
64 #include <sys/sysctl.h>
65 #include <sys/sysent.h>
66 #include <sys/vnode.h>
67 #include <sys/syslog.h>
68 #include <sys/eventhandler.h>
69 #include <sys/user.h>
70 
71 #include <net/zlib.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 static int __elfN(check_header)(const Elf_Ehdr *hdr);
88 static Elf_Brandinfo *__elfN(get_brandinfo)(struct image_params *imgp,
89     const char *interp, int interp_name_len, int32_t *osrel);
90 static int __elfN(load_file)(struct proc *p, const char *file, u_long *addr,
91     u_long *entry, size_t pagesize);
92 static int __elfN(load_section)(struct image_params *imgp, vm_offset_t offset,
93     caddr_t vmaddr, size_t memsz, size_t filsz, vm_prot_t prot,
94     size_t pagesize);
95 static int __CONCAT(exec_, __elfN(imgact))(struct image_params *imgp);
96 static boolean_t __elfN(freebsd_trans_osrel)(const Elf_Note *note,
97     int32_t *osrel);
98 static boolean_t kfreebsd_trans_osrel(const Elf_Note *note, int32_t *osrel);
99 static boolean_t __elfN(check_note)(struct image_params *imgp,
100     Elf_Brandnote *checknote, int32_t *osrel);
101 static vm_prot_t __elfN(trans_prot)(Elf_Word);
102 static Elf_Word __elfN(untrans_prot)(vm_prot_t);
103 
104 SYSCTL_NODE(_kern, OID_AUTO, __CONCAT(elf, __ELF_WORD_SIZE), CTLFLAG_RW, 0,
105     "");
106 
107 #ifdef COMPRESS_USER_CORES
108 static int compress_core(gzFile, char *, char *, unsigned int,
109     struct thread * td);
110 #endif
111 #define CORE_BUF_SIZE	(16 * 1024)
112 
113 int __elfN(fallback_brand) = -1;
114 SYSCTL_INT(__CONCAT(_kern_elf, __ELF_WORD_SIZE), OID_AUTO,
115     fallback_brand, CTLFLAG_RW, &__elfN(fallback_brand), 0,
116     __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE)) " brand of last resort");
117 TUNABLE_INT("kern.elf" __XSTRING(__ELF_WORD_SIZE) ".fallback_brand",
118     &__elfN(fallback_brand));
119 
120 static int elf_legacy_coredump = 0;
121 SYSCTL_INT(_debug, OID_AUTO, __elfN(legacy_coredump), CTLFLAG_RW,
122     &elf_legacy_coredump, 0, "");
123 
124 int __elfN(nxstack) =
125 #if defined(__amd64__) || defined(__powerpc64__) /* both 64 and 32 bit */
126 	1;
127 #else
128 	0;
129 #endif
130 SYSCTL_INT(__CONCAT(_kern_elf, __ELF_WORD_SIZE), OID_AUTO,
131     nxstack, CTLFLAG_RW, &__elfN(nxstack), 0,
132     __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE)) ": enable non-executable stack");
133 
134 #if __ELF_WORD_SIZE == 32
135 #if defined(__amd64__) || defined(__ia64__)
136 int i386_read_exec = 0;
137 SYSCTL_INT(_kern_elf32, OID_AUTO, read_exec, CTLFLAG_RW, &i386_read_exec, 0,
138     "enable execution from readable segments");
139 #endif
140 #endif
141 
142 static Elf_Brandinfo *elf_brand_list[MAX_BRANDS];
143 
144 #define	trunc_page_ps(va, ps)	((va) & ~(ps - 1))
145 #define	round_page_ps(va, ps)	(((va) + (ps - 1)) & ~(ps - 1))
146 #define	aligned(a, t)	(trunc_page_ps((u_long)(a), sizeof(t)) == (u_long)(a))
147 
148 static const char FREEBSD_ABI_VENDOR[] = "FreeBSD";
149 
150 Elf_Brandnote __elfN(freebsd_brandnote) = {
151 	.hdr.n_namesz	= sizeof(FREEBSD_ABI_VENDOR),
152 	.hdr.n_descsz	= sizeof(int32_t),
153 	.hdr.n_type	= 1,
154 	.vendor		= FREEBSD_ABI_VENDOR,
155 	.flags		= BN_TRANSLATE_OSREL,
156 	.trans_osrel	= __elfN(freebsd_trans_osrel)
157 };
158 
159 static boolean_t
160 __elfN(freebsd_trans_osrel)(const Elf_Note *note, int32_t *osrel)
161 {
162 	uintptr_t p;
163 
164 	p = (uintptr_t)(note + 1);
165 	p += roundup2(note->n_namesz, ELF_NOTE_ROUNDSIZE);
166 	*osrel = *(const int32_t *)(p);
167 
168 	return (TRUE);
169 }
170 
171 static const char GNU_ABI_VENDOR[] = "GNU";
172 static int GNU_KFREEBSD_ABI_DESC = 3;
173 
174 Elf_Brandnote __elfN(kfreebsd_brandnote) = {
175 	.hdr.n_namesz	= sizeof(GNU_ABI_VENDOR),
176 	.hdr.n_descsz	= 16,	/* XXX at least 16 */
177 	.hdr.n_type	= 1,
178 	.vendor		= GNU_ABI_VENDOR,
179 	.flags		= BN_TRANSLATE_OSREL,
180 	.trans_osrel	= kfreebsd_trans_osrel
181 };
182 
183 static boolean_t
184 kfreebsd_trans_osrel(const Elf_Note *note, int32_t *osrel)
185 {
186 	const Elf32_Word *desc;
187 	uintptr_t p;
188 
189 	p = (uintptr_t)(note + 1);
190 	p += roundup2(note->n_namesz, ELF_NOTE_ROUNDSIZE);
191 
192 	desc = (const Elf32_Word *)p;
193 	if (desc[0] != GNU_KFREEBSD_ABI_DESC)
194 		return (FALSE);
195 
196 	/*
197 	 * Debian GNU/kFreeBSD embed the earliest compatible kernel version
198 	 * (__FreeBSD_version: <major><two digit minor>Rxx) in the LSB way.
199 	 */
200 	*osrel = desc[1] * 100000 + desc[2] * 1000 + desc[3];
201 
202 	return (TRUE);
203 }
204 
205 int
206 __elfN(insert_brand_entry)(Elf_Brandinfo *entry)
207 {
208 	int i;
209 
210 	for (i = 0; i < MAX_BRANDS; i++) {
211 		if (elf_brand_list[i] == NULL) {
212 			elf_brand_list[i] = entry;
213 			break;
214 		}
215 	}
216 	if (i == MAX_BRANDS) {
217 		printf("WARNING: %s: could not insert brandinfo entry: %p\n",
218 			__func__, entry);
219 		return (-1);
220 	}
221 	return (0);
222 }
223 
224 int
225 __elfN(remove_brand_entry)(Elf_Brandinfo *entry)
226 {
227 	int i;
228 
229 	for (i = 0; i < MAX_BRANDS; i++) {
230 		if (elf_brand_list[i] == entry) {
231 			elf_brand_list[i] = NULL;
232 			break;
233 		}
234 	}
235 	if (i == MAX_BRANDS)
236 		return (-1);
237 	return (0);
238 }
239 
240 int
241 __elfN(brand_inuse)(Elf_Brandinfo *entry)
242 {
243 	struct proc *p;
244 	int rval = FALSE;
245 
246 	sx_slock(&allproc_lock);
247 	FOREACH_PROC_IN_SYSTEM(p) {
248 		if (p->p_sysent == entry->sysvec) {
249 			rval = TRUE;
250 			break;
251 		}
252 	}
253 	sx_sunlock(&allproc_lock);
254 
255 	return (rval);
256 }
257 
258 static Elf_Brandinfo *
259 __elfN(get_brandinfo)(struct image_params *imgp, const char *interp,
260     int interp_name_len, int32_t *osrel)
261 {
262 	const Elf_Ehdr *hdr = (const Elf_Ehdr *)imgp->image_header;
263 	Elf_Brandinfo *bi;
264 	const char *fname_name, *interp_brand_name;
265 	int fname_len, interp_len;
266 	boolean_t ret;
267 	int i;
268 
269 	/*
270 	 * We support four types of branding -- (1) the ELF EI_OSABI field
271 	 * that SCO added to the ELF spec, (2) FreeBSD 3.x's traditional string
272 	 * branding w/in the ELF header, (3) path of the `interp_path'
273 	 * field, and (4) the ".note.ABI-tag" ELF section.
274 	 */
275 
276 	/* Look for an ".note.ABI-tag" ELF section */
277 	for (i = 0; i < MAX_BRANDS; i++) {
278 		bi = elf_brand_list[i];
279 		if (bi == NULL)
280 			continue;
281 		if (hdr->e_machine == bi->machine && (bi->flags &
282 		    (BI_BRAND_NOTE|BI_BRAND_NOTE_MANDATORY)) != 0) {
283 			ret = __elfN(check_note)(imgp, bi->brand_note, osrel);
284 			if (ret)
285 				return (bi);
286 		}
287 	}
288 
289 	/* If the executable has a brand, search for it in the brand list. */
290 	for (i = 0; i < MAX_BRANDS; i++) {
291 		bi = elf_brand_list[i];
292 		if (bi == NULL || bi->flags & BI_BRAND_NOTE_MANDATORY)
293 			continue;
294 		if (hdr->e_machine == bi->machine &&
295 		    (hdr->e_ident[EI_OSABI] == bi->brand ||
296 		    strncmp((const char *)&hdr->e_ident[OLD_EI_BRAND],
297 		    bi->compat_3_brand, strlen(bi->compat_3_brand)) == 0))
298 			return (bi);
299 	}
300 
301 	/* Lacking a known brand, search for a recognized interpreter. */
302 	if (interp != NULL) {
303 		for (i = 0; i < MAX_BRANDS; i++) {
304 			bi = elf_brand_list[i];
305 			if (bi == NULL || bi->flags & BI_BRAND_NOTE_MANDATORY)
306 				continue;
307 			if (hdr->e_machine == bi->machine &&
308 			    /* ELF image p_filesz includes terminating zero */
309 			    strlen(bi->interp_path) + 1 == interp_name_len &&
310 			    strncmp(interp, bi->interp_path, interp_name_len)
311 			    == 0)
312 				return (bi);
313 		}
314 	}
315 
316 	/* Some ABI allows to run the interpreter itself. */
317 	for (i = 0; i < MAX_BRANDS; i++) {
318 		bi = elf_brand_list[i];
319 		if (bi == NULL || bi->flags & BI_BRAND_NOTE_MANDATORY)
320 			continue;
321 		if (hdr->e_machine != bi->machine ||
322 		    (bi->flags & BI_CAN_EXEC_INTERP) == 0)
323 			continue;
324 		/*
325 		 * Compare the interpreter name not the path to allow run it
326 		 * from everywhere.
327 		 */
328 		interp_brand_name = strrchr(bi->interp_path, '/');
329 		if (interp_brand_name == NULL)
330 			interp_brand_name = bi->interp_path;
331 		interp_len = strlen(interp_brand_name);
332 		fname_name = strrchr(imgp->args->fname, '/');
333 		if (fname_name == NULL)
334 			fname_name = imgp->args->fname;
335 		fname_len = strlen(fname_name);
336 		if (fname_len < interp_len)
337 			continue;
338 		ret = strncmp(fname_name, interp_brand_name, interp_len);
339 		if (ret == 0)
340 			return (bi);
341 	}
342 
343 	/* Lacking a recognized interpreter, try the default brand */
344 	for (i = 0; i < MAX_BRANDS; i++) {
345 		bi = elf_brand_list[i];
346 		if (bi == NULL || bi->flags & BI_BRAND_NOTE_MANDATORY)
347 			continue;
348 		if (hdr->e_machine == bi->machine &&
349 		    __elfN(fallback_brand) == bi->brand)
350 			return (bi);
351 	}
352 	return (NULL);
353 }
354 
355 static int
356 __elfN(check_header)(const Elf_Ehdr *hdr)
357 {
358 	Elf_Brandinfo *bi;
359 	int i;
360 
361 	if (!IS_ELF(*hdr) ||
362 	    hdr->e_ident[EI_CLASS] != ELF_TARG_CLASS ||
363 	    hdr->e_ident[EI_DATA] != ELF_TARG_DATA ||
364 	    hdr->e_ident[EI_VERSION] != EV_CURRENT ||
365 	    hdr->e_phentsize != sizeof(Elf_Phdr) ||
366 	    hdr->e_version != ELF_TARG_VER)
367 		return (ENOEXEC);
368 
369 	/*
370 	 * Make sure we have at least one brand for this machine.
371 	 */
372 
373 	for (i = 0; i < MAX_BRANDS; i++) {
374 		bi = elf_brand_list[i];
375 		if (bi != NULL && bi->machine == hdr->e_machine)
376 			break;
377 	}
378 	if (i == MAX_BRANDS)
379 		return (ENOEXEC);
380 
381 	return (0);
382 }
383 
384 static int
385 __elfN(map_partial)(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
386     vm_offset_t start, vm_offset_t end, vm_prot_t prot)
387 {
388 	struct sf_buf *sf;
389 	int error;
390 	vm_offset_t off;
391 
392 	/*
393 	 * Create the page if it doesn't exist yet. Ignore errors.
394 	 */
395 	vm_map_lock(map);
396 	vm_map_insert(map, NULL, 0, trunc_page(start), round_page(end),
397 	    VM_PROT_ALL, VM_PROT_ALL, 0);
398 	vm_map_unlock(map);
399 
400 	/*
401 	 * Find the page from the underlying object.
402 	 */
403 	if (object) {
404 		sf = vm_imgact_map_page(object, offset);
405 		if (sf == NULL)
406 			return (KERN_FAILURE);
407 		off = offset - trunc_page(offset);
408 		error = copyout((caddr_t)sf_buf_kva(sf) + off, (caddr_t)start,
409 		    end - start);
410 		vm_imgact_unmap_page(sf);
411 		if (error) {
412 			return (KERN_FAILURE);
413 		}
414 	}
415 
416 	return (KERN_SUCCESS);
417 }
418 
419 static int
420 __elfN(map_insert)(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
421     vm_offset_t start, vm_offset_t end, vm_prot_t prot, int cow)
422 {
423 	struct sf_buf *sf;
424 	vm_offset_t off;
425 	vm_size_t sz;
426 	int error, rv;
427 
428 	if (start != trunc_page(start)) {
429 		rv = __elfN(map_partial)(map, object, offset, start,
430 		    round_page(start), prot);
431 		if (rv)
432 			return (rv);
433 		offset += round_page(start) - start;
434 		start = round_page(start);
435 	}
436 	if (end != round_page(end)) {
437 		rv = __elfN(map_partial)(map, object, offset +
438 		    trunc_page(end) - start, trunc_page(end), end, prot);
439 		if (rv)
440 			return (rv);
441 		end = trunc_page(end);
442 	}
443 	if (end > start) {
444 		if (offset & PAGE_MASK) {
445 			/*
446 			 * The mapping is not page aligned. This means we have
447 			 * to copy the data. Sigh.
448 			 */
449 			rv = vm_map_find(map, NULL, 0, &start, end - start, 0,
450 			    VMFS_NO_SPACE, prot | VM_PROT_WRITE, VM_PROT_ALL,
451 			    0);
452 			if (rv)
453 				return (rv);
454 			if (object == NULL)
455 				return (KERN_SUCCESS);
456 			for (; start < end; start += sz) {
457 				sf = vm_imgact_map_page(object, offset);
458 				if (sf == NULL)
459 					return (KERN_FAILURE);
460 				off = offset - trunc_page(offset);
461 				sz = end - start;
462 				if (sz > PAGE_SIZE - off)
463 					sz = PAGE_SIZE - off;
464 				error = copyout((caddr_t)sf_buf_kva(sf) + off,
465 				    (caddr_t)start, sz);
466 				vm_imgact_unmap_page(sf);
467 				if (error) {
468 					return (KERN_FAILURE);
469 				}
470 				offset += sz;
471 			}
472 			rv = KERN_SUCCESS;
473 		} else {
474 			vm_object_reference(object);
475 			vm_map_lock(map);
476 			rv = vm_map_insert(map, object, offset, start, end,
477 			    prot, VM_PROT_ALL, cow);
478 			vm_map_unlock(map);
479 			if (rv != KERN_SUCCESS)
480 				vm_object_deallocate(object);
481 		}
482 		return (rv);
483 	} else {
484 		return (KERN_SUCCESS);
485 	}
486 }
487 
488 static int
489 __elfN(load_section)(struct image_params *imgp, vm_offset_t offset,
490     caddr_t vmaddr, size_t memsz, size_t filsz, vm_prot_t prot,
491     size_t pagesize)
492 {
493 	struct sf_buf *sf;
494 	size_t map_len;
495 	vm_map_t map;
496 	vm_object_t object;
497 	vm_offset_t map_addr;
498 	int error, rv, cow;
499 	size_t copy_len;
500 	vm_offset_t file_addr;
501 
502 	/*
503 	 * It's necessary to fail if the filsz + offset taken from the
504 	 * header is greater than the actual file pager object's size.
505 	 * If we were to allow this, then the vm_map_find() below would
506 	 * walk right off the end of the file object and into the ether.
507 	 *
508 	 * While I'm here, might as well check for something else that
509 	 * is invalid: filsz cannot be greater than memsz.
510 	 */
511 	if ((off_t)filsz + offset > imgp->attr->va_size || filsz > memsz) {
512 		uprintf("elf_load_section: truncated ELF file\n");
513 		return (ENOEXEC);
514 	}
515 
516 	object = imgp->object;
517 	map = &imgp->proc->p_vmspace->vm_map;
518 	map_addr = trunc_page_ps((vm_offset_t)vmaddr, pagesize);
519 	file_addr = trunc_page_ps(offset, pagesize);
520 
521 	/*
522 	 * We have two choices.  We can either clear the data in the last page
523 	 * of an oversized mapping, or we can start the anon mapping a page
524 	 * early and copy the initialized data into that first page.  We
525 	 * choose the second..
526 	 */
527 	if (memsz > filsz)
528 		map_len = trunc_page_ps(offset + filsz, pagesize) - file_addr;
529 	else
530 		map_len = round_page_ps(offset + filsz, pagesize) - file_addr;
531 
532 	if (map_len != 0) {
533 		/* cow flags: don't dump readonly sections in core */
534 		cow = MAP_COPY_ON_WRITE | MAP_PREFAULT |
535 		    (prot & VM_PROT_WRITE ? 0 : MAP_DISABLE_COREDUMP);
536 
537 		rv = __elfN(map_insert)(map,
538 				      object,
539 				      file_addr,	/* file offset */
540 				      map_addr,		/* virtual start */
541 				      map_addr + map_len,/* virtual end */
542 				      prot,
543 				      cow);
544 		if (rv != KERN_SUCCESS)
545 			return (EINVAL);
546 
547 		/* we can stop now if we've covered it all */
548 		if (memsz == filsz) {
549 			return (0);
550 		}
551 	}
552 
553 
554 	/*
555 	 * We have to get the remaining bit of the file into the first part
556 	 * of the oversized map segment.  This is normally because the .data
557 	 * segment in the file is extended to provide bss.  It's a neat idea
558 	 * to try and save a page, but it's a pain in the behind to implement.
559 	 */
560 	copy_len = (offset + filsz) - trunc_page_ps(offset + filsz, pagesize);
561 	map_addr = trunc_page_ps((vm_offset_t)vmaddr + filsz, pagesize);
562 	map_len = round_page_ps((vm_offset_t)vmaddr + memsz, pagesize) -
563 	    map_addr;
564 
565 	/* This had damn well better be true! */
566 	if (map_len != 0) {
567 		rv = __elfN(map_insert)(map, NULL, 0, map_addr, map_addr +
568 		    map_len, VM_PROT_ALL, 0);
569 		if (rv != KERN_SUCCESS) {
570 			return (EINVAL);
571 		}
572 	}
573 
574 	if (copy_len != 0) {
575 		vm_offset_t off;
576 
577 		sf = vm_imgact_map_page(object, offset + filsz);
578 		if (sf == NULL)
579 			return (EIO);
580 
581 		/* send the page fragment to user space */
582 		off = trunc_page_ps(offset + filsz, pagesize) -
583 		    trunc_page(offset + filsz);
584 		error = copyout((caddr_t)sf_buf_kva(sf) + off,
585 		    (caddr_t)map_addr, copy_len);
586 		vm_imgact_unmap_page(sf);
587 		if (error) {
588 			return (error);
589 		}
590 	}
591 
592 	/*
593 	 * set it to the specified protection.
594 	 * XXX had better undo the damage from pasting over the cracks here!
595 	 */
596 	vm_map_protect(map, trunc_page(map_addr), round_page(map_addr +
597 	    map_len), prot, FALSE);
598 
599 	return (0);
600 }
601 
602 /*
603  * Load the file "file" into memory.  It may be either a shared object
604  * or an executable.
605  *
606  * The "addr" reference parameter is in/out.  On entry, it specifies
607  * the address where a shared object should be loaded.  If the file is
608  * an executable, this value is ignored.  On exit, "addr" specifies
609  * where the file was actually loaded.
610  *
611  * The "entry" reference parameter is out only.  On exit, it specifies
612  * the entry point for the loaded file.
613  */
614 static int
615 __elfN(load_file)(struct proc *p, const char *file, u_long *addr,
616 	u_long *entry, size_t pagesize)
617 {
618 	struct {
619 		struct nameidata nd;
620 		struct vattr attr;
621 		struct image_params image_params;
622 	} *tempdata;
623 	const Elf_Ehdr *hdr = NULL;
624 	const Elf_Phdr *phdr = NULL;
625 	struct nameidata *nd;
626 	struct vattr *attr;
627 	struct image_params *imgp;
628 	vm_prot_t prot;
629 	u_long rbase;
630 	u_long base_addr = 0;
631 	int error, i, numsegs;
632 
633 #ifdef CAPABILITY_MODE
634 	/*
635 	 * XXXJA: This check can go away once we are sufficiently confident
636 	 * that the checks in namei() are correct.
637 	 */
638 	if (IN_CAPABILITY_MODE(curthread))
639 		return (ECAPMODE);
640 #endif
641 
642 	tempdata = malloc(sizeof(*tempdata), M_TEMP, M_WAITOK);
643 	nd = &tempdata->nd;
644 	attr = &tempdata->attr;
645 	imgp = &tempdata->image_params;
646 
647 	/*
648 	 * Initialize part of the common data
649 	 */
650 	imgp->proc = p;
651 	imgp->attr = attr;
652 	imgp->firstpage = NULL;
653 	imgp->image_header = NULL;
654 	imgp->object = NULL;
655 	imgp->execlabel = NULL;
656 
657 	NDINIT(nd, LOOKUP, LOCKLEAF | FOLLOW, UIO_SYSSPACE, file, curthread);
658 	if ((error = namei(nd)) != 0) {
659 		nd->ni_vp = NULL;
660 		goto fail;
661 	}
662 	NDFREE(nd, NDF_ONLY_PNBUF);
663 	imgp->vp = nd->ni_vp;
664 
665 	/*
666 	 * Check permissions, modes, uid, etc on the file, and "open" it.
667 	 */
668 	error = exec_check_permissions(imgp);
669 	if (error)
670 		goto fail;
671 
672 	error = exec_map_first_page(imgp);
673 	if (error)
674 		goto fail;
675 
676 	/*
677 	 * Also make certain that the interpreter stays the same, so set
678 	 * its VV_TEXT flag, too.
679 	 */
680 	VOP_SET_TEXT(nd->ni_vp);
681 
682 	imgp->object = nd->ni_vp->v_object;
683 
684 	hdr = (const Elf_Ehdr *)imgp->image_header;
685 	if ((error = __elfN(check_header)(hdr)) != 0)
686 		goto fail;
687 	if (hdr->e_type == ET_DYN)
688 		rbase = *addr;
689 	else if (hdr->e_type == ET_EXEC)
690 		rbase = 0;
691 	else {
692 		error = ENOEXEC;
693 		goto fail;
694 	}
695 
696 	/* Only support headers that fit within first page for now      */
697 	if ((hdr->e_phoff > PAGE_SIZE) ||
698 	    (u_int)hdr->e_phentsize * hdr->e_phnum > PAGE_SIZE - hdr->e_phoff) {
699 		error = ENOEXEC;
700 		goto fail;
701 	}
702 
703 	phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
704 	if (!aligned(phdr, Elf_Addr)) {
705 		error = ENOEXEC;
706 		goto fail;
707 	}
708 
709 	for (i = 0, numsegs = 0; i < hdr->e_phnum; i++) {
710 		if (phdr[i].p_type == PT_LOAD && phdr[i].p_memsz != 0) {
711 			/* Loadable segment */
712 			prot = __elfN(trans_prot)(phdr[i].p_flags);
713 			error = __elfN(load_section)(imgp, phdr[i].p_offset,
714 			    (caddr_t)(uintptr_t)phdr[i].p_vaddr + rbase,
715 			    phdr[i].p_memsz, phdr[i].p_filesz, prot, pagesize);
716 			if (error != 0)
717 				goto fail;
718 			/*
719 			 * Establish the base address if this is the
720 			 * first segment.
721 			 */
722 			if (numsegs == 0)
723   				base_addr = trunc_page(phdr[i].p_vaddr +
724 				    rbase);
725 			numsegs++;
726 		}
727 	}
728 	*addr = base_addr;
729 	*entry = (unsigned long)hdr->e_entry + rbase;
730 
731 fail:
732 	if (imgp->firstpage)
733 		exec_unmap_first_page(imgp);
734 
735 	if (nd->ni_vp)
736 		vput(nd->ni_vp);
737 
738 	free(tempdata, M_TEMP);
739 
740 	return (error);
741 }
742 
743 static int
744 __CONCAT(exec_, __elfN(imgact))(struct image_params *imgp)
745 {
746 	const Elf_Ehdr *hdr = (const Elf_Ehdr *)imgp->image_header;
747 	const Elf_Phdr *phdr;
748 	Elf_Auxargs *elf_auxargs;
749 	struct vmspace *vmspace;
750 	vm_prot_t prot;
751 	u_long text_size = 0, data_size = 0, total_size = 0;
752 	u_long text_addr = 0, data_addr = 0;
753 	u_long seg_size, seg_addr;
754 	u_long addr, baddr, et_dyn_addr, entry = 0, proghdr = 0;
755 	int32_t osrel = 0;
756 	int error = 0, i, n, interp_name_len = 0;
757 	const char *interp = NULL, *newinterp = NULL;
758 	Elf_Brandinfo *brand_info;
759 	char *path;
760 	struct sysentvec *sv;
761 
762 	/*
763 	 * Do we have a valid ELF header ?
764 	 *
765 	 * Only allow ET_EXEC & ET_DYN here, reject ET_DYN later
766 	 * if particular brand doesn't support it.
767 	 */
768 	if (__elfN(check_header)(hdr) != 0 ||
769 	    (hdr->e_type != ET_EXEC && hdr->e_type != ET_DYN))
770 		return (-1);
771 
772 	/*
773 	 * From here on down, we return an errno, not -1, as we've
774 	 * detected an ELF file.
775 	 */
776 
777 	if ((hdr->e_phoff > PAGE_SIZE) ||
778 	    (u_int)hdr->e_phentsize * hdr->e_phnum > PAGE_SIZE - hdr->e_phoff) {
779 		/* Only support headers in first page for now */
780 		return (ENOEXEC);
781 	}
782 	phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
783 	if (!aligned(phdr, Elf_Addr))
784 		return (ENOEXEC);
785 	n = 0;
786 	baddr = 0;
787 	for (i = 0; i < hdr->e_phnum; i++) {
788 		switch (phdr[i].p_type) {
789 		case PT_LOAD:
790 			if (n == 0)
791 				baddr = phdr[i].p_vaddr;
792 			n++;
793 			break;
794 		case PT_INTERP:
795 			/* Path to interpreter */
796 			if (phdr[i].p_filesz > MAXPATHLEN ||
797 			    phdr[i].p_offset > PAGE_SIZE ||
798 			    phdr[i].p_filesz > PAGE_SIZE - phdr[i].p_offset)
799 				return (ENOEXEC);
800 			interp = imgp->image_header + phdr[i].p_offset;
801 			interp_name_len = phdr[i].p_filesz;
802 			break;
803 		case PT_GNU_STACK:
804 			if (__elfN(nxstack))
805 				imgp->stack_prot =
806 				    __elfN(trans_prot)(phdr[i].p_flags);
807 			break;
808 		}
809 	}
810 
811 	brand_info = __elfN(get_brandinfo)(imgp, interp, interp_name_len,
812 	    &osrel);
813 	if (brand_info == NULL) {
814 		uprintf("ELF binary type \"%u\" not known.\n",
815 		    hdr->e_ident[EI_OSABI]);
816 		return (ENOEXEC);
817 	}
818 	if (hdr->e_type == ET_DYN) {
819 		if ((brand_info->flags & BI_CAN_EXEC_DYN) == 0)
820 			return (ENOEXEC);
821 		/*
822 		 * Honour the base load address from the dso if it is
823 		 * non-zero for some reason.
824 		 */
825 		if (baddr == 0)
826 			et_dyn_addr = ET_DYN_LOAD_ADDR;
827 		else
828 			et_dyn_addr = 0;
829 	} else
830 		et_dyn_addr = 0;
831 	sv = brand_info->sysvec;
832 	if (interp != NULL && brand_info->interp_newpath != NULL)
833 		newinterp = brand_info->interp_newpath;
834 
835 	/*
836 	 * Avoid a possible deadlock if the current address space is destroyed
837 	 * and that address space maps the locked vnode.  In the common case,
838 	 * the locked vnode's v_usecount is decremented but remains greater
839 	 * than zero.  Consequently, the vnode lock is not needed by vrele().
840 	 * However, in cases where the vnode lock is external, such as nullfs,
841 	 * v_usecount may become zero.
842 	 *
843 	 * The VV_TEXT flag prevents modifications to the executable while
844 	 * the vnode is unlocked.
845 	 */
846 	VOP_UNLOCK(imgp->vp, 0);
847 
848 	error = exec_new_vmspace(imgp, sv);
849 	imgp->proc->p_sysent = sv;
850 
851 	vn_lock(imgp->vp, LK_EXCLUSIVE | LK_RETRY);
852 	if (error)
853 		return (error);
854 
855 	for (i = 0; i < hdr->e_phnum; i++) {
856 		switch (phdr[i].p_type) {
857 		case PT_LOAD:	/* Loadable segment */
858 			if (phdr[i].p_memsz == 0)
859 				break;
860 			prot = __elfN(trans_prot)(phdr[i].p_flags);
861 			error = __elfN(load_section)(imgp, phdr[i].p_offset,
862 			    (caddr_t)(uintptr_t)phdr[i].p_vaddr + et_dyn_addr,
863 			    phdr[i].p_memsz, phdr[i].p_filesz, prot,
864 			    sv->sv_pagesize);
865 			if (error != 0)
866 				return (error);
867 
868 			/*
869 			 * If this segment contains the program headers,
870 			 * remember their virtual address for the AT_PHDR
871 			 * aux entry. Static binaries don't usually include
872 			 * a PT_PHDR entry.
873 			 */
874 			if (phdr[i].p_offset == 0 &&
875 			    hdr->e_phoff + hdr->e_phnum * hdr->e_phentsize
876 				<= phdr[i].p_filesz)
877 				proghdr = phdr[i].p_vaddr + hdr->e_phoff +
878 				    et_dyn_addr;
879 
880 			seg_addr = trunc_page(phdr[i].p_vaddr + et_dyn_addr);
881 			seg_size = round_page(phdr[i].p_memsz +
882 			    phdr[i].p_vaddr + et_dyn_addr - seg_addr);
883 
884 			/*
885 			 * Make the largest executable segment the official
886 			 * text segment and all others data.
887 			 *
888 			 * Note that obreak() assumes that data_addr +
889 			 * data_size == end of data load area, and the ELF
890 			 * file format expects segments to be sorted by
891 			 * address.  If multiple data segments exist, the
892 			 * last one will be used.
893 			 */
894 
895 			if (phdr[i].p_flags & PF_X && text_size < seg_size) {
896 				text_size = seg_size;
897 				text_addr = seg_addr;
898 			} else {
899 				data_size = seg_size;
900 				data_addr = seg_addr;
901 			}
902 			total_size += seg_size;
903 			break;
904 		case PT_PHDR: 	/* Program header table info */
905 			proghdr = phdr[i].p_vaddr + et_dyn_addr;
906 			break;
907 		default:
908 			break;
909 		}
910 	}
911 
912 	if (data_addr == 0 && data_size == 0) {
913 		data_addr = text_addr;
914 		data_size = text_size;
915 	}
916 
917 	entry = (u_long)hdr->e_entry + et_dyn_addr;
918 
919 	/*
920 	 * Check limits.  It should be safe to check the
921 	 * limits after loading the segments since we do
922 	 * not actually fault in all the segments pages.
923 	 */
924 	PROC_LOCK(imgp->proc);
925 	if (data_size > lim_cur(imgp->proc, RLIMIT_DATA) ||
926 	    text_size > maxtsiz ||
927 	    total_size > lim_cur(imgp->proc, RLIMIT_VMEM) ||
928 	    racct_set(imgp->proc, RACCT_DATA, data_size) != 0 ||
929 	    racct_set(imgp->proc, RACCT_VMEM, total_size) != 0) {
930 		PROC_UNLOCK(imgp->proc);
931 		return (ENOMEM);
932 	}
933 
934 	vmspace = imgp->proc->p_vmspace;
935 	vmspace->vm_tsize = text_size >> PAGE_SHIFT;
936 	vmspace->vm_taddr = (caddr_t)(uintptr_t)text_addr;
937 	vmspace->vm_dsize = data_size >> PAGE_SHIFT;
938 	vmspace->vm_daddr = (caddr_t)(uintptr_t)data_addr;
939 
940 	/*
941 	 * We load the dynamic linker where a userland call
942 	 * to mmap(0, ...) would put it.  The rationale behind this
943 	 * calculation is that it leaves room for the heap to grow to
944 	 * its maximum allowed size.
945 	 */
946 	addr = round_page((vm_offset_t)vmspace->vm_daddr + lim_max(imgp->proc,
947 	    RLIMIT_DATA));
948 	PROC_UNLOCK(imgp->proc);
949 
950 	imgp->entry_addr = entry;
951 
952 	if (interp != NULL) {
953 		int have_interp = FALSE;
954 		VOP_UNLOCK(imgp->vp, 0);
955 		if (brand_info->emul_path != NULL &&
956 		    brand_info->emul_path[0] != '\0') {
957 			path = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
958 			snprintf(path, MAXPATHLEN, "%s%s",
959 			    brand_info->emul_path, interp);
960 			error = __elfN(load_file)(imgp->proc, path, &addr,
961 			    &imgp->entry_addr, sv->sv_pagesize);
962 			free(path, M_TEMP);
963 			if (error == 0)
964 				have_interp = TRUE;
965 		}
966 		if (!have_interp && newinterp != NULL) {
967 			error = __elfN(load_file)(imgp->proc, newinterp, &addr,
968 			    &imgp->entry_addr, sv->sv_pagesize);
969 			if (error == 0)
970 				have_interp = TRUE;
971 		}
972 		if (!have_interp) {
973 			error = __elfN(load_file)(imgp->proc, interp, &addr,
974 			    &imgp->entry_addr, sv->sv_pagesize);
975 		}
976 		vn_lock(imgp->vp, LK_EXCLUSIVE | LK_RETRY);
977 		if (error != 0) {
978 			uprintf("ELF interpreter %s not found\n", interp);
979 			return (error);
980 		}
981 	} else
982 		addr = et_dyn_addr;
983 
984 	/*
985 	 * Construct auxargs table (used by the fixup routine)
986 	 */
987 	elf_auxargs = malloc(sizeof(Elf_Auxargs), M_TEMP, M_WAITOK);
988 	elf_auxargs->execfd = -1;
989 	elf_auxargs->phdr = proghdr;
990 	elf_auxargs->phent = hdr->e_phentsize;
991 	elf_auxargs->phnum = hdr->e_phnum;
992 	elf_auxargs->pagesz = PAGE_SIZE;
993 	elf_auxargs->base = addr;
994 	elf_auxargs->flags = 0;
995 	elf_auxargs->entry = entry;
996 
997 	imgp->auxargs = elf_auxargs;
998 	imgp->interpreted = 0;
999 	imgp->reloc_base = addr;
1000 	imgp->proc->p_osrel = osrel;
1001 
1002 	return (error);
1003 }
1004 
1005 #define	suword __CONCAT(suword, __ELF_WORD_SIZE)
1006 
1007 int
1008 __elfN(freebsd_fixup)(register_t **stack_base, struct image_params *imgp)
1009 {
1010 	Elf_Auxargs *args = (Elf_Auxargs *)imgp->auxargs;
1011 	Elf_Addr *base;
1012 	Elf_Addr *pos;
1013 
1014 	base = (Elf_Addr *)*stack_base;
1015 	pos = base + (imgp->args->argc + imgp->args->envc + 2);
1016 
1017 	if (args->execfd != -1)
1018 		AUXARGS_ENTRY(pos, AT_EXECFD, args->execfd);
1019 	AUXARGS_ENTRY(pos, AT_PHDR, args->phdr);
1020 	AUXARGS_ENTRY(pos, AT_PHENT, args->phent);
1021 	AUXARGS_ENTRY(pos, AT_PHNUM, args->phnum);
1022 	AUXARGS_ENTRY(pos, AT_PAGESZ, args->pagesz);
1023 	AUXARGS_ENTRY(pos, AT_FLAGS, args->flags);
1024 	AUXARGS_ENTRY(pos, AT_ENTRY, args->entry);
1025 	AUXARGS_ENTRY(pos, AT_BASE, args->base);
1026 	if (imgp->execpathp != 0)
1027 		AUXARGS_ENTRY(pos, AT_EXECPATH, imgp->execpathp);
1028 	AUXARGS_ENTRY(pos, AT_OSRELDATE, osreldate);
1029 	if (imgp->canary != 0) {
1030 		AUXARGS_ENTRY(pos, AT_CANARY, imgp->canary);
1031 		AUXARGS_ENTRY(pos, AT_CANARYLEN, imgp->canarylen);
1032 	}
1033 	AUXARGS_ENTRY(pos, AT_NCPUS, mp_ncpus);
1034 	if (imgp->pagesizes != 0) {
1035 		AUXARGS_ENTRY(pos, AT_PAGESIZES, imgp->pagesizes);
1036 		AUXARGS_ENTRY(pos, AT_PAGESIZESLEN, imgp->pagesizeslen);
1037 	}
1038 	if (imgp->sysent->sv_timekeep_base != 0) {
1039 		AUXARGS_ENTRY(pos, AT_TIMEKEEP,
1040 		    imgp->sysent->sv_timekeep_base);
1041 	}
1042 	AUXARGS_ENTRY(pos, AT_STACKPROT, imgp->sysent->sv_shared_page_obj
1043 	    != NULL && imgp->stack_prot != 0 ? imgp->stack_prot :
1044 	    imgp->sysent->sv_stackprot);
1045 	AUXARGS_ENTRY(pos, AT_NULL, 0);
1046 
1047 	free(imgp->auxargs, M_TEMP);
1048 	imgp->auxargs = NULL;
1049 
1050 	base--;
1051 	suword(base, (long)imgp->args->argc);
1052 	*stack_base = (register_t *)base;
1053 	return (0);
1054 }
1055 
1056 /*
1057  * Code for generating ELF core dumps.
1058  */
1059 
1060 typedef void (*segment_callback)(vm_map_entry_t, void *);
1061 
1062 /* Closure for cb_put_phdr(). */
1063 struct phdr_closure {
1064 	Elf_Phdr *phdr;		/* Program header to fill in */
1065 	Elf_Off offset;		/* Offset of segment in core file */
1066 };
1067 
1068 /* Closure for cb_size_segment(). */
1069 struct sseg_closure {
1070 	int count;		/* Count of writable segments. */
1071 	size_t size;		/* Total size of all writable segments. */
1072 };
1073 
1074 typedef void (*outfunc_t)(void *, struct sbuf *, size_t *);
1075 
1076 struct note_info {
1077 	int		type;		/* Note type. */
1078 	outfunc_t 	outfunc; 	/* Output function. */
1079 	void		*outarg;	/* Argument for the output function. */
1080 	size_t		outsize;	/* Output size. */
1081 	TAILQ_ENTRY(note_info) link;	/* Link to the next note info. */
1082 };
1083 
1084 TAILQ_HEAD(note_info_list, note_info);
1085 
1086 static void cb_put_phdr(vm_map_entry_t, void *);
1087 static void cb_size_segment(vm_map_entry_t, void *);
1088 static void each_writable_segment(struct thread *, segment_callback, void *);
1089 static int __elfN(corehdr)(struct thread *, struct vnode *, struct ucred *,
1090     int, void *, size_t, struct note_info_list *, size_t, gzFile);
1091 static void __elfN(prepare_notes)(struct thread *, struct note_info_list *,
1092     size_t *);
1093 static void __elfN(puthdr)(struct thread *, void *, size_t, int, size_t);
1094 static void __elfN(putnote)(struct note_info *, struct sbuf *);
1095 static size_t register_note(struct note_info_list *, int, outfunc_t, void *);
1096 static int sbuf_drain_core_output(void *, const char *, int);
1097 static int sbuf_drain_count(void *arg, const char *data, int len);
1098 
1099 static void __elfN(note_fpregset)(void *, struct sbuf *, size_t *);
1100 static void __elfN(note_prpsinfo)(void *, struct sbuf *, size_t *);
1101 static void __elfN(note_prstatus)(void *, struct sbuf *, size_t *);
1102 static void __elfN(note_threadmd)(void *, struct sbuf *, size_t *);
1103 static void __elfN(note_thrmisc)(void *, struct sbuf *, size_t *);
1104 static void __elfN(note_procstat_auxv)(void *, struct sbuf *, size_t *);
1105 static void __elfN(note_procstat_proc)(void *, struct sbuf *, size_t *);
1106 static void __elfN(note_procstat_psstrings)(void *, struct sbuf *, size_t *);
1107 static void note_procstat_files(void *, struct sbuf *, size_t *);
1108 static void note_procstat_groups(void *, struct sbuf *, size_t *);
1109 static void note_procstat_osrel(void *, struct sbuf *, size_t *);
1110 static void note_procstat_rlimit(void *, struct sbuf *, size_t *);
1111 static void note_procstat_umask(void *, struct sbuf *, size_t *);
1112 static void note_procstat_vmmap(void *, struct sbuf *, size_t *);
1113 
1114 #ifdef COMPRESS_USER_CORES
1115 extern int compress_user_cores;
1116 extern int compress_user_cores_gzlevel;
1117 #endif
1118 
1119 static int
1120 core_output(struct vnode *vp, void *base, size_t len, off_t offset,
1121     struct ucred *active_cred, struct ucred *file_cred,
1122     struct thread *td, char *core_buf, gzFile gzfile) {
1123 
1124 	int error;
1125 	if (gzfile) {
1126 #ifdef COMPRESS_USER_CORES
1127 		error = compress_core(gzfile, base, core_buf, len, td);
1128 #else
1129 		panic("shouldn't be here");
1130 #endif
1131 	} else {
1132 		error = vn_rdwr_inchunks(UIO_WRITE, vp, base, len, offset,
1133 		    UIO_USERSPACE, IO_UNIT | IO_DIRECT, active_cred, file_cred,
1134 		    NULL, td);
1135 	}
1136 	return (error);
1137 }
1138 
1139 /* Coredump output parameters for sbuf drain routine. */
1140 struct sbuf_drain_core_params {
1141 	off_t		offset;
1142 	struct ucred	*active_cred;
1143 	struct ucred	*file_cred;
1144 	struct thread	*td;
1145 	struct vnode	*vp;
1146 #ifdef COMPRESS_USER_CORES
1147 	gzFile		gzfile;
1148 #endif
1149 };
1150 
1151 /*
1152  * Drain into a core file.
1153  */
1154 static int
1155 sbuf_drain_core_output(void *arg, const char *data, int len)
1156 {
1157 	struct sbuf_drain_core_params *p;
1158 	int error, locked;
1159 
1160 	p = (struct sbuf_drain_core_params *)arg;
1161 
1162 	/*
1163 	 * Some kern_proc out routines that print to this sbuf may
1164 	 * call us with the process lock held. Draining with the
1165 	 * non-sleepable lock held is unsafe. The lock is needed for
1166 	 * those routines when dumping a live process. In our case we
1167 	 * can safely release the lock before draining and acquire
1168 	 * again after.
1169 	 */
1170 	locked = PROC_LOCKED(p->td->td_proc);
1171 	if (locked)
1172 		PROC_UNLOCK(p->td->td_proc);
1173 #ifdef COMPRESS_USER_CORES
1174 	if (p->gzfile != Z_NULL)
1175 		error = compress_core(p->gzfile, NULL, __DECONST(char *, data),
1176 		    len, p->td);
1177 	else
1178 #endif
1179 		error = vn_rdwr_inchunks(UIO_WRITE, p->vp,
1180 		    __DECONST(void *, data), len, p->offset, UIO_SYSSPACE,
1181 		    IO_UNIT | IO_DIRECT, p->active_cred, p->file_cred, NULL,
1182 		    p->td);
1183 	if (locked)
1184 		PROC_LOCK(p->td->td_proc);
1185 	if (error != 0)
1186 		return (-error);
1187 	p->offset += len;
1188 	return (len);
1189 }
1190 
1191 /*
1192  * Drain into a counter.
1193  */
1194 static int
1195 sbuf_drain_count(void *arg, const char *data __unused, int len)
1196 {
1197 	size_t *sizep;
1198 
1199 	sizep = (size_t *)arg;
1200 	*sizep += len;
1201 	return (len);
1202 }
1203 
1204 int
1205 __elfN(coredump)(struct thread *td, struct vnode *vp, off_t limit, int flags)
1206 {
1207 	struct ucred *cred = td->td_ucred;
1208 	int error = 0;
1209 	struct sseg_closure seginfo;
1210 	struct note_info_list notelst;
1211 	struct note_info *ninfo;
1212 	void *hdr;
1213 	size_t hdrsize, notesz, coresize;
1214 
1215 	gzFile gzfile = Z_NULL;
1216 	char *core_buf = NULL;
1217 #ifdef COMPRESS_USER_CORES
1218 	char gzopen_flags[8];
1219 	char *p;
1220 	int doing_compress = flags & IMGACT_CORE_COMPRESS;
1221 #endif
1222 
1223 	hdr = NULL;
1224 	TAILQ_INIT(&notelst);
1225 
1226 #ifdef COMPRESS_USER_CORES
1227         if (doing_compress) {
1228                 p = gzopen_flags;
1229                 *p++ = 'w';
1230                 if (compress_user_cores_gzlevel >= 0 &&
1231                     compress_user_cores_gzlevel <= 9)
1232                         *p++ = '0' + compress_user_cores_gzlevel;
1233                 *p = 0;
1234                 gzfile = gz_open("", gzopen_flags, vp);
1235                 if (gzfile == Z_NULL) {
1236                         error = EFAULT;
1237                         goto done;
1238                 }
1239                 core_buf = malloc(CORE_BUF_SIZE, M_TEMP, M_WAITOK | M_ZERO);
1240                 if (!core_buf) {
1241                         error = ENOMEM;
1242                         goto done;
1243                 }
1244         }
1245 #endif
1246 
1247 	/* Size the program segments. */
1248 	seginfo.count = 0;
1249 	seginfo.size = 0;
1250 	each_writable_segment(td, cb_size_segment, &seginfo);
1251 
1252 	/*
1253 	 * Collect info about the core file header area.
1254 	 */
1255 	hdrsize = sizeof(Elf_Ehdr) + sizeof(Elf_Phdr) * (1 + seginfo.count);
1256 	__elfN(prepare_notes)(td, &notelst, &notesz);
1257 	coresize = round_page(hdrsize + notesz) + seginfo.size;
1258 
1259 #ifdef RACCT
1260 	PROC_LOCK(td->td_proc);
1261 	error = racct_add(td->td_proc, RACCT_CORE, coresize);
1262 	PROC_UNLOCK(td->td_proc);
1263 	if (error != 0) {
1264 		error = EFAULT;
1265 		goto done;
1266 	}
1267 #endif
1268 	if (coresize >= limit) {
1269 		error = EFAULT;
1270 		goto done;
1271 	}
1272 
1273 	/*
1274 	 * Allocate memory for building the header, fill it up,
1275 	 * and write it out following the notes.
1276 	 */
1277 	hdr = malloc(hdrsize, M_TEMP, M_WAITOK);
1278 	if (hdr == NULL) {
1279 		error = EINVAL;
1280 		goto done;
1281 	}
1282 	error = __elfN(corehdr)(td, vp, cred, seginfo.count, hdr, hdrsize,
1283 	    &notelst, notesz, gzfile);
1284 
1285 	/* Write the contents of all of the writable segments. */
1286 	if (error == 0) {
1287 		Elf_Phdr *php;
1288 		off_t offset;
1289 		int i;
1290 
1291 		php = (Elf_Phdr *)((char *)hdr + sizeof(Elf_Ehdr)) + 1;
1292 		offset = round_page(hdrsize + notesz);
1293 		for (i = 0; i < seginfo.count; i++) {
1294 			error = core_output(vp, (caddr_t)(uintptr_t)php->p_vaddr,
1295 			    php->p_filesz, offset, cred, NOCRED, curthread, core_buf, gzfile);
1296 			if (error != 0)
1297 				break;
1298 			offset += php->p_filesz;
1299 			php++;
1300 		}
1301 	}
1302 	if (error) {
1303 		log(LOG_WARNING,
1304 		    "Failed to write core file for process %s (error %d)\n",
1305 		    curproc->p_comm, error);
1306 	}
1307 
1308 done:
1309 #ifdef COMPRESS_USER_CORES
1310 	if (core_buf)
1311 		free(core_buf, M_TEMP);
1312 	if (gzfile)
1313 		gzclose(gzfile);
1314 #endif
1315 	while ((ninfo = TAILQ_FIRST(&notelst)) != NULL) {
1316 		TAILQ_REMOVE(&notelst, ninfo, link);
1317 		free(ninfo, M_TEMP);
1318 	}
1319 	if (hdr != NULL)
1320 		free(hdr, M_TEMP);
1321 
1322 	return (error);
1323 }
1324 
1325 /*
1326  * A callback for each_writable_segment() to write out the segment's
1327  * program header entry.
1328  */
1329 static void
1330 cb_put_phdr(entry, closure)
1331 	vm_map_entry_t entry;
1332 	void *closure;
1333 {
1334 	struct phdr_closure *phc = (struct phdr_closure *)closure;
1335 	Elf_Phdr *phdr = phc->phdr;
1336 
1337 	phc->offset = round_page(phc->offset);
1338 
1339 	phdr->p_type = PT_LOAD;
1340 	phdr->p_offset = phc->offset;
1341 	phdr->p_vaddr = entry->start;
1342 	phdr->p_paddr = 0;
1343 	phdr->p_filesz = phdr->p_memsz = entry->end - entry->start;
1344 	phdr->p_align = PAGE_SIZE;
1345 	phdr->p_flags = __elfN(untrans_prot)(entry->protection);
1346 
1347 	phc->offset += phdr->p_filesz;
1348 	phc->phdr++;
1349 }
1350 
1351 /*
1352  * A callback for each_writable_segment() to gather information about
1353  * the number of segments and their total size.
1354  */
1355 static void
1356 cb_size_segment(entry, closure)
1357 	vm_map_entry_t entry;
1358 	void *closure;
1359 {
1360 	struct sseg_closure *ssc = (struct sseg_closure *)closure;
1361 
1362 	ssc->count++;
1363 	ssc->size += entry->end - entry->start;
1364 }
1365 
1366 /*
1367  * For each writable segment in the process's memory map, call the given
1368  * function with a pointer to the map entry and some arbitrary
1369  * caller-supplied data.
1370  */
1371 static void
1372 each_writable_segment(td, func, closure)
1373 	struct thread *td;
1374 	segment_callback func;
1375 	void *closure;
1376 {
1377 	struct proc *p = td->td_proc;
1378 	vm_map_t map = &p->p_vmspace->vm_map;
1379 	vm_map_entry_t entry;
1380 	vm_object_t backing_object, object;
1381 	boolean_t ignore_entry;
1382 
1383 	vm_map_lock_read(map);
1384 	for (entry = map->header.next; entry != &map->header;
1385 	    entry = entry->next) {
1386 		/*
1387 		 * Don't dump inaccessible mappings, deal with legacy
1388 		 * coredump mode.
1389 		 *
1390 		 * Note that read-only segments related to the elf binary
1391 		 * are marked MAP_ENTRY_NOCOREDUMP now so we no longer
1392 		 * need to arbitrarily ignore such segments.
1393 		 */
1394 		if (elf_legacy_coredump) {
1395 			if ((entry->protection & VM_PROT_RW) != VM_PROT_RW)
1396 				continue;
1397 		} else {
1398 			if ((entry->protection & VM_PROT_ALL) == 0)
1399 				continue;
1400 		}
1401 
1402 		/*
1403 		 * Dont include memory segment in the coredump if
1404 		 * MAP_NOCORE is set in mmap(2) or MADV_NOCORE in
1405 		 * madvise(2).  Do not dump submaps (i.e. parts of the
1406 		 * kernel map).
1407 		 */
1408 		if (entry->eflags & (MAP_ENTRY_NOCOREDUMP|MAP_ENTRY_IS_SUB_MAP))
1409 			continue;
1410 
1411 		if ((object = entry->object.vm_object) == NULL)
1412 			continue;
1413 
1414 		/* Ignore memory-mapped devices and such things. */
1415 		VM_OBJECT_RLOCK(object);
1416 		while ((backing_object = object->backing_object) != NULL) {
1417 			VM_OBJECT_RLOCK(backing_object);
1418 			VM_OBJECT_RUNLOCK(object);
1419 			object = backing_object;
1420 		}
1421 		ignore_entry = object->type != OBJT_DEFAULT &&
1422 		    object->type != OBJT_SWAP && object->type != OBJT_VNODE;
1423 		VM_OBJECT_RUNLOCK(object);
1424 		if (ignore_entry)
1425 			continue;
1426 
1427 		(*func)(entry, closure);
1428 	}
1429 	vm_map_unlock_read(map);
1430 }
1431 
1432 /*
1433  * Write the core file header to the file, including padding up to
1434  * the page boundary.
1435  */
1436 static int
1437 __elfN(corehdr)(struct thread *td, struct vnode *vp, struct ucred *cred,
1438     int numsegs, void *hdr, size_t hdrsize, struct note_info_list *notelst,
1439     size_t notesz, gzFile gzfile)
1440 {
1441 	struct sbuf_drain_core_params params;
1442 	struct note_info *ninfo;
1443 	struct sbuf *sb;
1444 	int error;
1445 
1446 	/* Fill in the header. */
1447 	bzero(hdr, hdrsize);
1448 	__elfN(puthdr)(td, hdr, hdrsize, numsegs, notesz);
1449 
1450 	params.offset = 0;
1451 	params.active_cred = cred;
1452 	params.file_cred = NOCRED;
1453 	params.td = td;
1454 	params.vp = vp;
1455 #ifdef COMPRESS_USER_CORES
1456 	params.gzfile = gzfile;
1457 #endif
1458 	sb = sbuf_new(NULL, NULL, CORE_BUF_SIZE, SBUF_FIXEDLEN);
1459 	sbuf_set_drain(sb, sbuf_drain_core_output, &params);
1460 	sbuf_start_section(sb, NULL);
1461 	sbuf_bcat(sb, hdr, hdrsize);
1462 	TAILQ_FOREACH(ninfo, notelst, link)
1463 	    __elfN(putnote)(ninfo, sb);
1464 	/* Align up to a page boundary for the program segments. */
1465 	sbuf_end_section(sb, -1, PAGE_SIZE, 0);
1466 	error = sbuf_finish(sb);
1467 	sbuf_delete(sb);
1468 
1469 	return (error);
1470 }
1471 
1472 static void
1473 __elfN(prepare_notes)(struct thread *td, struct note_info_list *list,
1474     size_t *sizep)
1475 {
1476 	struct proc *p;
1477 	struct thread *thr;
1478 	size_t size;
1479 
1480 	p = td->td_proc;
1481 	size = 0;
1482 
1483 	size += register_note(list, NT_PRPSINFO, __elfN(note_prpsinfo), p);
1484 
1485 	/*
1486 	 * To have the debugger select the right thread (LWP) as the initial
1487 	 * thread, we dump the state of the thread passed to us in td first.
1488 	 * This is the thread that causes the core dump and thus likely to
1489 	 * be the right thread one wants to have selected in the debugger.
1490 	 */
1491 	thr = td;
1492 	while (thr != NULL) {
1493 		size += register_note(list, NT_PRSTATUS,
1494 		    __elfN(note_prstatus), thr);
1495 		size += register_note(list, NT_FPREGSET,
1496 		    __elfN(note_fpregset), thr);
1497 		size += register_note(list, NT_THRMISC,
1498 		    __elfN(note_thrmisc), thr);
1499 		size += register_note(list, -1,
1500 		    __elfN(note_threadmd), thr);
1501 
1502 		thr = (thr == td) ? TAILQ_FIRST(&p->p_threads) :
1503 		    TAILQ_NEXT(thr, td_plist);
1504 		if (thr == td)
1505 			thr = TAILQ_NEXT(thr, td_plist);
1506 	}
1507 
1508 	size += register_note(list, NT_PROCSTAT_PROC,
1509 	    __elfN(note_procstat_proc), p);
1510 	size += register_note(list, NT_PROCSTAT_FILES,
1511 	    note_procstat_files, p);
1512 	size += register_note(list, NT_PROCSTAT_VMMAP,
1513 	    note_procstat_vmmap, p);
1514 	size += register_note(list, NT_PROCSTAT_GROUPS,
1515 	    note_procstat_groups, p);
1516 	size += register_note(list, NT_PROCSTAT_UMASK,
1517 	    note_procstat_umask, p);
1518 	size += register_note(list, NT_PROCSTAT_RLIMIT,
1519 	    note_procstat_rlimit, p);
1520 	size += register_note(list, NT_PROCSTAT_OSREL,
1521 	    note_procstat_osrel, p);
1522 	size += register_note(list, NT_PROCSTAT_PSSTRINGS,
1523 	    __elfN(note_procstat_psstrings), p);
1524 	size += register_note(list, NT_PROCSTAT_AUXV,
1525 	    __elfN(note_procstat_auxv), p);
1526 
1527 	*sizep = size;
1528 }
1529 
1530 static void
1531 __elfN(puthdr)(struct thread *td, void *hdr, size_t hdrsize, int numsegs,
1532     size_t notesz)
1533 {
1534 	Elf_Ehdr *ehdr;
1535 	Elf_Phdr *phdr;
1536 	struct phdr_closure phc;
1537 
1538 	ehdr = (Elf_Ehdr *)hdr;
1539 	phdr = (Elf_Phdr *)((char *)hdr + sizeof(Elf_Ehdr));
1540 
1541 	ehdr->e_ident[EI_MAG0] = ELFMAG0;
1542 	ehdr->e_ident[EI_MAG1] = ELFMAG1;
1543 	ehdr->e_ident[EI_MAG2] = ELFMAG2;
1544 	ehdr->e_ident[EI_MAG3] = ELFMAG3;
1545 	ehdr->e_ident[EI_CLASS] = ELF_CLASS;
1546 	ehdr->e_ident[EI_DATA] = ELF_DATA;
1547 	ehdr->e_ident[EI_VERSION] = EV_CURRENT;
1548 	ehdr->e_ident[EI_OSABI] = ELFOSABI_FREEBSD;
1549 	ehdr->e_ident[EI_ABIVERSION] = 0;
1550 	ehdr->e_ident[EI_PAD] = 0;
1551 	ehdr->e_type = ET_CORE;
1552 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
1553 	ehdr->e_machine = ELF_ARCH32;
1554 #else
1555 	ehdr->e_machine = ELF_ARCH;
1556 #endif
1557 	ehdr->e_version = EV_CURRENT;
1558 	ehdr->e_entry = 0;
1559 	ehdr->e_phoff = sizeof(Elf_Ehdr);
1560 	ehdr->e_flags = 0;
1561 	ehdr->e_ehsize = sizeof(Elf_Ehdr);
1562 	ehdr->e_phentsize = sizeof(Elf_Phdr);
1563 	ehdr->e_phnum = numsegs + 1;
1564 	ehdr->e_shentsize = sizeof(Elf_Shdr);
1565 	ehdr->e_shnum = 0;
1566 	ehdr->e_shstrndx = SHN_UNDEF;
1567 
1568 	/*
1569 	 * Fill in the program header entries.
1570 	 */
1571 
1572 	/* The note segement. */
1573 	phdr->p_type = PT_NOTE;
1574 	phdr->p_offset = hdrsize;
1575 	phdr->p_vaddr = 0;
1576 	phdr->p_paddr = 0;
1577 	phdr->p_filesz = notesz;
1578 	phdr->p_memsz = 0;
1579 	phdr->p_flags = PF_R;
1580 	phdr->p_align = ELF_NOTE_ROUNDSIZE;
1581 	phdr++;
1582 
1583 	/* All the writable segments from the program. */
1584 	phc.phdr = phdr;
1585 	phc.offset = round_page(hdrsize + notesz);
1586 	each_writable_segment(td, cb_put_phdr, &phc);
1587 }
1588 
1589 static size_t
1590 register_note(struct note_info_list *list, int type, outfunc_t out, void *arg)
1591 {
1592 	struct note_info *ninfo;
1593 	size_t size, notesize;
1594 
1595 	size = 0;
1596 	out(arg, NULL, &size);
1597 	ninfo = malloc(sizeof(*ninfo), M_TEMP, M_ZERO | M_WAITOK);
1598 	ninfo->type = type;
1599 	ninfo->outfunc = out;
1600 	ninfo->outarg = arg;
1601 	ninfo->outsize = size;
1602 	TAILQ_INSERT_TAIL(list, ninfo, link);
1603 
1604 	if (type == -1)
1605 		return (size);
1606 
1607 	notesize = sizeof(Elf_Note) +		/* note header */
1608 	    roundup2(8, ELF_NOTE_ROUNDSIZE) +	/* note name ("FreeBSD") */
1609 	    roundup2(size, ELF_NOTE_ROUNDSIZE);	/* note description */
1610 
1611 	return (notesize);
1612 }
1613 
1614 static void
1615 __elfN(putnote)(struct note_info *ninfo, struct sbuf *sb)
1616 {
1617 	Elf_Note note;
1618 	ssize_t old_len;
1619 
1620 	if (ninfo->type == -1) {
1621 		ninfo->outfunc(ninfo->outarg, sb, &ninfo->outsize);
1622 		return;
1623 	}
1624 
1625 	note.n_namesz = 8; /* strlen("FreeBSD") + 1 */
1626 	note.n_descsz = ninfo->outsize;
1627 	note.n_type = ninfo->type;
1628 
1629 	sbuf_bcat(sb, &note, sizeof(note));
1630 	sbuf_start_section(sb, &old_len);
1631 	sbuf_bcat(sb, "FreeBSD", note.n_namesz);
1632 	sbuf_end_section(sb, old_len, ELF_NOTE_ROUNDSIZE, 0);
1633 	if (note.n_descsz == 0)
1634 		return;
1635 	sbuf_start_section(sb, &old_len);
1636 	ninfo->outfunc(ninfo->outarg, sb, &ninfo->outsize);
1637 	sbuf_end_section(sb, old_len, ELF_NOTE_ROUNDSIZE, 0);
1638 }
1639 
1640 /*
1641  * Miscellaneous note out functions.
1642  */
1643 
1644 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
1645 #include <compat/freebsd32/freebsd32.h>
1646 
1647 typedef struct prstatus32 elf_prstatus_t;
1648 typedef struct prpsinfo32 elf_prpsinfo_t;
1649 typedef struct fpreg32 elf_prfpregset_t;
1650 typedef struct fpreg32 elf_fpregset_t;
1651 typedef struct reg32 elf_gregset_t;
1652 typedef struct thrmisc32 elf_thrmisc_t;
1653 #define ELF_KERN_PROC_MASK	KERN_PROC_MASK32
1654 typedef struct kinfo_proc32 elf_kinfo_proc_t;
1655 typedef uint32_t elf_ps_strings_t;
1656 #else
1657 typedef prstatus_t elf_prstatus_t;
1658 typedef prpsinfo_t elf_prpsinfo_t;
1659 typedef prfpregset_t elf_prfpregset_t;
1660 typedef prfpregset_t elf_fpregset_t;
1661 typedef gregset_t elf_gregset_t;
1662 typedef thrmisc_t elf_thrmisc_t;
1663 #define ELF_KERN_PROC_MASK	0
1664 typedef struct kinfo_proc elf_kinfo_proc_t;
1665 typedef vm_offset_t elf_ps_strings_t;
1666 #endif
1667 
1668 static void
1669 __elfN(note_prpsinfo)(void *arg, struct sbuf *sb, size_t *sizep)
1670 {
1671 	struct proc *p;
1672 	elf_prpsinfo_t *psinfo;
1673 
1674 	p = (struct proc *)arg;
1675 	if (sb != NULL) {
1676 		KASSERT(*sizep == sizeof(*psinfo), ("invalid size"));
1677 		psinfo = malloc(sizeof(*psinfo), M_TEMP, M_ZERO | M_WAITOK);
1678 		psinfo->pr_version = PRPSINFO_VERSION;
1679 		psinfo->pr_psinfosz = sizeof(elf_prpsinfo_t);
1680 		strlcpy(psinfo->pr_fname, p->p_comm, sizeof(psinfo->pr_fname));
1681 		/*
1682 		 * XXX - We don't fill in the command line arguments properly
1683 		 * yet.
1684 		 */
1685 		strlcpy(psinfo->pr_psargs, p->p_comm,
1686 		    sizeof(psinfo->pr_psargs));
1687 
1688 		sbuf_bcat(sb, psinfo, sizeof(*psinfo));
1689 		free(psinfo, M_TEMP);
1690 	}
1691 	*sizep = sizeof(*psinfo);
1692 }
1693 
1694 static void
1695 __elfN(note_prstatus)(void *arg, struct sbuf *sb, size_t *sizep)
1696 {
1697 	struct thread *td;
1698 	elf_prstatus_t *status;
1699 
1700 	td = (struct thread *)arg;
1701 	if (sb != NULL) {
1702 		KASSERT(*sizep == sizeof(*status), ("invalid size"));
1703 		status = malloc(sizeof(*status), M_TEMP, M_ZERO | M_WAITOK);
1704 		status->pr_version = PRSTATUS_VERSION;
1705 		status->pr_statussz = sizeof(elf_prstatus_t);
1706 		status->pr_gregsetsz = sizeof(elf_gregset_t);
1707 		status->pr_fpregsetsz = sizeof(elf_fpregset_t);
1708 		status->pr_osreldate = osreldate;
1709 		status->pr_cursig = td->td_proc->p_sig;
1710 		status->pr_pid = td->td_tid;
1711 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
1712 		fill_regs32(td, &status->pr_reg);
1713 #else
1714 		fill_regs(td, &status->pr_reg);
1715 #endif
1716 		sbuf_bcat(sb, status, sizeof(*status));
1717 		free(status, M_TEMP);
1718 	}
1719 	*sizep = sizeof(*status);
1720 }
1721 
1722 static void
1723 __elfN(note_fpregset)(void *arg, struct sbuf *sb, size_t *sizep)
1724 {
1725 	struct thread *td;
1726 	elf_prfpregset_t *fpregset;
1727 
1728 	td = (struct thread *)arg;
1729 	if (sb != NULL) {
1730 		KASSERT(*sizep == sizeof(*fpregset), ("invalid size"));
1731 		fpregset = malloc(sizeof(*fpregset), M_TEMP, M_ZERO | M_WAITOK);
1732 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
1733 		fill_fpregs32(td, fpregset);
1734 #else
1735 		fill_fpregs(td, fpregset);
1736 #endif
1737 		sbuf_bcat(sb, fpregset, sizeof(*fpregset));
1738 		free(fpregset, M_TEMP);
1739 	}
1740 	*sizep = sizeof(*fpregset);
1741 }
1742 
1743 static void
1744 __elfN(note_thrmisc)(void *arg, struct sbuf *sb, size_t *sizep)
1745 {
1746 	struct thread *td;
1747 	elf_thrmisc_t thrmisc;
1748 
1749 	td = (struct thread *)arg;
1750 	if (sb != NULL) {
1751 		KASSERT(*sizep == sizeof(thrmisc), ("invalid size"));
1752 		bzero(&thrmisc._pad, sizeof(thrmisc._pad));
1753 		strcpy(thrmisc.pr_tname, td->td_name);
1754 		sbuf_bcat(sb, &thrmisc, sizeof(thrmisc));
1755 	}
1756 	*sizep = sizeof(thrmisc);
1757 }
1758 
1759 /*
1760  * Allow for MD specific notes, as well as any MD
1761  * specific preparations for writing MI notes.
1762  */
1763 static void
1764 __elfN(note_threadmd)(void *arg, struct sbuf *sb, size_t *sizep)
1765 {
1766 	struct thread *td;
1767 	void *buf;
1768 	size_t size;
1769 
1770 	td = (struct thread *)arg;
1771 	size = *sizep;
1772 	if (size != 0 && sb != NULL)
1773 		buf = malloc(size, M_TEMP, M_ZERO | M_WAITOK);
1774 	else
1775 		buf = NULL;
1776 	size = 0;
1777 	__elfN(dump_thread)(td, buf, &size);
1778 	KASSERT(*sizep == size, ("invalid size"));
1779 	if (size != 0 && sb != NULL)
1780 		sbuf_bcat(sb, buf, size);
1781 	free(buf, M_TEMP);
1782 	*sizep = size;
1783 }
1784 
1785 #ifdef KINFO_PROC_SIZE
1786 CTASSERT(sizeof(struct kinfo_proc) == KINFO_PROC_SIZE);
1787 #endif
1788 
1789 static void
1790 __elfN(note_procstat_proc)(void *arg, struct sbuf *sb, size_t *sizep)
1791 {
1792 	struct proc *p;
1793 	size_t size;
1794 	int structsize;
1795 
1796 	p = (struct proc *)arg;
1797 	size = sizeof(structsize) + p->p_numthreads *
1798 	    sizeof(elf_kinfo_proc_t);
1799 
1800 	if (sb != NULL) {
1801 		KASSERT(*sizep == size, ("invalid size"));
1802 		structsize = sizeof(elf_kinfo_proc_t);
1803 		sbuf_bcat(sb, &structsize, sizeof(structsize));
1804 		PROC_LOCK(p);
1805 		kern_proc_out(p, sb, ELF_KERN_PROC_MASK);
1806 	}
1807 	*sizep = size;
1808 }
1809 
1810 #ifdef KINFO_FILE_SIZE
1811 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
1812 #endif
1813 
1814 static void
1815 note_procstat_files(void *arg, struct sbuf *sb, size_t *sizep)
1816 {
1817 	struct proc *p;
1818 	size_t size;
1819 	int structsize;
1820 
1821 	p = (struct proc *)arg;
1822 	if (sb == NULL) {
1823 		size = 0;
1824 		sb = sbuf_new(NULL, NULL, 128, SBUF_FIXEDLEN);
1825 		sbuf_set_drain(sb, sbuf_drain_count, &size);
1826 		sbuf_bcat(sb, &structsize, sizeof(structsize));
1827 		PROC_LOCK(p);
1828 		kern_proc_filedesc_out(p, sb, -1);
1829 		sbuf_finish(sb);
1830 		sbuf_delete(sb);
1831 		*sizep = size;
1832 	} else {
1833 		structsize = sizeof(struct kinfo_file);
1834 		sbuf_bcat(sb, &structsize, sizeof(structsize));
1835 		PROC_LOCK(p);
1836 		kern_proc_filedesc_out(p, sb, -1);
1837 	}
1838 }
1839 
1840 #ifdef KINFO_VMENTRY_SIZE
1841 CTASSERT(sizeof(struct kinfo_vmentry) == KINFO_VMENTRY_SIZE);
1842 #endif
1843 
1844 static void
1845 note_procstat_vmmap(void *arg, struct sbuf *sb, size_t *sizep)
1846 {
1847 	struct proc *p;
1848 	size_t size;
1849 	int structsize;
1850 
1851 	p = (struct proc *)arg;
1852 	if (sb == NULL) {
1853 		size = 0;
1854 		sb = sbuf_new(NULL, NULL, 128, SBUF_FIXEDLEN);
1855 		sbuf_set_drain(sb, sbuf_drain_count, &size);
1856 		sbuf_bcat(sb, &structsize, sizeof(structsize));
1857 		PROC_LOCK(p);
1858 		kern_proc_vmmap_out(p, sb);
1859 		sbuf_finish(sb);
1860 		sbuf_delete(sb);
1861 		*sizep = size;
1862 	} else {
1863 		structsize = sizeof(struct kinfo_vmentry);
1864 		sbuf_bcat(sb, &structsize, sizeof(structsize));
1865 		PROC_LOCK(p);
1866 		kern_proc_vmmap_out(p, sb);
1867 	}
1868 }
1869 
1870 static void
1871 note_procstat_groups(void *arg, struct sbuf *sb, size_t *sizep)
1872 {
1873 	struct proc *p;
1874 	size_t size;
1875 	int structsize;
1876 
1877 	p = (struct proc *)arg;
1878 	size = sizeof(structsize) + p->p_ucred->cr_ngroups * sizeof(gid_t);
1879 	if (sb != NULL) {
1880 		KASSERT(*sizep == size, ("invalid size"));
1881 		structsize = sizeof(gid_t);
1882 		sbuf_bcat(sb, &structsize, sizeof(structsize));
1883 		sbuf_bcat(sb, p->p_ucred->cr_groups, p->p_ucred->cr_ngroups *
1884 		    sizeof(gid_t));
1885 	}
1886 	*sizep = size;
1887 }
1888 
1889 static void
1890 note_procstat_umask(void *arg, struct sbuf *sb, size_t *sizep)
1891 {
1892 	struct proc *p;
1893 	size_t size;
1894 	int structsize;
1895 
1896 	p = (struct proc *)arg;
1897 	size = sizeof(structsize) + sizeof(p->p_fd->fd_cmask);
1898 	if (sb != NULL) {
1899 		KASSERT(*sizep == size, ("invalid size"));
1900 		structsize = sizeof(p->p_fd->fd_cmask);
1901 		sbuf_bcat(sb, &structsize, sizeof(structsize));
1902 		sbuf_bcat(sb, &p->p_fd->fd_cmask, sizeof(p->p_fd->fd_cmask));
1903 	}
1904 	*sizep = size;
1905 }
1906 
1907 static void
1908 note_procstat_rlimit(void *arg, struct sbuf *sb, size_t *sizep)
1909 {
1910 	struct proc *p;
1911 	struct rlimit rlim[RLIM_NLIMITS];
1912 	size_t size;
1913 	int structsize, i;
1914 
1915 	p = (struct proc *)arg;
1916 	size = sizeof(structsize) + sizeof(rlim);
1917 	if (sb != NULL) {
1918 		KASSERT(*sizep == size, ("invalid size"));
1919 		structsize = sizeof(rlim);
1920 		sbuf_bcat(sb, &structsize, sizeof(structsize));
1921 		PROC_LOCK(p);
1922 		for (i = 0; i < RLIM_NLIMITS; i++)
1923 			lim_rlimit(p, i, &rlim[i]);
1924 		PROC_UNLOCK(p);
1925 		sbuf_bcat(sb, rlim, sizeof(rlim));
1926 	}
1927 	*sizep = size;
1928 }
1929 
1930 static void
1931 note_procstat_osrel(void *arg, struct sbuf *sb, size_t *sizep)
1932 {
1933 	struct proc *p;
1934 	size_t size;
1935 	int structsize;
1936 
1937 	p = (struct proc *)arg;
1938 	size = sizeof(structsize) + sizeof(p->p_osrel);
1939 	if (sb != NULL) {
1940 		KASSERT(*sizep == size, ("invalid size"));
1941 		structsize = sizeof(p->p_osrel);
1942 		sbuf_bcat(sb, &structsize, sizeof(structsize));
1943 		sbuf_bcat(sb, &p->p_osrel, sizeof(p->p_osrel));
1944 	}
1945 	*sizep = size;
1946 }
1947 
1948 static void
1949 __elfN(note_procstat_psstrings)(void *arg, struct sbuf *sb, size_t *sizep)
1950 {
1951 	struct proc *p;
1952 	elf_ps_strings_t ps_strings;
1953 	size_t size;
1954 	int structsize;
1955 
1956 	p = (struct proc *)arg;
1957 	size = sizeof(structsize) + sizeof(ps_strings);
1958 	if (sb != NULL) {
1959 		KASSERT(*sizep == size, ("invalid size"));
1960 		structsize = sizeof(ps_strings);
1961 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
1962 		ps_strings = PTROUT(p->p_sysent->sv_psstrings);
1963 #else
1964 		ps_strings = p->p_sysent->sv_psstrings;
1965 #endif
1966 		sbuf_bcat(sb, &structsize, sizeof(structsize));
1967 		sbuf_bcat(sb, &ps_strings, sizeof(ps_strings));
1968 	}
1969 	*sizep = size;
1970 }
1971 
1972 static void
1973 __elfN(note_procstat_auxv)(void *arg, struct sbuf *sb, size_t *sizep)
1974 {
1975 	struct proc *p;
1976 	size_t size;
1977 	int structsize;
1978 
1979 	p = (struct proc *)arg;
1980 	if (sb == NULL) {
1981 		size = 0;
1982 		sb = sbuf_new(NULL, NULL, 128, SBUF_FIXEDLEN);
1983 		sbuf_set_drain(sb, sbuf_drain_count, &size);
1984 		sbuf_bcat(sb, &structsize, sizeof(structsize));
1985 		PHOLD(p);
1986 		proc_getauxv(curthread, p, sb);
1987 		PRELE(p);
1988 		sbuf_finish(sb);
1989 		sbuf_delete(sb);
1990 		*sizep = size;
1991 	} else {
1992 		structsize = sizeof(Elf_Auxinfo);
1993 		sbuf_bcat(sb, &structsize, sizeof(structsize));
1994 		PHOLD(p);
1995 		proc_getauxv(curthread, p, sb);
1996 		PRELE(p);
1997 	}
1998 }
1999 
2000 static boolean_t
2001 __elfN(parse_notes)(struct image_params *imgp, Elf_Brandnote *checknote,
2002     int32_t *osrel, const Elf_Phdr *pnote)
2003 {
2004 	const Elf_Note *note, *note0, *note_end;
2005 	const char *note_name;
2006 	int i;
2007 
2008 	if (pnote == NULL || pnote->p_offset > PAGE_SIZE ||
2009 	    pnote->p_filesz > PAGE_SIZE - pnote->p_offset)
2010 		return (FALSE);
2011 
2012 	note = note0 = (const Elf_Note *)(imgp->image_header + pnote->p_offset);
2013 	note_end = (const Elf_Note *)(imgp->image_header +
2014 	    pnote->p_offset + pnote->p_filesz);
2015 	for (i = 0; i < 100 && note >= note0 && note < note_end; i++) {
2016 		if (!aligned(note, Elf32_Addr) || (const char *)note_end -
2017 		    (const char *)note < sizeof(Elf_Note))
2018 			return (FALSE);
2019 		if (note->n_namesz != checknote->hdr.n_namesz ||
2020 		    note->n_descsz != checknote->hdr.n_descsz ||
2021 		    note->n_type != checknote->hdr.n_type)
2022 			goto nextnote;
2023 		note_name = (const char *)(note + 1);
2024 		if (note_name + checknote->hdr.n_namesz >=
2025 		    (const char *)note_end || strncmp(checknote->vendor,
2026 		    note_name, checknote->hdr.n_namesz) != 0)
2027 			goto nextnote;
2028 
2029 		/*
2030 		 * Fetch the osreldate for binary
2031 		 * from the ELF OSABI-note if necessary.
2032 		 */
2033 		if ((checknote->flags & BN_TRANSLATE_OSREL) != 0 &&
2034 		    checknote->trans_osrel != NULL)
2035 			return (checknote->trans_osrel(note, osrel));
2036 		return (TRUE);
2037 
2038 nextnote:
2039 		note = (const Elf_Note *)((const char *)(note + 1) +
2040 		    roundup2(note->n_namesz, ELF_NOTE_ROUNDSIZE) +
2041 		    roundup2(note->n_descsz, ELF_NOTE_ROUNDSIZE));
2042 	}
2043 
2044 	return (FALSE);
2045 }
2046 
2047 /*
2048  * Try to find the appropriate ABI-note section for checknote,
2049  * fetch the osreldate for binary from the ELF OSABI-note. Only the
2050  * first page of the image is searched, the same as for headers.
2051  */
2052 static boolean_t
2053 __elfN(check_note)(struct image_params *imgp, Elf_Brandnote *checknote,
2054     int32_t *osrel)
2055 {
2056 	const Elf_Phdr *phdr;
2057 	const Elf_Ehdr *hdr;
2058 	int i;
2059 
2060 	hdr = (const Elf_Ehdr *)imgp->image_header;
2061 	phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
2062 
2063 	for (i = 0; i < hdr->e_phnum; i++) {
2064 		if (phdr[i].p_type == PT_NOTE &&
2065 		    __elfN(parse_notes)(imgp, checknote, osrel, &phdr[i]))
2066 			return (TRUE);
2067 	}
2068 	return (FALSE);
2069 
2070 }
2071 
2072 /*
2073  * Tell kern_execve.c about it, with a little help from the linker.
2074  */
2075 static struct execsw __elfN(execsw) = {
2076 	__CONCAT(exec_, __elfN(imgact)),
2077 	__XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE))
2078 };
2079 EXEC_SET(__CONCAT(elf, __ELF_WORD_SIZE), __elfN(execsw));
2080 
2081 #ifdef COMPRESS_USER_CORES
2082 /*
2083  * Compress and write out a core segment for a user process.
2084  *
2085  * 'inbuf' is the starting address of a VM segment in the process' address
2086  * space that is to be compressed and written out to the core file.  'dest_buf'
2087  * is a buffer in the kernel's address space.  The segment is copied from
2088  * 'inbuf' to 'dest_buf' first before being processed by the compression
2089  * routine gzwrite().  This copying is necessary because the content of the VM
2090  * segment may change between the compression pass and the crc-computation pass
2091  * in gzwrite().  This is because realtime threads may preempt the UNIX kernel.
2092  *
2093  * If inbuf is NULL it is assumed that data is already copied to 'dest_buf'.
2094  */
2095 static int
2096 compress_core (gzFile file, char *inbuf, char *dest_buf, unsigned int len,
2097     struct thread *td)
2098 {
2099 	int len_compressed;
2100 	int error = 0;
2101 	unsigned int chunk_len;
2102 
2103 	while (len) {
2104 		if (inbuf != NULL) {
2105 			chunk_len = (len > CORE_BUF_SIZE) ? CORE_BUF_SIZE : len;
2106 			copyin(inbuf, dest_buf, chunk_len);
2107 			inbuf += chunk_len;
2108 		} else {
2109 			chunk_len = len;
2110 		}
2111 		len_compressed = gzwrite(file, dest_buf, chunk_len);
2112 
2113 		EVENTHANDLER_INVOKE(app_coredump_progress, td, len_compressed);
2114 
2115 		if ((unsigned int)len_compressed != chunk_len) {
2116 			log(LOG_WARNING,
2117 			    "compress_core: length mismatch (0x%x returned, "
2118 			    "0x%x expected)\n", len_compressed, chunk_len);
2119 			EVENTHANDLER_INVOKE(app_coredump_error, td,
2120 			    "compress_core: length mismatch %x -> %x",
2121 			    chunk_len, len_compressed);
2122 			error = EFAULT;
2123 			break;
2124 		}
2125 		len -= chunk_len;
2126 		maybe_yield();
2127 	}
2128 
2129 	return (error);
2130 }
2131 #endif /* COMPRESS_USER_CORES */
2132 
2133 static vm_prot_t
2134 __elfN(trans_prot)(Elf_Word flags)
2135 {
2136 	vm_prot_t prot;
2137 
2138 	prot = 0;
2139 	if (flags & PF_X)
2140 		prot |= VM_PROT_EXECUTE;
2141 	if (flags & PF_W)
2142 		prot |= VM_PROT_WRITE;
2143 	if (flags & PF_R)
2144 		prot |= VM_PROT_READ;
2145 #if __ELF_WORD_SIZE == 32
2146 #if defined(__amd64__) || defined(__ia64__)
2147 	if (i386_read_exec && (flags & PF_R))
2148 		prot |= VM_PROT_EXECUTE;
2149 #endif
2150 #endif
2151 	return (prot);
2152 }
2153 
2154 static Elf_Word
2155 __elfN(untrans_prot)(vm_prot_t prot)
2156 {
2157 	Elf_Word flags;
2158 
2159 	flags = 0;
2160 	if (prot & VM_PROT_EXECUTE)
2161 		flags |= PF_X;
2162 	if (prot & VM_PROT_READ)
2163 		flags |= PF_R;
2164 	if (prot & VM_PROT_WRITE)
2165 		flags |= PF_W;
2166 	return (flags);
2167 }
2168