xref: /dragonfly/sys/kern/link_elf.c (revision 135d05a574d45cd0f89e3c73b275766479ea23b5)
1 /*-
2  * Copyright (c) 1998 Doug Rabson
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $FreeBSD: src/sys/kern/link_elf.c,v 1.24 1999/12/24 15:33:36 bde Exp $
27  */
28 
29 #include <sys/param.h>
30 #include <sys/kernel.h>
31 #include <sys/systm.h>
32 #include <sys/malloc.h>
33 #include <sys/proc.h>
34 #include <sys/nlookup.h>
35 #include <sys/fcntl.h>
36 #include <sys/vnode.h>
37 #include <sys/linker.h>
38 #include <machine/elf.h>
39 
40 #include <vm/vm.h>
41 #include <vm/vm_param.h>
42 #include <vm/vm_zone.h>
43 #include <sys/lock.h>
44 #include <vm/pmap.h>
45 #include <vm/vm_map.h>
46 
47 #if defined(__x86_64__) && defined(_KERNEL_VIRTUAL)
48 #include <stdio.h>
49 #endif
50 
51 static int          link_elf_preload_file(const char *, linker_file_t *);
52 static int          link_elf_preload_finish(linker_file_t);
53 static int          link_elf_load_file(const char*, linker_file_t*);
54 static int          link_elf_lookup_symbol(linker_file_t, const char*,
55                                                c_linker_sym_t*);
56 static int          link_elf_symbol_values(linker_file_t, c_linker_sym_t, linker_symval_t*);
57 static int          link_elf_search_symbol(linker_file_t, caddr_t value,
58                                                c_linker_sym_t* sym, long* diffp);
59 
60 static void         link_elf_unload_file(linker_file_t);
61 static void         link_elf_unload_module(linker_file_t);
62 static int          link_elf_lookup_set(linker_file_t, const char *,
63                               void ***, void ***, int *);
64 static int          elf_lookup(linker_file_t lf, Elf_Size symidx, int deps, Elf_Addr *);
65 static void link_elf_reloc_local(linker_file_t lf);
66 
67 static struct linker_class_ops link_elf_class_ops = {
68     link_elf_load_file,
69     link_elf_preload_file,
70 };
71 
72 static struct linker_file_ops link_elf_file_ops = {
73     .lookup_symbol = link_elf_lookup_symbol,
74     .symbol_values = link_elf_symbol_values,
75     .search_symbol = link_elf_search_symbol,
76     .unload = link_elf_unload_file,
77     .lookup_set = link_elf_lookup_set
78 };
79 
80 static struct linker_file_ops link_elf_module_ops = {
81     .lookup_symbol = link_elf_lookup_symbol,
82     .symbol_values = link_elf_symbol_values,
83     .search_symbol = link_elf_search_symbol,
84     .preload_finish = link_elf_preload_finish,
85     .unload = link_elf_unload_module,
86     .lookup_set = link_elf_lookup_set,
87 };
88 
89 typedef struct elf_file {
90     caddr_t                   address;  /* Relocation address */
91     const Elf_Dyn*  dynamic;  /* Symbol table etc. */
92     Elf_Hashelt               nbuckets; /* DT_HASH info */
93     Elf_Hashelt               nchains;
94     const Elf_Hashelt*        buckets;
95     const Elf_Hashelt*        chains;
96     caddr_t                   hash;
97     caddr_t                   strtab;             /* DT_STRTAB */
98     int                       strsz;              /* DT_STRSZ */
99     const Elf_Sym*  symtab;             /* DT_SYMTAB */
100     Elf_Addr*                 got;                /* DT_PLTGOT */
101     const Elf_Rel*  pltrel;             /* DT_JMPREL */
102     int                       pltrelsize;         /* DT_PLTRELSZ */
103     const Elf_Rela* pltrela;  /* DT_JMPREL */
104     int                       pltrelasize;        /* DT_PLTRELSZ */
105     const Elf_Rel*  rel;                /* DT_REL */
106     int                       relsize;  /* DT_RELSZ */
107     const Elf_Rela* rela;               /* DT_RELA */
108     int                       relasize; /* DT_RELASZ */
109     caddr_t                   modptr;
110     const Elf_Sym*  ddbsymtab;          /* The symbol table we are using */
111     long            ddbsymcnt;          /* Number of symbols */
112     caddr_t                   ddbstrtab;          /* String table */
113     long            ddbstrcnt;          /* number of bytes in string table */
114     caddr_t                   symbase;  /* malloc'ed symbold base */
115     caddr_t                   strbase;  /* malloc'ed string base */
116 } *elf_file_t;
117 
118 static int                    parse_dynamic(linker_file_t lf);
119 static int                    relocate_file(linker_file_t lf);
120 static int                    parse_module_symbols(linker_file_t lf);
121 
122 /*
123  * The kernel symbol table starts here.
124  */
125 extern struct _dynamic _DYNAMIC;
126 
127 static void
link_elf_init(void * arg)128 link_elf_init(void* arg)
129 {
130     Elf_Dyn         *dp;
131     caddr_t         modptr, baseptr, sizeptr;
132     elf_file_t      ef;
133     char  *modname;
134 
135 #if ELF_TARG_CLASS == ELFCLASS32
136     linker_add_class("elf32", NULL, &link_elf_class_ops);
137 #else
138     linker_add_class("elf64", NULL, &link_elf_class_ops);
139 #endif
140 
141     dp = (Elf_Dyn*) &_DYNAMIC;
142     if (dp) {
143           ef = kmalloc(sizeof(struct elf_file), M_LINKER, M_INTWAIT | M_ZERO);
144           ef->address = NULL;
145           ef->dynamic = dp;
146           modname = NULL;
147           modptr = preload_search_by_type("elf kernel");
148           if (modptr)
149               modname = (char *)preload_search_info(modptr, MODINFO_NAME);
150           if (modname == NULL)
151               modname = "kernel";
152           linker_kernel_file = linker_make_file(modname, ef, &link_elf_file_ops);
153           if (linker_kernel_file == NULL)
154               panic("link_elf_init: Can't create linker structures for kernel");
155           parse_dynamic(linker_kernel_file);
156 #if defined(__x86_64__) && defined(_KERNEL_VIRTUAL)
157           fprintf(stderr, "WARNING: KERNBASE being used\n");
158 #endif
159           linker_kernel_file->address = (caddr_t) KERNBASE;
160           linker_kernel_file->size = -(intptr_t)linker_kernel_file->address;
161 
162           if (modptr) {
163               ef->modptr = modptr;
164               baseptr = preload_search_info(modptr, MODINFO_ADDR);
165               if (baseptr)
166                     linker_kernel_file->address = *(caddr_t *)baseptr;
167               sizeptr = preload_search_info(modptr, MODINFO_SIZE);
168               if (sizeptr)
169                     linker_kernel_file->size = *(size_t *)sizeptr;
170           }
171           parse_module_symbols(linker_kernel_file);
172           linker_current_file = linker_kernel_file;
173           linker_kernel_file->flags |= LINKER_FILE_LINKED;
174     }
175 }
176 
177 SYSINIT(link_elf, SI_BOOT2_KLD, SI_ORDER_SECOND, link_elf_init, 0);
178 
179 static int
parse_module_symbols(linker_file_t lf)180 parse_module_symbols(linker_file_t lf)
181 {
182     elf_file_t ef = lf->priv;
183     caddr_t         pointer;
184     caddr_t         ssym, esym, base;
185     caddr_t         strtab;
186     int             strcnt;
187     Elf_Sym*        symtab;
188     int             symcnt;
189 
190     if (ef->modptr == NULL)
191           return 0;
192     pointer = preload_search_info(ef->modptr, MODINFO_METADATA|MODINFOMD_SSYM);
193     if (pointer == NULL)
194           return 0;
195     ssym = *(caddr_t *)pointer;
196     pointer = preload_search_info(ef->modptr, MODINFO_METADATA|MODINFOMD_ESYM);
197     if (pointer == NULL)
198           return 0;
199     esym = *(caddr_t *)pointer;
200 
201     base = ssym;
202 
203     symcnt = *(long *)base;
204     base += sizeof(long);
205     symtab = (Elf_Sym *)base;
206     base += roundup(symcnt, sizeof(long));
207 
208     if (base > esym || base < ssym) {
209           kprintf("Symbols are corrupt!\n");
210           return EINVAL;
211     }
212 
213     strcnt = *(long *)base;
214     base += sizeof(long);
215     strtab = base;
216     base += roundup(strcnt, sizeof(long));
217 
218     if (base > esym || base < ssym) {
219           kprintf("Symbols are corrupt!\n");
220           return EINVAL;
221     }
222 
223     ef->ddbsymtab = symtab;
224     ef->ddbsymcnt = symcnt / sizeof(Elf_Sym);
225     ef->ddbstrtab = strtab;
226     ef->ddbstrcnt = strcnt;
227 
228     return 0;
229 }
230 
231 static int
parse_dynamic(linker_file_t lf)232 parse_dynamic(linker_file_t lf)
233 {
234     elf_file_t ef = lf->priv;
235     const Elf_Dyn *dp;
236     int plttype = DT_REL;
237 
238     for (dp = ef->dynamic; dp->d_tag != DT_NULL; dp++) {
239           switch (dp->d_tag) {
240           case DT_HASH:
241           {
242               /* From src/libexec/rtld-elf/rtld.c */
243               const Elf_Hashelt *hashtab = (const Elf_Hashelt *)
244                     (ef->address + dp->d_un.d_ptr);
245               ef->nbuckets = hashtab[0];
246               ef->nchains = hashtab[1];
247               ef->buckets = hashtab + 2;
248               ef->chains = ef->buckets + ef->nbuckets;
249               break;
250           }
251           case DT_STRTAB:
252               ef->strtab = (caddr_t) (ef->address + dp->d_un.d_ptr);
253               break;
254           case DT_STRSZ:
255               ef->strsz = dp->d_un.d_val;
256               break;
257           case DT_SYMTAB:
258               ef->symtab = (Elf_Sym*) (ef->address + dp->d_un.d_ptr);
259               break;
260           case DT_SYMENT:
261               if (dp->d_un.d_val != sizeof(Elf_Sym))
262                     return ENOEXEC;
263               break;
264           case DT_PLTGOT:
265               ef->got = (Elf_Addr *) (ef->address + dp->d_un.d_ptr);
266               break;
267           case DT_REL:
268               ef->rel = (const Elf_Rel *) (ef->address + dp->d_un.d_ptr);
269               break;
270           case DT_RELSZ:
271               ef->relsize = dp->d_un.d_val;
272               break;
273           case DT_RELENT:
274               if (dp->d_un.d_val != sizeof(Elf_Rel))
275                     return ENOEXEC;
276               break;
277           case DT_JMPREL:
278               ef->pltrel = (const Elf_Rel *) (ef->address + dp->d_un.d_ptr);
279               break;
280           case DT_PLTRELSZ:
281               ef->pltrelsize = dp->d_un.d_val;
282               break;
283           case DT_RELA:
284               ef->rela = (const Elf_Rela *) (ef->address + dp->d_un.d_ptr);
285               break;
286           case DT_RELASZ:
287               ef->relasize = dp->d_un.d_val;
288               break;
289           case DT_RELAENT:
290               if (dp->d_un.d_val != sizeof(Elf_Rela))
291                     return ENOEXEC;
292               break;
293           case DT_PLTREL:
294               plttype = dp->d_un.d_val;
295               if (plttype != DT_REL && plttype != DT_RELA)
296                     return ENOEXEC;
297               break;
298           }
299     }
300 
301     if (plttype == DT_RELA) {
302           ef->pltrela = (const Elf_Rela *) ef->pltrel;
303           ef->pltrel = NULL;
304           ef->pltrelasize = ef->pltrelsize;
305           ef->pltrelsize = 0;
306     }
307 
308     ef->ddbsymtab = ef->symtab;
309     ef->ddbsymcnt = ef->nchains;
310     ef->ddbstrtab = ef->strtab;
311     ef->ddbstrcnt = ef->strsz;
312 
313     return 0;
314 }
315 
316 static void
link_elf_error(const char * s)317 link_elf_error(const char *s)
318 {
319     kprintf("kldload: %s\n", s);
320 }
321 
322 static int
link_elf_preload_file(const char * filename,linker_file_t * result)323 link_elf_preload_file(const char *filename, linker_file_t *result)
324 {
325     caddr_t                   modptr, baseptr, sizeptr, dynptr;
326     char            *type;
327     elf_file_t                ef;
328     linker_file_t   lf;
329     int                       error;
330     vm_offset_t               dp;
331 
332     /*
333      * Look to see if we have the module preloaded.
334      */
335     modptr = preload_search_by_name(filename);
336     if (modptr == NULL)
337           return ENOENT;
338 
339     /* It's preloaded, check we can handle it and collect information */
340     type = (char *)preload_search_info(modptr, MODINFO_TYPE);
341     baseptr = preload_search_info(modptr, MODINFO_ADDR);
342     sizeptr = preload_search_info(modptr, MODINFO_SIZE);
343     dynptr = preload_search_info(modptr, MODINFO_METADATA|MODINFOMD_DYNAMIC);
344     if (type == NULL ||
345               (strcmp(type, "elf" __XSTRING(__ELF_WORD_SIZE) " module") != 0 &&
346               strcmp(type, "elf module") != 0))
347           return (EFTYPE);
348     if (baseptr == NULL || sizeptr == NULL || dynptr == NULL)
349           return (EINVAL);
350 
351     ef = kmalloc(sizeof(struct elf_file), M_LINKER, M_WAITOK | M_ZERO);
352     ef->modptr = modptr;
353     ef->address = *(caddr_t *)baseptr;
354     dp = (vm_offset_t)ef->address + *(vm_offset_t *)dynptr;
355     ef->dynamic = (Elf_Dyn *)dp;
356     lf = linker_make_file(filename, ef, &link_elf_module_ops);
357     if (lf == NULL) {
358           kfree(ef, M_LINKER);
359           return ENOMEM;
360     }
361     lf->address = ef->address;
362     lf->size = *(size_t *)sizeptr;
363 
364     error = parse_dynamic(lf);
365     if (error) {
366           linker_file_unload(lf);
367           return error;
368     }
369     link_elf_reloc_local(lf);
370     *result = lf;
371     return (0);
372 }
373 
374 static int
link_elf_preload_finish(linker_file_t lf)375 link_elf_preload_finish(linker_file_t lf)
376 {
377     int                       error;
378 
379     error = relocate_file(lf);
380     if (error)
381           return error;
382     parse_module_symbols(lf);
383 
384     return (0);
385 }
386 
387 static int
link_elf_load_file(const char * filename,linker_file_t * result)388 link_elf_load_file(const char* filename, linker_file_t* result)
389 {
390     struct nlookupdata nd;
391     struct thread *td = curthread;      /* XXX */
392     struct proc *p = td->td_proc;
393     struct vnode *vp;
394     Elf_Ehdr *hdr;
395     caddr_t firstpage;
396     int nbytes, i;
397     Elf_Phdr *phdr;
398     Elf_Phdr *phlimit;
399     Elf_Phdr *segs[2];
400     int nsegs;
401     Elf_Phdr *phdyn;
402     caddr_t mapbase;
403     size_t mapsize;
404     Elf_Addr base_vaddr;
405     Elf_Addr base_vlimit;
406     int error = 0;
407     int resid;
408     elf_file_t ef;
409     linker_file_t lf;
410     char *pathname;
411     Elf_Shdr *shdr;
412     int symtabindex;
413     int symstrindex;
414     int symcnt;
415     int strcnt;
416 
417     /* XXX Hack for firmware loading where p == NULL */
418     if (p == NULL) {
419           p = &proc0;
420     }
421 
422     KKASSERT(p != NULL);
423     if (p->p_ucred == NULL) {
424           kprintf("link_elf_load_file: cannot load '%s' from filesystem"
425                     " this early\n", filename);
426           return ENOENT;
427     }
428     shdr = NULL;
429     lf = NULL;
430     pathname = linker_search_path(filename);
431     if (pathname == NULL)
432           return ENOENT;
433 
434     error = nlookup_init(&nd, pathname, UIO_SYSSPACE, NLC_FOLLOW|NLC_LOCKVP);
435     if (error == 0)
436           error = vn_open(&nd, NULL, FREAD, 0);
437     kfree(pathname, M_LINKER);
438     if (error) {
439           nlookup_done(&nd);
440           return error;
441     }
442     vp = nd.nl_open_vp;
443     nd.nl_open_vp = NULL;
444     nlookup_done(&nd);
445 
446     /*
447      * Read the elf header from the file.
448      */
449     firstpage = kmalloc(PAGE_SIZE, M_LINKER, M_WAITOK);
450     hdr = (Elf_Ehdr *)firstpage;
451     error = vn_rdwr(UIO_READ, vp, firstpage, PAGE_SIZE, 0,
452                         UIO_SYSSPACE, IO_NODELOCKED, p->p_ucred, &resid);
453     nbytes = PAGE_SIZE - resid;
454     if (error)
455           goto out;
456 
457     if (!IS_ELF(*hdr)) {
458           error = ENOEXEC;
459           goto out;
460     }
461 
462     if (hdr->e_ident[EI_CLASS] != ELF_TARG_CLASS
463       || hdr->e_ident[EI_DATA] != ELF_TARG_DATA) {
464           link_elf_error("Unsupported file layout");
465           error = ENOEXEC;
466           goto out;
467     }
468     if (hdr->e_ident[EI_VERSION] != EV_CURRENT
469       || hdr->e_version != EV_CURRENT) {
470           link_elf_error("Unsupported file version");
471           error = ENOEXEC;
472           goto out;
473     }
474     if (hdr->e_type != ET_EXEC && hdr->e_type != ET_DYN) {
475           error = ENOSYS;
476           goto out;
477     }
478     if (hdr->e_machine != ELF_TARG_MACH) {
479           link_elf_error("Unsupported machine");
480           error = ENOEXEC;
481           goto out;
482     }
483 
484     /*
485      * We rely on the program header being in the first page.  This is
486      * not strictly required by the ABI specification, but it seems to
487      * always true in practice.  And, it simplifies things considerably.
488      */
489     if (!((hdr->e_phentsize == sizeof(Elf_Phdr)) &&
490             (hdr->e_phoff + hdr->e_phnum*sizeof(Elf_Phdr) <= PAGE_SIZE) &&
491             (hdr->e_phoff + hdr->e_phnum*sizeof(Elf_Phdr) <= nbytes)))
492           link_elf_error("Unreadable program headers");
493 
494     /*
495      * Scan the program header entries, and save key information.
496      *
497      * We rely on there being exactly two load segments, text and data,
498      * in that order.
499      */
500     phdr = (Elf_Phdr *) (firstpage + hdr->e_phoff);
501     phlimit = phdr + hdr->e_phnum;
502     nsegs = 0;
503     phdyn = NULL;
504     while (phdr < phlimit) {
505           switch (phdr->p_type) {
506 
507           case PT_LOAD:
508               if (nsegs == 2) {
509                     link_elf_error("Too many sections");
510                     error = ENOEXEC;
511                     goto out;
512               }
513               segs[nsegs] = phdr;
514               ++nsegs;
515               break;
516 
517           case PT_PHDR:
518               break;
519 
520           case PT_DYNAMIC:
521               phdyn = phdr;
522               break;
523 
524           case PT_INTERP:
525               error = ENOSYS;
526               goto out;
527           }
528 
529           ++phdr;
530     }
531     if (phdyn == NULL) {
532           link_elf_error("Object is not dynamically-linked");
533           error = ENOEXEC;
534           goto out;
535     }
536 
537     /*
538      * Allocate the entire address space of the object, to stake out our
539      * contiguous region, and to establish the base address for relocation.
540      */
541     base_vaddr = trunc_page(segs[0]->p_vaddr);
542     base_vlimit = round_page(segs[1]->p_vaddr + segs[1]->p_memsz);
543     mapsize = base_vlimit - base_vaddr;
544 
545     ef = kmalloc(sizeof(struct elf_file), M_LINKER, M_WAITOK | M_ZERO);
546     ef->address = kmalloc(mapsize, M_LINKER, M_WAITOK);
547     mapbase = ef->address;
548 
549     /*
550      * Read the text and data sections and zero the bss.
551      */
552     for (i = 0; i < 2; i++) {
553           caddr_t segbase = mapbase + segs[i]->p_vaddr - base_vaddr;
554           error = vn_rdwr(UIO_READ, vp,
555                               segbase, segs[i]->p_filesz, segs[i]->p_offset,
556                               UIO_SYSSPACE, IO_NODELOCKED, p->p_ucred, &resid);
557           if (error) {
558               kfree(ef->address, M_LINKER);
559               kfree(ef, M_LINKER);
560               goto out;
561           }
562           bzero(segbase + segs[i]->p_filesz,
563                 segs[i]->p_memsz - segs[i]->p_filesz);
564     }
565 
566     ef->dynamic = (const Elf_Dyn *) (mapbase + phdyn->p_vaddr - base_vaddr);
567 
568     lf = linker_make_file(filename, ef, &link_elf_file_ops);
569     if (lf == NULL) {
570           kfree(ef->address, M_LINKER);
571           kfree(ef, M_LINKER);
572           error = ENOMEM;
573           goto out;
574     }
575     lf->address = ef->address;
576     lf->size = mapsize;
577 
578     error = parse_dynamic(lf);
579     if (error)
580           goto out;
581     link_elf_reloc_local(lf);
582     error = linker_load_dependencies(lf);
583     if (error)
584           goto out;
585     error = relocate_file(lf);
586     if (error)
587           goto out;
588 
589     /* Try and load the symbol table if it's present.  (you can strip it!) */
590     nbytes = hdr->e_shnum * hdr->e_shentsize;
591     if (nbytes == 0 || hdr->e_shoff == 0)
592           goto nosyms;
593     shdr = kmalloc(nbytes, M_LINKER, M_WAITOK | M_ZERO);
594     error = vn_rdwr(UIO_READ, vp,
595                         (caddr_t)shdr, nbytes, hdr->e_shoff,
596                         UIO_SYSSPACE, IO_NODELOCKED, p->p_ucred, &resid);
597     if (error)
598           goto out;
599     symtabindex = -1;
600     symstrindex = -1;
601     for (i = 0; i < hdr->e_shnum; i++) {
602           if (shdr[i].sh_type == SHT_SYMTAB) {
603               symtabindex = i;
604               symstrindex = shdr[i].sh_link;
605           }
606     }
607     if (symtabindex < 0 || symstrindex < 0)
608           goto nosyms;
609 
610     symcnt = shdr[symtabindex].sh_size;
611     ef->symbase = kmalloc(symcnt, M_LINKER, M_WAITOK);
612     strcnt = shdr[symstrindex].sh_size;
613     ef->strbase = kmalloc(strcnt, M_LINKER, M_WAITOK);
614     error = vn_rdwr(UIO_READ, vp,
615                         ef->symbase, symcnt, shdr[symtabindex].sh_offset,
616                         UIO_SYSSPACE, IO_NODELOCKED, p->p_ucred, &resid);
617     if (error)
618           goto out;
619     error = vn_rdwr(UIO_READ, vp,
620                         ef->strbase, strcnt, shdr[symstrindex].sh_offset,
621                         UIO_SYSSPACE, IO_NODELOCKED, p->p_ucred, &resid);
622     if (error)
623           goto out;
624 
625     ef->ddbsymcnt = symcnt / sizeof(Elf_Sym);
626     ef->ddbsymtab = (const Elf_Sym *)ef->symbase;
627     ef->ddbstrcnt = strcnt;
628     ef->ddbstrtab = ef->strbase;
629 
630 nosyms:
631 
632     *result = lf;
633 
634 out:
635     if (error && lf)
636           linker_file_unload(lf);
637     if (shdr)
638           kfree(shdr, M_LINKER);
639     if (firstpage)
640           kfree(firstpage, M_LINKER);
641     vn_unlock(vp);
642     vn_close(vp, FREAD, NULL);
643 
644     return error;
645 }
646 
647 Elf_Addr
elf_relocaddr(linker_file_t lf,Elf_Addr x)648 elf_relocaddr(linker_file_t lf, Elf_Addr x)
649 {
650 #if 0
651     elf_file_t ef;
652 
653     ef = lf->priv;
654     if (x >= ef->pcpu_start && x < ef->pcpu_stop)
655           return ((x - ef->pcpu_start) + ef->pcpu_base);
656 #ifdef VIMAGE
657     if (x >= ef->vnet_start && x < ef->vnet_stop)
658           return ((x - ef->vnet_start) + ef->vnet_base);
659 #endif
660 #endif
661     return (x);
662 }
663 
664 static void
link_elf_unload_file(linker_file_t file)665 link_elf_unload_file(linker_file_t file)
666 {
667     elf_file_t ef = file->priv;
668 
669     if (ef) {
670           if (ef->address)
671               kfree(ef->address, M_LINKER);
672           if (ef->symbase)
673               kfree(ef->symbase, M_LINKER);
674           if (ef->strbase)
675               kfree(ef->strbase, M_LINKER);
676           kfree(ef, M_LINKER);
677     }
678 }
679 
680 static void
link_elf_unload_module(linker_file_t file)681 link_elf_unload_module(linker_file_t file)
682 {
683     elf_file_t ef = file->priv;
684 
685     if (ef)
686           kfree(ef, M_LINKER);
687     if (file->pathname)
688           preload_delete_name(file->pathname);
689 }
690 
691 static const char *
symbol_name(elf_file_t ef,Elf_Size r_info)692 symbol_name(elf_file_t ef, Elf_Size r_info)
693 {
694     const Elf_Sym *ref;
695 
696     if (ELF_R_SYM(r_info)) {
697           ref = ef->symtab + ELF_R_SYM(r_info);
698           return ef->strtab + ref->st_name;
699     } else
700           return NULL;
701 }
702 
703 static int
relocate_file(linker_file_t lf)704 relocate_file(linker_file_t lf)
705 {
706     elf_file_t ef = lf->priv;
707     const Elf_Rel *rellim;
708     const Elf_Rel *rel;
709     const Elf_Rela *relalim;
710     const Elf_Rela *rela;
711     const char *symname;
712 
713     /* Perform relocations without addend if there are any: */
714     rel = ef->rel;
715     if (rel) {
716           rellim = (const Elf_Rel *)((const char *)ef->rel + ef->relsize);
717           while (rel < rellim) {
718               if (elf_reloc(lf, (Elf_Addr)ef->address, rel, ELF_RELOC_REL, elf_lookup)) {
719                     symname = symbol_name(ef, rel->r_info);
720                     kprintf("link_elf: symbol %s undefined\n", symname);
721                     return ENOENT;
722               }
723               rel++;
724           }
725     }
726 
727     /* Perform relocations with addend if there are any: */
728     rela = ef->rela;
729     if (rela) {
730           relalim = (const Elf_Rela *)((const char *)ef->rela + ef->relasize);
731           while (rela < relalim) {
732               if (elf_reloc(lf, (Elf_Addr)ef->address, rela, ELF_RELOC_RELA, elf_lookup)) {
733                     symname = symbol_name(ef, rela->r_info);
734                     kprintf("link_elf: symbol %s undefined\n", symname);
735                     return ENOENT;
736               }
737               rela++;
738           }
739     }
740 
741     /* Perform PLT relocations without addend if there are any: */
742     rel = ef->pltrel;
743     if (rel) {
744           rellim = (const Elf_Rel *)((const char *)ef->pltrel + ef->pltrelsize);
745           while (rel < rellim) {
746               if (elf_reloc(lf, (Elf_Addr)ef->address, rel, ELF_RELOC_REL, elf_lookup)) {
747                     symname = symbol_name(ef, rel->r_info);
748                     kprintf("link_elf: symbol %s undefined\n", symname);
749                     return ENOENT;
750               }
751               rel++;
752           }
753     }
754 
755     /* Perform relocations with addend if there are any: */
756     rela = ef->pltrela;
757     if (rela) {
758           relalim = (const Elf_Rela *)((const char *)ef->pltrela + ef->pltrelasize);
759           while (rela < relalim) {
760               symname = symbol_name(ef, rela->r_info);
761               if (elf_reloc(lf, (Elf_Addr)ef->address, rela, ELF_RELOC_RELA, elf_lookup)) {
762                     kprintf("link_elf: symbol %s undefined\n", symname);
763                     return ENOENT;
764               }
765               rela++;
766           }
767     }
768 
769     return 0;
770 }
771 
772 /*
773  * Hash function for symbol table lookup.  Don't even think about changing
774  * this.  It is specified by the System V ABI.
775  */
776 static unsigned long
elf_hash(const char * name)777 elf_hash(const char *name)
778 {
779     const unsigned char *p = (const unsigned char *) name;
780     unsigned long h = 0;
781     unsigned long g;
782 
783     while (*p != '\0') {
784           h = (h << 4) + *p++;
785           if ((g = h & 0xf0000000) != 0)
786               h ^= g >> 24;
787           h &= ~g;
788     }
789     return h;
790 }
791 
792 static int
link_elf_lookup_symbol(linker_file_t lf,const char * name,c_linker_sym_t * sym)793 link_elf_lookup_symbol(linker_file_t lf, const char* name, c_linker_sym_t* sym)
794 {
795     elf_file_t ef = lf->priv;
796     unsigned long symnum;
797     const Elf_Sym* symp;
798     const char *strp;
799     unsigned long hash;
800     int i;
801 
802     /* If we don't have a hash, bail. */
803     if (ef->buckets == NULL || ef->nbuckets == 0) {
804           kprintf("link_elf_lookup_symbol: missing symbol hash table\n");
805           return ENOENT;
806     }
807 
808     /* First, search hashed global symbols */
809     hash = elf_hash(name);
810     symnum = ef->buckets[hash % ef->nbuckets];
811 
812     while (symnum != STN_UNDEF) {
813           if (symnum >= ef->nchains) {
814               kprintf("link_elf_lookup_symbol: corrupt symbol table\n");
815               return ENOENT;
816           }
817 
818           symp = ef->symtab + symnum;
819           if (symp->st_name == 0) {
820               kprintf("link_elf_lookup_symbol: corrupt symbol table\n");
821               return ENOENT;
822           }
823 
824           strp = ef->strtab + symp->st_name;
825 
826           if (strcmp(name, strp) == 0) {
827               if (symp->st_shndx != SHN_UNDEF ||
828                     (symp->st_value != 0 &&
829                      ELF_ST_TYPE(symp->st_info) == STT_FUNC)
830                ) {
831                     *sym = (c_linker_sym_t) symp;
832                     return 0;
833               } else {
834                     return ENOENT;
835               }
836           }
837 
838           symnum = ef->chains[symnum];
839     }
840 
841     /* If we have not found it, look at the full table (if loaded) */
842     if (ef->symtab == ef->ddbsymtab)
843           return ENOENT;
844 
845     /* Exhaustive search */
846     for (i = 0, symp = ef->ddbsymtab; i < ef->ddbsymcnt; i++, symp++) {
847           strp = ef->ddbstrtab + symp->st_name;
848           if (strcmp(name, strp) == 0) {
849               if (symp->st_shndx != SHN_UNDEF ||
850                     (symp->st_value != 0 &&
851                      ELF_ST_TYPE(symp->st_info) == STT_FUNC)) {
852                     *sym = (c_linker_sym_t) symp;
853                     return 0;
854               } else {
855                     return ENOENT;
856               }
857           }
858     }
859     return ENOENT;
860 }
861 
862 static int
link_elf_symbol_values(linker_file_t lf,c_linker_sym_t sym,linker_symval_t * symval)863 link_elf_symbol_values(linker_file_t lf, c_linker_sym_t sym, linker_symval_t *symval)
864 {
865     elf_file_t          ef = lf->priv;
866     const Elf_Sym  *es = (const Elf_Sym *)sym;
867 
868     symval->value = 0;        /* avoid gcc warnings */
869 
870     if (es >= ef->symtab && es < (ef->symtab + ef->nchains)) {
871           symval->name = ef->strtab + es->st_name;
872           symval->value = ef->address + es->st_value;
873           symval->size = es->st_size;
874           return 0;
875     }
876     if (ef->symtab == ef->ddbsymtab)
877           return ENOENT;
878     if (es >= ef->ddbsymtab && es < (ef->ddbsymtab + ef->ddbsymcnt)) {
879           symval->name = ef->ddbstrtab + es->st_name;
880           symval->value = ef->address + es->st_value;
881           symval->size = es->st_size;
882           return 0;
883     }
884     return ENOENT;
885 }
886 
887 static int
link_elf_search_symbol(linker_file_t lf,caddr_t value,c_linker_sym_t * sym,long * diffp)888 link_elf_search_symbol(linker_file_t lf, caddr_t value,
889                            c_linker_sym_t *sym, long *diffp)
890 {
891     elf_file_t          ef = lf->priv;
892     u_long              off = (uintptr_t)(void *)value;
893     u_long              diff = off;
894     u_long              st_value;
895     const Elf_Sym  *es;
896     const Elf_Sym  *best = NULL;
897     int                 i;
898 
899     for (i = 0, es = ef->ddbsymtab; i < ef->ddbsymcnt; i++, es++) {
900           if (es->st_name == 0)
901               continue;
902           st_value = es->st_value + (uintptr_t)(void *)ef->address;
903           if (off >= st_value) {
904               if (off - st_value < diff) {
905                     diff = off - st_value;
906                     best = es;
907                     if (diff == 0)
908                         break;
909               } else if (off - st_value == diff) {
910                     best = es;
911               }
912           }
913     }
914     if (best == NULL)
915           *diffp = off;
916     else
917           *diffp = diff;
918     *sym = (c_linker_sym_t) best;
919 
920     return 0;
921 }
922 
923 /*
924  * Look up a linker set on an ELF system.
925  */
926 static int
link_elf_lookup_set(linker_file_t lf,const char * name,void *** startp,void *** stopp,int * countp)927 link_elf_lookup_set(linker_file_t lf, const char *name,
928                         void ***startp, void ***stopp, int *countp)
929 {
930     c_linker_sym_t  sym;
931     linker_symval_t symval;
932     char           *setsym;
933     void          **start, **stop;
934     int                 len, error = 0, count;
935 
936     len = strlen(name) + sizeof("__start_set_");  /* sizeof includes \0 */
937     setsym = kmalloc(len, M_LINKER, M_WAITOK);
938 
939     /* get address of first entry */
940     ksnprintf(setsym, len, "%s%s", "__start_set_", name);
941     error = link_elf_lookup_symbol(lf, setsym, &sym);
942     if (error)
943           goto out;
944     link_elf_symbol_values(lf, sym, &symval);
945     if (symval.value == NULL) {
946           error = ESRCH;
947           goto out;
948     }
949     start = (void **)symval.value;
950 
951     /* get address of last entry */
952     ksnprintf(setsym, len, "%s%s", "__stop_set_", name);
953     error = link_elf_lookup_symbol(lf, setsym, &sym);
954     if (error)
955           goto out;
956     link_elf_symbol_values(lf, sym, &symval);
957     if (symval.value == NULL) {
958           error = ESRCH;
959           goto out;
960     }
961     stop = (void **)symval.value;
962 
963     /* and the number of entries */
964     count = stop - start;
965 
966     /* and copy out */
967     if (startp)
968           *startp = start;
969     if (stopp)
970           *stopp = stop;
971     if (countp)
972           *countp = count;
973 
974 out:
975     kfree(setsym, M_LINKER);
976     return error;
977 }
978 
979 /*
980  * Symbol lookup function that can be used when the symbol index is known (ie
981  * in relocations). It uses the symbol index instead of doing a fully fledged
982  * hash table based lookup when such is valid. For example for local symbols.
983  * This is not only more efficient, it's also more correct. It's not always
984  * the case that the symbol can be found through the hash table.
985  */
986 static int
elf_lookup(linker_file_t lf,Elf_Size symidx,int deps,Elf_Addr * result)987 elf_lookup(linker_file_t lf, Elf_Size symidx, int deps, Elf_Addr *result)
988 {
989     elf_file_t          ef = lf->priv;
990     const Elf_Sym  *sym;
991     const char     *symbol;
992 
993     /* Don't even try to lookup the symbol if the index is bogus. */
994     if (symidx >= ef->nchains)
995           return (ENOENT);
996 
997     sym = ef->symtab + symidx;
998 
999     /*
1000      * Don't do a full lookup when the symbol is local. It may even
1001      * fail because it may not be found through the hash table.
1002      */
1003     if (ELF_ST_BIND(sym->st_info) == STB_LOCAL) {
1004           /* Force lookup failure when we have an insanity. */
1005           if (sym->st_shndx == SHN_UNDEF || sym->st_value == 0)
1006               return (ENOENT);
1007           return ((Elf_Addr) ef->address + sym->st_value);
1008     }
1009     /*
1010      * XXX we can avoid doing a hash table based lookup for global
1011      * symbols as well. This however is not always valid, so we'll
1012      * just do it the hard way for now. Performance tweaks can
1013      * always be added.
1014      */
1015 
1016     symbol = ef->strtab + sym->st_name;
1017 
1018     /* Force a lookup failure if the symbol name is bogus. */
1019     if (*symbol == 0)
1020           return (ENOENT);
1021 
1022     return (linker_file_lookup_symbol(lf, symbol, deps, (caddr_t *)result));
1023 }
1024 static void
link_elf_reloc_local(linker_file_t lf)1025 link_elf_reloc_local(linker_file_t lf)
1026 {
1027     elf_file_t ef = lf->priv;
1028     const Elf_Rel *rellim;
1029     const Elf_Rel *rel;
1030     const Elf_Rela *relalim;
1031     const Elf_Rela *rela;
1032 
1033     /* Perform relocations without addend if there are any: */
1034     if ((rel = ef->rel) != NULL) {
1035           rellim = (const Elf_Rel *)((const char *)ef->rel + ef->relsize);
1036           while (rel < rellim) {
1037               elf_reloc_local(lf, (Elf_Addr)ef->address, rel, ELF_RELOC_REL,
1038                                   elf_lookup);
1039               rel++;
1040           }
1041     }
1042 
1043     /* Perform relocations with addend if there are any: */
1044     if ((rela = ef->rela) != NULL) {
1045           relalim = (const Elf_Rela *)((const char *)ef->rela + ef->relasize);
1046           while (rela < relalim) {
1047               elf_reloc_local(lf, (Elf_Addr)ef->address, rela, ELF_RELOC_RELA,
1048                                   elf_lookup);
1049               rela++;
1050           }
1051     }
1052 }
1053