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