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