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