fix __P
[dragonfly.git] / sys / kern / imgact_elf.c
1 /*-
2  * Copyright (c) 1995-1996 Søren Schmidt
3  * Copyright (c) 1996 Peter Wemm
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer
11  *    in this position and unchanged.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. The name of the author may not be used to endorse or promote products
16  *    derived from this software withough specific prior written permission
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  *
29  * $FreeBSD: src/sys/kern/imgact_elf.c,v 1.73.2.13 2002/12/28 19:49:41 dillon Exp $
30  * $DragonFly: src/sys/kern/imgact_elf.c,v 1.8 2003/08/27 01:43:07 dillon Exp $
31  */
32
33 #include <sys/param.h>
34 #include <sys/exec.h>
35 #include <sys/fcntl.h>
36 #include <sys/imgact.h>
37 #include <sys/imgact_elf.h>
38 #include <sys/kernel.h>
39 #include <sys/malloc.h>
40 #include <sys/mman.h>
41 #include <sys/systm.h>
42 #include <sys/proc.h>
43 #include <sys/namei.h>
44 #include <sys/pioctl.h>
45 #include <sys/procfs.h>
46 #include <sys/resourcevar.h>
47 #include <sys/signalvar.h>
48 #include <sys/stat.h>
49 #include <sys/syscall.h>
50 #include <sys/sysctl.h>
51 #include <sys/sysent.h>
52 #include <sys/vnode.h>
53
54 #include <vm/vm.h>
55 #include <vm/vm_kern.h>
56 #include <vm/vm_param.h>
57 #include <vm/pmap.h>
58 #include <sys/lock.h>
59 #include <vm/vm_map.h>
60 #include <vm/vm_object.h>
61 #include <vm/vm_extern.h>
62
63 #include <machine/elf.h>
64 #include <machine/md_var.h>
65
66 #define OLD_EI_BRAND    8
67
68 __ElfType(Brandinfo);
69 __ElfType(Auxargs);
70
71 static int elf_check_header (const Elf_Ehdr *hdr);
72 static int elf_freebsd_fixup (register_t **stack_base,
73     struct image_params *imgp);
74 static int elf_load_file (struct proc *p, const char *file, u_long *addr,
75     u_long *entry);
76 static int elf_load_section (struct proc *p,
77     struct vmspace *vmspace, struct vnode *vp,
78     vm_offset_t offset, caddr_t vmaddr, size_t memsz, size_t filsz,
79     vm_prot_t prot);
80 static int exec_elf_imgact (struct image_params *imgp);
81
82 static int elf_trace = 0;
83 SYSCTL_INT(_debug, OID_AUTO, elf_trace, CTLFLAG_RW, &elf_trace, 0, "");
84 static int elf_legacy_coredump = 0;
85 SYSCTL_INT(_debug, OID_AUTO, elf_legacy_coredump, CTLFLAG_RW,
86     &elf_legacy_coredump, 0, "");
87
88 static struct sysentvec elf_freebsd_sysvec = {
89         SYS_MAXSYSCALL,
90         sysent,
91         0,
92         0,
93         0,
94         0,
95         0,
96         0,
97         elf_freebsd_fixup,
98         sendsig,
99         sigcode,
100         &szsigcode,
101         0,
102         "FreeBSD ELF",
103         elf_coredump,
104         NULL,
105         MINSIGSTKSZ
106 };
107
108 static Elf_Brandinfo freebsd_brand_info = {
109                                                 ELFOSABI_FREEBSD,
110                                                 "FreeBSD",
111                                                 "",
112                                                 "/usr/libexec/ld-elf.so.1",
113                                                 &elf_freebsd_sysvec
114                                           };
115 static Elf_Brandinfo *elf_brand_list[MAX_BRANDS] = {
116                                                         &freebsd_brand_info,
117                                                         NULL, NULL, NULL,
118                                                         NULL, NULL, NULL, NULL
119                                                     };
120
121 int
122 elf_insert_brand_entry(Elf_Brandinfo *entry)
123 {
124         int i;
125
126         for (i=1; i<MAX_BRANDS; i++) {
127                 if (elf_brand_list[i] == NULL) {
128                         elf_brand_list[i] = entry;
129                         break;
130                 }
131         }
132         if (i == MAX_BRANDS)
133                 return -1;
134         return 0;
135 }
136
137 int
138 elf_remove_brand_entry(Elf_Brandinfo *entry)
139 {
140         int i;
141
142         for (i=1; i<MAX_BRANDS; i++) {
143                 if (elf_brand_list[i] == entry) {
144                         elf_brand_list[i] = NULL;
145                         break;
146                 }
147         }
148         if (i == MAX_BRANDS)
149                 return -1;
150         return 0;
151 }
152
153 int
154 elf_brand_inuse(Elf_Brandinfo *entry)
155 {
156         struct proc *p;
157         int rval = FALSE;
158
159         FOREACH_PROC_IN_SYSTEM(p) {
160                 if (p->p_sysent == entry->sysvec) {
161                         rval = TRUE;
162                         break;
163                 }
164         }
165
166         return (rval);
167 }
168
169 static int
170 elf_check_header(const Elf_Ehdr *hdr)
171 {
172         if (!IS_ELF(*hdr) ||
173             hdr->e_ident[EI_CLASS] != ELF_TARG_CLASS ||
174             hdr->e_ident[EI_DATA] != ELF_TARG_DATA ||
175             hdr->e_ident[EI_VERSION] != EV_CURRENT)
176                 return ENOEXEC;
177
178         if (!ELF_MACHINE_OK(hdr->e_machine))
179                 return ENOEXEC;
180
181         if (hdr->e_version != ELF_TARG_VER)
182                 return ENOEXEC;
183         
184         return 0;
185 }
186
187 static int
188 elf_load_section(struct proc *p, struct vmspace *vmspace, struct vnode *vp, vm_offset_t offset, caddr_t vmaddr, size_t memsz, size_t filsz, vm_prot_t prot)
189 {
190         size_t map_len;
191         vm_offset_t map_addr;
192         int error, rv, cow;
193         int count;
194         size_t copy_len;
195         vm_object_t object;
196         vm_offset_t file_addr;
197         vm_offset_t data_buf = 0;
198
199         VOP_GETVOBJECT(vp, &object);
200         error = 0;
201
202         /*
203          * It's necessary to fail if the filsz + offset taken from the
204          * header is greater than the actual file pager object's size.
205          * If we were to allow this, then the vm_map_find() below would
206          * walk right off the end of the file object and into the ether.
207          *
208          * While I'm here, might as well check for something else that
209          * is invalid: filsz cannot be greater than memsz.
210          */
211         if ((off_t)filsz + offset > object->un_pager.vnp.vnp_size ||
212             filsz > memsz) {
213                 uprintf("elf_load_section: truncated ELF file\n");
214                 return (ENOEXEC);
215         }
216
217         map_addr = trunc_page((vm_offset_t)vmaddr);
218         file_addr = trunc_page(offset);
219
220         /*
221          * We have two choices.  We can either clear the data in the last page
222          * of an oversized mapping, or we can start the anon mapping a page
223          * early and copy the initialized data into that first page.  We
224          * choose the second..
225          */
226         if (memsz > filsz)
227                 map_len = trunc_page(offset+filsz) - file_addr;
228         else
229                 map_len = round_page(offset+filsz) - file_addr;
230
231         if (map_len != 0) {
232                 vm_object_reference(object);
233
234                 /* cow flags: don't dump readonly sections in core */
235                 cow = MAP_COPY_ON_WRITE | MAP_PREFAULT |
236                     (prot & VM_PROT_WRITE ? 0 : MAP_DISABLE_COREDUMP);
237
238                 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
239                 vm_map_lock(&vmspace->vm_map);
240                 rv = vm_map_insert(&vmspace->vm_map, &count,
241                                       object,
242                                       file_addr,        /* file offset */
243                                       map_addr,         /* virtual start */
244                                       map_addr + map_len,/* virtual end */
245                                       prot,
246                                       VM_PROT_ALL,
247                                       cow);
248                 vm_map_unlock(&vmspace->vm_map);
249                 vm_map_entry_release(count);
250                 if (rv != KERN_SUCCESS) {
251                         vm_object_deallocate(object);
252                         return EINVAL;
253                 }
254
255                 /* we can stop now if we've covered it all */
256                 if (memsz == filsz) {
257                         return 0;
258                 }
259         }
260
261
262         /*
263          * We have to get the remaining bit of the file into the first part
264          * of the oversized map segment.  This is normally because the .data
265          * segment in the file is extended to provide bss.  It's a neat idea
266          * to try and save a page, but it's a pain in the behind to implement.
267          */
268         copy_len = (offset + filsz) - trunc_page(offset + filsz);
269         map_addr = trunc_page((vm_offset_t)vmaddr + filsz);
270         map_len = round_page((vm_offset_t)vmaddr + memsz) - map_addr;
271
272         /* This had damn well better be true! */
273         if (map_len != 0) {
274                 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
275                 vm_map_lock(&vmspace->vm_map);
276                 rv = vm_map_insert(&vmspace->vm_map, &count,
277                                         NULL, 0,
278                                         map_addr, map_addr + map_len,
279                                         VM_PROT_ALL, VM_PROT_ALL, 0);
280                 vm_map_unlock(&vmspace->vm_map);
281                 vm_map_entry_release(count);
282                 if (rv != KERN_SUCCESS) {
283                         return EINVAL; 
284                 }
285         }
286
287         if (copy_len != 0) {
288                 vm_object_reference(object);
289                 rv = vm_map_find(exec_map,
290                                  object, 
291                                  trunc_page(offset + filsz),
292                                  &data_buf,
293                                  PAGE_SIZE,
294                                  TRUE,
295                                  VM_PROT_READ,
296                                  VM_PROT_ALL,
297                                  MAP_COPY_ON_WRITE | MAP_PREFAULT_PARTIAL);
298                 if (rv != KERN_SUCCESS) {
299                         vm_object_deallocate(object);
300                         return EINVAL;
301                 }
302
303                 /* send the page fragment to user space */
304                 error = copyout((caddr_t)data_buf, (caddr_t)map_addr, copy_len);
305                 vm_map_remove(exec_map, data_buf, data_buf + PAGE_SIZE);
306                 if (error) {
307                         return (error);
308                 }
309         }
310
311         /*
312          * set it to the specified protection
313          */
314         vm_map_protect(&vmspace->vm_map, map_addr, map_addr + map_len,  prot,
315                        FALSE);
316
317         return error;
318 }
319
320 /*
321  * Load the file "file" into memory.  It may be either a shared object
322  * or an executable.
323  *
324  * The "addr" reference parameter is in/out.  On entry, it specifies
325  * the address where a shared object should be loaded.  If the file is
326  * an executable, this value is ignored.  On exit, "addr" specifies
327  * where the file was actually loaded.
328  *
329  * The "entry" reference parameter is out only.  On exit, it specifies
330  * the entry point for the loaded file.
331  */
332 static int
333 elf_load_file(struct proc *p, const char *file, u_long *addr, u_long *entry)
334 {
335         struct {
336                 struct nameidata nd;
337                 struct vattr attr;
338                 struct image_params image_params;
339         } *tempdata;
340         const Elf_Ehdr *hdr = NULL;
341         const Elf_Phdr *phdr = NULL;
342         struct nameidata *nd;
343         struct vmspace *vmspace = p->p_vmspace;
344         struct vattr *attr;
345         struct image_params *imgp;
346         vm_prot_t prot;
347         u_long rbase;
348         u_long base_addr = 0;
349         int error, i, numsegs;
350         struct thread *td = p->p_thread;
351
352         tempdata = malloc(sizeof(*tempdata), M_TEMP, M_WAITOK);
353         nd = &tempdata->nd;
354         attr = &tempdata->attr;
355         imgp = &tempdata->image_params;
356
357         /*
358          * Initialize part of the common data
359          */
360         imgp->proc = p;
361         imgp->uap = NULL;
362         imgp->attr = attr;
363         imgp->firstpage = NULL;
364         imgp->image_header = (char *)kmem_alloc_wait(exec_map, PAGE_SIZE);
365
366         if (imgp->image_header == NULL) {
367                 nd->ni_vp = NULL;
368                 error = ENOMEM;
369                 goto fail;
370         }
371
372         NDINIT(nd, LOOKUP, LOCKLEAF|FOLLOW, UIO_SYSSPACE, file, td);
373                          
374         if ((error = namei(nd)) != 0) {
375                 nd->ni_vp = NULL;
376                 goto fail;
377         }
378         NDFREE(nd, NDF_ONLY_PNBUF);
379         imgp->vp = nd->ni_vp;
380
381         /*
382          * Check permissions, modes, uid, etc on the file, and "open" it.
383          */
384         error = exec_check_permissions(imgp);
385         if (error) {
386                 VOP_UNLOCK(nd->ni_vp, 0, td);
387                 goto fail;
388         }
389
390         error = exec_map_first_page(imgp);
391         /*
392          * Also make certain that the interpreter stays the same, so set
393          * its VTEXT flag, too.
394          */
395         if (error == 0)
396                 nd->ni_vp->v_flag |= VTEXT;
397         VOP_UNLOCK(nd->ni_vp, 0, td);
398         if (error)
399                 goto fail;
400
401         hdr = (const Elf_Ehdr *)imgp->image_header;
402         if ((error = elf_check_header(hdr)) != 0)
403                 goto fail;
404         if (hdr->e_type == ET_DYN)
405                 rbase = *addr;
406         else if (hdr->e_type == ET_EXEC)
407                 rbase = 0;
408         else {
409                 error = ENOEXEC;
410                 goto fail;
411         }
412
413         /* Only support headers that fit within first page for now */
414         if ((hdr->e_phoff > PAGE_SIZE) ||
415             (hdr->e_phoff + hdr->e_phentsize * hdr->e_phnum) > PAGE_SIZE) {
416                 error = ENOEXEC;
417                 goto fail;
418         }
419
420         phdr = (const Elf_Phdr *)(imgp->image_header + hdr->e_phoff);
421
422         for (i = 0, numsegs = 0; i < hdr->e_phnum; i++) {
423                 if (phdr[i].p_type == PT_LOAD) {        /* Loadable segment */
424                         prot = 0;
425                         if (phdr[i].p_flags & PF_X)
426                                 prot |= VM_PROT_EXECUTE;
427                         if (phdr[i].p_flags & PF_W)
428                                 prot |= VM_PROT_WRITE;
429                         if (phdr[i].p_flags & PF_R)
430                                 prot |= VM_PROT_READ;
431
432                         error = elf_load_section(
433                                     p, vmspace, nd->ni_vp,
434                                     phdr[i].p_offset,
435                                     (caddr_t)phdr[i].p_vaddr +
436                                     rbase,
437                                     phdr[i].p_memsz,
438                                     phdr[i].p_filesz, prot);
439                         if (error != 0)
440                                 goto fail;
441                         /*
442                          * Establish the base address if this is the
443                          * first segment.
444                          */
445                         if (numsegs == 0)
446                                 base_addr = trunc_page(phdr[i].p_vaddr + rbase);
447                         numsegs++;
448                 }
449         }
450         *addr = base_addr;
451         *entry=(unsigned long)hdr->e_entry + rbase;
452
453 fail:
454         if (imgp->firstpage)
455                 exec_unmap_first_page(imgp);
456         if (imgp->image_header)
457                 kmem_free_wakeup(exec_map, (vm_offset_t)imgp->image_header,
458                         PAGE_SIZE);
459         if (nd->ni_vp)
460                 vrele(nd->ni_vp);
461
462         free(tempdata, M_TEMP);
463
464         return error;
465 }
466
467 /*
468  * non static, as it can be overridden by start_init()
469  */
470 int fallback_elf_brand = -1;
471 SYSCTL_INT(_kern, OID_AUTO, fallback_elf_brand, CTLFLAG_RW,
472                 &fallback_elf_brand, -1,
473                 "ELF brand of last resort");
474
475 static int
476 exec_elf_imgact(struct image_params *imgp)
477 {
478         const Elf_Ehdr *hdr = (const Elf_Ehdr *) imgp->image_header;
479         const Elf_Phdr *phdr;
480         Elf_Auxargs *elf_auxargs = NULL;
481         struct vmspace *vmspace;
482         vm_prot_t prot;
483         u_long text_size = 0, data_size = 0, total_size = 0;
484         u_long text_addr = 0, data_addr = 0;
485         u_long seg_size, seg_addr;
486         u_long addr, entry = 0, proghdr = 0;
487         int error, i;
488         const char *interp = NULL;
489         Elf_Brandinfo *brand_info;
490         char *path;
491
492         /*
493          * Do we have a valid ELF header ?
494          */
495         if (elf_check_header(hdr) != 0 || hdr->e_type != ET_EXEC)
496                 return -1;
497
498         /*
499          * From here on down, we return an errno, not -1, as we've
500          * detected an ELF file.
501          */
502
503         if ((hdr->e_phoff > PAGE_SIZE) ||
504             (hdr->e_phoff + hdr->e_phentsize * hdr->e_phnum) > PAGE_SIZE) {
505                 /* Only support headers in first page for now */
506                 return ENOEXEC;
507         }
508         phdr = (const Elf_Phdr*)(imgp->image_header + hdr->e_phoff);
509         
510         /*
511          * From this point on, we may have resources that need to be freed.
512          */
513
514         if ((error = exec_extract_strings(imgp)) != 0)
515                 goto fail;
516
517         exec_new_vmspace(imgp);
518
519         /*
520          * Yeah, I'm paranoid.  There is every reason in the world to get
521          * VTEXT now since from here on out, there are places we can have
522          * a context switch.  Better safe than sorry; I really don't want
523          * the file to change while it's being loaded.
524          */
525         lwkt_gettoken(&imgp->vp->v_interlock);
526         imgp->vp->v_flag |= VTEXT;
527         lwkt_reltoken(&imgp->vp->v_interlock);
528
529         vmspace = imgp->proc->p_vmspace;
530
531         for (i = 0; i < hdr->e_phnum; i++) {
532                 switch(phdr[i].p_type) {
533
534                 case PT_LOAD:   /* Loadable segment */
535                         prot = 0;
536                         if (phdr[i].p_flags & PF_X)
537                                 prot |= VM_PROT_EXECUTE;
538                         if (phdr[i].p_flags & PF_W)
539                                 prot |= VM_PROT_WRITE;
540                         if (phdr[i].p_flags & PF_R)
541                                 prot |= VM_PROT_READ;
542
543                         if ((error = elf_load_section(imgp->proc,
544                                                      vmspace, imgp->vp,
545                                                      phdr[i].p_offset,
546                                                      (caddr_t)phdr[i].p_vaddr,
547                                                      phdr[i].p_memsz,
548                                                      phdr[i].p_filesz, prot)) != 0)
549                                 goto fail;
550
551                         seg_addr = trunc_page(phdr[i].p_vaddr);
552                         seg_size = round_page(phdr[i].p_memsz +
553                                 phdr[i].p_vaddr - seg_addr);
554
555                         /*
556                          * Is this .text or .data?  We can't use
557                          * VM_PROT_WRITE or VM_PROT_EXEC, it breaks the
558                          * alpha terribly and possibly does other bad
559                          * things so we stick to the old way of figuring
560                          * it out:  If the segment contains the program
561                          * entry point, it's a text segment, otherwise it
562                          * is a data segment.
563                          *
564                          * Note that obreak() assumes that data_addr + 
565                          * data_size == end of data load area, and the ELF
566                          * file format expects segments to be sorted by
567                          * address.  If multiple data segments exist, the
568                          * last one will be used.
569                          */
570                         if (hdr->e_entry >= phdr[i].p_vaddr &&
571                             hdr->e_entry < (phdr[i].p_vaddr +
572                             phdr[i].p_memsz)) {
573                                 text_size = seg_size;
574                                 text_addr = seg_addr;
575                                 entry = (u_long)hdr->e_entry;
576                         } else {
577                                 data_size = seg_size;
578                                 data_addr = seg_addr;
579                         }
580                         total_size += seg_size;
581
582                         /*
583                          * Check limits.  It should be safe to check the
584                          * limits after loading the segment since we do
585                          * not actually fault in all the segment's pages.
586                          */
587                         if (data_size >
588                             imgp->proc->p_rlimit[RLIMIT_DATA].rlim_cur ||
589                             text_size > maxtsiz ||
590                             total_size >
591                             imgp->proc->p_rlimit[RLIMIT_VMEM].rlim_cur) {
592                                 error = ENOMEM;
593                                 goto fail;
594                         }
595                         break;
596                 case PT_INTERP: /* Path to interpreter */
597                         if (phdr[i].p_filesz > MAXPATHLEN ||
598                             phdr[i].p_offset + phdr[i].p_filesz > PAGE_SIZE) {
599                                 error = ENOEXEC;
600                                 goto fail;
601                         }
602                         interp = imgp->image_header + phdr[i].p_offset;
603                         break;
604                 case PT_PHDR:   /* Program header table info */
605                         proghdr = phdr[i].p_vaddr;
606                         break;
607                 default:
608                         break;
609                 }
610         }
611
612         vmspace->vm_tsize = text_size >> PAGE_SHIFT;
613         vmspace->vm_taddr = (caddr_t)(uintptr_t)text_addr;
614         vmspace->vm_dsize = data_size >> PAGE_SHIFT;
615         vmspace->vm_daddr = (caddr_t)(uintptr_t)data_addr;
616
617         addr = ELF_RTLD_ADDR(vmspace);
618
619         imgp->entry_addr = entry;
620
621         brand_info = NULL;
622
623         /* We support three types of branding -- (1) the ELF EI_OSABI field
624          * that SCO added to the ELF spec, (2) FreeBSD 3.x's traditional string
625          * branding w/in the ELF header, and (3) path of the `interp_path'
626          * field.  We should also look for an ".note.ABI-tag" ELF section now
627          * in all Linux ELF binaries, FreeBSD 4.1+, and some NetBSD ones.
628          */
629
630         /* If the executable has a brand, search for it in the brand list. */
631         if (brand_info == NULL) {
632                 for (i = 0;  i < MAX_BRANDS;  i++) {
633                         Elf_Brandinfo *bi = elf_brand_list[i];
634
635                         if (bi != NULL && 
636                             (hdr->e_ident[EI_OSABI] == bi->brand
637                             || 0 == 
638                             strncmp((const char *)&hdr->e_ident[OLD_EI_BRAND], 
639                             bi->compat_3_brand, strlen(bi->compat_3_brand)))) {
640                                 brand_info = bi;
641                                 break;
642                         }
643                 }
644         }
645
646         /* Lacking a known brand, search for a recognized interpreter. */
647         if (brand_info == NULL && interp != NULL) {
648                 for (i = 0;  i < MAX_BRANDS;  i++) {
649                         Elf_Brandinfo *bi = elf_brand_list[i];
650
651                         if (bi != NULL &&
652                             strcmp(interp, bi->interp_path) == 0) {
653                                 brand_info = bi;
654                                 break;
655                         }
656                 }
657         }
658
659         /* Lacking a recognized interpreter, try the default brand */
660         if (brand_info == NULL) {
661                 for (i = 0; i < MAX_BRANDS; i++) {
662                         Elf_Brandinfo *bi = elf_brand_list[i];
663
664                         if (bi != NULL && fallback_elf_brand == bi->brand) {
665                                 brand_info = bi;
666                                 break;
667                         }
668                 }
669         }
670
671         if (brand_info == NULL) {
672                 uprintf("ELF binary type \"%u\" not known.\n",
673                     hdr->e_ident[EI_OSABI]);
674                 error = ENOEXEC;
675                 goto fail;
676         }
677
678         imgp->proc->p_sysent = brand_info->sysvec;
679         if (interp != NULL) {
680                 path = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
681                 snprintf(path, MAXPATHLEN, "%s%s",
682                          brand_info->emul_path, interp);
683                 if ((error = elf_load_file(imgp->proc, path, &addr,
684                                            &imgp->entry_addr)) != 0) {
685                         if ((error = elf_load_file(imgp->proc, interp, &addr,
686                                                    &imgp->entry_addr)) != 0) {
687                                 uprintf("ELF interpreter %s not found\n", path);
688                                 free(path, M_TEMP);
689                                 goto fail;
690                         }
691                 }
692                 free(path, M_TEMP);
693         }
694
695         /*
696          * Construct auxargs table (used by the fixup routine)
697          */
698         elf_auxargs = malloc(sizeof(Elf_Auxargs), M_TEMP, M_WAITOK);
699         elf_auxargs->execfd = -1;
700         elf_auxargs->phdr = proghdr;
701         elf_auxargs->phent = hdr->e_phentsize;
702         elf_auxargs->phnum = hdr->e_phnum;
703         elf_auxargs->pagesz = PAGE_SIZE;
704         elf_auxargs->base = addr;
705         elf_auxargs->flags = 0;
706         elf_auxargs->entry = entry;
707         elf_auxargs->trace = elf_trace;
708
709         imgp->auxargs = elf_auxargs;
710         imgp->interpreted = 0;
711
712 fail:
713         return error;
714 }
715
716 static int
717 elf_freebsd_fixup(register_t **stack_base, struct image_params *imgp)
718 {
719         Elf_Auxargs *args = (Elf_Auxargs *)imgp->auxargs;
720         register_t *pos;
721
722         pos = *stack_base + (imgp->argc + imgp->envc + 2);
723
724         if (args->trace) {
725                 AUXARGS_ENTRY(pos, AT_DEBUG, 1);
726         }
727         if (args->execfd != -1) {
728                 AUXARGS_ENTRY(pos, AT_EXECFD, args->execfd);
729         }
730         AUXARGS_ENTRY(pos, AT_PHDR, args->phdr);
731         AUXARGS_ENTRY(pos, AT_PHENT, args->phent);
732         AUXARGS_ENTRY(pos, AT_PHNUM, args->phnum);
733         AUXARGS_ENTRY(pos, AT_PAGESZ, args->pagesz);
734         AUXARGS_ENTRY(pos, AT_FLAGS, args->flags);
735         AUXARGS_ENTRY(pos, AT_ENTRY, args->entry);
736         AUXARGS_ENTRY(pos, AT_BASE, args->base);
737         AUXARGS_ENTRY(pos, AT_NULL, 0);
738
739         free(imgp->auxargs, M_TEMP);
740         imgp->auxargs = NULL;
741
742         (*stack_base)--;
743         suword(*stack_base, (long) imgp->argc);
744         return 0;
745
746
747 /*
748  * Code for generating ELF core dumps.
749  */
750
751 typedef void (*segment_callback) (vm_map_entry_t, void *);
752
753 /* Closure for cb_put_phdr(). */
754 struct phdr_closure {
755         Elf_Phdr *phdr;         /* Program header to fill in */
756         Elf_Off offset;         /* Offset of segment in core file */
757 };
758
759 /* Closure for cb_size_segment(). */
760 struct sseg_closure {
761         int count;              /* Count of writable segments. */
762         size_t size;            /* Total size of all writable segments. */
763 };
764
765 static void cb_put_phdr (vm_map_entry_t, void *);
766 static void cb_size_segment (vm_map_entry_t, void *);
767 static void each_writable_segment (struct proc *, segment_callback,
768     void *);
769 static int elf_corehdr (struct proc *, struct vnode *, struct ucred *,
770     int, void *, size_t);
771 static void elf_puthdr (struct proc *, void *, size_t *,
772     const prstatus_t *, const prfpregset_t *, const prpsinfo_t *, int);
773 static void elf_putnote (void *, size_t *, const char *, int,
774     const void *, size_t);
775
776 extern int osreldate;
777
778 int
779 elf_coredump(p, vp, limit)
780         struct proc *p;
781         struct vnode *vp;
782         off_t limit;
783 {
784         struct ucred *cred = p->p_ucred;
785         struct thread *td = p->p_thread;
786         int error = 0;
787         struct sseg_closure seginfo;
788         void *hdr;
789         size_t hdrsize;
790
791         /* Size the program segments. */
792         seginfo.count = 0;
793         seginfo.size = 0;
794         each_writable_segment(p, cb_size_segment, &seginfo);
795
796         /*
797          * Calculate the size of the core file header area by making
798          * a dry run of generating it.  Nothing is written, but the
799          * size is calculated.
800          */
801         hdrsize = 0;
802         elf_puthdr((struct proc *)NULL, (void *)NULL, &hdrsize,
803             (const prstatus_t *)NULL, (const prfpregset_t *)NULL,
804             (const prpsinfo_t *)NULL, seginfo.count);
805
806         if (hdrsize + seginfo.size >= limit)
807                 return (EFAULT);
808
809         /*
810          * Allocate memory for building the header, fill it up,
811          * and write it out.
812          */
813         hdr = malloc(hdrsize, M_TEMP, M_WAITOK);
814         if (hdr == NULL) {
815                 return EINVAL;
816         }
817         error = elf_corehdr(p, vp, cred, seginfo.count, hdr, hdrsize);
818
819         /* Write the contents of all of the writable segments. */
820         if (error == 0) {
821                 Elf_Phdr *php;
822                 off_t offset;
823                 int i;
824
825                 php = (Elf_Phdr *)((char *)hdr + sizeof(Elf_Ehdr)) + 1;
826                 offset = hdrsize;
827                 for (i = 0;  i < seginfo.count;  i++) {
828                         error = vn_rdwr_inchunks(UIO_WRITE, vp, 
829                             (caddr_t)php->p_vaddr,
830                             php->p_filesz, offset, UIO_USERSPACE,
831                             IO_UNIT | IO_DIRECT | IO_CORE, cred, 
832                             (int *)NULL, td);
833                         if (error != 0)
834                                 break;
835                         offset += php->p_filesz;
836                         php++;
837                 }
838         }
839         free(hdr, M_TEMP);
840         
841         return error;
842 }
843
844 /*
845  * A callback for each_writable_segment() to write out the segment's
846  * program header entry.
847  */
848 static void
849 cb_put_phdr(entry, closure)
850         vm_map_entry_t entry;
851         void *closure;
852 {
853         struct phdr_closure *phc = (struct phdr_closure *)closure;
854         Elf_Phdr *phdr = phc->phdr;
855
856         phc->offset = round_page(phc->offset);
857
858         phdr->p_type = PT_LOAD;
859         phdr->p_offset = phc->offset;
860         phdr->p_vaddr = entry->start;
861         phdr->p_paddr = 0;
862         phdr->p_filesz = phdr->p_memsz = entry->end - entry->start;
863         phdr->p_align = PAGE_SIZE;
864         phdr->p_flags = 0;
865         if (entry->protection & VM_PROT_READ)
866                 phdr->p_flags |= PF_R;
867         if (entry->protection & VM_PROT_WRITE)
868                 phdr->p_flags |= PF_W;
869         if (entry->protection & VM_PROT_EXECUTE)
870                 phdr->p_flags |= PF_X;
871
872         phc->offset += phdr->p_filesz;
873         phc->phdr++;
874 }
875
876 /*
877  * A callback for each_writable_segment() to gather information about
878  * the number of segments and their total size.
879  */
880 static void
881 cb_size_segment(entry, closure)
882         vm_map_entry_t entry;
883         void *closure;
884 {
885         struct sseg_closure *ssc = (struct sseg_closure *)closure;
886
887         ssc->count++;
888         ssc->size += entry->end - entry->start;
889 }
890
891 /*
892  * For each writable segment in the process's memory map, call the given
893  * function with a pointer to the map entry and some arbitrary
894  * caller-supplied data.
895  */
896 static void
897 each_writable_segment(p, func, closure)
898         struct proc *p;
899         segment_callback func;
900         void *closure;
901 {
902         vm_map_t map = &p->p_vmspace->vm_map;
903         vm_map_entry_t entry;
904
905         for (entry = map->header.next;  entry != &map->header;
906             entry = entry->next) {
907                 vm_object_t obj;
908
909                 /*
910                  * Don't dump inaccessible mappings, deal with legacy
911                  * coredump mode.
912                  *
913                  * Note that read-only segments related to the elf binary
914                  * are marked MAP_ENTRY_NOCOREDUMP now so we no longer
915                  * need to arbitrarily ignore such segments.
916                  */
917                 if (elf_legacy_coredump) {
918                         if ((entry->protection & VM_PROT_RW) != VM_PROT_RW)
919                                 continue;
920                 } else {
921                         if ((entry->protection & VM_PROT_ALL) == 0)
922                                 continue;
923                 }
924
925                 /*
926                  * Dont include memory segment in the coredump if
927                  * MAP_NOCORE is set in mmap(2) or MADV_NOCORE in
928                  * madvise(2).  Do not dump submaps (i.e. parts of the
929                  * kernel map).
930                  */
931                 if (entry->eflags & (MAP_ENTRY_NOCOREDUMP|MAP_ENTRY_IS_SUB_MAP))
932                         continue;
933
934                 if ((obj = entry->object.vm_object) == NULL)
935                         continue;
936
937                 /* Find the deepest backing object. */
938                 while (obj->backing_object != NULL)
939                         obj = obj->backing_object;
940
941                 /* Ignore memory-mapped devices and such things. */
942                 if (obj->type != OBJT_DEFAULT &&
943                     obj->type != OBJT_SWAP &&
944                     obj->type != OBJT_VNODE)
945                         continue;
946
947                 (*func)(entry, closure);
948         }
949 }
950
951 /*
952  * Write the core file header to the file, including padding up to
953  * the page boundary.
954  */
955 static int
956 elf_corehdr(p, vp, cred, numsegs, hdr, hdrsize)
957         struct proc *p;
958         struct vnode *vp;
959         struct ucred *cred;
960         int numsegs;
961         size_t hdrsize;
962         void *hdr;
963 {
964         struct {
965                 prstatus_t status;
966                 prfpregset_t fpregset;
967                 prpsinfo_t psinfo;
968         } *tempdata;
969         size_t off;
970         prstatus_t *status;
971         prfpregset_t *fpregset;
972         prpsinfo_t *psinfo;
973         struct thread *td = p->p_thread;
974
975         tempdata = malloc(sizeof(*tempdata), M_TEMP, M_ZERO | M_WAITOK);
976         status = &tempdata->status;
977         fpregset = &tempdata->fpregset;
978         psinfo = &tempdata->psinfo;
979
980         /* Gather the information for the header. */
981         status->pr_version = PRSTATUS_VERSION;
982         status->pr_statussz = sizeof(prstatus_t);
983         status->pr_gregsetsz = sizeof(gregset_t);
984         status->pr_fpregsetsz = sizeof(fpregset_t);
985         status->pr_osreldate = osreldate;
986         status->pr_cursig = p->p_sig;
987         status->pr_pid = p->p_pid;
988         fill_regs(p, &status->pr_reg);
989
990         fill_fpregs(p, fpregset);
991
992         psinfo->pr_version = PRPSINFO_VERSION;
993         psinfo->pr_psinfosz = sizeof(prpsinfo_t);
994         strncpy(psinfo->pr_fname, p->p_comm, sizeof(psinfo->pr_fname) - 1);
995
996         /* XXX - We don't fill in the command line arguments properly yet. */
997         strncpy(psinfo->pr_psargs, p->p_comm, PRARGSZ);
998
999         /* Fill in the header. */
1000         bzero(hdr, hdrsize);
1001         off = 0;
1002         elf_puthdr(p, hdr, &off, status, fpregset, psinfo, numsegs);
1003
1004         free(tempdata, M_TEMP);
1005
1006         /* Write it to the core file. */
1007         return vn_rdwr_inchunks(UIO_WRITE, vp, hdr, hdrsize, (off_t)0,
1008             UIO_SYSSPACE, IO_UNIT | IO_DIRECT | IO_CORE, cred, NULL, td);
1009 }
1010
1011 static void
1012 elf_puthdr(struct proc *p, void *dst, size_t *off, const prstatus_t *status,
1013     const prfpregset_t *fpregset, const prpsinfo_t *psinfo, int numsegs)
1014 {
1015         size_t ehoff;
1016         size_t phoff;
1017         size_t noteoff;
1018         size_t notesz;
1019
1020         ehoff = *off;
1021         *off += sizeof(Elf_Ehdr);
1022
1023         phoff = *off;
1024         *off += (numsegs + 1) * sizeof(Elf_Phdr);
1025
1026         noteoff = *off;
1027         elf_putnote(dst, off, "FreeBSD", NT_PRSTATUS, status,
1028             sizeof *status);
1029         elf_putnote(dst, off, "FreeBSD", NT_FPREGSET, fpregset,
1030             sizeof *fpregset);
1031         elf_putnote(dst, off, "FreeBSD", NT_PRPSINFO, psinfo,
1032             sizeof *psinfo);
1033         notesz = *off - noteoff;
1034
1035         /* Align up to a page boundary for the program segments. */
1036         *off = round_page(*off);
1037
1038         if (dst != NULL) {
1039                 Elf_Ehdr *ehdr;
1040                 Elf_Phdr *phdr;
1041                 struct phdr_closure phc;
1042
1043                 /*
1044                  * Fill in the ELF header.
1045                  */
1046                 ehdr = (Elf_Ehdr *)((char *)dst + ehoff);
1047                 ehdr->e_ident[EI_MAG0] = ELFMAG0;
1048                 ehdr->e_ident[EI_MAG1] = ELFMAG1;
1049                 ehdr->e_ident[EI_MAG2] = ELFMAG2;
1050                 ehdr->e_ident[EI_MAG3] = ELFMAG3;
1051                 ehdr->e_ident[EI_CLASS] = ELF_CLASS;
1052                 ehdr->e_ident[EI_DATA] = ELF_DATA;
1053                 ehdr->e_ident[EI_VERSION] = EV_CURRENT;
1054                 ehdr->e_ident[EI_OSABI] = ELFOSABI_FREEBSD;
1055                 ehdr->e_ident[EI_ABIVERSION] = 0;
1056                 ehdr->e_ident[EI_PAD] = 0;
1057                 ehdr->e_type = ET_CORE;
1058                 ehdr->e_machine = ELF_ARCH;
1059                 ehdr->e_version = EV_CURRENT;
1060                 ehdr->e_entry = 0;
1061                 ehdr->e_phoff = phoff;
1062                 ehdr->e_flags = 0;
1063                 ehdr->e_ehsize = sizeof(Elf_Ehdr);
1064                 ehdr->e_phentsize = sizeof(Elf_Phdr);
1065                 ehdr->e_phnum = numsegs + 1;
1066                 ehdr->e_shentsize = sizeof(Elf_Shdr);
1067                 ehdr->e_shnum = 0;
1068                 ehdr->e_shstrndx = SHN_UNDEF;
1069
1070                 /*
1071                  * Fill in the program header entries.
1072                  */
1073                 phdr = (Elf_Phdr *)((char *)dst + phoff);
1074
1075                 /* The note segement. */
1076                 phdr->p_type = PT_NOTE;
1077                 phdr->p_offset = noteoff;
1078                 phdr->p_vaddr = 0;
1079                 phdr->p_paddr = 0;
1080                 phdr->p_filesz = notesz;
1081                 phdr->p_memsz = 0;
1082                 phdr->p_flags = 0;
1083                 phdr->p_align = 0;
1084                 phdr++;
1085
1086                 /* All the writable segments from the program. */
1087                 phc.phdr = phdr;
1088                 phc.offset = *off;
1089                 each_writable_segment(p, cb_put_phdr, &phc);
1090         }
1091 }
1092
1093 static void
1094 elf_putnote(void *dst, size_t *off, const char *name, int type,
1095     const void *desc, size_t descsz)
1096 {
1097         Elf_Note note;
1098
1099         note.n_namesz = strlen(name) + 1;
1100         note.n_descsz = descsz;
1101         note.n_type = type;
1102         if (dst != NULL)
1103                 bcopy(&note, (char *)dst + *off, sizeof note);
1104         *off += sizeof note;
1105         if (dst != NULL)
1106                 bcopy(name, (char *)dst + *off, note.n_namesz);
1107         *off += roundup2(note.n_namesz, sizeof(Elf_Size));
1108         if (dst != NULL)
1109                 bcopy(desc, (char *)dst + *off, note.n_descsz);
1110         *off += roundup2(note.n_descsz, sizeof(Elf_Size));
1111 }
1112
1113 /*
1114  * Tell kern_execve.c about it, with a little help from the linker.
1115  */
1116 static struct execsw elf_execsw = {exec_elf_imgact, "ELF"};
1117 EXEC_SET(elf, elf_execsw);