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