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