ca26137579dab1b9224cebad3fd3c559822bfb1a
[dragonfly.git] / sys / kern / imgact_elf.c
1 /*-
2  * Copyright (c) 1995-1996 Søren Schmidt
3  * Copyright (c) 1996 Peter Wemm
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
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 withough specific prior written permission
17  *
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.
28  *
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.10 2003/10/19 19:24:18 dillon Exp $
31  */
32
33 #include <sys/param.h>
34 #include <sys/exec.h>
35 #include <sys/fcntl.h>
36 #include <sys/file.h>
37 #include <sys/imgact.h>
38 #include <sys/imgact_elf.h>
39 #include <sys/kernel.h>
40 #include <sys/malloc.h>
41 #include <sys/mman.h>
42 #include <sys/systm.h>
43 #include <sys/proc.h>
44 #include <sys/namei.h>
45 #include <sys/pioctl.h>
46 #include <sys/procfs.h>
47 #include <sys/resourcevar.h>
48 #include <sys/signalvar.h>
49 #include <sys/stat.h>
50 #include <sys/syscall.h>
51 #include <sys/sysctl.h>
52 #include <sys/sysent.h>
53 #include <sys/vnode.h>
54
55 #include <vm/vm.h>
56 #include <vm/vm_kern.h>
57 #include <vm/vm_param.h>
58 #include <vm/pmap.h>
59 #include <sys/lock.h>
60 #include <vm/vm_map.h>
61 #include <vm/vm_object.h>
62 #include <vm/vm_extern.h>
63
64 #include <machine/elf.h>
65 #include <machine/md_var.h>
66 #include <sys/mount.h>
67 #include <sys/ckpt.h>
68 #define OLD_EI_BRAND    8
69
70 __ElfType(Brandinfo);
71 __ElfType(Auxargs);
72
73 static int elf_check_header (const Elf_Ehdr *hdr);
74 static int elf_freebsd_fixup (register_t **stack_base,
75     struct image_params *imgp);
76 static int elf_load_file (struct proc *p, const char *file, u_long *addr,
77     u_long *entry);
78 static int elf_load_section (struct proc *p,
79     struct vmspace *vmspace, struct vnode *vp,
80     vm_offset_t offset, caddr_t vmaddr, size_t memsz, size_t filsz,
81     vm_prot_t prot);
82 static int exec_elf_imgact (struct image_params *imgp);
83
84 static int elf_trace = 0;
85 SYSCTL_INT(_debug, OID_AUTO, elf_trace, CTLFLAG_RW, &elf_trace, 0, "");
86 static int elf_legacy_coredump = 0;
87 SYSCTL_INT(_debug, OID_AUTO, elf_legacy_coredump, CTLFLAG_RW,
88     &elf_legacy_coredump, 0, "");
89
90 static struct sysentvec elf_freebsd_sysvec = {
91         SYS_MAXSYSCALL,
92         sysent,
93         0,
94         0,
95         0,
96         0,
97         0,
98         0,
99         elf_freebsd_fixup,
100         sendsig,
101         sigcode,
102         &szsigcode,
103         0,
104         "FreeBSD ELF",
105         elf_coredump,
106         NULL,
107         MINSIGSTKSZ
108 };
109
110 static Elf_Brandinfo freebsd_brand_info = {
111                                                 ELFOSABI_FREEBSD,
112                                                 "FreeBSD",
113                                                 "",
114                                                 "/usr/libexec/ld-elf.so.1",
115                                                 &elf_freebsd_sysvec
116                                           };
117 static Elf_Brandinfo *elf_brand_list[MAX_BRANDS] = {
118                                                         &freebsd_brand_info,
119                                                         NULL, NULL, NULL,
120                                                         NULL, NULL, NULL, NULL
121                                                     };
122
123 int
124 elf_insert_brand_entry(Elf_Brandinfo *entry)
125 {
126         int i;
127
128         for (i=1; i<MAX_BRANDS; i++) {
129                 if (elf_brand_list[i] == NULL) {
130                         elf_brand_list[i] = entry;
131                         break;
132                 }
133         }
134         if (i == MAX_BRANDS)
135                 return -1;
136         return 0;
137 }
138
139 int
140 elf_remove_brand_entry(Elf_Brandinfo *entry)
141 {
142         int i;
143
144         for (i=1; i<MAX_BRANDS; i++) {
145                 if (elf_brand_list[i] == entry) {
146                         elf_brand_list[i] = NULL;
147                         break;
148                 }
149         }
150         if (i == MAX_BRANDS)
151                 return -1;
152         return 0;
153 }
154
155 int
156 elf_brand_inuse(Elf_Brandinfo *entry)
157 {
158         struct proc *p;
159         int rval = FALSE;
160
161         FOREACH_PROC_IN_SYSTEM(p) {
162                 if (p->p_sysent == entry->sysvec) {
163                         rval = TRUE;
164                         break;
165                 }
166         }
167
168         return (rval);
169 }
170
171 static int
172 elf_check_header(const Elf_Ehdr *hdr)
173 {
174         if (!IS_ELF(*hdr) ||
175             hdr->e_ident[EI_CLASS] != ELF_TARG_CLASS ||
176             hdr->e_ident[EI_DATA] != ELF_TARG_DATA ||
177             hdr->e_ident[EI_VERSION] != EV_CURRENT)
178                 return ENOEXEC;
179
180         if (!ELF_MACHINE_OK(hdr->e_machine))
181                 return ENOEXEC;
182
183         if (hdr->e_version != ELF_TARG_VER)
184                 return ENOEXEC;
185         
186         return 0;
187 }
188
189 static int
190 elf_load_section(struct proc *p, struct vmspace *vmspace, struct vnode *vp, 
191                  vm_offset_t offset, caddr_t vmaddr, size_t memsz, size_t filsz, 
192                  vm_prot_t prot)
193 {
194         size_t map_len;
195         vm_offset_t map_addr;
196         int error, rv, cow;
197         int count;
198         size_t copy_len;
199         vm_object_t object;
200         vm_offset_t file_addr;
201         vm_offset_t data_buf = 0;
202
203         VOP_GETVOBJECT(vp, &object);
204         error = 0;
205
206         /*
207          * It's necessary to fail if the filsz + offset taken from the
208          * header is greater than the actual file pager object's size.
209          * If we were to allow this, then the vm_map_find() below would
210          * walk right off the end of the file object and into the ether.
211          *
212          * While I'm here, might as well check for something else that
213          * is invalid: filsz cannot be greater than memsz.
214          */
215         if ((off_t)filsz + offset > object->un_pager.vnp.vnp_size ||
216             filsz > memsz) {
217                 uprintf("elf_load_section: truncated ELF file\n");
218                 return (ENOEXEC);
219         }
220
221         map_addr = trunc_page((vm_offset_t)vmaddr);
222         file_addr = trunc_page(offset);
223
224         /*
225          * We have two choices.  We can either clear the data in the last page
226          * of an oversized mapping, or we can start the anon mapping a page
227          * early and copy the initialized data into that first page.  We
228          * choose the second..
229          */
230         if (memsz > filsz)
231                 map_len = trunc_page(offset+filsz) - file_addr;
232         else
233                 map_len = round_page(offset+filsz) - file_addr;
234
235         if (map_len != 0) {
236                 vm_object_reference(object);
237
238                 /* cow flags: don't dump readonly sections in core */
239                 cow = MAP_COPY_ON_WRITE | MAP_PREFAULT |
240                     (prot & VM_PROT_WRITE ? 0 : MAP_DISABLE_COREDUMP);
241
242                 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
243                 vm_map_lock(&vmspace->vm_map);
244                 rv = vm_map_insert(&vmspace->vm_map, &count,
245                                       object,
246                                       file_addr,        /* file offset */
247                                       map_addr,         /* virtual start */
248                                       map_addr + map_len,/* virtual end */
249                                       prot,
250                                       VM_PROT_ALL,
251                                       cow);
252                 vm_map_unlock(&vmspace->vm_map);
253                 vm_map_entry_release(count);
254                 if (rv != KERN_SUCCESS) {
255                         vm_object_deallocate(object);
256                         return EINVAL;
257                 }
258
259                 /* we can stop now if we've covered it all */
260                 if (memsz == filsz) {
261                         return 0;
262                 }
263         }
264
265
266         /*
267          * We have to get the remaining bit of the file into the first part
268          * of the oversized map segment.  This is normally because the .data
269          * segment in the file is extended to provide bss.  It's a neat idea
270          * to try and save a page, but it's a pain in the behind to implement.
271          */
272         copy_len = (offset + filsz) - trunc_page(offset + filsz);
273         map_addr = trunc_page((vm_offset_t)vmaddr + filsz);
274         map_len = round_page((vm_offset_t)vmaddr + memsz) - map_addr;
275
276         /* This had damn well better be true! */
277         if (map_len != 0) {
278                 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
279                 vm_map_lock(&vmspace->vm_map);
280                 rv = vm_map_insert(&vmspace->vm_map, &count,
281                                         NULL, 0,
282                                         map_addr, map_addr + map_len,
283                                         VM_PROT_ALL, VM_PROT_ALL, 0);
284                 vm_map_unlock(&vmspace->vm_map);
285                 vm_map_entry_release(count);
286                 if (rv != KERN_SUCCESS) {
287                         return EINVAL; 
288                 }
289         }
290
291         if (copy_len != 0) {
292                 vm_object_reference(object);
293                 rv = vm_map_find(exec_map,
294                                  object, 
295                                  trunc_page(offset + filsz),
296                                  &data_buf,
297                                  PAGE_SIZE,
298                                  TRUE,
299                                  VM_PROT_READ,
300                                  VM_PROT_ALL,
301                                  MAP_COPY_ON_WRITE | MAP_PREFAULT_PARTIAL);
302                 if (rv != KERN_SUCCESS) {
303                         vm_object_deallocate(object);
304                         return EINVAL;
305                 }
306
307                 /* send the page fragment to user space */
308                 error = copyout((caddr_t)data_buf, (caddr_t)map_addr, copy_len);
309                 vm_map_remove(exec_map, data_buf, data_buf + PAGE_SIZE);
310                 if (error) {
311                         return (error);
312                 }
313         }
314
315         /*
316          * set it to the specified protection
317          */
318         vm_map_protect(&vmspace->vm_map, map_addr, map_addr + map_len,  prot,
319                        FALSE);
320
321         return error;
322 }
323
324 /*
325  * Load the file "file" into memory.  It may be either a shared object
326  * or an executable.
327  *
328  * The "addr" reference parameter is in/out.  On entry, it specifies
329  * the address where a shared object should be loaded.  If the file is
330  * an executable, this value is ignored.  On exit, "addr" specifies
331  * where the file was actually loaded.
332  *
333  * The "entry" reference parameter is out only.  On exit, it specifies
334  * the entry point for the loaded file.
335  */
336 static int
337 elf_load_file(struct proc *p, const char *file, u_long *addr, u_long *entry)
338 {
339         struct {
340                 struct nameidata nd;
341                 struct vattr attr;
342                 struct image_params image_params;
343         } *tempdata;
344         const Elf_Ehdr *hdr = NULL;
345         const Elf_Phdr *phdr = NULL;
346         struct nameidata *nd;
347         struct vmspace *vmspace = p->p_vmspace;
348         struct vattr *attr;
349         struct image_params *imgp;
350         vm_prot_t prot;
351         u_long rbase;
352         u_long base_addr = 0;
353         int error, i, numsegs;
354         struct thread *td = p->p_thread;
355
356         tempdata = malloc(sizeof(*tempdata), M_TEMP, M_WAITOK);
357         nd = &tempdata->nd;
358         attr = &tempdata->attr;
359         imgp = &tempdata->image_params;
360
361         /*
362          * Initialize part of the common data
363          */
364         imgp->proc = p;
365         imgp->uap = NULL;
366         imgp->attr = attr;
367         imgp->firstpage = NULL;
368         imgp->image_header = (char *)kmem_alloc_wait(exec_map, PAGE_SIZE);
369
370         if (imgp->image_header == NULL) {
371                 nd->ni_vp = NULL;
372                 error = ENOMEM;
373                 goto fail;
374         }
375
376         NDINIT(nd, NAMEI_LOOKUP, CNP_LOCKLEAF | CNP_FOLLOW,
377             UIO_SYSSPACE, file, td);
378                          
379         if ((error = namei(nd)) != 0) {
380                 nd->ni_vp = NULL;
381                 goto fail;
382         }
383         NDFREE(nd, NDF_ONLY_PNBUF);
384         imgp->vp = nd->ni_vp;
385
386         /*
387          * Check permissions, modes, uid, etc on the file, and "open" it.
388          */
389         error = exec_check_permissions(imgp);
390         if (error) {
391                 VOP_UNLOCK(nd->ni_vp, 0, td);
392                 goto fail;
393         }
394
395         error = exec_map_first_page(imgp);
396         /*
397          * Also make certain that the interpreter stays the same, so set
398          * its VTEXT flag, too.
399          */
400         if (error == 0)
401                 nd->ni_vp->v_flag |= VTEXT;
402         VOP_UNLOCK(nd->ni_vp, 0, td);
403         if (error)
404                 goto fail;
405
406         hdr = (const Elf_Ehdr *)imgp->image_header;
407         if ((error = elf_check_header(hdr)) != 0)
408                 goto fail;
409         if (hdr->e_type == ET_DYN)
410                 rbase = *addr;
411         else if (hdr->e_type == ET_EXEC)
412                 rbase = 0;
413         else {
414                 error = ENOEXEC;
415                 goto fail;
416         }
417
418         /* Only support headers that fit within first page for now */
419         if ((hdr->e_phoff > PAGE_SIZE) ||
420             (hdr->e_phoff + hdr->e_phentsize * hdr->e_phnum) > PAGE_SIZE) {
421                 error = ENOEXEC;
422                 goto fail;
423         }
424
425         phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
426
427         for (i = 0, numsegs = 0; i < hdr->e_phnum; i++) {
428                 if (phdr[i].p_type == PT_LOAD) {        /* Loadable segment */
429                         prot = 0;
430                         if (phdr[i].p_flags & PF_X)
431                                 prot |= VM_PROT_EXECUTE;
432                         if (phdr[i].p_flags & PF_W)
433                                 prot |= VM_PROT_WRITE;
434                         if (phdr[i].p_flags & PF_R)
435                                 prot |= VM_PROT_READ;
436
437                         error = elf_load_section(
438                                     p, vmspace, nd->ni_vp,
439                                     phdr[i].p_offset,
440                                     (caddr_t)phdr[i].p_vaddr +
441                                     rbase,
442                                     phdr[i].p_memsz,
443                                     phdr[i].p_filesz, prot);
444                         if (error != 0)
445                                 goto fail;
446                         /*
447                          * Establish the base address if this is the
448                          * first segment.
449                          */
450                         if (numsegs == 0)
451                                 base_addr = trunc_page(phdr[i].p_vaddr + rbase);
452                         numsegs++;
453                 }
454         }
455         *addr = base_addr;
456         *entry=(unsigned long)hdr->e_entry + rbase;
457
458 fail:
459         if (imgp->firstpage)
460                 exec_unmap_first_page(imgp);
461         if (imgp->image_header)
462                 kmem_free_wakeup(exec_map, (vm_offset_t)imgp->image_header,
463                         PAGE_SIZE);
464         if (nd->ni_vp)
465                 vrele(nd->ni_vp);
466
467         free(tempdata, M_TEMP);
468
469         return error;
470 }
471
472 /*
473  * non static, as it can be overridden by start_init()
474  */
475 int fallback_elf_brand = -1;
476 SYSCTL_INT(_kern, OID_AUTO, fallback_elf_brand, CTLFLAG_RW,
477                 &fallback_elf_brand, -1,
478                 "ELF brand of last resort");
479
480 static int
481 exec_elf_imgact(struct image_params *imgp)
482 {
483         const Elf_Ehdr *hdr = (const Elf_Ehdr *) imgp->image_header;
484         const Elf_Phdr *phdr;
485         Elf_Auxargs *elf_auxargs = NULL;
486         struct vmspace *vmspace;
487         vm_prot_t prot;
488         u_long text_size = 0, data_size = 0, total_size = 0;
489         u_long text_addr = 0, data_addr = 0;
490         u_long seg_size, seg_addr;
491         u_long addr, entry = 0, proghdr = 0;
492         int error, i;
493         const char *interp = NULL;
494         Elf_Brandinfo *brand_info;
495         char *path;
496
497         /*
498          * Do we have a valid ELF header ?
499          */
500         if (elf_check_header(hdr) != 0 || hdr->e_type != ET_EXEC)
501                 return -1;
502
503         /*
504          * From here on down, we return an errno, not -1, as we've
505          * detected an ELF file.
506          */
507
508         if ((hdr->e_phoff > PAGE_SIZE) ||
509             (hdr->e_phoff + hdr->e_phentsize * hdr->e_phnum) > PAGE_SIZE) {
510                 /* Only support headers in first page for now */
511                 return ENOEXEC;
512         }
513         phdr = (const Elf_Phdr*)(imgp->image_header + hdr->e_phoff);
514         
515         /*
516          * From this point on, we may have resources that need to be freed.
517          */
518
519         if ((error = exec_extract_strings(imgp)) != 0)
520                 goto fail;
521
522         exec_new_vmspace(imgp);
523
524         /*
525          * Yeah, I'm paranoid.  There is every reason in the world to get
526          * VTEXT now since from here on out, there are places we can have
527          * a context switch.  Better safe than sorry; I really don't want
528          * the file to change while it's being loaded.
529          */
530         lwkt_gettoken(&imgp->vp->v_interlock);
531         imgp->vp->v_flag |= VTEXT;
532         lwkt_reltoken(&imgp->vp->v_interlock);
533
534         vmspace = imgp->proc->p_vmspace;
535
536         for (i = 0; i < hdr->e_phnum; i++) {
537                 switch(phdr[i].p_type) {
538
539                 case PT_LOAD:   /* Loadable segment */
540                         prot = 0;
541                         if (phdr[i].p_flags & PF_X)
542                                 prot |= VM_PROT_EXECUTE;
543                         if (phdr[i].p_flags & PF_W)
544                                 prot |= VM_PROT_WRITE;
545                         if (phdr[i].p_flags & PF_R)
546                                 prot |= VM_PROT_READ;
547
548                         if ((error = elf_load_section(imgp->proc,
549                                                      vmspace, imgp->vp,
550                                                      phdr[i].p_offset,
551                                                      (caddr_t)phdr[i].p_vaddr,
552                                                      phdr[i].p_memsz,
553                                                      phdr[i].p_filesz, prot)) != 0)
554                                 goto fail;
555
556                         seg_addr = trunc_page(phdr[i].p_vaddr);
557                         seg_size = round_page(phdr[i].p_memsz +
558                                 phdr[i].p_vaddr - seg_addr);
559
560                         /*
561                          * Is this .text or .data?  We can't use
562                          * VM_PROT_WRITE or VM_PROT_EXEC, it breaks the
563                          * alpha terribly and possibly does other bad
564                          * things so we stick to the old way of figuring
565                          * it out:  If the segment contains the program
566                          * entry point, it's a text segment, otherwise it
567                          * is a data segment.
568                          *
569                          * Note that obreak() assumes that data_addr + 
570                          * data_size == end of data load area, and the ELF
571                          * file format expects segments to be sorted by
572                          * address.  If multiple data segments exist, the
573                          * last one will be used.
574                          */
575                         if (hdr->e_entry >= phdr[i].p_vaddr &&
576                             hdr->e_entry < (phdr[i].p_vaddr +
577                             phdr[i].p_memsz)) {
578                                 text_size = seg_size;
579                                 text_addr = seg_addr;
580                                 entry = (u_long)hdr->e_entry;
581                         } else {
582                                 data_size = seg_size;
583                                 data_addr = seg_addr;
584                         }
585                         total_size += seg_size;
586
587                         /*
588                          * Check limits.  It should be safe to check the
589                          * limits after loading the segment since we do
590                          * not actually fault in all the segment's pages.
591                          */
592                         if (data_size >
593                             imgp->proc->p_rlimit[RLIMIT_DATA].rlim_cur ||
594                             text_size > maxtsiz ||
595                             total_size >
596                             imgp->proc->p_rlimit[RLIMIT_VMEM].rlim_cur) {
597                                 error = ENOMEM;
598                                 goto fail;
599                         }
600                         break;
601                 case PT_INTERP: /* Path to interpreter */
602                         if (phdr[i].p_filesz > MAXPATHLEN ||
603                             phdr[i].p_offset + phdr[i].p_filesz > PAGE_SIZE) {
604                                 error = ENOEXEC;
605                                 goto fail;
606                         }
607                         interp = imgp->image_header + phdr[i].p_offset;
608                         break;
609                 case PT_PHDR:   /* Program header table info */
610                         proghdr = phdr[i].p_vaddr;
611                         break;
612                 default:
613                         break;
614                 }
615         }
616
617         vmspace->vm_tsize = text_size >> PAGE_SHIFT;
618         vmspace->vm_taddr = (caddr_t)(uintptr_t)text_addr;
619         vmspace->vm_dsize = data_size >> PAGE_SHIFT;
620         vmspace->vm_daddr = (caddr_t)(uintptr_t)data_addr;
621
622         addr = ELF_RTLD_ADDR(vmspace);
623
624         imgp->entry_addr = entry;
625
626         brand_info = NULL;
627
628         /* We support three types of branding -- (1) the ELF EI_OSABI field
629          * that SCO added to the ELF spec, (2) FreeBSD 3.x's traditional string
630          * branding w/in the ELF header, and (3) path of the `interp_path'
631          * field.  We should also look for an ".note.ABI-tag" ELF section now
632          * in all Linux ELF binaries, FreeBSD 4.1+, and some NetBSD ones.
633          */
634
635         /* If the executable has a brand, search for it in the brand list. */
636         if (brand_info == NULL) {
637                 for (i = 0;  i < MAX_BRANDS;  i++) {
638                         Elf_Brandinfo *bi = elf_brand_list[i];
639
640                         if (bi != NULL && 
641                             (hdr->e_ident[EI_OSABI] == bi->brand
642                             || 0 == 
643                             strncmp((const char *)&hdr->e_ident[OLD_EI_BRAND], 
644                             bi->compat_3_brand, strlen(bi->compat_3_brand)))) {
645                                 brand_info = bi;
646                                 break;
647                         }
648                 }
649         }
650
651         /* Lacking a known brand, search for a recognized interpreter. */
652         if (brand_info == NULL && interp != NULL) {
653                 for (i = 0;  i < MAX_BRANDS;  i++) {
654                         Elf_Brandinfo *bi = elf_brand_list[i];
655
656                         if (bi != NULL &&
657                             strcmp(interp, bi->interp_path) == 0) {
658                                 brand_info = bi;
659                                 break;
660                         }
661                 }
662         }
663
664         /* Lacking a recognized interpreter, try the default brand */
665         if (brand_info == NULL) {
666                 for (i = 0; i < MAX_BRANDS; i++) {
667                         Elf_Brandinfo *bi = elf_brand_list[i];
668
669                         if (bi != NULL && fallback_elf_brand == bi->brand) {
670                                 brand_info = bi;
671                                 break;
672                         }
673                 }
674         }
675
676         if (brand_info == NULL) {
677                 uprintf("ELF binary type \"%u\" not known.\n",
678                     hdr->e_ident[EI_OSABI]);
679                 error = ENOEXEC;
680                 goto fail;
681         }
682
683         imgp->proc->p_sysent = brand_info->sysvec;
684         if (interp != NULL) {
685                 path = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
686                 snprintf(path, MAXPATHLEN, "%s%s",
687                          brand_info->emul_path, interp);
688                 if ((error = elf_load_file(imgp->proc, path, &addr,
689                                            &imgp->entry_addr)) != 0) {
690                         if ((error = elf_load_file(imgp->proc, interp, &addr,
691                                                    &imgp->entry_addr)) != 0) {
692                                 uprintf("ELF interpreter %s not found\n", path);
693                                 free(path, M_TEMP);
694                                 goto fail;
695                         }
696                 }
697                 free(path, M_TEMP);
698         }
699
700         /*
701          * Construct auxargs table (used by the fixup routine)
702          */
703         elf_auxargs = malloc(sizeof(Elf_Auxargs), M_TEMP, M_WAITOK);
704         elf_auxargs->execfd = -1;
705         elf_auxargs->phdr = proghdr;
706         elf_auxargs->phent = hdr->e_phentsize;
707         elf_auxargs->phnum = hdr->e_phnum;
708         elf_auxargs->pagesz = PAGE_SIZE;
709         elf_auxargs->base = addr;
710         elf_auxargs->flags = 0;
711         elf_auxargs->entry = entry;
712         elf_auxargs->trace = elf_trace;
713
714         imgp->auxargs = elf_auxargs;
715         imgp->interpreted = 0;
716
717 fail:
718         return error;
719 }
720
721 static int
722 elf_freebsd_fixup(register_t **stack_base, struct image_params *imgp)
723 {
724         Elf_Auxargs *args = (Elf_Auxargs *)imgp->auxargs;
725         register_t *pos;
726
727         pos = *stack_base + (imgp->argc + imgp->envc + 2);
728
729         if (args->trace) {
730                 AUXARGS_ENTRY(pos, AT_DEBUG, 1);
731         }
732         if (args->execfd != -1) {
733                 AUXARGS_ENTRY(pos, AT_EXECFD, args->execfd);
734         }
735         AUXARGS_ENTRY(pos, AT_PHDR, args->phdr);
736         AUXARGS_ENTRY(pos, AT_PHENT, args->phent);
737         AUXARGS_ENTRY(pos, AT_PHNUM, args->phnum);
738         AUXARGS_ENTRY(pos, AT_PAGESZ, args->pagesz);
739         AUXARGS_ENTRY(pos, AT_FLAGS, args->flags);
740         AUXARGS_ENTRY(pos, AT_ENTRY, args->entry);
741         AUXARGS_ENTRY(pos, AT_BASE, args->base);
742         AUXARGS_ENTRY(pos, AT_NULL, 0);
743
744         free(imgp->auxargs, M_TEMP);
745         imgp->auxargs = NULL;
746
747         (*stack_base)--;
748         suword(*stack_base, (long) imgp->argc);
749         return 0;
750
751
752 /*
753  * Code for generating ELF core dumps.
754  */
755
756 typedef void (*segment_callback) (vm_map_entry_t, void *);
757
758 /* Closure for cb_put_phdr(). */
759 struct phdr_closure {
760         Elf_Phdr *phdr;         /* Program header to fill in */
761         Elf_Off offset;         /* Offset of segment in core file */
762 };
763
764 /* Closure for cb_size_segment(). */
765 struct sseg_closure {
766         int count;              /* Count of writable segments. */
767         size_t size;            /* Total size of all writable segments. */
768 };
769
770 struct fp_closure {
771         struct vn_hdr *vnh;
772         int count;
773         struct stat *sb;
774 };
775
776         
777
778 static void cb_put_phdr (vm_map_entry_t, void *);
779 static void cb_size_segment (vm_map_entry_t, void *);
780 static void cb_fpcount_segment(vm_map_entry_t, void *);
781 static void cb_put_fp(vm_map_entry_t, void *);
782
783
784 static void each_segment (struct proc *, segment_callback,
785     void *, int);
786 static int elf_corehdr (struct proc *, struct file *, struct ucred *,
787     int, void *, size_t);
788 static void elf_puthdr (struct proc *, void *, size_t *,
789     const prstatus_t *, const prfpregset_t *, const prpsinfo_t *, int);
790 static void elf_putnote (void *, size_t *, const char *, int,
791     const void *, size_t);
792
793 static void elf_putsigs(struct proc *, void *, int *);
794
795 static void elf_puttextvp(struct proc *, void *, int *);
796 static void elf_putfiles(struct proc *, void *, int *); 
797
798
799 extern int osreldate;
800
801 int
802 elf_coredump(struct proc *p, struct vnode *vp, off_t limit)
803 {
804         struct file *fp; 
805         int error;
806
807         if ((error = falloc(NULL, &fp, NULL)) != 0)
808                 return (error);
809         fsetcred(fp, p->p_ucred);
810
811         fp->f_data = (caddr_t)vp;
812         fp->f_flag = O_CREAT|O_WRONLY|O_NOFOLLOW;
813         fp->f_ops = &vnops;
814         fp->f_type = DTYPE_VNODE;
815         VOP_UNLOCK(vp, 0, p->p_thread);
816         
817         error = generic_elf_coredump(p, fp, limit);
818
819         fp->f_data = NULL;
820         fp->f_flag = 0;
821         fp->f_ops = &badfileops;
822         fp->f_type = 0;
823         fdrop(fp, p->p_thread);
824         return (error);
825 }
826
827 int
828 generic_elf_coredump(struct proc *p, struct file *fp, off_t limit)
829 {
830
831         struct ucred *cred = p->p_ucred;
832         int error = 0;
833         struct sseg_closure seginfo;
834         void *hdr;
835         size_t hdrsize;
836
837         if (!fp)
838                 printf("can't dump core - null fp\n");
839         /* Size the program segments. */
840         seginfo.count = 0;
841         seginfo.size = 0;
842         each_segment(p, cb_size_segment, &seginfo, 1);
843
844         /*
845          * Calculate the size of the core file header area by making
846          * a dry run of generating it.  Nothing is written, but the
847          * size is calculated.
848          */
849
850         hdrsize = 0;
851         elf_puthdr(p, (void *)NULL, &hdrsize,
852             (const prstatus_t *)NULL, (const prfpregset_t *)NULL,
853             (const prpsinfo_t *)NULL, seginfo.count);
854
855         if (hdrsize + seginfo.size >= limit)
856                 return (EFAULT);
857
858         /*
859          * Allocate memory for building the header, fill it up,
860          * and write it out.
861          */
862         hdr = malloc(hdrsize, M_TEMP, M_WAITOK);
863         if (hdr == NULL) {
864                 return EINVAL;
865         }
866         error = elf_corehdr(p, fp, cred, seginfo.count, hdr, hdrsize);
867
868         /* Write the contents of all of the writable segments. */
869         if (error == 0) {
870                 Elf_Phdr *php;
871                 off_t offset;
872                 int i;
873
874                 php = (Elf_Phdr *)((char *)hdr + sizeof(Elf_Ehdr)) + 1;
875                 offset = hdrsize;
876                 for (i = 0;  i < seginfo.count;  i++) {
877                         int nbytes;
878                         error = fp_pwrite(fp, (caddr_t)php->p_vaddr, php->p_filesz, 
879                                          offset, &nbytes);
880                         if (error != 0)
881                                 break;
882                         offset += php->p_filesz;
883                         php++;
884                 }
885         }
886         free(hdr, M_TEMP);
887         
888         return error;
889 }
890
891 /*
892  * A callback for each_segment() to write out the segment's
893  * program header entry.
894  */
895 static void
896 cb_put_phdr(vm_map_entry_t entry, void *closure)
897 {
898         struct phdr_closure *phc = (struct phdr_closure *)closure;
899         Elf_Phdr *phdr = phc->phdr;
900
901         phc->offset = round_page(phc->offset);
902
903         phdr->p_type = PT_LOAD;
904         phdr->p_offset = phc->offset;
905         phdr->p_vaddr = entry->start;
906         phdr->p_paddr = 0;
907         phdr->p_filesz = phdr->p_memsz = entry->end - entry->start;
908         phdr->p_align = PAGE_SIZE;
909         phdr->p_flags = 0;
910         if (entry->protection & VM_PROT_READ)
911                 phdr->p_flags |= PF_R;
912         if (entry->protection & VM_PROT_WRITE)
913                 phdr->p_flags |= PF_W;
914         if (entry->protection & VM_PROT_EXECUTE)
915                 phdr->p_flags |= PF_X;
916
917         phc->offset += phdr->p_filesz;
918         phc->phdr++;
919 }
920
921 /*
922  * A callback for each_writable_segment() to gather information about
923  * the number of segments and their total size.
924  */
925 static void
926 cb_size_segment(vm_map_entry_t entry, void *closure)
927 {
928         struct sseg_closure *ssc = (struct sseg_closure *)closure;
929
930         ssc->count++;
931         ssc->size += entry->end - entry->start;
932 }
933
934 /*
935  * A callback for each_segment() to gather information about
936  * the number of text segments.
937  */
938 static void
939 cb_fpcount_segment(vm_map_entry_t entry, void *closure)
940 {
941         int *count = (int *)closure;
942         if (entry->object.vm_object->type == OBJT_VNODE)
943                 ++*count;
944 }
945
946 static void
947 cb_put_fp(vm_map_entry_t entry, void *closure) 
948 {
949         struct fp_closure *fpc = (struct fp_closure *)closure;
950         struct vn_hdr *vnh = fpc->vnh;
951         Elf_Phdr *phdr = &vnh->vnh_phdr;
952         struct vnode *vp;
953         int error;
954
955         if (entry->object.vm_object->type == OBJT_VNODE) {
956                 vp = (struct vnode *)entry->object.vm_object->handle;
957                 
958                 vnh->vnh_fh.fh_fsid = vp->v_mount->mnt_stat.f_fsid;
959                 error = VFS_VPTOFH(vp, &vnh->vnh_fh.fh_fid);
960                 if (error) 
961                         return;
962                 
963                 
964                 phdr->p_type = PT_LOAD;
965                 phdr->p_offset = 0;        /* not written to core */
966                 phdr->p_vaddr = entry->start;
967                 phdr->p_paddr = 0;
968                 phdr->p_filesz = phdr->p_memsz = entry->end - entry->start;
969                 phdr->p_align = PAGE_SIZE;
970                 phdr->p_flags = 0;
971                 if (entry->protection & VM_PROT_READ)
972                         phdr->p_flags |= PF_R;
973                 if (entry->protection & VM_PROT_WRITE)
974                         phdr->p_flags |= PF_W;
975                 if (entry->protection & VM_PROT_EXECUTE)
976                         phdr->p_flags |= PF_X;
977                 ++fpc->vnh;
978                 ++fpc->count;
979         }
980 }
981
982
983
984
985 /*
986  * For each writable segment in the process's memory map, call the given
987  * function with a pointer to the map entry and some arbitrary
988  * caller-supplied data.
989  */
990 static void
991 each_segment(struct proc *p, segment_callback func, void *closure, int writable)
992 {
993         vm_map_t map = &p->p_vmspace->vm_map;
994         vm_map_entry_t entry;
995
996         for (entry = map->header.next;  entry != &map->header;
997             entry = entry->next) {
998                 vm_object_t obj;
999
1000                 /*
1001                  * Don't dump inaccessible mappings, deal with legacy
1002                  * coredump mode.
1003                  *
1004                  * Note that read-only segments related to the elf binary
1005                  * are marked MAP_ENTRY_NOCOREDUMP now so we no longer
1006                  * need to arbitrarily ignore such segments.
1007                  */
1008                 if (elf_legacy_coredump) {
1009                         if (writable && (entry->protection & VM_PROT_RW) != VM_PROT_RW)
1010                                 continue;
1011                 } else {
1012                         if (writable && (entry->protection & VM_PROT_ALL) == 0)
1013                                 continue;
1014                 }
1015
1016                 /*
1017                  * Dont include memory segment in the coredump if
1018                  * MAP_NOCORE is set in mmap(2) or MADV_NOCORE in
1019                  * madvise(2).  Do not dump submaps (i.e. parts of the
1020                  * kernel map).
1021                  */
1022                 if (writable && entry->eflags & (MAP_ENTRY_NOCOREDUMP|MAP_ENTRY_IS_SUB_MAP))
1023                         continue;
1024
1025                 if ((obj = entry->object.vm_object) == NULL)
1026                         continue;
1027
1028                 /* Find the deepest backing object. */
1029                 while (obj->backing_object != NULL)
1030                         obj = obj->backing_object;
1031
1032                 /* Ignore memory-mapped devices and such things. */
1033                 if (obj->type != OBJT_DEFAULT &&
1034                     obj->type != OBJT_SWAP &&
1035                     obj->type != OBJT_VNODE)
1036                         continue;
1037
1038                 (*func)(entry, closure);
1039         }
1040 }
1041
1042 /*
1043  * Write the core file header to the file, including padding up to
1044  * the page boundary.
1045  */
1046 static int
1047 elf_corehdr(struct proc *p, struct file *fp, struct ucred *cred, int numsegs, 
1048             void *hdr, size_t hdrsize)
1049 {
1050         struct {
1051                 prstatus_t status;
1052                 prfpregset_t fpregset;
1053                 prpsinfo_t psinfo;
1054         } *tempdata;
1055         size_t off;
1056         prstatus_t *status;
1057         prfpregset_t *fpregset;
1058         prpsinfo_t *psinfo;
1059         int nbytes;
1060         tempdata = malloc(sizeof(*tempdata), M_TEMP, M_ZERO | M_WAITOK);
1061         status = &tempdata->status;
1062         fpregset = &tempdata->fpregset;
1063         psinfo = &tempdata->psinfo;
1064
1065         /* Gather the information for the header. */
1066         status->pr_version = PRSTATUS_VERSION;
1067         status->pr_statussz = sizeof(prstatus_t);
1068         status->pr_gregsetsz = sizeof(gregset_t);
1069         status->pr_fpregsetsz = sizeof(fpregset_t);
1070         status->pr_osreldate = osreldate;
1071         status->pr_cursig = p->p_sig;
1072         status->pr_pid = p->p_pid;
1073         fill_regs(p, &status->pr_reg);
1074
1075         fill_fpregs(p, fpregset);
1076
1077         psinfo->pr_version = PRPSINFO_VERSION;
1078         psinfo->pr_psinfosz = sizeof(prpsinfo_t);
1079         strncpy(psinfo->pr_fname, p->p_comm, sizeof(psinfo->pr_fname) - 1);
1080
1081         /* XXX - We don't fill in the command line arguments properly yet. */
1082         strncpy(psinfo->pr_psargs, p->p_comm, PRARGSZ);
1083
1084         /* Fill in the header. */
1085         bzero(hdr, hdrsize);
1086         off = 0;
1087         elf_puthdr(p, hdr, &off, status, fpregset, psinfo, numsegs);
1088
1089         free(tempdata, M_TEMP);
1090
1091         /* Write it to the core file. */
1092         return fp_pwrite(fp, hdr, hdrsize, (off_t)0, &nbytes);
1093 }
1094
1095 static void
1096 elf_puthdr(struct proc *p, void *dst, size_t *off, const prstatus_t *status,
1097     const prfpregset_t *fpregset, const prpsinfo_t *psinfo, int numsegs)
1098 {
1099         size_t ehoff;
1100         size_t phoff;
1101         size_t noteoff;
1102         size_t notesz;
1103
1104         ehoff = *off;
1105         *off += sizeof(Elf_Ehdr);
1106
1107         phoff = *off;
1108         *off += (numsegs + 1) * sizeof(Elf_Phdr);
1109
1110         noteoff = *off;
1111         elf_putnote(dst, off, "FreeBSD", NT_PRSTATUS, status,
1112             sizeof *status);
1113         elf_putnote(dst, off, "FreeBSD", NT_FPREGSET, fpregset,
1114             sizeof *fpregset);
1115         elf_putnote(dst, off, "FreeBSD", NT_PRPSINFO, psinfo,
1116             sizeof *psinfo);
1117         notesz = *off - noteoff;
1118
1119         /* put extra cruft for dumping process state here 
1120         *  - we really want it be before all the program 
1121         *    mappings
1122         *  - we just need to update the offset accordingly
1123         *    and GDB will be none the wiser.
1124         */
1125         elf_puttextvp(p, dst, off);
1126         elf_putsigs(p, dst, off);
1127         elf_putfiles(p, dst, off);
1128
1129         /* Align up to a page boundary for the program segments. */
1130         *off = round_page(*off);
1131
1132         if (dst != NULL) {
1133                 Elf_Ehdr *ehdr;
1134                 Elf_Phdr *phdr;
1135                 struct phdr_closure phc;
1136
1137                 /*
1138                  * Fill in the ELF header.
1139                  */
1140                 ehdr = (Elf_Ehdr *)((char *)dst + ehoff);
1141                 ehdr->e_ident[EI_MAG0] = ELFMAG0;
1142                 ehdr->e_ident[EI_MAG1] = ELFMAG1;
1143                 ehdr->e_ident[EI_MAG2] = ELFMAG2;
1144                 ehdr->e_ident[EI_MAG3] = ELFMAG3;
1145                 ehdr->e_ident[EI_CLASS] = ELF_CLASS;
1146                 ehdr->e_ident[EI_DATA] = ELF_DATA;
1147                 ehdr->e_ident[EI_VERSION] = EV_CURRENT;
1148                 ehdr->e_ident[EI_OSABI] = ELFOSABI_FREEBSD;
1149                 ehdr->e_ident[EI_ABIVERSION] = 0;
1150                 ehdr->e_ident[EI_PAD] = 0;
1151                 ehdr->e_type = ET_CORE;
1152                 ehdr->e_machine = ELF_ARCH;
1153                 ehdr->e_version = EV_CURRENT;
1154                 ehdr->e_entry = 0;
1155                 ehdr->e_phoff = phoff;
1156                 ehdr->e_flags = 0;
1157                 ehdr->e_ehsize = sizeof(Elf_Ehdr);
1158                 ehdr->e_phentsize = sizeof(Elf_Phdr);
1159                 ehdr->e_phnum = numsegs + 1;
1160                 ehdr->e_shentsize = sizeof(Elf_Shdr);
1161                 ehdr->e_shnum = 0;
1162                 ehdr->e_shstrndx = SHN_UNDEF;
1163
1164                 /*
1165                  * Fill in the program header entries.
1166                  */
1167                 phdr = (Elf_Phdr *)((char *)dst + phoff);
1168
1169                 /* The note segement. */
1170                 phdr->p_type = PT_NOTE;
1171                 phdr->p_offset = noteoff;
1172                 phdr->p_vaddr = 0;
1173                 phdr->p_paddr = 0;
1174                 phdr->p_filesz = notesz;
1175                 phdr->p_memsz = 0;
1176                 phdr->p_flags = 0;
1177                 phdr->p_align = 0;
1178                 phdr++;
1179
1180                 /* All the writable segments from the program. */
1181                 phc.phdr = phdr;
1182                 phc.offset = *off;
1183                 each_segment(p, cb_put_phdr, &phc, 1);
1184         }
1185 }
1186
1187 static void
1188 elf_putnote(void *dst, size_t *off, const char *name, int type,
1189     const void *desc, size_t descsz)
1190 {
1191         Elf_Note note;
1192
1193         note.n_namesz = strlen(name) + 1;
1194         note.n_descsz = descsz;
1195         note.n_type = type;
1196         if (dst != NULL)
1197                 bcopy(&note, (char *)dst + *off, sizeof note);
1198         *off += sizeof note;
1199         if (dst != NULL)
1200                 bcopy(name, (char *)dst + *off, note.n_namesz);
1201         *off += roundup2(note.n_namesz, sizeof(Elf_Size));
1202         if (dst != NULL)
1203                 bcopy(desc, (char *)dst + *off, note.n_descsz);
1204         *off += roundup2(note.n_descsz, sizeof(Elf_Size));
1205 }
1206
1207
1208 static void
1209 elf_putsigs(struct proc *p, void *dst, int *off) 
1210 {
1211         struct ckpt_siginfo *csi;
1212         if (dst == NULL) { 
1213                 *off += sizeof(struct ckpt_siginfo);
1214                 return;
1215         }
1216         csi = (struct ckpt_siginfo *)((char *)dst + *off);      
1217
1218         csi->csi_ckptpisz = sizeof(struct ckpt_siginfo);
1219         bcopy(p->p_procsig, &csi->csi_procsig, sizeof(struct procsig));
1220         bcopy(p->p_procsig->ps_sigacts, &csi->csi_sigacts, sizeof(struct sigacts));
1221         bcopy(&p->p_realtimer, &csi->csi_itimerval, sizeof(struct itimerval));
1222         csi->csi_sigparent = p->p_sigparent;
1223         *off += sizeof(struct ckpt_siginfo);
1224 }
1225
1226 static void
1227 elf_putfiles(struct proc *p, void *dst, int *off)
1228 {
1229         int i, error;
1230         struct ckpt_filehdr *cfh;
1231         struct ckpt_fileinfo *cfi;
1232         struct file *fp;        
1233         struct vnode *vp;
1234         /*
1235          * the duplicated loop is gross, but it was the only way
1236          * to eliminate uninitialized variable warnings 
1237          */
1238         if (dst) {
1239                 cfh = (struct ckpt_filehdr *)((char *)dst + *off);
1240                 *off += sizeof(struct ckpt_filehdr); 
1241                 cfh->cfh_nfiles = 0;            
1242                 /*
1243                  * ignore STDIN/STDERR/STDOUT
1244                  */
1245                 for (i = 3; i < p->p_fd->fd_nfiles; i++) {
1246                         if ((fp = p->p_fd->fd_ofiles[i]) != NULL && fp->f_type == DTYPE_VNODE) {        
1247                                 cfh->cfh_nfiles++;
1248                                 printf("saving fd: %d\n", i);
1249                                 cfi = (struct ckpt_fileinfo *)((char *)dst + *off);
1250                                 cfi->cfi_index = i;
1251                                 cfi->cfi_flags = fp->f_flag;
1252                                 cfi->cfi_offset = fp->f_offset;
1253                                 vp = (struct vnode *)fp->f_data;
1254                                 cfi->cfi_fh.fh_fsid = vp->v_mount->mnt_stat.f_fsid;
1255                                 error = VFS_VPTOFH(vp, &cfi->cfi_fh.fh_fid);
1256
1257                                 *off += sizeof(struct ckpt_fileinfo);
1258                         }
1259                 }
1260         } else {
1261                 *off += sizeof(struct ckpt_filehdr); 
1262                 for (i = 0; i < p->p_fd->fd_nfiles; i++) 
1263                         if ((fp = p->p_fd->fd_ofiles[i]) != NULL  && fp->f_type == DTYPE_VNODE)         
1264                                 *off += sizeof(struct ckpt_fileinfo);
1265         }
1266         
1267 }
1268
1269 static void
1270 elf_puttextvp(struct proc *p, void *dst, int *off) 
1271 {
1272         int count = 0;
1273         struct fp_closure fpc;
1274         int *vn_count;
1275         if (!dst) {
1276                 each_segment(p, cb_fpcount_segment, &count, 0);
1277                 *off += sizeof(struct vn_hdr)*count + sizeof(int);
1278                 return;
1279         }
1280         vn_count = (int *)((char *)dst + *off);
1281         *off += sizeof(int);
1282         fpc.vnh = (struct vn_hdr *)((char *)dst + *off);
1283         fpc.count = 0;
1284         each_segment(p, cb_put_fp, &fpc, 0);
1285         *vn_count = fpc.count;
1286         *off += fpc.count*sizeof(struct vn_hdr);
1287 }
1288
1289
1290 /*
1291  * Tell kern_execve.c about it, with a little help from the linker.
1292  */
1293 static struct execsw elf_execsw = {exec_elf_imgact, "ELF"};
1294 EXEC_SET(elf, elf_execsw);