xref: /freebsd/stand/common/load_elf_obj.c (revision d4eeb02986980bf33dd56c41ceb9fc5f180c0d47)
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 	if (module_verbose > MODULE_VERBOSE_SILENT)
188 		printf("%s ", filename);
189 
190 	fp->f_size = __elfN(obj_loadimage)(fp, &ef, dest);
191 	if (fp->f_size == 0 || fp->f_addr == 0)
192 		goto ioerr;
193 
194 	/* save exec header as metadata */
195 	file_addmetadata(fp, MODINFOMD_ELFHDR, sizeof(*hdr), hdr);
196 
197 	/* Load OK, return module pointer */
198 	*result = (struct preloaded_file *)fp;
199 	err = 0;
200 	goto out;
201 
202 ioerr:
203 	err = EIO;
204 oerr:
205 	file_discard(fp);
206 out:
207 #ifdef LOADER_VERIEXEC_VECTX
208 	if (!err && ef.vctx) {
209 		int verror;
210 
211 		verror = vectx_close(ef.vctx, VE_MUST, __func__);
212 		if (verror) {
213 			err = EAUTH;
214 			file_discard(fp);
215 		}
216 	}
217 #endif
218 	close(ef.fd);
219 	if (ef.e_shdr != NULL)
220 		free(ef.e_shdr);
221 
222 	return(err);
223 }
224 
225 /*
226  * With the file (fd) open on the image, and (ehdr) containing
227  * the Elf header, load the image at (off)
228  */
229 static int
230 __elfN(obj_loadimage)(struct preloaded_file *fp, elf_file_t ef, uint64_t off)
231 {
232 	Elf_Ehdr *hdr;
233 	Elf_Shdr *shdr, *cshdr, *lshdr;
234 	vm_offset_t firstaddr, lastaddr;
235 	int i, nsym, res, ret, shdrbytes, symstrindex;
236 
237 	ret = 0;
238 	firstaddr = lastaddr = (vm_offset_t)off;
239 	hdr = &ef->hdr;
240 	ef->off = (vm_offset_t)off;
241 
242 	/* Read in the section headers. */
243 	shdrbytes = hdr->e_shnum * hdr->e_shentsize;
244 	shdr = alloc_pread(VECTX_HANDLE(ef), (off_t)hdr->e_shoff, shdrbytes);
245 	if (shdr == NULL) {
246 		printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
247 		    "_obj_loadimage: read section headers failed\n");
248 		goto out;
249 	}
250 	ef->e_shdr = shdr;
251 
252 	/*
253 	 * Decide where to load everything, but don't read it yet.
254 	 * We store the load address as a non-zero sh_addr value.
255 	 * Start with the code/data and bss.
256 	 */
257 	for (i = 0; i < hdr->e_shnum; i++)
258 		shdr[i].sh_addr = 0;
259 	for (i = 0; i < hdr->e_shnum; i++) {
260 		if (shdr[i].sh_size == 0)
261 			continue;
262 		switch (shdr[i].sh_type) {
263 		case SHT_PROGBITS:
264 		case SHT_NOBITS:
265 #if defined(__i386__) || defined(__amd64__)
266 		case SHT_X86_64_UNWIND:
267 #endif
268 		case SHT_INIT_ARRAY:
269 		case SHT_FINI_ARRAY:
270 			if ((shdr[i].sh_flags & SHF_ALLOC) == 0)
271 				break;
272 			lastaddr = roundup(lastaddr, shdr[i].sh_addralign);
273 			shdr[i].sh_addr = (Elf_Addr)lastaddr;
274 			lastaddr += shdr[i].sh_size;
275 			break;
276 		}
277 	}
278 
279 	/* Symbols. */
280 	nsym = 0;
281 	for (i = 0; i < hdr->e_shnum; i++) {
282 		switch (shdr[i].sh_type) {
283 		case SHT_SYMTAB:
284 			nsym++;
285 			ef->symtabindex = i;
286 			break;
287 		}
288 	}
289 	if (nsym != 1) {
290 		printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
291 		    "_obj_loadimage: file has no valid symbol table\n");
292 		goto out;
293 	}
294 	lastaddr = roundup(lastaddr, shdr[ef->symtabindex].sh_addralign);
295 	shdr[ef->symtabindex].sh_addr = (Elf_Addr)lastaddr;
296 	lastaddr += shdr[ef->symtabindex].sh_size;
297 
298 	symstrindex = shdr[ef->symtabindex].sh_link;
299 	if (symstrindex < 0 || symstrindex >= hdr->e_shnum ||
300 	    shdr[symstrindex].sh_type != SHT_STRTAB) {
301 		printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
302 		    "_obj_loadimage: file has invalid symbol strings\n");
303 		goto out;
304 	}
305 	lastaddr = roundup(lastaddr, shdr[symstrindex].sh_addralign);
306 	shdr[symstrindex].sh_addr = (Elf_Addr)lastaddr;
307 	lastaddr += shdr[symstrindex].sh_size;
308 
309 	/* Section names. */
310 	if (hdr->e_shstrndx == 0 || hdr->e_shstrndx >= hdr->e_shnum ||
311 	    shdr[hdr->e_shstrndx].sh_type != SHT_STRTAB) {
312 		printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
313 		    "_obj_loadimage: file has no section names\n");
314 		goto out;
315 	}
316 	ef->shstrindex = hdr->e_shstrndx;
317 	lastaddr = roundup(lastaddr, shdr[ef->shstrindex].sh_addralign);
318 	shdr[ef->shstrindex].sh_addr = (Elf_Addr)lastaddr;
319 	lastaddr += shdr[ef->shstrindex].sh_size;
320 
321 	/* Relocation tables. */
322 	for (i = 0; i < hdr->e_shnum; i++) {
323 		switch (shdr[i].sh_type) {
324 		case SHT_REL:
325 		case SHT_RELA:
326 			if ((shdr[shdr[i].sh_info].sh_flags & SHF_ALLOC) == 0)
327 				break;
328 			lastaddr = roundup(lastaddr, shdr[i].sh_addralign);
329 			shdr[i].sh_addr = (Elf_Addr)lastaddr;
330 			lastaddr += shdr[i].sh_size;
331 			break;
332 		}
333 	}
334 
335 	/* Clear the whole area, including bss regions. */
336 	kern_bzero(firstaddr, lastaddr - firstaddr);
337 
338 	/* Figure section with the lowest file offset we haven't loaded yet. */
339 	for (cshdr = NULL; /* none */; /* none */)
340 	{
341 		/*
342 		 * Find next section to load. The complexity of this loop is
343 		 * O(n^2), but with  the number of sections being typically
344 		 * small, we do not care.
345 		 */
346 		lshdr = cshdr;
347 
348 		for (i = 0; i < hdr->e_shnum; i++) {
349 			if (shdr[i].sh_addr == 0 ||
350 			    shdr[i].sh_type == SHT_NOBITS)
351 				continue;
352 			/* Skip sections that were loaded already. */
353 			if (lshdr != NULL &&
354 			    lshdr->sh_offset >= shdr[i].sh_offset)
355 				continue;
356 			/* Find section with smallest offset. */
357 			if (cshdr == lshdr ||
358 			    cshdr->sh_offset > shdr[i].sh_offset)
359 				cshdr = &shdr[i];
360 		}
361 
362 		if (cshdr == lshdr)
363 			break;
364 
365 		if (kern_pread(VECTX_HANDLE(ef), (vm_offset_t)cshdr->sh_addr,
366 		    cshdr->sh_size, (off_t)cshdr->sh_offset) != 0) {
367 			printf("\nelf" __XSTRING(__ELF_WORD_SIZE)
368 			    "_obj_loadimage: read failed\n");
369 			goto out;
370 		}
371 	}
372 
373 	file_addmetadata(fp, MODINFOMD_SHDR, shdrbytes, shdr);
374 
375 	res = __elfN(obj_parse_modmetadata)(fp, ef);
376 	if (res != 0)
377 		goto out;
378 
379 	ret = lastaddr - firstaddr;
380 	fp->f_addr = firstaddr;
381 
382 	if (module_verbose > MODULE_VERBOSE_SILENT)
383 		printf("size 0x%lx at 0x%lx", (u_long)ret, (u_long)firstaddr);
384 
385 out:
386 	if (module_verbose > MODULE_VERBOSE_SILENT)
387 		printf("\n");
388 	return ret;
389 }
390 
391 #if defined(__i386__) && __ELF_WORD_SIZE == 64
392 struct mod_metadata64 {
393 	int		md_version;	/* structure version MDTV_* */
394 	int		md_type;	/* type of entry MDT_* */
395 	uint64_t	md_data;	/* specific data */
396 	uint64_t	md_cval;	/* common string label */
397 };
398 #endif
399 
400 int
401 __elfN(obj_parse_modmetadata)(struct preloaded_file *fp, elf_file_t ef)
402 {
403 	struct mod_metadata md;
404 #if defined(__i386__) && __ELF_WORD_SIZE == 64
405 	struct mod_metadata64 md64;
406 #endif
407 	struct mod_depend *mdepend;
408 	struct mod_version mver;
409 	char *s;
410 	int error, modcnt, minfolen;
411 	Elf_Addr v, p, p_stop;
412 
413 	if (__elfN(obj_lookup_set)(fp, ef, "modmetadata_set", &p, &p_stop,
414 	    &modcnt) != 0)
415 		return 0;
416 
417 	modcnt = 0;
418 	while (p < p_stop) {
419 		COPYOUT(p, &v, sizeof(v));
420 		error = __elfN(obj_reloc_ptr)(fp, ef, p, &v, sizeof(v));
421 		if (error != 0)
422 			return (error);
423 #if defined(__i386__) && __ELF_WORD_SIZE == 64
424 		COPYOUT(v, &md64, sizeof(md64));
425 		error = __elfN(obj_reloc_ptr)(fp, ef, v, &md64, sizeof(md64));
426 		if (error != 0)
427 			return (error);
428 		md.md_version = md64.md_version;
429 		md.md_type = md64.md_type;
430 		md.md_cval = (const char *)(uintptr_t)md64.md_cval;
431 		md.md_data = (void *)(uintptr_t)md64.md_data;
432 #else
433 		COPYOUT(v, &md, sizeof(md));
434 		error = __elfN(obj_reloc_ptr)(fp, ef, v, &md, sizeof(md));
435 		if (error != 0)
436 			return (error);
437 #endif
438 		p += sizeof(Elf_Addr);
439 		switch(md.md_type) {
440 		case MDT_DEPEND:
441 			s = strdupout((vm_offset_t)md.md_cval);
442 			minfolen = sizeof(*mdepend) + strlen(s) + 1;
443 			mdepend = malloc(minfolen);
444 			if (mdepend == NULL)
445 				return ENOMEM;
446 			COPYOUT((vm_offset_t)md.md_data, mdepend,
447 			    sizeof(*mdepend));
448 			strcpy((char*)(mdepend + 1), s);
449 			free(s);
450 			file_addmetadata(fp, MODINFOMD_DEPLIST, minfolen,
451 			    mdepend);
452 			free(mdepend);
453 			break;
454 		case MDT_VERSION:
455 			s = strdupout((vm_offset_t)md.md_cval);
456 			COPYOUT((vm_offset_t)md.md_data, &mver, sizeof(mver));
457 			file_addmodule(fp, s, mver.mv_version, NULL);
458 			free(s);
459 			modcnt++;
460 			break;
461 		case MDT_MODULE:
462 		case MDT_PNP_INFO:
463 			break;
464 		default:
465 			printf("unknown type %d\n", md.md_type);
466 			break;
467 		}
468 	}
469 	return 0;
470 }
471 
472 static int
473 __elfN(obj_lookup_set)(struct preloaded_file *fp, elf_file_t ef,
474     const char* name, Elf_Addr *startp, Elf_Addr *stopp, int *countp)
475 {
476 	Elf_Ehdr *hdr;
477 	Elf_Shdr *shdr;
478 	char *p;
479 	vm_offset_t shstrtab;
480 	int i;
481 
482 	hdr = &ef->hdr;
483 	shdr = ef->e_shdr;
484 	shstrtab = shdr[ef->shstrindex].sh_addr;
485 
486 	for (i = 0; i < hdr->e_shnum; i++) {
487 		if (shdr[i].sh_type != SHT_PROGBITS)
488 			continue;
489 		if (shdr[i].sh_name == 0)
490 			continue;
491 		p = strdupout(shstrtab + shdr[i].sh_name);
492 		if (strncmp(p, "set_", 4) == 0 && strcmp(p + 4, name) == 0) {
493 			*startp = shdr[i].sh_addr;
494 			*stopp = shdr[i].sh_addr +  shdr[i].sh_size;
495 			*countp = (*stopp - *startp) / sizeof(Elf_Addr);
496 			free(p);
497 			return (0);
498 		}
499 		free(p);
500 	}
501 
502 	return (ESRCH);
503 }
504 
505 /*
506  * Apply any intra-module relocations to the value. p is the load address
507  * of the value and val/len is the value to be modified. This does NOT modify
508  * the image in-place, because this is done by kern_linker later on.
509  */
510 static int
511 __elfN(obj_reloc_ptr)(struct preloaded_file *mp, elf_file_t ef, Elf_Addr p,
512     void *val, size_t len)
513 {
514 	Elf_Ehdr *hdr;
515 	Elf_Shdr *shdr;
516 	Elf_Addr off = p;
517 	Elf_Addr base;
518 	Elf_Rela a, *abase;
519 	Elf_Rel r, *rbase;
520 	int error, i, j, nrel, nrela;
521 
522 	hdr = &ef->hdr;
523 	shdr = ef->e_shdr;
524 
525 	for (i = 0; i < hdr->e_shnum; i++) {
526 		if (shdr[i].sh_type != SHT_RELA && shdr[i].sh_type != SHT_REL)
527 			continue;
528 		base = shdr[shdr[i].sh_info].sh_addr;
529 		if (base == 0 || shdr[i].sh_addr == 0)
530 			continue;
531 		if (off < base || off + len > base +
532 		    shdr[shdr[i].sh_info].sh_size)
533 			continue;
534 
535 		switch (shdr[i].sh_type) {
536 		case SHT_RELA:
537 			abase = (Elf_Rela *)(intptr_t)shdr[i].sh_addr;
538 
539 			nrela = shdr[i].sh_size / sizeof(Elf_Rela);
540 			for (j = 0; j < nrela; j++) {
541 				COPYOUT(abase + j, &a, sizeof(a));
542 
543 				error = __elfN(reloc)(ef, __elfN(obj_symaddr),
544 				    &a, ELF_RELOC_RELA, base, off, val, len);
545 				if (error != 0)
546 					return (error);
547 			}
548 			break;
549 		case SHT_REL:
550 			rbase = (Elf_Rel *)(intptr_t)shdr[i].sh_addr;
551 
552 			nrel = shdr[i].sh_size / sizeof(Elf_Rel);
553 			for (j = 0; j < nrel; j++) {
554 				COPYOUT(rbase + j, &r, sizeof(r));
555 
556 				error = __elfN(reloc)(ef, __elfN(obj_symaddr),
557 				    &r, ELF_RELOC_REL, base, off, val, len);
558 				if (error != 0)
559 					return (error);
560 			}
561 			break;
562 		}
563 	}
564 	return (0);
565 }
566 
567 /* Look up the address of a specified symbol. */
568 static Elf_Addr
569 __elfN(obj_symaddr)(struct elf_file *ef, Elf_Size symidx)
570 {
571 	Elf_Sym sym;
572 	Elf_Addr base;
573 
574 	if (symidx >= ef->e_shdr[ef->symtabindex].sh_size / sizeof(Elf_Sym))
575 		return (0);
576 	COPYOUT(ef->e_shdr[ef->symtabindex].sh_addr + symidx * sizeof(Elf_Sym),
577 	    &sym, sizeof(sym));
578 	if (sym.st_shndx == SHN_UNDEF || sym.st_shndx >= ef->hdr.e_shnum)
579 		return (0);
580 	base = ef->e_shdr[sym.st_shndx].sh_addr;
581 	if (base == 0)
582 		return (0);
583 	return (base + sym.st_value);
584 }
585