source: mainline/uspace/lib/c/generic/elf/elf_mod.c@ 99013b84

Last change on this file since 99013b84 was 888a2c6, checked in by Jiří Zárevúcky <jiri.zarevucky@…>, 7 years ago

Ignore GNU program headers.

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