]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/boot/common/load_elf.c
Add code to support loading relocatable kernels at offsets that are not
[FreeBSD/FreeBSD.git] / sys / boot / common / load_elf.c
1 /*-
2  * Copyright (c) 1998 Michael Smith <msmith@freebsd.org>
3  * Copyright (c) 1998 Peter Wemm <peter@freebsd.org>
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  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30
31 #include <sys/param.h>
32 #include <sys/exec.h>
33 #include <sys/linker.h>
34 #include <sys/module.h>
35 #include <sys/stdint.h>
36 #include <string.h>
37 #include <machine/elf.h>
38 #include <stand.h>
39 #define FREEBSD_ELF
40 #include <link.h>
41
42 #include "bootstrap.h"
43
44 #define COPYOUT(s,d,l)  archsw.arch_copyout((vm_offset_t)(s), d, l)
45
46 #if defined(__i386__) && __ELF_WORD_SIZE == 64
47 #undef ELF_TARG_CLASS
48 #undef ELF_TARG_MACH
49 #define ELF_TARG_CLASS  ELFCLASS64
50 #define ELF_TARG_MACH   EM_X86_64
51 #endif
52
53 typedef struct elf_file {
54     Elf_Phdr    *ph;
55     Elf_Ehdr    *ehdr;
56     Elf_Sym     *symtab;
57     Elf_Hashelt *hashtab;
58     Elf_Hashelt nbuckets;
59     Elf_Hashelt nchains;
60     Elf_Hashelt *buckets;
61     Elf_Hashelt *chains;
62     Elf_Rel     *rel;
63     size_t      relsz;
64     Elf_Rela    *rela;
65     size_t      relasz;
66     char        *strtab;
67     size_t      strsz;
68     int         fd;
69     caddr_t     firstpage;
70     size_t      firstlen;
71     int         kernel;
72     u_int64_t   off;
73 } *elf_file_t;
74
75 static int __elfN(loadimage)(struct preloaded_file *mp, elf_file_t ef, u_int64_t loadaddr);
76 static int __elfN(lookup_symbol)(struct preloaded_file *mp, elf_file_t ef, const char* name, Elf_Sym* sym);
77 static int __elfN(reloc_ptr)(struct preloaded_file *mp, elf_file_t ef,
78     Elf_Addr p, void *val, size_t len);
79 static int __elfN(parse_modmetadata)(struct preloaded_file *mp, elf_file_t ef,
80     Elf_Addr p_start, Elf_Addr p_end);
81 static symaddr_fn __elfN(symaddr);
82 static char     *fake_modname(const char *name);
83
84 const char      *__elfN(kerneltype) = "elf kernel";
85 const char      *__elfN(moduletype) = "elf module";
86
87 u_int64_t       __elfN(relocation_offset) = 0;
88
89 static int
90 __elfN(load_elf_header)(char *filename, elf_file_t ef)
91 {
92         ssize_t                  bytes_read;
93         Elf_Ehdr                *ehdr;
94         int                      err;
95
96         /*
97         * Open the image, read and validate the ELF header 
98         */
99         if (filename == NULL)   /* can't handle nameless */
100                 return (EFTYPE);
101         if ((ef->fd = open(filename, O_RDONLY)) == -1)
102                 return (errno);
103         ef->firstpage = malloc(PAGE_SIZE);
104         if (ef->firstpage == NULL) {
105                 close(ef->fd);
106                 return (ENOMEM);
107         }
108         bytes_read = read(ef->fd, ef->firstpage, PAGE_SIZE);
109         ef->firstlen = (size_t)bytes_read;
110         if (bytes_read < 0 || ef->firstlen <= sizeof(Elf_Ehdr)) {
111                 err = EFTYPE; /* could be EIO, but may be small file */
112                 goto error;
113         }
114         ehdr = ef->ehdr = (Elf_Ehdr *)ef->firstpage;
115
116         /* Is it ELF? */
117         if (!IS_ELF(*ehdr)) {
118                 err = EFTYPE;
119                 goto error;
120         }
121         if (ehdr->e_ident[EI_CLASS] != ELF_TARG_CLASS || /* Layout ? */
122             ehdr->e_ident[EI_DATA] != ELF_TARG_DATA ||
123             ehdr->e_ident[EI_VERSION] != EV_CURRENT || /* Version ? */
124             ehdr->e_version != EV_CURRENT ||
125             ehdr->e_machine != ELF_TARG_MACH) { /* Machine ? */
126                 err = EFTYPE;
127                 goto error;
128         }
129
130         return (0);
131
132 error:
133         if (ef->firstpage != NULL) {
134                 free(ef->firstpage);
135                 ef->firstpage = NULL;
136         }
137         if (ef->fd != -1) {
138                 close(ef->fd);
139                 ef->fd = -1;
140         }
141         return (err);
142 }
143
144 /*
145  * Attempt to load the file (file) as an ELF module.  It will be stored at
146  * (dest), and a pointer to a module structure describing the loaded object
147  * will be saved in (result).
148  */
149 int
150 __elfN(loadfile)(char *filename, u_int64_t dest, struct preloaded_file **result)
151 {
152         return (__elfN(loadfile_raw)(filename, dest, result, 0));
153 }
154
155 int
156 __elfN(loadfile_raw)(char *filename, u_int64_t dest,
157     struct preloaded_file **result, int multiboot)
158 {
159     struct preloaded_file       *fp, *kfp;
160     struct elf_file             ef;
161     Elf_Ehdr                    *ehdr;
162     int                         err;
163
164     fp = NULL;
165     bzero(&ef, sizeof(struct elf_file));
166     ef.fd = -1;
167
168     err = __elfN(load_elf_header)(filename, &ef);
169     if (err != 0)
170         return (err);
171
172     ehdr = ef.ehdr;
173
174     /*
175      * Check to see what sort of module we are.
176      */
177     kfp = file_findfile(NULL, __elfN(kerneltype));
178 #ifdef __powerpc__
179     /*
180      * Kernels can be ET_DYN, so just assume the first loaded object is the
181      * kernel. This assumption will be checked later.
182      */
183     if (kfp == NULL)
184         ef.kernel = 1;
185 #endif
186     if (ef.kernel || ehdr->e_type == ET_EXEC) {
187         /* Looks like a kernel */
188         if (kfp != NULL) {
189             printf("elf" __XSTRING(__ELF_WORD_SIZE) "_loadfile: kernel already loaded\n");
190             err = EPERM;
191             goto oerr;
192         }
193         /* 
194          * Calculate destination address based on kernel entrypoint     
195          */
196         if (ehdr->e_type == ET_EXEC)
197             dest = (ehdr->e_entry & ~PAGE_MASK);
198         if ((ehdr->e_entry & ~PAGE_MASK) == 0) {
199             printf("elf" __XSTRING(__ELF_WORD_SIZE) "_loadfile: not a kernel (maybe static binary?)\n");
200             err = EPERM;
201             goto oerr;
202         }
203         ef.kernel = 1;
204
205     } else if (ehdr->e_type == ET_DYN) {
206         /* Looks like a kld module */
207         if (multiboot != 0) {
208                 printf("elf" __XSTRING(__ELF_WORD_SIZE) "_loadfile: can't load module as multiboot\n");
209                 err = EPERM;
210                 goto oerr;
211         }
212         if (kfp == NULL) {
213             printf("elf" __XSTRING(__ELF_WORD_SIZE) "_loadfile: can't load module before kernel\n");
214             err = EPERM;
215             goto oerr;
216         }
217         if (strcmp(__elfN(kerneltype), kfp->f_type)) {
218             printf("elf" __XSTRING(__ELF_WORD_SIZE) "_loadfile: can't load module with kernel type '%s'\n", kfp->f_type);
219             err = EPERM;
220             goto oerr;
221         }
222         /* Looks OK, got ahead */
223         ef.kernel = 0;
224
225     } else {
226         err = EFTYPE;
227         goto oerr;
228     }
229
230     if (archsw.arch_loadaddr != NULL)
231         dest = archsw.arch_loadaddr(LOAD_ELF, ehdr, dest);
232     else
233         dest = roundup(dest, PAGE_SIZE);
234
235     /* 
236      * Ok, we think we should handle this.
237      */
238     fp = file_alloc();
239     if (fp == NULL) {
240             printf("elf" __XSTRING(__ELF_WORD_SIZE) "_loadfile: cannot allocate module info\n");
241             err = EPERM;
242             goto out;
243     }
244     if (ef.kernel == 1 && multiboot == 0)
245         setenv("kernelname", filename, 1);
246     fp->f_name = strdup(filename);
247     if (multiboot == 0)
248         fp->f_type = strdup(ef.kernel ?
249             __elfN(kerneltype) : __elfN(moduletype));
250     else
251         fp->f_type = strdup("elf multiboot kernel");
252
253 #ifdef ELF_VERBOSE
254     if (ef.kernel)
255         printf("%s entry at 0x%jx\n", filename, (uintmax_t)ehdr->e_entry);
256 #else
257     printf("%s ", filename);
258 #endif
259
260     fp->f_size = __elfN(loadimage)(fp, &ef, dest);
261     if (fp->f_size == 0 || fp->f_addr == 0)
262         goto ioerr;
263
264     /* save exec header as metadata */
265     file_addmetadata(fp, MODINFOMD_ELFHDR, sizeof(*ehdr), ehdr);
266
267     /* Load OK, return module pointer */
268     *result = (struct preloaded_file *)fp;
269     err = 0;
270     goto out;
271     
272  ioerr:
273     err = EIO;
274  oerr:
275     file_discard(fp);
276  out:
277     if (ef.firstpage)
278         free(ef.firstpage);
279     if (ef.fd != -1)
280         close(ef.fd);
281     return(err);
282 }
283
284 /*
285  * With the file (fd) open on the image, and (ehdr) containing
286  * the Elf header, load the image at (off)
287  */
288 static int
289 __elfN(loadimage)(struct preloaded_file *fp, elf_file_t ef, u_int64_t off)
290 {
291     int         i;
292     u_int       j;
293     Elf_Ehdr    *ehdr;
294     Elf_Phdr    *phdr, *php;
295     Elf_Shdr    *shdr;
296     char        *shstr;
297     int         ret;
298     vm_offset_t firstaddr;
299     vm_offset_t lastaddr;
300     size_t      chunk;
301     ssize_t     result;
302     Elf_Addr    ssym, esym;
303     Elf_Dyn     *dp;
304     Elf_Addr    adp;
305     Elf_Addr    ctors;
306     int         ndp;
307     int         symstrindex;
308     int         symtabindex;
309     Elf_Size    size;
310     u_int       fpcopy;
311     Elf_Sym     sym;
312     Elf_Addr    p_start, p_end;
313
314     dp = NULL;
315     shdr = NULL;
316     ret = 0;
317     firstaddr = lastaddr = 0;
318     ehdr = ef->ehdr;
319     if (ehdr->e_type == ET_EXEC) {
320 #if defined(__i386__) || defined(__amd64__)
321 #if __ELF_WORD_SIZE == 64
322         off = - (off & 0xffffffffff000000ull);/* x86_64 relocates after locore */
323 #else
324         off = - (off & 0xff000000u);    /* i386 relocates after locore */
325 #endif
326 #elif defined(__powerpc__)
327         /*
328          * On the purely virtual memory machines like e500, the kernel is
329          * linked against its final VA range, which is most often not
330          * available at the loader stage, but only after kernel initializes
331          * and completes its VM settings. In such cases we cannot use p_vaddr
332          * field directly to load ELF segments, but put them at some
333          * 'load-time' locations.
334          */
335         if (off & 0xf0000000u) {
336             off = -(off & 0xf0000000u);
337             /*
338              * XXX the physical load address should not be hardcoded. Note
339              * that the Book-E kernel assumes that it's loaded at a 16MB
340              * boundary for now...
341              */
342             off += 0x01000000;
343             ehdr->e_entry += off;
344 #ifdef ELF_VERBOSE
345             printf("Converted entry 0x%08x\n", ehdr->e_entry);
346 #endif
347         } else
348             off = 0;
349 #elif defined(__arm__)
350         /*
351          * The elf headers in some kernels specify virtual addresses in all
352          * header fields.  More recently, the e_entry and p_paddr fields are the
353          * proper physical addresses.  Even when the p_paddr fields are correct,
354          * the MI code below uses the p_vaddr fields with an offset added for
355          * loading (doing so is arguably wrong).  To make loading work, we need
356          * an offset that represents the difference between physical and virtual
357          * addressing.  ARM kernels are always linked at 0xCnnnnnnn.  Depending
358          * on the headers, the offset value passed in may be physical or virtual
359          * (because it typically comes from e_entry), but we always replace
360          * whatever is passed in with the va<->pa offset.  On the other hand, we
361          * always remove the high-order part of the entry address whether it's
362          * physical or virtual, because it will be adjusted later for the actual
363          * physical entry point based on where the image gets loaded.
364          */
365         off = -0xc0000000;
366         ehdr->e_entry &= ~0xf0000000;
367 #ifdef ELF_VERBOSE
368         printf("ehdr->e_entry 0x%08x, va<->pa off %llx\n", ehdr->e_entry, off);
369 #endif
370 #else
371         off = 0;                /* other archs use direct mapped kernels */
372 #endif
373     }
374     ef->off = off;
375
376     if (ef->kernel)
377         __elfN(relocation_offset) = off;
378
379     if ((ehdr->e_phoff + ehdr->e_phnum * sizeof(*phdr)) > ef->firstlen) {
380         printf("elf" __XSTRING(__ELF_WORD_SIZE) "_loadimage: program header not within first page\n");
381         goto out;
382     }
383     phdr = (Elf_Phdr *)(ef->firstpage + ehdr->e_phoff);
384
385     for (i = 0; i < ehdr->e_phnum; i++) {
386         /* We want to load PT_LOAD segments only.. */
387         if (phdr[i].p_type != PT_LOAD)
388             continue;
389
390 #ifdef ELF_VERBOSE
391         printf("Segment: 0x%lx@0x%lx -> 0x%lx-0x%lx",
392             (long)phdr[i].p_filesz, (long)phdr[i].p_offset,
393             (long)(phdr[i].p_vaddr + off),
394             (long)(phdr[i].p_vaddr + off + phdr[i].p_memsz - 1));
395 #else
396         if ((phdr[i].p_flags & PF_W) == 0) {
397             printf("text=0x%lx ", (long)phdr[i].p_filesz);
398         } else {
399             printf("data=0x%lx", (long)phdr[i].p_filesz);
400             if (phdr[i].p_filesz < phdr[i].p_memsz)
401                 printf("+0x%lx", (long)(phdr[i].p_memsz -phdr[i].p_filesz));
402             printf(" ");
403         }
404 #endif
405         fpcopy = 0;
406         if (ef->firstlen > phdr[i].p_offset) {
407             fpcopy = ef->firstlen - phdr[i].p_offset;
408             archsw.arch_copyin(ef->firstpage + phdr[i].p_offset,
409                                phdr[i].p_vaddr + off, fpcopy);
410         }
411         if (phdr[i].p_filesz > fpcopy) {
412             if (kern_pread(ef->fd, phdr[i].p_vaddr + off + fpcopy,
413                 phdr[i].p_filesz - fpcopy, phdr[i].p_offset + fpcopy) != 0) {
414                 printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
415                     "_loadimage: read failed\n");
416                 goto out;
417             }
418         }
419         /* clear space from oversized segments; eg: bss */
420         if (phdr[i].p_filesz < phdr[i].p_memsz) {
421 #ifdef ELF_VERBOSE
422             printf(" (bss: 0x%lx-0x%lx)",
423                 (long)(phdr[i].p_vaddr + off + phdr[i].p_filesz),
424                 (long)(phdr[i].p_vaddr + off + phdr[i].p_memsz - 1));
425 #endif
426
427             kern_bzero(phdr[i].p_vaddr + off + phdr[i].p_filesz,
428                 phdr[i].p_memsz - phdr[i].p_filesz);
429         }
430 #ifdef ELF_VERBOSE
431         printf("\n");
432 #endif
433
434         if (archsw.arch_loadseg != NULL)
435             archsw.arch_loadseg(ehdr, phdr + i, off);
436
437         if (firstaddr == 0 || firstaddr > (phdr[i].p_vaddr + off))
438             firstaddr = phdr[i].p_vaddr + off;
439         if (lastaddr == 0 || lastaddr < (phdr[i].p_vaddr + off + phdr[i].p_memsz))
440             lastaddr = phdr[i].p_vaddr + off + phdr[i].p_memsz;
441     }
442     lastaddr = roundup(lastaddr, sizeof(long));
443
444     /*
445      * Get the section headers.  We need this for finding the .ctors
446      * section as well as for loading any symbols.  Both may be hard
447      * to do if reading from a .gz file as it involves seeking.  I
448      * think the rule is going to have to be that you must strip a
449      * file to remove symbols before gzipping it.
450      */
451     chunk = ehdr->e_shnum * ehdr->e_shentsize;
452     if (chunk == 0 || ehdr->e_shoff == 0)
453         goto nosyms;
454     shdr = alloc_pread(ef->fd, ehdr->e_shoff, chunk);
455     if (shdr == NULL) {
456         printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
457             "_loadimage: failed to read section headers");
458         goto nosyms;
459     }
460     file_addmetadata(fp, MODINFOMD_SHDR, chunk, shdr);
461
462     /*
463      * Read the section string table and look for the .ctors section.
464      * We need to tell the kernel where it is so that it can call the
465      * ctors.
466      */
467     chunk = shdr[ehdr->e_shstrndx].sh_size;
468     if (chunk) {
469         shstr = alloc_pread(ef->fd, shdr[ehdr->e_shstrndx].sh_offset, chunk);
470         if (shstr) {
471             for (i = 0; i < ehdr->e_shnum; i++) {
472                 if (strcmp(shstr + shdr[i].sh_name, ".ctors") != 0)
473                     continue;
474                 ctors = shdr[i].sh_addr;
475                 file_addmetadata(fp, MODINFOMD_CTORS_ADDR, sizeof(ctors),
476                     &ctors);
477                 size = shdr[i].sh_size;
478                 file_addmetadata(fp, MODINFOMD_CTORS_SIZE, sizeof(size),
479                     &size);
480                 break;
481             }
482             free(shstr);
483         }
484     }
485
486     /*
487      * Now load any symbols.
488      */
489     symtabindex = -1;
490     symstrindex = -1;
491     for (i = 0; i < ehdr->e_shnum; i++) {
492         if (shdr[i].sh_type != SHT_SYMTAB)
493             continue;
494         for (j = 0; j < ehdr->e_phnum; j++) {
495             if (phdr[j].p_type != PT_LOAD)
496                 continue;
497             if (shdr[i].sh_offset >= phdr[j].p_offset &&
498                 (shdr[i].sh_offset + shdr[i].sh_size <=
499                  phdr[j].p_offset + phdr[j].p_filesz)) {
500                 shdr[i].sh_offset = 0;
501                 shdr[i].sh_size = 0;
502                 break;
503             }
504         }
505         if (shdr[i].sh_offset == 0 || shdr[i].sh_size == 0)
506             continue;           /* alread loaded in a PT_LOAD above */
507         /* Save it for loading below */
508         symtabindex = i;
509         symstrindex = shdr[i].sh_link;
510     }
511     if (symtabindex < 0 || symstrindex < 0)
512         goto nosyms;
513
514     /* Ok, committed to a load. */
515 #ifndef ELF_VERBOSE
516     printf("syms=[");
517 #endif
518     ssym = lastaddr;
519     for (i = symtabindex; i >= 0; i = symstrindex) {
520 #ifdef ELF_VERBOSE
521         char    *secname;
522
523         switch(shdr[i].sh_type) {
524             case SHT_SYMTAB:            /* Symbol table */
525                 secname = "symtab";
526                 break;
527             case SHT_STRTAB:            /* String table */
528                 secname = "strtab";
529                 break;
530             default:
531                 secname = "WHOA!!";
532                 break;
533         }
534 #endif
535
536         size = shdr[i].sh_size;
537         archsw.arch_copyin(&size, lastaddr, sizeof(size));
538         lastaddr += sizeof(size);
539
540 #ifdef ELF_VERBOSE
541         printf("\n%s: 0x%jx@0x%jx -> 0x%jx-0x%jx", secname,
542             (uintmax_t)shdr[i].sh_size, (uintmax_t)shdr[i].sh_offset,
543             (uintmax_t)lastaddr, (uintmax_t)(lastaddr + shdr[i].sh_size));
544 #else
545         if (i == symstrindex)
546             printf("+");
547         printf("0x%lx+0x%lx", (long)sizeof(size), (long)size);
548 #endif
549
550         if (lseek(ef->fd, (off_t)shdr[i].sh_offset, SEEK_SET) == -1) {
551             printf("\nelf" __XSTRING(__ELF_WORD_SIZE) "_loadimage: could not seek for symbols - skipped!");
552             lastaddr = ssym;
553             ssym = 0;
554             goto nosyms;
555         }
556         result = archsw.arch_readin(ef->fd, lastaddr, shdr[i].sh_size);
557         if (result < 0 || (size_t)result != shdr[i].sh_size) {
558             printf("\nelf" __XSTRING(__ELF_WORD_SIZE) "_loadimage: could not read symbols - skipped! (%ju != %ju)", (uintmax_t)result,
559                 (uintmax_t)shdr[i].sh_size);
560             lastaddr = ssym;
561             ssym = 0;
562             goto nosyms;
563         }
564         /* Reset offsets relative to ssym */
565         lastaddr += shdr[i].sh_size;
566         lastaddr = roundup(lastaddr, sizeof(size));
567         if (i == symtabindex)
568             symtabindex = -1;
569         else if (i == symstrindex)
570             symstrindex = -1;
571     }
572     esym = lastaddr;
573 #ifndef ELF_VERBOSE
574     printf("]");
575 #endif
576
577     file_addmetadata(fp, MODINFOMD_SSYM, sizeof(ssym), &ssym);
578     file_addmetadata(fp, MODINFOMD_ESYM, sizeof(esym), &esym);
579
580 nosyms:
581     printf("\n");
582
583     ret = lastaddr - firstaddr;
584     fp->f_addr = firstaddr;
585
586     php = NULL;
587     for (i = 0; i < ehdr->e_phnum; i++) {
588         if (phdr[i].p_type == PT_DYNAMIC) {
589             php = phdr + i;
590             adp = php->p_vaddr;
591             file_addmetadata(fp, MODINFOMD_DYNAMIC, sizeof(adp), &adp);
592             break;
593         }
594     }
595
596     if (php == NULL)    /* this is bad, we cannot get to symbols or _DYNAMIC */
597         goto out;
598
599     ndp = php->p_filesz / sizeof(Elf_Dyn);
600     if (ndp == 0)
601         goto out;
602     dp = malloc(php->p_filesz);
603     if (dp == NULL)
604         goto out;
605     archsw.arch_copyout(php->p_vaddr + off, dp, php->p_filesz);
606
607     ef->strsz = 0;
608     for (i = 0; i < ndp; i++) {
609         if (dp[i].d_tag == 0)
610             break;
611         switch (dp[i].d_tag) {
612         case DT_HASH:
613             ef->hashtab = (Elf_Hashelt*)(uintptr_t)(dp[i].d_un.d_ptr + off);
614             break;
615         case DT_STRTAB:
616             ef->strtab = (char *)(uintptr_t)(dp[i].d_un.d_ptr + off);
617             break;
618         case DT_STRSZ:
619             ef->strsz = dp[i].d_un.d_val;
620             break;
621         case DT_SYMTAB:
622             ef->symtab = (Elf_Sym*)(uintptr_t)(dp[i].d_un.d_ptr + off);
623             break;
624         case DT_REL:
625             ef->rel = (Elf_Rel *)(uintptr_t)(dp[i].d_un.d_ptr + off);
626             break;
627         case DT_RELSZ:
628             ef->relsz = dp[i].d_un.d_val;
629             break;
630         case DT_RELA:
631             ef->rela = (Elf_Rela *)(uintptr_t)(dp[i].d_un.d_ptr + off);
632             break;
633         case DT_RELASZ:
634             ef->relasz = dp[i].d_un.d_val;
635             break;
636         default:
637             break;
638         }
639     }
640     if (ef->hashtab == NULL || ef->symtab == NULL ||
641         ef->strtab == NULL || ef->strsz == 0)
642         goto out;
643     COPYOUT(ef->hashtab, &ef->nbuckets, sizeof(ef->nbuckets));
644     COPYOUT(ef->hashtab + 1, &ef->nchains, sizeof(ef->nchains));
645     ef->buckets = ef->hashtab + 2;
646     ef->chains = ef->buckets + ef->nbuckets;
647
648     if (__elfN(lookup_symbol)(fp, ef, "__start_set_modmetadata_set", &sym) != 0)
649         return 0;
650     p_start = sym.st_value + ef->off;
651     if (__elfN(lookup_symbol)(fp, ef, "__stop_set_modmetadata_set", &sym) != 0)
652         return ENOENT;
653     p_end = sym.st_value + ef->off;
654
655     if (__elfN(parse_modmetadata)(fp, ef, p_start, p_end) == 0)
656         goto out;
657
658     if (ef->kernel)                     /* kernel must not depend on anything */
659         goto out;
660
661 out:
662     if (dp)
663         free(dp);
664     if (shdr)
665         free(shdr);
666     return ret;
667 }
668
669 static char invalid_name[] = "bad";
670
671 char *
672 fake_modname(const char *name)
673 {
674     const char *sp, *ep;
675     char *fp;
676     size_t len;
677
678     sp = strrchr(name, '/');
679     if (sp)
680         sp++;
681     else
682         sp = name;
683     ep = strrchr(name, '.');
684     if (ep) {
685             if (ep == name) {
686                 sp = invalid_name;
687                 ep = invalid_name + sizeof(invalid_name) - 1;
688             } 
689     } else
690         ep = name + strlen(name);
691     len = ep - sp;
692     fp = malloc(len + 1);
693     if (fp == NULL)
694         return NULL;
695     memcpy(fp, sp, len);
696     fp[len] = '\0';
697     return fp;
698 }
699
700 #if (defined(__i386__) || defined(__powerpc__)) && __ELF_WORD_SIZE == 64
701 struct mod_metadata64 {
702         int             md_version;     /* structure version MDTV_* */  
703         int             md_type;        /* type of entry MDT_* */
704         u_int64_t       md_data;        /* specific data */
705         u_int64_t       md_cval;        /* common string label */
706 };
707 #endif
708 #if defined(__amd64__) && __ELF_WORD_SIZE == 32
709 struct mod_metadata32 {
710         int             md_version;     /* structure version MDTV_* */  
711         int             md_type;        /* type of entry MDT_* */
712         u_int32_t       md_data;        /* specific data */
713         u_int32_t       md_cval;        /* common string label */
714 };
715 #endif
716
717 int
718 __elfN(load_modmetadata)(struct preloaded_file *fp, u_int64_t dest)
719 {
720         struct elf_file          ef;
721         int                      err, i, j;
722         Elf_Shdr                *sh_meta, *shdr = NULL;
723         Elf_Shdr                *sh_data[2];
724         char                    *shstrtab = NULL;
725         size_t                   size;
726         Elf_Addr                 p_start, p_end;
727
728         bzero(&ef, sizeof(struct elf_file));
729         ef.fd = -1;
730
731         err = __elfN(load_elf_header)(fp->f_name, &ef);
732         if (err != 0)
733                 goto out;
734
735         if (ef.kernel == 1 || ef.ehdr->e_type == ET_EXEC) {
736                 ef.kernel = 1;
737         } else if (ef.ehdr->e_type != ET_DYN) {
738                 err = EFTYPE;
739                 goto out;
740         }
741
742         size = ef.ehdr->e_shnum * ef.ehdr->e_shentsize;
743         shdr = alloc_pread(ef.fd, ef.ehdr->e_shoff, size);
744         if (shdr == NULL) {
745                 err = ENOMEM;
746                 goto out;
747         }
748
749         /* Load shstrtab. */
750         shstrtab = alloc_pread(ef.fd, shdr[ef.ehdr->e_shstrndx].sh_offset,
751             shdr[ef.ehdr->e_shstrndx].sh_size);
752         if (shstrtab == NULL) {
753                 printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
754                     "load_modmetadata: unable to load shstrtab\n");
755                 err = EFTYPE;
756                 goto out;
757         }
758
759         /* Find set_modmetadata_set and data sections. */
760         sh_data[0] = sh_data[1] = sh_meta = NULL;
761         for (i = 0, j = 0; i < ef.ehdr->e_shnum; i++) {
762                 if (strcmp(&shstrtab[shdr[i].sh_name],
763                     "set_modmetadata_set") == 0) {
764                         sh_meta = &shdr[i];
765                 }
766                 if ((strcmp(&shstrtab[shdr[i].sh_name], ".data") == 0) ||
767                     (strcmp(&shstrtab[shdr[i].sh_name], ".rodata") == 0)) {
768                         sh_data[j++] = &shdr[i];
769                 }
770         }
771         if (sh_meta == NULL || sh_data[0] == NULL || sh_data[1] == NULL) {
772                 printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
773     "load_modmetadata: unable to find set_modmetadata_set or data sections\n");
774                 err = EFTYPE;
775                 goto out;
776         }
777
778         /* Load set_modmetadata_set into memory */
779         err = kern_pread(ef.fd, dest, sh_meta->sh_size, sh_meta->sh_offset);
780         if (err != 0) {
781                 printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
782     "load_modmetadata: unable to load set_modmetadata_set: %d\n", err);
783                 goto out;
784         }
785         p_start = dest;
786         p_end = dest + sh_meta->sh_size;
787         dest += sh_meta->sh_size;
788
789         /* Load data sections into memory. */
790         err = kern_pread(ef.fd, dest, sh_data[0]->sh_size,
791             sh_data[0]->sh_offset);
792         if (err != 0) {
793                 printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
794                     "load_modmetadata: unable to load data: %d\n", err);
795                 goto out;
796         }
797
798         /*
799          * We have to increment the dest, so that the offset is the same into
800          * both the .rodata and .data sections.
801          */
802         ef.off = -(sh_data[0]->sh_addr - dest);
803         dest += (sh_data[1]->sh_addr - sh_data[0]->sh_addr);
804
805         err = kern_pread(ef.fd, dest, sh_data[1]->sh_size,
806             sh_data[1]->sh_offset);
807         if (err != 0) {
808                 printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
809                     "load_modmetadata: unable to load data: %d\n", err);
810                 goto out;
811         }
812
813         err = __elfN(parse_modmetadata)(fp, &ef, p_start, p_end);
814         if (err != 0) {
815                 printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
816                     "load_modmetadata: unable to parse metadata: %d\n", err);
817                 goto out;
818         }
819
820 out:
821         if (shstrtab != NULL)
822                 free(shstrtab);
823         if (shdr != NULL)
824                 free(shdr);
825         if (ef.firstpage != NULL)
826                 free(ef.firstpage);
827         if (ef.fd != -1)
828                 close(ef.fd);
829         return (err);
830 }
831
832 int
833 __elfN(parse_modmetadata)(struct preloaded_file *fp, elf_file_t ef,
834     Elf_Addr p_start, Elf_Addr p_end)
835 {
836     struct mod_metadata md;
837 #if (defined(__i386__) || defined(__powerpc__)) && __ELF_WORD_SIZE == 64
838     struct mod_metadata64 md64;
839 #elif defined(__amd64__) && __ELF_WORD_SIZE == 32
840     struct mod_metadata32 md32;
841 #endif
842     struct mod_depend *mdepend;
843     struct mod_version mver;
844     char *s;
845     int error, modcnt, minfolen;
846     Elf_Addr v, p;
847
848     modcnt = 0;
849     p = p_start;
850     while (p < p_end) {
851         COPYOUT(p, &v, sizeof(v));
852         error = __elfN(reloc_ptr)(fp, ef, p, &v, sizeof(v));
853         if (error == EOPNOTSUPP)
854             v += ef->off;
855         else if (error != 0)
856             return (error);
857 #if (defined(__i386__) || defined(__powerpc__)) && __ELF_WORD_SIZE == 64
858         COPYOUT(v, &md64, sizeof(md64));
859         error = __elfN(reloc_ptr)(fp, ef, v, &md64, sizeof(md64));
860         if (error == EOPNOTSUPP) {
861             md64.md_cval += ef->off;
862             md64.md_data += ef->off;
863         } else if (error != 0)
864             return (error);
865         md.md_version = md64.md_version;
866         md.md_type = md64.md_type;
867         md.md_cval = (const char *)(uintptr_t)md64.md_cval;
868         md.md_data = (void *)(uintptr_t)md64.md_data;
869 #elif defined(__amd64__) && __ELF_WORD_SIZE == 32
870         COPYOUT(v, &md32, sizeof(md32));
871         error = __elfN(reloc_ptr)(fp, ef, v, &md32, sizeof(md32));
872         if (error == EOPNOTSUPP) {
873             md32.md_cval += ef->off;
874             md32.md_data += ef->off;
875         } else if (error != 0)
876             return (error);
877         md.md_version = md32.md_version;
878         md.md_type = md32.md_type;
879         md.md_cval = (const char *)(uintptr_t)md32.md_cval;
880         md.md_data = (void *)(uintptr_t)md32.md_data;
881 #else
882         COPYOUT(v, &md, sizeof(md));
883         error = __elfN(reloc_ptr)(fp, ef, v, &md, sizeof(md));
884         if (error == EOPNOTSUPP) {
885             md.md_cval += ef->off;
886             md.md_data += ef->off;
887         } else if (error != 0)
888             return (error);
889 #endif
890         p += sizeof(Elf_Addr);
891         switch(md.md_type) {
892           case MDT_DEPEND:
893             if (ef->kernel)             /* kernel must not depend on anything */
894               break;
895             s = strdupout((vm_offset_t)md.md_cval);
896             minfolen = sizeof(*mdepend) + strlen(s) + 1;
897             mdepend = malloc(minfolen);
898             if (mdepend == NULL)
899                 return ENOMEM;
900             COPYOUT((vm_offset_t)md.md_data, mdepend, sizeof(*mdepend));
901             strcpy((char*)(mdepend + 1), s);
902             free(s);
903             file_addmetadata(fp, MODINFOMD_DEPLIST, minfolen, mdepend);
904             free(mdepend);
905             break;
906           case MDT_VERSION:
907             s = strdupout((vm_offset_t)md.md_cval);
908             COPYOUT((vm_offset_t)md.md_data, &mver, sizeof(mver));
909             file_addmodule(fp, s, mver.mv_version, NULL);
910             free(s);
911             modcnt++;
912             break;
913         }
914     }
915     if (modcnt == 0) {
916         s = fake_modname(fp->f_name);
917         file_addmodule(fp, s, 1, NULL);
918         free(s);
919     }
920     return 0;
921 }
922
923 static unsigned long
924 elf_hash(const char *name)
925 {
926     const unsigned char *p = (const unsigned char *) name;
927     unsigned long h = 0;
928     unsigned long g;
929
930     while (*p != '\0') {
931         h = (h << 4) + *p++;
932         if ((g = h & 0xf0000000) != 0)
933             h ^= g >> 24;
934         h &= ~g;
935     }
936     return h;
937 }
938
939 static const char __elfN(bad_symtable)[] = "elf" __XSTRING(__ELF_WORD_SIZE) "_lookup_symbol: corrupt symbol table\n";
940 int
941 __elfN(lookup_symbol)(struct preloaded_file *fp, elf_file_t ef, const char* name,
942                   Elf_Sym *symp)
943 {
944     Elf_Hashelt symnum;
945     Elf_Sym sym;
946     char *strp;
947     unsigned long hash;
948
949     hash = elf_hash(name);
950     COPYOUT(&ef->buckets[hash % ef->nbuckets], &symnum, sizeof(symnum));
951
952     while (symnum != STN_UNDEF) {
953         if (symnum >= ef->nchains) {
954             printf(__elfN(bad_symtable));
955             return ENOENT;
956         }
957
958         COPYOUT(ef->symtab + symnum, &sym, sizeof(sym));
959         if (sym.st_name == 0) {
960             printf(__elfN(bad_symtable));
961             return ENOENT;
962         }
963
964         strp = strdupout((vm_offset_t)(ef->strtab + sym.st_name));
965         if (strcmp(name, strp) == 0) {
966             free(strp);
967             if (sym.st_shndx != SHN_UNDEF ||
968                 (sym.st_value != 0 &&
969                  ELF_ST_TYPE(sym.st_info) == STT_FUNC)) {
970                 *symp = sym;
971                 return 0;
972             }
973             return ENOENT;
974         }
975         free(strp);
976         COPYOUT(&ef->chains[symnum], &symnum, sizeof(symnum));
977     }
978     return ENOENT;
979 }
980
981 /*
982  * Apply any intra-module relocations to the value. p is the load address
983  * of the value and val/len is the value to be modified. This does NOT modify
984  * the image in-place, because this is done by kern_linker later on.
985  *
986  * Returns EOPNOTSUPP if no relocation method is supplied.
987  */
988 static int
989 __elfN(reloc_ptr)(struct preloaded_file *mp, elf_file_t ef,
990     Elf_Addr p, void *val, size_t len)
991 {
992         size_t n;
993         Elf_Rela a;
994         Elf_Rel r;
995         int error;
996
997         /*
998          * The kernel is already relocated, but we still want to apply
999          * offset adjustments.
1000          */
1001         if (ef->kernel)
1002                 return (EOPNOTSUPP);
1003
1004         for (n = 0; n < ef->relsz / sizeof(r); n++) {
1005                 COPYOUT(ef->rel + n, &r, sizeof(r));
1006
1007                 error = __elfN(reloc)(ef, __elfN(symaddr), &r, ELF_RELOC_REL,
1008                     ef->off, p, val, len);
1009                 if (error != 0)
1010                         return (error);
1011         }
1012         for (n = 0; n < ef->relasz / sizeof(a); n++) {
1013                 COPYOUT(ef->rela + n, &a, sizeof(a));
1014
1015                 error = __elfN(reloc)(ef, __elfN(symaddr), &a, ELF_RELOC_RELA,
1016                     ef->off, p, val, len);
1017                 if (error != 0)
1018                         return (error);
1019         }
1020
1021         return (0);
1022 }
1023
1024 static Elf_Addr
1025 __elfN(symaddr)(struct elf_file *ef, Elf_Size symidx)
1026 {
1027
1028         /* Symbol lookup by index not required here. */
1029         return (0);
1030 }