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