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>
54 #include <sys/procfs.h>
55 #include <sys/ptrace.h>
56 #include <sys/racct.h>
57 #include <sys/resourcevar.h>
58 #include <sys/rwlock.h>
60 #include <sys/sf_buf.h>
62 #include <sys/systm.h>
63 #include <sys/signalvar.h>
66 #include <sys/syscall.h>
67 #include <sys/sysctl.h>
68 #include <sys/sysent.h>
69 #include <sys/vnode.h>
70 #include <sys/syslog.h>
71 #include <sys/eventhandler.h>
75 #include <vm/vm_kern.h>
76 #include <vm/vm_param.h>
78 #include <vm/vm_map.h>
79 #include <vm/vm_object.h>
80 #include <vm/vm_extern.h>
82 #include <machine/elf.h>
83 #include <machine/md_var.h>
85 #define ELF_NOTE_ROUNDSIZE 4
86 #define OLD_EI_BRAND 8
88 static int __elfN(check_header)(const Elf_Ehdr *hdr);
89 static Elf_Brandinfo *__elfN(get_brandinfo)(struct image_params *imgp,
90 const char *interp, int32_t *osrel, uint32_t *fctl0);
91 static int __elfN(load_file)(struct proc *p, const char *file, u_long *addr,
93 static int __elfN(load_section)(struct image_params *imgp, vm_ooffset_t offset,
94 caddr_t vmaddr, size_t memsz, size_t filsz, vm_prot_t prot);
95 static int __CONCAT(exec_, __elfN(imgact))(struct image_params *imgp);
96 static bool __elfN(freebsd_trans_osrel)(const Elf_Note *note,
98 static bool 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, uint32_t *fctl0);
101 static vm_prot_t __elfN(trans_prot)(Elf_Word);
102 static Elf_Word __elfN(untrans_prot)(vm_prot_t);
104 SYSCTL_NODE(_kern, OID_AUTO, __CONCAT(elf, __ELF_WORD_SIZE),
105 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
108 #define CORE_BUF_SIZE (16 * 1024)
110 int __elfN(fallback_brand) = -1;
111 SYSCTL_INT(__CONCAT(_kern_elf, __ELF_WORD_SIZE), OID_AUTO,
112 fallback_brand, CTLFLAG_RWTUN, &__elfN(fallback_brand), 0,
113 __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE)) " brand of last resort");
115 static int elf_legacy_coredump = 0;
116 SYSCTL_INT(_debug, OID_AUTO, __elfN(legacy_coredump), CTLFLAG_RW,
117 &elf_legacy_coredump, 0,
118 "include all and only RW pages in core dumps");
120 int __elfN(nxstack) =
121 #if defined(__amd64__) || defined(__powerpc64__) /* both 64 and 32 bit */ || \
122 (defined(__arm__) && __ARM_ARCH >= 7) || defined(__aarch64__) || \
128 SYSCTL_INT(__CONCAT(_kern_elf, __ELF_WORD_SIZE), OID_AUTO,
129 nxstack, CTLFLAG_RW, &__elfN(nxstack), 0,
130 __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE)) ": enable non-executable stack");
132 #if __ELF_WORD_SIZE == 32 && (defined(__amd64__) || defined(__i386__))
133 int i386_read_exec = 0;
134 SYSCTL_INT(_kern_elf32, OID_AUTO, read_exec, CTLFLAG_RW, &i386_read_exec, 0,
135 "enable execution from readable segments");
138 static u_long __elfN(pie_base) = ET_DYN_LOAD_ADDR;
140 sysctl_pie_base(SYSCTL_HANDLER_ARGS)
145 val = __elfN(pie_base);
146 error = sysctl_handle_long(oidp, &val, 0, req);
147 if (error != 0 || req->newptr == NULL)
149 if ((val & PAGE_MASK) != 0)
151 __elfN(pie_base) = val;
154 SYSCTL_PROC(__CONCAT(_kern_elf, __ELF_WORD_SIZE), OID_AUTO, pie_base,
155 CTLTYPE_ULONG | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0,
156 sysctl_pie_base, "LU",
157 "PIE load base without randomization");
159 SYSCTL_NODE(__CONCAT(_kern_elf, __ELF_WORD_SIZE), OID_AUTO, aslr,
160 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
162 #define ASLR_NODE_OID __CONCAT(__CONCAT(_kern_elf, __ELF_WORD_SIZE), _aslr)
164 static int __elfN(aslr_enabled) = 0;
165 SYSCTL_INT(ASLR_NODE_OID, OID_AUTO, enable, CTLFLAG_RWTUN,
166 &__elfN(aslr_enabled), 0,
167 __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE))
168 ": enable address map randomization");
170 static int __elfN(pie_aslr_enabled) = 0;
171 SYSCTL_INT(ASLR_NODE_OID, OID_AUTO, pie_enable, CTLFLAG_RWTUN,
172 &__elfN(pie_aslr_enabled), 0,
173 __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE))
174 ": enable address map randomization for PIE binaries");
176 static int __elfN(aslr_honor_sbrk) = 1;
177 SYSCTL_INT(ASLR_NODE_OID, OID_AUTO, honor_sbrk, CTLFLAG_RW,
178 &__elfN(aslr_honor_sbrk), 0,
179 __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE)) ": assume sbrk is used");
181 static int __elfN(aslr_stack_gap) = 3;
182 SYSCTL_INT(ASLR_NODE_OID, OID_AUTO, stack_gap, CTLFLAG_RW,
183 &__elfN(aslr_stack_gap), 0,
184 __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE))
185 ": maximum percentage of main stack to waste on a random gap");
187 static int __elfN(sigfastblock) = 1;
188 SYSCTL_INT(__CONCAT(_kern_elf, __ELF_WORD_SIZE), OID_AUTO, sigfastblock,
189 CTLFLAG_RWTUN, &__elfN(sigfastblock), 0,
190 "enable sigfastblock for new processes");
192 static Elf_Brandinfo *elf_brand_list[MAX_BRANDS];
194 #define aligned(a, t) (rounddown2((u_long)(a), sizeof(t)) == (u_long)(a))
196 static const char FREEBSD_ABI_VENDOR[] = "FreeBSD";
198 Elf_Brandnote __elfN(freebsd_brandnote) = {
199 .hdr.n_namesz = sizeof(FREEBSD_ABI_VENDOR),
200 .hdr.n_descsz = sizeof(int32_t),
201 .hdr.n_type = NT_FREEBSD_ABI_TAG,
202 .vendor = FREEBSD_ABI_VENDOR,
203 .flags = BN_TRANSLATE_OSREL,
204 .trans_osrel = __elfN(freebsd_trans_osrel)
208 __elfN(freebsd_trans_osrel)(const Elf_Note *note, int32_t *osrel)
212 p = (uintptr_t)(note + 1);
213 p += roundup2(note->n_namesz, ELF_NOTE_ROUNDSIZE);
214 *osrel = *(const int32_t *)(p);
219 static const char GNU_ABI_VENDOR[] = "GNU";
220 static int GNU_KFREEBSD_ABI_DESC = 3;
222 Elf_Brandnote __elfN(kfreebsd_brandnote) = {
223 .hdr.n_namesz = sizeof(GNU_ABI_VENDOR),
224 .hdr.n_descsz = 16, /* XXX at least 16 */
226 .vendor = GNU_ABI_VENDOR,
227 .flags = BN_TRANSLATE_OSREL,
228 .trans_osrel = kfreebsd_trans_osrel
232 kfreebsd_trans_osrel(const Elf_Note *note, int32_t *osrel)
234 const Elf32_Word *desc;
237 p = (uintptr_t)(note + 1);
238 p += roundup2(note->n_namesz, ELF_NOTE_ROUNDSIZE);
240 desc = (const Elf32_Word *)p;
241 if (desc[0] != GNU_KFREEBSD_ABI_DESC)
245 * Debian GNU/kFreeBSD embed the earliest compatible kernel version
246 * (__FreeBSD_version: <major><two digit minor>Rxx) in the LSB way.
248 *osrel = desc[1] * 100000 + desc[2] * 1000 + desc[3];
254 __elfN(insert_brand_entry)(Elf_Brandinfo *entry)
258 for (i = 0; i < MAX_BRANDS; i++) {
259 if (elf_brand_list[i] == NULL) {
260 elf_brand_list[i] = entry;
264 if (i == MAX_BRANDS) {
265 printf("WARNING: %s: could not insert brandinfo entry: %p\n",
273 __elfN(remove_brand_entry)(Elf_Brandinfo *entry)
277 for (i = 0; i < MAX_BRANDS; i++) {
278 if (elf_brand_list[i] == entry) {
279 elf_brand_list[i] = NULL;
289 __elfN(brand_inuse)(Elf_Brandinfo *entry)
294 sx_slock(&allproc_lock);
295 FOREACH_PROC_IN_SYSTEM(p) {
296 if (p->p_sysent == entry->sysvec) {
301 sx_sunlock(&allproc_lock);
306 static Elf_Brandinfo *
307 __elfN(get_brandinfo)(struct image_params *imgp, const char *interp,
308 int32_t *osrel, uint32_t *fctl0)
310 const Elf_Ehdr *hdr = (const Elf_Ehdr *)imgp->image_header;
311 Elf_Brandinfo *bi, *bi_m;
313 int i, interp_name_len;
315 interp_name_len = interp != NULL ? strlen(interp) + 1 : 0;
318 * We support four types of branding -- (1) the ELF EI_OSABI field
319 * that SCO added to the ELF spec, (2) FreeBSD 3.x's traditional string
320 * branding w/in the ELF header, (3) path of the `interp_path'
321 * field, and (4) the ".note.ABI-tag" ELF section.
324 /* Look for an ".note.ABI-tag" ELF section */
326 for (i = 0; i < MAX_BRANDS; i++) {
327 bi = elf_brand_list[i];
330 if (interp != NULL && (bi->flags & BI_BRAND_ONLY_STATIC) != 0)
332 if (hdr->e_machine == bi->machine && (bi->flags &
333 (BI_BRAND_NOTE|BI_BRAND_NOTE_MANDATORY)) != 0) {
334 ret = __elfN(check_note)(imgp, bi->brand_note, osrel,
336 /* Give brand a chance to veto check_note's guess */
337 if (ret && bi->header_supported)
338 ret = bi->header_supported(imgp);
340 * If note checker claimed the binary, but the
341 * interpreter path in the image does not
342 * match default one for the brand, try to
343 * search for other brands with the same
344 * interpreter. Either there is better brand
345 * with the right interpreter, or, failing
346 * this, we return first brand which accepted
347 * our note and, optionally, header.
349 if (ret && bi_m == NULL && interp != NULL &&
350 (bi->interp_path == NULL ||
351 (strlen(bi->interp_path) + 1 != interp_name_len ||
352 strncmp(interp, bi->interp_path, interp_name_len)
364 /* If the executable has a brand, search for it in the brand list. */
365 for (i = 0; i < MAX_BRANDS; i++) {
366 bi = elf_brand_list[i];
367 if (bi == NULL || (bi->flags & BI_BRAND_NOTE_MANDATORY) != 0 ||
368 (interp != NULL && (bi->flags & BI_BRAND_ONLY_STATIC) != 0))
370 if (hdr->e_machine == bi->machine &&
371 (hdr->e_ident[EI_OSABI] == bi->brand ||
372 (bi->compat_3_brand != NULL &&
373 strcmp((const char *)&hdr->e_ident[OLD_EI_BRAND],
374 bi->compat_3_brand) == 0))) {
375 /* Looks good, but give brand a chance to veto */
376 if (bi->header_supported == NULL ||
377 bi->header_supported(imgp)) {
379 * Again, prefer strictly matching
382 if (interp_name_len == 0 &&
383 bi->interp_path == NULL)
385 if (bi->interp_path != NULL &&
386 strlen(bi->interp_path) + 1 ==
387 interp_name_len && strncmp(interp,
388 bi->interp_path, interp_name_len) == 0)
398 /* No known brand, see if the header is recognized by any brand */
399 for (i = 0; i < MAX_BRANDS; i++) {
400 bi = elf_brand_list[i];
401 if (bi == NULL || bi->flags & BI_BRAND_NOTE_MANDATORY ||
402 bi->header_supported == NULL)
404 if (hdr->e_machine == bi->machine) {
405 ret = bi->header_supported(imgp);
411 /* Lacking a known brand, search for a recognized interpreter. */
412 if (interp != NULL) {
413 for (i = 0; i < MAX_BRANDS; i++) {
414 bi = elf_brand_list[i];
415 if (bi == NULL || (bi->flags &
416 (BI_BRAND_NOTE_MANDATORY | BI_BRAND_ONLY_STATIC))
419 if (hdr->e_machine == bi->machine &&
420 bi->interp_path != NULL &&
421 /* ELF image p_filesz includes terminating zero */
422 strlen(bi->interp_path) + 1 == interp_name_len &&
423 strncmp(interp, bi->interp_path, interp_name_len)
424 == 0 && (bi->header_supported == NULL ||
425 bi->header_supported(imgp)))
430 /* Lacking a recognized interpreter, try the default brand */
431 for (i = 0; i < MAX_BRANDS; i++) {
432 bi = elf_brand_list[i];
433 if (bi == NULL || (bi->flags & BI_BRAND_NOTE_MANDATORY) != 0 ||
434 (interp != NULL && (bi->flags & BI_BRAND_ONLY_STATIC) != 0))
436 if (hdr->e_machine == bi->machine &&
437 __elfN(fallback_brand) == bi->brand &&
438 (bi->header_supported == NULL ||
439 bi->header_supported(imgp)))
446 __elfN(check_header)(const Elf_Ehdr *hdr)
452 hdr->e_ident[EI_CLASS] != ELF_TARG_CLASS ||
453 hdr->e_ident[EI_DATA] != ELF_TARG_DATA ||
454 hdr->e_ident[EI_VERSION] != EV_CURRENT ||
455 hdr->e_phentsize != sizeof(Elf_Phdr) ||
456 hdr->e_version != ELF_TARG_VER)
460 * Make sure we have at least one brand for this machine.
463 for (i = 0; i < MAX_BRANDS; i++) {
464 bi = elf_brand_list[i];
465 if (bi != NULL && bi->machine == hdr->e_machine)
475 __elfN(map_partial)(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
476 vm_offset_t start, vm_offset_t end, vm_prot_t prot)
483 * Create the page if it doesn't exist yet. Ignore errors.
485 vm_map_fixed(map, NULL, 0, trunc_page(start), round_page(end) -
486 trunc_page(start), VM_PROT_ALL, VM_PROT_ALL, MAP_CHECK_EXCL);
489 * Find the page from the underlying object.
491 if (object != NULL) {
492 sf = vm_imgact_map_page(object, offset);
494 return (KERN_FAILURE);
495 off = offset - trunc_page(offset);
496 error = copyout((caddr_t)sf_buf_kva(sf) + off, (caddr_t)start,
498 vm_imgact_unmap_page(sf);
500 return (KERN_FAILURE);
503 return (KERN_SUCCESS);
507 __elfN(map_insert)(struct image_params *imgp, vm_map_t map, vm_object_t object,
508 vm_ooffset_t offset, vm_offset_t start, vm_offset_t end, vm_prot_t prot,
514 int error, locked, rv;
516 if (start != trunc_page(start)) {
517 rv = __elfN(map_partial)(map, object, offset, start,
518 round_page(start), prot);
519 if (rv != KERN_SUCCESS)
521 offset += round_page(start) - start;
522 start = round_page(start);
524 if (end != round_page(end)) {
525 rv = __elfN(map_partial)(map, object, offset +
526 trunc_page(end) - start, trunc_page(end), end, prot);
527 if (rv != KERN_SUCCESS)
529 end = trunc_page(end);
532 return (KERN_SUCCESS);
533 if ((offset & PAGE_MASK) != 0) {
535 * The mapping is not page aligned. This means that we have
538 rv = vm_map_fixed(map, NULL, 0, start, end - start,
539 prot | VM_PROT_WRITE, VM_PROT_ALL, MAP_CHECK_EXCL);
540 if (rv != KERN_SUCCESS)
543 return (KERN_SUCCESS);
544 for (; start < end; start += sz) {
545 sf = vm_imgact_map_page(object, offset);
547 return (KERN_FAILURE);
548 off = offset - trunc_page(offset);
550 if (sz > PAGE_SIZE - off)
551 sz = PAGE_SIZE - off;
552 error = copyout((caddr_t)sf_buf_kva(sf) + off,
554 vm_imgact_unmap_page(sf);
556 return (KERN_FAILURE);
560 vm_object_reference(object);
561 rv = vm_map_fixed(map, object, offset, start, end - start,
562 prot, VM_PROT_ALL, cow | MAP_CHECK_EXCL |
563 (object != NULL ? MAP_VN_EXEC : 0));
564 if (rv != KERN_SUCCESS) {
565 locked = VOP_ISLOCKED(imgp->vp);
566 VOP_UNLOCK(imgp->vp);
567 vm_object_deallocate(object);
568 vn_lock(imgp->vp, locked | LK_RETRY);
570 } else if (object != NULL) {
571 MPASS(imgp->vp->v_object == object);
572 VOP_SET_TEXT_CHECKED(imgp->vp);
575 return (KERN_SUCCESS);
579 __elfN(load_section)(struct image_params *imgp, vm_ooffset_t offset,
580 caddr_t vmaddr, size_t memsz, size_t filsz, vm_prot_t prot)
586 vm_offset_t map_addr;
589 vm_ooffset_t file_addr;
592 * It's necessary to fail if the filsz + offset taken from the
593 * header is greater than the actual file pager object's size.
594 * If we were to allow this, then the vm_map_find() below would
595 * walk right off the end of the file object and into the ether.
597 * While I'm here, might as well check for something else that
598 * is invalid: filsz cannot be greater than memsz.
600 if ((filsz != 0 && (off_t)filsz + offset > imgp->attr->va_size) ||
602 uprintf("elf_load_section: truncated ELF file\n");
606 object = imgp->object;
607 map = &imgp->proc->p_vmspace->vm_map;
608 map_addr = trunc_page((vm_offset_t)vmaddr);
609 file_addr = trunc_page(offset);
612 * We have two choices. We can either clear the data in the last page
613 * of an oversized mapping, or we can start the anon mapping a page
614 * early and copy the initialized data into that first page. We
619 else if (memsz > filsz)
620 map_len = trunc_page(offset + filsz) - file_addr;
622 map_len = round_page(offset + filsz) - file_addr;
625 /* cow flags: don't dump readonly sections in core */
626 cow = MAP_COPY_ON_WRITE | MAP_PREFAULT |
627 (prot & VM_PROT_WRITE ? 0 : MAP_DISABLE_COREDUMP);
629 rv = __elfN(map_insert)(imgp, map, object, file_addr,
630 map_addr, map_addr + map_len, prot, cow);
631 if (rv != KERN_SUCCESS)
634 /* we can stop now if we've covered it all */
640 * We have to get the remaining bit of the file into the first part
641 * of the oversized map segment. This is normally because the .data
642 * segment in the file is extended to provide bss. It's a neat idea
643 * to try and save a page, but it's a pain in the behind to implement.
645 copy_len = filsz == 0 ? 0 : (offset + filsz) - trunc_page(offset +
647 map_addr = trunc_page((vm_offset_t)vmaddr + filsz);
648 map_len = round_page((vm_offset_t)vmaddr + memsz) - map_addr;
650 /* This had damn well better be true! */
652 rv = __elfN(map_insert)(imgp, map, NULL, 0, map_addr,
653 map_addr + map_len, prot, 0);
654 if (rv != KERN_SUCCESS)
659 sf = vm_imgact_map_page(object, offset + filsz);
663 /* send the page fragment to user space */
664 error = copyout((caddr_t)sf_buf_kva(sf), (caddr_t)map_addr,
666 vm_imgact_unmap_page(sf);
672 * Remove write access to the page if it was only granted by map_insert
675 if ((prot & VM_PROT_WRITE) == 0)
676 vm_map_protect(map, trunc_page(map_addr), round_page(map_addr +
677 map_len), prot, FALSE);
683 __elfN(load_sections)(struct image_params *imgp, const Elf_Ehdr *hdr,
684 const Elf_Phdr *phdr, u_long rbase, u_long *base_addrp)
691 ASSERT_VOP_LOCKED(imgp->vp, __func__);
696 for (i = 0; i < hdr->e_phnum; i++) {
697 if (phdr[i].p_type != PT_LOAD || phdr[i].p_memsz == 0)
700 /* Loadable segment */
701 prot = __elfN(trans_prot)(phdr[i].p_flags);
702 error = __elfN(load_section)(imgp, phdr[i].p_offset,
703 (caddr_t)(uintptr_t)phdr[i].p_vaddr + rbase,
704 phdr[i].p_memsz, phdr[i].p_filesz, prot);
709 * Establish the base address if this is the first segment.
712 base_addr = trunc_page(phdr[i].p_vaddr + rbase);
717 if (base_addrp != NULL)
718 *base_addrp = base_addr;
724 * Load the file "file" into memory. It may be either a shared object
727 * The "addr" reference parameter is in/out. On entry, it specifies
728 * the address where a shared object should be loaded. If the file is
729 * an executable, this value is ignored. On exit, "addr" specifies
730 * where the file was actually loaded.
732 * The "entry" reference parameter is out only. On exit, it specifies
733 * the entry point for the loaded file.
736 __elfN(load_file)(struct proc *p, const char *file, u_long *addr,
742 struct image_params image_params;
744 const Elf_Ehdr *hdr = NULL;
745 const Elf_Phdr *phdr = NULL;
746 struct nameidata *nd;
748 struct image_params *imgp;
750 u_long base_addr = 0;
753 #ifdef CAPABILITY_MODE
755 * XXXJA: This check can go away once we are sufficiently confident
756 * that the checks in namei() are correct.
758 if (IN_CAPABILITY_MODE(curthread))
762 tempdata = malloc(sizeof(*tempdata), M_TEMP, M_WAITOK | M_ZERO);
764 attr = &tempdata->attr;
765 imgp = &tempdata->image_params;
768 * Initialize part of the common data
773 NDINIT(nd, LOOKUP, ISOPEN | FOLLOW | LOCKSHARED | LOCKLEAF,
774 UIO_SYSSPACE, file, curthread);
775 if ((error = namei(nd)) != 0) {
779 NDFREE(nd, NDF_ONLY_PNBUF);
780 imgp->vp = nd->ni_vp;
783 * Check permissions, modes, uid, etc on the file, and "open" it.
785 error = exec_check_permissions(imgp);
789 error = exec_map_first_page(imgp);
793 imgp->object = nd->ni_vp->v_object;
795 hdr = (const Elf_Ehdr *)imgp->image_header;
796 if ((error = __elfN(check_header)(hdr)) != 0)
798 if (hdr->e_type == ET_DYN)
800 else if (hdr->e_type == ET_EXEC)
807 /* Only support headers that fit within first page for now */
808 if ((hdr->e_phoff > PAGE_SIZE) ||
809 (u_int)hdr->e_phentsize * hdr->e_phnum > PAGE_SIZE - hdr->e_phoff) {
814 phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
815 if (!aligned(phdr, Elf_Addr)) {
820 error = __elfN(load_sections)(imgp, hdr, phdr, rbase, &base_addr);
825 *entry = (unsigned long)hdr->e_entry + rbase;
829 exec_unmap_first_page(imgp);
833 VOP_UNSET_TEXT_CHECKED(nd->ni_vp);
836 free(tempdata, M_TEMP);
842 __CONCAT(rnd_, __elfN(base))(vm_map_t map __unused, u_long minv, u_long maxv,
847 MPASS(vm_map_min(map) <= minv);
848 MPASS(maxv <= vm_map_max(map));
850 MPASS(minv + align < maxv);
851 arc4rand(&rbase, sizeof(rbase), 0);
852 res = roundup(minv, (u_long)align) + rbase % (maxv - minv);
853 res &= ~((u_long)align - 1);
857 ("res %#lx < minv %#lx, maxv %#lx rbase %#lx",
858 res, minv, maxv, rbase));
860 ("res %#lx > maxv %#lx, minv %#lx rbase %#lx",
861 res, maxv, minv, rbase));
866 __elfN(enforce_limits)(struct image_params *imgp, const Elf_Ehdr *hdr,
867 const Elf_Phdr *phdr, u_long et_dyn_addr)
869 struct vmspace *vmspace;
871 u_long text_size, data_size, total_size, text_addr, data_addr;
872 u_long seg_size, seg_addr;
876 text_size = data_size = total_size = text_addr = data_addr = 0;
878 for (i = 0; i < hdr->e_phnum; i++) {
879 if (phdr[i].p_type != PT_LOAD || phdr[i].p_memsz == 0)
882 seg_addr = trunc_page(phdr[i].p_vaddr + et_dyn_addr);
883 seg_size = round_page(phdr[i].p_memsz +
884 phdr[i].p_vaddr + et_dyn_addr - seg_addr);
887 * Make the largest executable segment the official
888 * text segment and all others data.
890 * Note that obreak() assumes that data_addr + data_size == end
891 * of data load area, and the ELF file format expects segments
892 * to be sorted by address. If multiple data segments exist,
893 * the last one will be used.
896 if ((phdr[i].p_flags & PF_X) != 0 && text_size < seg_size) {
897 text_size = seg_size;
898 text_addr = seg_addr;
900 data_size = seg_size;
901 data_addr = seg_addr;
903 total_size += seg_size;
906 if (data_addr == 0 && data_size == 0) {
907 data_addr = text_addr;
908 data_size = text_size;
912 * Check limits. It should be safe to check the
913 * limits after loading the segments since we do
914 * not actually fault in all the segments pages.
916 PROC_LOCK(imgp->proc);
917 if (data_size > lim_cur_proc(imgp->proc, RLIMIT_DATA))
918 err_str = "Data segment size exceeds process limit";
919 else if (text_size > maxtsiz)
920 err_str = "Text segment size exceeds system limit";
921 else if (total_size > lim_cur_proc(imgp->proc, RLIMIT_VMEM))
922 err_str = "Total segment size exceeds process limit";
923 else if (racct_set(imgp->proc, RACCT_DATA, data_size) != 0)
924 err_str = "Data segment size exceeds resource limit";
925 else if (racct_set(imgp->proc, RACCT_VMEM, total_size) != 0)
926 err_str = "Total segment size exceeds resource limit";
927 PROC_UNLOCK(imgp->proc);
928 if (err_str != NULL) {
929 uprintf("%s\n", err_str);
933 vmspace = imgp->proc->p_vmspace;
934 vmspace->vm_tsize = text_size >> PAGE_SHIFT;
935 vmspace->vm_taddr = (caddr_t)(uintptr_t)text_addr;
936 vmspace->vm_dsize = data_size >> PAGE_SHIFT;
937 vmspace->vm_daddr = (caddr_t)(uintptr_t)data_addr;
943 __elfN(get_interp)(struct image_params *imgp, const Elf_Phdr *phdr,
944 char **interpp, bool *free_interpp)
948 int error, interp_name_len;
950 KASSERT(phdr->p_type == PT_INTERP,
951 ("%s: p_type %u != PT_INTERP", __func__, phdr->p_type));
952 ASSERT_VOP_LOCKED(imgp->vp, __func__);
956 /* Path to interpreter */
957 if (phdr->p_filesz < 2 || phdr->p_filesz > MAXPATHLEN) {
958 uprintf("Invalid PT_INTERP\n");
962 interp_name_len = phdr->p_filesz;
963 if (phdr->p_offset > PAGE_SIZE ||
964 interp_name_len > PAGE_SIZE - phdr->p_offset) {
966 * The vnode lock might be needed by the pagedaemon to
967 * clean pages owned by the vnode. Do not allow sleep
968 * waiting for memory with the vnode locked, instead
969 * try non-sleepable allocation first, and if it
970 * fails, go to the slow path were we drop the lock
971 * and do M_WAITOK. A text reference prevents
972 * modifications to the vnode content.
974 interp = malloc(interp_name_len + 1, M_TEMP, M_NOWAIT);
975 if (interp == NULL) {
976 VOP_UNLOCK(imgp->vp);
977 interp = malloc(interp_name_len + 1, M_TEMP, M_WAITOK);
978 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
981 error = vn_rdwr(UIO_READ, imgp->vp, interp,
982 interp_name_len, phdr->p_offset,
983 UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred,
986 free(interp, M_TEMP);
987 uprintf("i/o error PT_INTERP %d\n", error);
990 interp[interp_name_len] = '\0';
993 *free_interpp = true;
997 interp = __DECONST(char *, imgp->image_header) + phdr->p_offset;
998 if (interp[interp_name_len - 1] != '\0') {
999 uprintf("Invalid PT_INTERP\n");
1004 *free_interpp = false;
1009 __elfN(load_interp)(struct image_params *imgp, const Elf_Brandinfo *brand_info,
1010 const char *interp, u_long *addr, u_long *entry)
1015 if (brand_info->emul_path != NULL &&
1016 brand_info->emul_path[0] != '\0') {
1017 path = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1018 snprintf(path, MAXPATHLEN, "%s%s",
1019 brand_info->emul_path, interp);
1020 error = __elfN(load_file)(imgp->proc, path, addr, entry);
1026 if (brand_info->interp_newpath != NULL &&
1027 (brand_info->interp_path == NULL ||
1028 strcmp(interp, brand_info->interp_path) == 0)) {
1029 error = __elfN(load_file)(imgp->proc,
1030 brand_info->interp_newpath, addr, entry);
1035 error = __elfN(load_file)(imgp->proc, interp, addr, entry);
1039 uprintf("ELF interpreter %s not found, error %d\n", interp, error);
1044 * Impossible et_dyn_addr initial value indicating that the real base
1045 * must be calculated later with some randomization applied.
1047 #define ET_DYN_ADDR_RAND 1
1050 __CONCAT(exec_, __elfN(imgact))(struct image_params *imgp)
1053 const Elf_Ehdr *hdr;
1054 const Elf_Phdr *phdr;
1055 Elf_Auxargs *elf_auxargs;
1056 struct vmspace *vmspace;
1059 Elf_Brandinfo *brand_info;
1060 struct sysentvec *sv;
1061 u_long addr, baddr, et_dyn_addr, entry, proghdr;
1062 u_long maxalign, mapsz, maxv, maxv1;
1068 hdr = (const Elf_Ehdr *)imgp->image_header;
1071 * Do we have a valid ELF header ?
1073 * Only allow ET_EXEC & ET_DYN here, reject ET_DYN later
1074 * if particular brand doesn't support it.
1076 if (__elfN(check_header)(hdr) != 0 ||
1077 (hdr->e_type != ET_EXEC && hdr->e_type != ET_DYN))
1081 * From here on down, we return an errno, not -1, as we've
1082 * detected an ELF file.
1085 if ((hdr->e_phoff > PAGE_SIZE) ||
1086 (u_int)hdr->e_phentsize * hdr->e_phnum > PAGE_SIZE - hdr->e_phoff) {
1087 /* Only support headers in first page for now */
1088 uprintf("Program headers not in the first page\n");
1091 phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
1092 if (!aligned(phdr, Elf_Addr)) {
1093 uprintf("Unaligned program headers\n");
1101 entry = proghdr = 0;
1103 free_interp = false;
1105 maxalign = PAGE_SIZE;
1108 for (i = 0; i < hdr->e_phnum; i++) {
1109 switch (phdr[i].p_type) {
1112 baddr = phdr[i].p_vaddr;
1113 if (phdr[i].p_align > maxalign)
1114 maxalign = phdr[i].p_align;
1115 mapsz += phdr[i].p_memsz;
1119 * If this segment contains the program headers,
1120 * remember their virtual address for the AT_PHDR
1121 * aux entry. Static binaries don't usually include
1124 if (phdr[i].p_offset == 0 &&
1125 hdr->e_phoff + hdr->e_phnum * hdr->e_phentsize
1126 <= phdr[i].p_filesz)
1127 proghdr = phdr[i].p_vaddr + hdr->e_phoff;
1130 /* Path to interpreter */
1131 if (interp != NULL) {
1132 uprintf("Multiple PT_INTERP headers\n");
1136 error = __elfN(get_interp)(imgp, &phdr[i], &interp,
1142 if (__elfN(nxstack))
1144 __elfN(trans_prot)(phdr[i].p_flags);
1145 imgp->stack_sz = phdr[i].p_memsz;
1147 case PT_PHDR: /* Program header table info */
1148 proghdr = phdr[i].p_vaddr;
1153 brand_info = __elfN(get_brandinfo)(imgp, interp, &osrel, &fctl0);
1154 if (brand_info == NULL) {
1155 uprintf("ELF binary type \"%u\" not known.\n",
1156 hdr->e_ident[EI_OSABI]);
1160 sv = brand_info->sysvec;
1162 if (hdr->e_type == ET_DYN) {
1163 if ((brand_info->flags & BI_CAN_EXEC_DYN) == 0) {
1164 uprintf("Cannot execute shared object\n");
1169 * Honour the base load address from the dso if it is
1170 * non-zero for some reason.
1173 if ((sv->sv_flags & SV_ASLR) == 0 ||
1174 (fctl0 & NT_FREEBSD_FCTL_ASLR_DISABLE) != 0)
1175 et_dyn_addr = __elfN(pie_base);
1176 else if ((__elfN(pie_aslr_enabled) &&
1177 (imgp->proc->p_flag2 & P2_ASLR_DISABLE) == 0) ||
1178 (imgp->proc->p_flag2 & P2_ASLR_ENABLE) != 0)
1179 et_dyn_addr = ET_DYN_ADDR_RAND;
1181 et_dyn_addr = __elfN(pie_base);
1186 * Avoid a possible deadlock if the current address space is destroyed
1187 * and that address space maps the locked vnode. In the common case,
1188 * the locked vnode's v_usecount is decremented but remains greater
1189 * than zero. Consequently, the vnode lock is not needed by vrele().
1190 * However, in cases where the vnode lock is external, such as nullfs,
1191 * v_usecount may become zero.
1193 * The VV_TEXT flag prevents modifications to the executable while
1194 * the vnode is unlocked.
1196 VOP_UNLOCK(imgp->vp);
1199 * Decide whether to enable randomization of user mappings.
1200 * First, reset user preferences for the setid binaries.
1201 * Then, account for the support of the randomization by the
1202 * ABI, by user preferences, and make special treatment for
1205 if (imgp->credential_setid) {
1206 PROC_LOCK(imgp->proc);
1207 imgp->proc->p_flag2 &= ~(P2_ASLR_ENABLE | P2_ASLR_DISABLE);
1208 PROC_UNLOCK(imgp->proc);
1210 if ((sv->sv_flags & SV_ASLR) == 0 ||
1211 (imgp->proc->p_flag2 & P2_ASLR_DISABLE) != 0 ||
1212 (fctl0 & NT_FREEBSD_FCTL_ASLR_DISABLE) != 0) {
1213 KASSERT(et_dyn_addr != ET_DYN_ADDR_RAND,
1214 ("et_dyn_addr == RAND and !ASLR"));
1215 } else if ((imgp->proc->p_flag2 & P2_ASLR_ENABLE) != 0 ||
1216 (__elfN(aslr_enabled) && hdr->e_type == ET_EXEC) ||
1217 et_dyn_addr == ET_DYN_ADDR_RAND) {
1218 imgp->map_flags |= MAP_ASLR;
1220 * If user does not care about sbrk, utilize the bss
1221 * grow region for mappings as well. We can select
1222 * the base for the image anywere and still not suffer
1223 * from the fragmentation.
1225 if (!__elfN(aslr_honor_sbrk) ||
1226 (imgp->proc->p_flag2 & P2_ASLR_IGNSTART) != 0)
1227 imgp->map_flags |= MAP_ASLR_IGNSTART;
1230 error = exec_new_vmspace(imgp, sv);
1231 vmspace = imgp->proc->p_vmspace;
1232 map = &vmspace->vm_map;
1234 imgp->proc->p_sysent = sv;
1236 maxv = vm_map_max(map) - lim_max(td, RLIMIT_STACK);
1237 if (et_dyn_addr == ET_DYN_ADDR_RAND) {
1238 KASSERT((map->flags & MAP_ASLR) != 0,
1239 ("ET_DYN_ADDR_RAND but !MAP_ASLR"));
1240 et_dyn_addr = __CONCAT(rnd_, __elfN(base))(map,
1241 vm_map_min(map) + mapsz + lim_max(td, RLIMIT_DATA),
1242 /* reserve half of the address space to interpreter */
1243 maxv / 2, 1UL << flsl(maxalign));
1246 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
1250 error = __elfN(load_sections)(imgp, hdr, phdr, et_dyn_addr, NULL);
1254 error = __elfN(enforce_limits)(imgp, hdr, phdr, et_dyn_addr);
1258 entry = (u_long)hdr->e_entry + et_dyn_addr;
1261 * We load the dynamic linker where a userland call
1262 * to mmap(0, ...) would put it. The rationale behind this
1263 * calculation is that it leaves room for the heap to grow to
1264 * its maximum allowed size.
1266 addr = round_page((vm_offset_t)vmspace->vm_daddr + lim_max(td,
1268 if ((map->flags & MAP_ASLR) != 0) {
1269 maxv1 = maxv / 2 + addr / 2;
1270 MPASS(maxv1 >= addr); /* No overflow */
1271 map->anon_loc = __CONCAT(rnd_, __elfN(base))(map, addr, maxv1,
1272 MAXPAGESIZES > 1 ? pagesizes[1] : pagesizes[0]);
1274 map->anon_loc = addr;
1277 imgp->entry_addr = entry;
1279 if (interp != NULL) {
1280 VOP_UNLOCK(imgp->vp);
1281 if ((map->flags & MAP_ASLR) != 0) {
1282 /* Assume that interpeter fits into 1/4 of AS */
1283 maxv1 = maxv / 2 + addr / 2;
1284 MPASS(maxv1 >= addr); /* No overflow */
1285 addr = __CONCAT(rnd_, __elfN(base))(map, addr,
1288 error = __elfN(load_interp)(imgp, brand_info, interp, &addr,
1290 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
1297 * Construct auxargs table (used by the copyout_auxargs routine)
1299 elf_auxargs = malloc(sizeof(Elf_Auxargs), M_TEMP, M_NOWAIT);
1300 if (elf_auxargs == NULL) {
1301 VOP_UNLOCK(imgp->vp);
1302 elf_auxargs = malloc(sizeof(Elf_Auxargs), M_TEMP, M_WAITOK);
1303 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
1305 elf_auxargs->execfd = -1;
1306 elf_auxargs->phdr = proghdr + et_dyn_addr;
1307 elf_auxargs->phent = hdr->e_phentsize;
1308 elf_auxargs->phnum = hdr->e_phnum;
1309 elf_auxargs->pagesz = PAGE_SIZE;
1310 elf_auxargs->base = addr;
1311 elf_auxargs->flags = 0;
1312 elf_auxargs->entry = entry;
1313 elf_auxargs->hdr_eflags = hdr->e_flags;
1315 imgp->auxargs = elf_auxargs;
1316 imgp->interpreted = 0;
1317 imgp->reloc_base = addr;
1318 imgp->proc->p_osrel = osrel;
1319 imgp->proc->p_fctl0 = fctl0;
1320 imgp->proc->p_elf_machine = hdr->e_machine;
1321 imgp->proc->p_elf_flags = hdr->e_flags;
1325 free(interp, M_TEMP);
1329 #define suword __CONCAT(suword, __ELF_WORD_SIZE)
1332 __elfN(freebsd_copyout_auxargs)(struct image_params *imgp, uintptr_t base)
1334 Elf_Auxargs *args = (Elf_Auxargs *)imgp->auxargs;
1335 Elf_Auxinfo *argarray, *pos;
1338 argarray = pos = malloc(AT_COUNT * sizeof(*pos), M_TEMP,
1341 if (args->execfd != -1)
1342 AUXARGS_ENTRY(pos, AT_EXECFD, args->execfd);
1343 AUXARGS_ENTRY(pos, AT_PHDR, args->phdr);
1344 AUXARGS_ENTRY(pos, AT_PHENT, args->phent);
1345 AUXARGS_ENTRY(pos, AT_PHNUM, args->phnum);
1346 AUXARGS_ENTRY(pos, AT_PAGESZ, args->pagesz);
1347 AUXARGS_ENTRY(pos, AT_FLAGS, args->flags);
1348 AUXARGS_ENTRY(pos, AT_ENTRY, args->entry);
1349 AUXARGS_ENTRY(pos, AT_BASE, args->base);
1350 AUXARGS_ENTRY(pos, AT_EHDRFLAGS, args->hdr_eflags);
1351 if (imgp->execpathp != 0)
1352 AUXARGS_ENTRY(pos, AT_EXECPATH, imgp->execpathp);
1353 AUXARGS_ENTRY(pos, AT_OSRELDATE,
1354 imgp->proc->p_ucred->cr_prison->pr_osreldate);
1355 if (imgp->canary != 0) {
1356 AUXARGS_ENTRY(pos, AT_CANARY, imgp->canary);
1357 AUXARGS_ENTRY(pos, AT_CANARYLEN, imgp->canarylen);
1359 AUXARGS_ENTRY(pos, AT_NCPUS, mp_ncpus);
1360 if (imgp->pagesizes != 0) {
1361 AUXARGS_ENTRY(pos, AT_PAGESIZES, imgp->pagesizes);
1362 AUXARGS_ENTRY(pos, AT_PAGESIZESLEN, imgp->pagesizeslen);
1364 if (imgp->sysent->sv_timekeep_base != 0) {
1365 AUXARGS_ENTRY(pos, AT_TIMEKEEP,
1366 imgp->sysent->sv_timekeep_base);
1368 AUXARGS_ENTRY(pos, AT_STACKPROT, imgp->sysent->sv_shared_page_obj
1369 != NULL && imgp->stack_prot != 0 ? imgp->stack_prot :
1370 imgp->sysent->sv_stackprot);
1371 if (imgp->sysent->sv_hwcap != NULL)
1372 AUXARGS_ENTRY(pos, AT_HWCAP, *imgp->sysent->sv_hwcap);
1373 if (imgp->sysent->sv_hwcap2 != NULL)
1374 AUXARGS_ENTRY(pos, AT_HWCAP2, *imgp->sysent->sv_hwcap2);
1375 AUXARGS_ENTRY(pos, AT_BSDFLAGS, __elfN(sigfastblock) ?
1376 ELF_BSDF_SIGFASTBLK : 0);
1377 AUXARGS_ENTRY(pos, AT_NULL, 0);
1379 free(imgp->auxargs, M_TEMP);
1380 imgp->auxargs = NULL;
1381 KASSERT(pos - argarray <= AT_COUNT, ("Too many auxargs"));
1383 error = copyout(argarray, (void *)base, sizeof(*argarray) * AT_COUNT);
1384 free(argarray, M_TEMP);
1389 __elfN(freebsd_fixup)(uintptr_t *stack_base, struct image_params *imgp)
1393 base = (Elf_Addr *)*stack_base;
1395 if (suword(base, imgp->args->argc) == -1)
1397 *stack_base = (uintptr_t)base;
1402 * Code for generating ELF core dumps.
1405 typedef void (*segment_callback)(vm_map_entry_t, void *);
1407 /* Closure for cb_put_phdr(). */
1408 struct phdr_closure {
1409 Elf_Phdr *phdr; /* Program header to fill in */
1410 Elf_Off offset; /* Offset of segment in core file */
1413 /* Closure for cb_size_segment(). */
1414 struct sseg_closure {
1415 int count; /* Count of writable segments. */
1416 size_t size; /* Total size of all writable segments. */
1419 typedef void (*outfunc_t)(void *, struct sbuf *, size_t *);
1422 int type; /* Note type. */
1423 outfunc_t outfunc; /* Output function. */
1424 void *outarg; /* Argument for the output function. */
1425 size_t outsize; /* Output size. */
1426 TAILQ_ENTRY(note_info) link; /* Link to the next note info. */
1429 TAILQ_HEAD(note_info_list, note_info);
1431 /* Coredump output parameters. */
1432 struct coredump_params {
1434 struct ucred *active_cred;
1435 struct ucred *file_cred;
1438 struct compressor *comp;
1441 extern int compress_user_cores;
1442 extern int compress_user_cores_level;
1444 static void cb_put_phdr(vm_map_entry_t, void *);
1445 static void cb_size_segment(vm_map_entry_t, void *);
1446 static int core_write(struct coredump_params *, const void *, size_t, off_t,
1448 static void each_dumpable_segment(struct thread *, segment_callback, void *);
1449 static int __elfN(corehdr)(struct coredump_params *, int, void *, size_t,
1450 struct note_info_list *, size_t);
1451 static void __elfN(prepare_notes)(struct thread *, struct note_info_list *,
1453 static void __elfN(puthdr)(struct thread *, void *, size_t, int, size_t);
1454 static void __elfN(putnote)(struct note_info *, struct sbuf *);
1455 static size_t register_note(struct note_info_list *, int, outfunc_t, void *);
1456 static int sbuf_drain_core_output(void *, const char *, int);
1458 static void __elfN(note_fpregset)(void *, struct sbuf *, size_t *);
1459 static void __elfN(note_prpsinfo)(void *, struct sbuf *, size_t *);
1460 static void __elfN(note_prstatus)(void *, struct sbuf *, size_t *);
1461 static void __elfN(note_threadmd)(void *, struct sbuf *, size_t *);
1462 static void __elfN(note_thrmisc)(void *, struct sbuf *, size_t *);
1463 static void __elfN(note_ptlwpinfo)(void *, struct sbuf *, size_t *);
1464 static void __elfN(note_procstat_auxv)(void *, struct sbuf *, size_t *);
1465 static void __elfN(note_procstat_proc)(void *, struct sbuf *, size_t *);
1466 static void __elfN(note_procstat_psstrings)(void *, struct sbuf *, size_t *);
1467 static void note_procstat_files(void *, struct sbuf *, size_t *);
1468 static void note_procstat_groups(void *, struct sbuf *, size_t *);
1469 static void note_procstat_osrel(void *, struct sbuf *, size_t *);
1470 static void note_procstat_rlimit(void *, struct sbuf *, size_t *);
1471 static void note_procstat_umask(void *, struct sbuf *, size_t *);
1472 static void note_procstat_vmmap(void *, struct sbuf *, size_t *);
1475 * Write out a core segment to the compression stream.
1478 compress_chunk(struct coredump_params *p, char *base, char *buf, u_int len)
1484 chunk_len = MIN(len, CORE_BUF_SIZE);
1487 * We can get EFAULT error here.
1488 * In that case zero out the current chunk of the segment.
1490 error = copyin(base, buf, chunk_len);
1492 bzero(buf, chunk_len);
1493 error = compressor_write(p->comp, buf, chunk_len);
1503 core_compressed_write(void *base, size_t len, off_t offset, void *arg)
1506 return (core_write((struct coredump_params *)arg, base, len, offset,
1511 core_write(struct coredump_params *p, const void *base, size_t len,
1512 off_t offset, enum uio_seg seg)
1515 return (vn_rdwr_inchunks(UIO_WRITE, p->vp, __DECONST(void *, base),
1516 len, offset, seg, IO_UNIT | IO_DIRECT | IO_RANGELOCKED,
1517 p->active_cred, p->file_cred, NULL, p->td));
1521 core_output(void *base, size_t len, off_t offset, struct coredump_params *p,
1526 if (p->comp != NULL)
1527 return (compress_chunk(p, base, tmpbuf, len));
1530 * EFAULT is a non-fatal error that we can get, for example,
1531 * if the segment is backed by a file but extends beyond its
1534 error = core_write(p, base, len, offset, UIO_USERSPACE);
1535 if (error == EFAULT) {
1536 log(LOG_WARNING, "Failed to fully fault in a core file segment "
1537 "at VA %p with size 0x%zx to be written at offset 0x%jx "
1538 "for process %s\n", base, len, offset, curproc->p_comm);
1541 * Write a "real" zero byte at the end of the target region
1542 * in the case this is the last segment.
1543 * The intermediate space will be implicitly zero-filled.
1545 error = core_write(p, zero_region, 1, offset + len - 1,
1552 * Drain into a core file.
1555 sbuf_drain_core_output(void *arg, const char *data, int len)
1557 struct coredump_params *p;
1560 p = (struct coredump_params *)arg;
1563 * Some kern_proc out routines that print to this sbuf may
1564 * call us with the process lock held. Draining with the
1565 * non-sleepable lock held is unsafe. The lock is needed for
1566 * those routines when dumping a live process. In our case we
1567 * can safely release the lock before draining and acquire
1570 locked = PROC_LOCKED(p->td->td_proc);
1572 PROC_UNLOCK(p->td->td_proc);
1573 if (p->comp != NULL)
1574 error = compressor_write(p->comp, __DECONST(char *, data), len);
1576 error = core_write(p, __DECONST(void *, data), len, p->offset,
1579 PROC_LOCK(p->td->td_proc);
1587 __elfN(coredump)(struct thread *td, struct vnode *vp, off_t limit, int flags)
1589 struct ucred *cred = td->td_ucred;
1591 struct sseg_closure seginfo;
1592 struct note_info_list notelst;
1593 struct coredump_params params;
1594 struct note_info *ninfo;
1596 size_t hdrsize, notesz, coresize;
1600 TAILQ_INIT(¬elst);
1602 /* Size the program segments. */
1605 each_dumpable_segment(td, cb_size_segment, &seginfo);
1608 * Collect info about the core file header area.
1610 hdrsize = sizeof(Elf_Ehdr) + sizeof(Elf_Phdr) * (1 + seginfo.count);
1611 if (seginfo.count + 1 >= PN_XNUM)
1612 hdrsize += sizeof(Elf_Shdr);
1613 __elfN(prepare_notes)(td, ¬elst, ¬esz);
1614 coresize = round_page(hdrsize + notesz) + seginfo.size;
1616 /* Set up core dump parameters. */
1618 params.active_cred = cred;
1619 params.file_cred = NOCRED;
1626 PROC_LOCK(td->td_proc);
1627 error = racct_add(td->td_proc, RACCT_CORE, coresize);
1628 PROC_UNLOCK(td->td_proc);
1635 if (coresize >= limit) {
1640 /* Create a compression stream if necessary. */
1641 if (compress_user_cores != 0) {
1642 params.comp = compressor_init(core_compressed_write,
1643 compress_user_cores, CORE_BUF_SIZE,
1644 compress_user_cores_level, ¶ms);
1645 if (params.comp == NULL) {
1649 tmpbuf = malloc(CORE_BUF_SIZE, M_TEMP, M_WAITOK | M_ZERO);
1653 * Allocate memory for building the header, fill it up,
1654 * and write it out following the notes.
1656 hdr = malloc(hdrsize, M_TEMP, M_WAITOK);
1657 error = __elfN(corehdr)(¶ms, seginfo.count, hdr, hdrsize, ¬elst,
1660 /* Write the contents of all of the writable segments. */
1666 php = (Elf_Phdr *)((char *)hdr + sizeof(Elf_Ehdr)) + 1;
1667 offset = round_page(hdrsize + notesz);
1668 for (i = 0; i < seginfo.count; i++) {
1669 error = core_output((caddr_t)(uintptr_t)php->p_vaddr,
1670 php->p_filesz, offset, ¶ms, tmpbuf);
1673 offset += php->p_filesz;
1676 if (error == 0 && params.comp != NULL)
1677 error = compressor_flush(params.comp);
1681 "Failed to write core file for process %s (error %d)\n",
1682 curproc->p_comm, error);
1686 free(tmpbuf, M_TEMP);
1687 if (params.comp != NULL)
1688 compressor_fini(params.comp);
1689 while ((ninfo = TAILQ_FIRST(¬elst)) != NULL) {
1690 TAILQ_REMOVE(¬elst, ninfo, link);
1691 free(ninfo, M_TEMP);
1700 * A callback for each_dumpable_segment() to write out the segment's
1701 * program header entry.
1704 cb_put_phdr(vm_map_entry_t entry, void *closure)
1706 struct phdr_closure *phc = (struct phdr_closure *)closure;
1707 Elf_Phdr *phdr = phc->phdr;
1709 phc->offset = round_page(phc->offset);
1711 phdr->p_type = PT_LOAD;
1712 phdr->p_offset = phc->offset;
1713 phdr->p_vaddr = entry->start;
1715 phdr->p_filesz = phdr->p_memsz = entry->end - entry->start;
1716 phdr->p_align = PAGE_SIZE;
1717 phdr->p_flags = __elfN(untrans_prot)(entry->protection);
1719 phc->offset += phdr->p_filesz;
1724 * A callback for each_dumpable_segment() to gather information about
1725 * the number of segments and their total size.
1728 cb_size_segment(vm_map_entry_t entry, void *closure)
1730 struct sseg_closure *ssc = (struct sseg_closure *)closure;
1733 ssc->size += entry->end - entry->start;
1737 * For each writable segment in the process's memory map, call the given
1738 * function with a pointer to the map entry and some arbitrary
1739 * caller-supplied data.
1742 each_dumpable_segment(struct thread *td, segment_callback func, void *closure)
1744 struct proc *p = td->td_proc;
1745 vm_map_t map = &p->p_vmspace->vm_map;
1746 vm_map_entry_t entry;
1747 vm_object_t backing_object, object;
1748 boolean_t ignore_entry;
1750 vm_map_lock_read(map);
1751 VM_MAP_ENTRY_FOREACH(entry, map) {
1753 * Don't dump inaccessible mappings, deal with legacy
1756 * Note that read-only segments related to the elf binary
1757 * are marked MAP_ENTRY_NOCOREDUMP now so we no longer
1758 * need to arbitrarily ignore such segments.
1760 if (elf_legacy_coredump) {
1761 if ((entry->protection & VM_PROT_RW) != VM_PROT_RW)
1764 if ((entry->protection & VM_PROT_ALL) == 0)
1769 * Dont include memory segment in the coredump if
1770 * MAP_NOCORE is set in mmap(2) or MADV_NOCORE in
1771 * madvise(2). Do not dump submaps (i.e. parts of the
1774 if (entry->eflags & (MAP_ENTRY_NOCOREDUMP|MAP_ENTRY_IS_SUB_MAP))
1777 if ((object = entry->object.vm_object) == NULL)
1780 /* Ignore memory-mapped devices and such things. */
1781 VM_OBJECT_RLOCK(object);
1782 while ((backing_object = object->backing_object) != NULL) {
1783 VM_OBJECT_RLOCK(backing_object);
1784 VM_OBJECT_RUNLOCK(object);
1785 object = backing_object;
1787 ignore_entry = object->type != OBJT_DEFAULT &&
1788 object->type != OBJT_SWAP && object->type != OBJT_VNODE &&
1789 object->type != OBJT_PHYS;
1790 VM_OBJECT_RUNLOCK(object);
1794 (*func)(entry, closure);
1796 vm_map_unlock_read(map);
1800 * Write the core file header to the file, including padding up to
1801 * the page boundary.
1804 __elfN(corehdr)(struct coredump_params *p, int numsegs, void *hdr,
1805 size_t hdrsize, struct note_info_list *notelst, size_t notesz)
1807 struct note_info *ninfo;
1811 /* Fill in the header. */
1812 bzero(hdr, hdrsize);
1813 __elfN(puthdr)(p->td, hdr, hdrsize, numsegs, notesz);
1815 sb = sbuf_new(NULL, NULL, CORE_BUF_SIZE, SBUF_FIXEDLEN);
1816 sbuf_set_drain(sb, sbuf_drain_core_output, p);
1817 sbuf_start_section(sb, NULL);
1818 sbuf_bcat(sb, hdr, hdrsize);
1819 TAILQ_FOREACH(ninfo, notelst, link)
1820 __elfN(putnote)(ninfo, sb);
1821 /* Align up to a page boundary for the program segments. */
1822 sbuf_end_section(sb, -1, PAGE_SIZE, 0);
1823 error = sbuf_finish(sb);
1830 __elfN(prepare_notes)(struct thread *td, struct note_info_list *list,
1840 size += register_note(list, NT_PRPSINFO, __elfN(note_prpsinfo), p);
1843 * To have the debugger select the right thread (LWP) as the initial
1844 * thread, we dump the state of the thread passed to us in td first.
1845 * This is the thread that causes the core dump and thus likely to
1846 * be the right thread one wants to have selected in the debugger.
1849 while (thr != NULL) {
1850 size += register_note(list, NT_PRSTATUS,
1851 __elfN(note_prstatus), thr);
1852 size += register_note(list, NT_FPREGSET,
1853 __elfN(note_fpregset), thr);
1854 size += register_note(list, NT_THRMISC,
1855 __elfN(note_thrmisc), thr);
1856 size += register_note(list, NT_PTLWPINFO,
1857 __elfN(note_ptlwpinfo), thr);
1858 size += register_note(list, -1,
1859 __elfN(note_threadmd), thr);
1861 thr = (thr == td) ? TAILQ_FIRST(&p->p_threads) :
1862 TAILQ_NEXT(thr, td_plist);
1864 thr = TAILQ_NEXT(thr, td_plist);
1867 size += register_note(list, NT_PROCSTAT_PROC,
1868 __elfN(note_procstat_proc), p);
1869 size += register_note(list, NT_PROCSTAT_FILES,
1870 note_procstat_files, p);
1871 size += register_note(list, NT_PROCSTAT_VMMAP,
1872 note_procstat_vmmap, p);
1873 size += register_note(list, NT_PROCSTAT_GROUPS,
1874 note_procstat_groups, p);
1875 size += register_note(list, NT_PROCSTAT_UMASK,
1876 note_procstat_umask, p);
1877 size += register_note(list, NT_PROCSTAT_RLIMIT,
1878 note_procstat_rlimit, p);
1879 size += register_note(list, NT_PROCSTAT_OSREL,
1880 note_procstat_osrel, p);
1881 size += register_note(list, NT_PROCSTAT_PSSTRINGS,
1882 __elfN(note_procstat_psstrings), p);
1883 size += register_note(list, NT_PROCSTAT_AUXV,
1884 __elfN(note_procstat_auxv), p);
1890 __elfN(puthdr)(struct thread *td, void *hdr, size_t hdrsize, int numsegs,
1896 struct phdr_closure phc;
1898 ehdr = (Elf_Ehdr *)hdr;
1900 ehdr->e_ident[EI_MAG0] = ELFMAG0;
1901 ehdr->e_ident[EI_MAG1] = ELFMAG1;
1902 ehdr->e_ident[EI_MAG2] = ELFMAG2;
1903 ehdr->e_ident[EI_MAG3] = ELFMAG3;
1904 ehdr->e_ident[EI_CLASS] = ELF_CLASS;
1905 ehdr->e_ident[EI_DATA] = ELF_DATA;
1906 ehdr->e_ident[EI_VERSION] = EV_CURRENT;
1907 ehdr->e_ident[EI_OSABI] = ELFOSABI_FREEBSD;
1908 ehdr->e_ident[EI_ABIVERSION] = 0;
1909 ehdr->e_ident[EI_PAD] = 0;
1910 ehdr->e_type = ET_CORE;
1911 ehdr->e_machine = td->td_proc->p_elf_machine;
1912 ehdr->e_version = EV_CURRENT;
1914 ehdr->e_phoff = sizeof(Elf_Ehdr);
1915 ehdr->e_flags = td->td_proc->p_elf_flags;
1916 ehdr->e_ehsize = sizeof(Elf_Ehdr);
1917 ehdr->e_phentsize = sizeof(Elf_Phdr);
1918 ehdr->e_shentsize = sizeof(Elf_Shdr);
1919 ehdr->e_shstrndx = SHN_UNDEF;
1920 if (numsegs + 1 < PN_XNUM) {
1921 ehdr->e_phnum = numsegs + 1;
1924 ehdr->e_phnum = PN_XNUM;
1927 ehdr->e_shoff = ehdr->e_phoff +
1928 (numsegs + 1) * ehdr->e_phentsize;
1929 KASSERT(ehdr->e_shoff == hdrsize - sizeof(Elf_Shdr),
1930 ("e_shoff: %zu, hdrsize - shdr: %zu",
1931 (size_t)ehdr->e_shoff, hdrsize - sizeof(Elf_Shdr)));
1933 shdr = (Elf_Shdr *)((char *)hdr + ehdr->e_shoff);
1934 memset(shdr, 0, sizeof(*shdr));
1936 * A special first section is used to hold large segment and
1937 * section counts. This was proposed by Sun Microsystems in
1938 * Solaris and has been adopted by Linux; the standard ELF
1939 * tools are already familiar with the technique.
1941 * See table 7-7 of the Solaris "Linker and Libraries Guide"
1942 * (or 12-7 depending on the version of the document) for more
1945 shdr->sh_type = SHT_NULL;
1946 shdr->sh_size = ehdr->e_shnum;
1947 shdr->sh_link = ehdr->e_shstrndx;
1948 shdr->sh_info = numsegs + 1;
1952 * Fill in the program header entries.
1954 phdr = (Elf_Phdr *)((char *)hdr + ehdr->e_phoff);
1956 /* The note segement. */
1957 phdr->p_type = PT_NOTE;
1958 phdr->p_offset = hdrsize;
1961 phdr->p_filesz = notesz;
1963 phdr->p_flags = PF_R;
1964 phdr->p_align = ELF_NOTE_ROUNDSIZE;
1967 /* All the writable segments from the program. */
1969 phc.offset = round_page(hdrsize + notesz);
1970 each_dumpable_segment(td, cb_put_phdr, &phc);
1974 register_note(struct note_info_list *list, int type, outfunc_t out, void *arg)
1976 struct note_info *ninfo;
1977 size_t size, notesize;
1980 out(arg, NULL, &size);
1981 ninfo = malloc(sizeof(*ninfo), M_TEMP, M_ZERO | M_WAITOK);
1983 ninfo->outfunc = out;
1984 ninfo->outarg = arg;
1985 ninfo->outsize = size;
1986 TAILQ_INSERT_TAIL(list, ninfo, link);
1991 notesize = sizeof(Elf_Note) + /* note header */
1992 roundup2(sizeof(FREEBSD_ABI_VENDOR), ELF_NOTE_ROUNDSIZE) +
1994 roundup2(size, ELF_NOTE_ROUNDSIZE); /* note description */
2000 append_note_data(const void *src, void *dst, size_t len)
2004 padded_len = roundup2(len, ELF_NOTE_ROUNDSIZE);
2006 bcopy(src, dst, len);
2007 bzero((char *)dst + len, padded_len - len);
2009 return (padded_len);
2013 __elfN(populate_note)(int type, void *src, void *dst, size_t size, void **descp)
2021 note = (Elf_Note *)buf;
2022 note->n_namesz = sizeof(FREEBSD_ABI_VENDOR);
2023 note->n_descsz = size;
2024 note->n_type = type;
2025 buf += sizeof(*note);
2026 buf += append_note_data(FREEBSD_ABI_VENDOR, buf,
2027 sizeof(FREEBSD_ABI_VENDOR));
2028 append_note_data(src, buf, size);
2033 notesize = sizeof(Elf_Note) + /* note header */
2034 roundup2(sizeof(FREEBSD_ABI_VENDOR), ELF_NOTE_ROUNDSIZE) +
2036 roundup2(size, ELF_NOTE_ROUNDSIZE); /* note description */
2042 __elfN(putnote)(struct note_info *ninfo, struct sbuf *sb)
2045 ssize_t old_len, sect_len;
2046 size_t new_len, descsz, i;
2048 if (ninfo->type == -1) {
2049 ninfo->outfunc(ninfo->outarg, sb, &ninfo->outsize);
2053 note.n_namesz = sizeof(FREEBSD_ABI_VENDOR);
2054 note.n_descsz = ninfo->outsize;
2055 note.n_type = ninfo->type;
2057 sbuf_bcat(sb, ¬e, sizeof(note));
2058 sbuf_start_section(sb, &old_len);
2059 sbuf_bcat(sb, FREEBSD_ABI_VENDOR, sizeof(FREEBSD_ABI_VENDOR));
2060 sbuf_end_section(sb, old_len, ELF_NOTE_ROUNDSIZE, 0);
2061 if (note.n_descsz == 0)
2063 sbuf_start_section(sb, &old_len);
2064 ninfo->outfunc(ninfo->outarg, sb, &ninfo->outsize);
2065 sect_len = sbuf_end_section(sb, old_len, ELF_NOTE_ROUNDSIZE, 0);
2069 new_len = (size_t)sect_len;
2070 descsz = roundup(note.n_descsz, ELF_NOTE_ROUNDSIZE);
2071 if (new_len < descsz) {
2073 * It is expected that individual note emitters will correctly
2074 * predict their expected output size and fill up to that size
2075 * themselves, padding in a format-specific way if needed.
2076 * However, in case they don't, just do it here with zeros.
2078 for (i = 0; i < descsz - new_len; i++)
2080 } else if (new_len > descsz) {
2082 * We can't always truncate sb -- we may have drained some
2085 KASSERT(new_len == descsz, ("%s: Note type %u changed as we "
2086 "read it (%zu > %zu). Since it is longer than "
2087 "expected, this coredump's notes are corrupt. THIS "
2088 "IS A BUG in the note_procstat routine for type %u.\n",
2089 __func__, (unsigned)note.n_type, new_len, descsz,
2090 (unsigned)note.n_type));
2095 * Miscellaneous note out functions.
2098 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
2099 #include <compat/freebsd32/freebsd32.h>
2100 #include <compat/freebsd32/freebsd32_signal.h>
2102 typedef struct prstatus32 elf_prstatus_t;
2103 typedef struct prpsinfo32 elf_prpsinfo_t;
2104 typedef struct fpreg32 elf_prfpregset_t;
2105 typedef struct fpreg32 elf_fpregset_t;
2106 typedef struct reg32 elf_gregset_t;
2107 typedef struct thrmisc32 elf_thrmisc_t;
2108 #define ELF_KERN_PROC_MASK KERN_PROC_MASK32
2109 typedef struct kinfo_proc32 elf_kinfo_proc_t;
2110 typedef uint32_t elf_ps_strings_t;
2112 typedef prstatus_t elf_prstatus_t;
2113 typedef prpsinfo_t elf_prpsinfo_t;
2114 typedef prfpregset_t elf_prfpregset_t;
2115 typedef prfpregset_t elf_fpregset_t;
2116 typedef gregset_t elf_gregset_t;
2117 typedef thrmisc_t elf_thrmisc_t;
2118 #define ELF_KERN_PROC_MASK 0
2119 typedef struct kinfo_proc elf_kinfo_proc_t;
2120 typedef vm_offset_t elf_ps_strings_t;
2124 __elfN(note_prpsinfo)(void *arg, struct sbuf *sb, size_t *sizep)
2130 elf_prpsinfo_t *psinfo;
2133 p = (struct proc *)arg;
2135 KASSERT(*sizep == sizeof(*psinfo), ("invalid size"));
2136 psinfo = malloc(sizeof(*psinfo), M_TEMP, M_ZERO | M_WAITOK);
2137 psinfo->pr_version = PRPSINFO_VERSION;
2138 psinfo->pr_psinfosz = sizeof(elf_prpsinfo_t);
2139 strlcpy(psinfo->pr_fname, p->p_comm, sizeof(psinfo->pr_fname));
2141 if (p->p_args != NULL) {
2142 len = sizeof(psinfo->pr_psargs) - 1;
2143 if (len > p->p_args->ar_length)
2144 len = p->p_args->ar_length;
2145 memcpy(psinfo->pr_psargs, p->p_args->ar_args, len);
2151 sbuf_new(&sbarg, psinfo->pr_psargs,
2152 sizeof(psinfo->pr_psargs), SBUF_FIXEDLEN);
2153 error = proc_getargv(curthread, p, &sbarg);
2155 if (sbuf_finish(&sbarg) == 0)
2156 len = sbuf_len(&sbarg) - 1;
2158 len = sizeof(psinfo->pr_psargs) - 1;
2159 sbuf_delete(&sbarg);
2161 if (error || len == 0)
2162 strlcpy(psinfo->pr_psargs, p->p_comm,
2163 sizeof(psinfo->pr_psargs));
2165 KASSERT(len < sizeof(psinfo->pr_psargs),
2166 ("len is too long: %zu vs %zu", len,
2167 sizeof(psinfo->pr_psargs)));
2168 cp = psinfo->pr_psargs;
2171 cp = memchr(cp, '\0', end - cp);
2177 psinfo->pr_pid = p->p_pid;
2178 sbuf_bcat(sb, psinfo, sizeof(*psinfo));
2179 free(psinfo, M_TEMP);
2181 *sizep = sizeof(*psinfo);
2185 __elfN(note_prstatus)(void *arg, struct sbuf *sb, size_t *sizep)
2188 elf_prstatus_t *status;
2190 td = (struct thread *)arg;
2192 KASSERT(*sizep == sizeof(*status), ("invalid size"));
2193 status = malloc(sizeof(*status), M_TEMP, M_ZERO | M_WAITOK);
2194 status->pr_version = PRSTATUS_VERSION;
2195 status->pr_statussz = sizeof(elf_prstatus_t);
2196 status->pr_gregsetsz = sizeof(elf_gregset_t);
2197 status->pr_fpregsetsz = sizeof(elf_fpregset_t);
2198 status->pr_osreldate = osreldate;
2199 status->pr_cursig = td->td_proc->p_sig;
2200 status->pr_pid = td->td_tid;
2201 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
2202 fill_regs32(td, &status->pr_reg);
2204 fill_regs(td, &status->pr_reg);
2206 sbuf_bcat(sb, status, sizeof(*status));
2207 free(status, M_TEMP);
2209 *sizep = sizeof(*status);
2213 __elfN(note_fpregset)(void *arg, struct sbuf *sb, size_t *sizep)
2216 elf_prfpregset_t *fpregset;
2218 td = (struct thread *)arg;
2220 KASSERT(*sizep == sizeof(*fpregset), ("invalid size"));
2221 fpregset = malloc(sizeof(*fpregset), M_TEMP, M_ZERO | M_WAITOK);
2222 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
2223 fill_fpregs32(td, fpregset);
2225 fill_fpregs(td, fpregset);
2227 sbuf_bcat(sb, fpregset, sizeof(*fpregset));
2228 free(fpregset, M_TEMP);
2230 *sizep = sizeof(*fpregset);
2234 __elfN(note_thrmisc)(void *arg, struct sbuf *sb, size_t *sizep)
2237 elf_thrmisc_t thrmisc;
2239 td = (struct thread *)arg;
2241 KASSERT(*sizep == sizeof(thrmisc), ("invalid size"));
2242 bzero(&thrmisc, sizeof(thrmisc));
2243 strcpy(thrmisc.pr_tname, td->td_name);
2244 sbuf_bcat(sb, &thrmisc, sizeof(thrmisc));
2246 *sizep = sizeof(thrmisc);
2250 __elfN(note_ptlwpinfo)(void *arg, struct sbuf *sb, size_t *sizep)
2255 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
2256 struct ptrace_lwpinfo32 pl;
2258 struct ptrace_lwpinfo pl;
2261 td = (struct thread *)arg;
2262 size = sizeof(structsize) + sizeof(pl);
2264 KASSERT(*sizep == size, ("invalid size"));
2265 structsize = sizeof(pl);
2266 sbuf_bcat(sb, &structsize, sizeof(structsize));
2267 bzero(&pl, sizeof(pl));
2268 pl.pl_lwpid = td->td_tid;
2269 pl.pl_event = PL_EVENT_NONE;
2270 pl.pl_sigmask = td->td_sigmask;
2271 pl.pl_siglist = td->td_siglist;
2272 if (td->td_si.si_signo != 0) {
2273 pl.pl_event = PL_EVENT_SIGNAL;
2274 pl.pl_flags |= PL_FLAG_SI;
2275 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
2276 siginfo_to_siginfo32(&td->td_si, &pl.pl_siginfo);
2278 pl.pl_siginfo = td->td_si;
2281 strcpy(pl.pl_tdname, td->td_name);
2282 /* XXX TODO: supply more information in struct ptrace_lwpinfo*/
2283 sbuf_bcat(sb, &pl, sizeof(pl));
2289 * Allow for MD specific notes, as well as any MD
2290 * specific preparations for writing MI notes.
2293 __elfN(note_threadmd)(void *arg, struct sbuf *sb, size_t *sizep)
2299 td = (struct thread *)arg;
2301 if (size != 0 && sb != NULL)
2302 buf = malloc(size, M_TEMP, M_ZERO | M_WAITOK);
2306 __elfN(dump_thread)(td, buf, &size);
2307 KASSERT(sb == NULL || *sizep == size, ("invalid size"));
2308 if (size != 0 && sb != NULL)
2309 sbuf_bcat(sb, buf, size);
2314 #ifdef KINFO_PROC_SIZE
2315 CTASSERT(sizeof(struct kinfo_proc) == KINFO_PROC_SIZE);
2319 __elfN(note_procstat_proc)(void *arg, struct sbuf *sb, size_t *sizep)
2325 p = (struct proc *)arg;
2326 size = sizeof(structsize) + p->p_numthreads *
2327 sizeof(elf_kinfo_proc_t);
2330 KASSERT(*sizep == size, ("invalid size"));
2331 structsize = sizeof(elf_kinfo_proc_t);
2332 sbuf_bcat(sb, &structsize, sizeof(structsize));
2334 kern_proc_out(p, sb, ELF_KERN_PROC_MASK);
2339 #ifdef KINFO_FILE_SIZE
2340 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
2344 note_procstat_files(void *arg, struct sbuf *sb, size_t *sizep)
2347 size_t size, sect_sz, i;
2348 ssize_t start_len, sect_len;
2349 int structsize, filedesc_flags;
2351 if (coredump_pack_fileinfo)
2352 filedesc_flags = KERN_FILEDESC_PACK_KINFO;
2356 p = (struct proc *)arg;
2357 structsize = sizeof(struct kinfo_file);
2360 sb = sbuf_new(NULL, NULL, 128, SBUF_FIXEDLEN);
2361 sbuf_set_drain(sb, sbuf_count_drain, &size);
2362 sbuf_bcat(sb, &structsize, sizeof(structsize));
2364 kern_proc_filedesc_out(p, sb, -1, filedesc_flags);
2369 sbuf_start_section(sb, &start_len);
2371 sbuf_bcat(sb, &structsize, sizeof(structsize));
2373 kern_proc_filedesc_out(p, sb, *sizep - sizeof(structsize),
2376 sect_len = sbuf_end_section(sb, start_len, 0, 0);
2381 KASSERT(sect_sz <= *sizep,
2382 ("kern_proc_filedesc_out did not respect maxlen; "
2383 "requested %zu, got %zu", *sizep - sizeof(structsize),
2384 sect_sz - sizeof(structsize)));
2386 for (i = 0; i < *sizep - sect_sz && sb->s_error == 0; i++)
2391 #ifdef KINFO_VMENTRY_SIZE
2392 CTASSERT(sizeof(struct kinfo_vmentry) == KINFO_VMENTRY_SIZE);
2396 note_procstat_vmmap(void *arg, struct sbuf *sb, size_t *sizep)
2400 int structsize, vmmap_flags;
2402 if (coredump_pack_vmmapinfo)
2403 vmmap_flags = KERN_VMMAP_PACK_KINFO;
2407 p = (struct proc *)arg;
2408 structsize = sizeof(struct kinfo_vmentry);
2411 sb = sbuf_new(NULL, NULL, 128, SBUF_FIXEDLEN);
2412 sbuf_set_drain(sb, sbuf_count_drain, &size);
2413 sbuf_bcat(sb, &structsize, sizeof(structsize));
2415 kern_proc_vmmap_out(p, sb, -1, vmmap_flags);
2420 sbuf_bcat(sb, &structsize, sizeof(structsize));
2422 kern_proc_vmmap_out(p, sb, *sizep - sizeof(structsize),
2428 note_procstat_groups(void *arg, struct sbuf *sb, size_t *sizep)
2434 p = (struct proc *)arg;
2435 size = sizeof(structsize) + p->p_ucred->cr_ngroups * sizeof(gid_t);
2437 KASSERT(*sizep == size, ("invalid size"));
2438 structsize = sizeof(gid_t);
2439 sbuf_bcat(sb, &structsize, sizeof(structsize));
2440 sbuf_bcat(sb, p->p_ucred->cr_groups, p->p_ucred->cr_ngroups *
2447 note_procstat_umask(void *arg, struct sbuf *sb, size_t *sizep)
2453 p = (struct proc *)arg;
2454 size = sizeof(structsize) + sizeof(p->p_fd->fd_cmask);
2456 KASSERT(*sizep == size, ("invalid size"));
2457 structsize = sizeof(p->p_fd->fd_cmask);
2458 sbuf_bcat(sb, &structsize, sizeof(structsize));
2459 sbuf_bcat(sb, &p->p_fd->fd_cmask, sizeof(p->p_fd->fd_cmask));
2465 note_procstat_rlimit(void *arg, struct sbuf *sb, size_t *sizep)
2468 struct rlimit rlim[RLIM_NLIMITS];
2472 p = (struct proc *)arg;
2473 size = sizeof(structsize) + sizeof(rlim);
2475 KASSERT(*sizep == size, ("invalid size"));
2476 structsize = sizeof(rlim);
2477 sbuf_bcat(sb, &structsize, sizeof(structsize));
2479 for (i = 0; i < RLIM_NLIMITS; i++)
2480 lim_rlimit_proc(p, i, &rlim[i]);
2482 sbuf_bcat(sb, rlim, sizeof(rlim));
2488 note_procstat_osrel(void *arg, struct sbuf *sb, size_t *sizep)
2494 p = (struct proc *)arg;
2495 size = sizeof(structsize) + sizeof(p->p_osrel);
2497 KASSERT(*sizep == size, ("invalid size"));
2498 structsize = sizeof(p->p_osrel);
2499 sbuf_bcat(sb, &structsize, sizeof(structsize));
2500 sbuf_bcat(sb, &p->p_osrel, sizeof(p->p_osrel));
2506 __elfN(note_procstat_psstrings)(void *arg, struct sbuf *sb, size_t *sizep)
2509 elf_ps_strings_t ps_strings;
2513 p = (struct proc *)arg;
2514 size = sizeof(structsize) + sizeof(ps_strings);
2516 KASSERT(*sizep == size, ("invalid size"));
2517 structsize = sizeof(ps_strings);
2518 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
2519 ps_strings = PTROUT(p->p_sysent->sv_psstrings);
2521 ps_strings = p->p_sysent->sv_psstrings;
2523 sbuf_bcat(sb, &structsize, sizeof(structsize));
2524 sbuf_bcat(sb, &ps_strings, sizeof(ps_strings));
2530 __elfN(note_procstat_auxv)(void *arg, struct sbuf *sb, size_t *sizep)
2536 p = (struct proc *)arg;
2539 sb = sbuf_new(NULL, NULL, 128, SBUF_FIXEDLEN);
2540 sbuf_set_drain(sb, sbuf_count_drain, &size);
2541 sbuf_bcat(sb, &structsize, sizeof(structsize));
2543 proc_getauxv(curthread, p, sb);
2549 structsize = sizeof(Elf_Auxinfo);
2550 sbuf_bcat(sb, &structsize, sizeof(structsize));
2552 proc_getauxv(curthread, p, sb);
2558 __elfN(parse_notes)(struct image_params *imgp, Elf_Note *checknote,
2559 const char *note_vendor, const Elf_Phdr *pnote,
2560 boolean_t (*cb)(const Elf_Note *, void *, boolean_t *), void *cb_arg)
2562 const Elf_Note *note, *note0, *note_end;
2563 const char *note_name;
2568 /* We need some limit, might as well use PAGE_SIZE. */
2569 if (pnote == NULL || pnote->p_filesz > PAGE_SIZE)
2571 ASSERT_VOP_LOCKED(imgp->vp, "parse_notes");
2572 if (pnote->p_offset > PAGE_SIZE ||
2573 pnote->p_filesz > PAGE_SIZE - pnote->p_offset) {
2574 buf = malloc(pnote->p_filesz, M_TEMP, M_NOWAIT);
2576 VOP_UNLOCK(imgp->vp);
2577 buf = malloc(pnote->p_filesz, M_TEMP, M_WAITOK);
2578 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
2580 error = vn_rdwr(UIO_READ, imgp->vp, buf, pnote->p_filesz,
2581 pnote->p_offset, UIO_SYSSPACE, IO_NODELOCKED,
2582 curthread->td_ucred, NOCRED, NULL, curthread);
2584 uprintf("i/o error PT_NOTE\n");
2587 note = note0 = (const Elf_Note *)buf;
2588 note_end = (const Elf_Note *)(buf + pnote->p_filesz);
2590 note = note0 = (const Elf_Note *)(imgp->image_header +
2592 note_end = (const Elf_Note *)(imgp->image_header +
2593 pnote->p_offset + pnote->p_filesz);
2596 for (i = 0; i < 100 && note >= note0 && note < note_end; i++) {
2597 if (!aligned(note, Elf32_Addr) || (const char *)note_end -
2598 (const char *)note < sizeof(Elf_Note)) {
2601 if (note->n_namesz != checknote->n_namesz ||
2602 note->n_descsz != checknote->n_descsz ||
2603 note->n_type != checknote->n_type)
2605 note_name = (const char *)(note + 1);
2606 if (note_name + checknote->n_namesz >=
2607 (const char *)note_end || strncmp(note_vendor,
2608 note_name, checknote->n_namesz) != 0)
2611 if (cb(note, cb_arg, &res))
2614 note = (const Elf_Note *)((const char *)(note + 1) +
2615 roundup2(note->n_namesz, ELF_NOTE_ROUNDSIZE) +
2616 roundup2(note->n_descsz, ELF_NOTE_ROUNDSIZE));
2625 struct brandnote_cb_arg {
2626 Elf_Brandnote *brandnote;
2631 brandnote_cb(const Elf_Note *note, void *arg0, boolean_t *res)
2633 struct brandnote_cb_arg *arg;
2638 * Fetch the osreldate for binary from the ELF OSABI-note if
2641 *res = (arg->brandnote->flags & BN_TRANSLATE_OSREL) != 0 &&
2642 arg->brandnote->trans_osrel != NULL ?
2643 arg->brandnote->trans_osrel(note, arg->osrel) : TRUE;
2648 static Elf_Note fctl_note = {
2649 .n_namesz = sizeof(FREEBSD_ABI_VENDOR),
2650 .n_descsz = sizeof(uint32_t),
2651 .n_type = NT_FREEBSD_FEATURE_CTL,
2654 struct fctl_cb_arg {
2659 note_fctl_cb(const Elf_Note *note, void *arg0, boolean_t *res)
2661 struct fctl_cb_arg *arg;
2662 const Elf32_Word *desc;
2666 p = (uintptr_t)(note + 1);
2667 p += roundup2(note->n_namesz, ELF_NOTE_ROUNDSIZE);
2668 desc = (const Elf32_Word *)p;
2669 *arg->fctl0 = desc[0];
2674 * Try to find the appropriate ABI-note section for checknote, fetch
2675 * the osreldate and feature control flags for binary from the ELF
2676 * OSABI-note. Only the first page of the image is searched, the same
2680 __elfN(check_note)(struct image_params *imgp, Elf_Brandnote *brandnote,
2681 int32_t *osrel, uint32_t *fctl0)
2683 const Elf_Phdr *phdr;
2684 const Elf_Ehdr *hdr;
2685 struct brandnote_cb_arg b_arg;
2686 struct fctl_cb_arg f_arg;
2689 hdr = (const Elf_Ehdr *)imgp->image_header;
2690 phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
2691 b_arg.brandnote = brandnote;
2692 b_arg.osrel = osrel;
2693 f_arg.fctl0 = fctl0;
2695 for (i = 0; i < hdr->e_phnum; i++) {
2696 if (phdr[i].p_type == PT_NOTE && __elfN(parse_notes)(imgp,
2697 &brandnote->hdr, brandnote->vendor, &phdr[i], brandnote_cb,
2699 for (j = 0; j < hdr->e_phnum; j++) {
2700 if (phdr[j].p_type == PT_NOTE &&
2701 __elfN(parse_notes)(imgp, &fctl_note,
2702 FREEBSD_ABI_VENDOR, &phdr[j],
2703 note_fctl_cb, &f_arg))
2714 * Tell kern_execve.c about it, with a little help from the linker.
2716 static struct execsw __elfN(execsw) = {
2717 .ex_imgact = __CONCAT(exec_, __elfN(imgact)),
2718 .ex_name = __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE))
2720 EXEC_SET(__CONCAT(elf, __ELF_WORD_SIZE), __elfN(execsw));
2723 __elfN(trans_prot)(Elf_Word flags)
2729 prot |= VM_PROT_EXECUTE;
2731 prot |= VM_PROT_WRITE;
2733 prot |= VM_PROT_READ;
2734 #if __ELF_WORD_SIZE == 32 && (defined(__amd64__) || defined(__i386__))
2735 if (i386_read_exec && (flags & PF_R))
2736 prot |= VM_PROT_EXECUTE;
2742 __elfN(untrans_prot)(vm_prot_t prot)
2747 if (prot & VM_PROT_EXECUTE)
2749 if (prot & VM_PROT_READ)
2751 if (prot & VM_PROT_WRITE)
2757 __elfN(stackgap)(struct image_params *imgp, uintptr_t *stack_base)
2759 uintptr_t range, rbase, gap;
2762 if ((imgp->map_flags & MAP_ASLR) == 0)
2764 pct = __elfN(aslr_stack_gap);
2769 range = imgp->eff_stack_sz * pct / 100;
2770 arc4rand(&rbase, sizeof(rbase), 0);
2771 gap = rbase % range;
2772 gap &= ~(sizeof(u_long) - 1);