]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/boot/common/load_elf.c
Merge ^/head r274961 through r276418.
[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 static symaddr_fn __elfN(symaddr);
81 static char     *fake_modname(const char *name);
82
83 const char      *__elfN(kerneltype) = "elf kernel";
84 const char      *__elfN(moduletype) = "elf module";
85
86 u_int64_t       __elfN(relocation_offset) = 0;
87
88 /*
89  * Attempt to load the file (file) as an ELF module.  It will be stored at
90  * (dest), and a pointer to a module structure describing the loaded object
91  * will be saved in (result).
92  */
93 int
94 __elfN(loadfile)(char *filename, u_int64_t dest, struct preloaded_file **result)
95 {
96     struct preloaded_file       *fp, *kfp;
97     struct elf_file             ef;
98     Elf_Ehdr                    *ehdr;
99     int                         err;
100     ssize_t                     bytes_read;
101
102     fp = NULL;
103     bzero(&ef, sizeof(struct elf_file));
104
105     /*
106      * Open the image, read and validate the ELF header 
107      */
108     if (filename == NULL)       /* can't handle nameless */
109         return(EFTYPE);
110     if ((ef.fd = open(filename, O_RDONLY)) == -1)
111         return(errno);
112     ef.firstpage = malloc(PAGE_SIZE);
113     if (ef.firstpage == NULL) {
114         close(ef.fd);
115         return(ENOMEM);
116     }
117     bytes_read = read(ef.fd, ef.firstpage, PAGE_SIZE);
118     ef.firstlen = (size_t)bytes_read;
119     if (bytes_read < 0 || ef.firstlen <= sizeof(Elf_Ehdr)) {
120         err = EFTYPE;           /* could be EIO, but may be small file */
121         goto oerr;
122     }
123     ehdr = ef.ehdr = (Elf_Ehdr *)ef.firstpage;
124
125     /* Is it ELF? */
126     if (!IS_ELF(*ehdr)) {
127         err = EFTYPE;
128         goto oerr;
129     }
130     if (ehdr->e_ident[EI_CLASS] != ELF_TARG_CLASS ||    /* Layout ? */
131         ehdr->e_ident[EI_DATA] != ELF_TARG_DATA ||
132         ehdr->e_ident[EI_VERSION] != EV_CURRENT ||      /* Version ? */
133         ehdr->e_version != EV_CURRENT ||
134         ehdr->e_machine != ELF_TARG_MACH) {             /* Machine ? */
135         err = EFTYPE;
136         goto oerr;
137     }
138
139
140     /*
141      * Check to see what sort of module we are.
142      */
143     kfp = file_findfile(NULL, NULL);
144     if (ehdr->e_type == ET_DYN) {
145         /* Looks like a kld module */
146         if (kfp == NULL) {
147             printf("elf" __XSTRING(__ELF_WORD_SIZE) "_loadfile: can't load module before kernel\n");
148             err = EPERM;
149             goto oerr;
150         }
151         if (strcmp(__elfN(kerneltype), kfp->f_type)) {
152             printf("elf" __XSTRING(__ELF_WORD_SIZE) "_loadfile: can't load module with kernel type '%s'\n", kfp->f_type);
153             err = EPERM;
154             goto oerr;
155         }
156         /* Looks OK, got ahead */
157         ef.kernel = 0;
158
159     } else if (ehdr->e_type == ET_EXEC) {
160         /* Looks like a kernel */
161         if (kfp != NULL) {
162             printf("elf" __XSTRING(__ELF_WORD_SIZE) "_loadfile: kernel already loaded\n");
163             err = EPERM;
164             goto oerr;
165         }
166         /* 
167          * Calculate destination address based on kernel entrypoint     
168          */
169         dest = (ehdr->e_entry & ~PAGE_MASK);
170         if (dest == 0) {
171             printf("elf" __XSTRING(__ELF_WORD_SIZE) "_loadfile: not a kernel (maybe static binary?)\n");
172             err = EPERM;
173             goto oerr;
174         }
175         ef.kernel = 1;
176
177     } else {
178         err = EFTYPE;
179         goto oerr;
180     }
181
182     if (archsw.arch_loadaddr != NULL)
183         dest = archsw.arch_loadaddr(LOAD_ELF, ehdr, dest);
184     else
185         dest = roundup(dest, PAGE_SIZE);
186
187     /* 
188      * Ok, we think we should handle this.
189      */
190     fp = file_alloc();
191     if (fp == NULL) {
192             printf("elf" __XSTRING(__ELF_WORD_SIZE) "_loadfile: cannot allocate module info\n");
193             err = EPERM;
194             goto out;
195     }
196     if (ef.kernel)
197         setenv("kernelname", filename, 1);
198     fp->f_name = strdup(filename);
199     fp->f_type = strdup(ef.kernel ? __elfN(kerneltype) : __elfN(moduletype));
200
201 #ifdef ELF_VERBOSE
202     if (ef.kernel)
203         printf("%s entry at 0x%jx\n", filename, (uintmax_t)ehdr->e_entry);
204 #else
205     printf("%s ", filename);
206 #endif
207
208     fp->f_size = __elfN(loadimage)(fp, &ef, dest);
209     if (fp->f_size == 0 || fp->f_addr == 0)
210         goto ioerr;
211
212     /* save exec header as metadata */
213     file_addmetadata(fp, MODINFOMD_ELFHDR, sizeof(*ehdr), ehdr);
214
215     /* Load OK, return module pointer */
216     *result = (struct preloaded_file *)fp;
217     err = 0;
218     goto out;
219     
220  ioerr:
221     err = EIO;
222  oerr:
223     file_discard(fp);
224  out:
225     if (ef.firstpage)
226         free(ef.firstpage);
227     close(ef.fd);
228     return(err);
229 }
230
231 /*
232  * With the file (fd) open on the image, and (ehdr) containing
233  * the Elf header, load the image at (off)
234  */
235 static int
236 __elfN(loadimage)(struct preloaded_file *fp, elf_file_t ef, u_int64_t off)
237 {
238     int         i;
239     u_int       j;
240     Elf_Ehdr    *ehdr;
241     Elf_Phdr    *phdr, *php;
242     Elf_Shdr    *shdr;
243     char        *shstr;
244     int         ret;
245     vm_offset_t firstaddr;
246     vm_offset_t lastaddr;
247     size_t      chunk;
248     ssize_t     result;
249     Elf_Addr    ssym, esym;
250     Elf_Dyn     *dp;
251     Elf_Addr    adp;
252     Elf_Addr    ctors;
253     int         ndp;
254     int         symstrindex;
255     int         symtabindex;
256     Elf_Size    size;
257     u_int       fpcopy;
258
259     dp = NULL;
260     shdr = NULL;
261     ret = 0;
262     firstaddr = lastaddr = 0;
263     ehdr = ef->ehdr;
264     if (ef->kernel) {
265 #if defined(__i386__) || defined(__amd64__)
266 #if __ELF_WORD_SIZE == 64
267         off = - (off & 0xffffffffff000000ull);/* x86_64 relocates after locore */
268 #else
269         off = - (off & 0xff000000u);    /* i386 relocates after locore */
270 #endif
271 #elif defined(__powerpc__)
272         /*
273          * On the purely virtual memory machines like e500, the kernel is
274          * linked against its final VA range, which is most often not
275          * available at the loader stage, but only after kernel initializes
276          * and completes its VM settings. In such cases we cannot use p_vaddr
277          * field directly to load ELF segments, but put them at some
278          * 'load-time' locations.
279          */
280         if (off & 0xf0000000u) {
281             off = -(off & 0xf0000000u);
282             /*
283              * XXX the physical load address should not be hardcoded. Note
284              * that the Book-E kernel assumes that it's loaded at a 16MB
285              * boundary for now...
286              */
287             off += 0x01000000;
288             ehdr->e_entry += off;
289 #ifdef ELF_VERBOSE
290             printf("Converted entry 0x%08x\n", ehdr->e_entry);
291 #endif
292         } else
293             off = 0;
294 #elif defined(__arm__)
295         /*
296          * The elf headers in some kernels specify virtual addresses in all
297          * header fields.  More recently, the e_entry and p_paddr fields are the
298          * proper physical addresses.  Even when the p_paddr fields are correct,
299          * the MI code below uses the p_vaddr fields with an offset added for
300          * loading (doing so is arguably wrong).  To make loading work, we need
301          * an offset that represents the difference between physical and virtual
302          * addressing.  ARM kernels are always linked at 0xCnnnnnnn.  Depending
303          * on the headers, the offset value passed in may be physical or virtual
304          * (because it typically comes from e_entry), but we always replace
305          * whatever is passed in with the va<->pa offset.  On the other hand, we
306          * always remove the high-order part of the entry address whether it's
307          * physical or virtual, because it will be adjusted later for the actual
308          * physical entry point based on where the image gets loaded.
309          */
310         off = -0xc0000000;
311         ehdr->e_entry &= ~0xf0000000;
312 #ifdef ELF_VERBOSE
313         printf("ehdr->e_entry 0x%08x, va<->pa off %llx\n", ehdr->e_entry, off);
314 #endif
315 #else
316         off = 0;                /* other archs use direct mapped kernels */
317 #endif
318         __elfN(relocation_offset) = off;
319     }
320     ef->off = off;
321
322     if ((ehdr->e_phoff + ehdr->e_phnum * sizeof(*phdr)) > ef->firstlen) {
323         printf("elf" __XSTRING(__ELF_WORD_SIZE) "_loadimage: program header not within first page\n");
324         goto out;
325     }
326     phdr = (Elf_Phdr *)(ef->firstpage + ehdr->e_phoff);
327
328     for (i = 0; i < ehdr->e_phnum; i++) {
329         /* We want to load PT_LOAD segments only.. */
330         if (phdr[i].p_type != PT_LOAD)
331             continue;
332
333 #ifdef ELF_VERBOSE
334         printf("Segment: 0x%lx@0x%lx -> 0x%lx-0x%lx",
335             (long)phdr[i].p_filesz, (long)phdr[i].p_offset,
336             (long)(phdr[i].p_vaddr + off),
337             (long)(phdr[i].p_vaddr + off + phdr[i].p_memsz - 1));
338 #else
339         if ((phdr[i].p_flags & PF_W) == 0) {
340             printf("text=0x%lx ", (long)phdr[i].p_filesz);
341         } else {
342             printf("data=0x%lx", (long)phdr[i].p_filesz);
343             if (phdr[i].p_filesz < phdr[i].p_memsz)
344                 printf("+0x%lx", (long)(phdr[i].p_memsz -phdr[i].p_filesz));
345             printf(" ");
346         }
347 #endif
348         fpcopy = 0;
349         if (ef->firstlen > phdr[i].p_offset) {
350             fpcopy = ef->firstlen - phdr[i].p_offset;
351             archsw.arch_copyin(ef->firstpage + phdr[i].p_offset,
352                                phdr[i].p_vaddr + off, fpcopy);
353         }
354         if (phdr[i].p_filesz > fpcopy) {
355             if (kern_pread(ef->fd, phdr[i].p_vaddr + off + fpcopy,
356                 phdr[i].p_filesz - fpcopy, phdr[i].p_offset + fpcopy) != 0) {
357                 printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
358                     "_loadimage: read failed\n");
359                 goto out;
360             }
361         }
362         /* clear space from oversized segments; eg: bss */
363         if (phdr[i].p_filesz < phdr[i].p_memsz) {
364 #ifdef ELF_VERBOSE
365             printf(" (bss: 0x%lx-0x%lx)",
366                 (long)(phdr[i].p_vaddr + off + phdr[i].p_filesz),
367                 (long)(phdr[i].p_vaddr + off + phdr[i].p_memsz - 1));
368 #endif
369
370             kern_bzero(phdr[i].p_vaddr + off + phdr[i].p_filesz,
371                 phdr[i].p_memsz - phdr[i].p_filesz);
372         }
373 #ifdef ELF_VERBOSE
374         printf("\n");
375 #endif
376
377         if (archsw.arch_loadseg != NULL)
378             archsw.arch_loadseg(ehdr, phdr + i, off);
379
380         if (firstaddr == 0 || firstaddr > (phdr[i].p_vaddr + off))
381             firstaddr = phdr[i].p_vaddr + off;
382         if (lastaddr == 0 || lastaddr < (phdr[i].p_vaddr + off + phdr[i].p_memsz))
383             lastaddr = phdr[i].p_vaddr + off + phdr[i].p_memsz;
384     }
385     lastaddr = roundup(lastaddr, sizeof(long));
386
387     /*
388      * Get the section headers.  We need this for finding the .ctors
389      * section as well as for loading any symbols.  Both may be hard
390      * to do if reading from a .gz file as it involves seeking.  I
391      * think the rule is going to have to be that you must strip a
392      * file to remove symbols before gzipping it.
393      */
394     chunk = ehdr->e_shnum * ehdr->e_shentsize;
395     if (chunk == 0 || ehdr->e_shoff == 0)
396         goto nosyms;
397     shdr = alloc_pread(ef->fd, ehdr->e_shoff, chunk);
398     if (shdr == NULL) {
399         printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
400             "_loadimage: failed to read section headers");
401         goto nosyms;
402     }
403     file_addmetadata(fp, MODINFOMD_SHDR, chunk, shdr);
404
405     /*
406      * Read the section string table and look for the .ctors section.
407      * We need to tell the kernel where it is so that it can call the
408      * ctors.
409      */
410     chunk = shdr[ehdr->e_shstrndx].sh_size;
411     if (chunk) {
412         shstr = alloc_pread(ef->fd, shdr[ehdr->e_shstrndx].sh_offset, chunk);
413         if (shstr) {
414             for (i = 0; i < ehdr->e_shnum; i++) {
415                 if (strcmp(shstr + shdr[i].sh_name, ".ctors") != 0)
416                     continue;
417                 ctors = shdr[i].sh_addr;
418                 file_addmetadata(fp, MODINFOMD_CTORS_ADDR, sizeof(ctors),
419                     &ctors);
420                 size = shdr[i].sh_size;
421                 file_addmetadata(fp, MODINFOMD_CTORS_SIZE, sizeof(size),
422                     &size);
423                 break;
424             }
425             free(shstr);
426         }
427     }
428
429     /*
430      * Now load any symbols.
431      */
432     symtabindex = -1;
433     symstrindex = -1;
434     for (i = 0; i < ehdr->e_shnum; i++) {
435         if (shdr[i].sh_type != SHT_SYMTAB)
436             continue;
437         for (j = 0; j < ehdr->e_phnum; j++) {
438             if (phdr[j].p_type != PT_LOAD)
439                 continue;
440             if (shdr[i].sh_offset >= phdr[j].p_offset &&
441                 (shdr[i].sh_offset + shdr[i].sh_size <=
442                  phdr[j].p_offset + phdr[j].p_filesz)) {
443                 shdr[i].sh_offset = 0;
444                 shdr[i].sh_size = 0;
445                 break;
446             }
447         }
448         if (shdr[i].sh_offset == 0 || shdr[i].sh_size == 0)
449             continue;           /* alread loaded in a PT_LOAD above */
450         /* Save it for loading below */
451         symtabindex = i;
452         symstrindex = shdr[i].sh_link;
453     }
454     if (symtabindex < 0 || symstrindex < 0)
455         goto nosyms;
456
457     /* Ok, committed to a load. */
458 #ifndef ELF_VERBOSE
459     printf("syms=[");
460 #endif
461     ssym = lastaddr;
462     for (i = symtabindex; i >= 0; i = symstrindex) {
463 #ifdef ELF_VERBOSE
464         char    *secname;
465
466         switch(shdr[i].sh_type) {
467             case SHT_SYMTAB:            /* Symbol table */
468                 secname = "symtab";
469                 break;
470             case SHT_STRTAB:            /* String table */
471                 secname = "strtab";
472                 break;
473             default:
474                 secname = "WHOA!!";
475                 break;
476         }
477 #endif
478
479         size = shdr[i].sh_size;
480         archsw.arch_copyin(&size, lastaddr, sizeof(size));
481         lastaddr += sizeof(size);
482
483 #ifdef ELF_VERBOSE
484         printf("\n%s: 0x%jx@0x%jx -> 0x%jx-0x%jx", secname,
485             (uintmax_t)shdr[i].sh_size, (uintmax_t)shdr[i].sh_offset,
486             (uintmax_t)lastaddr, (uintmax_t)(lastaddr + shdr[i].sh_size));
487 #else
488         if (i == symstrindex)
489             printf("+");
490         printf("0x%lx+0x%lx", (long)sizeof(size), (long)size);
491 #endif
492
493         if (lseek(ef->fd, (off_t)shdr[i].sh_offset, SEEK_SET) == -1) {
494             printf("\nelf" __XSTRING(__ELF_WORD_SIZE) "_loadimage: could not seek for symbols - skipped!");
495             lastaddr = ssym;
496             ssym = 0;
497             goto nosyms;
498         }
499         result = archsw.arch_readin(ef->fd, lastaddr, shdr[i].sh_size);
500         if (result < 0 || (size_t)result != shdr[i].sh_size) {
501             printf("\nelf" __XSTRING(__ELF_WORD_SIZE) "_loadimage: could not read symbols - skipped! (%ju != %ju)", (uintmax_t)result,
502                 (uintmax_t)shdr[i].sh_size);
503             lastaddr = ssym;
504             ssym = 0;
505             goto nosyms;
506         }
507         /* Reset offsets relative to ssym */
508         lastaddr += shdr[i].sh_size;
509         lastaddr = roundup(lastaddr, sizeof(size));
510         if (i == symtabindex)
511             symtabindex = -1;
512         else if (i == symstrindex)
513             symstrindex = -1;
514     }
515     esym = lastaddr;
516 #ifndef ELF_VERBOSE
517     printf("]");
518 #endif
519
520     file_addmetadata(fp, MODINFOMD_SSYM, sizeof(ssym), &ssym);
521     file_addmetadata(fp, MODINFOMD_ESYM, sizeof(esym), &esym);
522
523 nosyms:
524     printf("\n");
525
526     ret = lastaddr - firstaddr;
527     fp->f_addr = firstaddr;
528
529     php = NULL;
530     for (i = 0; i < ehdr->e_phnum; i++) {
531         if (phdr[i].p_type == PT_DYNAMIC) {
532             php = phdr + i;
533             adp = php->p_vaddr;
534             file_addmetadata(fp, MODINFOMD_DYNAMIC, sizeof(adp), &adp);
535             break;
536         }
537     }
538
539     if (php == NULL)    /* this is bad, we cannot get to symbols or _DYNAMIC */
540         goto out;
541
542     ndp = php->p_filesz / sizeof(Elf_Dyn);
543     if (ndp == 0)
544         goto out;
545     dp = malloc(php->p_filesz);
546     if (dp == NULL)
547         goto out;
548     archsw.arch_copyout(php->p_vaddr + off, dp, php->p_filesz);
549
550     ef->strsz = 0;
551     for (i = 0; i < ndp; i++) {
552         if (dp[i].d_tag == 0)
553             break;
554         switch (dp[i].d_tag) {
555         case DT_HASH:
556             ef->hashtab = (Elf_Hashelt*)(uintptr_t)(dp[i].d_un.d_ptr + off);
557             break;
558         case DT_STRTAB:
559             ef->strtab = (char *)(uintptr_t)(dp[i].d_un.d_ptr + off);
560             break;
561         case DT_STRSZ:
562             ef->strsz = dp[i].d_un.d_val;
563             break;
564         case DT_SYMTAB:
565             ef->symtab = (Elf_Sym*)(uintptr_t)(dp[i].d_un.d_ptr + off);
566             break;
567         case DT_REL:
568             ef->rel = (Elf_Rel *)(uintptr_t)(dp[i].d_un.d_ptr + off);
569             break;
570         case DT_RELSZ:
571             ef->relsz = dp[i].d_un.d_val;
572             break;
573         case DT_RELA:
574             ef->rela = (Elf_Rela *)(uintptr_t)(dp[i].d_un.d_ptr + off);
575             break;
576         case DT_RELASZ:
577             ef->relasz = dp[i].d_un.d_val;
578             break;
579         default:
580             break;
581         }
582     }
583     if (ef->hashtab == NULL || ef->symtab == NULL ||
584         ef->strtab == NULL || ef->strsz == 0)
585         goto out;
586     COPYOUT(ef->hashtab, &ef->nbuckets, sizeof(ef->nbuckets));
587     COPYOUT(ef->hashtab + 1, &ef->nchains, sizeof(ef->nchains));
588     ef->buckets = ef->hashtab + 2;
589     ef->chains = ef->buckets + ef->nbuckets;
590     if (__elfN(parse_modmetadata)(fp, ef) == 0)
591         goto out;
592
593     if (ef->kernel)                     /* kernel must not depend on anything */
594         goto out;
595
596 out:
597     if (dp)
598         free(dp);
599     if (shdr)
600         free(shdr);
601     return ret;
602 }
603
604 static char invalid_name[] = "bad";
605
606 char *
607 fake_modname(const char *name)
608 {
609     const char *sp, *ep;
610     char *fp;
611     size_t len;
612
613     sp = strrchr(name, '/');
614     if (sp)
615         sp++;
616     else
617         sp = name;
618     ep = strrchr(name, '.');
619     if (ep) {
620             if (ep == name) {
621                 sp = invalid_name;
622                 ep = invalid_name + sizeof(invalid_name) - 1;
623             } 
624     } else
625         ep = name + strlen(name);
626     len = ep - sp;
627     fp = malloc(len + 1);
628     if (fp == NULL)
629         return NULL;
630     memcpy(fp, sp, len);
631     fp[len] = '\0';
632     return fp;
633 }
634
635 #if (defined(__i386__) || defined(__powerpc__)) && __ELF_WORD_SIZE == 64
636 struct mod_metadata64 {
637         int             md_version;     /* structure version MDTV_* */  
638         int             md_type;        /* type of entry MDT_* */
639         u_int64_t       md_data;        /* specific data */
640         u_int64_t       md_cval;        /* common string label */
641 };
642 #endif
643 #if defined(__amd64__) && __ELF_WORD_SIZE == 32
644 struct mod_metadata32 {
645         int             md_version;     /* structure version MDTV_* */  
646         int             md_type;        /* type of entry MDT_* */
647         u_int32_t       md_data;        /* specific data */
648         u_int32_t       md_cval;        /* common string label */
649 };
650 #endif
651
652 int
653 __elfN(parse_modmetadata)(struct preloaded_file *fp, elf_file_t ef)
654 {
655     struct mod_metadata md;
656 #if (defined(__i386__) || defined(__powerpc__)) && __ELF_WORD_SIZE == 64
657     struct mod_metadata64 md64;
658 #elif defined(__amd64__) && __ELF_WORD_SIZE == 32
659     struct mod_metadata32 md32;
660 #endif
661     struct mod_depend *mdepend;
662     struct mod_version mver;
663     Elf_Sym sym;
664     char *s;
665     int error, modcnt, minfolen;
666     Elf_Addr v, p, p_stop;
667
668     if (__elfN(lookup_symbol)(fp, ef, "__start_set_modmetadata_set", &sym) != 0)
669         return 0;
670     p = sym.st_value + ef->off;
671     if (__elfN(lookup_symbol)(fp, ef, "__stop_set_modmetadata_set", &sym) != 0)
672         return ENOENT;
673     p_stop = sym.st_value + ef->off;
674
675     modcnt = 0;
676     while (p < p_stop) {
677         COPYOUT(p, &v, sizeof(v));
678         error = __elfN(reloc_ptr)(fp, ef, p, &v, sizeof(v));
679         if (error == EOPNOTSUPP)
680             v += ef->off;
681         else if (error != 0)
682             return (error);
683 #if (defined(__i386__) || defined(__powerpc__)) && __ELF_WORD_SIZE == 64
684         COPYOUT(v, &md64, sizeof(md64));
685         error = __elfN(reloc_ptr)(fp, ef, v, &md64, sizeof(md64));
686         if (error == EOPNOTSUPP) {
687             md64.md_cval += ef->off;
688             md64.md_data += ef->off;
689         } else if (error != 0)
690             return (error);
691         md.md_version = md64.md_version;
692         md.md_type = md64.md_type;
693         md.md_cval = (const char *)(uintptr_t)md64.md_cval;
694         md.md_data = (void *)(uintptr_t)md64.md_data;
695 #elif defined(__amd64__) && __ELF_WORD_SIZE == 32
696         COPYOUT(v, &md32, sizeof(md32));
697         error = __elfN(reloc_ptr)(fp, ef, v, &md32, sizeof(md32));
698         if (error == EOPNOTSUPP) {
699             md32.md_cval += ef->off;
700             md32.md_data += ef->off;
701         } else if (error != 0)
702             return (error);
703         md.md_version = md32.md_version;
704         md.md_type = md32.md_type;
705         md.md_cval = (const char *)(uintptr_t)md32.md_cval;
706         md.md_data = (void *)(uintptr_t)md32.md_data;
707 #else
708         COPYOUT(v, &md, sizeof(md));
709         error = __elfN(reloc_ptr)(fp, ef, v, &md, sizeof(md));
710         if (error == EOPNOTSUPP) {
711             md.md_cval += ef->off;
712             md.md_data += ef->off;
713         } else if (error != 0)
714             return (error);
715 #endif
716         p += sizeof(Elf_Addr);
717         switch(md.md_type) {
718           case MDT_DEPEND:
719             if (ef->kernel)             /* kernel must not depend on anything */
720               break;
721             s = strdupout((vm_offset_t)md.md_cval);
722             minfolen = sizeof(*mdepend) + strlen(s) + 1;
723             mdepend = malloc(minfolen);
724             if (mdepend == NULL)
725                 return ENOMEM;
726             COPYOUT((vm_offset_t)md.md_data, mdepend, sizeof(*mdepend));
727             strcpy((char*)(mdepend + 1), s);
728             free(s);
729             file_addmetadata(fp, MODINFOMD_DEPLIST, minfolen, mdepend);
730             free(mdepend);
731             break;
732           case MDT_VERSION:
733             s = strdupout((vm_offset_t)md.md_cval);
734             COPYOUT((vm_offset_t)md.md_data, &mver, sizeof(mver));
735             file_addmodule(fp, s, mver.mv_version, NULL);
736             free(s);
737             modcnt++;
738             break;
739         }
740     }
741     if (modcnt == 0) {
742         s = fake_modname(fp->f_name);
743         file_addmodule(fp, s, 1, NULL);
744         free(s);
745     }
746     return 0;
747 }
748
749 static unsigned long
750 elf_hash(const char *name)
751 {
752     const unsigned char *p = (const unsigned char *) name;
753     unsigned long h = 0;
754     unsigned long g;
755
756     while (*p != '\0') {
757         h = (h << 4) + *p++;
758         if ((g = h & 0xf0000000) != 0)
759             h ^= g >> 24;
760         h &= ~g;
761     }
762     return h;
763 }
764
765 static const char __elfN(bad_symtable)[] = "elf" __XSTRING(__ELF_WORD_SIZE) "_lookup_symbol: corrupt symbol table\n";
766 int
767 __elfN(lookup_symbol)(struct preloaded_file *fp, elf_file_t ef, const char* name,
768                   Elf_Sym *symp)
769 {
770     Elf_Hashelt symnum;
771     Elf_Sym sym;
772     char *strp;
773     unsigned long hash;
774
775     hash = elf_hash(name);
776     COPYOUT(&ef->buckets[hash % ef->nbuckets], &symnum, sizeof(symnum));
777
778     while (symnum != STN_UNDEF) {
779         if (symnum >= ef->nchains) {
780             printf(__elfN(bad_symtable));
781             return ENOENT;
782         }
783
784         COPYOUT(ef->symtab + symnum, &sym, sizeof(sym));
785         if (sym.st_name == 0) {
786             printf(__elfN(bad_symtable));
787             return ENOENT;
788         }
789
790         strp = strdupout((vm_offset_t)(ef->strtab + sym.st_name));
791         if (strcmp(name, strp) == 0) {
792             free(strp);
793             if (sym.st_shndx != SHN_UNDEF ||
794                 (sym.st_value != 0 &&
795                  ELF_ST_TYPE(sym.st_info) == STT_FUNC)) {
796                 *symp = sym;
797                 return 0;
798             }
799             return ENOENT;
800         }
801         free(strp);
802         COPYOUT(&ef->chains[symnum], &symnum, sizeof(symnum));
803     }
804     return ENOENT;
805 }
806
807 /*
808  * Apply any intra-module relocations to the value. p is the load address
809  * of the value and val/len is the value to be modified. This does NOT modify
810  * the image in-place, because this is done by kern_linker later on.
811  *
812  * Returns EOPNOTSUPP if no relocation method is supplied.
813  */
814 static int
815 __elfN(reloc_ptr)(struct preloaded_file *mp, elf_file_t ef,
816     Elf_Addr p, void *val, size_t len)
817 {
818         size_t n;
819         Elf_Rela a;
820         Elf_Rel r;
821         int error;
822
823         /*
824          * The kernel is already relocated, but we still want to apply
825          * offset adjustments.
826          */
827         if (ef->kernel)
828                 return (EOPNOTSUPP);
829
830         for (n = 0; n < ef->relsz / sizeof(r); n++) {
831                 COPYOUT(ef->rel + n, &r, sizeof(r));
832
833                 error = __elfN(reloc)(ef, __elfN(symaddr), &r, ELF_RELOC_REL,
834                     ef->off, p, val, len);
835                 if (error != 0)
836                         return (error);
837         }
838         for (n = 0; n < ef->relasz / sizeof(a); n++) {
839                 COPYOUT(ef->rela + n, &a, sizeof(a));
840
841                 error = __elfN(reloc)(ef, __elfN(symaddr), &a, ELF_RELOC_RELA,
842                     ef->off, p, val, len);
843                 if (error != 0)
844                         return (error);
845         }
846
847         return (0);
848 }
849
850 static Elf_Addr
851 __elfN(symaddr)(struct elf_file *ef, Elf_Size symidx)
852 {
853
854         /* Symbol lookup by index not required here. */
855         return (0);
856 }