xref: /freebsd/sys/kern/link_elf.c (revision 38d120bc13ac1de5b739b67b87016b9122149374)
1 /*-
2  * Copyright (c) 1998-2000 Doug Rabson
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include "opt_ddb.h"
31 #include "opt_gdb.h"
32 
33 #include <sys/param.h>
34 #include <sys/systm.h>
35 #ifdef GPROF
36 #include <sys/gmon.h>
37 #endif
38 #include <sys/kernel.h>
39 #include <sys/lock.h>
40 #include <sys/malloc.h>
41 #include <sys/mutex.h>
42 #include <sys/mount.h>
43 #include <sys/pcpu.h>
44 #include <sys/proc.h>
45 #include <sys/namei.h>
46 #include <sys/fcntl.h>
47 #include <sys/vnode.h>
48 #include <sys/linker.h>
49 
50 #include <machine/elf.h>
51 
52 #include <net/vnet.h>
53 
54 #include <security/mac/mac_framework.h>
55 
56 #include <vm/vm.h>
57 #include <vm/vm_param.h>
58 #ifdef SPARSE_MAPPING
59 #include <vm/vm_object.h>
60 #include <vm/vm_kern.h>
61 #include <vm/vm_extern.h>
62 #endif
63 #include <vm/pmap.h>
64 #include <vm/vm_map.h>
65 
66 #include <sys/link_elf.h>
67 
68 #ifdef DDB_CTF
69 #include <net/zlib.h>
70 #endif
71 
72 #include "linker_if.h"
73 
74 #define MAXSEGS 4
75 
76 typedef struct elf_file {
77 	struct linker_file lf;		/* Common fields */
78 	int		preloaded;	/* Was file pre-loaded */
79 	caddr_t		address;	/* Relocation address */
80 #ifdef SPARSE_MAPPING
81 	vm_object_t	object;		/* VM object to hold file pages */
82 #endif
83 	Elf_Dyn		*dynamic;	/* Symbol table etc. */
84 	Elf_Hashelt	nbuckets;	/* DT_HASH info */
85 	Elf_Hashelt	nchains;
86 	const Elf_Hashelt *buckets;
87 	const Elf_Hashelt *chains;
88 	caddr_t		hash;
89 	caddr_t		strtab;		/* DT_STRTAB */
90 	int		strsz;		/* DT_STRSZ */
91 	const Elf_Sym	*symtab;		/* DT_SYMTAB */
92 	Elf_Addr	*got;		/* DT_PLTGOT */
93 	const Elf_Rel	*pltrel;	/* DT_JMPREL */
94 	int		pltrelsize;	/* DT_PLTRELSZ */
95 	const Elf_Rela	*pltrela;	/* DT_JMPREL */
96 	int		pltrelasize;	/* DT_PLTRELSZ */
97 	const Elf_Rel	*rel;		/* DT_REL */
98 	int		relsize;	/* DT_RELSZ */
99 	const Elf_Rela	*rela;		/* DT_RELA */
100 	int		relasize;	/* DT_RELASZ */
101 	caddr_t		modptr;
102 	const Elf_Sym	*ddbsymtab;	/* The symbol table we are using */
103 	long		ddbsymcnt;	/* Number of symbols */
104 	caddr_t		ddbstrtab;	/* String table */
105 	long		ddbstrcnt;	/* number of bytes in string table */
106 	caddr_t		symbase;	/* malloc'ed symbold base */
107 	caddr_t		strbase;	/* malloc'ed string base */
108 	caddr_t		ctftab;		/* CTF table */
109 	long		ctfcnt;		/* number of bytes in CTF table */
110 	caddr_t		ctfoff;		/* CTF offset table */
111 	caddr_t		typoff;		/* Type offset table */
112 	long		typlen;		/* Number of type entries. */
113 	Elf_Addr	pcpu_start;	/* Pre-relocation pcpu set start. */
114 	Elf_Addr	pcpu_stop;	/* Pre-relocation pcpu set stop. */
115 	Elf_Addr	pcpu_base;	/* Relocated pcpu set address. */
116 #ifdef VIMAGE
117 	Elf_Addr	vnet_start;	/* Pre-relocation vnet set start. */
118 	Elf_Addr	vnet_stop;	/* Pre-relocation vnet set stop. */
119 	Elf_Addr	vnet_base;	/* Relocated vnet set address. */
120 #endif
121 #ifdef GDB
122 	struct link_map	gdb;		/* hooks for gdb */
123 #endif
124 } *elf_file_t;
125 
126 struct elf_set {
127 	Elf_Addr	es_start;
128 	Elf_Addr	es_stop;
129 	Elf_Addr	es_base;
130 	TAILQ_ENTRY(elf_set)	es_link;
131 };
132 
133 TAILQ_HEAD(elf_set_head, elf_set);
134 
135 #include <kern/kern_ctf.c>
136 
137 static int	link_elf_link_common_finish(linker_file_t);
138 static int	link_elf_link_preload(linker_class_t cls,
139 				      const char *, linker_file_t *);
140 static int	link_elf_link_preload_finish(linker_file_t);
141 static int	link_elf_load_file(linker_class_t, const char *,
142 		    linker_file_t *);
143 static int	link_elf_lookup_symbol(linker_file_t, const char *,
144 		    c_linker_sym_t *);
145 static int	link_elf_symbol_values(linker_file_t, c_linker_sym_t,
146 		    linker_symval_t *);
147 static int	link_elf_search_symbol(linker_file_t, caddr_t,
148 		    c_linker_sym_t *, long *);
149 
150 static void	link_elf_unload_file(linker_file_t);
151 static void	link_elf_unload_preload(linker_file_t);
152 static int	link_elf_lookup_set(linker_file_t, const char *,
153 		    void ***, void ***, int *);
154 static int	link_elf_each_function_name(linker_file_t,
155 		    int (*)(const char *, void *), void *);
156 static int	link_elf_each_function_nameval(linker_file_t,
157 		    linker_function_nameval_callback_t, void *);
158 static void	link_elf_reloc_local(linker_file_t);
159 static long	link_elf_symtab_get(linker_file_t, const Elf_Sym **);
160 static long	link_elf_strtab_get(linker_file_t, caddr_t *);
161 static Elf_Addr	elf_lookup(linker_file_t, Elf_Size, int);
162 
163 static kobj_method_t link_elf_methods[] = {
164 	KOBJMETHOD(linker_lookup_symbol,	link_elf_lookup_symbol),
165 	KOBJMETHOD(linker_symbol_values,	link_elf_symbol_values),
166 	KOBJMETHOD(linker_search_symbol,	link_elf_search_symbol),
167 	KOBJMETHOD(linker_unload,		link_elf_unload_file),
168 	KOBJMETHOD(linker_load_file,		link_elf_load_file),
169 	KOBJMETHOD(linker_link_preload,		link_elf_link_preload),
170 	KOBJMETHOD(linker_link_preload_finish,	link_elf_link_preload_finish),
171 	KOBJMETHOD(linker_lookup_set,		link_elf_lookup_set),
172 	KOBJMETHOD(linker_each_function_name,	link_elf_each_function_name),
173 	KOBJMETHOD(linker_each_function_nameval, link_elf_each_function_nameval),
174 	KOBJMETHOD(linker_ctf_get,		link_elf_ctf_get),
175 	KOBJMETHOD(linker_symtab_get,		link_elf_symtab_get),
176 	KOBJMETHOD(linker_strtab_get,		link_elf_strtab_get),
177 	{ 0, 0 }
178 };
179 
180 static struct linker_class link_elf_class = {
181 #if ELF_TARG_CLASS == ELFCLASS32
182 	"elf32",
183 #else
184 	"elf64",
185 #endif
186 	link_elf_methods, sizeof(struct elf_file)
187 };
188 
189 static int	parse_dynamic(elf_file_t);
190 static int	relocate_file(elf_file_t);
191 static int	link_elf_preload_parse_symbols(elf_file_t);
192 
193 static struct elf_set_head set_pcpu_list;
194 #ifdef VIMAGE
195 static struct elf_set_head set_vnet_list;
196 #endif
197 
198 static void
199 elf_set_add(struct elf_set_head *list, Elf_Addr start, Elf_Addr stop, Elf_Addr base)
200 {
201 	struct elf_set *set, *iter;
202 
203 	set = malloc(sizeof(*set), M_LINKER, M_WAITOK);
204 	set->es_start = start;
205 	set->es_stop = stop;
206 	set->es_base = base;
207 
208 	TAILQ_FOREACH(iter, list, es_link) {
209 
210 		KASSERT((set->es_start < iter->es_start && set->es_stop < iter->es_stop) ||
211 		    (set->es_start > iter->es_start && set->es_stop > iter->es_stop),
212 		    ("linker sets intersection: to insert: 0x%jx-0x%jx; inserted: 0x%jx-0x%jx",
213 		    (uintmax_t)set->es_start, (uintmax_t)set->es_stop,
214 		    (uintmax_t)iter->es_start, (uintmax_t)iter->es_stop));
215 
216 		if (iter->es_start > set->es_start) {
217 			TAILQ_INSERT_BEFORE(iter, set, es_link);
218 			break;
219 		}
220 	}
221 
222 	if (iter == NULL)
223 		TAILQ_INSERT_TAIL(list, set, es_link);
224 }
225 
226 static int
227 elf_set_find(struct elf_set_head *list, Elf_Addr addr, Elf_Addr *start, Elf_Addr *base)
228 {
229 	struct elf_set *set;
230 
231 	TAILQ_FOREACH(set, list, es_link) {
232 		if (addr < set->es_start)
233 			return (0);
234 		if (addr < set->es_stop) {
235 			*start = set->es_start;
236 			*base = set->es_base;
237 			return (1);
238 		}
239 	}
240 
241 	return (0);
242 }
243 
244 static void
245 elf_set_delete(struct elf_set_head *list, Elf_Addr start)
246 {
247 	struct elf_set *set;
248 
249 	TAILQ_FOREACH(set, list, es_link) {
250 		if (start < set->es_start)
251 			break;
252 		if (start == set->es_start) {
253 			TAILQ_REMOVE(list, set, es_link);
254 			free(set, M_LINKER);
255 			return;
256 		}
257 	}
258 	KASSERT(0, ("deleting unknown linker set (start = 0x%jx)",
259 	    (uintmax_t)start));
260 }
261 
262 #ifdef GDB
263 static void	r_debug_state(struct r_debug *, struct link_map *);
264 
265 /*
266  * A list of loaded modules for GDB to use for loading symbols.
267  */
268 struct r_debug r_debug;
269 
270 #define GDB_STATE(s) do {				\
271 	r_debug.r_state = s; r_debug_state(NULL, NULL);	\
272 } while (0)
273 
274 /*
275  * Function for the debugger to set a breakpoint on to gain control.
276  */
277 static void
278 r_debug_state(struct r_debug *dummy_one __unused,
279 	      struct link_map *dummy_two __unused)
280 {
281 }
282 
283 static void
284 link_elf_add_gdb(struct link_map *l)
285 {
286 	struct link_map *prev;
287 
288 	l->l_next = NULL;
289 
290 	if (r_debug.r_map == NULL) {
291 		/* Add first. */
292 		l->l_prev = NULL;
293 		r_debug.r_map = l;
294 	} else {
295 		/* Append to list. */
296 		for (prev = r_debug.r_map;
297 		    prev->l_next != NULL;
298 		    prev = prev->l_next)
299 			;
300 		l->l_prev = prev;
301 		prev->l_next = l;
302 	}
303 }
304 
305 static void
306 link_elf_delete_gdb(struct link_map *l)
307 {
308 	if (l->l_prev == NULL) {
309 		/* Remove first. */
310 		if ((r_debug.r_map = l->l_next) != NULL)
311 			l->l_next->l_prev = NULL;
312 	} else {
313 		/* Remove any but first. */
314 		if ((l->l_prev->l_next = l->l_next) != NULL)
315 			l->l_next->l_prev = l->l_prev;
316 	}
317 }
318 #endif /* GDB */
319 
320 /*
321  * The kernel symbol table starts here.
322  */
323 extern struct _dynamic _DYNAMIC;
324 
325 static void
326 link_elf_error(const char *filename, const char *s)
327 {
328 	if (filename == NULL)
329 		printf("kldload: %s\n", s);
330 	else
331 		printf("kldload: %s: %s\n", filename, s);
332 }
333 
334 static void
335 link_elf_invoke_ctors(caddr_t addr, size_t size)
336 {
337 	void (**ctor)(void);
338 	size_t i, cnt;
339 
340 	if (addr == NULL || size == 0)
341 		return;
342 	cnt = size / sizeof(*ctor);
343 	ctor = (void *)addr;
344 	for (i = 0; i < cnt; i++) {
345 		if (ctor[i] != NULL)
346 			(*ctor[i])();
347 	}
348 }
349 
350 /*
351  * Actions performed after linking/loading both the preloaded kernel and any
352  * modules; whether preloaded or dynamicly loaded.
353  */
354 static int
355 link_elf_link_common_finish(linker_file_t lf)
356 {
357 #ifdef GDB
358 	elf_file_t ef = (elf_file_t)lf;
359 	char *newfilename;
360 #endif
361 	int error;
362 
363 	/* Notify MD code that a module is being loaded. */
364 	error = elf_cpu_load_file(lf);
365 	if (error != 0)
366 		return (error);
367 
368 #ifdef GDB
369 	GDB_STATE(RT_ADD);
370 	ef->gdb.l_addr = lf->address;
371 	newfilename = malloc(strlen(lf->filename) + 1, M_LINKER, M_WAITOK);
372 	strcpy(newfilename, lf->filename);
373 	ef->gdb.l_name = newfilename;
374 	ef->gdb.l_ld = ef->dynamic;
375 	link_elf_add_gdb(&ef->gdb);
376 	GDB_STATE(RT_CONSISTENT);
377 #endif
378 
379 	/* Invoke .ctors */
380 	link_elf_invoke_ctors(lf->ctors_addr, lf->ctors_size);
381 	return (0);
382 }
383 
384 static void
385 link_elf_init(void* arg)
386 {
387 	Elf_Dyn *dp;
388 	Elf_Addr *ctors_addrp;
389 	Elf_Size *ctors_sizep;
390 	caddr_t modptr, baseptr, sizeptr;
391 	elf_file_t ef;
392 	char *modname;
393 
394 	linker_add_class(&link_elf_class);
395 
396 	dp = (Elf_Dyn *)&_DYNAMIC;
397 	modname = NULL;
398 	modptr = preload_search_by_type("elf" __XSTRING(__ELF_WORD_SIZE) " kernel");
399 	if (modptr == NULL)
400 		modptr = preload_search_by_type("elf kernel");
401 	if (modptr != NULL)
402 		modname = (char *)preload_search_info(modptr, MODINFO_NAME);
403 	if (modname == NULL)
404 		modname = "kernel";
405 	linker_kernel_file = linker_make_file(modname, &link_elf_class);
406 	if (linker_kernel_file == NULL)
407 		panic("%s: Can't create linker structures for kernel",
408 		    __func__);
409 
410 	ef = (elf_file_t) linker_kernel_file;
411 	ef->preloaded = 1;
412 	ef->address = 0;
413 #ifdef SPARSE_MAPPING
414 	ef->object = 0;
415 #endif
416 	ef->dynamic = dp;
417 
418 	if (dp != NULL)
419 		parse_dynamic(ef);
420 	linker_kernel_file->address = (caddr_t) KERNBASE;
421 	linker_kernel_file->size = -(intptr_t)linker_kernel_file->address;
422 
423 	if (modptr != NULL) {
424 		ef->modptr = modptr;
425 		baseptr = preload_search_info(modptr, MODINFO_ADDR);
426 		if (baseptr != NULL)
427 			linker_kernel_file->address = *(caddr_t *)baseptr;
428 		sizeptr = preload_search_info(modptr, MODINFO_SIZE);
429 		if (sizeptr != NULL)
430 			linker_kernel_file->size = *(size_t *)sizeptr;
431 		ctors_addrp = (Elf_Addr *)preload_search_info(modptr,
432 			MODINFO_METADATA | MODINFOMD_CTORS_ADDR);
433 		ctors_sizep = (Elf_Size *)preload_search_info(modptr,
434 			MODINFO_METADATA | MODINFOMD_CTORS_SIZE);
435 		if (ctors_addrp != NULL && ctors_sizep != NULL) {
436 			linker_kernel_file->ctors_addr = ef->address +
437 			    *ctors_addrp;
438 			linker_kernel_file->ctors_size = *ctors_sizep;
439 		}
440 	}
441 	(void)link_elf_preload_parse_symbols(ef);
442 
443 #ifdef GDB
444 	r_debug.r_map = NULL;
445 	r_debug.r_brk = r_debug_state;
446 	r_debug.r_state = RT_CONSISTENT;
447 #endif
448 
449 	(void)link_elf_link_common_finish(linker_kernel_file);
450 	linker_kernel_file->flags |= LINKER_FILE_LINKED;
451 	TAILQ_INIT(&set_pcpu_list);
452 #ifdef VIMAGE
453 	TAILQ_INIT(&set_vnet_list);
454 #endif
455 }
456 
457 SYSINIT(link_elf, SI_SUB_KLD, SI_ORDER_THIRD, link_elf_init, 0);
458 
459 static int
460 link_elf_preload_parse_symbols(elf_file_t ef)
461 {
462 	caddr_t pointer;
463 	caddr_t ssym, esym, base;
464 	caddr_t strtab;
465 	int strcnt;
466 	Elf_Sym *symtab;
467 	int symcnt;
468 
469 	if (ef->modptr == NULL)
470 		return (0);
471 	pointer = preload_search_info(ef->modptr,
472 	    MODINFO_METADATA | MODINFOMD_SSYM);
473 	if (pointer == NULL)
474 		return (0);
475 	ssym = *(caddr_t *)pointer;
476 	pointer = preload_search_info(ef->modptr,
477 	    MODINFO_METADATA | MODINFOMD_ESYM);
478 	if (pointer == NULL)
479 		return (0);
480 	esym = *(caddr_t *)pointer;
481 
482 	base = ssym;
483 
484 	symcnt = *(long *)base;
485 	base += sizeof(long);
486 	symtab = (Elf_Sym *)base;
487 	base += roundup(symcnt, sizeof(long));
488 
489 	if (base > esym || base < ssym) {
490 		printf("Symbols are corrupt!\n");
491 		return (EINVAL);
492 	}
493 
494 	strcnt = *(long *)base;
495 	base += sizeof(long);
496 	strtab = base;
497 	base += roundup(strcnt, sizeof(long));
498 
499 	if (base > esym || base < ssym) {
500 		printf("Symbols are corrupt!\n");
501 		return (EINVAL);
502 	}
503 
504 	ef->ddbsymtab = symtab;
505 	ef->ddbsymcnt = symcnt / sizeof(Elf_Sym);
506 	ef->ddbstrtab = strtab;
507 	ef->ddbstrcnt = strcnt;
508 
509 	return (0);
510 }
511 
512 static int
513 parse_dynamic(elf_file_t ef)
514 {
515 	Elf_Dyn *dp;
516 	int plttype = DT_REL;
517 
518 	for (dp = ef->dynamic; dp->d_tag != DT_NULL; dp++) {
519 		switch (dp->d_tag) {
520 		case DT_HASH:
521 		{
522 			/* From src/libexec/rtld-elf/rtld.c */
523 			const Elf_Hashelt *hashtab = (const Elf_Hashelt *)
524 			    (ef->address + dp->d_un.d_ptr);
525 			ef->nbuckets = hashtab[0];
526 			ef->nchains = hashtab[1];
527 			ef->buckets = hashtab + 2;
528 			ef->chains = ef->buckets + ef->nbuckets;
529 			break;
530 		}
531 		case DT_STRTAB:
532 			ef->strtab = (caddr_t) (ef->address + dp->d_un.d_ptr);
533 			break;
534 		case DT_STRSZ:
535 			ef->strsz = dp->d_un.d_val;
536 			break;
537 		case DT_SYMTAB:
538 			ef->symtab = (Elf_Sym*) (ef->address + dp->d_un.d_ptr);
539 			break;
540 		case DT_SYMENT:
541 			if (dp->d_un.d_val != sizeof(Elf_Sym))
542 				return (ENOEXEC);
543 			break;
544 		case DT_PLTGOT:
545 			ef->got = (Elf_Addr *) (ef->address + dp->d_un.d_ptr);
546 			break;
547 		case DT_REL:
548 			ef->rel = (const Elf_Rel *) (ef->address + dp->d_un.d_ptr);
549 			break;
550 		case DT_RELSZ:
551 			ef->relsize = dp->d_un.d_val;
552 			break;
553 		case DT_RELENT:
554 			if (dp->d_un.d_val != sizeof(Elf_Rel))
555 				return (ENOEXEC);
556 			break;
557 		case DT_JMPREL:
558 			ef->pltrel = (const Elf_Rel *) (ef->address + dp->d_un.d_ptr);
559 			break;
560 		case DT_PLTRELSZ:
561 			ef->pltrelsize = dp->d_un.d_val;
562 			break;
563 		case DT_RELA:
564 			ef->rela = (const Elf_Rela *) (ef->address + dp->d_un.d_ptr);
565 			break;
566 		case DT_RELASZ:
567 			ef->relasize = dp->d_un.d_val;
568 			break;
569 		case DT_RELAENT:
570 			if (dp->d_un.d_val != sizeof(Elf_Rela))
571 				return (ENOEXEC);
572 			break;
573 		case DT_PLTREL:
574 			plttype = dp->d_un.d_val;
575 			if (plttype != DT_REL && plttype != DT_RELA)
576 				return (ENOEXEC);
577 			break;
578 #ifdef GDB
579 		case DT_DEBUG:
580 			dp->d_un.d_ptr = (Elf_Addr)&r_debug;
581 			break;
582 #endif
583 		}
584 	}
585 
586 	if (plttype == DT_RELA) {
587 		ef->pltrela = (const Elf_Rela *)ef->pltrel;
588 		ef->pltrel = NULL;
589 		ef->pltrelasize = ef->pltrelsize;
590 		ef->pltrelsize = 0;
591 	}
592 
593 	ef->ddbsymtab = ef->symtab;
594 	ef->ddbsymcnt = ef->nchains;
595 	ef->ddbstrtab = ef->strtab;
596 	ef->ddbstrcnt = ef->strsz;
597 
598 	return (0);
599 }
600 
601 static int
602 parse_dpcpu(elf_file_t ef)
603 {
604 	int count;
605 	int error;
606 
607 	ef->pcpu_start = 0;
608 	ef->pcpu_stop = 0;
609 	error = link_elf_lookup_set(&ef->lf, "pcpu", (void ***)&ef->pcpu_start,
610 	    (void ***)&ef->pcpu_stop, &count);
611 	/* Error just means there is no pcpu set to relocate. */
612 	if (error != 0)
613 		return (0);
614 	count *= sizeof(void *);
615 	/*
616 	 * Allocate space in the primary pcpu area.  Copy in our
617 	 * initialization from the data section and then initialize
618 	 * all per-cpu storage from that.
619 	 */
620 	ef->pcpu_base = (Elf_Addr)(uintptr_t)dpcpu_alloc(count);
621 	if (ef->pcpu_base == 0)
622 		return (ENOSPC);
623 	memcpy((void *)ef->pcpu_base, (void *)ef->pcpu_start, count);
624 	dpcpu_copy((void *)ef->pcpu_base, count);
625 	elf_set_add(&set_pcpu_list, ef->pcpu_start, ef->pcpu_stop,
626 	    ef->pcpu_base);
627 
628 	return (0);
629 }
630 
631 #ifdef VIMAGE
632 static int
633 parse_vnet(elf_file_t ef)
634 {
635 	int count;
636 	int error;
637 
638 	ef->vnet_start = 0;
639 	ef->vnet_stop = 0;
640 	error = link_elf_lookup_set(&ef->lf, "vnet", (void ***)&ef->vnet_start,
641 	    (void ***)&ef->vnet_stop, &count);
642 	/* Error just means there is no vnet data set to relocate. */
643 	if (error != 0)
644 		return (0);
645 	count *= sizeof(void *);
646 	/*
647 	 * Allocate space in the primary vnet area.  Copy in our
648 	 * initialization from the data section and then initialize
649 	 * all per-vnet storage from that.
650 	 */
651 	ef->vnet_base = (Elf_Addr)(uintptr_t)vnet_data_alloc(count);
652 	if (ef->vnet_base == 0)
653 		return (ENOSPC);
654 	memcpy((void *)ef->vnet_base, (void *)ef->vnet_start, count);
655 	vnet_data_copy((void *)ef->vnet_base, count);
656 	elf_set_add(&set_vnet_list, ef->vnet_start, ef->vnet_stop,
657 	    ef->vnet_base);
658 
659 	return (0);
660 }
661 #endif
662 
663 static int
664 link_elf_link_preload(linker_class_t cls,
665     const char* filename, linker_file_t *result)
666 {
667 	Elf_Addr *ctors_addrp;
668 	Elf_Size *ctors_sizep;
669 	caddr_t modptr, baseptr, sizeptr, dynptr;
670 	char *type;
671 	elf_file_t ef;
672 	linker_file_t lf;
673 	int error;
674 	vm_offset_t dp;
675 
676 	/* Look to see if we have the file preloaded */
677 	modptr = preload_search_by_name(filename);
678 	if (modptr == NULL)
679 		return (ENOENT);
680 
681 	type = (char *)preload_search_info(modptr, MODINFO_TYPE);
682 	baseptr = preload_search_info(modptr, MODINFO_ADDR);
683 	sizeptr = preload_search_info(modptr, MODINFO_SIZE);
684 	dynptr = preload_search_info(modptr,
685 	    MODINFO_METADATA | MODINFOMD_DYNAMIC);
686 	if (type == NULL ||
687 	    (strcmp(type, "elf" __XSTRING(__ELF_WORD_SIZE) " module") != 0 &&
688 	     strcmp(type, "elf module") != 0))
689 		return (EFTYPE);
690 	if (baseptr == NULL || sizeptr == NULL || dynptr == NULL)
691 		return (EINVAL);
692 
693 	lf = linker_make_file(filename, &link_elf_class);
694 	if (lf == NULL)
695 		return (ENOMEM);
696 
697 	ef = (elf_file_t) lf;
698 	ef->preloaded = 1;
699 	ef->modptr = modptr;
700 	ef->address = *(caddr_t *)baseptr;
701 #ifdef SPARSE_MAPPING
702 	ef->object = 0;
703 #endif
704 	dp = (vm_offset_t)ef->address + *(vm_offset_t *)dynptr;
705 	ef->dynamic = (Elf_Dyn *)dp;
706 	lf->address = ef->address;
707 	lf->size = *(size_t *)sizeptr;
708 
709 	ctors_addrp = (Elf_Addr *)preload_search_info(modptr,
710 	    MODINFO_METADATA | MODINFOMD_CTORS_ADDR);
711 	ctors_sizep = (Elf_Size *)preload_search_info(modptr,
712 	    MODINFO_METADATA | MODINFOMD_CTORS_SIZE);
713 	if (ctors_addrp != NULL && ctors_sizep != NULL) {
714 		lf->ctors_addr = ef->address + *ctors_addrp;
715 		lf->ctors_size = *ctors_sizep;
716 	}
717 
718 	error = parse_dynamic(ef);
719 	if (error == 0)
720 		error = parse_dpcpu(ef);
721 #ifdef VIMAGE
722 	if (error == 0)
723 		error = parse_vnet(ef);
724 #endif
725 	if (error != 0) {
726 		linker_file_unload(lf, LINKER_UNLOAD_FORCE);
727 		return (error);
728 	}
729 	link_elf_reloc_local(lf);
730 	*result = lf;
731 	return (0);
732 }
733 
734 static int
735 link_elf_link_preload_finish(linker_file_t lf)
736 {
737 	elf_file_t ef;
738 	int error;
739 
740 	ef = (elf_file_t) lf;
741 	error = relocate_file(ef);
742 	if (error != 0)
743 		return (error);
744 	(void)link_elf_preload_parse_symbols(ef);
745 
746 	return (link_elf_link_common_finish(lf));
747 }
748 
749 static int
750 link_elf_load_file(linker_class_t cls, const char* filename,
751     linker_file_t* result)
752 {
753 	struct nameidata nd;
754 	struct thread* td = curthread;	/* XXX */
755 	Elf_Ehdr *hdr;
756 	caddr_t firstpage;
757 	int nbytes, i;
758 	Elf_Phdr *phdr;
759 	Elf_Phdr *phlimit;
760 	Elf_Phdr *segs[MAXSEGS];
761 	int nsegs;
762 	Elf_Phdr *phdyn;
763 	Elf_Phdr *phphdr;
764 	caddr_t mapbase;
765 	size_t mapsize;
766 	Elf_Off base_offset;
767 	Elf_Addr base_vaddr;
768 	Elf_Addr base_vlimit;
769 	int error = 0;
770 	ssize_t resid;
771 	int flags;
772 	elf_file_t ef;
773 	linker_file_t lf;
774 	Elf_Shdr *shdr;
775 	int symtabindex;
776 	int symstrindex;
777 	int shstrindex;
778 	int symcnt;
779 	int strcnt;
780 	char *shstrs;
781 
782 	shdr = NULL;
783 	lf = NULL;
784 	shstrs = NULL;
785 
786 	NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, filename, td);
787 	flags = FREAD;
788 	error = vn_open(&nd, &flags, 0, NULL);
789 	if (error != 0)
790 		return (error);
791 	NDFREE(&nd, NDF_ONLY_PNBUF);
792 	if (nd.ni_vp->v_type != VREG) {
793 		error = ENOEXEC;
794 		firstpage = NULL;
795 		goto out;
796 	}
797 #ifdef MAC
798 	error = mac_kld_check_load(curthread->td_ucred, nd.ni_vp);
799 	if (error != 0) {
800 		firstpage = NULL;
801 		goto out;
802 	}
803 #endif
804 
805 	/*
806 	 * Read the elf header from the file.
807 	 */
808 	firstpage = malloc(PAGE_SIZE, M_LINKER, M_WAITOK);
809 	hdr = (Elf_Ehdr *)firstpage;
810 	error = vn_rdwr(UIO_READ, nd.ni_vp, firstpage, PAGE_SIZE, 0,
811 	    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred, NOCRED,
812 	    &resid, td);
813 	nbytes = PAGE_SIZE - resid;
814 	if (error != 0)
815 		goto out;
816 
817 	if (!IS_ELF(*hdr)) {
818 		error = ENOEXEC;
819 		goto out;
820 	}
821 
822 	if (hdr->e_ident[EI_CLASS] != ELF_TARG_CLASS ||
823 	    hdr->e_ident[EI_DATA] != ELF_TARG_DATA) {
824 		link_elf_error(filename, "Unsupported file layout");
825 		error = ENOEXEC;
826 		goto out;
827 	}
828 	if (hdr->e_ident[EI_VERSION] != EV_CURRENT ||
829 	    hdr->e_version != EV_CURRENT) {
830 		link_elf_error(filename, "Unsupported file version");
831 		error = ENOEXEC;
832 		goto out;
833 	}
834 	if (hdr->e_type != ET_EXEC && hdr->e_type != ET_DYN) {
835 		error = ENOSYS;
836 		goto out;
837 	}
838 	if (hdr->e_machine != ELF_TARG_MACH) {
839 		link_elf_error(filename, "Unsupported machine");
840 		error = ENOEXEC;
841 		goto out;
842 	}
843 
844 	/*
845 	 * We rely on the program header being in the first page.
846 	 * This is not strictly required by the ABI specification, but
847 	 * it seems to always true in practice.  And, it simplifies
848 	 * things considerably.
849 	 */
850 	if (!((hdr->e_phentsize == sizeof(Elf_Phdr)) &&
851 	      (hdr->e_phoff + hdr->e_phnum*sizeof(Elf_Phdr) <= PAGE_SIZE) &&
852 	      (hdr->e_phoff + hdr->e_phnum*sizeof(Elf_Phdr) <= nbytes)))
853 		link_elf_error(filename, "Unreadable program headers");
854 
855 	/*
856 	 * Scan the program header entries, and save key information.
857 	 *
858 	 * We rely on there being exactly two load segments, text and data,
859 	 * in that order.
860 	 */
861 	phdr = (Elf_Phdr *) (firstpage + hdr->e_phoff);
862 	phlimit = phdr + hdr->e_phnum;
863 	nsegs = 0;
864 	phdyn = NULL;
865 	phphdr = NULL;
866 	while (phdr < phlimit) {
867 		switch (phdr->p_type) {
868 		case PT_LOAD:
869 			if (nsegs == MAXSEGS) {
870 				link_elf_error(filename, "Too many sections");
871 				error = ENOEXEC;
872 				goto out;
873 			}
874 			/*
875 			 * XXX: We just trust they come in right order ??
876 			 */
877 			segs[nsegs] = phdr;
878 			++nsegs;
879 			break;
880 
881 		case PT_PHDR:
882 			phphdr = phdr;
883 			break;
884 
885 		case PT_DYNAMIC:
886 			phdyn = phdr;
887 			break;
888 
889 		case PT_INTERP:
890 			error = ENOSYS;
891 			goto out;
892 		}
893 
894 		++phdr;
895 	}
896 	if (phdyn == NULL) {
897 		link_elf_error(filename, "Object is not dynamically-linked");
898 		error = ENOEXEC;
899 		goto out;
900 	}
901 	if (nsegs == 0) {
902 		link_elf_error(filename, "No sections");
903 		error = ENOEXEC;
904 		goto out;
905 	}
906 
907 	/*
908 	 * Allocate the entire address space of the object, to stake
909 	 * out our contiguous region, and to establish the base
910 	 * address for relocation.
911 	 */
912 	base_offset = trunc_page(segs[0]->p_offset);
913 	base_vaddr = trunc_page(segs[0]->p_vaddr);
914 	base_vlimit = round_page(segs[nsegs - 1]->p_vaddr +
915 	    segs[nsegs - 1]->p_memsz);
916 	mapsize = base_vlimit - base_vaddr;
917 
918 	lf = linker_make_file(filename, &link_elf_class);
919 	if (lf == NULL) {
920 		error = ENOMEM;
921 		goto out;
922 	}
923 
924 	ef = (elf_file_t) lf;
925 #ifdef SPARSE_MAPPING
926 	ef->object = vm_object_allocate(OBJT_DEFAULT, mapsize >> PAGE_SHIFT);
927 	if (ef->object == NULL) {
928 		error = ENOMEM;
929 		goto out;
930 	}
931 	ef->address = (caddr_t) vm_map_min(kernel_map);
932 	error = vm_map_find(kernel_map, ef->object, 0,
933 	    (vm_offset_t *) &ef->address, mapsize, 0, VMFS_OPTIMAL_SPACE,
934 	    VM_PROT_ALL, VM_PROT_ALL, 0);
935 	if (error != 0) {
936 		vm_object_deallocate(ef->object);
937 		ef->object = 0;
938 		goto out;
939 	}
940 #else
941 	ef->address = malloc(mapsize, M_LINKER, M_WAITOK);
942 #endif
943 	mapbase = ef->address;
944 
945 	/*
946 	 * Read the text and data sections and zero the bss.
947 	 */
948 	for (i = 0; i < nsegs; i++) {
949 		caddr_t segbase = mapbase + segs[i]->p_vaddr - base_vaddr;
950 		error = vn_rdwr(UIO_READ, nd.ni_vp,
951 		    segbase, segs[i]->p_filesz, segs[i]->p_offset,
952 		    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred, NOCRED,
953 		    &resid, td);
954 		if (error != 0)
955 			goto out;
956 		bzero(segbase + segs[i]->p_filesz,
957 		    segs[i]->p_memsz - segs[i]->p_filesz);
958 
959 #ifdef SPARSE_MAPPING
960 		/*
961 		 * Wire down the pages
962 		 */
963 		error = vm_map_wire(kernel_map,
964 		    (vm_offset_t) segbase,
965 		    (vm_offset_t) segbase + segs[i]->p_memsz,
966 		    VM_MAP_WIRE_SYSTEM|VM_MAP_WIRE_NOHOLES);
967 		if (error != KERN_SUCCESS) {
968 			error = ENOMEM;
969 			goto out;
970 		}
971 #endif
972 	}
973 
974 #ifdef GPROF
975 	/* Update profiling information with the new text segment. */
976 	mtx_lock(&Giant);
977 	kmupetext((uintfptr_t)(mapbase + segs[0]->p_vaddr - base_vaddr +
978 	    segs[0]->p_memsz));
979 	mtx_unlock(&Giant);
980 #endif
981 
982 	ef->dynamic = (Elf_Dyn *) (mapbase + phdyn->p_vaddr - base_vaddr);
983 
984 	lf->address = ef->address;
985 	lf->size = mapsize;
986 
987 	error = parse_dynamic(ef);
988 	if (error != 0)
989 		goto out;
990 	error = parse_dpcpu(ef);
991 	if (error != 0)
992 		goto out;
993 #ifdef VIMAGE
994 	error = parse_vnet(ef);
995 	if (error != 0)
996 		goto out;
997 #endif
998 	link_elf_reloc_local(lf);
999 
1000 	VOP_UNLOCK(nd.ni_vp, 0);
1001 	error = linker_load_dependencies(lf);
1002 	vn_lock(nd.ni_vp, LK_EXCLUSIVE | LK_RETRY);
1003 	if (error != 0)
1004 		goto out;
1005 	error = relocate_file(ef);
1006 	if (error != 0)
1007 		goto out;
1008 
1009 	/*
1010 	 * Try and load the symbol table if it's present.  (you can
1011 	 * strip it!)
1012 	 */
1013 	nbytes = hdr->e_shnum * hdr->e_shentsize;
1014 	if (nbytes == 0 || hdr->e_shoff == 0)
1015 		goto nosyms;
1016 	shdr = malloc(nbytes, M_LINKER, M_WAITOK | M_ZERO);
1017 	error = vn_rdwr(UIO_READ, nd.ni_vp,
1018 	    (caddr_t)shdr, nbytes, hdr->e_shoff,
1019 	    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred, NOCRED,
1020 	    &resid, td);
1021 	if (error != 0)
1022 		goto out;
1023 
1024 	/* Read section string table */
1025 	shstrindex = hdr->e_shstrndx;
1026 	if (shstrindex != 0 && shdr[shstrindex].sh_type == SHT_STRTAB &&
1027 	    shdr[shstrindex].sh_size != 0) {
1028 		nbytes = shdr[shstrindex].sh_size;
1029 		shstrs = malloc(nbytes, M_LINKER, M_WAITOK | M_ZERO);
1030 		error = vn_rdwr(UIO_READ, nd.ni_vp, (caddr_t)shstrs, nbytes,
1031 		    shdr[shstrindex].sh_offset, UIO_SYSSPACE, IO_NODELOCKED,
1032 		    td->td_ucred, NOCRED, &resid, td);
1033 		if (error)
1034 			goto out;
1035 	}
1036 
1037 	symtabindex = -1;
1038 	symstrindex = -1;
1039 	for (i = 0; i < hdr->e_shnum; i++) {
1040 		if (shdr[i].sh_type == SHT_SYMTAB) {
1041 			symtabindex = i;
1042 			symstrindex = shdr[i].sh_link;
1043 		} else if (shstrs != NULL && shdr[i].sh_name != 0 &&
1044 		    strcmp(shstrs + shdr[i].sh_name, ".ctors") == 0) {
1045 			/* Record relocated address and size of .ctors. */
1046 			lf->ctors_addr = mapbase + shdr[i].sh_addr - base_vaddr;
1047 			lf->ctors_size = shdr[i].sh_size;
1048 		}
1049 	}
1050 	if (symtabindex < 0 || symstrindex < 0)
1051 		goto nosyms;
1052 
1053 	symcnt = shdr[symtabindex].sh_size;
1054 	ef->symbase = malloc(symcnt, M_LINKER, M_WAITOK);
1055 	strcnt = shdr[symstrindex].sh_size;
1056 	ef->strbase = malloc(strcnt, M_LINKER, M_WAITOK);
1057 
1058 	error = vn_rdwr(UIO_READ, nd.ni_vp,
1059 	    ef->symbase, symcnt, shdr[symtabindex].sh_offset,
1060 	    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred, NOCRED,
1061 	    &resid, td);
1062 	if (error != 0)
1063 		goto out;
1064 	error = vn_rdwr(UIO_READ, nd.ni_vp,
1065 	    ef->strbase, strcnt, shdr[symstrindex].sh_offset,
1066 	    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred, NOCRED,
1067 	    &resid, td);
1068 	if (error != 0)
1069 		goto out;
1070 
1071 	ef->ddbsymcnt = symcnt / sizeof(Elf_Sym);
1072 	ef->ddbsymtab = (const Elf_Sym *)ef->symbase;
1073 	ef->ddbstrcnt = strcnt;
1074 	ef->ddbstrtab = ef->strbase;
1075 
1076 nosyms:
1077 	error = link_elf_link_common_finish(lf);
1078 	if (error != 0)
1079 		goto out;
1080 
1081 	*result = lf;
1082 
1083 out:
1084 	VOP_UNLOCK(nd.ni_vp, 0);
1085 	vn_close(nd.ni_vp, FREAD, td->td_ucred, td);
1086 	if (error != 0 && lf != NULL)
1087 		linker_file_unload(lf, LINKER_UNLOAD_FORCE);
1088 	if (shdr != NULL)
1089 		free(shdr, M_LINKER);
1090 	if (firstpage != NULL)
1091 		free(firstpage, M_LINKER);
1092 	if (shstrs != NULL)
1093 		free(shstrs, M_LINKER);
1094 
1095 	return (error);
1096 }
1097 
1098 Elf_Addr
1099 elf_relocaddr(linker_file_t lf, Elf_Addr x)
1100 {
1101 	elf_file_t ef;
1102 
1103 	ef = (elf_file_t)lf;
1104 	if (x >= ef->pcpu_start && x < ef->pcpu_stop)
1105 		return ((x - ef->pcpu_start) + ef->pcpu_base);
1106 #ifdef VIMAGE
1107 	if (x >= ef->vnet_start && x < ef->vnet_stop)
1108 		return ((x - ef->vnet_start) + ef->vnet_base);
1109 #endif
1110 	return (x);
1111 }
1112 
1113 
1114 static void
1115 link_elf_unload_file(linker_file_t file)
1116 {
1117 	elf_file_t ef = (elf_file_t) file;
1118 
1119 	if (ef->pcpu_base != 0) {
1120 		dpcpu_free((void *)ef->pcpu_base,
1121 		    ef->pcpu_stop - ef->pcpu_start);
1122 		elf_set_delete(&set_pcpu_list, ef->pcpu_start);
1123 	}
1124 #ifdef VIMAGE
1125 	if (ef->vnet_base != 0) {
1126 		vnet_data_free((void *)ef->vnet_base,
1127 		    ef->vnet_stop - ef->vnet_start);
1128 		elf_set_delete(&set_vnet_list, ef->vnet_start);
1129 	}
1130 #endif
1131 #ifdef GDB
1132 	if (ef->gdb.l_ld != NULL) {
1133 		GDB_STATE(RT_DELETE);
1134 		free((void *)(uintptr_t)ef->gdb.l_name, M_LINKER);
1135 		link_elf_delete_gdb(&ef->gdb);
1136 		GDB_STATE(RT_CONSISTENT);
1137 	}
1138 #endif
1139 
1140 	/* Notify MD code that a module is being unloaded. */
1141 	elf_cpu_unload_file(file);
1142 
1143 	if (ef->preloaded) {
1144 		link_elf_unload_preload(file);
1145 		return;
1146 	}
1147 
1148 #ifdef SPARSE_MAPPING
1149 	if (ef->object != NULL) {
1150 		vm_map_remove(kernel_map, (vm_offset_t) ef->address,
1151 		    (vm_offset_t) ef->address
1152 		    + (ef->object->size << PAGE_SHIFT));
1153 	}
1154 #else
1155 	if (ef->address != NULL)
1156 		free(ef->address, M_LINKER);
1157 #endif
1158 	if (ef->symbase != NULL)
1159 		free(ef->symbase, M_LINKER);
1160 	if (ef->strbase != NULL)
1161 		free(ef->strbase, M_LINKER);
1162 	if (ef->ctftab != NULL)
1163 		free(ef->ctftab, M_LINKER);
1164 	if (ef->ctfoff != NULL)
1165 		free(ef->ctfoff, M_LINKER);
1166 	if (ef->typoff != NULL)
1167 		free(ef->typoff, M_LINKER);
1168 }
1169 
1170 static void
1171 link_elf_unload_preload(linker_file_t file)
1172 {
1173 	if (file->filename != NULL)
1174 		preload_delete_name(file->filename);
1175 }
1176 
1177 static const char *
1178 symbol_name(elf_file_t ef, Elf_Size r_info)
1179 {
1180 	const Elf_Sym *ref;
1181 
1182 	if (ELF_R_SYM(r_info)) {
1183 		ref = ef->symtab + ELF_R_SYM(r_info);
1184 		return (ef->strtab + ref->st_name);
1185 	}
1186 	return (NULL);
1187 }
1188 
1189 static int
1190 relocate_file(elf_file_t ef)
1191 {
1192 	const Elf_Rel *rellim;
1193 	const Elf_Rel *rel;
1194 	const Elf_Rela *relalim;
1195 	const Elf_Rela *rela;
1196 	const char *symname;
1197 
1198 	/* Perform relocations without addend if there are any: */
1199 	rel = ef->rel;
1200 	if (rel != NULL) {
1201 		rellim = (const Elf_Rel *)
1202 		    ((const char *)ef->rel + ef->relsize);
1203 		while (rel < rellim) {
1204 			if (elf_reloc(&ef->lf, (Elf_Addr)ef->address, rel,
1205 			    ELF_RELOC_REL, elf_lookup)) {
1206 				symname = symbol_name(ef, rel->r_info);
1207 				printf("link_elf: symbol %s undefined\n", symname);
1208 				return (ENOENT);
1209 			}
1210 			rel++;
1211 		}
1212 	}
1213 
1214 	/* Perform relocations with addend if there are any: */
1215 	rela = ef->rela;
1216 	if (rela != NULL) {
1217 		relalim = (const Elf_Rela *)
1218 		    ((const char *)ef->rela + ef->relasize);
1219 		while (rela < relalim) {
1220 			if (elf_reloc(&ef->lf, (Elf_Addr)ef->address, rela,
1221 			    ELF_RELOC_RELA, elf_lookup)) {
1222 				symname = symbol_name(ef, rela->r_info);
1223 				printf("link_elf: symbol %s undefined\n",
1224 				    symname);
1225 				return (ENOENT);
1226 			}
1227 			rela++;
1228 		}
1229 	}
1230 
1231 	/* Perform PLT relocations without addend if there are any: */
1232 	rel = ef->pltrel;
1233 	if (rel != NULL) {
1234 		rellim = (const Elf_Rel *)
1235 		    ((const char *)ef->pltrel + ef->pltrelsize);
1236 		while (rel < rellim) {
1237 			if (elf_reloc(&ef->lf, (Elf_Addr)ef->address, rel,
1238 			    ELF_RELOC_REL, elf_lookup)) {
1239 				symname = symbol_name(ef, rel->r_info);
1240 				printf("link_elf: symbol %s undefined\n",
1241 				    symname);
1242 				return (ENOENT);
1243 			}
1244 			rel++;
1245 		}
1246 	}
1247 
1248 	/* Perform relocations with addend if there are any: */
1249 	rela = ef->pltrela;
1250 	if (rela != NULL) {
1251 		relalim = (const Elf_Rela *)
1252 		    ((const char *)ef->pltrela + ef->pltrelasize);
1253 		while (rela < relalim) {
1254 			if (elf_reloc(&ef->lf, (Elf_Addr)ef->address, rela,
1255 			    ELF_RELOC_RELA, elf_lookup)) {
1256 				symname = symbol_name(ef, rela->r_info);
1257 				printf("link_elf: symbol %s undefined\n",
1258 				    symname);
1259 				return (ENOENT);
1260 			}
1261 			rela++;
1262 		}
1263 	}
1264 
1265 	return (0);
1266 }
1267 
1268 /*
1269  * Hash function for symbol table lookup.  Don't even think about changing
1270  * this.  It is specified by the System V ABI.
1271  */
1272 static unsigned long
1273 elf_hash(const char *name)
1274 {
1275 	const unsigned char *p = (const unsigned char *) name;
1276 	unsigned long h = 0;
1277 	unsigned long g;
1278 
1279 	while (*p != '\0') {
1280 		h = (h << 4) + *p++;
1281 		if ((g = h & 0xf0000000) != 0)
1282 			h ^= g >> 24;
1283 		h &= ~g;
1284 	}
1285 	return (h);
1286 }
1287 
1288 static int
1289 link_elf_lookup_symbol(linker_file_t lf, const char* name, c_linker_sym_t* sym)
1290 {
1291 	elf_file_t ef = (elf_file_t) lf;
1292 	unsigned long symnum;
1293 	const Elf_Sym* symp;
1294 	const char *strp;
1295 	unsigned long hash;
1296 	int i;
1297 
1298 	/* If we don't have a hash, bail. */
1299 	if (ef->buckets == NULL || ef->nbuckets == 0) {
1300 		printf("link_elf_lookup_symbol: missing symbol hash table\n");
1301 		return (ENOENT);
1302 	}
1303 
1304 	/* First, search hashed global symbols */
1305 	hash = elf_hash(name);
1306 	symnum = ef->buckets[hash % ef->nbuckets];
1307 
1308 	while (symnum != STN_UNDEF) {
1309 		if (symnum >= ef->nchains) {
1310 			printf("%s: corrupt symbol table\n", __func__);
1311 			return (ENOENT);
1312 		}
1313 
1314 		symp = ef->symtab + symnum;
1315 		if (symp->st_name == 0) {
1316 			printf("%s: corrupt symbol table\n", __func__);
1317 			return (ENOENT);
1318 		}
1319 
1320 		strp = ef->strtab + symp->st_name;
1321 
1322 		if (strcmp(name, strp) == 0) {
1323 			if (symp->st_shndx != SHN_UNDEF ||
1324 			    (symp->st_value != 0 &&
1325 			     ELF_ST_TYPE(symp->st_info) == STT_FUNC)) {
1326 				*sym = (c_linker_sym_t) symp;
1327 				return (0);
1328 			}
1329 			return (ENOENT);
1330 		}
1331 
1332 		symnum = ef->chains[symnum];
1333 	}
1334 
1335 	/* If we have not found it, look at the full table (if loaded) */
1336 	if (ef->symtab == ef->ddbsymtab)
1337 		return (ENOENT);
1338 
1339 	/* Exhaustive search */
1340 	for (i = 0, symp = ef->ddbsymtab; i < ef->ddbsymcnt; i++, symp++) {
1341 		strp = ef->ddbstrtab + symp->st_name;
1342 		if (strcmp(name, strp) == 0) {
1343 			if (symp->st_shndx != SHN_UNDEF ||
1344 			    (symp->st_value != 0 &&
1345 			     ELF_ST_TYPE(symp->st_info) == STT_FUNC)) {
1346 				*sym = (c_linker_sym_t) symp;
1347 				return (0);
1348 			}
1349 			return (ENOENT);
1350 		}
1351 	}
1352 
1353 	return (ENOENT);
1354 }
1355 
1356 static int
1357 link_elf_symbol_values(linker_file_t lf, c_linker_sym_t sym,
1358     linker_symval_t *symval)
1359 {
1360 	elf_file_t ef = (elf_file_t) lf;
1361 	const Elf_Sym* es = (const Elf_Sym*) sym;
1362 
1363 	if (es >= ef->symtab && es < (ef->symtab + ef->nchains)) {
1364 		symval->name = ef->strtab + es->st_name;
1365 		symval->value = (caddr_t) ef->address + es->st_value;
1366 		symval->size = es->st_size;
1367 		return (0);
1368 	}
1369 	if (ef->symtab == ef->ddbsymtab)
1370 		return (ENOENT);
1371 	if (es >= ef->ddbsymtab && es < (ef->ddbsymtab + ef->ddbsymcnt)) {
1372 		symval->name = ef->ddbstrtab + es->st_name;
1373 		symval->value = (caddr_t) ef->address + es->st_value;
1374 		symval->size = es->st_size;
1375 		return (0);
1376 	}
1377 	return (ENOENT);
1378 }
1379 
1380 static int
1381 link_elf_search_symbol(linker_file_t lf, caddr_t value,
1382     c_linker_sym_t *sym, long *diffp)
1383 {
1384 	elf_file_t ef = (elf_file_t) lf;
1385 	u_long off = (uintptr_t) (void *) value;
1386 	u_long diff = off;
1387 	u_long st_value;
1388 	const Elf_Sym* es;
1389 	const Elf_Sym* best = 0;
1390 	int i;
1391 
1392 	for (i = 0, es = ef->ddbsymtab; i < ef->ddbsymcnt; i++, es++) {
1393 		if (es->st_name == 0)
1394 			continue;
1395 		st_value = es->st_value + (uintptr_t) (void *) ef->address;
1396 		if (off >= st_value) {
1397 			if (off - st_value < diff) {
1398 				diff = off - st_value;
1399 				best = es;
1400 				if (diff == 0)
1401 					break;
1402 			} else if (off - st_value == diff) {
1403 				best = es;
1404 			}
1405 		}
1406 	}
1407 	if (best == 0)
1408 		*diffp = off;
1409 	else
1410 		*diffp = diff;
1411 	*sym = (c_linker_sym_t) best;
1412 
1413 	return (0);
1414 }
1415 
1416 /*
1417  * Look up a linker set on an ELF system.
1418  */
1419 static int
1420 link_elf_lookup_set(linker_file_t lf, const char *name,
1421     void ***startp, void ***stopp, int *countp)
1422 {
1423 	c_linker_sym_t sym;
1424 	linker_symval_t symval;
1425 	char *setsym;
1426 	void **start, **stop;
1427 	int len, error = 0, count;
1428 
1429 	len = strlen(name) + sizeof("__start_set_"); /* sizeof includes \0 */
1430 	setsym = malloc(len, M_LINKER, M_WAITOK);
1431 
1432 	/* get address of first entry */
1433 	snprintf(setsym, len, "%s%s", "__start_set_", name);
1434 	error = link_elf_lookup_symbol(lf, setsym, &sym);
1435 	if (error != 0)
1436 		goto out;
1437 	link_elf_symbol_values(lf, sym, &symval);
1438 	if (symval.value == 0) {
1439 		error = ESRCH;
1440 		goto out;
1441 	}
1442 	start = (void **)symval.value;
1443 
1444 	/* get address of last entry */
1445 	snprintf(setsym, len, "%s%s", "__stop_set_", name);
1446 	error = link_elf_lookup_symbol(lf, setsym, &sym);
1447 	if (error != 0)
1448 		goto out;
1449 	link_elf_symbol_values(lf, sym, &symval);
1450 	if (symval.value == 0) {
1451 		error = ESRCH;
1452 		goto out;
1453 	}
1454 	stop = (void **)symval.value;
1455 
1456 	/* and the number of entries */
1457 	count = stop - start;
1458 
1459 	/* and copy out */
1460 	if (startp != NULL)
1461 		*startp = start;
1462 	if (stopp != NULL)
1463 		*stopp = stop;
1464 	if (countp != NULL)
1465 		*countp = count;
1466 
1467 out:
1468 	free(setsym, M_LINKER);
1469 	return (error);
1470 }
1471 
1472 static int
1473 link_elf_each_function_name(linker_file_t file,
1474   int (*callback)(const char *, void *), void *opaque)
1475 {
1476 	elf_file_t ef = (elf_file_t)file;
1477 	const Elf_Sym *symp;
1478 	int i, error;
1479 
1480 	/* Exhaustive search */
1481 	for (i = 0, symp = ef->ddbsymtab; i < ef->ddbsymcnt; i++, symp++) {
1482 		if (symp->st_value != 0 &&
1483 		    ELF_ST_TYPE(symp->st_info) == STT_FUNC) {
1484 			error = callback(ef->ddbstrtab + symp->st_name, opaque);
1485 			if (error != 0)
1486 				return (error);
1487 		}
1488 	}
1489 	return (0);
1490 }
1491 
1492 static int
1493 link_elf_each_function_nameval(linker_file_t file,
1494     linker_function_nameval_callback_t callback, void *opaque)
1495 {
1496 	linker_symval_t symval;
1497 	elf_file_t ef = (elf_file_t)file;
1498 	const Elf_Sym* symp;
1499 	int i, error;
1500 
1501 	/* Exhaustive search */
1502 	for (i = 0, symp = ef->ddbsymtab; i < ef->ddbsymcnt; i++, symp++) {
1503 		if (symp->st_value != 0 &&
1504 		    ELF_ST_TYPE(symp->st_info) == STT_FUNC) {
1505 			error = link_elf_symbol_values(file,
1506 			    (c_linker_sym_t) symp, &symval);
1507 			if (error != 0)
1508 				return (error);
1509 			error = callback(file, i, &symval, opaque);
1510 			if (error != 0)
1511 				return (error);
1512 		}
1513 	}
1514 	return (0);
1515 }
1516 
1517 const Elf_Sym *
1518 elf_get_sym(linker_file_t lf, Elf_Size symidx)
1519 {
1520 	elf_file_t ef = (elf_file_t)lf;
1521 
1522 	if (symidx >= ef->nchains)
1523 		return (NULL);
1524 	return (ef->symtab + symidx);
1525 }
1526 
1527 const char *
1528 elf_get_symname(linker_file_t lf, Elf_Size symidx)
1529 {
1530 	elf_file_t ef = (elf_file_t)lf;
1531 	const Elf_Sym *sym;
1532 
1533 	if (symidx >= ef->nchains)
1534 		return (NULL);
1535 	sym = ef->symtab + symidx;
1536 	return (ef->strtab + sym->st_name);
1537 }
1538 
1539 /*
1540  * Symbol lookup function that can be used when the symbol index is known (ie
1541  * in relocations). It uses the symbol index instead of doing a fully fledged
1542  * hash table based lookup when such is valid. For example for local symbols.
1543  * This is not only more efficient, it's also more correct. It's not always
1544  * the case that the symbol can be found through the hash table.
1545  */
1546 static Elf_Addr
1547 elf_lookup(linker_file_t lf, Elf_Size symidx, int deps)
1548 {
1549 	elf_file_t ef = (elf_file_t)lf;
1550 	const Elf_Sym *sym;
1551 	const char *symbol;
1552 	Elf_Addr addr, start, base;
1553 
1554 	/* Don't even try to lookup the symbol if the index is bogus. */
1555 	if (symidx >= ef->nchains)
1556 		return (0);
1557 
1558 	sym = ef->symtab + symidx;
1559 
1560 	/*
1561 	 * Don't do a full lookup when the symbol is local. It may even
1562 	 * fail because it may not be found through the hash table.
1563 	 */
1564 	if (ELF_ST_BIND(sym->st_info) == STB_LOCAL) {
1565 		/* Force lookup failure when we have an insanity. */
1566 		if (sym->st_shndx == SHN_UNDEF || sym->st_value == 0)
1567 			return (0);
1568 		return ((Elf_Addr)ef->address + sym->st_value);
1569 	}
1570 
1571 	/*
1572 	 * XXX we can avoid doing a hash table based lookup for global
1573 	 * symbols as well. This however is not always valid, so we'll
1574 	 * just do it the hard way for now. Performance tweaks can
1575 	 * always be added.
1576 	 */
1577 
1578 	symbol = ef->strtab + sym->st_name;
1579 
1580 	/* Force a lookup failure if the symbol name is bogus. */
1581 	if (*symbol == 0)
1582 		return (0);
1583 
1584 	addr = ((Elf_Addr)linker_file_lookup_symbol(lf, symbol, deps));
1585 
1586 	if (elf_set_find(&set_pcpu_list, addr, &start, &base))
1587 		addr = addr - start + base;
1588 #ifdef VIMAGE
1589 	else if (elf_set_find(&set_vnet_list, addr, &start, &base))
1590 		addr = addr - start + base;
1591 #endif
1592 	return addr;
1593 }
1594 
1595 static void
1596 link_elf_reloc_local(linker_file_t lf)
1597 {
1598 	const Elf_Rel *rellim;
1599 	const Elf_Rel *rel;
1600 	const Elf_Rela *relalim;
1601 	const Elf_Rela *rela;
1602 	elf_file_t ef = (elf_file_t)lf;
1603 
1604 	/* Perform relocations without addend if there are any: */
1605 	if ((rel = ef->rel) != NULL) {
1606 		rellim = (const Elf_Rel *)((const char *)ef->rel + ef->relsize);
1607 		while (rel < rellim) {
1608 			elf_reloc_local(lf, (Elf_Addr)ef->address, rel,
1609 			    ELF_RELOC_REL, elf_lookup);
1610 			rel++;
1611 		}
1612 	}
1613 
1614 	/* Perform relocations with addend if there are any: */
1615 	if ((rela = ef->rela) != NULL) {
1616 		relalim = (const Elf_Rela *)
1617 		    ((const char *)ef->rela + ef->relasize);
1618 		while (rela < relalim) {
1619 			elf_reloc_local(lf, (Elf_Addr)ef->address, rela,
1620 			    ELF_RELOC_RELA, elf_lookup);
1621 			rela++;
1622 		}
1623 	}
1624 }
1625 
1626 static long
1627 link_elf_symtab_get(linker_file_t lf, const Elf_Sym **symtab)
1628 {
1629 	elf_file_t ef = (elf_file_t)lf;
1630 
1631 	*symtab = ef->ddbsymtab;
1632 
1633 	if (*symtab == NULL)
1634 		return (0);
1635 
1636 	return (ef->ddbsymcnt);
1637 }
1638 
1639 static long
1640 link_elf_strtab_get(linker_file_t lf, caddr_t *strtab)
1641 {
1642 	elf_file_t ef = (elf_file_t)lf;
1643 
1644 	*strtab = ef->ddbstrtab;
1645 
1646 	if (*strtab == NULL)
1647 		return (0);
1648 
1649 	return (ef->ddbstrcnt);
1650 }
1651