2 * Copyright (c) 1995-1996 Søren Schmidt
3 * Copyright (c) 1996 Peter Wemm
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer
11 * in this position and unchanged.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. The name of the author may not be used to endorse or promote products
16 * derived from this software without specific prior written permission
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 * $FreeBSD: src/sys/kern/imgact_elf.c,v 1.73.2.13 2002/12/28 19:49:41 dillon Exp $
30 * $DragonFly: src/sys/kern/imgact_elf.c,v 1.55 2008/08/17 17:21:36 nth Exp $
33 #include <sys/param.h>
35 #include <sys/fcntl.h>
37 #include <sys/imgact.h>
38 #include <sys/imgact_elf.h>
39 #include <sys/kernel.h>
40 #include <sys/malloc.h>
42 #include <sys/systm.h>
44 #include <sys/nlookup.h>
45 #include <sys/pioctl.h>
46 #include <sys/procfs.h>
47 #include <sys/resourcevar.h>
48 #include <sys/signalvar.h>
50 #include <sys/syscall.h>
51 #include <sys/sysctl.h>
52 #include <sys/sysent.h>
53 #include <sys/vnode.h>
54 #include <sys/eventhandler.h>
56 #include <cpu/lwbuf.h>
59 #include <vm/vm_kern.h>
60 #include <vm/vm_param.h>
63 #include <vm/vm_map.h>
64 #include <vm/vm_object.h>
65 #include <vm/vm_extern.h>
67 #include <machine/elf.h>
68 #include <machine/md_var.h>
69 #include <sys/mount.h>
71 #define OLD_EI_BRAND 8
76 static int elf_check_header (const Elf_Ehdr *hdr);
77 static int elf_freebsd_fixup (register_t **stack_base,
78 struct image_params *imgp);
79 static int elf_load_file (struct proc *p, const char *file, u_long *addr,
81 static int elf_load_section (struct proc *p,
82 struct vmspace *vmspace, struct vnode *vp,
83 vm_offset_t offset, caddr_t vmaddr, size_t memsz, size_t filsz,
85 static int exec_elf_imgact (struct image_params *imgp);
87 static int elf_trace = 0;
88 SYSCTL_INT(_debug, OID_AUTO, elf_trace, CTLFLAG_RW, &elf_trace, 0, "");
89 static int elf_legacy_coredump = 0;
90 SYSCTL_INT(_debug, OID_AUTO, elf_legacy_coredump, CTLFLAG_RW,
91 &elf_legacy_coredump, 0,
92 "Do not dump inaccessible mappings, legacy coredump mode");
94 static int dragonfly_match_abi_note(const Elf_Note *);
95 static int freebsd_match_abi_note(const Elf_Note *);
97 static struct sysentvec elf_freebsd_sysvec = {
111 #if defined(__x86_64__)
121 static Elf_Brandinfo freebsd_brand_info = {
124 freebsd_match_abi_note,
126 "/usr/libexec/ld-elf.so.1",
130 static Elf_Brandinfo dragonfly_brand_info = {
133 dragonfly_match_abi_note,
135 "/usr/libexec/ld-elf.so.2",
139 static Elf_Brandinfo *elf_brand_list[MAX_BRANDS] = {
140 &dragonfly_brand_info,
147 freebsd_match_abi_note(const Elf_Note *abi_note)
149 const char *abi_name = (const char *)
150 ((const uint8_t *)abi_note + sizeof(*abi_note));
152 if (abi_note->n_namesz != sizeof("FreeBSD"))
154 if (memcmp(abi_name, "FreeBSD", sizeof("FreeBSD")))
160 dragonfly_match_abi_note(const Elf_Note *abi_note)
162 const char *abi_name = (const char *)
163 ((const uint8_t *)abi_note + sizeof(*abi_note));
165 if (abi_note->n_namesz != sizeof("DragonFly"))
167 if (memcmp(abi_name, "DragonFly", sizeof("DragonFly")))
173 elf_insert_brand_entry(Elf_Brandinfo *entry)
177 for (i=1; i<MAX_BRANDS; i++) {
178 if (elf_brand_list[i] == NULL) {
179 elf_brand_list[i] = entry;
189 elf_remove_brand_entry(Elf_Brandinfo *entry)
193 for (i=1; i<MAX_BRANDS; i++) {
194 if (elf_brand_list[i] == entry) {
195 elf_brand_list[i] = NULL;
205 * Check if an elf brand is being used anywhere in the system.
207 * Used by the linux emulation module unloader. This isn't safe from
210 struct elf_brand_inuse_info {
212 Elf_Brandinfo *entry;
215 static int elf_brand_inuse_callback(struct proc *p, void *data);
218 elf_brand_inuse(Elf_Brandinfo *entry)
220 struct elf_brand_inuse_info info;
224 allproc_scan(elf_brand_inuse_callback, entry);
230 elf_brand_inuse_callback(struct proc *p, void *data)
232 struct elf_brand_inuse_info *info = data;
234 if (p->p_sysent == info->entry->sysvec) {
242 elf_check_header(const Elf_Ehdr *hdr)
245 hdr->e_ident[EI_CLASS] != ELF_TARG_CLASS ||
246 hdr->e_ident[EI_DATA] != ELF_TARG_DATA ||
247 hdr->e_ident[EI_VERSION] != EV_CURRENT ||
248 hdr->e_phentsize != sizeof(Elf_Phdr) ||
249 hdr->e_ehsize != sizeof(Elf_Ehdr) ||
250 hdr->e_version != ELF_TARG_VER)
253 if (!ELF_MACHINE_OK(hdr->e_machine))
259 static Elf_Brandinfo *
260 elf_check_abi_note(struct image_params *imgp, const Elf_Phdr *ph)
262 Elf_Brandinfo *match = NULL;
263 const Elf_Note *tmp_note;
265 struct lwbuf lwb_cache;
276 firstoff = off & PAGE_MASK;
277 firstlen = PAGE_SIZE - firstoff;
279 if (len < sizeof(Elf_Note) || len > PAGE_SIZE)
280 return NULL; /* ENOEXEC? */
283 if (exec_map_page(imgp, off >> PAGE_SHIFT, &lwb, &page))
287 * Crosses page boundary? Is that allowed?
289 if (firstlen < len) {
290 data = kmalloc(len, M_TEMP, M_WAITOK);
292 bcopy(page + firstoff, data, firstlen);
294 exec_unmap_page(lwb);
296 if (exec_map_page(imgp, (off >> PAGE_SHIFT) + 1, &lwb, &page)) {
300 bcopy(page, data + firstlen, len - firstlen);
301 tmp_note = (void *)data;
303 tmp_note = (const void *)(page + firstoff);
306 while (len >= sizeof(Elf_Note)) {
308 size_t nlen = roundup(tmp_note->n_namesz, sizeof(Elf_Word)) +
309 roundup(tmp_note->n_descsz, sizeof(Elf_Word)) +
315 if (tmp_note->n_type != 1)
318 for (i = 0; i < MAX_BRANDS; i++) {
319 Elf_Brandinfo *bi = elf_brand_list[i];
321 if (bi != NULL && bi->match_abi_note != NULL &&
322 bi->match_abi_note(tmp_note)) {
338 exec_unmap_page(lwb);
344 elf_load_section(struct proc *p, struct vmspace *vmspace, struct vnode *vp,
345 vm_offset_t offset, caddr_t vmaddr, size_t memsz,
346 size_t filsz, vm_prot_t prot)
349 vm_offset_t map_addr;
354 vm_offset_t file_addr;
356 object = vp->v_object;
360 * It's necessary to fail if the filsz + offset taken from the
361 * header is greater than the actual file pager object's size.
362 * If we were to allow this, then the vm_map_find() below would
363 * walk right off the end of the file object and into the ether.
365 * While I'm here, might as well check for something else that
366 * is invalid: filsz cannot be greater than memsz.
368 if ((off_t)filsz + offset > vp->v_filesize || filsz > memsz) {
369 uprintf("elf_load_section: truncated ELF file\n");
373 map_addr = trunc_page((vm_offset_t)vmaddr);
374 file_addr = trunc_page(offset);
377 * We have two choices. We can either clear the data in the last page
378 * of an oversized mapping, or we can start the anon mapping a page
379 * early and copy the initialized data into that first page. We
380 * choose the second..
383 map_len = trunc_page(offset+filsz) - file_addr;
385 map_len = round_page(offset+filsz) - file_addr;
388 vm_object_reference(object);
390 /* cow flags: don't dump readonly sections in core */
391 cow = MAP_COPY_ON_WRITE | MAP_PREFAULT |
392 (prot & VM_PROT_WRITE ? 0 : MAP_DISABLE_COREDUMP);
394 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
395 vm_map_lock(&vmspace->vm_map);
396 rv = vm_map_insert(&vmspace->vm_map, &count,
398 file_addr, /* file offset */
399 map_addr, /* virtual start */
400 map_addr + map_len,/* virtual end */
404 vm_map_unlock(&vmspace->vm_map);
405 vm_map_entry_release(count);
406 if (rv != KERN_SUCCESS) {
407 vm_object_deallocate(object);
411 /* we can stop now if we've covered it all */
412 if (memsz == filsz) {
419 * We have to get the remaining bit of the file into the first part
420 * of the oversized map segment. This is normally because the .data
421 * segment in the file is extended to provide bss. It's a neat idea
422 * to try and save a page, but it's a pain in the behind to implement.
424 copy_len = (offset + filsz) - trunc_page(offset + filsz);
425 map_addr = trunc_page((vm_offset_t)vmaddr + filsz);
426 map_len = round_page((vm_offset_t)vmaddr + memsz) - map_addr;
428 /* This had damn well better be true! */
430 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
431 vm_map_lock(&vmspace->vm_map);
432 rv = vm_map_insert(&vmspace->vm_map, &count,
434 map_addr, map_addr + map_len,
436 VM_PROT_ALL, VM_PROT_ALL,
438 vm_map_unlock(&vmspace->vm_map);
439 vm_map_entry_release(count);
440 if (rv != KERN_SUCCESS) {
448 struct lwbuf lwb_cache;
450 m = vm_fault_object_page(object, trunc_page(offset + filsz),
451 VM_PROT_READ, 0, &error);
453 lwb = lwbuf_alloc(m, &lwb_cache);
454 error = copyout((caddr_t)lwbuf_kva(lwb),
455 (caddr_t)map_addr, copy_len);
465 * set it to the specified protection
467 vm_map_protect(&vmspace->vm_map, map_addr, map_addr + map_len, prot,
474 * Load the file "file" into memory. It may be either a shared object
477 * The "addr" reference parameter is in/out. On entry, it specifies
478 * the address where a shared object should be loaded. If the file is
479 * an executable, this value is ignored. On exit, "addr" specifies
480 * where the file was actually loaded.
482 * The "entry" reference parameter is out only. On exit, it specifies
483 * the entry point for the loaded file.
486 elf_load_file(struct proc *p, const char *file, u_long *addr, u_long *entry)
489 struct nlookupdata nd;
491 struct image_params image_params;
493 const Elf_Ehdr *hdr = NULL;
494 const Elf_Phdr *phdr = NULL;
495 struct nlookupdata *nd;
496 struct vmspace *vmspace = p->p_vmspace;
498 struct image_params *imgp;
499 struct mount *topmnt;
502 u_long base_addr = 0;
503 int error, i, numsegs;
505 tempdata = kmalloc(sizeof(*tempdata), M_TEMP, M_WAITOK);
507 attr = &tempdata->attr;
508 imgp = &tempdata->image_params;
511 * Initialize part of the common data
515 imgp->firstpage = NULL;
516 imgp->image_header = NULL;
519 error = nlookup_init(nd, file, UIO_SYSSPACE, NLC_FOLLOW);
523 error = cache_vget(&nd->nl_nch, nd->nl_cred, LK_EXCLUSIVE, &imgp->vp);
524 topmnt = nd->nl_nch.mount;
530 * Check permissions, modes, uid, etc on the file, and "open" it.
532 error = exec_check_permissions(imgp, topmnt);
538 error = exec_map_first_page(imgp);
540 * Also make certain that the interpreter stays the same, so set
541 * its VTEXT flag, too.
544 vsetflags(imgp->vp, VTEXT);
549 hdr = (const Elf_Ehdr *)imgp->image_header;
550 if ((error = elf_check_header(hdr)) != 0)
552 if (hdr->e_type == ET_DYN)
554 else if (hdr->e_type == ET_EXEC)
561 /* Only support headers that fit within first page for now
562 * (multiplication of two Elf_Half fields will not overflow) */
563 if ((hdr->e_phoff > PAGE_SIZE) ||
564 (hdr->e_phentsize * hdr->e_phnum) > PAGE_SIZE - hdr->e_phoff) {
569 phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
571 for (i = 0, numsegs = 0; i < hdr->e_phnum; i++) {
572 if (phdr[i].p_type == PT_LOAD) { /* Loadable segment */
574 if (phdr[i].p_flags & PF_X)
575 prot |= VM_PROT_EXECUTE;
576 if (phdr[i].p_flags & PF_W)
577 prot |= VM_PROT_WRITE;
578 if (phdr[i].p_flags & PF_R)
579 prot |= VM_PROT_READ;
581 error = elf_load_section(
582 p, vmspace, imgp->vp,
584 (caddr_t)phdr[i].p_vaddr +
587 phdr[i].p_filesz, prot);
591 * Establish the base address if this is the
595 base_addr = trunc_page(phdr[i].p_vaddr + rbase);
600 *entry=(unsigned long)hdr->e_entry + rbase;
604 exec_unmap_first_page(imgp);
609 kfree(tempdata, M_TEMP);
615 * non static, as it can be overridden by start_init()
617 int fallback_elf_brand = -1;
618 SYSCTL_INT(_kern, OID_AUTO, fallback_elf_brand, CTLFLAG_RW,
619 &fallback_elf_brand, -1,
620 "ELF brand of last resort");
622 static int can_exec_dyn = 1;
623 SYSCTL_INT(_kern, OID_AUTO, elf_exec_dyn, CTLFLAG_RW,
625 "ELF: can exec shared libraries");
628 exec_elf_imgact(struct image_params *imgp)
630 const Elf_Ehdr *hdr = (const Elf_Ehdr *) imgp->image_header;
631 const Elf_Phdr *phdr;
632 Elf_Auxargs *elf_auxargs = NULL;
633 struct vmspace *vmspace;
635 u_long text_size = 0, data_size = 0, total_size = 0;
636 u_long text_addr = 0, data_addr = 0;
637 u_long seg_size, seg_addr;
638 u_long addr, entry = 0, proghdr = 0;
640 const char *interp = NULL;
641 const Elf_Note *abi_note = NULL;
642 Elf_Brandinfo *brand_info = NULL;
648 * Do we have a valid ELF header ?
649 * We allow execution of ET_EXEC and, if kern.elf_exec_dyn is 1, ET_DYN.
651 if (elf_check_header(hdr) != 0 ||
652 (hdr->e_type != ET_EXEC && (!can_exec_dyn || hdr->e_type != ET_DYN)))
656 * From here on down, we return an errno, not -1, as we've
657 * detected an ELF file.
660 if ((hdr->e_phoff > PAGE_SIZE) ||
661 (hdr->e_phoff + hdr->e_phentsize * hdr->e_phnum) > PAGE_SIZE) {
662 /* Only support headers in first page for now */
665 phdr = (const Elf_Phdr*)(imgp->image_header + hdr->e_phoff);
668 * From this point on, we may have resources that need to be freed.
671 exec_new_vmspace(imgp, NULL);
674 * Yeah, I'm paranoid. There is every reason in the world to get
675 * VTEXT now since from here on out, there are places we can have
676 * a context switch. Better safe than sorry; I really don't want
677 * the file to change while it's being loaded.
679 vsetflags(imgp->vp, VTEXT);
681 vmspace = imgp->proc->p_vmspace;
683 for (i = 0; i < hdr->e_phnum; i++) {
684 switch(phdr[i].p_type) {
686 case PT_LOAD: /* Loadable segment */
688 if (phdr[i].p_flags & PF_X)
689 prot |= VM_PROT_EXECUTE;
690 if (phdr[i].p_flags & PF_W)
691 prot |= VM_PROT_WRITE;
692 if (phdr[i].p_flags & PF_R)
693 prot |= VM_PROT_READ;
695 if ((error = elf_load_section(imgp->proc,
698 (caddr_t)phdr[i].p_vaddr,
700 phdr[i].p_filesz, prot)) != 0)
704 * If this segment contains the program headers,
705 * remember their virtual address for the AT_PHDR
706 * aux entry. Static binaries don't usually include
709 if (phdr[i].p_offset == 0 &&
710 hdr->e_phoff + hdr->e_phnum * hdr->e_phentsize
712 proghdr = phdr[i].p_vaddr + hdr->e_phoff;
714 seg_addr = trunc_page(phdr[i].p_vaddr);
715 seg_size = round_page(phdr[i].p_memsz +
716 phdr[i].p_vaddr - seg_addr);
719 * Is this .text or .data? We can't use
720 * VM_PROT_WRITE or VM_PROT_EXEC, it breaks the
721 * alpha terribly and possibly does other bad
722 * things so we stick to the old way of figuring
723 * it out: If the segment contains the program
724 * entry point, it's a text segment, otherwise it
727 * Note that obreak() assumes that data_addr +
728 * data_size == end of data load area, and the ELF
729 * file format expects segments to be sorted by
730 * address. If multiple data segments exist, the
731 * last one will be used.
733 if (hdr->e_entry >= phdr[i].p_vaddr &&
734 hdr->e_entry < (phdr[i].p_vaddr +
736 text_size = seg_size;
737 text_addr = seg_addr;
738 entry = (u_long)hdr->e_entry;
740 data_size = seg_size;
741 data_addr = seg_addr;
743 total_size += seg_size;
746 * Check limits. It should be safe to check the
747 * limits after loading the segment since we do
748 * not actually fault in all the segment's pages.
751 imgp->proc->p_rlimit[RLIMIT_DATA].rlim_cur ||
752 text_size > maxtsiz ||
754 imgp->proc->p_rlimit[RLIMIT_VMEM].rlim_cur) {
759 case PT_INTERP: /* Path to interpreter */
760 if (phdr[i].p_filesz > MAXPATHLEN ||
761 phdr[i].p_offset + phdr[i].p_filesz > PAGE_SIZE) {
765 interp = imgp->image_header + phdr[i].p_offset;
767 case PT_NOTE: /* Check for .note.ABI-tag */
768 if (brand_info == NULL)
769 brand_info = elf_check_abi_note(imgp, &phdr[i]);
771 case PT_PHDR: /* Program header table info */
772 proghdr = phdr[i].p_vaddr;
779 vmspace->vm_tsize = text_size >> PAGE_SHIFT;
780 vmspace->vm_taddr = (caddr_t)(uintptr_t)text_addr;
781 vmspace->vm_dsize = data_size >> PAGE_SHIFT;
782 vmspace->vm_daddr = (caddr_t)(uintptr_t)data_addr;
784 addr = ELF_RTLD_ADDR(vmspace);
786 imgp->entry_addr = entry;
788 /* We support three types of branding -- (1) the ELF EI_OSABI field
789 * that SCO added to the ELF spec, (2) FreeBSD 3.x's traditional string
790 * branding w/in the ELF header, and (3) path of the `interp_path'
791 * field. We should also look for an ".note.ABI-tag" ELF section now
792 * in all Linux ELF binaries, FreeBSD 4.1+, and some NetBSD ones.
795 /* If the executable has a brand, search for it in the brand list. */
796 if (brand_info == NULL && hdr->e_ident[EI_OSABI] != ELFOSABI_NONE) {
797 for (i = 0; i < MAX_BRANDS; i++) {
798 Elf_Brandinfo *bi = elf_brand_list[i];
801 (hdr->e_ident[EI_OSABI] == bi->brand
803 strncmp((const char *)&hdr->e_ident[OLD_EI_BRAND],
804 bi->compat_3_brand, strlen(bi->compat_3_brand)))) {
811 /* Search for a recognized ABI. */
812 if (brand_info == NULL && abi_note != NULL) {
816 * ELFOSABI_NONE == ELFOSABI_SYSV, so a SYSV binary misses all
817 * checks so far, since it is neither branded nor does it have
818 * an ABI note. If the EI_OSABI field is ELFOSABI_NONE, assume
819 * it is svr4 and look for an entry in the elf_brand_list with
820 * match_abi_note == NULL.
822 if (brand_info == NULL && hdr->e_ident[EI_OSABI] == ELFOSABI_NONE) {
823 for (i = 0; i < MAX_BRANDS; i++) {
824 Elf_Brandinfo *bi = elf_brand_list[i];
826 if (bi != NULL && bi->match_abi_note == NULL &&
827 ELFOSABI_SYSV == bi->brand) {
834 /* Lacking a recognized ABI, search for a recognized interpreter. */
835 if (brand_info == NULL && interp != NULL) {
836 for (i = 0; i < MAX_BRANDS; i++) {
837 Elf_Brandinfo *bi = elf_brand_list[i];
840 strcmp(interp, bi->interp_path) == 0) {
847 /* Lacking a recognized interpreter, try the default brand */
848 if (brand_info == NULL) {
849 for (i = 0; i < MAX_BRANDS; i++) {
850 Elf_Brandinfo *bi = elf_brand_list[i];
852 if (bi != NULL && fallback_elf_brand == bi->brand) {
859 if (brand_info == NULL) {
860 uprintf("ELF binary type \"%u\" not known.\n",
861 hdr->e_ident[EI_OSABI]);
866 imgp->proc->p_sysent = brand_info->sysvec;
867 EVENTHANDLER_INVOKE(process_exec, imgp);
869 if (interp != NULL) {
870 path = kmalloc(MAXPATHLEN, M_TEMP, M_WAITOK);
871 ksnprintf(path, MAXPATHLEN, "%s%s",
872 brand_info->emul_path, interp);
873 if ((error = elf_load_file(imgp->proc, path, &addr,
874 &imgp->entry_addr)) != 0) {
875 if ((error = elf_load_file(imgp->proc, interp, &addr,
876 &imgp->entry_addr)) != 0) {
877 uprintf("ELF interpreter %s not found\n", path);
888 * Construct auxargs table (used by the fixup routine)
890 elf_auxargs = kmalloc(sizeof(Elf_Auxargs), M_TEMP, M_WAITOK);
891 elf_auxargs->execfd = -1;
892 elf_auxargs->phdr = proghdr;
893 elf_auxargs->phent = hdr->e_phentsize;
894 elf_auxargs->phnum = hdr->e_phnum;
895 elf_auxargs->pagesz = PAGE_SIZE;
896 elf_auxargs->base = addr;
897 elf_auxargs->flags = 0;
898 elf_auxargs->entry = entry;
899 elf_auxargs->trace = elf_trace;
901 imgp->auxargs = elf_auxargs;
902 imgp->interpreted = 0;
909 elf_freebsd_fixup(register_t **stack_base, struct image_params *imgp)
911 Elf_Auxargs *args = (Elf_Auxargs *)imgp->auxargs;
914 pos = *stack_base + (imgp->args->argc + imgp->args->envc + 2);
917 AUXARGS_ENTRY(pos, AT_DEBUG, 1);
919 if (args->execfd != -1) {
920 AUXARGS_ENTRY(pos, AT_EXECFD, args->execfd);
922 AUXARGS_ENTRY(pos, AT_PHDR, args->phdr);
923 AUXARGS_ENTRY(pos, AT_PHENT, args->phent);
924 AUXARGS_ENTRY(pos, AT_PHNUM, args->phnum);
925 AUXARGS_ENTRY(pos, AT_PAGESZ, args->pagesz);
926 AUXARGS_ENTRY(pos, AT_FLAGS, args->flags);
927 AUXARGS_ENTRY(pos, AT_ENTRY, args->entry);
928 AUXARGS_ENTRY(pos, AT_BASE, args->base);
929 if (imgp->execpathp != 0)
930 AUXARGS_ENTRY(pos, AT_EXECPATH, imgp->execpathp);
931 AUXARGS_ENTRY(pos, AT_NULL, 0);
933 kfree(imgp->auxargs, M_TEMP);
934 imgp->auxargs = NULL;
937 suword(*stack_base, (long) imgp->args->argc);
942 * Code for generating ELF core dumps.
945 typedef int (*segment_callback) (vm_map_entry_t, void *);
947 /* Closure for cb_put_phdr(). */
948 struct phdr_closure {
949 Elf_Phdr *phdr; /* Program header to fill in (incremented) */
950 Elf_Phdr *phdr_max; /* Pointer bound for error check */
951 Elf_Off offset; /* Offset of segment in core file */
954 /* Closure for cb_size_segment(). */
955 struct sseg_closure {
956 int count; /* Count of writable segments. */
957 size_t vsize; /* Total size of all writable segments. */
960 /* Closure for cb_put_fp(). */
963 struct vn_hdr *vnh_max;
968 typedef struct elf_buf {
974 static void *target_reserve(elf_buf_t target, size_t bytes, int *error);
976 static int cb_put_phdr (vm_map_entry_t, void *);
977 static int cb_size_segment (vm_map_entry_t, void *);
978 static int cb_fpcount_segment(vm_map_entry_t, void *);
979 static int cb_put_fp(vm_map_entry_t, void *);
982 static int each_segment (struct proc *, segment_callback, void *, int);
983 static int elf_corehdr (struct lwp *, int, struct file *, struct ucred *,
985 enum putmode { WRITE, DRYRUN };
986 static int elf_puthdr (struct lwp *, elf_buf_t, int sig, enum putmode,
988 static int elf_putallnotes(struct lwp *, elf_buf_t, int, enum putmode);
989 static int elf_putnote (elf_buf_t, const char *, int, const void *, size_t);
991 static int elf_putsigs(struct lwp *, elf_buf_t);
992 static int elf_puttextvp(struct proc *, elf_buf_t);
993 static int elf_putfiles(struct proc *, elf_buf_t, struct file *);
995 extern int osreldate;
998 elf_coredump(struct lwp *lp, int sig, struct vnode *vp, off_t limit)
1003 if ((error = falloc(NULL, &fp, NULL)) != 0)
1005 fsetcred(fp, lp->lwp_proc->p_ucred);
1010 fp->f_type = DTYPE_VNODE;
1011 fp->f_flag = O_CREAT|O_WRONLY|O_NOFOLLOW;
1012 fp->f_ops = &vnode_fileops;
1016 error = generic_elf_coredump(lp, sig, fp, limit);
1020 fp->f_ops = &badfileops;
1027 generic_elf_coredump(struct lwp *lp, int sig, struct file *fp, off_t limit)
1029 struct proc *p = lp->lwp_proc;
1030 struct ucred *cred = p->p_ucred;
1032 struct sseg_closure seginfo;
1033 struct elf_buf target;
1036 kprintf("can't dump core - null fp\n");
1039 * Size the program segments
1043 each_segment(p, cb_size_segment, &seginfo, 1);
1046 * Calculate the size of the core file header area by making
1047 * a dry run of generating it. Nothing is written, but the
1048 * size is calculated.
1050 bzero(&target, sizeof(target));
1051 elf_puthdr(lp, &target, sig, DRYRUN, seginfo.count, fp);
1053 if (target.off + seginfo.vsize >= limit)
1057 * Allocate memory for building the header, fill it up,
1060 target.off_max = target.off;
1062 target.buf = kmalloc(target.off_max, M_TEMP, M_WAITOK|M_ZERO);
1064 error = elf_corehdr(lp, sig, fp, cred, seginfo.count, &target);
1066 /* Write the contents of all of the writable segments. */
1072 php = (Elf_Phdr *)(target.buf + sizeof(Elf_Ehdr)) + 1;
1073 for (i = 0; i < seginfo.count; i++) {
1074 error = fp_write(fp, (caddr_t)php->p_vaddr,
1075 php->p_filesz, &nbytes, UIO_USERSPACE);
1081 kfree(target.buf, M_TEMP);
1087 * A callback for each_segment() to write out the segment's
1088 * program header entry.
1091 cb_put_phdr(vm_map_entry_t entry, void *closure)
1093 struct phdr_closure *phc = closure;
1094 Elf_Phdr *phdr = phc->phdr;
1096 if (phc->phdr == phc->phdr_max)
1099 phc->offset = round_page(phc->offset);
1101 phdr->p_type = PT_LOAD;
1102 phdr->p_offset = phc->offset;
1103 phdr->p_vaddr = entry->start;
1105 phdr->p_filesz = phdr->p_memsz = entry->end - entry->start;
1106 phdr->p_align = PAGE_SIZE;
1108 if (entry->protection & VM_PROT_READ)
1109 phdr->p_flags |= PF_R;
1110 if (entry->protection & VM_PROT_WRITE)
1111 phdr->p_flags |= PF_W;
1112 if (entry->protection & VM_PROT_EXECUTE)
1113 phdr->p_flags |= PF_X;
1115 phc->offset += phdr->p_filesz;
1121 * A callback for each_writable_segment() to gather information about
1122 * the number of segments and their total size.
1125 cb_size_segment(vm_map_entry_t entry, void *closure)
1127 struct sseg_closure *ssc = closure;
1130 ssc->vsize += entry->end - entry->start;
1135 * A callback for each_segment() to gather information about
1136 * the number of text segments.
1139 cb_fpcount_segment(vm_map_entry_t entry, void *closure)
1141 int *count = closure;
1144 if (entry->object.vm_object->type == OBJT_VNODE) {
1145 vp = (struct vnode *)entry->object.vm_object->handle;
1146 if ((vp->v_flag & VCKPT) && curproc->p_textvp == vp)
1154 cb_put_fp(vm_map_entry_t entry, void *closure)
1156 struct fp_closure *fpc = closure;
1157 struct vn_hdr *vnh = fpc->vnh;
1158 Elf_Phdr *phdr = &vnh->vnh_phdr;
1163 * If an entry represents a vnode then write out a file handle.
1165 * If we are checkpointing a checkpoint-restored program we do
1166 * NOT record the filehandle for the old checkpoint vnode (which
1167 * is mapped all over the place). Instead we rely on the fact
1168 * that a checkpoint-restored program does not mmap() the checkpt
1169 * vnode NOCORE, so its contents will be written out to the
1170 * new checkpoint file. This is necessary because the 'old'
1171 * checkpoint file is typically destroyed when a new one is created
1172 * and thus cannot be used to restore the new checkpoint.
1174 * Theoretically we could create a chain of checkpoint files and
1175 * operate the checkpointing operation kinda like an incremental
1176 * checkpoint, but a checkpoint restore would then likely wind up
1177 * referencing many prior checkpoint files and that is a bit over
1178 * the top for the purpose of the checkpoint API.
1180 if (entry->object.vm_object->type == OBJT_VNODE) {
1181 vp = (struct vnode *)entry->object.vm_object->handle;
1182 if ((vp->v_flag & VCKPT) && curproc->p_textvp == vp)
1184 if (vnh == fpc->vnh_max)
1188 vnh->vnh_fh.fh_fsid = vp->v_mount->mnt_stat.f_fsid;
1189 error = VFS_VPTOFH(vp, &vnh->vnh_fh.fh_fid);
1191 char *freepath, *fullpath;
1193 if (vn_fullpath(curproc, vp, &fullpath, &freepath, 0)) {
1194 kprintf("Warning: coredump, error %d: cannot store file handle for vnode %p\n", error, vp);
1196 kprintf("Warning: coredump, error %d: cannot store file handle for %s\n", error, fullpath);
1197 kfree(freepath, M_TEMP);
1202 phdr->p_type = PT_LOAD;
1203 phdr->p_offset = 0; /* not written to core */
1204 phdr->p_vaddr = entry->start;
1206 phdr->p_filesz = phdr->p_memsz = entry->end - entry->start;
1207 phdr->p_align = PAGE_SIZE;
1209 if (entry->protection & VM_PROT_READ)
1210 phdr->p_flags |= PF_R;
1211 if (entry->protection & VM_PROT_WRITE)
1212 phdr->p_flags |= PF_W;
1213 if (entry->protection & VM_PROT_EXECUTE)
1214 phdr->p_flags |= PF_X;
1222 * For each writable segment in the process's memory map, call the given
1223 * function with a pointer to the map entry and some arbitrary
1224 * caller-supplied data.
1227 each_segment(struct proc *p, segment_callback func, void *closure, int writable)
1230 vm_map_t map = &p->p_vmspace->vm_map;
1231 vm_map_entry_t entry;
1233 for (entry = map->header.next; error == 0 && entry != &map->header;
1234 entry = entry->next) {
1238 * Don't dump inaccessible mappings, deal with legacy
1241 * Note that read-only segments related to the elf binary
1242 * are marked MAP_ENTRY_NOCOREDUMP now so we no longer
1243 * need to arbitrarily ignore such segments.
1245 if (elf_legacy_coredump) {
1246 if (writable && (entry->protection & VM_PROT_RW) != VM_PROT_RW)
1249 if (writable && (entry->protection & VM_PROT_ALL) == 0)
1254 * Dont include memory segment in the coredump if
1255 * MAP_NOCORE is set in mmap(2) or MADV_NOCORE in
1258 * Currently we only dump normal VM object maps. We do
1259 * not dump submaps or virtual page tables.
1261 if (writable && (entry->eflags & MAP_ENTRY_NOCOREDUMP))
1263 if (entry->maptype != VM_MAPTYPE_NORMAL)
1265 if ((obj = entry->object.vm_object) == NULL)
1268 /* Find the deepest backing object. */
1269 while (obj->backing_object != NULL)
1270 obj = obj->backing_object;
1272 /* Ignore memory-mapped devices and such things. */
1273 if (obj->type != OBJT_DEFAULT &&
1274 obj->type != OBJT_SWAP &&
1275 obj->type != OBJT_VNODE)
1278 error = (*func)(entry, closure);
1285 target_reserve(elf_buf_t target, size_t bytes, int *error)
1290 if (target->off + bytes > target->off_max)
1293 res = target->buf + target->off;
1295 target->off += bytes;
1300 * Write the core file header to the file, including padding up to
1301 * the page boundary.
1304 elf_corehdr(struct lwp *lp, int sig, struct file *fp, struct ucred *cred,
1305 int numsegs, elf_buf_t target)
1311 * Fill in the header. The fp is passed so we can detect and flag
1312 * a checkpoint file pointer within the core file itself, because
1313 * it may not be restored from the same file handle.
1315 error = elf_puthdr(lp, target, sig, WRITE, numsegs, fp);
1317 /* Write it to the core file. */
1319 error = fp_write(fp, target->buf, target->off, &nbytes,
1326 elf_puthdr(struct lwp *lp, elf_buf_t target, int sig, enum putmode mode,
1327 int numsegs, struct file *fp)
1329 struct proc *p = lp->lwp_proc;
1337 ehdr = target_reserve(target, sizeof(Elf_Ehdr), &error);
1339 phoff = target->off;
1340 phdr = target_reserve(target, (numsegs + 1) * sizeof(Elf_Phdr), &error);
1342 noteoff = target->off;
1344 elf_putallnotes(lp, target, sig, mode);
1345 notesz = target->off - noteoff;
1348 * put extra cruft for dumping process state here
1349 * - we really want it be before all the program
1351 * - we just need to update the offset accordingly
1352 * and GDB will be none the wiser.
1355 error = elf_puttextvp(p, target);
1357 error = elf_putsigs(lp, target);
1359 error = elf_putfiles(p, target, fp);
1362 * Align up to a page boundary for the program segments. The
1363 * actual data will be written to the outptu file, not to elf_buf_t,
1364 * so we do not have to do any further bounds checking.
1366 target->off = round_page(target->off);
1367 if (error == 0 && ehdr != NULL) {
1369 * Fill in the ELF header.
1371 ehdr->e_ident[EI_MAG0] = ELFMAG0;
1372 ehdr->e_ident[EI_MAG1] = ELFMAG1;
1373 ehdr->e_ident[EI_MAG2] = ELFMAG2;
1374 ehdr->e_ident[EI_MAG3] = ELFMAG3;
1375 ehdr->e_ident[EI_CLASS] = ELF_CLASS;
1376 ehdr->e_ident[EI_DATA] = ELF_DATA;
1377 ehdr->e_ident[EI_VERSION] = EV_CURRENT;
1378 ehdr->e_ident[EI_OSABI] = ELFOSABI_NONE;
1379 ehdr->e_ident[EI_ABIVERSION] = 0;
1380 ehdr->e_ident[EI_PAD] = 0;
1381 ehdr->e_type = ET_CORE;
1382 ehdr->e_machine = ELF_ARCH;
1383 ehdr->e_version = EV_CURRENT;
1385 ehdr->e_phoff = phoff;
1387 ehdr->e_ehsize = sizeof(Elf_Ehdr);
1388 ehdr->e_phentsize = sizeof(Elf_Phdr);
1389 ehdr->e_phnum = numsegs + 1;
1390 ehdr->e_shentsize = sizeof(Elf_Shdr);
1392 ehdr->e_shstrndx = SHN_UNDEF;
1394 if (error == 0 && phdr != NULL) {
1396 * Fill in the program header entries.
1398 struct phdr_closure phc;
1400 /* The note segement. */
1401 phdr->p_type = PT_NOTE;
1402 phdr->p_offset = noteoff;
1405 phdr->p_filesz = notesz;
1411 /* All the writable segments from the program. */
1413 phc.phdr_max = phdr + numsegs;
1414 phc.offset = target->off;
1415 each_segment(p, cb_put_phdr, &phc, 1);
1421 * Append core dump notes to target ELF buffer or simply update target size
1422 * if dryrun selected.
1425 elf_putallnotes(struct lwp *corelp, elf_buf_t target, int sig,
1428 struct proc *p = corelp->lwp_proc;
1432 prfpregset_t fpregs;
1436 prfpregset_t *fpregs;
1441 * Allocate temporary storage for notes on heap to avoid stack overflow.
1443 if (mode != DRYRUN) {
1444 tmpdata = kmalloc(sizeof(*tmpdata), M_TEMP, M_ZERO | M_WAITOK);
1445 status = &tmpdata->status;
1446 fpregs = &tmpdata->fpregs;
1447 psinfo = &tmpdata->psinfo;
1456 * Append LWP-agnostic note.
1458 if (mode != DRYRUN) {
1459 psinfo->pr_version = PRPSINFO_VERSION;
1460 psinfo->pr_psinfosz = sizeof(prpsinfo_t);
1461 strncpy(psinfo->pr_fname, p->p_comm,
1462 sizeof(psinfo->pr_fname) - 1);
1464 * XXX - We don't fill in the command line arguments
1467 strncpy(psinfo->pr_psargs, p->p_comm, PRARGSZ);
1470 elf_putnote(target, "CORE", NT_PRPSINFO, psinfo, sizeof *psinfo);
1475 * Append first note for LWP that triggered core so that it is
1476 * the selected one when the debugger starts.
1478 if (mode != DRYRUN) {
1479 status->pr_version = PRSTATUS_VERSION;
1480 status->pr_statussz = sizeof(prstatus_t);
1481 status->pr_gregsetsz = sizeof(gregset_t);
1482 status->pr_fpregsetsz = sizeof(fpregset_t);
1483 status->pr_osreldate = osreldate;
1484 status->pr_cursig = sig;
1486 * XXX GDB needs unique pr_pid for each LWP and does not
1487 * not support pr_pid==0 but lwp_tid can be 0, so hack unique
1490 status->pr_pid = corelp->lwp_tid;
1491 fill_regs(corelp, &status->pr_reg);
1492 fill_fpregs(corelp, fpregs);
1495 elf_putnote(target, "CORE", NT_PRSTATUS, status, sizeof *status);
1499 elf_putnote(target, "CORE", NT_FPREGSET, fpregs, sizeof *fpregs);
1504 * Then append notes for other LWPs.
1506 FOREACH_LWP_IN_PROC(lp, p) {
1509 /* skip lwps being created */
1510 if (lp->lwp_thread == NULL)
1512 if (mode != DRYRUN) {
1513 status->pr_pid = lp->lwp_tid;
1514 fill_regs(lp, &status->pr_reg);
1515 fill_fpregs(lp, fpregs);
1517 error = elf_putnote(target, "CORE", NT_PRSTATUS,
1518 status, sizeof *status);
1521 error = elf_putnote(target, "CORE", NT_FPREGSET,
1522 fpregs, sizeof *fpregs);
1528 if (tmpdata != NULL)
1529 kfree(tmpdata, M_TEMP);
1534 * Generate a note sub-structure.
1536 * NOTE: 4-byte alignment.
1539 elf_putnote(elf_buf_t target, const char *name, int type,
1540 const void *desc, size_t descsz)
1546 note.n_namesz = strlen(name) + 1;
1547 note.n_descsz = descsz;
1549 dst = target_reserve(target, sizeof(note), &error);
1551 bcopy(¬e, dst, sizeof note);
1552 dst = target_reserve(target, note.n_namesz, &error);
1554 bcopy(name, dst, note.n_namesz);
1555 target->off = roundup2(target->off, sizeof(Elf_Word));
1556 dst = target_reserve(target, note.n_descsz, &error);
1558 bcopy(desc, dst, note.n_descsz);
1559 target->off = roundup2(target->off, sizeof(Elf_Word));
1565 elf_putsigs(struct lwp *lp, elf_buf_t target)
1567 /* XXX lwp handle more than one lwp */
1568 struct proc *p = lp->lwp_proc;
1570 struct ckpt_siginfo *csi;
1572 csi = target_reserve(target, sizeof(struct ckpt_siginfo), &error);
1574 csi->csi_ckptpisz = sizeof(struct ckpt_siginfo);
1575 bcopy(p->p_sigacts, &csi->csi_sigacts, sizeof(*p->p_sigacts));
1576 bcopy(&p->p_realtimer, &csi->csi_itimerval, sizeof(struct itimerval));
1577 bcopy(&lp->lwp_sigmask, &csi->csi_sigmask,
1579 csi->csi_sigparent = p->p_sigparent;
1585 elf_putfiles(struct proc *p, elf_buf_t target, struct file *ckfp)
1589 struct ckpt_filehdr *cfh = NULL;
1590 struct ckpt_fileinfo *cfi;
1594 * the duplicated loop is gross, but it was the only way
1595 * to eliminate uninitialized variable warnings
1597 cfh = target_reserve(target, sizeof(struct ckpt_filehdr), &error);
1599 cfh->cfh_nfiles = 0;
1603 * ignore STDIN/STDERR/STDOUT.
1605 for (i = 3; error == 0 && i < p->p_fd->fd_nfiles; i++) {
1606 fp = holdfp(p->p_fd, i, -1);
1610 * XXX Only checkpoint vnodes for now.
1612 if (fp->f_type != DTYPE_VNODE) {
1616 cfi = target_reserve(target, sizeof(struct ckpt_fileinfo),
1622 cfi->cfi_index = -1;
1623 cfi->cfi_type = fp->f_type;
1624 cfi->cfi_flags = fp->f_flag;
1625 cfi->cfi_offset = fp->f_offset;
1626 cfi->cfi_ckflags = 0;
1629 cfi->cfi_ckflags |= CKFIF_ISCKPTFD;
1630 /* f_count and f_msgcount should not be saved/restored */
1631 /* XXX save cred info */
1633 switch(fp->f_type) {
1635 vp = (struct vnode *)fp->f_data;
1637 * it looks like a bug in ptrace is marking
1638 * a non-vnode as a vnode - until we find the
1639 * root cause this will at least prevent
1640 * further panics from truss
1642 if (vp == NULL || vp->v_mount == NULL)
1646 cfi->cfi_fh.fh_fsid = vp->v_mount->mnt_stat.f_fsid;
1647 error = VFS_VPTOFH(vp, &cfi->cfi_fh.fh_fid);
1658 elf_puttextvp(struct proc *p, elf_buf_t target)
1662 struct fp_closure fpc;
1663 struct ckpt_vminfo *vminfo;
1665 vminfo = target_reserve(target, sizeof(struct ckpt_vminfo), &error);
1666 if (vminfo != NULL) {
1667 vminfo->cvm_dsize = p->p_vmspace->vm_dsize;
1668 vminfo->cvm_tsize = p->p_vmspace->vm_tsize;
1669 vminfo->cvm_daddr = p->p_vmspace->vm_daddr;
1670 vminfo->cvm_taddr = p->p_vmspace->vm_taddr;
1674 vn_count = target_reserve(target, sizeof(int), &error);
1675 if (target->buf != NULL) {
1676 fpc.vnh = (struct vn_hdr *)(target->buf + target->off);
1677 fpc.vnh_max = fpc.vnh +
1678 (target->off_max - target->off) / sizeof(struct vn_hdr);
1679 error = each_segment(p, cb_put_fp, &fpc, 0);
1681 *vn_count = fpc.count;
1683 error = each_segment(p, cb_fpcount_segment, &fpc.count, 0);
1685 target->off += fpc.count * sizeof(struct vn_hdr);
1691 * Tell kern_execve.c about it, with a little help from the linker.
1693 static struct execsw elf_execsw = {exec_elf_imgact, "ELF"};
1694 EXEC_SET_ORDERED(elf, elf_execsw, SI_ORDER_FIRST);