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