• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Test program for reading and writing out the same file in-place
2    Copyright (C) 2019 Red Hat, Inc.
3    This file is part of elfutils.
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 
19 #ifdef HAVE_CONFIG_H
20 # include <config.h>
21 #endif
22 
23 #include <errno.h>
24 #include <fcntl.h>
25 #include <inttypes.h>
26 #include <stdbool.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <unistd.h>
31 #include <sys/types.h>
32 #include <sys/stat.h>
33 
34 #include ELFUTILS_HEADER(elf)
35 #include <gelf.h>
36 
37 
38 int
main(int argc,const char * argv[])39 main (int argc, const char *argv[])
40 {
41   /* Takes the given file, and create a new identical one.  */
42   if (argc != 2)
43     {
44       fprintf (stderr, "elfrdwrnop elf-file\n");
45       exit (1);
46     }
47 
48   elf_version (EV_CURRENT);
49 
50   const char *name = argv[1];
51   printf ("elfrdwrdnop %s\n", name);
52 
53   int fd = open (name, O_RDWR);
54   if (fd < 0)
55     {
56       fprintf (stderr, "Couldn't open file '%s': %s\n",
57 	       name, strerror (errno));
58       exit (1);
59     }
60 
61   Elf *elf = elf_begin (fd, ELF_C_RDWR, NULL);
62   if (elf == NULL)
63     {
64       fprintf (stderr, "Couldn't open ELF file '%s': %s\n",
65 	       name, elf_errmsg (-1));
66       exit (1);
67     }
68 
69   /* Write everything to disk.  If there are any phdrs, then we want
70      the exact same layout.  */
71   size_t phnum;
72   if (elf_getphdrnum (elf, &phnum) != 0)
73     {
74       printf ("cannot get phdrs: %s\n", elf_errmsg (-1));
75       exit (1);
76     }
77 
78   if (phnum > 0)
79     elf_flagelf (elf, ELF_C_SET, ELF_F_LAYOUT);
80 
81   if (elf_update (elf, ELF_C_WRITE) < 0)
82     {
83       printf ("failure in elf_update: %s\n", elf_errmsg (-1));
84       exit (1);
85     }
86 
87   if (elf_end (elf) != 0)
88     {
89       printf ("couldn't cleanup elf '%s': %s\n", name, elf_errmsg (-1));
90       exit (1);
91     }
92 
93   if (close (fd) != 0)
94     {
95       printf ("couldn't close '%s': %s\n", name, strerror (errno));
96       exit (1);
97     }
98 
99   return 0;
100 }
101