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