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