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