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