2 * Copyright (c) 2000 David O'Brien
3 * Copyright (c) 1995-1996 Søren Schmidt
4 * Copyright (c) 1996 Peter Wemm
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer
12 * in this position and unchanged.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. The name of the author may not be used to endorse or promote products
17 * derived from this software without specific prior written permission
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
34 #include "opt_capsicum.h"
35 #include "opt_compat.h"
38 #include <sys/param.h>
39 #include <sys/capsicum.h>
41 #include <sys/fcntl.h>
42 #include <sys/imgact.h>
43 #include <sys/imgact_elf.h>
45 #include <sys/kernel.h>
47 #include <sys/malloc.h>
48 #include <sys/mount.h>
50 #include <sys/namei.h>
51 #include <sys/pioctl.h>
53 #include <sys/procfs.h>
54 #include <sys/racct.h>
55 #include <sys/resourcevar.h>
56 #include <sys/rwlock.h>
58 #include <sys/sf_buf.h>
60 #include <sys/systm.h>
61 #include <sys/signalvar.h>
64 #include <sys/syscall.h>
65 #include <sys/sysctl.h>
66 #include <sys/sysent.h>
67 #include <sys/vnode.h>
68 #include <sys/syslog.h>
69 #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, int interp_name_len, int32_t *osrel);
91 static int __elfN(load_file)(struct proc *p, const char *file, u_long *addr,
92 u_long *entry, size_t pagesize);
93 static int __elfN(load_section)(struct image_params *imgp, vm_offset_t offset,
94 caddr_t vmaddr, size_t memsz, size_t filsz, vm_prot_t prot,
96 static int __CONCAT(exec_, __elfN(imgact))(struct image_params *imgp);
97 static boolean_t __elfN(freebsd_trans_osrel)(const Elf_Note *note,
99 static boolean_t kfreebsd_trans_osrel(const Elf_Note *note, int32_t *osrel);
100 static boolean_t __elfN(check_note)(struct image_params *imgp,
101 Elf_Brandnote *checknote, int32_t *osrel);
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), CTLFLAG_RW, 0,
108 #ifdef COMPRESS_USER_CORES
109 static int compress_core(gzFile, char *, char *, unsigned int,
112 #define CORE_BUF_SIZE (16 * 1024)
114 int __elfN(fallback_brand) = -1;
115 SYSCTL_INT(__CONCAT(_kern_elf, __ELF_WORD_SIZE), OID_AUTO,
116 fallback_brand, CTLFLAG_RW, &__elfN(fallback_brand), 0,
117 __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE)) " brand of last resort");
118 TUNABLE_INT("kern.elf" __XSTRING(__ELF_WORD_SIZE) ".fallback_brand",
119 &__elfN(fallback_brand));
121 static int elf_legacy_coredump = 0;
122 SYSCTL_INT(_debug, OID_AUTO, __elfN(legacy_coredump), CTLFLAG_RW,
123 &elf_legacy_coredump, 0, "");
125 int __elfN(nxstack) =
126 #if defined(__amd64__) || defined(__powerpc64__) /* both 64 and 32 bit */
131 SYSCTL_INT(__CONCAT(_kern_elf, __ELF_WORD_SIZE), OID_AUTO,
132 nxstack, CTLFLAG_RW, &__elfN(nxstack), 0,
133 __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE)) ": enable non-executable stack");
135 #if __ELF_WORD_SIZE == 32
136 #if defined(__amd64__) || defined(__ia64__)
137 int i386_read_exec = 0;
138 SYSCTL_INT(_kern_elf32, OID_AUTO, read_exec, CTLFLAG_RW, &i386_read_exec, 0,
139 "enable execution from readable segments");
143 static Elf_Brandinfo *elf_brand_list[MAX_BRANDS];
145 #define trunc_page_ps(va, ps) ((va) & ~(ps - 1))
146 #define round_page_ps(va, ps) (((va) + (ps - 1)) & ~(ps - 1))
147 #define aligned(a, t) (trunc_page_ps((u_long)(a), sizeof(t)) == (u_long)(a))
149 static const char FREEBSD_ABI_VENDOR[] = "FreeBSD";
151 Elf_Brandnote __elfN(freebsd_brandnote) = {
152 .hdr.n_namesz = sizeof(FREEBSD_ABI_VENDOR),
153 .hdr.n_descsz = sizeof(int32_t),
155 .vendor = FREEBSD_ABI_VENDOR,
156 .flags = BN_TRANSLATE_OSREL,
157 .trans_osrel = __elfN(freebsd_trans_osrel)
161 __elfN(freebsd_trans_osrel)(const Elf_Note *note, int32_t *osrel)
165 p = (uintptr_t)(note + 1);
166 p += roundup2(note->n_namesz, ELF_NOTE_ROUNDSIZE);
167 *osrel = *(const int32_t *)(p);
172 static const char GNU_ABI_VENDOR[] = "GNU";
173 static int GNU_KFREEBSD_ABI_DESC = 3;
175 Elf_Brandnote __elfN(kfreebsd_brandnote) = {
176 .hdr.n_namesz = sizeof(GNU_ABI_VENDOR),
177 .hdr.n_descsz = 16, /* XXX at least 16 */
179 .vendor = GNU_ABI_VENDOR,
180 .flags = BN_TRANSLATE_OSREL,
181 .trans_osrel = kfreebsd_trans_osrel
185 kfreebsd_trans_osrel(const Elf_Note *note, int32_t *osrel)
187 const Elf32_Word *desc;
190 p = (uintptr_t)(note + 1);
191 p += roundup2(note->n_namesz, ELF_NOTE_ROUNDSIZE);
193 desc = (const Elf32_Word *)p;
194 if (desc[0] != GNU_KFREEBSD_ABI_DESC)
198 * Debian GNU/kFreeBSD embed the earliest compatible kernel version
199 * (__FreeBSD_version: <major><two digit minor>Rxx) in the LSB way.
201 *osrel = desc[1] * 100000 + desc[2] * 1000 + desc[3];
207 __elfN(insert_brand_entry)(Elf_Brandinfo *entry)
211 for (i = 0; i < MAX_BRANDS; i++) {
212 if (elf_brand_list[i] == NULL) {
213 elf_brand_list[i] = entry;
217 if (i == MAX_BRANDS) {
218 printf("WARNING: %s: could not insert brandinfo entry: %p\n",
226 __elfN(remove_brand_entry)(Elf_Brandinfo *entry)
230 for (i = 0; i < MAX_BRANDS; i++) {
231 if (elf_brand_list[i] == entry) {
232 elf_brand_list[i] = NULL;
242 __elfN(brand_inuse)(Elf_Brandinfo *entry)
247 sx_slock(&allproc_lock);
248 FOREACH_PROC_IN_SYSTEM(p) {
249 if (p->p_sysent == entry->sysvec) {
254 sx_sunlock(&allproc_lock);
259 static Elf_Brandinfo *
260 __elfN(get_brandinfo)(struct image_params *imgp, const char *interp,
261 int interp_name_len, int32_t *osrel)
263 const Elf_Ehdr *hdr = (const Elf_Ehdr *)imgp->image_header;
264 Elf_Brandinfo *bi, *bi_m;
269 * We support four types of branding -- (1) the ELF EI_OSABI field
270 * that SCO added to the ELF spec, (2) FreeBSD 3.x's traditional string
271 * branding w/in the ELF header, (3) path of the `interp_path'
272 * field, and (4) the ".note.ABI-tag" ELF section.
275 /* Look for an ".note.ABI-tag" ELF section */
277 for (i = 0; i < MAX_BRANDS; i++) {
278 bi = elf_brand_list[i];
281 if (hdr->e_machine == bi->machine && (bi->flags &
282 (BI_BRAND_NOTE|BI_BRAND_NOTE_MANDATORY)) != 0) {
283 ret = __elfN(check_note)(imgp, bi->brand_note, osrel);
285 * If note checker claimed the binary, but the
286 * interpreter path in the image does not
287 * match default one for the brand, try to
288 * search for other brands with the same
289 * interpreter. Either there is better brand
290 * with the right interpreter, or, failing
291 * this, we return first brand which accepted
292 * our note and, optionally, header.
294 if (ret && bi_m == NULL && (strlen(bi->interp_path) +
295 1 != interp_name_len || strncmp(interp,
296 bi->interp_path, interp_name_len) != 0)) {
307 /* If the executable has a brand, search for it in the brand list. */
308 for (i = 0; i < MAX_BRANDS; i++) {
309 bi = elf_brand_list[i];
310 if (bi == NULL || bi->flags & BI_BRAND_NOTE_MANDATORY)
312 if (hdr->e_machine == bi->machine &&
313 (hdr->e_ident[EI_OSABI] == bi->brand ||
314 strncmp((const char *)&hdr->e_ident[OLD_EI_BRAND],
315 bi->compat_3_brand, strlen(bi->compat_3_brand)) == 0))
319 /* Lacking a known brand, search for a recognized interpreter. */
320 if (interp != NULL) {
321 for (i = 0; i < MAX_BRANDS; i++) {
322 bi = elf_brand_list[i];
323 if (bi == NULL || bi->flags & BI_BRAND_NOTE_MANDATORY)
325 if (hdr->e_machine == bi->machine &&
326 /* ELF image p_filesz includes terminating zero */
327 strlen(bi->interp_path) + 1 == interp_name_len &&
328 strncmp(interp, bi->interp_path, interp_name_len)
334 /* Lacking a recognized interpreter, try the default brand */
335 for (i = 0; i < MAX_BRANDS; i++) {
336 bi = elf_brand_list[i];
337 if (bi == NULL || bi->flags & BI_BRAND_NOTE_MANDATORY)
339 if (hdr->e_machine == bi->machine &&
340 __elfN(fallback_brand) == bi->brand)
347 __elfN(check_header)(const Elf_Ehdr *hdr)
353 hdr->e_ident[EI_CLASS] != ELF_TARG_CLASS ||
354 hdr->e_ident[EI_DATA] != ELF_TARG_DATA ||
355 hdr->e_ident[EI_VERSION] != EV_CURRENT ||
356 hdr->e_phentsize != sizeof(Elf_Phdr) ||
357 hdr->e_version != ELF_TARG_VER)
361 * Make sure we have at least one brand for this machine.
364 for (i = 0; i < MAX_BRANDS; i++) {
365 bi = elf_brand_list[i];
366 if (bi != NULL && bi->machine == hdr->e_machine)
376 __elfN(map_partial)(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
377 vm_offset_t start, vm_offset_t end, vm_prot_t prot)
384 * Create the page if it doesn't exist yet. Ignore errors.
387 vm_map_insert(map, NULL, 0, trunc_page(start), round_page(end),
388 VM_PROT_ALL, VM_PROT_ALL, 0);
392 * Find the page from the underlying object.
395 sf = vm_imgact_map_page(object, offset);
397 return (KERN_FAILURE);
398 off = offset - trunc_page(offset);
399 error = copyout((caddr_t)sf_buf_kva(sf) + off, (caddr_t)start,
401 vm_imgact_unmap_page(sf);
403 return (KERN_FAILURE);
407 return (KERN_SUCCESS);
411 __elfN(map_insert)(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
412 vm_offset_t start, vm_offset_t end, vm_prot_t prot, int cow)
419 if (start != trunc_page(start)) {
420 rv = __elfN(map_partial)(map, object, offset, start,
421 round_page(start), prot);
424 offset += round_page(start) - start;
425 start = round_page(start);
427 if (end != round_page(end)) {
428 rv = __elfN(map_partial)(map, object, offset +
429 trunc_page(end) - start, trunc_page(end), end, prot);
432 end = trunc_page(end);
435 if (offset & PAGE_MASK) {
437 * The mapping is not page aligned. This means we have
438 * to copy the data. Sigh.
440 rv = vm_map_find(map, NULL, 0, &start, end - start, 0,
441 VMFS_NO_SPACE, prot | VM_PROT_WRITE, VM_PROT_ALL,
443 if (rv != KERN_SUCCESS)
446 return (KERN_SUCCESS);
447 for (; start < end; start += sz) {
448 sf = vm_imgact_map_page(object, offset);
450 return (KERN_FAILURE);
451 off = offset - trunc_page(offset);
453 if (sz > PAGE_SIZE - off)
454 sz = PAGE_SIZE - off;
455 error = copyout((caddr_t)sf_buf_kva(sf) + off,
457 vm_imgact_unmap_page(sf);
459 return (KERN_FAILURE);
464 vm_object_reference(object);
466 rv = vm_map_insert(map, object, offset, start, end,
467 prot, VM_PROT_ALL, cow);
469 if (rv != KERN_SUCCESS)
470 vm_object_deallocate(object);
474 return (KERN_SUCCESS);
479 __elfN(load_section)(struct image_params *imgp, vm_offset_t offset,
480 caddr_t vmaddr, size_t memsz, size_t filsz, vm_prot_t prot,
487 vm_offset_t map_addr;
490 vm_offset_t file_addr;
493 * It's necessary to fail if the filsz + offset taken from the
494 * header is greater than the actual file pager object's size.
495 * If we were to allow this, then the vm_map_find() below would
496 * walk right off the end of the file object and into the ether.
498 * While I'm here, might as well check for something else that
499 * is invalid: filsz cannot be greater than memsz.
501 if ((off_t)filsz + offset > imgp->attr->va_size || filsz > memsz) {
502 uprintf("elf_load_section: truncated ELF file\n");
506 object = imgp->object;
507 map = &imgp->proc->p_vmspace->vm_map;
508 map_addr = trunc_page_ps((vm_offset_t)vmaddr, pagesize);
509 file_addr = trunc_page_ps(offset, pagesize);
512 * We have two choices. We can either clear the data in the last page
513 * of an oversized mapping, or we can start the anon mapping a page
514 * early and copy the initialized data into that first page. We
515 * choose the second..
518 map_len = trunc_page_ps(offset + filsz, pagesize) - file_addr;
520 map_len = round_page_ps(offset + filsz, pagesize) - file_addr;
523 /* cow flags: don't dump readonly sections in core */
524 cow = MAP_COPY_ON_WRITE | MAP_PREFAULT |
525 (prot & VM_PROT_WRITE ? 0 : MAP_DISABLE_COREDUMP);
527 rv = __elfN(map_insert)(map,
529 file_addr, /* file offset */
530 map_addr, /* virtual start */
531 map_addr + map_len,/* virtual end */
534 if (rv != KERN_SUCCESS)
537 /* we can stop now if we've covered it all */
538 if (memsz == filsz) {
545 * We have to get the remaining bit of the file into the first part
546 * of the oversized map segment. This is normally because the .data
547 * segment in the file is extended to provide bss. It's a neat idea
548 * to try and save a page, but it's a pain in the behind to implement.
550 copy_len = (offset + filsz) - trunc_page_ps(offset + filsz, pagesize);
551 map_addr = trunc_page_ps((vm_offset_t)vmaddr + filsz, pagesize);
552 map_len = round_page_ps((vm_offset_t)vmaddr + memsz, pagesize) -
555 /* This had damn well better be true! */
557 rv = __elfN(map_insert)(map, NULL, 0, map_addr, map_addr +
558 map_len, VM_PROT_ALL, 0);
559 if (rv != KERN_SUCCESS) {
567 sf = vm_imgact_map_page(object, offset + filsz);
571 /* send the page fragment to user space */
572 off = trunc_page_ps(offset + filsz, pagesize) -
573 trunc_page(offset + filsz);
574 error = copyout((caddr_t)sf_buf_kva(sf) + off,
575 (caddr_t)map_addr, copy_len);
576 vm_imgact_unmap_page(sf);
583 * set it to the specified protection.
584 * XXX had better undo the damage from pasting over the cracks here!
586 vm_map_protect(map, trunc_page(map_addr), round_page(map_addr +
587 map_len), prot, FALSE);
593 * Load the file "file" into memory. It may be either a shared object
596 * The "addr" reference parameter is in/out. On entry, it specifies
597 * the address where a shared object should be loaded. If the file is
598 * an executable, this value is ignored. On exit, "addr" specifies
599 * where the file was actually loaded.
601 * The "entry" reference parameter is out only. On exit, it specifies
602 * the entry point for the loaded file.
605 __elfN(load_file)(struct proc *p, const char *file, u_long *addr,
606 u_long *entry, size_t pagesize)
611 struct image_params image_params;
613 const Elf_Ehdr *hdr = NULL;
614 const Elf_Phdr *phdr = NULL;
615 struct nameidata *nd;
617 struct image_params *imgp;
620 u_long base_addr = 0;
621 int error, i, numsegs;
623 #ifdef CAPABILITY_MODE
625 * XXXJA: This check can go away once we are sufficiently confident
626 * that the checks in namei() are correct.
628 if (IN_CAPABILITY_MODE(curthread))
632 tempdata = malloc(sizeof(*tempdata), M_TEMP, M_WAITOK);
634 attr = &tempdata->attr;
635 imgp = &tempdata->image_params;
638 * Initialize part of the common data
642 imgp->firstpage = NULL;
643 imgp->image_header = NULL;
645 imgp->execlabel = NULL;
647 NDINIT(nd, LOOKUP, LOCKLEAF | FOLLOW, UIO_SYSSPACE, file, curthread);
648 if ((error = namei(nd)) != 0) {
652 NDFREE(nd, NDF_ONLY_PNBUF);
653 imgp->vp = nd->ni_vp;
656 * Check permissions, modes, uid, etc on the file, and "open" it.
658 error = exec_check_permissions(imgp);
662 error = exec_map_first_page(imgp);
667 * Also make certain that the interpreter stays the same, so set
668 * its VV_TEXT flag, too.
670 VOP_SET_TEXT(nd->ni_vp);
672 imgp->object = nd->ni_vp->v_object;
674 hdr = (const Elf_Ehdr *)imgp->image_header;
675 if ((error = __elfN(check_header)(hdr)) != 0)
677 if (hdr->e_type == ET_DYN)
679 else if (hdr->e_type == ET_EXEC)
686 /* Only support headers that fit within first page for now */
687 if ((hdr->e_phoff > PAGE_SIZE) ||
688 (u_int)hdr->e_phentsize * hdr->e_phnum > PAGE_SIZE - hdr->e_phoff) {
693 phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
694 if (!aligned(phdr, Elf_Addr)) {
699 for (i = 0, numsegs = 0; i < hdr->e_phnum; i++) {
700 if (phdr[i].p_type == PT_LOAD && phdr[i].p_memsz != 0) {
701 /* Loadable segment */
702 prot = __elfN(trans_prot)(phdr[i].p_flags);
703 error = __elfN(load_section)(imgp, phdr[i].p_offset,
704 (caddr_t)(uintptr_t)phdr[i].p_vaddr + rbase,
705 phdr[i].p_memsz, phdr[i].p_filesz, prot, pagesize);
709 * Establish the base address if this is the
713 base_addr = trunc_page(phdr[i].p_vaddr +
719 *entry = (unsigned long)hdr->e_entry + rbase;
723 exec_unmap_first_page(imgp);
728 free(tempdata, M_TEMP);
734 __CONCAT(exec_, __elfN(imgact))(struct image_params *imgp)
738 const Elf_Phdr *phdr;
739 Elf_Auxargs *elf_auxargs;
740 struct vmspace *vmspace;
741 const char *err_str, *newinterp;
742 char *interp, *interp_buf, *path;
743 Elf_Brandinfo *brand_info;
744 struct sysentvec *sv;
746 u_long text_size, data_size, total_size, text_addr, data_addr;
747 u_long seg_size, seg_addr, addr, baddr, et_dyn_addr, entry, proghdr;
749 int error, i, n, interp_name_len, have_interp;
751 hdr = (const Elf_Ehdr *)imgp->image_header;
754 * Do we have a valid ELF header ?
756 * Only allow ET_EXEC & ET_DYN here, reject ET_DYN later
757 * if particular brand doesn't support it.
759 if (__elfN(check_header)(hdr) != 0 ||
760 (hdr->e_type != ET_EXEC && hdr->e_type != ET_DYN))
764 * From here on down, we return an errno, not -1, as we've
765 * detected an ELF file.
768 if ((hdr->e_phoff > PAGE_SIZE) ||
769 (u_int)hdr->e_phentsize * hdr->e_phnum > PAGE_SIZE - hdr->e_phoff) {
770 /* Only support headers in first page for now */
771 uprintf("Program headers not in the first page\n");
774 phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
775 if (!aligned(phdr, Elf_Addr)) {
776 uprintf("Unaligned program headers\n");
783 text_size = data_size = total_size = text_addr = data_addr = 0;
786 err_str = newinterp = NULL;
787 interp = interp_buf = NULL;
790 for (i = 0; i < hdr->e_phnum; i++) {
791 switch (phdr[i].p_type) {
794 baddr = phdr[i].p_vaddr;
798 /* Path to interpreter */
799 if (phdr[i].p_filesz > MAXPATHLEN) {
800 uprintf("Invalid PT_INTERP\n");
804 if (interp != NULL) {
805 uprintf("Multiple PT_INTERP headers\n");
809 interp_name_len = phdr[i].p_filesz;
810 if (phdr[i].p_offset > PAGE_SIZE ||
811 interp_name_len > PAGE_SIZE - phdr[i].p_offset) {
812 VOP_UNLOCK(imgp->vp, 0);
813 interp_buf = malloc(interp_name_len + 1, M_TEMP,
815 vn_lock(imgp->vp, LK_EXCLUSIVE | LK_RETRY);
816 error = vn_rdwr(UIO_READ, imgp->vp, interp_buf,
817 interp_name_len, phdr[i].p_offset,
818 UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred,
821 uprintf("i/o error PT_INTERP\n");
824 interp_buf[interp_name_len] = '\0';
827 interp = __DECONST(char *, imgp->image_header) +
834 __elfN(trans_prot)(phdr[i].p_flags);
835 imgp->stack_sz = phdr[i].p_memsz;
840 brand_info = __elfN(get_brandinfo)(imgp, interp, interp_name_len,
842 if (brand_info == NULL) {
843 uprintf("ELF binary type \"%u\" not known.\n",
844 hdr->e_ident[EI_OSABI]);
848 if (hdr->e_type == ET_DYN) {
849 if ((brand_info->flags & BI_CAN_EXEC_DYN) == 0) {
850 uprintf("Cannot execute shared object\n");
855 * Honour the base load address from the dso if it is
856 * non-zero for some reason.
859 et_dyn_addr = ET_DYN_LOAD_ADDR;
864 sv = brand_info->sysvec;
865 if (interp != NULL && brand_info->interp_newpath != NULL)
866 newinterp = brand_info->interp_newpath;
869 * Avoid a possible deadlock if the current address space is destroyed
870 * and that address space maps the locked vnode. In the common case,
871 * the locked vnode's v_usecount is decremented but remains greater
872 * than zero. Consequently, the vnode lock is not needed by vrele().
873 * However, in cases where the vnode lock is external, such as nullfs,
874 * v_usecount may become zero.
876 * The VV_TEXT flag prevents modifications to the executable while
877 * the vnode is unlocked.
879 VOP_UNLOCK(imgp->vp, 0);
881 error = exec_new_vmspace(imgp, sv);
882 imgp->proc->p_sysent = sv;
884 vn_lock(imgp->vp, LK_EXCLUSIVE | LK_RETRY);
888 for (i = 0; i < hdr->e_phnum; i++) {
889 switch (phdr[i].p_type) {
890 case PT_LOAD: /* Loadable segment */
891 if (phdr[i].p_memsz == 0)
893 prot = __elfN(trans_prot)(phdr[i].p_flags);
894 error = __elfN(load_section)(imgp, phdr[i].p_offset,
895 (caddr_t)(uintptr_t)phdr[i].p_vaddr + et_dyn_addr,
896 phdr[i].p_memsz, phdr[i].p_filesz, prot,
902 * If this segment contains the program headers,
903 * remember their virtual address for the AT_PHDR
904 * aux entry. Static binaries don't usually include
907 if (phdr[i].p_offset == 0 &&
908 hdr->e_phoff + hdr->e_phnum * hdr->e_phentsize
910 proghdr = phdr[i].p_vaddr + hdr->e_phoff +
913 seg_addr = trunc_page(phdr[i].p_vaddr + et_dyn_addr);
914 seg_size = round_page(phdr[i].p_memsz +
915 phdr[i].p_vaddr + et_dyn_addr - seg_addr);
918 * Make the largest executable segment the official
919 * text segment and all others data.
921 * Note that obreak() assumes that data_addr +
922 * data_size == end of data load area, and the ELF
923 * file format expects segments to be sorted by
924 * address. If multiple data segments exist, the
925 * last one will be used.
928 if (phdr[i].p_flags & PF_X && text_size < seg_size) {
929 text_size = seg_size;
930 text_addr = seg_addr;
932 data_size = seg_size;
933 data_addr = seg_addr;
935 total_size += seg_size;
937 case PT_PHDR: /* Program header table info */
938 proghdr = phdr[i].p_vaddr + et_dyn_addr;
945 if (data_addr == 0 && data_size == 0) {
946 data_addr = text_addr;
947 data_size = text_size;
950 entry = (u_long)hdr->e_entry + et_dyn_addr;
953 * Check limits. It should be safe to check the
954 * limits after loading the segments since we do
955 * not actually fault in all the segments pages.
957 PROC_LOCK(imgp->proc);
958 if (data_size > lim_cur(imgp->proc, RLIMIT_DATA))
959 err_str = "Data segment size exceeds process limit";
960 else if (text_size > maxtsiz)
961 err_str = "Text segment size exceeds system limit";
962 else if (total_size > lim_cur(imgp->proc, RLIMIT_VMEM))
963 err_str = "Total segment size exceeds process limit";
964 else if (racct_set(imgp->proc, RACCT_DATA, data_size) != 0)
965 err_str = "Data segment size exceeds resource limit";
966 else if (racct_set(imgp->proc, RACCT_VMEM, total_size) != 0)
967 err_str = "Total segment size exceeds resource limit";
968 if (err_str != NULL) {
969 PROC_UNLOCK(imgp->proc);
970 uprintf("%s\n", err_str);
975 vmspace = imgp->proc->p_vmspace;
976 vmspace->vm_tsize = text_size >> PAGE_SHIFT;
977 vmspace->vm_taddr = (caddr_t)(uintptr_t)text_addr;
978 vmspace->vm_dsize = data_size >> PAGE_SHIFT;
979 vmspace->vm_daddr = (caddr_t)(uintptr_t)data_addr;
982 * We load the dynamic linker where a userland call
983 * to mmap(0, ...) would put it. The rationale behind this
984 * calculation is that it leaves room for the heap to grow to
985 * its maximum allowed size.
987 addr = round_page((vm_offset_t)vmspace->vm_daddr + lim_max(imgp->proc,
989 PROC_UNLOCK(imgp->proc);
991 imgp->entry_addr = entry;
993 if (interp != NULL) {
995 VOP_UNLOCK(imgp->vp, 0);
996 if (brand_info->emul_path != NULL &&
997 brand_info->emul_path[0] != '\0') {
998 path = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
999 snprintf(path, MAXPATHLEN, "%s%s",
1000 brand_info->emul_path, interp);
1001 error = __elfN(load_file)(imgp->proc, path, &addr,
1002 &imgp->entry_addr, sv->sv_pagesize);
1007 if (!have_interp && newinterp != NULL &&
1008 (brand_info->interp_path == NULL ||
1009 strcmp(interp, brand_info->interp_path) == 0)) {
1010 error = __elfN(load_file)(imgp->proc, newinterp, &addr,
1011 &imgp->entry_addr, sv->sv_pagesize);
1016 error = __elfN(load_file)(imgp->proc, interp, &addr,
1017 &imgp->entry_addr, sv->sv_pagesize);
1019 vn_lock(imgp->vp, LK_EXCLUSIVE | LK_RETRY);
1021 uprintf("ELF interpreter %s not found, error %d\n",
1029 * Construct auxargs table (used by the fixup routine)
1031 elf_auxargs = malloc(sizeof(Elf_Auxargs), M_TEMP, M_WAITOK);
1032 elf_auxargs->execfd = -1;
1033 elf_auxargs->phdr = proghdr;
1034 elf_auxargs->phent = hdr->e_phentsize;
1035 elf_auxargs->phnum = hdr->e_phnum;
1036 elf_auxargs->pagesz = PAGE_SIZE;
1037 elf_auxargs->base = addr;
1038 elf_auxargs->flags = 0;
1039 elf_auxargs->entry = entry;
1041 imgp->auxargs = elf_auxargs;
1042 imgp->interpreted = 0;
1043 imgp->reloc_base = addr;
1044 imgp->proc->p_osrel = osrel;
1047 free(interp_buf, M_TEMP);
1051 #define suword __CONCAT(suword, __ELF_WORD_SIZE)
1054 __elfN(freebsd_fixup)(register_t **stack_base, struct image_params *imgp)
1056 Elf_Auxargs *args = (Elf_Auxargs *)imgp->auxargs;
1060 base = (Elf_Addr *)*stack_base;
1061 pos = base + (imgp->args->argc + imgp->args->envc + 2);
1063 if (args->execfd != -1)
1064 AUXARGS_ENTRY(pos, AT_EXECFD, args->execfd);
1065 AUXARGS_ENTRY(pos, AT_PHDR, args->phdr);
1066 AUXARGS_ENTRY(pos, AT_PHENT, args->phent);
1067 AUXARGS_ENTRY(pos, AT_PHNUM, args->phnum);
1068 AUXARGS_ENTRY(pos, AT_PAGESZ, args->pagesz);
1069 AUXARGS_ENTRY(pos, AT_FLAGS, args->flags);
1070 AUXARGS_ENTRY(pos, AT_ENTRY, args->entry);
1071 AUXARGS_ENTRY(pos, AT_BASE, args->base);
1072 if (imgp->execpathp != 0)
1073 AUXARGS_ENTRY(pos, AT_EXECPATH, imgp->execpathp);
1074 AUXARGS_ENTRY(pos, AT_OSRELDATE,
1075 imgp->proc->p_ucred->cr_prison->pr_osreldate);
1076 if (imgp->canary != 0) {
1077 AUXARGS_ENTRY(pos, AT_CANARY, imgp->canary);
1078 AUXARGS_ENTRY(pos, AT_CANARYLEN, imgp->canarylen);
1080 AUXARGS_ENTRY(pos, AT_NCPUS, mp_ncpus);
1081 if (imgp->pagesizes != 0) {
1082 AUXARGS_ENTRY(pos, AT_PAGESIZES, imgp->pagesizes);
1083 AUXARGS_ENTRY(pos, AT_PAGESIZESLEN, imgp->pagesizeslen);
1085 if (imgp->sysent->sv_timekeep_base != 0) {
1086 AUXARGS_ENTRY(pos, AT_TIMEKEEP,
1087 imgp->sysent->sv_timekeep_base);
1089 AUXARGS_ENTRY(pos, AT_STACKPROT, imgp->sysent->sv_shared_page_obj
1090 != NULL && imgp->stack_prot != 0 ? imgp->stack_prot :
1091 imgp->sysent->sv_stackprot);
1092 AUXARGS_ENTRY(pos, AT_NULL, 0);
1094 free(imgp->auxargs, M_TEMP);
1095 imgp->auxargs = NULL;
1098 suword(base, (long)imgp->args->argc);
1099 *stack_base = (register_t *)base;
1104 * Code for generating ELF core dumps.
1107 typedef void (*segment_callback)(vm_map_entry_t, void *);
1109 /* Closure for cb_put_phdr(). */
1110 struct phdr_closure {
1111 Elf_Phdr *phdr; /* Program header to fill in */
1112 Elf_Off offset; /* Offset of segment in core file */
1115 /* Closure for cb_size_segment(). */
1116 struct sseg_closure {
1117 int count; /* Count of writable segments. */
1118 size_t size; /* Total size of all writable segments. */
1121 typedef void (*outfunc_t)(void *, struct sbuf *, size_t *);
1124 int type; /* Note type. */
1125 outfunc_t outfunc; /* Output function. */
1126 void *outarg; /* Argument for the output function. */
1127 size_t outsize; /* Output size. */
1128 TAILQ_ENTRY(note_info) link; /* Link to the next note info. */
1131 TAILQ_HEAD(note_info_list, note_info);
1133 static void cb_put_phdr(vm_map_entry_t, void *);
1134 static void cb_size_segment(vm_map_entry_t, void *);
1135 static void each_writable_segment(struct thread *, segment_callback, void *);
1136 static int __elfN(corehdr)(struct thread *, struct vnode *, struct ucred *,
1137 int, void *, size_t, struct note_info_list *, size_t, gzFile);
1138 static void __elfN(prepare_notes)(struct thread *, struct note_info_list *,
1140 static void __elfN(puthdr)(struct thread *, void *, size_t, int, size_t);
1141 static void __elfN(putnote)(struct note_info *, struct sbuf *);
1142 static size_t register_note(struct note_info_list *, int, outfunc_t, void *);
1143 static int sbuf_drain_core_output(void *, const char *, int);
1144 static int sbuf_drain_count(void *arg, const char *data, int len);
1146 static void __elfN(note_fpregset)(void *, struct sbuf *, size_t *);
1147 static void __elfN(note_prpsinfo)(void *, struct sbuf *, size_t *);
1148 static void __elfN(note_prstatus)(void *, struct sbuf *, size_t *);
1149 static void __elfN(note_threadmd)(void *, struct sbuf *, size_t *);
1150 static void __elfN(note_thrmisc)(void *, struct sbuf *, size_t *);
1151 static void __elfN(note_procstat_auxv)(void *, struct sbuf *, size_t *);
1152 static void __elfN(note_procstat_proc)(void *, struct sbuf *, size_t *);
1153 static void __elfN(note_procstat_psstrings)(void *, struct sbuf *, size_t *);
1154 static void note_procstat_files(void *, struct sbuf *, size_t *);
1155 static void note_procstat_groups(void *, struct sbuf *, size_t *);
1156 static void note_procstat_osrel(void *, struct sbuf *, size_t *);
1157 static void note_procstat_rlimit(void *, struct sbuf *, size_t *);
1158 static void note_procstat_umask(void *, struct sbuf *, size_t *);
1159 static void note_procstat_vmmap(void *, struct sbuf *, size_t *);
1161 #ifdef COMPRESS_USER_CORES
1162 extern int compress_user_cores;
1163 extern int compress_user_cores_gzlevel;
1167 core_output(struct vnode *vp, void *base, size_t len, off_t offset,
1168 struct ucred *active_cred, struct ucred *file_cred,
1169 struct thread *td, char *core_buf, gzFile gzfile) {
1173 #ifdef COMPRESS_USER_CORES
1174 error = compress_core(gzfile, base, core_buf, len, td);
1176 panic("shouldn't be here");
1179 error = vn_rdwr_inchunks(UIO_WRITE, vp, base, len, offset,
1180 UIO_USERSPACE, IO_UNIT | IO_DIRECT, active_cred, file_cred,
1186 /* Coredump output parameters for sbuf drain routine. */
1187 struct sbuf_drain_core_params {
1189 struct ucred *active_cred;
1190 struct ucred *file_cred;
1193 #ifdef COMPRESS_USER_CORES
1199 * Drain into a core file.
1202 sbuf_drain_core_output(void *arg, const char *data, int len)
1204 struct sbuf_drain_core_params *p;
1207 p = (struct sbuf_drain_core_params *)arg;
1210 * Some kern_proc out routines that print to this sbuf may
1211 * call us with the process lock held. Draining with the
1212 * non-sleepable lock held is unsafe. The lock is needed for
1213 * those routines when dumping a live process. In our case we
1214 * can safely release the lock before draining and acquire
1217 locked = PROC_LOCKED(p->td->td_proc);
1219 PROC_UNLOCK(p->td->td_proc);
1220 #ifdef COMPRESS_USER_CORES
1221 if (p->gzfile != Z_NULL)
1222 error = compress_core(p->gzfile, NULL, __DECONST(char *, data),
1226 error = vn_rdwr_inchunks(UIO_WRITE, p->vp,
1227 __DECONST(void *, data), len, p->offset, UIO_SYSSPACE,
1228 IO_UNIT | IO_DIRECT, p->active_cred, p->file_cred, NULL,
1231 PROC_LOCK(p->td->td_proc);
1239 * Drain into a counter.
1242 sbuf_drain_count(void *arg, const char *data __unused, int len)
1246 sizep = (size_t *)arg;
1252 __elfN(coredump)(struct thread *td, struct vnode *vp, off_t limit, int flags)
1254 struct ucred *cred = td->td_ucred;
1256 struct sseg_closure seginfo;
1257 struct note_info_list notelst;
1258 struct note_info *ninfo;
1260 size_t hdrsize, notesz, coresize;
1262 gzFile gzfile = Z_NULL;
1263 char *core_buf = NULL;
1264 #ifdef COMPRESS_USER_CORES
1265 char gzopen_flags[8];
1267 int doing_compress = flags & IMGACT_CORE_COMPRESS;
1271 TAILQ_INIT(¬elst);
1273 #ifdef COMPRESS_USER_CORES
1274 if (doing_compress) {
1277 if (compress_user_cores_gzlevel >= 0 &&
1278 compress_user_cores_gzlevel <= 9)
1279 *p++ = '0' + compress_user_cores_gzlevel;
1281 gzfile = gz_open("", gzopen_flags, vp);
1282 if (gzfile == Z_NULL) {
1286 core_buf = malloc(CORE_BUF_SIZE, M_TEMP, M_WAITOK | M_ZERO);
1294 /* Size the program segments. */
1297 each_writable_segment(td, cb_size_segment, &seginfo);
1300 * Collect info about the core file header area.
1302 hdrsize = sizeof(Elf_Ehdr) + sizeof(Elf_Phdr) * (1 + seginfo.count);
1303 __elfN(prepare_notes)(td, ¬elst, ¬esz);
1304 coresize = round_page(hdrsize + notesz) + seginfo.size;
1308 PROC_LOCK(td->td_proc);
1309 error = racct_add(td->td_proc, RACCT_CORE, coresize);
1310 PROC_UNLOCK(td->td_proc);
1317 if (coresize >= limit) {
1323 * Allocate memory for building the header, fill it up,
1324 * and write it out following the notes.
1326 hdr = malloc(hdrsize, M_TEMP, M_WAITOK);
1327 error = __elfN(corehdr)(td, vp, cred, seginfo.count, hdr, hdrsize,
1328 ¬elst, notesz, gzfile);
1330 /* Write the contents of all of the writable segments. */
1336 php = (Elf_Phdr *)((char *)hdr + sizeof(Elf_Ehdr)) + 1;
1337 offset = round_page(hdrsize + notesz);
1338 for (i = 0; i < seginfo.count; i++) {
1339 error = core_output(vp, (caddr_t)(uintptr_t)php->p_vaddr,
1340 php->p_filesz, offset, cred, NOCRED, curthread, core_buf, gzfile);
1343 offset += php->p_filesz;
1349 "Failed to write core file for process %s (error %d)\n",
1350 curproc->p_comm, error);
1354 #ifdef COMPRESS_USER_CORES
1356 free(core_buf, M_TEMP);
1360 while ((ninfo = TAILQ_FIRST(¬elst)) != NULL) {
1361 TAILQ_REMOVE(¬elst, ninfo, link);
1362 free(ninfo, M_TEMP);
1371 * A callback for each_writable_segment() to write out the segment's
1372 * program header entry.
1375 cb_put_phdr(entry, closure)
1376 vm_map_entry_t entry;
1379 struct phdr_closure *phc = (struct phdr_closure *)closure;
1380 Elf_Phdr *phdr = phc->phdr;
1382 phc->offset = round_page(phc->offset);
1384 phdr->p_type = PT_LOAD;
1385 phdr->p_offset = phc->offset;
1386 phdr->p_vaddr = entry->start;
1388 phdr->p_filesz = phdr->p_memsz = entry->end - entry->start;
1389 phdr->p_align = PAGE_SIZE;
1390 phdr->p_flags = __elfN(untrans_prot)(entry->protection);
1392 phc->offset += phdr->p_filesz;
1397 * A callback for each_writable_segment() to gather information about
1398 * the number of segments and their total size.
1401 cb_size_segment(entry, closure)
1402 vm_map_entry_t entry;
1405 struct sseg_closure *ssc = (struct sseg_closure *)closure;
1408 ssc->size += entry->end - entry->start;
1412 * For each writable segment in the process's memory map, call the given
1413 * function with a pointer to the map entry and some arbitrary
1414 * caller-supplied data.
1417 each_writable_segment(td, func, closure)
1419 segment_callback func;
1422 struct proc *p = td->td_proc;
1423 vm_map_t map = &p->p_vmspace->vm_map;
1424 vm_map_entry_t entry;
1425 vm_object_t backing_object, object;
1426 boolean_t ignore_entry;
1428 vm_map_lock_read(map);
1429 for (entry = map->header.next; entry != &map->header;
1430 entry = entry->next) {
1432 * Don't dump inaccessible mappings, deal with legacy
1435 * Note that read-only segments related to the elf binary
1436 * are marked MAP_ENTRY_NOCOREDUMP now so we no longer
1437 * need to arbitrarily ignore such segments.
1439 if (elf_legacy_coredump) {
1440 if ((entry->protection & VM_PROT_RW) != VM_PROT_RW)
1443 if ((entry->protection & VM_PROT_ALL) == 0)
1448 * Dont include memory segment in the coredump if
1449 * MAP_NOCORE is set in mmap(2) or MADV_NOCORE in
1450 * madvise(2). Do not dump submaps (i.e. parts of the
1453 if (entry->eflags & (MAP_ENTRY_NOCOREDUMP|MAP_ENTRY_IS_SUB_MAP))
1456 if ((object = entry->object.vm_object) == NULL)
1459 /* Ignore memory-mapped devices and such things. */
1460 VM_OBJECT_RLOCK(object);
1461 while ((backing_object = object->backing_object) != NULL) {
1462 VM_OBJECT_RLOCK(backing_object);
1463 VM_OBJECT_RUNLOCK(object);
1464 object = backing_object;
1466 ignore_entry = object->type != OBJT_DEFAULT &&
1467 object->type != OBJT_SWAP && object->type != OBJT_VNODE &&
1468 object->type != OBJT_PHYS;
1469 VM_OBJECT_RUNLOCK(object);
1473 (*func)(entry, closure);
1475 vm_map_unlock_read(map);
1479 * Write the core file header to the file, including padding up to
1480 * the page boundary.
1483 __elfN(corehdr)(struct thread *td, struct vnode *vp, struct ucred *cred,
1484 int numsegs, void *hdr, size_t hdrsize, struct note_info_list *notelst,
1485 size_t notesz, gzFile gzfile)
1487 struct sbuf_drain_core_params params;
1488 struct note_info *ninfo;
1492 /* Fill in the header. */
1493 bzero(hdr, hdrsize);
1494 __elfN(puthdr)(td, hdr, hdrsize, numsegs, notesz);
1497 params.active_cred = cred;
1498 params.file_cred = NOCRED;
1501 #ifdef COMPRESS_USER_CORES
1502 params.gzfile = gzfile;
1504 sb = sbuf_new(NULL, NULL, CORE_BUF_SIZE, SBUF_FIXEDLEN);
1505 sbuf_set_drain(sb, sbuf_drain_core_output, ¶ms);
1506 sbuf_start_section(sb, NULL);
1507 sbuf_bcat(sb, hdr, hdrsize);
1508 TAILQ_FOREACH(ninfo, notelst, link)
1509 __elfN(putnote)(ninfo, sb);
1510 /* Align up to a page boundary for the program segments. */
1511 sbuf_end_section(sb, -1, PAGE_SIZE, 0);
1512 error = sbuf_finish(sb);
1519 __elfN(prepare_notes)(struct thread *td, struct note_info_list *list,
1529 size += register_note(list, NT_PRPSINFO, __elfN(note_prpsinfo), p);
1532 * To have the debugger select the right thread (LWP) as the initial
1533 * thread, we dump the state of the thread passed to us in td first.
1534 * This is the thread that causes the core dump and thus likely to
1535 * be the right thread one wants to have selected in the debugger.
1538 while (thr != NULL) {
1539 size += register_note(list, NT_PRSTATUS,
1540 __elfN(note_prstatus), thr);
1541 size += register_note(list, NT_FPREGSET,
1542 __elfN(note_fpregset), thr);
1543 size += register_note(list, NT_THRMISC,
1544 __elfN(note_thrmisc), thr);
1545 size += register_note(list, -1,
1546 __elfN(note_threadmd), thr);
1548 thr = (thr == td) ? TAILQ_FIRST(&p->p_threads) :
1549 TAILQ_NEXT(thr, td_plist);
1551 thr = TAILQ_NEXT(thr, td_plist);
1554 size += register_note(list, NT_PROCSTAT_PROC,
1555 __elfN(note_procstat_proc), p);
1556 size += register_note(list, NT_PROCSTAT_FILES,
1557 note_procstat_files, p);
1558 size += register_note(list, NT_PROCSTAT_VMMAP,
1559 note_procstat_vmmap, p);
1560 size += register_note(list, NT_PROCSTAT_GROUPS,
1561 note_procstat_groups, p);
1562 size += register_note(list, NT_PROCSTAT_UMASK,
1563 note_procstat_umask, p);
1564 size += register_note(list, NT_PROCSTAT_RLIMIT,
1565 note_procstat_rlimit, p);
1566 size += register_note(list, NT_PROCSTAT_OSREL,
1567 note_procstat_osrel, p);
1568 size += register_note(list, NT_PROCSTAT_PSSTRINGS,
1569 __elfN(note_procstat_psstrings), p);
1570 size += register_note(list, NT_PROCSTAT_AUXV,
1571 __elfN(note_procstat_auxv), p);
1577 __elfN(puthdr)(struct thread *td, void *hdr, size_t hdrsize, int numsegs,
1582 struct phdr_closure phc;
1584 ehdr = (Elf_Ehdr *)hdr;
1585 phdr = (Elf_Phdr *)((char *)hdr + sizeof(Elf_Ehdr));
1587 ehdr->e_ident[EI_MAG0] = ELFMAG0;
1588 ehdr->e_ident[EI_MAG1] = ELFMAG1;
1589 ehdr->e_ident[EI_MAG2] = ELFMAG2;
1590 ehdr->e_ident[EI_MAG3] = ELFMAG3;
1591 ehdr->e_ident[EI_CLASS] = ELF_CLASS;
1592 ehdr->e_ident[EI_DATA] = ELF_DATA;
1593 ehdr->e_ident[EI_VERSION] = EV_CURRENT;
1594 ehdr->e_ident[EI_OSABI] = ELFOSABI_FREEBSD;
1595 ehdr->e_ident[EI_ABIVERSION] = 0;
1596 ehdr->e_ident[EI_PAD] = 0;
1597 ehdr->e_type = ET_CORE;
1598 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
1599 ehdr->e_machine = ELF_ARCH32;
1601 ehdr->e_machine = ELF_ARCH;
1603 ehdr->e_version = EV_CURRENT;
1605 ehdr->e_phoff = sizeof(Elf_Ehdr);
1607 ehdr->e_ehsize = sizeof(Elf_Ehdr);
1608 ehdr->e_phentsize = sizeof(Elf_Phdr);
1609 ehdr->e_phnum = numsegs + 1;
1610 ehdr->e_shentsize = sizeof(Elf_Shdr);
1612 ehdr->e_shstrndx = SHN_UNDEF;
1615 * Fill in the program header entries.
1618 /* The note segement. */
1619 phdr->p_type = PT_NOTE;
1620 phdr->p_offset = hdrsize;
1623 phdr->p_filesz = notesz;
1625 phdr->p_flags = PF_R;
1626 phdr->p_align = ELF_NOTE_ROUNDSIZE;
1629 /* All the writable segments from the program. */
1631 phc.offset = round_page(hdrsize + notesz);
1632 each_writable_segment(td, cb_put_phdr, &phc);
1636 register_note(struct note_info_list *list, int type, outfunc_t out, void *arg)
1638 struct note_info *ninfo;
1639 size_t size, notesize;
1642 out(arg, NULL, &size);
1643 ninfo = malloc(sizeof(*ninfo), M_TEMP, M_ZERO | M_WAITOK);
1645 ninfo->outfunc = out;
1646 ninfo->outarg = arg;
1647 ninfo->outsize = size;
1648 TAILQ_INSERT_TAIL(list, ninfo, link);
1653 notesize = sizeof(Elf_Note) + /* note header */
1654 roundup2(sizeof(FREEBSD_ABI_VENDOR), ELF_NOTE_ROUNDSIZE) +
1656 roundup2(size, ELF_NOTE_ROUNDSIZE); /* note description */
1662 append_note_data(const void *src, void *dst, size_t len)
1666 padded_len = roundup2(len, ELF_NOTE_ROUNDSIZE);
1668 bcopy(src, dst, len);
1669 bzero((char *)dst + len, padded_len - len);
1671 return (padded_len);
1675 __elfN(populate_note)(int type, void *src, void *dst, size_t size, void **descp)
1683 note = (Elf_Note *)buf;
1684 note->n_namesz = sizeof(FREEBSD_ABI_VENDOR);
1685 note->n_descsz = size;
1686 note->n_type = type;
1687 buf += sizeof(*note);
1688 buf += append_note_data(FREEBSD_ABI_VENDOR, buf,
1689 sizeof(FREEBSD_ABI_VENDOR));
1690 append_note_data(src, buf, size);
1695 notesize = sizeof(Elf_Note) + /* note header */
1696 roundup2(sizeof(FREEBSD_ABI_VENDOR), ELF_NOTE_ROUNDSIZE) +
1698 roundup2(size, ELF_NOTE_ROUNDSIZE); /* note description */
1704 __elfN(putnote)(struct note_info *ninfo, struct sbuf *sb)
1707 ssize_t old_len, sect_len;
1708 size_t new_len, descsz, i;
1710 if (ninfo->type == -1) {
1711 ninfo->outfunc(ninfo->outarg, sb, &ninfo->outsize);
1715 note.n_namesz = sizeof(FREEBSD_ABI_VENDOR);
1716 note.n_descsz = ninfo->outsize;
1717 note.n_type = ninfo->type;
1719 sbuf_bcat(sb, ¬e, sizeof(note));
1720 sbuf_start_section(sb, &old_len);
1721 sbuf_bcat(sb, FREEBSD_ABI_VENDOR, sizeof(FREEBSD_ABI_VENDOR));
1722 sbuf_end_section(sb, old_len, ELF_NOTE_ROUNDSIZE, 0);
1723 if (note.n_descsz == 0)
1725 sbuf_start_section(sb, &old_len);
1726 ninfo->outfunc(ninfo->outarg, sb, &ninfo->outsize);
1727 sect_len = sbuf_end_section(sb, old_len, ELF_NOTE_ROUNDSIZE, 0);
1731 new_len = (size_t)sect_len;
1732 descsz = roundup(note.n_descsz, ELF_NOTE_ROUNDSIZE);
1733 if (new_len < descsz) {
1735 * It is expected that individual note emitters will correctly
1736 * predict their expected output size and fill up to that size
1737 * themselves, padding in a format-specific way if needed.
1738 * However, in case they don't, just do it here with zeros.
1740 for (i = 0; i < descsz - new_len; i++)
1742 } else if (new_len > descsz) {
1744 * We can't always truncate sb -- we may have drained some
1747 KASSERT(new_len == descsz, ("%s: Note type %u changed as we "
1748 "read it (%zu > %zu). Since it is longer than "
1749 "expected, this coredump's notes are corrupt. THIS "
1750 "IS A BUG in the note_procstat routine for type %u.\n",
1751 __func__, (unsigned)note.n_type, new_len, descsz,
1752 (unsigned)note.n_type));
1757 * Miscellaneous note out functions.
1760 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
1761 #include <compat/freebsd32/freebsd32.h>
1763 typedef struct prstatus32 elf_prstatus_t;
1764 typedef struct prpsinfo32 elf_prpsinfo_t;
1765 typedef struct fpreg32 elf_prfpregset_t;
1766 typedef struct fpreg32 elf_fpregset_t;
1767 typedef struct reg32 elf_gregset_t;
1768 typedef struct thrmisc32 elf_thrmisc_t;
1769 #define ELF_KERN_PROC_MASK KERN_PROC_MASK32
1770 typedef struct kinfo_proc32 elf_kinfo_proc_t;
1771 typedef uint32_t elf_ps_strings_t;
1773 typedef prstatus_t elf_prstatus_t;
1774 typedef prpsinfo_t elf_prpsinfo_t;
1775 typedef prfpregset_t elf_prfpregset_t;
1776 typedef prfpregset_t elf_fpregset_t;
1777 typedef gregset_t elf_gregset_t;
1778 typedef thrmisc_t elf_thrmisc_t;
1779 #define ELF_KERN_PROC_MASK 0
1780 typedef struct kinfo_proc elf_kinfo_proc_t;
1781 typedef vm_offset_t elf_ps_strings_t;
1785 __elfN(note_prpsinfo)(void *arg, struct sbuf *sb, size_t *sizep)
1791 elf_prpsinfo_t *psinfo;
1794 p = (struct proc *)arg;
1796 KASSERT(*sizep == sizeof(*psinfo), ("invalid size"));
1797 psinfo = malloc(sizeof(*psinfo), M_TEMP, M_ZERO | M_WAITOK);
1798 psinfo->pr_version = PRPSINFO_VERSION;
1799 psinfo->pr_psinfosz = sizeof(elf_prpsinfo_t);
1800 strlcpy(psinfo->pr_fname, p->p_comm, sizeof(psinfo->pr_fname));
1802 if (p->p_args != NULL) {
1803 len = sizeof(psinfo->pr_psargs) - 1;
1804 if (len > p->p_args->ar_length)
1805 len = p->p_args->ar_length;
1806 memcpy(psinfo->pr_psargs, p->p_args->ar_args, len);
1812 sbuf_new(&sbarg, psinfo->pr_psargs,
1813 sizeof(psinfo->pr_psargs), SBUF_FIXEDLEN);
1814 error = proc_getargv(curthread, p, &sbarg);
1816 if (sbuf_finish(&sbarg) == 0)
1817 len = sbuf_len(&sbarg) - 1;
1819 len = sizeof(psinfo->pr_psargs) - 1;
1820 sbuf_delete(&sbarg);
1822 if (error || len == 0)
1823 strlcpy(psinfo->pr_psargs, p->p_comm,
1824 sizeof(psinfo->pr_psargs));
1826 KASSERT(len < sizeof(psinfo->pr_psargs),
1827 ("len is too long: %zu vs %zu", len,
1828 sizeof(psinfo->pr_psargs)));
1829 cp = psinfo->pr_psargs;
1832 cp = memchr(cp, '\0', end - cp);
1838 psinfo->pr_pid = p->p_pid;
1839 sbuf_bcat(sb, psinfo, sizeof(*psinfo));
1840 free(psinfo, M_TEMP);
1842 *sizep = sizeof(*psinfo);
1846 __elfN(note_prstatus)(void *arg, struct sbuf *sb, size_t *sizep)
1849 elf_prstatus_t *status;
1851 td = (struct thread *)arg;
1853 KASSERT(*sizep == sizeof(*status), ("invalid size"));
1854 status = malloc(sizeof(*status), M_TEMP, M_ZERO | M_WAITOK);
1855 status->pr_version = PRSTATUS_VERSION;
1856 status->pr_statussz = sizeof(elf_prstatus_t);
1857 status->pr_gregsetsz = sizeof(elf_gregset_t);
1858 status->pr_fpregsetsz = sizeof(elf_fpregset_t);
1859 status->pr_osreldate = osreldate;
1860 status->pr_cursig = td->td_proc->p_sig;
1861 status->pr_pid = td->td_tid;
1862 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
1863 fill_regs32(td, &status->pr_reg);
1865 fill_regs(td, &status->pr_reg);
1867 sbuf_bcat(sb, status, sizeof(*status));
1868 free(status, M_TEMP);
1870 *sizep = sizeof(*status);
1874 __elfN(note_fpregset)(void *arg, struct sbuf *sb, size_t *sizep)
1877 elf_prfpregset_t *fpregset;
1879 td = (struct thread *)arg;
1881 KASSERT(*sizep == sizeof(*fpregset), ("invalid size"));
1882 fpregset = malloc(sizeof(*fpregset), M_TEMP, M_ZERO | M_WAITOK);
1883 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
1884 fill_fpregs32(td, fpregset);
1886 fill_fpregs(td, fpregset);
1888 sbuf_bcat(sb, fpregset, sizeof(*fpregset));
1889 free(fpregset, M_TEMP);
1891 *sizep = sizeof(*fpregset);
1895 __elfN(note_thrmisc)(void *arg, struct sbuf *sb, size_t *sizep)
1898 elf_thrmisc_t thrmisc;
1900 td = (struct thread *)arg;
1902 KASSERT(*sizep == sizeof(thrmisc), ("invalid size"));
1903 bzero(&thrmisc._pad, sizeof(thrmisc._pad));
1904 strcpy(thrmisc.pr_tname, td->td_name);
1905 sbuf_bcat(sb, &thrmisc, sizeof(thrmisc));
1907 *sizep = sizeof(thrmisc);
1911 * Allow for MD specific notes, as well as any MD
1912 * specific preparations for writing MI notes.
1915 __elfN(note_threadmd)(void *arg, struct sbuf *sb, size_t *sizep)
1921 td = (struct thread *)arg;
1923 if (size != 0 && sb != NULL)
1924 buf = malloc(size, M_TEMP, M_ZERO | M_WAITOK);
1928 __elfN(dump_thread)(td, buf, &size);
1929 KASSERT(sb == NULL || *sizep == size, ("invalid size"));
1930 if (size != 0 && sb != NULL)
1931 sbuf_bcat(sb, buf, size);
1936 #ifdef KINFO_PROC_SIZE
1937 CTASSERT(sizeof(struct kinfo_proc) == KINFO_PROC_SIZE);
1941 __elfN(note_procstat_proc)(void *arg, struct sbuf *sb, size_t *sizep)
1947 p = (struct proc *)arg;
1948 size = sizeof(structsize) + p->p_numthreads *
1949 sizeof(elf_kinfo_proc_t);
1952 KASSERT(*sizep == size, ("invalid size"));
1953 structsize = sizeof(elf_kinfo_proc_t);
1954 sbuf_bcat(sb, &structsize, sizeof(structsize));
1956 kern_proc_out(p, sb, ELF_KERN_PROC_MASK);
1961 #ifdef KINFO_FILE_SIZE
1962 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
1966 note_procstat_files(void *arg, struct sbuf *sb, size_t *sizep)
1969 size_t size, sect_sz, i;
1970 ssize_t start_len, sect_len;
1971 int structsize, filedesc_flags;
1973 if (coredump_pack_fileinfo)
1974 filedesc_flags = KERN_FILEDESC_PACK_KINFO;
1978 p = (struct proc *)arg;
1979 structsize = sizeof(struct kinfo_file);
1982 sb = sbuf_new(NULL, NULL, 128, SBUF_FIXEDLEN);
1983 sbuf_set_drain(sb, sbuf_drain_count, &size);
1984 sbuf_bcat(sb, &structsize, sizeof(structsize));
1986 kern_proc_filedesc_out(p, sb, -1, filedesc_flags);
1991 sbuf_start_section(sb, &start_len);
1993 sbuf_bcat(sb, &structsize, sizeof(structsize));
1995 kern_proc_filedesc_out(p, sb, *sizep - sizeof(structsize),
1998 sect_len = sbuf_end_section(sb, start_len, 0, 0);
2003 KASSERT(sect_sz <= *sizep,
2004 ("kern_proc_filedesc_out did not respect maxlen; "
2005 "requested %zu, got %zu", *sizep - sizeof(structsize),
2006 sect_sz - sizeof(structsize)));
2008 for (i = 0; i < *sizep - sect_sz && sb->s_error == 0; i++)
2013 #ifdef KINFO_VMENTRY_SIZE
2014 CTASSERT(sizeof(struct kinfo_vmentry) == KINFO_VMENTRY_SIZE);
2018 note_procstat_vmmap(void *arg, struct sbuf *sb, size_t *sizep)
2022 int structsize, vmmap_flags;
2024 if (coredump_pack_vmmapinfo)
2025 vmmap_flags = KERN_VMMAP_PACK_KINFO;
2029 p = (struct proc *)arg;
2030 structsize = sizeof(struct kinfo_vmentry);
2033 sb = sbuf_new(NULL, NULL, 128, SBUF_FIXEDLEN);
2034 sbuf_set_drain(sb, sbuf_drain_count, &size);
2035 sbuf_bcat(sb, &structsize, sizeof(structsize));
2037 kern_proc_vmmap_out(p, sb, -1, vmmap_flags);
2042 sbuf_bcat(sb, &structsize, sizeof(structsize));
2044 kern_proc_vmmap_out(p, sb, *sizep - sizeof(structsize),
2050 note_procstat_groups(void *arg, struct sbuf *sb, size_t *sizep)
2056 p = (struct proc *)arg;
2057 size = sizeof(structsize) + p->p_ucred->cr_ngroups * sizeof(gid_t);
2059 KASSERT(*sizep == size, ("invalid size"));
2060 structsize = sizeof(gid_t);
2061 sbuf_bcat(sb, &structsize, sizeof(structsize));
2062 sbuf_bcat(sb, p->p_ucred->cr_groups, p->p_ucred->cr_ngroups *
2069 note_procstat_umask(void *arg, struct sbuf *sb, size_t *sizep)
2075 p = (struct proc *)arg;
2076 size = sizeof(structsize) + sizeof(p->p_fd->fd_cmask);
2078 KASSERT(*sizep == size, ("invalid size"));
2079 structsize = sizeof(p->p_fd->fd_cmask);
2080 sbuf_bcat(sb, &structsize, sizeof(structsize));
2081 sbuf_bcat(sb, &p->p_fd->fd_cmask, sizeof(p->p_fd->fd_cmask));
2087 note_procstat_rlimit(void *arg, struct sbuf *sb, size_t *sizep)
2090 struct rlimit rlim[RLIM_NLIMITS];
2094 p = (struct proc *)arg;
2095 size = sizeof(structsize) + sizeof(rlim);
2097 KASSERT(*sizep == size, ("invalid size"));
2098 structsize = sizeof(rlim);
2099 sbuf_bcat(sb, &structsize, sizeof(structsize));
2101 for (i = 0; i < RLIM_NLIMITS; i++)
2102 lim_rlimit(p, i, &rlim[i]);
2104 sbuf_bcat(sb, rlim, sizeof(rlim));
2110 note_procstat_osrel(void *arg, struct sbuf *sb, size_t *sizep)
2116 p = (struct proc *)arg;
2117 size = sizeof(structsize) + sizeof(p->p_osrel);
2119 KASSERT(*sizep == size, ("invalid size"));
2120 structsize = sizeof(p->p_osrel);
2121 sbuf_bcat(sb, &structsize, sizeof(structsize));
2122 sbuf_bcat(sb, &p->p_osrel, sizeof(p->p_osrel));
2128 __elfN(note_procstat_psstrings)(void *arg, struct sbuf *sb, size_t *sizep)
2131 elf_ps_strings_t ps_strings;
2135 p = (struct proc *)arg;
2136 size = sizeof(structsize) + sizeof(ps_strings);
2138 KASSERT(*sizep == size, ("invalid size"));
2139 structsize = sizeof(ps_strings);
2140 #if defined(COMPAT_FREEBSD32) && __ELF_WORD_SIZE == 32
2141 ps_strings = PTROUT(p->p_sysent->sv_psstrings);
2143 ps_strings = p->p_sysent->sv_psstrings;
2145 sbuf_bcat(sb, &structsize, sizeof(structsize));
2146 sbuf_bcat(sb, &ps_strings, sizeof(ps_strings));
2152 __elfN(note_procstat_auxv)(void *arg, struct sbuf *sb, size_t *sizep)
2158 p = (struct proc *)arg;
2161 sb = sbuf_new(NULL, NULL, 128, SBUF_FIXEDLEN);
2162 sbuf_set_drain(sb, sbuf_drain_count, &size);
2163 sbuf_bcat(sb, &structsize, sizeof(structsize));
2165 proc_getauxv(curthread, p, sb);
2171 structsize = sizeof(Elf_Auxinfo);
2172 sbuf_bcat(sb, &structsize, sizeof(structsize));
2174 proc_getauxv(curthread, p, sb);
2180 __elfN(parse_notes)(struct image_params *imgp, Elf_Brandnote *checknote,
2181 int32_t *osrel, const Elf_Phdr *pnote)
2183 const Elf_Note *note, *note0, *note_end;
2184 const char *note_name;
2189 /* We need some limit, might as well use PAGE_SIZE. */
2190 if (pnote == NULL || pnote->p_filesz > PAGE_SIZE)
2192 ASSERT_VOP_LOCKED(imgp->vp, "parse_notes");
2193 if (pnote->p_offset > PAGE_SIZE ||
2194 pnote->p_filesz > PAGE_SIZE - pnote->p_offset) {
2195 VOP_UNLOCK(imgp->vp, 0);
2196 buf = malloc(pnote->p_filesz, M_TEMP, M_WAITOK);
2197 vn_lock(imgp->vp, LK_EXCLUSIVE | LK_RETRY);
2198 error = vn_rdwr(UIO_READ, imgp->vp, buf, pnote->p_filesz,
2199 pnote->p_offset, UIO_SYSSPACE, IO_NODELOCKED,
2200 curthread->td_ucred, NOCRED, NULL, curthread);
2202 uprintf("i/o error PT_NOTE\n");
2206 note = note0 = (const Elf_Note *)buf;
2207 note_end = (const Elf_Note *)(buf + pnote->p_filesz);
2209 note = note0 = (const Elf_Note *)(imgp->image_header +
2211 note_end = (const Elf_Note *)(imgp->image_header +
2212 pnote->p_offset + pnote->p_filesz);
2215 for (i = 0; i < 100 && note >= note0 && note < note_end; i++) {
2216 if (!aligned(note, Elf32_Addr) || (const char *)note_end -
2217 (const char *)note < sizeof(Elf_Note)) {
2221 if (note->n_namesz != checknote->hdr.n_namesz ||
2222 note->n_descsz != checknote->hdr.n_descsz ||
2223 note->n_type != checknote->hdr.n_type)
2225 note_name = (const char *)(note + 1);
2226 if (note_name + checknote->hdr.n_namesz >=
2227 (const char *)note_end || strncmp(checknote->vendor,
2228 note_name, checknote->hdr.n_namesz) != 0)
2232 * Fetch the osreldate for binary
2233 * from the ELF OSABI-note if necessary.
2235 if ((checknote->flags & BN_TRANSLATE_OSREL) != 0 &&
2236 checknote->trans_osrel != NULL) {
2237 res = checknote->trans_osrel(note, osrel);
2243 note = (const Elf_Note *)((const char *)(note + 1) +
2244 roundup2(note->n_namesz, ELF_NOTE_ROUNDSIZE) +
2245 roundup2(note->n_descsz, ELF_NOTE_ROUNDSIZE));
2254 * Try to find the appropriate ABI-note section for checknote,
2255 * fetch the osreldate for binary from the ELF OSABI-note. Only the
2256 * first page of the image is searched, the same as for headers.
2259 __elfN(check_note)(struct image_params *imgp, Elf_Brandnote *checknote,
2262 const Elf_Phdr *phdr;
2263 const Elf_Ehdr *hdr;
2266 hdr = (const Elf_Ehdr *)imgp->image_header;
2267 phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
2269 for (i = 0; i < hdr->e_phnum; i++) {
2270 if (phdr[i].p_type == PT_NOTE &&
2271 __elfN(parse_notes)(imgp, checknote, osrel, &phdr[i]))
2279 * Tell kern_execve.c about it, with a little help from the linker.
2281 static struct execsw __elfN(execsw) = {
2282 __CONCAT(exec_, __elfN(imgact)),
2283 __XSTRING(__CONCAT(ELF, __ELF_WORD_SIZE))
2285 EXEC_SET(__CONCAT(elf, __ELF_WORD_SIZE), __elfN(execsw));
2287 #ifdef COMPRESS_USER_CORES
2289 * Compress and write out a core segment for a user process.
2291 * 'inbuf' is the starting address of a VM segment in the process' address
2292 * space that is to be compressed and written out to the core file. 'dest_buf'
2293 * is a buffer in the kernel's address space. The segment is copied from
2294 * 'inbuf' to 'dest_buf' first before being processed by the compression
2295 * routine gzwrite(). This copying is necessary because the content of the VM
2296 * segment may change between the compression pass and the crc-computation pass
2297 * in gzwrite(). This is because realtime threads may preempt the UNIX kernel.
2299 * If inbuf is NULL it is assumed that data is already copied to 'dest_buf'.
2302 compress_core (gzFile file, char *inbuf, char *dest_buf, unsigned int len,
2307 unsigned int chunk_len;
2310 if (inbuf != NULL) {
2311 chunk_len = (len > CORE_BUF_SIZE) ? CORE_BUF_SIZE : len;
2312 copyin(inbuf, dest_buf, chunk_len);
2317 len_compressed = gzwrite(file, dest_buf, chunk_len);
2319 EVENTHANDLER_INVOKE(app_coredump_progress, td, len_compressed);
2321 if ((unsigned int)len_compressed != chunk_len) {
2323 "compress_core: length mismatch (0x%x returned, "
2324 "0x%x expected)\n", len_compressed, chunk_len);
2325 EVENTHANDLER_INVOKE(app_coredump_error, td,
2326 "compress_core: length mismatch %x -> %x",
2327 chunk_len, len_compressed);
2337 #endif /* COMPRESS_USER_CORES */
2340 __elfN(trans_prot)(Elf_Word flags)
2346 prot |= VM_PROT_EXECUTE;
2348 prot |= VM_PROT_WRITE;
2350 prot |= VM_PROT_READ;
2351 #if __ELF_WORD_SIZE == 32
2352 #if defined(__amd64__) || defined(__ia64__)
2353 if (i386_read_exec && (flags & PF_R))
2354 prot |= VM_PROT_EXECUTE;
2361 __elfN(untrans_prot)(vm_prot_t prot)
2366 if (prot & VM_PROT_EXECUTE)
2368 if (prot & VM_PROT_READ)
2370 if (prot & VM_PROT_WRITE)