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