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