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