Imported Upstream version 0.155
[platform/upstream/elfutils.git] / libdw / dwarf_getsrc_die.c
1 /* Find line information for address.
2    Copyright (C) 2004, 2005 Red Hat, Inc.
3    This file is part of elfutils.
4    Written by Ulrich Drepper <drepper@redhat.com>, 2004.
5
6    This file is free software; you can redistribute it and/or modify
7    it under the terms of either
8
9      * the GNU Lesser General Public License as published by the Free
10        Software Foundation; either version 3 of the License, or (at
11        your option) any later version
12
13    or
14
15      * the GNU General Public License as published by the Free
16        Software Foundation; either version 2 of the License, or (at
17        your option) any later version
18
19    or both in parallel, as here.
20
21    elfutils is distributed in the hope that it will be useful, but
22    WITHOUT ANY WARRANTY; without even the implied warranty of
23    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
24    General Public License for more details.
25
26    You should have received copies of the GNU General Public License and
27    the GNU Lesser General Public License along with this program.  If
28    not, see <http://www.gnu.org/licenses/>.  */
29
30 #ifdef HAVE_CONFIG_H
31 # include <config.h>
32 #endif
33
34 #include "libdwP.h"
35 #include <assert.h>
36
37
38 Dwarf_Line *
39 dwarf_getsrc_die (Dwarf_Die *cudie, Dwarf_Addr addr)
40 {
41   Dwarf_Lines *lines;
42   size_t nlines;
43
44   if (INTUSE(dwarf_getsrclines) (cudie, &lines, &nlines) != 0)
45     return NULL;
46
47   /* The lines are sorted by address, so we can use binary search.  */
48   size_t l = 0, u = nlines;
49   while (l < u)
50     {
51       size_t idx = (l + u) / 2;
52       if (addr < lines->info[idx].addr)
53         u = idx;
54       else if (addr > lines->info[idx].addr || lines->info[idx].end_sequence)
55         l = idx + 1;
56       else
57         return &lines->info[idx];
58     }
59
60   if (nlines > 0)
61     assert (lines->info[nlines - 1].end_sequence);
62
63   /* If none were equal, the closest one below is what we want.  We
64      never want the last one, because it's the end-sequence marker
65      with an address at the high bound of the CU's code.  If the debug
66      information is faulty and no end-sequence marker is present, we
67      still ignore it.  */
68   if (u > 0 && u < nlines && addr > lines->info[u - 1].addr)
69     {
70       while (lines->info[u - 1].end_sequence && u > 0)
71         --u;
72       if (u > 0)
73         return &lines->info[u - 1];
74     }
75
76   __libdw_seterrno (DWARF_E_ADDR_OUTOFRANGE);
77   return NULL;
78 }