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.
30 * $FreeBSD: src/sys/kern/imgact_elf.c,v 1.73.2.13 2002/12/28 19:49:41 dillon 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>
72 #define OLD_EI_BRAND 8
73 #define truncps(va,ps) ((va) & ~(ps - 1))
74 #define aligned(a,t) (truncps((u_long)(a), sizeof(t)) == (u_long)(a))
76 static int __elfN(check_header)(const Elf_Ehdr *hdr);
77 static Elf_Brandinfo *__elfN(get_brandinfo)(struct image_params *imgp,
78 const char *interp, int32_t *osrel);
79 static int __elfN(load_file)(struct proc *p, const char *file, u_long *addr,
81 static int __elfN(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 __CONCAT(exec_, __elfN(imgact))(struct image_params *imgp);
86 static boolean_t __elfN(check_note)(struct image_params *imgp,
87 Elf_Brandnote *checknote, int32_t *osrel);
89 static int elf_legacy_coredump = 0;
90 static int __elfN(fallback_brand) = -1;
91 #if defined(__x86_64__)
92 SYSCTL_NODE(_kern, OID_AUTO, elf64, CTLFLAG_RW, 0, "");
93 SYSCTL_INT(_debug, OID_AUTO, elf64_legacy_coredump, CTLFLAG_RW,
94 &elf_legacy_coredump, 0, "legacy coredump mode");
95 SYSCTL_INT(_kern_elf64, OID_AUTO, fallback_brand, CTLFLAG_RW,
96 &elf64_fallback_brand, 0, "ELF64 brand of last resort");
97 TUNABLE_INT("kern.elf64.fallback_brand", &elf64_fallback_brand);
98 #else /* i386 assumed */
99 SYSCTL_NODE(_kern, OID_AUTO, elf32, CTLFLAG_RW, 0, "");
100 SYSCTL_INT(_debug, OID_AUTO, elf32_legacy_coredump, CTLFLAG_RW,
101 &elf_legacy_coredump, 0, "legacy coredump mode");
102 SYSCTL_INT(_kern_elf32, OID_AUTO, fallback_brand, CTLFLAG_RW,
103 &elf32_fallback_brand, 0, "ELF32 brand of last resort");
104 TUNABLE_INT("kern.elf32.fallback_brand", &elf32_fallback_brand);
107 static Elf_Brandinfo *elf_brand_list[MAX_BRANDS];
109 static const char DRAGONFLY_ABI_VENDOR[] = "DragonFly";
111 Elf_Brandnote __elfN(dragonfly_brandnote) = {
112 .hdr.n_namesz = sizeof(DRAGONFLY_ABI_VENDOR),
113 .hdr.n_descsz = sizeof(int32_t),
115 .vendor = DRAGONFLY_ABI_VENDOR,
116 .flags = BN_CAN_FETCH_OSREL,
120 __elfN(insert_brand_entry)(Elf_Brandinfo *entry)
124 for (i = 0; i < MAX_BRANDS; i++) {
125 if (elf_brand_list[i] == NULL) {
126 elf_brand_list[i] = entry;
130 if (i == MAX_BRANDS) {
131 uprintf("WARNING: %s: could not insert brandinfo entry: %p\n",
139 __elfN(remove_brand_entry)(Elf_Brandinfo *entry)
143 for (i = 0; i < MAX_BRANDS; i++) {
144 if (elf_brand_list[i] == entry) {
145 elf_brand_list[i] = NULL;
155 * Check if an elf brand is being used anywhere in the system.
157 * Used by the linux emulation module unloader. This isn't safe from
160 struct elf_brand_inuse_info {
162 Elf_Brandinfo *entry;
165 static int elf_brand_inuse_callback(struct proc *p, void *data);
168 __elfN(brand_inuse)(Elf_Brandinfo *entry)
170 struct elf_brand_inuse_info info;
174 allproc_scan(elf_brand_inuse_callback, entry);
180 elf_brand_inuse_callback(struct proc *p, void *data)
182 struct elf_brand_inuse_info *info = data;
184 if (p->p_sysent == info->entry->sysvec) {
192 __elfN(check_header)(const Elf_Ehdr *hdr)
198 hdr->e_ident[EI_CLASS] != ELF_TARG_CLASS ||
199 hdr->e_ident[EI_DATA] != ELF_TARG_DATA ||
200 hdr->e_ident[EI_VERSION] != EV_CURRENT ||
201 hdr->e_phentsize != sizeof(Elf_Phdr) ||
202 hdr->e_ehsize != sizeof(Elf_Ehdr) ||
203 hdr->e_version != ELF_TARG_VER)
207 * Make sure we have at least one brand for this machine.
210 for (i = 0; i < MAX_BRANDS; i++) {
211 bi = elf_brand_list[i];
212 if (bi != NULL && bi->machine == hdr->e_machine)
222 __elfN(load_section)(struct proc *p, struct vmspace *vmspace, struct vnode *vp,
223 vm_offset_t offset, caddr_t vmaddr, size_t memsz,
224 size_t filsz, vm_prot_t prot)
227 vm_offset_t map_addr;
232 vm_offset_t file_addr;
234 object = vp->v_object;
238 * It's necessary to fail if the filsz + offset taken from the
239 * header is greater than the actual file pager object's size.
240 * If we were to allow this, then the vm_map_find() below would
241 * walk right off the end of the file object and into the ether.
243 * While I'm here, might as well check for something else that
244 * is invalid: filsz cannot be greater than memsz.
246 if ((off_t)filsz + offset > vp->v_filesize || filsz > memsz) {
247 uprintf("elf_load_section: truncated ELF file\n");
251 map_addr = trunc_page((vm_offset_t)vmaddr);
252 file_addr = trunc_page(offset);
255 * We have two choices. We can either clear the data in the last page
256 * of an oversized mapping, or we can start the anon mapping a page
257 * early and copy the initialized data into that first page. We
258 * choose the second..
261 map_len = trunc_page(offset+filsz) - file_addr;
263 map_len = round_page(offset+filsz) - file_addr;
266 vm_object_reference(object);
268 /* cow flags: don't dump readonly sections in core */
269 cow = MAP_COPY_ON_WRITE | MAP_PREFAULT |
270 (prot & VM_PROT_WRITE ? 0 : MAP_DISABLE_COREDUMP);
272 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
273 vm_map_lock(&vmspace->vm_map);
274 rv = vm_map_insert(&vmspace->vm_map, &count,
276 file_addr, /* file offset */
277 map_addr, /* virtual start */
278 map_addr + map_len,/* virtual end */
282 vm_map_unlock(&vmspace->vm_map);
283 vm_map_entry_release(count);
284 if (rv != KERN_SUCCESS) {
285 vm_object_deallocate(object);
289 /* we can stop now if we've covered it all */
290 if (memsz == filsz) {
297 * We have to get the remaining bit of the file into the first part
298 * of the oversized map segment. This is normally because the .data
299 * segment in the file is extended to provide bss. It's a neat idea
300 * to try and save a page, but it's a pain in the behind to implement.
302 copy_len = (offset + filsz) - trunc_page(offset + filsz);
303 map_addr = trunc_page((vm_offset_t)vmaddr + filsz);
304 map_len = round_page((vm_offset_t)vmaddr + memsz) - map_addr;
306 /* This had damn well better be true! */
308 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
309 vm_map_lock(&vmspace->vm_map);
310 rv = vm_map_insert(&vmspace->vm_map, &count,
312 map_addr, map_addr + map_len,
314 VM_PROT_ALL, VM_PROT_ALL,
316 vm_map_unlock(&vmspace->vm_map);
317 vm_map_entry_release(count);
318 if (rv != KERN_SUCCESS) {
326 struct lwbuf lwb_cache;
328 m = vm_fault_object_page(object, trunc_page(offset + filsz),
329 VM_PROT_READ, 0, &error);
331 lwb = lwbuf_alloc(m, &lwb_cache);
332 error = copyout((caddr_t)lwbuf_kva(lwb),
333 (caddr_t)map_addr, copy_len);
343 * set it to the specified protection
345 vm_map_protect(&vmspace->vm_map, map_addr, map_addr + map_len, prot,
352 * Load the file "file" into memory. It may be either a shared object
355 * The "addr" reference parameter is in/out. On entry, it specifies
356 * the address where a shared object should be loaded. If the file is
357 * an executable, this value is ignored. On exit, "addr" specifies
358 * where the file was actually loaded.
360 * The "entry" reference parameter is out only. On exit, it specifies
361 * the entry point for the loaded file.
364 __elfN(load_file)(struct proc *p, const char *file, u_long *addr, u_long *entry)
367 struct nlookupdata nd;
369 struct image_params image_params;
371 const Elf_Ehdr *hdr = NULL;
372 const Elf_Phdr *phdr = NULL;
373 struct nlookupdata *nd;
374 struct vmspace *vmspace = p->p_vmspace;
376 struct image_params *imgp;
377 struct mount *topmnt;
380 u_long base_addr = 0;
381 int error, i, numsegs;
383 tempdata = kmalloc(sizeof(*tempdata), M_TEMP, M_WAITOK);
385 attr = &tempdata->attr;
386 imgp = &tempdata->image_params;
389 * Initialize part of the common data
393 imgp->firstpage = NULL;
394 imgp->image_header = NULL;
397 error = nlookup_init(nd, file, UIO_SYSSPACE, NLC_FOLLOW);
401 error = cache_vget(&nd->nl_nch, nd->nl_cred, LK_EXCLUSIVE, &imgp->vp);
402 topmnt = nd->nl_nch.mount;
408 * Check permissions, modes, uid, etc on the file, and "open" it.
410 error = exec_check_permissions(imgp, topmnt);
416 error = exec_map_first_page(imgp);
418 * Also make certain that the interpreter stays the same, so set
419 * its VTEXT flag, too.
422 vsetflags(imgp->vp, VTEXT);
427 hdr = (const Elf_Ehdr *)imgp->image_header;
428 if ((error = __elfN(check_header)(hdr)) != 0)
430 if (hdr->e_type == ET_DYN)
432 else if (hdr->e_type == ET_EXEC)
439 /* Only support headers that fit within first page for now */
440 /* (multiplication of two Elf_Half fields will not overflow) */
441 if ((hdr->e_phoff > PAGE_SIZE) ||
442 (hdr->e_phentsize * hdr->e_phnum) > PAGE_SIZE - hdr->e_phoff) {
447 phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
449 for (i = 0, numsegs = 0; i < hdr->e_phnum; i++) {
450 if (phdr[i].p_type == PT_LOAD && phdr[i].p_memsz != 0) {
451 /* Loadable segment */
453 if (phdr[i].p_flags & PF_X)
454 prot |= VM_PROT_EXECUTE;
455 if (phdr[i].p_flags & PF_W)
456 prot |= VM_PROT_WRITE;
457 if (phdr[i].p_flags & PF_R)
458 prot |= VM_PROT_READ;
460 error = __elfN(load_section)(
461 p, vmspace, imgp->vp,
463 (caddr_t)phdr[i].p_vaddr +
466 phdr[i].p_filesz, prot);
470 * Establish the base address if this is the
474 base_addr = trunc_page(phdr[i].p_vaddr + rbase);
479 *entry = (unsigned long)hdr->e_entry + rbase;
483 exec_unmap_first_page(imgp);
488 kfree(tempdata, M_TEMP);
493 static Elf_Brandinfo *
494 __elfN(get_brandinfo)(struct image_params *imgp, const char *interp,
497 const Elf_Ehdr *hdr = (const Elf_Ehdr *)imgp->image_header;
502 /* We support four types of branding -- (1) the ELF EI_OSABI field
503 * that SCO added to the ELF spec, (2) FreeBSD 3.x's traditional string
504 * branding within the ELF header, (3) path of the `interp_path' field,
505 * and (4) the ".note.ABI-tag" ELF section.
508 /* Look for an ".note.ABI-tag" ELF section */
509 for (i = 0; i < MAX_BRANDS; i++) {
510 bi = elf_brand_list[i];
514 if (hdr->e_machine == bi->machine && (bi->flags &
515 (BI_BRAND_NOTE|BI_BRAND_NOTE_MANDATORY)) != 0) {
516 ret = __elfN(check_note)(imgp, bi->brand_note, osrel);
522 /* If the executable has a brand, search for it in the brand list. */
523 for (i = 0; i < MAX_BRANDS; i++) {
524 bi = elf_brand_list[i];
526 if (bi == NULL || bi->flags & BI_BRAND_NOTE_MANDATORY)
528 if (hdr->e_machine == bi->machine &&
529 (hdr->e_ident[EI_OSABI] == bi->brand ||
530 strncmp((const char *)&hdr->e_ident[OLD_EI_BRAND],
531 bi->compat_3_brand, strlen(bi->compat_3_brand)) == 0))
535 /* Lacking a known brand, search for a recognized interpreter. */
536 if (interp != NULL) {
537 for (i = 0; i < MAX_BRANDS; i++) {
538 bi = elf_brand_list[i];
540 if (bi == NULL || bi->flags & BI_BRAND_NOTE_MANDATORY)
542 if (hdr->e_machine == bi->machine &&
543 strcmp(interp, bi->interp_path) == 0)
548 /* Lacking a recognized interpreter, try the default brand */
549 for (i = 0; i < MAX_BRANDS; i++) {
550 bi = elf_brand_list[i];
552 if (bi == NULL || bi->flags & BI_BRAND_NOTE_MANDATORY)
554 if (hdr->e_machine == bi->machine &&
555 __elfN(fallback_brand) == bi->brand)
562 __CONCAT(exec_,__elfN(imgact))(struct image_params *imgp)
564 const Elf_Ehdr *hdr = (const Elf_Ehdr *) imgp->image_header;
565 const Elf_Phdr *phdr;
566 Elf_Auxargs *elf_auxargs = NULL;
567 struct vmspace *vmspace;
569 u_long text_size = 0, data_size = 0, total_size = 0;
570 u_long text_addr = 0, data_addr = 0;
571 u_long seg_size, seg_addr;
572 u_long addr, entry = 0, proghdr = 0;
575 const char *interp = NULL, *newinterp = NULL;
576 Elf_Brandinfo *brand_info;
582 * Do we have a valid ELF header ?
584 * Only allow ET_EXEC & ET_DYN here, reject ET_DYN later if a particular
585 * brand doesn't support it. Both DragonFly platforms do by default.
587 if (__elfN(check_header)(hdr) != 0 ||
588 (hdr->e_type != ET_EXEC && hdr->e_type != ET_DYN))
592 * From here on down, we return an errno, not -1, as we've
593 * detected an ELF file.
596 if ((hdr->e_phoff > PAGE_SIZE) ||
597 (hdr->e_phoff + hdr->e_phentsize * hdr->e_phnum) > PAGE_SIZE) {
598 /* Only support headers in first page for now */
601 phdr = (const Elf_Phdr*)(imgp->image_header + hdr->e_phoff);
602 for (i = 0; i < hdr->e_phnum; i++) {
603 if (phdr[i].p_type == PT_INTERP) {
604 /* Path to interpreter */
605 if (phdr[i].p_filesz > MAXPATHLEN ||
606 phdr[i].p_offset + phdr[i].p_filesz > PAGE_SIZE)
608 interp = imgp->image_header + phdr[i].p_offset;
613 brand_info = __elfN(get_brandinfo)(imgp, interp, &osrel);
614 if (brand_info == NULL) {
615 uprintf("ELF binary type \"%u\" not known.\n",
616 hdr->e_ident[EI_OSABI]);
619 if (hdr->e_type == ET_DYN &&
620 (brand_info->flags & BI_CAN_EXEC_DYN) == 0) {
624 if (interp != NULL && brand_info->interp_newpath != NULL)
625 newinterp = brand_info->interp_newpath;
627 exec_new_vmspace(imgp, NULL);
630 * Yeah, I'm paranoid. There is every reason in the world to get
631 * VTEXT now since from here on out, there are places we can have
632 * a context switch. Better safe than sorry; I really don't want
633 * the file to change while it's being loaded.
635 vsetflags(imgp->vp, VTEXT);
637 vmspace = imgp->proc->p_vmspace;
639 for (i = 0; i < hdr->e_phnum; i++) {
640 switch (phdr[i].p_type) {
642 case PT_LOAD: /* Loadable segment */
643 if (phdr[i].p_memsz == 0)
646 if (phdr[i].p_flags & PF_X)
647 prot |= VM_PROT_EXECUTE;
648 if (phdr[i].p_flags & PF_W)
649 prot |= VM_PROT_WRITE;
650 if (phdr[i].p_flags & PF_R)
651 prot |= VM_PROT_READ;
653 if ((error = __elfN(load_section)(
657 (caddr_t)phdr[i].p_vaddr,
659 phdr[i].p_filesz, prot)) != 0)
663 * If this segment contains the program headers,
664 * remember their virtual address for the AT_PHDR
665 * aux entry. Static binaries don't usually include
668 if (phdr[i].p_offset == 0 &&
669 hdr->e_phoff + hdr->e_phnum * hdr->e_phentsize
671 proghdr = phdr[i].p_vaddr + hdr->e_phoff;
673 seg_addr = trunc_page(phdr[i].p_vaddr);
674 seg_size = round_page(phdr[i].p_memsz +
675 phdr[i].p_vaddr - seg_addr);
678 * Is this .text or .data? We can't use
679 * VM_PROT_WRITE or VM_PROT_EXEC, it breaks the
680 * alpha terribly and possibly does other bad
681 * things so we stick to the old way of figuring
682 * it out: If the segment contains the program
683 * entry point, it's a text segment, otherwise it
686 * Note that obreak() assumes that data_addr +
687 * data_size == end of data load area, and the ELF
688 * file format expects segments to be sorted by
689 * address. If multiple data segments exist, the
690 * last one will be used.
692 if (hdr->e_entry >= phdr[i].p_vaddr &&
693 hdr->e_entry < (phdr[i].p_vaddr +
695 text_size = seg_size;
696 text_addr = seg_addr;
697 entry = (u_long)hdr->e_entry;
699 data_size = seg_size;
700 data_addr = seg_addr;
702 total_size += seg_size;
705 * Check limits. It should be safe to check the
706 * limits after loading the segment since we do
707 * not actually fault in all the segment's pages.
710 imgp->proc->p_rlimit[RLIMIT_DATA].rlim_cur ||
711 text_size > maxtsiz ||
713 imgp->proc->p_rlimit[RLIMIT_VMEM].rlim_cur) {
718 case PT_PHDR: /* Program header table info */
719 proghdr = phdr[i].p_vaddr;
726 vmspace->vm_tsize = text_size >> PAGE_SHIFT;
727 vmspace->vm_taddr = (caddr_t)(uintptr_t)text_addr;
728 vmspace->vm_dsize = data_size >> PAGE_SHIFT;
729 vmspace->vm_daddr = (caddr_t)(uintptr_t)data_addr;
731 addr = ELF_RTLD_ADDR(vmspace);
733 imgp->entry_addr = entry;
735 imgp->proc->p_sysent = brand_info->sysvec;
736 EVENTHANDLER_INVOKE(process_exec, imgp);
738 if (interp != NULL) {
739 int have_interp = FALSE;
740 if (brand_info->emul_path != NULL &&
741 brand_info->emul_path[0] != '\0') {
742 path = kmalloc(MAXPATHLEN, M_TEMP, M_WAITOK);
743 ksnprintf(path, MAXPATHLEN, "%s%s",
744 brand_info->emul_path, interp);
745 error = __elfN(load_file)(imgp->proc, path, &addr,
751 if (!have_interp && newinterp != NULL) {
752 error = __elfN(load_file)(imgp->proc, newinterp,
753 &addr, &imgp->entry_addr);
758 error = __elfN(load_file)(imgp->proc, interp, &addr,
762 uprintf("ELF interpreter %s not found\n", interp);
769 * Construct auxargs table (used by the fixup routine)
771 elf_auxargs = kmalloc(sizeof(Elf_Auxargs), M_TEMP, M_WAITOK);
772 elf_auxargs->execfd = -1;
773 elf_auxargs->phdr = proghdr;
774 elf_auxargs->phent = hdr->e_phentsize;
775 elf_auxargs->phnum = hdr->e_phnum;
776 elf_auxargs->pagesz = PAGE_SIZE;
777 elf_auxargs->base = addr;
778 elf_auxargs->flags = 0;
779 elf_auxargs->entry = entry;
781 imgp->auxargs = elf_auxargs;
782 imgp->interpreted = 0;
783 imgp->proc->p_osrel = osrel;
789 __elfN(dragonfly_fixup)(register_t **stack_base, struct image_params *imgp)
791 Elf_Auxargs *args = (Elf_Auxargs *)imgp->auxargs;
795 base = (Elf_Addr *)*stack_base;
796 pos = base + (imgp->args->argc + imgp->args->envc + 2);
798 if (args->execfd != -1)
799 AUXARGS_ENTRY(pos, AT_EXECFD, args->execfd);
800 AUXARGS_ENTRY(pos, AT_PHDR, args->phdr);
801 AUXARGS_ENTRY(pos, AT_PHENT, args->phent);
802 AUXARGS_ENTRY(pos, AT_PHNUM, args->phnum);
803 AUXARGS_ENTRY(pos, AT_PAGESZ, args->pagesz);
804 AUXARGS_ENTRY(pos, AT_FLAGS, args->flags);
805 AUXARGS_ENTRY(pos, AT_ENTRY, args->entry);
806 AUXARGS_ENTRY(pos, AT_BASE, args->base);
807 if (imgp->execpathp != 0)
808 AUXARGS_ENTRY(pos, AT_EXECPATH, imgp->execpathp);
809 AUXARGS_ENTRY(pos, AT_NULL, 0);
811 kfree(imgp->auxargs, M_TEMP);
812 imgp->auxargs = NULL;
815 suword(base, (long)imgp->args->argc);
816 *stack_base = (register_t *)base;
821 * Code for generating ELF core dumps.
824 typedef int (*segment_callback) (vm_map_entry_t, void *);
826 /* Closure for cb_put_phdr(). */
827 struct phdr_closure {
828 Elf_Phdr *phdr; /* Program header to fill in (incremented) */
829 Elf_Phdr *phdr_max; /* Pointer bound for error check */
830 Elf_Off offset; /* Offset of segment in core file */
833 /* Closure for cb_size_segment(). */
834 struct sseg_closure {
835 int count; /* Count of writable segments. */
836 size_t vsize; /* Total size of all writable segments. */
839 /* Closure for cb_put_fp(). */
842 struct vn_hdr *vnh_max;
847 typedef struct elf_buf {
853 static void *target_reserve(elf_buf_t target, size_t bytes, int *error);
855 static int cb_put_phdr (vm_map_entry_t, void *);
856 static int cb_size_segment (vm_map_entry_t, void *);
857 static int cb_fpcount_segment(vm_map_entry_t, void *);
858 static int cb_put_fp(vm_map_entry_t, void *);
861 static int each_segment (struct proc *, segment_callback, void *, int);
862 static int __elfN(corehdr)(struct lwp *, int, struct file *, struct ucred *,
864 enum putmode { WRITE, DRYRUN };
865 static int __elfN(puthdr)(struct lwp *, elf_buf_t, int sig, enum putmode,
867 static int elf_putallnotes(struct lwp *, elf_buf_t, int, enum putmode);
868 static int __elfN(putnote)(elf_buf_t, const char *, int, const void *, size_t);
870 static int elf_putsigs(struct lwp *, elf_buf_t);
871 static int elf_puttextvp(struct proc *, elf_buf_t);
872 static int elf_putfiles(struct proc *, elf_buf_t, struct file *);
875 __elfN(coredump)(struct lwp *lp, int sig, struct vnode *vp, off_t limit)
880 if ((error = falloc(NULL, &fp, NULL)) != 0)
882 fsetcred(fp, lp->lwp_proc->p_ucred);
887 fp->f_type = DTYPE_VNODE;
888 fp->f_flag = O_CREAT|O_WRONLY|O_NOFOLLOW;
889 fp->f_ops = &vnode_fileops;
893 error = generic_elf_coredump(lp, sig, fp, limit);
897 fp->f_ops = &badfileops;
904 generic_elf_coredump(struct lwp *lp, int sig, struct file *fp, off_t limit)
906 struct proc *p = lp->lwp_proc;
907 struct ucred *cred = p->p_ucred;
909 struct sseg_closure seginfo;
910 struct elf_buf target;
913 kprintf("can't dump core - null fp\n");
916 * Size the program segments
920 each_segment(p, cb_size_segment, &seginfo, 1);
923 * Calculate the size of the core file header area by making
924 * a dry run of generating it. Nothing is written, but the
925 * size is calculated.
927 bzero(&target, sizeof(target));
928 __elfN(puthdr)(lp, &target, sig, DRYRUN, seginfo.count, fp);
930 if (target.off + seginfo.vsize >= limit)
934 * Allocate memory for building the header, fill it up,
937 target.off_max = target.off;
939 target.buf = kmalloc(target.off_max, M_TEMP, M_WAITOK|M_ZERO);
941 error = __elfN(corehdr)(lp, sig, fp, cred, seginfo.count, &target);
943 /* Write the contents of all of the writable segments. */
949 php = (Elf_Phdr *)(target.buf + sizeof(Elf_Ehdr)) + 1;
950 for (i = 0; i < seginfo.count; i++) {
951 error = fp_write(fp, (caddr_t)php->p_vaddr,
952 php->p_filesz, &nbytes, UIO_USERSPACE);
958 kfree(target.buf, M_TEMP);
964 * A callback for each_segment() to write out the segment's
965 * program header entry.
968 cb_put_phdr(vm_map_entry_t entry, void *closure)
970 struct phdr_closure *phc = closure;
971 Elf_Phdr *phdr = phc->phdr;
973 if (phc->phdr == phc->phdr_max)
976 phc->offset = round_page(phc->offset);
978 phdr->p_type = PT_LOAD;
979 phdr->p_offset = phc->offset;
980 phdr->p_vaddr = entry->start;
982 phdr->p_filesz = phdr->p_memsz = entry->end - entry->start;
983 phdr->p_align = PAGE_SIZE;
985 if (entry->protection & VM_PROT_READ)
986 phdr->p_flags |= PF_R;
987 if (entry->protection & VM_PROT_WRITE)
988 phdr->p_flags |= PF_W;
989 if (entry->protection & VM_PROT_EXECUTE)
990 phdr->p_flags |= PF_X;
992 phc->offset += phdr->p_filesz;
998 * A callback for each_writable_segment() to gather information about
999 * the number of segments and their total size.
1002 cb_size_segment(vm_map_entry_t entry, void *closure)
1004 struct sseg_closure *ssc = closure;
1007 ssc->vsize += entry->end - entry->start;
1012 * A callback for each_segment() to gather information about
1013 * the number of text segments.
1016 cb_fpcount_segment(vm_map_entry_t entry, void *closure)
1018 int *count = closure;
1021 if (entry->object.vm_object->type == OBJT_VNODE) {
1022 vp = (struct vnode *)entry->object.vm_object->handle;
1023 if ((vp->v_flag & VCKPT) && curproc->p_textvp == vp)
1031 cb_put_fp(vm_map_entry_t entry, void *closure)
1033 struct fp_closure *fpc = closure;
1034 struct vn_hdr *vnh = fpc->vnh;
1035 Elf_Phdr *phdr = &vnh->vnh_phdr;
1040 * If an entry represents a vnode then write out a file handle.
1042 * If we are checkpointing a checkpoint-restored program we do
1043 * NOT record the filehandle for the old checkpoint vnode (which
1044 * is mapped all over the place). Instead we rely on the fact
1045 * that a checkpoint-restored program does not mmap() the checkpt
1046 * vnode NOCORE, so its contents will be written out to the
1047 * new checkpoint file. This is necessary because the 'old'
1048 * checkpoint file is typically destroyed when a new one is created
1049 * and thus cannot be used to restore the new checkpoint.
1051 * Theoretically we could create a chain of checkpoint files and
1052 * operate the checkpointing operation kinda like an incremental
1053 * checkpoint, but a checkpoint restore would then likely wind up
1054 * referencing many prior checkpoint files and that is a bit over
1055 * the top for the purpose of the checkpoint API.
1057 if (entry->object.vm_object->type == OBJT_VNODE) {
1058 vp = (struct vnode *)entry->object.vm_object->handle;
1059 if ((vp->v_flag & VCKPT) && curproc->p_textvp == vp)
1061 if (vnh == fpc->vnh_max)
1065 vnh->vnh_fh.fh_fsid = vp->v_mount->mnt_stat.f_fsid;
1066 error = VFS_VPTOFH(vp, &vnh->vnh_fh.fh_fid);
1068 char *freepath, *fullpath;
1070 if (vn_fullpath(curproc, vp, &fullpath, &freepath, 0)) {
1071 kprintf("Warning: coredump, error %d: cannot store file handle for vnode %p\n", error, vp);
1073 kprintf("Warning: coredump, error %d: cannot store file handle for %s\n", error, fullpath);
1074 kfree(freepath, M_TEMP);
1079 phdr->p_type = PT_LOAD;
1080 phdr->p_offset = 0; /* not written to core */
1081 phdr->p_vaddr = entry->start;
1083 phdr->p_filesz = phdr->p_memsz = entry->end - entry->start;
1084 phdr->p_align = PAGE_SIZE;
1086 if (entry->protection & VM_PROT_READ)
1087 phdr->p_flags |= PF_R;
1088 if (entry->protection & VM_PROT_WRITE)
1089 phdr->p_flags |= PF_W;
1090 if (entry->protection & VM_PROT_EXECUTE)
1091 phdr->p_flags |= PF_X;
1099 * For each writable segment in the process's memory map, call the given
1100 * function with a pointer to the map entry and some arbitrary
1101 * caller-supplied data.
1104 each_segment(struct proc *p, segment_callback func, void *closure, int writable)
1107 vm_map_t map = &p->p_vmspace->vm_map;
1108 vm_map_entry_t entry;
1110 for (entry = map->header.next; error == 0 && entry != &map->header;
1111 entry = entry->next) {
1115 * Don't dump inaccessible mappings, deal with legacy
1118 * Note that read-only segments related to the elf binary
1119 * are marked MAP_ENTRY_NOCOREDUMP now so we no longer
1120 * need to arbitrarily ignore such segments.
1122 if (elf_legacy_coredump) {
1123 if (writable && (entry->protection & VM_PROT_RW) != VM_PROT_RW)
1126 if (writable && (entry->protection & VM_PROT_ALL) == 0)
1131 * Dont include memory segment in the coredump if
1132 * MAP_NOCORE is set in mmap(2) or MADV_NOCORE in
1135 * Currently we only dump normal VM object maps. We do
1136 * not dump submaps or virtual page tables.
1138 if (writable && (entry->eflags & MAP_ENTRY_NOCOREDUMP))
1140 if (entry->maptype != VM_MAPTYPE_NORMAL)
1142 if ((obj = entry->object.vm_object) == NULL)
1145 /* Find the deepest backing object. */
1146 while (obj->backing_object != NULL)
1147 obj = obj->backing_object;
1149 /* Ignore memory-mapped devices and such things. */
1150 if (obj->type != OBJT_DEFAULT &&
1151 obj->type != OBJT_SWAP &&
1152 obj->type != OBJT_VNODE)
1155 error = (*func)(entry, closure);
1162 target_reserve(elf_buf_t target, size_t bytes, int *error)
1167 if (target->off + bytes > target->off_max)
1170 res = target->buf + target->off;
1172 target->off += bytes;
1177 * Write the core file header to the file, including padding up to
1178 * the page boundary.
1181 __elfN(corehdr)(struct lwp *lp, int sig, struct file *fp, struct ucred *cred,
1182 int numsegs, elf_buf_t target)
1188 * Fill in the header. The fp is passed so we can detect and flag
1189 * a checkpoint file pointer within the core file itself, because
1190 * it may not be restored from the same file handle.
1192 error = __elfN(puthdr)(lp, target, sig, WRITE, numsegs, fp);
1194 /* Write it to the core file. */
1196 error = fp_write(fp, target->buf, target->off, &nbytes,
1203 __elfN(puthdr)(struct lwp *lp, elf_buf_t target, int sig, enum putmode mode,
1204 int numsegs, struct file *fp)
1206 struct proc *p = lp->lwp_proc;
1214 ehdr = target_reserve(target, sizeof(Elf_Ehdr), &error);
1216 phoff = target->off;
1217 phdr = target_reserve(target, (numsegs + 1) * sizeof(Elf_Phdr), &error);
1219 noteoff = target->off;
1221 elf_putallnotes(lp, target, sig, mode);
1222 notesz = target->off - noteoff;
1225 * put extra cruft for dumping process state here
1226 * - we really want it be before all the program
1228 * - we just need to update the offset accordingly
1229 * and GDB will be none the wiser.
1232 error = elf_puttextvp(p, target);
1234 error = elf_putsigs(lp, target);
1236 error = elf_putfiles(p, target, fp);
1239 * Align up to a page boundary for the program segments. The
1240 * actual data will be written to the outptu file, not to elf_buf_t,
1241 * so we do not have to do any further bounds checking.
1243 target->off = round_page(target->off);
1244 if (error == 0 && ehdr != NULL) {
1246 * Fill in the ELF header.
1248 ehdr->e_ident[EI_MAG0] = ELFMAG0;
1249 ehdr->e_ident[EI_MAG1] = ELFMAG1;
1250 ehdr->e_ident[EI_MAG2] = ELFMAG2;
1251 ehdr->e_ident[EI_MAG3] = ELFMAG3;
1252 ehdr->e_ident[EI_CLASS] = ELF_CLASS;
1253 ehdr->e_ident[EI_DATA] = ELF_DATA;
1254 ehdr->e_ident[EI_VERSION] = EV_CURRENT;
1255 ehdr->e_ident[EI_OSABI] = ELFOSABI_NONE;
1256 ehdr->e_ident[EI_ABIVERSION] = 0;
1257 ehdr->e_ident[EI_PAD] = 0;
1258 ehdr->e_type = ET_CORE;
1259 ehdr->e_machine = ELF_ARCH;
1260 ehdr->e_version = EV_CURRENT;
1262 ehdr->e_phoff = phoff;
1264 ehdr->e_ehsize = sizeof(Elf_Ehdr);
1265 ehdr->e_phentsize = sizeof(Elf_Phdr);
1266 ehdr->e_phnum = numsegs + 1;
1267 ehdr->e_shentsize = sizeof(Elf_Shdr);
1269 ehdr->e_shstrndx = SHN_UNDEF;
1271 if (error == 0 && phdr != NULL) {
1273 * Fill in the program header entries.
1275 struct phdr_closure phc;
1277 /* The note segement. */
1278 phdr->p_type = PT_NOTE;
1279 phdr->p_offset = noteoff;
1282 phdr->p_filesz = notesz;
1288 /* All the writable segments from the program. */
1290 phc.phdr_max = phdr + numsegs;
1291 phc.offset = target->off;
1292 each_segment(p, cb_put_phdr, &phc, 1);
1298 * Append core dump notes to target ELF buffer or simply update target size
1299 * if dryrun selected.
1302 elf_putallnotes(struct lwp *corelp, elf_buf_t target, int sig,
1305 struct proc *p = corelp->lwp_proc;
1309 prfpregset_t fpregs;
1313 prfpregset_t *fpregs;
1318 * Allocate temporary storage for notes on heap to avoid stack overflow.
1320 if (mode != DRYRUN) {
1321 tmpdata = kmalloc(sizeof(*tmpdata), M_TEMP, M_ZERO | M_WAITOK);
1322 status = &tmpdata->status;
1323 fpregs = &tmpdata->fpregs;
1324 psinfo = &tmpdata->psinfo;
1333 * Append LWP-agnostic note.
1335 if (mode != DRYRUN) {
1336 psinfo->pr_version = PRPSINFO_VERSION;
1337 psinfo->pr_psinfosz = sizeof(prpsinfo_t);
1338 strlcpy(psinfo->pr_fname, p->p_comm,
1339 sizeof(psinfo->pr_fname));
1341 * XXX - We don't fill in the command line arguments
1344 strlcpy(psinfo->pr_psargs, p->p_comm,
1345 sizeof(psinfo->pr_psargs));
1348 __elfN(putnote)(target, "CORE", NT_PRPSINFO, psinfo, sizeof *psinfo);
1353 * Append first note for LWP that triggered core so that it is
1354 * the selected one when the debugger starts.
1356 if (mode != DRYRUN) {
1357 status->pr_version = PRSTATUS_VERSION;
1358 status->pr_statussz = sizeof(prstatus_t);
1359 status->pr_gregsetsz = sizeof(gregset_t);
1360 status->pr_fpregsetsz = sizeof(fpregset_t);
1361 status->pr_osreldate = osreldate;
1362 status->pr_cursig = sig;
1364 * XXX GDB needs unique pr_pid for each LWP and does not
1365 * not support pr_pid==0 but lwp_tid can be 0, so hack unique
1368 status->pr_pid = corelp->lwp_tid;
1369 fill_regs(corelp, &status->pr_reg);
1370 fill_fpregs(corelp, fpregs);
1373 __elfN(putnote)(target, "CORE", NT_PRSTATUS, status, sizeof *status);
1377 __elfN(putnote)(target, "CORE", NT_FPREGSET, fpregs, sizeof *fpregs);
1382 * Then append notes for other LWPs.
1384 FOREACH_LWP_IN_PROC(lp, p) {
1387 /* skip lwps being created */
1388 if (lp->lwp_thread == NULL)
1390 if (mode != DRYRUN) {
1391 status->pr_pid = lp->lwp_tid;
1392 fill_regs(lp, &status->pr_reg);
1393 fill_fpregs(lp, fpregs);
1395 error = __elfN(putnote)(target, "CORE", NT_PRSTATUS,
1396 status, sizeof *status);
1399 error = __elfN(putnote)(target, "CORE", NT_FPREGSET,
1400 fpregs, sizeof *fpregs);
1406 if (tmpdata != NULL)
1407 kfree(tmpdata, M_TEMP);
1412 * Generate a note sub-structure.
1414 * NOTE: 4-byte alignment.
1417 __elfN(putnote)(elf_buf_t target, const char *name, int type,
1418 const void *desc, size_t descsz)
1424 note.n_namesz = strlen(name) + 1;
1425 note.n_descsz = descsz;
1427 dst = target_reserve(target, sizeof(note), &error);
1429 bcopy(¬e, dst, sizeof note);
1430 dst = target_reserve(target, note.n_namesz, &error);
1432 bcopy(name, dst, note.n_namesz);
1433 target->off = roundup2(target->off, sizeof(Elf_Word));
1434 dst = target_reserve(target, note.n_descsz, &error);
1436 bcopy(desc, dst, note.n_descsz);
1437 target->off = roundup2(target->off, sizeof(Elf_Word));
1443 elf_putsigs(struct lwp *lp, elf_buf_t target)
1445 /* XXX lwp handle more than one lwp */
1446 struct proc *p = lp->lwp_proc;
1448 struct ckpt_siginfo *csi;
1450 csi = target_reserve(target, sizeof(struct ckpt_siginfo), &error);
1452 csi->csi_ckptpisz = sizeof(struct ckpt_siginfo);
1453 bcopy(p->p_sigacts, &csi->csi_sigacts, sizeof(*p->p_sigacts));
1454 bcopy(&p->p_realtimer, &csi->csi_itimerval, sizeof(struct itimerval));
1455 bcopy(&lp->lwp_sigmask, &csi->csi_sigmask,
1457 csi->csi_sigparent = p->p_sigparent;
1463 elf_putfiles(struct proc *p, elf_buf_t target, struct file *ckfp)
1467 struct ckpt_filehdr *cfh = NULL;
1468 struct ckpt_fileinfo *cfi;
1472 * the duplicated loop is gross, but it was the only way
1473 * to eliminate uninitialized variable warnings
1475 cfh = target_reserve(target, sizeof(struct ckpt_filehdr), &error);
1477 cfh->cfh_nfiles = 0;
1481 * ignore STDIN/STDERR/STDOUT.
1483 for (i = 3; error == 0 && i < p->p_fd->fd_nfiles; i++) {
1484 fp = holdfp(p->p_fd, i, -1);
1488 * XXX Only checkpoint vnodes for now.
1490 if (fp->f_type != DTYPE_VNODE) {
1494 cfi = target_reserve(target, sizeof(struct ckpt_fileinfo),
1500 cfi->cfi_index = -1;
1501 cfi->cfi_type = fp->f_type;
1502 cfi->cfi_flags = fp->f_flag;
1503 cfi->cfi_offset = fp->f_offset;
1504 cfi->cfi_ckflags = 0;
1507 cfi->cfi_ckflags |= CKFIF_ISCKPTFD;
1508 /* f_count and f_msgcount should not be saved/restored */
1509 /* XXX save cred info */
1511 switch(fp->f_type) {
1513 vp = (struct vnode *)fp->f_data;
1515 * it looks like a bug in ptrace is marking
1516 * a non-vnode as a vnode - until we find the
1517 * root cause this will at least prevent
1518 * further panics from truss
1520 if (vp == NULL || vp->v_mount == NULL)
1524 cfi->cfi_fh.fh_fsid = vp->v_mount->mnt_stat.f_fsid;
1525 error = VFS_VPTOFH(vp, &cfi->cfi_fh.fh_fid);
1536 elf_puttextvp(struct proc *p, elf_buf_t target)
1540 struct fp_closure fpc;
1541 struct ckpt_vminfo *vminfo;
1543 vminfo = target_reserve(target, sizeof(struct ckpt_vminfo), &error);
1544 if (vminfo != NULL) {
1545 vminfo->cvm_dsize = p->p_vmspace->vm_dsize;
1546 vminfo->cvm_tsize = p->p_vmspace->vm_tsize;
1547 vminfo->cvm_daddr = p->p_vmspace->vm_daddr;
1548 vminfo->cvm_taddr = p->p_vmspace->vm_taddr;
1552 vn_count = target_reserve(target, sizeof(int), &error);
1553 if (target->buf != NULL) {
1554 fpc.vnh = (struct vn_hdr *)(target->buf + target->off);
1555 fpc.vnh_max = fpc.vnh +
1556 (target->off_max - target->off) / sizeof(struct vn_hdr);
1557 error = each_segment(p, cb_put_fp, &fpc, 0);
1559 *vn_count = fpc.count;
1561 error = each_segment(p, cb_fpcount_segment, &fpc.count, 0);
1563 target->off += fpc.count * sizeof(struct vn_hdr);
1568 * Try to find the appropriate ABI-note section for checknote,
1569 * fetch the osreldate for binary from the ELF OSABI-note. Only the
1570 * first page of the image is searched, the same as for headers.
1573 __elfN(check_note)(struct image_params *imgp, Elf_Brandnote *checknote,
1576 const Elf_Note *note, *note0, *note_end;
1577 const Elf_Phdr *phdr, *pnote;
1578 const Elf_Ehdr *hdr;
1579 const char *note_name;
1583 hdr = (const Elf_Ehdr *)imgp->image_header;
1584 phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
1586 for (i = 0; i < hdr->e_phnum; i++) {
1587 if (phdr[i].p_type == PT_NOTE) {
1593 if (pnote == NULL || pnote->p_offset >= PAGE_SIZE ||
1594 pnote->p_offset + pnote->p_filesz >= PAGE_SIZE)
1597 note = note0 = (const Elf_Note *)(imgp->image_header + pnote->p_offset);
1598 note_end = (const Elf_Note *)(imgp->image_header +
1599 pnote->p_offset + pnote->p_filesz);
1600 for (i = 0; i < 100 && note >= note0 && note < note_end; i++) {
1601 if (!aligned(note, Elf32_Addr))
1603 if (note->n_namesz != checknote->hdr.n_namesz ||
1604 note->n_descsz != checknote->hdr.n_descsz ||
1605 note->n_type != checknote->hdr.n_type)
1607 note_name = (const char *)(note + 1);
1608 if (strncmp(checknote->vendor, note_name,
1609 checknote->hdr.n_namesz) != 0)
1613 * Fetch the osreldate for binary
1614 * from the ELF OSABI-note if necessary.
1616 if ((checknote->flags & BN_CAN_FETCH_OSREL) != 0 &&
1618 *osrel = *(const int32_t *) (note_name +
1619 roundup2(checknote->hdr.n_namesz,
1620 sizeof(Elf32_Addr)));
1624 note = (const Elf_Note *)((const char *)(note + 1) +
1625 roundup2(note->n_namesz, sizeof(Elf32_Addr)) +
1626 roundup2(note->n_descsz, sizeof(Elf32_Addr)));
1633 * Tell kern_execve.c about it, with a little help from the linker.
1635 #if defined(__x86_64__)
1636 static struct execsw elf_execsw = {exec_elf64_imgact, "ELF64"};
1637 EXEC_SET_ORDERED(elf64, elf_execsw, SI_ORDER_FIRST);
1638 #else /* i386 assumed */
1639 static struct execsw elf_execsw = {exec_elf32_imgact, "ELF32"};
1640 EXEC_SET_ORDERED(elf32, elf_execsw, SI_ORDER_FIRST);