xref: /freebsd/sys/kern/link_elf.c (revision 6829dae12bb055451fa467da4589c43bd03b1e64)
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 		printf("%s: pcpu module space is out of space; "
642 		    "cannot allocate %d for %s\n",
643 		    __func__, size, ef->lf.pathname);
644 		return (ENOSPC);
645 	}
646 	memcpy((void *)ef->pcpu_base, (void *)ef->pcpu_start, size);
647 	dpcpu_copy((void *)ef->pcpu_base, size);
648 	elf_set_add(&set_pcpu_list, ef->pcpu_start, ef->pcpu_stop,
649 	    ef->pcpu_base);
650 
651 	return (0);
652 }
653 
654 #ifdef VIMAGE
655 static int
656 parse_vnet(elf_file_t ef)
657 {
658 	int error, size;
659 
660 	ef->vnet_start = 0;
661 	ef->vnet_stop = 0;
662 	error = link_elf_lookup_set(&ef->lf, "vnet", (void ***)&ef->vnet_start,
663 	    (void ***)&ef->vnet_stop, NULL);
664 	/* Error just means there is no vnet data set to relocate. */
665 	if (error != 0)
666 		return (0);
667 	size = (uintptr_t)ef->vnet_stop - (uintptr_t)ef->vnet_start;
668 	/* Empty set? */
669 	if (size < 1)
670 		return (0);
671 	/*
672 	 * Allocate space in the primary vnet area.  Copy in our
673 	 * initialization from the data section and then initialize
674 	 * all per-vnet storage from that.
675 	 */
676 	ef->vnet_base = (Elf_Addr)(uintptr_t)vnet_data_alloc(size);
677 	if (ef->vnet_base == 0) {
678 		printf("%s: vnet module space is out of space; "
679 		    "cannot allocate %d for %s\n",
680 		    __func__, size, ef->lf.pathname);
681 		return (ENOSPC);
682 	}
683 	memcpy((void *)ef->vnet_base, (void *)ef->vnet_start, size);
684 	vnet_data_copy((void *)ef->vnet_base, size);
685 	elf_set_add(&set_vnet_list, ef->vnet_start, ef->vnet_stop,
686 	    ef->vnet_base);
687 
688 	return (0);
689 }
690 #endif
691 
692 static int
693 link_elf_link_preload(linker_class_t cls,
694     const char* filename, linker_file_t *result)
695 {
696 	Elf_Addr *ctors_addrp;
697 	Elf_Size *ctors_sizep;
698 	caddr_t modptr, baseptr, sizeptr, dynptr;
699 	char *type;
700 	elf_file_t ef;
701 	linker_file_t lf;
702 	int error;
703 	vm_offset_t dp;
704 
705 	/* Look to see if we have the file preloaded */
706 	modptr = preload_search_by_name(filename);
707 	if (modptr == NULL)
708 		return (ENOENT);
709 
710 	type = (char *)preload_search_info(modptr, MODINFO_TYPE);
711 	baseptr = preload_search_info(modptr, MODINFO_ADDR);
712 	sizeptr = preload_search_info(modptr, MODINFO_SIZE);
713 	dynptr = preload_search_info(modptr,
714 	    MODINFO_METADATA | MODINFOMD_DYNAMIC);
715 	if (type == NULL ||
716 	    (strcmp(type, "elf" __XSTRING(__ELF_WORD_SIZE) " module") != 0 &&
717 	     strcmp(type, "elf module") != 0))
718 		return (EFTYPE);
719 	if (baseptr == NULL || sizeptr == NULL || dynptr == NULL)
720 		return (EINVAL);
721 
722 	lf = linker_make_file(filename, &link_elf_class);
723 	if (lf == NULL)
724 		return (ENOMEM);
725 
726 	ef = (elf_file_t) lf;
727 	ef->preloaded = 1;
728 	ef->modptr = modptr;
729 	ef->address = *(caddr_t *)baseptr;
730 #ifdef SPARSE_MAPPING
731 	ef->object = 0;
732 #endif
733 	dp = (vm_offset_t)ef->address + *(vm_offset_t *)dynptr;
734 	ef->dynamic = (Elf_Dyn *)dp;
735 	lf->address = ef->address;
736 	lf->size = *(size_t *)sizeptr;
737 
738 	ctors_addrp = (Elf_Addr *)preload_search_info(modptr,
739 	    MODINFO_METADATA | MODINFOMD_CTORS_ADDR);
740 	ctors_sizep = (Elf_Size *)preload_search_info(modptr,
741 	    MODINFO_METADATA | MODINFOMD_CTORS_SIZE);
742 	if (ctors_addrp != NULL && ctors_sizep != NULL) {
743 		lf->ctors_addr = ef->address + *ctors_addrp;
744 		lf->ctors_size = *ctors_sizep;
745 	}
746 
747 	error = parse_dynamic(ef);
748 	if (error == 0)
749 		error = parse_dpcpu(ef);
750 #ifdef VIMAGE
751 	if (error == 0)
752 		error = parse_vnet(ef);
753 #endif
754 	if (error != 0) {
755 		linker_file_unload(lf, LINKER_UNLOAD_FORCE);
756 		return (error);
757 	}
758 	link_elf_reloc_local(lf);
759 	*result = lf;
760 	return (0);
761 }
762 
763 static int
764 link_elf_link_preload_finish(linker_file_t lf)
765 {
766 	elf_file_t ef;
767 	int error;
768 
769 	ef = (elf_file_t) lf;
770 	error = relocate_file(ef);
771 	if (error != 0)
772 		return (error);
773 	(void)link_elf_preload_parse_symbols(ef);
774 
775 	return (link_elf_link_common_finish(lf));
776 }
777 
778 static int
779 link_elf_load_file(linker_class_t cls, const char* filename,
780     linker_file_t* result)
781 {
782 	struct nameidata nd;
783 	struct thread* td = curthread;	/* XXX */
784 	Elf_Ehdr *hdr;
785 	caddr_t firstpage;
786 	int nbytes, i;
787 	Elf_Phdr *phdr;
788 	Elf_Phdr *phlimit;
789 	Elf_Phdr *segs[MAXSEGS];
790 	int nsegs;
791 	Elf_Phdr *phdyn;
792 	caddr_t mapbase;
793 	size_t mapsize;
794 	Elf_Addr base_vaddr;
795 	Elf_Addr base_vlimit;
796 	int error = 0;
797 	ssize_t resid;
798 	int flags;
799 	elf_file_t ef;
800 	linker_file_t lf;
801 	Elf_Shdr *shdr;
802 	int symtabindex;
803 	int symstrindex;
804 	int shstrindex;
805 	int symcnt;
806 	int strcnt;
807 	char *shstrs;
808 
809 	shdr = NULL;
810 	lf = NULL;
811 	shstrs = NULL;
812 
813 	NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, filename, td);
814 	flags = FREAD;
815 	error = vn_open(&nd, &flags, 0, NULL);
816 	if (error != 0)
817 		return (error);
818 	NDFREE(&nd, NDF_ONLY_PNBUF);
819 	if (nd.ni_vp->v_type != VREG) {
820 		error = ENOEXEC;
821 		firstpage = NULL;
822 		goto out;
823 	}
824 #ifdef MAC
825 	error = mac_kld_check_load(curthread->td_ucred, nd.ni_vp);
826 	if (error != 0) {
827 		firstpage = NULL;
828 		goto out;
829 	}
830 #endif
831 
832 	/*
833 	 * Read the elf header from the file.
834 	 */
835 	firstpage = malloc(PAGE_SIZE, M_LINKER, M_WAITOK);
836 	hdr = (Elf_Ehdr *)firstpage;
837 	error = vn_rdwr(UIO_READ, nd.ni_vp, firstpage, PAGE_SIZE, 0,
838 	    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred, NOCRED,
839 	    &resid, td);
840 	nbytes = PAGE_SIZE - resid;
841 	if (error != 0)
842 		goto out;
843 
844 	if (!IS_ELF(*hdr)) {
845 		error = ENOEXEC;
846 		goto out;
847 	}
848 
849 	if (hdr->e_ident[EI_CLASS] != ELF_TARG_CLASS ||
850 	    hdr->e_ident[EI_DATA] != ELF_TARG_DATA) {
851 		link_elf_error(filename, "Unsupported file layout");
852 		error = ENOEXEC;
853 		goto out;
854 	}
855 	if (hdr->e_ident[EI_VERSION] != EV_CURRENT ||
856 	    hdr->e_version != EV_CURRENT) {
857 		link_elf_error(filename, "Unsupported file version");
858 		error = ENOEXEC;
859 		goto out;
860 	}
861 	if (hdr->e_type != ET_EXEC && hdr->e_type != ET_DYN) {
862 		error = ENOSYS;
863 		goto out;
864 	}
865 	if (hdr->e_machine != ELF_TARG_MACH) {
866 		link_elf_error(filename, "Unsupported machine");
867 		error = ENOEXEC;
868 		goto out;
869 	}
870 
871 	/*
872 	 * We rely on the program header being in the first page.
873 	 * This is not strictly required by the ABI specification, but
874 	 * it seems to always true in practice.  And, it simplifies
875 	 * things considerably.
876 	 */
877 	if (!((hdr->e_phentsize == sizeof(Elf_Phdr)) &&
878 	      (hdr->e_phoff + hdr->e_phnum*sizeof(Elf_Phdr) <= PAGE_SIZE) &&
879 	      (hdr->e_phoff + hdr->e_phnum*sizeof(Elf_Phdr) <= nbytes)))
880 		link_elf_error(filename, "Unreadable program headers");
881 
882 	/*
883 	 * Scan the program header entries, and save key information.
884 	 *
885 	 * We rely on there being exactly two load segments, text and data,
886 	 * in that order.
887 	 */
888 	phdr = (Elf_Phdr *) (firstpage + hdr->e_phoff);
889 	phlimit = phdr + hdr->e_phnum;
890 	nsegs = 0;
891 	phdyn = NULL;
892 	while (phdr < phlimit) {
893 		switch (phdr->p_type) {
894 		case PT_LOAD:
895 			if (nsegs == MAXSEGS) {
896 				link_elf_error(filename, "Too many sections");
897 				error = ENOEXEC;
898 				goto out;
899 			}
900 			/*
901 			 * XXX: We just trust they come in right order ??
902 			 */
903 			segs[nsegs] = phdr;
904 			++nsegs;
905 			break;
906 
907 		case PT_DYNAMIC:
908 			phdyn = phdr;
909 			break;
910 
911 		case PT_INTERP:
912 			error = ENOSYS;
913 			goto out;
914 		}
915 
916 		++phdr;
917 	}
918 	if (phdyn == NULL) {
919 		link_elf_error(filename, "Object is not dynamically-linked");
920 		error = ENOEXEC;
921 		goto out;
922 	}
923 	if (nsegs == 0) {
924 		link_elf_error(filename, "No sections");
925 		error = ENOEXEC;
926 		goto out;
927 	}
928 
929 	/*
930 	 * Allocate the entire address space of the object, to stake
931 	 * out our contiguous region, and to establish the base
932 	 * address for relocation.
933 	 */
934 	base_vaddr = trunc_page(segs[0]->p_vaddr);
935 	base_vlimit = round_page(segs[nsegs - 1]->p_vaddr +
936 	    segs[nsegs - 1]->p_memsz);
937 	mapsize = base_vlimit - base_vaddr;
938 
939 	lf = linker_make_file(filename, &link_elf_class);
940 	if (lf == NULL) {
941 		error = ENOMEM;
942 		goto out;
943 	}
944 
945 	ef = (elf_file_t) lf;
946 #ifdef SPARSE_MAPPING
947 	ef->object = vm_object_allocate(OBJT_DEFAULT, mapsize >> PAGE_SHIFT);
948 	if (ef->object == NULL) {
949 		error = ENOMEM;
950 		goto out;
951 	}
952 	ef->address = (caddr_t) vm_map_min(kernel_map);
953 	error = vm_map_find(kernel_map, ef->object, 0,
954 	    (vm_offset_t *) &ef->address, mapsize, 0, VMFS_OPTIMAL_SPACE,
955 	    VM_PROT_ALL, VM_PROT_ALL, 0);
956 	if (error != 0) {
957 		vm_object_deallocate(ef->object);
958 		ef->object = 0;
959 		goto out;
960 	}
961 #else
962 	ef->address = malloc(mapsize, M_LINKER, M_EXEC | M_WAITOK);
963 #endif
964 	mapbase = ef->address;
965 
966 	/*
967 	 * Read the text and data sections and zero the bss.
968 	 */
969 	for (i = 0; i < nsegs; i++) {
970 		caddr_t segbase = mapbase + segs[i]->p_vaddr - base_vaddr;
971 		error = vn_rdwr(UIO_READ, nd.ni_vp,
972 		    segbase, segs[i]->p_filesz, segs[i]->p_offset,
973 		    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred, NOCRED,
974 		    &resid, td);
975 		if (error != 0)
976 			goto out;
977 		bzero(segbase + segs[i]->p_filesz,
978 		    segs[i]->p_memsz - segs[i]->p_filesz);
979 
980 #ifdef SPARSE_MAPPING
981 		/*
982 		 * Wire down the pages
983 		 */
984 		error = vm_map_wire(kernel_map,
985 		    (vm_offset_t) segbase,
986 		    (vm_offset_t) segbase + segs[i]->p_memsz,
987 		    VM_MAP_WIRE_SYSTEM|VM_MAP_WIRE_NOHOLES);
988 		if (error != KERN_SUCCESS) {
989 			error = ENOMEM;
990 			goto out;
991 		}
992 #endif
993 	}
994 
995 #ifdef GPROF
996 	/* Update profiling information with the new text segment. */
997 	mtx_lock(&Giant);
998 	kmupetext((uintfptr_t)(mapbase + segs[0]->p_vaddr - base_vaddr +
999 	    segs[0]->p_memsz));
1000 	mtx_unlock(&Giant);
1001 #endif
1002 
1003 	ef->dynamic = (Elf_Dyn *) (mapbase + phdyn->p_vaddr - base_vaddr);
1004 
1005 	lf->address = ef->address;
1006 	lf->size = mapsize;
1007 
1008 	error = parse_dynamic(ef);
1009 	if (error != 0)
1010 		goto out;
1011 	error = parse_dpcpu(ef);
1012 	if (error != 0)
1013 		goto out;
1014 #ifdef VIMAGE
1015 	error = parse_vnet(ef);
1016 	if (error != 0)
1017 		goto out;
1018 #endif
1019 	link_elf_reloc_local(lf);
1020 
1021 	VOP_UNLOCK(nd.ni_vp, 0);
1022 	error = linker_load_dependencies(lf);
1023 	vn_lock(nd.ni_vp, LK_EXCLUSIVE | LK_RETRY);
1024 	if (error != 0)
1025 		goto out;
1026 	error = relocate_file(ef);
1027 	if (error != 0)
1028 		goto out;
1029 
1030 	/*
1031 	 * Try and load the symbol table if it's present.  (you can
1032 	 * strip it!)
1033 	 */
1034 	nbytes = hdr->e_shnum * hdr->e_shentsize;
1035 	if (nbytes == 0 || hdr->e_shoff == 0)
1036 		goto nosyms;
1037 	shdr = malloc(nbytes, M_LINKER, M_WAITOK | M_ZERO);
1038 	error = vn_rdwr(UIO_READ, nd.ni_vp,
1039 	    (caddr_t)shdr, nbytes, hdr->e_shoff,
1040 	    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred, NOCRED,
1041 	    &resid, td);
1042 	if (error != 0)
1043 		goto out;
1044 
1045 	/* Read section string table */
1046 	shstrindex = hdr->e_shstrndx;
1047 	if (shstrindex != 0 && shdr[shstrindex].sh_type == SHT_STRTAB &&
1048 	    shdr[shstrindex].sh_size != 0) {
1049 		nbytes = shdr[shstrindex].sh_size;
1050 		shstrs = malloc(nbytes, M_LINKER, M_WAITOK | M_ZERO);
1051 		error = vn_rdwr(UIO_READ, nd.ni_vp, (caddr_t)shstrs, nbytes,
1052 		    shdr[shstrindex].sh_offset, UIO_SYSSPACE, IO_NODELOCKED,
1053 		    td->td_ucred, NOCRED, &resid, td);
1054 		if (error)
1055 			goto out;
1056 	}
1057 
1058 	symtabindex = -1;
1059 	symstrindex = -1;
1060 	for (i = 0; i < hdr->e_shnum; i++) {
1061 		if (shdr[i].sh_type == SHT_SYMTAB) {
1062 			symtabindex = i;
1063 			symstrindex = shdr[i].sh_link;
1064 		} else if (shstrs != NULL && shdr[i].sh_name != 0 &&
1065 		    strcmp(shstrs + shdr[i].sh_name, ".ctors") == 0) {
1066 			/* Record relocated address and size of .ctors. */
1067 			lf->ctors_addr = mapbase + shdr[i].sh_addr - base_vaddr;
1068 			lf->ctors_size = shdr[i].sh_size;
1069 		}
1070 	}
1071 	if (symtabindex < 0 || symstrindex < 0)
1072 		goto nosyms;
1073 
1074 	symcnt = shdr[symtabindex].sh_size;
1075 	ef->symbase = malloc(symcnt, M_LINKER, M_WAITOK);
1076 	strcnt = shdr[symstrindex].sh_size;
1077 	ef->strbase = malloc(strcnt, M_LINKER, M_WAITOK);
1078 
1079 	error = vn_rdwr(UIO_READ, nd.ni_vp,
1080 	    ef->symbase, symcnt, shdr[symtabindex].sh_offset,
1081 	    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred, NOCRED,
1082 	    &resid, td);
1083 	if (error != 0)
1084 		goto out;
1085 	error = vn_rdwr(UIO_READ, nd.ni_vp,
1086 	    ef->strbase, strcnt, shdr[symstrindex].sh_offset,
1087 	    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred, NOCRED,
1088 	    &resid, td);
1089 	if (error != 0)
1090 		goto out;
1091 
1092 	ef->ddbsymcnt = symcnt / sizeof(Elf_Sym);
1093 	ef->ddbsymtab = (const Elf_Sym *)ef->symbase;
1094 	ef->ddbstrcnt = strcnt;
1095 	ef->ddbstrtab = ef->strbase;
1096 
1097 nosyms:
1098 	error = link_elf_link_common_finish(lf);
1099 	if (error != 0)
1100 		goto out;
1101 
1102 	*result = lf;
1103 
1104 out:
1105 	VOP_UNLOCK(nd.ni_vp, 0);
1106 	vn_close(nd.ni_vp, FREAD, td->td_ucred, td);
1107 	if (error != 0 && lf != NULL)
1108 		linker_file_unload(lf, LINKER_UNLOAD_FORCE);
1109 	free(shdr, M_LINKER);
1110 	free(firstpage, M_LINKER);
1111 	free(shstrs, M_LINKER);
1112 
1113 	return (error);
1114 }
1115 
1116 Elf_Addr
1117 elf_relocaddr(linker_file_t lf, Elf_Addr x)
1118 {
1119 	elf_file_t ef;
1120 
1121 	ef = (elf_file_t)lf;
1122 	if (x >= ef->pcpu_start && x < ef->pcpu_stop)
1123 		return ((x - ef->pcpu_start) + ef->pcpu_base);
1124 #ifdef VIMAGE
1125 	if (x >= ef->vnet_start && x < ef->vnet_stop)
1126 		return ((x - ef->vnet_start) + ef->vnet_base);
1127 #endif
1128 	return (x);
1129 }
1130 
1131 
1132 static void
1133 link_elf_unload_file(linker_file_t file)
1134 {
1135 	elf_file_t ef = (elf_file_t) file;
1136 
1137 	if (ef->pcpu_base != 0) {
1138 		dpcpu_free((void *)ef->pcpu_base,
1139 		    ef->pcpu_stop - ef->pcpu_start);
1140 		elf_set_delete(&set_pcpu_list, ef->pcpu_start);
1141 	}
1142 #ifdef VIMAGE
1143 	if (ef->vnet_base != 0) {
1144 		vnet_data_free((void *)ef->vnet_base,
1145 		    ef->vnet_stop - ef->vnet_start);
1146 		elf_set_delete(&set_vnet_list, ef->vnet_start);
1147 	}
1148 #endif
1149 #ifdef GDB
1150 	if (ef->gdb.l_ld != NULL) {
1151 		GDB_STATE(RT_DELETE);
1152 		free((void *)(uintptr_t)ef->gdb.l_name, M_LINKER);
1153 		link_elf_delete_gdb(&ef->gdb);
1154 		GDB_STATE(RT_CONSISTENT);
1155 	}
1156 #endif
1157 
1158 	/* Notify MD code that a module is being unloaded. */
1159 	elf_cpu_unload_file(file);
1160 
1161 	if (ef->preloaded) {
1162 		link_elf_unload_preload(file);
1163 		return;
1164 	}
1165 
1166 #ifdef SPARSE_MAPPING
1167 	if (ef->object != NULL) {
1168 		vm_map_remove(kernel_map, (vm_offset_t) ef->address,
1169 		    (vm_offset_t) ef->address
1170 		    + (ef->object->size << PAGE_SHIFT));
1171 	}
1172 #else
1173 	free(ef->address, M_LINKER);
1174 #endif
1175 	free(ef->symbase, M_LINKER);
1176 	free(ef->strbase, M_LINKER);
1177 	free(ef->ctftab, M_LINKER);
1178 	free(ef->ctfoff, M_LINKER);
1179 	free(ef->typoff, M_LINKER);
1180 }
1181 
1182 static void
1183 link_elf_unload_preload(linker_file_t file)
1184 {
1185 	if (file->pathname != NULL)
1186 		preload_delete_name(file->pathname);
1187 }
1188 
1189 static const char *
1190 symbol_name(elf_file_t ef, Elf_Size r_info)
1191 {
1192 	const Elf_Sym *ref;
1193 
1194 	if (ELF_R_SYM(r_info)) {
1195 		ref = ef->symtab + ELF_R_SYM(r_info);
1196 		return (ef->strtab + ref->st_name);
1197 	}
1198 	return (NULL);
1199 }
1200 
1201 static int
1202 symbol_type(elf_file_t ef, Elf_Size r_info)
1203 {
1204 	const Elf_Sym *ref;
1205 
1206 	if (ELF_R_SYM(r_info)) {
1207 		ref = ef->symtab + ELF_R_SYM(r_info);
1208 		return (ELF_ST_TYPE(ref->st_info));
1209 	}
1210 	return (STT_NOTYPE);
1211 }
1212 
1213 static int
1214 relocate_file1(elf_file_t ef, elf_lookup_fn lookup, elf_reloc_fn reloc,
1215     bool ifuncs)
1216 {
1217 	const Elf_Rel *rel;
1218 	const Elf_Rela *rela;
1219 	const char *symname;
1220 
1221 #define	APPLY_RELOCS(iter, tbl, tblsize, type) do {			\
1222 	for ((iter) = (tbl); (iter) != NULL &&				\
1223 	    (iter) < (tbl) + (tblsize) / sizeof(*(iter)); (iter)++) {	\
1224 		if ((symbol_type(ef, (iter)->r_info) ==			\
1225 		    STT_GNU_IFUNC ||					\
1226 		    elf_is_ifunc_reloc((iter)->r_info)) != ifuncs)	\
1227 			continue;					\
1228 		if (reloc(&ef->lf, (Elf_Addr)ef->address,		\
1229 		    (iter), (type), lookup)) {				\
1230 			symname = symbol_name(ef, (iter)->r_info);	\
1231 			printf("link_elf: symbol %s undefined\n",	\
1232 			    symname);					\
1233 			return (ENOENT);				\
1234 		}							\
1235 	}								\
1236 } while (0)
1237 
1238 	APPLY_RELOCS(rel, ef->rel, ef->relsize, ELF_RELOC_REL);
1239 	APPLY_RELOCS(rela, ef->rela, ef->relasize, ELF_RELOC_RELA);
1240 	APPLY_RELOCS(rel, ef->pltrel, ef->pltrelsize, ELF_RELOC_REL);
1241 	APPLY_RELOCS(rela, ef->pltrela, ef->pltrelasize, ELF_RELOC_RELA);
1242 
1243 #undef APPLY_RELOCS
1244 
1245 	return (0);
1246 }
1247 
1248 static int
1249 relocate_file(elf_file_t ef)
1250 {
1251 	int error;
1252 
1253 	error = relocate_file1(ef, elf_lookup, elf_reloc, false);
1254 	if (error == 0)
1255 		error = relocate_file1(ef, elf_lookup, elf_reloc, true);
1256 	return (error);
1257 }
1258 
1259 /*
1260  * Hash function for symbol table lookup.  Don't even think about changing
1261  * this.  It is specified by the System V ABI.
1262  */
1263 static unsigned long
1264 elf_hash(const char *name)
1265 {
1266 	const unsigned char *p = (const unsigned char *) name;
1267 	unsigned long h = 0;
1268 	unsigned long g;
1269 
1270 	while (*p != '\0') {
1271 		h = (h << 4) + *p++;
1272 		if ((g = h & 0xf0000000) != 0)
1273 			h ^= g >> 24;
1274 		h &= ~g;
1275 	}
1276 	return (h);
1277 }
1278 
1279 static int
1280 link_elf_lookup_symbol(linker_file_t lf, const char *name, c_linker_sym_t *sym)
1281 {
1282 	elf_file_t ef = (elf_file_t) lf;
1283 	unsigned long symnum;
1284 	const Elf_Sym* symp;
1285 	const char *strp;
1286 	unsigned long hash;
1287 	int i;
1288 
1289 	/* If we don't have a hash, bail. */
1290 	if (ef->buckets == NULL || ef->nbuckets == 0) {
1291 		printf("link_elf_lookup_symbol: missing symbol hash table\n");
1292 		return (ENOENT);
1293 	}
1294 
1295 	/* First, search hashed global symbols */
1296 	hash = elf_hash(name);
1297 	symnum = ef->buckets[hash % ef->nbuckets];
1298 
1299 	while (symnum != STN_UNDEF) {
1300 		if (symnum >= ef->nchains) {
1301 			printf("%s: corrupt symbol table\n", __func__);
1302 			return (ENOENT);
1303 		}
1304 
1305 		symp = ef->symtab + symnum;
1306 		if (symp->st_name == 0) {
1307 			printf("%s: corrupt symbol table\n", __func__);
1308 			return (ENOENT);
1309 		}
1310 
1311 		strp = ef->strtab + symp->st_name;
1312 
1313 		if (strcmp(name, strp) == 0) {
1314 			if (symp->st_shndx != SHN_UNDEF ||
1315 			    (symp->st_value != 0 &&
1316 			    (ELF_ST_TYPE(symp->st_info) == STT_FUNC ||
1317 			    ELF_ST_TYPE(symp->st_info) == STT_GNU_IFUNC))) {
1318 				*sym = (c_linker_sym_t) symp;
1319 				return (0);
1320 			}
1321 			return (ENOENT);
1322 		}
1323 
1324 		symnum = ef->chains[symnum];
1325 	}
1326 
1327 	/* If we have not found it, look at the full table (if loaded) */
1328 	if (ef->symtab == ef->ddbsymtab)
1329 		return (ENOENT);
1330 
1331 	/* Exhaustive search */
1332 	for (i = 0, symp = ef->ddbsymtab; i < ef->ddbsymcnt; i++, symp++) {
1333 		strp = ef->ddbstrtab + symp->st_name;
1334 		if (strcmp(name, strp) == 0) {
1335 			if (symp->st_shndx != SHN_UNDEF ||
1336 			    (symp->st_value != 0 &&
1337 			    (ELF_ST_TYPE(symp->st_info) == STT_FUNC ||
1338 			    ELF_ST_TYPE(symp->st_info) == STT_GNU_IFUNC))) {
1339 				*sym = (c_linker_sym_t) symp;
1340 				return (0);
1341 			}
1342 			return (ENOENT);
1343 		}
1344 	}
1345 
1346 	return (ENOENT);
1347 }
1348 
1349 static int
1350 link_elf_symbol_values(linker_file_t lf, c_linker_sym_t sym,
1351     linker_symval_t *symval)
1352 {
1353 	elf_file_t ef;
1354 	const Elf_Sym *es;
1355 	caddr_t val;
1356 
1357 	ef = (elf_file_t)lf;
1358 	es = (const Elf_Sym *)sym;
1359 	if (es >= ef->symtab && es < (ef->symtab + ef->nchains)) {
1360 		symval->name = ef->strtab + es->st_name;
1361 		val = (caddr_t)ef->address + es->st_value;
1362 		if (ELF_ST_TYPE(es->st_info) == STT_GNU_IFUNC)
1363 			val = ((caddr_t (*)(void))val)();
1364 		symval->value = val;
1365 		symval->size = es->st_size;
1366 		return (0);
1367 	}
1368 	if (ef->symtab == ef->ddbsymtab)
1369 		return (ENOENT);
1370 	if (es >= ef->ddbsymtab && es < (ef->ddbsymtab + ef->ddbsymcnt)) {
1371 		symval->name = ef->ddbstrtab + es->st_name;
1372 		val = (caddr_t)ef->address + es->st_value;
1373 		if (ELF_ST_TYPE(es->st_info) == STT_GNU_IFUNC)
1374 			val = ((caddr_t (*)(void))val)();
1375 		symval->value = val;
1376 		symval->size = es->st_size;
1377 		return (0);
1378 	}
1379 	return (ENOENT);
1380 }
1381 
1382 static int
1383 link_elf_search_symbol(linker_file_t lf, caddr_t value,
1384     c_linker_sym_t *sym, long *diffp)
1385 {
1386 	elf_file_t ef = (elf_file_t) lf;
1387 	u_long off = (uintptr_t) (void *) value;
1388 	u_long diff = off;
1389 	u_long st_value;
1390 	const Elf_Sym* es;
1391 	const Elf_Sym* best = NULL;
1392 	int i;
1393 
1394 	for (i = 0, es = ef->ddbsymtab; i < ef->ddbsymcnt; i++, es++) {
1395 		if (es->st_name == 0)
1396 			continue;
1397 		st_value = es->st_value + (uintptr_t) (void *) ef->address;
1398 		if (off >= st_value) {
1399 			if (off - st_value < diff) {
1400 				diff = off - st_value;
1401 				best = es;
1402 				if (diff == 0)
1403 					break;
1404 			} else if (off - st_value == diff) {
1405 				best = es;
1406 			}
1407 		}
1408 	}
1409 	if (best == NULL)
1410 		*diffp = off;
1411 	else
1412 		*diffp = diff;
1413 	*sym = (c_linker_sym_t) best;
1414 
1415 	return (0);
1416 }
1417 
1418 /*
1419  * Look up a linker set on an ELF system.
1420  */
1421 static int
1422 link_elf_lookup_set(linker_file_t lf, const char *name,
1423     void ***startp, void ***stopp, int *countp)
1424 {
1425 	c_linker_sym_t sym;
1426 	linker_symval_t symval;
1427 	char *setsym;
1428 	void **start, **stop;
1429 	int len, error = 0, count;
1430 
1431 	len = strlen(name) + sizeof("__start_set_"); /* sizeof includes \0 */
1432 	setsym = malloc(len, M_LINKER, M_WAITOK);
1433 
1434 	/* get address of first entry */
1435 	snprintf(setsym, len, "%s%s", "__start_set_", name);
1436 	error = link_elf_lookup_symbol(lf, setsym, &sym);
1437 	if (error != 0)
1438 		goto out;
1439 	link_elf_symbol_values(lf, sym, &symval);
1440 	if (symval.value == 0) {
1441 		error = ESRCH;
1442 		goto out;
1443 	}
1444 	start = (void **)symval.value;
1445 
1446 	/* get address of last entry */
1447 	snprintf(setsym, len, "%s%s", "__stop_set_", name);
1448 	error = link_elf_lookup_symbol(lf, setsym, &sym);
1449 	if (error != 0)
1450 		goto out;
1451 	link_elf_symbol_values(lf, sym, &symval);
1452 	if (symval.value == 0) {
1453 		error = ESRCH;
1454 		goto out;
1455 	}
1456 	stop = (void **)symval.value;
1457 
1458 	/* and the number of entries */
1459 	count = stop - start;
1460 
1461 	/* and copy out */
1462 	if (startp != NULL)
1463 		*startp = start;
1464 	if (stopp != NULL)
1465 		*stopp = stop;
1466 	if (countp != NULL)
1467 		*countp = count;
1468 
1469 out:
1470 	free(setsym, M_LINKER);
1471 	return (error);
1472 }
1473 
1474 static int
1475 link_elf_each_function_name(linker_file_t file,
1476   int (*callback)(const char *, void *), void *opaque)
1477 {
1478 	elf_file_t ef = (elf_file_t)file;
1479 	const Elf_Sym *symp;
1480 	int i, error;
1481 
1482 	/* Exhaustive search */
1483 	for (i = 0, symp = ef->ddbsymtab; i < ef->ddbsymcnt; i++, symp++) {
1484 		if (symp->st_value != 0 &&
1485 		    (ELF_ST_TYPE(symp->st_info) == STT_FUNC ||
1486 		    ELF_ST_TYPE(symp->st_info) == STT_GNU_IFUNC)) {
1487 			error = callback(ef->ddbstrtab + symp->st_name, opaque);
1488 			if (error != 0)
1489 				return (error);
1490 		}
1491 	}
1492 	return (0);
1493 }
1494 
1495 static int
1496 link_elf_each_function_nameval(linker_file_t file,
1497     linker_function_nameval_callback_t callback, void *opaque)
1498 {
1499 	linker_symval_t symval;
1500 	elf_file_t ef = (elf_file_t)file;
1501 	const Elf_Sym* symp;
1502 	int i, error;
1503 
1504 	/* Exhaustive search */
1505 	for (i = 0, symp = ef->ddbsymtab; i < ef->ddbsymcnt; i++, symp++) {
1506 		if (symp->st_value != 0 &&
1507 		    (ELF_ST_TYPE(symp->st_info) == STT_FUNC ||
1508 		    ELF_ST_TYPE(symp->st_info) == STT_GNU_IFUNC)) {
1509 			error = link_elf_symbol_values(file,
1510 			    (c_linker_sym_t) symp, &symval);
1511 			if (error != 0)
1512 				return (error);
1513 			error = callback(file, i, &symval, opaque);
1514 			if (error != 0)
1515 				return (error);
1516 		}
1517 	}
1518 	return (0);
1519 }
1520 
1521 const Elf_Sym *
1522 elf_get_sym(linker_file_t lf, Elf_Size symidx)
1523 {
1524 	elf_file_t ef = (elf_file_t)lf;
1525 
1526 	if (symidx >= ef->nchains)
1527 		return (NULL);
1528 	return (ef->symtab + symidx);
1529 }
1530 
1531 const char *
1532 elf_get_symname(linker_file_t lf, Elf_Size symidx)
1533 {
1534 	elf_file_t ef = (elf_file_t)lf;
1535 	const Elf_Sym *sym;
1536 
1537 	if (symidx >= ef->nchains)
1538 		return (NULL);
1539 	sym = ef->symtab + symidx;
1540 	return (ef->strtab + sym->st_name);
1541 }
1542 
1543 /*
1544  * Symbol lookup function that can be used when the symbol index is known (ie
1545  * in relocations). It uses the symbol index instead of doing a fully fledged
1546  * hash table based lookup when such is valid. For example for local symbols.
1547  * This is not only more efficient, it's also more correct. It's not always
1548  * the case that the symbol can be found through the hash table.
1549  */
1550 static int
1551 elf_lookup(linker_file_t lf, Elf_Size symidx, int deps, Elf_Addr *res)
1552 {
1553 	elf_file_t ef = (elf_file_t)lf;
1554 	const Elf_Sym *sym;
1555 	const char *symbol;
1556 	Elf_Addr addr, start, base;
1557 
1558 	/* Don't even try to lookup the symbol if the index is bogus. */
1559 	if (symidx >= ef->nchains) {
1560 		*res = 0;
1561 		return (EINVAL);
1562 	}
1563 
1564 	sym = ef->symtab + symidx;
1565 
1566 	/*
1567 	 * Don't do a full lookup when the symbol is local. It may even
1568 	 * fail because it may not be found through the hash table.
1569 	 */
1570 	if (ELF_ST_BIND(sym->st_info) == STB_LOCAL) {
1571 		/* Force lookup failure when we have an insanity. */
1572 		if (sym->st_shndx == SHN_UNDEF || sym->st_value == 0) {
1573 			*res = 0;
1574 			return (EINVAL);
1575 		}
1576 		*res = ((Elf_Addr)ef->address + sym->st_value);
1577 		return (0);
1578 	}
1579 
1580 	/*
1581 	 * XXX we can avoid doing a hash table based lookup for global
1582 	 * symbols as well. This however is not always valid, so we'll
1583 	 * just do it the hard way for now. Performance tweaks can
1584 	 * always be added.
1585 	 */
1586 
1587 	symbol = ef->strtab + sym->st_name;
1588 
1589 	/* Force a lookup failure if the symbol name is bogus. */
1590 	if (*symbol == 0) {
1591 		*res = 0;
1592 		return (EINVAL);
1593 	}
1594 
1595 	addr = ((Elf_Addr)linker_file_lookup_symbol(lf, symbol, deps));
1596 	if (addr == 0 && ELF_ST_BIND(sym->st_info) != STB_WEAK) {
1597 		*res = 0;
1598 		return (EINVAL);
1599 	}
1600 
1601 	if (elf_set_find(&set_pcpu_list, addr, &start, &base))
1602 		addr = addr - start + base;
1603 #ifdef VIMAGE
1604 	else if (elf_set_find(&set_vnet_list, addr, &start, &base))
1605 		addr = addr - start + base;
1606 #endif
1607 	*res = addr;
1608 	return (0);
1609 }
1610 
1611 static void
1612 link_elf_reloc_local(linker_file_t lf)
1613 {
1614 	const Elf_Rel *rellim;
1615 	const Elf_Rel *rel;
1616 	const Elf_Rela *relalim;
1617 	const Elf_Rela *rela;
1618 	elf_file_t ef = (elf_file_t)lf;
1619 
1620 	/* Perform relocations without addend if there are any: */
1621 	if ((rel = ef->rel) != NULL) {
1622 		rellim = (const Elf_Rel *)((const char *)ef->rel + ef->relsize);
1623 		while (rel < rellim) {
1624 			elf_reloc_local(lf, (Elf_Addr)ef->address, rel,
1625 			    ELF_RELOC_REL, elf_lookup);
1626 			rel++;
1627 		}
1628 	}
1629 
1630 	/* Perform relocations with addend if there are any: */
1631 	if ((rela = ef->rela) != NULL) {
1632 		relalim = (const Elf_Rela *)
1633 		    ((const char *)ef->rela + ef->relasize);
1634 		while (rela < relalim) {
1635 			elf_reloc_local(lf, (Elf_Addr)ef->address, rela,
1636 			    ELF_RELOC_RELA, elf_lookup);
1637 			rela++;
1638 		}
1639 	}
1640 }
1641 
1642 static long
1643 link_elf_symtab_get(linker_file_t lf, const Elf_Sym **symtab)
1644 {
1645 	elf_file_t ef = (elf_file_t)lf;
1646 
1647 	*symtab = ef->ddbsymtab;
1648 
1649 	if (*symtab == NULL)
1650 		return (0);
1651 
1652 	return (ef->ddbsymcnt);
1653 }
1654 
1655 static long
1656 link_elf_strtab_get(linker_file_t lf, caddr_t *strtab)
1657 {
1658 	elf_file_t ef = (elf_file_t)lf;
1659 
1660 	*strtab = ef->ddbstrtab;
1661 
1662 	if (*strtab == NULL)
1663 		return (0);
1664 
1665 	return (ef->ddbstrcnt);
1666 }
1667 
1668 #if defined(__i386__) || defined(__amd64__) || defined(__aarch64__)
1669 /*
1670  * Use this lookup routine when performing relocations early during boot.
1671  * The generic lookup routine depends on kobj, which is not initialized
1672  * at that point.
1673  */
1674 static int
1675 elf_lookup_ifunc(linker_file_t lf, Elf_Size symidx, int deps __unused,
1676     Elf_Addr *res)
1677 {
1678 	elf_file_t ef;
1679 	const Elf_Sym *symp;
1680 	caddr_t val;
1681 
1682 	ef = (elf_file_t)lf;
1683 	symp = ef->symtab + symidx;
1684 	if (ELF_ST_TYPE(symp->st_info) == STT_GNU_IFUNC) {
1685 		val = (caddr_t)ef->address + symp->st_value;
1686 		*res = ((Elf_Addr (*)(void))val)();
1687 		return (0);
1688 	}
1689 	return (ENOENT);
1690 }
1691 
1692 void
1693 link_elf_ireloc(caddr_t kmdp)
1694 {
1695 	struct elf_file eff;
1696 	elf_file_t ef;
1697 
1698 	ef = &eff;
1699 
1700 	bzero_early(ef, sizeof(*ef));
1701 
1702 	ef->modptr = kmdp;
1703 	ef->dynamic = (Elf_Dyn *)&_DYNAMIC;
1704 	parse_dynamic(ef);
1705 	ef->address = 0;
1706 	link_elf_preload_parse_symbols(ef);
1707 	relocate_file1(ef, elf_lookup_ifunc, elf_reloc, true);
1708 }
1709 #endif
1710