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