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);
146 * Kernels can be ET_DYN, so just assume the first loaded object is the
147 * kernel. This assumption will be checked later.
152 if (ef.kernel || ehdr->e_type == ET_EXEC) {
153 /* Looks like a kernel */
155 printf("elf" __XSTRING(__ELF_WORD_SIZE) "_loadfile: kernel already loaded\n");
160 * Calculate destination address based on kernel entrypoint.
162 * For ARM, the destination address is independent of any values in the
163 * elf header (an ARM kernel can be loaded at any 2MB boundary), so we
164 * leave dest set to the value calculated by archsw.arch_loadaddr() and
165 * passed in to this function.
168 if (ehdr->e_type == ET_EXEC)
169 dest = (ehdr->e_entry & ~PAGE_MASK);
171 if ((ehdr->e_entry & ~PAGE_MASK) == 0) {
172 printf("elf" __XSTRING(__ELF_WORD_SIZE) "_loadfile: not a kernel (maybe static binary?)\n");
178 } else if (ehdr->e_type == ET_DYN) {
179 /* Looks like a kld module */
181 printf("elf" __XSTRING(__ELF_WORD_SIZE) "_loadfile: can't load module before kernel\n");
185 if (strcmp(__elfN(kerneltype), kfp->f_type)) {
186 printf("elf" __XSTRING(__ELF_WORD_SIZE) "_loadfile: can't load module with kernel type '%s'\n", kfp->f_type);
190 /* Looks OK, got ahead */
198 if (archsw.arch_loadaddr != NULL)
199 dest = archsw.arch_loadaddr(LOAD_ELF, ehdr, dest);
201 dest = roundup(dest, PAGE_SIZE);
204 * Ok, we think we should handle this.
208 printf("elf" __XSTRING(__ELF_WORD_SIZE) "_loadfile: cannot allocate module info\n");
213 setenv("kernelname", filename, 1);
214 fp->f_name = strdup(filename);
215 fp->f_type = strdup(ef.kernel ? __elfN(kerneltype) : __elfN(moduletype));
219 printf("%s entry at 0x%jx\n", filename, (uintmax_t)ehdr->e_entry);
221 printf("%s ", filename);
224 fp->f_size = __elfN(loadimage)(fp, &ef, dest);
225 if (fp->f_size == 0 || fp->f_addr == 0)
228 /* save exec header as metadata */
229 file_addmetadata(fp, MODINFOMD_ELFHDR, sizeof(*ehdr), ehdr);
231 /* Load OK, return module pointer */
232 *result = (struct preloaded_file *)fp;
248 * With the file (fd) open on the image, and (ehdr) containing
249 * the Elf header, load the image at (off)
252 __elfN(loadimage)(struct preloaded_file *fp, elf_file_t ef, u_int64_t off)
257 Elf_Phdr *phdr, *php;
260 vm_offset_t firstaddr;
261 vm_offset_t lastaddr;
276 firstaddr = lastaddr = 0;
278 if (ehdr->e_type == ET_EXEC) {
279 #if defined(__i386__) || defined(__amd64__)
280 #if __ELF_WORD_SIZE == 64
281 off = - (off & 0xffffffffff000000ull);/* x86_64 relocates after locore */
283 off = - (off & 0xff000000u); /* i386 relocates after locore */
285 #elif defined(__powerpc__)
287 * On the purely virtual memory machines like e500, the kernel is
288 * linked against its final VA range, which is most often not
289 * available at the loader stage, but only after kernel initializes
290 * and completes its VM settings. In such cases we cannot use p_vaddr
291 * field directly to load ELF segments, but put them at some
292 * 'load-time' locations.
294 if (off & 0xf0000000u) {
295 off = -(off & 0xf0000000u);
297 * XXX the physical load address should not be hardcoded. Note
298 * that the Book-E kernel assumes that it's loaded at a 16MB
299 * boundary for now...
302 ehdr->e_entry += off;
304 printf("Converted entry 0x%08x\n", ehdr->e_entry);
308 #elif defined(__arm__)
310 * The elf headers in arm kernels specify virtual addresses in all
311 * header fields, even the ones that should be physical addresses.
312 * We assume the entry point is in the first page, and masking the page
313 * offset will leave us with the virtual address the kernel was linked
314 * at. We subtract that from the load offset, making 'off' into the
315 * value which, when added to a virtual address in an elf header,
316 * translates it to a physical address. We do the va->pa conversion on
317 * the entry point address in the header now, so that later we can
318 * launch the kernel by just jumping to that address.
320 off -= ehdr->e_entry & ~PAGE_MASK;
321 ehdr->e_entry += off;
323 printf("ehdr->e_entry 0x%08x, va<->pa off %llx\n", ehdr->e_entry, off);
326 off = 0; /* other archs use direct mapped kernels */
332 __elfN(relocation_offset) = off;
334 if ((ehdr->e_phoff + ehdr->e_phnum * sizeof(*phdr)) > ef->firstlen) {
335 printf("elf" __XSTRING(__ELF_WORD_SIZE) "_loadimage: program header not within first page\n");
338 phdr = (Elf_Phdr *)(ef->firstpage + ehdr->e_phoff);
340 for (i = 0; i < ehdr->e_phnum; i++) {
341 /* We want to load PT_LOAD segments only.. */
342 if (phdr[i].p_type != PT_LOAD)
346 printf("Segment: 0x%lx@0x%lx -> 0x%lx-0x%lx",
347 (long)phdr[i].p_filesz, (long)phdr[i].p_offset,
348 (long)(phdr[i].p_vaddr + off),
349 (long)(phdr[i].p_vaddr + off + phdr[i].p_memsz - 1));
351 if ((phdr[i].p_flags & PF_W) == 0) {
352 printf("text=0x%lx ", (long)phdr[i].p_filesz);
354 printf("data=0x%lx", (long)phdr[i].p_filesz);
355 if (phdr[i].p_filesz < phdr[i].p_memsz)
356 printf("+0x%lx", (long)(phdr[i].p_memsz -phdr[i].p_filesz));
361 if (ef->firstlen > phdr[i].p_offset) {
362 fpcopy = ef->firstlen - phdr[i].p_offset;
363 archsw.arch_copyin(ef->firstpage + phdr[i].p_offset,
364 phdr[i].p_vaddr + off, fpcopy);
366 if (phdr[i].p_filesz > fpcopy) {
367 if (kern_pread(ef->fd, phdr[i].p_vaddr + off + fpcopy,
368 phdr[i].p_filesz - fpcopy, phdr[i].p_offset + fpcopy) != 0) {
369 printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
370 "_loadimage: read failed\n");
374 /* clear space from oversized segments; eg: bss */
375 if (phdr[i].p_filesz < phdr[i].p_memsz) {
377 printf(" (bss: 0x%lx-0x%lx)",
378 (long)(phdr[i].p_vaddr + off + phdr[i].p_filesz),
379 (long)(phdr[i].p_vaddr + off + phdr[i].p_memsz - 1));
382 kern_bzero(phdr[i].p_vaddr + off + phdr[i].p_filesz,
383 phdr[i].p_memsz - phdr[i].p_filesz);
389 if (archsw.arch_loadseg != NULL)
390 archsw.arch_loadseg(ehdr, phdr + i, off);
392 if (firstaddr == 0 || firstaddr > (phdr[i].p_vaddr + off))
393 firstaddr = phdr[i].p_vaddr + off;
394 if (lastaddr == 0 || lastaddr < (phdr[i].p_vaddr + off + phdr[i].p_memsz))
395 lastaddr = phdr[i].p_vaddr + off + phdr[i].p_memsz;
397 lastaddr = roundup(lastaddr, sizeof(long));
400 * Now grab the symbol tables. This isn't easy if we're reading a
401 * .gz file. I think the rule is going to have to be that you must
402 * strip a file to remove symbols before gzipping it so that we do not
403 * try to lseek() on it.
405 chunk = ehdr->e_shnum * ehdr->e_shentsize;
406 if (chunk == 0 || ehdr->e_shoff == 0)
408 shdr = alloc_pread(ef->fd, ehdr->e_shoff, chunk);
410 printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
411 "_loadimage: failed to read section headers");
414 file_addmetadata(fp, MODINFOMD_SHDR, chunk, shdr);
418 for (i = 0; i < ehdr->e_shnum; i++) {
419 if (shdr[i].sh_type != SHT_SYMTAB)
421 for (j = 0; j < ehdr->e_phnum; j++) {
422 if (phdr[j].p_type != PT_LOAD)
424 if (shdr[i].sh_offset >= phdr[j].p_offset &&
425 (shdr[i].sh_offset + shdr[i].sh_size <=
426 phdr[j].p_offset + phdr[j].p_filesz)) {
427 shdr[i].sh_offset = 0;
432 if (shdr[i].sh_offset == 0 || shdr[i].sh_size == 0)
433 continue; /* alread loaded in a PT_LOAD above */
434 /* Save it for loading below */
436 symstrindex = shdr[i].sh_link;
438 if (symtabindex < 0 || symstrindex < 0)
441 /* Ok, committed to a load. */
446 for (i = symtabindex; i >= 0; i = symstrindex) {
450 switch(shdr[i].sh_type) {
451 case SHT_SYMTAB: /* Symbol table */
454 case SHT_STRTAB: /* String table */
463 size = shdr[i].sh_size;
464 archsw.arch_copyin(&size, lastaddr, sizeof(size));
465 lastaddr += sizeof(size);
468 printf("\n%s: 0x%jx@0x%jx -> 0x%jx-0x%jx", secname,
469 (uintmax_t)shdr[i].sh_size, (uintmax_t)shdr[i].sh_offset,
470 (uintmax_t)lastaddr, (uintmax_t)(lastaddr + shdr[i].sh_size));
472 if (i == symstrindex)
474 printf("0x%lx+0x%lx", (long)sizeof(size), (long)size);
477 if (lseek(ef->fd, (off_t)shdr[i].sh_offset, SEEK_SET) == -1) {
478 printf("\nelf" __XSTRING(__ELF_WORD_SIZE) "_loadimage: could not seek for symbols - skipped!");
483 result = archsw.arch_readin(ef->fd, lastaddr, shdr[i].sh_size);
484 if (result < 0 || (size_t)result != shdr[i].sh_size) {
485 printf("\nelf" __XSTRING(__ELF_WORD_SIZE) "_loadimage: could not read symbols - skipped! (%ju != %ju)", (uintmax_t)result,
486 (uintmax_t)shdr[i].sh_size);
491 /* Reset offsets relative to ssym */
492 lastaddr += shdr[i].sh_size;
493 lastaddr = roundup(lastaddr, sizeof(size));
494 if (i == symtabindex)
496 else if (i == symstrindex)
504 file_addmetadata(fp, MODINFOMD_SSYM, sizeof(ssym), &ssym);
505 file_addmetadata(fp, MODINFOMD_ESYM, sizeof(esym), &esym);
510 ret = lastaddr - firstaddr;
511 fp->f_addr = firstaddr;
514 for (i = 0; i < ehdr->e_phnum; i++) {
515 if (phdr[i].p_type == PT_DYNAMIC) {
518 file_addmetadata(fp, MODINFOMD_DYNAMIC, sizeof(adp), &adp);
523 if (php == NULL) /* this is bad, we cannot get to symbols or _DYNAMIC */
526 ndp = php->p_filesz / sizeof(Elf_Dyn);
529 dp = malloc(php->p_filesz);
532 archsw.arch_copyout(php->p_vaddr + off, dp, php->p_filesz);
535 for (i = 0; i < ndp; i++) {
536 if (dp[i].d_tag == 0)
538 switch (dp[i].d_tag) {
540 ef->hashtab = (Elf_Hashelt*)(uintptr_t)(dp[i].d_un.d_ptr + off);
543 ef->strtab = (char *)(uintptr_t)(dp[i].d_un.d_ptr + off);
546 ef->strsz = dp[i].d_un.d_val;
549 ef->symtab = (Elf_Sym*)(uintptr_t)(dp[i].d_un.d_ptr + off);
552 ef->rel = (Elf_Rel *)(uintptr_t)(dp[i].d_un.d_ptr + off);
555 ef->relsz = dp[i].d_un.d_val;
558 ef->rela = (Elf_Rela *)(uintptr_t)(dp[i].d_un.d_ptr + off);
561 ef->relasz = dp[i].d_un.d_val;
567 if (ef->hashtab == NULL || ef->symtab == NULL ||
568 ef->strtab == NULL || ef->strsz == 0)
570 COPYOUT(ef->hashtab, &ef->nbuckets, sizeof(ef->nbuckets));
571 COPYOUT(ef->hashtab + 1, &ef->nchains, sizeof(ef->nchains));
572 ef->buckets = ef->hashtab + 2;
573 ef->chains = ef->buckets + ef->nbuckets;
574 if (__elfN(parse_modmetadata)(fp, ef) == 0)
577 if (ef->kernel) /* kernel must not depend on anything */
588 static char invalid_name[] = "bad";
591 fake_modname(const char *name)
597 sp = strrchr(name, '/');
602 ep = strrchr(name, '.');
606 ep = invalid_name + sizeof(invalid_name) - 1;
609 ep = name + strlen(name);
611 fp = malloc(len + 1);
619 #if (defined(__i386__) || defined(__powerpc__)) && __ELF_WORD_SIZE == 64
620 struct mod_metadata64 {
621 int md_version; /* structure version MDTV_* */
622 int md_type; /* type of entry MDT_* */
623 u_int64_t md_data; /* specific data */
624 u_int64_t md_cval; /* common string label */
627 #if defined(__amd64__) && __ELF_WORD_SIZE == 32
628 struct mod_metadata32 {
629 int md_version; /* structure version MDTV_* */
630 int md_type; /* type of entry MDT_* */
631 u_int32_t md_data; /* specific data */
632 u_int32_t md_cval; /* common string label */
637 __elfN(parse_modmetadata)(struct preloaded_file *fp, elf_file_t ef)
639 struct mod_metadata md;
640 #if (defined(__i386__) || defined(__powerpc__)) && __ELF_WORD_SIZE == 64
641 struct mod_metadata64 md64;
642 #elif defined(__amd64__) && __ELF_WORD_SIZE == 32
643 struct mod_metadata32 md32;
645 struct mod_depend *mdepend;
646 struct mod_version mver;
649 int error, modcnt, minfolen;
650 Elf_Addr v, p, p_stop;
652 if (__elfN(lookup_symbol)(fp, ef, "__start_set_modmetadata_set", &sym) != 0)
654 p = sym.st_value + ef->off;
655 if (__elfN(lookup_symbol)(fp, ef, "__stop_set_modmetadata_set", &sym) != 0)
657 p_stop = sym.st_value + ef->off;
661 COPYOUT(p, &v, sizeof(v));
662 error = __elfN(reloc_ptr)(fp, ef, p, &v, sizeof(v));
663 if (error == EOPNOTSUPP)
667 #if (defined(__i386__) || defined(__powerpc__)) && __ELF_WORD_SIZE == 64
668 COPYOUT(v, &md64, sizeof(md64));
669 error = __elfN(reloc_ptr)(fp, ef, v, &md64, sizeof(md64));
670 if (error == EOPNOTSUPP) {
671 md64.md_cval += ef->off;
672 md64.md_data += ef->off;
673 } else if (error != 0)
675 md.md_version = md64.md_version;
676 md.md_type = md64.md_type;
677 md.md_cval = (const char *)(uintptr_t)md64.md_cval;
678 md.md_data = (void *)(uintptr_t)md64.md_data;
679 #elif defined(__amd64__) && __ELF_WORD_SIZE == 32
680 COPYOUT(v, &md32, sizeof(md32));
681 error = __elfN(reloc_ptr)(fp, ef, v, &md32, sizeof(md32));
682 if (error == EOPNOTSUPP) {
683 md32.md_cval += ef->off;
684 md32.md_data += ef->off;
685 } else if (error != 0)
687 md.md_version = md32.md_version;
688 md.md_type = md32.md_type;
689 md.md_cval = (const char *)(uintptr_t)md32.md_cval;
690 md.md_data = (void *)(uintptr_t)md32.md_data;
692 COPYOUT(v, &md, sizeof(md));
693 error = __elfN(reloc_ptr)(fp, ef, v, &md, sizeof(md));
694 if (error == EOPNOTSUPP) {
695 md.md_cval += ef->off;
696 md.md_data += ef->off;
697 } else if (error != 0)
700 p += sizeof(Elf_Addr);
703 if (ef->kernel) /* kernel must not depend on anything */
705 s = strdupout((vm_offset_t)md.md_cval);
706 minfolen = sizeof(*mdepend) + strlen(s) + 1;
707 mdepend = malloc(minfolen);
710 COPYOUT((vm_offset_t)md.md_data, mdepend, sizeof(*mdepend));
711 strcpy((char*)(mdepend + 1), s);
713 file_addmetadata(fp, MODINFOMD_DEPLIST, minfolen, mdepend);
717 s = strdupout((vm_offset_t)md.md_cval);
718 COPYOUT((vm_offset_t)md.md_data, &mver, sizeof(mver));
719 file_addmodule(fp, s, mver.mv_version, NULL);
726 s = fake_modname(fp->f_name);
727 file_addmodule(fp, s, 1, NULL);
734 elf_hash(const char *name)
736 const unsigned char *p = (const unsigned char *) name;
742 if ((g = h & 0xf0000000) != 0)
749 static const char __elfN(bad_symtable)[] = "elf" __XSTRING(__ELF_WORD_SIZE) "_lookup_symbol: corrupt symbol table\n";
751 __elfN(lookup_symbol)(struct preloaded_file *fp, elf_file_t ef, const char* name,
759 hash = elf_hash(name);
760 COPYOUT(&ef->buckets[hash % ef->nbuckets], &symnum, sizeof(symnum));
762 while (symnum != STN_UNDEF) {
763 if (symnum >= ef->nchains) {
764 printf(__elfN(bad_symtable));
768 COPYOUT(ef->symtab + symnum, &sym, sizeof(sym));
769 if (sym.st_name == 0) {
770 printf(__elfN(bad_symtable));
774 strp = strdupout((vm_offset_t)(ef->strtab + sym.st_name));
775 if (strcmp(name, strp) == 0) {
777 if (sym.st_shndx != SHN_UNDEF ||
778 (sym.st_value != 0 &&
779 ELF_ST_TYPE(sym.st_info) == STT_FUNC)) {
786 COPYOUT(&ef->chains[symnum], &symnum, sizeof(symnum));
792 * Apply any intra-module relocations to the value. p is the load address
793 * of the value and val/len is the value to be modified. This does NOT modify
794 * the image in-place, because this is done by kern_linker later on.
796 * Returns EOPNOTSUPP if no relocation method is supplied.
799 __elfN(reloc_ptr)(struct preloaded_file *mp, elf_file_t ef,
800 Elf_Addr p, void *val, size_t len)
808 * The kernel is already relocated, but we still want to apply
809 * offset adjustments.
814 for (n = 0; n < ef->relsz / sizeof(r); n++) {
815 COPYOUT(ef->rel + n, &r, sizeof(r));
817 error = __elfN(reloc)(ef, __elfN(symaddr), &r, ELF_RELOC_REL,
818 ef->off, p, val, len);
822 for (n = 0; n < ef->relasz / sizeof(a); n++) {
823 COPYOUT(ef->rela + n, &a, sizeof(a));
825 error = __elfN(reloc)(ef, __elfN(symaddr), &a, ELF_RELOC_RELA,
826 ef->off, p, val, len);
835 __elfN(symaddr)(struct elf_file *ef, Elf_Size symidx)
838 /* Symbol lookup by index not required here. */