1/* Test program for dwarf_ranges
2   Copyright (C) 2015, 2018 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#include <config.h>
19#include ELFUTILS_HEADER(dw)
20#include <dwarf.h>
21#include <sys/types.h>
22#include <sys/stat.h>
23#include <fcntl.h>
24#include <stdio.h>
25#include <stdint.h>
26#include <stdlib.h>
27#include <assert.h>
28#include <inttypes.h>
29
30static void
31ranges_die (Dwarf_Die *die)
32{
33  Dwarf_Addr base, start, end;
34  int ranges = dwarf_ranges (die, 0, &base, &start, &end);
35  if (ranges < 0)
36    puts (dwarf_errmsg (-1));
37  else if (ranges > 0)
38    {
39      printf ("die: %s (%x)\n", dwarf_diename (die) ?: "<unknown>",
40	      dwarf_tag (die));
41      for (ptrdiff_t off = 0;
42	   (off = dwarf_ranges (die, off, &base, &start, &end)); )
43	if (off == -1)
44	  {
45	    puts (dwarf_errmsg (-1));
46	    break;
47	  }
48	else
49	  printf (" %"PRIx64"..%"PRIx64"\n", start, end);
50      printf ("\n");
51    }
52}
53
54static void
55walk_tree (Dwarf_Die *dwarf_die)
56{
57  Dwarf_Die die = *dwarf_die;
58  do
59    {
60      Dwarf_Die child;
61      ranges_die (&die);
62      if (dwarf_child (&die, &child) == 0)
63	walk_tree (&child);
64    }
65  while (dwarf_siblingof (&die, &die) == 0);
66}
67
68int
69main (int argc, char *argv[])
70{
71  assert (argc >= 2);
72  const char *name = argv[1];
73
74  int fd = open (name, O_RDONLY);
75  Dwarf *dbg = dwarf_begin (fd, DWARF_C_READ);
76
77  Dwarf_CU *cu = NULL;
78  Dwarf_Die cudie, subdie;
79  uint8_t unit_type;
80  while (dwarf_get_units (dbg, cu, &cu, NULL,
81			  &unit_type, &cudie, &subdie) == 0)
82    {
83      Dwarf_Die die = (unit_type == DW_UT_skeleton
84		       ? subdie : cudie);
85      walk_tree (&die);
86    }
87  dwarf_end (dbg);
88
89  return 0;
90}
91