xref: /freebsd/sys/kern/link_elf.c (revision a687910fc4352117413b8e0275383e4c687d4c4c)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
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 #include "opt_ddb.h"
31 #include "opt_gdb.h"
32 
33 #include <sys/param.h>
34 #include <sys/systm.h>
35 #include <sys/kernel.h>
36 #include <sys/lock.h>
37 #include <sys/malloc.h>
38 #ifdef SPARSE_MAPPING
39 #include <sys/mman.h>
40 #endif
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 #include <sys/sysctl.h>
50 #include <sys/tslog.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 #include "linker_if.h"
71 
72 #define MAXSEGS 4
73 
74 typedef struct elf_file {
75 	struct linker_file lf;		/* Common fields */
76 	int		preloaded;	/* Was file pre-loaded */
77 	caddr_t		address;	/* Relocation address */
78 #ifdef SPARSE_MAPPING
79 	vm_object_t	object;		/* VM object to hold file pages */
80 #endif
81 	Elf_Dyn		*dynamic;	/* Symbol table etc. */
82 	Elf_Hashelt	nbuckets;	/* DT_HASH info */
83 	Elf_Hashelt	nchains;
84 	const Elf_Hashelt *buckets;
85 	const Elf_Hashelt *chains;
86 	caddr_t		hash;
87 	caddr_t		strtab;		/* DT_STRTAB */
88 	int		strsz;		/* DT_STRSZ */
89 	const Elf_Sym	*symtab;		/* DT_SYMTAB */
90 	Elf_Addr	*got;		/* DT_PLTGOT */
91 	const Elf_Rel	*pltrel;	/* DT_JMPREL */
92 	int		pltrelsize;	/* DT_PLTRELSZ */
93 	const Elf_Rela	*pltrela;	/* DT_JMPREL */
94 	int		pltrelasize;	/* DT_PLTRELSZ */
95 	const Elf_Rel	*rel;		/* DT_REL */
96 	int		relsize;	/* DT_RELSZ */
97 	const Elf_Rela	*rela;		/* DT_RELA */
98 	int		relasize;	/* DT_RELASZ */
99 	caddr_t		modptr;
100 	const Elf_Sym	*ddbsymtab;	/* The symbol table we are using */
101 	long		ddbsymcnt;	/* Number of symbols */
102 	caddr_t		ddbstrtab;	/* String table */
103 	long		ddbstrcnt;	/* number of bytes in string table */
104 	caddr_t		symbase;	/* malloc'ed symbold base */
105 	caddr_t		strbase;	/* malloc'ed string base */
106 	caddr_t		ctftab;		/* CTF table */
107 	long		ctfcnt;		/* number of bytes in CTF table */
108 	caddr_t		ctfoff;		/* CTF offset table */
109 	caddr_t		typoff;		/* Type offset table */
110 	long		typlen;		/* Number of type entries. */
111 	Elf_Addr	pcpu_start;	/* Pre-relocation pcpu set start. */
112 	Elf_Addr	pcpu_stop;	/* Pre-relocation pcpu set stop. */
113 	Elf_Addr	pcpu_base;	/* Relocated pcpu set address. */
114 #ifdef VIMAGE
115 	Elf_Addr	vnet_start;	/* Pre-relocation vnet set start. */
116 	Elf_Addr	vnet_stop;	/* Pre-relocation vnet set stop. */
117 	Elf_Addr	vnet_base;	/* Relocated vnet set address. */
118 #endif
119 #ifdef GDB
120 	struct link_map	gdb;		/* hooks for gdb */
121 #endif
122 } *elf_file_t;
123 
124 struct elf_set {
125 	Elf_Addr	es_start;
126 	Elf_Addr	es_stop;
127 	Elf_Addr	es_base;
128 	TAILQ_ENTRY(elf_set)	es_link;
129 };
130 
131 TAILQ_HEAD(elf_set_head, elf_set);
132 
133 #include <kern/kern_ctf.c>
134 
135 static int	link_elf_link_common_finish(linker_file_t);
136 static int	link_elf_link_preload(linker_class_t cls,
137 				      const char *, linker_file_t *);
138 static int	link_elf_link_preload_finish(linker_file_t);
139 static int	link_elf_load_file(linker_class_t, const char *,
140 		    linker_file_t *);
141 static int	link_elf_lookup_symbol(linker_file_t, const char *,
142 		    c_linker_sym_t *);
143 static int	link_elf_lookup_debug_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_debug_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 #ifdef VIMAGE
164 static void	link_elf_propagate_vnets(linker_file_t);
165 #endif
166 static int	elf_lookup(linker_file_t, Elf_Size, int, Elf_Addr *);
167 
168 static kobj_method_t link_elf_methods[] = {
169 	KOBJMETHOD(linker_lookup_symbol,	link_elf_lookup_symbol),
170 	KOBJMETHOD(linker_lookup_debug_symbol,	link_elf_lookup_debug_symbol),
171 	KOBJMETHOD(linker_symbol_values,	link_elf_symbol_values),
172 	KOBJMETHOD(linker_debug_symbol_values,	link_elf_debug_symbol_values),
173 	KOBJMETHOD(linker_search_symbol,	link_elf_search_symbol),
174 	KOBJMETHOD(linker_unload,		link_elf_unload_file),
175 	KOBJMETHOD(linker_load_file,		link_elf_load_file),
176 	KOBJMETHOD(linker_link_preload,		link_elf_link_preload),
177 	KOBJMETHOD(linker_link_preload_finish,	link_elf_link_preload_finish),
178 	KOBJMETHOD(linker_lookup_set,		link_elf_lookup_set),
179 	KOBJMETHOD(linker_each_function_name,	link_elf_each_function_name),
180 	KOBJMETHOD(linker_each_function_nameval, link_elf_each_function_nameval),
181 	KOBJMETHOD(linker_ctf_get,		link_elf_ctf_get),
182 	KOBJMETHOD(linker_symtab_get,		link_elf_symtab_get),
183 	KOBJMETHOD(linker_strtab_get,		link_elf_strtab_get),
184 #ifdef VIMAGE
185 	KOBJMETHOD(linker_propagate_vnets,	link_elf_propagate_vnets),
186 #endif
187 	KOBJMETHOD_END
188 };
189 
190 static struct linker_class link_elf_class = {
191 #if ELF_TARG_CLASS == ELFCLASS32
192 	"elf32",
193 #else
194 	"elf64",
195 #endif
196 	link_elf_methods, sizeof(struct elf_file)
197 };
198 
199 static bool link_elf_leak_locals = true;
200 SYSCTL_BOOL(_debug, OID_AUTO, link_elf_leak_locals,
201     CTLFLAG_RWTUN, &link_elf_leak_locals, 0,
202     "Allow local symbols to participate in global module symbol resolution");
203 
204 typedef int (*elf_reloc_fn)(linker_file_t lf, Elf_Addr relocbase,
205     const void *data, int type, elf_lookup_fn lookup);
206 
207 static int	parse_dynamic(elf_file_t);
208 static int	relocate_file(elf_file_t);
209 static int	relocate_file1(elf_file_t ef, elf_lookup_fn lookup,
210 		    elf_reloc_fn reloc, bool ifuncs);
211 static int	link_elf_preload_parse_symbols(elf_file_t);
212 
213 static struct elf_set_head set_pcpu_list;
214 #ifdef VIMAGE
215 static struct elf_set_head set_vnet_list;
216 #endif
217 
218 static void
219 elf_set_add(struct elf_set_head *list, Elf_Addr start, Elf_Addr stop, Elf_Addr base)
220 {
221 	struct elf_set *set, *iter;
222 
223 	set = malloc(sizeof(*set), M_LINKER, M_WAITOK);
224 	set->es_start = start;
225 	set->es_stop = stop;
226 	set->es_base = base;
227 
228 	TAILQ_FOREACH(iter, list, es_link) {
229 		KASSERT((set->es_start < iter->es_start && set->es_stop < iter->es_stop) ||
230 		    (set->es_start > iter->es_start && set->es_stop > iter->es_stop),
231 		    ("linker sets intersection: to insert: 0x%jx-0x%jx; inserted: 0x%jx-0x%jx",
232 		    (uintmax_t)set->es_start, (uintmax_t)set->es_stop,
233 		    (uintmax_t)iter->es_start, (uintmax_t)iter->es_stop));
234 
235 		if (iter->es_start > set->es_start) {
236 			TAILQ_INSERT_BEFORE(iter, set, es_link);
237 			break;
238 		}
239 	}
240 
241 	if (iter == NULL)
242 		TAILQ_INSERT_TAIL(list, set, es_link);
243 }
244 
245 static int
246 elf_set_find(struct elf_set_head *list, Elf_Addr addr, Elf_Addr *start, Elf_Addr *base)
247 {
248 	struct elf_set *set;
249 
250 	TAILQ_FOREACH(set, list, es_link) {
251 		if (addr < set->es_start)
252 			return (0);
253 		if (addr < set->es_stop) {
254 			*start = set->es_start;
255 			*base = set->es_base;
256 			return (1);
257 		}
258 	}
259 
260 	return (0);
261 }
262 
263 static void
264 elf_set_delete(struct elf_set_head *list, Elf_Addr start)
265 {
266 	struct elf_set *set;
267 
268 	TAILQ_FOREACH(set, list, es_link) {
269 		if (start < set->es_start)
270 			break;
271 		if (start == set->es_start) {
272 			TAILQ_REMOVE(list, set, es_link);
273 			free(set, M_LINKER);
274 			return;
275 		}
276 	}
277 	KASSERT(0, ("deleting unknown linker set (start = 0x%jx)",
278 	    (uintmax_t)start));
279 }
280 
281 #ifdef GDB
282 static void	r_debug_state(struct r_debug *, struct link_map *);
283 
284 /*
285  * A list of loaded modules for GDB to use for loading symbols.
286  */
287 struct r_debug r_debug;
288 
289 #define GDB_STATE(s) do {				\
290 	r_debug.r_state = s; r_debug_state(NULL, NULL);	\
291 } while (0)
292 
293 /*
294  * Function for the debugger to set a breakpoint on to gain control.
295  */
296 static void
297 r_debug_state(struct r_debug *dummy_one __unused,
298 	      struct link_map *dummy_two __unused)
299 {
300 }
301 
302 static void
303 link_elf_add_gdb(struct link_map *l)
304 {
305 	struct link_map *prev;
306 
307 	l->l_next = NULL;
308 
309 	if (r_debug.r_map == NULL) {
310 		/* Add first. */
311 		l->l_prev = NULL;
312 		r_debug.r_map = l;
313 	} else {
314 		/* Append to list. */
315 		for (prev = r_debug.r_map;
316 		    prev->l_next != NULL;
317 		    prev = prev->l_next)
318 			;
319 		l->l_prev = prev;
320 		prev->l_next = l;
321 	}
322 }
323 
324 static void
325 link_elf_delete_gdb(struct link_map *l)
326 {
327 	if (l->l_prev == NULL) {
328 		/* Remove first. */
329 		if ((r_debug.r_map = l->l_next) != NULL)
330 			l->l_next->l_prev = NULL;
331 	} else {
332 		/* Remove any but first. */
333 		if ((l->l_prev->l_next = l->l_next) != NULL)
334 			l->l_next->l_prev = l->l_prev;
335 	}
336 }
337 #endif /* GDB */
338 
339 /*
340  * The kernel symbol table starts here.
341  */
342 extern struct _dynamic _DYNAMIC;
343 
344 static void
345 link_elf_error(const char *filename, const char *s)
346 {
347 	if (filename == NULL)
348 		printf("kldload: %s\n", s);
349 	else
350 		printf("kldload: %s: %s\n", filename, s);
351 }
352 
353 static void
354 link_elf_invoke_ctors(caddr_t addr, size_t size)
355 {
356 	void (**ctor)(void);
357 	size_t i, cnt;
358 
359 	if (addr == NULL || size == 0)
360 		return;
361 	cnt = size / sizeof(*ctor);
362 	ctor = (void *)addr;
363 	for (i = 0; i < cnt; i++) {
364 		if (ctor[i] != NULL)
365 			(*ctor[i])();
366 	}
367 }
368 
369 /*
370  * Actions performed after linking/loading both the preloaded kernel and any
371  * modules; whether preloaded or dynamicly loaded.
372  */
373 static int
374 link_elf_link_common_finish(linker_file_t lf)
375 {
376 #ifdef GDB
377 	elf_file_t ef = (elf_file_t)lf;
378 	char *newfilename;
379 #endif
380 	int error;
381 
382 	/* Notify MD code that a module is being loaded. */
383 	error = elf_cpu_load_file(lf);
384 	if (error != 0)
385 		return (error);
386 
387 #ifdef GDB
388 	GDB_STATE(RT_ADD);
389 	ef->gdb.l_addr = lf->address;
390 	newfilename = malloc(strlen(lf->filename) + 1, M_LINKER, M_WAITOK);
391 	strcpy(newfilename, lf->filename);
392 	ef->gdb.l_name = newfilename;
393 	ef->gdb.l_ld = ef->dynamic;
394 	link_elf_add_gdb(&ef->gdb);
395 	GDB_STATE(RT_CONSISTENT);
396 #endif
397 
398 	/* Invoke .ctors */
399 	link_elf_invoke_ctors(lf->ctors_addr, lf->ctors_size);
400 	return (0);
401 }
402 
403 #ifdef RELOCATABLE_KERNEL
404 /*
405  * __startkernel and __endkernel are symbols set up as relocation canaries.
406  *
407  * They are defined in locore to reference linker script symbols at the
408  * beginning and end of the LOAD area. This has the desired side effect of
409  * giving us variables that have relative relocations pointing at them, so
410  * relocation of the kernel object will cause the variables to be updated
411  * automatically by the runtime linker when we initialize.
412  *
413  * There are two main reasons to relocate the kernel:
414  * 1) If the loader needed to load the kernel at an alternate load address.
415  * 2) If the kernel is switching address spaces on machines like POWER9
416  *    under Radix where the high bits of the effective address are used to
417  *    differentiate between hypervisor, host, guest, and problem state.
418  */
419 extern vm_offset_t __startkernel, __endkernel;
420 #endif
421 
422 static unsigned long kern_relbase = KERNBASE;
423 
424 SYSCTL_ULONG(_kern, OID_AUTO, base_address, CTLFLAG_RD,
425 	SYSCTL_NULL_ULONG_PTR, KERNBASE, "Kernel base address");
426 SYSCTL_ULONG(_kern, OID_AUTO, relbase_address, CTLFLAG_RD,
427 	&kern_relbase, 0, "Kernel relocated base address");
428 
429 static void
430 link_elf_init(void* arg)
431 {
432 	Elf_Dyn *dp;
433 	Elf_Addr *ctors_addrp;
434 	Elf_Size *ctors_sizep;
435 	caddr_t modptr, baseptr, sizeptr;
436 	elf_file_t ef;
437 	const char *modname;
438 
439 	linker_add_class(&link_elf_class);
440 
441 	dp = (Elf_Dyn *)&_DYNAMIC;
442 	modname = NULL;
443 	modptr = preload_search_by_type("elf" __XSTRING(__ELF_WORD_SIZE) " kernel");
444 	if (modptr == NULL)
445 		modptr = preload_search_by_type("elf kernel");
446 	modname = (char *)preload_search_info(modptr, MODINFO_NAME);
447 	if (modname == NULL)
448 		modname = "kernel";
449 	linker_kernel_file = linker_make_file(modname, &link_elf_class);
450 	if (linker_kernel_file == NULL)
451 		panic("%s: Can't create linker structures for kernel",
452 		    __func__);
453 
454 	ef = (elf_file_t) linker_kernel_file;
455 	ef->preloaded = 1;
456 #ifdef RELOCATABLE_KERNEL
457 	/* Compute relative displacement */
458 	ef->address = (caddr_t) (__startkernel - KERNBASE);
459 #else
460 	ef->address = 0;
461 #endif
462 #ifdef SPARSE_MAPPING
463 	ef->object = NULL;
464 #endif
465 	ef->dynamic = dp;
466 
467 	if (dp != NULL)
468 		parse_dynamic(ef);
469 #ifdef RELOCATABLE_KERNEL
470 	linker_kernel_file->address = (caddr_t)__startkernel;
471 	linker_kernel_file->size = (intptr_t)(__endkernel - __startkernel);
472 	kern_relbase = (unsigned long)__startkernel;
473 #else
474 	linker_kernel_file->address += KERNBASE;
475 	linker_kernel_file->size = -(intptr_t)linker_kernel_file->address;
476 #endif
477 
478 	if (modptr != NULL) {
479 		ef->modptr = modptr;
480 		baseptr = preload_search_info(modptr, MODINFO_ADDR);
481 		if (baseptr != NULL)
482 			linker_kernel_file->address = *(caddr_t *)baseptr;
483 		sizeptr = preload_search_info(modptr, MODINFO_SIZE);
484 		if (sizeptr != NULL)
485 			linker_kernel_file->size = *(size_t *)sizeptr;
486 		ctors_addrp = (Elf_Addr *)preload_search_info(modptr,
487 			MODINFO_METADATA | MODINFOMD_CTORS_ADDR);
488 		ctors_sizep = (Elf_Size *)preload_search_info(modptr,
489 			MODINFO_METADATA | MODINFOMD_CTORS_SIZE);
490 		if (ctors_addrp != NULL && ctors_sizep != NULL) {
491 			linker_kernel_file->ctors_addr = ef->address +
492 			    *ctors_addrp;
493 			linker_kernel_file->ctors_size = *ctors_sizep;
494 		}
495 	}
496 	(void)link_elf_preload_parse_symbols(ef);
497 
498 #ifdef GDB
499 	r_debug.r_map = NULL;
500 	r_debug.r_brk = r_debug_state;
501 	r_debug.r_state = RT_CONSISTENT;
502 #endif
503 
504 	(void)link_elf_link_common_finish(linker_kernel_file);
505 	linker_kernel_file->flags |= LINKER_FILE_LINKED;
506 	TAILQ_INIT(&set_pcpu_list);
507 #ifdef VIMAGE
508 	TAILQ_INIT(&set_vnet_list);
509 #endif
510 }
511 
512 SYSINIT(link_elf, SI_SUB_KLD, SI_ORDER_THIRD, link_elf_init, NULL);
513 
514 static int
515 link_elf_preload_parse_symbols(elf_file_t ef)
516 {
517 	caddr_t pointer;
518 	caddr_t ssym, esym, base;
519 	caddr_t strtab;
520 	int strcnt;
521 	Elf_Sym *symtab;
522 	int symcnt;
523 
524 	if (ef->modptr == NULL)
525 		return (0);
526 	pointer = preload_search_info(ef->modptr,
527 	    MODINFO_METADATA | MODINFOMD_SSYM);
528 	if (pointer == NULL)
529 		return (0);
530 	ssym = *(caddr_t *)pointer;
531 	pointer = preload_search_info(ef->modptr,
532 	    MODINFO_METADATA | MODINFOMD_ESYM);
533 	if (pointer == NULL)
534 		return (0);
535 	esym = *(caddr_t *)pointer;
536 
537 	base = ssym;
538 
539 	symcnt = *(long *)base;
540 	base += sizeof(long);
541 	symtab = (Elf_Sym *)base;
542 	base += roundup(symcnt, sizeof(long));
543 
544 	if (base > esym || base < ssym) {
545 		printf("Symbols are corrupt!\n");
546 		return (EINVAL);
547 	}
548 
549 	strcnt = *(long *)base;
550 	base += sizeof(long);
551 	strtab = base;
552 	base += roundup(strcnt, sizeof(long));
553 
554 	if (base > esym || base < ssym) {
555 		printf("Symbols are corrupt!\n");
556 		return (EINVAL);
557 	}
558 
559 	ef->ddbsymtab = symtab;
560 	ef->ddbsymcnt = symcnt / sizeof(Elf_Sym);
561 	ef->ddbstrtab = strtab;
562 	ef->ddbstrcnt = strcnt;
563 
564 	return (0);
565 }
566 
567 static int
568 parse_dynamic(elf_file_t ef)
569 {
570 	Elf_Dyn *dp;
571 	int plttype = DT_REL;
572 
573 	for (dp = ef->dynamic; dp->d_tag != DT_NULL; dp++) {
574 		switch (dp->d_tag) {
575 		case DT_HASH:
576 		{
577 			/* From src/libexec/rtld-elf/rtld.c */
578 			const Elf_Hashelt *hashtab = (const Elf_Hashelt *)
579 			    (ef->address + dp->d_un.d_ptr);
580 			ef->nbuckets = hashtab[0];
581 			ef->nchains = hashtab[1];
582 			ef->buckets = hashtab + 2;
583 			ef->chains = ef->buckets + ef->nbuckets;
584 			break;
585 		}
586 		case DT_STRTAB:
587 			ef->strtab = (caddr_t) (ef->address + dp->d_un.d_ptr);
588 			break;
589 		case DT_STRSZ:
590 			ef->strsz = dp->d_un.d_val;
591 			break;
592 		case DT_SYMTAB:
593 			ef->symtab = (Elf_Sym*) (ef->address + dp->d_un.d_ptr);
594 			break;
595 		case DT_SYMENT:
596 			if (dp->d_un.d_val != sizeof(Elf_Sym))
597 				return (ENOEXEC);
598 			break;
599 		case DT_PLTGOT:
600 			ef->got = (Elf_Addr *) (ef->address + dp->d_un.d_ptr);
601 			break;
602 		case DT_REL:
603 			ef->rel = (const Elf_Rel *) (ef->address + dp->d_un.d_ptr);
604 			break;
605 		case DT_RELSZ:
606 			ef->relsize = dp->d_un.d_val;
607 			break;
608 		case DT_RELENT:
609 			if (dp->d_un.d_val != sizeof(Elf_Rel))
610 				return (ENOEXEC);
611 			break;
612 		case DT_JMPREL:
613 			ef->pltrel = (const Elf_Rel *) (ef->address + dp->d_un.d_ptr);
614 			break;
615 		case DT_PLTRELSZ:
616 			ef->pltrelsize = dp->d_un.d_val;
617 			break;
618 		case DT_RELA:
619 			ef->rela = (const Elf_Rela *) (ef->address + dp->d_un.d_ptr);
620 			break;
621 		case DT_RELASZ:
622 			ef->relasize = dp->d_un.d_val;
623 			break;
624 		case DT_RELAENT:
625 			if (dp->d_un.d_val != sizeof(Elf_Rela))
626 				return (ENOEXEC);
627 			break;
628 		case DT_PLTREL:
629 			plttype = dp->d_un.d_val;
630 			if (plttype != DT_REL && plttype != DT_RELA)
631 				return (ENOEXEC);
632 			break;
633 #ifdef GDB
634 		case DT_DEBUG:
635 			dp->d_un.d_ptr = (Elf_Addr)&r_debug;
636 			break;
637 #endif
638 		}
639 	}
640 
641 	if (plttype == DT_RELA) {
642 		ef->pltrela = (const Elf_Rela *)ef->pltrel;
643 		ef->pltrel = NULL;
644 		ef->pltrelasize = ef->pltrelsize;
645 		ef->pltrelsize = 0;
646 	}
647 
648 	ef->ddbsymtab = ef->symtab;
649 	ef->ddbsymcnt = ef->nchains;
650 	ef->ddbstrtab = ef->strtab;
651 	ef->ddbstrcnt = ef->strsz;
652 
653 	return elf_cpu_parse_dynamic(ef->address, ef->dynamic);
654 }
655 
656 #define	LS_PADDING	0x90909090
657 static int
658 parse_dpcpu(elf_file_t ef)
659 {
660 	int error, size;
661 #if defined(__i386__)
662 	uint32_t pad;
663 #endif
664 
665 	ef->pcpu_start = 0;
666 	ef->pcpu_stop = 0;
667 	error = link_elf_lookup_set(&ef->lf, "pcpu", (void ***)&ef->pcpu_start,
668 	    (void ***)&ef->pcpu_stop, NULL);
669 	/* Error just means there is no pcpu set to relocate. */
670 	if (error != 0)
671 		return (0);
672 	size = (uintptr_t)ef->pcpu_stop - (uintptr_t)ef->pcpu_start;
673 	/* Empty set? */
674 	if (size < 1)
675 		return (0);
676 #if defined(__i386__)
677 	/* In case we do find __start/stop_set_ symbols double-check. */
678 	if (size < 4) {
679 		uprintf("Kernel module '%s' must be recompiled with "
680 		    "linker script\n", ef->lf.pathname);
681 		return (ENOEXEC);
682 	}
683 
684 	/* Padding from linker-script correct? */
685 	pad = *(uint32_t *)((uintptr_t)ef->pcpu_stop - sizeof(pad));
686 	if (pad != LS_PADDING) {
687 		uprintf("Kernel module '%s' must be recompiled with "
688 		    "linker script, invalid padding %#04x (%#04x)\n",
689 		    ef->lf.pathname, pad, LS_PADDING);
690 		return (ENOEXEC);
691 	}
692 	/* If we only have valid padding, nothing to do. */
693 	if (size == 4)
694 		return (0);
695 #endif
696 	/*
697 	 * Allocate space in the primary pcpu area.  Copy in our
698 	 * initialization from the data section and then initialize
699 	 * all per-cpu storage from that.
700 	 */
701 	ef->pcpu_base = (Elf_Addr)(uintptr_t)dpcpu_alloc(size);
702 	if (ef->pcpu_base == 0) {
703 		printf("%s: pcpu module space is out of space; "
704 		    "cannot allocate %d for %s\n",
705 		    __func__, size, ef->lf.pathname);
706 		return (ENOSPC);
707 	}
708 	memcpy((void *)ef->pcpu_base, (void *)ef->pcpu_start, size);
709 	dpcpu_copy((void *)ef->pcpu_base, size);
710 	elf_set_add(&set_pcpu_list, ef->pcpu_start, ef->pcpu_stop,
711 	    ef->pcpu_base);
712 
713 	return (0);
714 }
715 
716 #ifdef VIMAGE
717 static int
718 parse_vnet(elf_file_t ef)
719 {
720 	int error, size;
721 #if defined(__i386__)
722 	uint32_t pad;
723 #endif
724 
725 	ef->vnet_start = 0;
726 	ef->vnet_stop = 0;
727 	ef->vnet_base = 0;
728 	error = link_elf_lookup_set(&ef->lf, "vnet", (void ***)&ef->vnet_start,
729 	    (void ***)&ef->vnet_stop, NULL);
730 	/* Error just means there is no vnet data set to relocate. */
731 	if (error != 0)
732 		return (0);
733 	size = (uintptr_t)ef->vnet_stop - (uintptr_t)ef->vnet_start;
734 	/* Empty set? */
735 	if (size < 1)
736 		return (0);
737 #if defined(__i386__)
738 	/* In case we do find __start/stop_set_ symbols double-check. */
739 	if (size < 4) {
740 		uprintf("Kernel module '%s' must be recompiled with "
741 		    "linker script\n", ef->lf.pathname);
742 		return (ENOEXEC);
743 	}
744 
745 	/* Padding from linker-script correct? */
746 	pad = *(uint32_t *)((uintptr_t)ef->vnet_stop - sizeof(pad));
747 	if (pad != LS_PADDING) {
748 		uprintf("Kernel module '%s' must be recompiled with "
749 		    "linker script, invalid padding %#04x (%#04x)\n",
750 		    ef->lf.pathname, pad, LS_PADDING);
751 		return (ENOEXEC);
752 	}
753 	/* If we only have valid padding, nothing to do. */
754 	if (size == 4)
755 		return (0);
756 #endif
757 	/*
758 	 * Allocate space in the primary vnet area.  Copy in our
759 	 * initialization from the data section and then initialize
760 	 * all per-vnet storage from that.
761 	 */
762 	ef->vnet_base = (Elf_Addr)(uintptr_t)vnet_data_alloc(size);
763 	if (ef->vnet_base == 0) {
764 		printf("%s: vnet module space is out of space; "
765 		    "cannot allocate %d for %s\n",
766 		    __func__, size, ef->lf.pathname);
767 		return (ENOSPC);
768 	}
769 	memcpy((void *)ef->vnet_base, (void *)ef->vnet_start, size);
770 	elf_set_add(&set_vnet_list, ef->vnet_start, ef->vnet_stop,
771 	    ef->vnet_base);
772 
773 	return (0);
774 }
775 #endif
776 #undef LS_PADDING
777 
778 /*
779  * Apply the specified protection to the loadable segments of a preloaded linker
780  * file.
781  */
782 static int
783 preload_protect(elf_file_t ef, vm_prot_t prot)
784 {
785 #if defined(__aarch64__) || defined(__amd64__)
786 	Elf_Ehdr *hdr;
787 	Elf_Phdr *phdr, *phlimit;
788 	vm_prot_t nprot;
789 	int error;
790 
791 	error = 0;
792 	hdr = (Elf_Ehdr *)ef->address;
793 	phdr = (Elf_Phdr *)(ef->address + hdr->e_phoff);
794 	phlimit = phdr + hdr->e_phnum;
795 	for (; phdr < phlimit; phdr++) {
796 		if (phdr->p_type != PT_LOAD)
797 			continue;
798 
799 		nprot = prot | VM_PROT_READ;
800 		if ((phdr->p_flags & PF_W) != 0)
801 			nprot |= VM_PROT_WRITE;
802 		if ((phdr->p_flags & PF_X) != 0)
803 			nprot |= VM_PROT_EXECUTE;
804 		error = pmap_change_prot((vm_offset_t)ef->address +
805 		    phdr->p_vaddr, round_page(phdr->p_memsz), nprot);
806 		if (error != 0)
807 			break;
808 	}
809 	return (error);
810 #else
811 	return (0);
812 #endif
813 }
814 
815 #ifdef __arm__
816 /*
817  * Locate the ARM exception/unwind table info for DDB and stack(9) use by
818  * searching for the section header that describes it.  There may be no unwind
819  * info, for example in a module containing only data.
820  */
821 static void
822 link_elf_locate_exidx(linker_file_t lf, Elf_Shdr *shdr, int nhdr)
823 {
824 	int i;
825 
826 	for (i = 0; i < nhdr; i++) {
827 		if (shdr[i].sh_type == SHT_ARM_EXIDX) {
828 			lf->exidx_addr = shdr[i].sh_addr + lf->address;
829 			lf->exidx_size = shdr[i].sh_size;
830 			break;
831 		}
832 	}
833 }
834 
835 /*
836  * Locate the section headers metadata in a preloaded module, then use it to
837  * locate the exception/unwind table in the module.  The size of the metadata
838  * block is stored in a uint32 word immediately before the data itself, and a
839  * comment in preload_search_info() says it is safe to rely on that.
840  */
841 static void
842 link_elf_locate_exidx_preload(struct linker_file *lf, caddr_t modptr)
843 {
844 	uint32_t *modinfo;
845 	Elf_Shdr *shdr;
846 	uint32_t  nhdr;
847 
848 	modinfo = (uint32_t *)preload_search_info(modptr,
849 	    MODINFO_METADATA | MODINFOMD_SHDR);
850 	if (modinfo != NULL) {
851 		shdr = (Elf_Shdr *)modinfo;
852 		nhdr = modinfo[-1] / sizeof(Elf_Shdr);
853 		link_elf_locate_exidx(lf, shdr, nhdr);
854 	}
855 }
856 
857 #endif /* __arm__ */
858 
859 static int
860 link_elf_link_preload(linker_class_t cls, const char *filename,
861     linker_file_t *result)
862 {
863 	Elf_Addr *ctors_addrp;
864 	Elf_Size *ctors_sizep;
865 	caddr_t modptr, baseptr, sizeptr, dynptr;
866 	char *type;
867 	elf_file_t ef;
868 	linker_file_t lf;
869 	int error;
870 	vm_offset_t dp;
871 
872 	/* Look to see if we have the file preloaded */
873 	modptr = preload_search_by_name(filename);
874 	if (modptr == NULL)
875 		return (ENOENT);
876 
877 	type = (char *)preload_search_info(modptr, MODINFO_TYPE);
878 	baseptr = preload_search_info(modptr, MODINFO_ADDR);
879 	sizeptr = preload_search_info(modptr, MODINFO_SIZE);
880 	dynptr = preload_search_info(modptr,
881 	    MODINFO_METADATA | MODINFOMD_DYNAMIC);
882 	if (type == NULL ||
883 	    (strcmp(type, "elf" __XSTRING(__ELF_WORD_SIZE) " module") != 0 &&
884 	     strcmp(type, "elf module") != 0))
885 		return (EFTYPE);
886 	if (baseptr == NULL || sizeptr == NULL || dynptr == NULL)
887 		return (EINVAL);
888 
889 	lf = linker_make_file(filename, &link_elf_class);
890 	if (lf == NULL)
891 		return (ENOMEM);
892 
893 	ef = (elf_file_t) lf;
894 	ef->preloaded = 1;
895 	ef->modptr = modptr;
896 	ef->address = *(caddr_t *)baseptr;
897 #ifdef SPARSE_MAPPING
898 	ef->object = NULL;
899 #endif
900 	dp = (vm_offset_t)ef->address + *(vm_offset_t *)dynptr;
901 	ef->dynamic = (Elf_Dyn *)dp;
902 	lf->address = ef->address;
903 	lf->size = *(size_t *)sizeptr;
904 
905 	ctors_addrp = (Elf_Addr *)preload_search_info(modptr,
906 	    MODINFO_METADATA | MODINFOMD_CTORS_ADDR);
907 	ctors_sizep = (Elf_Size *)preload_search_info(modptr,
908 	    MODINFO_METADATA | MODINFOMD_CTORS_SIZE);
909 	if (ctors_addrp != NULL && ctors_sizep != NULL) {
910 		lf->ctors_addr = ef->address + *ctors_addrp;
911 		lf->ctors_size = *ctors_sizep;
912 	}
913 
914 #ifdef __arm__
915 	link_elf_locate_exidx_preload(lf, modptr);
916 #endif
917 
918 	error = parse_dynamic(ef);
919 	if (error == 0)
920 		error = parse_dpcpu(ef);
921 #ifdef VIMAGE
922 	if (error == 0)
923 		error = parse_vnet(ef);
924 #endif
925 	if (error == 0)
926 		error = preload_protect(ef, VM_PROT_ALL);
927 	if (error != 0) {
928 		linker_file_unload(lf, LINKER_UNLOAD_FORCE);
929 		return (error);
930 	}
931 	link_elf_reloc_local(lf);
932 	*result = lf;
933 	return (0);
934 }
935 
936 static int
937 link_elf_link_preload_finish(linker_file_t lf)
938 {
939 	elf_file_t ef;
940 	int error;
941 
942 	ef = (elf_file_t) lf;
943 	error = relocate_file(ef);
944 	if (error == 0)
945 		error = preload_protect(ef, VM_PROT_NONE);
946 	if (error != 0)
947 		return (error);
948 	(void)link_elf_preload_parse_symbols(ef);
949 
950 	return (link_elf_link_common_finish(lf));
951 }
952 
953 static int
954 link_elf_load_file(linker_class_t cls, const char* filename,
955     linker_file_t* result)
956 {
957 	struct nameidata nd;
958 	struct thread* td = curthread;	/* XXX */
959 	Elf_Ehdr *hdr;
960 	caddr_t firstpage, segbase;
961 	int nbytes, i;
962 	Elf_Phdr *phdr;
963 	Elf_Phdr *phlimit;
964 	Elf_Phdr *segs[MAXSEGS];
965 	int nsegs;
966 	Elf_Phdr *phdyn;
967 	caddr_t mapbase;
968 	size_t mapsize;
969 	Elf_Addr base_vaddr;
970 	Elf_Addr base_vlimit;
971 	int error = 0;
972 	ssize_t resid;
973 	int flags;
974 	elf_file_t ef;
975 	linker_file_t lf;
976 	Elf_Shdr *shdr;
977 	int symtabindex;
978 	int symstrindex;
979 	int shstrindex;
980 	int symcnt;
981 	int strcnt;
982 	char *shstrs;
983 
984 	shdr = NULL;
985 	lf = NULL;
986 	shstrs = NULL;
987 
988 	NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, filename);
989 	flags = FREAD;
990 	error = vn_open(&nd, &flags, 0, NULL);
991 	if (error != 0)
992 		return (error);
993 	NDFREE_PNBUF(&nd);
994 	if (nd.ni_vp->v_type != VREG) {
995 		error = ENOEXEC;
996 		firstpage = NULL;
997 		goto out;
998 	}
999 #ifdef MAC
1000 	error = mac_kld_check_load(curthread->td_ucred, nd.ni_vp);
1001 	if (error != 0) {
1002 		firstpage = NULL;
1003 		goto out;
1004 	}
1005 #endif
1006 
1007 	/*
1008 	 * Read the elf header from the file.
1009 	 */
1010 	firstpage = malloc(PAGE_SIZE, M_LINKER, M_WAITOK);
1011 	hdr = (Elf_Ehdr *)firstpage;
1012 	error = vn_rdwr(UIO_READ, nd.ni_vp, firstpage, PAGE_SIZE, 0,
1013 	    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred, NOCRED,
1014 	    &resid, td);
1015 	nbytes = PAGE_SIZE - resid;
1016 	if (error != 0)
1017 		goto out;
1018 
1019 	if (!IS_ELF(*hdr)) {
1020 		error = ENOEXEC;
1021 		goto out;
1022 	}
1023 
1024 	if (hdr->e_ident[EI_CLASS] != ELF_TARG_CLASS ||
1025 	    hdr->e_ident[EI_DATA] != ELF_TARG_DATA) {
1026 		link_elf_error(filename, "Unsupported file layout");
1027 		error = ENOEXEC;
1028 		goto out;
1029 	}
1030 	if (hdr->e_ident[EI_VERSION] != EV_CURRENT ||
1031 	    hdr->e_version != EV_CURRENT) {
1032 		link_elf_error(filename, "Unsupported file version");
1033 		error = ENOEXEC;
1034 		goto out;
1035 	}
1036 	if (hdr->e_type != ET_EXEC && hdr->e_type != ET_DYN) {
1037 		error = ENOSYS;
1038 		goto out;
1039 	}
1040 	if (hdr->e_machine != ELF_TARG_MACH) {
1041 		link_elf_error(filename, "Unsupported machine");
1042 		error = ENOEXEC;
1043 		goto out;
1044 	}
1045 
1046 	/*
1047 	 * We rely on the program header being in the first page.
1048 	 * This is not strictly required by the ABI specification, but
1049 	 * it seems to always true in practice.  And, it simplifies
1050 	 * things considerably.
1051 	 */
1052 	if (!((hdr->e_phentsize == sizeof(Elf_Phdr)) &&
1053 	      (hdr->e_phoff + hdr->e_phnum*sizeof(Elf_Phdr) <= PAGE_SIZE) &&
1054 	      (hdr->e_phoff + hdr->e_phnum*sizeof(Elf_Phdr) <= nbytes)))
1055 		link_elf_error(filename, "Unreadable program headers");
1056 
1057 	/*
1058 	 * Scan the program header entries, and save key information.
1059 	 *
1060 	 * We rely on there being exactly two load segments, text and data,
1061 	 * in that order.
1062 	 */
1063 	phdr = (Elf_Phdr *) (firstpage + hdr->e_phoff);
1064 	phlimit = phdr + hdr->e_phnum;
1065 	nsegs = 0;
1066 	phdyn = NULL;
1067 	while (phdr < phlimit) {
1068 		switch (phdr->p_type) {
1069 		case PT_LOAD:
1070 			if (nsegs == MAXSEGS) {
1071 				link_elf_error(filename, "Too many sections");
1072 				error = ENOEXEC;
1073 				goto out;
1074 			}
1075 			/*
1076 			 * XXX: We just trust they come in right order ??
1077 			 */
1078 			segs[nsegs] = phdr;
1079 			++nsegs;
1080 			break;
1081 
1082 		case PT_DYNAMIC:
1083 			phdyn = phdr;
1084 			break;
1085 
1086 		case PT_INTERP:
1087 			error = ENOSYS;
1088 			goto out;
1089 		}
1090 
1091 		++phdr;
1092 	}
1093 	if (phdyn == NULL) {
1094 		link_elf_error(filename, "Object is not dynamically-linked");
1095 		error = ENOEXEC;
1096 		goto out;
1097 	}
1098 	if (nsegs == 0) {
1099 		link_elf_error(filename, "No sections");
1100 		error = ENOEXEC;
1101 		goto out;
1102 	}
1103 
1104 	/*
1105 	 * Allocate the entire address space of the object, to stake
1106 	 * out our contiguous region, and to establish the base
1107 	 * address for relocation.
1108 	 */
1109 	base_vaddr = trunc_page(segs[0]->p_vaddr);
1110 	base_vlimit = round_page(segs[nsegs - 1]->p_vaddr +
1111 	    segs[nsegs - 1]->p_memsz);
1112 	mapsize = base_vlimit - base_vaddr;
1113 
1114 	lf = linker_make_file(filename, &link_elf_class);
1115 	if (lf == NULL) {
1116 		error = ENOMEM;
1117 		goto out;
1118 	}
1119 
1120 	ef = (elf_file_t) lf;
1121 #ifdef SPARSE_MAPPING
1122 	ef->object = vm_pager_allocate(OBJT_PHYS, NULL, mapsize, VM_PROT_ALL,
1123 	    0, thread0.td_ucred);
1124 	if (ef->object == NULL) {
1125 		error = ENOMEM;
1126 		goto out;
1127 	}
1128 #ifdef __amd64__
1129 	mapbase = (caddr_t)KERNBASE;
1130 #else
1131 	mapbase = (caddr_t)vm_map_min(kernel_map);
1132 #endif
1133 	/*
1134 	 * Mapping protections are downgraded after relocation processing.
1135 	 */
1136 	error = vm_map_find(kernel_map, ef->object, 0,
1137 	    (vm_offset_t *)&mapbase, mapsize, 0, VMFS_OPTIMAL_SPACE,
1138 	    VM_PROT_ALL, VM_PROT_ALL, 0);
1139 	if (error != 0) {
1140 		vm_object_deallocate(ef->object);
1141 		ef->object = NULL;
1142 		goto out;
1143 	}
1144 #else
1145 	mapbase = malloc_exec(mapsize, M_LINKER, M_WAITOK);
1146 #endif
1147 	ef->address = mapbase;
1148 
1149 	/*
1150 	 * Read the text and data sections and zero the bss.
1151 	 */
1152 	for (i = 0; i < nsegs; i++) {
1153 		segbase = mapbase + segs[i]->p_vaddr - base_vaddr;
1154 
1155 #ifdef SPARSE_MAPPING
1156 		/*
1157 		 * Consecutive segments may have different mapping permissions,
1158 		 * so be strict and verify that their mappings do not overlap.
1159 		 */
1160 		if (((vm_offset_t)segbase & PAGE_MASK) != 0) {
1161 			error = EINVAL;
1162 			goto out;
1163 		}
1164 
1165 		error = vm_map_wire(kernel_map,
1166 		    (vm_offset_t)segbase,
1167 		    (vm_offset_t)segbase + round_page(segs[i]->p_memsz),
1168 		    VM_MAP_WIRE_SYSTEM | VM_MAP_WIRE_NOHOLES);
1169 		if (error != KERN_SUCCESS) {
1170 			error = ENOMEM;
1171 			goto out;
1172 		}
1173 #endif
1174 
1175 		error = vn_rdwr(UIO_READ, nd.ni_vp,
1176 		    segbase, segs[i]->p_filesz, segs[i]->p_offset,
1177 		    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred, NOCRED,
1178 		    &resid, td);
1179 		if (error != 0)
1180 			goto out;
1181 		bzero(segbase + segs[i]->p_filesz,
1182 		    segs[i]->p_memsz - segs[i]->p_filesz);
1183 	}
1184 
1185 	ef->dynamic = (Elf_Dyn *) (mapbase + phdyn->p_vaddr - base_vaddr);
1186 
1187 	lf->address = ef->address;
1188 	lf->size = mapsize;
1189 
1190 	error = parse_dynamic(ef);
1191 	if (error != 0)
1192 		goto out;
1193 	error = parse_dpcpu(ef);
1194 	if (error != 0)
1195 		goto out;
1196 #ifdef VIMAGE
1197 	error = parse_vnet(ef);
1198 	if (error != 0)
1199 		goto out;
1200 #endif
1201 	link_elf_reloc_local(lf);
1202 
1203 	VOP_UNLOCK(nd.ni_vp);
1204 	error = linker_load_dependencies(lf);
1205 	vn_lock(nd.ni_vp, LK_EXCLUSIVE | LK_RETRY);
1206 	if (error != 0)
1207 		goto out;
1208 	error = relocate_file(ef);
1209 	if (error != 0)
1210 		goto out;
1211 
1212 #ifdef SPARSE_MAPPING
1213 	/*
1214 	 * Downgrade permissions on text segment mappings now that relocation
1215 	 * processing is complete.  Restrict permissions on read-only segments.
1216 	 */
1217 	for (i = 0; i < nsegs; i++) {
1218 		vm_prot_t prot;
1219 
1220 		if (segs[i]->p_type != PT_LOAD)
1221 			continue;
1222 
1223 		prot = VM_PROT_READ;
1224 		if ((segs[i]->p_flags & PF_W) != 0)
1225 			prot |= VM_PROT_WRITE;
1226 		if ((segs[i]->p_flags & PF_X) != 0)
1227 			prot |= VM_PROT_EXECUTE;
1228 		segbase = mapbase + segs[i]->p_vaddr - base_vaddr;
1229 		error = vm_map_protect(kernel_map,
1230 		    (vm_offset_t)segbase,
1231 		    (vm_offset_t)segbase + round_page(segs[i]->p_memsz),
1232 		    prot, 0, VM_MAP_PROTECT_SET_PROT);
1233 		if (error != KERN_SUCCESS) {
1234 			error = ENOMEM;
1235 			goto out;
1236 		}
1237 	}
1238 #endif
1239 
1240 	/*
1241 	 * Try and load the symbol table if it's present.  (you can
1242 	 * strip it!)
1243 	 */
1244 	nbytes = hdr->e_shnum * hdr->e_shentsize;
1245 	if (nbytes == 0 || hdr->e_shoff == 0)
1246 		goto nosyms;
1247 	shdr = malloc(nbytes, M_LINKER, M_WAITOK | M_ZERO);
1248 	error = vn_rdwr(UIO_READ, nd.ni_vp,
1249 	    (caddr_t)shdr, nbytes, hdr->e_shoff,
1250 	    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred, NOCRED,
1251 	    &resid, td);
1252 	if (error != 0)
1253 		goto out;
1254 
1255 	/* Read section string table */
1256 	shstrindex = hdr->e_shstrndx;
1257 	if (shstrindex != 0 && shdr[shstrindex].sh_type == SHT_STRTAB &&
1258 	    shdr[shstrindex].sh_size != 0) {
1259 		nbytes = shdr[shstrindex].sh_size;
1260 		shstrs = malloc(nbytes, M_LINKER, M_WAITOK | M_ZERO);
1261 		error = vn_rdwr(UIO_READ, nd.ni_vp, (caddr_t)shstrs, nbytes,
1262 		    shdr[shstrindex].sh_offset, UIO_SYSSPACE, IO_NODELOCKED,
1263 		    td->td_ucred, NOCRED, &resid, td);
1264 		if (error)
1265 			goto out;
1266 	}
1267 
1268 	symtabindex = -1;
1269 	symstrindex = -1;
1270 	for (i = 0; i < hdr->e_shnum; i++) {
1271 		if (shdr[i].sh_type == SHT_SYMTAB) {
1272 			symtabindex = i;
1273 			symstrindex = shdr[i].sh_link;
1274 		} else if (shstrs != NULL && shdr[i].sh_name != 0 &&
1275 		    strcmp(shstrs + shdr[i].sh_name, ".ctors") == 0) {
1276 			/* Record relocated address and size of .ctors. */
1277 			lf->ctors_addr = mapbase + shdr[i].sh_addr - base_vaddr;
1278 			lf->ctors_size = shdr[i].sh_size;
1279 		}
1280 	}
1281 	if (symtabindex < 0 || symstrindex < 0)
1282 		goto nosyms;
1283 
1284 	symcnt = shdr[symtabindex].sh_size;
1285 	ef->symbase = malloc(symcnt, M_LINKER, M_WAITOK);
1286 	strcnt = shdr[symstrindex].sh_size;
1287 	ef->strbase = malloc(strcnt, M_LINKER, M_WAITOK);
1288 
1289 	error = vn_rdwr(UIO_READ, nd.ni_vp,
1290 	    ef->symbase, symcnt, shdr[symtabindex].sh_offset,
1291 	    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred, NOCRED,
1292 	    &resid, td);
1293 	if (error != 0)
1294 		goto out;
1295 	error = vn_rdwr(UIO_READ, nd.ni_vp,
1296 	    ef->strbase, strcnt, shdr[symstrindex].sh_offset,
1297 	    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred, NOCRED,
1298 	    &resid, td);
1299 	if (error != 0)
1300 		goto out;
1301 
1302 	ef->ddbsymcnt = symcnt / sizeof(Elf_Sym);
1303 	ef->ddbsymtab = (const Elf_Sym *)ef->symbase;
1304 	ef->ddbstrcnt = strcnt;
1305 	ef->ddbstrtab = ef->strbase;
1306 
1307 nosyms:
1308 
1309 #ifdef __arm__
1310 	link_elf_locate_exidx(lf, shdr, hdr->e_shnum);
1311 #endif
1312 
1313 	error = link_elf_link_common_finish(lf);
1314 	if (error != 0)
1315 		goto out;
1316 
1317 	*result = lf;
1318 
1319 out:
1320 	VOP_UNLOCK(nd.ni_vp);
1321 	vn_close(nd.ni_vp, FREAD, td->td_ucred, td);
1322 	if (error != 0 && lf != NULL)
1323 		linker_file_unload(lf, LINKER_UNLOAD_FORCE);
1324 	free(shdr, M_LINKER);
1325 	free(firstpage, M_LINKER);
1326 	free(shstrs, M_LINKER);
1327 
1328 	return (error);
1329 }
1330 
1331 Elf_Addr
1332 elf_relocaddr(linker_file_t lf, Elf_Addr x)
1333 {
1334 	elf_file_t ef;
1335 
1336 	KASSERT(lf->ops->cls == (kobj_class_t)&link_elf_class,
1337 	    ("elf_relocaddr: unexpected linker file %p", lf));
1338 
1339 	ef = (elf_file_t)lf;
1340 	if (x >= ef->pcpu_start && x < ef->pcpu_stop)
1341 		return ((x - ef->pcpu_start) + ef->pcpu_base);
1342 #ifdef VIMAGE
1343 	if (x >= ef->vnet_start && x < ef->vnet_stop)
1344 		return ((x - ef->vnet_start) + ef->vnet_base);
1345 #endif
1346 	return (x);
1347 }
1348 
1349 static void
1350 link_elf_unload_file(linker_file_t file)
1351 {
1352 	elf_file_t ef = (elf_file_t) file;
1353 
1354 	if (ef->pcpu_base != 0) {
1355 		dpcpu_free((void *)ef->pcpu_base,
1356 		    ef->pcpu_stop - ef->pcpu_start);
1357 		elf_set_delete(&set_pcpu_list, ef->pcpu_start);
1358 	}
1359 #ifdef VIMAGE
1360 	if (ef->vnet_base != 0) {
1361 		vnet_data_free((void *)ef->vnet_base,
1362 		    ef->vnet_stop - ef->vnet_start);
1363 		elf_set_delete(&set_vnet_list, ef->vnet_start);
1364 	}
1365 #endif
1366 #ifdef GDB
1367 	if (ef->gdb.l_ld != NULL) {
1368 		GDB_STATE(RT_DELETE);
1369 		free((void *)(uintptr_t)ef->gdb.l_name, M_LINKER);
1370 		link_elf_delete_gdb(&ef->gdb);
1371 		GDB_STATE(RT_CONSISTENT);
1372 	}
1373 #endif
1374 
1375 	/* Notify MD code that a module is being unloaded. */
1376 	elf_cpu_unload_file(file);
1377 
1378 	if (ef->preloaded) {
1379 		link_elf_unload_preload(file);
1380 		return;
1381 	}
1382 
1383 #ifdef SPARSE_MAPPING
1384 	if (ef->object != NULL) {
1385 		vm_map_remove(kernel_map, (vm_offset_t) ef->address,
1386 		    (vm_offset_t) ef->address
1387 		    + (ef->object->size << PAGE_SHIFT));
1388 	}
1389 #else
1390 	free(ef->address, M_LINKER);
1391 #endif
1392 	free(ef->symbase, M_LINKER);
1393 	free(ef->strbase, M_LINKER);
1394 	free(ef->ctftab, M_LINKER);
1395 	free(ef->ctfoff, M_LINKER);
1396 	free(ef->typoff, M_LINKER);
1397 }
1398 
1399 static void
1400 link_elf_unload_preload(linker_file_t file)
1401 {
1402 
1403 	if (file->pathname != NULL)
1404 		preload_delete_name(file->pathname);
1405 }
1406 
1407 static const char *
1408 symbol_name(elf_file_t ef, Elf_Size r_info)
1409 {
1410 	const Elf_Sym *ref;
1411 
1412 	if (ELF_R_SYM(r_info)) {
1413 		ref = ef->symtab + ELF_R_SYM(r_info);
1414 		return (ef->strtab + ref->st_name);
1415 	}
1416 	return (NULL);
1417 }
1418 
1419 static int
1420 symbol_type(elf_file_t ef, Elf_Size r_info)
1421 {
1422 	const Elf_Sym *ref;
1423 
1424 	if (ELF_R_SYM(r_info)) {
1425 		ref = ef->symtab + ELF_R_SYM(r_info);
1426 		return (ELF_ST_TYPE(ref->st_info));
1427 	}
1428 	return (STT_NOTYPE);
1429 }
1430 
1431 static int
1432 relocate_file1(elf_file_t ef, elf_lookup_fn lookup, elf_reloc_fn reloc,
1433     bool ifuncs)
1434 {
1435 	const Elf_Rel *rel;
1436 	const Elf_Rela *rela;
1437 	const char *symname;
1438 
1439 	TSENTER();
1440 #define	APPLY_RELOCS(iter, tbl, tblsize, type) do {			\
1441 	for ((iter) = (tbl); (iter) != NULL &&				\
1442 	    (iter) < (tbl) + (tblsize) / sizeof(*(iter)); (iter)++) {	\
1443 		if ((symbol_type(ef, (iter)->r_info) ==			\
1444 		    STT_GNU_IFUNC ||					\
1445 		    elf_is_ifunc_reloc((iter)->r_info)) != ifuncs)	\
1446 			continue;					\
1447 		if (reloc(&ef->lf, (Elf_Addr)ef->address,		\
1448 		    (iter), (type), lookup)) {				\
1449 			symname = symbol_name(ef, (iter)->r_info);	\
1450 			printf("link_elf: symbol %s undefined\n",	\
1451 			    symname);					\
1452 			return (ENOENT);				\
1453 		}							\
1454 	}								\
1455 } while (0)
1456 
1457 	APPLY_RELOCS(rel, ef->rel, ef->relsize, ELF_RELOC_REL);
1458 	TSENTER2("ef->rela");
1459 	APPLY_RELOCS(rela, ef->rela, ef->relasize, ELF_RELOC_RELA);
1460 	TSEXIT2("ef->rela");
1461 	APPLY_RELOCS(rel, ef->pltrel, ef->pltrelsize, ELF_RELOC_REL);
1462 	APPLY_RELOCS(rela, ef->pltrela, ef->pltrelasize, ELF_RELOC_RELA);
1463 
1464 #undef APPLY_RELOCS
1465 
1466 	TSEXIT();
1467 	return (0);
1468 }
1469 
1470 static int
1471 relocate_file(elf_file_t ef)
1472 {
1473 	int error;
1474 
1475 	error = relocate_file1(ef, elf_lookup, elf_reloc, false);
1476 	if (error == 0)
1477 		error = relocate_file1(ef, elf_lookup, elf_reloc, true);
1478 	return (error);
1479 }
1480 
1481 /*
1482  * SysV hash function for symbol table lookup.  It is specified by the
1483  * System V ABI.
1484  */
1485 static Elf32_Word
1486 elf_hash(const char *name)
1487 {
1488 	const unsigned char *p = (const unsigned char *)name;
1489 	Elf32_Word h = 0;
1490 
1491 	while (*p != '\0') {
1492 		h = (h << 4) + *p++;
1493 		h ^= (h >> 24) & 0xf0;
1494 	}
1495 	return (h & 0x0fffffff);
1496 }
1497 
1498 static int
1499 link_elf_lookup_symbol1(linker_file_t lf, const char *name, c_linker_sym_t *sym,
1500     bool see_local)
1501 {
1502 	elf_file_t ef = (elf_file_t) lf;
1503 	unsigned long symnum;
1504 	const Elf_Sym* symp;
1505 	const char *strp;
1506 	Elf32_Word hash;
1507 
1508 	/* If we don't have a hash, bail. */
1509 	if (ef->buckets == NULL || ef->nbuckets == 0) {
1510 		printf("link_elf_lookup_symbol: missing symbol hash table\n");
1511 		return (ENOENT);
1512 	}
1513 
1514 	/* First, search hashed global symbols */
1515 	hash = elf_hash(name);
1516 	symnum = ef->buckets[hash % ef->nbuckets];
1517 
1518 	while (symnum != STN_UNDEF) {
1519 		if (symnum >= ef->nchains) {
1520 			printf("%s: corrupt symbol table\n", __func__);
1521 			return (ENOENT);
1522 		}
1523 
1524 		symp = ef->symtab + symnum;
1525 		if (symp->st_name == 0) {
1526 			printf("%s: corrupt symbol table\n", __func__);
1527 			return (ENOENT);
1528 		}
1529 
1530 		strp = ef->strtab + symp->st_name;
1531 
1532 		if (strcmp(name, strp) == 0) {
1533 			if (symp->st_shndx != SHN_UNDEF ||
1534 			    (symp->st_value != 0 &&
1535 			    (ELF_ST_TYPE(symp->st_info) == STT_FUNC ||
1536 			    ELF_ST_TYPE(symp->st_info) == STT_GNU_IFUNC))) {
1537 				if (see_local ||
1538 				    ELF_ST_BIND(symp->st_info) != STB_LOCAL) {
1539 					*sym = (c_linker_sym_t) symp;
1540 					return (0);
1541 				}
1542 			}
1543 			return (ENOENT);
1544 		}
1545 
1546 		symnum = ef->chains[symnum];
1547 	}
1548 
1549 	return (ENOENT);
1550 }
1551 
1552 static int
1553 link_elf_lookup_symbol(linker_file_t lf, const char *name, c_linker_sym_t *sym)
1554 {
1555 	if (link_elf_leak_locals)
1556 		return (link_elf_lookup_debug_symbol(lf, name, sym));
1557 	return (link_elf_lookup_symbol1(lf, name, sym, false));
1558 }
1559 
1560 static int
1561 link_elf_lookup_debug_symbol(linker_file_t lf, const char *name,
1562     c_linker_sym_t *sym)
1563 {
1564 	elf_file_t ef = (elf_file_t)lf;
1565 	const Elf_Sym* symp;
1566 	const char *strp;
1567 	int i;
1568 
1569 	if (link_elf_lookup_symbol1(lf, name, sym, true) == 0)
1570 		return (0);
1571 
1572 	for (i = 0, symp = ef->ddbsymtab; i < ef->ddbsymcnt; i++, symp++) {
1573 		strp = ef->ddbstrtab + symp->st_name;
1574 		if (strcmp(name, strp) == 0) {
1575 			if (symp->st_shndx != SHN_UNDEF ||
1576 			    (symp->st_value != 0 &&
1577 			    (ELF_ST_TYPE(symp->st_info) == STT_FUNC ||
1578 			    ELF_ST_TYPE(symp->st_info) == STT_GNU_IFUNC))) {
1579 				*sym = (c_linker_sym_t) symp;
1580 				return (0);
1581 			}
1582 			return (ENOENT);
1583 		}
1584 	}
1585 
1586 	return (ENOENT);
1587 }
1588 
1589 static int
1590 link_elf_symbol_values1(linker_file_t lf, c_linker_sym_t sym,
1591     linker_symval_t *symval, bool see_local)
1592 {
1593 	elf_file_t ef;
1594 	const Elf_Sym *es;
1595 	caddr_t val;
1596 
1597 	ef = (elf_file_t)lf;
1598 	es = (const Elf_Sym *)sym;
1599 	if (es >= ef->symtab && es < ef->symtab + ef->nchains) {
1600 		if (!see_local && ELF_ST_BIND(es->st_info) == STB_LOCAL)
1601 			return (ENOENT);
1602 		symval->name = ef->strtab + es->st_name;
1603 		val = (caddr_t)ef->address + es->st_value;
1604 		if (ELF_ST_TYPE(es->st_info) == STT_GNU_IFUNC)
1605 			val = ((caddr_t (*)(void))val)();
1606 		symval->value = val;
1607 		symval->size = es->st_size;
1608 		return (0);
1609 	}
1610 	return (ENOENT);
1611 }
1612 
1613 static int
1614 link_elf_symbol_values(linker_file_t lf, c_linker_sym_t sym,
1615     linker_symval_t *symval)
1616 {
1617 	if (link_elf_leak_locals)
1618 		return (link_elf_debug_symbol_values(lf, sym, symval));
1619 	return (link_elf_symbol_values1(lf, sym, symval, false));
1620 }
1621 
1622 static int
1623 link_elf_debug_symbol_values(linker_file_t lf, c_linker_sym_t sym,
1624     linker_symval_t *symval)
1625 {
1626 	elf_file_t ef = (elf_file_t)lf;
1627 	const Elf_Sym *es = (const Elf_Sym *)sym;
1628 	caddr_t val;
1629 
1630 	if (link_elf_symbol_values1(lf, sym, symval, true) == 0)
1631 		return (0);
1632 	if (ef->symtab == ef->ddbsymtab)
1633 		return (ENOENT);
1634 
1635 	if (es >= ef->ddbsymtab && es < (ef->ddbsymtab + ef->ddbsymcnt)) {
1636 		symval->name = ef->ddbstrtab + es->st_name;
1637 		val = (caddr_t)ef->address + es->st_value;
1638 		if (ELF_ST_TYPE(es->st_info) == STT_GNU_IFUNC)
1639 			val = ((caddr_t (*)(void))val)();
1640 		symval->value = val;
1641 		symval->size = es->st_size;
1642 		return (0);
1643 	}
1644 	return (ENOENT);
1645 }
1646 
1647 static int
1648 link_elf_search_symbol(linker_file_t lf, caddr_t value,
1649     c_linker_sym_t *sym, long *diffp)
1650 {
1651 	elf_file_t ef = (elf_file_t)lf;
1652 	u_long off = (uintptr_t)(void *)value;
1653 	u_long diff = off;
1654 	u_long st_value;
1655 	const Elf_Sym *es;
1656 	const Elf_Sym *best = NULL;
1657 	int i;
1658 
1659 	for (i = 0, es = ef->ddbsymtab; i < ef->ddbsymcnt; i++, es++) {
1660 		if (es->st_name == 0)
1661 			continue;
1662 		st_value = es->st_value + (uintptr_t) (void *) ef->address;
1663 		if (off >= st_value) {
1664 			if (off - st_value < diff) {
1665 				diff = off - st_value;
1666 				best = es;
1667 				if (diff == 0)
1668 					break;
1669 			} else if (off - st_value == diff) {
1670 				best = es;
1671 			}
1672 		}
1673 	}
1674 	if (best == NULL)
1675 		*diffp = off;
1676 	else
1677 		*diffp = diff;
1678 	*sym = (c_linker_sym_t) best;
1679 
1680 	return (0);
1681 }
1682 
1683 /*
1684  * Look up a linker set on an ELF system.
1685  */
1686 static int
1687 link_elf_lookup_set(linker_file_t lf, const char *name,
1688     void ***startp, void ***stopp, int *countp)
1689 {
1690 	c_linker_sym_t sym;
1691 	linker_symval_t symval;
1692 	char *setsym;
1693 	void **start, **stop;
1694 	int len, error = 0, count;
1695 
1696 	len = strlen(name) + sizeof("__start_set_"); /* sizeof includes \0 */
1697 	setsym = malloc(len, M_LINKER, M_WAITOK);
1698 
1699 	/* get address of first entry */
1700 	snprintf(setsym, len, "%s%s", "__start_set_", name);
1701 	error = link_elf_lookup_symbol(lf, setsym, &sym);
1702 	if (error != 0)
1703 		goto out;
1704 	link_elf_symbol_values(lf, sym, &symval);
1705 	if (symval.value == 0) {
1706 		error = ESRCH;
1707 		goto out;
1708 	}
1709 	start = (void **)symval.value;
1710 
1711 	/* get address of last entry */
1712 	snprintf(setsym, len, "%s%s", "__stop_set_", name);
1713 	error = link_elf_lookup_symbol(lf, setsym, &sym);
1714 	if (error != 0)
1715 		goto out;
1716 	link_elf_symbol_values(lf, sym, &symval);
1717 	if (symval.value == 0) {
1718 		error = ESRCH;
1719 		goto out;
1720 	}
1721 	stop = (void **)symval.value;
1722 
1723 	/* and the number of entries */
1724 	count = stop - start;
1725 
1726 	/* and copy out */
1727 	if (startp != NULL)
1728 		*startp = start;
1729 	if (stopp != NULL)
1730 		*stopp = stop;
1731 	if (countp != NULL)
1732 		*countp = count;
1733 
1734 out:
1735 	free(setsym, M_LINKER);
1736 	return (error);
1737 }
1738 
1739 static int
1740 link_elf_each_function_name(linker_file_t file,
1741   int (*callback)(const char *, void *), void *opaque)
1742 {
1743 	elf_file_t ef = (elf_file_t)file;
1744 	const Elf_Sym *symp;
1745 	int i, error;
1746 
1747 	/* Exhaustive search */
1748 	for (i = 0, symp = ef->ddbsymtab; i < ef->ddbsymcnt; i++, symp++) {
1749 		if (symp->st_value != 0 &&
1750 		    (ELF_ST_TYPE(symp->st_info) == STT_FUNC ||
1751 		    ELF_ST_TYPE(symp->st_info) == STT_GNU_IFUNC)) {
1752 			error = callback(ef->ddbstrtab + symp->st_name, opaque);
1753 			if (error != 0)
1754 				return (error);
1755 		}
1756 	}
1757 	return (0);
1758 }
1759 
1760 static int
1761 link_elf_each_function_nameval(linker_file_t file,
1762     linker_function_nameval_callback_t callback, void *opaque)
1763 {
1764 	linker_symval_t symval;
1765 	elf_file_t ef = (elf_file_t)file;
1766 	const Elf_Sym *symp;
1767 	int i, error;
1768 
1769 	/* Exhaustive search */
1770 	for (i = 0, symp = ef->ddbsymtab; i < ef->ddbsymcnt; i++, symp++) {
1771 		if (symp->st_value != 0 &&
1772 		    (ELF_ST_TYPE(symp->st_info) == STT_FUNC ||
1773 		    ELF_ST_TYPE(symp->st_info) == STT_GNU_IFUNC)) {
1774 			error = link_elf_debug_symbol_values(file,
1775 			    (c_linker_sym_t) symp, &symval);
1776 			if (error == 0)
1777 				error = callback(file, i, &symval, opaque);
1778 			if (error != 0)
1779 				return (error);
1780 		}
1781 	}
1782 	return (0);
1783 }
1784 
1785 const Elf_Sym *
1786 elf_get_sym(linker_file_t lf, Elf_Size symidx)
1787 {
1788 	elf_file_t ef = (elf_file_t)lf;
1789 
1790 	if (symidx >= ef->nchains)
1791 		return (NULL);
1792 	return (ef->symtab + symidx);
1793 }
1794 
1795 const char *
1796 elf_get_symname(linker_file_t lf, Elf_Size symidx)
1797 {
1798 	elf_file_t ef = (elf_file_t)lf;
1799 	const Elf_Sym *sym;
1800 
1801 	if (symidx >= ef->nchains)
1802 		return (NULL);
1803 	sym = ef->symtab + symidx;
1804 	return (ef->strtab + sym->st_name);
1805 }
1806 
1807 /*
1808  * Symbol lookup function that can be used when the symbol index is known (ie
1809  * in relocations). It uses the symbol index instead of doing a fully fledged
1810  * hash table based lookup when such is valid. For example for local symbols.
1811  * This is not only more efficient, it's also more correct. It's not always
1812  * the case that the symbol can be found through the hash table.
1813  */
1814 static int
1815 elf_lookup(linker_file_t lf, Elf_Size symidx, int deps, Elf_Addr *res)
1816 {
1817 	elf_file_t ef = (elf_file_t)lf;
1818 	const Elf_Sym *sym;
1819 	const char *symbol;
1820 	Elf_Addr addr, start, base;
1821 
1822 	/* Don't even try to lookup the symbol if the index is bogus. */
1823 	if (symidx >= ef->nchains) {
1824 		*res = 0;
1825 		return (EINVAL);
1826 	}
1827 
1828 	sym = ef->symtab + symidx;
1829 
1830 	/*
1831 	 * Don't do a full lookup when the symbol is local. It may even
1832 	 * fail because it may not be found through the hash table.
1833 	 */
1834 	if (ELF_ST_BIND(sym->st_info) == STB_LOCAL) {
1835 		/* Force lookup failure when we have an insanity. */
1836 		if (sym->st_shndx == SHN_UNDEF || sym->st_value == 0) {
1837 			*res = 0;
1838 			return (EINVAL);
1839 		}
1840 		*res = ((Elf_Addr)ef->address + sym->st_value);
1841 		return (0);
1842 	}
1843 
1844 	/*
1845 	 * XXX we can avoid doing a hash table based lookup for global
1846 	 * symbols as well. This however is not always valid, so we'll
1847 	 * just do it the hard way for now. Performance tweaks can
1848 	 * always be added.
1849 	 */
1850 
1851 	symbol = ef->strtab + sym->st_name;
1852 
1853 	/* Force a lookup failure if the symbol name is bogus. */
1854 	if (*symbol == 0) {
1855 		*res = 0;
1856 		return (EINVAL);
1857 	}
1858 
1859 	addr = ((Elf_Addr)linker_file_lookup_symbol(lf, symbol, deps));
1860 	if (addr == 0 && ELF_ST_BIND(sym->st_info) != STB_WEAK) {
1861 		*res = 0;
1862 		return (EINVAL);
1863 	}
1864 
1865 	if (elf_set_find(&set_pcpu_list, addr, &start, &base))
1866 		addr = addr - start + base;
1867 #ifdef VIMAGE
1868 	else if (elf_set_find(&set_vnet_list, addr, &start, &base))
1869 		addr = addr - start + base;
1870 #endif
1871 	*res = addr;
1872 	return (0);
1873 }
1874 
1875 static void
1876 link_elf_reloc_local(linker_file_t lf)
1877 {
1878 	const Elf_Rel *rellim;
1879 	const Elf_Rel *rel;
1880 	const Elf_Rela *relalim;
1881 	const Elf_Rela *rela;
1882 	elf_file_t ef = (elf_file_t)lf;
1883 
1884 	/* Perform relocations without addend if there are any: */
1885 	if ((rel = ef->rel) != NULL) {
1886 		rellim = (const Elf_Rel *)((const char *)ef->rel + ef->relsize);
1887 		while (rel < rellim) {
1888 			elf_reloc_local(lf, (Elf_Addr)ef->address, rel,
1889 			    ELF_RELOC_REL, elf_lookup);
1890 			rel++;
1891 		}
1892 	}
1893 
1894 	/* Perform relocations with addend if there are any: */
1895 	if ((rela = ef->rela) != NULL) {
1896 		relalim = (const Elf_Rela *)
1897 		    ((const char *)ef->rela + ef->relasize);
1898 		while (rela < relalim) {
1899 			elf_reloc_local(lf, (Elf_Addr)ef->address, rela,
1900 			    ELF_RELOC_RELA, elf_lookup);
1901 			rela++;
1902 		}
1903 	}
1904 }
1905 
1906 static long
1907 link_elf_symtab_get(linker_file_t lf, const Elf_Sym **symtab)
1908 {
1909 	elf_file_t ef = (elf_file_t)lf;
1910 
1911 	*symtab = ef->ddbsymtab;
1912 
1913 	if (*symtab == NULL)
1914 		return (0);
1915 
1916 	return (ef->ddbsymcnt);
1917 }
1918 
1919 static long
1920 link_elf_strtab_get(linker_file_t lf, caddr_t *strtab)
1921 {
1922 	elf_file_t ef = (elf_file_t)lf;
1923 
1924 	*strtab = ef->ddbstrtab;
1925 
1926 	if (*strtab == NULL)
1927 		return (0);
1928 
1929 	return (ef->ddbstrcnt);
1930 }
1931 
1932 #ifdef VIMAGE
1933 static void
1934 link_elf_propagate_vnets(linker_file_t lf)
1935 {
1936 	elf_file_t ef = (elf_file_t)lf;
1937 	int size;
1938 
1939 	if (ef->vnet_base != 0) {
1940 		size = (uintptr_t)ef->vnet_stop - (uintptr_t)ef->vnet_start;
1941 		vnet_data_copy((void *)ef->vnet_base, size);
1942 	}
1943 }
1944 #endif
1945 
1946 #if defined(__i386__) || defined(__amd64__) || defined(__aarch64__) || defined(__powerpc__)
1947 /*
1948  * Use this lookup routine when performing relocations early during boot.
1949  * The generic lookup routine depends on kobj, which is not initialized
1950  * at that point.
1951  */
1952 static int
1953 elf_lookup_ifunc(linker_file_t lf, Elf_Size symidx, int deps __unused,
1954     Elf_Addr *res)
1955 {
1956 	elf_file_t ef;
1957 	const Elf_Sym *symp;
1958 	caddr_t val;
1959 
1960 	ef = (elf_file_t)lf;
1961 	symp = ef->symtab + symidx;
1962 	if (ELF_ST_TYPE(symp->st_info) == STT_GNU_IFUNC) {
1963 		val = (caddr_t)ef->address + symp->st_value;
1964 		*res = ((Elf_Addr (*)(void))val)();
1965 		return (0);
1966 	}
1967 	return (ENOENT);
1968 }
1969 
1970 void
1971 link_elf_ireloc(caddr_t kmdp)
1972 {
1973 	struct elf_file eff;
1974 	elf_file_t ef;
1975 
1976 	TSENTER();
1977 	ef = &eff;
1978 
1979 	bzero_early(ef, sizeof(*ef));
1980 
1981 	ef->modptr = kmdp;
1982 	ef->dynamic = (Elf_Dyn *)&_DYNAMIC;
1983 
1984 #ifdef RELOCATABLE_KERNEL
1985 	ef->address = (caddr_t) (__startkernel - KERNBASE);
1986 #else
1987 	ef->address = 0;
1988 #endif
1989 	parse_dynamic(ef);
1990 
1991 	link_elf_preload_parse_symbols(ef);
1992 	relocate_file1(ef, elf_lookup_ifunc, elf_reloc, true);
1993 	TSEXIT();
1994 }
1995 
1996 #if defined(__aarch64__) || defined(__amd64__)
1997 void
1998 link_elf_late_ireloc(void)
1999 {
2000 	elf_file_t ef;
2001 
2002 	KASSERT(linker_kernel_file != NULL,
2003 	    ("link_elf_late_ireloc: No kernel linker file found"));
2004 	ef = (elf_file_t)linker_kernel_file;
2005 
2006 	relocate_file1(ef, elf_lookup_ifunc, elf_reloc_late, true);
2007 }
2008 #endif
2009 #endif
2010