source: mainline/uspace/lib/c/generic/elf/elf_mod.c@ 174156fd

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since 174156fd was 174156fd, checked in by Jakub Jermar <jakub@…>, 7 years ago

Disambiguate doxygroup generic*

  • Property mode set to 100644
File size: 13.0 KB
Line 
1/*
2 * Copyright (c) 2006 Sergey Bondari
3 * Copyright (c) 2006 Jakub Jermar
4 * Copyright (c) 2011 Jiri Svoboda
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 *
11 * - Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * - Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * - The name of the author may not be used to endorse or promote products
17 * derived from this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 */
30
31/** @addtogroup libc
32 * @{
33 */
34
35/**
36 * @file
37 * @brief Userspace ELF module loader.
38 *
39 * This module allows loading ELF binaries (both executables and
40 * shared objects) from VFS. The current implementation allocates
41 * anonymous memory, fills it with segment data and then adjusts
42 * the memory areas' flags to the final value. In the future,
43 * the segments will be mapped directly from the file.
44 */
45
46#include <errno.h>
47#include <stdio.h>
48#include <vfs/vfs.h>
49#include <stddef.h>
50#include <stdint.h>
51#include <align.h>
52#include <assert.h>
53#include <as.h>
54#include <elf/elf.h>
55#include <smc.h>
56#include <loader/pcb.h>
57#include <entry_point.h>
58#include <str_error.h>
59#include <stdlib.h>
60#include <macros.h>
61
62#include <elf/elf_load.h>
63
64#define DPRINTF(...)
65
66static const char *error_codes[] = {
67 "no error",
68 "invalid image",
69 "address space error",
70 "incompatible image",
71 "unsupported image type",
72 "irrecoverable error",
73 "file io error"
74};
75
76static unsigned int elf_load_module(elf_ld_t *elf);
77static int segment_header(elf_ld_t *elf, elf_segment_header_t *entry);
78static int load_segment(elf_ld_t *elf, elf_segment_header_t *entry);
79
80/** Load ELF binary from a file.
81 *
82 * Load an ELF binary from the specified file. If the file is
83 * an executable program, it is loaded unbiased. If it is a shared
84 * object, it is loaded with the bias @a so_bias. Some information
85 * extracted from the binary is stored in a elf_info_t structure
86 * pointed to by @a info.
87 *
88 * @param file ELF file.
89 * @param info Pointer to a structure for storing information
90 * extracted from the binary.
91 *
92 * @return EE_OK on success or EE_xx error code.
93 *
94 */
95int elf_load_file(int file, eld_flags_t flags, elf_finfo_t *info)
96{
97 elf_ld_t elf;
98
99 int ofile;
100 errno_t rc = vfs_clone(file, -1, true, &ofile);
101 if (rc == EOK) {
102 rc = vfs_open(ofile, MODE_READ);
103 }
104 if (rc != EOK) {
105 return EE_IO;
106 }
107
108 elf.fd = ofile;
109 elf.info = info;
110 elf.flags = flags;
111
112 int ret = elf_load_module(&elf);
113
114 vfs_put(ofile);
115 return ret;
116}
117
118int elf_load_file_name(const char *path, eld_flags_t flags, elf_finfo_t *info)
119{
120 int file;
121 errno_t rc = vfs_lookup(path, 0, &file);
122 if (rc == EOK) {
123 int ret = elf_load_file(file, flags, info);
124 vfs_put(file);
125 return ret;
126 } else {
127 return EE_IO;
128 }
129}
130
131/** Load an ELF binary.
132 *
133 * The @a elf structure contains the loader state, including
134 * an open file, from which the binary will be loaded,
135 * a pointer to the @c info structure etc.
136 *
137 * @param elf Pointer to loader state buffer.
138 * @return EE_OK on success or EE_xx error code.
139 */
140static unsigned int elf_load_module(elf_ld_t *elf)
141{
142 elf_header_t header_buf;
143 elf_header_t *header = &header_buf;
144 aoff64_t pos = 0;
145 size_t nr;
146 int i, ret;
147 errno_t rc;
148
149 rc = vfs_read(elf->fd, &pos, header, sizeof(elf_header_t), &nr);
150 if (rc != EOK || nr != sizeof(elf_header_t)) {
151 DPRINTF("Read error.\n");
152 return EE_IO;
153 }
154
155 /* Identify ELF */
156 if (header->e_ident[EI_MAG0] != ELFMAG0 ||
157 header->e_ident[EI_MAG1] != ELFMAG1 ||
158 header->e_ident[EI_MAG2] != ELFMAG2 ||
159 header->e_ident[EI_MAG3] != ELFMAG3) {
160 DPRINTF("Invalid header.\n");
161 return EE_INVALID;
162 }
163
164 /* Identify ELF compatibility */
165 if (header->e_ident[EI_DATA] != ELF_DATA_ENCODING ||
166 header->e_machine != ELF_MACHINE ||
167 header->e_ident[EI_VERSION] != EV_CURRENT ||
168 header->e_version != EV_CURRENT ||
169 header->e_ident[EI_CLASS] != ELF_CLASS) {
170 DPRINTF("Incompatible data/version/class.\n");
171 return EE_INCOMPATIBLE;
172 }
173
174 if (header->e_phentsize != sizeof(elf_segment_header_t)) {
175 DPRINTF("e_phentsize: %u != %zu\n", header->e_phentsize,
176 sizeof(elf_segment_header_t));
177 return EE_INCOMPATIBLE;
178 }
179
180 /* Check if the object type is supported. */
181 if (header->e_type != ET_EXEC && header->e_type != ET_DYN) {
182 DPRINTF("Object type %d is not supported\n", header->e_type);
183 return EE_UNSUPPORTED;
184 }
185
186 if (header->e_phoff == 0) {
187 DPRINTF("Program header table is not present!\n");
188 return EE_UNSUPPORTED;
189 }
190
191 /*
192 * Read program header table.
193 * Normally, there are very few program headers, so don't bother
194 * with allocating memory dynamically.
195 */
196 const int phdr_cap = 16;
197 elf_segment_header_t phdr[phdr_cap];
198 size_t phdr_len = header->e_phnum * header->e_phentsize;
199
200 elf->info->interp = NULL;
201 elf->info->dynamic = NULL;
202
203 if (phdr_len > sizeof(phdr)) {
204 DPRINTF("more than %d program headers\n", phdr_cap);
205 return EE_UNSUPPORTED;
206 }
207
208 pos = header->e_phoff;
209 rc = vfs_read(elf->fd, &pos, phdr, phdr_len, &nr);
210 if (rc != EOK || nr != phdr_len) {
211 DPRINTF("Read error.\n");
212 return EE_IO;
213 }
214
215 uintptr_t module_base = UINTPTR_MAX;
216 uintptr_t module_top = 0;
217 uintptr_t base_offset = UINTPTR_MAX;
218
219 /* Walk through PT_LOAD headers, to find out the size of the module. */
220 for (i = 0; i < header->e_phnum; i++) {
221 if (phdr[i].p_type != PT_LOAD)
222 continue;
223
224 if (module_base > phdr[i].p_vaddr) {
225 module_base = phdr[i].p_vaddr;
226 base_offset = phdr[i].p_offset;
227 }
228 module_top = max(module_top, phdr[i].p_vaddr + phdr[i].p_memsz);
229 }
230
231 if (base_offset != 0) {
232 DPRINTF("ELF headers not present in the text segment.\n");
233 return EE_INVALID;
234 }
235
236 /* Shared objects can be loaded with a bias */
237 if (header->e_type != ET_DYN) {
238 elf->bias = 0;
239 } else {
240 if (module_base != 0) {
241 DPRINTF("Unexpected shared object format.\n");
242 return EE_INVALID;
243 }
244
245 /*
246 * Attempt to allocate a span of memory large enough for the
247 * shared object.
248 */
249 // FIXME: This is not reliable when we're running
250 // multi-threaded. Even if this part succeeds, later
251 // allocation can fail because another thread took the
252 // space in the meantime. This is only relevant for
253 // dlopen() though.
254 void *area = as_area_create(AS_AREA_ANY, module_top,
255 AS_AREA_READ | AS_AREA_WRITE | AS_AREA_CACHEABLE |
256 AS_AREA_LATE_RESERVE, AS_AREA_UNPAGED);
257
258 if (area == AS_MAP_FAILED) {
259 DPRINTF("Can't find suitable memory area.\n");
260 return EE_MEMORY;
261 }
262
263 elf->bias = (uintptr_t) area;
264 as_area_destroy(area);
265 }
266
267 /* Load all loadable segments. */
268 for (i = 0; i < header->e_phnum; i++) {
269 if (phdr[i].p_type != PT_LOAD)
270 continue;
271
272 ret = load_segment(elf, &phdr[i]);
273 if (ret != EE_OK)
274 return ret;
275 }
276
277 void *base = (void *) module_base + elf->bias;
278 elf->info->base = base;
279
280 /* Ensure valid TLS info even if there is no TLS header. */
281 elf->info->tls.tdata = NULL;
282 elf->info->tls.tdata_size = 0;
283 elf->info->tls.tbss_size = 0;
284 elf->info->tls.tls_align = 1;
285
286 elf->info->interp = NULL;
287 elf->info->dynamic = NULL;
288
289 /* Walk through all segment headers and process them. */
290 for (i = 0; i < header->e_phnum; i++) {
291 if (phdr[i].p_type == PT_LOAD)
292 continue;
293
294 ret = segment_header(elf, &phdr[i]);
295 if (ret != EE_OK)
296 return ret;
297 }
298
299 elf->info->entry =
300 (entry_point_t)((uint8_t *)header->e_entry + elf->bias);
301
302 DPRINTF("Done.\n");
303
304 return EE_OK;
305}
306
307/** Print error message according to error code.
308 *
309 * @param rc Return code returned by elf_load().
310 *
311 * @return NULL terminated description of error.
312 */
313const char *elf_error(unsigned int rc)
314{
315 assert(rc < sizeof(error_codes) / sizeof(char *));
316
317 return error_codes[rc];
318}
319
320/** Process TLS program header.
321 *
322 * @param elf Pointer to loader state buffer.
323 * @param hdr TLS program header
324 * @param info Place to store TLS info
325 */
326static void tls_program_header(elf_ld_t *elf, elf_segment_header_t *hdr,
327 elf_tls_info_t *info)
328{
329 info->tdata = (void *)((uint8_t *)hdr->p_vaddr + elf->bias);
330 info->tdata_size = hdr->p_filesz;
331 info->tbss_size = hdr->p_memsz - hdr->p_filesz;
332 info->tls_align = hdr->p_align;
333}
334
335/** Process segment header.
336 *
337 * @param elf Pointer to loader state buffer.
338 * @param entry Segment header.
339 *
340 * @return EE_OK on success, error code otherwise.
341 */
342static int segment_header(elf_ld_t *elf, elf_segment_header_t *entry)
343{
344 switch (entry->p_type) {
345 case PT_NULL:
346 case PT_PHDR:
347 case PT_NOTE:
348 break;
349 case PT_GNU_EH_FRAME:
350 case PT_GNU_STACK:
351 case PT_GNU_RELRO:
352 /* Ignore GNU headers, if present. */
353 break;
354 case PT_INTERP:
355 elf->info->interp =
356 (void *)((uint8_t *)entry->p_vaddr + elf->bias);
357
358 if (entry->p_filesz == 0) {
359 DPRINTF("Zero-sized ELF interp string.\n");
360 return EE_INVALID;
361 }
362 if (elf->info->interp[entry->p_filesz - 1] != '\0') {
363 DPRINTF("Unterminated ELF interp string.\n");
364 return EE_INVALID;
365 }
366 DPRINTF("interpreter: \"%s\"\n", elf->info->interp);
367 break;
368 case PT_DYNAMIC:
369 /* Record pointer to dynamic section into info structure */
370 elf->info->dynamic =
371 (void *)((uint8_t *)entry->p_vaddr + elf->bias);
372 DPRINTF("dynamic section found at %p\n",
373 (void *)elf->info->dynamic);
374 break;
375 case 0x70000000:
376 case 0x70000001:
377 case 0x70000002:
378 case 0x70000003:
379 // FIXME: Architecture-specific headers.
380 /* PT_MIPS_REGINFO, PT_MIPS_ABIFLAGS, PT_ARM_UNWIND, ... */
381 break;
382 case PT_TLS:
383 /* Parse TLS program header */
384 tls_program_header(elf, entry, &elf->info->tls);
385 DPRINTF("TLS header found at %p\n",
386 (void *)((uint8_t *)entry->p_vaddr + elf->bias));
387 break;
388 case PT_SHLIB:
389 default:
390 DPRINTF("Segment p_type %d unknown.\n", entry->p_type);
391 return EE_UNSUPPORTED;
392 break;
393 }
394 return EE_OK;
395}
396
397/** Load segment described by program header entry.
398 *
399 * @param elf Loader state.
400 * @param entry Program header entry describing segment to be loaded.
401 *
402 * @return EE_OK on success, error code otherwise.
403 */
404int load_segment(elf_ld_t *elf, elf_segment_header_t *entry)
405{
406 void *a;
407 int flags = 0;
408 uintptr_t bias;
409 uintptr_t base;
410 void *seg_ptr;
411 uintptr_t seg_addr;
412 size_t mem_sz;
413 aoff64_t pos;
414 errno_t rc;
415 size_t nr;
416
417 bias = elf->bias;
418
419 seg_addr = entry->p_vaddr + bias;
420 seg_ptr = (void *) seg_addr;
421
422 DPRINTF("Load segment at addr %p, size 0x%zx\n", (void *) seg_addr,
423 entry->p_memsz);
424
425 if (entry->p_align > 1) {
426 if ((entry->p_offset % entry->p_align) !=
427 (seg_addr % entry->p_align)) {
428 DPRINTF("Align check 1 failed offset%%align=0x%zx, "
429 "vaddr%%align=0x%zx\n",
430 entry->p_offset % entry->p_align,
431 seg_addr % entry->p_align);
432 return EE_INVALID;
433 }
434 }
435
436 /* Final flags that will be set for the memory area */
437
438 if (entry->p_flags & PF_X)
439 flags |= AS_AREA_EXEC;
440 if (entry->p_flags & PF_W)
441 flags |= AS_AREA_WRITE;
442 if (entry->p_flags & PF_R)
443 flags |= AS_AREA_READ;
444 flags |= AS_AREA_CACHEABLE;
445
446 base = ALIGN_DOWN(entry->p_vaddr, PAGE_SIZE);
447 mem_sz = entry->p_memsz + (entry->p_vaddr - base);
448
449 DPRINTF("Map to seg_addr=%p-%p.\n", (void *) seg_addr,
450 (void *) (entry->p_vaddr + bias +
451 ALIGN_UP(entry->p_memsz, PAGE_SIZE)));
452
453 /*
454 * For the course of loading, the area needs to be readable
455 * and writeable.
456 */
457 a = as_area_create((uint8_t *) base + bias, mem_sz,
458 AS_AREA_READ | AS_AREA_WRITE | AS_AREA_CACHEABLE,
459 AS_AREA_UNPAGED);
460 if (a == AS_MAP_FAILED) {
461 DPRINTF("memory mapping failed (%p, %zu)\n",
462 (void *) (base + bias), mem_sz);
463 return EE_MEMORY;
464 }
465
466 DPRINTF("as_area_create(%p, %#zx, %d) -> %p\n",
467 (void *) (base + bias), mem_sz, flags, (void *) a);
468
469 /*
470 * Load segment data
471 */
472 pos = entry->p_offset;
473 rc = vfs_read(elf->fd, &pos, seg_ptr, entry->p_filesz, &nr);
474 if (rc != EOK || nr != entry->p_filesz) {
475 DPRINTF("read error\n");
476 return EE_IO;
477 }
478
479 /*
480 * The caller wants to modify the segments first. He will then
481 * need to set the right access mode and ensure SMC coherence.
482 */
483 if ((elf->flags & ELDF_RW) != 0)
484 return EE_OK;
485
486 rc = as_area_change_flags(seg_ptr, flags);
487 if (rc != EOK) {
488 DPRINTF("Failed to set memory area flags.\n");
489 return EE_MEMORY;
490 }
491
492 if (flags & AS_AREA_EXEC) {
493 /* Enforce SMC coherence for the segment */
494 if (smc_coherence(seg_ptr, entry->p_filesz))
495 return EE_MEMORY;
496 }
497
498 return EE_OK;
499}
500
501/** @}
502 */
Note: See TracBrowser for help on using the repository browser.