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;
104 bzero(&ef, sizeof(struct elf_file));
107 * Open the image, read and validate the ELF header
109 if (filename == NULL) /* can't handle nameless */
111 if ((ef.fd = open(filename, O_RDONLY)) == -1)
113 ef.firstpage = malloc(PAGE_SIZE);
114 if (ef.firstpage == NULL) {
118 bytes_read = read(ef.fd, ef.firstpage, PAGE_SIZE);
119 ef.firstlen = (size_t)bytes_read;
120 if (bytes_read < 0 || ef.firstlen <= sizeof(Elf_Ehdr)) {
121 err = EFTYPE; /* could be EIO, but may be small file */
124 ehdr = ef.ehdr = (Elf_Ehdr *)ef.firstpage;
127 if (!IS_ELF(*ehdr)) {
131 if (ehdr->e_ident[EI_CLASS] != ELF_TARG_CLASS || /* Layout ? */
132 ehdr->e_ident[EI_DATA] != ELF_TARG_DATA ||
133 ehdr->e_ident[EI_VERSION] != EV_CURRENT || /* Version ? */
134 ehdr->e_version != EV_CURRENT ||
135 ehdr->e_machine != ELF_TARG_MACH) { /* Machine ? */
142 * Check to see what sort of module we are.
144 kfp = file_findfile(NULL, NULL);
145 if (ehdr->e_type == ET_DYN) {
146 /* Looks like a kld module */
148 printf("elf" __XSTRING(__ELF_WORD_SIZE) "_loadfile: can't load module before kernel\n");
152 if (strcmp(__elfN(kerneltype), kfp->f_type)) {
153 printf("elf" __XSTRING(__ELF_WORD_SIZE) "_loadfile: can't load module with kernel type '%s'\n", kfp->f_type);
157 /* Looks OK, got ahead */
160 /* Page-align the load address */
161 pad = (u_int)dest & PAGE_MASK;
163 pad = PAGE_SIZE - pad;
166 } else if (ehdr->e_type == ET_EXEC) {
167 /* Looks like a kernel */
169 printf("elf" __XSTRING(__ELF_WORD_SIZE) "_loadfile: kernel already loaded\n");
174 * Calculate destination address based on kernel entrypoint
176 dest = ehdr->e_entry;
178 printf("elf" __XSTRING(__ELF_WORD_SIZE) "_loadfile: not a kernel (maybe static binary?)\n");
190 * Ok, we think we should handle this.
194 printf("elf" __XSTRING(__ELF_WORD_SIZE) "_loadfile: cannot allocate module info\n");
199 setenv("kernelname", filename, 1);
200 fp->f_name = strdup(filename);
201 fp->f_type = strdup(ef.kernel ? __elfN(kerneltype) : __elfN(moduletype));
205 printf("%s entry at 0x%jx\n", filename, (uintmax_t)dest);
207 printf("%s ", filename);
210 fp->f_size = __elfN(loadimage)(fp, &ef, dest);
211 if (fp->f_size == 0 || fp->f_addr == 0)
214 /* save exec header as metadata */
215 file_addmetadata(fp, MODINFOMD_ELFHDR, sizeof(*ehdr), ehdr);
217 /* Load OK, return module pointer */
218 *result = (struct preloaded_file *)fp;
234 * With the file (fd) open on the image, and (ehdr) containing
235 * the Elf header, load the image at (off)
238 __elfN(loadimage)(struct preloaded_file *fp, elf_file_t ef, u_int64_t off)
243 Elf_Phdr *phdr, *php;
246 vm_offset_t firstaddr;
247 vm_offset_t lastaddr;
262 firstaddr = lastaddr = 0;
266 #if __ELF_WORD_SIZE == 64
267 off = - (off & 0xffffffffff000000ull);/* x86_64 relocates after locore */
269 off = - (off & 0xff000000u); /* i386 relocates after locore */
271 #elif defined(__powerpc__)
273 * On the purely virtual memory machines like e500, the kernel is
274 * linked against its final VA range, which is most often not
275 * available at the loader stage, but only after kernel initializes
276 * and completes its VM settings. In such cases we cannot use p_vaddr
277 * field directly to load ELF segments, but put them at some
278 * 'load-time' locations.
280 if (off & 0xf0000000u) {
281 off = -(off & 0xf0000000u);
283 * XXX the physical load address should not be hardcoded. Note
284 * that the Book-E kernel assumes that it's loaded at a 16MB
285 * boundary for now...
288 ehdr->e_entry += off;
290 printf("Converted entry 0x%08x\n", ehdr->e_entry);
294 #elif defined(__arm__)
295 if (off & 0xf0000000u) {
296 off = -(off & 0xf0000000u);
297 ehdr->e_entry += off;
299 printf("Converted entry 0x%08x\n", ehdr->e_entry);
304 off = 0; /* other archs use direct mapped kernels */
306 __elfN(relocation_offset) = off;
310 if ((ehdr->e_phoff + ehdr->e_phnum * sizeof(*phdr)) > ef->firstlen) {
311 printf("elf" __XSTRING(__ELF_WORD_SIZE) "_loadimage: program header not within first page\n");
314 phdr = (Elf_Phdr *)(ef->firstpage + ehdr->e_phoff);
316 for (i = 0; i < ehdr->e_phnum; i++) {
317 /* We want to load PT_LOAD segments only.. */
318 if (phdr[i].p_type != PT_LOAD)
322 printf("Segment: 0x%lx@0x%lx -> 0x%lx-0x%lx",
323 (long)phdr[i].p_filesz, (long)phdr[i].p_offset,
324 (long)(phdr[i].p_vaddr + off),
325 (long)(phdr[i].p_vaddr + off + phdr[i].p_memsz - 1));
327 if ((phdr[i].p_flags & PF_W) == 0) {
328 printf("text=0x%lx ", (long)phdr[i].p_filesz);
330 printf("data=0x%lx", (long)phdr[i].p_filesz);
331 if (phdr[i].p_filesz < phdr[i].p_memsz)
332 printf("+0x%lx", (long)(phdr[i].p_memsz -phdr[i].p_filesz));
337 if (ef->firstlen > phdr[i].p_offset) {
338 fpcopy = ef->firstlen - phdr[i].p_offset;
339 archsw.arch_copyin(ef->firstpage + phdr[i].p_offset,
340 phdr[i].p_vaddr + off, fpcopy);
342 if (phdr[i].p_filesz > fpcopy) {
343 if (kern_pread(ef->fd, phdr[i].p_vaddr + off + fpcopy,
344 phdr[i].p_filesz - fpcopy, phdr[i].p_offset + fpcopy) != 0) {
345 printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
346 "_loadimage: read failed\n");
350 /* clear space from oversized segments; eg: bss */
351 if (phdr[i].p_filesz < phdr[i].p_memsz) {
353 printf(" (bss: 0x%lx-0x%lx)",
354 (long)(phdr[i].p_vaddr + off + phdr[i].p_filesz),
355 (long)(phdr[i].p_vaddr + off + phdr[i].p_memsz - 1));
358 kern_bzero(phdr[i].p_vaddr + off + phdr[i].p_filesz,
359 phdr[i].p_memsz - phdr[i].p_filesz);
365 if (firstaddr == 0 || firstaddr > (phdr[i].p_vaddr + off))
366 firstaddr = phdr[i].p_vaddr + off;
367 if (lastaddr == 0 || lastaddr < (phdr[i].p_vaddr + off + phdr[i].p_memsz))
368 lastaddr = phdr[i].p_vaddr + off + phdr[i].p_memsz;
370 lastaddr = roundup(lastaddr, sizeof(long));
373 * Now grab the symbol tables. This isn't easy if we're reading a
374 * .gz file. I think the rule is going to have to be that you must
375 * strip a file to remove symbols before gzipping it so that we do not
376 * try to lseek() on it.
378 chunk = ehdr->e_shnum * ehdr->e_shentsize;
379 if (chunk == 0 || ehdr->e_shoff == 0)
381 shdr = alloc_pread(ef->fd, ehdr->e_shoff, chunk);
383 printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
384 "_loadimage: failed to read section headers");
389 for (i = 0; i < ehdr->e_shnum; i++) {
390 if (shdr[i].sh_type != SHT_SYMTAB)
392 for (j = 0; j < ehdr->e_phnum; j++) {
393 if (phdr[j].p_type != PT_LOAD)
395 if (shdr[i].sh_offset >= phdr[j].p_offset &&
396 (shdr[i].sh_offset + shdr[i].sh_size <=
397 phdr[j].p_offset + phdr[j].p_filesz)) {
398 shdr[i].sh_offset = 0;
403 if (shdr[i].sh_offset == 0 || shdr[i].sh_size == 0)
404 continue; /* alread loaded in a PT_LOAD above */
405 /* Save it for loading below */
407 symstrindex = shdr[i].sh_link;
409 if (symtabindex < 0 || symstrindex < 0)
412 /* Ok, committed to a load. */
417 for (i = symtabindex; i >= 0; i = symstrindex) {
421 switch(shdr[i].sh_type) {
422 case SHT_SYMTAB: /* Symbol table */
425 case SHT_STRTAB: /* String table */
434 size = shdr[i].sh_size;
435 archsw.arch_copyin(&size, lastaddr, sizeof(size));
436 lastaddr += sizeof(size);
439 printf("\n%s: 0x%jx@0x%jx -> 0x%jx-0x%jx", secname,
440 (uintmax_t)shdr[i].sh_size, (uintmax_t)shdr[i].sh_offset,
441 (uintmax_t)lastaddr, (uintmax_t)(lastaddr + shdr[i].sh_size));
443 if (i == symstrindex)
445 printf("0x%lx+0x%lx", (long)sizeof(size), (long)size);
448 if (lseek(ef->fd, (off_t)shdr[i].sh_offset, SEEK_SET) == -1) {
449 printf("\nelf" __XSTRING(__ELF_WORD_SIZE) "_loadimage: could not seek for symbols - skipped!");
454 result = archsw.arch_readin(ef->fd, lastaddr, shdr[i].sh_size);
455 if (result < 0 || (size_t)result != shdr[i].sh_size) {
456 printf("\nelf" __XSTRING(__ELF_WORD_SIZE) "_loadimage: could not read symbols - skipped! (%ju != %ju)", (uintmax_t)result,
457 (uintmax_t)shdr[i].sh_size);
462 /* Reset offsets relative to ssym */
463 lastaddr += shdr[i].sh_size;
464 lastaddr = roundup(lastaddr, sizeof(size));
465 if (i == symtabindex)
467 else if (i == symstrindex)
475 file_addmetadata(fp, MODINFOMD_SSYM, sizeof(ssym), &ssym);
476 file_addmetadata(fp, MODINFOMD_ESYM, sizeof(esym), &esym);
481 ret = lastaddr - firstaddr;
482 fp->f_addr = firstaddr;
485 for (i = 0; i < ehdr->e_phnum; i++) {
486 if (phdr[i].p_type == PT_DYNAMIC) {
489 file_addmetadata(fp, MODINFOMD_DYNAMIC, sizeof(adp), &adp);
494 if (php == NULL) /* this is bad, we cannot get to symbols or _DYNAMIC */
497 ndp = php->p_filesz / sizeof(Elf_Dyn);
500 dp = malloc(php->p_filesz);
503 archsw.arch_copyout(php->p_vaddr + off, dp, php->p_filesz);
506 for (i = 0; i < ndp; i++) {
507 if (dp[i].d_tag == 0)
509 switch (dp[i].d_tag) {
511 ef->hashtab = (Elf_Hashelt*)(uintptr_t)(dp[i].d_un.d_ptr + off);
514 ef->strtab = (char *)(uintptr_t)(dp[i].d_un.d_ptr + off);
517 ef->strsz = dp[i].d_un.d_val;
520 ef->symtab = (Elf_Sym*)(uintptr_t)(dp[i].d_un.d_ptr + off);
523 ef->rel = (Elf_Rel *)(uintptr_t)(dp[i].d_un.d_ptr + off);
526 ef->relsz = dp[i].d_un.d_val;
529 ef->rela = (Elf_Rela *)(uintptr_t)(dp[i].d_un.d_ptr + off);
532 ef->relasz = dp[i].d_un.d_val;
538 if (ef->hashtab == NULL || ef->symtab == NULL ||
539 ef->strtab == NULL || ef->strsz == 0)
541 COPYOUT(ef->hashtab, &ef->nbuckets, sizeof(ef->nbuckets));
542 COPYOUT(ef->hashtab + 1, &ef->nchains, sizeof(ef->nchains));
543 ef->buckets = ef->hashtab + 2;
544 ef->chains = ef->buckets + ef->nbuckets;
545 if (__elfN(parse_modmetadata)(fp, ef) == 0)
548 if (ef->kernel) /* kernel must not depend on anything */
559 static char invalid_name[] = "bad";
562 fake_modname(const char *name)
568 sp = strrchr(name, '/');
573 ep = strrchr(name, '.');
577 ep = invalid_name + sizeof(invalid_name) - 1;
580 ep = name + strlen(name);
582 fp = malloc(len + 1);
590 #if defined(__i386__) && __ELF_WORD_SIZE == 64
591 struct mod_metadata64 {
592 int md_version; /* structure version MDTV_* */
593 int md_type; /* type of entry MDT_* */
594 u_int64_t md_data; /* specific data */
595 u_int64_t md_cval; /* common string label */
600 __elfN(parse_modmetadata)(struct preloaded_file *fp, elf_file_t ef)
602 struct mod_metadata md;
603 #if defined(__i386__) && __ELF_WORD_SIZE == 64
604 struct mod_metadata64 md64;
606 struct mod_depend *mdepend;
607 struct mod_version mver;
610 int error, modcnt, minfolen;
611 Elf_Addr v, p, p_stop;
613 if (__elfN(lookup_symbol)(fp, ef, "__start_set_modmetadata_set", &sym) != 0)
615 p = sym.st_value + ef->off;
616 if (__elfN(lookup_symbol)(fp, ef, "__stop_set_modmetadata_set", &sym) != 0)
618 p_stop = sym.st_value + ef->off;
622 COPYOUT(p, &v, sizeof(v));
623 error = __elfN(reloc_ptr)(fp, ef, p, &v, sizeof(v));
624 if (error == EOPNOTSUPP)
628 #if defined(__i386__) && __ELF_WORD_SIZE == 64
629 COPYOUT(v, &md64, sizeof(md64));
630 error = __elfN(reloc_ptr)(fp, ef, v, &md64, sizeof(md64));
631 if (error == EOPNOTSUPP) {
632 md64.md_cval += ef->off;
633 md64.md_data += ef->off;
634 } else if (error != 0)
636 md.md_version = md64.md_version;
637 md.md_type = md64.md_type;
638 md.md_cval = (const char *)(uintptr_t)md64.md_cval;
639 md.md_data = (void *)(uintptr_t)md64.md_data;
641 COPYOUT(v, &md, sizeof(md));
642 error = __elfN(reloc_ptr)(fp, ef, v, &md, sizeof(md));
643 if (error == EOPNOTSUPP) {
644 md.md_cval += ef->off;
645 md.md_data += ef->off;
646 } else if (error != 0)
649 p += sizeof(Elf_Addr);
652 if (ef->kernel) /* kernel must not depend on anything */
654 s = strdupout((vm_offset_t)md.md_cval);
655 minfolen = sizeof(*mdepend) + strlen(s) + 1;
656 mdepend = malloc(minfolen);
659 COPYOUT((vm_offset_t)md.md_data, mdepend, sizeof(*mdepend));
660 strcpy((char*)(mdepend + 1), s);
662 file_addmetadata(fp, MODINFOMD_DEPLIST, minfolen, mdepend);
666 s = strdupout((vm_offset_t)md.md_cval);
667 COPYOUT((vm_offset_t)md.md_data, &mver, sizeof(mver));
668 file_addmodule(fp, s, mver.mv_version, NULL);
675 s = fake_modname(fp->f_name);
676 file_addmodule(fp, s, 1, NULL);
683 elf_hash(const char *name)
685 const unsigned char *p = (const unsigned char *) name;
691 if ((g = h & 0xf0000000) != 0)
698 static const char __elfN(bad_symtable)[] = "elf" __XSTRING(__ELF_WORD_SIZE) "_lookup_symbol: corrupt symbol table\n";
700 __elfN(lookup_symbol)(struct preloaded_file *fp, elf_file_t ef, const char* name,
708 hash = elf_hash(name);
709 COPYOUT(&ef->buckets[hash % ef->nbuckets], &symnum, sizeof(symnum));
711 while (symnum != STN_UNDEF) {
712 if (symnum >= ef->nchains) {
713 printf(__elfN(bad_symtable));
717 COPYOUT(ef->symtab + symnum, &sym, sizeof(sym));
718 if (sym.st_name == 0) {
719 printf(__elfN(bad_symtable));
723 strp = strdupout((vm_offset_t)(ef->strtab + sym.st_name));
724 if (strcmp(name, strp) == 0) {
726 if (sym.st_shndx != SHN_UNDEF ||
727 (sym.st_value != 0 &&
728 ELF_ST_TYPE(sym.st_info) == STT_FUNC)) {
735 COPYOUT(&ef->chains[symnum], &symnum, sizeof(symnum));
741 * Apply any intra-module relocations to the value. p is the load address
742 * of the value and val/len is the value to be modified. This does NOT modify
743 * the image in-place, because this is done by kern_linker later on.
745 * Returns EOPNOTSUPP if no relocation method is supplied.
748 __elfN(reloc_ptr)(struct preloaded_file *mp, elf_file_t ef,
749 Elf_Addr p, void *val, size_t len)
757 * The kernel is already relocated, but we still want to apply
758 * offset adjustments.
763 for (n = 0; n < ef->relsz / sizeof(r); n++) {
764 COPYOUT(ef->rel + n, &r, sizeof(r));
766 error = __elfN(reloc)(ef, __elfN(symaddr), &r, ELF_RELOC_REL,
767 ef->off, p, val, len);
771 for (n = 0; n < ef->relasz / sizeof(a); n++) {
772 COPYOUT(ef->rela + n, &a, sizeof(a));
774 error = __elfN(reloc)(ef, __elfN(symaddr), &a, ELF_RELOC_RELA,
775 ef->off, p, val, len);
784 __elfN(symaddr)(struct elf_file *ef, Elf_Size symidx)
787 /* Symbol lookup by index not required here. */