1 /* Copyright (C) 1998, 1999, 2000, 2002, 2005 Red Hat, Inc.
2    This file is part of elfutils.
3    Written by Ulrich Drepper <drepper@redhat.com>, 1998.
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 <config.h>
19 
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <gelf.h>
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <string.h>
26 
27 int
main(int argc,char * argv[])28 main (int argc, char *argv[])
29 {
30   Elf *elf;
31   int fd;
32   GElf_Ehdr ehdr;
33   size_t strndx;
34   Elf_Scn *scn;
35 
36   if (argc < 2)
37     {
38       puts ("missing parameter");
39       exit (1);
40     }
41 
42   fd = open (argv[1], O_RDONLY);
43   if (fd == -1)
44     {
45       printf ("cannot open \"%s\": %s\n", argv[1], strerror (errno));
46       exit (1);
47     }
48 
49   elf_version (EV_CURRENT);
50 
51   elf = elf_begin (fd, ELF_C_READ, NULL);
52   if (elf == NULL)
53     {
54       printf ("cannot open ELF file: %s\n", elf_errmsg (-1));
55       exit (1);
56     }
57 
58   if (elf_kind (elf) != ELF_K_ELF)
59     {
60       printf ("\"%s\" is not an ELF file\n", argv[1]);
61       exit (1);
62     }
63 
64   if (gelf_getehdr (elf, &ehdr) == NULL)
65     {
66       printf ("cannot get the ELF header: %s\n", elf_errmsg (-1));
67       exit (1);
68     }
69 
70   strndx = ehdr.e_shstrndx;
71 
72   scn = NULL;
73   while ((scn = elf_nextscn (elf, scn)) != NULL)
74     {
75       char *name = NULL;
76       GElf_Shdr shdr;
77 
78       if (gelf_getshdr (scn, &shdr) != NULL)
79 	name = elf_strptr (elf, strndx, (size_t) shdr.sh_name);
80 
81       printf ("section: `%s'\n", name);
82     }
83 
84   if (elf_end (elf) != 0)
85     {
86       printf ("error while freeing ELF descriptor: %s\n", elf_errmsg (-1));
87       exit (1);
88     }
89 
90   return 0;
91 }
92