Merge branch 'apic_io'
[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 without 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.55 2008/08/17 17:21:36 nth 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/nlookup.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 #include <sys/eventhandler.h>
55
56 #include <cpu/lwbuf.h>
57
58 #include <vm/vm.h>
59 #include <vm/vm_kern.h>
60 #include <vm/vm_param.h>
61 #include <vm/pmap.h>
62 #include <sys/lock.h>
63 #include <vm/vm_map.h>
64 #include <vm/vm_object.h>
65 #include <vm/vm_extern.h>
66
67 #include <machine/elf.h>
68 #include <machine/md_var.h>
69 #include <sys/mount.h>
70 #include <sys/ckpt.h>
71 #define OLD_EI_BRAND    8
72
73 __ElfType(Brandinfo);
74 __ElfType(Auxargs);
75
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,
80     u_long *entry);
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,
84     vm_prot_t prot);
85 static int exec_elf_imgact (struct image_params *imgp);
86
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
93 static int dragonfly_match_abi_note(const Elf_Note *);
94 static int freebsd_match_abi_note(const Elf_Note *);
95
96 static struct sysentvec elf_freebsd_sysvec = {
97         SYS_MAXSYSCALL,
98         sysent,
99         -1,
100         0,
101         0,
102         0,
103         0,
104         0,
105         elf_freebsd_fixup,
106         sendsig,
107         sigcode,
108         &szsigcode,
109         0,
110 #if defined(__x86_64__)
111         "FreeBSD ELF64",
112 #else
113         "FreeBSD ELF32",
114 #endif
115         elf_coredump,
116         NULL,
117         MINSIGSTKSZ
118 };
119
120 static Elf_Brandinfo freebsd_brand_info = {
121                                                 ELFOSABI_FREEBSD,
122                                                 "FreeBSD",
123                                                 freebsd_match_abi_note,
124                                                 "",
125                                                 "/usr/libexec/ld-elf.so.1",
126                                                 &elf_freebsd_sysvec
127                                           };
128
129 static Elf_Brandinfo dragonfly_brand_info = {
130                                                 ELFOSABI_NONE,
131                                                 "DragonFly",
132                                                 dragonfly_match_abi_note,
133                                                 "",
134                                                 "/usr/libexec/ld-elf.so.2",
135                                                 &elf_freebsd_sysvec
136                                           };
137
138 static Elf_Brandinfo *elf_brand_list[MAX_BRANDS] = {
139                                                         &dragonfly_brand_info,
140                                                         &freebsd_brand_info,
141                                                         NULL, NULL, NULL,
142                                                         NULL, NULL, NULL
143                                                     };
144
145 static int
146 freebsd_match_abi_note(const Elf_Note *abi_note)
147 {
148         const char *abi_name = (const char *)
149             ((const uint8_t *)abi_note + sizeof(*abi_note));
150
151         if (abi_note->n_namesz != sizeof("FreeBSD"))
152                 return(FALSE);
153         if (memcmp(abi_name, "FreeBSD", sizeof("FreeBSD")))
154                 return(FALSE);
155         return(TRUE);
156 }
157
158 static int
159 dragonfly_match_abi_note(const Elf_Note *abi_note)
160 {
161         const char *abi_name = (const char *)
162             ((const uint8_t *)abi_note + sizeof(*abi_note));
163
164         if (abi_note->n_namesz != sizeof("DragonFly"))
165                 return(FALSE);
166         if (memcmp(abi_name, "DragonFly", sizeof("DragonFly")))
167                 return(FALSE);
168         return(TRUE);
169 }
170
171 int
172 elf_insert_brand_entry(Elf_Brandinfo *entry)
173 {
174         int i;
175
176         for (i=1; i<MAX_BRANDS; i++) {
177                 if (elf_brand_list[i] == NULL) {
178                         elf_brand_list[i] = entry;
179                         break;
180                 }
181         }
182         if (i == MAX_BRANDS)
183                 return -1;
184         return 0;
185 }
186
187 int
188 elf_remove_brand_entry(Elf_Brandinfo *entry)
189 {
190         int i;
191
192         for (i=1; i<MAX_BRANDS; i++) {
193                 if (elf_brand_list[i] == entry) {
194                         elf_brand_list[i] = NULL;
195                         break;
196                 }
197         }
198         if (i == MAX_BRANDS)
199                 return -1;
200         return 0;
201 }
202
203 /*
204  * Check if an elf brand is being used anywhere in the system.
205  *
206  * Used by the linux emulation module unloader.  This isn't safe from
207  * races.
208  */
209 struct elf_brand_inuse_info {
210         int rval;
211         Elf_Brandinfo *entry;
212 };
213
214 static int elf_brand_inuse_callback(struct proc *p, void *data);
215
216 int
217 elf_brand_inuse(Elf_Brandinfo *entry)
218 {
219         struct elf_brand_inuse_info info;
220
221         info.rval = FALSE;
222         info.entry = entry;
223         allproc_scan(elf_brand_inuse_callback, entry);
224         return (info.rval);
225 }
226
227 static
228 int
229 elf_brand_inuse_callback(struct proc *p, void *data)
230 {
231         struct elf_brand_inuse_info *info = data;
232
233         if (p->p_sysent == info->entry->sysvec) {
234                 info->rval = TRUE;
235                 return(-1);
236         }
237         return(0);
238 }
239
240 static int
241 elf_check_header(const Elf_Ehdr *hdr)
242 {
243         if (!IS_ELF(*hdr) ||
244             hdr->e_ident[EI_CLASS] != ELF_TARG_CLASS ||
245             hdr->e_ident[EI_DATA] != ELF_TARG_DATA ||
246             hdr->e_ident[EI_VERSION] != EV_CURRENT ||
247             hdr->e_phentsize != sizeof(Elf_Phdr) ||
248             hdr->e_ehsize != sizeof(Elf_Ehdr) ||
249             hdr->e_version != ELF_TARG_VER)
250                 return ENOEXEC;
251
252         if (!ELF_MACHINE_OK(hdr->e_machine))
253                 return ENOEXEC;
254
255         return 0;
256 }
257
258 static Elf_Brandinfo *
259 elf_check_abi_note(struct image_params *imgp, const Elf_Phdr *ph)
260 {
261         Elf_Brandinfo *match = NULL;
262         const Elf_Note *tmp_note;
263         struct lwbuf *lwb;
264         const char *page;
265         char *data = NULL;
266         Elf_Off off;
267         size_t firstoff;
268         size_t len;
269         size_t firstlen;
270
271         len = ph->p_filesz;
272         off = ph->p_offset;
273
274         firstoff = off & PAGE_MASK;
275         firstlen = PAGE_SIZE - firstoff;
276
277         if (len < sizeof(Elf_Note) || len > PAGE_SIZE)
278                 return NULL; /* ENOEXEC? */
279
280         if (exec_map_page(imgp, off >> PAGE_SHIFT, &lwb, &page))
281                 return NULL;
282
283         /*
284          * Crosses page boundary?  Is that allowed?
285          */
286         if (firstlen < len) {
287                 data = kmalloc(len, M_TEMP, M_WAITOK);
288
289                 bcopy(page + firstoff, data, firstlen);
290
291                 exec_unmap_page(lwb);
292                 if (exec_map_page(imgp, (off >> PAGE_SHIFT) + 1, &lwb, &page)) {
293                         kfree(data, M_TEMP);
294                         return NULL;
295                 }
296                 bcopy(page, data + firstlen, len - firstlen);
297                 tmp_note = (void *)data;
298         } else {
299                 tmp_note = (const void *)(page + firstoff);
300         }
301
302         while (len >= sizeof(Elf_Note)) {
303                 int i;
304                 size_t nlen = roundup(tmp_note->n_namesz, sizeof(Elf_Word)) +
305                               roundup(tmp_note->n_descsz, sizeof(Elf_Word)) +
306                               sizeof(Elf_Note);
307
308                 if (nlen > len)
309                         break;
310
311                 if (tmp_note->n_type != 1)
312                         goto next;
313
314                 for (i = 0; i < MAX_BRANDS; i++) {
315                         Elf_Brandinfo *bi = elf_brand_list[i];
316
317                         if (bi != NULL && bi->match_abi_note != NULL &&
318                             bi->match_abi_note(tmp_note)) {
319                                 match = bi;
320                                 break;
321                         }
322                 }
323
324                 if (match != NULL)
325                         break;
326
327 next:
328                 len -= nlen;
329                 tmp_note += nlen;
330         }
331
332         if (data != NULL)
333                 kfree(data, M_TEMP);
334         exec_unmap_page(lwb);
335
336         return (match);
337 }
338
339 static int
340 elf_load_section(struct proc *p, struct vmspace *vmspace, struct vnode *vp, 
341                  vm_offset_t offset, caddr_t vmaddr, size_t memsz,
342                  size_t filsz, vm_prot_t prot)
343 {
344         size_t map_len;
345         vm_offset_t map_addr;
346         int error, rv, cow;
347         int count;
348         size_t copy_len;
349         vm_object_t object;
350         vm_offset_t file_addr;
351
352         object = vp->v_object;
353         error = 0;
354
355         /*
356          * It's necessary to fail if the filsz + offset taken from the
357          * header is greater than the actual file pager object's size.
358          * If we were to allow this, then the vm_map_find() below would
359          * walk right off the end of the file object and into the ether.
360          *
361          * While I'm here, might as well check for something else that
362          * is invalid: filsz cannot be greater than memsz.
363          */
364         if ((off_t)filsz + offset > vp->v_filesize || filsz > memsz) {
365                 uprintf("elf_load_section: truncated ELF file\n");
366                 return (ENOEXEC);
367         }
368
369         map_addr = trunc_page((vm_offset_t)vmaddr);
370         file_addr = trunc_page(offset);
371
372         /*
373          * We have two choices.  We can either clear the data in the last page
374          * of an oversized mapping, or we can start the anon mapping a page
375          * early and copy the initialized data into that first page.  We
376          * choose the second..
377          */
378         if (memsz > filsz)
379                 map_len = trunc_page(offset+filsz) - file_addr;
380         else
381                 map_len = round_page(offset+filsz) - file_addr;
382
383         if (map_len != 0) {
384                 vm_object_reference(object);
385
386                 /* cow flags: don't dump readonly sections in core */
387                 cow = MAP_COPY_ON_WRITE | MAP_PREFAULT |
388                     (prot & VM_PROT_WRITE ? 0 : MAP_DISABLE_COREDUMP);
389
390                 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
391                 vm_map_lock(&vmspace->vm_map);
392                 rv = vm_map_insert(&vmspace->vm_map, &count,
393                                       object,
394                                       file_addr,        /* file offset */
395                                       map_addr,         /* virtual start */
396                                       map_addr + map_len,/* virtual end */
397                                       VM_MAPTYPE_NORMAL,
398                                       prot, VM_PROT_ALL,
399                                       cow);
400                 vm_map_unlock(&vmspace->vm_map);
401                 vm_map_entry_release(count);
402                 if (rv != KERN_SUCCESS) {
403                         vm_object_deallocate(object);
404                         return EINVAL;
405                 }
406
407                 /* we can stop now if we've covered it all */
408                 if (memsz == filsz) {
409                         return 0;
410                 }
411         }
412
413
414         /*
415          * We have to get the remaining bit of the file into the first part
416          * of the oversized map segment.  This is normally because the .data
417          * segment in the file is extended to provide bss.  It's a neat idea
418          * to try and save a page, but it's a pain in the behind to implement.
419          */
420         copy_len = (offset + filsz) - trunc_page(offset + filsz);
421         map_addr = trunc_page((vm_offset_t)vmaddr + filsz);
422         map_len = round_page((vm_offset_t)vmaddr + memsz) - map_addr;
423
424         /* This had damn well better be true! */
425         if (map_len != 0) {
426                 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
427                 vm_map_lock(&vmspace->vm_map);
428                 rv = vm_map_insert(&vmspace->vm_map, &count,
429                                         NULL, 0,
430                                         map_addr, map_addr + map_len,
431                                         VM_MAPTYPE_NORMAL,
432                                         VM_PROT_ALL, VM_PROT_ALL,
433                                         0);
434                 vm_map_unlock(&vmspace->vm_map);
435                 vm_map_entry_release(count);
436                 if (rv != KERN_SUCCESS) {
437                         return EINVAL; 
438                 }
439         }
440
441         if (copy_len != 0) {
442                 vm_page_t m;
443                 struct lwbuf *lwb;
444
445                 m = vm_fault_object_page(object, trunc_page(offset + filsz),
446                                          VM_PROT_READ, 0, &error);
447                 if (m) {
448                         lwb = lwbuf_alloc(m);
449                         error = copyout((caddr_t)lwbuf_kva(lwb),
450                                         (caddr_t)map_addr, copy_len);
451                         lwbuf_free(lwb);
452                         vm_page_unhold(m);
453                 }
454                 if (error) {
455                         return (error);
456                 }
457         }
458
459         /*
460          * set it to the specified protection
461          */
462         vm_map_protect(&vmspace->vm_map, map_addr, map_addr + map_len,  prot,
463                        FALSE);
464
465         return error;
466 }
467
468 /*
469  * Load the file "file" into memory.  It may be either a shared object
470  * or an executable.
471  *
472  * The "addr" reference parameter is in/out.  On entry, it specifies
473  * the address where a shared object should be loaded.  If the file is
474  * an executable, this value is ignored.  On exit, "addr" specifies
475  * where the file was actually loaded.
476  *
477  * The "entry" reference parameter is out only.  On exit, it specifies
478  * the entry point for the loaded file.
479  */
480 static int
481 elf_load_file(struct proc *p, const char *file, u_long *addr, u_long *entry)
482 {
483         struct {
484                 struct nlookupdata nd;
485                 struct vattr attr;
486                 struct image_params image_params;
487         } *tempdata;
488         const Elf_Ehdr *hdr = NULL;
489         const Elf_Phdr *phdr = NULL;
490         struct nlookupdata *nd;
491         struct vmspace *vmspace = p->p_vmspace;
492         struct vattr *attr;
493         struct image_params *imgp;
494         struct mount *topmnt;
495         vm_prot_t prot;
496         u_long rbase;
497         u_long base_addr = 0;
498         int error, i, numsegs;
499
500         tempdata = kmalloc(sizeof(*tempdata), M_TEMP, M_WAITOK);
501         nd = &tempdata->nd;
502         attr = &tempdata->attr;
503         imgp = &tempdata->image_params;
504
505         /*
506          * Initialize part of the common data
507          */
508         imgp->proc = p;
509         imgp->attr = attr;
510         imgp->firstpage = NULL;
511         imgp->image_header = NULL;
512         imgp->vp = NULL;
513
514         error = nlookup_init(nd, file, UIO_SYSSPACE, NLC_FOLLOW);
515         if (error == 0)
516                 error = nlookup(nd);
517         if (error == 0)
518                 error = cache_vget(&nd->nl_nch, nd->nl_cred, LK_EXCLUSIVE, &imgp->vp);
519         topmnt = nd->nl_nch.mount;
520         nlookup_done(nd);
521         if (error)
522                 goto fail;
523
524         /*
525          * Check permissions, modes, uid, etc on the file, and "open" it.
526          */
527         error = exec_check_permissions(imgp, topmnt);
528         if (error) {
529                 vn_unlock(imgp->vp);
530                 goto fail;
531         }
532
533         error = exec_map_first_page(imgp);
534         /*
535          * Also make certain that the interpreter stays the same, so set
536          * its VTEXT flag, too.
537          */
538         if (error == 0)
539                 vsetflags(imgp->vp, VTEXT);
540         vn_unlock(imgp->vp);
541         if (error)
542                 goto fail;
543
544         hdr = (const Elf_Ehdr *)imgp->image_header;
545         if ((error = elf_check_header(hdr)) != 0)
546                 goto fail;
547         if (hdr->e_type == ET_DYN)
548                 rbase = *addr;
549         else if (hdr->e_type == ET_EXEC)
550                 rbase = 0;
551         else {
552                 error = ENOEXEC;
553                 goto fail;
554         }
555
556         /* Only support headers that fit within first page for now
557          * (multiplication of two Elf_Half fields will not overflow) */
558         if ((hdr->e_phoff > PAGE_SIZE) ||
559             (hdr->e_phentsize * hdr->e_phnum) > PAGE_SIZE - hdr->e_phoff) {
560                 error = ENOEXEC;
561                 goto fail;
562         }
563
564         phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
565
566         for (i = 0, numsegs = 0; i < hdr->e_phnum; i++) {
567                 if (phdr[i].p_type == PT_LOAD) {        /* Loadable segment */
568                         prot = 0;
569                         if (phdr[i].p_flags & PF_X)
570                                 prot |= VM_PROT_EXECUTE;
571                         if (phdr[i].p_flags & PF_W)
572                                 prot |= VM_PROT_WRITE;
573                         if (phdr[i].p_flags & PF_R)
574                                 prot |= VM_PROT_READ;
575
576                         error = elf_load_section(
577                                     p, vmspace, imgp->vp,
578                                     phdr[i].p_offset,
579                                     (caddr_t)phdr[i].p_vaddr +
580                                     rbase,
581                                     phdr[i].p_memsz,
582                                     phdr[i].p_filesz, prot);
583                         if (error != 0)
584                                 goto fail;
585                         /*
586                          * Establish the base address if this is the
587                          * first segment.
588                          */
589                         if (numsegs == 0)
590                                 base_addr = trunc_page(phdr[i].p_vaddr + rbase);
591                         numsegs++;
592                 }
593         }
594         *addr = base_addr;
595         *entry=(unsigned long)hdr->e_entry + rbase;
596
597 fail:
598         if (imgp->firstpage)
599                 exec_unmap_first_page(imgp);
600         if (imgp->vp) {
601                 vrele(imgp->vp);
602                 imgp->vp = NULL;
603         }
604         kfree(tempdata, M_TEMP);
605
606         return error;
607 }
608
609 /*
610  * non static, as it can be overridden by start_init()
611  */
612 int fallback_elf_brand = -1;
613 SYSCTL_INT(_kern, OID_AUTO, fallback_elf_brand, CTLFLAG_RW,
614                 &fallback_elf_brand, -1,
615                 "ELF brand of last resort");
616
617 static int can_exec_dyn = 1;
618 SYSCTL_INT(_kern, OID_AUTO, elf_exec_dyn, CTLFLAG_RW,
619                 &can_exec_dyn, 1,
620                 "ELF: can exec shared libraries");
621
622 static int
623 exec_elf_imgact(struct image_params *imgp)
624 {
625         const Elf_Ehdr *hdr = (const Elf_Ehdr *) imgp->image_header;
626         const Elf_Phdr *phdr;
627         Elf_Auxargs *elf_auxargs = NULL;
628         struct vmspace *vmspace;
629         vm_prot_t prot;
630         u_long text_size = 0, data_size = 0, total_size = 0;
631         u_long text_addr = 0, data_addr = 0;
632         u_long seg_size, seg_addr;
633         u_long addr, entry = 0, proghdr = 0;
634         int error, i;
635         const char *interp = NULL;
636         const Elf_Note *abi_note = NULL;
637         Elf_Brandinfo *brand_info = NULL;
638         char *path;
639
640         error = 0;
641
642         /*
643          * Do we have a valid ELF header ?
644          * We allow execution of ET_EXEC and, if kern.elf_exec_dyn is 1, ET_DYN.
645          */
646         if (elf_check_header(hdr) != 0 ||
647             (hdr->e_type != ET_EXEC && (!can_exec_dyn || hdr->e_type != ET_DYN)))
648                 return -1;
649
650         /*
651          * From here on down, we return an errno, not -1, as we've
652          * detected an ELF file.
653          */
654
655         if ((hdr->e_phoff > PAGE_SIZE) ||
656             (hdr->e_phoff + hdr->e_phentsize * hdr->e_phnum) > PAGE_SIZE) {
657                 /* Only support headers in first page for now */
658                 return ENOEXEC;
659         }
660         phdr = (const Elf_Phdr*)(imgp->image_header + hdr->e_phoff);
661         
662         /*
663          * From this point on, we may have resources that need to be freed.
664          */
665
666         exec_new_vmspace(imgp, NULL);
667
668         /*
669          * Yeah, I'm paranoid.  There is every reason in the world to get
670          * VTEXT now since from here on out, there are places we can have
671          * a context switch.  Better safe than sorry; I really don't want
672          * the file to change while it's being loaded.
673          */
674         vsetflags(imgp->vp, VTEXT);
675
676         vmspace = imgp->proc->p_vmspace;
677
678         for (i = 0; i < hdr->e_phnum; i++) {
679                 switch(phdr[i].p_type) {
680
681                 case PT_LOAD:   /* Loadable segment */
682                         prot = 0;
683                         if (phdr[i].p_flags & PF_X)
684                                 prot |= VM_PROT_EXECUTE;
685                         if (phdr[i].p_flags & PF_W)
686                                 prot |= VM_PROT_WRITE;
687                         if (phdr[i].p_flags & PF_R)
688                                 prot |= VM_PROT_READ;
689
690                         if ((error = elf_load_section(imgp->proc,
691                                                      vmspace, imgp->vp,
692                                                      phdr[i].p_offset,
693                                                      (caddr_t)phdr[i].p_vaddr,
694                                                      phdr[i].p_memsz,
695                                                      phdr[i].p_filesz, prot)) != 0)
696                                 goto fail;
697
698                         /*
699                          * If this segment contains the program headers,
700                          * remember their virtual address for the AT_PHDR
701                          * aux entry. Static binaries don't usually include
702                          * a PT_PHDR entry.
703                          */
704                         if (phdr[i].p_offset == 0 &&
705                             hdr->e_phoff + hdr->e_phnum * hdr->e_phentsize
706                                 <= phdr[i].p_filesz)
707                                 proghdr = phdr[i].p_vaddr + hdr->e_phoff;
708
709                         seg_addr = trunc_page(phdr[i].p_vaddr);
710                         seg_size = round_page(phdr[i].p_memsz +
711                                 phdr[i].p_vaddr - seg_addr);
712
713                         /*
714                          * Is this .text or .data?  We can't use
715                          * VM_PROT_WRITE or VM_PROT_EXEC, it breaks the
716                          * alpha terribly and possibly does other bad
717                          * things so we stick to the old way of figuring
718                          * it out:  If the segment contains the program
719                          * entry point, it's a text segment, otherwise it
720                          * is a data segment.
721                          *
722                          * Note that obreak() assumes that data_addr + 
723                          * data_size == end of data load area, and the ELF
724                          * file format expects segments to be sorted by
725                          * address.  If multiple data segments exist, the
726                          * last one will be used.
727                          */
728                         if (hdr->e_entry >= phdr[i].p_vaddr &&
729                             hdr->e_entry < (phdr[i].p_vaddr +
730                             phdr[i].p_memsz)) {
731                                 text_size = seg_size;
732                                 text_addr = seg_addr;
733                                 entry = (u_long)hdr->e_entry;
734                         } else {
735                                 data_size = seg_size;
736                                 data_addr = seg_addr;
737                         }
738                         total_size += seg_size;
739
740                         /*
741                          * Check limits.  It should be safe to check the
742                          * limits after loading the segment since we do
743                          * not actually fault in all the segment's pages.
744                          */
745                         if (data_size >
746                             imgp->proc->p_rlimit[RLIMIT_DATA].rlim_cur ||
747                             text_size > maxtsiz ||
748                             total_size >
749                             imgp->proc->p_rlimit[RLIMIT_VMEM].rlim_cur) {
750                                 error = ENOMEM;
751                                 goto fail;
752                         }
753                         break;
754                 case PT_INTERP: /* Path to interpreter */
755                         if (phdr[i].p_filesz > MAXPATHLEN ||
756                             phdr[i].p_offset + phdr[i].p_filesz > PAGE_SIZE) {
757                                 error = ENOEXEC;
758                                 goto fail;
759                         }
760                         interp = imgp->image_header + phdr[i].p_offset;
761                         break;
762                 case PT_NOTE:   /* Check for .note.ABI-tag */
763                         if (brand_info == NULL)
764                                 brand_info = elf_check_abi_note(imgp, &phdr[i]);
765                         break;
766                 case PT_PHDR:   /* Program header table info */
767                         proghdr = phdr[i].p_vaddr;
768                         break;
769                 default:
770                         break;
771                 }
772         }
773
774         vmspace->vm_tsize = text_size >> PAGE_SHIFT;
775         vmspace->vm_taddr = (caddr_t)(uintptr_t)text_addr;
776         vmspace->vm_dsize = data_size >> PAGE_SHIFT;
777         vmspace->vm_daddr = (caddr_t)(uintptr_t)data_addr;
778
779         addr = ELF_RTLD_ADDR(vmspace);
780
781         imgp->entry_addr = entry;
782
783         /* We support three types of branding -- (1) the ELF EI_OSABI field
784          * that SCO added to the ELF spec, (2) FreeBSD 3.x's traditional string
785          * branding w/in the ELF header, and (3) path of the `interp_path'
786          * field.  We should also look for an ".note.ABI-tag" ELF section now
787          * in all Linux ELF binaries, FreeBSD 4.1+, and some NetBSD ones.
788          */
789
790         /* If the executable has a brand, search for it in the brand list. */
791         if (brand_info == NULL && hdr->e_ident[EI_OSABI] != ELFOSABI_NONE) {
792                 for (i = 0;  i < MAX_BRANDS;  i++) {
793                         Elf_Brandinfo *bi = elf_brand_list[i];
794
795                         if (bi != NULL && 
796                             (hdr->e_ident[EI_OSABI] == bi->brand
797                             || 0 == 
798                             strncmp((const char *)&hdr->e_ident[OLD_EI_BRAND], 
799                             bi->compat_3_brand, strlen(bi->compat_3_brand)))) {
800                                 brand_info = bi;
801                                 break;
802                         }
803                 }
804         }
805
806         /* Search for a recognized ABI. */
807         if (brand_info == NULL && abi_note != NULL) {
808         }
809
810         /*
811          * ELFOSABI_NONE == ELFOSABI_SYSV, so a SYSV binary misses all
812          * checks so far, since it is neither branded nor does it have
813          * an ABI note.  If the EI_OSABI field is ELFOSABI_NONE, assume
814          * it is svr4 and look for an entry in the elf_brand_list with
815          * match_abi_note == NULL.
816          */
817         if (brand_info == NULL && hdr->e_ident[EI_OSABI] == ELFOSABI_NONE) {
818                 for (i = 0; i < MAX_BRANDS; i++) {
819                         Elf_Brandinfo *bi = elf_brand_list[i];
820
821                         if (bi != NULL && bi->match_abi_note == NULL &&
822                             ELFOSABI_SYSV == bi->brand) {
823                                 brand_info = bi;
824                                 break;
825                         }
826                 }
827         }
828
829         /* Lacking a recognized ABI, search for a recognized interpreter. */
830         if (brand_info == NULL && interp != NULL) {
831                 for (i = 0;  i < MAX_BRANDS;  i++) {
832                         Elf_Brandinfo *bi = elf_brand_list[i];
833
834                         if (bi != NULL &&
835                             strcmp(interp, bi->interp_path) == 0) {
836                                 brand_info = bi;
837                                 break;
838                         }
839                 }
840         }
841
842         /* Lacking a recognized interpreter, try the default brand */
843         if (brand_info == NULL) {
844                 for (i = 0; i < MAX_BRANDS; i++) {
845                         Elf_Brandinfo *bi = elf_brand_list[i];
846
847                         if (bi != NULL && fallback_elf_brand == bi->brand) {
848                                 brand_info = bi;
849                                 break;
850                         }
851                 }
852         }
853
854         if (brand_info == NULL) {
855                 uprintf("ELF binary type \"%u\" not known.\n",
856                     hdr->e_ident[EI_OSABI]);
857                 error = ENOEXEC;
858                 goto fail;
859         }
860
861         imgp->proc->p_sysent = brand_info->sysvec;
862         EVENTHANDLER_INVOKE(process_exec, imgp);
863
864         if (interp != NULL) {
865                 path = kmalloc(MAXPATHLEN, M_TEMP, M_WAITOK);
866                 ksnprintf(path, MAXPATHLEN, "%s%s",
867                          brand_info->emul_path, interp);
868                 if ((error = elf_load_file(imgp->proc, path, &addr,
869                                            &imgp->entry_addr)) != 0) {
870                         if ((error = elf_load_file(imgp->proc, interp, &addr,
871                                                    &imgp->entry_addr)) != 0) {
872                                 uprintf("ELF interpreter %s not found\n", path);
873                                 kfree(path, M_TEMP);
874                                 goto fail;
875                         }
876                 }
877                 kfree(path, M_TEMP);
878         } else {
879                 addr = 0;
880         }
881
882         /*
883          * Construct auxargs table (used by the fixup routine)
884          */
885         elf_auxargs = kmalloc(sizeof(Elf_Auxargs), M_TEMP, M_WAITOK);
886         elf_auxargs->execfd = -1;
887         elf_auxargs->phdr = proghdr;
888         elf_auxargs->phent = hdr->e_phentsize;
889         elf_auxargs->phnum = hdr->e_phnum;
890         elf_auxargs->pagesz = PAGE_SIZE;
891         elf_auxargs->base = addr;
892         elf_auxargs->flags = 0;
893         elf_auxargs->entry = entry;
894         elf_auxargs->trace = elf_trace;
895
896         imgp->auxargs = elf_auxargs;
897         imgp->interpreted = 0;
898
899 fail:
900         return error;
901 }
902
903 static int
904 elf_freebsd_fixup(register_t **stack_base, struct image_params *imgp)
905 {
906         Elf_Auxargs *args = (Elf_Auxargs *)imgp->auxargs;
907         register_t *pos;
908
909         pos = *stack_base + (imgp->args->argc + imgp->args->envc + 2);
910
911         if (args->trace) {
912                 AUXARGS_ENTRY(pos, AT_DEBUG, 1);
913         }
914         if (args->execfd != -1) {
915                 AUXARGS_ENTRY(pos, AT_EXECFD, args->execfd);
916         }
917         AUXARGS_ENTRY(pos, AT_PHDR, args->phdr);
918         AUXARGS_ENTRY(pos, AT_PHENT, args->phent);
919         AUXARGS_ENTRY(pos, AT_PHNUM, args->phnum);
920         AUXARGS_ENTRY(pos, AT_PAGESZ, args->pagesz);
921         AUXARGS_ENTRY(pos, AT_FLAGS, args->flags);
922         AUXARGS_ENTRY(pos, AT_ENTRY, args->entry);
923         AUXARGS_ENTRY(pos, AT_BASE, args->base);
924         AUXARGS_ENTRY(pos, AT_NULL, 0);
925
926         kfree(imgp->auxargs, M_TEMP);
927         imgp->auxargs = NULL;
928
929         (*stack_base)--;
930         suword(*stack_base, (long) imgp->args->argc);
931         return 0;
932
933
934 /*
935  * Code for generating ELF core dumps.
936  */
937
938 typedef int (*segment_callback) (vm_map_entry_t, void *);
939
940 /* Closure for cb_put_phdr(). */
941 struct phdr_closure {
942         Elf_Phdr *phdr;         /* Program header to fill in (incremented) */
943         Elf_Phdr *phdr_max;     /* Pointer bound for error check */
944         Elf_Off offset;         /* Offset of segment in core file */
945 };
946
947 /* Closure for cb_size_segment(). */
948 struct sseg_closure {
949         int count;              /* Count of writable segments. */
950         size_t vsize;           /* Total size of all writable segments. */
951 };
952
953 /* Closure for cb_put_fp(). */
954 struct fp_closure {
955         struct vn_hdr *vnh;
956         struct vn_hdr *vnh_max;
957         int count;
958         struct stat *sb;
959 };
960
961 typedef struct elf_buf {
962         char    *buf;
963         size_t  off;
964         size_t  off_max;
965 } *elf_buf_t;
966
967 static void *target_reserve(elf_buf_t target, size_t bytes, int *error);
968
969 static int cb_put_phdr (vm_map_entry_t, void *);
970 static int cb_size_segment (vm_map_entry_t, void *);
971 static int cb_fpcount_segment(vm_map_entry_t, void *);
972 static int cb_put_fp(vm_map_entry_t, void *);
973
974
975 static int each_segment (struct proc *, segment_callback, void *, int);
976 static int elf_corehdr (struct lwp *, int, struct file *, struct ucred *,
977                         int, elf_buf_t);
978 enum putmode { WRITE, DRYRUN };
979 static int elf_puthdr (struct lwp *, elf_buf_t, int sig, enum putmode,
980                         int, struct file *);
981 static int elf_putallnotes(struct lwp *, elf_buf_t, int, enum putmode);
982 static int elf_putnote (elf_buf_t, const char *, int, const void *, size_t);
983
984 static int elf_putsigs(struct lwp *, elf_buf_t);
985 static int elf_puttextvp(struct proc *, elf_buf_t);
986 static int elf_putfiles(struct proc *, elf_buf_t, struct file *);
987
988 extern int osreldate;
989
990 int
991 elf_coredump(struct lwp *lp, int sig, struct vnode *vp, off_t limit)
992 {
993         struct file *fp; 
994         int error;
995
996         if ((error = falloc(NULL, &fp, NULL)) != 0)
997                 return (error);
998         fsetcred(fp, lp->lwp_proc->p_ucred);
999
1000         /*
1001          * XXX fixme.
1002          */
1003         fp->f_type = DTYPE_VNODE;
1004         fp->f_flag = O_CREAT|O_WRONLY|O_NOFOLLOW;
1005         fp->f_ops = &vnode_fileops;
1006         fp->f_data = vp;
1007         vn_unlock(vp);
1008         
1009         error = generic_elf_coredump(lp, sig, fp, limit);
1010
1011         fp->f_type = 0;
1012         fp->f_flag = 0;
1013         fp->f_ops = &badfileops;
1014         fp->f_data = NULL;
1015         fdrop(fp);
1016         return (error);
1017 }
1018
1019 int
1020 generic_elf_coredump(struct lwp *lp, int sig, struct file *fp, off_t limit)
1021 {
1022         struct proc *p = lp->lwp_proc;
1023         struct ucred *cred = p->p_ucred;
1024         int error = 0;
1025         struct sseg_closure seginfo;
1026         struct elf_buf target;
1027
1028         if (!fp)
1029                 kprintf("can't dump core - null fp\n");
1030
1031         /*
1032          * Size the program segments
1033          */
1034         seginfo.count = 0;
1035         seginfo.vsize = 0;
1036         each_segment(p, cb_size_segment, &seginfo, 1);
1037
1038         /*
1039          * Calculate the size of the core file header area by making
1040          * a dry run of generating it.  Nothing is written, but the
1041          * size is calculated.
1042          */
1043         bzero(&target, sizeof(target));
1044         elf_puthdr(lp, &target, sig, DRYRUN, seginfo.count, fp);
1045
1046         if (target.off + seginfo.vsize >= limit)
1047                 return (EFAULT);
1048
1049         /*
1050          * Allocate memory for building the header, fill it up,
1051          * and write it out.
1052          */
1053         target.off_max = target.off;
1054         target.off = 0;
1055         target.buf = kmalloc(target.off_max, M_TEMP, M_WAITOK|M_ZERO);
1056
1057         error = elf_corehdr(lp, sig, fp, cred, seginfo.count, &target);
1058
1059         /* Write the contents of all of the writable segments. */
1060         if (error == 0) {
1061                 Elf_Phdr *php;
1062                 int i;
1063                 ssize_t nbytes;
1064
1065                 php = (Elf_Phdr *)(target.buf + sizeof(Elf_Ehdr)) + 1;
1066                 for (i = 0; i < seginfo.count; i++) {
1067                         error = fp_write(fp, (caddr_t)php->p_vaddr,
1068                                         php->p_filesz, &nbytes, UIO_USERSPACE);
1069                         if (error != 0)
1070                                 break;
1071                         php++;
1072                 }
1073         }
1074         kfree(target.buf, M_TEMP);
1075         
1076         return error;
1077 }
1078
1079 /*
1080  * A callback for each_segment() to write out the segment's
1081  * program header entry.
1082  */
1083 static int
1084 cb_put_phdr(vm_map_entry_t entry, void *closure)
1085 {
1086         struct phdr_closure *phc = closure;
1087         Elf_Phdr *phdr = phc->phdr;
1088
1089         if (phc->phdr == phc->phdr_max)
1090                 return EINVAL;
1091
1092         phc->offset = round_page(phc->offset);
1093
1094         phdr->p_type = PT_LOAD;
1095         phdr->p_offset = phc->offset;
1096         phdr->p_vaddr = entry->start;
1097         phdr->p_paddr = 0;
1098         phdr->p_filesz = phdr->p_memsz = entry->end - entry->start;
1099         phdr->p_align = PAGE_SIZE;
1100         phdr->p_flags = 0;
1101         if (entry->protection & VM_PROT_READ)
1102                 phdr->p_flags |= PF_R;
1103         if (entry->protection & VM_PROT_WRITE)
1104                 phdr->p_flags |= PF_W;
1105         if (entry->protection & VM_PROT_EXECUTE)
1106                 phdr->p_flags |= PF_X;
1107
1108         phc->offset += phdr->p_filesz;
1109         ++phc->phdr;
1110         return 0;
1111 }
1112
1113 /*
1114  * A callback for each_writable_segment() to gather information about
1115  * the number of segments and their total size.
1116  */
1117 static int
1118 cb_size_segment(vm_map_entry_t entry, void *closure)
1119 {
1120         struct sseg_closure *ssc = closure;
1121
1122         ++ssc->count;
1123         ssc->vsize += entry->end - entry->start;
1124         return 0;
1125 }
1126
1127 /*
1128  * A callback for each_segment() to gather information about
1129  * the number of text segments.
1130  */
1131 static int
1132 cb_fpcount_segment(vm_map_entry_t entry, void *closure)
1133 {
1134         int *count = closure;
1135         struct vnode *vp;
1136
1137         if (entry->object.vm_object->type == OBJT_VNODE) {
1138                 vp = (struct vnode *)entry->object.vm_object->handle;
1139                 if ((vp->v_flag & VCKPT) && curproc->p_textvp == vp)
1140                         return 0;
1141                 ++*count;
1142         }
1143         return 0;
1144 }
1145
1146 static int
1147 cb_put_fp(vm_map_entry_t entry, void *closure) 
1148 {
1149         struct fp_closure *fpc = closure;
1150         struct vn_hdr *vnh = fpc->vnh;
1151         Elf_Phdr *phdr = &vnh->vnh_phdr;
1152         struct vnode *vp;
1153         int error;
1154
1155         /*
1156          * If an entry represents a vnode then write out a file handle.
1157          *
1158          * If we are checkpointing a checkpoint-restored program we do
1159          * NOT record the filehandle for the old checkpoint vnode (which
1160          * is mapped all over the place).  Instead we rely on the fact
1161          * that a checkpoint-restored program does not mmap() the checkpt
1162          * vnode NOCORE, so its contents will be written out to the
1163          * new checkpoint file.  This is necessary because the 'old'
1164          * checkpoint file is typically destroyed when a new one is created
1165          * and thus cannot be used to restore the new checkpoint.
1166          *
1167          * Theoretically we could create a chain of checkpoint files and
1168          * operate the checkpointing operation kinda like an incremental
1169          * checkpoint, but a checkpoint restore would then likely wind up
1170          * referencing many prior checkpoint files and that is a bit over
1171          * the top for the purpose of the checkpoint API.
1172          */
1173         if (entry->object.vm_object->type == OBJT_VNODE) {
1174                 vp = (struct vnode *)entry->object.vm_object->handle;
1175                 if ((vp->v_flag & VCKPT) && curproc->p_textvp == vp)
1176                         return 0;
1177                 if (vnh == fpc->vnh_max)
1178                         return EINVAL;
1179
1180                 if (vp->v_mount)
1181                         vnh->vnh_fh.fh_fsid = vp->v_mount->mnt_stat.f_fsid;
1182                 error = VFS_VPTOFH(vp, &vnh->vnh_fh.fh_fid);
1183                 if (error) {
1184                         char *freepath, *fullpath;
1185
1186                         if (vn_fullpath(curproc, vp, &fullpath, &freepath, 0)) {
1187                                 kprintf("Warning: coredump, error %d: cannot store file handle for vnode %p\n", error, vp);
1188                         } else {
1189                                 kprintf("Warning: coredump, error %d: cannot store file handle for %s\n", error, fullpath);
1190                                 kfree(freepath, M_TEMP);
1191                         }
1192                         error = 0;
1193                 }
1194
1195                 phdr->p_type = PT_LOAD;
1196                 phdr->p_offset = 0;        /* not written to core */
1197                 phdr->p_vaddr = entry->start;
1198                 phdr->p_paddr = 0;
1199                 phdr->p_filesz = phdr->p_memsz = entry->end - entry->start;
1200                 phdr->p_align = PAGE_SIZE;
1201                 phdr->p_flags = 0;
1202                 if (entry->protection & VM_PROT_READ)
1203                         phdr->p_flags |= PF_R;
1204                 if (entry->protection & VM_PROT_WRITE)
1205                         phdr->p_flags |= PF_W;
1206                 if (entry->protection & VM_PROT_EXECUTE)
1207                         phdr->p_flags |= PF_X;
1208                 ++fpc->vnh;
1209                 ++fpc->count;
1210         }
1211         return 0;
1212 }
1213
1214 /*
1215  * For each writable segment in the process's memory map, call the given
1216  * function with a pointer to the map entry and some arbitrary
1217  * caller-supplied data.
1218  */
1219 static int
1220 each_segment(struct proc *p, segment_callback func, void *closure, int writable)
1221 {
1222         int error = 0;
1223         vm_map_t map = &p->p_vmspace->vm_map;
1224         vm_map_entry_t entry;
1225
1226         for (entry = map->header.next; error == 0 && entry != &map->header;
1227             entry = entry->next) {
1228                 vm_object_t obj;
1229
1230                 /*
1231                  * Don't dump inaccessible mappings, deal with legacy
1232                  * coredump mode.
1233                  *
1234                  * Note that read-only segments related to the elf binary
1235                  * are marked MAP_ENTRY_NOCOREDUMP now so we no longer
1236                  * need to arbitrarily ignore such segments.
1237                  */
1238                 if (elf_legacy_coredump) {
1239                         if (writable && (entry->protection & VM_PROT_RW) != VM_PROT_RW)
1240                                 continue;
1241                 } else {
1242                         if (writable && (entry->protection & VM_PROT_ALL) == 0)
1243                                 continue;
1244                 }
1245
1246                 /*
1247                  * Dont include memory segment in the coredump if
1248                  * MAP_NOCORE is set in mmap(2) or MADV_NOCORE in
1249                  * madvise(2).
1250                  *
1251                  * Currently we only dump normal VM object maps.  We do
1252                  * not dump submaps or virtual page tables.
1253                  */
1254                 if (writable && (entry->eflags & MAP_ENTRY_NOCOREDUMP))
1255                         continue;
1256                 if (entry->maptype != VM_MAPTYPE_NORMAL)
1257                         continue;
1258                 if ((obj = entry->object.vm_object) == NULL)
1259                         continue;
1260
1261                 /* Find the deepest backing object. */
1262                 while (obj->backing_object != NULL)
1263                         obj = obj->backing_object;
1264
1265                 /* Ignore memory-mapped devices and such things. */
1266                 if (obj->type != OBJT_DEFAULT &&
1267                     obj->type != OBJT_SWAP &&
1268                     obj->type != OBJT_VNODE)
1269                         continue;
1270
1271                 error = (*func)(entry, closure);
1272         }
1273         return error;
1274 }
1275
1276 static
1277 void *
1278 target_reserve(elf_buf_t target, size_t bytes, int *error)
1279 {
1280     void *res = NULL;
1281
1282     if (target->buf) {
1283             if (target->off + bytes > target->off_max)
1284                     *error = EINVAL;
1285             else
1286                     res = target->buf + target->off;
1287     }
1288     target->off += bytes;
1289     return (res);
1290 }
1291
1292 /*
1293  * Write the core file header to the file, including padding up to
1294  * the page boundary.
1295  */
1296 static int
1297 elf_corehdr(struct lwp *lp, int sig, struct file *fp, struct ucred *cred,
1298             int numsegs, elf_buf_t target)
1299 {
1300         int error;
1301         ssize_t nbytes;
1302
1303         /*
1304          * Fill in the header.  The fp is passed so we can detect and flag
1305          * a checkpoint file pointer within the core file itself, because
1306          * it may not be restored from the same file handle.
1307          */
1308         error = elf_puthdr(lp, target, sig, WRITE, numsegs, fp);
1309
1310         /* Write it to the core file. */
1311         if (error == 0) {
1312                 error = fp_write(fp, target->buf, target->off, &nbytes,
1313                                  UIO_SYSSPACE);
1314         }
1315         return error;
1316 }
1317
1318 static int
1319 elf_puthdr(struct lwp *lp, elf_buf_t target, int sig, enum putmode mode,
1320     int numsegs, struct file *fp)
1321 {
1322         struct proc *p = lp->lwp_proc;
1323         int error = 0;
1324         size_t phoff;
1325         size_t noteoff;
1326         size_t notesz;
1327         Elf_Ehdr *ehdr;
1328         Elf_Phdr *phdr;
1329
1330         ehdr = target_reserve(target, sizeof(Elf_Ehdr), &error);
1331
1332         phoff = target->off;
1333         phdr = target_reserve(target, (numsegs + 1) * sizeof(Elf_Phdr), &error);
1334
1335         noteoff = target->off;
1336         if (error == 0)
1337                 elf_putallnotes(lp, target, sig, mode);
1338         notesz = target->off - noteoff;
1339
1340         /*
1341          * put extra cruft for dumping process state here 
1342          *  - we really want it be before all the program 
1343          *    mappings
1344          *  - we just need to update the offset accordingly
1345          *    and GDB will be none the wiser.
1346          */
1347         if (error == 0)
1348                 error = elf_puttextvp(p, target);
1349         if (error == 0)
1350                 error = elf_putsigs(lp, target);
1351         if (error == 0)
1352                 error = elf_putfiles(p, target, fp);
1353
1354         /*
1355          * Align up to a page boundary for the program segments.  The
1356          * actual data will be written to the outptu file, not to elf_buf_t,
1357          * so we do not have to do any further bounds checking.
1358          */
1359         target->off = round_page(target->off);
1360         if (error == 0 && ehdr != NULL) {
1361                 /*
1362                  * Fill in the ELF header.
1363                  */
1364                 ehdr->e_ident[EI_MAG0] = ELFMAG0;
1365                 ehdr->e_ident[EI_MAG1] = ELFMAG1;
1366                 ehdr->e_ident[EI_MAG2] = ELFMAG2;
1367                 ehdr->e_ident[EI_MAG3] = ELFMAG3;
1368                 ehdr->e_ident[EI_CLASS] = ELF_CLASS;
1369                 ehdr->e_ident[EI_DATA] = ELF_DATA;
1370                 ehdr->e_ident[EI_VERSION] = EV_CURRENT;
1371                 ehdr->e_ident[EI_OSABI] = ELFOSABI_NONE;
1372                 ehdr->e_ident[EI_ABIVERSION] = 0;
1373                 ehdr->e_ident[EI_PAD] = 0;
1374                 ehdr->e_type = ET_CORE;
1375                 ehdr->e_machine = ELF_ARCH;
1376                 ehdr->e_version = EV_CURRENT;
1377                 ehdr->e_entry = 0;
1378                 ehdr->e_phoff = phoff;
1379                 ehdr->e_flags = 0;
1380                 ehdr->e_ehsize = sizeof(Elf_Ehdr);
1381                 ehdr->e_phentsize = sizeof(Elf_Phdr);
1382                 ehdr->e_phnum = numsegs + 1;
1383                 ehdr->e_shentsize = sizeof(Elf_Shdr);
1384                 ehdr->e_shnum = 0;
1385                 ehdr->e_shstrndx = SHN_UNDEF;
1386         }
1387         if (error == 0 && phdr != NULL) {
1388                 /*
1389                  * Fill in the program header entries.
1390                  */
1391                 struct phdr_closure phc;
1392
1393                 /* The note segement. */
1394                 phdr->p_type = PT_NOTE;
1395                 phdr->p_offset = noteoff;
1396                 phdr->p_vaddr = 0;
1397                 phdr->p_paddr = 0;
1398                 phdr->p_filesz = notesz;
1399                 phdr->p_memsz = 0;
1400                 phdr->p_flags = 0;
1401                 phdr->p_align = 0;
1402                 ++phdr;
1403
1404                 /* All the writable segments from the program. */
1405                 phc.phdr = phdr;
1406                 phc.phdr_max = phdr + numsegs;
1407                 phc.offset = target->off;
1408                 each_segment(p, cb_put_phdr, &phc, 1);
1409         }
1410         return (error);
1411 }
1412
1413 /*
1414  * Append core dump notes to target ELF buffer or simply update target size
1415  * if dryrun selected.
1416  */
1417 static int
1418 elf_putallnotes(struct lwp *corelp, elf_buf_t target, int sig,
1419     enum putmode mode)
1420 {
1421         struct proc *p = corelp->lwp_proc;
1422         int error;
1423         struct {
1424                 prstatus_t status;
1425                 prfpregset_t fpregs;
1426                 prpsinfo_t psinfo;
1427         } *tmpdata;
1428         prstatus_t *status;
1429         prfpregset_t *fpregs;
1430         prpsinfo_t *psinfo;
1431         struct lwp *lp;
1432
1433         /*
1434          * Allocate temporary storage for notes on heap to avoid stack overflow.
1435          */
1436         if (mode != DRYRUN) {
1437                 tmpdata = kmalloc(sizeof(*tmpdata), M_TEMP, M_ZERO | M_WAITOK);
1438                 status = &tmpdata->status;
1439                 fpregs = &tmpdata->fpregs;
1440                 psinfo = &tmpdata->psinfo;
1441         } else {
1442                 tmpdata = NULL;
1443                 status = NULL;
1444                 fpregs = NULL;
1445                 psinfo = NULL;
1446         }
1447
1448         /*
1449          * Append LWP-agnostic note.
1450          */
1451         if (mode != DRYRUN) {
1452                 psinfo->pr_version = PRPSINFO_VERSION;
1453                 psinfo->pr_psinfosz = sizeof(prpsinfo_t);
1454                 strncpy(psinfo->pr_fname, p->p_comm,
1455                         sizeof(psinfo->pr_fname) - 1);
1456                 /*
1457                  * XXX - We don't fill in the command line arguments
1458                  * properly yet.
1459                  */
1460                 strncpy(psinfo->pr_psargs, p->p_comm, PRARGSZ);
1461         }
1462         error =
1463             elf_putnote(target, "CORE", NT_PRPSINFO, psinfo, sizeof *psinfo);
1464         if (error)
1465                 goto exit;
1466
1467         /*
1468          * Append first note for LWP that triggered core so that it is
1469          * the selected one when the debugger starts.
1470          */
1471         if (mode != DRYRUN) {
1472                 status->pr_version = PRSTATUS_VERSION;
1473                 status->pr_statussz = sizeof(prstatus_t);
1474                 status->pr_gregsetsz = sizeof(gregset_t);
1475                 status->pr_fpregsetsz = sizeof(fpregset_t);
1476                 status->pr_osreldate = osreldate;
1477                 status->pr_cursig = sig;
1478                 /*
1479                  * XXX GDB needs unique pr_pid for each LWP and does not
1480                  * not support pr_pid==0 but lwp_tid can be 0, so hack unique
1481                  * value.
1482                  */
1483                 status->pr_pid = corelp->lwp_tid;
1484                 fill_regs(corelp, &status->pr_reg);
1485                 fill_fpregs(corelp, fpregs);
1486         }
1487         error =
1488             elf_putnote(target, "CORE", NT_PRSTATUS, status, sizeof *status);
1489         if (error)
1490                 goto exit;
1491         error =
1492             elf_putnote(target, "CORE", NT_FPREGSET, fpregs, sizeof *fpregs);
1493         if (error)
1494                 goto exit;
1495
1496         /*
1497          * Then append notes for other LWPs.
1498          */
1499         FOREACH_LWP_IN_PROC(lp, p) {
1500                 if (lp == corelp)
1501                         continue;
1502                 /* skip lwps being created */
1503                 if (lp->lwp_thread == NULL)
1504                         continue;
1505                 if (mode != DRYRUN) {
1506                         status->pr_pid = lp->lwp_tid;
1507                         fill_regs(lp, &status->pr_reg);
1508                         fill_fpregs(lp, fpregs);
1509                 }
1510                 error = elf_putnote(target, "CORE", NT_PRSTATUS,
1511                                         status, sizeof *status);
1512                 if (error)
1513                         goto exit;
1514                 error = elf_putnote(target, "CORE", NT_FPREGSET,
1515                                         fpregs, sizeof *fpregs);
1516                 if (error)
1517                         goto exit;
1518         }
1519
1520 exit:
1521         if (tmpdata != NULL)
1522                 kfree(tmpdata, M_TEMP);
1523         return (error);
1524 }
1525
1526 /*
1527  * Generate a note sub-structure.
1528  *
1529  * NOTE: 4-byte alignment.
1530  */
1531 static int
1532 elf_putnote(elf_buf_t target, const char *name, int type,
1533             const void *desc, size_t descsz)
1534 {
1535         int error = 0;
1536         char *dst;
1537         Elf_Note note;
1538
1539         note.n_namesz = strlen(name) + 1;
1540         note.n_descsz = descsz;
1541         note.n_type = type;
1542         dst = target_reserve(target, sizeof(note), &error);
1543         if (dst != NULL)
1544                 bcopy(&note, dst, sizeof note);
1545         dst = target_reserve(target, note.n_namesz, &error);
1546         if (dst != NULL)
1547                 bcopy(name, dst, note.n_namesz);
1548         target->off = roundup2(target->off, sizeof(Elf_Word));
1549         dst = target_reserve(target, note.n_descsz, &error);
1550         if (dst != NULL)
1551                 bcopy(desc, dst, note.n_descsz);
1552         target->off = roundup2(target->off, sizeof(Elf_Word));
1553         return(error);
1554 }
1555
1556
1557 static int
1558 elf_putsigs(struct lwp *lp, elf_buf_t target)
1559 {
1560         /* XXX lwp handle more than one lwp */
1561         struct proc *p = lp->lwp_proc;
1562         int error = 0;
1563         struct ckpt_siginfo *csi;
1564
1565         csi = target_reserve(target, sizeof(struct ckpt_siginfo), &error);
1566         if (csi) {
1567                 csi->csi_ckptpisz = sizeof(struct ckpt_siginfo);
1568                 bcopy(p->p_sigacts, &csi->csi_sigacts, sizeof(*p->p_sigacts));
1569                 bcopy(&p->p_realtimer, &csi->csi_itimerval, sizeof(struct itimerval));
1570                 bcopy(&lp->lwp_sigmask, &csi->csi_sigmask,
1571                         sizeof(sigset_t));
1572                 csi->csi_sigparent = p->p_sigparent;
1573         }
1574         return(error);
1575 }
1576
1577 static int
1578 elf_putfiles(struct proc *p, elf_buf_t target, struct file *ckfp)
1579 {
1580         int error = 0;
1581         int i;
1582         struct ckpt_filehdr *cfh = NULL;
1583         struct ckpt_fileinfo *cfi;
1584         struct file *fp;        
1585         struct vnode *vp;
1586         /*
1587          * the duplicated loop is gross, but it was the only way
1588          * to eliminate uninitialized variable warnings 
1589          */
1590         cfh = target_reserve(target, sizeof(struct ckpt_filehdr), &error);
1591         if (cfh) {
1592                 cfh->cfh_nfiles = 0;            
1593         }
1594
1595         /*
1596          * ignore STDIN/STDERR/STDOUT.
1597          */
1598         for (i = 3; error == 0 && i < p->p_fd->fd_nfiles; i++) {
1599                 fp = holdfp(p->p_fd, i, -1);
1600                 if (fp == NULL)
1601                         continue;
1602                 /* 
1603                  * XXX Only checkpoint vnodes for now.
1604                  */
1605                 if (fp->f_type != DTYPE_VNODE) {
1606                         fdrop(fp);
1607                         continue;
1608                 }
1609                 cfi = target_reserve(target, sizeof(struct ckpt_fileinfo),
1610                                         &error);
1611                 if (cfi == NULL) {
1612                         fdrop(fp);
1613                         continue;
1614                 }
1615                 cfi->cfi_index = -1;
1616                 cfi->cfi_type = fp->f_type;
1617                 cfi->cfi_flags = fp->f_flag;
1618                 cfi->cfi_offset = fp->f_offset;
1619                 cfi->cfi_ckflags = 0;
1620
1621                 if (fp == ckfp)
1622                         cfi->cfi_ckflags |= CKFIF_ISCKPTFD;
1623                 /* f_count and f_msgcount should not be saved/restored */
1624                 /* XXX save cred info */
1625
1626                 switch(fp->f_type) {
1627                 case DTYPE_VNODE:
1628                         vp = (struct vnode *)fp->f_data;
1629                         /*
1630                          * it looks like a bug in ptrace is marking 
1631                          * a non-vnode as a vnode - until we find the 
1632                          * root cause this will at least prevent
1633                          * further panics from truss
1634                          */
1635                         if (vp == NULL || vp->v_mount == NULL)
1636                                 break;
1637                         cfh->cfh_nfiles++;
1638                         cfi->cfi_index = i;
1639                         cfi->cfi_fh.fh_fsid = vp->v_mount->mnt_stat.f_fsid;
1640                         error = VFS_VPTOFH(vp, &cfi->cfi_fh.fh_fid);
1641                         break;
1642                 default:
1643                         break;
1644                 }
1645                 fdrop(fp);
1646         }
1647         return(error);
1648 }
1649
1650 static int
1651 elf_puttextvp(struct proc *p, elf_buf_t target)
1652 {
1653         int error = 0;
1654         int *vn_count;
1655         struct fp_closure fpc;
1656         struct ckpt_vminfo *vminfo;
1657
1658         vminfo = target_reserve(target, sizeof(struct ckpt_vminfo), &error);
1659         if (vminfo != NULL) {
1660                 vminfo->cvm_dsize = p->p_vmspace->vm_dsize;
1661                 vminfo->cvm_tsize = p->p_vmspace->vm_tsize;
1662                 vminfo->cvm_daddr = p->p_vmspace->vm_daddr;
1663                 vminfo->cvm_taddr = p->p_vmspace->vm_taddr;
1664         }
1665
1666         fpc.count = 0;
1667         vn_count = target_reserve(target, sizeof(int), &error);
1668         if (target->buf != NULL) {
1669                 fpc.vnh = (struct vn_hdr *)(target->buf + target->off);
1670                 fpc.vnh_max = fpc.vnh + 
1671                         (target->off_max - target->off) / sizeof(struct vn_hdr);
1672                 error = each_segment(p, cb_put_fp, &fpc, 0);
1673                 if (vn_count)
1674                         *vn_count = fpc.count;
1675         } else {
1676                 error = each_segment(p, cb_fpcount_segment, &fpc.count, 0);
1677         }
1678         target->off += fpc.count * sizeof(struct vn_hdr);
1679         return(error);
1680 }
1681
1682
1683 /*
1684  * Tell kern_execve.c about it, with a little help from the linker.
1685  */
1686 static struct execsw elf_execsw = {exec_elf_imgact, "ELF"};
1687 EXEC_SET_ORDERED(elf, elf_execsw, SI_ORDER_FIRST);