xref: /freebsd/stand/common/load_elf.c (revision 2e4311906d8c8dc7a7c726345268253bca6d4acc)
1 /*-
2  * Copyright (c) 1998 Michael Smith <msmith@freebsd.org>
3  * Copyright (c) 1998 Peter Wemm <peter@freebsd.org>
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 <sys/param.h>
32 #include <sys/endian.h>
33 #include <sys/exec.h>
34 #include <sys/linker.h>
35 #include <sys/module.h>
36 #include <sys/stdint.h>
37 #include <string.h>
38 #include <machine/elf.h>
39 #include <stand.h>
40 #define FREEBSD_ELF
41 #include <sys/link_elf.h>
42 
43 #include "bootstrap.h"
44 
45 #define COPYOUT(s,d,l)	archsw.arch_copyout((vm_offset_t)(s), d, l)
46 
47 #if defined(__i386__) && __ELF_WORD_SIZE == 64
48 #undef ELF_TARG_CLASS
49 #undef ELF_TARG_MACH
50 #define ELF_TARG_CLASS  ELFCLASS64
51 #define ELF_TARG_MACH   EM_X86_64
52 #endif
53 
54 typedef struct elf_file {
55 	Elf_Phdr	*ph;
56 	Elf_Ehdr	*ehdr;
57 	Elf_Sym		*symtab;
58 	Elf_Hashelt	*hashtab;
59 	Elf_Hashelt	nbuckets;
60 	Elf_Hashelt	nchains;
61 	Elf_Hashelt	*buckets;
62 	Elf_Hashelt	*chains;
63 	Elf_Rel	*rel;
64 	size_t	relsz;
65 	Elf_Rela	*rela;
66 	size_t	relasz;
67 	char	*strtab;
68 	size_t	strsz;
69 	int		fd;
70 	caddr_t	firstpage;
71 	size_t	firstlen;
72 	int		kernel;
73 	uint64_t	off;
74 #ifdef LOADER_VERIEXEC_VECTX
75 	struct vectx	*vctx;
76 #endif
77 } *elf_file_t;
78 
79 #ifdef LOADER_VERIEXEC_VECTX
80 #define VECTX_HANDLE(ef) (ef)->vctx
81 #else
82 #define VECTX_HANDLE(ef) (ef)->fd
83 #endif
84 
85 static int __elfN(loadimage)(struct preloaded_file *mp, elf_file_t ef,
86     uint64_t loadaddr);
87 static int __elfN(lookup_symbol)(elf_file_t ef, const char* name,
88     Elf_Sym *sym, unsigned char type);
89 static int __elfN(reloc_ptr)(struct preloaded_file *mp, elf_file_t ef,
90     Elf_Addr p, void *val, size_t len);
91 static int __elfN(parse_modmetadata)(struct preloaded_file *mp, elf_file_t ef,
92     Elf_Addr p_start, Elf_Addr p_end);
93 static symaddr_fn __elfN(symaddr);
94 static char	*fake_modname(const char *name);
95 
96 const char	*__elfN(kerneltype) = "elf kernel";
97 const char	*__elfN(moduletype) = "elf module";
98 
99 uint64_t	__elfN(relocation_offset) = 0;
100 
101 extern void elf_wrong_field_size(void);
102 #define CONVERT_FIELD(b, f, e)			\
103 	switch (sizeof((b)->f)) {		\
104 	case 2:					\
105 		(b)->f = e ## 16toh((b)->f);	\
106 		break;				\
107 	case 4:					\
108 		(b)->f = e ## 32toh((b)->f);	\
109 		break;				\
110 	case 8:					\
111 		(b)->f = e ## 64toh((b)->f);	\
112 		break;				\
113 	default:				\
114 		/* Force a link time error. */	\
115 		elf_wrong_field_size();		\
116 		break;				\
117 	}
118 
119 #define CONVERT_SWITCH(h, d, f)			\
120 	switch ((h)->e_ident[EI_DATA]) {	\
121 	case ELFDATA2MSB:			\
122 		f(d, be);			\
123 		break;				\
124 	case ELFDATA2LSB:			\
125 		f(d, le);			\
126 		break;				\
127 	default:				\
128 		return (EINVAL);		\
129 	}
130 
131 
132 static int elf_header_convert(Elf_Ehdr *ehdr)
133 {
134 	/*
135 	 * Fixup ELF header endianness.
136 	 *
137 	 * The Xhdr structure was loaded using block read call to optimize file
138 	 * accesses. It might happen, that the endianness of the system memory
139 	 * is different that endianness of the ELF header.  Swap fields here to
140 	 * guarantee that Xhdr always contain valid data regardless of
141 	 * architecture.
142 	 */
143 #define HEADER_FIELDS(b, e)			\
144 	CONVERT_FIELD(b, e_type, e);		\
145 	CONVERT_FIELD(b, e_machine, e);		\
146 	CONVERT_FIELD(b, e_version, e);		\
147 	CONVERT_FIELD(b, e_entry, e);		\
148 	CONVERT_FIELD(b, e_phoff, e);		\
149 	CONVERT_FIELD(b, e_shoff, e);		\
150 	CONVERT_FIELD(b, e_flags, e);		\
151 	CONVERT_FIELD(b, e_ehsize, e);		\
152 	CONVERT_FIELD(b, e_phentsize, e);	\
153 	CONVERT_FIELD(b, e_phnum, e);		\
154 	CONVERT_FIELD(b, e_shentsize, e);	\
155 	CONVERT_FIELD(b, e_shnum, e);		\
156 	CONVERT_FIELD(b, e_shstrndx, e)
157 
158 	CONVERT_SWITCH(ehdr, ehdr, HEADER_FIELDS);
159 
160 #undef HEADER_FIELDS
161 
162 	return (0);
163 }
164 
165 static int elf_program_header_convert(const Elf_Ehdr *ehdr, Elf_Phdr *phdr)
166 {
167 #define PROGRAM_HEADER_FIELDS(b, e)		\
168 	CONVERT_FIELD(b, p_type, e);		\
169 	CONVERT_FIELD(b, p_flags, e);		\
170 	CONVERT_FIELD(b, p_offset, e);		\
171 	CONVERT_FIELD(b, p_vaddr, e);		\
172 	CONVERT_FIELD(b, p_paddr, e);		\
173 	CONVERT_FIELD(b, p_filesz, e);		\
174 	CONVERT_FIELD(b, p_memsz, e);		\
175 	CONVERT_FIELD(b, p_align, e)
176 
177 	CONVERT_SWITCH(ehdr, phdr, PROGRAM_HEADER_FIELDS);
178 
179 #undef PROGRAM_HEADER_FIELDS
180 
181 	return (0);
182 }
183 
184 static int elf_section_header_convert(const Elf_Ehdr *ehdr, Elf_Shdr *shdr)
185 {
186 #define SECTION_HEADER_FIELDS(b, e)		\
187 	CONVERT_FIELD(b, sh_name, e);		\
188 	CONVERT_FIELD(b, sh_type, e);		\
189 	CONVERT_FIELD(b, sh_link, e);		\
190 	CONVERT_FIELD(b, sh_info, e);		\
191 	CONVERT_FIELD(b, sh_flags, e);		\
192 	CONVERT_FIELD(b, sh_addr, e);		\
193 	CONVERT_FIELD(b, sh_offset, e);		\
194 	CONVERT_FIELD(b, sh_size, e);		\
195 	CONVERT_FIELD(b, sh_addralign, e);	\
196 	CONVERT_FIELD(b, sh_entsize, e)
197 
198 	CONVERT_SWITCH(ehdr, shdr, SECTION_HEADER_FIELDS);
199 
200 #undef SECTION_HEADER_FIELDS
201 
202 	return (0);
203 }
204 #undef CONVERT_SWITCH
205 #undef CONVERT_FIELD
206 
207 
208 #ifdef __amd64__
209 static bool
210 is_kernphys_relocatable(elf_file_t ef)
211 {
212 	Elf_Sym sym;
213 
214 	return (__elfN(lookup_symbol)(ef, "kernphys", &sym, STT_OBJECT) == 0 &&
215 	    sym.st_size == 8);
216 }
217 #endif
218 
219 #ifdef __i386__
220 static bool
221 is_tg_kernel_support(struct preloaded_file *fp, elf_file_t ef)
222 {
223 	Elf_Sym		sym;
224 	Elf_Addr	p_start, p_end, v, p;
225 	char		vd_name[16];
226 	int		error;
227 
228 	if (__elfN(lookup_symbol)(ef, "__start_set_vt_drv_set", &sym, STT_NOTYPE) != 0)
229 		return (false);
230 	p_start = sym.st_value + ef->off;
231 	if (__elfN(lookup_symbol)(ef, "__stop_set_vt_drv_set", &sym, STT_NOTYPE) != 0)
232 		return (false);
233 	p_end = sym.st_value + ef->off;
234 
235 	/*
236 	 * Walk through vt_drv_set, each vt driver structure starts with
237 	 * static 16 chars for driver name. If we have "vbefb", return true.
238 	 */
239 	for (p = p_start; p < p_end; p += sizeof(Elf_Addr)) {
240 		COPYOUT(p, &v, sizeof(v));
241 
242 		error = __elfN(reloc_ptr)(fp, ef, p, &v, sizeof(v));
243 		if (error == EOPNOTSUPP)
244 			v += ef->off;
245 		else if (error != 0)
246 			return (false);
247 		COPYOUT(v, &vd_name, sizeof(vd_name));
248 		if (strncmp(vd_name, "vbefb", sizeof(vd_name)) == 0)
249 			return (true);
250 	}
251 
252 	return (false);
253 }
254 #endif
255 
256 static int
257 __elfN(load_elf_header)(char *filename, elf_file_t ef)
258 {
259 	ssize_t			 bytes_read;
260 	Elf_Ehdr		*ehdr;
261 	int			 err;
262 
263 	/*
264 	 * Open the image, read and validate the ELF header
265 	 */
266 	if (filename == NULL)	/* can't handle nameless */
267 		return (EFTYPE);
268 	if ((ef->fd = open(filename, O_RDONLY)) == -1)
269 		return (errno);
270 	ef->firstpage = malloc(PAGE_SIZE);
271 	if (ef->firstpage == NULL) {
272 		close(ef->fd);
273 		return (ENOMEM);
274 	}
275 	preload(ef->fd);
276 #ifdef LOADER_VERIEXEC_VECTX
277 	{
278 		int verror;
279 
280 		ef->vctx = vectx_open(ef->fd, filename, 0L, NULL, &verror, __func__);
281 		if (verror) {
282 			printf("Unverified %s: %s\n", filename, ve_error_get());
283 			close(ef->fd);
284 			free(ef->vctx);
285 			return (EAUTH);
286 		}
287 	}
288 #endif
289 	bytes_read = VECTX_READ(VECTX_HANDLE(ef), ef->firstpage, PAGE_SIZE);
290 	ef->firstlen = (size_t)bytes_read;
291 	if (bytes_read < 0 || ef->firstlen <= sizeof(Elf_Ehdr)) {
292 		err = EFTYPE; /* could be EIO, but may be small file */
293 		goto error;
294 	}
295 	ehdr = ef->ehdr = (Elf_Ehdr *)ef->firstpage;
296 
297 	/* Is it ELF? */
298 	if (!IS_ELF(*ehdr)) {
299 		err = EFTYPE;
300 		goto error;
301 	}
302 
303 	if (ehdr->e_ident[EI_CLASS] != ELF_TARG_CLASS || /* Layout ? */
304 	    ehdr->e_ident[EI_DATA] != ELF_TARG_DATA ||
305 	    ehdr->e_ident[EI_VERSION] != EV_CURRENT) /* Version ? */ {
306 		err = EFTYPE;
307 		goto error;
308 	}
309 
310 	err = elf_header_convert(ehdr);
311 	if (err)
312 		goto error;
313 
314 	if (ehdr->e_version != EV_CURRENT || ehdr->e_machine != ELF_TARG_MACH) {
315 		/* Machine ? */
316 		err = EFTYPE;
317 		goto error;
318 	}
319 
320 #if defined(LOADER_VERIEXEC) && !defined(LOADER_VERIEXEC_VECTX)
321 	if (verify_file(ef->fd, filename, bytes_read, VE_MUST, __func__) < 0) {
322 		err = EAUTH;
323 		goto error;
324 	}
325 #endif
326 	return (0);
327 
328 error:
329 	if (ef->firstpage != NULL) {
330 		free(ef->firstpage);
331 		ef->firstpage = NULL;
332 	}
333 	if (ef->fd != -1) {
334 #ifdef LOADER_VERIEXEC_VECTX
335 		free(ef->vctx);
336 #endif
337 		close(ef->fd);
338 		ef->fd = -1;
339 	}
340 	return (err);
341 }
342 
343 /*
344  * Attempt to load the file (file) as an ELF module.  It will be stored at
345  * (dest), and a pointer to a module structure describing the loaded object
346  * will be saved in (result).
347  */
348 int
349 __elfN(loadfile)(char *filename, uint64_t dest, struct preloaded_file **result)
350 {
351 	return (__elfN(loadfile_raw)(filename, dest, result, 0));
352 }
353 
354 int
355 __elfN(loadfile_raw)(char *filename, uint64_t dest,
356     struct preloaded_file **result, int multiboot)
357 {
358 	struct preloaded_file	*fp, *kfp;
359 	struct elf_file		ef;
360 	Elf_Ehdr		*ehdr;
361 	int			err;
362 
363 	fp = NULL;
364 	bzero(&ef, sizeof(struct elf_file));
365 	ef.fd = -1;
366 
367 	err = __elfN(load_elf_header)(filename, &ef);
368 	if (err != 0)
369 		return (err);
370 
371 	ehdr = ef.ehdr;
372 
373 	/*
374 	 * Check to see what sort of module we are.
375 	 */
376 	kfp = file_findfile(NULL, __elfN(kerneltype));
377 #ifdef __powerpc__
378 	/*
379 	 * Kernels can be ET_DYN, so just assume the first loaded object is the
380 	 * kernel. This assumption will be checked later.
381 	 */
382 	if (kfp == NULL)
383 		ef.kernel = 1;
384 #endif
385 	if (ef.kernel || ehdr->e_type == ET_EXEC) {
386 		/* Looks like a kernel */
387 		if (kfp != NULL) {
388 			printf("elf" __XSTRING(__ELF_WORD_SIZE)
389 			    "_loadfile: kernel already loaded\n");
390 			err = EPERM;
391 			goto oerr;
392 		}
393 		/*
394 		 * Calculate destination address based on kernel entrypoint.
395 		 *
396 		 * For ARM, the destination address is independent of any values
397 		 * in the elf header (an ARM kernel can be loaded at any 2MB
398 		 * boundary), so we leave dest set to the value calculated by
399 		 * archsw.arch_loadaddr() and passed in to this function.
400 		 */
401 #ifndef __arm__
402 		if (ehdr->e_type == ET_EXEC)
403 			dest = (ehdr->e_entry & ~PAGE_MASK);
404 #endif
405 		if ((ehdr->e_entry & ~PAGE_MASK) == 0) {
406 			printf("elf" __XSTRING(__ELF_WORD_SIZE)
407 			    "_loadfile: not a kernel (maybe static binary?)\n");
408 			err = EPERM;
409 			goto oerr;
410 		}
411 		ef.kernel = 1;
412 
413 	} else if (ehdr->e_type == ET_DYN) {
414 		/* Looks like a kld module */
415 		if (multiboot != 0) {
416 			printf("elf" __XSTRING(__ELF_WORD_SIZE)
417 			    "_loadfile: can't load module as multiboot\n");
418 			err = EPERM;
419 			goto oerr;
420 		}
421 		if (kfp == NULL) {
422 			printf("elf" __XSTRING(__ELF_WORD_SIZE)
423 			    "_loadfile: can't load module before kernel\n");
424 			err = EPERM;
425 			goto oerr;
426 		}
427 		if (strcmp(__elfN(kerneltype), kfp->f_type)) {
428 			printf("elf" __XSTRING(__ELF_WORD_SIZE)
429 			 "_loadfile: can't load module with kernel type '%s'\n",
430 			    kfp->f_type);
431 			err = EPERM;
432 			goto oerr;
433 		}
434 		/* Looks OK, got ahead */
435 		ef.kernel = 0;
436 
437 	} else {
438 		err = EFTYPE;
439 		goto oerr;
440 	}
441 
442 	if (archsw.arch_loadaddr != NULL)
443 		dest = archsw.arch_loadaddr(LOAD_ELF, ehdr, dest);
444 	else
445 		dest = roundup(dest, PAGE_SIZE);
446 
447 	/*
448 	 * Ok, we think we should handle this.
449 	 */
450 	fp = file_alloc();
451 	if (fp == NULL) {
452 		printf("elf" __XSTRING(__ELF_WORD_SIZE)
453 		    "_loadfile: cannot allocate module info\n");
454 		err = EPERM;
455 		goto out;
456 	}
457 	if (ef.kernel == 1 && multiboot == 0)
458 		setenv("kernelname", filename, 1);
459 	fp->f_name = strdup(filename);
460 	if (multiboot == 0)
461 		fp->f_type = strdup(ef.kernel ?
462 		    __elfN(kerneltype) : __elfN(moduletype));
463 	else
464 		fp->f_type = strdup("elf multiboot kernel");
465 
466 #ifdef ELF_VERBOSE
467 	if (ef.kernel)
468 		printf("%s entry at 0x%jx\n", filename,
469 		    (uintmax_t)ehdr->e_entry);
470 #else
471 	printf("%s ", filename);
472 #endif
473 
474 	fp->f_size = __elfN(loadimage)(fp, &ef, dest);
475 	if (fp->f_size == 0 || fp->f_addr == 0)
476 		goto ioerr;
477 
478 	/* save exec header as metadata */
479 	file_addmetadata(fp, MODINFOMD_ELFHDR, sizeof(*ehdr), ehdr);
480 
481 	/* Load OK, return module pointer */
482 	*result = (struct preloaded_file *)fp;
483 	err = 0;
484 #ifdef __amd64__
485 	fp->f_kernphys_relocatable = multiboot || is_kernphys_relocatable(&ef);
486 #endif
487 #ifdef __i386__
488 	fp->f_tg_kernel_support = is_tg_kernel_support(fp, &ef);
489 #endif
490 	goto out;
491 
492 ioerr:
493 	err = EIO;
494 oerr:
495 	file_discard(fp);
496 out:
497 	if (ef.firstpage)
498 		free(ef.firstpage);
499 	if (ef.fd != -1) {
500 #ifdef LOADER_VERIEXEC_VECTX
501 		if (!err && ef.vctx) {
502 			int verror;
503 
504 			verror = vectx_close(ef.vctx, VE_MUST, __func__);
505 			if (verror) {
506 				err = EAUTH;
507 				file_discard(fp);
508 			}
509 		}
510 #endif
511 		close(ef.fd);
512 	}
513 	return (err);
514 }
515 
516 /*
517  * With the file (fd) open on the image, and (ehdr) containing
518  * the Elf header, load the image at (off)
519  */
520 static int
521 __elfN(loadimage)(struct preloaded_file *fp, elf_file_t ef, uint64_t off)
522 {
523 	int		i;
524 	u_int		j;
525 	Elf_Ehdr	*ehdr;
526 	Elf_Phdr	*phdr, *php;
527 	Elf_Shdr	*shdr;
528 	char		*shstr;
529 	int		ret;
530 	vm_offset_t	firstaddr;
531 	vm_offset_t	lastaddr;
532 	size_t		chunk;
533 	ssize_t		result;
534 	Elf_Addr	ssym, esym;
535 	Elf_Dyn		*dp;
536 	Elf_Addr	adp;
537 	Elf_Addr	ctors;
538 	int		ndp;
539 	int		symstrindex;
540 	int		symtabindex;
541 	Elf_Size	size;
542 	u_int		fpcopy;
543 	Elf_Sym		sym;
544 	Elf_Addr	p_start, p_end;
545 
546 	dp = NULL;
547 	shdr = NULL;
548 	ret = 0;
549 	firstaddr = lastaddr = 0;
550 	ehdr = ef->ehdr;
551 #ifdef __powerpc__
552 	if (ef->kernel) {
553 #else
554 	if (ehdr->e_type == ET_EXEC) {
555 #endif
556 #if defined(__i386__) || defined(__amd64__)
557 #if __ELF_WORD_SIZE == 64
558 		/* x86_64 relocates after locore */
559 		off = - (off & 0xffffffffff000000ull);
560 #else
561 		/* i386 relocates after locore */
562 		off = - (off & 0xff000000u);
563 #endif
564 #elif defined(__powerpc__)
565 		/*
566 		 * On the purely virtual memory machines like e500, the kernel
567 		 * is linked against its final VA range, which is most often
568 		 * not available at the loader stage, but only after kernel
569 		 * initializes and completes its VM settings. In such cases we
570 		 * cannot use p_vaddr field directly to load ELF segments, but
571 		 * put them at some 'load-time' locations.
572 		 */
573 		if (off & 0xf0000000u) {
574 			off = -(off & 0xf0000000u);
575 			/*
576 			 * XXX the physical load address should not be
577 			 * hardcoded. Note that the Book-E kernel assumes that
578 			 * it's loaded at a 16MB boundary for now...
579 			 */
580 			off += 0x01000000;
581 		}
582 		ehdr->e_entry += off;
583 #ifdef ELF_VERBOSE
584 		printf("Converted entry 0x%jx\n", (uintmax_t)ehdr->e_entry);
585 #endif
586 #elif defined(__arm__) && !defined(EFI)
587 		/*
588 		 * The elf headers in arm kernels specify virtual addresses in
589 		 * all header fields, even the ones that should be physical
590 		 * addresses.  We assume the entry point is in the first page,
591 		 * and masking the page offset will leave us with the virtual
592 		 * address the kernel was linked at.  We subtract that from the
593 		 * load offset, making 'off' into the value which, when added
594 		 * to a virtual address in an elf header, translates it to a
595 		 * physical address.  We do the va->pa conversion on the entry
596 		 * point address in the header now, so that later we can launch
597 		 * the kernel by just jumping to that address.
598 		 *
599 		 * When booting from UEFI the copyin and copyout functions
600 		 * handle adjusting the location relative to the first virtual
601 		 * address.  Because of this there is no need to adjust the
602 		 * offset or entry point address as these will both be handled
603 		 * by the efi code.
604 		 */
605 		off -= ehdr->e_entry & ~PAGE_MASK;
606 		ehdr->e_entry += off;
607 #ifdef ELF_VERBOSE
608 		printf("ehdr->e_entry 0x%jx, va<->pa off %llx\n",
609 		    (uintmax_t)ehdr->e_entry, off);
610 #endif
611 #else
612 		off = 0;	/* other archs use direct mapped kernels */
613 #endif
614 	}
615 	ef->off = off;
616 
617 	if (ef->kernel)
618 		__elfN(relocation_offset) = off;
619 
620 	if ((ehdr->e_phoff + ehdr->e_phnum * sizeof(*phdr)) > ef->firstlen) {
621 		printf("elf" __XSTRING(__ELF_WORD_SIZE)
622 		    "_loadimage: program header not within first page\n");
623 		goto out;
624 	}
625 	phdr = (Elf_Phdr *)(ef->firstpage + ehdr->e_phoff);
626 
627 	for (i = 0; i < ehdr->e_phnum; i++) {
628 		if (elf_program_header_convert(ehdr, phdr))
629 			continue;
630 
631 		/* We want to load PT_LOAD segments only.. */
632 		if (phdr[i].p_type != PT_LOAD)
633 			continue;
634 
635 #ifdef ELF_VERBOSE
636 		printf("Segment: 0x%lx@0x%lx -> 0x%lx-0x%lx",
637 		    (long)phdr[i].p_filesz, (long)phdr[i].p_offset,
638 		    (long)(phdr[i].p_vaddr + off),
639 		    (long)(phdr[i].p_vaddr + off + phdr[i].p_memsz - 1));
640 #else
641 		if ((phdr[i].p_flags & PF_W) == 0) {
642 			printf("text=0x%lx ", (long)phdr[i].p_filesz);
643 		} else {
644 			printf("data=0x%lx", (long)phdr[i].p_filesz);
645 			if (phdr[i].p_filesz < phdr[i].p_memsz)
646 				printf("+0x%lx", (long)(phdr[i].p_memsz -
647 				    phdr[i].p_filesz));
648 			printf(" ");
649 		}
650 #endif
651 		fpcopy = 0;
652 		if (ef->firstlen > phdr[i].p_offset) {
653 			fpcopy = ef->firstlen - phdr[i].p_offset;
654 			archsw.arch_copyin(ef->firstpage + phdr[i].p_offset,
655 			    phdr[i].p_vaddr + off, fpcopy);
656 		}
657 		if (phdr[i].p_filesz > fpcopy) {
658 			if (kern_pread(VECTX_HANDLE(ef),
659 			    phdr[i].p_vaddr + off + fpcopy,
660 			    phdr[i].p_filesz - fpcopy,
661 			    phdr[i].p_offset + fpcopy) != 0) {
662 				printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
663 				    "_loadimage: read failed\n");
664 				goto out;
665 			}
666 		}
667 		/* clear space from oversized segments; eg: bss */
668 		if (phdr[i].p_filesz < phdr[i].p_memsz) {
669 #ifdef ELF_VERBOSE
670 			printf(" (bss: 0x%lx-0x%lx)",
671 			    (long)(phdr[i].p_vaddr + off + phdr[i].p_filesz),
672 			    (long)(phdr[i].p_vaddr + off + phdr[i].p_memsz -1));
673 #endif
674 
675 			kern_bzero(phdr[i].p_vaddr + off + phdr[i].p_filesz,
676 			    phdr[i].p_memsz - phdr[i].p_filesz);
677 		}
678 #ifdef ELF_VERBOSE
679 		printf("\n");
680 #endif
681 
682 		if (archsw.arch_loadseg != NULL)
683 			archsw.arch_loadseg(ehdr, phdr + i, off);
684 
685 		if (firstaddr == 0 || firstaddr > (phdr[i].p_vaddr + off))
686 			firstaddr = phdr[i].p_vaddr + off;
687 		if (lastaddr == 0 || lastaddr <
688 		    (phdr[i].p_vaddr + off + phdr[i].p_memsz))
689 			lastaddr = phdr[i].p_vaddr + off + phdr[i].p_memsz;
690 	}
691 	lastaddr = roundup(lastaddr, sizeof(long));
692 
693 	/*
694 	 * Get the section headers.  We need this for finding the .ctors
695 	 * section as well as for loading any symbols.  Both may be hard
696 	 * to do if reading from a .gz file as it involves seeking.  I
697 	 * think the rule is going to have to be that you must strip a
698 	 * file to remove symbols before gzipping it.
699 	 */
700 	chunk = (size_t)ehdr->e_shnum * (size_t)ehdr->e_shentsize;
701 	if (chunk == 0 || ehdr->e_shoff == 0)
702 		goto nosyms;
703 	shdr = alloc_pread(VECTX_HANDLE(ef), ehdr->e_shoff, chunk);
704 	if (shdr == NULL) {
705 		printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
706 		    "_loadimage: failed to read section headers");
707 		goto nosyms;
708 	}
709 
710 	for (i = 0; i < ehdr->e_shnum; i++)
711 		elf_section_header_convert(ehdr, &shdr[i]);
712 
713 	file_addmetadata(fp, MODINFOMD_SHDR, chunk, shdr);
714 
715 	/*
716 	 * Read the section string table and look for the .ctors section.
717 	 * We need to tell the kernel where it is so that it can call the
718 	 * ctors.
719 	 */
720 	chunk = shdr[ehdr->e_shstrndx].sh_size;
721 	if (chunk) {
722 		shstr = alloc_pread(VECTX_HANDLE(ef),
723 		    shdr[ehdr->e_shstrndx].sh_offset, chunk);
724 		if (shstr) {
725 			for (i = 0; i < ehdr->e_shnum; i++) {
726 				if (strcmp(shstr + shdr[i].sh_name,
727 				    ".ctors") != 0)
728 					continue;
729 				ctors = shdr[i].sh_addr;
730 				file_addmetadata(fp, MODINFOMD_CTORS_ADDR,
731 				    sizeof(ctors), &ctors);
732 				size = shdr[i].sh_size;
733 				file_addmetadata(fp, MODINFOMD_CTORS_SIZE,
734 				    sizeof(size), &size);
735 				break;
736 			}
737 			free(shstr);
738 		}
739 	}
740 
741 	/*
742 	 * Now load any symbols.
743 	 */
744 	symtabindex = -1;
745 	symstrindex = -1;
746 	for (i = 0; i < ehdr->e_shnum; i++) {
747 		if (shdr[i].sh_type != SHT_SYMTAB)
748 			continue;
749 		for (j = 0; j < ehdr->e_phnum; j++) {
750 			if (phdr[j].p_type != PT_LOAD)
751 				continue;
752 			if (shdr[i].sh_offset >= phdr[j].p_offset &&
753 			    (shdr[i].sh_offset + shdr[i].sh_size <=
754 			    phdr[j].p_offset + phdr[j].p_filesz)) {
755 				shdr[i].sh_offset = 0;
756 				shdr[i].sh_size = 0;
757 				break;
758 			}
759 		}
760 		if (shdr[i].sh_offset == 0 || shdr[i].sh_size == 0)
761 			continue;	/* alread loaded in a PT_LOAD above */
762 		/* Save it for loading below */
763 		symtabindex = i;
764 		symstrindex = shdr[i].sh_link;
765 	}
766 	if (symtabindex < 0 || symstrindex < 0)
767 		goto nosyms;
768 
769 	/* Ok, committed to a load. */
770 #ifndef ELF_VERBOSE
771 	printf("syms=[");
772 #endif
773 	ssym = lastaddr;
774 	for (i = symtabindex; i >= 0; i = symstrindex) {
775 #ifdef ELF_VERBOSE
776 		char	*secname;
777 
778 		switch(shdr[i].sh_type) {
779 		case SHT_SYMTAB:		/* Symbol table */
780 			secname = "symtab";
781 			break;
782 		case SHT_STRTAB:		/* String table */
783 			secname = "strtab";
784 			break;
785 		default:
786 			secname = "WHOA!!";
787 			break;
788 		}
789 #endif
790 		size = shdr[i].sh_size;
791 
792 		archsw.arch_copyin(&size, lastaddr, sizeof(size));
793 		lastaddr += sizeof(size);
794 
795 #ifdef ELF_VERBOSE
796 		printf("\n%s: 0x%jx@0x%jx -> 0x%jx-0x%jx", secname,
797 		    (uintmax_t)shdr[i].sh_size, (uintmax_t)shdr[i].sh_offset,
798 		    (uintmax_t)lastaddr,
799 		    (uintmax_t)(lastaddr + shdr[i].sh_size));
800 #else
801 		if (i == symstrindex)
802 			printf("+");
803 		printf("0x%lx+0x%lx", (long)sizeof(size), (long)size);
804 #endif
805 
806 		if (VECTX_LSEEK(VECTX_HANDLE(ef), (off_t)shdr[i].sh_offset, SEEK_SET) == -1) {
807 			printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
808 			   "_loadimage: could not seek for symbols - skipped!");
809 			lastaddr = ssym;
810 			ssym = 0;
811 			goto nosyms;
812 		}
813 		result = archsw.arch_readin(VECTX_HANDLE(ef), lastaddr, shdr[i].sh_size);
814 		if (result < 0 || (size_t)result != shdr[i].sh_size) {
815 			printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
816 			    "_loadimage: could not read symbols - skipped! "
817 			    "(%ju != %ju)", (uintmax_t)result,
818 			    (uintmax_t)shdr[i].sh_size);
819 			lastaddr = ssym;
820 			ssym = 0;
821 			goto nosyms;
822 		}
823 		/* Reset offsets relative to ssym */
824 		lastaddr += shdr[i].sh_size;
825 		lastaddr = roundup(lastaddr, sizeof(size));
826 		if (i == symtabindex)
827 			symtabindex = -1;
828 		else if (i == symstrindex)
829 			symstrindex = -1;
830 	}
831 	esym = lastaddr;
832 #ifndef ELF_VERBOSE
833 	printf("]");
834 #endif
835 
836 	file_addmetadata(fp, MODINFOMD_SSYM, sizeof(ssym), &ssym);
837 	file_addmetadata(fp, MODINFOMD_ESYM, sizeof(esym), &esym);
838 
839 nosyms:
840 	printf("\n");
841 
842 	ret = lastaddr - firstaddr;
843 	fp->f_addr = firstaddr;
844 
845 	php = NULL;
846 	for (i = 0; i < ehdr->e_phnum; i++) {
847 		if (phdr[i].p_type == PT_DYNAMIC) {
848 			php = phdr + i;
849 			adp = php->p_vaddr;
850 			file_addmetadata(fp, MODINFOMD_DYNAMIC, sizeof(adp),
851 			    &adp);
852 			break;
853 		}
854 	}
855 
856 	if (php == NULL) /* this is bad, we cannot get to symbols or _DYNAMIC */
857 		goto out;
858 
859 	ndp = php->p_filesz / sizeof(Elf_Dyn);
860 	if (ndp == 0)
861 		goto out;
862 	dp = malloc(php->p_filesz);
863 	if (dp == NULL)
864 		goto out;
865 	archsw.arch_copyout(php->p_vaddr + off, dp, php->p_filesz);
866 
867 	ef->strsz = 0;
868 	for (i = 0; i < ndp; i++) {
869 		if (dp[i].d_tag == 0)
870 			break;
871 		switch (dp[i].d_tag) {
872 		case DT_HASH:
873 			ef->hashtab =
874 			    (Elf_Hashelt*)(uintptr_t)(dp[i].d_un.d_ptr + off);
875 			break;
876 		case DT_STRTAB:
877 			ef->strtab =
878 			    (char *)(uintptr_t)(dp[i].d_un.d_ptr + off);
879 			break;
880 		case DT_STRSZ:
881 			ef->strsz = dp[i].d_un.d_val;
882 			break;
883 		case DT_SYMTAB:
884 			ef->symtab =
885 			    (Elf_Sym *)(uintptr_t)(dp[i].d_un.d_ptr + off);
886 			break;
887 		case DT_REL:
888 			ef->rel =
889 			    (Elf_Rel *)(uintptr_t)(dp[i].d_un.d_ptr + off);
890 			break;
891 		case DT_RELSZ:
892 			ef->relsz = dp[i].d_un.d_val;
893 			break;
894 		case DT_RELA:
895 			ef->rela =
896 			    (Elf_Rela *)(uintptr_t)(dp[i].d_un.d_ptr + off);
897 			break;
898 		case DT_RELASZ:
899 			ef->relasz = dp[i].d_un.d_val;
900 			break;
901 		default:
902 			break;
903 		}
904 	}
905 	if (ef->hashtab == NULL || ef->symtab == NULL ||
906 	    ef->strtab == NULL || ef->strsz == 0)
907 		goto out;
908 	COPYOUT(ef->hashtab, &ef->nbuckets, sizeof(ef->nbuckets));
909 	COPYOUT(ef->hashtab + 1, &ef->nchains, sizeof(ef->nchains));
910 	ef->buckets = ef->hashtab + 2;
911 	ef->chains = ef->buckets + ef->nbuckets;
912 
913 	if (__elfN(lookup_symbol)(ef, "__start_set_modmetadata_set", &sym,
914 	    STT_NOTYPE) != 0)
915 		return 0;
916 	p_start = sym.st_value + ef->off;
917 	if (__elfN(lookup_symbol)(ef, "__stop_set_modmetadata_set", &sym,
918 	    STT_NOTYPE) != 0)
919 		return 0;
920 	p_end = sym.st_value + ef->off;
921 
922 	if (__elfN(parse_modmetadata)(fp, ef, p_start, p_end) == 0)
923 		goto out;
924 
925 	if (ef->kernel)		/* kernel must not depend on anything */
926 		goto out;
927 
928 out:
929 	if (dp)
930 		free(dp);
931 	if (shdr)
932 		free(shdr);
933 	return ret;
934 }
935 
936 static char invalid_name[] = "bad";
937 
938 char *
939 fake_modname(const char *name)
940 {
941 	const char *sp, *ep;
942 	char *fp;
943 	size_t len;
944 
945 	sp = strrchr(name, '/');
946 	if (sp)
947 		sp++;
948 	else
949 		sp = name;
950 
951 	ep = strrchr(sp, '.');
952 	if (ep == NULL) {
953 		ep = sp + strlen(sp);
954 	}
955 	if (ep == sp) {
956 		sp = invalid_name;
957 		ep = invalid_name + sizeof(invalid_name) - 1;
958 	}
959 
960 	len = ep - sp;
961 	fp = malloc(len + 1);
962 	if (fp == NULL)
963 		return NULL;
964 	memcpy(fp, sp, len);
965 	fp[len] = '\0';
966 	return fp;
967 }
968 
969 #if (defined(__i386__) || defined(__powerpc__)) && __ELF_WORD_SIZE == 64
970 struct mod_metadata64 {
971 	int		md_version;	/* structure version MDTV_* */
972 	int		md_type;	/* type of entry MDT_* */
973 	uint64_t	md_data;	/* specific data */
974 	uint64_t	md_cval;	/* common string label */
975 };
976 #endif
977 #if defined(__amd64__) && __ELF_WORD_SIZE == 32
978 struct mod_metadata32 {
979 	int		md_version;	/* structure version MDTV_* */
980 	int		md_type;	/* type of entry MDT_* */
981 	uint32_t	md_data;	/* specific data */
982 	uint32_t	md_cval;	/* common string label */
983 };
984 #endif
985 
986 int
987 __elfN(load_modmetadata)(struct preloaded_file *fp, uint64_t dest)
988 {
989 	struct elf_file		 ef;
990 	int			 err, i, j;
991 	Elf_Shdr		*sh_meta, *shdr = NULL;
992 	Elf_Shdr		*sh_data[2];
993 	char			*shstrtab = NULL;
994 	size_t			 size;
995 	Elf_Addr		 p_start, p_end;
996 
997 	bzero(&ef, sizeof(struct elf_file));
998 	ef.fd = -1;
999 
1000 	err = __elfN(load_elf_header)(fp->f_name, &ef);
1001 	if (err != 0)
1002 		goto out;
1003 
1004 	if (ef.kernel == 1 || ef.ehdr->e_type == ET_EXEC) {
1005 		ef.kernel = 1;
1006 	} else if (ef.ehdr->e_type != ET_DYN) {
1007 		err = EFTYPE;
1008 		goto out;
1009 	}
1010 
1011 	size = (size_t)ef.ehdr->e_shnum * (size_t)ef.ehdr->e_shentsize;
1012 	shdr = alloc_pread(VECTX_HANDLE(&ef), ef.ehdr->e_shoff, size);
1013 	if (shdr == NULL) {
1014 		err = ENOMEM;
1015 		goto out;
1016 	}
1017 
1018 	/* Load shstrtab. */
1019 	shstrtab = alloc_pread(VECTX_HANDLE(&ef), shdr[ef.ehdr->e_shstrndx].sh_offset,
1020 	    shdr[ef.ehdr->e_shstrndx].sh_size);
1021 	if (shstrtab == NULL) {
1022 		printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
1023 		    "load_modmetadata: unable to load shstrtab\n");
1024 		err = EFTYPE;
1025 		goto out;
1026 	}
1027 
1028 	/* Find set_modmetadata_set and data sections. */
1029 	sh_data[0] = sh_data[1] = sh_meta = NULL;
1030 	for (i = 0, j = 0; i < ef.ehdr->e_shnum; i++) {
1031 		if (strcmp(&shstrtab[shdr[i].sh_name],
1032 		    "set_modmetadata_set") == 0) {
1033 			sh_meta = &shdr[i];
1034 		}
1035 		if ((strcmp(&shstrtab[shdr[i].sh_name], ".data") == 0) ||
1036 		    (strcmp(&shstrtab[shdr[i].sh_name], ".rodata") == 0)) {
1037 			sh_data[j++] = &shdr[i];
1038 		}
1039 	}
1040 	if (sh_meta == NULL || sh_data[0] == NULL || sh_data[1] == NULL) {
1041 		printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
1042     "load_modmetadata: unable to find set_modmetadata_set or data sections\n");
1043 		err = EFTYPE;
1044 		goto out;
1045 	}
1046 
1047 	/* Load set_modmetadata_set into memory */
1048 	err = kern_pread(VECTX_HANDLE(&ef), dest, sh_meta->sh_size, sh_meta->sh_offset);
1049 	if (err != 0) {
1050 		printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
1051     "load_modmetadata: unable to load set_modmetadata_set: %d\n", err);
1052 		goto out;
1053 	}
1054 	p_start = dest;
1055 	p_end = dest + sh_meta->sh_size;
1056 	dest += sh_meta->sh_size;
1057 
1058 	/* Load data sections into memory. */
1059 	err = kern_pread(VECTX_HANDLE(&ef), dest, sh_data[0]->sh_size,
1060 	    sh_data[0]->sh_offset);
1061 	if (err != 0) {
1062 		printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
1063 		    "load_modmetadata: unable to load data: %d\n", err);
1064 		goto out;
1065 	}
1066 
1067 	/*
1068 	 * We have to increment the dest, so that the offset is the same into
1069 	 * both the .rodata and .data sections.
1070 	 */
1071 	ef.off = -(sh_data[0]->sh_addr - dest);
1072 	dest +=	(sh_data[1]->sh_addr - sh_data[0]->sh_addr);
1073 
1074 	err = kern_pread(VECTX_HANDLE(&ef), dest, sh_data[1]->sh_size,
1075 	    sh_data[1]->sh_offset);
1076 	if (err != 0) {
1077 		printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
1078 		    "load_modmetadata: unable to load data: %d\n", err);
1079 		goto out;
1080 	}
1081 
1082 	err = __elfN(parse_modmetadata)(fp, &ef, p_start, p_end);
1083 	if (err != 0) {
1084 		printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
1085 		    "load_modmetadata: unable to parse metadata: %d\n", err);
1086 		goto out;
1087 	}
1088 
1089 out:
1090 	if (shstrtab != NULL)
1091 		free(shstrtab);
1092 	if (shdr != NULL)
1093 		free(shdr);
1094 	if (ef.firstpage != NULL)
1095 		free(ef.firstpage);
1096 	if (ef.fd != -1) {
1097 #ifdef LOADER_VERIEXEC_VECTX
1098 		if (!err && ef.vctx) {
1099 			int verror;
1100 
1101 			verror = vectx_close(ef.vctx, VE_MUST, __func__);
1102 			if (verror) {
1103 				err = EAUTH;
1104 				file_discard(fp);
1105 			}
1106 		}
1107 #endif
1108 		close(ef.fd);
1109 	}
1110 	return (err);
1111 }
1112 
1113 int
1114 __elfN(parse_modmetadata)(struct preloaded_file *fp, elf_file_t ef,
1115     Elf_Addr p_start, Elf_Addr p_end)
1116 {
1117 	struct mod_metadata md;
1118 #if (defined(__i386__) || defined(__powerpc__)) && __ELF_WORD_SIZE == 64
1119 	struct mod_metadata64 md64;
1120 #elif defined(__amd64__) && __ELF_WORD_SIZE == 32
1121 	struct mod_metadata32 md32;
1122 #endif
1123 	struct mod_depend *mdepend;
1124 	struct mod_version mver;
1125 	char *s;
1126 	int error, modcnt, minfolen;
1127 	Elf_Addr v, p;
1128 
1129 	modcnt = 0;
1130 	p = p_start;
1131 	while (p < p_end) {
1132 		COPYOUT(p, &v, sizeof(v));
1133 		error = __elfN(reloc_ptr)(fp, ef, p, &v, sizeof(v));
1134 		if (error == EOPNOTSUPP)
1135 			v += ef->off;
1136 		else if (error != 0)
1137 			return (error);
1138 #if (defined(__i386__) || defined(__powerpc__)) && __ELF_WORD_SIZE == 64
1139 		COPYOUT(v, &md64, sizeof(md64));
1140 		error = __elfN(reloc_ptr)(fp, ef, v, &md64, sizeof(md64));
1141 		if (error == EOPNOTSUPP) {
1142 			md64.md_cval += ef->off;
1143 			md64.md_data += ef->off;
1144 		} else if (error != 0)
1145 			return (error);
1146 		md.md_version = md64.md_version;
1147 		md.md_type = md64.md_type;
1148 		md.md_cval = (const char *)(uintptr_t)md64.md_cval;
1149 		md.md_data = (void *)(uintptr_t)md64.md_data;
1150 #elif defined(__amd64__) && __ELF_WORD_SIZE == 32
1151 		COPYOUT(v, &md32, sizeof(md32));
1152 		error = __elfN(reloc_ptr)(fp, ef, v, &md32, sizeof(md32));
1153 		if (error == EOPNOTSUPP) {
1154 			md32.md_cval += ef->off;
1155 			md32.md_data += ef->off;
1156 		} else if (error != 0)
1157 			return (error);
1158 		md.md_version = md32.md_version;
1159 		md.md_type = md32.md_type;
1160 		md.md_cval = (const char *)(uintptr_t)md32.md_cval;
1161 		md.md_data = (void *)(uintptr_t)md32.md_data;
1162 #else
1163 		COPYOUT(v, &md, sizeof(md));
1164 		error = __elfN(reloc_ptr)(fp, ef, v, &md, sizeof(md));
1165 		if (error == EOPNOTSUPP) {
1166 			md.md_cval += ef->off;
1167 			md.md_data = (void *)((uintptr_t)md.md_data +
1168 			    (uintptr_t)ef->off);
1169 		} else if (error != 0)
1170 			return (error);
1171 #endif
1172 		p += sizeof(Elf_Addr);
1173 		switch(md.md_type) {
1174 		case MDT_DEPEND:
1175 			if (ef->kernel) /* kernel must not depend on anything */
1176 				break;
1177 			s = strdupout((vm_offset_t)md.md_cval);
1178 			minfolen = sizeof(*mdepend) + strlen(s) + 1;
1179 			mdepend = malloc(minfolen);
1180 			if (mdepend == NULL)
1181 				return ENOMEM;
1182 			COPYOUT((vm_offset_t)md.md_data, mdepend,
1183 			    sizeof(*mdepend));
1184 			strcpy((char*)(mdepend + 1), s);
1185 			free(s);
1186 			file_addmetadata(fp, MODINFOMD_DEPLIST, minfolen,
1187 			    mdepend);
1188 			free(mdepend);
1189 			break;
1190 		case MDT_VERSION:
1191 			s = strdupout((vm_offset_t)md.md_cval);
1192 			COPYOUT((vm_offset_t)md.md_data, &mver, sizeof(mver));
1193 			file_addmodule(fp, s, mver.mv_version, NULL);
1194 			free(s);
1195 			modcnt++;
1196 			break;
1197 		}
1198 	}
1199 	if (modcnt == 0) {
1200 		s = fake_modname(fp->f_name);
1201 		file_addmodule(fp, s, 1, NULL);
1202 		free(s);
1203 	}
1204 	return 0;
1205 }
1206 
1207 static unsigned long
1208 elf_hash(const char *name)
1209 {
1210 	const unsigned char *p = (const unsigned char *) name;
1211 	unsigned long h = 0;
1212 	unsigned long g;
1213 
1214 	while (*p != '\0') {
1215 		h = (h << 4) + *p++;
1216 		if ((g = h & 0xf0000000) != 0)
1217 			h ^= g >> 24;
1218 		h &= ~g;
1219 	}
1220 	return h;
1221 }
1222 
1223 static const char __elfN(bad_symtable)[] = "elf" __XSTRING(__ELF_WORD_SIZE)
1224     "_lookup_symbol: corrupt symbol table\n";
1225 int
1226 __elfN(lookup_symbol)(elf_file_t ef, const char* name, Elf_Sym *symp,
1227     unsigned char type)
1228 {
1229 	Elf_Hashelt symnum;
1230 	Elf_Sym sym;
1231 	char *strp;
1232 	unsigned long hash;
1233 
1234 	if (ef->nbuckets == 0) {
1235 		printf(__elfN(bad_symtable));
1236 		return ENOENT;
1237 	}
1238 
1239 	hash = elf_hash(name);
1240 	COPYOUT(&ef->buckets[hash % ef->nbuckets], &symnum, sizeof(symnum));
1241 
1242 	while (symnum != STN_UNDEF) {
1243 		if (symnum >= ef->nchains) {
1244 			printf(__elfN(bad_symtable));
1245 			return ENOENT;
1246 		}
1247 
1248 		COPYOUT(ef->symtab + symnum, &sym, sizeof(sym));
1249 		if (sym.st_name == 0) {
1250 			printf(__elfN(bad_symtable));
1251 			return ENOENT;
1252 		}
1253 
1254 		strp = strdupout((vm_offset_t)(ef->strtab + sym.st_name));
1255 		if (strcmp(name, strp) == 0) {
1256 			free(strp);
1257 			if (sym.st_shndx != SHN_UNDEF ||
1258 			    (sym.st_value != 0 &&
1259 			    ELF_ST_TYPE(sym.st_info) == type)) {
1260 				*symp = sym;
1261 				return 0;
1262 			}
1263 			return ENOENT;
1264 		}
1265 		free(strp);
1266 		COPYOUT(&ef->chains[symnum], &symnum, sizeof(symnum));
1267 	}
1268 	return ENOENT;
1269 }
1270 
1271 /*
1272  * Apply any intra-module relocations to the value. p is the load address
1273  * of the value and val/len is the value to be modified. This does NOT modify
1274  * the image in-place, because this is done by kern_linker later on.
1275  *
1276  * Returns EOPNOTSUPP if no relocation method is supplied.
1277  */
1278 static int
1279 __elfN(reloc_ptr)(struct preloaded_file *mp, elf_file_t ef,
1280     Elf_Addr p, void *val, size_t len)
1281 {
1282 	size_t n;
1283 	Elf_Rela a;
1284 	Elf_Rel r;
1285 	int error;
1286 
1287 	/*
1288 	 * The kernel is already relocated, but we still want to apply
1289 	 * offset adjustments.
1290 	 */
1291 	if (ef->kernel)
1292 		return (EOPNOTSUPP);
1293 
1294 	for (n = 0; n < ef->relsz / sizeof(r); n++) {
1295 		COPYOUT(ef->rel + n, &r, sizeof(r));
1296 
1297 		error = __elfN(reloc)(ef, __elfN(symaddr), &r, ELF_RELOC_REL,
1298 		    ef->off, p, val, len);
1299 		if (error != 0)
1300 			return (error);
1301 	}
1302 	for (n = 0; n < ef->relasz / sizeof(a); n++) {
1303 		COPYOUT(ef->rela + n, &a, sizeof(a));
1304 
1305 		error = __elfN(reloc)(ef, __elfN(symaddr), &a, ELF_RELOC_RELA,
1306 		    ef->off, p, val, len);
1307 		if (error != 0)
1308 			return (error);
1309 	}
1310 
1311 	return (0);
1312 }
1313 
1314 static Elf_Addr
1315 __elfN(symaddr)(struct elf_file *ef, Elf_Size symidx)
1316 {
1317 
1318 	/* Symbol lookup by index not required here. */
1319 	return (0);
1320 }
1321