xref: /freebsd/sys/kern/link_elf.c (revision c4f6a2a9e1b1879b618c436ab4f56ff75c73a0f5)
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  * $FreeBSD$
27  */
28 
29 #include "opt_ddb.h"
30 
31 #include <sys/param.h>
32 #include <sys/systm.h>
33 #include <sys/kernel.h>
34 #include <sys/lock.h>
35 #include <sys/malloc.h>
36 #include <sys/mutex.h>
37 #include <sys/proc.h>
38 #include <sys/namei.h>
39 #include <sys/fcntl.h>
40 #include <sys/vnode.h>
41 #include <sys/linker.h>
42 
43 #include <machine/elf.h>
44 #ifdef GPROF
45 #include <machine/profile.h>
46 #endif
47 
48 #include <vm/vm.h>
49 #include <vm/vm_param.h>
50 #ifdef SPARSE_MAPPING
51 #include <vm/vm_object.h>
52 #include <vm/vm_kern.h>
53 #include <vm/vm_extern.h>
54 #endif
55 #include <vm/pmap.h>
56 #include <vm/vm_map.h>
57 
58 #ifdef __AOUT__
59 #include <nlist.h>
60 #endif
61 #include <link.h>
62 
63 #include "linker_if.h"
64 
65 typedef struct elf_file {
66     struct linker_file	lf;		/* Common fields */
67     int			preloaded;	/* Was file pre-loaded */
68     caddr_t		address;	/* Relocation address */
69 #ifdef SPARSE_MAPPING
70     vm_object_t		object;		/* VM object to hold file pages */
71 #endif
72     Elf_Dyn*		dynamic;	/* Symbol table etc. */
73     Elf_Hashelt		nbuckets;	/* DT_HASH info */
74     Elf_Hashelt		nchains;
75     const Elf_Hashelt*	buckets;
76     const Elf_Hashelt*	chains;
77     caddr_t		hash;
78     caddr_t		strtab;		/* DT_STRTAB */
79     int			strsz;		/* DT_STRSZ */
80     const Elf_Sym*	symtab;		/* DT_SYMTAB */
81     Elf_Addr*		got;		/* DT_PLTGOT */
82     const Elf_Rel*	pltrel;		/* DT_JMPREL */
83     int			pltrelsize;	/* DT_PLTRELSZ */
84     const Elf_Rela*	pltrela;	/* DT_JMPREL */
85     int			pltrelasize;	/* DT_PLTRELSZ */
86     const Elf_Rel*	rel;		/* DT_REL */
87     int			relsize;	/* DT_RELSZ */
88     const Elf_Rela*	rela;		/* DT_RELA */
89     int			relasize;	/* DT_RELASZ */
90     caddr_t		modptr;
91     const Elf_Sym*	ddbsymtab;	/* The symbol table we are using */
92     long		ddbsymcnt;	/* Number of symbols */
93     caddr_t		ddbstrtab;	/* String table */
94     long		ddbstrcnt;	/* number of bytes in string table */
95     caddr_t		symbase;	/* malloc'ed symbold base */
96     caddr_t		strbase;	/* malloc'ed string base */
97 #ifdef DDB
98     struct link_map	gdb;		/* hooks for gdb */
99 #endif
100 } *elf_file_t;
101 
102 static int	link_elf_link_preload(linker_class_t cls,
103 				      const char*, linker_file_t*);
104 static int	link_elf_link_preload_finish(linker_file_t);
105 static int	link_elf_load_file(linker_class_t, const char*, linker_file_t*);
106 static int	link_elf_lookup_symbol(linker_file_t, const char*,
107 				       c_linker_sym_t*);
108 static int	link_elf_symbol_values(linker_file_t, c_linker_sym_t, linker_symval_t*);
109 static int	link_elf_search_symbol(linker_file_t, caddr_t value,
110 				       c_linker_sym_t* sym, long* diffp);
111 
112 static void	link_elf_unload_file(linker_file_t);
113 static void	link_elf_unload_preload(linker_file_t);
114 static int	link_elf_lookup_set(linker_file_t, const char *,
115 				    void ***, void ***, int *);
116 static int	link_elf_each_function_name(linker_file_t,
117 				int (*)(const char *, void *),
118 				void *);
119 
120 static kobj_method_t link_elf_methods[] = {
121     KOBJMETHOD(linker_lookup_symbol,	link_elf_lookup_symbol),
122     KOBJMETHOD(linker_symbol_values,	link_elf_symbol_values),
123     KOBJMETHOD(linker_search_symbol,	link_elf_search_symbol),
124     KOBJMETHOD(linker_unload,		link_elf_unload_file),
125     KOBJMETHOD(linker_load_file,	link_elf_load_file),
126     KOBJMETHOD(linker_link_preload,	link_elf_link_preload),
127     KOBJMETHOD(linker_link_preload_finish, link_elf_link_preload_finish),
128     KOBJMETHOD(linker_lookup_set,	link_elf_lookup_set),
129     KOBJMETHOD(linker_each_function_name, link_elf_each_function_name),
130     { 0, 0 }
131 };
132 
133 static struct linker_class link_elf_class = {
134 #if ELF_TARG_CLASS == ELFCLASS32
135     "elf32",
136 #else
137     "elf64",
138 #endif
139     link_elf_methods, sizeof(struct elf_file)
140 };
141 
142 static int		parse_dynamic(elf_file_t ef);
143 static int		relocate_file(elf_file_t ef);
144 static int		link_elf_preload_parse_symbols(elf_file_t ef);
145 
146 #ifdef DDB
147 static void		r_debug_state(struct r_debug *dummy_one,
148 				      struct link_map *dummy_two);
149 
150 /*
151  * A list of loaded modules for GDB to use for loading symbols.
152  */
153 struct r_debug r_debug;
154 
155 #define GDB_STATE(s)	r_debug.r_state = s; r_debug_state(NULL, NULL);
156 
157 /*
158  * Function for the debugger to set a breakpoint on to gain control.
159  */
160 void
161 r_debug_state(struct r_debug *dummy_one __unused,
162 	      struct link_map *dummy_two __unused)
163 {
164 }
165 
166 #endif
167 
168 #ifdef __ia64__
169 Elf_Addr link_elf_get_gp(linker_file_t);
170 #endif
171 
172 /*
173  * The kernel symbol table starts here.
174  */
175 extern struct _dynamic _DYNAMIC;
176 
177 static void
178 link_elf_init(void* arg)
179 {
180 #ifdef __ELF__
181     Elf_Dyn	*dp;
182     caddr_t	modptr, baseptr, sizeptr;
183     elf_file_t	ef;
184     char	*modname;
185 #ifdef DDB
186     char *newfilename;
187 #endif
188 #endif
189 
190     linker_add_class(&link_elf_class);
191 
192 #ifdef __ELF__
193     dp = (Elf_Dyn*) &_DYNAMIC;
194     modname = NULL;
195     modptr = preload_search_by_type("elf kernel");
196     if (modptr)
197 	modname = (char *)preload_search_info(modptr, MODINFO_NAME);
198     if (modname == NULL)
199 	modname = "kernel";
200     linker_kernel_file = linker_make_file(modname, &link_elf_class);
201     if (linker_kernel_file == NULL)
202 	panic("link_elf_init: Can't create linker structures for kernel");
203 
204     ef = (elf_file_t) linker_kernel_file;
205     ef->preloaded = 1;
206     ef->address = 0;
207 #ifdef SPARSE_MAPPING
208     ef->object = 0;
209 #endif
210     ef->dynamic = dp;
211 
212     if (dp)
213 	parse_dynamic(ef);
214     linker_kernel_file->address = (caddr_t) KERNBASE;
215     linker_kernel_file->size = -(intptr_t)linker_kernel_file->address;
216 
217     if (modptr) {
218 	ef->modptr = modptr;
219 	baseptr = preload_search_info(modptr, MODINFO_ADDR);
220 	if (baseptr)
221 	    linker_kernel_file->address = *(caddr_t *)baseptr;
222 	sizeptr = preload_search_info(modptr, MODINFO_SIZE);
223 	if (sizeptr)
224 	    linker_kernel_file->size = *(size_t *)sizeptr;
225     }
226     (void)link_elf_preload_parse_symbols(ef);
227 
228 #ifdef DDB
229     ef->gdb.l_addr = linker_kernel_file->address;
230     newfilename = malloc(strlen(modname) + 1, M_LINKER, M_WAITOK);
231     strcpy(newfilename, modname);
232     ef->gdb.l_name = newfilename;
233     ef->gdb.l_ld = dp;
234     ef->gdb.l_prev = 0;
235     ef->gdb.l_next = 0;
236 
237     r_debug.r_map = &ef->gdb;
238     r_debug.r_brk = r_debug_state;
239     r_debug.r_state = RT_CONSISTENT;
240 
241     r_debug_state(NULL, NULL);	/* say hello to gdb! */
242 #endif
243 
244 #endif
245 }
246 
247 SYSINIT(link_elf, SI_SUB_KLD, SI_ORDER_SECOND, link_elf_init, 0);
248 
249 static int
250 link_elf_preload_parse_symbols(elf_file_t ef)
251 {
252     caddr_t	pointer;
253     caddr_t	ssym, esym, base;
254     caddr_t	strtab;
255     int		strcnt;
256     Elf_Sym*	symtab;
257     int		symcnt;
258 
259     if (ef->modptr == NULL)
260 	return 0;
261     pointer = preload_search_info(ef->modptr, MODINFO_METADATA|MODINFOMD_SSYM);
262     if (pointer == NULL)
263 	return 0;
264     ssym = *(caddr_t *)pointer;
265     pointer = preload_search_info(ef->modptr, MODINFO_METADATA|MODINFOMD_ESYM);
266     if (pointer == NULL)
267 	return 0;
268     esym = *(caddr_t *)pointer;
269 
270     base = ssym;
271 
272     symcnt = *(long *)base;
273     base += sizeof(long);
274     symtab = (Elf_Sym *)base;
275     base += roundup(symcnt, sizeof(long));
276 
277     if (base > esym || base < ssym) {
278 	printf("Symbols are corrupt!\n");
279 	return EINVAL;
280     }
281 
282     strcnt = *(long *)base;
283     base += sizeof(long);
284     strtab = base;
285     base += roundup(strcnt, sizeof(long));
286 
287     if (base > esym || base < ssym) {
288 	printf("Symbols are corrupt!\n");
289 	return EINVAL;
290     }
291 
292     ef->ddbsymtab = symtab;
293     ef->ddbsymcnt = symcnt / sizeof(Elf_Sym);
294     ef->ddbstrtab = strtab;
295     ef->ddbstrcnt = strcnt;
296 
297     return 0;
298 }
299 
300 static int
301 parse_dynamic(elf_file_t ef)
302 {
303     Elf_Dyn *dp;
304     int plttype = DT_REL;
305 
306     for (dp = ef->dynamic; dp->d_tag != DT_NULL; dp++) {
307 	switch (dp->d_tag) {
308 	case DT_HASH:
309 	{
310 	    /* From src/libexec/rtld-elf/rtld.c */
311 	    const Elf_Hashelt *hashtab = (const Elf_Hashelt *)
312 		(ef->address + dp->d_un.d_ptr);
313 	    ef->nbuckets = hashtab[0];
314 	    ef->nchains = hashtab[1];
315 	    ef->buckets = hashtab + 2;
316 	    ef->chains = ef->buckets + ef->nbuckets;
317 	    break;
318 	}
319 	case DT_STRTAB:
320 	    ef->strtab = (caddr_t) (ef->address + dp->d_un.d_ptr);
321 	    break;
322 	case DT_STRSZ:
323 	    ef->strsz = dp->d_un.d_val;
324 	    break;
325 	case DT_SYMTAB:
326 	    ef->symtab = (Elf_Sym*) (ef->address + dp->d_un.d_ptr);
327 	    break;
328 	case DT_SYMENT:
329 	    if (dp->d_un.d_val != sizeof(Elf_Sym))
330 		return ENOEXEC;
331 	    break;
332 	case DT_PLTGOT:
333 	    ef->got = (Elf_Addr *) (ef->address + dp->d_un.d_ptr);
334 	    break;
335 	case DT_REL:
336 	    ef->rel = (const Elf_Rel *) (ef->address + dp->d_un.d_ptr);
337 	    break;
338 	case DT_RELSZ:
339 	    ef->relsize = dp->d_un.d_val;
340 	    break;
341 	case DT_RELENT:
342 	    if (dp->d_un.d_val != sizeof(Elf_Rel))
343 		return ENOEXEC;
344 	    break;
345 	case DT_JMPREL:
346 	    ef->pltrel = (const Elf_Rel *) (ef->address + dp->d_un.d_ptr);
347 	    break;
348 	case DT_PLTRELSZ:
349 	    ef->pltrelsize = dp->d_un.d_val;
350 	    break;
351 	case DT_RELA:
352 	    ef->rela = (const Elf_Rela *) (ef->address + dp->d_un.d_ptr);
353 	    break;
354 	case DT_RELASZ:
355 	    ef->relasize = dp->d_un.d_val;
356 	    break;
357 	case DT_RELAENT:
358 	    if (dp->d_un.d_val != sizeof(Elf_Rela))
359 		return ENOEXEC;
360 	    break;
361 	case DT_PLTREL:
362 	    plttype = dp->d_un.d_val;
363 	    if (plttype != DT_REL && plttype != DT_RELA)
364 		return ENOEXEC;
365 	    break;
366 #ifdef DDB
367 	case DT_DEBUG:
368 	    dp->d_un.d_ptr = (Elf_Addr) &r_debug;
369 	    break;
370 #endif
371 	}
372     }
373 
374     if (plttype == DT_RELA) {
375 	ef->pltrela = (const Elf_Rela *) ef->pltrel;
376 	ef->pltrel = NULL;
377 	ef->pltrelasize = ef->pltrelsize;
378 	ef->pltrelsize = 0;
379     }
380 
381     ef->ddbsymtab = ef->symtab;
382     ef->ddbsymcnt = ef->nchains;
383     ef->ddbstrtab = ef->strtab;
384     ef->ddbstrcnt = ef->strsz;
385 
386     return 0;
387 }
388 
389 static void
390 link_elf_error(const char *s)
391 {
392     printf("kldload: %s\n", s);
393 }
394 
395 #ifdef DDB
396 
397 static void
398 link_elf_add_gdb(struct link_map *l)
399 {
400     struct link_map *prev;
401 
402     /*
403      * Scan to the end of the list.
404      */
405     for (prev = r_debug.r_map; prev->l_next != NULL; prev = prev->l_next)
406 	;
407 
408     /* Link in the new entry. */
409     l->l_prev = prev;
410     l->l_next = prev->l_next;
411     prev->l_next = l;
412 }
413 
414 static void
415 link_elf_delete_gdb(struct link_map *l)
416 {
417     if (l->l_prev == NULL) {
418 	if ((r_debug.r_map = l->l_next) != NULL)
419 	    l->l_next->l_prev = NULL;
420 	return;
421     }
422 
423     if ((l->l_prev->l_next = l->l_next) != NULL)
424 	l->l_next->l_prev = l->l_prev;
425 }
426 
427 #endif /* DDB */
428 
429 static int
430 link_elf_link_preload(linker_class_t cls,
431 		      const char* filename, linker_file_t *result)
432 {
433     caddr_t		modptr, baseptr, sizeptr, dynptr;
434     char		*type;
435     elf_file_t		ef;
436     linker_file_t	lf;
437     int			error;
438     vm_offset_t		dp;
439 
440     /* Look to see if we have the file preloaded */
441     modptr = preload_search_by_name(filename);
442     if (modptr == NULL)
443 	return ENOENT;
444 
445     type = (char *)preload_search_info(modptr, MODINFO_TYPE);
446     baseptr = preload_search_info(modptr, MODINFO_ADDR);
447     sizeptr = preload_search_info(modptr, MODINFO_SIZE);
448     dynptr = preload_search_info(modptr, MODINFO_METADATA|MODINFOMD_DYNAMIC);
449     if (type == NULL || strcmp(type, "elf module") != 0)
450 	return (EFTYPE);
451     if (baseptr == NULL || sizeptr == NULL || dynptr == NULL)
452 	return (EINVAL);
453 
454     lf = linker_make_file(filename, &link_elf_class);
455     if (lf == NULL) {
456 	return ENOMEM;
457     }
458 
459     ef = (elf_file_t) lf;
460     ef->preloaded = 1;
461     ef->modptr = modptr;
462     ef->address = *(caddr_t *)baseptr;
463 #ifdef SPARSE_MAPPING
464     ef->object = 0;
465 #endif
466     dp = (vm_offset_t)ef->address + *(vm_offset_t *)dynptr;
467     ef->dynamic = (Elf_Dyn *)dp;
468     lf->address = ef->address;
469     lf->size = *(size_t *)sizeptr;
470 
471     error = parse_dynamic(ef);
472     if (error) {
473 	linker_file_unload(lf);
474 	return error;
475     }
476     *result = lf;
477     return (0);
478 }
479 
480 static int
481 link_elf_link_preload_finish(linker_file_t lf)
482 {
483     elf_file_t		ef;
484     int error;
485 #ifdef DDB
486     char *newfilename;
487 #endif
488 
489     ef = (elf_file_t) lf;
490 #if 0	/* this will be more trouble than it's worth for now */
491     for (dp = ef->dynamic; dp->d_tag != DT_NULL; dp++) {
492 	if (dp->d_tag != DT_NEEDED)
493 	    continue;
494 	modname = ef->strtab + dp->d_un.d_val;
495 	error = linker_load_module(modname, lf);
496 	if (error)
497 	    goto out;
498     }
499 #endif
500     error = relocate_file(ef);
501     if (error)
502 	return error;
503     (void)link_elf_preload_parse_symbols(ef);
504 
505 #ifdef DDB
506     GDB_STATE(RT_ADD);
507     ef->gdb.l_addr = lf->address;
508     newfilename = malloc(strlen(lf->filename) + 1, M_LINKER, M_WAITOK);
509     strcpy(newfilename, lf->filename);
510     ef->gdb.l_name = newfilename;
511     ef->gdb.l_ld = ef->dynamic;
512     link_elf_add_gdb(&ef->gdb);
513     GDB_STATE(RT_CONSISTENT);
514 #endif
515 
516     return (0);
517 }
518 
519 static int
520 link_elf_load_file(linker_class_t cls, const char* filename, linker_file_t* result)
521 {
522     struct nameidata nd;
523     struct thread* td = curthread;	/* XXX */
524     Elf_Ehdr *hdr;
525     caddr_t firstpage;
526     int nbytes, i;
527     Elf_Phdr *phdr;
528     Elf_Phdr *phlimit;
529     Elf_Phdr *segs[2];
530     int nsegs;
531     Elf_Phdr *phdyn;
532     Elf_Phdr *phphdr;
533     caddr_t mapbase;
534     size_t mapsize;
535     Elf_Off base_offset;
536     Elf_Addr base_vaddr;
537     Elf_Addr base_vlimit;
538     int error = 0;
539     int resid, flags;
540     elf_file_t ef;
541     linker_file_t lf;
542     Elf_Shdr *shdr;
543     int symtabindex;
544     int symstrindex;
545     int symcnt;
546     int strcnt;
547 #ifdef DDB
548     char *newfilename;
549 #endif
550 
551     GIANT_REQUIRED;
552 
553     shdr = NULL;
554     lf = NULL;
555 
556     NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, filename, td);
557     flags = FREAD;
558     error = vn_open(&nd, &flags, 0);
559     if (error)
560 	return error;
561     NDFREE(&nd, NDF_ONLY_PNBUF);
562 
563     /*
564      * Read the elf header from the file.
565      */
566     firstpage = malloc(PAGE_SIZE, M_LINKER, M_WAITOK);
567     if (firstpage == NULL) {
568 	error = ENOMEM;
569 	goto out;
570     }
571     hdr = (Elf_Ehdr *)firstpage;
572     error = vn_rdwr(UIO_READ, nd.ni_vp, firstpage, PAGE_SIZE, 0,
573 		    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred, NOCRED,
574 		    &resid, td);
575     nbytes = PAGE_SIZE - resid;
576     if (error)
577 	goto out;
578 
579     if (!IS_ELF(*hdr)) {
580 	error = ENOEXEC;
581 	goto out;
582     }
583 
584     if (hdr->e_ident[EI_CLASS] != ELF_TARG_CLASS
585       || hdr->e_ident[EI_DATA] != ELF_TARG_DATA) {
586 	link_elf_error("Unsupported file layout");
587 	error = ENOEXEC;
588 	goto out;
589     }
590     if (hdr->e_ident[EI_VERSION] != EV_CURRENT
591       || hdr->e_version != EV_CURRENT) {
592 	link_elf_error("Unsupported file version");
593 	error = ENOEXEC;
594 	goto out;
595     }
596     if (hdr->e_type != ET_EXEC && hdr->e_type != ET_DYN) {
597 	link_elf_error("Unsupported file type");
598 	error = ENOEXEC;
599 	goto out;
600     }
601     if (hdr->e_machine != ELF_TARG_MACH) {
602 	link_elf_error("Unsupported machine");
603 	error = ENOEXEC;
604 	goto out;
605     }
606 
607     /*
608      * We rely on the program header being in the first page.  This is
609      * not strictly required by the ABI specification, but it seems to
610      * always true in practice.  And, it simplifies things considerably.
611      */
612     if (!((hdr->e_phentsize == sizeof(Elf_Phdr)) &&
613 	  (hdr->e_phoff + hdr->e_phnum*sizeof(Elf_Phdr) <= PAGE_SIZE) &&
614 	  (hdr->e_phoff + hdr->e_phnum*sizeof(Elf_Phdr) <= nbytes)))
615 	link_elf_error("Unreadable program headers");
616 
617     /*
618      * Scan the program header entries, and save key information.
619      *
620      * We rely on there being exactly two load segments, text and data,
621      * in that order.
622      */
623     phdr = (Elf_Phdr *) (firstpage + hdr->e_phoff);
624     phlimit = phdr + hdr->e_phnum;
625     nsegs = 0;
626     phdyn = NULL;
627     phphdr = NULL;
628     while (phdr < phlimit) {
629 	switch (phdr->p_type) {
630 
631 	case PT_LOAD:
632 	    if (nsegs == 2) {
633 		link_elf_error("Too many sections");
634 		error = ENOEXEC;
635 		goto out;
636 	    }
637 	    segs[nsegs] = phdr;
638 	    ++nsegs;
639 	    break;
640 
641 	case PT_PHDR:
642 	    phphdr = phdr;
643 	    break;
644 
645 	case PT_DYNAMIC:
646 	    phdyn = phdr;
647 	    break;
648 
649 	case PT_INTERP:
650 	    link_elf_error("Unsupported file type");
651 	    error = ENOEXEC;
652 	    goto out;
653 	}
654 
655 	++phdr;
656     }
657     if (phdyn == NULL) {
658 	link_elf_error("Object is not dynamically-linked");
659 	error = ENOEXEC;
660 	goto out;
661     }
662 
663     /*
664      * Allocate the entire address space of the object, to stake out our
665      * contiguous region, and to establish the base address for relocation.
666      */
667     base_offset = trunc_page(segs[0]->p_offset);
668     base_vaddr = trunc_page(segs[0]->p_vaddr);
669     base_vlimit = round_page(segs[1]->p_vaddr + segs[1]->p_memsz);
670     mapsize = base_vlimit - base_vaddr;
671 
672     lf = linker_make_file(filename, &link_elf_class);
673     if (!lf) {
674 	error = ENOMEM;
675 	goto out;
676     }
677 
678     ef = (elf_file_t) lf;
679 #ifdef SPARSE_MAPPING
680     ef->object = vm_object_allocate(OBJT_DEFAULT, mapsize >> PAGE_SHIFT);
681     if (ef->object == NULL) {
682 	free(ef, M_LINKER);
683 	error = ENOMEM;
684 	goto out;
685     }
686     vm_object_reference(ef->object);
687     ef->address = (caddr_t) vm_map_min(kernel_map);
688     error = vm_map_find(kernel_map, ef->object, 0,
689 			(vm_offset_t *) &ef->address,
690 			mapsize, 1,
691 			VM_PROT_ALL, VM_PROT_ALL, 0);
692     if (error) {
693 	vm_object_deallocate(ef->object);
694 	ef->object = 0;
695 	goto out;
696     }
697 #else
698     ef->address = malloc(mapsize, M_LINKER, M_WAITOK);
699     if (!ef->address) {
700 	error = ENOMEM;
701 	goto out;
702     }
703 #endif
704     mapbase = ef->address;
705 
706     /*
707      * Read the text and data sections and zero the bss.
708      */
709     for (i = 0; i < 2; i++) {
710 	caddr_t segbase = mapbase + segs[i]->p_vaddr - base_vaddr;
711 	error = vn_rdwr(UIO_READ, nd.ni_vp,
712 			segbase, segs[i]->p_filesz, segs[i]->p_offset,
713 			UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred, NOCRED,
714 			&resid, td);
715 	if (error) {
716 	    goto out;
717 	}
718 	bzero(segbase + segs[i]->p_filesz,
719 	      segs[i]->p_memsz - segs[i]->p_filesz);
720 
721 #ifdef SPARSE_MAPPING
722 	/*
723 	 * Wire down the pages
724 	 */
725 	vm_map_pageable(kernel_map,
726 			(vm_offset_t) segbase,
727 			(vm_offset_t) segbase + segs[i]->p_memsz,
728 			FALSE);
729 #endif
730     }
731 
732 #ifdef GPROF
733     /* Update profiling information with the new text segment. */
734     kmupetext((uintfptr_t)(mapbase + segs[0]->p_vaddr - base_vaddr +
735 	segs[0]->p_memsz));
736 #endif
737 
738     ef->dynamic = (Elf_Dyn *) (mapbase + phdyn->p_vaddr - base_vaddr);
739 
740     lf->address = ef->address;
741     lf->size = mapsize;
742 
743     error = parse_dynamic(ef);
744     if (error)
745 	goto out;
746     error = linker_load_dependencies(lf);
747     if (error)
748 	goto out;
749 #if 0	/* this will be more trouble than it's worth for now */
750     for (dp = ef->dynamic; dp->d_tag != DT_NULL; dp++) {
751 	if (dp->d_tag != DT_NEEDED)
752 	    continue;
753 	modname = ef->strtab + dp->d_un.d_val;
754 	error = linker_load_module(modname, lf);
755 	if (error)
756 	    goto out;
757     }
758 #endif
759     error = relocate_file(ef);
760     if (error)
761 	goto out;
762 
763     /* Try and load the symbol table if it's present.  (you can strip it!) */
764     nbytes = hdr->e_shnum * hdr->e_shentsize;
765     if (nbytes == 0 || hdr->e_shoff == 0)
766 	goto nosyms;
767     shdr = malloc(nbytes, M_LINKER, M_WAITOK | M_ZERO);
768     if (shdr == NULL) {
769 	error = ENOMEM;
770 	goto out;
771     }
772     error = vn_rdwr(UIO_READ, nd.ni_vp,
773 		    (caddr_t)shdr, nbytes, hdr->e_shoff,
774 		    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred, NOCRED,
775 		    &resid, td);
776     if (error)
777 	goto out;
778     symtabindex = -1;
779     symstrindex = -1;
780     for (i = 0; i < hdr->e_shnum; i++) {
781 	if (shdr[i].sh_type == SHT_SYMTAB) {
782 	    symtabindex = i;
783 	    symstrindex = shdr[i].sh_link;
784 	}
785     }
786     if (symtabindex < 0 || symstrindex < 0)
787 	goto nosyms;
788 
789     symcnt = shdr[symtabindex].sh_size;
790     ef->symbase = malloc(symcnt, M_LINKER, M_WAITOK);
791     strcnt = shdr[symstrindex].sh_size;
792     ef->strbase = malloc(strcnt, M_LINKER, M_WAITOK);
793 
794     if (ef->symbase == NULL || ef->strbase == NULL) {
795 	error = ENOMEM;
796 	goto out;
797     }
798     error = vn_rdwr(UIO_READ, nd.ni_vp,
799 		    ef->symbase, symcnt, shdr[symtabindex].sh_offset,
800 		    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred, NOCRED,
801 		    &resid, td);
802     if (error)
803 	goto out;
804     error = vn_rdwr(UIO_READ, nd.ni_vp,
805 		    ef->strbase, strcnt, shdr[symstrindex].sh_offset,
806 		    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred, NOCRED,
807 		    &resid, td);
808     if (error)
809 	goto out;
810 
811     ef->ddbsymcnt = symcnt / sizeof(Elf_Sym);
812     ef->ddbsymtab = (const Elf_Sym *)ef->symbase;
813     ef->ddbstrcnt = strcnt;
814     ef->ddbstrtab = ef->strbase;
815 
816 #ifdef DDB
817     GDB_STATE(RT_ADD);
818     ef->gdb.l_addr = lf->address;
819     newfilename = malloc(strlen(filename) + 1, M_LINKER, M_WAITOK);
820     strcpy(newfilename, filename);
821     ef->gdb.l_name = (const char *)newfilename;
822     ef->gdb.l_ld = ef->dynamic;
823     link_elf_add_gdb(&ef->gdb);
824     GDB_STATE(RT_CONSISTENT);
825 #endif
826 
827 nosyms:
828 
829     *result = lf;
830 
831 out:
832     if (error && lf)
833 	linker_file_unload(lf);
834     if (shdr)
835 	free(shdr, M_LINKER);
836     if (firstpage)
837 	free(firstpage, M_LINKER);
838     VOP_UNLOCK(nd.ni_vp, 0, td);
839     vn_close(nd.ni_vp, FREAD, td->td_ucred, td);
840 
841     return error;
842 }
843 
844 static void
845 link_elf_unload_file(linker_file_t file)
846 {
847     elf_file_t ef = (elf_file_t) file;
848 
849 #ifdef DDB
850     if (ef->gdb.l_ld) {
851 	GDB_STATE(RT_DELETE);
852 	free((void *)(uintptr_t)ef->gdb.l_name, M_LINKER);
853 	link_elf_delete_gdb(&ef->gdb);
854 	GDB_STATE(RT_CONSISTENT);
855     }
856 #endif
857 
858     if (ef->preloaded) {
859 	link_elf_unload_preload(file);
860 	return;
861     }
862 #ifdef SPARSE_MAPPING
863     if (ef->object) {
864 	vm_map_remove(kernel_map, (vm_offset_t) ef->address,
865 		      (vm_offset_t) ef->address
866 		      + (ef->object->size << PAGE_SHIFT));
867 	vm_object_deallocate(ef->object);
868     }
869 #else
870     if (ef->address)
871 	free(ef->address, M_LINKER);
872 #endif
873     if (ef->symbase)
874 	free(ef->symbase, M_LINKER);
875     if (ef->strbase)
876 	free(ef->strbase, M_LINKER);
877 }
878 
879 static void
880 link_elf_unload_preload(linker_file_t file)
881 {
882     if (file->filename)
883 	preload_delete_name(file->filename);
884 }
885 
886 static const char *
887 symbol_name(elf_file_t ef, Elf_Word r_info)
888 {
889     const Elf_Sym *ref;
890 
891     if (ELF_R_SYM(r_info)) {
892 	ref = ef->symtab + ELF_R_SYM(r_info);
893 	return ef->strtab + ref->st_name;
894     } else
895 	return NULL;
896 }
897 
898 static int
899 relocate_file(elf_file_t ef)
900 {
901     const Elf_Rel *rellim;
902     const Elf_Rel *rel;
903     const Elf_Rela *relalim;
904     const Elf_Rela *rela;
905     const char *symname;
906 
907     /* Perform relocations without addend if there are any: */
908     rel = ef->rel;
909     if (rel) {
910 	rellim = (const Elf_Rel *)((const char *)ef->rel + ef->relsize);
911 	while (rel < rellim) {
912 	    if (elf_reloc(&ef->lf, rel, ELF_RELOC_REL)) {
913 		symname = symbol_name(ef, rel->r_info);
914 		printf("link_elf: symbol %s undefined\n", symname);
915 		return ENOENT;
916 	    }
917 	    rel++;
918 	}
919     }
920 
921     /* Perform relocations with addend if there are any: */
922     rela = ef->rela;
923     if (rela) {
924 	relalim = (const Elf_Rela *)((const char *)ef->rela + ef->relasize);
925 	while (rela < relalim) {
926 	    if (elf_reloc(&ef->lf, rela, ELF_RELOC_RELA)) {
927 		symname = symbol_name(ef, rela->r_info);
928 		printf("link_elf: symbol %s undefined\n", symname);
929 		return ENOENT;
930 	    }
931 	    rela++;
932 	}
933     }
934 
935     /* Perform PLT relocations without addend if there are any: */
936     rel = ef->pltrel;
937     if (rel) {
938 	rellim = (const Elf_Rel *)((const char *)ef->pltrel + ef->pltrelsize);
939 	while (rel < rellim) {
940 	    if (elf_reloc(&ef->lf, rel, ELF_RELOC_REL)) {
941 		symname = symbol_name(ef, rel->r_info);
942 		printf("link_elf: symbol %s undefined\n", symname);
943 		return ENOENT;
944 	    }
945 	    rel++;
946 	}
947     }
948 
949     /* Perform relocations with addend if there are any: */
950     rela = ef->pltrela;
951     if (rela) {
952 	relalim = (const Elf_Rela *)((const char *)ef->pltrela + ef->pltrelasize);
953 	while (rela < relalim) {
954 	    if (elf_reloc(&ef->lf, rela, ELF_RELOC_RELA)) {
955 		symname = symbol_name(ef, rela->r_info);
956 		printf("link_elf: symbol %s undefined\n", symname);
957 		return ENOENT;
958 	    }
959 	    rela++;
960 	}
961     }
962 
963     return 0;
964 }
965 
966 /*
967  * Hash function for symbol table lookup.  Don't even think about changing
968  * this.  It is specified by the System V ABI.
969  */
970 static unsigned long
971 elf_hash(const char *name)
972 {
973     const unsigned char *p = (const unsigned char *) name;
974     unsigned long h = 0;
975     unsigned long g;
976 
977     while (*p != '\0') {
978 	h = (h << 4) + *p++;
979 	if ((g = h & 0xf0000000) != 0)
980 	    h ^= g >> 24;
981 	h &= ~g;
982     }
983     return h;
984 }
985 
986 int
987 link_elf_lookup_symbol(linker_file_t lf, const char* name, c_linker_sym_t* sym)
988 {
989     elf_file_t ef = (elf_file_t) lf;
990     unsigned long symnum;
991     const Elf_Sym* symp;
992     const char *strp;
993     unsigned long hash;
994     int i;
995 
996     /* First, search hashed global symbols */
997     hash = elf_hash(name);
998     symnum = ef->buckets[hash % ef->nbuckets];
999 
1000     while (symnum != STN_UNDEF) {
1001 	if (symnum >= ef->nchains) {
1002 	    printf("link_elf_lookup_symbol: corrupt symbol table\n");
1003 	    return ENOENT;
1004 	}
1005 
1006 	symp = ef->symtab + symnum;
1007 	if (symp->st_name == 0) {
1008 	    printf("link_elf_lookup_symbol: corrupt symbol table\n");
1009 	    return ENOENT;
1010 	}
1011 
1012 	strp = ef->strtab + symp->st_name;
1013 
1014 	if (strcmp(name, strp) == 0) {
1015 	    if (symp->st_shndx != SHN_UNDEF ||
1016 		(symp->st_value != 0 &&
1017 		 ELF_ST_TYPE(symp->st_info) == STT_FUNC)) {
1018 		*sym = (c_linker_sym_t) symp;
1019 		return 0;
1020 	    } else
1021 		return ENOENT;
1022 	}
1023 
1024 	symnum = ef->chains[symnum];
1025     }
1026 
1027     /* If we have not found it, look at the full table (if loaded) */
1028     if (ef->symtab == ef->ddbsymtab)
1029 	return ENOENT;
1030 
1031     /* Exhaustive search */
1032     for (i = 0, symp = ef->ddbsymtab; i < ef->ddbsymcnt; i++, symp++) {
1033 	strp = ef->ddbstrtab + symp->st_name;
1034 	if (strcmp(name, strp) == 0) {
1035 	    if (symp->st_shndx != SHN_UNDEF ||
1036 		(symp->st_value != 0 &&
1037 		 ELF_ST_TYPE(symp->st_info) == STT_FUNC)) {
1038 		*sym = (c_linker_sym_t) symp;
1039 		return 0;
1040 	    } else
1041 		return ENOENT;
1042 	}
1043     }
1044 
1045     return ENOENT;
1046 }
1047 
1048 static int
1049 link_elf_symbol_values(linker_file_t lf, c_linker_sym_t sym, linker_symval_t* symval)
1050 {
1051 	elf_file_t ef = (elf_file_t) lf;
1052 	const Elf_Sym* es = (const Elf_Sym*) sym;
1053 
1054 	if (es >= ef->symtab && ((es - ef->symtab) < ef->nchains)) {
1055 	    symval->name = ef->strtab + es->st_name;
1056 	    symval->value = (caddr_t) ef->address + es->st_value;
1057 	    symval->size = es->st_size;
1058 	    return 0;
1059 	}
1060 	if (ef->symtab == ef->ddbsymtab)
1061 	    return ENOENT;
1062 	if (es >= ef->ddbsymtab && ((es - ef->ddbsymtab) < ef->ddbsymcnt)) {
1063 	    symval->name = ef->ddbstrtab + es->st_name;
1064 	    symval->value = (caddr_t) ef->address + es->st_value;
1065 	    symval->size = es->st_size;
1066 	    return 0;
1067 	}
1068 	return ENOENT;
1069 }
1070 
1071 static int
1072 link_elf_search_symbol(linker_file_t lf, caddr_t value,
1073 		       c_linker_sym_t* sym, long* diffp)
1074 {
1075 	elf_file_t ef = (elf_file_t) lf;
1076 	u_long off = (uintptr_t) (void *) value;
1077 	u_long diff = off;
1078 	u_long st_value;
1079 	const Elf_Sym* es;
1080 	const Elf_Sym* best = 0;
1081 	int i;
1082 
1083 	for (i = 0, es = ef->ddbsymtab; i < ef->ddbsymcnt; i++, es++) {
1084 		if (es->st_name == 0)
1085 			continue;
1086 		st_value = es->st_value + (uintptr_t) (void *) ef->address;
1087 		if (off >= st_value) {
1088 			if (off - st_value < diff) {
1089 				diff = off - st_value;
1090 				best = es;
1091 				if (diff == 0)
1092 					break;
1093 			} else if (off - st_value == diff) {
1094 				best = es;
1095 			}
1096 		}
1097 	}
1098 	if (best == 0)
1099 		*diffp = off;
1100 	else
1101 		*diffp = diff;
1102 	*sym = (c_linker_sym_t) best;
1103 
1104 	return 0;
1105 }
1106 
1107 /*
1108  * Look up a linker set on an ELF system.
1109  */
1110 static int
1111 link_elf_lookup_set(linker_file_t lf, const char *name,
1112 		    void ***startp, void ***stopp, int *countp)
1113 {
1114 	c_linker_sym_t sym;
1115 	linker_symval_t symval;
1116 	char *setsym;
1117 	void **start, **stop;
1118 	int len, error = 0, count;
1119 
1120 	len = strlen(name) + sizeof("__start_set_"); /* sizeof includes \0 */
1121 	setsym = malloc(len, M_LINKER, M_WAITOK);
1122 	if (setsym == NULL)
1123 		return ENOMEM;
1124 
1125 	/* get address of first entry */
1126 	snprintf(setsym, len, "%s%s", "__start_set_", name);
1127 	error = link_elf_lookup_symbol(lf, setsym, &sym);
1128 	if (error)
1129 		goto out;
1130 	link_elf_symbol_values(lf, sym, &symval);
1131 	if (symval.value == 0) {
1132 		error = ESRCH;
1133 		goto out;
1134 	}
1135 	start = (void **)symval.value;
1136 
1137 	/* get address of last entry */
1138 	snprintf(setsym, len, "%s%s", "__stop_set_", name);
1139 	error = link_elf_lookup_symbol(lf, setsym, &sym);
1140 	if (error)
1141 		goto out;
1142 	link_elf_symbol_values(lf, sym, &symval);
1143 	if (symval.value == 0) {
1144 		error = ESRCH;
1145 		goto out;
1146 	}
1147 	stop = (void **)symval.value;
1148 
1149 	/* and the number of entries */
1150 	count = stop - start;
1151 
1152 	/* and copy out */
1153 	if (startp)
1154 		*startp = start;
1155 	if (stopp)
1156 		*stopp = stop;
1157 	if (countp)
1158 		*countp = count;
1159 
1160 out:
1161 	free(setsym, M_LINKER);
1162 	return error;
1163 }
1164 
1165 static int
1166 link_elf_each_function_name(linker_file_t file,
1167   int (*callback)(const char *, void *), void *opaque) {
1168     elf_file_t ef = (elf_file_t)file;
1169     const Elf_Sym* symp;
1170     int i, error;
1171 
1172     /* Exhaustive search */
1173     for (i = 0, symp = ef->ddbsymtab; i < ef->ddbsymcnt; i++, symp++) {
1174 	if (symp->st_value != 0 &&
1175 	    ELF_ST_TYPE(symp->st_info) == STT_FUNC) {
1176 		error = callback(ef->ddbstrtab + symp->st_name, opaque);
1177 		if (error)
1178 		    return (error);
1179 	}
1180     }
1181     return (0);
1182 }
1183 
1184 #ifdef __ia64__
1185 /*
1186  * Each KLD has its own GP. The GP value for each load module is given by
1187  * DT_PLTGOT on ia64. We need GP to construct function descriptors, but
1188  * don't have direct access to the ELF file structure. The link_elf_get_gp()
1189  * function returns the GP given a pointer to a generic linker file struct.
1190  */
1191 Elf_Addr
1192 link_elf_get_gp(linker_file_t lf)
1193 {
1194 	elf_file_t ef = (elf_file_t)lf;
1195 	return (Elf_Addr)ef->got;
1196 }
1197 #endif
1198 
1199 /*
1200  * Symbol lookup function that can be used when the symbol index is known (ie
1201  * in relocations). It uses the symbol index instead of doing a fully fledged
1202  * hash table based lookup when such is valid. For example for local symbols.
1203  * This is not only more efficient, it's also more correct. It's not always
1204  * the case that the symbol can be found through the hash table.
1205  */
1206 Elf_Addr
1207 elf_lookup(linker_file_t lf, Elf_Word symidx, int deps)
1208 {
1209 	elf_file_t ef = (elf_file_t)lf;
1210 	const Elf_Sym *sym;
1211 	const char *symbol;
1212 
1213 	/* Don't even try to lookup the symbol if the index is bogus. */
1214 	if (symidx >= ef->nchains)
1215 		return (0);
1216 
1217 	sym = ef->symtab + symidx;
1218 
1219 	/*
1220 	 * Don't do a full lookup when the symbol is local. It may even
1221 	 * fail because it may not be found through the hash table.
1222 	 */
1223 	if (ELF_ST_BIND(sym->st_info) == STB_LOCAL) {
1224 		/* Force lookup failure when we have an insanity. */
1225 		if (sym->st_shndx == SHN_UNDEF || sym->st_value == 0)
1226 			return (0);
1227 		return ((Elf_Addr)ef->address + sym->st_value);
1228 	}
1229 
1230 	/*
1231 	 * XXX we can avoid doing a hash table based lookup for global
1232 	 * symbols as well. This however is not always valid, so we'll
1233 	 * just do it the hard way for now. Performance tweaks can
1234 	 * always be added.
1235 	 */
1236 
1237 	symbol = ef->strtab + sym->st_name;
1238 
1239 	/* Force a lookup failure if the symbol name is bogus. */
1240 	if (*symbol == 0)
1241 		return (0);
1242 
1243 	return ((Elf_Addr)linker_file_lookup_symbol(lf, symbol, deps));
1244 }
1245