source: mainline/uspace/lib/c/generic/elf/elf_mod.c@ 5c76cc61

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since 5c76cc61 was 7c3fb9b, checked in by Jiri Svoboda <jiri@…>, 7 years ago

Fix block comment formatting (ccheck).

  • Property mode set to 100644
File size: 12.9 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 generic
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 if (phdr_len > sizeof(phdr)) {
201 DPRINTF("more than %d program headers\n", phdr_cap);
202 return EE_UNSUPPORTED;
203 }
204
205 pos = header->e_phoff;
206 rc = vfs_read(elf->fd, &pos, phdr, phdr_len, &nr);
207 if (rc != EOK || nr != phdr_len) {
208 DPRINTF("Read error.\n");
209 return EE_IO;
210 }
211
212 uintptr_t module_base = UINTPTR_MAX;
213 uintptr_t module_top = 0;
214 uintptr_t base_offset = UINTPTR_MAX;
215
216 /* Walk through PT_LOAD headers, to find out the size of the module. */
217 for (i = 0; i < header->e_phnum; i++) {
218 if (phdr[i].p_type != PT_LOAD)
219 continue;
220
221 if (module_base > phdr[i].p_vaddr) {
222 module_base = phdr[i].p_vaddr;
223 base_offset = phdr[i].p_offset;
224 }
225 module_top = max(module_top, phdr[i].p_vaddr + phdr[i].p_memsz);
226 }
227
228 if (base_offset != 0) {
229 DPRINTF("ELF headers not present in the text segment.\n");
230 return EE_INVALID;
231 }
232
233 /* Shared objects can be loaded with a bias */
234 if (header->e_type != ET_DYN) {
235 elf->bias = 0;
236 } else {
237 if (module_base != 0) {
238 DPRINTF("Unexpected shared object format.\n");
239 return EE_INVALID;
240 }
241
242 /*
243 * Attempt to allocate a span of memory large enough for the
244 * shared object.
245 */
246 // FIXME: This is not reliable when we're running
247 // multi-threaded. Even if this part succeeds, later
248 // allocation can fail because another thread took the
249 // space in the meantime. This is only relevant for
250 // dlopen() though.
251 void *area = as_area_create(AS_AREA_ANY, module_top,
252 AS_AREA_READ | AS_AREA_WRITE | AS_AREA_CACHEABLE |
253 AS_AREA_LATE_RESERVE, AS_AREA_UNPAGED);
254
255 if (area == AS_MAP_FAILED) {
256 DPRINTF("Can't find suitable memory area.\n");
257 return EE_MEMORY;
258 }
259
260 elf->bias = (uintptr_t) area;
261 as_area_destroy(area);
262 }
263
264 /* Load all loadable segments. */
265 for (i = 0; i < header->e_phnum; i++) {
266 if (phdr[i].p_type != PT_LOAD)
267 continue;
268
269 ret = load_segment(elf, &phdr[i]);
270 if (ret != EE_OK)
271 return ret;
272 }
273
274 void *base = (void *) module_base + elf->bias;
275 elf->info->base = base;
276
277 /* Ensure valid TLS info even if there is no TLS header. */
278 elf->info->tls.tdata = NULL;
279 elf->info->tls.tdata_size = 0;
280 elf->info->tls.tbss_size = 0;
281 elf->info->tls.tls_align = 1;
282
283 elf->info->interp = NULL;
284 elf->info->dynamic = NULL;
285
286 /* Walk through all segment headers and process them. */
287 for (i = 0; i < header->e_phnum; i++) {
288 if (phdr[i].p_type == PT_LOAD)
289 continue;
290
291 ret = segment_header(elf, &phdr[i]);
292 if (ret != EE_OK)
293 return ret;
294 }
295
296 elf->info->entry =
297 (entry_point_t)((uint8_t *)header->e_entry + elf->bias);
298
299 DPRINTF("Done.\n");
300
301 return EE_OK;
302}
303
304/** Print error message according to error code.
305 *
306 * @param rc Return code returned by elf_load().
307 *
308 * @return NULL terminated description of error.
309 */
310const char *elf_error(unsigned int rc)
311{
312 assert(rc < sizeof(error_codes) / sizeof(char *));
313
314 return error_codes[rc];
315}
316
317/** Process TLS program header.
318 *
319 * @param elf Pointer to loader state buffer.
320 * @param hdr TLS program header
321 * @param info Place to store TLS info
322 */
323static void tls_program_header(elf_ld_t *elf, elf_segment_header_t *hdr,
324 elf_tls_info_t *info)
325{
326 info->tdata = (void *)((uint8_t *)hdr->p_vaddr + elf->bias);
327 info->tdata_size = hdr->p_filesz;
328 info->tbss_size = hdr->p_memsz - hdr->p_filesz;
329 info->tls_align = hdr->p_align;
330}
331
332/** Process segment header.
333 *
334 * @param elf Pointer to loader state buffer.
335 * @param entry Segment header.
336 *
337 * @return EE_OK on success, error code otherwise.
338 */
339static int segment_header(elf_ld_t *elf, elf_segment_header_t *entry)
340{
341 switch (entry->p_type) {
342 case PT_NULL:
343 case PT_PHDR:
344 case PT_NOTE:
345 break;
346 case PT_GNU_EH_FRAME:
347 case PT_GNU_STACK:
348 case PT_GNU_RELRO:
349 /* Ignore GNU headers, if present. */
350 break;
351 case PT_INTERP:
352 elf->info->interp =
353 (void *)((uint8_t *)entry->p_vaddr + elf->bias);
354
355 if (elf->info->interp[entry->p_filesz - 1] != '\0') {
356 DPRINTF("Unterminated ELF interp string.\n");
357 return EE_INVALID;
358 }
359 DPRINTF("interpreter: \"%s\"\n", elf->info->interp);
360 break;
361 case PT_DYNAMIC:
362 /* Record pointer to dynamic section into info structure */
363 elf->info->dynamic =
364 (void *)((uint8_t *)entry->p_vaddr + elf->bias);
365 DPRINTF("dynamic section found at %p\n",
366 (void *)elf->info->dynamic);
367 break;
368 case 0x70000000:
369 case 0x70000001:
370 case 0x70000002:
371 case 0x70000003:
372 // FIXME: Architecture-specific headers.
373 /* PT_MIPS_REGINFO, PT_MIPS_ABIFLAGS, PT_ARM_UNWIND, ... */
374 break;
375 case PT_TLS:
376 /* Parse TLS program header */
377 tls_program_header(elf, entry, &elf->info->tls);
378 DPRINTF("TLS header found at %p\n",
379 (void *)((uint8_t *)entry->p_vaddr + elf->bias));
380 break;
381 case PT_SHLIB:
382 default:
383 DPRINTF("Segment p_type %d unknown.\n", entry->p_type);
384 return EE_UNSUPPORTED;
385 break;
386 }
387 return EE_OK;
388}
389
390/** Load segment described by program header entry.
391 *
392 * @param elf Loader state.
393 * @param entry Program header entry describing segment to be loaded.
394 *
395 * @return EE_OK on success, error code otherwise.
396 */
397int load_segment(elf_ld_t *elf, elf_segment_header_t *entry)
398{
399 void *a;
400 int flags = 0;
401 uintptr_t bias;
402 uintptr_t base;
403 void *seg_ptr;
404 uintptr_t seg_addr;
405 size_t mem_sz;
406 aoff64_t pos;
407 errno_t rc;
408 size_t nr;
409
410 bias = elf->bias;
411
412 seg_addr = entry->p_vaddr + bias;
413 seg_ptr = (void *) seg_addr;
414
415 DPRINTF("Load segment at addr %p, size 0x%zx\n", (void *) seg_addr,
416 entry->p_memsz);
417
418 if (entry->p_align > 1) {
419 if ((entry->p_offset % entry->p_align) !=
420 (seg_addr % entry->p_align)) {
421 DPRINTF("Align check 1 failed offset%%align=0x%zx, "
422 "vaddr%%align=0x%zx\n",
423 entry->p_offset % entry->p_align,
424 seg_addr % entry->p_align);
425 return EE_INVALID;
426 }
427 }
428
429 /* Final flags that will be set for the memory area */
430
431 if (entry->p_flags & PF_X)
432 flags |= AS_AREA_EXEC;
433 if (entry->p_flags & PF_W)
434 flags |= AS_AREA_WRITE;
435 if (entry->p_flags & PF_R)
436 flags |= AS_AREA_READ;
437 flags |= AS_AREA_CACHEABLE;
438
439 base = ALIGN_DOWN(entry->p_vaddr, PAGE_SIZE);
440 mem_sz = entry->p_memsz + (entry->p_vaddr - base);
441
442 DPRINTF("Map to seg_addr=%p-%p.\n", (void *) seg_addr,
443 (void *) (entry->p_vaddr + bias +
444 ALIGN_UP(entry->p_memsz, PAGE_SIZE)));
445
446 /*
447 * For the course of loading, the area needs to be readable
448 * and writeable.
449 */
450 a = as_area_create((uint8_t *) base + bias, mem_sz,
451 AS_AREA_READ | AS_AREA_WRITE | AS_AREA_CACHEABLE,
452 AS_AREA_UNPAGED);
453 if (a == AS_MAP_FAILED) {
454 DPRINTF("memory mapping failed (%p, %zu)\n",
455 (void *) (base + bias), mem_sz);
456 return EE_MEMORY;
457 }
458
459 DPRINTF("as_area_create(%p, %#zx, %d) -> %p\n",
460 (void *) (base + bias), mem_sz, flags, (void *) a);
461
462 /*
463 * Load segment data
464 */
465 pos = entry->p_offset;
466 rc = vfs_read(elf->fd, &pos, seg_ptr, entry->p_filesz, &nr);
467 if (rc != EOK || nr != entry->p_filesz) {
468 DPRINTF("read error\n");
469 return EE_IO;
470 }
471
472 /*
473 * The caller wants to modify the segments first. He will then
474 * need to set the right access mode and ensure SMC coherence.
475 */
476 if ((elf->flags & ELDF_RW) != 0)
477 return EE_OK;
478
479 rc = as_area_change_flags(seg_ptr, flags);
480 if (rc != EOK) {
481 DPRINTF("Failed to set memory area flags.\n");
482 return EE_MEMORY;
483 }
484
485 if (flags & AS_AREA_EXEC) {
486 /* Enforce SMC coherence for the segment */
487 if (smc_coherence(seg_ptr, entry->p_filesz))
488 return EE_MEMORY;
489 }
490
491 return EE_OK;
492}
493
494/** @}
495 */
Note: See TracBrowser for help on using the repository browser.