xref: /freebsd/sys/kern/link_elf.c (revision 2ad872c5794e4c26fdf6ed219ad3f09ca0d5304a)
1 /*-
2  * Copyright (c) 1998 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  *	$Id: link_elf.c,v 1.10 1998/11/06 15:16:07 peter Exp $
27  */
28 
29 #include <sys/param.h>
30 #include <sys/kernel.h>
31 #include <sys/systm.h>
32 #include <sys/malloc.h>
33 #include <sys/proc.h>
34 #include <sys/namei.h>
35 #include <sys/fcntl.h>
36 #include <sys/vnode.h>
37 #include <sys/linker.h>
38 #include <machine/elf.h>
39 
40 #include <vm/vm.h>
41 #include <vm/vm_prot.h>
42 #include <vm/vm_param.h>
43 #include <sys/lock.h>
44 #include <vm/vm_object.h>
45 #include <vm/vm_kern.h>
46 #include <vm/vm_extern.h>
47 #include <vm/pmap.h>
48 #include <vm/vm_map.h>
49 
50 static int	link_elf_load_module(const char*, linker_file_t*);
51 static int	link_elf_load_file(const char*, linker_file_t*);
52 static int	link_elf_lookup_symbol(linker_file_t, const char*,
53 				       linker_sym_t*);
54 static int	link_elf_symbol_values(linker_file_t, linker_sym_t, linker_symval_t*);
55 static int	link_elf_search_symbol(linker_file_t, caddr_t value,
56 				       linker_sym_t* sym, long* diffp);
57 
58 static void	link_elf_unload_file(linker_file_t);
59 static void	link_elf_unload_module(linker_file_t);
60 
61 static struct linker_class_ops link_elf_class_ops = {
62     link_elf_load_module,
63 };
64 
65 static struct linker_file_ops link_elf_file_ops = {
66     link_elf_lookup_symbol,
67     link_elf_symbol_values,
68     link_elf_search_symbol,
69     link_elf_unload_file,
70 };
71 
72 static struct linker_file_ops link_elf_module_ops = {
73     link_elf_lookup_symbol,
74     link_elf_symbol_values,
75     link_elf_search_symbol,
76     link_elf_unload_module,
77 };
78 typedef struct elf_file {
79     caddr_t		address;	/* Relocation address */
80 #ifdef SPARSE_MAPPING
81     vm_object_t		object;		/* VM object to hold file pages */
82 #endif
83     const Elf_Dyn*	dynamic;	/* Symbol table etc. */
84     Elf_Off		nbuckets;	/* DT_HASH info */
85     Elf_Off		nchains;
86     const Elf_Off*	buckets;
87     const Elf_Off*	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 } *elf_file_t;
109 
110 static int		parse_dynamic(linker_file_t lf);
111 static int		load_dependancies(linker_file_t lf);
112 static int		relocate_file(linker_file_t lf);
113 static int		parse_module_symbols(linker_file_t lf);
114 
115 /*
116  * The kernel symbol table starts here.
117  */
118 extern struct _dynamic _DYNAMIC;
119 
120 static void
121 link_elf_init(void* arg)
122 {
123 #ifdef __ELF__
124     Elf_Dyn	*dp;
125     caddr_t	modptr, baseptr, sizeptr;
126     elf_file_t	ef;
127     char	*modname;
128 #endif
129 
130 #if ELF_TARG_CLASS == ELFCLASS32
131     linker_add_class("elf32", NULL, &link_elf_class_ops);
132 #else
133     linker_add_class("elf64", NULL, &link_elf_class_ops);
134 #endif
135 
136 #ifdef __ELF__
137     dp = (Elf_Dyn*) &_DYNAMIC;
138     if (dp) {
139 	ef = malloc(sizeof(struct elf_file), M_LINKER, M_NOWAIT);
140 	if (ef == NULL)
141 	    panic("link_elf_init: Can't create linker structures for kernel");
142 	bzero(ef, sizeof(*ef));
143 
144 	ef->address = 0;
145 #ifdef SPARSE_MAPPING
146 	ef->object = 0;
147 #endif
148 	ef->dynamic = dp;
149 	modname = NULL;
150 	modptr = preload_search_by_type("elf kernel");
151 	if (modptr)
152 	    modname = (char *)preload_search_info(modptr, MODINFO_NAME);
153 	if (modname == NULL)
154 	    modname = "kernel";
155 	linker_kernel_file = linker_make_file(modname, ef, &link_elf_file_ops);
156 	if (linker_kernel_file == NULL)
157 	    panic("link_elf_init: Can't create linker structures for kernel");
158 	parse_dynamic(linker_kernel_file);
159 	/* Sigh, magic constants. */
160 #ifdef __alpha__
161 	linker_kernel_file->address = (caddr_t) 0xfffffc0000300000;
162 #else
163 	linker_kernel_file->address = (caddr_t) 0xf0100000;
164 #endif
165 	linker_kernel_file->size = -(long)linker_kernel_file->address;
166 
167 	if (modptr) {
168 	    ef->modptr = modptr;
169 	    baseptr = preload_search_info(modptr, MODINFO_ADDR);
170 	    if (baseptr)
171 		linker_kernel_file->address = *(caddr_t *)baseptr;
172 	    sizeptr = preload_search_info(modptr, MODINFO_SIZE);
173 	    if (sizeptr)
174 		linker_kernel_file->size = *(size_t *)sizeptr;
175 	}
176 	(void)parse_module_symbols(linker_kernel_file);
177 	linker_current_file = linker_kernel_file;
178     }
179 #endif
180 }
181 
182 SYSINIT(link_elf, SI_SUB_KLD, SI_ORDER_SECOND, link_elf_init, 0);
183 
184 static int
185 parse_module_symbols(linker_file_t lf)
186 {
187     elf_file_t ef = lf->priv;
188     caddr_t	pointer;
189     caddr_t	ssym, esym, base;
190     caddr_t	strtab;
191     int		strcnt;
192     Elf_Sym*	symtab;
193     int		symcnt;
194 
195     if (ef->modptr == NULL)
196 	return 0;
197     pointer = preload_search_info(ef->modptr, MODINFO_METADATA|MODINFOMD_SSYM);
198     if (pointer == NULL)
199 	return 0;
200     ssym = *(caddr_t *)pointer;
201     pointer = preload_search_info(ef->modptr, MODINFO_METADATA|MODINFOMD_ESYM);
202     if (pointer == NULL)
203 	return 0;
204     esym = *(caddr_t *)pointer;
205 
206     base = ssym;
207 
208     symcnt = *(long *)base;
209     base += sizeof(long);
210     symtab = (Elf_Sym *)base;
211     base += roundup(symcnt, sizeof(long));
212 
213     if (base > esym || base < ssym) {
214 	printf("Symbols are corrupt!\n");
215 	return EINVAL;
216     }
217 
218     strcnt = *(long *)base;
219     base += sizeof(long);
220     strtab = base;
221     base += roundup(strcnt, sizeof(long));
222 
223     if (base > esym || base < ssym) {
224 	printf("Symbols are corrupt!\n");
225 	return EINVAL;
226     }
227 
228     ef->ddbsymtab = symtab;
229     ef->ddbsymcnt = symcnt / sizeof(Elf_Sym);
230     ef->ddbstrtab = strtab;
231     ef->ddbstrcnt = strcnt;
232 
233     return 0;
234 }
235 
236 static int
237 parse_dynamic(linker_file_t lf)
238 {
239     elf_file_t ef = lf->priv;
240     const Elf_Dyn *dp;
241     int plttype = DT_REL;
242 
243     for (dp = ef->dynamic; dp->d_tag != DT_NULL; dp++) {
244 	switch (dp->d_tag) {
245 	case DT_HASH:
246 	{
247 	    /* From src/libexec/rtld-elf/rtld.c */
248 	    const Elf_Off *hashtab = (const Elf_Off *)
249 		(ef->address + dp->d_un.d_ptr);
250 	    ef->nbuckets = hashtab[0];
251 	    ef->nchains = hashtab[1];
252 	    ef->buckets = hashtab + 2;
253 	    ef->chains = ef->buckets + ef->nbuckets;
254 	    break;
255 	}
256 	case DT_STRTAB:
257 	    ef->strtab = (caddr_t) (ef->address + dp->d_un.d_ptr);
258 	    break;
259 	case DT_STRSZ:
260 	    ef->strsz = dp->d_un.d_val;
261 	    break;
262 	case DT_SYMTAB:
263 	    ef->symtab = (Elf_Sym*) (ef->address + dp->d_un.d_ptr);
264 	    break;
265 	case DT_SYMENT:
266 	    if (dp->d_un.d_val != sizeof(Elf_Sym))
267 		return ENOEXEC;
268 	    break;
269 	case DT_PLTGOT:
270 	    ef->got = (Elf_Addr *) (ef->address + dp->d_un.d_ptr);
271 	    break;
272 	case DT_REL:
273 	    ef->rel = (const Elf_Rel *) (ef->address + dp->d_un.d_ptr);
274 	    break;
275 	case DT_RELSZ:
276 	    ef->relsize = dp->d_un.d_val;
277 	    break;
278 	case DT_RELENT:
279 	    if (dp->d_un.d_val != sizeof(Elf_Rel))
280 		return ENOEXEC;
281 	    break;
282 	case DT_JMPREL:
283 	    ef->pltrel = (const Elf_Rel *) (ef->address + dp->d_un.d_ptr);
284 	    break;
285 	case DT_PLTRELSZ:
286 	    ef->pltrelsize = dp->d_un.d_val;
287 	    break;
288 	case DT_RELA:
289 	    ef->rela = (const Elf_Rela *) (ef->address + dp->d_un.d_ptr);
290 	    break;
291 	case DT_RELASZ:
292 	    ef->relasize = dp->d_un.d_val;
293 	    break;
294 	case DT_RELAENT:
295 	    if (dp->d_un.d_val != sizeof(Elf_Rela))
296 		return ENOEXEC;
297 	    break;
298 	case DT_PLTREL:
299 	    plttype = dp->d_un.d_val;
300 	    if (plttype != DT_REL && plttype != DT_RELA)
301 		return ENOEXEC;
302 	    break;
303 	}
304     }
305 
306     if (plttype == DT_RELA) {
307 	ef->pltrela = (const Elf_Rela *) ef->pltrel;
308 	ef->pltrel = NULL;
309 	ef->pltrelasize = ef->pltrelsize;
310 	ef->pltrelsize = 0;
311     }
312 
313     ef->ddbsymtab = ef->symtab;
314     ef->ddbsymcnt = ef->nchains;
315     ef->ddbstrtab = ef->strtab;
316     ef->ddbstrcnt = ef->strsz;
317 
318     return 0;
319 }
320 
321 static void
322 link_elf_error(const char *s)
323 {
324     printf("kldload: %s\n", s);
325 }
326 
327 static int
328 link_elf_load_module(const char *filename, linker_file_t *result)
329 {
330     caddr_t		modptr, baseptr, sizeptr, dynptr;
331     char		*type;
332     elf_file_t		ef;
333     linker_file_t	lf;
334     int			error;
335     vm_offset_t		dp;
336 
337     /* Look to see if we have the module preloaded */
338     modptr = preload_search_by_name(filename);
339     if (modptr == NULL)
340 	return (link_elf_load_file(filename, result));
341 
342     /* It's preloaded, check we can handle it and collect information */
343     type = (char *)preload_search_info(modptr, MODINFO_TYPE);
344     baseptr = preload_search_info(modptr, MODINFO_ADDR);
345     sizeptr = preload_search_info(modptr, MODINFO_SIZE);
346     dynptr = preload_search_info(modptr, MODINFO_METADATA|MODINFOMD_DYNAMIC);
347     if (type == NULL || strcmp(type, "elf module") != 0)
348 	return (EFTYPE);
349     if (baseptr == NULL || sizeptr == NULL || dynptr == NULL)
350 	return (EINVAL);
351 
352     ef = malloc(sizeof(struct elf_file), M_LINKER, M_WAITOK);
353     if (ef == NULL)
354 	return (ENOMEM);
355     bzero(ef, sizeof(*ef));
356     ef->modptr = modptr;
357     ef->address = *(caddr_t *)baseptr;
358 #ifdef SPARSE_MAPPING
359     ef->object = 0;
360 #endif
361     dp = (vm_offset_t)ef->address + *(vm_offset_t *)dynptr;
362     ef->dynamic = (Elf_Dyn *)dp;
363     lf = linker_make_file(filename, ef, &link_elf_module_ops);
364     if (lf == NULL) {
365 	free(ef, M_LINKER);
366 	return ENOMEM;
367     }
368     lf->address = ef->address;
369     lf->size = *(size_t *)sizeptr;
370 
371     error = parse_dynamic(lf);
372     if (error) {
373 	linker_file_unload(lf);
374 	return error;
375     }
376     error = load_dependancies(lf);
377     if (error) {
378 	linker_file_unload(lf);
379 	return error;
380     }
381     error = relocate_file(lf);
382     if (error) {
383 	linker_file_unload(lf);
384 	return error;
385     }
386     (void)parse_module_symbols(lf);
387     *result = lf;
388     return (0);
389 }
390 
391 static int
392 link_elf_load_file(const char* filename, linker_file_t* result)
393 {
394     struct nameidata nd;
395     struct proc* p = curproc;	/* XXX */
396     Elf_Ehdr *hdr;
397     caddr_t firstpage;
398     int nbytes, i;
399     Elf_Phdr *phdr;
400     Elf_Phdr *phlimit;
401     Elf_Phdr *segs[2];
402     int nsegs;
403     Elf_Phdr *phdyn;
404     Elf_Phdr *phphdr;
405     caddr_t mapbase;
406     size_t mapsize;
407     Elf_Off base_offset;
408     Elf_Addr base_vaddr;
409     Elf_Addr base_vlimit;
410     int error = 0;
411     int resid;
412     elf_file_t ef;
413     linker_file_t lf;
414     char *pathname;
415     Elf_Shdr *shdr;
416     int symtabindex;
417     int symstrindex;
418     int symcnt;
419     int strcnt;
420 
421     shdr = NULL;
422     lf = NULL;
423 
424     pathname = linker_search_path(filename);
425     if (pathname == NULL)
426 	return ENOENT;
427 
428     NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, pathname, p);
429     error = vn_open(&nd, FREAD, 0);
430     free(pathname, M_LINKER);
431     if (error)
432 	return error;
433 
434     /*
435      * Read the elf header from the file.
436      */
437     firstpage = malloc(PAGE_SIZE, M_LINKER, M_WAITOK);
438     if (firstpage == NULL) {
439 	error = ENOMEM;
440 	goto out;
441     }
442     hdr = (Elf_Ehdr *)firstpage;
443     error = vn_rdwr(UIO_READ, nd.ni_vp, firstpage, PAGE_SIZE, 0,
444 		    UIO_SYSSPACE, IO_NODELOCKED, p->p_ucred, &resid, p);
445     nbytes = PAGE_SIZE - resid;
446     if (error)
447 	goto out;
448 
449     if (!IS_ELF(*hdr)) {
450 	error = ENOEXEC;
451 	goto out;
452     }
453 
454     if (hdr->e_ident[EI_CLASS] != ELF_TARG_CLASS
455       || hdr->e_ident[EI_DATA] != ELF_TARG_DATA) {
456 	link_elf_error("Unsupported file layout");
457 	error = ENOEXEC;
458 	goto out;
459     }
460     if (hdr->e_ident[EI_VERSION] != EV_CURRENT
461       || hdr->e_version != EV_CURRENT) {
462 	link_elf_error("Unsupported file version");
463 	error = ENOEXEC;
464 	goto out;
465     }
466     if (hdr->e_type != ET_EXEC && hdr->e_type != ET_DYN) {
467 	link_elf_error("Unsupported file type");
468 	error = ENOEXEC;
469 	goto out;
470     }
471     if (hdr->e_machine != ELF_TARG_MACH) {
472 	link_elf_error("Unsupported machine");
473 	error = ENOEXEC;
474 	goto out;
475     }
476 
477     /*
478      * We rely on the program header being in the first page.  This is
479      * not strictly required by the ABI specification, but it seems to
480      * always true in practice.  And, it simplifies things considerably.
481      */
482     if (!((hdr->e_phentsize == sizeof(Elf_Phdr)) &&
483 	  (hdr->e_phoff + hdr->e_phnum*sizeof(Elf_Phdr) <= PAGE_SIZE) &&
484 	  (hdr->e_phoff + hdr->e_phnum*sizeof(Elf_Phdr) <= nbytes)))
485 	link_elf_error("Unreadable program headers");
486 
487     /*
488      * Scan the program header entries, and save key information.
489      *
490      * We rely on there being exactly two load segments, text and data,
491      * in that order.
492      */
493     phdr = (Elf_Phdr *) (firstpage + hdr->e_phoff);
494     phlimit = phdr + hdr->e_phnum;
495     nsegs = 0;
496     phdyn = NULL;
497     phphdr = NULL;
498     while (phdr < phlimit) {
499 	switch (phdr->p_type) {
500 
501 	case PT_LOAD:
502 	    if (nsegs == 2) {
503 		link_elf_error("Too many sections");
504 		error = ENOEXEC;
505 		goto out;
506 	    }
507 	    segs[nsegs] = phdr;
508 	    ++nsegs;
509 	    break;
510 
511 	case PT_PHDR:
512 	    phphdr = phdr;
513 	    break;
514 
515 	case PT_DYNAMIC:
516 	    phdyn = phdr;
517 	    break;
518 	}
519 
520 	++phdr;
521     }
522     if (phdyn == NULL) {
523 	link_elf_error("Object is not dynamically-linked");
524 	error = ENOEXEC;
525 	goto out;
526     }
527 
528     /*
529      * Allocate the entire address space of the object, to stake out our
530      * contiguous region, and to establish the base address for relocation.
531      */
532     base_offset = trunc_page(segs[0]->p_offset);
533     base_vaddr = trunc_page(segs[0]->p_vaddr);
534     base_vlimit = round_page(segs[1]->p_vaddr + segs[1]->p_memsz);
535     mapsize = base_vlimit - base_vaddr;
536 
537     ef = malloc(sizeof(struct elf_file), M_LINKER, M_WAITOK);
538     bzero(ef, sizeof(*ef));
539 #ifdef SPARSE_MAPPING
540     ef->object = vm_object_allocate(OBJT_DEFAULT, mapsize >> PAGE_SHIFT);
541     if (ef->object == NULL) {
542 	free(ef, M_LINKER);
543 	error = ENOMEM;
544 	goto out;
545     }
546     vm_object_reference(ef->object);
547     ef->address = (caddr_t) vm_map_min(kernel_map);
548     error = vm_map_find(kernel_map, ef->object, 0,
549 			(vm_offset_t *) &ef->address,
550 			mapsize, 1,
551 			VM_PROT_ALL, VM_PROT_ALL, 0);
552     if (error) {
553 	vm_object_deallocate(ef->object);
554 	free(ef, M_LINKER);
555 	goto out;
556     }
557 #else
558     ef->address = malloc(mapsize, M_LINKER, M_WAITOK);
559 #endif
560     mapbase = ef->address;
561 
562     /*
563      * Read the text and data sections and zero the bss.
564      */
565     for (i = 0; i < 2; i++) {
566 	caddr_t segbase = mapbase + segs[i]->p_vaddr - base_vaddr;
567 	error = vn_rdwr(UIO_READ, nd.ni_vp,
568 			segbase, segs[i]->p_filesz, segs[i]->p_offset,
569 			UIO_SYSSPACE, IO_NODELOCKED, p->p_ucred, &resid, p);
570 	if (error) {
571 #ifdef SPARSE_MAPPING
572 	    vm_map_remove(kernel_map, (vm_offset_t) ef->address,
573 			  (vm_offset_t) ef->address
574 			  + (ef->object->size << PAGE_SHIFT));
575 	    vm_object_deallocate(ef->object);
576 #else
577 	    free(ef->address, M_LINKER);
578 #endif
579 	    free(ef, M_LINKER);
580 	    goto out;
581 	}
582 	bzero(segbase + segs[i]->p_filesz,
583 	      segs[i]->p_memsz - segs[i]->p_filesz);
584 
585 #ifdef SPARSE_MAPPING
586 	/*
587 	 * Wire down the pages
588 	 */
589 	vm_map_pageable(kernel_map,
590 			(vm_offset_t) segbase,
591 			(vm_offset_t) segbase + segs[i]->p_memsz,
592 			FALSE);
593 #endif
594     }
595 
596     ef->dynamic = (const Elf_Dyn *) (mapbase + phdyn->p_vaddr - base_vaddr);
597 
598     lf = linker_make_file(filename, ef, &link_elf_file_ops);
599     if (lf == NULL) {
600 #ifdef SPARSE_MAPPING
601 	vm_map_remove(kernel_map, (vm_offset_t) ef->address,
602 		      (vm_offset_t) ef->address
603 		      + (ef->object->size << PAGE_SHIFT));
604 	vm_object_deallocate(ef->object);
605 #else
606 	free(ef->address, M_LINKER);
607 #endif
608 	free(ef, M_LINKER);
609 	error = ENOMEM;
610 	goto out;
611     }
612     lf->address = ef->address;
613     lf->size = mapsize;
614 
615     error = parse_dynamic(lf);
616     if (error)
617 	goto out;
618     error = load_dependancies(lf);
619     if (error)
620 	goto out;
621     error = relocate_file(lf);
622     if (error)
623 	goto out;
624 
625     /* Try and load the symbol table if it's present.  (you can strip it!) */
626     nbytes = hdr->e_shnum * hdr->e_shentsize;
627     if (nbytes == 0 || hdr->e_shoff == 0)
628 	goto nosyms;
629     shdr = malloc(nbytes, M_LINKER, M_WAITOK);
630     if (shdr == NULL) {
631 	error = ENOMEM;
632 	goto out;
633     }
634     bzero(shdr, nbytes);
635     error = vn_rdwr(UIO_READ, nd.ni_vp,
636 		    (caddr_t)shdr, nbytes, hdr->e_shoff,
637 		    UIO_SYSSPACE, IO_NODELOCKED, p->p_ucred, &resid, p);
638     if (error)
639 	goto out;
640     symtabindex = -1;
641     symstrindex = -1;
642     for (i = 0; i < hdr->e_shnum; i++) {
643 	if (shdr[i].sh_type == SHT_SYMTAB) {
644 	    symtabindex = i;
645 	    symstrindex = shdr[i].sh_link;
646 	}
647     }
648     if (symtabindex < 0 || symstrindex < 0)
649 	goto nosyms;
650 
651     symcnt = shdr[symtabindex].sh_size;
652     ef->symbase = malloc(symcnt, M_LINKER, M_WAITOK);
653     strcnt = shdr[symstrindex].sh_size;
654     ef->strbase = malloc(strcnt, M_LINKER, M_WAITOK);
655 
656     if (ef->symbase == NULL || ef->strbase == NULL) {
657 	error = ENOMEM;
658 	goto out;
659     }
660     error = vn_rdwr(UIO_READ, nd.ni_vp,
661 		    ef->symbase, symcnt, shdr[symtabindex].sh_offset,
662 		    UIO_SYSSPACE, IO_NODELOCKED, p->p_ucred, &resid, p);
663     if (error)
664 	goto out;
665     error = vn_rdwr(UIO_READ, nd.ni_vp,
666 		    ef->strbase, strcnt, shdr[symstrindex].sh_offset,
667 		    UIO_SYSSPACE, IO_NODELOCKED, p->p_ucred, &resid, p);
668     if (error)
669 	goto out;
670 
671     ef->ddbsymcnt = symcnt / sizeof(Elf_Sym);
672     ef->ddbsymtab = (const Elf_Sym *)ef->symbase;
673     ef->ddbstrcnt = strcnt;
674     ef->ddbstrtab = ef->strbase;
675 
676 nosyms:
677 
678     *result = lf;
679 
680 out:
681     if (error && lf)
682 	linker_file_unload(lf);
683     if (shdr)
684 	free(shdr, M_LINKER);
685     if (firstpage)
686 	free(firstpage, M_LINKER);
687     VOP_UNLOCK(nd.ni_vp, 0, p);
688     vn_close(nd.ni_vp, FREAD, p->p_ucred, p);
689 
690     return error;
691 }
692 
693 static void
694 link_elf_unload_file(linker_file_t file)
695 {
696     elf_file_t ef = file->priv;
697 
698     if (ef) {
699 #ifdef SPARSE_MAPPING
700 	if (ef->object) {
701 	    vm_map_remove(kernel_map, (vm_offset_t) ef->address,
702 			  (vm_offset_t) ef->address
703 			  + (ef->object->size << PAGE_SHIFT));
704 	    vm_object_deallocate(ef->object);
705 	}
706 #else
707 	if (ef->address)
708 	    free(ef->address, M_LINKER);
709 #endif
710 	if (ef->symbase)
711 	    free(ef->symbase, M_LINKER);
712 	if (ef->strbase)
713 	    free(ef->strbase, M_LINKER);
714 	free(ef, M_LINKER);
715     }
716 }
717 
718 static void
719 link_elf_unload_module(linker_file_t file)
720 {
721     elf_file_t ef = file->priv;
722 
723     if (ef)
724 	free(ef, M_LINKER);
725     if (file->filename)
726 	preload_delete_name(file->filename);
727 }
728 
729 static int
730 load_dependancies(linker_file_t lf)
731 {
732     elf_file_t ef = lf->priv;
733     linker_file_t lfdep;
734     char* name;
735     const Elf_Dyn *dp;
736     int error = 0;
737 
738     /*
739      * All files are dependant on /kernel.
740      */
741     if (linker_kernel_file) {
742 	linker_kernel_file->refs++;
743 	linker_file_add_dependancy(lf, linker_kernel_file);
744     }
745 
746     for (dp = ef->dynamic; dp->d_tag != DT_NULL; dp++) {
747 	if (dp->d_tag == DT_NEEDED) {
748 	    name = ef->strtab + dp->d_un.d_val;
749 
750 	    error = linker_load_file(name, &lfdep);
751 	    if (error)
752 		goto out;
753 	    error = linker_file_add_dependancy(lf, lfdep);
754 	    if (error)
755 		goto out;
756 	}
757     }
758 
759 out:
760     return error;
761 }
762 
763 static const char *
764 symbol_name(elf_file_t ef, Elf_Word r_info)
765 {
766     const Elf_Sym *ref;
767 
768     if (ELF_R_SYM(r_info)) {
769 	ref = ef->symtab + ELF_R_SYM(r_info);
770 	return ef->strtab + ref->st_name;
771     } else
772 	return NULL;
773 }
774 
775 static int
776 relocate_file(linker_file_t lf)
777 {
778     elf_file_t ef = lf->priv;
779     const Elf_Rel *rellim;
780     const Elf_Rel *rel;
781     const Elf_Rela *relalim;
782     const Elf_Rela *rela;
783     const char *symname;
784 
785     /* Perform relocations without addend if there are any: */
786     rel = ef->rel;
787     if (rel) {
788 	rellim = (const Elf_Rel *) ((caddr_t) ef->rel + ef->relsize);
789 	while (rel < rellim) {
790 	    symname = symbol_name(ef, rel->r_info);
791 	    if (elf_reloc(lf, rel, ELF_RELOC_REL, symname)) {
792 		printf("link_elf: symbol %s undefined\n", symname);
793 		return ENOENT;
794 	    }
795 	    rel++;
796 	}
797     }
798 
799     /* Perform relocations with addend if there are any: */
800     rela = ef->rela;
801     if (rela) {
802 	relalim = (const Elf_Rela *) ((caddr_t) ef->rela + ef->relasize);
803 	while (rela < relalim) {
804 	    symname = symbol_name(ef, rela->r_info);
805 	    if (elf_reloc(lf, rela, ELF_RELOC_RELA, symname)) {
806 		printf("link_elf: symbol %s undefined\n", symname);
807 		return ENOENT;
808 	    }
809 	    rela++;
810 	}
811     }
812 
813     /* Perform PLT relocations without addend if there are any: */
814     rel = ef->pltrel;
815     if (rel) {
816 	rellim = (const Elf_Rel *) ((caddr_t) ef->pltrel + ef->pltrelsize);
817 	while (rel < rellim) {
818 	    symname = symbol_name(ef, rel->r_info);
819 	    if (elf_reloc(lf, rel, ELF_RELOC_REL, symname)) {
820 		printf("link_elf: symbol %s undefined\n", symname);
821 		return ENOENT;
822 	    }
823 	    rel++;
824 	}
825     }
826 
827     /* Perform relocations with addend if there are any: */
828     rela = ef->pltrela;
829     if (rela) {
830 	relalim = (const Elf_Rela *) ((caddr_t) ef->pltrela + ef->pltrelasize);
831 	while (rela < relalim) {
832 	    symname = symbol_name(ef, rela->r_info);
833 	    if (elf_reloc(lf, rela, ELF_RELOC_RELA, symname)) {
834 		printf("link_elf: symbol %s undefined\n", symname);
835 		return ENOENT;
836 	    }
837 	    rela++;
838 	}
839     }
840 
841     return 0;
842 }
843 
844 /*
845  * Hash function for symbol table lookup.  Don't even think about changing
846  * this.  It is specified by the System V ABI.
847  */
848 static unsigned long
849 elf_hash(const char *name)
850 {
851     const unsigned char *p = (const unsigned char *) name;
852     unsigned long h = 0;
853     unsigned long g;
854 
855     while (*p != '\0') {
856 	h = (h << 4) + *p++;
857 	if ((g = h & 0xf0000000) != 0)
858 	    h ^= g >> 24;
859 	h &= ~g;
860     }
861     return h;
862 }
863 
864 int
865 link_elf_lookup_symbol(linker_file_t lf, const char* name, linker_sym_t* sym)
866 {
867     elf_file_t ef = lf->priv;
868     unsigned long symnum;
869     const Elf_Sym* symp;
870     const char *strp;
871     unsigned long hash;
872     int i;
873 
874     /* First, search hashed global symbols */
875     hash = elf_hash(name);
876     symnum = ef->buckets[hash % ef->nbuckets];
877 
878     while (symnum != STN_UNDEF) {
879 	if (symnum >= ef->nchains) {
880 	    printf("link_elf_lookup_symbol: corrupt symbol table\n");
881 	    return ENOENT;
882 	}
883 
884 	symp = ef->symtab + symnum;
885 	if (symp->st_name == 0) {
886 	    printf("link_elf_lookup_symbol: corrupt symbol table\n");
887 	    return ENOENT;
888 	}
889 
890 	strp = ef->strtab + symp->st_name;
891 
892 	if (strcmp(name, strp) == 0) {
893 	    if (symp->st_shndx != SHN_UNDEF ||
894 		(symp->st_value != 0 &&
895 		 ELF_ST_TYPE(symp->st_info) == STT_FUNC)) {
896 		*sym = (linker_sym_t) symp;
897 		return 0;
898 	    } else
899 		return ENOENT;
900 	}
901 
902 	symnum = ef->chains[symnum];
903     }
904 
905     /* If we have not found it, look at the full table (if loaded) */
906     if (ef->symtab == ef->ddbsymtab)
907 	return ENOENT;
908 
909     /* Exhaustive search */
910     for (i = 0, symp = ef->ddbsymtab; i < ef->ddbsymcnt; i++, symp++) {
911 	strp = ef->ddbstrtab + symp->st_name;
912 	if (strcmp(name, strp) == 0) {
913 	    if (symp->st_shndx != SHN_UNDEF ||
914 		(symp->st_value != 0 &&
915 		 ELF_ST_TYPE(symp->st_info) == STT_FUNC)) {
916 		*sym = (linker_sym_t) symp;
917 		return 0;
918 	    } else
919 		return ENOENT;
920 	}
921     }
922 
923     return ENOENT;
924 }
925 
926 static int
927 link_elf_symbol_values(linker_file_t lf, linker_sym_t sym, linker_symval_t* symval)
928 {
929 	elf_file_t ef = lf->priv;
930 	Elf_Sym* es = (Elf_Sym*) sym;
931 
932 	if (es >= ef->symtab && ((es - ef->symtab) < ef->nchains)) {
933 	    symval->name = ef->strtab + es->st_name;
934 	    symval->value = (caddr_t) ef->address + es->st_value;
935 	    symval->size = es->st_size;
936 	    return 0;
937 	}
938 	if (ef->symtab == ef->ddbsymtab)
939 	    return ENOENT;
940 	if (es >= ef->ddbsymtab && ((es - ef->ddbsymtab) < ef->ddbsymcnt)) {
941 	    symval->name = ef->ddbstrtab + es->st_name;
942 	    symval->value = (caddr_t) ef->address + es->st_value;
943 	    symval->size = es->st_size;
944 	    return 0;
945 	}
946 	return ENOENT;
947 }
948 
949 static int
950 link_elf_search_symbol(linker_file_t lf, caddr_t value,
951 		       linker_sym_t* sym, long* diffp)
952 {
953 	elf_file_t ef = lf->priv;
954 	u_long off = (u_long) value;
955 	u_long diff = off;
956 	const Elf_Sym* es;
957 	const Elf_Sym* best = 0;
958 	int i;
959 
960 	for (i = 0, es = ef->ddbsymtab; i < ef->ddbsymcnt; i++, es++) {
961 		if (es->st_name == 0)
962 			continue;
963 		if (off >= es->st_value) {
964 			if (off - es->st_value < diff) {
965 				diff = off - es->st_value;
966 				best = es;
967 				if (diff == 0)
968 					break;
969 			} else if (off - es->st_value == diff) {
970 				best = es;
971 			}
972 		}
973 	}
974 	if (best == 0)
975 		*diffp = off;
976 	else
977 		*diffp = diff;
978 	*sym = (linker_sym_t) best;
979 
980 	return 0;
981 }
982