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