blob: af7af524ebe232217b01a63e77417366a39782de [file] [log] [blame]
Brad Bishop316dfdd2018-06-25 12:45:53 -04001// dwarfsrcfiles.c - Get source files associated with the dwarf in a elf file.
2// gcc -Wall -g -O2 -lelf -ldw -o dwarfsrcfiles dwarfsrcfiles.c
3//
4// Copyright (C) 2011, Mark Wielaard <mjw@redhat.com>
5//
6// This file is free software. You can redistribute it and/or modify
7// it under the terms of the GNU General Public License (GPL); either
8// version 2, or (at your option) any later version.
9
10#include <argp.h>
11#include <stdio.h>
12
13#include <dwarf.h>
14#include <elfutils/libdw.h>
15#include <elfutils/libdwfl.h>
16
17static int
18process_cu (Dwarf_Die *cu_die)
19{
20 Dwarf_Attribute attr;
21 const char *name;
22 const char *dir = NULL;
23
24 Dwarf_Files *files;
25 size_t n;
26 int i;
27
28 if (dwarf_tag (cu_die) != DW_TAG_compile_unit)
29 {
30 fprintf (stderr, "DIE isn't a compile unit");
31 return -1;
32 }
33
34 if (dwarf_attr (cu_die, DW_AT_name, &attr) == NULL)
35 {
36 fprintf(stderr, "CU doesn't have a DW_AT_name");
37 return -1;
38 }
39
40 name = dwarf_formstring (&attr);
41 if (name == NULL)
42 {
43 fprintf(stderr, "Couldn't get DW_AT_name as string, %s",
44 dwarf_errmsg (-1));
45 return -1;
46 }
47
48 if (dwarf_attr (cu_die, DW_AT_comp_dir, &attr) != NULL)
49 {
50 dir = dwarf_formstring (&attr);
51 if (dir == NULL)
52 {
53 fprintf(stderr, "Couldn't get DW_AT_comp_die as string, %s",
54 dwarf_errmsg (-1));
55 return -1;
56 }
57 }
58
59 if (dir == NULL)
60 printf ("%s\n", name);
61 else
62 printf ("%s/%s\n", dir, name);
63
64 if (dwarf_getsrcfiles (cu_die, &files, &n) != 0)
65 {
66 fprintf(stderr, "Couldn't get CU file table, %s",
67 dwarf_errmsg (-1));
68 return -1;
69 }
70
71 for (i = 1; i < n; i++)
72 {
73 const char *file = dwarf_filesrc (files, i, NULL, NULL);
74 if (dir != NULL && file[0] != '/')
75 printf ("\t%s/%s\n", dir, file);
76 else
77 printf ("\t%s\n", file);
78 }
79
80 return 0;
81}
82
83int
84main (int argc, char **argv)
85{
86 char* args[3];
87 int res = 0;
88 Dwfl *dwfl;
89 Dwarf_Addr bias;
90
91 if (argc != 2)
92 fprintf(stderr, "Usage %s <file>", argv[0]);
93
94 // Pretend "dwarfsrcfiles -e <file>" was given, so we can use standard
95 // dwfl argp parser to open the file for us and get our Dwfl. Useful
96 // in case argument is an ET_REL file (like kernel modules). libdwfl
97 // will fix up relocations for us.
98 args[0] = argv[0];
99 args[1] = "-e";
100 args[2] = argv[1];
101
102 argp_parse (dwfl_standard_argp (), 3, args, 0, NULL, &dwfl);
103
104 Dwarf_Die *cu = NULL;
105 while ((cu = dwfl_nextcu (dwfl, cu, &bias)) != NULL)
106 res |= process_cu (cu);
107
108 dwfl_end (dwfl);
109
110 return res;
111}