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