OLD | NEW |
---|---|
(Empty) | |
1 /* Copyright (c) 2011 The Chromium Authors. All rights reserved. | |
2 * Use of this source code is governed by a BSD-style license that can be | |
3 * found in the LICENSE file. | |
4 * | |
5 * This is a trivial program to edit an ELF file in place, making | |
6 * one crucial modification to a program header. It's invoked: | |
7 * bootstrap_phdr_hacker FILENAME SEGMENT_NUMBER | |
8 * where SEGMENT_NUMBER is the zero-origin index of the program header | |
9 * we'll touch. This is a PT_LOAD with p_filesz of zero. We change its | |
10 * p_filesz to match its p_memsz value. | |
11 */ | |
Brad Chen
2011/08/29 23:04:57
It may be that this should go into tools/ instead
| |
12 | |
13 #define _FILE_OFFSET_BITS 64 | |
Mark Seaborn
2011/08/29 22:26:50
This needs a comment. Is it really needed?
| |
14 #include <errno.h> | |
15 #include <error.h> | |
16 #include <fcntl.h> | |
17 #include <gelf.h> | |
18 #include <libelf.h> | |
Mark Seaborn
2011/08/29 22:26:50
A new build-time dependency? If you must depend o
| |
19 #include <stdlib.h> | |
20 #include <unistd.h> | |
21 | |
22 int main(int argc, char **argv) { | |
23 if (argc != 3) | |
24 error(1, 0, "Usage: %s FILENAME SEGMENT_NUMBER", argv[0]); | |
25 | |
26 const char *const file = argv[1]; | |
27 const int segment = atoi(argv[2]); | |
28 | |
29 int fd = open(file, O_RDWR); | |
30 if (fd < 0) | |
31 error(2, errno, "Cannot open %s for read/write", file); | |
32 | |
33 if (elf_version(EV_CURRENT) == EV_NONE) | |
34 error(2, 0, "elf_version: %s", elf_errmsg(-1)); | |
35 | |
36 Elf *elf = elf_begin(fd, ELF_C_RDWR, NULL); | |
37 if (elf == NULL) | |
38 error(2, 0, "elf_begin: %s", elf_errmsg(-1)); | |
39 | |
40 if (elf_flagelf(elf, ELF_C_SET, ELF_F_LAYOUT) == 0) | |
41 error(2, 0, "elf_flagelf: %s", elf_errmsg(-1)); | |
42 | |
43 GElf_Phdr phdr; | |
44 GElf_Phdr *ph = gelf_getphdr(elf, segment, &phdr); | |
45 if (ph == NULL) | |
46 error(2, 0, "gelf_getphdr: %s", elf_errmsg(-1)); | |
47 | |
48 if (ph->p_type != PT_LOAD) | |
49 error(3, 0, "Program header %d is %u, not PT_LOAD", | |
50 segment, (unsigned int) ph->p_type); | |
51 if (ph->p_filesz != 0) | |
52 error(3, 0, "Program header %d has nonzero p_filesz", segment); | |
53 | |
54 ph->p_filesz = ph->p_memsz; | |
55 if (gelf_update_phdr(elf, segment, ph) == 0) | |
56 error(2, 0, "gelf_update_phdr: %s", elf_errmsg(-1)); | |
57 | |
58 if (elf_flagphdr(elf, ELF_C_SET, ELF_F_DIRTY) == 0) | |
59 error(2, 0, "elf_flagphdr: %s", elf_errmsg(-1)); | |
60 | |
61 if (elf_update(elf, ELF_C_WRITE) < 0) | |
62 error(2, 0, "elf_update: %s", elf_errmsg(-1)); | |
63 | |
64 close(fd); | |
65 | |
66 return 0; | |
67 } | |
OLD | NEW |