1 /* Copyright (C) 2002, 2005 Red Hat, Inc.
2 This file is part of elfutils.
3 Written by Ulrich Drepper <drepper@redhat.com>, 2002.
4
5 This file is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 3 of the License, or
8 (at your option) any later version.
9
10 elfutils is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17
18 #include <errno.h>
19 #include <error.h>
20 #include <fcntl.h>
21 #include <gelf.h>
22 #include <stdlib.h>
23 #include <unistd.h>
24
25 int
main(int argc,char * argv[])26 main (int argc, char *argv[])
27 {
28 if (argc < 3)
29 error (EXIT_FAILURE, 0, "usage: %s FROMNAME TONAME", argv[0]);
30
31 elf_version (EV_CURRENT);
32
33 int infd = open (argv[1], O_RDONLY);
34 if (infd == -1)
35 error (EXIT_FAILURE, errno, "cannot open input file '%s'", argv[1]);
36
37 Elf *inelf = elf_begin (infd, ELF_C_READ, NULL);
38 if (inelf == NULL)
39 error (EXIT_FAILURE, 0, "problems opening '%s' as ELF file: %s",
40 argv[1], elf_errmsg (-1));
41
42 int outfd = creat (argv[2], 0666);
43 if (outfd == -1)
44 error (EXIT_FAILURE, errno, "cannot open output file '%s'", argv[2]);
45
46 Elf *outelf = elf_begin (outfd, ELF_C_WRITE, NULL);
47 if (outelf == NULL)
48 error (EXIT_FAILURE, 0, "problems opening '%s' as ELF file: %s",
49 argv[2], elf_errmsg (-1));
50
51 gelf_newehdr (outelf, gelf_getclass (inelf));
52
53 GElf_Ehdr ehdr_mem;
54 GElf_Ehdr *ehdr;
55 gelf_update_ehdr (outelf, (ehdr = gelf_getehdr (inelf, &ehdr_mem)));
56
57 if (ehdr->e_phnum > 0)
58 {
59 int cnt;
60
61 if (gelf_newphdr (outelf, ehdr->e_phnum) == 0)
62 error (EXIT_FAILURE, 0, "cannot create program header: %s",
63 elf_errmsg (-1));
64
65 for (cnt = 0; cnt < ehdr->e_phnum; ++cnt)
66 {
67 GElf_Phdr phdr_mem;
68
69 gelf_update_phdr (outelf, cnt, gelf_getphdr (inelf, cnt, &phdr_mem));
70 }
71 }
72
73 Elf_Scn *scn = NULL;
74 while ((scn = elf_nextscn (inelf, scn)) != NULL)
75 {
76 Elf_Scn *newscn = elf_newscn (outelf);
77
78 GElf_Shdr shdr_mem;
79 gelf_update_shdr (newscn, gelf_getshdr (scn, &shdr_mem));
80
81 *elf_newdata (newscn) = *elf_getdata (scn, NULL);
82 }
83
84 elf_flagelf (outelf, ELF_C_SET, ELF_F_LAYOUT);
85
86 if (elf_update (outelf, ELF_C_WRITE) == -1)
87 error (EXIT_FAILURE, 0, "elf_update failed: %s", elf_errmsg (-1));
88
89 elf_end (outelf);
90 close (outfd);
91
92 elf_end (inelf);
93
94 return 0;
95 }
96