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