2 * Copyright (c) 1998 Michael Smith <msmith@freebsd.org>
3 * Copyright (c) 1998 Peter Wemm <peter@freebsd.org>
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
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.
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
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
31 #include <sys/param.h>
33 #include <sys/linker.h>
34 #include <sys/module.h>
35 #include <sys/stdint.h>
37 #include <machine/elf.h>
42 #include "bootstrap.h"
44 #define COPYOUT(s,d,l) archsw.arch_copyout((vm_offset_t)(s), d, l)
46 #if defined(__i386__) && __ELF_WORD_SIZE == 64
49 #define ELF_TARG_CLASS ELFCLASS64
50 #define ELF_TARG_MACH EM_X86_64
53 typedef struct elf_file {
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);
83 const char *__elfN(kerneltype) = "elf kernel";
84 const char *__elfN(moduletype) = "elf module";
86 u_int64_t __elfN(relocation_offset) = 0;
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).
94 __elfN(loadfile)(char *filename, u_int64_t dest, struct preloaded_file **result)
96 struct preloaded_file *fp, *kfp;
103 bzero(&ef, sizeof(struct elf_file));
106 * Open the image, read and validate the ELF header
108 if (filename == NULL) /* can't handle nameless */
110 if ((ef.fd = open(filename, O_RDONLY)) == -1)
112 ef.firstpage = malloc(PAGE_SIZE);
113 if (ef.firstpage == NULL) {
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 */
123 ehdr = ef.ehdr = (Elf_Ehdr *)ef.firstpage;
126 if (!IS_ELF(*ehdr)) {
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 ? */
141 * Check to see what sort of module we are.
143 kfp = file_findfile(NULL, NULL);
144 if (ehdr->e_type == ET_DYN) {
145 /* Looks like a kld module */
147 printf("elf" __XSTRING(__ELF_WORD_SIZE) "_loadfile: can't load module before kernel\n");
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);
156 /* Looks OK, got ahead */
159 } else if (ehdr->e_type == ET_EXEC) {
160 /* Looks like a kernel */
162 printf("elf" __XSTRING(__ELF_WORD_SIZE) "_loadfile: kernel already loaded\n");
167 * Calculate destination address based on kernel entrypoint
169 dest = (ehdr->e_entry & ~PAGE_MASK);
171 printf("elf" __XSTRING(__ELF_WORD_SIZE) "_loadfile: not a kernel (maybe static binary?)\n");
182 if (archsw.arch_loadaddr != NULL)
183 dest = archsw.arch_loadaddr(LOAD_ELF, ehdr, dest);
185 dest = roundup(dest, PAGE_SIZE);
188 * Ok, we think we should handle this.
192 printf("elf" __XSTRING(__ELF_WORD_SIZE) "_loadfile: cannot allocate module info\n");
197 setenv("kernelname", filename, 1);
198 fp->f_name = strdup(filename);
199 fp->f_type = strdup(ef.kernel ? __elfN(kerneltype) : __elfN(moduletype));
203 printf("%s entry at 0x%jx\n", filename, (uintmax_t)ehdr->e_entry);
205 printf("%s ", filename);
208 fp->f_size = __elfN(loadimage)(fp, &ef, dest);
209 if (fp->f_size == 0 || fp->f_addr == 0)
212 /* save exec header as metadata */
213 file_addmetadata(fp, MODINFOMD_ELFHDR, sizeof(*ehdr), ehdr);
215 /* Load OK, return module pointer */
216 *result = (struct preloaded_file *)fp;
232 * With the file (fd) open on the image, and (ehdr) containing
233 * the Elf header, load the image at (off)
236 __elfN(loadimage)(struct preloaded_file *fp, elf_file_t ef, u_int64_t off)
241 Elf_Phdr *phdr, *php;
244 vm_offset_t firstaddr;
245 vm_offset_t lastaddr;
260 firstaddr = lastaddr = 0;
263 #if defined(__i386__) || defined(__amd64__)
264 #if __ELF_WORD_SIZE == 64
265 off = - (off & 0xffffffffff000000ull);/* x86_64 relocates after locore */
267 off = - (off & 0xff000000u); /* i386 relocates after locore */
269 #elif defined(__powerpc__)
271 * On the purely virtual memory machines like e500, the kernel is
272 * linked against its final VA range, which is most often not
273 * available at the loader stage, but only after kernel initializes
274 * and completes its VM settings. In such cases we cannot use p_vaddr
275 * field directly to load ELF segments, but put them at some
276 * 'load-time' locations.
278 if (off & 0xf0000000u) {
279 off = -(off & 0xf0000000u);
281 * XXX the physical load address should not be hardcoded. Note
282 * that the Book-E kernel assumes that it's loaded at a 16MB
283 * boundary for now...
286 ehdr->e_entry += off;
288 printf("Converted entry 0x%08x\n", ehdr->e_entry);
292 #elif defined(__arm__)
293 if (off & 0xf0000000u) {
294 off = -(off & 0xf0000000u);
295 ehdr->e_entry += off;
297 printf("Converted entry 0x%08x\n", ehdr->e_entry);
302 off = 0; /* other archs use direct mapped kernels */
304 __elfN(relocation_offset) = off;
308 if ((ehdr->e_phoff + ehdr->e_phnum * sizeof(*phdr)) > ef->firstlen) {
309 printf("elf" __XSTRING(__ELF_WORD_SIZE) "_loadimage: program header not within first page\n");
312 phdr = (Elf_Phdr *)(ef->firstpage + ehdr->e_phoff);
314 for (i = 0; i < ehdr->e_phnum; i++) {
315 /* We want to load PT_LOAD segments only.. */
316 if (phdr[i].p_type != PT_LOAD)
320 printf("Segment: 0x%lx@0x%lx -> 0x%lx-0x%lx",
321 (long)phdr[i].p_filesz, (long)phdr[i].p_offset,
322 (long)(phdr[i].p_vaddr + off),
323 (long)(phdr[i].p_vaddr + off + phdr[i].p_memsz - 1));
325 if ((phdr[i].p_flags & PF_W) == 0) {
326 printf("text=0x%lx ", (long)phdr[i].p_filesz);
328 printf("data=0x%lx", (long)phdr[i].p_filesz);
329 if (phdr[i].p_filesz < phdr[i].p_memsz)
330 printf("+0x%lx", (long)(phdr[i].p_memsz -phdr[i].p_filesz));
335 if (ef->firstlen > phdr[i].p_offset) {
336 fpcopy = ef->firstlen - phdr[i].p_offset;
337 archsw.arch_copyin(ef->firstpage + phdr[i].p_offset,
338 phdr[i].p_vaddr + off, fpcopy);
340 if (phdr[i].p_filesz > fpcopy) {
341 if (kern_pread(ef->fd, phdr[i].p_vaddr + off + fpcopy,
342 phdr[i].p_filesz - fpcopy, phdr[i].p_offset + fpcopy) != 0) {
343 printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
344 "_loadimage: read failed\n");
348 /* clear space from oversized segments; eg: bss */
349 if (phdr[i].p_filesz < phdr[i].p_memsz) {
351 printf(" (bss: 0x%lx-0x%lx)",
352 (long)(phdr[i].p_vaddr + off + phdr[i].p_filesz),
353 (long)(phdr[i].p_vaddr + off + phdr[i].p_memsz - 1));
356 kern_bzero(phdr[i].p_vaddr + off + phdr[i].p_filesz,
357 phdr[i].p_memsz - phdr[i].p_filesz);
363 if (archsw.arch_loadseg != NULL)
364 archsw.arch_loadseg(ehdr, phdr + i, off);
366 if (firstaddr == 0 || firstaddr > (phdr[i].p_vaddr + off))
367 firstaddr = phdr[i].p_vaddr + off;
368 if (lastaddr == 0 || lastaddr < (phdr[i].p_vaddr + off + phdr[i].p_memsz))
369 lastaddr = phdr[i].p_vaddr + off + phdr[i].p_memsz;
371 lastaddr = roundup(lastaddr, sizeof(long));
374 * Now grab the symbol tables. This isn't easy if we're reading a
375 * .gz file. I think the rule is going to have to be that you must
376 * strip a file to remove symbols before gzipping it so that we do not
377 * try to lseek() on it.
379 chunk = ehdr->e_shnum * ehdr->e_shentsize;
380 if (chunk == 0 || ehdr->e_shoff == 0)
382 shdr = alloc_pread(ef->fd, ehdr->e_shoff, chunk);
384 printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
385 "_loadimage: failed to read section headers");
390 for (i = 0; i < ehdr->e_shnum; i++) {
391 if (shdr[i].sh_type != SHT_SYMTAB)
393 for (j = 0; j < ehdr->e_phnum; j++) {
394 if (phdr[j].p_type != PT_LOAD)
396 if (shdr[i].sh_offset >= phdr[j].p_offset &&
397 (shdr[i].sh_offset + shdr[i].sh_size <=
398 phdr[j].p_offset + phdr[j].p_filesz)) {
399 shdr[i].sh_offset = 0;
404 if (shdr[i].sh_offset == 0 || shdr[i].sh_size == 0)
405 continue; /* alread loaded in a PT_LOAD above */
406 /* Save it for loading below */
408 symstrindex = shdr[i].sh_link;
410 if (symtabindex < 0 || symstrindex < 0)
413 /* Ok, committed to a load. */
418 for (i = symtabindex; i >= 0; i = symstrindex) {
422 switch(shdr[i].sh_type) {
423 case SHT_SYMTAB: /* Symbol table */
426 case SHT_STRTAB: /* String table */
435 size = shdr[i].sh_size;
436 archsw.arch_copyin(&size, lastaddr, sizeof(size));
437 lastaddr += sizeof(size);
440 printf("\n%s: 0x%jx@0x%jx -> 0x%jx-0x%jx", secname,
441 (uintmax_t)shdr[i].sh_size, (uintmax_t)shdr[i].sh_offset,
442 (uintmax_t)lastaddr, (uintmax_t)(lastaddr + shdr[i].sh_size));
444 if (i == symstrindex)
446 printf("0x%lx+0x%lx", (long)sizeof(size), (long)size);
449 if (lseek(ef->fd, (off_t)shdr[i].sh_offset, SEEK_SET) == -1) {
450 printf("\nelf" __XSTRING(__ELF_WORD_SIZE) "_loadimage: could not seek for symbols - skipped!");
455 result = archsw.arch_readin(ef->fd, lastaddr, shdr[i].sh_size);
456 if (result < 0 || (size_t)result != shdr[i].sh_size) {
457 printf("\nelf" __XSTRING(__ELF_WORD_SIZE) "_loadimage: could not read symbols - skipped! (%ju != %ju)", (uintmax_t)result,
458 (uintmax_t)shdr[i].sh_size);
463 /* Reset offsets relative to ssym */
464 lastaddr += shdr[i].sh_size;
465 lastaddr = roundup(lastaddr, sizeof(size));
466 if (i == symtabindex)
468 else if (i == symstrindex)
476 file_addmetadata(fp, MODINFOMD_SSYM, sizeof(ssym), &ssym);
477 file_addmetadata(fp, MODINFOMD_ESYM, sizeof(esym), &esym);
482 ret = lastaddr - firstaddr;
483 fp->f_addr = firstaddr;
486 for (i = 0; i < ehdr->e_phnum; i++) {
487 if (phdr[i].p_type == PT_DYNAMIC) {
490 file_addmetadata(fp, MODINFOMD_DYNAMIC, sizeof(adp), &adp);
495 if (php == NULL) /* this is bad, we cannot get to symbols or _DYNAMIC */
498 ndp = php->p_filesz / sizeof(Elf_Dyn);
501 dp = malloc(php->p_filesz);
504 archsw.arch_copyout(php->p_vaddr + off, dp, php->p_filesz);
507 for (i = 0; i < ndp; i++) {
508 if (dp[i].d_tag == 0)
510 switch (dp[i].d_tag) {
512 ef->hashtab = (Elf_Hashelt*)(uintptr_t)(dp[i].d_un.d_ptr + off);
515 ef->strtab = (char *)(uintptr_t)(dp[i].d_un.d_ptr + off);
518 ef->strsz = dp[i].d_un.d_val;
521 ef->symtab = (Elf_Sym*)(uintptr_t)(dp[i].d_un.d_ptr + off);
524 ef->rel = (Elf_Rel *)(uintptr_t)(dp[i].d_un.d_ptr + off);
527 ef->relsz = dp[i].d_un.d_val;
530 ef->rela = (Elf_Rela *)(uintptr_t)(dp[i].d_un.d_ptr + off);
533 ef->relasz = dp[i].d_un.d_val;
539 if (ef->hashtab == NULL || ef->symtab == NULL ||
540 ef->strtab == NULL || ef->strsz == 0)
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)
549 if (ef->kernel) /* kernel must not depend on anything */
560 static char invalid_name[] = "bad";
563 fake_modname(const char *name)
569 sp = strrchr(name, '/');
574 ep = strrchr(name, '.');
578 ep = invalid_name + sizeof(invalid_name) - 1;
581 ep = name + strlen(name);
583 fp = malloc(len + 1);
591 #if (defined(__i386__) || defined(__powerpc__)) && __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 */
601 __elfN(parse_modmetadata)(struct preloaded_file *fp, elf_file_t ef)
603 struct mod_metadata md;
604 #if (defined(__i386__) || defined(__powerpc__)) && __ELF_WORD_SIZE == 64
605 struct mod_metadata64 md64;
607 struct mod_depend *mdepend;
608 struct mod_version mver;
611 int error, modcnt, minfolen;
612 Elf_Addr v, p, p_stop;
614 if (__elfN(lookup_symbol)(fp, ef, "__start_set_modmetadata_set", &sym) != 0)
616 p = sym.st_value + ef->off;
617 if (__elfN(lookup_symbol)(fp, ef, "__stop_set_modmetadata_set", &sym) != 0)
619 p_stop = sym.st_value + ef->off;
623 COPYOUT(p, &v, sizeof(v));
624 error = __elfN(reloc_ptr)(fp, ef, p, &v, sizeof(v));
625 if (error == EOPNOTSUPP)
629 #if (defined(__i386__) || defined(__powerpc__)) && __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)
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;
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)
650 p += sizeof(Elf_Addr);
653 if (ef->kernel) /* kernel must not depend on anything */
655 s = strdupout((vm_offset_t)md.md_cval);
656 minfolen = sizeof(*mdepend) + strlen(s) + 1;
657 mdepend = malloc(minfolen);
660 COPYOUT((vm_offset_t)md.md_data, mdepend, sizeof(*mdepend));
661 strcpy((char*)(mdepend + 1), s);
663 file_addmetadata(fp, MODINFOMD_DEPLIST, minfolen, mdepend);
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);
676 s = fake_modname(fp->f_name);
677 file_addmodule(fp, s, 1, NULL);
684 elf_hash(const char *name)
686 const unsigned char *p = (const unsigned char *) name;
692 if ((g = h & 0xf0000000) != 0)
699 static const char __elfN(bad_symtable)[] = "elf" __XSTRING(__ELF_WORD_SIZE) "_lookup_symbol: corrupt symbol table\n";
701 __elfN(lookup_symbol)(struct preloaded_file *fp, elf_file_t ef, const char* name,
709 hash = elf_hash(name);
710 COPYOUT(&ef->buckets[hash % ef->nbuckets], &symnum, sizeof(symnum));
712 while (symnum != STN_UNDEF) {
713 if (symnum >= ef->nchains) {
714 printf(__elfN(bad_symtable));
718 COPYOUT(ef->symtab + symnum, &sym, sizeof(sym));
719 if (sym.st_name == 0) {
720 printf(__elfN(bad_symtable));
724 strp = strdupout((vm_offset_t)(ef->strtab + sym.st_name));
725 if (strcmp(name, strp) == 0) {
727 if (sym.st_shndx != SHN_UNDEF ||
728 (sym.st_value != 0 &&
729 ELF_ST_TYPE(sym.st_info) == STT_FUNC)) {
736 COPYOUT(&ef->chains[symnum], &symnum, sizeof(symnum));
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.
746 * Returns EOPNOTSUPP if no relocation method is supplied.
749 __elfN(reloc_ptr)(struct preloaded_file *mp, elf_file_t ef,
750 Elf_Addr p, void *val, size_t len)
758 * The kernel is already relocated, but we still want to apply
759 * offset adjustments.
764 for (n = 0; n < ef->relsz / sizeof(r); n++) {
765 COPYOUT(ef->rel + n, &r, sizeof(r));
767 error = __elfN(reloc)(ef, __elfN(symaddr), &r, ELF_RELOC_REL,
768 ef->off, p, val, len);
772 for (n = 0; n < ef->relasz / sizeof(a); n++) {
773 COPYOUT(ef->rela + n, &a, sizeof(a));
775 error = __elfN(reloc)(ef, __elfN(symaddr), &a, ELF_RELOC_RELA,
776 ef->off, p, val, len);
785 __elfN(symaddr)(struct elf_file *ef, Elf_Size symidx)
788 /* Symbol lookup by index not required here. */