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