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