]> CyberLeo.Net >> Repos - FreeBSD/releng/7.2.git/blob - sys/boot/common/load_elf.c
Create releng/7.2 from stable/7 in preparation for 7.2-RELEASE.
[FreeBSD/releng/7.2.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 /*
87  * Attempt to load the file (file) as an ELF module.  It will be stored at
88  * (dest), and a pointer to a module structure describing the loaded object
89  * will be saved in (result).
90  */
91 int
92 __elfN(loadfile)(char *filename, u_int64_t dest, struct preloaded_file **result)
93 {
94     struct preloaded_file       *fp, *kfp;
95     struct elf_file             ef;
96     Elf_Ehdr                    *ehdr;
97     int                         err;
98     u_int                       pad;
99     ssize_t                     bytes_read;
100
101     fp = NULL;
102     bzero(&ef, sizeof(struct elf_file));
103     
104     /*
105      * Open the image, read and validate the ELF header 
106      */
107     if (filename == NULL)       /* can't handle nameless */
108         return(EFTYPE);
109     if ((ef.fd = open(filename, O_RDONLY)) == -1)
110         return(errno);
111     ef.firstpage = malloc(PAGE_SIZE);
112     if (ef.firstpage == NULL) {
113         close(ef.fd);
114         return(ENOMEM);
115     }
116     bytes_read = read(ef.fd, ef.firstpage, PAGE_SIZE);
117     ef.firstlen = (size_t)bytes_read;
118     if (bytes_read < 0 || ef.firstlen <= sizeof(Elf_Ehdr)) {
119         err = EFTYPE;           /* could be EIO, but may be small file */
120         goto oerr;
121     }
122     ehdr = ef.ehdr = (Elf_Ehdr *)ef.firstpage;
123
124     /* Is it ELF? */
125     if (!IS_ELF(*ehdr)) {
126         err = EFTYPE;
127         goto oerr;
128     }
129     if (ehdr->e_ident[EI_CLASS] != ELF_TARG_CLASS ||    /* Layout ? */
130         ehdr->e_ident[EI_DATA] != ELF_TARG_DATA ||
131         ehdr->e_ident[EI_VERSION] != EV_CURRENT ||      /* Version ? */
132         ehdr->e_version != EV_CURRENT ||
133         ehdr->e_machine != ELF_TARG_MACH) {             /* Machine ? */
134         err = EFTYPE;
135         goto oerr;
136     }
137
138
139     /*
140      * Check to see what sort of module we are.
141      */
142     kfp = file_findfile(NULL, NULL);
143     if (ehdr->e_type == ET_DYN) {
144         /* Looks like a kld module */
145         if (kfp == NULL) {
146             printf("elf" __XSTRING(__ELF_WORD_SIZE) "_loadfile: can't load module before kernel\n");
147             err = EPERM;
148             goto oerr;
149         }
150         if (strcmp(__elfN(kerneltype), kfp->f_type)) {
151             printf("elf" __XSTRING(__ELF_WORD_SIZE) "_loadfile: can't load module with kernel type '%s'\n", kfp->f_type);
152             err = EPERM;
153             goto oerr;
154         }
155         /* Looks OK, got ahead */
156         ef.kernel = 0;
157
158         /* Page-align the load address */
159         pad = (u_int)dest & PAGE_MASK;
160         if (pad != 0) {
161             pad = PAGE_SIZE - pad;
162             dest += pad;
163         }
164     } else if (ehdr->e_type == ET_EXEC) {
165         /* Looks like a kernel */
166         if (kfp != NULL) {
167             printf("elf" __XSTRING(__ELF_WORD_SIZE) "_loadfile: kernel already loaded\n");
168             err = EPERM;
169             goto oerr;
170         }
171         /* 
172          * Calculate destination address based on kernel entrypoint     
173          */
174         dest = ehdr->e_entry;
175         if (dest == 0) {
176             printf("elf" __XSTRING(__ELF_WORD_SIZE) "_loadfile: not a kernel (maybe static binary?)\n");
177             err = EPERM;
178             goto oerr;
179         }
180         ef.kernel = 1;
181
182     } else {
183         err = EFTYPE;
184         goto oerr;
185     }
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)dest);
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     int         ret;
244     vm_offset_t firstaddr;
245     vm_offset_t lastaddr;
246     size_t      chunk;
247     ssize_t     result;
248     Elf_Addr    ssym, esym;
249     Elf_Dyn     *dp;
250     Elf_Addr    adp;
251     int         ndp;
252     int         symstrindex;
253     int         symtabindex;
254     Elf_Size    size;
255     u_int       fpcopy;
256
257     dp = NULL;
258     shdr = NULL;
259     ret = 0;
260     firstaddr = lastaddr = 0;
261     ehdr = ef->ehdr;
262     if (ef->kernel) {
263 #ifdef __i386__
264 #if __ELF_WORD_SIZE == 64
265         off = - (off & 0xffffffffff000000ull);/* x86_64 relocates after locore */
266 #else
267         off = - (off & 0xff000000u);    /* i386 relocates after locore */
268 #endif
269 #else
270         off = 0;                /* other archs use direct mapped kernels */
271 #endif
272     }
273     ef->off = off;
274
275     if ((ehdr->e_phoff + ehdr->e_phnum * sizeof(*phdr)) > ef->firstlen) {
276         printf("elf" __XSTRING(__ELF_WORD_SIZE) "_loadimage: program header not within first page\n");
277         goto out;
278     }
279     phdr = (Elf_Phdr *)(ef->firstpage + ehdr->e_phoff);
280
281     for (i = 0; i < ehdr->e_phnum; i++) {
282         /* We want to load PT_LOAD segments only.. */
283         if (phdr[i].p_type != PT_LOAD)
284             continue;
285
286 #ifdef ELF_VERBOSE
287         printf("Segment: 0x%lx@0x%lx -> 0x%lx-0x%lx",
288             (long)phdr[i].p_filesz, (long)phdr[i].p_offset,
289             (long)(phdr[i].p_vaddr + off),
290             (long)(phdr[i].p_vaddr + off + phdr[i].p_memsz - 1));
291 #else
292         if ((phdr[i].p_flags & PF_W) == 0) {
293             printf("text=0x%lx ", (long)phdr[i].p_filesz);
294         } else {
295             printf("data=0x%lx", (long)phdr[i].p_filesz);
296             if (phdr[i].p_filesz < phdr[i].p_memsz)
297                 printf("+0x%lx", (long)(phdr[i].p_memsz -phdr[i].p_filesz));
298             printf(" ");
299         }
300 #endif
301         fpcopy = 0;
302         if (ef->firstlen > phdr[i].p_offset) {
303             fpcopy = ef->firstlen - phdr[i].p_offset;
304             archsw.arch_copyin(ef->firstpage + phdr[i].p_offset,
305                                phdr[i].p_vaddr + off, fpcopy);
306         }
307         if (phdr[i].p_filesz > fpcopy) {
308             if (kern_pread(ef->fd, phdr[i].p_vaddr + off + fpcopy,
309                 phdr[i].p_filesz - fpcopy, phdr[i].p_offset + fpcopy) != 0) {
310                 printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
311                     "_loadimage: read failed\n");
312                 goto out;
313             }
314         }
315         /* clear space from oversized segments; eg: bss */
316         if (phdr[i].p_filesz < phdr[i].p_memsz) {
317 #ifdef ELF_VERBOSE
318             printf(" (bss: 0x%lx-0x%lx)",
319                 (long)(phdr[i].p_vaddr + off + phdr[i].p_filesz),
320                 (long)(phdr[i].p_vaddr + off + phdr[i].p_memsz - 1));
321 #endif
322
323             kern_bzero(phdr[i].p_vaddr + off + phdr[i].p_filesz,
324                 phdr[i].p_memsz - phdr[i].p_filesz);
325         }
326 #ifdef ELF_VERBOSE
327         printf("\n");
328 #endif
329
330         if (firstaddr == 0 || firstaddr > (phdr[i].p_vaddr + off))
331             firstaddr = phdr[i].p_vaddr + off;
332         if (lastaddr == 0 || lastaddr < (phdr[i].p_vaddr + off + phdr[i].p_memsz))
333             lastaddr = phdr[i].p_vaddr + off + phdr[i].p_memsz;
334     }
335     lastaddr = roundup(lastaddr, sizeof(long));
336
337     /*
338      * Now grab the symbol tables.  This isn't easy if we're reading a
339      * .gz file.  I think the rule is going to have to be that you must
340      * strip a file to remove symbols before gzipping it so that we do not
341      * try to lseek() on it.
342      */
343     chunk = ehdr->e_shnum * ehdr->e_shentsize;
344     if (chunk == 0 || ehdr->e_shoff == 0)
345         goto nosyms;
346     shdr = alloc_pread(ef->fd, ehdr->e_shoff, chunk);
347     if (shdr == NULL) {
348         printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
349             "_loadimage: failed to read section headers");
350         goto nosyms;
351     }
352     symtabindex = -1;
353     symstrindex = -1;
354     for (i = 0; i < ehdr->e_shnum; i++) {
355         if (shdr[i].sh_type != SHT_SYMTAB)
356             continue;
357         for (j = 0; j < ehdr->e_phnum; j++) {
358             if (phdr[j].p_type != PT_LOAD)
359                 continue;
360             if (shdr[i].sh_offset >= phdr[j].p_offset &&
361                 (shdr[i].sh_offset + shdr[i].sh_size <=
362                  phdr[j].p_offset + phdr[j].p_filesz)) {
363                 shdr[i].sh_offset = 0;
364                 shdr[i].sh_size = 0;
365                 break;
366             }
367         }
368         if (shdr[i].sh_offset == 0 || shdr[i].sh_size == 0)
369             continue;           /* alread loaded in a PT_LOAD above */
370         /* Save it for loading below */
371         symtabindex = i;
372         symstrindex = shdr[i].sh_link;
373     }
374     if (symtabindex < 0 || symstrindex < 0)
375         goto nosyms;
376
377     /* Ok, committed to a load. */
378 #ifndef ELF_VERBOSE
379     printf("syms=[");
380 #endif
381     ssym = lastaddr;
382     for (i = symtabindex; i >= 0; i = symstrindex) {
383 #ifdef ELF_VERBOSE
384         char    *secname;
385
386         switch(shdr[i].sh_type) {
387             case SHT_SYMTAB:            /* Symbol table */
388                 secname = "symtab";
389                 break;
390             case SHT_STRTAB:            /* String table */
391                 secname = "strtab";
392                 break;
393             default:
394                 secname = "WHOA!!";
395                 break;
396         }
397 #endif
398
399         size = shdr[i].sh_size;
400         archsw.arch_copyin(&size, lastaddr, sizeof(size));
401         lastaddr += sizeof(size);
402
403 #ifdef ELF_VERBOSE
404         printf("\n%s: 0x%jx@0x%jx -> 0x%jx-0x%jx", secname,
405             (uintmax_t)shdr[i].sh_size, (uintmax_t)shdr[i].sh_offset,
406             (uintmax_t)lastaddr, (uintmax_t)(lastaddr + shdr[i].sh_size));
407 #else
408         if (i == symstrindex)
409             printf("+");
410         printf("0x%lx+0x%lx", (long)sizeof(size), (long)size);
411 #endif
412
413         if (lseek(ef->fd, (off_t)shdr[i].sh_offset, SEEK_SET) == -1) {
414             printf("\nelf" __XSTRING(__ELF_WORD_SIZE) "_loadimage: could not seek for symbols - skipped!");
415             lastaddr = ssym;
416             ssym = 0;
417             goto nosyms;
418         }
419         result = archsw.arch_readin(ef->fd, lastaddr, shdr[i].sh_size);
420         if (result < 0 || (size_t)result != shdr[i].sh_size) {
421             printf("\nelf" __XSTRING(__ELF_WORD_SIZE) "_loadimage: could not read symbols - skipped!");
422             lastaddr = ssym;
423             ssym = 0;
424             goto nosyms;
425         }
426         /* Reset offsets relative to ssym */
427         lastaddr += shdr[i].sh_size;
428         lastaddr = roundup(lastaddr, sizeof(size));
429         if (i == symtabindex)
430             symtabindex = -1;
431         else if (i == symstrindex)
432             symstrindex = -1;
433     }
434     esym = lastaddr;
435 #ifndef ELF_VERBOSE
436     printf("]");
437 #endif
438
439     file_addmetadata(fp, MODINFOMD_SSYM, sizeof(ssym), &ssym);
440     file_addmetadata(fp, MODINFOMD_ESYM, sizeof(esym), &esym);
441
442 nosyms:
443     printf("\n");
444
445     ret = lastaddr - firstaddr;
446     fp->f_addr = firstaddr;
447
448     php = NULL;
449     for (i = 0; i < ehdr->e_phnum; i++) {
450         if (phdr[i].p_type == PT_DYNAMIC) {
451             php = phdr + i;
452             adp = php->p_vaddr;
453             file_addmetadata(fp, MODINFOMD_DYNAMIC, sizeof(adp), &adp);
454             break;
455         }
456     }
457
458     if (php == NULL)    /* this is bad, we cannot get to symbols or _DYNAMIC */
459         goto out;
460
461     ndp = php->p_filesz / sizeof(Elf_Dyn);
462     if (ndp == 0)
463         goto out;
464     dp = malloc(php->p_filesz);
465     if (dp == NULL)
466         goto out;
467     archsw.arch_copyout(php->p_vaddr + off, dp, php->p_filesz);
468
469     ef->strsz = 0;
470     for (i = 0; i < ndp; i++) {
471         if (dp[i].d_tag == 0)
472             break;
473         switch (dp[i].d_tag) {
474         case DT_HASH:
475             ef->hashtab = (Elf_Hashelt*)(uintptr_t)(dp[i].d_un.d_ptr + off);
476             break;
477         case DT_STRTAB:
478             ef->strtab = (char *)(uintptr_t)(dp[i].d_un.d_ptr + off);
479             break;
480         case DT_STRSZ:
481             ef->strsz = dp[i].d_un.d_val;
482             break;
483         case DT_SYMTAB:
484             ef->symtab = (Elf_Sym*)(uintptr_t)(dp[i].d_un.d_ptr + off);
485             break;
486         case DT_REL:
487             ef->rel = (Elf_Rel *)(uintptr_t)(dp[i].d_un.d_ptr + off);
488             break;
489         case DT_RELSZ:
490             ef->relsz = dp[i].d_un.d_val;
491             break;
492         case DT_RELA:
493             ef->rela = (Elf_Rela *)(uintptr_t)(dp[i].d_un.d_ptr + off);
494             break;
495         case DT_RELASZ:
496             ef->relasz = dp[i].d_un.d_val;
497             break;
498         default:
499             break;
500         }
501     }
502     if (ef->hashtab == NULL || ef->symtab == NULL ||
503         ef->strtab == NULL || ef->strsz == 0)
504         goto out;
505     COPYOUT(ef->hashtab, &ef->nbuckets, sizeof(ef->nbuckets));
506     COPYOUT(ef->hashtab + 1, &ef->nchains, sizeof(ef->nchains));
507     ef->buckets = ef->hashtab + 2;
508     ef->chains = ef->buckets + ef->nbuckets;
509     if (__elfN(parse_modmetadata)(fp, ef) == 0)
510         goto out;
511
512     if (ef->kernel)                     /* kernel must not depend on anything */
513         goto out;
514
515 out:
516     if (dp)
517         free(dp);
518     if (shdr)
519         free(shdr);
520     return ret;
521 }
522
523 static char invalid_name[] = "bad";
524
525 char *
526 fake_modname(const char *name)
527 {
528     const char *sp, *ep;
529     char *fp;
530     size_t len;
531
532     sp = strrchr(name, '/');
533     if (sp)
534         sp++;
535     else
536         sp = name;
537     ep = strrchr(name, '.');
538     if (ep) {
539             if (ep == name) {
540                 sp = invalid_name;
541                 ep = invalid_name + sizeof(invalid_name) - 1;
542             } 
543     } else
544         ep = name + strlen(name);
545     len = ep - sp;
546     fp = malloc(len + 1);
547     if (fp == NULL)
548         return NULL;
549     memcpy(fp, sp, len);
550     fp[len] = '\0';
551     return fp;
552 }
553
554 #if defined(__i386__) && __ELF_WORD_SIZE == 64
555 struct mod_metadata64 {
556         int             md_version;     /* structure version MDTV_* */  
557         int             md_type;        /* type of entry MDT_* */
558         u_int64_t       md_data;        /* specific data */
559         u_int64_t       md_cval;        /* common string label */
560 };
561 #endif
562
563 int
564 __elfN(parse_modmetadata)(struct preloaded_file *fp, elf_file_t ef)
565 {
566     struct mod_metadata md;
567 #if defined(__i386__) && __ELF_WORD_SIZE == 64
568     struct mod_metadata64 md64;
569 #endif
570     struct mod_depend *mdepend;
571     struct mod_version mver;
572     Elf_Sym sym;
573     char *s;
574     int error, modcnt, minfolen;
575     Elf_Addr v, p, p_stop;
576
577     if (__elfN(lookup_symbol)(fp, ef, "__start_set_modmetadata_set", &sym) != 0)
578         return ENOENT;
579     p = sym.st_value + ef->off;
580     if (__elfN(lookup_symbol)(fp, ef, "__stop_set_modmetadata_set", &sym) != 0)
581         return ENOENT;
582     p_stop = sym.st_value + ef->off;
583
584     modcnt = 0;
585     while (p < p_stop) {
586         COPYOUT(p, &v, sizeof(v));
587         error = __elfN(reloc_ptr)(fp, ef, p, &v, sizeof(v));
588         if (error == EOPNOTSUPP)
589             v += ef->off;
590         else if (error != 0)
591             return (error);
592 #if defined(__i386__) && __ELF_WORD_SIZE == 64
593         COPYOUT(v, &md64, sizeof(md64));
594         error = __elfN(reloc_ptr)(fp, ef, v, &md64, sizeof(md64));
595         if (error == EOPNOTSUPP) {
596             md64.md_cval += ef->off;
597             md64.md_data += ef->off;
598         } else if (error != 0)
599             return (error);
600         md.md_version = md64.md_version;
601         md.md_type = md64.md_type;
602         md.md_cval = (const char *)(uintptr_t)md64.md_cval;
603         md.md_data = (void *)(uintptr_t)md64.md_data;
604 #else
605         COPYOUT(v, &md, sizeof(md));
606         error = __elfN(reloc_ptr)(fp, ef, v, &md, sizeof(md));
607         if (error == EOPNOTSUPP) {
608             md.md_cval += ef->off;
609             md.md_data += ef->off;
610         } else if (error != 0)
611             return (error);
612 #endif
613         p += sizeof(Elf_Addr);
614         switch(md.md_type) {
615           case MDT_DEPEND:
616             if (ef->kernel)             /* kernel must not depend on anything */
617               break;
618             s = strdupout((vm_offset_t)md.md_cval);
619             minfolen = sizeof(*mdepend) + strlen(s) + 1;
620             mdepend = malloc(minfolen);
621             if (mdepend == NULL)
622                 return ENOMEM;
623             COPYOUT((vm_offset_t)md.md_data, mdepend, sizeof(*mdepend));
624             strcpy((char*)(mdepend + 1), s);
625             free(s);
626             file_addmetadata(fp, MODINFOMD_DEPLIST, minfolen, mdepend);
627             free(mdepend);
628             break;
629           case MDT_VERSION:
630             s = strdupout((vm_offset_t)md.md_cval);
631             COPYOUT((vm_offset_t)md.md_data, &mver, sizeof(mver));
632             file_addmodule(fp, s, mver.mv_version, NULL);
633             free(s);
634             modcnt++;
635             break;
636         }
637     }
638     if (modcnt == 0) {
639         s = fake_modname(fp->f_name);
640         file_addmodule(fp, s, 1, NULL);
641         free(s);
642     }
643     return 0;
644 }
645
646 static unsigned long
647 elf_hash(const char *name)
648 {
649     const unsigned char *p = (const unsigned char *) name;
650     unsigned long h = 0;
651     unsigned long g;
652
653     while (*p != '\0') {
654         h = (h << 4) + *p++;
655         if ((g = h & 0xf0000000) != 0)
656             h ^= g >> 24;
657         h &= ~g;
658     }
659     return h;
660 }
661
662 static const char __elfN(bad_symtable)[] = "elf" __XSTRING(__ELF_WORD_SIZE) "_lookup_symbol: corrupt symbol table\n";
663 int
664 __elfN(lookup_symbol)(struct preloaded_file *fp, elf_file_t ef, const char* name,
665                   Elf_Sym *symp)
666 {
667     Elf_Hashelt symnum;
668     Elf_Sym sym;
669     char *strp;
670     unsigned long hash;
671
672     hash = elf_hash(name);
673     COPYOUT(&ef->buckets[hash % ef->nbuckets], &symnum, sizeof(symnum));
674
675     while (symnum != STN_UNDEF) {
676         if (symnum >= ef->nchains) {
677             printf(__elfN(bad_symtable));
678             return ENOENT;
679         }
680
681         COPYOUT(ef->symtab + symnum, &sym, sizeof(sym));
682         if (sym.st_name == 0) {
683             printf(__elfN(bad_symtable));
684             return ENOENT;
685         }
686
687         strp = strdupout((vm_offset_t)(ef->strtab + sym.st_name));
688         if (strcmp(name, strp) == 0) {
689             free(strp);
690             if (sym.st_shndx != SHN_UNDEF ||
691                 (sym.st_value != 0 &&
692                  ELF_ST_TYPE(sym.st_info) == STT_FUNC)) {
693                 *symp = sym;
694                 return 0;
695             }
696             return ENOENT;
697         }
698         free(strp);
699         COPYOUT(&ef->chains[symnum], &symnum, sizeof(symnum));
700     }
701     return ENOENT;
702 }
703
704 /*
705  * Apply any intra-module relocations to the value. p is the load address
706  * of the value and val/len is the value to be modified. This does NOT modify
707  * the image in-place, because this is done by kern_linker later on.
708  *
709  * Returns EOPNOTSUPP if no relocation method is supplied.
710  */
711 static int
712 __elfN(reloc_ptr)(struct preloaded_file *mp, elf_file_t ef,
713     Elf_Addr p, void *val, size_t len)
714 {
715         size_t n;
716         Elf_Rela a;
717         Elf_Rel r;
718         int error;
719
720         /*
721          * The kernel is already relocated, but we still want to apply
722          * offset adjustments.
723          */
724         if (ef->kernel)
725                 return (EOPNOTSUPP);
726
727         for (n = 0; n < ef->relsz / sizeof(r); n++) {
728                 COPYOUT(ef->rel + n, &r, sizeof(r));
729
730                 error = __elfN(reloc)(ef, __elfN(symaddr), &r, ELF_RELOC_REL,
731                     ef->off, p, val, len);
732                 if (error != 0)
733                         return (error);
734         }
735         for (n = 0; n < ef->relasz / sizeof(a); n++) {
736                 COPYOUT(ef->rela + n, &a, sizeof(a));
737
738                 error = __elfN(reloc)(ef, __elfN(symaddr), &a, ELF_RELOC_RELA,
739                     ef->off, p, val, len);
740                 if (error != 0)
741                         return (error);
742         }
743
744         return (0);
745 }
746
747 static Elf_Addr
748 __elfN(symaddr)(struct elf_file *ef, Elf_Size symidx)
749 {
750
751         /* Symbol lookup by index not required here. */
752         return (0);
753 }