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