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