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