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