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