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