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