]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - stand/common/load_elf.c
MFV: cherry-pick "PR/358: Fix width for -f - (jpalus)"
[FreeBSD/FreeBSD.git] / stand / common / load_elf.c
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/endian.h>
33 #include <sys/exec.h>
34 #include <sys/linker.h>
35 #include <sys/module.h>
36 #include <sys/stdint.h>
37 #include <string.h>
38 #include <machine/elf.h>
39 #include <stand.h>
40 #define FREEBSD_ELF
41 #include <sys/link_elf.h>
42
43 #include "bootstrap.h"
44
45 #define COPYOUT(s,d,l)  archsw.arch_copyout((vm_offset_t)(s), d, l)
46
47 #if defined(__i386__) && __ELF_WORD_SIZE == 64
48 #undef ELF_TARG_CLASS
49 #undef ELF_TARG_MACH
50 #define ELF_TARG_CLASS  ELFCLASS64
51 #define ELF_TARG_MACH   EM_X86_64
52 #endif
53
54 typedef struct elf_file {
55         Elf_Phdr        *ph;
56         Elf_Ehdr        *ehdr;
57         Elf_Sym         *symtab;
58         Elf_Hashelt     *hashtab;
59         Elf_Hashelt     nbuckets;
60         Elf_Hashelt     nchains;
61         Elf_Hashelt     *buckets;
62         Elf_Hashelt     *chains;
63         Elf_Rel *rel;
64         size_t  relsz;
65         Elf_Rela        *rela;
66         size_t  relasz;
67         char    *strtab;
68         size_t  strsz;
69         int             fd;
70         caddr_t firstpage;
71         size_t  firstlen;
72         int             kernel;
73         uint64_t        off;
74 #ifdef LOADER_VERIEXEC_VECTX
75         struct vectx    *vctx;
76 #endif
77 } *elf_file_t;
78
79 #ifdef LOADER_VERIEXEC_VECTX
80 #define VECTX_HANDLE(ef) (ef)->vctx
81 #else
82 #define VECTX_HANDLE(ef) (ef)->fd
83 #endif
84
85 static int __elfN(loadimage)(struct preloaded_file *mp, elf_file_t ef,
86     uint64_t loadaddr);
87 static int __elfN(lookup_symbol)(elf_file_t ef, const char* name,
88     Elf_Sym *sym, unsigned char type);
89 static int __elfN(reloc_ptr)(struct preloaded_file *mp, elf_file_t ef,
90     Elf_Addr p, void *val, size_t len);
91 static int __elfN(parse_modmetadata)(struct preloaded_file *mp, elf_file_t ef,
92     Elf_Addr p_start, Elf_Addr p_end);
93 static symaddr_fn __elfN(symaddr);
94 static char     *fake_modname(const char *name);
95
96 const char      *__elfN(kerneltype) = "elf kernel";
97 const char      *__elfN(moduletype) = "elf module";
98
99 uint64_t        __elfN(relocation_offset) = 0;
100
101 extern void elf_wrong_field_size(void);
102 #define CONVERT_FIELD(b, f, e)                  \
103         switch (sizeof((b)->f)) {               \
104         case 2:                                 \
105                 (b)->f = e ## 16toh((b)->f);    \
106                 break;                          \
107         case 4:                                 \
108                 (b)->f = e ## 32toh((b)->f);    \
109                 break;                          \
110         case 8:                                 \
111                 (b)->f = e ## 64toh((b)->f);    \
112                 break;                          \
113         default:                                \
114                 /* Force a link time error. */  \
115                 elf_wrong_field_size();         \
116                 break;                          \
117         }
118
119 #define CONVERT_SWITCH(h, d, f)                 \
120         switch ((h)->e_ident[EI_DATA]) {        \
121         case ELFDATA2MSB:                       \
122                 f(d, be);                       \
123                 break;                          \
124         case ELFDATA2LSB:                       \
125                 f(d, le);                       \
126                 break;                          \
127         default:                                \
128                 return (EINVAL);                \
129         }
130
131
132 static int elf_header_convert(Elf_Ehdr *ehdr)
133 {
134         /*
135          * Fixup ELF header endianness.
136          *
137          * The Xhdr structure was loaded using block read call to optimize file
138          * accesses. It might happen, that the endianness of the system memory
139          * is different that endianness of the ELF header.  Swap fields here to
140          * guarantee that Xhdr always contain valid data regardless of
141          * architecture.
142          */
143 #define HEADER_FIELDS(b, e)                     \
144         CONVERT_FIELD(b, e_type, e);            \
145         CONVERT_FIELD(b, e_machine, e);         \
146         CONVERT_FIELD(b, e_version, e);         \
147         CONVERT_FIELD(b, e_entry, e);           \
148         CONVERT_FIELD(b, e_phoff, e);           \
149         CONVERT_FIELD(b, e_shoff, e);           \
150         CONVERT_FIELD(b, e_flags, e);           \
151         CONVERT_FIELD(b, e_ehsize, e);          \
152         CONVERT_FIELD(b, e_phentsize, e);       \
153         CONVERT_FIELD(b, e_phnum, e);           \
154         CONVERT_FIELD(b, e_shentsize, e);       \
155         CONVERT_FIELD(b, e_shnum, e);           \
156         CONVERT_FIELD(b, e_shstrndx, e)
157
158         CONVERT_SWITCH(ehdr, ehdr, HEADER_FIELDS);
159
160 #undef HEADER_FIELDS
161
162         return (0);
163 }
164
165 static int elf_program_header_convert(const Elf_Ehdr *ehdr, Elf_Phdr *phdr)
166 {
167 #define PROGRAM_HEADER_FIELDS(b, e)             \
168         CONVERT_FIELD(b, p_type, e);            \
169         CONVERT_FIELD(b, p_flags, e);           \
170         CONVERT_FIELD(b, p_offset, e);          \
171         CONVERT_FIELD(b, p_vaddr, e);           \
172         CONVERT_FIELD(b, p_paddr, e);           \
173         CONVERT_FIELD(b, p_filesz, e);          \
174         CONVERT_FIELD(b, p_memsz, e);           \
175         CONVERT_FIELD(b, p_align, e)
176
177         CONVERT_SWITCH(ehdr, phdr, PROGRAM_HEADER_FIELDS);
178
179 #undef PROGRAM_HEADER_FIELDS
180
181         return (0);
182 }
183
184 static int elf_section_header_convert(const Elf_Ehdr *ehdr, Elf_Shdr *shdr)
185 {
186 #define SECTION_HEADER_FIELDS(b, e)             \
187         CONVERT_FIELD(b, sh_name, e);           \
188         CONVERT_FIELD(b, sh_type, e);           \
189         CONVERT_FIELD(b, sh_link, e);           \
190         CONVERT_FIELD(b, sh_info, e);           \
191         CONVERT_FIELD(b, sh_flags, e);          \
192         CONVERT_FIELD(b, sh_addr, e);           \
193         CONVERT_FIELD(b, sh_offset, e);         \
194         CONVERT_FIELD(b, sh_size, e);           \
195         CONVERT_FIELD(b, sh_addralign, e);      \
196         CONVERT_FIELD(b, sh_entsize, e)
197
198         CONVERT_SWITCH(ehdr, shdr, SECTION_HEADER_FIELDS);
199
200 #undef SECTION_HEADER_FIELDS
201
202         return (0);
203 }
204 #undef CONVERT_SWITCH
205 #undef CONVERT_FIELD
206
207
208 #ifdef __amd64__
209 static bool
210 is_kernphys_relocatable(elf_file_t ef)
211 {
212         Elf_Sym sym;
213
214         return (__elfN(lookup_symbol)(ef, "kernphys", &sym, STT_OBJECT) == 0);
215 }
216 #endif
217
218 #ifdef __i386__
219 static bool
220 is_tg_kernel_support(struct preloaded_file *fp, elf_file_t ef)
221 {
222         Elf_Sym         sym;
223         Elf_Addr        p_start, p_end, v, p;
224         char            vd_name[16];
225         int             error;
226
227         if (__elfN(lookup_symbol)(ef, "__start_set_vt_drv_set", &sym, STT_NOTYPE) != 0)
228                 return (false);
229         p_start = sym.st_value + ef->off;
230         if (__elfN(lookup_symbol)(ef, "__stop_set_vt_drv_set", &sym, STT_NOTYPE) != 0)
231                 return (false);
232         p_end = sym.st_value + ef->off;
233
234         /*
235          * Walk through vt_drv_set, each vt driver structure starts with
236          * static 16 chars for driver name. If we have "vbefb", return true.
237          */
238         for (p = p_start; p < p_end; p += sizeof(Elf_Addr)) {
239                 COPYOUT(p, &v, sizeof(v));
240
241                 error = __elfN(reloc_ptr)(fp, ef, p, &v, sizeof(v));
242                 if (error == EOPNOTSUPP)
243                         v += ef->off;
244                 else if (error != 0)
245                         return (false);
246                 COPYOUT(v, &vd_name, sizeof(vd_name));
247                 if (strncmp(vd_name, "vbefb", sizeof(vd_name)) == 0)
248                         return (true);
249         }
250
251         return (false);
252 }
253 #endif
254
255 static int
256 __elfN(load_elf_header)(char *filename, elf_file_t ef)
257 {
258         ssize_t                  bytes_read;
259         Elf_Ehdr                *ehdr;
260         int                      err;
261
262         /*
263          * Open the image, read and validate the ELF header
264          */
265         if (filename == NULL)   /* can't handle nameless */
266                 return (EFTYPE);
267         if ((ef->fd = open(filename, O_RDONLY)) == -1)
268                 return (errno);
269         ef->firstpage = malloc(PAGE_SIZE);
270         if (ef->firstpage == NULL) {
271                 close(ef->fd);
272                 return (ENOMEM);
273         }
274         preload(ef->fd);
275 #ifdef LOADER_VERIEXEC_VECTX
276         {
277                 int verror;
278
279                 ef->vctx = vectx_open(ef->fd, filename, 0L, NULL, &verror, __func__);
280                 if (verror) {
281                         printf("Unverified %s: %s\n", filename, ve_error_get());
282                         close(ef->fd);
283                         free(ef->vctx);
284                         return (EAUTH);
285                 }
286         }
287 #endif
288         bytes_read = VECTX_READ(VECTX_HANDLE(ef), ef->firstpage, PAGE_SIZE);
289         ef->firstlen = (size_t)bytes_read;
290         if (bytes_read < 0 || ef->firstlen <= sizeof(Elf_Ehdr)) {
291                 err = EFTYPE; /* could be EIO, but may be small file */
292                 goto error;
293         }
294         ehdr = ef->ehdr = (Elf_Ehdr *)ef->firstpage;
295
296         /* Is it ELF? */
297         if (!IS_ELF(*ehdr)) {
298                 err = EFTYPE;
299                 goto error;
300         }
301
302         if (ehdr->e_ident[EI_CLASS] != ELF_TARG_CLASS || /* Layout ? */
303             ehdr->e_ident[EI_DATA] != ELF_TARG_DATA ||
304             ehdr->e_ident[EI_VERSION] != EV_CURRENT) /* Version ? */ {
305                 err = EFTYPE;
306                 goto error;
307         }
308
309         err = elf_header_convert(ehdr);
310         if (err)
311                 goto error;
312
313         if (ehdr->e_version != EV_CURRENT || ehdr->e_machine != ELF_TARG_MACH) {
314                 /* Machine ? */
315                 err = EFTYPE;
316                 goto error;
317         }
318
319 #if defined(LOADER_VERIEXEC) && !defined(LOADER_VERIEXEC_VECTX)
320         if (verify_file(ef->fd, filename, bytes_read, VE_MUST, __func__) < 0) {
321                 err = EAUTH;
322                 goto error;
323         }
324 #endif
325         return (0);
326
327 error:
328         if (ef->firstpage != NULL) {
329                 free(ef->firstpage);
330                 ef->firstpage = NULL;
331         }
332         if (ef->fd != -1) {
333 #ifdef LOADER_VERIEXEC_VECTX
334                 free(ef->vctx);
335 #endif
336                 close(ef->fd);
337                 ef->fd = -1;
338         }
339         return (err);
340 }
341
342 /*
343  * Attempt to load the file (file) as an ELF module.  It will be stored at
344  * (dest), and a pointer to a module structure describing the loaded object
345  * will be saved in (result).
346  */
347 int
348 __elfN(loadfile)(char *filename, uint64_t dest, struct preloaded_file **result)
349 {
350         return (__elfN(loadfile_raw)(filename, dest, result, 0));
351 }
352
353 int
354 __elfN(loadfile_raw)(char *filename, uint64_t dest,
355     struct preloaded_file **result, int multiboot)
356 {
357         struct preloaded_file   *fp, *kfp;
358         struct elf_file         ef;
359         Elf_Ehdr                *ehdr;
360         int                     err;
361
362         fp = NULL;
363         bzero(&ef, sizeof(struct elf_file));
364         ef.fd = -1;
365
366         err = __elfN(load_elf_header)(filename, &ef);
367         if (err != 0)
368                 return (err);
369
370         ehdr = ef.ehdr;
371
372         /*
373          * Check to see what sort of module we are.
374          */
375         kfp = file_findfile(NULL, __elfN(kerneltype));
376 #ifdef __powerpc__
377         /*
378          * Kernels can be ET_DYN, so just assume the first loaded object is the
379          * kernel. This assumption will be checked later.
380          */
381         if (kfp == NULL)
382                 ef.kernel = 1;
383 #endif
384         if (ef.kernel || ehdr->e_type == ET_EXEC) {
385                 /* Looks like a kernel */
386                 if (kfp != NULL) {
387                         printf("elf" __XSTRING(__ELF_WORD_SIZE)
388                             "_loadfile: kernel already loaded\n");
389                         err = EPERM;
390                         goto oerr;
391                 }
392                 /*
393                  * Calculate destination address based on kernel entrypoint.
394                  *
395                  * For ARM, the destination address is independent of any values
396                  * in the elf header (an ARM kernel can be loaded at any 2MB
397                  * boundary), so we leave dest set to the value calculated by
398                  * archsw.arch_loadaddr() and passed in to this function.
399                  */
400 #ifndef __arm__
401                 if (ehdr->e_type == ET_EXEC)
402                         dest = (ehdr->e_entry & ~PAGE_MASK);
403 #endif
404                 if ((ehdr->e_entry & ~PAGE_MASK) == 0) {
405                         printf("elf" __XSTRING(__ELF_WORD_SIZE)
406                             "_loadfile: not a kernel (maybe static binary?)\n");
407                         err = EPERM;
408                         goto oerr;
409                 }
410                 ef.kernel = 1;
411
412         } else if (ehdr->e_type == ET_DYN) {
413                 /* Looks like a kld module */
414                 if (multiboot != 0) {
415                         printf("elf" __XSTRING(__ELF_WORD_SIZE)
416                             "_loadfile: can't load module as multiboot\n");
417                         err = EPERM;
418                         goto oerr;
419                 }
420                 if (kfp == NULL) {
421                         printf("elf" __XSTRING(__ELF_WORD_SIZE)
422                             "_loadfile: can't load module before kernel\n");
423                         err = EPERM;
424                         goto oerr;
425                 }
426                 if (strcmp(__elfN(kerneltype), kfp->f_type)) {
427                         printf("elf" __XSTRING(__ELF_WORD_SIZE)
428                          "_loadfile: can't load module with kernel type '%s'\n",
429                             kfp->f_type);
430                         err = EPERM;
431                         goto oerr;
432                 }
433                 /* Looks OK, got ahead */
434                 ef.kernel = 0;
435         
436         } else {
437                 err = EFTYPE;
438                 goto oerr;
439         }
440
441         if (archsw.arch_loadaddr != NULL)
442                 dest = archsw.arch_loadaddr(LOAD_ELF, ehdr, dest);
443         else
444                 dest = roundup(dest, PAGE_SIZE);
445
446         /*
447          * Ok, we think we should handle this.
448          */
449         fp = file_alloc();
450         if (fp == NULL) {
451                 printf("elf" __XSTRING(__ELF_WORD_SIZE)
452                     "_loadfile: cannot allocate module info\n");
453                 err = EPERM;
454                 goto out;
455         }
456         if (ef.kernel == 1 && multiboot == 0)
457                 setenv("kernelname", filename, 1);
458         fp->f_name = strdup(filename);
459         if (multiboot == 0)
460                 fp->f_type = strdup(ef.kernel ?
461                     __elfN(kerneltype) : __elfN(moduletype));
462         else
463                 fp->f_type = strdup("elf multiboot kernel");
464
465         if (module_verbose >= MODULE_VERBOSE_FULL) {
466                 if (ef.kernel)
467                         printf("%s entry at 0x%jx\n", filename,
468                             (uintmax_t)ehdr->e_entry);
469         } else if (module_verbose > MODULE_VERBOSE_SILENT)
470                 printf("%s ", filename);
471
472         fp->f_size = __elfN(loadimage)(fp, &ef, dest);
473         if (fp->f_size == 0 || fp->f_addr == 0)
474                 goto ioerr;
475
476         /* save exec header as metadata */
477         file_addmetadata(fp, MODINFOMD_ELFHDR, sizeof(*ehdr), ehdr);
478
479         /* Load OK, return module pointer */
480         *result = (struct preloaded_file *)fp;
481         err = 0;
482 #ifdef __amd64__
483         fp->f_kernphys_relocatable = multiboot || is_kernphys_relocatable(&ef);
484 #endif
485 #ifdef __i386__
486         fp->f_tg_kernel_support = is_tg_kernel_support(fp, &ef);
487 #endif
488         goto out;
489
490 ioerr:
491         err = EIO;
492 oerr:
493         file_discard(fp);
494 out:
495         if (ef.firstpage)
496                 free(ef.firstpage);
497         if (ef.fd != -1) {
498 #ifdef LOADER_VERIEXEC_VECTX
499                 if (!err && ef.vctx) {
500                         int verror;
501
502                         verror = vectx_close(ef.vctx, VE_MUST, __func__);
503                         if (verror) {
504                                 err = EAUTH;
505                                 file_discard(fp);
506                         }
507                 }
508 #endif
509                 close(ef.fd);
510         }
511         return (err);
512 }
513
514 /*
515  * With the file (fd) open on the image, and (ehdr) containing
516  * the Elf header, load the image at (off)
517  */
518 static int
519 __elfN(loadimage)(struct preloaded_file *fp, elf_file_t ef, uint64_t off)
520 {
521         int             i;
522         u_int           j;
523         Elf_Ehdr        *ehdr;
524         Elf_Phdr        *phdr, *php;
525         Elf_Shdr        *shdr;
526         char            *shstr;
527         int             ret;
528         vm_offset_t     firstaddr;
529         vm_offset_t     lastaddr;
530         size_t          chunk;
531         ssize_t         result;
532         Elf_Addr        ssym, esym;
533         Elf_Dyn         *dp;
534         Elf_Addr        adp;
535         Elf_Addr        ctors;
536         int             ndp;
537         int             symstrindex;
538         int             symtabindex;
539         Elf_Size        size;
540         u_int           fpcopy;
541         Elf_Sym         sym;
542         Elf_Addr        p_start, p_end;
543
544         dp = NULL;
545         shdr = NULL;
546         ret = 0;
547         firstaddr = lastaddr = 0;
548         ehdr = ef->ehdr;
549 #ifdef __powerpc__
550         if (ef->kernel) {
551 #else
552         if (ehdr->e_type == ET_EXEC) {
553 #endif
554 #if defined(__i386__) || defined(__amd64__)
555 #if __ELF_WORD_SIZE == 64
556                 /* x86_64 relocates after locore */
557                 off = - (off & 0xffffffffff000000ull);
558 #else
559                 /* i386 relocates after locore */
560                 off = - (off & 0xff000000u);
561 #endif
562 #elif defined(__powerpc__)
563                 /*
564                  * On the purely virtual memory machines like e500, the kernel
565                  * is linked against its final VA range, which is most often
566                  * not available at the loader stage, but only after kernel
567                  * initializes and completes its VM settings. In such cases we
568                  * cannot use p_vaddr field directly to load ELF segments, but
569                  * put them at some 'load-time' locations.
570                  */
571                 if (off & 0xf0000000u) {
572                         off = -(off & 0xf0000000u);
573                         /*
574                          * XXX the physical load address should not be
575                          * hardcoded. Note that the Book-E kernel assumes that
576                          * it's loaded at a 16MB boundary for now...
577                          */
578                         off += 0x01000000;
579                 }
580                 ehdr->e_entry += off;
581                 if (module_verbose >= MODULE_VERBOSE_FULL)
582                         printf("Converted entry 0x%jx\n",
583                             (uintmax_t)ehdr->e_entry);
584
585 #elif defined(__arm__) && !defined(EFI)
586                 /*
587                  * The elf headers in arm kernels specify virtual addresses in
588                  * all header fields, even the ones that should be physical
589                  * addresses.  We assume the entry point is in the first page,
590                  * and masking the page offset will leave us with the virtual
591                  * address the kernel was linked at.  We subtract that from the
592                  * load offset, making 'off' into the value which, when added
593                  * to a virtual address in an elf header, translates it to a
594                  * physical address.  We do the va->pa conversion on the entry
595                  * point address in the header now, so that later we can launch
596                  * the kernel by just jumping to that address.
597                  *
598                  * When booting from UEFI the copyin and copyout functions
599                  * handle adjusting the location relative to the first virtual
600                  * address.  Because of this there is no need to adjust the
601                  * offset or entry point address as these will both be handled
602                  * by the efi code.
603                  */
604                 off -= ehdr->e_entry & ~PAGE_MASK;
605                 ehdr->e_entry += off;
606                 if (module_verbose >= MODULE_VERBOSE_FULL)
607                         printf("ehdr->e_entry 0x%jx, va<->pa off %llx\n",
608                             (uintmax_t)ehdr->e_entry, off);
609 #else
610                 off = 0;        /* other archs use direct mapped kernels */
611 #endif
612         }
613         ef->off = off;
614
615         if (ef->kernel)
616                 __elfN(relocation_offset) = off;
617
618         if ((ehdr->e_phoff + ehdr->e_phnum * sizeof(*phdr)) > ef->firstlen) {
619                 printf("elf" __XSTRING(__ELF_WORD_SIZE)
620                     "_loadimage: program header not within first page\n");
621                 goto out;
622         }
623         phdr = (Elf_Phdr *)(ef->firstpage + ehdr->e_phoff);
624
625         for (i = 0; i < ehdr->e_phnum; i++) {
626                 if (elf_program_header_convert(ehdr, phdr))
627                         continue;
628
629                 /* We want to load PT_LOAD segments only.. */
630                 if (phdr[i].p_type != PT_LOAD)
631                         continue;
632
633                 if (module_verbose >= MODULE_VERBOSE_FULL) {
634                         printf("Segment: 0x%lx@0x%lx -> 0x%lx-0x%lx",
635                             (long)phdr[i].p_filesz, (long)phdr[i].p_offset,
636                             (long)(phdr[i].p_vaddr + off),
637                             (long)(phdr[i].p_vaddr + off + phdr[i].p_memsz - 1));
638                 } else if (module_verbose > MODULE_VERBOSE_SILENT) {
639                         if ((phdr[i].p_flags & PF_W) == 0) {
640                                 printf("text=0x%lx ", (long)phdr[i].p_filesz);
641                         } else {
642                                 printf("data=0x%lx", (long)phdr[i].p_filesz);
643                                 if (phdr[i].p_filesz < phdr[i].p_memsz)
644                                         printf("+0x%lx", (long)(phdr[i].p_memsz -
645                                                 phdr[i].p_filesz));
646                                 printf(" ");
647                         }
648                 }
649                 fpcopy = 0;
650                 if (ef->firstlen > phdr[i].p_offset) {
651                         fpcopy = ef->firstlen - phdr[i].p_offset;
652                         archsw.arch_copyin(ef->firstpage + phdr[i].p_offset,
653                             phdr[i].p_vaddr + off, fpcopy);
654                 }
655                 if (phdr[i].p_filesz > fpcopy) {
656                         if (kern_pread(VECTX_HANDLE(ef),
657                             phdr[i].p_vaddr + off + fpcopy,
658                             phdr[i].p_filesz - fpcopy,
659                             phdr[i].p_offset + fpcopy) != 0) {
660                                 printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
661                                     "_loadimage: read failed\n");
662                                 goto out;
663                         }
664                 }
665                 /* clear space from oversized segments; eg: bss */
666                 if (phdr[i].p_filesz < phdr[i].p_memsz) {
667                         if (module_verbose >= MODULE_VERBOSE_FULL) {
668                                 printf(" (bss: 0x%lx-0x%lx)",
669                                     (long)(phdr[i].p_vaddr + off + phdr[i].p_filesz),
670                                     (long)(phdr[i].p_vaddr + off + phdr[i].p_memsz -1));
671                         }       
672                         kern_bzero(phdr[i].p_vaddr + off + phdr[i].p_filesz,
673                             phdr[i].p_memsz - phdr[i].p_filesz);
674                 }
675                 if (module_verbose >= MODULE_VERBOSE_FULL)
676                         printf("\n");
677
678                 if (archsw.arch_loadseg != NULL)
679                         archsw.arch_loadseg(ehdr, phdr + i, off);
680
681                 if (firstaddr == 0 || firstaddr > (phdr[i].p_vaddr + off))
682                         firstaddr = phdr[i].p_vaddr + off;
683                 if (lastaddr == 0 || lastaddr <
684                     (phdr[i].p_vaddr + off + phdr[i].p_memsz))
685                         lastaddr = phdr[i].p_vaddr + off + phdr[i].p_memsz;
686         }
687         lastaddr = roundup(lastaddr, sizeof(long));
688
689         /*
690          * Get the section headers.  We need this for finding the .ctors
691          * section as well as for loading any symbols.  Both may be hard
692          * to do if reading from a .gz file as it involves seeking.  I
693          * think the rule is going to have to be that you must strip a
694          * file to remove symbols before gzipping it.
695          */
696         chunk = (size_t)ehdr->e_shnum * (size_t)ehdr->e_shentsize;
697         if (chunk == 0 || ehdr->e_shoff == 0)
698                 goto nosyms;
699         shdr = alloc_pread(VECTX_HANDLE(ef), ehdr->e_shoff, chunk);
700         if (shdr == NULL) {
701                 printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
702                     "_loadimage: failed to read section headers");
703                 goto nosyms;
704         }
705
706         for (i = 0; i < ehdr->e_shnum; i++)
707                 elf_section_header_convert(ehdr, &shdr[i]);
708
709         file_addmetadata(fp, MODINFOMD_SHDR, chunk, shdr);
710
711         /*
712          * Read the section string table and look for the .ctors section.
713          * We need to tell the kernel where it is so that it can call the
714          * ctors.
715          */
716         chunk = shdr[ehdr->e_shstrndx].sh_size;
717         if (chunk) {
718                 shstr = alloc_pread(VECTX_HANDLE(ef),
719                     shdr[ehdr->e_shstrndx].sh_offset, chunk);
720                 if (shstr) {
721                         for (i = 0; i < ehdr->e_shnum; i++) {
722                                 if (strcmp(shstr + shdr[i].sh_name,
723                                     ".ctors") != 0)
724                                         continue;
725                                 ctors = shdr[i].sh_addr;
726                                 file_addmetadata(fp, MODINFOMD_CTORS_ADDR,
727                                     sizeof(ctors), &ctors);
728                                 size = shdr[i].sh_size;
729                                 file_addmetadata(fp, MODINFOMD_CTORS_SIZE,
730                                     sizeof(size), &size);
731                                 break;
732                         }
733                         free(shstr);
734                 }
735         }
736
737         /*
738          * Now load any symbols.
739          */
740         symtabindex = -1;
741         symstrindex = -1;
742         for (i = 0; i < ehdr->e_shnum; i++) {
743                 if (shdr[i].sh_type != SHT_SYMTAB)
744                         continue;
745                 for (j = 0; j < ehdr->e_phnum; j++) {
746                         if (phdr[j].p_type != PT_LOAD)
747                                 continue;
748                         if (shdr[i].sh_offset >= phdr[j].p_offset &&
749                             (shdr[i].sh_offset + shdr[i].sh_size <=
750                             phdr[j].p_offset + phdr[j].p_filesz)) {
751                                 shdr[i].sh_offset = 0;
752                                 shdr[i].sh_size = 0;
753                                 break;
754                         }
755                 }
756                 if (shdr[i].sh_offset == 0 || shdr[i].sh_size == 0)
757                         continue;       /* alread loaded in a PT_LOAD above */
758                 /* Save it for loading below */
759                 symtabindex = i;
760                 symstrindex = shdr[i].sh_link;
761         }
762         if (symtabindex < 0 || symstrindex < 0)
763                 goto nosyms;
764
765         /* Ok, committed to a load. */
766         if (module_verbose >= MODULE_VERBOSE_FULL)
767                 printf("syms=[");
768         ssym = lastaddr;
769         for (i = symtabindex; i >= 0; i = symstrindex) {
770                 char    *secname;
771
772                 switch(shdr[i].sh_type) {
773                 case SHT_SYMTAB:                /* Symbol table */
774                         secname = "symtab";
775                         break;
776                 case SHT_STRTAB:                /* String table */
777                         secname = "strtab";
778                         break;
779                 default:
780                         secname = "WHOA!!";
781                         break;
782                 }
783                 size = shdr[i].sh_size;
784
785                 archsw.arch_copyin(&size, lastaddr, sizeof(size));
786                 lastaddr += sizeof(size);
787
788                 if (module_verbose >= MODULE_VERBOSE_FULL) {
789                         printf("\n%s: 0x%jx@0x%jx -> 0x%jx-0x%jx", secname,
790                             (uintmax_t)shdr[i].sh_size, (uintmax_t)shdr[i].sh_offset,
791                             (uintmax_t)lastaddr,
792                             (uintmax_t)(lastaddr + shdr[i].sh_size));
793                 } else if (module_verbose > MODULE_VERBOSE_SILENT) {
794                         if (i == symstrindex)
795                                 printf("+");
796                         printf("0x%lx+0x%lx", (long)sizeof(size), (long)size);
797                 }
798                 if (VECTX_LSEEK(VECTX_HANDLE(ef), (off_t)shdr[i].sh_offset, SEEK_SET) == -1) {
799                         printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
800                            "_loadimage: could not seek for symbols - skipped!");
801                         lastaddr = ssym;
802                         ssym = 0;
803                         goto nosyms;
804                 }
805                 result = archsw.arch_readin(VECTX_HANDLE(ef), lastaddr, shdr[i].sh_size);
806                 if (result < 0 || (size_t)result != shdr[i].sh_size) {
807                         printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
808                             "_loadimage: could not read symbols - skipped! "
809                             "(%ju != %ju)", (uintmax_t)result,
810                             (uintmax_t)shdr[i].sh_size);
811                         lastaddr = ssym;
812                         ssym = 0;
813                         goto nosyms;
814                 }
815                 /* Reset offsets relative to ssym */
816                 lastaddr += shdr[i].sh_size;
817                 lastaddr = roundup(lastaddr, sizeof(size));
818                 if (i == symtabindex)
819                         symtabindex = -1;
820                 else if (i == symstrindex)
821                         symstrindex = -1;
822         }
823         esym = lastaddr;
824         if (module_verbose >= MODULE_VERBOSE_FULL)
825                 printf("]");
826
827         file_addmetadata(fp, MODINFOMD_SSYM, sizeof(ssym), &ssym);
828         file_addmetadata(fp, MODINFOMD_ESYM, sizeof(esym), &esym);
829
830 nosyms:
831         if (module_verbose > MODULE_VERBOSE_SILENT)
832                 printf("\n");
833
834         ret = lastaddr - firstaddr;
835         fp->f_addr = firstaddr;
836
837         php = NULL;
838         for (i = 0; i < ehdr->e_phnum; i++) {
839                 if (phdr[i].p_type == PT_DYNAMIC) {
840                         php = phdr + i;
841                         adp = php->p_vaddr;
842                         file_addmetadata(fp, MODINFOMD_DYNAMIC, sizeof(adp),
843                             &adp);
844                         break;
845                 }
846         }
847
848         if (php == NULL) /* this is bad, we cannot get to symbols or _DYNAMIC */
849                 goto out;
850
851         ndp = php->p_filesz / sizeof(Elf_Dyn);
852         if (ndp == 0)
853                 goto out;
854         dp = malloc(php->p_filesz);
855         if (dp == NULL)
856                 goto out;
857         archsw.arch_copyout(php->p_vaddr + off, dp, php->p_filesz);
858
859         ef->strsz = 0;
860         for (i = 0; i < ndp; i++) {
861                 if (dp[i].d_tag == 0)
862                         break;
863                 switch (dp[i].d_tag) {
864                 case DT_HASH:
865                         ef->hashtab =
866                             (Elf_Hashelt*)(uintptr_t)(dp[i].d_un.d_ptr + off);
867                         break;
868                 case DT_STRTAB:
869                         ef->strtab =
870                             (char *)(uintptr_t)(dp[i].d_un.d_ptr + off);
871                         break;
872                 case DT_STRSZ:
873                         ef->strsz = dp[i].d_un.d_val;
874                         break;
875                 case DT_SYMTAB:
876                         ef->symtab =
877                             (Elf_Sym *)(uintptr_t)(dp[i].d_un.d_ptr + off);
878                         break;
879                 case DT_REL:
880                         ef->rel =
881                             (Elf_Rel *)(uintptr_t)(dp[i].d_un.d_ptr + off);
882                         break;
883                 case DT_RELSZ:
884                         ef->relsz = dp[i].d_un.d_val;
885                         break;
886                 case DT_RELA:
887                         ef->rela =
888                             (Elf_Rela *)(uintptr_t)(dp[i].d_un.d_ptr + off);
889                         break;
890                 case DT_RELASZ:
891                         ef->relasz = dp[i].d_un.d_val;
892                         break;
893                 default:
894                         break;
895                 }
896         }
897         if (ef->hashtab == NULL || ef->symtab == NULL ||
898             ef->strtab == NULL || ef->strsz == 0)
899                 goto out;
900         COPYOUT(ef->hashtab, &ef->nbuckets, sizeof(ef->nbuckets));
901         COPYOUT(ef->hashtab + 1, &ef->nchains, sizeof(ef->nchains));
902         ef->buckets = ef->hashtab + 2;
903         ef->chains = ef->buckets + ef->nbuckets;
904
905         if (__elfN(lookup_symbol)(ef, "__start_set_modmetadata_set", &sym,
906             STT_NOTYPE) != 0)
907                 return 0;
908         p_start = sym.st_value + ef->off;
909         if (__elfN(lookup_symbol)(ef, "__stop_set_modmetadata_set", &sym,
910             STT_NOTYPE) != 0)
911                 return 0;
912         p_end = sym.st_value + ef->off;
913
914         if (__elfN(parse_modmetadata)(fp, ef, p_start, p_end) == 0)
915                 goto out;
916
917         if (ef->kernel)         /* kernel must not depend on anything */
918                 goto out;
919
920 out:
921         if (dp)
922                 free(dp);
923         if (shdr)
924                 free(shdr);
925         return ret;
926 }
927
928 static char invalid_name[] = "bad";
929
930 char *
931 fake_modname(const char *name)
932 {
933         const char *sp, *ep;
934         char *fp;
935         size_t len;
936
937         sp = strrchr(name, '/');
938         if (sp)
939                 sp++;
940         else
941                 sp = name;
942
943         ep = strrchr(sp, '.');
944         if (ep == NULL) {
945                 ep = sp + strlen(sp);
946         }
947         if (ep == sp) {
948                 sp = invalid_name;
949                 ep = invalid_name + sizeof(invalid_name) - 1;
950         }
951
952         len = ep - sp;
953         fp = malloc(len + 1);
954         if (fp == NULL)
955                 return NULL;
956         memcpy(fp, sp, len);
957         fp[len] = '\0';
958         return fp;
959 }
960
961 #if (defined(__i386__) || defined(__powerpc__)) && __ELF_WORD_SIZE == 64
962 struct mod_metadata64 {
963         int             md_version;     /* structure version MDTV_* */
964         int             md_type;        /* type of entry MDT_* */
965         uint64_t        md_data;        /* specific data */
966         uint64_t        md_cval;        /* common string label */
967 };
968 #endif
969 #if defined(__amd64__) && __ELF_WORD_SIZE == 32
970 struct mod_metadata32 {
971         int             md_version;     /* structure version MDTV_* */
972         int             md_type;        /* type of entry MDT_* */
973         uint32_t        md_data;        /* specific data */
974         uint32_t        md_cval;        /* common string label */
975 };
976 #endif
977
978 int
979 __elfN(load_modmetadata)(struct preloaded_file *fp, uint64_t dest)
980 {
981         struct elf_file          ef;
982         int                      err, i, j;
983         Elf_Shdr                *sh_meta, *shdr = NULL;
984         Elf_Shdr                *sh_data[2];
985         char                    *shstrtab = NULL;
986         size_t                   size;
987         Elf_Addr                 p_start, p_end;
988
989         bzero(&ef, sizeof(struct elf_file));
990         ef.fd = -1;
991
992         err = __elfN(load_elf_header)(fp->f_name, &ef);
993         if (err != 0)
994                 goto out;
995
996         if (ef.kernel == 1 || ef.ehdr->e_type == ET_EXEC) {
997                 ef.kernel = 1;
998         } else if (ef.ehdr->e_type != ET_DYN) {
999                 err = EFTYPE;
1000                 goto out;
1001         }
1002
1003         size = (size_t)ef.ehdr->e_shnum * (size_t)ef.ehdr->e_shentsize;
1004         shdr = alloc_pread(VECTX_HANDLE(&ef), ef.ehdr->e_shoff, size);
1005         if (shdr == NULL) {
1006                 err = ENOMEM;
1007                 goto out;
1008         }
1009
1010         /* Load shstrtab. */
1011         shstrtab = alloc_pread(VECTX_HANDLE(&ef), shdr[ef.ehdr->e_shstrndx].sh_offset,
1012             shdr[ef.ehdr->e_shstrndx].sh_size);
1013         if (shstrtab == NULL) {
1014                 printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
1015                     "load_modmetadata: unable to load shstrtab\n");
1016                 err = EFTYPE;
1017                 goto out;
1018         }
1019
1020         /* Find set_modmetadata_set and data sections. */
1021         sh_data[0] = sh_data[1] = sh_meta = NULL;
1022         for (i = 0, j = 0; i < ef.ehdr->e_shnum; i++) {
1023                 if (strcmp(&shstrtab[shdr[i].sh_name],
1024                     "set_modmetadata_set") == 0) {
1025                         sh_meta = &shdr[i];
1026                 }
1027                 if ((strcmp(&shstrtab[shdr[i].sh_name], ".data") == 0) ||
1028                     (strcmp(&shstrtab[shdr[i].sh_name], ".rodata") == 0)) {
1029                         sh_data[j++] = &shdr[i];
1030                 }
1031         }
1032         if (sh_meta == NULL || sh_data[0] == NULL || sh_data[1] == NULL) {
1033                 printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
1034     "load_modmetadata: unable to find set_modmetadata_set or data sections\n");
1035                 err = EFTYPE;
1036                 goto out;
1037         }
1038
1039         /* Load set_modmetadata_set into memory */
1040         err = kern_pread(VECTX_HANDLE(&ef), dest, sh_meta->sh_size, sh_meta->sh_offset);
1041         if (err != 0) {
1042                 printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
1043     "load_modmetadata: unable to load set_modmetadata_set: %d\n", err);
1044                 goto out;
1045         }
1046         p_start = dest;
1047         p_end = dest + sh_meta->sh_size;
1048         dest += sh_meta->sh_size;
1049
1050         /* Load data sections into memory. */
1051         err = kern_pread(VECTX_HANDLE(&ef), dest, sh_data[0]->sh_size,
1052             sh_data[0]->sh_offset);
1053         if (err != 0) {
1054                 printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
1055                     "load_modmetadata: unable to load data: %d\n", err);
1056                 goto out;
1057         }
1058
1059         /*
1060          * We have to increment the dest, so that the offset is the same into
1061          * both the .rodata and .data sections.
1062          */
1063         ef.off = -(sh_data[0]->sh_addr - dest);
1064         dest += (sh_data[1]->sh_addr - sh_data[0]->sh_addr);
1065
1066         err = kern_pread(VECTX_HANDLE(&ef), dest, sh_data[1]->sh_size,
1067             sh_data[1]->sh_offset);
1068         if (err != 0) {
1069                 printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
1070                     "load_modmetadata: unable to load data: %d\n", err);
1071                 goto out;
1072         }
1073
1074         err = __elfN(parse_modmetadata)(fp, &ef, p_start, p_end);
1075         if (err != 0) {
1076                 printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
1077                     "load_modmetadata: unable to parse metadata: %d\n", err);
1078                 goto out;
1079         }
1080
1081 out:
1082         if (shstrtab != NULL)
1083                 free(shstrtab);
1084         if (shdr != NULL)
1085                 free(shdr);
1086         if (ef.firstpage != NULL)
1087                 free(ef.firstpage);
1088         if (ef.fd != -1) {
1089 #ifdef LOADER_VERIEXEC_VECTX
1090                 if (!err && ef.vctx) {
1091                         int verror;
1092
1093                         verror = vectx_close(ef.vctx, VE_MUST, __func__);
1094                         if (verror) {
1095                                 err = EAUTH;
1096                                 file_discard(fp);
1097                         }
1098                 }
1099 #endif
1100                 close(ef.fd);
1101         }
1102         return (err);
1103 }
1104
1105 int
1106 __elfN(parse_modmetadata)(struct preloaded_file *fp, elf_file_t ef,
1107     Elf_Addr p_start, Elf_Addr p_end)
1108 {
1109         struct mod_metadata md;
1110 #if (defined(__i386__) || defined(__powerpc__)) && __ELF_WORD_SIZE == 64
1111         struct mod_metadata64 md64;
1112 #elif defined(__amd64__) && __ELF_WORD_SIZE == 32
1113         struct mod_metadata32 md32;
1114 #endif
1115         struct mod_depend *mdepend;
1116         struct mod_version mver;
1117         char *s;
1118         int error, modcnt, minfolen;
1119         Elf_Addr v, p;
1120
1121         modcnt = 0;
1122         p = p_start;
1123         while (p < p_end) {
1124                 COPYOUT(p, &v, sizeof(v));
1125                 error = __elfN(reloc_ptr)(fp, ef, p, &v, sizeof(v));
1126                 if (error == EOPNOTSUPP)
1127                         v += ef->off;
1128                 else if (error != 0)
1129                         return (error);
1130 #if (defined(__i386__) || defined(__powerpc__)) && __ELF_WORD_SIZE == 64
1131                 COPYOUT(v, &md64, sizeof(md64));
1132                 error = __elfN(reloc_ptr)(fp, ef, v, &md64, sizeof(md64));
1133                 if (error == EOPNOTSUPP) {
1134                         md64.md_cval += ef->off;
1135                         md64.md_data += ef->off;
1136                 } else if (error != 0)
1137                         return (error);
1138                 md.md_version = md64.md_version;
1139                 md.md_type = md64.md_type;
1140                 md.md_cval = (const char *)(uintptr_t)md64.md_cval;
1141                 md.md_data = (void *)(uintptr_t)md64.md_data;
1142 #elif defined(__amd64__) && __ELF_WORD_SIZE == 32
1143                 COPYOUT(v, &md32, sizeof(md32));
1144                 error = __elfN(reloc_ptr)(fp, ef, v, &md32, sizeof(md32));
1145                 if (error == EOPNOTSUPP) {
1146                         md32.md_cval += ef->off;
1147                         md32.md_data += ef->off;
1148                 } else if (error != 0)
1149                         return (error);
1150                 md.md_version = md32.md_version;
1151                 md.md_type = md32.md_type;
1152                 md.md_cval = (const char *)(uintptr_t)md32.md_cval;
1153                 md.md_data = (void *)(uintptr_t)md32.md_data;
1154 #else
1155                 COPYOUT(v, &md, sizeof(md));
1156                 error = __elfN(reloc_ptr)(fp, ef, v, &md, sizeof(md));
1157                 if (error == EOPNOTSUPP) {
1158                         md.md_cval += ef->off;
1159                         md.md_data = (void *)((uintptr_t)md.md_data +
1160                             (uintptr_t)ef->off);
1161                 } else if (error != 0)
1162                         return (error);
1163 #endif
1164                 p += sizeof(Elf_Addr);
1165                 switch(md.md_type) {
1166                 case MDT_DEPEND:
1167                         if (ef->kernel) /* kernel must not depend on anything */
1168                                 break;
1169                         s = strdupout((vm_offset_t)md.md_cval);
1170                         minfolen = sizeof(*mdepend) + strlen(s) + 1;
1171                         mdepend = malloc(minfolen);
1172                         if (mdepend == NULL)
1173                                 return ENOMEM;
1174                         COPYOUT((vm_offset_t)md.md_data, mdepend,
1175                             sizeof(*mdepend));
1176                         strcpy((char*)(mdepend + 1), s);
1177                         free(s);
1178                         file_addmetadata(fp, MODINFOMD_DEPLIST, minfolen,
1179                             mdepend);
1180                         free(mdepend);
1181                         break;
1182                 case MDT_VERSION:
1183                         s = strdupout((vm_offset_t)md.md_cval);
1184                         COPYOUT((vm_offset_t)md.md_data, &mver, sizeof(mver));
1185                         file_addmodule(fp, s, mver.mv_version, NULL);
1186                         free(s);
1187                         modcnt++;
1188                         break;
1189                 }
1190         }
1191         if (modcnt == 0) {
1192                 s = fake_modname(fp->f_name);
1193                 file_addmodule(fp, s, 1, NULL);
1194                 free(s);
1195         }
1196         return 0;
1197 }
1198
1199 static unsigned long
1200 elf_hash(const char *name)
1201 {
1202         const unsigned char *p = (const unsigned char *) name;
1203         unsigned long h = 0;
1204         unsigned long g;
1205
1206         while (*p != '\0') {
1207                 h = (h << 4) + *p++;
1208                 if ((g = h & 0xf0000000) != 0)
1209                         h ^= g >> 24;
1210                 h &= ~g;
1211         }
1212         return h;
1213 }
1214
1215 static const char __elfN(bad_symtable)[] = "elf" __XSTRING(__ELF_WORD_SIZE)
1216     "_lookup_symbol: corrupt symbol table\n";
1217 int
1218 __elfN(lookup_symbol)(elf_file_t ef, const char* name, Elf_Sym *symp,
1219     unsigned char type)
1220 {
1221         Elf_Hashelt symnum;
1222         Elf_Sym sym;
1223         char *strp;
1224         unsigned long hash;
1225
1226         if (ef->nbuckets == 0) {
1227                 printf(__elfN(bad_symtable));
1228                 return ENOENT;
1229         }
1230
1231         hash = elf_hash(name);
1232         COPYOUT(&ef->buckets[hash % ef->nbuckets], &symnum, sizeof(symnum));
1233
1234         while (symnum != STN_UNDEF) {
1235                 if (symnum >= ef->nchains) {
1236                         printf(__elfN(bad_symtable));
1237                         return ENOENT;
1238                 }
1239
1240                 COPYOUT(ef->symtab + symnum, &sym, sizeof(sym));
1241                 if (sym.st_name == 0) {
1242                         printf(__elfN(bad_symtable));
1243                         return ENOENT;
1244                 }
1245
1246                 strp = strdupout((vm_offset_t)(ef->strtab + sym.st_name));
1247                 if (strcmp(name, strp) == 0) {
1248                         free(strp);
1249                         if (sym.st_shndx != SHN_UNDEF ||
1250                             (sym.st_value != 0 &&
1251                             ELF_ST_TYPE(sym.st_info) == type)) {
1252                                 *symp = sym;
1253                                 return 0;
1254                         }
1255                         return ENOENT;
1256                 }
1257                 free(strp);
1258                 COPYOUT(&ef->chains[symnum], &symnum, sizeof(symnum));
1259         }
1260         return ENOENT;
1261 }
1262
1263 /*
1264  * Apply any intra-module relocations to the value. p is the load address
1265  * of the value and val/len is the value to be modified. This does NOT modify
1266  * the image in-place, because this is done by kern_linker later on.
1267  *
1268  * Returns EOPNOTSUPP if no relocation method is supplied.
1269  */
1270 static int
1271 __elfN(reloc_ptr)(struct preloaded_file *mp, elf_file_t ef,
1272     Elf_Addr p, void *val, size_t len)
1273 {
1274         size_t n;
1275         Elf_Rela a;
1276         Elf_Rel r;
1277         int error;
1278
1279         /*
1280          * The kernel is already relocated, but we still want to apply
1281          * offset adjustments.
1282          */
1283         if (ef->kernel)
1284                 return (EOPNOTSUPP);
1285
1286         for (n = 0; n < ef->relsz / sizeof(r); n++) {
1287                 COPYOUT(ef->rel + n, &r, sizeof(r));
1288
1289                 error = __elfN(reloc)(ef, __elfN(symaddr), &r, ELF_RELOC_REL,
1290                     ef->off, p, val, len);
1291                 if (error != 0)
1292                         return (error);
1293         }
1294         for (n = 0; n < ef->relasz / sizeof(a); n++) {
1295                 COPYOUT(ef->rela + n, &a, sizeof(a));
1296
1297                 error = __elfN(reloc)(ef, __elfN(symaddr), &a, ELF_RELOC_RELA,
1298                     ef->off, p, val, len);
1299                 if (error != 0)
1300                         return (error);
1301         }
1302
1303         return (0);
1304 }
1305
1306 static Elf_Addr
1307 __elfN(symaddr)(struct elf_file *ef, Elf_Size symidx)
1308 {
1309
1310         /* Symbol lookup by index not required here. */
1311         return (0);
1312 }