xref: /freebsd/sys/kern/link_elf_obj.c (revision 1e413cf93298b5b97441a21d9a50fdcd0ee9945e)
1 /*-
2  * Copyright (c) 1998-2000 Doug Rabson
3  * Copyright (c) 2004 Peter Wemm
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30 
31 #include "opt_ddb.h"
32 #include "opt_mac.h"
33 
34 #include <sys/param.h>
35 #include <sys/systm.h>
36 #include <sys/kernel.h>
37 #include <sys/lock.h>
38 #include <sys/malloc.h>
39 #include <sys/mutex.h>
40 #include <sys/mount.h>
41 #include <sys/proc.h>
42 #include <sys/namei.h>
43 #include <sys/fcntl.h>
44 #include <sys/vnode.h>
45 #include <sys/linker.h>
46 
47 #include <machine/elf.h>
48 
49 #include <security/mac/mac_framework.h>
50 
51 #include <vm/vm.h>
52 #include <vm/vm_param.h>
53 #include <vm/vm_object.h>
54 #include <vm/vm_kern.h>
55 #include <vm/vm_extern.h>
56 #include <vm/pmap.h>
57 #include <vm/vm_map.h>
58 
59 #include <sys/link_elf.h>
60 
61 #include "linker_if.h"
62 
63 typedef struct {
64 	void		*addr;
65 	Elf_Off		size;
66 	int		flags;
67 	int		sec;	/* Original section */
68 	char		*name;
69 } Elf_progent;
70 
71 typedef struct {
72 	Elf_Rel		*rel;
73 	int		nrel;
74 	int		sec;
75 } Elf_relent;
76 
77 typedef struct {
78 	Elf_Rela	*rela;
79 	int		nrela;
80 	int		sec;
81 } Elf_relaent;
82 
83 
84 typedef struct elf_file {
85 	struct linker_file lf;		/* Common fields */
86 
87 	int		preloaded;
88 	caddr_t		address;	/* Relocation address */
89 	vm_object_t	object;		/* VM object to hold file pages */
90 	Elf_Shdr	*e_shdr;
91 
92 	Elf_progent	*progtab;
93 	int		nprogtab;
94 
95 	Elf_relaent	*relatab;
96 	int		nrela;
97 
98 	Elf_relent	*reltab;
99 	int		nrel;
100 
101 	Elf_Sym		*ddbsymtab;	/* The symbol table we are using */
102 	long		ddbsymcnt;	/* Number of symbols */
103 	caddr_t		ddbstrtab;	/* String table */
104 	long		ddbstrcnt;	/* number of bytes in string table */
105 
106 	caddr_t		shstrtab;	/* Section name string table */
107 	long		shstrcnt;	/* number of bytes in string table */
108 
109 } *elf_file_t;
110 
111 static int	link_elf_link_preload(linker_class_t cls,
112 		    const char *, linker_file_t *);
113 static int	link_elf_link_preload_finish(linker_file_t);
114 static int	link_elf_load_file(linker_class_t, const char *, linker_file_t *);
115 static int	link_elf_lookup_symbol(linker_file_t, const char *,
116 		    c_linker_sym_t *);
117 static int	link_elf_symbol_values(linker_file_t, c_linker_sym_t,
118 		    linker_symval_t *);
119 static int	link_elf_search_symbol(linker_file_t, caddr_t value,
120 		    c_linker_sym_t *sym, long *diffp);
121 
122 static void	link_elf_unload_file(linker_file_t);
123 static int	link_elf_lookup_set(linker_file_t, const char *,
124 		    void ***, void ***, int *);
125 static int	link_elf_each_function_name(linker_file_t,
126 		    int (*)(const char *, void *), void *);
127 static void	link_elf_reloc_local(linker_file_t);
128 
129 static Elf_Addr elf_obj_lookup(linker_file_t lf, Elf_Size symidx, int deps);
130 
131 static kobj_method_t link_elf_methods[] = {
132 	KOBJMETHOD(linker_lookup_symbol,	link_elf_lookup_symbol),
133 	KOBJMETHOD(linker_symbol_values,	link_elf_symbol_values),
134 	KOBJMETHOD(linker_search_symbol,	link_elf_search_symbol),
135 	KOBJMETHOD(linker_unload,		link_elf_unload_file),
136 	KOBJMETHOD(linker_load_file,		link_elf_load_file),
137 	KOBJMETHOD(linker_link_preload,		link_elf_link_preload),
138 	KOBJMETHOD(linker_link_preload_finish,	link_elf_link_preload_finish),
139 	KOBJMETHOD(linker_lookup_set,		link_elf_lookup_set),
140 	KOBJMETHOD(linker_each_function_name,	link_elf_each_function_name),
141 	{ 0, 0 }
142 };
143 
144 static struct linker_class link_elf_class = {
145 #if ELF_TARG_CLASS == ELFCLASS32
146 	"elf32_obj",
147 #else
148 	"elf64_obj",
149 #endif
150 	link_elf_methods, sizeof(struct elf_file)
151 };
152 
153 static int	relocate_file(elf_file_t ef);
154 
155 static void
156 link_elf_error(const char *s)
157 {
158 	printf("kldload: %s\n", s);
159 }
160 
161 static void
162 link_elf_init(void *arg)
163 {
164 
165 	linker_add_class(&link_elf_class);
166 }
167 
168 SYSINIT(link_elf_obj, SI_SUB_KLD, SI_ORDER_SECOND, link_elf_init, 0);
169 
170 static int
171 link_elf_link_preload(linker_class_t cls, const char *filename,
172     linker_file_t *result)
173 {
174 	Elf_Ehdr *hdr;
175 	Elf_Shdr *shdr;
176 	Elf_Sym *es;
177 	void *modptr, *baseptr, *sizeptr;
178 	char *type;
179 	elf_file_t ef;
180 	linker_file_t lf;
181 	Elf_Addr off;
182 	int error, i, j, pb, ra, rl, shstrindex, symstrindex, symtabindex;
183 
184 	/* Look to see if we have the file preloaded */
185 	modptr = preload_search_by_name(filename);
186 	if (modptr == NULL)
187 		return ENOENT;
188 
189 	type = (char *)preload_search_info(modptr, MODINFO_TYPE);
190 	baseptr = preload_search_info(modptr, MODINFO_ADDR);
191 	sizeptr = preload_search_info(modptr, MODINFO_SIZE);
192 	hdr = (Elf_Ehdr *)preload_search_info(modptr, MODINFO_METADATA |
193 	    MODINFOMD_ELFHDR);
194 	shdr = (Elf_Shdr *)preload_search_info(modptr, MODINFO_METADATA |
195 	    MODINFOMD_SHDR);
196 	if (type == NULL || (strcmp(type, "elf" __XSTRING(__ELF_WORD_SIZE)
197 	    " obj module") != 0 &&
198 	    strcmp(type, "elf obj module") != 0)) {
199 		return (EFTYPE);
200 	}
201 	if (baseptr == NULL || sizeptr == NULL || hdr == NULL ||
202 	    shdr == NULL)
203 		return (EINVAL);
204 
205 	lf = linker_make_file(filename, &link_elf_class);
206 	if (lf == NULL)
207 		return (ENOMEM);
208 
209 	ef = (elf_file_t)lf;
210 	ef->preloaded = 1;
211 	ef->address = *(caddr_t *)baseptr;
212 	lf->address = *(caddr_t *)baseptr;
213 	lf->size = *(size_t *)sizeptr;
214 
215 	if (hdr->e_ident[EI_CLASS] != ELF_TARG_CLASS ||
216 	    hdr->e_ident[EI_DATA] != ELF_TARG_DATA ||
217 	    hdr->e_ident[EI_VERSION] != EV_CURRENT ||
218 	    hdr->e_version != EV_CURRENT ||
219 	    hdr->e_type != ET_REL ||
220 	    hdr->e_machine != ELF_TARG_MACH) {
221 		error = EFTYPE;
222 		goto out;
223 	}
224 	ef->e_shdr = shdr;
225 
226 	/* Scan the section header for information and table sizing. */
227 	symtabindex = -1;
228 	symstrindex = -1;
229 	for (i = 0; i < hdr->e_shnum; i++) {
230 		switch (shdr[i].sh_type) {
231 		case SHT_PROGBITS:
232 		case SHT_NOBITS:
233 			ef->nprogtab++;
234 			break;
235 		case SHT_SYMTAB:
236 			symtabindex = i;
237 			symstrindex = shdr[i].sh_link;
238 			break;
239 		case SHT_REL:
240 			ef->nrel++;
241 			break;
242 		case SHT_RELA:
243 			ef->nrela++;
244 			break;
245 		}
246 	}
247 
248 	shstrindex = hdr->e_shstrndx;
249 	if (ef->nprogtab == 0 || symstrindex < 0 ||
250 	    symstrindex >= hdr->e_shnum ||
251 	    shdr[symstrindex].sh_type != SHT_STRTAB || shstrindex == 0 ||
252 	    shstrindex >= hdr->e_shnum ||
253 	    shdr[shstrindex].sh_type != SHT_STRTAB) {
254 		printf("%s: bad/missing section headers\n", filename);
255 		error = ENOEXEC;
256 		goto out;
257 	}
258 
259 	/* Allocate space for tracking the load chunks */
260 	if (ef->nprogtab != 0)
261 		ef->progtab = malloc(ef->nprogtab * sizeof(*ef->progtab),
262 		    M_LINKER, M_WAITOK | M_ZERO);
263 	if (ef->nrel != 0)
264 		ef->reltab = malloc(ef->nrel * sizeof(*ef->reltab), M_LINKER,
265 		    M_WAITOK | M_ZERO);
266 	if (ef->nrela != 0)
267 		ef->relatab = malloc(ef->nrela * sizeof(*ef->relatab), M_LINKER,
268 		    M_WAITOK | M_ZERO);
269 	if ((ef->nprogtab != 0 && ef->progtab == NULL) ||
270 	    (ef->nrel != 0 && ef->reltab == NULL) ||
271 	    (ef->nrela != 0 && ef->relatab == NULL)) {
272 		error = ENOMEM;
273 		goto out;
274 	}
275 
276 	/* XXX, relocate the sh_addr fields saved by the loader. */
277 	off = 0;
278 	for (i = 0; i < hdr->e_shnum; i++) {
279 		if (shdr[i].sh_addr != 0 && (off == 0 || shdr[i].sh_addr < off))
280 			off = shdr[i].sh_addr;
281 	}
282 	for (i = 0; i < hdr->e_shnum; i++) {
283 		if (shdr[i].sh_addr != 0)
284 			shdr[i].sh_addr = shdr[i].sh_addr - off +
285 			    (Elf_Addr)ef->address;
286 	}
287 
288 	ef->ddbsymcnt = shdr[symtabindex].sh_size / sizeof(Elf_Sym);
289 	ef->ddbsymtab = (Elf_Sym *)shdr[symtabindex].sh_addr;
290 	ef->ddbstrcnt = shdr[symstrindex].sh_size;
291 	ef->ddbstrtab = (char *)shdr[symstrindex].sh_addr;
292 	ef->shstrcnt = shdr[shstrindex].sh_size;
293 	ef->shstrtab = (char *)shdr[shstrindex].sh_addr;
294 
295 	/* Now fill out progtab and the relocation tables. */
296 	pb = 0;
297 	rl = 0;
298 	ra = 0;
299 	for (i = 0; i < hdr->e_shnum; i++) {
300 		switch (shdr[i].sh_type) {
301 		case SHT_PROGBITS:
302 		case SHT_NOBITS:
303 			ef->progtab[pb].addr = (void *)shdr[i].sh_addr;
304 			if (shdr[i].sh_type == SHT_PROGBITS)
305 				ef->progtab[pb].name = "<<PROGBITS>>";
306 			else
307 				ef->progtab[pb].name = "<<NOBITS>>";
308 			ef->progtab[pb].size = shdr[i].sh_size;
309 			ef->progtab[pb].sec = i;
310 			if (ef->shstrtab && shdr[i].sh_name != 0)
311 				ef->progtab[pb].name =
312 				    ef->shstrtab + shdr[i].sh_name;
313 
314 			/* Update all symbol values with the offset. */
315 			for (j = 0; j < ef->ddbsymcnt; j++) {
316 				es = &ef->ddbsymtab[j];
317 				if (es->st_shndx != i)
318 					continue;
319 				es->st_value += (Elf_Addr)ef->progtab[pb].addr;
320 			}
321 			pb++;
322 			break;
323 		case SHT_REL:
324 			ef->reltab[rl].rel = (Elf_Rel *)shdr[i].sh_addr;
325 			ef->reltab[rl].nrel = shdr[i].sh_size / sizeof(Elf_Rel);
326 			ef->reltab[rl].sec = shdr[i].sh_info;
327 			rl++;
328 			break;
329 		case SHT_RELA:
330 			ef->relatab[ra].rela = (Elf_Rela *)shdr[i].sh_addr;
331 			ef->relatab[ra].nrela =
332 			    shdr[i].sh_size / sizeof(Elf_Rela);
333 			ef->relatab[ra].sec = shdr[i].sh_info;
334 			ra++;
335 			break;
336 		}
337 	}
338 	if (pb != ef->nprogtab)
339 		panic("lost progbits");
340 	if (rl != ef->nrel)
341 		panic("lost rel");
342 	if (ra != ef->nrela)
343 		panic("lost rela");
344 
345 	/* Local intra-module relocations */
346 	link_elf_reloc_local(lf);
347 
348 	*result = lf;
349 	return (0);
350 
351 out:
352 	/* preload not done this way */
353 	linker_file_unload(lf, LINKER_UNLOAD_FORCE);
354 	return (error);
355 }
356 
357 static int
358 link_elf_link_preload_finish(linker_file_t lf)
359 {
360 	elf_file_t ef;
361 	int error;
362 
363 	ef = (elf_file_t)lf;
364 	error = relocate_file(ef);
365 	if (error)
366 		return error;
367 
368 	/* Notify MD code that a module is being loaded. */
369 	error = elf_cpu_load_file(lf);
370 	if (error)
371 		return (error);
372 
373 	return (0);
374 }
375 
376 static int
377 link_elf_load_file(linker_class_t cls, const char *filename,
378     linker_file_t *result)
379 {
380 	struct nameidata nd;
381 	struct thread *td = curthread;	/* XXX */
382 	Elf_Ehdr *hdr;
383 	Elf_Shdr *shdr;
384 	Elf_Sym *es;
385 	int nbytes, i, j;
386 	vm_offset_t mapbase;
387 	size_t mapsize;
388 	int error = 0;
389 	int resid, flags;
390 	elf_file_t ef;
391 	linker_file_t lf;
392 	int symtabindex;
393 	int symstrindex;
394 	int shstrindex;
395 	int nsym;
396 	int pb, rl, ra;
397 	int alignmask;
398 	int vfslocked;
399 
400 	shdr = NULL;
401 	lf = NULL;
402 	mapsize = 0;
403 	hdr = NULL;
404 
405 	NDINIT(&nd, LOOKUP, FOLLOW | MPSAFE, UIO_SYSSPACE, filename, td);
406 	flags = FREAD;
407 	error = vn_open(&nd, &flags, 0, NULL);
408 	if (error)
409 		return error;
410 	vfslocked = NDHASGIANT(&nd);
411 	NDFREE(&nd, NDF_ONLY_PNBUF);
412 #ifdef MAC
413 	error = mac_kld_check_load(td->td_ucred, nd.ni_vp);
414 	if (error) {
415 		goto out;
416 	}
417 #endif
418 
419 	/* Read the elf header from the file. */
420 	hdr = malloc(sizeof(*hdr), M_LINKER, M_WAITOK);
421 	if (hdr == NULL) {
422 		error = ENOMEM;
423 		goto out;
424 	}
425 	error = vn_rdwr(UIO_READ, nd.ni_vp, (void *)hdr, sizeof(*hdr), 0,
426 	    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred, NOCRED,
427 	    &resid, td);
428 	if (error)
429 		goto out;
430 	if (resid != 0){
431 		error = ENOEXEC;
432 		goto out;
433 	}
434 
435 	if (!IS_ELF(*hdr)) {
436 		error = ENOEXEC;
437 		goto out;
438 	}
439 
440 	if (hdr->e_ident[EI_CLASS] != ELF_TARG_CLASS
441 	    || hdr->e_ident[EI_DATA] != ELF_TARG_DATA) {
442 		link_elf_error("Unsupported file layout");
443 		error = ENOEXEC;
444 		goto out;
445 	}
446 	if (hdr->e_ident[EI_VERSION] != EV_CURRENT
447 	    || hdr->e_version != EV_CURRENT) {
448 		link_elf_error("Unsupported file version");
449 		error = ENOEXEC;
450 		goto out;
451 	}
452 	if (hdr->e_type != ET_REL) {
453 		link_elf_error("Unsupported file type");
454 		error = ENOEXEC;
455 		goto out;
456 	}
457 	if (hdr->e_machine != ELF_TARG_MACH) {
458 		link_elf_error("Unsupported machine");
459 		error = ENOEXEC;
460 		goto out;
461 	}
462 
463 	lf = linker_make_file(filename, &link_elf_class);
464 	if (!lf) {
465 		error = ENOMEM;
466 		goto out;
467 	}
468 	ef = (elf_file_t) lf;
469 	ef->nprogtab = 0;
470 	ef->e_shdr = 0;
471 	ef->nrel = 0;
472 	ef->nrela = 0;
473 
474 	/* Allocate and read in the section header */
475 	nbytes = hdr->e_shnum * hdr->e_shentsize;
476 	if (nbytes == 0 || hdr->e_shoff == 0 ||
477 	    hdr->e_shentsize != sizeof(Elf_Shdr)) {
478 		error = ENOEXEC;
479 		goto out;
480 	}
481 	shdr = malloc(nbytes, M_LINKER, M_WAITOK);
482 	if (shdr == NULL) {
483 		error = ENOMEM;
484 		goto out;
485 	}
486 	ef->e_shdr = shdr;
487 	error = vn_rdwr(UIO_READ, nd.ni_vp, (caddr_t)shdr, nbytes, hdr->e_shoff,
488 	    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred, NOCRED, &resid, td);
489 	if (error)
490 		goto out;
491 	if (resid) {
492 		error = ENOEXEC;
493 		goto out;
494 	}
495 
496 	/* Scan the section header for information and table sizing. */
497 	nsym = 0;
498 	symtabindex = -1;
499 	symstrindex = -1;
500 	for (i = 0; i < hdr->e_shnum; i++) {
501 		switch (shdr[i].sh_type) {
502 		case SHT_PROGBITS:
503 		case SHT_NOBITS:
504 			ef->nprogtab++;
505 			break;
506 		case SHT_SYMTAB:
507 			nsym++;
508 			symtabindex = i;
509 			symstrindex = shdr[i].sh_link;
510 			break;
511 		case SHT_REL:
512 			ef->nrel++;
513 			break;
514 		case SHT_RELA:
515 			ef->nrela++;
516 			break;
517 		case SHT_STRTAB:
518 			break;
519 		}
520 	}
521 	if (ef->nprogtab == 0) {
522 		link_elf_error("file has no contents");
523 		error = ENOEXEC;
524 		goto out;
525 	}
526 	if (nsym != 1) {
527 		/* Only allow one symbol table for now */
528 		link_elf_error("file has no valid symbol table");
529 		error = ENOEXEC;
530 		goto out;
531 	}
532 	if (symstrindex < 0 || symstrindex > hdr->e_shnum ||
533 	    shdr[symstrindex].sh_type != SHT_STRTAB) {
534 		link_elf_error("file has invalid symbol strings");
535 		error = ENOEXEC;
536 		goto out;
537 	}
538 
539 	/* Allocate space for tracking the load chunks */
540 	if (ef->nprogtab != 0)
541 		ef->progtab = malloc(ef->nprogtab * sizeof(*ef->progtab),
542 		    M_LINKER, M_WAITOK | M_ZERO);
543 	if (ef->nrel != 0)
544 		ef->reltab = malloc(ef->nrel * sizeof(*ef->reltab), M_LINKER,
545 		    M_WAITOK | M_ZERO);
546 	if (ef->nrela != 0)
547 		ef->relatab = malloc(ef->nrela * sizeof(*ef->relatab), M_LINKER,
548 		    M_WAITOK | M_ZERO);
549 	if ((ef->nprogtab != 0 && ef->progtab == NULL) ||
550 	    (ef->nrel != 0 && ef->reltab == NULL) ||
551 	    (ef->nrela != 0 && ef->relatab == NULL)) {
552 		error = ENOMEM;
553 		goto out;
554 	}
555 
556 	if (symtabindex == -1)
557 		panic("lost symbol table index");
558 	/* Allocate space for and load the symbol table */
559 	ef->ddbsymcnt = shdr[symtabindex].sh_size / sizeof(Elf_Sym);
560 	ef->ddbsymtab = malloc(shdr[symtabindex].sh_size, M_LINKER, M_WAITOK);
561 	if (ef->ddbsymtab == NULL) {
562 		error = ENOMEM;
563 		goto out;
564 	}
565 	error = vn_rdwr(UIO_READ, nd.ni_vp, (void *)ef->ddbsymtab,
566 	    shdr[symtabindex].sh_size, shdr[symtabindex].sh_offset,
567 	    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred, NOCRED,
568 	    &resid, td);
569 	if (error)
570 		goto out;
571 	if (resid != 0){
572 		error = EINVAL;
573 		goto out;
574 	}
575 
576 	if (symstrindex == -1)
577 		panic("lost symbol string index");
578 	/* Allocate space for and load the symbol strings */
579 	ef->ddbstrcnt = shdr[symstrindex].sh_size;
580 	ef->ddbstrtab = malloc(shdr[symstrindex].sh_size, M_LINKER, M_WAITOK);
581 	if (ef->ddbstrtab == NULL) {
582 		error = ENOMEM;
583 		goto out;
584 	}
585 	error = vn_rdwr(UIO_READ, nd.ni_vp, ef->ddbstrtab,
586 	    shdr[symstrindex].sh_size, shdr[symstrindex].sh_offset,
587 	    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred, NOCRED,
588 	    &resid, td);
589 	if (error)
590 		goto out;
591 	if (resid != 0){
592 		error = EINVAL;
593 		goto out;
594 	}
595 
596 	/* Do we have a string table for the section names?  */
597 	shstrindex = -1;
598 	if (hdr->e_shstrndx != 0 &&
599 	    shdr[hdr->e_shstrndx].sh_type == SHT_STRTAB) {
600 		shstrindex = hdr->e_shstrndx;
601 		ef->shstrcnt = shdr[shstrindex].sh_size;
602 		ef->shstrtab = malloc(shdr[shstrindex].sh_size, M_LINKER,
603 		    M_WAITOK);
604 		if (ef->shstrtab == NULL) {
605 			error = ENOMEM;
606 			goto out;
607 		}
608 		error = vn_rdwr(UIO_READ, nd.ni_vp, ef->shstrtab,
609 		    shdr[shstrindex].sh_size, shdr[shstrindex].sh_offset,
610 		    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred, NOCRED,
611 		    &resid, td);
612 		if (error)
613 			goto out;
614 		if (resid != 0){
615 			error = EINVAL;
616 			goto out;
617 		}
618 	}
619 
620 	/* Size up code/data(progbits) and bss(nobits). */
621 	alignmask = 0;
622 	for (i = 0; i < hdr->e_shnum; i++) {
623 		switch (shdr[i].sh_type) {
624 		case SHT_PROGBITS:
625 		case SHT_NOBITS:
626 			alignmask = shdr[i].sh_addralign - 1;
627 			mapsize += alignmask;
628 			mapsize &= ~alignmask;
629 			mapsize += shdr[i].sh_size;
630 			break;
631 		}
632 	}
633 
634 	/*
635 	 * We know how much space we need for the text/data/bss/etc.
636 	 * This stuff needs to be in a single chunk so that profiling etc
637 	 * can get the bounds and gdb can associate offsets with modules
638 	 */
639 	ef->object = vm_object_allocate(OBJT_DEFAULT,
640 	    round_page(mapsize) >> PAGE_SHIFT);
641 	if (ef->object == NULL) {
642 		error = ENOMEM;
643 		goto out;
644 	}
645 	ef->address = (caddr_t) vm_map_min(kernel_map);
646 	error = vm_map_find(kernel_map, ef->object, 0, &mapbase,
647 	    round_page(mapsize), TRUE, VM_PROT_ALL, VM_PROT_ALL, FALSE);
648 	if (error) {
649 		vm_object_deallocate(ef->object);
650 		ef->object = 0;
651 		goto out;
652 	}
653 
654 	/* Wire the pages */
655 	error = vm_map_wire(kernel_map, mapbase,
656 	    mapbase + round_page(mapsize),
657 	    VM_MAP_WIRE_SYSTEM|VM_MAP_WIRE_NOHOLES);
658 	if (error != KERN_SUCCESS) {
659 		error = ENOMEM;
660 		goto out;
661 	}
662 
663 	/* Inform the kld system about the situation */
664 	lf->address = ef->address = (caddr_t)mapbase;
665 	lf->size = mapsize;
666 
667 	/*
668 	 * Now load code/data(progbits), zero bss(nobits), allocate space for
669 	 * and load relocs
670 	 */
671 	pb = 0;
672 	rl = 0;
673 	ra = 0;
674 	alignmask = 0;
675 	for (i = 0; i < hdr->e_shnum; i++) {
676 		switch (shdr[i].sh_type) {
677 		case SHT_PROGBITS:
678 		case SHT_NOBITS:
679 			alignmask = shdr[i].sh_addralign - 1;
680 			mapbase += alignmask;
681 			mapbase &= ~alignmask;
682 			ef->progtab[pb].addr = (void *)(uintptr_t)mapbase;
683 			if (shdr[i].sh_type == SHT_PROGBITS) {
684 				ef->progtab[pb].name = "<<PROGBITS>>";
685 				error = vn_rdwr(UIO_READ, nd.ni_vp,
686 				    ef->progtab[pb].addr,
687 				    shdr[i].sh_size, shdr[i].sh_offset,
688 				    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred,
689 				    NOCRED, &resid, td);
690 				if (error)
691 					goto out;
692 				if (resid != 0){
693 					error = EINVAL;
694 					goto out;
695 				}
696 			} else {
697 				ef->progtab[pb].name = "<<NOBITS>>";
698 				bzero(ef->progtab[pb].addr, shdr[i].sh_size);
699 			}
700 			ef->progtab[pb].size = shdr[i].sh_size;
701 			ef->progtab[pb].sec = i;
702 			if (ef->shstrtab && shdr[i].sh_name != 0)
703 				ef->progtab[pb].name =
704 				    ef->shstrtab + shdr[i].sh_name;
705 
706 			/* Update all symbol values with the offset. */
707 			for (j = 0; j < ef->ddbsymcnt; j++) {
708 				es = &ef->ddbsymtab[j];
709 				if (es->st_shndx != i)
710 					continue;
711 				es->st_value += (Elf_Addr)ef->progtab[pb].addr;
712 			}
713 			mapbase += shdr[i].sh_size;
714 			pb++;
715 			break;
716 		case SHT_REL:
717 			ef->reltab[rl].rel = malloc(shdr[i].sh_size, M_LINKER,
718 			    M_WAITOK);
719 			ef->reltab[rl].nrel = shdr[i].sh_size / sizeof(Elf_Rel);
720 			ef->reltab[rl].sec = shdr[i].sh_info;
721 			error = vn_rdwr(UIO_READ, nd.ni_vp,
722 			    (void *)ef->reltab[rl].rel,
723 			    shdr[i].sh_size, shdr[i].sh_offset,
724 			    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred, NOCRED,
725 			    &resid, td);
726 			if (error)
727 				goto out;
728 			if (resid != 0){
729 				error = EINVAL;
730 				goto out;
731 			}
732 			rl++;
733 			break;
734 		case SHT_RELA:
735 			ef->relatab[ra].rela = malloc(shdr[i].sh_size, M_LINKER,
736 			    M_WAITOK);
737 			ef->relatab[ra].nrela =
738 			    shdr[i].sh_size / sizeof(Elf_Rela);
739 			ef->relatab[ra].sec = shdr[i].sh_info;
740 			error = vn_rdwr(UIO_READ, nd.ni_vp,
741 			    (void *)ef->relatab[ra].rela,
742 			    shdr[i].sh_size, shdr[i].sh_offset,
743 			    UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred, NOCRED,
744 			    &resid, td);
745 			if (error)
746 				goto out;
747 			if (resid != 0){
748 				error = EINVAL;
749 				goto out;
750 			}
751 			ra++;
752 			break;
753 		}
754 	}
755 	if (pb != ef->nprogtab)
756 		panic("lost progbits");
757 	if (rl != ef->nrel)
758 		panic("lost rel");
759 	if (ra != ef->nrela)
760 		panic("lost rela");
761 	if (mapbase != (vm_offset_t)ef->address + mapsize)
762 		panic("mapbase 0x%lx != address %p + mapsize 0x%lx (0x%lx)\n",
763 		    mapbase, ef->address, mapsize,
764 		    (vm_offset_t)ef->address + mapsize);
765 
766 	/* Local intra-module relocations */
767 	link_elf_reloc_local(lf);
768 
769 	/* Pull in dependencies */
770 	error = linker_load_dependencies(lf);
771 	if (error)
772 		goto out;
773 
774 	/* External relocations */
775 	error = relocate_file(ef);
776 	if (error)
777 		goto out;
778 
779 	/* Notify MD code that a module is being loaded. */
780 	error = elf_cpu_load_file(lf);
781 	if (error)
782 		goto out;
783 
784 	*result = lf;
785 
786 out:
787 	if (error && lf)
788 		linker_file_unload(lf, LINKER_UNLOAD_FORCE);
789 	if (hdr)
790 		free(hdr, M_LINKER);
791 	VOP_UNLOCK(nd.ni_vp, 0);
792 	vn_close(nd.ni_vp, FREAD, td->td_ucred, td);
793 	VFS_UNLOCK_GIANT(vfslocked);
794 
795 	return error;
796 }
797 
798 static void
799 link_elf_unload_file(linker_file_t file)
800 {
801 	elf_file_t ef = (elf_file_t) file;
802 	int i;
803 
804 	/* Notify MD code that a module is being unloaded. */
805 	elf_cpu_unload_file(file);
806 
807 	if (ef->preloaded) {
808 		if (ef->reltab)
809 			free(ef->reltab, M_LINKER);
810 		if (ef->relatab)
811 			free(ef->relatab, M_LINKER);
812 		if (ef->progtab)
813 			free(ef->progtab, M_LINKER);
814 		if (file->filename != NULL)
815 			preload_delete_name(file->filename);
816 		/* XXX reclaim module memory? */
817 		return;
818 	}
819 
820 	for (i = 0; i < ef->nrel; i++)
821 		if (ef->reltab[i].rel)
822 			free(ef->reltab[i].rel, M_LINKER);
823 	for (i = 0; i < ef->nrela; i++)
824 		if (ef->relatab[i].rela)
825 			free(ef->relatab[i].rela, M_LINKER);
826 	if (ef->reltab)
827 		free(ef->reltab, M_LINKER);
828 	if (ef->relatab)
829 		free(ef->relatab, M_LINKER);
830 	if (ef->progtab)
831 		free(ef->progtab, M_LINKER);
832 
833 	if (ef->object) {
834 		vm_map_remove(kernel_map, (vm_offset_t) ef->address,
835 		    (vm_offset_t) ef->address +
836 		    (ef->object->size << PAGE_SHIFT));
837 	}
838 	if (ef->e_shdr)
839 		free(ef->e_shdr, M_LINKER);
840 	if (ef->ddbsymtab)
841 		free(ef->ddbsymtab, M_LINKER);
842 	if (ef->ddbstrtab)
843 		free(ef->ddbstrtab, M_LINKER);
844 	if (ef->shstrtab)
845 		free(ef->shstrtab, M_LINKER);
846 }
847 
848 static const char *
849 symbol_name(elf_file_t ef, Elf_Size r_info)
850 {
851 	const Elf_Sym *ref;
852 
853 	if (ELF_R_SYM(r_info)) {
854 		ref = ef->ddbsymtab + ELF_R_SYM(r_info);
855 		return ef->ddbstrtab + ref->st_name;
856 	} else
857 		return NULL;
858 }
859 
860 static Elf_Addr
861 findbase(elf_file_t ef, int sec)
862 {
863 	int i;
864 	Elf_Addr base = 0;
865 
866 	for (i = 0; i < ef->nprogtab; i++) {
867 		if (sec == ef->progtab[i].sec) {
868 			base = (Elf_Addr)ef->progtab[i].addr;
869 			break;
870 		}
871 	}
872 	return base;
873 }
874 
875 static int
876 relocate_file(elf_file_t ef)
877 {
878 	const Elf_Rel *rellim;
879 	const Elf_Rel *rel;
880 	const Elf_Rela *relalim;
881 	const Elf_Rela *rela;
882 	const char *symname;
883 	const Elf_Sym *sym;
884 	int i;
885 	Elf_Size symidx;
886 	Elf_Addr base;
887 
888 
889 	/* Perform relocations without addend if there are any: */
890 	for (i = 0; i < ef->nrel; i++) {
891 		rel = ef->reltab[i].rel;
892 		if (rel == NULL)
893 			panic("lost a reltab!");
894 		rellim = rel + ef->reltab[i].nrel;
895 		base = findbase(ef, ef->reltab[i].sec);
896 		if (base == 0)
897 			panic("lost base for reltab");
898 		for ( ; rel < rellim; rel++) {
899 			symidx = ELF_R_SYM(rel->r_info);
900 			if (symidx >= ef->ddbsymcnt)
901 				continue;
902 			sym = ef->ddbsymtab + symidx;
903 			/* Local relocs are already done */
904 			if (ELF_ST_BIND(sym->st_info) == STB_LOCAL)
905 				continue;
906 			if (elf_reloc(&ef->lf, base, rel, ELF_RELOC_REL,
907 			    elf_obj_lookup)) {
908 				symname = symbol_name(ef, rel->r_info);
909 				printf("link_elf_obj: symbol %s undefined\n",
910 				    symname);
911 				return ENOENT;
912 			}
913 		}
914 	}
915 
916 	/* Perform relocations with addend if there are any: */
917 	for (i = 0; i < ef->nrela; i++) {
918 		rela = ef->relatab[i].rela;
919 		if (rela == NULL)
920 			panic("lost a relatab!");
921 		relalim = rela + ef->relatab[i].nrela;
922 		base = findbase(ef, ef->relatab[i].sec);
923 		if (base == 0)
924 			panic("lost base for relatab");
925 		for ( ; rela < relalim; rela++) {
926 			symidx = ELF_R_SYM(rela->r_info);
927 			if (symidx >= ef->ddbsymcnt)
928 				continue;
929 			sym = ef->ddbsymtab + symidx;
930 			/* Local relocs are already done */
931 			if (ELF_ST_BIND(sym->st_info) == STB_LOCAL)
932 				continue;
933 			if (elf_reloc(&ef->lf, base, rela, ELF_RELOC_RELA,
934 			    elf_obj_lookup)) {
935 				symname = symbol_name(ef, rela->r_info);
936 				printf("link_elf_obj: symbol %s undefined\n",
937 				    symname);
938 				return ENOENT;
939 			}
940 		}
941 	}
942 
943 	return 0;
944 }
945 
946 static int
947 link_elf_lookup_symbol(linker_file_t lf, const char *name, c_linker_sym_t *sym)
948 {
949 	elf_file_t ef = (elf_file_t) lf;
950 	const Elf_Sym *symp;
951 	const char *strp;
952 	int i;
953 
954 	for (i = 0, symp = ef->ddbsymtab; i < ef->ddbsymcnt; i++, symp++) {
955 		strp = ef->ddbstrtab + symp->st_name;
956 		if (symp->st_shndx != SHN_UNDEF && strcmp(name, strp) == 0) {
957 			*sym = (c_linker_sym_t) symp;
958 			return 0;
959 		}
960 	}
961 	return ENOENT;
962 }
963 
964 static int
965 link_elf_symbol_values(linker_file_t lf, c_linker_sym_t sym,
966     linker_symval_t *symval)
967 {
968 	elf_file_t ef = (elf_file_t) lf;
969 	const Elf_Sym *es = (const Elf_Sym*) sym;
970 
971 	if (es >= ef->ddbsymtab && es < (ef->ddbsymtab + ef->ddbsymcnt)) {
972 		symval->name = ef->ddbstrtab + es->st_name;
973 		symval->value = (caddr_t)es->st_value;
974 		symval->size = es->st_size;
975 		return 0;
976 	}
977 	return ENOENT;
978 }
979 
980 static int
981 link_elf_search_symbol(linker_file_t lf, caddr_t value,
982     c_linker_sym_t *sym, long *diffp)
983 {
984 	elf_file_t ef = (elf_file_t) lf;
985 	u_long off = (uintptr_t) (void *) value;
986 	u_long diff = off;
987 	u_long st_value;
988 	const Elf_Sym *es;
989 	const Elf_Sym *best = 0;
990 	int i;
991 
992 	for (i = 0, es = ef->ddbsymtab; i < ef->ddbsymcnt; i++, es++) {
993 		if (es->st_name == 0)
994 			continue;
995 		st_value = es->st_value;
996 		if (off >= st_value) {
997 			if (off - st_value < diff) {
998 				diff = off - st_value;
999 				best = es;
1000 				if (diff == 0)
1001 					break;
1002 			} else if (off - st_value == diff) {
1003 				best = es;
1004 			}
1005 		}
1006 	}
1007 	if (best == 0)
1008 		*diffp = off;
1009 	else
1010 		*diffp = diff;
1011 	*sym = (c_linker_sym_t) best;
1012 
1013 	return 0;
1014 }
1015 
1016 /*
1017  * Look up a linker set on an ELF system.
1018  */
1019 static int
1020 link_elf_lookup_set(linker_file_t lf, const char *name,
1021     void ***startp, void ***stopp, int *countp)
1022 {
1023 	elf_file_t ef = (elf_file_t)lf;
1024 	void **start, **stop;
1025 	int i, count;
1026 
1027 	/* Relative to section number */
1028 	for (i = 0; i < ef->nprogtab; i++) {
1029 		if ((strncmp(ef->progtab[i].name, "set_", 4) == 0) &&
1030 		    strcmp(ef->progtab[i].name + 4, name) == 0) {
1031 			start  = (void **)ef->progtab[i].addr;
1032 			stop = (void **)((char *)ef->progtab[i].addr +
1033 			    ef->progtab[i].size);
1034 			count = stop - start;
1035 			if (startp)
1036 				*startp = start;
1037 			if (stopp)
1038 				*stopp = stop;
1039 			if (countp)
1040 				*countp = count;
1041 			return (0);
1042 		}
1043 	}
1044 	return (ESRCH);
1045 }
1046 
1047 static int
1048 link_elf_each_function_name(linker_file_t file,
1049     int (*callback)(const char *, void *), void *opaque)
1050 {
1051 	elf_file_t ef = (elf_file_t)file;
1052 	const Elf_Sym *symp;
1053 	int i, error;
1054 
1055 	/* Exhaustive search */
1056 	for (i = 0, symp = ef->ddbsymtab; i < ef->ddbsymcnt; i++, symp++) {
1057 		if (symp->st_value != 0 &&
1058 		    ELF_ST_TYPE(symp->st_info) == STT_FUNC) {
1059 			error = callback(ef->ddbstrtab + symp->st_name, opaque);
1060 			if (error)
1061 				return (error);
1062 		}
1063 	}
1064 	return (0);
1065 }
1066 
1067 /*
1068  * Symbol lookup function that can be used when the symbol index is known (ie
1069  * in relocations). It uses the symbol index instead of doing a fully fledged
1070  * hash table based lookup when such is valid. For example for local symbols.
1071  * This is not only more efficient, it's also more correct. It's not always
1072  * the case that the symbol can be found through the hash table.
1073  */
1074 static Elf_Addr
1075 elf_obj_lookup(linker_file_t lf, Elf_Size symidx, int deps)
1076 {
1077 	elf_file_t ef = (elf_file_t)lf;
1078 	const Elf_Sym *sym;
1079 	const char *symbol;
1080 	Elf_Addr ret;
1081 
1082 	/* Don't even try to lookup the symbol if the index is bogus. */
1083 	if (symidx >= ef->ddbsymcnt)
1084 		return (0);
1085 
1086 	sym = ef->ddbsymtab + symidx;
1087 
1088 	/* Quick answer if there is a definition included. */
1089 	if (sym->st_shndx != SHN_UNDEF)
1090 		return (sym->st_value);
1091 
1092 	/* If we get here, then it is undefined and needs a lookup. */
1093 	switch (ELF_ST_BIND(sym->st_info)) {
1094 	case STB_LOCAL:
1095 		/* Local, but undefined? huh? */
1096 		return (0);
1097 
1098 	case STB_GLOBAL:
1099 		/* Relative to Data or Function name */
1100 		symbol = ef->ddbstrtab + sym->st_name;
1101 
1102 		/* Force a lookup failure if the symbol name is bogus. */
1103 		if (*symbol == 0)
1104 			return (0);
1105 		ret = ((Elf_Addr)linker_file_lookup_symbol(lf, symbol, deps));
1106 		return ret;
1107 
1108 	case STB_WEAK:
1109 		printf("link_elf_obj: Weak symbols not supported\n");
1110 		return (0);
1111 
1112 	default:
1113 		return (0);
1114 	}
1115 }
1116 
1117 static void
1118 link_elf_fix_link_set(elf_file_t ef)
1119 {
1120 	static const char startn[] = "__start_";
1121 	static const char stopn[] = "__stop_";
1122 	Elf_Sym *sym;
1123 	const char *sym_name, *linkset_name;
1124 	Elf_Addr startp, stopp;
1125 	Elf_Size symidx;
1126 	int start, i;
1127 
1128 	startp = stopp = 0;
1129 	for (symidx = 1 /* zero entry is special */;
1130 		symidx < ef->ddbsymcnt; symidx++) {
1131 		sym = ef->ddbsymtab + symidx;
1132 		if (sym->st_shndx != SHN_UNDEF)
1133 			continue;
1134 
1135 		sym_name = ef->ddbstrtab + sym->st_name;
1136 		if (strncmp(sym_name, startn, sizeof(startn) - 1) == 0) {
1137 			start = 1;
1138 			linkset_name = sym_name + sizeof(startn) - 1;
1139 		}
1140 		else if (strncmp(sym_name, stopn, sizeof(stopn) - 1) == 0) {
1141 			start = 0;
1142 			linkset_name = sym_name + sizeof(stopn) - 1;
1143 		}
1144 		else
1145 			continue;
1146 
1147 		for (i = 0; i < ef->nprogtab; i++) {
1148 			if (strcmp(ef->progtab[i].name, linkset_name) == 0) {
1149 				startp = (Elf_Addr)ef->progtab[i].addr;
1150 				stopp = (Elf_Addr)(startp + ef->progtab[i].size);
1151 				break;
1152 			}
1153 		}
1154 		if (i == ef->nprogtab)
1155 			continue;
1156 
1157 		sym->st_value = start ? startp : stopp;
1158 		sym->st_shndx = i;
1159 	}
1160 }
1161 
1162 static void
1163 link_elf_reloc_local(linker_file_t lf)
1164 {
1165 	elf_file_t ef = (elf_file_t)lf;
1166 	const Elf_Rel *rellim;
1167 	const Elf_Rel *rel;
1168 	const Elf_Rela *relalim;
1169 	const Elf_Rela *rela;
1170 	const Elf_Sym *sym;
1171 	Elf_Addr base;
1172 	int i;
1173 	Elf_Size symidx;
1174 
1175 	link_elf_fix_link_set(ef);
1176 
1177 	/* Perform relocations without addend if there are any: */
1178 	for (i = 0; i < ef->nrel; i++) {
1179 		rel = ef->reltab[i].rel;
1180 		if (rel == NULL)
1181 			panic("lost a reltab!");
1182 		rellim = rel + ef->reltab[i].nrel;
1183 		base = findbase(ef, ef->reltab[i].sec);
1184 		if (base == 0)
1185 			panic("lost base for reltab");
1186 		for ( ; rel < rellim; rel++) {
1187 			symidx = ELF_R_SYM(rel->r_info);
1188 			if (symidx >= ef->ddbsymcnt)
1189 				continue;
1190 			sym = ef->ddbsymtab + symidx;
1191 			/* Only do local relocs */
1192 			if (ELF_ST_BIND(sym->st_info) != STB_LOCAL)
1193 				continue;
1194 			elf_reloc_local(lf, base, rel, ELF_RELOC_REL,
1195 			    elf_obj_lookup);
1196 		}
1197 	}
1198 
1199 	/* Perform relocations with addend if there are any: */
1200 	for (i = 0; i < ef->nrela; i++) {
1201 		rela = ef->relatab[i].rela;
1202 		if (rela == NULL)
1203 			panic("lost a relatab!");
1204 		relalim = rela + ef->relatab[i].nrela;
1205 		base = findbase(ef, ef->relatab[i].sec);
1206 		if (base == 0)
1207 			panic("lost base for relatab");
1208 		for ( ; rela < relalim; rela++) {
1209 			symidx = ELF_R_SYM(rela->r_info);
1210 			if (symidx >= ef->ddbsymcnt)
1211 				continue;
1212 			sym = ef->ddbsymtab + symidx;
1213 			/* Only do local relocs */
1214 			if (ELF_ST_BIND(sym->st_info) != STB_LOCAL)
1215 				continue;
1216 			elf_reloc_local(lf, base, rela, ELF_RELOC_RELA,
1217 			    elf_obj_lookup);
1218 		}
1219 	}
1220 }
1221