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