xref: /freebsd/stand/common/load_elf_obj.c (revision 6be3386466ab79a84b48429ae66244f21526d3df)
1 /*-
2  * Copyright (c) 2004 Ian Dowse <iedowse@freebsd.org>
3  * Copyright (c) 1998 Michael Smith <msmith@freebsd.org>
4  * Copyright (c) 1998 Peter Wemm <peter@freebsd.org>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include <sys/param.h>
33 #include <sys/exec.h>
34 #include <sys/linker.h>
35 #include <sys/module.h>
36 #include <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_Ehdr	hdr;
56 	Elf_Shdr	*e_shdr;
57 
58 	int		symtabindex;	/* Index of symbol table */
59 	int		shstrindex;	/* Index of section name string table */
60 
61 	int		fd;
62 	vm_offset_t	off;
63 #ifdef LOADER_VERIEXEC_VECTX
64 	struct vectx	*vctx;
65 #endif
66 } *elf_file_t;
67 
68 #ifdef LOADER_VERIEXEC_VECTX
69 #define VECTX_HANDLE(ef) (ef)->vctx
70 #else
71 #define VECTX_HANDLE(ef) (ef)->fd
72 #endif
73 
74 static int __elfN(obj_loadimage)(struct preloaded_file *mp, elf_file_t ef,
75     uint64_t loadaddr);
76 static int __elfN(obj_lookup_set)(struct preloaded_file *mp, elf_file_t ef,
77     const char *name, Elf_Addr *startp, Elf_Addr *stopp, int *countp);
78 static int __elfN(obj_reloc_ptr)(struct preloaded_file *mp, elf_file_t ef,
79     Elf_Addr p, void *val, size_t len);
80 static int __elfN(obj_parse_modmetadata)(struct preloaded_file *mp,
81     elf_file_t ef);
82 static Elf_Addr __elfN(obj_symaddr)(struct elf_file *ef, Elf_Size symidx);
83 
84 const char	*__elfN(obj_kerneltype) = "elf kernel";
85 const char	*__elfN(obj_moduletype) = "elf obj module";
86 
87 /*
88  * Attempt to load the file (file) as an ELF module.  It will be stored at
89  * (dest), and a pointer to a module structure describing the loaded object
90  * will be saved in (result).
91  */
92 int
93 __elfN(obj_loadfile)(char *filename, uint64_t dest,
94     struct preloaded_file **result)
95 {
96 	struct preloaded_file *fp, *kfp;
97 	struct elf_file	ef;
98 	Elf_Ehdr *hdr;
99 	int err;
100 	ssize_t bytes_read;
101 
102 	fp = NULL;
103 	bzero(&ef, sizeof(struct elf_file));
104 
105 	/*
106 	 * Open the image, read and validate the ELF header
107 	 */
108 	if (filename == NULL)	/* can't handle nameless */
109 		return(EFTYPE);
110 	if ((ef.fd = open(filename, O_RDONLY)) == -1)
111 		return(errno);
112 #ifdef LOADER_VERIEXEC_VECTX
113 	{
114 		int verror;
115 
116 		ef.vctx = vectx_open(ef.fd, filename, 0L, NULL, &verror, __func__);
117 		if (verror) {
118 			printf("Unverified %s: %s\n", filename, ve_error_get());
119 			close(ef.fd);
120 			free(ef.vctx);
121 			return (EAUTH);
122 		}
123 	}
124 #endif
125 
126 	hdr = &ef.hdr;
127 	bytes_read = VECTX_READ(VECTX_HANDLE(&ef), hdr, sizeof(*hdr));
128 	if (bytes_read != sizeof(*hdr)) {
129 		err = EFTYPE;	/* could be EIO, but may be small file */
130 		goto oerr;
131 	}
132 
133 	/* Is it ELF? */
134 	if (!IS_ELF(*hdr)) {
135 		err = EFTYPE;
136 		goto oerr;
137 	}
138 	if (hdr->e_ident[EI_CLASS] != ELF_TARG_CLASS ||	/* Layout ? */
139 	    hdr->e_ident[EI_DATA] != ELF_TARG_DATA ||
140 	    hdr->e_ident[EI_VERSION] != EV_CURRENT ||	/* Version ? */
141 	    hdr->e_version != EV_CURRENT ||
142 	    hdr->e_machine != ELF_TARG_MACH ||		/* Machine ? */
143 	    hdr->e_type != ET_REL) {
144 		err = EFTYPE;
145 		goto oerr;
146 	}
147 
148 	if (hdr->e_shnum * hdr->e_shentsize == 0 || hdr->e_shoff == 0 ||
149 	    hdr->e_shentsize != sizeof(Elf_Shdr)) {
150 		err = EFTYPE;
151 		goto oerr;
152 	}
153 
154 #if defined(LOADER_VERIEXEC) && !defined(LOADER_VERIEXEC_VECTX)
155 	if (verify_file(ef.fd, filename, bytes_read, VE_MUST, __func__) < 0) {
156 		err = EAUTH;
157 		goto oerr;
158 	}
159 #endif
160 
161 	kfp = file_findfile(NULL, __elfN(obj_kerneltype));
162 	if (kfp == NULL) {
163 		printf("elf" __XSTRING(__ELF_WORD_SIZE)
164 		    "_obj_loadfile: can't load module before kernel\n");
165 		err = EPERM;
166 		goto oerr;
167 	}
168 
169 	if (archsw.arch_loadaddr != NULL)
170 		dest = archsw.arch_loadaddr(LOAD_ELF, hdr, dest);
171 	else
172 		dest = roundup(dest, PAGE_SIZE);
173 
174 	/*
175 	 * Ok, we think we should handle this.
176 	 */
177 	fp = file_alloc();
178 	if (fp == NULL) {
179 		printf("elf" __XSTRING(__ELF_WORD_SIZE)
180 		    "_obj_loadfile: cannot allocate module info\n");
181 		err = EPERM;
182 		goto out;
183 	}
184 	fp->f_name = strdup(filename);
185 	fp->f_type = strdup(__elfN(obj_moduletype));
186 
187 	printf("%s ", filename);
188 
189 	fp->f_size = __elfN(obj_loadimage)(fp, &ef, dest);
190 	if (fp->f_size == 0 || fp->f_addr == 0)
191 		goto ioerr;
192 
193 	/* save exec header as metadata */
194 	file_addmetadata(fp, MODINFOMD_ELFHDR, sizeof(*hdr), hdr);
195 
196 	/* Load OK, return module pointer */
197 	*result = (struct preloaded_file *)fp;
198 	err = 0;
199 	goto out;
200 
201 ioerr:
202 	err = EIO;
203 oerr:
204 	file_discard(fp);
205 out:
206 #ifdef LOADER_VERIEXEC_VECTX
207 	if (!err && ef.vctx) {
208 		int verror;
209 
210 		verror = vectx_close(ef.vctx, VE_MUST, __func__);
211 		if (verror) {
212 			err = EAUTH;
213 			file_discard(fp);
214 		}
215 	}
216 #endif
217 	close(ef.fd);
218 	if (ef.e_shdr != NULL)
219 		free(ef.e_shdr);
220 
221 	return(err);
222 }
223 
224 /*
225  * With the file (fd) open on the image, and (ehdr) containing
226  * the Elf header, load the image at (off)
227  */
228 static int
229 __elfN(obj_loadimage)(struct preloaded_file *fp, elf_file_t ef, uint64_t off)
230 {
231 	Elf_Ehdr *hdr;
232 	Elf_Shdr *shdr, *cshdr, *lshdr;
233 	vm_offset_t firstaddr, lastaddr;
234 	int i, nsym, res, ret, shdrbytes, symstrindex;
235 
236 	ret = 0;
237 	firstaddr = lastaddr = (vm_offset_t)off;
238 	hdr = &ef->hdr;
239 	ef->off = (vm_offset_t)off;
240 
241 	/* Read in the section headers. */
242 	shdrbytes = hdr->e_shnum * hdr->e_shentsize;
243 	shdr = alloc_pread(VECTX_HANDLE(ef), (off_t)hdr->e_shoff, shdrbytes);
244 	if (shdr == NULL) {
245 		printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
246 		    "_obj_loadimage: read section headers failed\n");
247 		goto out;
248 	}
249 	ef->e_shdr = shdr;
250 
251 	/*
252 	 * Decide where to load everything, but don't read it yet.
253 	 * We store the load address as a non-zero sh_addr value.
254 	 * Start with the code/data and bss.
255 	 */
256 	for (i = 0; i < hdr->e_shnum; i++)
257 		shdr[i].sh_addr = 0;
258 	for (i = 0; i < hdr->e_shnum; i++) {
259 		if (shdr[i].sh_size == 0)
260 			continue;
261 		switch (shdr[i].sh_type) {
262 		case SHT_PROGBITS:
263 		case SHT_NOBITS:
264 #if defined(__i386__) || defined(__amd64__)
265 		case SHT_X86_64_UNWIND:
266 #endif
267 		case SHT_INIT_ARRAY:
268 		case SHT_FINI_ARRAY:
269 			if ((shdr[i].sh_flags & SHF_ALLOC) == 0)
270 				break;
271 			lastaddr = roundup(lastaddr, shdr[i].sh_addralign);
272 			shdr[i].sh_addr = (Elf_Addr)lastaddr;
273 			lastaddr += shdr[i].sh_size;
274 			break;
275 		}
276 	}
277 
278 	/* Symbols. */
279 	nsym = 0;
280 	for (i = 0; i < hdr->e_shnum; i++) {
281 		switch (shdr[i].sh_type) {
282 		case SHT_SYMTAB:
283 			nsym++;
284 			ef->symtabindex = i;
285 			shdr[i].sh_addr = (Elf_Addr)lastaddr;
286 			lastaddr += shdr[i].sh_size;
287 			break;
288 		}
289 	}
290 	if (nsym != 1) {
291 		printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
292 		    "_obj_loadimage: file has no valid symbol table\n");
293 		goto out;
294 	}
295 	lastaddr = roundup(lastaddr, shdr[ef->symtabindex].sh_addralign);
296 	shdr[ef->symtabindex].sh_addr = (Elf_Addr)lastaddr;
297 	lastaddr += shdr[ef->symtabindex].sh_size;
298 
299 	symstrindex = shdr[ef->symtabindex].sh_link;
300 	if (symstrindex < 0 || symstrindex >= hdr->e_shnum ||
301 	    shdr[symstrindex].sh_type != SHT_STRTAB) {
302 		printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
303 		    "_obj_loadimage: file has invalid symbol strings\n");
304 		goto out;
305 	}
306 	lastaddr = roundup(lastaddr, shdr[symstrindex].sh_addralign);
307 	shdr[symstrindex].sh_addr = (Elf_Addr)lastaddr;
308 	lastaddr += shdr[symstrindex].sh_size;
309 
310 	/* Section names. */
311 	if (hdr->e_shstrndx == 0 || hdr->e_shstrndx >= hdr->e_shnum ||
312 	    shdr[hdr->e_shstrndx].sh_type != SHT_STRTAB) {
313 		printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
314 		    "_obj_loadimage: file has no section names\n");
315 		goto out;
316 	}
317 	ef->shstrindex = hdr->e_shstrndx;
318 	lastaddr = roundup(lastaddr, shdr[ef->shstrindex].sh_addralign);
319 	shdr[ef->shstrindex].sh_addr = (Elf_Addr)lastaddr;
320 	lastaddr += shdr[ef->shstrindex].sh_size;
321 
322 	/* Relocation tables. */
323 	for (i = 0; i < hdr->e_shnum; i++) {
324 		switch (shdr[i].sh_type) {
325 		case SHT_REL:
326 		case SHT_RELA:
327 			if ((shdr[shdr[i].sh_info].sh_flags & SHF_ALLOC) == 0)
328 				break;
329 			lastaddr = roundup(lastaddr, shdr[i].sh_addralign);
330 			shdr[i].sh_addr = (Elf_Addr)lastaddr;
331 			lastaddr += shdr[i].sh_size;
332 			break;
333 		}
334 	}
335 
336 	/* Clear the whole area, including bss regions. */
337 	kern_bzero(firstaddr, lastaddr - firstaddr);
338 
339 	/* Figure section with the lowest file offset we haven't loaded yet. */
340 	for (cshdr = NULL; /* none */; /* none */)
341 	{
342 		/*
343 		 * Find next section to load. The complexity of this loop is
344 		 * O(n^2), but with  the number of sections being typically
345 		 * small, we do not care.
346 		 */
347 		lshdr = cshdr;
348 
349 		for (i = 0; i < hdr->e_shnum; i++) {
350 			if (shdr[i].sh_addr == 0 ||
351 			    shdr[i].sh_type == SHT_NOBITS)
352 				continue;
353 			/* Skip sections that were loaded already. */
354 			if (lshdr != NULL &&
355 			    lshdr->sh_offset >= shdr[i].sh_offset)
356 				continue;
357 			/* Find section with smallest offset. */
358 			if (cshdr == lshdr ||
359 			    cshdr->sh_offset > shdr[i].sh_offset)
360 				cshdr = &shdr[i];
361 		}
362 
363 		if (cshdr == lshdr)
364 			break;
365 
366 		if (kern_pread(VECTX_HANDLE(ef), (vm_offset_t)cshdr->sh_addr,
367 		    cshdr->sh_size, (off_t)cshdr->sh_offset) != 0) {
368 			printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
369 			    "_obj_loadimage: read failed\n");
370 			goto out;
371 		}
372 	}
373 
374 	file_addmetadata(fp, MODINFOMD_SHDR, shdrbytes, shdr);
375 
376 	res = __elfN(obj_parse_modmetadata)(fp, ef);
377 	if (res != 0)
378 		goto out;
379 
380 	ret = lastaddr - firstaddr;
381 	fp->f_addr = firstaddr;
382 
383 	printf("size 0x%lx at 0x%lx", (u_long)ret, (u_long)firstaddr);
384 
385 out:
386 	printf("\n");
387 	return ret;
388 }
389 
390 #if defined(__i386__) && __ELF_WORD_SIZE == 64
391 struct mod_metadata64 {
392 	int		md_version;	/* structure version MDTV_* */
393 	int		md_type;	/* type of entry MDT_* */
394 	uint64_t	md_data;	/* specific data */
395 	uint64_t	md_cval;	/* common string label */
396 };
397 #endif
398 
399 int
400 __elfN(obj_parse_modmetadata)(struct preloaded_file *fp, elf_file_t ef)
401 {
402 	struct mod_metadata md;
403 #if defined(__i386__) && __ELF_WORD_SIZE == 64
404 	struct mod_metadata64 md64;
405 #endif
406 	struct mod_depend *mdepend;
407 	struct mod_version mver;
408 	char *s;
409 	int error, modcnt, minfolen;
410 	Elf_Addr v, p, p_stop;
411 
412 	if (__elfN(obj_lookup_set)(fp, ef, "modmetadata_set", &p, &p_stop,
413 	    &modcnt) != 0)
414 		return 0;
415 
416 	modcnt = 0;
417 	while (p < p_stop) {
418 		COPYOUT(p, &v, sizeof(v));
419 		error = __elfN(obj_reloc_ptr)(fp, ef, p, &v, sizeof(v));
420 		if (error != 0)
421 			return (error);
422 #if defined(__i386__) && __ELF_WORD_SIZE == 64
423 		COPYOUT(v, &md64, sizeof(md64));
424 		error = __elfN(obj_reloc_ptr)(fp, ef, v, &md64, sizeof(md64));
425 		if (error != 0)
426 			return (error);
427 		md.md_version = md64.md_version;
428 		md.md_type = md64.md_type;
429 		md.md_cval = (const char *)(uintptr_t)md64.md_cval;
430 		md.md_data = (void *)(uintptr_t)md64.md_data;
431 #else
432 		COPYOUT(v, &md, sizeof(md));
433 		error = __elfN(obj_reloc_ptr)(fp, ef, v, &md, sizeof(md));
434 		if (error != 0)
435 			return (error);
436 #endif
437 		p += sizeof(Elf_Addr);
438 		switch(md.md_type) {
439 		case MDT_DEPEND:
440 			s = strdupout((vm_offset_t)md.md_cval);
441 			minfolen = sizeof(*mdepend) + strlen(s) + 1;
442 			mdepend = malloc(minfolen);
443 			if (mdepend == NULL)
444 				return ENOMEM;
445 			COPYOUT((vm_offset_t)md.md_data, mdepend,
446 			    sizeof(*mdepend));
447 			strcpy((char*)(mdepend + 1), s);
448 			free(s);
449 			file_addmetadata(fp, MODINFOMD_DEPLIST, minfolen,
450 			    mdepend);
451 			free(mdepend);
452 			break;
453 		case MDT_VERSION:
454 			s = strdupout((vm_offset_t)md.md_cval);
455 			COPYOUT((vm_offset_t)md.md_data, &mver, sizeof(mver));
456 			file_addmodule(fp, s, mver.mv_version, NULL);
457 			free(s);
458 			modcnt++;
459 			break;
460 		case MDT_MODULE:
461 		case MDT_PNP_INFO:
462 			break;
463 		default:
464 			printf("unknown type %d\n", md.md_type);
465 			break;
466 		}
467 	}
468 	return 0;
469 }
470 
471 static int
472 __elfN(obj_lookup_set)(struct preloaded_file *fp, elf_file_t ef,
473     const char* name, Elf_Addr *startp, Elf_Addr *stopp, int *countp)
474 {
475 	Elf_Ehdr *hdr;
476 	Elf_Shdr *shdr;
477 	char *p;
478 	vm_offset_t shstrtab;
479 	int i;
480 
481 	hdr = &ef->hdr;
482 	shdr = ef->e_shdr;
483 	shstrtab = shdr[ef->shstrindex].sh_addr;
484 
485 	for (i = 0; i < hdr->e_shnum; i++) {
486 		if (shdr[i].sh_type != SHT_PROGBITS)
487 			continue;
488 		if (shdr[i].sh_name == 0)
489 			continue;
490 		p = strdupout(shstrtab + shdr[i].sh_name);
491 		if (strncmp(p, "set_", 4) == 0 && strcmp(p + 4, name) == 0) {
492 			*startp = shdr[i].sh_addr;
493 			*stopp = shdr[i].sh_addr +  shdr[i].sh_size;
494 			*countp = (*stopp - *startp) / sizeof(Elf_Addr);
495 			free(p);
496 			return (0);
497 		}
498 		free(p);
499 	}
500 
501 	return (ESRCH);
502 }
503 
504 /*
505  * Apply any intra-module relocations to the value. p is the load address
506  * of the value and val/len is the value to be modified. This does NOT modify
507  * the image in-place, because this is done by kern_linker later on.
508  */
509 static int
510 __elfN(obj_reloc_ptr)(struct preloaded_file *mp, elf_file_t ef, Elf_Addr p,
511     void *val, size_t len)
512 {
513 	Elf_Ehdr *hdr;
514 	Elf_Shdr *shdr;
515 	Elf_Addr off = p;
516 	Elf_Addr base;
517 	Elf_Rela a, *abase;
518 	Elf_Rel r, *rbase;
519 	int error, i, j, nrel, nrela;
520 
521 	hdr = &ef->hdr;
522 	shdr = ef->e_shdr;
523 
524 	for (i = 0; i < hdr->e_shnum; i++) {
525 		if (shdr[i].sh_type != SHT_RELA && shdr[i].sh_type != SHT_REL)
526 			continue;
527 		base = shdr[shdr[i].sh_info].sh_addr;
528 		if (base == 0 || shdr[i].sh_addr == 0)
529 			continue;
530 		if (off < base || off + len > base +
531 		    shdr[shdr[i].sh_info].sh_size)
532 			continue;
533 
534 		switch (shdr[i].sh_type) {
535 		case SHT_RELA:
536 			abase = (Elf_Rela *)(intptr_t)shdr[i].sh_addr;
537 
538 			nrela = shdr[i].sh_size / sizeof(Elf_Rela);
539 			for (j = 0; j < nrela; j++) {
540 				COPYOUT(abase + j, &a, sizeof(a));
541 
542 				error = __elfN(reloc)(ef, __elfN(obj_symaddr),
543 				    &a, ELF_RELOC_RELA, base, off, val, len);
544 				if (error != 0)
545 					return (error);
546 			}
547 			break;
548 		case SHT_REL:
549 			rbase = (Elf_Rel *)(intptr_t)shdr[i].sh_addr;
550 
551 			nrel = shdr[i].sh_size / sizeof(Elf_Rel);
552 			for (j = 0; j < nrel; j++) {
553 				COPYOUT(rbase + j, &r, sizeof(r));
554 
555 				error = __elfN(reloc)(ef, __elfN(obj_symaddr),
556 				    &r, ELF_RELOC_REL, base, off, val, len);
557 				if (error != 0)
558 					return (error);
559 			}
560 			break;
561 		}
562 	}
563 	return (0);
564 }
565 
566 /* Look up the address of a specified symbol. */
567 static Elf_Addr
568 __elfN(obj_symaddr)(struct elf_file *ef, Elf_Size symidx)
569 {
570 	Elf_Sym sym;
571 	Elf_Addr base;
572 
573 	if (symidx >= ef->e_shdr[ef->symtabindex].sh_size / sizeof(Elf_Sym))
574 		return (0);
575 	COPYOUT(ef->e_shdr[ef->symtabindex].sh_addr + symidx * sizeof(Elf_Sym),
576 	    &sym, sizeof(sym));
577 	if (sym.st_shndx == SHN_UNDEF || sym.st_shndx >= ef->hdr.e_shnum)
578 		return (0);
579 	base = ef->e_shdr[sym.st_shndx].sh_addr;
580 	if (base == 0)
581 		return (0);
582 	return (base + sym.st_value);
583 }
584