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, boolean_t *has_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 int __elfN(fallback_brand) = -1;
110 SYSCTL_INT(__CONCAT(_kern_elf, __ELF_WORD_SIZE), OID_AUTO,
111 fallback_brand, CTLFLAG_RWTUN, &__elfN(fallback_brand), 0,
112 __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE)) " brand of last resort");
114 static int elf_legacy_coredump = 0;
115 SYSCTL_INT(_debug, OID_AUTO, __elfN(legacy_coredump), CTLFLAG_RW,
116 &elf_legacy_coredump, 0,
117 "include all and only RW pages in core dumps");
119 int __elfN(nxstack) =
120 #if defined(__amd64__) || defined(__powerpc64__) /* both 64 and 32 bit */ || \
121 (defined(__arm__) && __ARM_ARCH >= 7) || defined(__aarch64__) || \
127 SYSCTL_INT(__CONCAT(_kern_elf, __ELF_WORD_SIZE), OID_AUTO,
128 nxstack, CTLFLAG_RW, &__elfN(nxstack), 0,
129 __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE)) ": enable non-executable stack");
131 #if __ELF_WORD_SIZE == 32 && (defined(__amd64__) || defined(__i386__))
132 int i386_read_exec = 0;
133 SYSCTL_INT(_kern_elf32, OID_AUTO, read_exec, CTLFLAG_RW, &i386_read_exec, 0,
134 "enable execution from readable segments");
137 static u_long __elfN(pie_base) = ET_DYN_LOAD_ADDR;
139 sysctl_pie_base(SYSCTL_HANDLER_ARGS)
144 val = __elfN(pie_base);
145 error = sysctl_handle_long(oidp, &val, 0, req);
146 if (error != 0 || req->newptr == NULL)
148 if ((val & PAGE_MASK) != 0)
150 __elfN(pie_base) = val;
153 SYSCTL_PROC(__CONCAT(_kern_elf, __ELF_WORD_SIZE), OID_AUTO, pie_base,
154 CTLTYPE_ULONG | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0,
155 sysctl_pie_base, "LU",
156 "PIE load base without randomization");
158 SYSCTL_NODE(__CONCAT(_kern_elf, __ELF_WORD_SIZE), OID_AUTO, aslr,
159 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
161 #define ASLR_NODE_OID __CONCAT(__CONCAT(_kern_elf, __ELF_WORD_SIZE), _aslr)
163 static int __elfN(aslr_enabled) = 0;
164 SYSCTL_INT(ASLR_NODE_OID, OID_AUTO, enable, CTLFLAG_RWTUN,
165 &__elfN(aslr_enabled), 0,
166 __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE))
167 ": enable address map randomization");
169 static int __elfN(pie_aslr_enabled) = 0;
170 SYSCTL_INT(ASLR_NODE_OID, OID_AUTO, pie_enable, CTLFLAG_RWTUN,
171 &__elfN(pie_aslr_enabled), 0,
172 __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE))
173 ": enable address map randomization for PIE binaries");
175 static int __elfN(aslr_honor_sbrk) = 1;
176 SYSCTL_INT(ASLR_NODE_OID, OID_AUTO, honor_sbrk, CTLFLAG_RW,
177 &__elfN(aslr_honor_sbrk), 0,
178 __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE)) ": assume sbrk is used");
180 static int __elfN(aslr_stack_gap) = 3;
181 SYSCTL_INT(ASLR_NODE_OID, OID_AUTO, stack_gap, CTLFLAG_RW,
182 &__elfN(aslr_stack_gap), 0,
183 __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE))
184 ": maximum percentage of main stack to waste on a random gap");
186 static int __elfN(sigfastblock) = 1;
187 SYSCTL_INT(__CONCAT(_kern_elf, __ELF_WORD_SIZE), OID_AUTO, sigfastblock,
188 CTLFLAG_RWTUN, &__elfN(sigfastblock), 0,
189 "enable sigfastblock for new processes");
191 static bool __elfN(allow_wx) = true;
192 SYSCTL_BOOL(__CONCAT(_kern_elf, __ELF_WORD_SIZE), OID_AUTO, allow_wx,
193 CTLFLAG_RWTUN, &__elfN(allow_wx), 0,
194 "Allow pages to be mapped simultaneously writable and executable");
196 static Elf_Brandinfo *elf_brand_list[MAX_BRANDS];
198 #define aligned(a, t) (rounddown2((u_long)(a), sizeof(t)) == (u_long)(a))
200 static const char FREEBSD_ABI_VENDOR[] = "FreeBSD";
202 Elf_Brandnote __elfN(freebsd_brandnote) = {
203 .hdr.n_namesz = sizeof(FREEBSD_ABI_VENDOR),
204 .hdr.n_descsz = sizeof(int32_t),
205 .hdr.n_type = NT_FREEBSD_ABI_TAG,
206 .vendor = FREEBSD_ABI_VENDOR,
207 .flags = BN_TRANSLATE_OSREL,
208 .trans_osrel = __elfN(freebsd_trans_osrel)
212 __elfN(freebsd_trans_osrel)(const Elf_Note *note, int32_t *osrel)
216 p = (uintptr_t)(note + 1);
217 p += roundup2(note->n_namesz, ELF_NOTE_ROUNDSIZE);
218 *osrel = *(const int32_t *)(p);
223 static const char GNU_ABI_VENDOR[] = "GNU";
224 static int GNU_KFREEBSD_ABI_DESC = 3;
226 Elf_Brandnote __elfN(kfreebsd_brandnote) = {
227 .hdr.n_namesz = sizeof(GNU_ABI_VENDOR),
228 .hdr.n_descsz = 16, /* XXX at least 16 */
230 .vendor = GNU_ABI_VENDOR,
231 .flags = BN_TRANSLATE_OSREL,
232 .trans_osrel = kfreebsd_trans_osrel
236 kfreebsd_trans_osrel(const Elf_Note *note, int32_t *osrel)
238 const Elf32_Word *desc;
241 p = (uintptr_t)(note + 1);
242 p += roundup2(note->n_namesz, ELF_NOTE_ROUNDSIZE);
244 desc = (const Elf32_Word *)p;
245 if (desc[0] != GNU_KFREEBSD_ABI_DESC)
249 * Debian GNU/kFreeBSD embed the earliest compatible kernel version
250 * (__FreeBSD_version: <major><two digit minor>Rxx) in the LSB way.
252 *osrel = desc[1] * 100000 + desc[2] * 1000 + desc[3];
258 __elfN(insert_brand_entry)(Elf_Brandinfo *entry)
262 for (i = 0; i < MAX_BRANDS; i++) {
263 if (elf_brand_list[i] == NULL) {
264 elf_brand_list[i] = entry;
268 if (i == MAX_BRANDS) {
269 printf("WARNING: %s: could not insert brandinfo entry: %p\n",
277 __elfN(remove_brand_entry)(Elf_Brandinfo *entry)
281 for (i = 0; i < MAX_BRANDS; i++) {
282 if (elf_brand_list[i] == entry) {
283 elf_brand_list[i] = NULL;
293 __elfN(brand_inuse)(Elf_Brandinfo *entry)
298 sx_slock(&allproc_lock);
299 FOREACH_PROC_IN_SYSTEM(p) {
300 if (p->p_sysent == entry->sysvec) {
305 sx_sunlock(&allproc_lock);
310 static Elf_Brandinfo *
311 __elfN(get_brandinfo)(struct image_params *imgp, const char *interp,
312 int32_t *osrel, uint32_t *fctl0)
314 const Elf_Ehdr *hdr = (const Elf_Ehdr *)imgp->image_header;
315 Elf_Brandinfo *bi, *bi_m;
316 boolean_t ret, has_fctl0;
317 int i, interp_name_len;
319 interp_name_len = interp != NULL ? strlen(interp) + 1 : 0;
322 * We support four types of branding -- (1) the ELF EI_OSABI field
323 * that SCO added to the ELF spec, (2) FreeBSD 3.x's traditional string
324 * branding w/in the ELF header, (3) path of the `interp_path'
325 * field, and (4) the ".note.ABI-tag" ELF section.
328 /* Look for an ".note.ABI-tag" ELF section */
330 for (i = 0; i < MAX_BRANDS; i++) {
331 bi = elf_brand_list[i];
334 if (interp != NULL && (bi->flags & BI_BRAND_ONLY_STATIC) != 0)
336 if (hdr->e_machine == bi->machine && (bi->flags &
337 (BI_BRAND_NOTE|BI_BRAND_NOTE_MANDATORY)) != 0) {
341 ret = __elfN(check_note)(imgp, bi->brand_note, osrel,
343 /* Give brand a chance to veto check_note's guess */
344 if (ret && bi->header_supported) {
345 ret = bi->header_supported(imgp, osrel,
346 has_fctl0 ? fctl0 : NULL);
349 * If note checker claimed the binary, but the
350 * interpreter path in the image does not
351 * match default one for the brand, try to
352 * search for other brands with the same
353 * interpreter. Either there is better brand
354 * with the right interpreter, or, failing
355 * this, we return first brand which accepted
356 * our note and, optionally, header.
358 if (ret && bi_m == NULL && interp != NULL &&
359 (bi->interp_path == NULL ||
360 (strlen(bi->interp_path) + 1 != interp_name_len ||
361 strncmp(interp, bi->interp_path, interp_name_len)
373 /* If the executable has a brand, search for it in the brand list. */
374 for (i = 0; i < MAX_BRANDS; i++) {
375 bi = elf_brand_list[i];
376 if (bi == NULL || (bi->flags & BI_BRAND_NOTE_MANDATORY) != 0 ||
377 (interp != NULL && (bi->flags & BI_BRAND_ONLY_STATIC) != 0))
379 if (hdr->e_machine == bi->machine &&
380 (hdr->e_ident[EI_OSABI] == bi->brand ||
381 (bi->compat_3_brand != NULL &&
382 strcmp((const char *)&hdr->e_ident[OLD_EI_BRAND],
383 bi->compat_3_brand) == 0))) {
384 /* Looks good, but give brand a chance to veto */
385 if (bi->header_supported == NULL ||
386 bi->header_supported(imgp, NULL, NULL)) {
388 * Again, prefer strictly matching
391 if (interp_name_len == 0 &&
392 bi->interp_path == NULL)
394 if (bi->interp_path != NULL &&
395 strlen(bi->interp_path) + 1 ==
396 interp_name_len && strncmp(interp,
397 bi->interp_path, interp_name_len) == 0)
407 /* No known brand, see if the header is recognized by any brand */
408 for (i = 0; i < MAX_BRANDS; i++) {
409 bi = elf_brand_list[i];
410 if (bi == NULL || bi->flags & BI_BRAND_NOTE_MANDATORY ||
411 bi->header_supported == NULL)
413 if (hdr->e_machine == bi->machine) {
414 ret = bi->header_supported(imgp, NULL, NULL);
420 /* Lacking a known brand, search for a recognized interpreter. */
421 if (interp != NULL) {
422 for (i = 0; i < MAX_BRANDS; i++) {
423 bi = elf_brand_list[i];
424 if (bi == NULL || (bi->flags &
425 (BI_BRAND_NOTE_MANDATORY | BI_BRAND_ONLY_STATIC))
428 if (hdr->e_machine == bi->machine &&
429 bi->interp_path != NULL &&
430 /* ELF image p_filesz includes terminating zero */
431 strlen(bi->interp_path) + 1 == interp_name_len &&
432 strncmp(interp, bi->interp_path, interp_name_len)
433 == 0 && (bi->header_supported == NULL ||
434 bi->header_supported(imgp, NULL, NULL)))
439 /* Lacking a recognized interpreter, try the default brand */
440 for (i = 0; i < MAX_BRANDS; i++) {
441 bi = elf_brand_list[i];
442 if (bi == NULL || (bi->flags & BI_BRAND_NOTE_MANDATORY) != 0 ||
443 (interp != NULL && (bi->flags & BI_BRAND_ONLY_STATIC) != 0))
445 if (hdr->e_machine == bi->machine &&
446 __elfN(fallback_brand) == bi->brand &&
447 (bi->header_supported == NULL ||
448 bi->header_supported(imgp, NULL, NULL)))
455 __elfN(phdr_in_zero_page)(const Elf_Ehdr *hdr)
457 return (hdr->e_phoff <= PAGE_SIZE &&
458 (u_int)hdr->e_phentsize * hdr->e_phnum <= PAGE_SIZE - hdr->e_phoff);
462 __elfN(check_header)(const Elf_Ehdr *hdr)
468 hdr->e_ident[EI_CLASS] != ELF_TARG_CLASS ||
469 hdr->e_ident[EI_DATA] != ELF_TARG_DATA ||
470 hdr->e_ident[EI_VERSION] != EV_CURRENT ||
471 hdr->e_phentsize != sizeof(Elf_Phdr) ||
472 hdr->e_version != ELF_TARG_VER)
476 * Make sure we have at least one brand for this machine.
479 for (i = 0; i < MAX_BRANDS; i++) {
480 bi = elf_brand_list[i];
481 if (bi != NULL && bi->machine == hdr->e_machine)
491 __elfN(map_partial)(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
492 vm_offset_t start, vm_offset_t end, vm_prot_t prot)
499 * Create the page if it doesn't exist yet. Ignore errors.
501 vm_map_fixed(map, NULL, 0, trunc_page(start), round_page(end) -
502 trunc_page(start), VM_PROT_ALL, VM_PROT_ALL, MAP_CHECK_EXCL);
505 * Find the page from the underlying object.
507 if (object != NULL) {
508 sf = vm_imgact_map_page(object, offset);
510 return (KERN_FAILURE);
511 off = offset - trunc_page(offset);
512 error = copyout((caddr_t)sf_buf_kva(sf) + off, (caddr_t)start,
514 vm_imgact_unmap_page(sf);
516 return (KERN_FAILURE);
519 return (KERN_SUCCESS);
523 __elfN(map_insert)(struct image_params *imgp, vm_map_t map, vm_object_t object,
524 vm_ooffset_t offset, vm_offset_t start, vm_offset_t end, vm_prot_t prot,
530 int error, locked, rv;
532 if (start != trunc_page(start)) {
533 rv = __elfN(map_partial)(map, object, offset, start,
534 round_page(start), prot);
535 if (rv != KERN_SUCCESS)
537 offset += round_page(start) - start;
538 start = round_page(start);
540 if (end != round_page(end)) {
541 rv = __elfN(map_partial)(map, object, offset +
542 trunc_page(end) - start, trunc_page(end), end, prot);
543 if (rv != KERN_SUCCESS)
545 end = trunc_page(end);
548 return (KERN_SUCCESS);
549 if ((offset & PAGE_MASK) != 0) {
551 * The mapping is not page aligned. This means that we have
554 rv = vm_map_fixed(map, NULL, 0, start, end - start,
555 prot | VM_PROT_WRITE, VM_PROT_ALL, MAP_CHECK_EXCL);
556 if (rv != KERN_SUCCESS)
559 return (KERN_SUCCESS);
560 for (; start < end; start += sz) {
561 sf = vm_imgact_map_page(object, offset);
563 return (KERN_FAILURE);
564 off = offset - trunc_page(offset);
566 if (sz > PAGE_SIZE - off)
567 sz = PAGE_SIZE - off;
568 error = copyout((caddr_t)sf_buf_kva(sf) + off,
570 vm_imgact_unmap_page(sf);
572 return (KERN_FAILURE);
576 vm_object_reference(object);
577 rv = vm_map_fixed(map, object, offset, start, end - start,
578 prot, VM_PROT_ALL, cow | MAP_CHECK_EXCL |
579 (object != NULL ? MAP_VN_EXEC : 0));
580 if (rv != KERN_SUCCESS) {
581 locked = VOP_ISLOCKED(imgp->vp);
582 VOP_UNLOCK(imgp->vp);
583 vm_object_deallocate(object);
584 vn_lock(imgp->vp, locked | LK_RETRY);
586 } else if (object != NULL) {
587 MPASS(imgp->vp->v_object == object);
588 VOP_SET_TEXT_CHECKED(imgp->vp);
591 return (KERN_SUCCESS);
595 __elfN(load_section)(struct image_params *imgp, vm_ooffset_t offset,
596 caddr_t vmaddr, size_t memsz, size_t filsz, vm_prot_t prot)
602 vm_offset_t map_addr;
605 vm_ooffset_t file_addr;
608 * It's necessary to fail if the filsz + offset taken from the
609 * header is greater than the actual file pager object's size.
610 * If we were to allow this, then the vm_map_find() below would
611 * walk right off the end of the file object and into the ether.
613 * While I'm here, might as well check for something else that
614 * is invalid: filsz cannot be greater than memsz.
616 if ((filsz != 0 && (off_t)filsz + offset > imgp->attr->va_size) ||
618 uprintf("elf_load_section: truncated ELF file\n");
622 object = imgp->object;
623 map = &imgp->proc->p_vmspace->vm_map;
624 map_addr = trunc_page((vm_offset_t)vmaddr);
625 file_addr = trunc_page(offset);
628 * We have two choices. We can either clear the data in the last page
629 * of an oversized mapping, or we can start the anon mapping a page
630 * early and copy the initialized data into that first page. We
635 else if (memsz > filsz)
636 map_len = trunc_page(offset + filsz) - file_addr;
638 map_len = round_page(offset + filsz) - file_addr;
641 /* cow flags: don't dump readonly sections in core */
642 cow = MAP_COPY_ON_WRITE | MAP_PREFAULT |
643 (prot & VM_PROT_WRITE ? 0 : MAP_DISABLE_COREDUMP);
645 rv = __elfN(map_insert)(imgp, map, object, file_addr,
646 map_addr, map_addr + map_len, prot, cow);
647 if (rv != KERN_SUCCESS)
650 /* we can stop now if we've covered it all */
656 * We have to get the remaining bit of the file into the first part
657 * of the oversized map segment. This is normally because the .data
658 * segment in the file is extended to provide bss. It's a neat idea
659 * to try and save a page, but it's a pain in the behind to implement.
661 copy_len = filsz == 0 ? 0 : (offset + filsz) - trunc_page(offset +
663 map_addr = trunc_page((vm_offset_t)vmaddr + filsz);
664 map_len = round_page((vm_offset_t)vmaddr + memsz) - map_addr;
666 /* This had damn well better be true! */
668 rv = __elfN(map_insert)(imgp, map, NULL, 0, map_addr,
669 map_addr + map_len, prot, 0);
670 if (rv != KERN_SUCCESS)
675 sf = vm_imgact_map_page(object, offset + filsz);
679 /* send the page fragment to user space */
680 error = copyout((caddr_t)sf_buf_kva(sf), (caddr_t)map_addr,
682 vm_imgact_unmap_page(sf);
688 * Remove write access to the page if it was only granted by map_insert
691 if ((prot & VM_PROT_WRITE) == 0)
692 vm_map_protect(map, trunc_page(map_addr), round_page(map_addr +
693 map_len), prot, 0, VM_MAP_PROTECT_SET_PROT);
699 __elfN(load_sections)(struct image_params *imgp, const Elf_Ehdr *hdr,
700 const Elf_Phdr *phdr, u_long rbase, u_long *base_addrp)
707 ASSERT_VOP_LOCKED(imgp->vp, __func__);
712 for (i = 0; i < hdr->e_phnum; i++) {
713 if (phdr[i].p_type != PT_LOAD || phdr[i].p_memsz == 0)
716 /* Loadable segment */
717 prot = __elfN(trans_prot)(phdr[i].p_flags);
718 error = __elfN(load_section)(imgp, phdr[i].p_offset,
719 (caddr_t)(uintptr_t)phdr[i].p_vaddr + rbase,
720 phdr[i].p_memsz, phdr[i].p_filesz, prot);
725 * Establish the base address if this is the first segment.
728 base_addr = trunc_page(phdr[i].p_vaddr + rbase);
733 if (base_addrp != NULL)
734 *base_addrp = base_addr;
740 * Load the file "file" into memory. It may be either a shared object
743 * The "addr" reference parameter is in/out. On entry, it specifies
744 * the address where a shared object should be loaded. If the file is
745 * an executable, this value is ignored. On exit, "addr" specifies
746 * where the file was actually loaded.
748 * The "entry" reference parameter is out only. On exit, it specifies
749 * the entry point for the loaded file.
752 __elfN(load_file)(struct proc *p, const char *file, u_long *addr,
758 struct image_params image_params;
760 const Elf_Ehdr *hdr = NULL;
761 const Elf_Phdr *phdr = NULL;
762 struct nameidata *nd;
764 struct image_params *imgp;
766 u_long base_addr = 0;
769 #ifdef CAPABILITY_MODE
771 * XXXJA: This check can go away once we are sufficiently confident
772 * that the checks in namei() are correct.
774 if (IN_CAPABILITY_MODE(curthread))
778 tempdata = malloc(sizeof(*tempdata), M_TEMP, M_WAITOK | M_ZERO);
780 attr = &tempdata->attr;
781 imgp = &tempdata->image_params;
784 * Initialize part of the common data
789 NDINIT(nd, LOOKUP, ISOPEN | FOLLOW | LOCKSHARED | LOCKLEAF,
790 UIO_SYSSPACE, file, curthread);
791 if ((error = namei(nd)) != 0) {
795 NDFREE(nd, NDF_ONLY_PNBUF);
796 imgp->vp = nd->ni_vp;
799 * Check permissions, modes, uid, etc on the file, and "open" it.
801 error = exec_check_permissions(imgp);
805 error = exec_map_first_page(imgp);
809 imgp->object = nd->ni_vp->v_object;
811 hdr = (const Elf_Ehdr *)imgp->image_header;
812 if ((error = __elfN(check_header)(hdr)) != 0)
814 if (hdr->e_type == ET_DYN)
816 else if (hdr->e_type == ET_EXEC)
823 /* Only support headers that fit within first page for now */
824 if (!__elfN(phdr_in_zero_page)(hdr)) {
829 phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
830 if (!aligned(phdr, Elf_Addr)) {
835 error = __elfN(load_sections)(imgp, hdr, phdr, rbase, &base_addr);
840 *entry = (unsigned long)hdr->e_entry + rbase;
844 exec_unmap_first_page(imgp);
848 VOP_UNSET_TEXT_CHECKED(nd->ni_vp);
851 free(tempdata, M_TEMP);
857 __CONCAT(rnd_, __elfN(base))(vm_map_t map __unused, u_long minv, u_long maxv,
862 MPASS(vm_map_min(map) <= minv);
863 MPASS(maxv <= vm_map_max(map));
865 MPASS(minv + align < maxv);
866 arc4rand(&rbase, sizeof(rbase), 0);
867 res = roundup(minv, (u_long)align) + rbase % (maxv - minv);
868 res &= ~((u_long)align - 1);
872 ("res %#lx < minv %#lx, maxv %#lx rbase %#lx",
873 res, minv, maxv, rbase));
875 ("res %#lx > maxv %#lx, minv %#lx rbase %#lx",
876 res, maxv, minv, rbase));
881 __elfN(enforce_limits)(struct image_params *imgp, const Elf_Ehdr *hdr,
882 const Elf_Phdr *phdr, u_long et_dyn_addr)
884 struct vmspace *vmspace;
886 u_long text_size, data_size, total_size, text_addr, data_addr;
887 u_long seg_size, seg_addr;
891 text_size = data_size = total_size = text_addr = data_addr = 0;
893 for (i = 0; i < hdr->e_phnum; i++) {
894 if (phdr[i].p_type != PT_LOAD || phdr[i].p_memsz == 0)
897 seg_addr = trunc_page(phdr[i].p_vaddr + et_dyn_addr);
898 seg_size = round_page(phdr[i].p_memsz +
899 phdr[i].p_vaddr + et_dyn_addr - seg_addr);
902 * Make the largest executable segment the official
903 * text segment and all others data.
905 * Note that obreak() assumes that data_addr + data_size == end
906 * of data load area, and the ELF file format expects segments
907 * to be sorted by address. If multiple data segments exist,
908 * the last one will be used.
911 if ((phdr[i].p_flags & PF_X) != 0 && text_size < seg_size) {
912 text_size = seg_size;
913 text_addr = seg_addr;
915 data_size = seg_size;
916 data_addr = seg_addr;
918 total_size += seg_size;
921 if (data_addr == 0 && data_size == 0) {
922 data_addr = text_addr;
923 data_size = text_size;
927 * Check limits. It should be safe to check the
928 * limits after loading the segments since we do
929 * not actually fault in all the segments pages.
931 PROC_LOCK(imgp->proc);
932 if (data_size > lim_cur_proc(imgp->proc, RLIMIT_DATA))
933 err_str = "Data segment size exceeds process limit";
934 else if (text_size > maxtsiz)
935 err_str = "Text segment size exceeds system limit";
936 else if (total_size > lim_cur_proc(imgp->proc, RLIMIT_VMEM))
937 err_str = "Total segment size exceeds process limit";
938 else if (racct_set(imgp->proc, RACCT_DATA, data_size) != 0)
939 err_str = "Data segment size exceeds resource limit";
940 else if (racct_set(imgp->proc, RACCT_VMEM, total_size) != 0)
941 err_str = "Total segment size exceeds resource limit";
942 PROC_UNLOCK(imgp->proc);
943 if (err_str != NULL) {
944 uprintf("%s\n", err_str);
948 vmspace = imgp->proc->p_vmspace;
949 vmspace->vm_tsize = text_size >> PAGE_SHIFT;
950 vmspace->vm_taddr = (caddr_t)(uintptr_t)text_addr;
951 vmspace->vm_dsize = data_size >> PAGE_SHIFT;
952 vmspace->vm_daddr = (caddr_t)(uintptr_t)data_addr;
958 __elfN(get_interp)(struct image_params *imgp, const Elf_Phdr *phdr,
959 char **interpp, bool *free_interpp)
963 int error, interp_name_len;
965 KASSERT(phdr->p_type == PT_INTERP,
966 ("%s: p_type %u != PT_INTERP", __func__, phdr->p_type));
967 ASSERT_VOP_LOCKED(imgp->vp, __func__);
971 /* Path to interpreter */
972 if (phdr->p_filesz < 2 || phdr->p_filesz > MAXPATHLEN) {
973 uprintf("Invalid PT_INTERP\n");
977 interp_name_len = phdr->p_filesz;
978 if (phdr->p_offset > PAGE_SIZE ||
979 interp_name_len > PAGE_SIZE - phdr->p_offset) {
981 * The vnode lock might be needed by the pagedaemon to
982 * clean pages owned by the vnode. Do not allow sleep
983 * waiting for memory with the vnode locked, instead
984 * try non-sleepable allocation first, and if it
985 * fails, go to the slow path were we drop the lock
986 * and do M_WAITOK. A text reference prevents
987 * modifications to the vnode content.
989 interp = malloc(interp_name_len + 1, M_TEMP, M_NOWAIT);
990 if (interp == NULL) {
991 VOP_UNLOCK(imgp->vp);
992 interp = malloc(interp_name_len + 1, M_TEMP, M_WAITOK);
993 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
996 error = vn_rdwr(UIO_READ, imgp->vp, interp,
997 interp_name_len, phdr->p_offset,
998 UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred,
1001 free(interp, M_TEMP);
1002 uprintf("i/o error PT_INTERP %d\n", error);
1005 interp[interp_name_len] = '\0';
1008 *free_interpp = true;
1012 interp = __DECONST(char *, imgp->image_header) + phdr->p_offset;
1013 if (interp[interp_name_len - 1] != '\0') {
1014 uprintf("Invalid PT_INTERP\n");
1019 *free_interpp = false;
1024 __elfN(load_interp)(struct image_params *imgp, const Elf_Brandinfo *brand_info,
1025 const char *interp, u_long *addr, u_long *entry)
1030 if (brand_info->emul_path != NULL &&
1031 brand_info->emul_path[0] != '\0') {
1032 path = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1033 snprintf(path, MAXPATHLEN, "%s%s",
1034 brand_info->emul_path, interp);
1035 error = __elfN(load_file)(imgp->proc, path, addr, entry);
1041 if (brand_info->interp_newpath != NULL &&
1042 (brand_info->interp_path == NULL ||
1043 strcmp(interp, brand_info->interp_path) == 0)) {
1044 error = __elfN(load_file)(imgp->proc,
1045 brand_info->interp_newpath, addr, entry);
1050 error = __elfN(load_file)(imgp->proc, interp, addr, entry);
1054 uprintf("ELF interpreter %s not found, error %d\n", interp, error);
1059 * Impossible et_dyn_addr initial value indicating that the real base
1060 * must be calculated later with some randomization applied.
1062 #define ET_DYN_ADDR_RAND 1
1065 __CONCAT(exec_, __elfN(imgact))(struct image_params *imgp)
1068 const Elf_Ehdr *hdr;
1069 const Elf_Phdr *phdr;
1070 Elf_Auxargs *elf_auxargs;
1071 struct vmspace *vmspace;
1074 Elf_Brandinfo *brand_info;
1075 struct sysentvec *sv;
1076 u_long addr, baddr, et_dyn_addr, entry, proghdr;
1077 u_long maxalign, mapsz, maxv, maxv1;
1083 hdr = (const Elf_Ehdr *)imgp->image_header;
1086 * Do we have a valid ELF header ?
1088 * Only allow ET_EXEC & ET_DYN here, reject ET_DYN later
1089 * if particular brand doesn't support it.
1091 if (__elfN(check_header)(hdr) != 0 ||
1092 (hdr->e_type != ET_EXEC && hdr->e_type != ET_DYN))
1096 * From here on down, we return an errno, not -1, as we've
1097 * detected an ELF file.
1100 if (!__elfN(phdr_in_zero_page)(hdr)) {
1101 uprintf("Program headers not in the first page\n");
1104 phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
1105 if (!aligned(phdr, Elf_Addr)) {
1106 uprintf("Unaligned program headers\n");
1114 entry = proghdr = 0;
1116 free_interp = false;
1118 maxalign = PAGE_SIZE;
1121 for (i = 0; i < hdr->e_phnum; i++) {
1122 switch (phdr[i].p_type) {
1125 baddr = phdr[i].p_vaddr;
1126 if (phdr[i].p_align > maxalign)
1127 maxalign = phdr[i].p_align;
1128 mapsz += phdr[i].p_memsz;
1132 * If this segment contains the program headers,
1133 * remember their virtual address for the AT_PHDR
1134 * aux entry. Static binaries don't usually include
1137 if (phdr[i].p_offset == 0 &&
1138 hdr->e_phoff + hdr->e_phnum * hdr->e_phentsize
1139 <= phdr[i].p_filesz)
1140 proghdr = phdr[i].p_vaddr + hdr->e_phoff;
1143 /* Path to interpreter */
1144 if (interp != NULL) {
1145 uprintf("Multiple PT_INTERP headers\n");
1149 error = __elfN(get_interp)(imgp, &phdr[i], &interp,
1155 if (__elfN(nxstack))
1157 __elfN(trans_prot)(phdr[i].p_flags);
1158 imgp->stack_sz = phdr[i].p_memsz;
1160 case PT_PHDR: /* Program header table info */
1161 proghdr = phdr[i].p_vaddr;
1166 brand_info = __elfN(get_brandinfo)(imgp, interp, &osrel, &fctl0);
1167 if (brand_info == NULL) {
1168 uprintf("ELF binary type \"%u\" not known.\n",
1169 hdr->e_ident[EI_OSABI]);
1173 sv = brand_info->sysvec;
1175 if (hdr->e_type == ET_DYN) {
1176 if ((brand_info->flags & BI_CAN_EXEC_DYN) == 0) {
1177 uprintf("Cannot execute shared object\n");
1182 * Honour the base load address from the dso if it is
1183 * non-zero for some reason.
1186 if ((sv->sv_flags & SV_ASLR) == 0 ||
1187 (fctl0 & NT_FREEBSD_FCTL_ASLR_DISABLE) != 0)
1188 et_dyn_addr = __elfN(pie_base);
1189 else if ((__elfN(pie_aslr_enabled) &&
1190 (imgp->proc->p_flag2 & P2_ASLR_DISABLE) == 0) ||
1191 (imgp->proc->p_flag2 & P2_ASLR_ENABLE) != 0)
1192 et_dyn_addr = ET_DYN_ADDR_RAND;
1194 et_dyn_addr = __elfN(pie_base);
1199 * Avoid a possible deadlock if the current address space is destroyed
1200 * and that address space maps the locked vnode. In the common case,
1201 * the locked vnode's v_usecount is decremented but remains greater
1202 * than zero. Consequently, the vnode lock is not needed by vrele().
1203 * However, in cases where the vnode lock is external, such as nullfs,
1204 * v_usecount may become zero.
1206 * The VV_TEXT flag prevents modifications to the executable while
1207 * the vnode is unlocked.
1209 VOP_UNLOCK(imgp->vp);
1212 * Decide whether to enable randomization of user mappings.
1213 * First, reset user preferences for the setid binaries.
1214 * Then, account for the support of the randomization by the
1215 * ABI, by user preferences, and make special treatment for
1218 if (imgp->credential_setid) {
1219 PROC_LOCK(imgp->proc);
1220 imgp->proc->p_flag2 &= ~(P2_ASLR_ENABLE | P2_ASLR_DISABLE);
1221 PROC_UNLOCK(imgp->proc);
1223 if ((sv->sv_flags & SV_ASLR) == 0 ||
1224 (imgp->proc->p_flag2 & P2_ASLR_DISABLE) != 0 ||
1225 (fctl0 & NT_FREEBSD_FCTL_ASLR_DISABLE) != 0) {
1226 KASSERT(et_dyn_addr != ET_DYN_ADDR_RAND,
1227 ("et_dyn_addr == RAND and !ASLR"));
1228 } else if ((imgp->proc->p_flag2 & P2_ASLR_ENABLE) != 0 ||
1229 (__elfN(aslr_enabled) && hdr->e_type == ET_EXEC) ||
1230 et_dyn_addr == ET_DYN_ADDR_RAND) {
1231 imgp->map_flags |= MAP_ASLR;
1233 * If user does not care about sbrk, utilize the bss
1234 * grow region for mappings as well. We can select
1235 * the base for the image anywere and still not suffer
1236 * from the fragmentation.
1238 if (!__elfN(aslr_honor_sbrk) ||
1239 (imgp->proc->p_flag2 & P2_ASLR_IGNSTART) != 0)
1240 imgp->map_flags |= MAP_ASLR_IGNSTART;
1243 if (!__elfN(allow_wx) && (fctl0 & NT_FREEBSD_FCTL_WXNEEDED) == 0)
1244 imgp->map_flags |= MAP_WXORX;
1246 error = exec_new_vmspace(imgp, sv);
1247 vmspace = imgp->proc->p_vmspace;
1248 map = &vmspace->vm_map;
1250 imgp->proc->p_sysent = sv;
1252 maxv = vm_map_max(map) - lim_max(td, RLIMIT_STACK);
1253 if (et_dyn_addr == ET_DYN_ADDR_RAND) {
1254 KASSERT((map->flags & MAP_ASLR) != 0,
1255 ("ET_DYN_ADDR_RAND but !MAP_ASLR"));
1256 et_dyn_addr = __CONCAT(rnd_, __elfN(base))(map,
1257 vm_map_min(map) + mapsz + lim_max(td, RLIMIT_DATA),
1258 /* reserve half of the address space to interpreter */
1259 maxv / 2, 1UL << flsl(maxalign));
1262 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
1266 error = __elfN(load_sections)(imgp, hdr, phdr, et_dyn_addr, NULL);
1270 error = __elfN(enforce_limits)(imgp, hdr, phdr, et_dyn_addr);
1274 entry = (u_long)hdr->e_entry + et_dyn_addr;
1277 * We load the dynamic linker where a userland call
1278 * to mmap(0, ...) would put it. The rationale behind this
1279 * calculation is that it leaves room for the heap to grow to
1280 * its maximum allowed size.
1282 addr = round_page((vm_offset_t)vmspace->vm_daddr + lim_max(td,
1284 if ((map->flags & MAP_ASLR) != 0) {
1285 maxv1 = maxv / 2 + addr / 2;
1286 MPASS(maxv1 >= addr); /* No overflow */
1287 map->anon_loc = __CONCAT(rnd_, __elfN(base))(map, addr, maxv1,
1288 (MAXPAGESIZES > 1 && pagesizes[1] != 0) ?
1289 pagesizes[1] : pagesizes[0]);
1291 map->anon_loc = addr;
1294 imgp->entry_addr = entry;
1296 if (interp != NULL) {
1297 VOP_UNLOCK(imgp->vp);
1298 if ((map->flags & MAP_ASLR) != 0) {
1299 /* Assume that interpreter fits into 1/4 of AS */
1300 maxv1 = maxv / 2 + addr / 2;
1301 MPASS(maxv1 >= addr); /* No overflow */
1302 addr = __CONCAT(rnd_, __elfN(base))(map, addr,
1305 error = __elfN(load_interp)(imgp, brand_info, interp, &addr,
1307 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
1314 * Construct auxargs table (used by the copyout_auxargs routine)
1316 elf_auxargs = malloc(sizeof(Elf_Auxargs), M_TEMP, M_NOWAIT);
1317 if (elf_auxargs == NULL) {
1318 VOP_UNLOCK(imgp->vp);
1319 elf_auxargs = malloc(sizeof(Elf_Auxargs), M_TEMP, M_WAITOK);
1320 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
1322 elf_auxargs->execfd = -1;
1323 elf_auxargs->phdr = proghdr + et_dyn_addr;
1324 elf_auxargs->phent = hdr->e_phentsize;
1325 elf_auxargs->phnum = hdr->e_phnum;
1326 elf_auxargs->pagesz = PAGE_SIZE;
1327 elf_auxargs->base = addr;
1328 elf_auxargs->flags = 0;
1329 elf_auxargs->entry = entry;
1330 elf_auxargs->hdr_eflags = hdr->e_flags;
1332 imgp->auxargs = elf_auxargs;
1333 imgp->interpreted = 0;
1334 imgp->reloc_base = addr;
1335 imgp->proc->p_osrel = osrel;
1336 imgp->proc->p_fctl0 = fctl0;
1337 imgp->proc->p_elf_machine = hdr->e_machine;
1338 imgp->proc->p_elf_flags = hdr->e_flags;
1342 free(interp, M_TEMP);
1346 #define suword __CONCAT(suword, __ELF_WORD_SIZE)
1349 __elfN(freebsd_copyout_auxargs)(struct image_params *imgp, uintptr_t base)
1351 Elf_Auxargs *args = (Elf_Auxargs *)imgp->auxargs;
1352 Elf_Auxinfo *argarray, *pos;
1355 argarray = pos = malloc(AT_COUNT * sizeof(*pos), M_TEMP,
1358 if (args->execfd != -1)
1359 AUXARGS_ENTRY(pos, AT_EXECFD, args->execfd);
1360 AUXARGS_ENTRY(pos, AT_PHDR, args->phdr);
1361 AUXARGS_ENTRY(pos, AT_PHENT, args->phent);
1362 AUXARGS_ENTRY(pos, AT_PHNUM, args->phnum);
1363 AUXARGS_ENTRY(pos, AT_PAGESZ, args->pagesz);
1364 AUXARGS_ENTRY(pos, AT_FLAGS, args->flags);
1365 AUXARGS_ENTRY(pos, AT_ENTRY, args->entry);
1366 AUXARGS_ENTRY(pos, AT_BASE, args->base);
1367 AUXARGS_ENTRY(pos, AT_EHDRFLAGS, args->hdr_eflags);
1368 if (imgp->execpathp != 0)
1369 AUXARGS_ENTRY_PTR(pos, AT_EXECPATH, imgp->execpathp);
1370 AUXARGS_ENTRY(pos, AT_OSRELDATE,
1371 imgp->proc->p_ucred->cr_prison->pr_osreldate);
1372 if (imgp->canary != 0) {
1373 AUXARGS_ENTRY_PTR(pos, AT_CANARY, imgp->canary);
1374 AUXARGS_ENTRY(pos, AT_CANARYLEN, imgp->canarylen);
1376 AUXARGS_ENTRY(pos, AT_NCPUS, mp_ncpus);
1377 if (imgp->pagesizes != 0) {
1378 AUXARGS_ENTRY_PTR(pos, AT_PAGESIZES, imgp->pagesizes);
1379 AUXARGS_ENTRY(pos, AT_PAGESIZESLEN, imgp->pagesizeslen);
1381 if (imgp->sysent->sv_timekeep_base != 0) {
1382 AUXARGS_ENTRY(pos, AT_TIMEKEEP,
1383 imgp->sysent->sv_timekeep_base);
1385 AUXARGS_ENTRY(pos, AT_STACKPROT, imgp->sysent->sv_shared_page_obj
1386 != NULL && imgp->stack_prot != 0 ? imgp->stack_prot :
1387 imgp->sysent->sv_stackprot);
1388 if (imgp->sysent->sv_hwcap != NULL)
1389 AUXARGS_ENTRY(pos, AT_HWCAP, *imgp->sysent->sv_hwcap);
1390 if (imgp->sysent->sv_hwcap2 != NULL)
1391 AUXARGS_ENTRY(pos, AT_HWCAP2, *imgp->sysent->sv_hwcap2);
1392 AUXARGS_ENTRY(pos, AT_BSDFLAGS, __elfN(sigfastblock) ?
1393 ELF_BSDF_SIGFASTBLK : 0);
1394 AUXARGS_ENTRY(pos, AT_ARGC, imgp->args->argc);
1395 AUXARGS_ENTRY_PTR(pos, AT_ARGV, imgp->argv);
1396 AUXARGS_ENTRY(pos, AT_ENVC, imgp->args->envc);
1397 AUXARGS_ENTRY_PTR(pos, AT_ENVV, imgp->envv);
1398 AUXARGS_ENTRY_PTR(pos, AT_PS_STRINGS, imgp->ps_strings);
1399 if (imgp->sysent->sv_fxrng_gen_base != 0)
1400 AUXARGS_ENTRY(pos, AT_FXRNG, imgp->sysent->sv_fxrng_gen_base);
1401 AUXARGS_ENTRY(pos, AT_NULL, 0);
1403 free(imgp->auxargs, M_TEMP);
1404 imgp->auxargs = NULL;
1405 KASSERT(pos - argarray <= AT_COUNT, ("Too many auxargs"));
1407 error = copyout(argarray, (void *)base, sizeof(*argarray) * AT_COUNT);
1408 free(argarray, M_TEMP);
1413 __elfN(freebsd_fixup)(uintptr_t *stack_base, struct image_params *imgp)
1417 base = (Elf_Addr *)*stack_base;
1419 if (suword(base, imgp->args->argc) == -1)
1421 *stack_base = (uintptr_t)base;
1426 * Code for generating ELF core dumps.
1429 typedef void (*segment_callback)(vm_map_entry_t, void *);
1431 /* Closure for cb_put_phdr(). */
1432 struct phdr_closure {
1433 Elf_Phdr *phdr; /* Program header to fill in */
1434 Elf_Off offset; /* Offset of segment in core file */
1437 typedef void (*outfunc_t)(void *, struct sbuf *, size_t *);
1440 int type; /* Note type. */
1441 outfunc_t outfunc; /* Output function. */
1442 void *outarg; /* Argument for the output function. */
1443 size_t outsize; /* Output size. */
1444 TAILQ_ENTRY(note_info) link; /* Link to the next note info. */
1447 TAILQ_HEAD(note_info_list, note_info);
1449 extern int compress_user_cores;
1450 extern int compress_user_cores_level;
1452 static void cb_put_phdr(vm_map_entry_t, void *);
1453 static void cb_size_segment(vm_map_entry_t, void *);
1454 static void each_dumpable_segment(struct thread *, segment_callback, void *,
1456 static int __elfN(corehdr)(struct coredump_params *, int, void *, size_t,
1457 struct note_info_list *, size_t, int);
1458 static void __elfN(prepare_notes)(struct thread *, struct note_info_list *,
1460 static void __elfN(putnote)(struct note_info *, struct sbuf *);
1461 static size_t register_note(struct note_info_list *, int, outfunc_t, void *);
1463 static void __elfN(note_fpregset)(void *, struct sbuf *, size_t *);
1464 static void __elfN(note_prpsinfo)(void *, struct sbuf *, size_t *);
1465 static void __elfN(note_prstatus)(void *, struct sbuf *, size_t *);
1466 static void __elfN(note_threadmd)(void *, struct sbuf *, size_t *);
1467 static void __elfN(note_thrmisc)(void *, struct sbuf *, size_t *);
1468 static void __elfN(note_ptlwpinfo)(void *, struct sbuf *, size_t *);
1469 static void __elfN(note_procstat_auxv)(void *, struct sbuf *, size_t *);
1470 static void __elfN(note_procstat_proc)(void *, struct sbuf *, size_t *);
1471 static void __elfN(note_procstat_psstrings)(void *, struct sbuf *, size_t *);
1472 static void note_procstat_files(void *, struct sbuf *, size_t *);
1473 static void note_procstat_groups(void *, struct sbuf *, size_t *);
1474 static void note_procstat_osrel(void *, struct sbuf *, size_t *);
1475 static void note_procstat_rlimit(void *, struct sbuf *, size_t *);
1476 static void note_procstat_umask(void *, struct sbuf *, size_t *);
1477 static void note_procstat_vmmap(void *, struct sbuf *, size_t *);
1480 core_compressed_write(void *base, size_t len, off_t offset, void *arg)
1483 return (core_write((struct coredump_params *)arg, base, len, offset,
1484 UIO_SYSSPACE, NULL));
1488 __elfN(coredump)(struct thread *td, struct vnode *vp, off_t limit, int flags)
1490 struct ucred *cred = td->td_ucred;
1491 int compm, error = 0;
1492 struct sseg_closure seginfo;
1493 struct note_info_list notelst;
1494 struct coredump_params params;
1495 struct note_info *ninfo;
1497 size_t hdrsize, notesz, coresize;
1501 TAILQ_INIT(¬elst);
1503 /* Size the program segments. */
1504 __elfN(size_segments)(td, &seginfo, flags);
1507 * Collect info about the core file header area.
1509 hdrsize = sizeof(Elf_Ehdr) + sizeof(Elf_Phdr) * (1 + seginfo.count);
1510 if (seginfo.count + 1 >= PN_XNUM)
1511 hdrsize += sizeof(Elf_Shdr);
1512 __elfN(prepare_notes)(td, ¬elst, ¬esz);
1513 coresize = round_page(hdrsize + notesz) + seginfo.size;
1515 /* Set up core dump parameters. */
1517 params.active_cred = cred;
1518 params.file_cred = NOCRED;
1525 PROC_LOCK(td->td_proc);
1526 error = racct_add(td->td_proc, RACCT_CORE, coresize);
1527 PROC_UNLOCK(td->td_proc);
1534 if (coresize >= limit) {
1539 /* Create a compression stream if necessary. */
1540 compm = compress_user_cores;
1541 if ((flags & (SVC_PT_COREDUMP | SVC_NOCOMPRESS)) == SVC_PT_COREDUMP &&
1543 compm = COMPRESS_GZIP;
1545 params.comp = compressor_init(core_compressed_write,
1546 compm, CORE_BUF_SIZE,
1547 compress_user_cores_level, ¶ms);
1548 if (params.comp == NULL) {
1552 tmpbuf = malloc(CORE_BUF_SIZE, M_TEMP, M_WAITOK | M_ZERO);
1556 * Allocate memory for building the header, fill it up,
1557 * and write it out following the notes.
1559 hdr = malloc(hdrsize, M_TEMP, M_WAITOK);
1560 error = __elfN(corehdr)(¶ms, seginfo.count, hdr, hdrsize, ¬elst,
1563 /* Write the contents of all of the writable segments. */
1569 php = (Elf_Phdr *)((char *)hdr + sizeof(Elf_Ehdr)) + 1;
1570 offset = round_page(hdrsize + notesz);
1571 for (i = 0; i < seginfo.count; i++) {
1572 error = core_output((char *)(uintptr_t)php->p_vaddr,
1573 php->p_filesz, offset, ¶ms, tmpbuf);
1576 offset += php->p_filesz;
1579 if (error == 0 && params.comp != NULL)
1580 error = compressor_flush(params.comp);
1584 "Failed to write core file for process %s (error %d)\n",
1585 curproc->p_comm, error);
1589 free(tmpbuf, M_TEMP);
1590 if (params.comp != NULL)
1591 compressor_fini(params.comp);
1592 while ((ninfo = TAILQ_FIRST(¬elst)) != NULL) {
1593 TAILQ_REMOVE(¬elst, ninfo, link);
1594 free(ninfo, M_TEMP);
1603 * A callback for each_dumpable_segment() to write out the segment's
1604 * program header entry.
1607 cb_put_phdr(vm_map_entry_t entry, void *closure)
1609 struct phdr_closure *phc = (struct phdr_closure *)closure;
1610 Elf_Phdr *phdr = phc->phdr;
1612 phc->offset = round_page(phc->offset);
1614 phdr->p_type = PT_LOAD;
1615 phdr->p_offset = phc->offset;
1616 phdr->p_vaddr = entry->start;
1618 phdr->p_filesz = phdr->p_memsz = entry->end - entry->start;
1619 phdr->p_align = PAGE_SIZE;
1620 phdr->p_flags = __elfN(untrans_prot)(entry->protection);
1622 phc->offset += phdr->p_filesz;
1627 * A callback for each_dumpable_segment() to gather information about
1628 * the number of segments and their total size.
1631 cb_size_segment(vm_map_entry_t entry, void *closure)
1633 struct sseg_closure *ssc = (struct sseg_closure *)closure;
1636 ssc->size += entry->end - entry->start;
1640 __elfN(size_segments)(struct thread *td, struct sseg_closure *seginfo,
1646 each_dumpable_segment(td, cb_size_segment, seginfo, flags);
1650 * For each writable segment in the process's memory map, call the given
1651 * function with a pointer to the map entry and some arbitrary
1652 * caller-supplied data.
1655 each_dumpable_segment(struct thread *td, segment_callback func, void *closure,
1658 struct proc *p = td->td_proc;
1659 vm_map_t map = &p->p_vmspace->vm_map;
1660 vm_map_entry_t entry;
1661 vm_object_t backing_object, object;
1664 vm_map_lock_read(map);
1665 VM_MAP_ENTRY_FOREACH(entry, map) {
1667 * Don't dump inaccessible mappings, deal with legacy
1670 * Note that read-only segments related to the elf binary
1671 * are marked MAP_ENTRY_NOCOREDUMP now so we no longer
1672 * need to arbitrarily ignore such segments.
1674 if ((flags & SVC_ALL) == 0) {
1675 if (elf_legacy_coredump) {
1676 if ((entry->protection & VM_PROT_RW) !=
1680 if ((entry->protection & VM_PROT_ALL) == 0)
1686 * Dont include memory segment in the coredump if
1687 * MAP_NOCORE is set in mmap(2) or MADV_NOCORE in
1688 * madvise(2). Do not dump submaps (i.e. parts of the
1691 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
1693 if ((entry->eflags & MAP_ENTRY_NOCOREDUMP) != 0 &&
1694 (flags & SVC_ALL) == 0)
1696 if ((object = entry->object.vm_object) == NULL)
1699 /* Ignore memory-mapped devices and such things. */
1700 VM_OBJECT_RLOCK(object);
1701 while ((backing_object = object->backing_object) != NULL) {
1702 VM_OBJECT_RLOCK(backing_object);
1703 VM_OBJECT_RUNLOCK(object);
1704 object = backing_object;
1706 ignore_entry = (object->flags & OBJ_FICTITIOUS) != 0;
1707 VM_OBJECT_RUNLOCK(object);
1711 (*func)(entry, closure);
1713 vm_map_unlock_read(map);
1717 * Write the core file header to the file, including padding up to
1718 * the page boundary.
1721 __elfN(corehdr)(struct coredump_params *p, int numsegs, void *hdr,
1722 size_t hdrsize, struct note_info_list *notelst, size_t notesz,
1725 struct note_info *ninfo;
1729 /* Fill in the header. */
1730 bzero(hdr, hdrsize);
1731 __elfN(puthdr)(p->td, hdr, hdrsize, numsegs, notesz, flags);
1733 sb = sbuf_new(NULL, NULL, CORE_BUF_SIZE, SBUF_FIXEDLEN);
1734 sbuf_set_drain(sb, sbuf_drain_core_output, p);
1735 sbuf_start_section(sb, NULL);
1736 sbuf_bcat(sb, hdr, hdrsize);
1737 TAILQ_FOREACH(ninfo, notelst, link)
1738 __elfN(putnote)(ninfo, sb);
1739 /* Align up to a page boundary for the program segments. */
1740 sbuf_end_section(sb, -1, PAGE_SIZE, 0);
1741 error = sbuf_finish(sb);
1748 __elfN(prepare_notes)(struct thread *td, struct note_info_list *list,
1758 size += register_note(list, NT_PRPSINFO, __elfN(note_prpsinfo), p);
1761 * To have the debugger select the right thread (LWP) as the initial
1762 * thread, we dump the state of the thread passed to us in td first.
1763 * This is the thread that causes the core dump and thus likely to
1764 * be the right thread one wants to have selected in the debugger.
1767 while (thr != NULL) {
1768 size += register_note(list, NT_PRSTATUS,
1769 __elfN(note_prstatus), thr);
1770 size += register_note(list, NT_FPREGSET,
1771 __elfN(note_fpregset), thr);
1772 size += register_note(list, NT_THRMISC,
1773 __elfN(note_thrmisc), thr);
1774 size += register_note(list, NT_PTLWPINFO,
1775 __elfN(note_ptlwpinfo), thr);
1776 size += register_note(list, -1,
1777 __elfN(note_threadmd), thr);
1779 thr = (thr == td) ? TAILQ_FIRST(&p->p_threads) :
1780 TAILQ_NEXT(thr, td_plist);
1782 thr = TAILQ_NEXT(thr, td_plist);
1785 size += register_note(list, NT_PROCSTAT_PROC,
1786 __elfN(note_procstat_proc), p);
1787 size += register_note(list, NT_PROCSTAT_FILES,
1788 note_procstat_files, p);
1789 size += register_note(list, NT_PROCSTAT_VMMAP,
1790 note_procstat_vmmap, p);
1791 size += register_note(list, NT_PROCSTAT_GROUPS,
1792 note_procstat_groups, p);
1793 size += register_note(list, NT_PROCSTAT_UMASK,
1794 note_procstat_umask, p);
1795 size += register_note(list, NT_PROCSTAT_RLIMIT,
1796 note_procstat_rlimit, p);
1797 size += register_note(list, NT_PROCSTAT_OSREL,
1798 note_procstat_osrel, p);
1799 size += register_note(list, NT_PROCSTAT_PSSTRINGS,
1800 __elfN(note_procstat_psstrings), p);
1801 size += register_note(list, NT_PROCSTAT_AUXV,
1802 __elfN(note_procstat_auxv), p);
1808 __elfN(puthdr)(struct thread *td, void *hdr, size_t hdrsize, int numsegs,
1809 size_t notesz, int flags)
1814 struct phdr_closure phc;
1816 ehdr = (Elf_Ehdr *)hdr;
1818 ehdr->e_ident[EI_MAG0] = ELFMAG0;
1819 ehdr->e_ident[EI_MAG1] = ELFMAG1;
1820 ehdr->e_ident[EI_MAG2] = ELFMAG2;
1821 ehdr->e_ident[EI_MAG3] = ELFMAG3;
1822 ehdr->e_ident[EI_CLASS] = ELF_CLASS;
1823 ehdr->e_ident[EI_DATA] = ELF_DATA;
1824 ehdr->e_ident[EI_VERSION] = EV_CURRENT;
1825 ehdr->e_ident[EI_OSABI] = ELFOSABI_FREEBSD;
1826 ehdr->e_ident[EI_ABIVERSION] = 0;
1827 ehdr->e_ident[EI_PAD] = 0;
1828 ehdr->e_type = ET_CORE;
1829 ehdr->e_machine = td->td_proc->p_elf_machine;
1830 ehdr->e_version = EV_CURRENT;
1832 ehdr->e_phoff = sizeof(Elf_Ehdr);
1833 ehdr->e_flags = td->td_proc->p_elf_flags;
1834 ehdr->e_ehsize = sizeof(Elf_Ehdr);
1835 ehdr->e_phentsize = sizeof(Elf_Phdr);
1836 ehdr->e_shentsize = sizeof(Elf_Shdr);
1837 ehdr->e_shstrndx = SHN_UNDEF;
1838 if (numsegs + 1 < PN_XNUM) {
1839 ehdr->e_phnum = numsegs + 1;
1842 ehdr->e_phnum = PN_XNUM;
1845 ehdr->e_shoff = ehdr->e_phoff +
1846 (numsegs + 1) * ehdr->e_phentsize;
1847 KASSERT(ehdr->e_shoff == hdrsize - sizeof(Elf_Shdr),
1848 ("e_shoff: %zu, hdrsize - shdr: %zu",
1849 (size_t)ehdr->e_shoff, hdrsize - sizeof(Elf_Shdr)));
1851 shdr = (Elf_Shdr *)((char *)hdr + ehdr->e_shoff);
1852 memset(shdr, 0, sizeof(*shdr));
1854 * A special first section is used to hold large segment and
1855 * section counts. This was proposed by Sun Microsystems in
1856 * Solaris and has been adopted by Linux; the standard ELF
1857 * tools are already familiar with the technique.
1859 * See table 7-7 of the Solaris "Linker and Libraries Guide"
1860 * (or 12-7 depending on the version of the document) for more
1863 shdr->sh_type = SHT_NULL;
1864 shdr->sh_size = ehdr->e_shnum;
1865 shdr->sh_link = ehdr->e_shstrndx;
1866 shdr->sh_info = numsegs + 1;
1870 * Fill in the program header entries.
1872 phdr = (Elf_Phdr *)((char *)hdr + ehdr->e_phoff);
1874 /* The note segement. */
1875 phdr->p_type = PT_NOTE;
1876 phdr->p_offset = hdrsize;
1879 phdr->p_filesz = notesz;
1881 phdr->p_flags = PF_R;
1882 phdr->p_align = ELF_NOTE_ROUNDSIZE;
1885 /* All the writable segments from the program. */
1887 phc.offset = round_page(hdrsize + notesz);
1888 each_dumpable_segment(td, cb_put_phdr, &phc, flags);
1892 register_note(struct note_info_list *list, int type, outfunc_t out, void *arg)
1894 struct note_info *ninfo;
1895 size_t size, notesize;
1898 out(arg, NULL, &size);
1899 ninfo = malloc(sizeof(*ninfo), M_TEMP, M_ZERO | M_WAITOK);
1901 ninfo->outfunc = out;
1902 ninfo->outarg = arg;
1903 ninfo->outsize = size;
1904 TAILQ_INSERT_TAIL(list, ninfo, link);
1909 notesize = sizeof(Elf_Note) + /* note header */
1910 roundup2(sizeof(FREEBSD_ABI_VENDOR), ELF_NOTE_ROUNDSIZE) +
1912 roundup2(size, ELF_NOTE_ROUNDSIZE); /* note description */
1918 append_note_data(const void *src, void *dst, size_t len)
1922 padded_len = roundup2(len, ELF_NOTE_ROUNDSIZE);
1924 bcopy(src, dst, len);
1925 bzero((char *)dst + len, padded_len - len);
1927 return (padded_len);
1931 __elfN(populate_note)(int type, void *src, void *dst, size_t size, void **descp)
1939 note = (Elf_Note *)buf;
1940 note->n_namesz = sizeof(FREEBSD_ABI_VENDOR);
1941 note->n_descsz = size;
1942 note->n_type = type;
1943 buf += sizeof(*note);
1944 buf += append_note_data(FREEBSD_ABI_VENDOR, buf,
1945 sizeof(FREEBSD_ABI_VENDOR));
1946 append_note_data(src, buf, size);
1951 notesize = sizeof(Elf_Note) + /* note header */
1952 roundup2(sizeof(FREEBSD_ABI_VENDOR), ELF_NOTE_ROUNDSIZE) +
1954 roundup2(size, ELF_NOTE_ROUNDSIZE); /* note description */
1960 __elfN(putnote)(struct note_info *ninfo, struct sbuf *sb)
1963 ssize_t old_len, sect_len;
1964 size_t new_len, descsz, i;
1966 if (ninfo->type == -1) {
1967 ninfo->outfunc(ninfo->outarg, sb, &ninfo->outsize);
1971 note.n_namesz = sizeof(FREEBSD_ABI_VENDOR);
1972 note.n_descsz = ninfo->outsize;
1973 note.n_type = ninfo->type;
1975 sbuf_bcat(sb, ¬e, sizeof(note));
1976 sbuf_start_section(sb, &old_len);
1977 sbuf_bcat(sb, FREEBSD_ABI_VENDOR, sizeof(FREEBSD_ABI_VENDOR));
1978 sbuf_end_section(sb, old_len, ELF_NOTE_ROUNDSIZE, 0);
1979 if (note.n_descsz == 0)
1981 sbuf_start_section(sb, &old_len);
1982 ninfo->outfunc(ninfo->outarg, sb, &ninfo->outsize);
1983 sect_len = sbuf_end_section(sb, old_len, ELF_NOTE_ROUNDSIZE, 0);
1987 new_len = (size_t)sect_len;
1988 descsz = roundup(note.n_descsz, ELF_NOTE_ROUNDSIZE);
1989 if (new_len < descsz) {
1991 * It is expected that individual note emitters will correctly
1992 * predict their expected output size and fill up to that size
1993 * themselves, padding in a format-specific way if needed.
1994 * However, in case they don't, just do it here with zeros.
1996 for (i = 0; i < descsz - new_len; i++)
1998 } else if (new_len > descsz) {
2000 * We can't always truncate sb -- we may have drained some
2003 KASSERT(new_len == descsz, ("%s: Note type %u changed as we "
2004 "read it (%zu > %zu). Since it is longer than "
2005 "expected, this coredump's notes are corrupt. THIS "
2006 "IS A BUG in the note_procstat routine for type %u.\n",
2007 __func__, (unsigned)note.n_type, new_len, descsz,
2008 (unsigned)note.n_type));
2013 * Miscellaneous note out functions.
2016 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
2017 #include <compat/freebsd32/freebsd32.h>
2018 #include <compat/freebsd32/freebsd32_signal.h>
2020 typedef struct prstatus32 elf_prstatus_t;
2021 typedef struct prpsinfo32 elf_prpsinfo_t;
2022 typedef struct fpreg32 elf_prfpregset_t;
2023 typedef struct fpreg32 elf_fpregset_t;
2024 typedef struct reg32 elf_gregset_t;
2025 typedef struct thrmisc32 elf_thrmisc_t;
2026 #define ELF_KERN_PROC_MASK KERN_PROC_MASK32
2027 typedef struct kinfo_proc32 elf_kinfo_proc_t;
2028 typedef uint32_t elf_ps_strings_t;
2030 typedef prstatus_t elf_prstatus_t;
2031 typedef prpsinfo_t elf_prpsinfo_t;
2032 typedef prfpregset_t elf_prfpregset_t;
2033 typedef prfpregset_t elf_fpregset_t;
2034 typedef gregset_t elf_gregset_t;
2035 typedef thrmisc_t elf_thrmisc_t;
2036 #define ELF_KERN_PROC_MASK 0
2037 typedef struct kinfo_proc elf_kinfo_proc_t;
2038 typedef vm_offset_t elf_ps_strings_t;
2042 __elfN(note_prpsinfo)(void *arg, struct sbuf *sb, size_t *sizep)
2048 elf_prpsinfo_t *psinfo;
2051 p = (struct proc *)arg;
2053 KASSERT(*sizep == sizeof(*psinfo), ("invalid size"));
2054 psinfo = malloc(sizeof(*psinfo), M_TEMP, M_ZERO | M_WAITOK);
2055 psinfo->pr_version = PRPSINFO_VERSION;
2056 psinfo->pr_psinfosz = sizeof(elf_prpsinfo_t);
2057 strlcpy(psinfo->pr_fname, p->p_comm, sizeof(psinfo->pr_fname));
2059 if (p->p_args != NULL) {
2060 len = sizeof(psinfo->pr_psargs) - 1;
2061 if (len > p->p_args->ar_length)
2062 len = p->p_args->ar_length;
2063 memcpy(psinfo->pr_psargs, p->p_args->ar_args, len);
2069 sbuf_new(&sbarg, psinfo->pr_psargs,
2070 sizeof(psinfo->pr_psargs), SBUF_FIXEDLEN);
2071 error = proc_getargv(curthread, p, &sbarg);
2073 if (sbuf_finish(&sbarg) == 0)
2074 len = sbuf_len(&sbarg) - 1;
2076 len = sizeof(psinfo->pr_psargs) - 1;
2077 sbuf_delete(&sbarg);
2079 if (error || len == 0)
2080 strlcpy(psinfo->pr_psargs, p->p_comm,
2081 sizeof(psinfo->pr_psargs));
2083 KASSERT(len < sizeof(psinfo->pr_psargs),
2084 ("len is too long: %zu vs %zu", len,
2085 sizeof(psinfo->pr_psargs)));
2086 cp = psinfo->pr_psargs;
2089 cp = memchr(cp, '\0', end - cp);
2095 psinfo->pr_pid = p->p_pid;
2096 sbuf_bcat(sb, psinfo, sizeof(*psinfo));
2097 free(psinfo, M_TEMP);
2099 *sizep = sizeof(*psinfo);
2103 __elfN(note_prstatus)(void *arg, struct sbuf *sb, size_t *sizep)
2106 elf_prstatus_t *status;
2108 td = (struct thread *)arg;
2110 KASSERT(*sizep == sizeof(*status), ("invalid size"));
2111 status = malloc(sizeof(*status), M_TEMP, M_ZERO | M_WAITOK);
2112 status->pr_version = PRSTATUS_VERSION;
2113 status->pr_statussz = sizeof(elf_prstatus_t);
2114 status->pr_gregsetsz = sizeof(elf_gregset_t);
2115 status->pr_fpregsetsz = sizeof(elf_fpregset_t);
2116 status->pr_osreldate = osreldate;
2117 status->pr_cursig = td->td_proc->p_sig;
2118 status->pr_pid = td->td_tid;
2119 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
2120 fill_regs32(td, &status->pr_reg);
2122 fill_regs(td, &status->pr_reg);
2124 sbuf_bcat(sb, status, sizeof(*status));
2125 free(status, M_TEMP);
2127 *sizep = sizeof(*status);
2131 __elfN(note_fpregset)(void *arg, struct sbuf *sb, size_t *sizep)
2134 elf_prfpregset_t *fpregset;
2136 td = (struct thread *)arg;
2138 KASSERT(*sizep == sizeof(*fpregset), ("invalid size"));
2139 fpregset = malloc(sizeof(*fpregset), M_TEMP, M_ZERO | M_WAITOK);
2140 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
2141 fill_fpregs32(td, fpregset);
2143 fill_fpregs(td, fpregset);
2145 sbuf_bcat(sb, fpregset, sizeof(*fpregset));
2146 free(fpregset, M_TEMP);
2148 *sizep = sizeof(*fpregset);
2152 __elfN(note_thrmisc)(void *arg, struct sbuf *sb, size_t *sizep)
2155 elf_thrmisc_t thrmisc;
2157 td = (struct thread *)arg;
2159 KASSERT(*sizep == sizeof(thrmisc), ("invalid size"));
2160 bzero(&thrmisc, sizeof(thrmisc));
2161 strcpy(thrmisc.pr_tname, td->td_name);
2162 sbuf_bcat(sb, &thrmisc, sizeof(thrmisc));
2164 *sizep = sizeof(thrmisc);
2168 __elfN(note_ptlwpinfo)(void *arg, struct sbuf *sb, size_t *sizep)
2173 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
2174 struct ptrace_lwpinfo32 pl;
2176 struct ptrace_lwpinfo pl;
2179 td = (struct thread *)arg;
2180 size = sizeof(structsize) + sizeof(pl);
2182 KASSERT(*sizep == size, ("invalid size"));
2183 structsize = sizeof(pl);
2184 sbuf_bcat(sb, &structsize, sizeof(structsize));
2185 bzero(&pl, sizeof(pl));
2186 pl.pl_lwpid = td->td_tid;
2187 pl.pl_event = PL_EVENT_NONE;
2188 pl.pl_sigmask = td->td_sigmask;
2189 pl.pl_siglist = td->td_siglist;
2190 if (td->td_si.si_signo != 0) {
2191 pl.pl_event = PL_EVENT_SIGNAL;
2192 pl.pl_flags |= PL_FLAG_SI;
2193 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
2194 siginfo_to_siginfo32(&td->td_si, &pl.pl_siginfo);
2196 pl.pl_siginfo = td->td_si;
2199 strcpy(pl.pl_tdname, td->td_name);
2200 /* XXX TODO: supply more information in struct ptrace_lwpinfo*/
2201 sbuf_bcat(sb, &pl, sizeof(pl));
2207 * Allow for MD specific notes, as well as any MD
2208 * specific preparations for writing MI notes.
2211 __elfN(note_threadmd)(void *arg, struct sbuf *sb, size_t *sizep)
2217 td = (struct thread *)arg;
2219 if (size != 0 && sb != NULL)
2220 buf = malloc(size, M_TEMP, M_ZERO | M_WAITOK);
2224 __elfN(dump_thread)(td, buf, &size);
2225 KASSERT(sb == NULL || *sizep == size, ("invalid size"));
2226 if (size != 0 && sb != NULL)
2227 sbuf_bcat(sb, buf, size);
2232 #ifdef KINFO_PROC_SIZE
2233 CTASSERT(sizeof(struct kinfo_proc) == KINFO_PROC_SIZE);
2237 __elfN(note_procstat_proc)(void *arg, struct sbuf *sb, size_t *sizep)
2243 p = (struct proc *)arg;
2244 size = sizeof(structsize) + p->p_numthreads *
2245 sizeof(elf_kinfo_proc_t);
2248 KASSERT(*sizep == size, ("invalid size"));
2249 structsize = sizeof(elf_kinfo_proc_t);
2250 sbuf_bcat(sb, &structsize, sizeof(structsize));
2251 sx_slock(&proctree_lock);
2253 kern_proc_out(p, sb, ELF_KERN_PROC_MASK);
2254 sx_sunlock(&proctree_lock);
2259 #ifdef KINFO_FILE_SIZE
2260 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
2264 note_procstat_files(void *arg, struct sbuf *sb, size_t *sizep)
2267 size_t size, sect_sz, i;
2268 ssize_t start_len, sect_len;
2269 int structsize, filedesc_flags;
2271 if (coredump_pack_fileinfo)
2272 filedesc_flags = KERN_FILEDESC_PACK_KINFO;
2276 p = (struct proc *)arg;
2277 structsize = sizeof(struct kinfo_file);
2280 sb = sbuf_new(NULL, NULL, 128, SBUF_FIXEDLEN);
2281 sbuf_set_drain(sb, sbuf_count_drain, &size);
2282 sbuf_bcat(sb, &structsize, sizeof(structsize));
2284 kern_proc_filedesc_out(p, sb, -1, filedesc_flags);
2289 sbuf_start_section(sb, &start_len);
2291 sbuf_bcat(sb, &structsize, sizeof(structsize));
2293 kern_proc_filedesc_out(p, sb, *sizep - sizeof(structsize),
2296 sect_len = sbuf_end_section(sb, start_len, 0, 0);
2301 KASSERT(sect_sz <= *sizep,
2302 ("kern_proc_filedesc_out did not respect maxlen; "
2303 "requested %zu, got %zu", *sizep - sizeof(structsize),
2304 sect_sz - sizeof(structsize)));
2306 for (i = 0; i < *sizep - sect_sz && sb->s_error == 0; i++)
2311 #ifdef KINFO_VMENTRY_SIZE
2312 CTASSERT(sizeof(struct kinfo_vmentry) == KINFO_VMENTRY_SIZE);
2316 note_procstat_vmmap(void *arg, struct sbuf *sb, size_t *sizep)
2320 int structsize, vmmap_flags;
2322 if (coredump_pack_vmmapinfo)
2323 vmmap_flags = KERN_VMMAP_PACK_KINFO;
2327 p = (struct proc *)arg;
2328 structsize = sizeof(struct kinfo_vmentry);
2331 sb = sbuf_new(NULL, NULL, 128, SBUF_FIXEDLEN);
2332 sbuf_set_drain(sb, sbuf_count_drain, &size);
2333 sbuf_bcat(sb, &structsize, sizeof(structsize));
2335 kern_proc_vmmap_out(p, sb, -1, vmmap_flags);
2340 sbuf_bcat(sb, &structsize, sizeof(structsize));
2342 kern_proc_vmmap_out(p, sb, *sizep - sizeof(structsize),
2348 note_procstat_groups(void *arg, struct sbuf *sb, size_t *sizep)
2354 p = (struct proc *)arg;
2355 size = sizeof(structsize) + p->p_ucred->cr_ngroups * sizeof(gid_t);
2357 KASSERT(*sizep == size, ("invalid size"));
2358 structsize = sizeof(gid_t);
2359 sbuf_bcat(sb, &structsize, sizeof(structsize));
2360 sbuf_bcat(sb, p->p_ucred->cr_groups, p->p_ucred->cr_ngroups *
2367 note_procstat_umask(void *arg, struct sbuf *sb, size_t *sizep)
2373 p = (struct proc *)arg;
2374 size = sizeof(structsize) + sizeof(p->p_pd->pd_cmask);
2376 KASSERT(*sizep == size, ("invalid size"));
2377 structsize = sizeof(p->p_pd->pd_cmask);
2378 sbuf_bcat(sb, &structsize, sizeof(structsize));
2379 sbuf_bcat(sb, &p->p_pd->pd_cmask, sizeof(p->p_pd->pd_cmask));
2385 note_procstat_rlimit(void *arg, struct sbuf *sb, size_t *sizep)
2388 struct rlimit rlim[RLIM_NLIMITS];
2392 p = (struct proc *)arg;
2393 size = sizeof(structsize) + sizeof(rlim);
2395 KASSERT(*sizep == size, ("invalid size"));
2396 structsize = sizeof(rlim);
2397 sbuf_bcat(sb, &structsize, sizeof(structsize));
2399 for (i = 0; i < RLIM_NLIMITS; i++)
2400 lim_rlimit_proc(p, i, &rlim[i]);
2402 sbuf_bcat(sb, rlim, sizeof(rlim));
2408 note_procstat_osrel(void *arg, struct sbuf *sb, size_t *sizep)
2414 p = (struct proc *)arg;
2415 size = sizeof(structsize) + sizeof(p->p_osrel);
2417 KASSERT(*sizep == size, ("invalid size"));
2418 structsize = sizeof(p->p_osrel);
2419 sbuf_bcat(sb, &structsize, sizeof(structsize));
2420 sbuf_bcat(sb, &p->p_osrel, sizeof(p->p_osrel));
2426 __elfN(note_procstat_psstrings)(void *arg, struct sbuf *sb, size_t *sizep)
2429 elf_ps_strings_t ps_strings;
2433 p = (struct proc *)arg;
2434 size = sizeof(structsize) + sizeof(ps_strings);
2436 KASSERT(*sizep == size, ("invalid size"));
2437 structsize = sizeof(ps_strings);
2438 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
2439 ps_strings = PTROUT(p->p_sysent->sv_psstrings);
2441 ps_strings = p->p_sysent->sv_psstrings;
2443 sbuf_bcat(sb, &structsize, sizeof(structsize));
2444 sbuf_bcat(sb, &ps_strings, sizeof(ps_strings));
2450 __elfN(note_procstat_auxv)(void *arg, struct sbuf *sb, size_t *sizep)
2456 p = (struct proc *)arg;
2459 sb = sbuf_new(NULL, NULL, AT_COUNT * sizeof(Elf_Auxinfo),
2461 sbuf_set_drain(sb, sbuf_count_drain, &size);
2462 sbuf_bcat(sb, &structsize, sizeof(structsize));
2464 proc_getauxv(curthread, p, sb);
2470 structsize = sizeof(Elf_Auxinfo);
2471 sbuf_bcat(sb, &structsize, sizeof(structsize));
2473 proc_getauxv(curthread, p, sb);
2479 __elfN(parse_notes)(struct image_params *imgp, Elf_Note *checknote,
2480 const char *note_vendor, const Elf_Phdr *pnote,
2481 boolean_t (*cb)(const Elf_Note *, void *, boolean_t *), void *cb_arg)
2483 const Elf_Note *note, *note0, *note_end;
2484 const char *note_name;
2489 /* We need some limit, might as well use PAGE_SIZE. */
2490 if (pnote == NULL || pnote->p_filesz > PAGE_SIZE)
2492 ASSERT_VOP_LOCKED(imgp->vp, "parse_notes");
2493 if (pnote->p_offset > PAGE_SIZE ||
2494 pnote->p_filesz > PAGE_SIZE - pnote->p_offset) {
2495 buf = malloc(pnote->p_filesz, M_TEMP, M_NOWAIT);
2497 VOP_UNLOCK(imgp->vp);
2498 buf = malloc(pnote->p_filesz, M_TEMP, M_WAITOK);
2499 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
2501 error = vn_rdwr(UIO_READ, imgp->vp, buf, pnote->p_filesz,
2502 pnote->p_offset, UIO_SYSSPACE, IO_NODELOCKED,
2503 curthread->td_ucred, NOCRED, NULL, curthread);
2505 uprintf("i/o error PT_NOTE\n");
2508 note = note0 = (const Elf_Note *)buf;
2509 note_end = (const Elf_Note *)(buf + pnote->p_filesz);
2511 note = note0 = (const Elf_Note *)(imgp->image_header +
2513 note_end = (const Elf_Note *)(imgp->image_header +
2514 pnote->p_offset + pnote->p_filesz);
2517 for (i = 0; i < 100 && note >= note0 && note < note_end; i++) {
2518 if (!aligned(note, Elf32_Addr) || (const char *)note_end -
2519 (const char *)note < sizeof(Elf_Note)) {
2522 if (note->n_namesz != checknote->n_namesz ||
2523 note->n_descsz != checknote->n_descsz ||
2524 note->n_type != checknote->n_type)
2526 note_name = (const char *)(note + 1);
2527 if (note_name + checknote->n_namesz >=
2528 (const char *)note_end || strncmp(note_vendor,
2529 note_name, checknote->n_namesz) != 0)
2532 if (cb(note, cb_arg, &res))
2535 note = (const Elf_Note *)((const char *)(note + 1) +
2536 roundup2(note->n_namesz, ELF_NOTE_ROUNDSIZE) +
2537 roundup2(note->n_descsz, ELF_NOTE_ROUNDSIZE));
2546 struct brandnote_cb_arg {
2547 Elf_Brandnote *brandnote;
2552 brandnote_cb(const Elf_Note *note, void *arg0, boolean_t *res)
2554 struct brandnote_cb_arg *arg;
2559 * Fetch the osreldate for binary from the ELF OSABI-note if
2562 *res = (arg->brandnote->flags & BN_TRANSLATE_OSREL) != 0 &&
2563 arg->brandnote->trans_osrel != NULL ?
2564 arg->brandnote->trans_osrel(note, arg->osrel) : TRUE;
2569 static Elf_Note fctl_note = {
2570 .n_namesz = sizeof(FREEBSD_ABI_VENDOR),
2571 .n_descsz = sizeof(uint32_t),
2572 .n_type = NT_FREEBSD_FEATURE_CTL,
2575 struct fctl_cb_arg {
2576 boolean_t *has_fctl0;
2581 note_fctl_cb(const Elf_Note *note, void *arg0, boolean_t *res)
2583 struct fctl_cb_arg *arg;
2584 const Elf32_Word *desc;
2588 p = (uintptr_t)(note + 1);
2589 p += roundup2(note->n_namesz, ELF_NOTE_ROUNDSIZE);
2590 desc = (const Elf32_Word *)p;
2591 *arg->has_fctl0 = TRUE;
2592 *arg->fctl0 = desc[0];
2598 * Try to find the appropriate ABI-note section for checknote, fetch
2599 * the osreldate and feature control flags for binary from the ELF
2600 * OSABI-note. Only the first page of the image is searched, the same
2604 __elfN(check_note)(struct image_params *imgp, Elf_Brandnote *brandnote,
2605 int32_t *osrel, boolean_t *has_fctl0, uint32_t *fctl0)
2607 const Elf_Phdr *phdr;
2608 const Elf_Ehdr *hdr;
2609 struct brandnote_cb_arg b_arg;
2610 struct fctl_cb_arg f_arg;
2613 hdr = (const Elf_Ehdr *)imgp->image_header;
2614 phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
2615 b_arg.brandnote = brandnote;
2616 b_arg.osrel = osrel;
2617 f_arg.has_fctl0 = has_fctl0;
2618 f_arg.fctl0 = fctl0;
2620 for (i = 0; i < hdr->e_phnum; i++) {
2621 if (phdr[i].p_type == PT_NOTE && __elfN(parse_notes)(imgp,
2622 &brandnote->hdr, brandnote->vendor, &phdr[i], brandnote_cb,
2624 for (j = 0; j < hdr->e_phnum; j++) {
2625 if (phdr[j].p_type == PT_NOTE &&
2626 __elfN(parse_notes)(imgp, &fctl_note,
2627 FREEBSD_ABI_VENDOR, &phdr[j],
2628 note_fctl_cb, &f_arg))
2639 * Tell kern_execve.c about it, with a little help from the linker.
2641 static struct execsw __elfN(execsw) = {
2642 .ex_imgact = __CONCAT(exec_, __elfN(imgact)),
2643 .ex_name = __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE))
2645 EXEC_SET(__CONCAT(elf, __ELF_WORD_SIZE), __elfN(execsw));
2648 __elfN(trans_prot)(Elf_Word flags)
2654 prot |= VM_PROT_EXECUTE;
2656 prot |= VM_PROT_WRITE;
2658 prot |= VM_PROT_READ;
2659 #if __ELF_WORD_SIZE == 32 && (defined(__amd64__) || defined(__i386__))
2660 if (i386_read_exec && (flags & PF_R))
2661 prot |= VM_PROT_EXECUTE;
2667 __elfN(untrans_prot)(vm_prot_t prot)
2672 if (prot & VM_PROT_EXECUTE)
2674 if (prot & VM_PROT_READ)
2676 if (prot & VM_PROT_WRITE)
2682 __elfN(stackgap)(struct image_params *imgp, uintptr_t *stack_base)
2684 uintptr_t range, rbase, gap;
2687 pct = __elfN(aslr_stack_gap);
2692 range = imgp->eff_stack_sz * pct / 100;
2693 arc4rand(&rbase, sizeof(rbase), 0);
2694 gap = rbase % range;
2695 gap &= ~(sizeof(u_long) - 1);