1 /* Test program for elf_strptr function.
2    Copyright (C) 2015 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 #ifdef HAVE_CONFIG_H
19 # include <config.h>
20 #endif
21 
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <inttypes.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <unistd.h>
29 
30 #include ELFUTILS_HEADER(elf)
31 #include <gelf.h>
32 
33 int
main(int argc,char * argv[])34 main (int argc, char *argv[])
35 {
36   if (argc != 2)
37     {
38       printf ("No ELF file given as argument");
39       exit (1);
40     }
41 
42   const char *fname = argv[1];
43 
44   // Initialize libelf.
45   elf_version (EV_CURRENT);
46 
47   /* Read the ELF from disk now.  */
48   int fd = open (fname, O_RDONLY);
49   if (fd == -1)
50     {
51       printf ("cannot open `%s' read-only: %s\n", fname, strerror (errno));
52       exit (1);
53     }
54 
55   Elf *elf = elf_begin (fd, ELF_C_READ, NULL);
56   if (elf == NULL)
57     {
58       printf ("cannot create ELF descriptor read-only: %s\n", elf_errmsg (-1));
59       exit (1);
60     }
61 
62   size_t ndx;
63   if (elf_getshdrstrndx (elf, &ndx) != 0)
64     {
65       printf ("cannot get section header table index: %s\n", elf_errmsg (-1));
66       exit (1);
67     }
68 
69   if (ndx == SHN_UNDEF)
70     {
71       printf ("ELF file `%s' doesn't have a section header table index", fname);
72       exit (1);
73     }
74 
75   printf ("Strings in section %zd:\n", ndx);
76 
77   size_t off = 0;
78   const char *str = elf_strptr (elf, ndx, off);
79   while (str != NULL)
80     {
81       printf ("[%zx] '%s'\n", off, str);
82       off += strlen (str) + 1;
83       str = elf_strptr (elf, ndx, off);
84     }
85 
86   if (elf_end (elf) != 0)
87     {
88       printf ("failure in elf_end: %s\n", elf_errmsg (-1));
89       exit (1);
90     }
91 
92   close (fd);
93 
94   return 0;
95 }
96