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