source: mainline/uspace/lib/c/generic/elf/elf_mod.c@ 64d38cd

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

Make some effort to allocate space for libraries.

  • Property mode set to 100644
File size: 12.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 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 load_segment(elf_ld_t *elf, elf_segment_header_t *entry);
78
79/** Load ELF binary from a file.
80 *
81 * Load an ELF binary from the specified file. If the file is
82 * an executable program, it is loaded unbiased. If it is a shared
83 * object, it is loaded with the bias @a so_bias. Some information
84 * extracted from the binary is stored in a elf_info_t structure
85 * pointed to by @a info.
86 *
87 * @param file ELF file.
88 * @param info Pointer to a structure for storing information
89 * extracted from the binary.
90 *
91 * @return EE_OK on success or EE_xx error code.
92 *
93 */
94int elf_load_file(int file, eld_flags_t flags, elf_finfo_t *info)
95{
96 elf_ld_t elf;
97
98 int ofile;
99 errno_t rc = vfs_clone(file, -1, true, &ofile);
100 if (rc == EOK) {
101 rc = vfs_open(ofile, MODE_READ);
102 }
103 if (rc != EOK) {
104 return EE_IO;
105 }
106
107 elf.fd = ofile;
108 elf.info = info;
109 elf.flags = flags;
110
111 int ret = elf_load_module(&elf);
112
113 vfs_put(ofile);
114 return ret;
115}
116
117int elf_load_file_name(const char *path, eld_flags_t flags, elf_finfo_t *info)
118{
119 int file;
120 errno_t rc = vfs_lookup(path, 0, &file);
121 if (rc == EOK) {
122 int ret = elf_load_file(file, flags, info);
123 vfs_put(file);
124 return ret;
125 } else {
126 return EE_IO;
127 }
128}
129
130/** Process TLS program header.
131 *
132 * @param elf Pointer to loader state buffer.
133 * @param hdr TLS program header
134 * @param info Place to store TLS info
135 */
136static void tls_program_header(void *base, elf_tls_info_t *info)
137{
138 const elf_segment_header_t *tls = elf_get_phdr(base, PT_TLS);
139 size_t bias = elf_get_bias(base);
140
141 if (tls == NULL) {
142 /* Ensure valid TLS info even if there is no TLS header. */
143 info->tdata = NULL;
144 info->tdata_size = 0;
145 info->tbss_size = 0;
146 info->tls_align = 1;
147 } else {
148 info->tdata = (void *) tls->p_vaddr + bias;
149 info->tdata_size = tls->p_filesz;
150 info->tbss_size = tls->p_memsz - tls->p_filesz;
151 info->tls_align = tls->p_align;
152 }
153}
154
155/** Load an ELF binary.
156 *
157 * The @a elf structure contains the loader state, including
158 * an open file, from which the binary will be loaded,
159 * a pointer to the @c info structure etc.
160 *
161 * @param elf Pointer to loader state buffer.
162 * @return EE_OK on success or EE_xx error code.
163 */
164static unsigned int elf_load_module(elf_ld_t *elf)
165{
166 elf_header_t header_buf;
167 elf_header_t *header = &header_buf;
168 aoff64_t pos = 0;
169 size_t nr;
170 int i, ret;
171 errno_t rc;
172
173 rc = vfs_read(elf->fd, &pos, header, sizeof(elf_header_t), &nr);
174 if (rc != EOK || nr != sizeof(elf_header_t)) {
175 DPRINTF("Read error.\n");
176 return EE_IO;
177 }
178
179 /* Identify ELF */
180 if (header->e_ident[EI_MAG0] != ELFMAG0 ||
181 header->e_ident[EI_MAG1] != ELFMAG1 ||
182 header->e_ident[EI_MAG2] != ELFMAG2 ||
183 header->e_ident[EI_MAG3] != ELFMAG3) {
184 DPRINTF("Invalid header.\n");
185 return EE_INVALID;
186 }
187
188 /* Identify ELF compatibility */
189 if (header->e_ident[EI_DATA] != ELF_DATA_ENCODING ||
190 header->e_machine != ELF_MACHINE ||
191 header->e_ident[EI_VERSION] != EV_CURRENT ||
192 header->e_version != EV_CURRENT ||
193 header->e_ident[EI_CLASS] != ELF_CLASS) {
194 DPRINTF("Incompatible data/version/class.\n");
195 return EE_INCOMPATIBLE;
196 }
197
198 if (header->e_phentsize != sizeof(elf_segment_header_t)) {
199 DPRINTF("e_phentsize: %u != %zu\n", header->e_phentsize,
200 sizeof(elf_segment_header_t));
201 return EE_INCOMPATIBLE;
202 }
203
204 /* Check if the object type is supported. */
205 if (header->e_type != ET_EXEC && header->e_type != ET_DYN) {
206 DPRINTF("Object type %d is not supported\n", header->e_type);
207 return EE_UNSUPPORTED;
208 }
209
210 if (header->e_phoff == 0) {
211 DPRINTF("Program header table is not present!\n");
212 return EE_INCOMPATIBLE;
213 }
214
215 /* Read program header table.
216 * Normally, there is very few program headers, so don't bother
217 * with allocating memory dynamically.
218 */
219 const int phdr_cap = 16;
220 elf_segment_header_t phdr[phdr_cap];
221 size_t phdr_len = header->e_phnum * header->e_phentsize;
222
223 if (phdr_len > sizeof(phdr)) {
224 DPRINTF("more than %d program headers\n", phdr_cap);
225 return EE_UNSUPPORTED;
226 }
227
228 pos = header->e_phoff;
229 rc = vfs_read(elf->fd, &pos, phdr, phdr_len, &nr);
230 if (rc != EOK || nr != phdr_len) {
231 DPRINTF("Read error.\n");
232 return EE_IO;
233 }
234
235 uintptr_t module_base = UINTPTR_MAX;
236 uintptr_t module_top = 0;
237 uintptr_t base_offset = UINTPTR_MAX;
238
239 /* Walk through PT_LOAD headers, to find out the size of the module. */
240 for (i = 0; i < header->e_phnum; i++) {
241 if (phdr[i].p_type != PT_LOAD)
242 continue;
243
244 if (module_base > phdr[i].p_vaddr) {
245 module_base = phdr[i].p_vaddr;
246 base_offset = phdr[i].p_offset;
247 }
248 module_top = max(module_top, phdr[i].p_vaddr + phdr[i].p_memsz);
249 }
250
251 if (base_offset != 0) {
252 DPRINTF("ELF headers not present in the text segment.\n");
253 return EE_INVALID;
254 }
255
256 /* Shared objects can be loaded with a bias */
257 if (header->e_type != ET_DYN) {
258 elf->bias = 0;
259 } else {
260 if (module_base != 0) {
261 DPRINTF("Unexpected shared object format.\n");
262 return EE_INVALID;
263 }
264
265 /* Attempt to allocate a span of memory large enough for the
266 * shared object.
267 */
268 // FIXME: This is not reliable when we're running
269 // multi-threaded. Even if this part succeeds, later
270 // allocation can fail because another thread took the
271 // space in the meantime. This is only relevant for
272 // dlopen() though.
273 void *area = as_area_create(AS_AREA_ANY, module_top,
274 AS_AREA_READ | AS_AREA_WRITE | AS_AREA_CACHEABLE |
275 AS_AREA_LATE_RESERVE, AS_AREA_UNPAGED);
276
277 if (area == AS_MAP_FAILED) {
278 DPRINTF("Can't find suitable memory area.\n");
279 return EE_MEMORY;
280 }
281
282 elf->bias = (uintptr_t) area;
283 as_area_destroy(area);
284 }
285
286 /* Load all loadable segments. */
287 for (i = 0; i < header->e_phnum; i++) {
288 if (phdr[i].p_type != PT_LOAD)
289 continue;
290
291 ret = load_segment(elf, &phdr[i]);
292 if (ret != EE_OK)
293 return ret;
294 }
295
296 void *base = (void *) module_base + elf->bias;
297 elf->info->base = base;
298
299 /* Handle TLS. */
300 tls_program_header(base, &elf->info->tls);
301
302 /* Handle PT_INTERP. */
303
304 const elf_segment_header_t *interphdr = elf_get_phdr(base, PT_INTERP);
305
306 if (interphdr == NULL) {
307 interphdr = NULL;
308 } else {
309 elf->info->interp =
310 (const char *) (interphdr->p_vaddr + elf->bias);
311 if (elf->info->interp[interphdr->p_filesz - 1] != '\0') {
312 DPRINTF("Unterminated ELF interp string.\n");
313 elf->info->interp = NULL;
314 } else {
315 DPRINTF("interpreter: \"%s\"\n", elf->info->interp);
316 }
317 }
318
319 /* Handle PT_DYNAMIC. */
320
321 const elf_segment_header_t *dynphdr = elf_get_phdr(base, PT_DYNAMIC);
322
323 if (dynphdr == NULL) {
324 elf->info->dynamic = NULL;
325 } else {
326 /* Record pointer to dynamic section into info structure */
327 elf->info->dynamic = (void *) (dynphdr->p_vaddr + elf->bias);
328 DPRINTF("dynamic section found at %p\n",
329 (void *)elf->info->dynamic);
330 }
331
332 elf->info->entry =
333 (entry_point_t)((uint8_t *)header->e_entry + elf->bias);
334
335 DPRINTF("Done.\n");
336
337 return EE_OK;
338}
339
340/** Print error message according to error code.
341 *
342 * @param rc Return code returned by elf_load().
343 *
344 * @return NULL terminated description of error.
345 */
346const char *elf_error(unsigned int rc)
347{
348 assert(rc < sizeof(error_codes) / sizeof(char *));
349
350 return error_codes[rc];
351}
352
353/** Load segment described by program header entry.
354 *
355 * @param elf Loader state.
356 * @param entry Program header entry describing segment to be loaded.
357 *
358 * @return EE_OK on success, error code otherwise.
359 */
360int load_segment(elf_ld_t *elf, elf_segment_header_t *entry)
361{
362 void *a;
363 int flags = 0;
364 uintptr_t bias;
365 uintptr_t base;
366 void *seg_ptr;
367 uintptr_t seg_addr;
368 size_t mem_sz;
369 aoff64_t pos;
370 errno_t rc;
371 size_t nr;
372
373 bias = elf->bias;
374
375 seg_addr = entry->p_vaddr + bias;
376 seg_ptr = (void *) seg_addr;
377
378 DPRINTF("Load segment at addr %p, size 0x%zx\n", (void *) seg_addr,
379 entry->p_memsz);
380
381 if (entry->p_align > 1) {
382 if ((entry->p_offset % entry->p_align) !=
383 (seg_addr % entry->p_align)) {
384 DPRINTF("Align check 1 failed offset%%align=0x%zx, "
385 "vaddr%%align=0x%zx\n",
386 entry->p_offset % entry->p_align,
387 seg_addr % entry->p_align);
388 return EE_INVALID;
389 }
390 }
391
392 /* Final flags that will be set for the memory area */
393
394 if (entry->p_flags & PF_X)
395 flags |= AS_AREA_EXEC;
396 if (entry->p_flags & PF_W)
397 flags |= AS_AREA_WRITE;
398 if (entry->p_flags & PF_R)
399 flags |= AS_AREA_READ;
400 flags |= AS_AREA_CACHEABLE;
401
402 base = ALIGN_DOWN(entry->p_vaddr, PAGE_SIZE);
403 mem_sz = entry->p_memsz + (entry->p_vaddr - base);
404
405 DPRINTF("Map to seg_addr=%p-%p.\n", (void *) seg_addr,
406 (void *) (entry->p_vaddr + bias +
407 ALIGN_UP(entry->p_memsz, PAGE_SIZE)));
408
409 /*
410 * For the course of loading, the area needs to be readable
411 * and writeable.
412 */
413 a = as_area_create((uint8_t *) base + bias, mem_sz,
414 AS_AREA_READ | AS_AREA_WRITE | AS_AREA_CACHEABLE,
415 AS_AREA_UNPAGED);
416 if (a == AS_MAP_FAILED) {
417 DPRINTF("memory mapping failed (%p, %zu)\n",
418 (void *) (base + bias), mem_sz);
419 return EE_MEMORY;
420 }
421
422 DPRINTF("as_area_create(%p, %#zx, %d) -> %p\n",
423 (void *) (base + bias), mem_sz, flags, (void *) a);
424
425 /*
426 * Load segment data
427 */
428 pos = entry->p_offset;
429 rc = vfs_read(elf->fd, &pos, seg_ptr, entry->p_filesz, &nr);
430 if (rc != EOK || nr != entry->p_filesz) {
431 DPRINTF("read error\n");
432 return EE_IO;
433 }
434
435 /*
436 * The caller wants to modify the segments first. He will then
437 * need to set the right access mode and ensure SMC coherence.
438 */
439 if ((elf->flags & ELDF_RW) != 0)
440 return EE_OK;
441
442 rc = as_area_change_flags(seg_ptr, flags);
443 if (rc != EOK) {
444 DPRINTF("Failed to set memory area flags.\n");
445 return EE_MEMORY;
446 }
447
448 if (flags & AS_AREA_EXEC) {
449 /* Enforce SMC coherence for the segment */
450 if (smc_coherence(seg_ptr, entry->p_filesz))
451 return EE_MEMORY;
452 }
453
454 return EE_OK;
455}
456
457/** @}
458 */
Note: See TracBrowser for help on using the repository browser.