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