Upstream version 9.37.197.0
[platform/framework/web/crosswalk.git] / src / native_client / src / trusted / service_runtime / linux / nacl_bootstrap_munge_phdr.c
1 /*
2  * Copyright (c) 2011 The Native Client Authors. All rights reserved.
3  * Use of this source code is governed by a BSD-style license that can be
4  * found in the LICENSE file.
5  *
6  * This is a trivial program to edit an ELF file in place, making
7  * one crucial modification to a program header.  It's invoked:
8  *      bootstrap_phdr_hacker FILENAME SEGMENT_NUMBER
9  * where SEGMENT_NUMBER is the zero-origin index of the program header
10  * we'll touch.  This is a PT_LOAD with p_filesz of zero.  We change its
11  * p_filesz to match its p_memsz value.
12  */
13
14 #include <errno.h>
15 #include <error.h>
16 #include <fcntl.h>
17 #include <gelf.h>
18 #include <libelf.h>
19 #include <stdlib.h>
20 #include <unistd.h>
21
22 int main(int argc, char **argv) {
23   const char *file;
24   int segment;
25   int fd;
26   Elf *elf;
27   GElf_Phdr phdr;
28   GElf_Phdr *ph;
29
30   if (argc != 3)
31     error(1, 0, "Usage: %s FILENAME SEGMENT_NUMBER", argv[0]);
32
33   file = argv[1];
34   segment = atoi(argv[2]);
35
36   fd = open(file, O_RDWR);
37   if (fd < 0)
38     error(2, errno, "Cannot open %s for read/write", file);
39
40   if (elf_version(EV_CURRENT) == EV_NONE)
41     error(2, 0, "elf_version: %s", elf_errmsg(-1));
42
43   elf = elf_begin(fd, ELF_C_RDWR, NULL);
44   if (elf == NULL)
45     error(2, 0, "elf_begin: %s", elf_errmsg(-1));
46
47   if (elf_flagelf(elf, ELF_C_SET, ELF_F_LAYOUT) == 0)
48     error(2, 0, "elf_flagelf: %s", elf_errmsg(-1));
49
50   ph = gelf_getphdr(elf, segment, &phdr);
51   if (ph == NULL)
52     error(2, 0, "gelf_getphdr: %s", elf_errmsg(-1));
53
54   if (ph->p_type != PT_LOAD)
55     error(3, 0, "Program header %d is %u, not PT_LOAD",
56           segment, (unsigned int) ph->p_type);
57   if (ph->p_filesz != 0)
58     error(3, 0, "Program header %d has nonzero p_filesz", segment);
59
60   ph->p_filesz = ph->p_memsz;
61   if (gelf_update_phdr(elf, segment, ph) == 0)
62     error(2, 0, "gelf_update_phdr: %s", elf_errmsg(-1));
63
64   if (elf_flagphdr(elf, ELF_C_SET, ELF_F_DIRTY) == 0)
65     error(2, 0, "elf_flagphdr: %s", elf_errmsg(-1));
66
67   if (elf_update(elf, ELF_C_WRITE) < 0)
68     error(2, 0, "elf_update: %s", elf_errmsg(-1));
69
70   elf_end(elf);
71   close(fd);
72
73   return 0;
74 }