]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/link_elf.c
- Fix the sched_priority() invalid priority bugs. Use roundup() instead
[FreeBSD/FreeBSD.git] / sys / kern / link_elf.c
1 /*-
2  * Copyright (c) 1998-2000 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
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29
30 #include "opt_gdb.h"
31 #include "opt_mac.h"
32
33 #include <sys/param.h>
34 #include <sys/systm.h>
35 #ifdef GPROF
36 #include <sys/gmon.h>
37 #endif
38 #include <sys/kernel.h>
39 #include <sys/lock.h>
40 #include <sys/malloc.h>
41 #include <sys/mutex.h>
42 #include <sys/mount.h>
43 #include <sys/proc.h>
44 #include <sys/namei.h>
45 #include <sys/fcntl.h>
46 #include <sys/vnode.h>
47 #include <sys/linker.h>
48
49 #include <machine/elf.h>
50
51 #include <security/mac/mac_framework.h>
52
53 #include <vm/vm.h>
54 #include <vm/vm_param.h>
55 #ifdef SPARSE_MAPPING
56 #include <vm/vm_object.h>
57 #include <vm/vm_kern.h>
58 #include <vm/vm_extern.h>
59 #endif
60 #include <vm/pmap.h>
61 #include <vm/vm_map.h>
62
63 #include <sys/link_elf.h>
64
65 #include "linker_if.h"
66
67 #define MAXSEGS 4
68
69 typedef struct elf_file {
70     struct linker_file  lf;             /* Common fields */
71     int                 preloaded;      /* Was file pre-loaded */
72     caddr_t             address;        /* Relocation address */
73 #ifdef SPARSE_MAPPING
74     vm_object_t         object;         /* VM object to hold file pages */
75 #endif
76     Elf_Dyn*            dynamic;        /* Symbol table etc. */
77     Elf_Hashelt         nbuckets;       /* DT_HASH info */
78     Elf_Hashelt         nchains;
79     const Elf_Hashelt*  buckets;
80     const Elf_Hashelt*  chains;
81     caddr_t             hash;
82     caddr_t             strtab;         /* DT_STRTAB */
83     int                 strsz;          /* DT_STRSZ */
84     const Elf_Sym*      symtab;         /* DT_SYMTAB */
85     Elf_Addr*           got;            /* DT_PLTGOT */
86     const Elf_Rel*      pltrel;         /* DT_JMPREL */
87     int                 pltrelsize;     /* DT_PLTRELSZ */
88     const Elf_Rela*     pltrela;        /* DT_JMPREL */
89     int                 pltrelasize;    /* DT_PLTRELSZ */
90     const Elf_Rel*      rel;            /* DT_REL */
91     int                 relsize;        /* DT_RELSZ */
92     const Elf_Rela*     rela;           /* DT_RELA */
93     int                 relasize;       /* DT_RELASZ */
94     caddr_t             modptr;
95     const Elf_Sym*      ddbsymtab;      /* The symbol table we are using */
96     long                ddbsymcnt;      /* Number of symbols */
97     caddr_t             ddbstrtab;      /* String table */
98     long                ddbstrcnt;      /* number of bytes in string table */
99     caddr_t             symbase;        /* malloc'ed symbold base */
100     caddr_t             strbase;        /* malloc'ed string base */
101 #ifdef GDB
102     struct link_map     gdb;            /* hooks for gdb */
103 #endif
104 } *elf_file_t;
105
106 static int      link_elf_link_common_finish(linker_file_t);
107 static int      link_elf_link_preload(linker_class_t cls,
108                                       const char*, linker_file_t*);
109 static int      link_elf_link_preload_finish(linker_file_t);
110 static int      link_elf_load_file(linker_class_t, const char*, linker_file_t*);
111 static int      link_elf_lookup_symbol(linker_file_t, const char*,
112                                        c_linker_sym_t*);
113 static int      link_elf_symbol_values(linker_file_t, c_linker_sym_t, linker_symval_t*);
114 static int      link_elf_search_symbol(linker_file_t, caddr_t value,
115                                        c_linker_sym_t* sym, long* diffp);
116
117 static void     link_elf_unload_file(linker_file_t);
118 static void     link_elf_unload_preload(linker_file_t);
119 static int      link_elf_lookup_set(linker_file_t, const char *,
120                                     void ***, void ***, int *);
121 static int      link_elf_each_function_name(linker_file_t,
122                                 int (*)(const char *, void *),
123                                 void *);
124 static void     link_elf_reloc_local(linker_file_t);
125 static Elf_Addr elf_lookup(linker_file_t lf, Elf_Size symidx, int deps);
126
127 static kobj_method_t link_elf_methods[] = {
128     KOBJMETHOD(linker_lookup_symbol,    link_elf_lookup_symbol),
129     KOBJMETHOD(linker_symbol_values,    link_elf_symbol_values),
130     KOBJMETHOD(linker_search_symbol,    link_elf_search_symbol),
131     KOBJMETHOD(linker_unload,           link_elf_unload_file),
132     KOBJMETHOD(linker_load_file,        link_elf_load_file),
133     KOBJMETHOD(linker_link_preload,     link_elf_link_preload),
134     KOBJMETHOD(linker_link_preload_finish, link_elf_link_preload_finish),
135     KOBJMETHOD(linker_lookup_set,       link_elf_lookup_set),
136     KOBJMETHOD(linker_each_function_name, link_elf_each_function_name),
137     { 0, 0 }
138 };
139
140 static struct linker_class link_elf_class = {
141 #if ELF_TARG_CLASS == ELFCLASS32
142     "elf32",
143 #else
144     "elf64",
145 #endif
146     link_elf_methods, sizeof(struct elf_file)
147 };
148
149 static int              parse_dynamic(elf_file_t ef);
150 static int              relocate_file(elf_file_t ef);
151 static int              link_elf_preload_parse_symbols(elf_file_t ef);
152
153 #ifdef GDB
154 static void             r_debug_state(struct r_debug *dummy_one,
155                                       struct link_map *dummy_two);
156
157 /*
158  * A list of loaded modules for GDB to use for loading symbols.
159  */
160 struct r_debug r_debug;
161
162 #define GDB_STATE(s)    r_debug.r_state = s; r_debug_state(NULL, NULL);
163
164 /*
165  * Function for the debugger to set a breakpoint on to gain control.
166  */
167 static void
168 r_debug_state(struct r_debug *dummy_one __unused,
169               struct link_map *dummy_two __unused)
170 {
171 }
172
173 static void
174 link_elf_add_gdb(struct link_map *l)
175 {
176     struct link_map *prev;
177
178     l->l_next = NULL;
179
180     if (r_debug.r_map == NULL) {
181         /* Add first. */
182         l->l_prev = NULL;
183         r_debug.r_map = l;
184     } else {
185         /* Append to list. */
186         for (prev = r_debug.r_map; prev->l_next != NULL; prev = prev->l_next)
187             ;
188         l->l_prev = prev;
189         prev->l_next = l;
190     }
191 }
192
193 static void
194 link_elf_delete_gdb(struct link_map *l)
195 {
196     if (l->l_prev == NULL) {
197         /* Remove first. */
198         if ((r_debug.r_map = l->l_next) != NULL)
199             l->l_next->l_prev = NULL;
200     } else {
201         /* Remove any but first. */
202         if ((l->l_prev->l_next = l->l_next) != NULL)
203             l->l_next->l_prev = l->l_prev;
204     }
205 }
206 #endif /* GDB */
207
208 #ifdef __ia64__
209 Elf_Addr link_elf_get_gp(linker_file_t);
210 #endif
211
212 /*
213  * The kernel symbol table starts here.
214  */
215 extern struct _dynamic _DYNAMIC;
216
217 static void
218 link_elf_error(const char *s)
219 {
220     printf("kldload: %s\n", s);
221 }
222
223 /*
224  * Actions performed after linking/loading both the preloaded kernel and any
225  * modules; whether preloaded or dynamicly loaded.
226  */
227 static int
228 link_elf_link_common_finish(linker_file_t lf)
229 {
230 #ifdef GDB
231     elf_file_t ef = (elf_file_t)lf;
232     char *newfilename;
233 #endif
234     int error;
235
236     /* Notify MD code that a module is being loaded. */
237     error = elf_cpu_load_file(lf);
238     if (error)
239         return (error);
240
241 #ifdef GDB
242     GDB_STATE(RT_ADD);
243     ef->gdb.l_addr = lf->address;
244     newfilename = malloc(strlen(lf->filename) + 1, M_LINKER, M_WAITOK);
245     strcpy(newfilename, lf->filename);
246     ef->gdb.l_name = newfilename;
247     ef->gdb.l_ld = ef->dynamic;
248     link_elf_add_gdb(&ef->gdb);
249     GDB_STATE(RT_CONSISTENT);
250 #endif
251
252     return (0);
253 }
254
255 static void
256 link_elf_init(void* arg)
257 {
258     Elf_Dyn     *dp;
259     caddr_t     modptr, baseptr, sizeptr;
260     elf_file_t  ef;
261     char        *modname;
262
263     linker_add_class(&link_elf_class);
264
265     dp = (Elf_Dyn*) &_DYNAMIC;
266     modname = NULL;
267     modptr = preload_search_by_type("elf" __XSTRING(__ELF_WORD_SIZE) " kernel");
268     if (modptr == NULL)
269         modptr = preload_search_by_type("elf kernel");
270     if (modptr)
271         modname = (char *)preload_search_info(modptr, MODINFO_NAME);
272     if (modname == NULL)
273         modname = "kernel";
274     linker_kernel_file = linker_make_file(modname, &link_elf_class);
275     if (linker_kernel_file == NULL)
276         panic("link_elf_init: Can't create linker structures for kernel");
277
278     ef = (elf_file_t) linker_kernel_file;
279     ef->preloaded = 1;
280     ef->address = 0;
281 #ifdef SPARSE_MAPPING
282     ef->object = 0;
283 #endif
284     ef->dynamic = dp;
285
286     if (dp)
287         parse_dynamic(ef);
288     linker_kernel_file->address = (caddr_t) KERNBASE;
289     linker_kernel_file->size = -(intptr_t)linker_kernel_file->address;
290
291     if (modptr) {
292         ef->modptr = modptr;
293         baseptr = preload_search_info(modptr, MODINFO_ADDR);
294         if (baseptr)
295             linker_kernel_file->address = *(caddr_t *)baseptr;
296         sizeptr = preload_search_info(modptr, MODINFO_SIZE);
297         if (sizeptr)
298             linker_kernel_file->size = *(size_t *)sizeptr;
299     }
300     (void)link_elf_preload_parse_symbols(ef);
301
302 #ifdef GDB
303     r_debug.r_map = NULL;
304     r_debug.r_brk = r_debug_state;
305     r_debug.r_state = RT_CONSISTENT;
306 #endif
307
308     (void)link_elf_link_common_finish(linker_kernel_file);
309 }
310
311 SYSINIT(link_elf, SI_SUB_KLD, SI_ORDER_THIRD, link_elf_init, 0);
312
313 static int
314 link_elf_preload_parse_symbols(elf_file_t ef)
315 {
316     caddr_t     pointer;
317     caddr_t     ssym, esym, base;
318     caddr_t     strtab;
319     int         strcnt;
320     Elf_Sym*    symtab;
321     int         symcnt;
322
323     if (ef->modptr == NULL)
324         return 0;
325     pointer = preload_search_info(ef->modptr, MODINFO_METADATA|MODINFOMD_SSYM);
326     if (pointer == NULL)
327         return 0;
328     ssym = *(caddr_t *)pointer;
329     pointer = preload_search_info(ef->modptr, MODINFO_METADATA|MODINFOMD_ESYM);
330     if (pointer == NULL)
331         return 0;
332     esym = *(caddr_t *)pointer;
333
334     base = ssym;
335
336     symcnt = *(long *)base;
337     base += sizeof(long);
338     symtab = (Elf_Sym *)base;
339     base += roundup(symcnt, sizeof(long));
340
341     if (base > esym || base < ssym) {
342         printf("Symbols are corrupt!\n");
343         return EINVAL;
344     }
345
346     strcnt = *(long *)base;
347     base += sizeof(long);
348     strtab = base;
349     base += roundup(strcnt, sizeof(long));
350
351     if (base > esym || base < ssym) {
352         printf("Symbols are corrupt!\n");
353         return EINVAL;
354     }
355
356     ef->ddbsymtab = symtab;
357     ef->ddbsymcnt = symcnt / sizeof(Elf_Sym);
358     ef->ddbstrtab = strtab;
359     ef->ddbstrcnt = strcnt;
360
361     return 0;
362 }
363
364 static int
365 parse_dynamic(elf_file_t ef)
366 {
367     Elf_Dyn *dp;
368     int plttype = DT_REL;
369
370     for (dp = ef->dynamic; dp->d_tag != DT_NULL; dp++) {
371         switch (dp->d_tag) {
372         case DT_HASH:
373         {
374             /* From src/libexec/rtld-elf/rtld.c */
375             const Elf_Hashelt *hashtab = (const Elf_Hashelt *)
376                 (ef->address + dp->d_un.d_ptr);
377             ef->nbuckets = hashtab[0];
378             ef->nchains = hashtab[1];
379             ef->buckets = hashtab + 2;
380             ef->chains = ef->buckets + ef->nbuckets;
381             break;
382         }
383         case DT_STRTAB:
384             ef->strtab = (caddr_t) (ef->address + dp->d_un.d_ptr);
385             break;
386         case DT_STRSZ:
387             ef->strsz = dp->d_un.d_val;
388             break;
389         case DT_SYMTAB:
390             ef->symtab = (Elf_Sym*) (ef->address + dp->d_un.d_ptr);
391             break;
392         case DT_SYMENT:
393             if (dp->d_un.d_val != sizeof(Elf_Sym))
394                 return ENOEXEC;
395             break;
396         case DT_PLTGOT:
397             ef->got = (Elf_Addr *) (ef->address + dp->d_un.d_ptr);
398             break;
399         case DT_REL:
400             ef->rel = (const Elf_Rel *) (ef->address + dp->d_un.d_ptr);
401             break;
402         case DT_RELSZ:
403             ef->relsize = dp->d_un.d_val;
404             break;
405         case DT_RELENT:
406             if (dp->d_un.d_val != sizeof(Elf_Rel))
407                 return ENOEXEC;
408             break;
409         case DT_JMPREL:
410             ef->pltrel = (const Elf_Rel *) (ef->address + dp->d_un.d_ptr);
411             break;
412         case DT_PLTRELSZ:
413             ef->pltrelsize = dp->d_un.d_val;
414             break;
415         case DT_RELA:
416             ef->rela = (const Elf_Rela *) (ef->address + dp->d_un.d_ptr);
417             break;
418         case DT_RELASZ:
419             ef->relasize = dp->d_un.d_val;
420             break;
421         case DT_RELAENT:
422             if (dp->d_un.d_val != sizeof(Elf_Rela))
423                 return ENOEXEC;
424             break;
425         case DT_PLTREL:
426             plttype = dp->d_un.d_val;
427             if (plttype != DT_REL && plttype != DT_RELA)
428                 return ENOEXEC;
429             break;
430 #ifdef GDB
431         case DT_DEBUG:
432             dp->d_un.d_ptr = (Elf_Addr) &r_debug;
433             break;
434 #endif
435         }
436     }
437
438     if (plttype == DT_RELA) {
439         ef->pltrela = (const Elf_Rela *) ef->pltrel;
440         ef->pltrel = NULL;
441         ef->pltrelasize = ef->pltrelsize;
442         ef->pltrelsize = 0;
443     }
444
445     ef->ddbsymtab = ef->symtab;
446     ef->ddbsymcnt = ef->nchains;
447     ef->ddbstrtab = ef->strtab;
448     ef->ddbstrcnt = ef->strsz;
449
450     return 0;
451 }
452
453 static int
454 link_elf_link_preload(linker_class_t cls,
455                       const char* filename, linker_file_t *result)
456 {
457     caddr_t             modptr, baseptr, sizeptr, dynptr;
458     char                *type;
459     elf_file_t          ef;
460     linker_file_t       lf;
461     int                 error;
462     vm_offset_t         dp;
463
464     /* Look to see if we have the file preloaded */
465     modptr = preload_search_by_name(filename);
466     if (modptr == NULL)
467         return ENOENT;
468
469     type = (char *)preload_search_info(modptr, MODINFO_TYPE);
470     baseptr = preload_search_info(modptr, MODINFO_ADDR);
471     sizeptr = preload_search_info(modptr, MODINFO_SIZE);
472     dynptr = preload_search_info(modptr, MODINFO_METADATA|MODINFOMD_DYNAMIC);
473     if (type == NULL ||
474         (strcmp(type, "elf" __XSTRING(__ELF_WORD_SIZE) " module") != 0 &&
475          strcmp(type, "elf module") != 0))
476         return (EFTYPE);
477     if (baseptr == NULL || sizeptr == NULL || dynptr == NULL)
478         return (EINVAL);
479
480     lf = linker_make_file(filename, &link_elf_class);
481     if (lf == NULL) {
482         return ENOMEM;
483     }
484
485     ef = (elf_file_t) lf;
486     ef->preloaded = 1;
487     ef->modptr = modptr;
488     ef->address = *(caddr_t *)baseptr;
489 #ifdef SPARSE_MAPPING
490     ef->object = 0;
491 #endif
492     dp = (vm_offset_t)ef->address + *(vm_offset_t *)dynptr;
493     ef->dynamic = (Elf_Dyn *)dp;
494     lf->address = ef->address;
495     lf->size = *(size_t *)sizeptr;
496
497     error = parse_dynamic(ef);
498     if (error) {
499         linker_file_unload(lf, LINKER_UNLOAD_FORCE);
500         return error;
501     }
502     link_elf_reloc_local(lf);
503     *result = lf;
504     return (0);
505 }
506
507 static int
508 link_elf_link_preload_finish(linker_file_t lf)
509 {
510     elf_file_t          ef;
511     int error;
512
513     ef = (elf_file_t) lf;
514 #if 0   /* this will be more trouble than it's worth for now */
515     for (dp = ef->dynamic; dp->d_tag != DT_NULL; dp++) {
516         if (dp->d_tag != DT_NEEDED)
517             continue;
518         modname = ef->strtab + dp->d_un.d_val;
519         error = linker_load_module(modname, lf);
520         if (error)
521             goto out;
522     }
523 #endif
524     error = relocate_file(ef);
525     if (error)
526         return error;
527     (void)link_elf_preload_parse_symbols(ef);
528
529     return (link_elf_link_common_finish(lf));
530 }
531
532 static int
533 link_elf_load_file(linker_class_t cls, const char* filename,
534         linker_file_t* result)
535 {
536     struct nameidata nd;
537     struct thread* td = curthread;      /* XXX */
538     Elf_Ehdr *hdr;
539     caddr_t firstpage;
540     int nbytes, i;
541     Elf_Phdr *phdr;
542     Elf_Phdr *phlimit;
543     Elf_Phdr *segs[MAXSEGS];
544     int nsegs;
545     Elf_Phdr *phdyn;
546     Elf_Phdr *phphdr;
547     caddr_t mapbase;
548     size_t mapsize;
549     Elf_Off base_offset;
550     Elf_Addr base_vaddr;
551     Elf_Addr base_vlimit;
552     int error = 0;
553     int resid, flags;
554     elf_file_t ef;
555     linker_file_t lf;
556     Elf_Shdr *shdr;
557     int symtabindex;
558     int symstrindex;
559     int symcnt;
560     int strcnt;
561     int vfslocked;
562
563     shdr = NULL;
564     lf = NULL;
565
566     NDINIT(&nd, LOOKUP, FOLLOW | MPSAFE, UIO_SYSSPACE, filename, td);
567     flags = FREAD;
568     error = vn_open(&nd, &flags, 0, -1);
569     if (error)
570         return error;
571     vfslocked = NDHASGIANT(&nd);
572     NDFREE(&nd, NDF_ONLY_PNBUF);
573 #ifdef MAC
574     error = mac_check_kld_load(curthread->td_ucred, nd.ni_vp);
575     if (error) {
576         firstpage = NULL;
577         goto out;
578     }
579 #endif
580
581     /*
582      * Read the elf header from the file.
583      */
584     firstpage = malloc(PAGE_SIZE, M_LINKER, M_WAITOK);
585     if (firstpage == NULL) {
586         error = ENOMEM;
587         goto out;
588     }
589     hdr = (Elf_Ehdr *)firstpage;
590     error = vn_rdwr(UIO_READ, nd.ni_vp, firstpage, PAGE_SIZE, 0,
591                     UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred, NOCRED,
592                     &resid, td);
593     nbytes = PAGE_SIZE - resid;
594     if (error)
595         goto out;
596
597     if (!IS_ELF(*hdr)) {
598         error = ENOEXEC;
599         goto out;
600     }
601
602     if (hdr->e_ident[EI_CLASS] != ELF_TARG_CLASS
603       || hdr->e_ident[EI_DATA] != ELF_TARG_DATA) {
604         link_elf_error("Unsupported file layout");
605         error = ENOEXEC;
606         goto out;
607     }
608     if (hdr->e_ident[EI_VERSION] != EV_CURRENT
609       || hdr->e_version != EV_CURRENT) {
610         link_elf_error("Unsupported file version");
611         error = ENOEXEC;
612         goto out;
613     }
614     if (hdr->e_type != ET_EXEC && hdr->e_type != ET_DYN) {
615         link_elf_error("Unsupported file type");
616         error = ENOEXEC;
617         goto out;
618     }
619     if (hdr->e_machine != ELF_TARG_MACH) {
620         link_elf_error("Unsupported machine");
621         error = ENOEXEC;
622         goto out;
623     }
624
625     /*
626      * We rely on the program header being in the first page.  This is
627      * not strictly required by the ABI specification, but it seems to
628      * always true in practice.  And, it simplifies things considerably.
629      */
630     if (!((hdr->e_phentsize == sizeof(Elf_Phdr)) &&
631           (hdr->e_phoff + hdr->e_phnum*sizeof(Elf_Phdr) <= PAGE_SIZE) &&
632           (hdr->e_phoff + hdr->e_phnum*sizeof(Elf_Phdr) <= nbytes)))
633         link_elf_error("Unreadable program headers");
634
635     /*
636      * Scan the program header entries, and save key information.
637      *
638      * We rely on there being exactly two load segments, text and data,
639      * in that order.
640      */
641     phdr = (Elf_Phdr *) (firstpage + hdr->e_phoff);
642     phlimit = phdr + hdr->e_phnum;
643     nsegs = 0;
644     phdyn = NULL;
645     phphdr = NULL;
646     while (phdr < phlimit) {
647         switch (phdr->p_type) {
648
649         case PT_LOAD:
650             if (nsegs == MAXSEGS) {
651                 link_elf_error("Too many sections");
652                 error = ENOEXEC;
653                 goto out;
654             }
655             /*
656              * XXX: We just trust they come in right order ??
657              */
658             segs[nsegs] = phdr;
659             ++nsegs;
660             break;
661
662         case PT_PHDR:
663             phphdr = phdr;
664             break;
665
666         case PT_DYNAMIC:
667             phdyn = phdr;
668             break;
669
670         case PT_INTERP:
671             link_elf_error("Unsupported file type");
672             error = ENOEXEC;
673             goto out;
674         }
675
676         ++phdr;
677     }
678     if (phdyn == NULL) {
679         link_elf_error("Object is not dynamically-linked");
680         error = ENOEXEC;
681         goto out;
682     }
683     if (nsegs == 0) {
684         link_elf_error("No sections");
685         error = ENOEXEC;
686         goto out;
687     }
688
689     /*
690      * Allocate the entire address space of the object, to stake out our
691      * contiguous region, and to establish the base address for relocation.
692      */
693     base_offset = trunc_page(segs[0]->p_offset);
694     base_vaddr = trunc_page(segs[0]->p_vaddr);
695     base_vlimit = round_page(segs[nsegs - 1]->p_vaddr + 
696         segs[nsegs - 1]->p_memsz);
697     mapsize = base_vlimit - base_vaddr;
698
699     lf = linker_make_file(filename, &link_elf_class);
700     if (!lf) {
701         error = ENOMEM;
702         goto out;
703     }
704
705     ef = (elf_file_t) lf;
706 #ifdef SPARSE_MAPPING
707     ef->object = vm_object_allocate(OBJT_DEFAULT, mapsize >> PAGE_SHIFT);
708     if (ef->object == NULL) {
709         error = ENOMEM;
710         goto out;
711     }
712     ef->address = (caddr_t) vm_map_min(kernel_map);
713     error = vm_map_find(kernel_map, ef->object, 0,
714                         (vm_offset_t *) &ef->address,
715                         mapsize, 1,
716                         VM_PROT_ALL, VM_PROT_ALL, 0);
717     if (error) {
718         vm_object_deallocate(ef->object);
719         ef->object = 0;
720         goto out;
721     }
722 #else
723     ef->address = malloc(mapsize, M_LINKER, M_WAITOK);
724     if (!ef->address) {
725         error = ENOMEM;
726         goto out;
727     }
728 #endif
729     mapbase = ef->address;
730
731     /*
732      * Read the text and data sections and zero the bss.
733      */
734     for (i = 0; i < nsegs; i++) {
735         caddr_t segbase = mapbase + segs[i]->p_vaddr - base_vaddr;
736         error = vn_rdwr(UIO_READ, nd.ni_vp,
737                         segbase, segs[i]->p_filesz, segs[i]->p_offset,
738                         UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred, NOCRED,
739                         &resid, td);
740         if (error) {
741             goto out;
742         }
743         bzero(segbase + segs[i]->p_filesz,
744               segs[i]->p_memsz - segs[i]->p_filesz);
745
746 #ifdef SPARSE_MAPPING
747         /*
748          * Wire down the pages
749          */
750         error = vm_map_wire(kernel_map,
751                     (vm_offset_t) segbase,
752                     (vm_offset_t) segbase + segs[i]->p_memsz,
753                     VM_MAP_WIRE_SYSTEM|VM_MAP_WIRE_NOHOLES);
754         if (error != KERN_SUCCESS) {
755             error = ENOMEM;
756             goto out;
757         }
758 #endif
759     }
760
761 #ifdef GPROF
762     /* Update profiling information with the new text segment. */
763     mtx_lock(&Giant);
764     kmupetext((uintfptr_t)(mapbase + segs[0]->p_vaddr - base_vaddr +
765         segs[0]->p_memsz));
766     mtx_unlock(&Giant);
767 #endif
768
769     ef->dynamic = (Elf_Dyn *) (mapbase + phdyn->p_vaddr - base_vaddr);
770
771     lf->address = ef->address;
772     lf->size = mapsize;
773
774     error = parse_dynamic(ef);
775     if (error)
776         goto out;
777     link_elf_reloc_local(lf);
778
779     error = linker_load_dependencies(lf);
780     if (error)
781         goto out;
782 #if 0   /* this will be more trouble than it's worth for now */
783     for (dp = ef->dynamic; dp->d_tag != DT_NULL; dp++) {
784         if (dp->d_tag != DT_NEEDED)
785             continue;
786         modname = ef->strtab + dp->d_un.d_val;
787         error = linker_load_module(modname, lf);
788         if (error)
789             goto out;
790     }
791 #endif
792     error = relocate_file(ef);
793     if (error)
794         goto out;
795
796     /* Try and load the symbol table if it's present.  (you can strip it!) */
797     nbytes = hdr->e_shnum * hdr->e_shentsize;
798     if (nbytes == 0 || hdr->e_shoff == 0)
799         goto nosyms;
800     shdr = malloc(nbytes, M_LINKER, M_WAITOK | M_ZERO);
801     if (shdr == NULL) {
802         error = ENOMEM;
803         goto out;
804     }
805     error = vn_rdwr(UIO_READ, nd.ni_vp,
806                     (caddr_t)shdr, nbytes, hdr->e_shoff,
807                     UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred, NOCRED,
808                     &resid, td);
809     if (error)
810         goto out;
811     symtabindex = -1;
812     symstrindex = -1;
813     for (i = 0; i < hdr->e_shnum; i++) {
814         if (shdr[i].sh_type == SHT_SYMTAB) {
815             symtabindex = i;
816             symstrindex = shdr[i].sh_link;
817         }
818     }
819     if (symtabindex < 0 || symstrindex < 0)
820         goto nosyms;
821
822     symcnt = shdr[symtabindex].sh_size;
823     ef->symbase = malloc(symcnt, M_LINKER, M_WAITOK);
824     strcnt = shdr[symstrindex].sh_size;
825     ef->strbase = malloc(strcnt, M_LINKER, M_WAITOK);
826
827     if (ef->symbase == NULL || ef->strbase == NULL) {
828         error = ENOMEM;
829         goto out;
830     }
831     error = vn_rdwr(UIO_READ, nd.ni_vp,
832                     ef->symbase, symcnt, shdr[symtabindex].sh_offset,
833                     UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred, NOCRED,
834                     &resid, td);
835     if (error)
836         goto out;
837     error = vn_rdwr(UIO_READ, nd.ni_vp,
838                     ef->strbase, strcnt, shdr[symstrindex].sh_offset,
839                     UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred, NOCRED,
840                     &resid, td);
841     if (error)
842         goto out;
843
844     ef->ddbsymcnt = symcnt / sizeof(Elf_Sym);
845     ef->ddbsymtab = (const Elf_Sym *)ef->symbase;
846     ef->ddbstrcnt = strcnt;
847     ef->ddbstrtab = ef->strbase;
848
849     error = link_elf_link_common_finish(lf);
850     if (error)
851         goto out;
852
853 nosyms:
854
855     *result = lf;
856
857 out:
858     if (error && lf)
859         linker_file_unload(lf, LINKER_UNLOAD_FORCE);
860     if (shdr)
861         free(shdr, M_LINKER);
862     if (firstpage)
863         free(firstpage, M_LINKER);
864     VOP_UNLOCK(nd.ni_vp, 0, td);
865     vn_close(nd.ni_vp, FREAD, td->td_ucred, td);
866     VFS_UNLOCK_GIANT(vfslocked);
867
868     return error;
869 }
870
871 static void
872 link_elf_unload_file(linker_file_t file)
873 {
874     elf_file_t ef = (elf_file_t) file;
875
876 #ifdef GDB
877     if (ef->gdb.l_ld) {
878         GDB_STATE(RT_DELETE);
879         free((void *)(uintptr_t)ef->gdb.l_name, M_LINKER);
880         link_elf_delete_gdb(&ef->gdb);
881         GDB_STATE(RT_CONSISTENT);
882     }
883 #endif
884
885     /* Notify MD code that a module is being unloaded. */
886     elf_cpu_unload_file(file);
887
888     if (ef->preloaded) {
889         link_elf_unload_preload(file);
890         return;
891     }
892
893 #ifdef SPARSE_MAPPING
894     if (ef->object) {
895         vm_map_remove(kernel_map, (vm_offset_t) ef->address,
896                       (vm_offset_t) ef->address
897                       + (ef->object->size << PAGE_SHIFT));
898     }
899 #else
900     if (ef->address)
901         free(ef->address, M_LINKER);
902 #endif
903     if (ef->symbase)
904         free(ef->symbase, M_LINKER);
905     if (ef->strbase)
906         free(ef->strbase, M_LINKER);
907 }
908
909 static void
910 link_elf_unload_preload(linker_file_t file)
911 {
912     if (file->filename)
913         preload_delete_name(file->filename);
914 }
915
916 static const char *
917 symbol_name(elf_file_t ef, Elf_Size r_info)
918 {
919     const Elf_Sym *ref;
920
921     if (ELF_R_SYM(r_info)) {
922         ref = ef->symtab + ELF_R_SYM(r_info);
923         return ef->strtab + ref->st_name;
924     } else
925         return NULL;
926 }
927
928 static int
929 relocate_file(elf_file_t ef)
930 {
931     const Elf_Rel *rellim;
932     const Elf_Rel *rel;
933     const Elf_Rela *relalim;
934     const Elf_Rela *rela;
935     const char *symname;
936
937     /* Perform relocations without addend if there are any: */
938     rel = ef->rel;
939     if (rel) {
940         rellim = (const Elf_Rel *)((const char *)ef->rel + ef->relsize);
941         while (rel < rellim) {
942             if (elf_reloc(&ef->lf, (Elf_Addr)ef->address, rel, ELF_RELOC_REL,
943                           elf_lookup)) {
944                 symname = symbol_name(ef, rel->r_info);
945                 printf("link_elf: symbol %s undefined\n", symname);
946                 return ENOENT;
947             }
948             rel++;
949         }
950     }
951
952     /* Perform relocations with addend if there are any: */
953     rela = ef->rela;
954     if (rela) {
955         relalim = (const Elf_Rela *)((const char *)ef->rela + ef->relasize);
956         while (rela < relalim) {
957             if (elf_reloc(&ef->lf, (Elf_Addr)ef->address, rela, ELF_RELOC_RELA,
958                           elf_lookup)) {
959                 symname = symbol_name(ef, rela->r_info);
960                 printf("link_elf: symbol %s undefined\n", symname);
961                 return ENOENT;
962             }
963             rela++;
964         }
965     }
966
967     /* Perform PLT relocations without addend if there are any: */
968     rel = ef->pltrel;
969     if (rel) {
970         rellim = (const Elf_Rel *)((const char *)ef->pltrel + ef->pltrelsize);
971         while (rel < rellim) {
972             if (elf_reloc(&ef->lf, (Elf_Addr)ef->address, rel, ELF_RELOC_REL,
973                           elf_lookup)) {
974                 symname = symbol_name(ef, rel->r_info);
975                 printf("link_elf: symbol %s undefined\n", symname);
976                 return ENOENT;
977             }
978             rel++;
979         }
980     }
981
982     /* Perform relocations with addend if there are any: */
983     rela = ef->pltrela;
984     if (rela) {
985         relalim = (const Elf_Rela *)((const char *)ef->pltrela + ef->pltrelasize);
986         while (rela < relalim) {
987             if (elf_reloc(&ef->lf, (Elf_Addr)ef->address, rela, ELF_RELOC_RELA,
988                           elf_lookup)) {
989                 symname = symbol_name(ef, rela->r_info);
990                 printf("link_elf: symbol %s undefined\n", symname);
991                 return ENOENT;
992             }
993             rela++;
994         }
995     }
996
997     return 0;
998 }
999
1000 /*
1001  * Hash function for symbol table lookup.  Don't even think about changing
1002  * this.  It is specified by the System V ABI.
1003  */
1004 static unsigned long
1005 elf_hash(const char *name)
1006 {
1007     const unsigned char *p = (const unsigned char *) name;
1008     unsigned long h = 0;
1009     unsigned long g;
1010
1011     while (*p != '\0') {
1012         h = (h << 4) + *p++;
1013         if ((g = h & 0xf0000000) != 0)
1014             h ^= g >> 24;
1015         h &= ~g;
1016     }
1017     return h;
1018 }
1019
1020 static int
1021 link_elf_lookup_symbol(linker_file_t lf, const char* name, c_linker_sym_t* sym)
1022 {
1023     elf_file_t ef = (elf_file_t) lf;
1024     unsigned long symnum;
1025     const Elf_Sym* symp;
1026     const char *strp;
1027     unsigned long hash;
1028     int i;
1029
1030     /* If we don't have a hash, bail. */
1031     if (ef->buckets == NULL || ef->nbuckets == 0) {
1032         printf("link_elf_lookup_symbol: missing symbol hash table\n");
1033         return ENOENT;
1034     }
1035
1036     /* First, search hashed global symbols */
1037     hash = elf_hash(name);
1038     symnum = ef->buckets[hash % ef->nbuckets];
1039
1040     while (symnum != STN_UNDEF) {
1041         if (symnum >= ef->nchains) {
1042             printf("link_elf_lookup_symbol: corrupt symbol table\n");
1043             return ENOENT;
1044         }
1045
1046         symp = ef->symtab + symnum;
1047         if (symp->st_name == 0) {
1048             printf("link_elf_lookup_symbol: corrupt symbol table\n");
1049             return ENOENT;
1050         }
1051
1052         strp = ef->strtab + symp->st_name;
1053
1054         if (strcmp(name, strp) == 0) {
1055             if (symp->st_shndx != SHN_UNDEF ||
1056                 (symp->st_value != 0 &&
1057                  ELF_ST_TYPE(symp->st_info) == STT_FUNC)) {
1058                 *sym = (c_linker_sym_t) symp;
1059                 return 0;
1060             } else
1061                 return ENOENT;
1062         }
1063
1064         symnum = ef->chains[symnum];
1065     }
1066
1067     /* If we have not found it, look at the full table (if loaded) */
1068     if (ef->symtab == ef->ddbsymtab)
1069         return ENOENT;
1070
1071     /* Exhaustive search */
1072     for (i = 0, symp = ef->ddbsymtab; i < ef->ddbsymcnt; i++, symp++) {
1073         strp = ef->ddbstrtab + symp->st_name;
1074         if (strcmp(name, strp) == 0) {
1075             if (symp->st_shndx != SHN_UNDEF ||
1076                 (symp->st_value != 0 &&
1077                  ELF_ST_TYPE(symp->st_info) == STT_FUNC)) {
1078                 *sym = (c_linker_sym_t) symp;
1079                 return 0;
1080             } else
1081                 return ENOENT;
1082         }
1083     }
1084
1085     return ENOENT;
1086 }
1087
1088 static int
1089 link_elf_symbol_values(linker_file_t lf, c_linker_sym_t sym, linker_symval_t* symval)
1090 {
1091         elf_file_t ef = (elf_file_t) lf;
1092         const Elf_Sym* es = (const Elf_Sym*) sym;
1093
1094         if (es >= ef->symtab && es < (ef->symtab + ef->nchains)) {
1095             symval->name = ef->strtab + es->st_name;
1096             symval->value = (caddr_t) ef->address + es->st_value;
1097             symval->size = es->st_size;
1098             return 0;
1099         }
1100         if (ef->symtab == ef->ddbsymtab)
1101             return ENOENT;
1102         if (es >= ef->ddbsymtab && es < (ef->ddbsymtab + ef->ddbsymcnt)) {
1103             symval->name = ef->ddbstrtab + es->st_name;
1104             symval->value = (caddr_t) ef->address + es->st_value;
1105             symval->size = es->st_size;
1106             return 0;
1107         }
1108         return ENOENT;
1109 }
1110
1111 static int
1112 link_elf_search_symbol(linker_file_t lf, caddr_t value,
1113                        c_linker_sym_t* sym, long* diffp)
1114 {
1115         elf_file_t ef = (elf_file_t) lf;
1116         u_long off = (uintptr_t) (void *) value;
1117         u_long diff = off;
1118         u_long st_value;
1119         const Elf_Sym* es;
1120         const Elf_Sym* best = 0;
1121         int i;
1122
1123         for (i = 0, es = ef->ddbsymtab; i < ef->ddbsymcnt; i++, es++) {
1124                 if (es->st_name == 0)
1125                         continue;
1126                 st_value = es->st_value + (uintptr_t) (void *) ef->address;
1127                 if (off >= st_value) {
1128                         if (off - st_value < diff) {
1129                                 diff = off - st_value;
1130                                 best = es;
1131                                 if (diff == 0)
1132                                         break;
1133                         } else if (off - st_value == diff) {
1134                                 best = es;
1135                         }
1136                 }
1137         }
1138         if (best == 0)
1139                 *diffp = off;
1140         else
1141                 *diffp = diff;
1142         *sym = (c_linker_sym_t) best;
1143
1144         return 0;
1145 }
1146
1147 /*
1148  * Look up a linker set on an ELF system.
1149  */
1150 static int
1151 link_elf_lookup_set(linker_file_t lf, const char *name,
1152                     void ***startp, void ***stopp, int *countp)
1153 {
1154         c_linker_sym_t sym;
1155         linker_symval_t symval;
1156         char *setsym;
1157         void **start, **stop;
1158         int len, error = 0, count;
1159
1160         len = strlen(name) + sizeof("__start_set_"); /* sizeof includes \0 */
1161         setsym = malloc(len, M_LINKER, M_WAITOK);
1162         if (setsym == NULL)
1163                 return ENOMEM;
1164
1165         /* get address of first entry */
1166         snprintf(setsym, len, "%s%s", "__start_set_", name);
1167         error = link_elf_lookup_symbol(lf, setsym, &sym);
1168         if (error)
1169                 goto out;
1170         link_elf_symbol_values(lf, sym, &symval);
1171         if (symval.value == 0) {
1172                 error = ESRCH;
1173                 goto out;
1174         }
1175         start = (void **)symval.value;
1176
1177         /* get address of last entry */
1178         snprintf(setsym, len, "%s%s", "__stop_set_", name);
1179         error = link_elf_lookup_symbol(lf, setsym, &sym);
1180         if (error)
1181                 goto out;
1182         link_elf_symbol_values(lf, sym, &symval);
1183         if (symval.value == 0) {
1184                 error = ESRCH;
1185                 goto out;
1186         }
1187         stop = (void **)symval.value;
1188
1189         /* and the number of entries */
1190         count = stop - start;
1191
1192         /* and copy out */
1193         if (startp)
1194                 *startp = start;
1195         if (stopp)
1196                 *stopp = stop;
1197         if (countp)
1198                 *countp = count;
1199
1200 out:
1201         free(setsym, M_LINKER);
1202         return error;
1203 }
1204
1205 static int
1206 link_elf_each_function_name(linker_file_t file,
1207   int (*callback)(const char *, void *), void *opaque) {
1208     elf_file_t ef = (elf_file_t)file;
1209     const Elf_Sym* symp;
1210     int i, error;
1211         
1212     /* Exhaustive search */
1213     for (i = 0, symp = ef->ddbsymtab; i < ef->ddbsymcnt; i++, symp++) {
1214         if (symp->st_value != 0 &&
1215             ELF_ST_TYPE(symp->st_info) == STT_FUNC) {
1216                 error = callback(ef->ddbstrtab + symp->st_name, opaque);
1217                 if (error)
1218                     return (error);
1219         }
1220     }
1221     return (0);
1222 }
1223
1224 #ifdef __ia64__
1225 /*
1226  * Each KLD has its own GP. The GP value for each load module is given by
1227  * DT_PLTGOT on ia64. We need GP to construct function descriptors, but
1228  * don't have direct access to the ELF file structure. The link_elf_get_gp()
1229  * function returns the GP given a pointer to a generic linker file struct.
1230  */
1231 Elf_Addr
1232 link_elf_get_gp(linker_file_t lf)
1233 {
1234         elf_file_t ef = (elf_file_t)lf;
1235         return (Elf_Addr)ef->got;
1236 }
1237 #endif
1238
1239 const Elf_Sym *
1240 elf_get_sym(linker_file_t lf, Elf_Size symidx)
1241 {
1242         elf_file_t ef = (elf_file_t)lf;
1243
1244         if (symidx >= ef->nchains)
1245                 return (NULL);
1246         return (ef->symtab + symidx);
1247 }
1248
1249 const char *
1250 elf_get_symname(linker_file_t lf, Elf_Size symidx)
1251 {
1252         elf_file_t ef = (elf_file_t)lf;
1253         const Elf_Sym *sym;
1254
1255         if (symidx >= ef->nchains)
1256                 return (NULL);
1257         sym = ef->symtab + symidx;
1258         return (ef->strtab + sym->st_name);
1259 }
1260
1261 /*
1262  * Symbol lookup function that can be used when the symbol index is known (ie
1263  * in relocations). It uses the symbol index instead of doing a fully fledged
1264  * hash table based lookup when such is valid. For example for local symbols.
1265  * This is not only more efficient, it's also more correct. It's not always
1266  * the case that the symbol can be found through the hash table.
1267  */
1268 static Elf_Addr
1269 elf_lookup(linker_file_t lf, Elf_Size symidx, int deps)
1270 {
1271         elf_file_t ef = (elf_file_t)lf;
1272         const Elf_Sym *sym;
1273         const char *symbol;
1274
1275         /* Don't even try to lookup the symbol if the index is bogus. */
1276         if (symidx >= ef->nchains)
1277                 return (0);
1278
1279         sym = ef->symtab + symidx;
1280
1281         /*
1282          * Don't do a full lookup when the symbol is local. It may even
1283          * fail because it may not be found through the hash table.
1284          */
1285         if (ELF_ST_BIND(sym->st_info) == STB_LOCAL) {
1286                 /* Force lookup failure when we have an insanity. */
1287                 if (sym->st_shndx == SHN_UNDEF || sym->st_value == 0)
1288                         return (0);
1289                 return ((Elf_Addr)ef->address + sym->st_value);
1290         }
1291
1292         /*
1293          * XXX we can avoid doing a hash table based lookup for global
1294          * symbols as well. This however is not always valid, so we'll
1295          * just do it the hard way for now. Performance tweaks can
1296          * always be added.
1297          */
1298
1299         symbol = ef->strtab + sym->st_name;
1300
1301         /* Force a lookup failure if the symbol name is bogus. */
1302         if (*symbol == 0)
1303                 return (0);
1304
1305         return ((Elf_Addr)linker_file_lookup_symbol(lf, symbol, deps));
1306 }
1307
1308 static void
1309 link_elf_reloc_local(linker_file_t lf)
1310 {
1311     const Elf_Rel *rellim;
1312     const Elf_Rel *rel;
1313     const Elf_Rela *relalim;
1314     const Elf_Rela *rela;
1315     elf_file_t ef = (elf_file_t)lf;
1316
1317     /* Perform relocations without addend if there are any: */
1318     if ((rel = ef->rel) != NULL) {
1319         rellim = (const Elf_Rel *)((const char *)ef->rel + ef->relsize);
1320         while (rel < rellim) {
1321             elf_reloc_local(lf, (Elf_Addr)ef->address, rel, ELF_RELOC_REL,
1322                             elf_lookup);
1323             rel++;
1324         }
1325     }
1326
1327     /* Perform relocations with addend if there are any: */
1328     if ((rela = ef->rela) != NULL) {
1329         relalim = (const Elf_Rela *)((const char *)ef->rela + ef->relasize);
1330         while (rela < relalim) {
1331             elf_reloc_local(lf, (Elf_Addr)ef->address, rela, ELF_RELOC_RELA,
1332                             elf_lookup);
1333             rela++;
1334         }
1335     }
1336 }