xref: /freebsd/sys/kern/link_elf_obj.c (revision 07747afd516e710814fdc65afb0e5000d046f28f)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 1998-2000 Doug Rabson
5  * Copyright (c) 2004 Peter Wemm
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #include "opt_ddb.h"
31 
32 #include <sys/param.h>
33 #include <sys/systm.h>
34 #include <sys/fcntl.h>
35 #include <sys/kernel.h>
36 #include <sys/lock.h>
37 #include <sys/malloc.h>
38 #include <sys/linker.h>
39 #include <sys/mutex.h>
40 #include <sys/mount.h>
41 #include <sys/namei.h>
42 #include <sys/proc.h>
43 #include <sys/rwlock.h>
44 #include <sys/sysctl.h>
45 #include <sys/vnode.h>
46 
47 #include <machine/elf.h>
48 
49 #include <net/vnet.h>
50 
51 #include <security/mac/mac_framework.h>
52 
53 #include <vm/vm.h>
54 #include <vm/vm_param.h>
55 #include <vm/pmap.h>
56 #include <vm/vm_extern.h>
57 #include <vm/vm_kern.h>
58 #include <vm/vm_map.h>
59 #include <vm/vm_object.h>
60 #include <vm/vm_page.h>
61 #include <vm/vm_pager.h>
62 
63 #include <sys/link_elf.h>
64 
65 #ifdef DDB_CTF
66 #include <contrib/zlib/zlib.h>
67 #endif
68 
69 #include "linker_if.h"
70 
71 typedef struct {
72 	void		*addr;
73 	void		*origaddr; /* Used by debuggers. */
74 	Elf_Off		size;
75 	int		flags;	/* Section flags. */
76 	int		sec;	/* Original section number. */
77 	char		*name;
78 } Elf_progent;
79 
80 typedef struct {
81 	Elf_Rel		*rel;
82 	int		nrel;
83 	int		sec;
84 } Elf_relent;
85 
86 typedef struct {
87 	Elf_Rela	*rela;
88 	int		nrela;
89 	int		sec;
90 } Elf_relaent;
91 
92 typedef struct elf_file {
93 	struct linker_file lf;		/* Common fields */
94 
95 	int		preloaded;
96 	caddr_t		address;	/* Relocation address */
97 	vm_object_t	object;		/* VM object to hold file pages */
98 	Elf_Shdr	*e_shdr;
99 
100 	Elf_progent	*progtab;
101 	u_int		nprogtab;
102 
103 	Elf_relaent	*relatab;
104 	u_int		nrelatab;
105 
106 	Elf_relent	*reltab;
107 	int		nreltab;
108 
109 	Elf_Sym		*ddbsymtab;	/* The symbol table we are using */
110 	long		ddbsymcnt;	/* Number of symbols */
111 	caddr_t		ddbstrtab;	/* String table */
112 	long		ddbstrcnt;	/* number of bytes in string table */
113 
114 	caddr_t		shstrtab;	/* Section name string table */
115 	long		shstrcnt;	/* number of bytes in string table */
116 
117 	caddr_t		ctftab;		/* CTF table */
118 	long		ctfcnt;		/* number of bytes in CTF table */
119 	caddr_t		ctfoff;		/* CTF offset table */
120 	caddr_t		typoff;		/* Type offset table */
121 	long		typlen;		/* Number of type entries. */
122 
123 } *elf_file_t;
124 
125 #include <kern/kern_ctf.c>
126 
127 static int	link_elf_link_preload(linker_class_t cls,
128 		    const char *, linker_file_t *);
129 static int	link_elf_link_preload_finish(linker_file_t);
130 static int	link_elf_load_file(linker_class_t, const char *, linker_file_t *);
131 static int	link_elf_lookup_symbol(linker_file_t, const char *,
132 		    c_linker_sym_t *);
133 static int	link_elf_lookup_debug_symbol(linker_file_t, const char *,
134 		    c_linker_sym_t *);
135 static int	link_elf_lookup_debug_symbol_ctf(linker_file_t lf,
136 		    const char *name, c_linker_sym_t *sym, linker_ctf_t *lc);
137 static int	link_elf_symbol_values(linker_file_t, c_linker_sym_t,
138 		    linker_symval_t *);
139 static int	link_elf_debug_symbol_values(linker_file_t, c_linker_sym_t,
140 		    linker_symval_t *);
141 static int	link_elf_search_symbol(linker_file_t, caddr_t value,
142 		    c_linker_sym_t *sym, long *diffp);
143 
144 static void	link_elf_unload_file(linker_file_t);
145 static int	link_elf_lookup_set(linker_file_t, const char *,
146 		    void ***, void ***, int *);
147 static int	link_elf_each_function_name(linker_file_t,
148 		    int (*)(const char *, void *), void *);
149 static int	link_elf_each_function_nameval(linker_file_t,
150 				linker_function_nameval_callback_t,
151 				void *);
152 static int	link_elf_reloc_local(linker_file_t, bool);
153 static long	link_elf_symtab_get(linker_file_t, const Elf_Sym **);
154 static long	link_elf_strtab_get(linker_file_t, caddr_t *);
155 #ifdef VIMAGE
156 static void	link_elf_propagate_vnets(linker_file_t);
157 #endif
158 
159 static int	elf_obj_lookup(linker_file_t lf, Elf_Size symidx, int deps,
160 		    Elf_Addr *);
161 
162 static kobj_method_t link_elf_methods[] = {
163 	KOBJMETHOD(linker_lookup_symbol,	link_elf_lookup_symbol),
164 	KOBJMETHOD(linker_lookup_debug_symbol,	link_elf_lookup_debug_symbol),
165 	KOBJMETHOD(linker_lookup_debug_symbol_ctf, link_elf_lookup_debug_symbol_ctf),
166 	KOBJMETHOD(linker_symbol_values,	link_elf_symbol_values),
167 	KOBJMETHOD(linker_debug_symbol_values,	link_elf_debug_symbol_values),
168 	KOBJMETHOD(linker_search_symbol,	link_elf_search_symbol),
169 	KOBJMETHOD(linker_unload,		link_elf_unload_file),
170 	KOBJMETHOD(linker_load_file,		link_elf_load_file),
171 	KOBJMETHOD(linker_link_preload,		link_elf_link_preload),
172 	KOBJMETHOD(linker_link_preload_finish,	link_elf_link_preload_finish),
173 	KOBJMETHOD(linker_lookup_set,		link_elf_lookup_set),
174 	KOBJMETHOD(linker_each_function_name,	link_elf_each_function_name),
175 	KOBJMETHOD(linker_each_function_nameval, link_elf_each_function_nameval),
176 	KOBJMETHOD(linker_ctf_get,		link_elf_ctf_get),
177 	KOBJMETHOD(linker_ctf_lookup_typename,  link_elf_ctf_lookup_typename),
178 	KOBJMETHOD(linker_symtab_get, 		link_elf_symtab_get),
179 	KOBJMETHOD(linker_strtab_get, 		link_elf_strtab_get),
180 #ifdef VIMAGE
181 	KOBJMETHOD(linker_propagate_vnets,	link_elf_propagate_vnets),
182 #endif
183 	KOBJMETHOD_END
184 };
185 
186 static struct linker_class link_elf_class = {
187 #if ELF_TARG_CLASS == ELFCLASS32
188 	"elf32_obj",
189 #else
190 	"elf64_obj",
191 #endif
192 	link_elf_methods, sizeof(struct elf_file)
193 };
194 
195 static bool link_elf_obj_leak_locals = true;
196 SYSCTL_BOOL(_debug, OID_AUTO, link_elf_obj_leak_locals,
197     CTLFLAG_RWTUN, &link_elf_obj_leak_locals, 0,
198     "Allow local symbols to participate in global module symbol resolution");
199 
200 static int	relocate_file(elf_file_t ef);
201 static void	elf_obj_cleanup_globals_cache(elf_file_t);
202 
203 static void
link_elf_error(const char * filename,const char * s)204 link_elf_error(const char *filename, const char *s)
205 {
206 	if (filename == NULL)
207 		printf("kldload: %s\n", s);
208 	else
209 		printf("kldload: %s: %s\n", filename, s);
210 }
211 
212 static void
link_elf_init(void * arg)213 link_elf_init(void *arg)
214 {
215 
216 	linker_add_class(&link_elf_class);
217 }
218 SYSINIT(link_elf_obj, SI_SUB_KLD, SI_ORDER_SECOND, link_elf_init, NULL);
219 
220 static void
link_elf_protect_range(elf_file_t ef,vm_offset_t start,vm_offset_t end,vm_prot_t prot)221 link_elf_protect_range(elf_file_t ef, vm_offset_t start, vm_offset_t end,
222     vm_prot_t prot)
223 {
224 	int error __unused;
225 
226 	KASSERT(start <= end && start >= (vm_offset_t)ef->address &&
227 	    end <= round_page((vm_offset_t)ef->address + ef->lf.size),
228 	    ("link_elf_protect_range: invalid range %#jx-%#jx",
229 	    (uintmax_t)start, (uintmax_t)end));
230 
231 	if (start == end)
232 		return;
233 	if (ef->preloaded) {
234 #ifdef __amd64__
235 		error = pmap_change_prot(start, end - start, prot);
236 		KASSERT(error == 0,
237 		    ("link_elf_protect_range: pmap_change_prot() returned %d",
238 		    error));
239 #endif
240 		return;
241 	}
242 	error = vm_map_protect(kernel_map, start, end, prot, 0,
243 	    VM_MAP_PROTECT_SET_PROT);
244 	KASSERT(error == KERN_SUCCESS,
245 	    ("link_elf_protect_range: vm_map_protect() returned %d", error));
246 }
247 
248 /*
249  * Restrict permissions on linker file memory based on section flags.
250  * Sections need not be page-aligned, so overlap within a page is possible.
251  */
252 static void
link_elf_protect(elf_file_t ef)253 link_elf_protect(elf_file_t ef)
254 {
255 	vm_offset_t end, segend, segstart, start;
256 	vm_prot_t gapprot, prot, segprot;
257 	int i;
258 
259 	/*
260 	 * If the file was preloaded, the last page may contain other preloaded
261 	 * data which may need to be writeable.  ELF files are always
262 	 * page-aligned, but other preloaded data, such as entropy or CPU
263 	 * microcode may be loaded with a smaller alignment.
264 	 */
265 	gapprot = ef->preloaded ? VM_PROT_RW : VM_PROT_READ;
266 
267 	start = end = (vm_offset_t)ef->address;
268 	prot = VM_PROT_READ;
269 	for (i = 0; i < ef->nprogtab; i++) {
270 		/*
271 		 * VNET and DPCPU sections have their memory allocated by their
272 		 * respective subsystems.
273 		 */
274 		if (ef->progtab[i].name != NULL && (
275 #ifdef VIMAGE
276 		    strcmp(ef->progtab[i].name, VNET_SETNAME) == 0 ||
277 #endif
278 		    strcmp(ef->progtab[i].name, DPCPU_SETNAME) == 0))
279 			continue;
280 
281 		segstart = trunc_page((vm_offset_t)ef->progtab[i].addr);
282 		segend = round_page((vm_offset_t)ef->progtab[i].addr +
283 		    ef->progtab[i].size);
284 		segprot = VM_PROT_READ;
285 		if ((ef->progtab[i].flags & SHF_WRITE) != 0)
286 			segprot |= VM_PROT_WRITE;
287 		if ((ef->progtab[i].flags & SHF_EXECINSTR) != 0)
288 			segprot |= VM_PROT_EXECUTE;
289 
290 		if (end <= segstart) {
291 			/*
292 			 * Case 1: there is no overlap between the previous
293 			 * segment and this one.  Apply protections to the
294 			 * previous segment, and protect the gap between the
295 			 * previous and current segments, if any.
296 			 */
297 			link_elf_protect_range(ef, start, end, prot);
298 			link_elf_protect_range(ef, end, segstart, gapprot);
299 
300 			start = segstart;
301 			end = segend;
302 			prot = segprot;
303 		} else if (start < segstart && end == segend) {
304 			/*
305 			 * Case 2: the current segment is a subrange of the
306 			 * previous segment.  Apply protections to the
307 			 * non-overlapping portion of the previous segment.
308 			 */
309 			link_elf_protect_range(ef, start, segstart, prot);
310 
311 			start = segstart;
312 			prot |= segprot;
313 		} else if (end < segend) {
314 			/*
315 			 * Case 3: there is partial overlap between the previous
316 			 * and current segments.  Apply protections to the
317 			 * non-overlapping portion of the previous segment, and
318 			 * then the overlap, which must use the union of the two
319 			 * segments' protections.
320 			 */
321 			link_elf_protect_range(ef, start, segstart, prot);
322 			link_elf_protect_range(ef, segstart, end,
323 			    prot | segprot);
324 			start = end;
325 			end = segend;
326 			prot = segprot;
327 		} else {
328 			/*
329 			 * Case 4: the two segments reside in the same page.
330 			 */
331 			prot |= segprot;
332 		}
333 	}
334 
335 	/*
336 	 * Fix up the last unprotected segment and trailing data.
337 	 */
338 	link_elf_protect_range(ef, start, end, prot);
339 	link_elf_protect_range(ef, end,
340 	    round_page((vm_offset_t)ef->address + ef->lf.size), gapprot);
341 }
342 
343 static int
link_elf_link_preload(linker_class_t cls,const char * filename,linker_file_t * result)344 link_elf_link_preload(linker_class_t cls, const char *filename,
345     linker_file_t *result)
346 {
347 	Elf_Ehdr *hdr;
348 	Elf_Shdr *shdr;
349 	Elf_Sym *es;
350 	void *modptr, *baseptr, *sizeptr;
351 	char *type;
352 	elf_file_t ef;
353 	linker_file_t lf;
354 	Elf_Addr off;
355 	int error, i, j, pb, ra, rl, shstrindex, symstrindex, symtabindex;
356 
357 	/* Look to see if we have the file preloaded */
358 	modptr = preload_search_by_name(filename);
359 	if (modptr == NULL)
360 		return ENOENT;
361 
362 	type = (char *)preload_search_info(modptr, MODINFO_TYPE);
363 	baseptr = preload_search_info(modptr, MODINFO_ADDR);
364 	sizeptr = preload_search_info(modptr, MODINFO_SIZE);
365 	hdr = (Elf_Ehdr *)preload_search_info(modptr, MODINFO_METADATA |
366 	    MODINFOMD_ELFHDR);
367 	shdr = (Elf_Shdr *)preload_search_info(modptr, MODINFO_METADATA |
368 	    MODINFOMD_SHDR);
369 	if (type == NULL || strcmp(type, preload_modtype_obj) != 0)
370 		return (EFTYPE);
371 	if (baseptr == NULL || sizeptr == NULL || hdr == NULL ||
372 	    shdr == NULL)
373 		return (EINVAL);
374 
375 	lf = linker_make_file(filename, &link_elf_class);
376 	if (lf == NULL)
377 		return (ENOMEM);
378 
379 	ef = (elf_file_t)lf;
380 	ef->preloaded = 1;
381 	ef->address = *(caddr_t *)baseptr;
382 	lf->address = *(caddr_t *)baseptr;
383 	lf->size = *(size_t *)sizeptr;
384 
385 	if (hdr->e_ident[EI_CLASS] != ELF_TARG_CLASS ||
386 	    hdr->e_ident[EI_DATA] != ELF_TARG_DATA ||
387 	    hdr->e_ident[EI_VERSION] != EV_CURRENT ||
388 	    hdr->e_version != EV_CURRENT ||
389 	    hdr->e_type != ET_REL ||
390 	    hdr->e_machine != ELF_TARG_MACH) {
391 		error = EFTYPE;
392 		goto out;
393 	}
394 	ef->e_shdr = shdr;
395 
396 	/* Scan the section header for information and table sizing. */
397 	symtabindex = -1;
398 	symstrindex = -1;
399 	for (i = 0; i < hdr->e_shnum; i++) {
400 		switch (shdr[i].sh_type) {
401 		case SHT_PROGBITS:
402 		case SHT_NOBITS:
403 #ifdef __amd64__
404 		case SHT_X86_64_UNWIND:
405 #endif
406 		case SHT_INIT_ARRAY:
407 		case SHT_FINI_ARRAY:
408 			/* Ignore sections not loaded by the loader. */
409 			if (shdr[i].sh_addr == 0)
410 				break;
411 			ef->nprogtab++;
412 			break;
413 		case SHT_SYMTAB:
414 			symtabindex = i;
415 			symstrindex = shdr[i].sh_link;
416 			break;
417 		case SHT_REL:
418 			/*
419 			 * Ignore relocation tables for sections not
420 			 * loaded by the loader.
421 			 */
422 			if (shdr[shdr[i].sh_info].sh_addr == 0)
423 				break;
424 			ef->nreltab++;
425 			break;
426 		case SHT_RELA:
427 			if (shdr[shdr[i].sh_info].sh_addr == 0)
428 				break;
429 			ef->nrelatab++;
430 			break;
431 		}
432 	}
433 
434 	shstrindex = hdr->e_shstrndx;
435 	if (ef->nprogtab == 0 || symstrindex < 0 ||
436 	    symstrindex >= hdr->e_shnum ||
437 	    shdr[symstrindex].sh_type != SHT_STRTAB || shstrindex == 0 ||
438 	    shstrindex >= hdr->e_shnum ||
439 	    shdr[shstrindex].sh_type != SHT_STRTAB) {
440 		printf("%s: bad/missing section headers\n", filename);
441 		error = ENOEXEC;
442 		goto out;
443 	}
444 
445 	/* Allocate space for tracking the load chunks */
446 	if (ef->nprogtab != 0)
447 		ef->progtab = malloc(ef->nprogtab * sizeof(*ef->progtab),
448 		    M_LINKER, M_WAITOK | M_ZERO);
449 	if (ef->nreltab != 0)
450 		ef->reltab = malloc(ef->nreltab * sizeof(*ef->reltab),
451 		    M_LINKER, M_WAITOK | M_ZERO);
452 	if (ef->nrelatab != 0)
453 		ef->relatab = malloc(ef->nrelatab * sizeof(*ef->relatab),
454 		    M_LINKER, M_WAITOK | M_ZERO);
455 	if ((ef->nprogtab != 0 && ef->progtab == NULL) ||
456 	    (ef->nreltab != 0 && ef->reltab == NULL) ||
457 	    (ef->nrelatab != 0 && ef->relatab == NULL)) {
458 		error = ENOMEM;
459 		goto out;
460 	}
461 
462 	/* XXX, relocate the sh_addr fields saved by the loader. */
463 	off = 0;
464 	for (i = 0; i < hdr->e_shnum; i++) {
465 		if (shdr[i].sh_addr != 0 && (off == 0 || shdr[i].sh_addr < off))
466 			off = shdr[i].sh_addr;
467 	}
468 	for (i = 0; i < hdr->e_shnum; i++) {
469 		if (shdr[i].sh_addr != 0)
470 			shdr[i].sh_addr = shdr[i].sh_addr - off +
471 			    (Elf_Addr)ef->address;
472 	}
473 
474 	ef->ddbsymcnt = shdr[symtabindex].sh_size / sizeof(Elf_Sym);
475 	ef->ddbsymtab = (Elf_Sym *)shdr[symtabindex].sh_addr;
476 	ef->ddbstrcnt = shdr[symstrindex].sh_size;
477 	ef->ddbstrtab = (char *)shdr[symstrindex].sh_addr;
478 	ef->shstrcnt = shdr[shstrindex].sh_size;
479 	ef->shstrtab = (char *)shdr[shstrindex].sh_addr;
480 
481 	/* Now fill out progtab and the relocation tables. */
482 	pb = 0;
483 	rl = 0;
484 	ra = 0;
485 	for (i = 0; i < hdr->e_shnum; i++) {
486 		switch (shdr[i].sh_type) {
487 		case SHT_PROGBITS:
488 		case SHT_NOBITS:
489 #ifdef __amd64__
490 		case SHT_X86_64_UNWIND:
491 #endif
492 		case SHT_INIT_ARRAY:
493 		case SHT_FINI_ARRAY:
494 			if (shdr[i].sh_addr == 0)
495 				break;
496 			ef->progtab[pb].addr = ef->progtab[pb].origaddr =
497 			    (void *)shdr[i].sh_addr;
498 			if (shdr[i].sh_type == SHT_PROGBITS)
499 				ef->progtab[pb].name = "<<PROGBITS>>";
500 #ifdef __amd64__
501 			else if (shdr[i].sh_type == SHT_X86_64_UNWIND)
502 				ef->progtab[pb].name = "<<UNWIND>>";
503 #endif
504 			else if (shdr[i].sh_type == SHT_INIT_ARRAY)
505 				ef->progtab[pb].name = "<<INIT_ARRAY>>";
506 			else if (shdr[i].sh_type == SHT_FINI_ARRAY)
507 				ef->progtab[pb].name = "<<FINI_ARRAY>>";
508 			else
509 				ef->progtab[pb].name = "<<NOBITS>>";
510 			ef->progtab[pb].size = shdr[i].sh_size;
511 			ef->progtab[pb].flags = shdr[i].sh_flags;
512 			ef->progtab[pb].sec = i;
513 			if (ef->shstrtab && shdr[i].sh_name != 0)
514 				ef->progtab[pb].name =
515 				    ef->shstrtab + shdr[i].sh_name;
516 			if (ef->progtab[pb].name != NULL &&
517 			    !strcmp(ef->progtab[pb].name, DPCPU_SETNAME)) {
518 				void *dpcpu;
519 
520 				dpcpu = dpcpu_alloc(shdr[i].sh_size);
521 				if (dpcpu == NULL) {
522 					printf("%s: pcpu module space is out "
523 					    "of space; cannot allocate %#jx "
524 					    "for %s\n", __func__,
525 					    (uintmax_t)shdr[i].sh_size,
526 					    filename);
527 					error = ENOSPC;
528 					goto out;
529 				}
530 				memcpy(dpcpu, ef->progtab[pb].addr,
531 				    ef->progtab[pb].size);
532 				dpcpu_copy(dpcpu, shdr[i].sh_size);
533 				ef->progtab[pb].addr = dpcpu;
534 #ifdef VIMAGE
535 			} else if (ef->progtab[pb].name != NULL &&
536 			    !strcmp(ef->progtab[pb].name, VNET_SETNAME)) {
537 				void *vnet_data;
538 
539 				vnet_data = vnet_data_alloc(shdr[i].sh_size);
540 				if (vnet_data == NULL) {
541 					printf("%s: vnet module space is out "
542 					    "of space; cannot allocate %#jx "
543 					    "for %s\n", __func__,
544 					    (uintmax_t)shdr[i].sh_size,
545 					    filename);
546 					error = ENOSPC;
547 					goto out;
548 				}
549 				memcpy(vnet_data, ef->progtab[pb].addr,
550 				    ef->progtab[pb].size);
551 				ef->progtab[pb].addr = vnet_data;
552 				vnet_save_init(ef->progtab[pb].addr,
553 				    ef->progtab[pb].size);
554 #endif
555 			} else if ((ef->progtab[pb].name != NULL &&
556 			    strcmp(ef->progtab[pb].name, ".ctors") == 0) ||
557 			    shdr[i].sh_type == SHT_INIT_ARRAY) {
558 				if (lf->ctors_addr != 0) {
559 					printf(
560 				    "%s: multiple ctor sections in %s\n",
561 					    __func__, filename);
562 				} else {
563 					lf->ctors_addr = ef->progtab[pb].addr;
564 					lf->ctors_size = shdr[i].sh_size;
565 				}
566 			} else if ((ef->progtab[pb].name != NULL &&
567 			    strcmp(ef->progtab[pb].name, ".dtors") == 0) ||
568 			    shdr[i].sh_type == SHT_FINI_ARRAY) {
569 				if (lf->dtors_addr != 0) {
570 					printf(
571 				    "%s: multiple dtor sections in %s\n",
572 					    __func__, filename);
573 				} else {
574 					lf->dtors_addr = ef->progtab[pb].addr;
575 					lf->dtors_size = shdr[i].sh_size;
576 				}
577 			}
578 
579 			/* Update all symbol values with the offset. */
580 			for (j = 0; j < ef->ddbsymcnt; j++) {
581 				es = &ef->ddbsymtab[j];
582 				if (es->st_shndx != i)
583 					continue;
584 				es->st_value += (Elf_Addr)ef->progtab[pb].addr;
585 			}
586 			pb++;
587 			break;
588 		case SHT_REL:
589 			if (shdr[shdr[i].sh_info].sh_addr == 0)
590 				break;
591 			ef->reltab[rl].rel = (Elf_Rel *)shdr[i].sh_addr;
592 			ef->reltab[rl].nrel = shdr[i].sh_size / sizeof(Elf_Rel);
593 			ef->reltab[rl].sec = shdr[i].sh_info;
594 			rl++;
595 			break;
596 		case SHT_RELA:
597 			if (shdr[shdr[i].sh_info].sh_addr == 0)
598 				break;
599 			ef->relatab[ra].rela = (Elf_Rela *)shdr[i].sh_addr;
600 			ef->relatab[ra].nrela =
601 			    shdr[i].sh_size / sizeof(Elf_Rela);
602 			ef->relatab[ra].sec = shdr[i].sh_info;
603 			ra++;
604 			break;
605 		}
606 	}
607 	if (pb != ef->nprogtab) {
608 		printf("%s: lost progbits\n", filename);
609 		error = ENOEXEC;
610 		goto out;
611 	}
612 	if (rl != ef->nreltab) {
613 		printf("%s: lost reltab\n", filename);
614 		error = ENOEXEC;
615 		goto out;
616 	}
617 	if (ra != ef->nrelatab) {
618 		printf("%s: lost relatab\n", filename);
619 		error = ENOEXEC;
620 		goto out;
621 	}
622 
623 	/*
624 	 * The file needs to be writeable and executable while applying
625 	 * relocations.  Mapping protections are applied once relocation
626 	 * processing is complete.
627 	 */
628 	link_elf_protect_range(ef, (vm_offset_t)ef->address,
629 	    round_page((vm_offset_t)ef->address + ef->lf.size), VM_PROT_ALL);
630 
631 	/* Local intra-module relocations */
632 	error = link_elf_reloc_local(lf, false);
633 	if (error != 0)
634 		goto out;
635 	*result = lf;
636 	return (0);
637 
638 out:
639 	/* preload not done this way */
640 	linker_file_unload(lf, LINKER_UNLOAD_FORCE);
641 	return (error);
642 }
643 
644 static void
link_elf_invoke_cbs(caddr_t addr,size_t size)645 link_elf_invoke_cbs(caddr_t addr, size_t size)
646 {
647 	void (**ctor)(void);
648 	size_t i, cnt;
649 
650 	if (addr == NULL || size == 0)
651 		return;
652 	cnt = size / sizeof(*ctor);
653 	ctor = (void *)addr;
654 	for (i = 0; i < cnt; i++) {
655 		if (ctor[i] != NULL)
656 			(*ctor[i])();
657 	}
658 }
659 
660 static void
link_elf_invoke_ctors(linker_file_t lf)661 link_elf_invoke_ctors(linker_file_t lf)
662 {
663 	KASSERT(lf->ctors_invoked == LF_NONE,
664 	    ("%s: file %s ctor state %d",
665 	    __func__, lf->filename, lf->ctors_invoked));
666 
667 	link_elf_invoke_cbs(lf->ctors_addr, lf->ctors_size);
668 	lf->ctors_invoked = LF_CTORS;
669 }
670 
671 static void
link_elf_invoke_dtors(linker_file_t lf)672 link_elf_invoke_dtors(linker_file_t lf)
673 {
674 	KASSERT(lf->ctors_invoked != LF_DTORS,
675 	    ("%s: file %s ctor state %d",
676 	    __func__, lf->filename, lf->ctors_invoked));
677 
678 	if (lf->ctors_invoked == LF_CTORS) {
679 		link_elf_invoke_cbs(lf->dtors_addr, lf->dtors_size);
680 		lf->ctors_invoked = LF_DTORS;
681 	}
682 }
683 
684 static int
link_elf_link_preload_finish(linker_file_t lf)685 link_elf_link_preload_finish(linker_file_t lf)
686 {
687 	elf_file_t ef;
688 	int error;
689 
690 	ef = (elf_file_t)lf;
691 	error = relocate_file(ef);
692 	if (error)
693 		return (error);
694 
695 	/* Notify MD code that a module is being loaded. */
696 	error = elf_cpu_load_file(lf);
697 	if (error)
698 		return (error);
699 
700 #if defined(__i386__) || defined(__amd64__)
701 	/* Now ifuncs. */
702 	error = link_elf_reloc_local(lf, true);
703 	if (error != 0)
704 		return (error);
705 #endif
706 
707 	/* Apply protections now that relocation processing is complete. */
708 	link_elf_protect(ef);
709 
710 	link_elf_invoke_ctors(lf);
711 	return (0);
712 }
713 
714 static int
link_elf_load_file(linker_class_t cls,const char * filename,linker_file_t * result)715 link_elf_load_file(linker_class_t cls, const char *filename,
716     linker_file_t *result)
717 {
718 	struct nameidata *nd;
719 	struct thread *td = curthread;	/* XXX */
720 	Elf_Ehdr *hdr;
721 	Elf_Shdr *shdr;
722 	Elf_Sym *es;
723 	int nbytes, i, j;
724 	vm_offset_t mapbase;
725 	size_t mapsize;
726 	int error = 0;
727 	ssize_t resid;
728 	int flags;
729 	elf_file_t ef;
730 	linker_file_t lf;
731 	int symtabindex;
732 	int symstrindex;
733 	int shstrindex;
734 	int nsym;
735 	int pb, rl, ra;
736 	int alignmask;
737 
738 	shdr = NULL;
739 	lf = NULL;
740 	mapsize = 0;
741 	hdr = NULL;
742 
743 	nd = malloc(sizeof(struct nameidata), M_TEMP, M_WAITOK);
744 	NDINIT(nd, LOOKUP, FOLLOW, UIO_SYSSPACE, filename);
745 	flags = FREAD;
746 	error = vn_open(nd, &flags, 0, NULL);
747 	if (error) {
748 		free(nd, M_TEMP);
749 		return error;
750 	}
751 	NDFREE_PNBUF(nd);
752 	if (nd->ni_vp->v_type != VREG) {
753 		error = ENOEXEC;
754 		goto out;
755 	}
756 #ifdef MAC
757 	error = mac_kld_check_load(td->td_ucred, nd->ni_vp);
758 	if (error) {
759 		goto out;
760 	}
761 #endif
762 
763 	/* Read the elf header from the file. */
764 	hdr = malloc(sizeof(*hdr), M_LINKER, M_WAITOK);
765 	error = vn_rdwr(UIO_READ, nd->ni_vp, (void *)hdr, sizeof(*hdr), 0,
766 	    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred, NOCRED,
767 	    &resid, td);
768 	if (error)
769 		goto out;
770 	if (resid != 0){
771 		error = ENOEXEC;
772 		goto out;
773 	}
774 
775 	if (!IS_ELF(*hdr)) {
776 		error = ENOEXEC;
777 		goto out;
778 	}
779 
780 	if (hdr->e_ident[EI_CLASS] != ELF_TARG_CLASS
781 	    || hdr->e_ident[EI_DATA] != ELF_TARG_DATA) {
782 		link_elf_error(filename, "Unsupported file layout");
783 		error = ENOEXEC;
784 		goto out;
785 	}
786 	if (hdr->e_ident[EI_VERSION] != EV_CURRENT
787 	    || hdr->e_version != EV_CURRENT) {
788 		link_elf_error(filename, "Unsupported file version");
789 		error = ENOEXEC;
790 		goto out;
791 	}
792 	if (hdr->e_type != ET_REL) {
793 		error = ENOSYS;
794 		goto out;
795 	}
796 	if (hdr->e_machine != ELF_TARG_MACH) {
797 		link_elf_error(filename, "Unsupported machine");
798 		error = ENOEXEC;
799 		goto out;
800 	}
801 
802 	lf = linker_make_file(filename, &link_elf_class);
803 	if (!lf) {
804 		error = ENOMEM;
805 		goto out;
806 	}
807 	ef = (elf_file_t) lf;
808 	ef->nprogtab = 0;
809 	ef->e_shdr = 0;
810 	ef->nreltab = 0;
811 	ef->nrelatab = 0;
812 
813 	/* Allocate and read in the section header */
814 	nbytes = hdr->e_shnum * hdr->e_shentsize;
815 	if (nbytes == 0 || hdr->e_shoff == 0 ||
816 	    hdr->e_shentsize != sizeof(Elf_Shdr)) {
817 		error = ENOEXEC;
818 		goto out;
819 	}
820 	shdr = malloc(nbytes, M_LINKER, M_WAITOK);
821 	ef->e_shdr = shdr;
822 	error = vn_rdwr(UIO_READ, nd->ni_vp, (caddr_t)shdr, nbytes,
823 	    hdr->e_shoff, UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred,
824 	    NOCRED, &resid, td);
825 	if (error)
826 		goto out;
827 	if (resid) {
828 		error = ENOEXEC;
829 		goto out;
830 	}
831 
832 	/* Scan the section header for information and table sizing. */
833 	nsym = 0;
834 	symtabindex = -1;
835 	symstrindex = -1;
836 	for (i = 0; i < hdr->e_shnum; i++) {
837 		if (shdr[i].sh_size == 0)
838 			continue;
839 		switch (shdr[i].sh_type) {
840 		case SHT_PROGBITS:
841 		case SHT_NOBITS:
842 #ifdef __amd64__
843 		case SHT_X86_64_UNWIND:
844 #endif
845 		case SHT_INIT_ARRAY:
846 		case SHT_FINI_ARRAY:
847 			if ((shdr[i].sh_flags & SHF_ALLOC) == 0)
848 				break;
849 			ef->nprogtab++;
850 			break;
851 		case SHT_SYMTAB:
852 			nsym++;
853 			symtabindex = i;
854 			symstrindex = shdr[i].sh_link;
855 			break;
856 		case SHT_REL:
857 			/*
858 			 * Ignore relocation tables for unallocated
859 			 * sections.
860 			 */
861 			if ((shdr[shdr[i].sh_info].sh_flags & SHF_ALLOC) == 0)
862 				break;
863 			ef->nreltab++;
864 			break;
865 		case SHT_RELA:
866 			if ((shdr[shdr[i].sh_info].sh_flags & SHF_ALLOC) == 0)
867 				break;
868 			ef->nrelatab++;
869 			break;
870 		case SHT_STRTAB:
871 			break;
872 		}
873 	}
874 	if (ef->nprogtab == 0) {
875 		link_elf_error(filename, "file has no contents");
876 		error = ENOEXEC;
877 		goto out;
878 	}
879 	if (nsym != 1) {
880 		/* Only allow one symbol table for now */
881 		link_elf_error(filename,
882 		    "file must have exactly one symbol table");
883 		error = ENOEXEC;
884 		goto out;
885 	}
886 	if (symstrindex < 0 || symstrindex > hdr->e_shnum ||
887 	    shdr[symstrindex].sh_type != SHT_STRTAB) {
888 		link_elf_error(filename, "file has invalid symbol strings");
889 		error = ENOEXEC;
890 		goto out;
891 	}
892 
893 	/* Allocate space for tracking the load chunks */
894 	if (ef->nprogtab != 0)
895 		ef->progtab = malloc(ef->nprogtab * sizeof(*ef->progtab),
896 		    M_LINKER, M_WAITOK | M_ZERO);
897 	if (ef->nreltab != 0)
898 		ef->reltab = malloc(ef->nreltab * sizeof(*ef->reltab),
899 		    M_LINKER, M_WAITOK | M_ZERO);
900 	if (ef->nrelatab != 0)
901 		ef->relatab = malloc(ef->nrelatab * sizeof(*ef->relatab),
902 		    M_LINKER, M_WAITOK | M_ZERO);
903 
904 	if (symtabindex == -1) {
905 		link_elf_error(filename, "lost symbol table index");
906 		error = ENOEXEC;
907 		goto out;
908 	}
909 	/* Allocate space for and load the symbol table */
910 	ef->ddbsymcnt = shdr[symtabindex].sh_size / sizeof(Elf_Sym);
911 	ef->ddbsymtab = malloc(shdr[symtabindex].sh_size, M_LINKER, M_WAITOK);
912 	error = vn_rdwr(UIO_READ, nd->ni_vp, (void *)ef->ddbsymtab,
913 	    shdr[symtabindex].sh_size, shdr[symtabindex].sh_offset,
914 	    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred, NOCRED,
915 	    &resid, td);
916 	if (error)
917 		goto out;
918 	if (resid != 0){
919 		error = EINVAL;
920 		goto out;
921 	}
922 
923 	/* Allocate space for and load the symbol strings */
924 	ef->ddbstrcnt = shdr[symstrindex].sh_size;
925 	ef->ddbstrtab = malloc(shdr[symstrindex].sh_size, M_LINKER, M_WAITOK);
926 	error = vn_rdwr(UIO_READ, nd->ni_vp, ef->ddbstrtab,
927 	    shdr[symstrindex].sh_size, shdr[symstrindex].sh_offset,
928 	    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred, NOCRED,
929 	    &resid, td);
930 	if (error)
931 		goto out;
932 	if (resid != 0){
933 		error = EINVAL;
934 		goto out;
935 	}
936 
937 	/* Do we have a string table for the section names?  */
938 	shstrindex = -1;
939 	if (hdr->e_shstrndx != 0 &&
940 	    shdr[hdr->e_shstrndx].sh_type == SHT_STRTAB) {
941 		shstrindex = hdr->e_shstrndx;
942 		ef->shstrcnt = shdr[shstrindex].sh_size;
943 		ef->shstrtab = malloc(shdr[shstrindex].sh_size, M_LINKER,
944 		    M_WAITOK);
945 		error = vn_rdwr(UIO_READ, nd->ni_vp, ef->shstrtab,
946 		    shdr[shstrindex].sh_size, shdr[shstrindex].sh_offset,
947 		    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred, NOCRED,
948 		    &resid, td);
949 		if (error)
950 			goto out;
951 		if (resid != 0){
952 			error = EINVAL;
953 			goto out;
954 		}
955 	}
956 
957 	/* Size up code/data(progbits) and bss(nobits). */
958 	alignmask = 0;
959 	for (i = 0; i < hdr->e_shnum; i++) {
960 		if (shdr[i].sh_size == 0)
961 			continue;
962 		switch (shdr[i].sh_type) {
963 		case SHT_PROGBITS:
964 		case SHT_NOBITS:
965 #ifdef __amd64__
966 		case SHT_X86_64_UNWIND:
967 #endif
968 		case SHT_INIT_ARRAY:
969 		case SHT_FINI_ARRAY:
970 			if ((shdr[i].sh_flags & SHF_ALLOC) == 0)
971 				break;
972 			alignmask = shdr[i].sh_addralign - 1;
973 			mapsize += alignmask;
974 			mapsize &= ~alignmask;
975 			mapsize += shdr[i].sh_size;
976 			break;
977 		}
978 	}
979 
980 	/*
981 	 * We know how much space we need for the text/data/bss/etc.
982 	 * This stuff needs to be in a single chunk so that profiling etc
983 	 * can get the bounds and gdb can associate offsets with modules
984 	 */
985 	ef->object = vm_pager_allocate(OBJT_PHYS, NULL, round_page(mapsize),
986 	    VM_PROT_ALL, 0, thread0.td_ucred);
987 	if (ef->object == NULL) {
988 		error = ENOMEM;
989 		goto out;
990 	}
991 #if VM_NRESERVLEVEL > 0
992 	vm_object_color(ef->object, 0);
993 #endif
994 
995 	/*
996 	 * In order to satisfy amd64's architectural requirements on the
997 	 * location of code and data in the kernel's address space, request a
998 	 * mapping that is above the kernel.
999 	 *
1000 	 * Protections will be restricted once relocations are applied.
1001 	 */
1002 #ifdef __amd64__
1003 	mapbase = KERNBASE;
1004 #else
1005 	mapbase = VM_MIN_KERNEL_ADDRESS;
1006 #endif
1007 	error = vm_map_find(kernel_map, ef->object, 0, &mapbase,
1008 	    round_page(mapsize), 0, VMFS_OPTIMAL_SPACE, VM_PROT_ALL,
1009 	    VM_PROT_ALL, 0);
1010 	if (error != KERN_SUCCESS) {
1011 		vm_object_deallocate(ef->object);
1012 		ef->object = NULL;
1013 		error = ENOMEM;
1014 		goto out;
1015 	}
1016 
1017 	/* Wire the pages */
1018 	error = vm_map_wire(kernel_map, mapbase,
1019 	    mapbase + round_page(mapsize),
1020 	    VM_MAP_WIRE_SYSTEM|VM_MAP_WIRE_NOHOLES);
1021 	if (error != KERN_SUCCESS) {
1022 		error = ENOMEM;
1023 		goto out;
1024 	}
1025 
1026 	/* Inform the kld system about the situation */
1027 	lf->address = ef->address = (caddr_t)mapbase;
1028 	lf->size = mapsize;
1029 
1030 	/*
1031 	 * Now load code/data(progbits), zero bss(nobits), allocate space for
1032 	 * and load relocs
1033 	 */
1034 	pb = 0;
1035 	rl = 0;
1036 	ra = 0;
1037 	alignmask = 0;
1038 	for (i = 0; i < hdr->e_shnum; i++) {
1039 		if (shdr[i].sh_size == 0)
1040 			continue;
1041 		switch (shdr[i].sh_type) {
1042 		case SHT_PROGBITS:
1043 		case SHT_NOBITS:
1044 #ifdef __amd64__
1045 		case SHT_X86_64_UNWIND:
1046 #endif
1047 		case SHT_INIT_ARRAY:
1048 		case SHT_FINI_ARRAY:
1049 			if ((shdr[i].sh_flags & SHF_ALLOC) == 0)
1050 				break;
1051 			alignmask = shdr[i].sh_addralign - 1;
1052 			mapbase += alignmask;
1053 			mapbase &= ~alignmask;
1054 			if (ef->shstrtab != NULL && shdr[i].sh_name != 0) {
1055 				ef->progtab[pb].name =
1056 				    ef->shstrtab + shdr[i].sh_name;
1057 				if (!strcmp(ef->progtab[pb].name, ".ctors") ||
1058 				    shdr[i].sh_type == SHT_INIT_ARRAY) {
1059 					if (lf->ctors_addr != 0) {
1060 						printf(
1061 				    "%s: multiple ctor sections in %s\n",
1062 						    __func__, filename);
1063 					} else {
1064 						lf->ctors_addr =
1065 						    (caddr_t)mapbase;
1066 						lf->ctors_size =
1067 						    shdr[i].sh_size;
1068 					}
1069 				} else if (!strcmp(ef->progtab[pb].name,
1070 				    ".dtors") ||
1071 				    shdr[i].sh_type == SHT_FINI_ARRAY) {
1072 					if (lf->dtors_addr != 0) {
1073 						printf(
1074 				    "%s: multiple dtor sections in %s\n",
1075 						    __func__, filename);
1076 					} else {
1077 						lf->dtors_addr =
1078 						    (caddr_t)mapbase;
1079 						lf->dtors_size =
1080 						    shdr[i].sh_size;
1081 					}
1082 				}
1083 			} else if (shdr[i].sh_type == SHT_PROGBITS)
1084 				ef->progtab[pb].name = "<<PROGBITS>>";
1085 #ifdef __amd64__
1086 			else if (shdr[i].sh_type == SHT_X86_64_UNWIND)
1087 				ef->progtab[pb].name = "<<UNWIND>>";
1088 #endif
1089 			else
1090 				ef->progtab[pb].name = "<<NOBITS>>";
1091 			if (ef->progtab[pb].name != NULL &&
1092 			    !strcmp(ef->progtab[pb].name, DPCPU_SETNAME)) {
1093 				ef->progtab[pb].origaddr =
1094 				    (void *)(uintptr_t)mapbase;
1095 				ef->progtab[pb].addr =
1096 				    dpcpu_alloc(shdr[i].sh_size);
1097 				if (ef->progtab[pb].addr == NULL) {
1098 					printf("%s: pcpu module space is out "
1099 					    "of space; cannot allocate %#jx "
1100 					    "for %s\n", __func__,
1101 					    (uintmax_t)shdr[i].sh_size,
1102 					    filename);
1103 				}
1104 			}
1105 #ifdef VIMAGE
1106 			else if (ef->progtab[pb].name != NULL &&
1107 			    !strcmp(ef->progtab[pb].name, VNET_SETNAME)) {
1108 				ef->progtab[pb].origaddr =
1109 				    (void *)(uintptr_t)mapbase;
1110 				ef->progtab[pb].addr =
1111 				    vnet_data_alloc(shdr[i].sh_size);
1112 				if (ef->progtab[pb].addr == NULL) {
1113 					printf("%s: vnet module space is out "
1114 					    "of space; cannot allocate %#jx "
1115 					    "for %s\n", __func__,
1116 					    (uintmax_t)shdr[i].sh_size,
1117 					    filename);
1118 				}
1119 			}
1120 #endif
1121 			else
1122 				ef->progtab[pb].addr =
1123 				    (void *)(uintptr_t)mapbase;
1124 			if (ef->progtab[pb].addr == NULL) {
1125 				error = ENOSPC;
1126 				goto out;
1127 			}
1128 			ef->progtab[pb].size = shdr[i].sh_size;
1129 			ef->progtab[pb].flags = shdr[i].sh_flags;
1130 			ef->progtab[pb].sec = i;
1131 			if (shdr[i].sh_type == SHT_PROGBITS
1132 #ifdef __amd64__
1133 			    || shdr[i].sh_type == SHT_X86_64_UNWIND
1134 #endif
1135 			    ) {
1136 				error = vn_rdwr(UIO_READ, nd->ni_vp,
1137 				    ef->progtab[pb].addr,
1138 				    shdr[i].sh_size, shdr[i].sh_offset,
1139 				    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred,
1140 				    NOCRED, &resid, td);
1141 				if (error)
1142 					goto out;
1143 				if (resid != 0){
1144 					error = EINVAL;
1145 					goto out;
1146 				}
1147 				/* Initialize the per-cpu area. */
1148 				if (ef->progtab[pb].addr != (void *)mapbase &&
1149 				    !strcmp(ef->progtab[pb].name, DPCPU_SETNAME))
1150 					dpcpu_copy(ef->progtab[pb].addr,
1151 					    shdr[i].sh_size);
1152 			} else
1153 				bzero(ef->progtab[pb].addr, shdr[i].sh_size);
1154 
1155 #ifdef VIMAGE
1156 			if (ef->progtab[pb].addr != (void *)mapbase &&
1157 			    strcmp(ef->progtab[pb].name, VNET_SETNAME) == 0)
1158 				vnet_save_init(ef->progtab[pb].addr,
1159 				    ef->progtab[pb].size);
1160 #endif
1161 			/* Update all symbol values with the offset. */
1162 			for (j = 0; j < ef->ddbsymcnt; j++) {
1163 				es = &ef->ddbsymtab[j];
1164 				if (es->st_shndx != i)
1165 					continue;
1166 				es->st_value += (Elf_Addr)ef->progtab[pb].addr;
1167 			}
1168 			mapbase += shdr[i].sh_size;
1169 			pb++;
1170 			break;
1171 		case SHT_REL:
1172 			if ((shdr[shdr[i].sh_info].sh_flags & SHF_ALLOC) == 0)
1173 				break;
1174 			ef->reltab[rl].rel = malloc(shdr[i].sh_size, M_LINKER,
1175 			    M_WAITOK);
1176 			ef->reltab[rl].nrel = shdr[i].sh_size / sizeof(Elf_Rel);
1177 			ef->reltab[rl].sec = shdr[i].sh_info;
1178 			error = vn_rdwr(UIO_READ, nd->ni_vp,
1179 			    (void *)ef->reltab[rl].rel,
1180 			    shdr[i].sh_size, shdr[i].sh_offset,
1181 			    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred, NOCRED,
1182 			    &resid, td);
1183 			if (error)
1184 				goto out;
1185 			if (resid != 0){
1186 				error = EINVAL;
1187 				goto out;
1188 			}
1189 			rl++;
1190 			break;
1191 		case SHT_RELA:
1192 			if ((shdr[shdr[i].sh_info].sh_flags & SHF_ALLOC) == 0)
1193 				break;
1194 			ef->relatab[ra].rela = malloc(shdr[i].sh_size, M_LINKER,
1195 			    M_WAITOK);
1196 			ef->relatab[ra].nrela =
1197 			    shdr[i].sh_size / sizeof(Elf_Rela);
1198 			ef->relatab[ra].sec = shdr[i].sh_info;
1199 			error = vn_rdwr(UIO_READ, nd->ni_vp,
1200 			    (void *)ef->relatab[ra].rela,
1201 			    shdr[i].sh_size, shdr[i].sh_offset,
1202 			    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred, NOCRED,
1203 			    &resid, td);
1204 			if (error)
1205 				goto out;
1206 			if (resid != 0){
1207 				error = EINVAL;
1208 				goto out;
1209 			}
1210 			ra++;
1211 			break;
1212 		}
1213 	}
1214 	if (pb != ef->nprogtab) {
1215 		link_elf_error(filename, "lost progbits");
1216 		error = ENOEXEC;
1217 		goto out;
1218 	}
1219 	if (rl != ef->nreltab) {
1220 		link_elf_error(filename, "lost reltab");
1221 		error = ENOEXEC;
1222 		goto out;
1223 	}
1224 	if (ra != ef->nrelatab) {
1225 		link_elf_error(filename, "lost relatab");
1226 		error = ENOEXEC;
1227 		goto out;
1228 	}
1229 	if (mapbase != (vm_offset_t)ef->address + mapsize) {
1230 		printf(
1231 		    "%s: mapbase 0x%lx != address %p + mapsize 0x%lx (0x%lx)\n",
1232 		    filename != NULL ? filename : "<none>",
1233 		    (u_long)mapbase, ef->address, (u_long)mapsize,
1234 		    (u_long)(vm_offset_t)ef->address + mapsize);
1235 		error = ENOMEM;
1236 		goto out;
1237 	}
1238 
1239 	/* Local intra-module relocations */
1240 	error = link_elf_reloc_local(lf, false);
1241 	if (error != 0)
1242 		goto out;
1243 
1244 	/* Pull in dependencies */
1245 	VOP_UNLOCK(nd->ni_vp);
1246 	error = linker_load_dependencies(lf);
1247 	vn_lock(nd->ni_vp, LK_EXCLUSIVE | LK_RETRY);
1248 	if (error)
1249 		goto out;
1250 
1251 	/* External relocations */
1252 	error = relocate_file(ef);
1253 	if (error)
1254 		goto out;
1255 
1256 	/* Notify MD code that a module is being loaded. */
1257 	error = elf_cpu_load_file(lf);
1258 	if (error)
1259 		goto out;
1260 
1261 #if defined(__i386__) || defined(__amd64__)
1262 	/* Now ifuncs. */
1263 	error = link_elf_reloc_local(lf, true);
1264 	if (error != 0)
1265 		goto out;
1266 #endif
1267 
1268 	link_elf_protect(ef);
1269 	link_elf_invoke_ctors(lf);
1270 	*result = lf;
1271 
1272 out:
1273 	VOP_UNLOCK(nd->ni_vp);
1274 	vn_close(nd->ni_vp, FREAD, td->td_ucred, td);
1275 	free(nd, M_TEMP);
1276 	if (error && lf)
1277 		linker_file_unload(lf, LINKER_UNLOAD_FORCE);
1278 	free(hdr, M_LINKER);
1279 
1280 	return error;
1281 }
1282 
1283 static void
link_elf_unload_file(linker_file_t file)1284 link_elf_unload_file(linker_file_t file)
1285 {
1286 	elf_file_t ef = (elf_file_t) file;
1287 	u_int i;
1288 
1289 	link_elf_invoke_dtors(file);
1290 
1291 	/* Notify MD code that a module is being unloaded. */
1292 	elf_cpu_unload_file(file);
1293 
1294 	if (ef->progtab) {
1295 		for (i = 0; i < ef->nprogtab; i++) {
1296 			if (ef->progtab[i].size == 0)
1297 				continue;
1298 			if (ef->progtab[i].name == NULL)
1299 				continue;
1300 			if (!strcmp(ef->progtab[i].name, DPCPU_SETNAME))
1301 				dpcpu_free(ef->progtab[i].addr,
1302 				    ef->progtab[i].size);
1303 #ifdef VIMAGE
1304 			else if (!strcmp(ef->progtab[i].name, VNET_SETNAME))
1305 				vnet_data_free(ef->progtab[i].addr,
1306 				    ef->progtab[i].size);
1307 #endif
1308 		}
1309 	}
1310 	if (ef->preloaded) {
1311 		free(ef->reltab, M_LINKER);
1312 		free(ef->relatab, M_LINKER);
1313 		free(ef->progtab, M_LINKER);
1314 		free(ef->ctftab, M_LINKER);
1315 		free(ef->ctfoff, M_LINKER);
1316 		free(ef->typoff, M_LINKER);
1317 		if (file->pathname != NULL)
1318 			preload_delete_name(file->pathname);
1319 		return;
1320 	}
1321 
1322 	for (i = 0; i < ef->nreltab; i++)
1323 		free(ef->reltab[i].rel, M_LINKER);
1324 	for (i = 0; i < ef->nrelatab; i++)
1325 		free(ef->relatab[i].rela, M_LINKER);
1326 	free(ef->reltab, M_LINKER);
1327 	free(ef->relatab, M_LINKER);
1328 	free(ef->progtab, M_LINKER);
1329 
1330 	if (ef->object != NULL)
1331 		vm_map_remove(kernel_map, (vm_offset_t)ef->address,
1332 		    (vm_offset_t)ef->address + ptoa(ef->object->size));
1333 	free(ef->e_shdr, M_LINKER);
1334 	free(ef->ddbsymtab, M_LINKER);
1335 	free(ef->ddbstrtab, M_LINKER);
1336 	free(ef->shstrtab, M_LINKER);
1337 	free(ef->ctftab, M_LINKER);
1338 	free(ef->ctfoff, M_LINKER);
1339 	free(ef->typoff, M_LINKER);
1340 }
1341 
1342 static const char *
symbol_name(elf_file_t ef,Elf_Size r_info)1343 symbol_name(elf_file_t ef, Elf_Size r_info)
1344 {
1345 	const Elf_Sym *ref;
1346 
1347 	if (ELF_R_SYM(r_info)) {
1348 		ref = ef->ddbsymtab + ELF_R_SYM(r_info);
1349 		return ef->ddbstrtab + ref->st_name;
1350 	} else
1351 		return NULL;
1352 }
1353 
1354 static Elf_Addr
findbase(elf_file_t ef,int sec)1355 findbase(elf_file_t ef, int sec)
1356 {
1357 	int i;
1358 	Elf_Addr base = 0;
1359 
1360 	for (i = 0; i < ef->nprogtab; i++) {
1361 		if (sec == ef->progtab[i].sec) {
1362 			base = (Elf_Addr)ef->progtab[i].addr;
1363 			break;
1364 		}
1365 	}
1366 	return base;
1367 }
1368 
1369 static int
relocate_file1(elf_file_t ef,bool ifuncs)1370 relocate_file1(elf_file_t ef, bool ifuncs)
1371 {
1372 	const Elf_Rel *rellim;
1373 	const Elf_Rel *rel;
1374 	const Elf_Rela *relalim;
1375 	const Elf_Rela *rela;
1376 	const char *symname;
1377 	const Elf_Sym *sym;
1378 	int i;
1379 	Elf_Size symidx;
1380 	Elf_Addr base;
1381 
1382 	/* Perform relocations without addend if there are any: */
1383 	for (i = 0; i < ef->nreltab; i++) {
1384 		rel = ef->reltab[i].rel;
1385 		if (rel == NULL) {
1386 			link_elf_error(ef->lf.filename, "lost a reltab!");
1387 			return (ENOEXEC);
1388 		}
1389 		rellim = rel + ef->reltab[i].nrel;
1390 		base = findbase(ef, ef->reltab[i].sec);
1391 		if (base == 0) {
1392 			link_elf_error(ef->lf.filename, "lost base for reltab");
1393 			return (ENOEXEC);
1394 		}
1395 		for ( ; rel < rellim; rel++) {
1396 			symidx = ELF_R_SYM(rel->r_info);
1397 			if (symidx >= ef->ddbsymcnt)
1398 				continue;
1399 			sym = ef->ddbsymtab + symidx;
1400 			/* Local relocs are already done */
1401 			if (ELF_ST_BIND(sym->st_info) == STB_LOCAL)
1402 				continue;
1403 			if ((ELF_ST_TYPE(sym->st_info) == STT_GNU_IFUNC ||
1404 			    elf_is_ifunc_reloc(rel->r_info)) != ifuncs)
1405 				continue;
1406 			if (elf_reloc(&ef->lf, base, rel, ELF_RELOC_REL,
1407 			    elf_obj_lookup)) {
1408 				symname = symbol_name(ef, rel->r_info);
1409 				printf("link_elf_obj: symbol %s undefined\n",
1410 				    symname);
1411 				return (ENOENT);
1412 			}
1413 		}
1414 	}
1415 
1416 	/* Perform relocations with addend if there are any: */
1417 	for (i = 0; i < ef->nrelatab; i++) {
1418 		rela = ef->relatab[i].rela;
1419 		if (rela == NULL) {
1420 			link_elf_error(ef->lf.filename, "lost a relatab!");
1421 			return (ENOEXEC);
1422 		}
1423 		relalim = rela + ef->relatab[i].nrela;
1424 		base = findbase(ef, ef->relatab[i].sec);
1425 		if (base == 0) {
1426 			link_elf_error(ef->lf.filename,
1427 			    "lost base for relatab");
1428 			return (ENOEXEC);
1429 		}
1430 		for ( ; rela < relalim; rela++) {
1431 			symidx = ELF_R_SYM(rela->r_info);
1432 			if (symidx >= ef->ddbsymcnt)
1433 				continue;
1434 			sym = ef->ddbsymtab + symidx;
1435 			/* Local relocs are already done */
1436 			if (ELF_ST_BIND(sym->st_info) == STB_LOCAL)
1437 				continue;
1438 			if ((ELF_ST_TYPE(sym->st_info) == STT_GNU_IFUNC ||
1439 			    elf_is_ifunc_reloc(rela->r_info)) != ifuncs)
1440 				continue;
1441 			if (elf_reloc(&ef->lf, base, rela, ELF_RELOC_RELA,
1442 			    elf_obj_lookup)) {
1443 				symname = symbol_name(ef, rela->r_info);
1444 				printf("link_elf_obj: symbol %s undefined\n",
1445 				    symname);
1446 				return (ENOENT);
1447 			}
1448 		}
1449 	}
1450 
1451 	/*
1452 	 * Only clean SHN_FBSD_CACHED for successful return.  If we
1453 	 * modified symbol table for the object but found an
1454 	 * unresolved symbol, there is no reason to roll back.
1455 	 */
1456 	elf_obj_cleanup_globals_cache(ef);
1457 
1458 	return (0);
1459 }
1460 
1461 static int
relocate_file(elf_file_t ef)1462 relocate_file(elf_file_t ef)
1463 {
1464 	int error;
1465 
1466 	error = relocate_file1(ef, false);
1467 	if (error == 0)
1468 		error = relocate_file1(ef, true);
1469 	return (error);
1470 }
1471 
1472 static int
link_elf_lookup_symbol1(linker_file_t lf,const char * name,c_linker_sym_t * sym,bool see_local)1473 link_elf_lookup_symbol1(linker_file_t lf, const char *name, c_linker_sym_t *sym,
1474     bool see_local)
1475 {
1476 	elf_file_t ef = (elf_file_t)lf;
1477 	const Elf_Sym *symp;
1478 	const char *strp;
1479 	int i;
1480 
1481 	for (i = 0, symp = ef->ddbsymtab; i < ef->ddbsymcnt; i++, symp++) {
1482 		strp = ef->ddbstrtab + symp->st_name;
1483 		if (symp->st_shndx != SHN_UNDEF && strcmp(name, strp) == 0) {
1484 			if (see_local ||
1485 			    ELF_ST_BIND(symp->st_info) == STB_GLOBAL) {
1486 				*sym = (c_linker_sym_t) symp;
1487 				return (0);
1488 			}
1489 			return (ENOENT);
1490 		}
1491 	}
1492 	return (ENOENT);
1493 }
1494 
1495 static int
link_elf_lookup_symbol(linker_file_t lf,const char * name,c_linker_sym_t * sym)1496 link_elf_lookup_symbol(linker_file_t lf, const char *name, c_linker_sym_t *sym)
1497 {
1498 	return (link_elf_lookup_symbol1(lf, name, sym,
1499 	    link_elf_obj_leak_locals));
1500 }
1501 
1502 static int
link_elf_lookup_debug_symbol(linker_file_t lf,const char * name,c_linker_sym_t * sym)1503 link_elf_lookup_debug_symbol(linker_file_t lf, const char *name,
1504     c_linker_sym_t *sym)
1505 {
1506 	return (link_elf_lookup_symbol1(lf, name, sym, true));
1507 }
1508 
1509 static int
link_elf_lookup_debug_symbol_ctf(linker_file_t lf,const char * name,c_linker_sym_t * sym,linker_ctf_t * lc)1510 link_elf_lookup_debug_symbol_ctf(linker_file_t lf, const char *name,
1511     c_linker_sym_t *sym, linker_ctf_t *lc)
1512 {
1513 	if (link_elf_lookup_debug_symbol(lf, name, sym))
1514 		return (ENOENT);
1515 
1516 	return (link_elf_ctf_get_ddb(lf, lc));
1517 }
1518 
1519 static void
link_elf_ifunc_symbol_value(linker_file_t lf,caddr_t * valp,size_t * sizep)1520 link_elf_ifunc_symbol_value(linker_file_t lf, caddr_t *valp, size_t *sizep)
1521 {
1522 	c_linker_sym_t sym;
1523 	const Elf_Sym *es;
1524 	caddr_t val;
1525 	long off;
1526 
1527 	val = *valp;
1528 
1529 	/* Provide the value and size of the target symbol, if available. */
1530 	val = ((caddr_t (*)(void))val)();
1531 	if (link_elf_search_symbol(lf, val, &sym, &off) == 0 && off == 0) {
1532 		es = (const Elf_Sym *)sym;
1533 		*valp = (caddr_t)es->st_value;
1534 		*sizep = es->st_size;
1535 	} else {
1536 		*valp = val;
1537 		*sizep = 0;
1538 	}
1539 }
1540 
1541 static int
link_elf_symbol_values1(linker_file_t lf,c_linker_sym_t sym,linker_symval_t * symval,bool see_local)1542 link_elf_symbol_values1(linker_file_t lf, c_linker_sym_t sym,
1543     linker_symval_t *symval, bool see_local)
1544 {
1545 	elf_file_t ef;
1546 	const Elf_Sym *es;
1547 	caddr_t val;
1548 	size_t size;
1549 
1550 	ef = (elf_file_t) lf;
1551 	es = (const Elf_Sym*) sym;
1552 	val = (caddr_t)es->st_value;
1553 	if (es >= ef->ddbsymtab && es < (ef->ddbsymtab + ef->ddbsymcnt)) {
1554 		if (!see_local && ELF_ST_BIND(es->st_info) == STB_LOCAL)
1555 			return (ENOENT);
1556 		symval->name = ef->ddbstrtab + es->st_name;
1557 		val = (caddr_t)es->st_value;
1558 		if (ELF_ST_TYPE(es->st_info) == STT_GNU_IFUNC)
1559 			link_elf_ifunc_symbol_value(lf, &val, &size);
1560 		else
1561 			size = es->st_size;
1562 		symval->value = val;
1563 		symval->size = size;
1564 		return (0);
1565 	}
1566 	return (ENOENT);
1567 }
1568 
1569 static int
link_elf_symbol_values(linker_file_t lf,c_linker_sym_t sym,linker_symval_t * symval)1570 link_elf_symbol_values(linker_file_t lf, c_linker_sym_t sym,
1571     linker_symval_t *symval)
1572 {
1573 	return (link_elf_symbol_values1(lf, sym, symval,
1574 	    link_elf_obj_leak_locals));
1575 }
1576 
1577 static int
link_elf_debug_symbol_values(linker_file_t lf,c_linker_sym_t sym,linker_symval_t * symval)1578 link_elf_debug_symbol_values(linker_file_t lf, c_linker_sym_t sym,
1579     linker_symval_t *symval)
1580 {
1581 	return (link_elf_symbol_values1(lf, sym, symval, true));
1582 }
1583 
1584 static int
link_elf_search_symbol(linker_file_t lf,caddr_t value,c_linker_sym_t * sym,long * diffp)1585 link_elf_search_symbol(linker_file_t lf, caddr_t value,
1586     c_linker_sym_t *sym, long *diffp)
1587 {
1588 	elf_file_t ef = (elf_file_t)lf;
1589 	u_long off = (uintptr_t)(void *)value;
1590 	u_long diff = off;
1591 	u_long st_value;
1592 	const Elf_Sym *es;
1593 	const Elf_Sym *best = NULL;
1594 	int i;
1595 
1596 	for (i = 0, es = ef->ddbsymtab; i < ef->ddbsymcnt; i++, es++) {
1597 		if (es->st_name == 0)
1598 			continue;
1599 		st_value = es->st_value;
1600 		if (off >= st_value) {
1601 			if (off - st_value < diff) {
1602 				diff = off - st_value;
1603 				best = es;
1604 				if (diff == 0)
1605 					break;
1606 			} else if (off - st_value == diff) {
1607 				best = es;
1608 			}
1609 		}
1610 	}
1611 	if (best == NULL)
1612 		*diffp = off;
1613 	else
1614 		*diffp = diff;
1615 	*sym = (c_linker_sym_t) best;
1616 
1617 	return (0);
1618 }
1619 
1620 /*
1621  * Look up a linker set on an ELF system.
1622  */
1623 static int
link_elf_lookup_set(linker_file_t lf,const char * name,void *** startp,void *** stopp,int * countp)1624 link_elf_lookup_set(linker_file_t lf, const char *name,
1625     void ***startp, void ***stopp, int *countp)
1626 {
1627 	elf_file_t ef = (elf_file_t)lf;
1628 	void **start, **stop;
1629 	int i, count;
1630 
1631 	/* Relative to section number */
1632 	for (i = 0; i < ef->nprogtab; i++) {
1633 		if ((strncmp(ef->progtab[i].name, "set_", 4) == 0) &&
1634 		    strcmp(ef->progtab[i].name + 4, name) == 0) {
1635 			start  = (void **)ef->progtab[i].addr;
1636 			stop = (void **)((char *)ef->progtab[i].addr +
1637 			    ef->progtab[i].size);
1638 			count = stop - start;
1639 			if (startp)
1640 				*startp = start;
1641 			if (stopp)
1642 				*stopp = stop;
1643 			if (countp)
1644 				*countp = count;
1645 			return (0);
1646 		}
1647 	}
1648 	return (ESRCH);
1649 }
1650 
1651 static int
link_elf_each_function_name(linker_file_t file,int (* callback)(const char *,void *),void * opaque)1652 link_elf_each_function_name(linker_file_t file,
1653     int (*callback)(const char *, void *), void *opaque)
1654 {
1655 	elf_file_t ef = (elf_file_t)file;
1656 	const Elf_Sym *symp;
1657 	int i, error;
1658 
1659 	/* Exhaustive search */
1660 	for (i = 0, symp = ef->ddbsymtab; i < ef->ddbsymcnt; i++, symp++) {
1661 		if (symp->st_value != 0 &&
1662 		    (ELF_ST_TYPE(symp->st_info) == STT_FUNC ||
1663 		    ELF_ST_TYPE(symp->st_info) == STT_GNU_IFUNC)) {
1664 			error = callback(ef->ddbstrtab + symp->st_name, opaque);
1665 			if (error)
1666 				return (error);
1667 		}
1668 	}
1669 	return (0);
1670 }
1671 
1672 static int
link_elf_each_function_nameval(linker_file_t file,linker_function_nameval_callback_t callback,void * opaque)1673 link_elf_each_function_nameval(linker_file_t file,
1674     linker_function_nameval_callback_t callback, void *opaque)
1675 {
1676 	linker_symval_t symval;
1677 	elf_file_t ef = (elf_file_t)file;
1678 	const Elf_Sym *symp;
1679 	int i, error;
1680 
1681 	/* Exhaustive search */
1682 	for (i = 0, symp = ef->ddbsymtab; i < ef->ddbsymcnt; i++, symp++) {
1683 		if (symp->st_value != 0 &&
1684 		    (ELF_ST_TYPE(symp->st_info) == STT_FUNC ||
1685 		    ELF_ST_TYPE(symp->st_info) == STT_GNU_IFUNC)) {
1686 			error = link_elf_debug_symbol_values(file,
1687 			    (c_linker_sym_t)symp, &symval);
1688 			if (error == 0)
1689 				error = callback(file, i, &symval, opaque);
1690 			if (error != 0)
1691 				return (error);
1692 		}
1693 	}
1694 	return (0);
1695 }
1696 
1697 static void
elf_obj_cleanup_globals_cache(elf_file_t ef)1698 elf_obj_cleanup_globals_cache(elf_file_t ef)
1699 {
1700 	Elf_Sym *sym;
1701 	Elf_Size i;
1702 
1703 	for (i = 0; i < ef->ddbsymcnt; i++) {
1704 		sym = ef->ddbsymtab + i;
1705 		if (sym->st_shndx == SHN_FBSD_CACHED) {
1706 			sym->st_shndx = SHN_UNDEF;
1707 			sym->st_value = 0;
1708 		}
1709 	}
1710 }
1711 
1712 /*
1713  * Symbol lookup function that can be used when the symbol index is known (ie
1714  * in relocations). It uses the symbol index instead of doing a fully fledged
1715  * hash table based lookup when such is valid. For example for local symbols.
1716  * This is not only more efficient, it's also more correct. It's not always
1717  * the case that the symbol can be found through the hash table.
1718  */
1719 static int
elf_obj_lookup(linker_file_t lf,Elf_Size symidx,int deps,Elf_Addr * res)1720 elf_obj_lookup(linker_file_t lf, Elf_Size symidx, int deps, Elf_Addr *res)
1721 {
1722 	elf_file_t ef = (elf_file_t)lf;
1723 	Elf_Sym *sym;
1724 	const char *symbol;
1725 	Elf_Addr res1;
1726 
1727 	/* Don't even try to lookup the symbol if the index is bogus. */
1728 	if (symidx >= ef->ddbsymcnt) {
1729 		*res = 0;
1730 		return (EINVAL);
1731 	}
1732 
1733 	sym = ef->ddbsymtab + symidx;
1734 
1735 	/* Quick answer if there is a definition included. */
1736 	if (sym->st_shndx != SHN_UNDEF) {
1737 		res1 = (Elf_Addr)sym->st_value;
1738 		if (ELF_ST_TYPE(sym->st_info) == STT_GNU_IFUNC)
1739 			res1 = ((Elf_Addr (*)(void))res1)();
1740 		*res = res1;
1741 		return (0);
1742 	}
1743 
1744 	/* If we get here, then it is undefined and needs a lookup. */
1745 	switch (ELF_ST_BIND(sym->st_info)) {
1746 	case STB_LOCAL:
1747 		/* Local, but undefined? huh? */
1748 		*res = 0;
1749 		return (EINVAL);
1750 
1751 	case STB_GLOBAL:
1752 	case STB_WEAK:
1753 		/* Relative to Data or Function name */
1754 		symbol = ef->ddbstrtab + sym->st_name;
1755 
1756 		/* Force a lookup failure if the symbol name is bogus. */
1757 		if (*symbol == 0) {
1758 			*res = 0;
1759 			return (EINVAL);
1760 		}
1761 		res1 = (Elf_Addr)linker_file_lookup_symbol(lf, symbol, deps);
1762 
1763 		/*
1764 		 * Cache global lookups during module relocation. The failure
1765 		 * case is particularly expensive for callers, who must scan
1766 		 * through the entire globals table doing strcmp(). Cache to
1767 		 * avoid doing such work repeatedly.
1768 		 *
1769 		 * After relocation is complete, undefined globals will be
1770 		 * restored to SHN_UNDEF in elf_obj_cleanup_globals_cache(),
1771 		 * above.
1772 		 */
1773 		if (res1 != 0) {
1774 			sym->st_shndx = SHN_FBSD_CACHED;
1775 			sym->st_value = res1;
1776 			*res = res1;
1777 			return (0);
1778 		} else if (ELF_ST_BIND(sym->st_info) == STB_WEAK) {
1779 			sym->st_value = 0;
1780 			*res = 0;
1781 			return (0);
1782 		}
1783 		return (EINVAL);
1784 
1785 	default:
1786 		return (EINVAL);
1787 	}
1788 }
1789 
1790 static void
link_elf_fix_link_set(elf_file_t ef)1791 link_elf_fix_link_set(elf_file_t ef)
1792 {
1793 	static const char startn[] = "__start_";
1794 	static const char stopn[] = "__stop_";
1795 	Elf_Sym *sym;
1796 	const char *sym_name, *linkset_name;
1797 	Elf_Addr startp, stopp;
1798 	Elf_Size symidx;
1799 	int start, i;
1800 
1801 	startp = stopp = 0;
1802 	for (symidx = 1 /* zero entry is special */;
1803 		symidx < ef->ddbsymcnt; symidx++) {
1804 		sym = ef->ddbsymtab + symidx;
1805 		if (sym->st_shndx != SHN_UNDEF)
1806 			continue;
1807 
1808 		sym_name = ef->ddbstrtab + sym->st_name;
1809 		if (strncmp(sym_name, startn, sizeof(startn) - 1) == 0) {
1810 			start = 1;
1811 			linkset_name = sym_name + sizeof(startn) - 1;
1812 		}
1813 		else if (strncmp(sym_name, stopn, sizeof(stopn) - 1) == 0) {
1814 			start = 0;
1815 			linkset_name = sym_name + sizeof(stopn) - 1;
1816 		}
1817 		else
1818 			continue;
1819 
1820 		for (i = 0; i < ef->nprogtab; i++) {
1821 			if (strcmp(ef->progtab[i].name, linkset_name) == 0) {
1822 				startp = (Elf_Addr)ef->progtab[i].addr;
1823 				stopp = (Elf_Addr)(startp + ef->progtab[i].size);
1824 				break;
1825 			}
1826 		}
1827 		if (i == ef->nprogtab)
1828 			continue;
1829 
1830 		sym->st_value = start ? startp : stopp;
1831 		sym->st_shndx = i;
1832 	}
1833 }
1834 
1835 static int
link_elf_reloc_local(linker_file_t lf,bool ifuncs)1836 link_elf_reloc_local(linker_file_t lf, bool ifuncs)
1837 {
1838 	elf_file_t ef = (elf_file_t)lf;
1839 	const Elf_Rel *rellim;
1840 	const Elf_Rel *rel;
1841 	const Elf_Rela *relalim;
1842 	const Elf_Rela *rela;
1843 	const Elf_Sym *sym;
1844 	Elf_Addr base;
1845 	int i;
1846 	Elf_Size symidx;
1847 
1848 	link_elf_fix_link_set(ef);
1849 
1850 	/* Perform relocations without addend if there are any: */
1851 	for (i = 0; i < ef->nreltab; i++) {
1852 		rel = ef->reltab[i].rel;
1853 		if (rel == NULL) {
1854 			link_elf_error(ef->lf.filename, "lost a reltab");
1855 			return (ENOEXEC);
1856 		}
1857 		rellim = rel + ef->reltab[i].nrel;
1858 		base = findbase(ef, ef->reltab[i].sec);
1859 		if (base == 0) {
1860 			link_elf_error(ef->lf.filename, "lost base for reltab");
1861 			return (ENOEXEC);
1862 		}
1863 		for ( ; rel < rellim; rel++) {
1864 			symidx = ELF_R_SYM(rel->r_info);
1865 			if (symidx >= ef->ddbsymcnt)
1866 				continue;
1867 			sym = ef->ddbsymtab + symidx;
1868 			/* Only do local relocs */
1869 			if (ELF_ST_BIND(sym->st_info) != STB_LOCAL)
1870 				continue;
1871 			if ((ELF_ST_TYPE(sym->st_info) == STT_GNU_IFUNC ||
1872 			    elf_is_ifunc_reloc(rel->r_info)) != ifuncs)
1873 				continue;
1874 			if (elf_reloc_local(lf, base, rel, ELF_RELOC_REL,
1875 			    elf_obj_lookup) != 0)
1876 				return (ENOEXEC);
1877 		}
1878 	}
1879 
1880 	/* Perform relocations with addend if there are any: */
1881 	for (i = 0; i < ef->nrelatab; i++) {
1882 		rela = ef->relatab[i].rela;
1883 		if (rela == NULL) {
1884 			link_elf_error(ef->lf.filename, "lost a relatab!");
1885 			return (ENOEXEC);
1886 		}
1887 		relalim = rela + ef->relatab[i].nrela;
1888 		base = findbase(ef, ef->relatab[i].sec);
1889 		if (base == 0) {
1890 			link_elf_error(ef->lf.filename, "lost base for reltab");
1891 			return (ENOEXEC);
1892 		}
1893 		for ( ; rela < relalim; rela++) {
1894 			symidx = ELF_R_SYM(rela->r_info);
1895 			if (symidx >= ef->ddbsymcnt)
1896 				continue;
1897 			sym = ef->ddbsymtab + symidx;
1898 			/* Only do local relocs */
1899 			if (ELF_ST_BIND(sym->st_info) != STB_LOCAL)
1900 				continue;
1901 			if ((ELF_ST_TYPE(sym->st_info) == STT_GNU_IFUNC ||
1902 			    elf_is_ifunc_reloc(rela->r_info)) != ifuncs)
1903 				continue;
1904 			if (elf_reloc_local(lf, base, rela, ELF_RELOC_RELA,
1905 			    elf_obj_lookup) != 0)
1906 				return (ENOEXEC);
1907 		}
1908 	}
1909 	return (0);
1910 }
1911 
1912 static long
link_elf_symtab_get(linker_file_t lf,const Elf_Sym ** symtab)1913 link_elf_symtab_get(linker_file_t lf, const Elf_Sym **symtab)
1914 {
1915 	elf_file_t ef = (elf_file_t)lf;
1916 
1917 	*symtab = ef->ddbsymtab;
1918 	if (*symtab == NULL)
1919 		return (0);
1920 	return (ef->ddbsymcnt);
1921 }
1922 
1923 static long
link_elf_strtab_get(linker_file_t lf,caddr_t * strtab)1924 link_elf_strtab_get(linker_file_t lf, caddr_t *strtab)
1925 {
1926 	elf_file_t ef = (elf_file_t)lf;
1927 
1928 	*strtab = ef->ddbstrtab;
1929 	if (*strtab == NULL)
1930 		return (0);
1931 	return (ef->ddbstrcnt);
1932 }
1933 
1934 #ifdef VIMAGE
1935 static void
link_elf_propagate_vnets(linker_file_t lf)1936 link_elf_propagate_vnets(linker_file_t lf)
1937 {
1938 	elf_file_t ef = (elf_file_t) lf;
1939 
1940 	if (ef->progtab) {
1941 		for (int i = 0; i < ef->nprogtab; i++) {
1942 			if (ef->progtab[i].size == 0)
1943 				continue;
1944 			if (ef->progtab[i].name == NULL)
1945 				continue;
1946 			if (strcmp(ef->progtab[i].name, VNET_SETNAME) == 0) {
1947 				vnet_data_copy(ef->progtab[i].addr,
1948 				    ef->progtab[i].size);
1949 				break;
1950 			}
1951 		}
1952 	}
1953 }
1954 #endif
1955