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