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