2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 2017 Dell EMC
5 * Copyright (c) 2000-2001, 2003 David O'Brien
6 * Copyright (c) 1995-1996 Søren Schmidt
7 * Copyright (c) 1996 Peter Wemm
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer
15 * in this position and unchanged.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. The name of the author may not be used to endorse or promote products
20 * derived from this software without specific prior written permission
22 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
23 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
24 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
25 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
26 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
27 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
31 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
37 #include "opt_capsicum.h"
39 #include <sys/param.h>
40 #include <sys/capsicum.h>
41 #include <sys/compressor.h>
43 #include <sys/fcntl.h>
44 #include <sys/imgact.h>
45 #include <sys/imgact_elf.h>
47 #include <sys/kernel.h>
49 #include <sys/malloc.h>
50 #include <sys/mount.h>
52 #include <sys/namei.h>
53 #include <sys/pioctl.h>
55 #include <sys/procfs.h>
56 #include <sys/ptrace.h>
57 #include <sys/racct.h>
58 #include <sys/resourcevar.h>
59 #include <sys/rwlock.h>
61 #include <sys/sf_buf.h>
63 #include <sys/systm.h>
64 #include <sys/signalvar.h>
67 #include <sys/syscall.h>
68 #include <sys/sysctl.h>
69 #include <sys/sysent.h>
70 #include <sys/vnode.h>
71 #include <sys/syslog.h>
72 #include <sys/eventhandler.h>
76 #include <vm/vm_kern.h>
77 #include <vm/vm_param.h>
79 #include <vm/vm_map.h>
80 #include <vm/vm_object.h>
81 #include <vm/vm_extern.h>
83 #include <machine/elf.h>
84 #include <machine/md_var.h>
86 #define ELF_NOTE_ROUNDSIZE 4
87 #define OLD_EI_BRAND 8
89 static int __elfN(check_header)(const Elf_Ehdr *hdr);
90 static Elf_Brandinfo *__elfN(get_brandinfo)(struct image_params *imgp,
91 const char *interp, int32_t *osrel, uint32_t *fctl0);
92 static int __elfN(load_file)(struct proc *p, const char *file, u_long *addr,
94 static int __elfN(load_section)(struct image_params *imgp, vm_ooffset_t offset,
95 caddr_t vmaddr, size_t memsz, size_t filsz, vm_prot_t prot);
96 static int __CONCAT(exec_, __elfN(imgact))(struct image_params *imgp);
97 static bool __elfN(freebsd_trans_osrel)(const Elf_Note *note,
99 static bool kfreebsd_trans_osrel(const Elf_Note *note, int32_t *osrel);
100 static boolean_t __elfN(check_note)(struct image_params *imgp,
101 Elf_Brandnote *checknote, int32_t *osrel, uint32_t *fctl0);
102 static vm_prot_t __elfN(trans_prot)(Elf_Word);
103 static Elf_Word __elfN(untrans_prot)(vm_prot_t);
105 SYSCTL_NODE(_kern, OID_AUTO, __CONCAT(elf, __ELF_WORD_SIZE),
106 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
109 #define CORE_BUF_SIZE (16 * 1024)
111 int __elfN(fallback_brand) = -1;
112 SYSCTL_INT(__CONCAT(_kern_elf, __ELF_WORD_SIZE), OID_AUTO,
113 fallback_brand, CTLFLAG_RWTUN, &__elfN(fallback_brand), 0,
114 __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE)) " brand of last resort");
116 static int elf_legacy_coredump = 0;
117 SYSCTL_INT(_debug, OID_AUTO, __elfN(legacy_coredump), CTLFLAG_RW,
118 &elf_legacy_coredump, 0,
119 "include all and only RW pages in core dumps");
121 int __elfN(nxstack) =
122 #if defined(__amd64__) || defined(__powerpc64__) /* both 64 and 32 bit */ || \
123 (defined(__arm__) && __ARM_ARCH >= 7) || defined(__aarch64__) || \
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");
133 #if __ELF_WORD_SIZE == 32 && (defined(__amd64__) || defined(__i386__))
134 int i386_read_exec = 0;
135 SYSCTL_INT(_kern_elf32, OID_AUTO, read_exec, CTLFLAG_RW, &i386_read_exec, 0,
136 "enable execution from readable segments");
139 static u_long __elfN(pie_base) = ET_DYN_LOAD_ADDR;
141 sysctl_pie_base(SYSCTL_HANDLER_ARGS)
146 val = __elfN(pie_base);
147 error = sysctl_handle_long(oidp, &val, 0, req);
148 if (error != 0 || req->newptr == NULL)
150 if ((val & PAGE_MASK) != 0)
152 __elfN(pie_base) = val;
155 SYSCTL_PROC(__CONCAT(_kern_elf, __ELF_WORD_SIZE), OID_AUTO, pie_base,
156 CTLTYPE_ULONG | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0,
157 sysctl_pie_base, "LU",
158 "PIE load base without randomization");
160 SYSCTL_NODE(__CONCAT(_kern_elf, __ELF_WORD_SIZE), OID_AUTO, aslr,
161 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
163 #define ASLR_NODE_OID __CONCAT(__CONCAT(_kern_elf, __ELF_WORD_SIZE), _aslr)
165 static int __elfN(aslr_enabled) = 0;
166 SYSCTL_INT(ASLR_NODE_OID, OID_AUTO, enable, CTLFLAG_RWTUN,
167 &__elfN(aslr_enabled), 0,
168 __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE))
169 ": enable address map randomization");
171 static int __elfN(pie_aslr_enabled) = 0;
172 SYSCTL_INT(ASLR_NODE_OID, OID_AUTO, pie_enable, CTLFLAG_RWTUN,
173 &__elfN(pie_aslr_enabled), 0,
174 __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE))
175 ": enable address map randomization for PIE binaries");
177 static int __elfN(aslr_honor_sbrk) = 1;
178 SYSCTL_INT(ASLR_NODE_OID, OID_AUTO, honor_sbrk, CTLFLAG_RW,
179 &__elfN(aslr_honor_sbrk), 0,
180 __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE)) ": assume sbrk is used");
182 static int __elfN(aslr_stack_gap) = 3;
183 SYSCTL_INT(ASLR_NODE_OID, OID_AUTO, stack_gap, CTLFLAG_RW,
184 &__elfN(aslr_stack_gap), 0,
185 __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE))
186 ": maximum percentage of main stack to waste on a random gap");
188 static int __elfN(sigfastblock) = 1;
189 SYSCTL_INT(__CONCAT(_kern_elf, __ELF_WORD_SIZE), OID_AUTO, sigfastblock,
190 CTLFLAG_RWTUN, &__elfN(sigfastblock), 0,
191 "enable sigfastblock for new processes");
193 static Elf_Brandinfo *elf_brand_list[MAX_BRANDS];
195 #define aligned(a, t) (rounddown2((u_long)(a), sizeof(t)) == (u_long)(a))
197 static const char FREEBSD_ABI_VENDOR[] = "FreeBSD";
199 Elf_Brandnote __elfN(freebsd_brandnote) = {
200 .hdr.n_namesz = sizeof(FREEBSD_ABI_VENDOR),
201 .hdr.n_descsz = sizeof(int32_t),
202 .hdr.n_type = NT_FREEBSD_ABI_TAG,
203 .vendor = FREEBSD_ABI_VENDOR,
204 .flags = BN_TRANSLATE_OSREL,
205 .trans_osrel = __elfN(freebsd_trans_osrel)
209 __elfN(freebsd_trans_osrel)(const Elf_Note *note, int32_t *osrel)
213 p = (uintptr_t)(note + 1);
214 p += roundup2(note->n_namesz, ELF_NOTE_ROUNDSIZE);
215 *osrel = *(const int32_t *)(p);
220 static const char GNU_ABI_VENDOR[] = "GNU";
221 static int GNU_KFREEBSD_ABI_DESC = 3;
223 Elf_Brandnote __elfN(kfreebsd_brandnote) = {
224 .hdr.n_namesz = sizeof(GNU_ABI_VENDOR),
225 .hdr.n_descsz = 16, /* XXX at least 16 */
227 .vendor = GNU_ABI_VENDOR,
228 .flags = BN_TRANSLATE_OSREL,
229 .trans_osrel = kfreebsd_trans_osrel
233 kfreebsd_trans_osrel(const Elf_Note *note, int32_t *osrel)
235 const Elf32_Word *desc;
238 p = (uintptr_t)(note + 1);
239 p += roundup2(note->n_namesz, ELF_NOTE_ROUNDSIZE);
241 desc = (const Elf32_Word *)p;
242 if (desc[0] != GNU_KFREEBSD_ABI_DESC)
246 * Debian GNU/kFreeBSD embed the earliest compatible kernel version
247 * (__FreeBSD_version: <major><two digit minor>Rxx) in the LSB way.
249 *osrel = desc[1] * 100000 + desc[2] * 1000 + desc[3];
255 __elfN(insert_brand_entry)(Elf_Brandinfo *entry)
259 for (i = 0; i < MAX_BRANDS; i++) {
260 if (elf_brand_list[i] == NULL) {
261 elf_brand_list[i] = entry;
265 if (i == MAX_BRANDS) {
266 printf("WARNING: %s: could not insert brandinfo entry: %p\n",
274 __elfN(remove_brand_entry)(Elf_Brandinfo *entry)
278 for (i = 0; i < MAX_BRANDS; i++) {
279 if (elf_brand_list[i] == entry) {
280 elf_brand_list[i] = NULL;
290 __elfN(brand_inuse)(Elf_Brandinfo *entry)
295 sx_slock(&allproc_lock);
296 FOREACH_PROC_IN_SYSTEM(p) {
297 if (p->p_sysent == entry->sysvec) {
302 sx_sunlock(&allproc_lock);
307 static Elf_Brandinfo *
308 __elfN(get_brandinfo)(struct image_params *imgp, const char *interp,
309 int32_t *osrel, uint32_t *fctl0)
311 const Elf_Ehdr *hdr = (const Elf_Ehdr *)imgp->image_header;
312 Elf_Brandinfo *bi, *bi_m;
314 int i, interp_name_len;
316 interp_name_len = interp != NULL ? strlen(interp) + 1 : 0;
319 * We support four types of branding -- (1) the ELF EI_OSABI field
320 * that SCO added to the ELF spec, (2) FreeBSD 3.x's traditional string
321 * branding w/in the ELF header, (3) path of the `interp_path'
322 * field, and (4) the ".note.ABI-tag" ELF section.
325 /* Look for an ".note.ABI-tag" ELF section */
327 for (i = 0; i < MAX_BRANDS; i++) {
328 bi = elf_brand_list[i];
331 if (interp != NULL && (bi->flags & BI_BRAND_ONLY_STATIC) != 0)
333 if (hdr->e_machine == bi->machine && (bi->flags &
334 (BI_BRAND_NOTE|BI_BRAND_NOTE_MANDATORY)) != 0) {
335 ret = __elfN(check_note)(imgp, bi->brand_note, osrel,
337 /* Give brand a chance to veto check_note's guess */
338 if (ret && bi->header_supported)
339 ret = bi->header_supported(imgp);
341 * If note checker claimed the binary, but the
342 * interpreter path in the image does not
343 * match default one for the brand, try to
344 * search for other brands with the same
345 * interpreter. Either there is better brand
346 * with the right interpreter, or, failing
347 * this, we return first brand which accepted
348 * our note and, optionally, header.
350 if (ret && bi_m == NULL && interp != NULL &&
351 (bi->interp_path == NULL ||
352 (strlen(bi->interp_path) + 1 != interp_name_len ||
353 strncmp(interp, bi->interp_path, interp_name_len)
365 /* If the executable has a brand, search for it in the brand list. */
366 for (i = 0; i < MAX_BRANDS; i++) {
367 bi = elf_brand_list[i];
368 if (bi == NULL || (bi->flags & BI_BRAND_NOTE_MANDATORY) != 0 ||
369 (interp != NULL && (bi->flags & BI_BRAND_ONLY_STATIC) != 0))
371 if (hdr->e_machine == bi->machine &&
372 (hdr->e_ident[EI_OSABI] == bi->brand ||
373 (bi->compat_3_brand != NULL &&
374 strcmp((const char *)&hdr->e_ident[OLD_EI_BRAND],
375 bi->compat_3_brand) == 0))) {
376 /* Looks good, but give brand a chance to veto */
377 if (bi->header_supported == NULL ||
378 bi->header_supported(imgp)) {
380 * Again, prefer strictly matching
383 if (interp_name_len == 0 &&
384 bi->interp_path == NULL)
386 if (bi->interp_path != NULL &&
387 strlen(bi->interp_path) + 1 ==
388 interp_name_len && strncmp(interp,
389 bi->interp_path, interp_name_len) == 0)
399 /* No known brand, see if the header is recognized by any brand */
400 for (i = 0; i < MAX_BRANDS; i++) {
401 bi = elf_brand_list[i];
402 if (bi == NULL || bi->flags & BI_BRAND_NOTE_MANDATORY ||
403 bi->header_supported == NULL)
405 if (hdr->e_machine == bi->machine) {
406 ret = bi->header_supported(imgp);
412 /* Lacking a known brand, search for a recognized interpreter. */
413 if (interp != NULL) {
414 for (i = 0; i < MAX_BRANDS; i++) {
415 bi = elf_brand_list[i];
416 if (bi == NULL || (bi->flags &
417 (BI_BRAND_NOTE_MANDATORY | BI_BRAND_ONLY_STATIC))
420 if (hdr->e_machine == bi->machine &&
421 bi->interp_path != NULL &&
422 /* ELF image p_filesz includes terminating zero */
423 strlen(bi->interp_path) + 1 == interp_name_len &&
424 strncmp(interp, bi->interp_path, interp_name_len)
425 == 0 && (bi->header_supported == NULL ||
426 bi->header_supported(imgp)))
431 /* Lacking a recognized interpreter, try the default brand */
432 for (i = 0; i < MAX_BRANDS; i++) {
433 bi = elf_brand_list[i];
434 if (bi == NULL || (bi->flags & BI_BRAND_NOTE_MANDATORY) != 0 ||
435 (interp != NULL && (bi->flags & BI_BRAND_ONLY_STATIC) != 0))
437 if (hdr->e_machine == bi->machine &&
438 __elfN(fallback_brand) == bi->brand &&
439 (bi->header_supported == NULL ||
440 bi->header_supported(imgp)))
447 __elfN(check_header)(const Elf_Ehdr *hdr)
453 hdr->e_ident[EI_CLASS] != ELF_TARG_CLASS ||
454 hdr->e_ident[EI_DATA] != ELF_TARG_DATA ||
455 hdr->e_ident[EI_VERSION] != EV_CURRENT ||
456 hdr->e_phentsize != sizeof(Elf_Phdr) ||
457 hdr->e_version != ELF_TARG_VER)
461 * Make sure we have at least one brand for this machine.
464 for (i = 0; i < MAX_BRANDS; i++) {
465 bi = elf_brand_list[i];
466 if (bi != NULL && bi->machine == hdr->e_machine)
476 __elfN(map_partial)(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
477 vm_offset_t start, vm_offset_t end, vm_prot_t prot)
484 * Create the page if it doesn't exist yet. Ignore errors.
486 vm_map_fixed(map, NULL, 0, trunc_page(start), round_page(end) -
487 trunc_page(start), VM_PROT_ALL, VM_PROT_ALL, MAP_CHECK_EXCL);
490 * Find the page from the underlying object.
492 if (object != NULL) {
493 sf = vm_imgact_map_page(object, offset);
495 return (KERN_FAILURE);
496 off = offset - trunc_page(offset);
497 error = copyout((caddr_t)sf_buf_kva(sf) + off, (caddr_t)start,
499 vm_imgact_unmap_page(sf);
501 return (KERN_FAILURE);
504 return (KERN_SUCCESS);
508 __elfN(map_insert)(struct image_params *imgp, vm_map_t map, vm_object_t object,
509 vm_ooffset_t offset, vm_offset_t start, vm_offset_t end, vm_prot_t prot,
515 int error, locked, rv;
517 if (start != trunc_page(start)) {
518 rv = __elfN(map_partial)(map, object, offset, start,
519 round_page(start), prot);
520 if (rv != KERN_SUCCESS)
522 offset += round_page(start) - start;
523 start = round_page(start);
525 if (end != round_page(end)) {
526 rv = __elfN(map_partial)(map, object, offset +
527 trunc_page(end) - start, trunc_page(end), end, prot);
528 if (rv != KERN_SUCCESS)
530 end = trunc_page(end);
533 return (KERN_SUCCESS);
534 if ((offset & PAGE_MASK) != 0) {
536 * The mapping is not page aligned. This means that we have
539 rv = vm_map_fixed(map, NULL, 0, start, end - start,
540 prot | VM_PROT_WRITE, VM_PROT_ALL, MAP_CHECK_EXCL);
541 if (rv != KERN_SUCCESS)
544 return (KERN_SUCCESS);
545 for (; start < end; start += sz) {
546 sf = vm_imgact_map_page(object, offset);
548 return (KERN_FAILURE);
549 off = offset - trunc_page(offset);
551 if (sz > PAGE_SIZE - off)
552 sz = PAGE_SIZE - off;
553 error = copyout((caddr_t)sf_buf_kva(sf) + off,
555 vm_imgact_unmap_page(sf);
557 return (KERN_FAILURE);
561 vm_object_reference(object);
562 rv = vm_map_fixed(map, object, offset, start, end - start,
563 prot, VM_PROT_ALL, cow | MAP_CHECK_EXCL |
564 (object != NULL ? MAP_VN_EXEC : 0));
565 if (rv != KERN_SUCCESS) {
566 locked = VOP_ISLOCKED(imgp->vp);
567 VOP_UNLOCK(imgp->vp);
568 vm_object_deallocate(object);
569 vn_lock(imgp->vp, locked | LK_RETRY);
571 } else if (object != NULL) {
572 MPASS(imgp->vp->v_object == object);
573 VOP_SET_TEXT_CHECKED(imgp->vp);
576 return (KERN_SUCCESS);
580 __elfN(load_section)(struct image_params *imgp, vm_ooffset_t offset,
581 caddr_t vmaddr, size_t memsz, size_t filsz, vm_prot_t prot)
587 vm_offset_t map_addr;
590 vm_ooffset_t file_addr;
593 * It's necessary to fail if the filsz + offset taken from the
594 * header is greater than the actual file pager object's size.
595 * If we were to allow this, then the vm_map_find() below would
596 * walk right off the end of the file object and into the ether.
598 * While I'm here, might as well check for something else that
599 * is invalid: filsz cannot be greater than memsz.
601 if ((filsz != 0 && (off_t)filsz + offset > imgp->attr->va_size) ||
603 uprintf("elf_load_section: truncated ELF file\n");
607 object = imgp->object;
608 map = &imgp->proc->p_vmspace->vm_map;
609 map_addr = trunc_page((vm_offset_t)vmaddr);
610 file_addr = trunc_page(offset);
613 * We have two choices. We can either clear the data in the last page
614 * of an oversized mapping, or we can start the anon mapping a page
615 * early and copy the initialized data into that first page. We
620 else if (memsz > filsz)
621 map_len = trunc_page(offset + filsz) - file_addr;
623 map_len = round_page(offset + filsz) - file_addr;
626 /* cow flags: don't dump readonly sections in core */
627 cow = MAP_COPY_ON_WRITE | MAP_PREFAULT |
628 (prot & VM_PROT_WRITE ? 0 : MAP_DISABLE_COREDUMP);
630 rv = __elfN(map_insert)(imgp, map, object, file_addr,
631 map_addr, map_addr + map_len, prot, cow);
632 if (rv != KERN_SUCCESS)
635 /* we can stop now if we've covered it all */
641 * We have to get the remaining bit of the file into the first part
642 * of the oversized map segment. This is normally because the .data
643 * segment in the file is extended to provide bss. It's a neat idea
644 * to try and save a page, but it's a pain in the behind to implement.
646 copy_len = filsz == 0 ? 0 : (offset + filsz) - trunc_page(offset +
648 map_addr = trunc_page((vm_offset_t)vmaddr + filsz);
649 map_len = round_page((vm_offset_t)vmaddr + memsz) - map_addr;
651 /* This had damn well better be true! */
653 rv = __elfN(map_insert)(imgp, map, NULL, 0, map_addr,
654 map_addr + map_len, prot, 0);
655 if (rv != KERN_SUCCESS)
660 sf = vm_imgact_map_page(object, offset + filsz);
664 /* send the page fragment to user space */
665 error = copyout((caddr_t)sf_buf_kva(sf), (caddr_t)map_addr,
667 vm_imgact_unmap_page(sf);
673 * Remove write access to the page if it was only granted by map_insert
676 if ((prot & VM_PROT_WRITE) == 0)
677 vm_map_protect(map, trunc_page(map_addr), round_page(map_addr +
678 map_len), prot, FALSE);
684 __elfN(load_sections)(struct image_params *imgp, const Elf_Ehdr *hdr,
685 const Elf_Phdr *phdr, u_long rbase, u_long *base_addrp)
692 ASSERT_VOP_LOCKED(imgp->vp, __func__);
697 for (i = 0; i < hdr->e_phnum; i++) {
698 if (phdr[i].p_type != PT_LOAD || phdr[i].p_memsz == 0)
701 /* Loadable segment */
702 prot = __elfN(trans_prot)(phdr[i].p_flags);
703 error = __elfN(load_section)(imgp, phdr[i].p_offset,
704 (caddr_t)(uintptr_t)phdr[i].p_vaddr + rbase,
705 phdr[i].p_memsz, phdr[i].p_filesz, prot);
710 * Establish the base address if this is the first segment.
713 base_addr = trunc_page(phdr[i].p_vaddr + rbase);
718 if (base_addrp != NULL)
719 *base_addrp = base_addr;
725 * Load the file "file" into memory. It may be either a shared object
728 * The "addr" reference parameter is in/out. On entry, it specifies
729 * the address where a shared object should be loaded. If the file is
730 * an executable, this value is ignored. On exit, "addr" specifies
731 * where the file was actually loaded.
733 * The "entry" reference parameter is out only. On exit, it specifies
734 * the entry point for the loaded file.
737 __elfN(load_file)(struct proc *p, const char *file, u_long *addr,
743 struct image_params image_params;
745 const Elf_Ehdr *hdr = NULL;
746 const Elf_Phdr *phdr = NULL;
747 struct nameidata *nd;
749 struct image_params *imgp;
751 u_long base_addr = 0;
754 #ifdef CAPABILITY_MODE
756 * XXXJA: This check can go away once we are sufficiently confident
757 * that the checks in namei() are correct.
759 if (IN_CAPABILITY_MODE(curthread))
763 tempdata = malloc(sizeof(*tempdata), M_TEMP, M_WAITOK | M_ZERO);
765 attr = &tempdata->attr;
766 imgp = &tempdata->image_params;
769 * Initialize part of the common data
774 NDINIT(nd, LOOKUP, ISOPEN | FOLLOW | LOCKSHARED | LOCKLEAF,
775 UIO_SYSSPACE, file, curthread);
776 if ((error = namei(nd)) != 0) {
780 NDFREE(nd, NDF_ONLY_PNBUF);
781 imgp->vp = nd->ni_vp;
784 * Check permissions, modes, uid, etc on the file, and "open" it.
786 error = exec_check_permissions(imgp);
790 error = exec_map_first_page(imgp);
794 imgp->object = nd->ni_vp->v_object;
796 hdr = (const Elf_Ehdr *)imgp->image_header;
797 if ((error = __elfN(check_header)(hdr)) != 0)
799 if (hdr->e_type == ET_DYN)
801 else if (hdr->e_type == ET_EXEC)
808 /* Only support headers that fit within first page for now */
809 if ((hdr->e_phoff > PAGE_SIZE) ||
810 (u_int)hdr->e_phentsize * hdr->e_phnum > PAGE_SIZE - hdr->e_phoff) {
815 phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
816 if (!aligned(phdr, Elf_Addr)) {
821 error = __elfN(load_sections)(imgp, hdr, phdr, rbase, &base_addr);
826 *entry = (unsigned long)hdr->e_entry + rbase;
830 exec_unmap_first_page(imgp);
834 VOP_UNSET_TEXT_CHECKED(nd->ni_vp);
837 free(tempdata, M_TEMP);
843 __CONCAT(rnd_, __elfN(base))(vm_map_t map __unused, u_long minv, u_long maxv,
848 MPASS(vm_map_min(map) <= minv);
849 MPASS(maxv <= vm_map_max(map));
851 MPASS(minv + align < maxv);
852 arc4rand(&rbase, sizeof(rbase), 0);
853 res = roundup(minv, (u_long)align) + rbase % (maxv - minv);
854 res &= ~((u_long)align - 1);
858 ("res %#lx < minv %#lx, maxv %#lx rbase %#lx",
859 res, minv, maxv, rbase));
861 ("res %#lx > maxv %#lx, minv %#lx rbase %#lx",
862 res, maxv, minv, rbase));
867 __elfN(enforce_limits)(struct image_params *imgp, const Elf_Ehdr *hdr,
868 const Elf_Phdr *phdr, u_long et_dyn_addr)
870 struct vmspace *vmspace;
872 u_long text_size, data_size, total_size, text_addr, data_addr;
873 u_long seg_size, seg_addr;
877 text_size = data_size = total_size = text_addr = data_addr = 0;
879 for (i = 0; i < hdr->e_phnum; i++) {
880 if (phdr[i].p_type != PT_LOAD || phdr[i].p_memsz == 0)
883 seg_addr = trunc_page(phdr[i].p_vaddr + et_dyn_addr);
884 seg_size = round_page(phdr[i].p_memsz +
885 phdr[i].p_vaddr + et_dyn_addr - seg_addr);
888 * Make the largest executable segment the official
889 * text segment and all others data.
891 * Note that obreak() assumes that data_addr + data_size == end
892 * of data load area, and the ELF file format expects segments
893 * to be sorted by address. If multiple data segments exist,
894 * the last one will be used.
897 if ((phdr[i].p_flags & PF_X) != 0 && text_size < seg_size) {
898 text_size = seg_size;
899 text_addr = seg_addr;
901 data_size = seg_size;
902 data_addr = seg_addr;
904 total_size += seg_size;
907 if (data_addr == 0 && data_size == 0) {
908 data_addr = text_addr;
909 data_size = text_size;
913 * Check limits. It should be safe to check the
914 * limits after loading the segments since we do
915 * not actually fault in all the segments pages.
917 PROC_LOCK(imgp->proc);
918 if (data_size > lim_cur_proc(imgp->proc, RLIMIT_DATA))
919 err_str = "Data segment size exceeds process limit";
920 else if (text_size > maxtsiz)
921 err_str = "Text segment size exceeds system limit";
922 else if (total_size > lim_cur_proc(imgp->proc, RLIMIT_VMEM))
923 err_str = "Total segment size exceeds process limit";
924 else if (racct_set(imgp->proc, RACCT_DATA, data_size) != 0)
925 err_str = "Data segment size exceeds resource limit";
926 else if (racct_set(imgp->proc, RACCT_VMEM, total_size) != 0)
927 err_str = "Total segment size exceeds resource limit";
928 PROC_UNLOCK(imgp->proc);
929 if (err_str != NULL) {
930 uprintf("%s\n", err_str);
934 vmspace = imgp->proc->p_vmspace;
935 vmspace->vm_tsize = text_size >> PAGE_SHIFT;
936 vmspace->vm_taddr = (caddr_t)(uintptr_t)text_addr;
937 vmspace->vm_dsize = data_size >> PAGE_SHIFT;
938 vmspace->vm_daddr = (caddr_t)(uintptr_t)data_addr;
944 __elfN(get_interp)(struct image_params *imgp, const Elf_Phdr *phdr,
945 char **interpp, bool *free_interpp)
949 int error, interp_name_len;
951 KASSERT(phdr->p_type == PT_INTERP,
952 ("%s: p_type %u != PT_INTERP", __func__, phdr->p_type));
953 ASSERT_VOP_LOCKED(imgp->vp, __func__);
957 /* Path to interpreter */
958 if (phdr->p_filesz < 2 || phdr->p_filesz > MAXPATHLEN) {
959 uprintf("Invalid PT_INTERP\n");
963 interp_name_len = phdr->p_filesz;
964 if (phdr->p_offset > PAGE_SIZE ||
965 interp_name_len > PAGE_SIZE - phdr->p_offset) {
967 * The vnode lock might be needed by the pagedaemon to
968 * clean pages owned by the vnode. Do not allow sleep
969 * waiting for memory with the vnode locked, instead
970 * try non-sleepable allocation first, and if it
971 * fails, go to the slow path were we drop the lock
972 * and do M_WAITOK. A text reference prevents
973 * modifications to the vnode content.
975 interp = malloc(interp_name_len + 1, M_TEMP, M_NOWAIT);
976 if (interp == NULL) {
977 VOP_UNLOCK(imgp->vp);
978 interp = malloc(interp_name_len + 1, M_TEMP, M_WAITOK);
979 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
982 error = vn_rdwr(UIO_READ, imgp->vp, interp,
983 interp_name_len, phdr->p_offset,
984 UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred,
987 free(interp, M_TEMP);
988 uprintf("i/o error PT_INTERP %d\n", error);
991 interp[interp_name_len] = '\0';
994 *free_interpp = true;
998 interp = __DECONST(char *, imgp->image_header) + phdr->p_offset;
999 if (interp[interp_name_len - 1] != '\0') {
1000 uprintf("Invalid PT_INTERP\n");
1005 *free_interpp = false;
1010 __elfN(load_interp)(struct image_params *imgp, const Elf_Brandinfo *brand_info,
1011 const char *interp, u_long *addr, u_long *entry)
1016 if (brand_info->emul_path != NULL &&
1017 brand_info->emul_path[0] != '\0') {
1018 path = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1019 snprintf(path, MAXPATHLEN, "%s%s",
1020 brand_info->emul_path, interp);
1021 error = __elfN(load_file)(imgp->proc, path, addr, entry);
1027 if (brand_info->interp_newpath != NULL &&
1028 (brand_info->interp_path == NULL ||
1029 strcmp(interp, brand_info->interp_path) == 0)) {
1030 error = __elfN(load_file)(imgp->proc,
1031 brand_info->interp_newpath, addr, entry);
1036 error = __elfN(load_file)(imgp->proc, interp, addr, entry);
1040 uprintf("ELF interpreter %s not found, error %d\n", interp, error);
1045 * Impossible et_dyn_addr initial value indicating that the real base
1046 * must be calculated later with some randomization applied.
1048 #define ET_DYN_ADDR_RAND 1
1051 __CONCAT(exec_, __elfN(imgact))(struct image_params *imgp)
1054 const Elf_Ehdr *hdr;
1055 const Elf_Phdr *phdr;
1056 Elf_Auxargs *elf_auxargs;
1057 struct vmspace *vmspace;
1060 Elf_Brandinfo *brand_info;
1061 struct sysentvec *sv;
1062 u_long addr, baddr, et_dyn_addr, entry, proghdr;
1063 u_long maxalign, mapsz, maxv, maxv1;
1069 hdr = (const Elf_Ehdr *)imgp->image_header;
1072 * Do we have a valid ELF header ?
1074 * Only allow ET_EXEC & ET_DYN here, reject ET_DYN later
1075 * if particular brand doesn't support it.
1077 if (__elfN(check_header)(hdr) != 0 ||
1078 (hdr->e_type != ET_EXEC && hdr->e_type != ET_DYN))
1082 * From here on down, we return an errno, not -1, as we've
1083 * detected an ELF file.
1086 if ((hdr->e_phoff > PAGE_SIZE) ||
1087 (u_int)hdr->e_phentsize * hdr->e_phnum > PAGE_SIZE - hdr->e_phoff) {
1088 /* Only support headers in first page for now */
1089 uprintf("Program headers not in the first page\n");
1092 phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
1093 if (!aligned(phdr, Elf_Addr)) {
1094 uprintf("Unaligned program headers\n");
1102 entry = proghdr = 0;
1104 free_interp = false;
1106 maxalign = PAGE_SIZE;
1109 for (i = 0; i < hdr->e_phnum; i++) {
1110 switch (phdr[i].p_type) {
1113 baddr = phdr[i].p_vaddr;
1114 if (phdr[i].p_align > maxalign)
1115 maxalign = phdr[i].p_align;
1116 mapsz += phdr[i].p_memsz;
1120 * If this segment contains the program headers,
1121 * remember their virtual address for the AT_PHDR
1122 * aux entry. Static binaries don't usually include
1125 if (phdr[i].p_offset == 0 &&
1126 hdr->e_phoff + hdr->e_phnum * hdr->e_phentsize
1127 <= phdr[i].p_filesz)
1128 proghdr = phdr[i].p_vaddr + hdr->e_phoff;
1131 /* Path to interpreter */
1132 if (interp != NULL) {
1133 uprintf("Multiple PT_INTERP headers\n");
1137 error = __elfN(get_interp)(imgp, &phdr[i], &interp,
1143 if (__elfN(nxstack))
1145 __elfN(trans_prot)(phdr[i].p_flags);
1146 imgp->stack_sz = phdr[i].p_memsz;
1148 case PT_PHDR: /* Program header table info */
1149 proghdr = phdr[i].p_vaddr;
1154 brand_info = __elfN(get_brandinfo)(imgp, interp, &osrel, &fctl0);
1155 if (brand_info == NULL) {
1156 uprintf("ELF binary type \"%u\" not known.\n",
1157 hdr->e_ident[EI_OSABI]);
1161 sv = brand_info->sysvec;
1163 if (hdr->e_type == ET_DYN) {
1164 if ((brand_info->flags & BI_CAN_EXEC_DYN) == 0) {
1165 uprintf("Cannot execute shared object\n");
1170 * Honour the base load address from the dso if it is
1171 * non-zero for some reason.
1174 if ((sv->sv_flags & SV_ASLR) == 0 ||
1175 (fctl0 & NT_FREEBSD_FCTL_ASLR_DISABLE) != 0)
1176 et_dyn_addr = __elfN(pie_base);
1177 else if ((__elfN(pie_aslr_enabled) &&
1178 (imgp->proc->p_flag2 & P2_ASLR_DISABLE) == 0) ||
1179 (imgp->proc->p_flag2 & P2_ASLR_ENABLE) != 0)
1180 et_dyn_addr = ET_DYN_ADDR_RAND;
1182 et_dyn_addr = __elfN(pie_base);
1187 * Avoid a possible deadlock if the current address space is destroyed
1188 * and that address space maps the locked vnode. In the common case,
1189 * the locked vnode's v_usecount is decremented but remains greater
1190 * than zero. Consequently, the vnode lock is not needed by vrele().
1191 * However, in cases where the vnode lock is external, such as nullfs,
1192 * v_usecount may become zero.
1194 * The VV_TEXT flag prevents modifications to the executable while
1195 * the vnode is unlocked.
1197 VOP_UNLOCK(imgp->vp);
1200 * Decide whether to enable randomization of user mappings.
1201 * First, reset user preferences for the setid binaries.
1202 * Then, account for the support of the randomization by the
1203 * ABI, by user preferences, and make special treatment for
1206 if (imgp->credential_setid) {
1207 PROC_LOCK(imgp->proc);
1208 imgp->proc->p_flag2 &= ~(P2_ASLR_ENABLE | P2_ASLR_DISABLE);
1209 PROC_UNLOCK(imgp->proc);
1211 if ((sv->sv_flags & SV_ASLR) == 0 ||
1212 (imgp->proc->p_flag2 & P2_ASLR_DISABLE) != 0 ||
1213 (fctl0 & NT_FREEBSD_FCTL_ASLR_DISABLE) != 0) {
1214 KASSERT(et_dyn_addr != ET_DYN_ADDR_RAND,
1215 ("et_dyn_addr == RAND and !ASLR"));
1216 } else if ((imgp->proc->p_flag2 & P2_ASLR_ENABLE) != 0 ||
1217 (__elfN(aslr_enabled) && hdr->e_type == ET_EXEC) ||
1218 et_dyn_addr == ET_DYN_ADDR_RAND) {
1219 imgp->map_flags |= MAP_ASLR;
1221 * If user does not care about sbrk, utilize the bss
1222 * grow region for mappings as well. We can select
1223 * the base for the image anywere and still not suffer
1224 * from the fragmentation.
1226 if (!__elfN(aslr_honor_sbrk) ||
1227 (imgp->proc->p_flag2 & P2_ASLR_IGNSTART) != 0)
1228 imgp->map_flags |= MAP_ASLR_IGNSTART;
1231 error = exec_new_vmspace(imgp, sv);
1232 vmspace = imgp->proc->p_vmspace;
1233 map = &vmspace->vm_map;
1235 imgp->proc->p_sysent = sv;
1237 maxv = vm_map_max(map) - lim_max(td, RLIMIT_STACK);
1238 if (et_dyn_addr == ET_DYN_ADDR_RAND) {
1239 KASSERT((map->flags & MAP_ASLR) != 0,
1240 ("ET_DYN_ADDR_RAND but !MAP_ASLR"));
1241 et_dyn_addr = __CONCAT(rnd_, __elfN(base))(map,
1242 vm_map_min(map) + mapsz + lim_max(td, RLIMIT_DATA),
1243 /* reserve half of the address space to interpreter */
1244 maxv / 2, 1UL << flsl(maxalign));
1247 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
1251 error = __elfN(load_sections)(imgp, hdr, phdr, et_dyn_addr, NULL);
1255 error = __elfN(enforce_limits)(imgp, hdr, phdr, et_dyn_addr);
1259 entry = (u_long)hdr->e_entry + et_dyn_addr;
1262 * We load the dynamic linker where a userland call
1263 * to mmap(0, ...) would put it. The rationale behind this
1264 * calculation is that it leaves room for the heap to grow to
1265 * its maximum allowed size.
1267 addr = round_page((vm_offset_t)vmspace->vm_daddr + lim_max(td,
1269 if ((map->flags & MAP_ASLR) != 0) {
1270 maxv1 = maxv / 2 + addr / 2;
1271 MPASS(maxv1 >= addr); /* No overflow */
1272 map->anon_loc = __CONCAT(rnd_, __elfN(base))(map, addr, maxv1,
1273 MAXPAGESIZES > 1 ? pagesizes[1] : pagesizes[0]);
1275 map->anon_loc = addr;
1278 imgp->entry_addr = entry;
1280 if (interp != NULL) {
1281 VOP_UNLOCK(imgp->vp);
1282 if ((map->flags & MAP_ASLR) != 0) {
1283 /* Assume that interpeter fits into 1/4 of AS */
1284 maxv1 = maxv / 2 + addr / 2;
1285 MPASS(maxv1 >= addr); /* No overflow */
1286 addr = __CONCAT(rnd_, __elfN(base))(map, addr,
1289 error = __elfN(load_interp)(imgp, brand_info, interp, &addr,
1291 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
1298 * Construct auxargs table (used by the copyout_auxargs routine)
1300 elf_auxargs = malloc(sizeof(Elf_Auxargs), M_TEMP, M_NOWAIT);
1301 if (elf_auxargs == NULL) {
1302 VOP_UNLOCK(imgp->vp);
1303 elf_auxargs = malloc(sizeof(Elf_Auxargs), M_TEMP, M_WAITOK);
1304 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
1306 elf_auxargs->execfd = -1;
1307 elf_auxargs->phdr = proghdr + et_dyn_addr;
1308 elf_auxargs->phent = hdr->e_phentsize;
1309 elf_auxargs->phnum = hdr->e_phnum;
1310 elf_auxargs->pagesz = PAGE_SIZE;
1311 elf_auxargs->base = addr;
1312 elf_auxargs->flags = 0;
1313 elf_auxargs->entry = entry;
1314 elf_auxargs->hdr_eflags = hdr->e_flags;
1316 imgp->auxargs = elf_auxargs;
1317 imgp->interpreted = 0;
1318 imgp->reloc_base = addr;
1319 imgp->proc->p_osrel = osrel;
1320 imgp->proc->p_fctl0 = fctl0;
1321 imgp->proc->p_elf_machine = hdr->e_machine;
1322 imgp->proc->p_elf_flags = hdr->e_flags;
1326 free(interp, M_TEMP);
1330 #define suword __CONCAT(suword, __ELF_WORD_SIZE)
1333 __elfN(freebsd_copyout_auxargs)(struct image_params *imgp, uintptr_t base)
1335 Elf_Auxargs *args = (Elf_Auxargs *)imgp->auxargs;
1336 Elf_Auxinfo *argarray, *pos;
1339 argarray = pos = malloc(AT_COUNT * sizeof(*pos), M_TEMP,
1342 if (args->execfd != -1)
1343 AUXARGS_ENTRY(pos, AT_EXECFD, args->execfd);
1344 AUXARGS_ENTRY(pos, AT_PHDR, args->phdr);
1345 AUXARGS_ENTRY(pos, AT_PHENT, args->phent);
1346 AUXARGS_ENTRY(pos, AT_PHNUM, args->phnum);
1347 AUXARGS_ENTRY(pos, AT_PAGESZ, args->pagesz);
1348 AUXARGS_ENTRY(pos, AT_FLAGS, args->flags);
1349 AUXARGS_ENTRY(pos, AT_ENTRY, args->entry);
1350 AUXARGS_ENTRY(pos, AT_BASE, args->base);
1351 AUXARGS_ENTRY(pos, AT_EHDRFLAGS, args->hdr_eflags);
1352 if (imgp->execpathp != 0)
1353 AUXARGS_ENTRY(pos, AT_EXECPATH, imgp->execpathp);
1354 AUXARGS_ENTRY(pos, AT_OSRELDATE,
1355 imgp->proc->p_ucred->cr_prison->pr_osreldate);
1356 if (imgp->canary != 0) {
1357 AUXARGS_ENTRY(pos, AT_CANARY, imgp->canary);
1358 AUXARGS_ENTRY(pos, AT_CANARYLEN, imgp->canarylen);
1360 AUXARGS_ENTRY(pos, AT_NCPUS, mp_ncpus);
1361 if (imgp->pagesizes != 0) {
1362 AUXARGS_ENTRY(pos, AT_PAGESIZES, imgp->pagesizes);
1363 AUXARGS_ENTRY(pos, AT_PAGESIZESLEN, imgp->pagesizeslen);
1365 if (imgp->sysent->sv_timekeep_base != 0) {
1366 AUXARGS_ENTRY(pos, AT_TIMEKEEP,
1367 imgp->sysent->sv_timekeep_base);
1369 AUXARGS_ENTRY(pos, AT_STACKPROT, imgp->sysent->sv_shared_page_obj
1370 != NULL && imgp->stack_prot != 0 ? imgp->stack_prot :
1371 imgp->sysent->sv_stackprot);
1372 if (imgp->sysent->sv_hwcap != NULL)
1373 AUXARGS_ENTRY(pos, AT_HWCAP, *imgp->sysent->sv_hwcap);
1374 if (imgp->sysent->sv_hwcap2 != NULL)
1375 AUXARGS_ENTRY(pos, AT_HWCAP2, *imgp->sysent->sv_hwcap2);
1376 AUXARGS_ENTRY(pos, AT_BSDFLAGS, __elfN(sigfastblock) ?
1377 ELF_BSDF_SIGFASTBLK : 0);
1378 AUXARGS_ENTRY(pos, AT_NULL, 0);
1380 free(imgp->auxargs, M_TEMP);
1381 imgp->auxargs = NULL;
1382 KASSERT(pos - argarray <= AT_COUNT, ("Too many auxargs"));
1384 error = copyout(argarray, (void *)base, sizeof(*argarray) * AT_COUNT);
1385 free(argarray, M_TEMP);
1390 __elfN(freebsd_fixup)(uintptr_t *stack_base, struct image_params *imgp)
1394 base = (Elf_Addr *)*stack_base;
1396 if (suword(base, imgp->args->argc) == -1)
1398 *stack_base = (uintptr_t)base;
1403 * Code for generating ELF core dumps.
1406 typedef void (*segment_callback)(vm_map_entry_t, void *);
1408 /* Closure for cb_put_phdr(). */
1409 struct phdr_closure {
1410 Elf_Phdr *phdr; /* Program header to fill in */
1411 Elf_Off offset; /* Offset of segment in core file */
1414 /* Closure for cb_size_segment(). */
1415 struct sseg_closure {
1416 int count; /* Count of writable segments. */
1417 size_t size; /* Total size of all writable segments. */
1420 typedef void (*outfunc_t)(void *, struct sbuf *, size_t *);
1423 int type; /* Note type. */
1424 outfunc_t outfunc; /* Output function. */
1425 void *outarg; /* Argument for the output function. */
1426 size_t outsize; /* Output size. */
1427 TAILQ_ENTRY(note_info) link; /* Link to the next note info. */
1430 TAILQ_HEAD(note_info_list, note_info);
1432 /* Coredump output parameters. */
1433 struct coredump_params {
1435 struct ucred *active_cred;
1436 struct ucred *file_cred;
1439 struct compressor *comp;
1442 extern int compress_user_cores;
1443 extern int compress_user_cores_level;
1445 static void cb_put_phdr(vm_map_entry_t, void *);
1446 static void cb_size_segment(vm_map_entry_t, void *);
1447 static int core_write(struct coredump_params *, const void *, size_t, off_t,
1449 static void each_dumpable_segment(struct thread *, segment_callback, void *);
1450 static int __elfN(corehdr)(struct coredump_params *, int, void *, size_t,
1451 struct note_info_list *, size_t);
1452 static void __elfN(prepare_notes)(struct thread *, struct note_info_list *,
1454 static void __elfN(puthdr)(struct thread *, void *, size_t, int, size_t);
1455 static void __elfN(putnote)(struct note_info *, struct sbuf *);
1456 static size_t register_note(struct note_info_list *, int, outfunc_t, void *);
1457 static int sbuf_drain_core_output(void *, const char *, int);
1459 static void __elfN(note_fpregset)(void *, struct sbuf *, size_t *);
1460 static void __elfN(note_prpsinfo)(void *, struct sbuf *, size_t *);
1461 static void __elfN(note_prstatus)(void *, struct sbuf *, size_t *);
1462 static void __elfN(note_threadmd)(void *, struct sbuf *, size_t *);
1463 static void __elfN(note_thrmisc)(void *, struct sbuf *, size_t *);
1464 static void __elfN(note_ptlwpinfo)(void *, struct sbuf *, size_t *);
1465 static void __elfN(note_procstat_auxv)(void *, struct sbuf *, size_t *);
1466 static void __elfN(note_procstat_proc)(void *, struct sbuf *, size_t *);
1467 static void __elfN(note_procstat_psstrings)(void *, struct sbuf *, size_t *);
1468 static void note_procstat_files(void *, struct sbuf *, size_t *);
1469 static void note_procstat_groups(void *, struct sbuf *, size_t *);
1470 static void note_procstat_osrel(void *, struct sbuf *, size_t *);
1471 static void note_procstat_rlimit(void *, struct sbuf *, size_t *);
1472 static void note_procstat_umask(void *, struct sbuf *, size_t *);
1473 static void note_procstat_vmmap(void *, struct sbuf *, size_t *);
1476 * Write out a core segment to the compression stream.
1479 compress_chunk(struct coredump_params *p, char *base, char *buf, u_int len)
1485 chunk_len = MIN(len, CORE_BUF_SIZE);
1488 * We can get EFAULT error here.
1489 * In that case zero out the current chunk of the segment.
1491 error = copyin(base, buf, chunk_len);
1493 bzero(buf, chunk_len);
1494 error = compressor_write(p->comp, buf, chunk_len);
1504 core_compressed_write(void *base, size_t len, off_t offset, void *arg)
1507 return (core_write((struct coredump_params *)arg, base, len, offset,
1512 core_write(struct coredump_params *p, const void *base, size_t len,
1513 off_t offset, enum uio_seg seg)
1516 return (vn_rdwr_inchunks(UIO_WRITE, p->vp, __DECONST(void *, base),
1517 len, offset, seg, IO_UNIT | IO_DIRECT | IO_RANGELOCKED,
1518 p->active_cred, p->file_cred, NULL, p->td));
1522 core_output(void *base, size_t len, off_t offset, struct coredump_params *p,
1527 if (p->comp != NULL)
1528 return (compress_chunk(p, base, tmpbuf, len));
1531 * EFAULT is a non-fatal error that we can get, for example,
1532 * if the segment is backed by a file but extends beyond its
1535 error = core_write(p, base, len, offset, UIO_USERSPACE);
1536 if (error == EFAULT) {
1537 log(LOG_WARNING, "Failed to fully fault in a core file segment "
1538 "at VA %p with size 0x%zx to be written at offset 0x%jx "
1539 "for process %s\n", base, len, offset, curproc->p_comm);
1542 * Write a "real" zero byte at the end of the target region
1543 * in the case this is the last segment.
1544 * The intermediate space will be implicitly zero-filled.
1546 error = core_write(p, zero_region, 1, offset + len - 1,
1553 * Drain into a core file.
1556 sbuf_drain_core_output(void *arg, const char *data, int len)
1558 struct coredump_params *p;
1561 p = (struct coredump_params *)arg;
1564 * Some kern_proc out routines that print to this sbuf may
1565 * call us with the process lock held. Draining with the
1566 * non-sleepable lock held is unsafe. The lock is needed for
1567 * those routines when dumping a live process. In our case we
1568 * can safely release the lock before draining and acquire
1571 locked = PROC_LOCKED(p->td->td_proc);
1573 PROC_UNLOCK(p->td->td_proc);
1574 if (p->comp != NULL)
1575 error = compressor_write(p->comp, __DECONST(char *, data), len);
1577 error = core_write(p, __DECONST(void *, data), len, p->offset,
1580 PROC_LOCK(p->td->td_proc);
1588 __elfN(coredump)(struct thread *td, struct vnode *vp, off_t limit, int flags)
1590 struct ucred *cred = td->td_ucred;
1592 struct sseg_closure seginfo;
1593 struct note_info_list notelst;
1594 struct coredump_params params;
1595 struct note_info *ninfo;
1597 size_t hdrsize, notesz, coresize;
1601 TAILQ_INIT(¬elst);
1603 /* Size the program segments. */
1606 each_dumpable_segment(td, cb_size_segment, &seginfo);
1609 * Collect info about the core file header area.
1611 hdrsize = sizeof(Elf_Ehdr) + sizeof(Elf_Phdr) * (1 + seginfo.count);
1612 if (seginfo.count + 1 >= PN_XNUM)
1613 hdrsize += sizeof(Elf_Shdr);
1614 __elfN(prepare_notes)(td, ¬elst, ¬esz);
1615 coresize = round_page(hdrsize + notesz) + seginfo.size;
1617 /* Set up core dump parameters. */
1619 params.active_cred = cred;
1620 params.file_cred = NOCRED;
1627 PROC_LOCK(td->td_proc);
1628 error = racct_add(td->td_proc, RACCT_CORE, coresize);
1629 PROC_UNLOCK(td->td_proc);
1636 if (coresize >= limit) {
1641 /* Create a compression stream if necessary. */
1642 if (compress_user_cores != 0) {
1643 params.comp = compressor_init(core_compressed_write,
1644 compress_user_cores, CORE_BUF_SIZE,
1645 compress_user_cores_level, ¶ms);
1646 if (params.comp == NULL) {
1650 tmpbuf = malloc(CORE_BUF_SIZE, M_TEMP, M_WAITOK | M_ZERO);
1654 * Allocate memory for building the header, fill it up,
1655 * and write it out following the notes.
1657 hdr = malloc(hdrsize, M_TEMP, M_WAITOK);
1658 error = __elfN(corehdr)(¶ms, seginfo.count, hdr, hdrsize, ¬elst,
1661 /* Write the contents of all of the writable segments. */
1667 php = (Elf_Phdr *)((char *)hdr + sizeof(Elf_Ehdr)) + 1;
1668 offset = round_page(hdrsize + notesz);
1669 for (i = 0; i < seginfo.count; i++) {
1670 error = core_output((caddr_t)(uintptr_t)php->p_vaddr,
1671 php->p_filesz, offset, ¶ms, tmpbuf);
1674 offset += php->p_filesz;
1677 if (error == 0 && params.comp != NULL)
1678 error = compressor_flush(params.comp);
1682 "Failed to write core file for process %s (error %d)\n",
1683 curproc->p_comm, error);
1687 free(tmpbuf, M_TEMP);
1688 if (params.comp != NULL)
1689 compressor_fini(params.comp);
1690 while ((ninfo = TAILQ_FIRST(¬elst)) != NULL) {
1691 TAILQ_REMOVE(¬elst, ninfo, link);
1692 free(ninfo, M_TEMP);
1701 * A callback for each_dumpable_segment() to write out the segment's
1702 * program header entry.
1705 cb_put_phdr(vm_map_entry_t entry, void *closure)
1707 struct phdr_closure *phc = (struct phdr_closure *)closure;
1708 Elf_Phdr *phdr = phc->phdr;
1710 phc->offset = round_page(phc->offset);
1712 phdr->p_type = PT_LOAD;
1713 phdr->p_offset = phc->offset;
1714 phdr->p_vaddr = entry->start;
1716 phdr->p_filesz = phdr->p_memsz = entry->end - entry->start;
1717 phdr->p_align = PAGE_SIZE;
1718 phdr->p_flags = __elfN(untrans_prot)(entry->protection);
1720 phc->offset += phdr->p_filesz;
1725 * A callback for each_dumpable_segment() to gather information about
1726 * the number of segments and their total size.
1729 cb_size_segment(vm_map_entry_t entry, void *closure)
1731 struct sseg_closure *ssc = (struct sseg_closure *)closure;
1734 ssc->size += entry->end - entry->start;
1738 * For each writable segment in the process's memory map, call the given
1739 * function with a pointer to the map entry and some arbitrary
1740 * caller-supplied data.
1743 each_dumpable_segment(struct thread *td, segment_callback func, void *closure)
1745 struct proc *p = td->td_proc;
1746 vm_map_t map = &p->p_vmspace->vm_map;
1747 vm_map_entry_t entry;
1748 vm_object_t backing_object, object;
1749 boolean_t ignore_entry;
1751 vm_map_lock_read(map);
1752 VM_MAP_ENTRY_FOREACH(entry, map) {
1754 * Don't dump inaccessible mappings, deal with legacy
1757 * Note that read-only segments related to the elf binary
1758 * are marked MAP_ENTRY_NOCOREDUMP now so we no longer
1759 * need to arbitrarily ignore such segments.
1761 if (elf_legacy_coredump) {
1762 if ((entry->protection & VM_PROT_RW) != VM_PROT_RW)
1765 if ((entry->protection & VM_PROT_ALL) == 0)
1770 * Dont include memory segment in the coredump if
1771 * MAP_NOCORE is set in mmap(2) or MADV_NOCORE in
1772 * madvise(2). Do not dump submaps (i.e. parts of the
1775 if (entry->eflags & (MAP_ENTRY_NOCOREDUMP|MAP_ENTRY_IS_SUB_MAP))
1778 if ((object = entry->object.vm_object) == NULL)
1781 /* Ignore memory-mapped devices and such things. */
1782 VM_OBJECT_RLOCK(object);
1783 while ((backing_object = object->backing_object) != NULL) {
1784 VM_OBJECT_RLOCK(backing_object);
1785 VM_OBJECT_RUNLOCK(object);
1786 object = backing_object;
1788 ignore_entry = object->type != OBJT_DEFAULT &&
1789 object->type != OBJT_SWAP && object->type != OBJT_VNODE &&
1790 object->type != OBJT_PHYS;
1791 VM_OBJECT_RUNLOCK(object);
1795 (*func)(entry, closure);
1797 vm_map_unlock_read(map);
1801 * Write the core file header to the file, including padding up to
1802 * the page boundary.
1805 __elfN(corehdr)(struct coredump_params *p, int numsegs, void *hdr,
1806 size_t hdrsize, struct note_info_list *notelst, size_t notesz)
1808 struct note_info *ninfo;
1812 /* Fill in the header. */
1813 bzero(hdr, hdrsize);
1814 __elfN(puthdr)(p->td, hdr, hdrsize, numsegs, notesz);
1816 sb = sbuf_new(NULL, NULL, CORE_BUF_SIZE, SBUF_FIXEDLEN);
1817 sbuf_set_drain(sb, sbuf_drain_core_output, p);
1818 sbuf_start_section(sb, NULL);
1819 sbuf_bcat(sb, hdr, hdrsize);
1820 TAILQ_FOREACH(ninfo, notelst, link)
1821 __elfN(putnote)(ninfo, sb);
1822 /* Align up to a page boundary for the program segments. */
1823 sbuf_end_section(sb, -1, PAGE_SIZE, 0);
1824 error = sbuf_finish(sb);
1831 __elfN(prepare_notes)(struct thread *td, struct note_info_list *list,
1841 size += register_note(list, NT_PRPSINFO, __elfN(note_prpsinfo), p);
1844 * To have the debugger select the right thread (LWP) as the initial
1845 * thread, we dump the state of the thread passed to us in td first.
1846 * This is the thread that causes the core dump and thus likely to
1847 * be the right thread one wants to have selected in the debugger.
1850 while (thr != NULL) {
1851 size += register_note(list, NT_PRSTATUS,
1852 __elfN(note_prstatus), thr);
1853 size += register_note(list, NT_FPREGSET,
1854 __elfN(note_fpregset), thr);
1855 size += register_note(list, NT_THRMISC,
1856 __elfN(note_thrmisc), thr);
1857 size += register_note(list, NT_PTLWPINFO,
1858 __elfN(note_ptlwpinfo), thr);
1859 size += register_note(list, -1,
1860 __elfN(note_threadmd), thr);
1862 thr = (thr == td) ? TAILQ_FIRST(&p->p_threads) :
1863 TAILQ_NEXT(thr, td_plist);
1865 thr = TAILQ_NEXT(thr, td_plist);
1868 size += register_note(list, NT_PROCSTAT_PROC,
1869 __elfN(note_procstat_proc), p);
1870 size += register_note(list, NT_PROCSTAT_FILES,
1871 note_procstat_files, p);
1872 size += register_note(list, NT_PROCSTAT_VMMAP,
1873 note_procstat_vmmap, p);
1874 size += register_note(list, NT_PROCSTAT_GROUPS,
1875 note_procstat_groups, p);
1876 size += register_note(list, NT_PROCSTAT_UMASK,
1877 note_procstat_umask, p);
1878 size += register_note(list, NT_PROCSTAT_RLIMIT,
1879 note_procstat_rlimit, p);
1880 size += register_note(list, NT_PROCSTAT_OSREL,
1881 note_procstat_osrel, p);
1882 size += register_note(list, NT_PROCSTAT_PSSTRINGS,
1883 __elfN(note_procstat_psstrings), p);
1884 size += register_note(list, NT_PROCSTAT_AUXV,
1885 __elfN(note_procstat_auxv), p);
1891 __elfN(puthdr)(struct thread *td, void *hdr, size_t hdrsize, int numsegs,
1897 struct phdr_closure phc;
1899 ehdr = (Elf_Ehdr *)hdr;
1901 ehdr->e_ident[EI_MAG0] = ELFMAG0;
1902 ehdr->e_ident[EI_MAG1] = ELFMAG1;
1903 ehdr->e_ident[EI_MAG2] = ELFMAG2;
1904 ehdr->e_ident[EI_MAG3] = ELFMAG3;
1905 ehdr->e_ident[EI_CLASS] = ELF_CLASS;
1906 ehdr->e_ident[EI_DATA] = ELF_DATA;
1907 ehdr->e_ident[EI_VERSION] = EV_CURRENT;
1908 ehdr->e_ident[EI_OSABI] = ELFOSABI_FREEBSD;
1909 ehdr->e_ident[EI_ABIVERSION] = 0;
1910 ehdr->e_ident[EI_PAD] = 0;
1911 ehdr->e_type = ET_CORE;
1912 ehdr->e_machine = td->td_proc->p_elf_machine;
1913 ehdr->e_version = EV_CURRENT;
1915 ehdr->e_phoff = sizeof(Elf_Ehdr);
1916 ehdr->e_flags = td->td_proc->p_elf_flags;
1917 ehdr->e_ehsize = sizeof(Elf_Ehdr);
1918 ehdr->e_phentsize = sizeof(Elf_Phdr);
1919 ehdr->e_shentsize = sizeof(Elf_Shdr);
1920 ehdr->e_shstrndx = SHN_UNDEF;
1921 if (numsegs + 1 < PN_XNUM) {
1922 ehdr->e_phnum = numsegs + 1;
1925 ehdr->e_phnum = PN_XNUM;
1928 ehdr->e_shoff = ehdr->e_phoff +
1929 (numsegs + 1) * ehdr->e_phentsize;
1930 KASSERT(ehdr->e_shoff == hdrsize - sizeof(Elf_Shdr),
1931 ("e_shoff: %zu, hdrsize - shdr: %zu",
1932 (size_t)ehdr->e_shoff, hdrsize - sizeof(Elf_Shdr)));
1934 shdr = (Elf_Shdr *)((char *)hdr + ehdr->e_shoff);
1935 memset(shdr, 0, sizeof(*shdr));
1937 * A special first section is used to hold large segment and
1938 * section counts. This was proposed by Sun Microsystems in
1939 * Solaris and has been adopted by Linux; the standard ELF
1940 * tools are already familiar with the technique.
1942 * See table 7-7 of the Solaris "Linker and Libraries Guide"
1943 * (or 12-7 depending on the version of the document) for more
1946 shdr->sh_type = SHT_NULL;
1947 shdr->sh_size = ehdr->e_shnum;
1948 shdr->sh_link = ehdr->e_shstrndx;
1949 shdr->sh_info = numsegs + 1;
1953 * Fill in the program header entries.
1955 phdr = (Elf_Phdr *)((char *)hdr + ehdr->e_phoff);
1957 /* The note segement. */
1958 phdr->p_type = PT_NOTE;
1959 phdr->p_offset = hdrsize;
1962 phdr->p_filesz = notesz;
1964 phdr->p_flags = PF_R;
1965 phdr->p_align = ELF_NOTE_ROUNDSIZE;
1968 /* All the writable segments from the program. */
1970 phc.offset = round_page(hdrsize + notesz);
1971 each_dumpable_segment(td, cb_put_phdr, &phc);
1975 register_note(struct note_info_list *list, int type, outfunc_t out, void *arg)
1977 struct note_info *ninfo;
1978 size_t size, notesize;
1981 out(arg, NULL, &size);
1982 ninfo = malloc(sizeof(*ninfo), M_TEMP, M_ZERO | M_WAITOK);
1984 ninfo->outfunc = out;
1985 ninfo->outarg = arg;
1986 ninfo->outsize = size;
1987 TAILQ_INSERT_TAIL(list, ninfo, link);
1992 notesize = sizeof(Elf_Note) + /* note header */
1993 roundup2(sizeof(FREEBSD_ABI_VENDOR), ELF_NOTE_ROUNDSIZE) +
1995 roundup2(size, ELF_NOTE_ROUNDSIZE); /* note description */
2001 append_note_data(const void *src, void *dst, size_t len)
2005 padded_len = roundup2(len, ELF_NOTE_ROUNDSIZE);
2007 bcopy(src, dst, len);
2008 bzero((char *)dst + len, padded_len - len);
2010 return (padded_len);
2014 __elfN(populate_note)(int type, void *src, void *dst, size_t size, void **descp)
2022 note = (Elf_Note *)buf;
2023 note->n_namesz = sizeof(FREEBSD_ABI_VENDOR);
2024 note->n_descsz = size;
2025 note->n_type = type;
2026 buf += sizeof(*note);
2027 buf += append_note_data(FREEBSD_ABI_VENDOR, buf,
2028 sizeof(FREEBSD_ABI_VENDOR));
2029 append_note_data(src, buf, size);
2034 notesize = sizeof(Elf_Note) + /* note header */
2035 roundup2(sizeof(FREEBSD_ABI_VENDOR), ELF_NOTE_ROUNDSIZE) +
2037 roundup2(size, ELF_NOTE_ROUNDSIZE); /* note description */
2043 __elfN(putnote)(struct note_info *ninfo, struct sbuf *sb)
2046 ssize_t old_len, sect_len;
2047 size_t new_len, descsz, i;
2049 if (ninfo->type == -1) {
2050 ninfo->outfunc(ninfo->outarg, sb, &ninfo->outsize);
2054 note.n_namesz = sizeof(FREEBSD_ABI_VENDOR);
2055 note.n_descsz = ninfo->outsize;
2056 note.n_type = ninfo->type;
2058 sbuf_bcat(sb, ¬e, sizeof(note));
2059 sbuf_start_section(sb, &old_len);
2060 sbuf_bcat(sb, FREEBSD_ABI_VENDOR, sizeof(FREEBSD_ABI_VENDOR));
2061 sbuf_end_section(sb, old_len, ELF_NOTE_ROUNDSIZE, 0);
2062 if (note.n_descsz == 0)
2064 sbuf_start_section(sb, &old_len);
2065 ninfo->outfunc(ninfo->outarg, sb, &ninfo->outsize);
2066 sect_len = sbuf_end_section(sb, old_len, ELF_NOTE_ROUNDSIZE, 0);
2070 new_len = (size_t)sect_len;
2071 descsz = roundup(note.n_descsz, ELF_NOTE_ROUNDSIZE);
2072 if (new_len < descsz) {
2074 * It is expected that individual note emitters will correctly
2075 * predict their expected output size and fill up to that size
2076 * themselves, padding in a format-specific way if needed.
2077 * However, in case they don't, just do it here with zeros.
2079 for (i = 0; i < descsz - new_len; i++)
2081 } else if (new_len > descsz) {
2083 * We can't always truncate sb -- we may have drained some
2086 KASSERT(new_len == descsz, ("%s: Note type %u changed as we "
2087 "read it (%zu > %zu). Since it is longer than "
2088 "expected, this coredump's notes are corrupt. THIS "
2089 "IS A BUG in the note_procstat routine for type %u.\n",
2090 __func__, (unsigned)note.n_type, new_len, descsz,
2091 (unsigned)note.n_type));
2096 * Miscellaneous note out functions.
2099 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
2100 #include <compat/freebsd32/freebsd32.h>
2101 #include <compat/freebsd32/freebsd32_signal.h>
2103 typedef struct prstatus32 elf_prstatus_t;
2104 typedef struct prpsinfo32 elf_prpsinfo_t;
2105 typedef struct fpreg32 elf_prfpregset_t;
2106 typedef struct fpreg32 elf_fpregset_t;
2107 typedef struct reg32 elf_gregset_t;
2108 typedef struct thrmisc32 elf_thrmisc_t;
2109 #define ELF_KERN_PROC_MASK KERN_PROC_MASK32
2110 typedef struct kinfo_proc32 elf_kinfo_proc_t;
2111 typedef uint32_t elf_ps_strings_t;
2113 typedef prstatus_t elf_prstatus_t;
2114 typedef prpsinfo_t elf_prpsinfo_t;
2115 typedef prfpregset_t elf_prfpregset_t;
2116 typedef prfpregset_t elf_fpregset_t;
2117 typedef gregset_t elf_gregset_t;
2118 typedef thrmisc_t elf_thrmisc_t;
2119 #define ELF_KERN_PROC_MASK 0
2120 typedef struct kinfo_proc elf_kinfo_proc_t;
2121 typedef vm_offset_t elf_ps_strings_t;
2125 __elfN(note_prpsinfo)(void *arg, struct sbuf *sb, size_t *sizep)
2131 elf_prpsinfo_t *psinfo;
2134 p = (struct proc *)arg;
2136 KASSERT(*sizep == sizeof(*psinfo), ("invalid size"));
2137 psinfo = malloc(sizeof(*psinfo), M_TEMP, M_ZERO | M_WAITOK);
2138 psinfo->pr_version = PRPSINFO_VERSION;
2139 psinfo->pr_psinfosz = sizeof(elf_prpsinfo_t);
2140 strlcpy(psinfo->pr_fname, p->p_comm, sizeof(psinfo->pr_fname));
2142 if (p->p_args != NULL) {
2143 len = sizeof(psinfo->pr_psargs) - 1;
2144 if (len > p->p_args->ar_length)
2145 len = p->p_args->ar_length;
2146 memcpy(psinfo->pr_psargs, p->p_args->ar_args, len);
2152 sbuf_new(&sbarg, psinfo->pr_psargs,
2153 sizeof(psinfo->pr_psargs), SBUF_FIXEDLEN);
2154 error = proc_getargv(curthread, p, &sbarg);
2156 if (sbuf_finish(&sbarg) == 0)
2157 len = sbuf_len(&sbarg) - 1;
2159 len = sizeof(psinfo->pr_psargs) - 1;
2160 sbuf_delete(&sbarg);
2162 if (error || len == 0)
2163 strlcpy(psinfo->pr_psargs, p->p_comm,
2164 sizeof(psinfo->pr_psargs));
2166 KASSERT(len < sizeof(psinfo->pr_psargs),
2167 ("len is too long: %zu vs %zu", len,
2168 sizeof(psinfo->pr_psargs)));
2169 cp = psinfo->pr_psargs;
2172 cp = memchr(cp, '\0', end - cp);
2178 psinfo->pr_pid = p->p_pid;
2179 sbuf_bcat(sb, psinfo, sizeof(*psinfo));
2180 free(psinfo, M_TEMP);
2182 *sizep = sizeof(*psinfo);
2186 __elfN(note_prstatus)(void *arg, struct sbuf *sb, size_t *sizep)
2189 elf_prstatus_t *status;
2191 td = (struct thread *)arg;
2193 KASSERT(*sizep == sizeof(*status), ("invalid size"));
2194 status = malloc(sizeof(*status), M_TEMP, M_ZERO | M_WAITOK);
2195 status->pr_version = PRSTATUS_VERSION;
2196 status->pr_statussz = sizeof(elf_prstatus_t);
2197 status->pr_gregsetsz = sizeof(elf_gregset_t);
2198 status->pr_fpregsetsz = sizeof(elf_fpregset_t);
2199 status->pr_osreldate = osreldate;
2200 status->pr_cursig = td->td_proc->p_sig;
2201 status->pr_pid = td->td_tid;
2202 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
2203 fill_regs32(td, &status->pr_reg);
2205 fill_regs(td, &status->pr_reg);
2207 sbuf_bcat(sb, status, sizeof(*status));
2208 free(status, M_TEMP);
2210 *sizep = sizeof(*status);
2214 __elfN(note_fpregset)(void *arg, struct sbuf *sb, size_t *sizep)
2217 elf_prfpregset_t *fpregset;
2219 td = (struct thread *)arg;
2221 KASSERT(*sizep == sizeof(*fpregset), ("invalid size"));
2222 fpregset = malloc(sizeof(*fpregset), M_TEMP, M_ZERO | M_WAITOK);
2223 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
2224 fill_fpregs32(td, fpregset);
2226 fill_fpregs(td, fpregset);
2228 sbuf_bcat(sb, fpregset, sizeof(*fpregset));
2229 free(fpregset, M_TEMP);
2231 *sizep = sizeof(*fpregset);
2235 __elfN(note_thrmisc)(void *arg, struct sbuf *sb, size_t *sizep)
2238 elf_thrmisc_t thrmisc;
2240 td = (struct thread *)arg;
2242 KASSERT(*sizep == sizeof(thrmisc), ("invalid size"));
2243 bzero(&thrmisc, sizeof(thrmisc));
2244 strcpy(thrmisc.pr_tname, td->td_name);
2245 sbuf_bcat(sb, &thrmisc, sizeof(thrmisc));
2247 *sizep = sizeof(thrmisc);
2251 __elfN(note_ptlwpinfo)(void *arg, struct sbuf *sb, size_t *sizep)
2256 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
2257 struct ptrace_lwpinfo32 pl;
2259 struct ptrace_lwpinfo pl;
2262 td = (struct thread *)arg;
2263 size = sizeof(structsize) + sizeof(pl);
2265 KASSERT(*sizep == size, ("invalid size"));
2266 structsize = sizeof(pl);
2267 sbuf_bcat(sb, &structsize, sizeof(structsize));
2268 bzero(&pl, sizeof(pl));
2269 pl.pl_lwpid = td->td_tid;
2270 pl.pl_event = PL_EVENT_NONE;
2271 pl.pl_sigmask = td->td_sigmask;
2272 pl.pl_siglist = td->td_siglist;
2273 if (td->td_si.si_signo != 0) {
2274 pl.pl_event = PL_EVENT_SIGNAL;
2275 pl.pl_flags |= PL_FLAG_SI;
2276 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
2277 siginfo_to_siginfo32(&td->td_si, &pl.pl_siginfo);
2279 pl.pl_siginfo = td->td_si;
2282 strcpy(pl.pl_tdname, td->td_name);
2283 /* XXX TODO: supply more information in struct ptrace_lwpinfo*/
2284 sbuf_bcat(sb, &pl, sizeof(pl));
2290 * Allow for MD specific notes, as well as any MD
2291 * specific preparations for writing MI notes.
2294 __elfN(note_threadmd)(void *arg, struct sbuf *sb, size_t *sizep)
2300 td = (struct thread *)arg;
2302 if (size != 0 && sb != NULL)
2303 buf = malloc(size, M_TEMP, M_ZERO | M_WAITOK);
2307 __elfN(dump_thread)(td, buf, &size);
2308 KASSERT(sb == NULL || *sizep == size, ("invalid size"));
2309 if (size != 0 && sb != NULL)
2310 sbuf_bcat(sb, buf, size);
2315 #ifdef KINFO_PROC_SIZE
2316 CTASSERT(sizeof(struct kinfo_proc) == KINFO_PROC_SIZE);
2320 __elfN(note_procstat_proc)(void *arg, struct sbuf *sb, size_t *sizep)
2326 p = (struct proc *)arg;
2327 size = sizeof(structsize) + p->p_numthreads *
2328 sizeof(elf_kinfo_proc_t);
2331 KASSERT(*sizep == size, ("invalid size"));
2332 structsize = sizeof(elf_kinfo_proc_t);
2333 sbuf_bcat(sb, &structsize, sizeof(structsize));
2335 kern_proc_out(p, sb, ELF_KERN_PROC_MASK);
2340 #ifdef KINFO_FILE_SIZE
2341 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
2345 note_procstat_files(void *arg, struct sbuf *sb, size_t *sizep)
2348 size_t size, sect_sz, i;
2349 ssize_t start_len, sect_len;
2350 int structsize, filedesc_flags;
2352 if (coredump_pack_fileinfo)
2353 filedesc_flags = KERN_FILEDESC_PACK_KINFO;
2357 p = (struct proc *)arg;
2358 structsize = sizeof(struct kinfo_file);
2361 sb = sbuf_new(NULL, NULL, 128, SBUF_FIXEDLEN);
2362 sbuf_set_drain(sb, sbuf_count_drain, &size);
2363 sbuf_bcat(sb, &structsize, sizeof(structsize));
2365 kern_proc_filedesc_out(p, sb, -1, filedesc_flags);
2370 sbuf_start_section(sb, &start_len);
2372 sbuf_bcat(sb, &structsize, sizeof(structsize));
2374 kern_proc_filedesc_out(p, sb, *sizep - sizeof(structsize),
2377 sect_len = sbuf_end_section(sb, start_len, 0, 0);
2382 KASSERT(sect_sz <= *sizep,
2383 ("kern_proc_filedesc_out did not respect maxlen; "
2384 "requested %zu, got %zu", *sizep - sizeof(structsize),
2385 sect_sz - sizeof(structsize)));
2387 for (i = 0; i < *sizep - sect_sz && sb->s_error == 0; i++)
2392 #ifdef KINFO_VMENTRY_SIZE
2393 CTASSERT(sizeof(struct kinfo_vmentry) == KINFO_VMENTRY_SIZE);
2397 note_procstat_vmmap(void *arg, struct sbuf *sb, size_t *sizep)
2401 int structsize, vmmap_flags;
2403 if (coredump_pack_vmmapinfo)
2404 vmmap_flags = KERN_VMMAP_PACK_KINFO;
2408 p = (struct proc *)arg;
2409 structsize = sizeof(struct kinfo_vmentry);
2412 sb = sbuf_new(NULL, NULL, 128, SBUF_FIXEDLEN);
2413 sbuf_set_drain(sb, sbuf_count_drain, &size);
2414 sbuf_bcat(sb, &structsize, sizeof(structsize));
2416 kern_proc_vmmap_out(p, sb, -1, vmmap_flags);
2421 sbuf_bcat(sb, &structsize, sizeof(structsize));
2423 kern_proc_vmmap_out(p, sb, *sizep - sizeof(structsize),
2429 note_procstat_groups(void *arg, struct sbuf *sb, size_t *sizep)
2435 p = (struct proc *)arg;
2436 size = sizeof(structsize) + p->p_ucred->cr_ngroups * sizeof(gid_t);
2438 KASSERT(*sizep == size, ("invalid size"));
2439 structsize = sizeof(gid_t);
2440 sbuf_bcat(sb, &structsize, sizeof(structsize));
2441 sbuf_bcat(sb, p->p_ucred->cr_groups, p->p_ucred->cr_ngroups *
2448 note_procstat_umask(void *arg, struct sbuf *sb, size_t *sizep)
2454 p = (struct proc *)arg;
2455 size = sizeof(structsize) + sizeof(p->p_fd->fd_cmask);
2457 KASSERT(*sizep == size, ("invalid size"));
2458 structsize = sizeof(p->p_fd->fd_cmask);
2459 sbuf_bcat(sb, &structsize, sizeof(structsize));
2460 sbuf_bcat(sb, &p->p_fd->fd_cmask, sizeof(p->p_fd->fd_cmask));
2466 note_procstat_rlimit(void *arg, struct sbuf *sb, size_t *sizep)
2469 struct rlimit rlim[RLIM_NLIMITS];
2473 p = (struct proc *)arg;
2474 size = sizeof(structsize) + sizeof(rlim);
2476 KASSERT(*sizep == size, ("invalid size"));
2477 structsize = sizeof(rlim);
2478 sbuf_bcat(sb, &structsize, sizeof(structsize));
2480 for (i = 0; i < RLIM_NLIMITS; i++)
2481 lim_rlimit_proc(p, i, &rlim[i]);
2483 sbuf_bcat(sb, rlim, sizeof(rlim));
2489 note_procstat_osrel(void *arg, struct sbuf *sb, size_t *sizep)
2495 p = (struct proc *)arg;
2496 size = sizeof(structsize) + sizeof(p->p_osrel);
2498 KASSERT(*sizep == size, ("invalid size"));
2499 structsize = sizeof(p->p_osrel);
2500 sbuf_bcat(sb, &structsize, sizeof(structsize));
2501 sbuf_bcat(sb, &p->p_osrel, sizeof(p->p_osrel));
2507 __elfN(note_procstat_psstrings)(void *arg, struct sbuf *sb, size_t *sizep)
2510 elf_ps_strings_t ps_strings;
2514 p = (struct proc *)arg;
2515 size = sizeof(structsize) + sizeof(ps_strings);
2517 KASSERT(*sizep == size, ("invalid size"));
2518 structsize = sizeof(ps_strings);
2519 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
2520 ps_strings = PTROUT(p->p_sysent->sv_psstrings);
2522 ps_strings = p->p_sysent->sv_psstrings;
2524 sbuf_bcat(sb, &structsize, sizeof(structsize));
2525 sbuf_bcat(sb, &ps_strings, sizeof(ps_strings));
2531 __elfN(note_procstat_auxv)(void *arg, struct sbuf *sb, size_t *sizep)
2537 p = (struct proc *)arg;
2540 sb = sbuf_new(NULL, NULL, 128, SBUF_FIXEDLEN);
2541 sbuf_set_drain(sb, sbuf_count_drain, &size);
2542 sbuf_bcat(sb, &structsize, sizeof(structsize));
2544 proc_getauxv(curthread, p, sb);
2550 structsize = sizeof(Elf_Auxinfo);
2551 sbuf_bcat(sb, &structsize, sizeof(structsize));
2553 proc_getauxv(curthread, p, sb);
2559 __elfN(parse_notes)(struct image_params *imgp, Elf_Note *checknote,
2560 const char *note_vendor, const Elf_Phdr *pnote,
2561 boolean_t (*cb)(const Elf_Note *, void *, boolean_t *), void *cb_arg)
2563 const Elf_Note *note, *note0, *note_end;
2564 const char *note_name;
2569 /* We need some limit, might as well use PAGE_SIZE. */
2570 if (pnote == NULL || pnote->p_filesz > PAGE_SIZE)
2572 ASSERT_VOP_LOCKED(imgp->vp, "parse_notes");
2573 if (pnote->p_offset > PAGE_SIZE ||
2574 pnote->p_filesz > PAGE_SIZE - pnote->p_offset) {
2575 buf = malloc(pnote->p_filesz, M_TEMP, M_NOWAIT);
2577 VOP_UNLOCK(imgp->vp);
2578 buf = malloc(pnote->p_filesz, M_TEMP, M_WAITOK);
2579 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
2581 error = vn_rdwr(UIO_READ, imgp->vp, buf, pnote->p_filesz,
2582 pnote->p_offset, UIO_SYSSPACE, IO_NODELOCKED,
2583 curthread->td_ucred, NOCRED, NULL, curthread);
2585 uprintf("i/o error PT_NOTE\n");
2588 note = note0 = (const Elf_Note *)buf;
2589 note_end = (const Elf_Note *)(buf + pnote->p_filesz);
2591 note = note0 = (const Elf_Note *)(imgp->image_header +
2593 note_end = (const Elf_Note *)(imgp->image_header +
2594 pnote->p_offset + pnote->p_filesz);
2597 for (i = 0; i < 100 && note >= note0 && note < note_end; i++) {
2598 if (!aligned(note, Elf32_Addr) || (const char *)note_end -
2599 (const char *)note < sizeof(Elf_Note)) {
2602 if (note->n_namesz != checknote->n_namesz ||
2603 note->n_descsz != checknote->n_descsz ||
2604 note->n_type != checknote->n_type)
2606 note_name = (const char *)(note + 1);
2607 if (note_name + checknote->n_namesz >=
2608 (const char *)note_end || strncmp(note_vendor,
2609 note_name, checknote->n_namesz) != 0)
2612 if (cb(note, cb_arg, &res))
2615 note = (const Elf_Note *)((const char *)(note + 1) +
2616 roundup2(note->n_namesz, ELF_NOTE_ROUNDSIZE) +
2617 roundup2(note->n_descsz, ELF_NOTE_ROUNDSIZE));
2626 struct brandnote_cb_arg {
2627 Elf_Brandnote *brandnote;
2632 brandnote_cb(const Elf_Note *note, void *arg0, boolean_t *res)
2634 struct brandnote_cb_arg *arg;
2639 * Fetch the osreldate for binary from the ELF OSABI-note if
2642 *res = (arg->brandnote->flags & BN_TRANSLATE_OSREL) != 0 &&
2643 arg->brandnote->trans_osrel != NULL ?
2644 arg->brandnote->trans_osrel(note, arg->osrel) : TRUE;
2649 static Elf_Note fctl_note = {
2650 .n_namesz = sizeof(FREEBSD_ABI_VENDOR),
2651 .n_descsz = sizeof(uint32_t),
2652 .n_type = NT_FREEBSD_FEATURE_CTL,
2655 struct fctl_cb_arg {
2660 note_fctl_cb(const Elf_Note *note, void *arg0, boolean_t *res)
2662 struct fctl_cb_arg *arg;
2663 const Elf32_Word *desc;
2667 p = (uintptr_t)(note + 1);
2668 p += roundup2(note->n_namesz, ELF_NOTE_ROUNDSIZE);
2669 desc = (const Elf32_Word *)p;
2670 *arg->fctl0 = desc[0];
2675 * Try to find the appropriate ABI-note section for checknote, fetch
2676 * the osreldate and feature control flags for binary from the ELF
2677 * OSABI-note. Only the first page of the image is searched, the same
2681 __elfN(check_note)(struct image_params *imgp, Elf_Brandnote *brandnote,
2682 int32_t *osrel, uint32_t *fctl0)
2684 const Elf_Phdr *phdr;
2685 const Elf_Ehdr *hdr;
2686 struct brandnote_cb_arg b_arg;
2687 struct fctl_cb_arg f_arg;
2690 hdr = (const Elf_Ehdr *)imgp->image_header;
2691 phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
2692 b_arg.brandnote = brandnote;
2693 b_arg.osrel = osrel;
2694 f_arg.fctl0 = fctl0;
2696 for (i = 0; i < hdr->e_phnum; i++) {
2697 if (phdr[i].p_type == PT_NOTE && __elfN(parse_notes)(imgp,
2698 &brandnote->hdr, brandnote->vendor, &phdr[i], brandnote_cb,
2700 for (j = 0; j < hdr->e_phnum; j++) {
2701 if (phdr[j].p_type == PT_NOTE &&
2702 __elfN(parse_notes)(imgp, &fctl_note,
2703 FREEBSD_ABI_VENDOR, &phdr[j],
2704 note_fctl_cb, &f_arg))
2715 * Tell kern_execve.c about it, with a little help from the linker.
2717 static struct execsw __elfN(execsw) = {
2718 .ex_imgact = __CONCAT(exec_, __elfN(imgact)),
2719 .ex_name = __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE))
2721 EXEC_SET(__CONCAT(elf, __ELF_WORD_SIZE), __elfN(execsw));
2724 __elfN(trans_prot)(Elf_Word flags)
2730 prot |= VM_PROT_EXECUTE;
2732 prot |= VM_PROT_WRITE;
2734 prot |= VM_PROT_READ;
2735 #if __ELF_WORD_SIZE == 32 && (defined(__amd64__) || defined(__i386__))
2736 if (i386_read_exec && (flags & PF_R))
2737 prot |= VM_PROT_EXECUTE;
2743 __elfN(untrans_prot)(vm_prot_t prot)
2748 if (prot & VM_PROT_EXECUTE)
2750 if (prot & VM_PROT_READ)
2752 if (prot & VM_PROT_WRITE)
2758 __elfN(stackgap)(struct image_params *imgp, uintptr_t *stack_base)
2760 uintptr_t range, rbase, gap;
2763 if ((imgp->map_flags & MAP_ASLR) == 0)
2765 pct = __elfN(aslr_stack_gap);
2770 range = imgp->eff_stack_sz * pct / 100;
2771 arc4rand(&rbase, sizeof(rbase), 0);
2772 gap = rbase % range;
2773 gap &= ~(sizeof(u_long) - 1);