1 //===- DWARFDebugLoc.cpp --------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/DebugInfo/DWARF/DWARFDebugLoc.h"
10 #include "llvm/ADT/StringRef.h"
11 #include "llvm/BinaryFormat/Dwarf.h"
12 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
13 #include "llvm/DebugInfo/DWARF/DWARFExpression.h"
14 #include "llvm/DebugInfo/DWARF/DWARFRelocMap.h"
15 #include "llvm/DebugInfo/DWARF/DWARFUnit.h"
16 #include "llvm/Support/Compiler.h"
17 #include "llvm/Support/Format.h"
18 #include "llvm/Support/WithColor.h"
19 #include "llvm/Support/raw_ostream.h"
20 #include <algorithm>
21 #include <cinttypes>
22 #include <cstdint>
23 
24 using namespace llvm;
25 using object::SectionedAddress;
26 
27 namespace {
28 class DWARFLocationInterpreter {
29   Optional<object::SectionedAddress> Base;
30   std::function<Optional<object::SectionedAddress>(uint32_t)> LookupAddr;
31 
32 public:
33   DWARFLocationInterpreter(
34       Optional<object::SectionedAddress> Base,
35       std::function<Optional<object::SectionedAddress>(uint32_t)> LookupAddr)
36       : Base(Base), LookupAddr(std::move(LookupAddr)) {}
37 
38   Expected<Optional<DWARFLocationExpression>>
39   Interpret(const DWARFLocationEntry &E);
40 };
41 } // namespace
42 
43 static Error createResolverError(uint32_t Index, unsigned Kind) {
44   return createStringError(errc::invalid_argument,
45                            "Unable to resolve indirect address %u for: %s",
46                            Index, dwarf::LocListEncodingString(Kind).data());
47 }
48 
49 Expected<Optional<DWARFLocationExpression>>
50 DWARFLocationInterpreter::Interpret(const DWARFLocationEntry &E) {
51   switch (E.Kind) {
52   case dwarf::DW_LLE_end_of_list:
53     return None;
54   case dwarf::DW_LLE_base_addressx: {
55     Base = LookupAddr(E.Value0);
56     if (!Base)
57       return createResolverError(E.Value0, E.Kind);
58     return None;
59   }
60   case dwarf::DW_LLE_startx_length: {
61     Optional<SectionedAddress> LowPC = LookupAddr(E.Value0);
62     if (!LowPC)
63       return createResolverError(E.Value0, E.Kind);
64     return DWARFLocationExpression{DWARFAddressRange{LowPC->Address,
65                                                      LowPC->Address + E.Value1,
66                                                      LowPC->SectionIndex},
67                                    E.Loc};
68   }
69   case dwarf::DW_LLE_offset_pair:
70     if (!Base) {
71       return createStringError(
72           inconvertibleErrorCode(),
73           "Unable to resolve DW_LLE_offset_pair: base address unknown");
74     }
75     return DWARFLocationExpression{DWARFAddressRange{Base->Address + E.Value0,
76                                                      Base->Address + E.Value1,
77                                                      Base->SectionIndex},
78                                    E.Loc};
79   case dwarf::DW_LLE_base_address:
80     Base = SectionedAddress{E.Value0, SectionedAddress::UndefSection};
81     return None;
82   case dwarf::DW_LLE_start_length:
83     return DWARFLocationExpression{
84         DWARFAddressRange{E.Value0, E.Value0 + E.Value1,
85                           SectionedAddress::UndefSection},
86         E.Loc};
87   default:
88     llvm_unreachable("unreachable locations list kind");
89   }
90 }
91 
92 // When directly dumping the .debug_loc without a compile unit, we have to guess
93 // at the DWARF version. This only affects DW_OP_call_ref, which is a rare
94 // expression that LLVM doesn't produce. Guessing the wrong version means we
95 // won't be able to pretty print expressions in DWARF2 binaries produced by
96 // non-LLVM tools.
97 static void dumpExpression(raw_ostream &OS, ArrayRef<uint8_t> Data,
98                            bool IsLittleEndian, unsigned AddressSize,
99                            const MCRegisterInfo *MRI, DWARFUnit *U) {
100   DWARFDataExtractor Extractor(toStringRef(Data), IsLittleEndian, AddressSize);
101   DWARFExpression(Extractor, dwarf::DWARF_VERSION, AddressSize).print(OS, MRI, U);
102 }
103 
104 bool DWARFLocationTable::dumpLocationList(uint64_t *Offset, raw_ostream &OS,
105                                           Optional<SectionedAddress> BaseAddr,
106                                           const MCRegisterInfo *MRI,
107                                           DWARFUnit *U, DIDumpOptions DumpOpts,
108                                           unsigned Indent) const {
109   DWARFLocationInterpreter Interp(
110       BaseAddr, [U](uint32_t Index) -> Optional<SectionedAddress> {
111         if (U)
112           return U->getAddrOffsetSectionItem(Index);
113         return None;
114       });
115   OS << format("0x%8.8" PRIx64 ": ", *Offset);
116   Error E = visitLocationList(Offset, [&](const DWARFLocationEntry &E) {
117     Expected<Optional<DWARFLocationExpression>> Loc = Interp.Interpret(E);
118     if (!Loc || DumpOpts.DisplayRawContents)
119       dumpRawEntry(E, OS, Indent);
120     if (Loc && *Loc) {
121       OS << "\n";
122       OS.indent(Indent);
123       if (DumpOpts.DisplayRawContents)
124         OS << "          => ";
125 
126       DIDumpOptions RangeDumpOpts(DumpOpts);
127       RangeDumpOpts.DisplayRawContents = false;
128       const DWARFObject *Obj = nullptr;
129       if (U)
130         Obj = &U->getContext().getDWARFObj();
131       Loc.get()->Range->dump(OS, Data.getAddressSize(), RangeDumpOpts, Obj);
132     }
133     if (!Loc)
134       consumeError(Loc.takeError());
135 
136     if (E.Kind != dwarf::DW_LLE_base_address &&
137         E.Kind != dwarf::DW_LLE_base_addressx &&
138         E.Kind != dwarf::DW_LLE_end_of_list) {
139       OS << ": ";
140       dumpExpression(OS, E.Loc, Data.isLittleEndian(), Data.getAddressSize(),
141                      MRI, U);
142     }
143     return true;
144   });
145   if (E) {
146     OS << "\n";
147     OS.indent(Indent);
148     OS << "error: " << toString(std::move(E));
149     return false;
150   }
151   return true;
152 }
153 
154 Error DWARFLocationTable::visitAbsoluteLocationList(
155     uint64_t Offset, Optional<SectionedAddress> BaseAddr,
156     std::function<Optional<SectionedAddress>(uint32_t)> LookupAddr,
157     function_ref<bool(Expected<DWARFLocationExpression>)> Callback) const {
158   DWARFLocationInterpreter Interp(BaseAddr, std::move(LookupAddr));
159   return visitLocationList(&Offset, [&](const DWARFLocationEntry &E) {
160     Expected<Optional<DWARFLocationExpression>> Loc = Interp.Interpret(E);
161     if (!Loc)
162       return Callback(Loc.takeError());
163     if (*Loc)
164       return Callback(**Loc);
165     return true;
166   });
167 }
168 
169 void DWARFDebugLoc::dump(raw_ostream &OS, const MCRegisterInfo *MRI,
170                          DIDumpOptions DumpOpts,
171                          Optional<uint64_t> DumpOffset) const {
172   auto BaseAddr = None;
173   unsigned Indent = 12;
174   if (DumpOffset) {
175     dumpLocationList(&*DumpOffset, OS, BaseAddr, MRI, nullptr, DumpOpts,
176                      Indent);
177   } else {
178     uint64_t Offset = 0;
179     StringRef Separator;
180     bool CanContinue = true;
181     while (CanContinue && Data.isValidOffset(Offset)) {
182       OS << Separator;
183       Separator = "\n";
184 
185       CanContinue = dumpLocationList(&Offset, OS, BaseAddr, MRI, nullptr,
186                                      DumpOpts, Indent);
187       OS << '\n';
188     }
189   }
190 }
191 
192 Error DWARFDebugLoc::visitLocationList(
193     uint64_t *Offset,
194     function_ref<bool(const DWARFLocationEntry &)> Callback) const {
195   DataExtractor::Cursor C(*Offset);
196   while (true) {
197     uint64_t Value0 = Data.getRelocatedAddress(C);
198     uint64_t Value1 = Data.getRelocatedAddress(C);
199 
200     DWARFLocationEntry E;
201 
202     // The end of any given location list is marked by an end of list entry,
203     // which consists of a 0 for the beginning address offset and a 0 for the
204     // ending address offset. A beginning offset of 0xff...f marks the base
205     // address selection entry.
206     if (Value0 == 0 && Value1 == 0) {
207       E.Kind = dwarf::DW_LLE_end_of_list;
208     } else if (Value0 == (Data.getAddressSize() == 4 ? -1U : -1ULL)) {
209       E.Kind = dwarf::DW_LLE_base_address;
210       E.Value0 = Value1;
211     } else {
212       E.Kind = dwarf::DW_LLE_offset_pair;
213       E.Value0 = Value0;
214       E.Value1 = Value1;
215       unsigned Bytes = Data.getU16(C);
216       // A single location description describing the location of the object...
217       Data.getU8(C, E.Loc, Bytes);
218     }
219 
220     if (!C)
221       return C.takeError();
222     if (!Callback(E) || E.Kind == dwarf::DW_LLE_end_of_list)
223       break;
224   }
225   *Offset = C.tell();
226   return Error::success();
227 }
228 
229 void DWARFDebugLoc::dumpRawEntry(const DWARFLocationEntry &Entry,
230                                  raw_ostream &OS, unsigned Indent) const {
231   uint64_t Value0, Value1;
232   switch (Entry.Kind) {
233   case dwarf::DW_LLE_base_address:
234     Value0 = Data.getAddressSize() == 4 ? -1U : -1ULL;
235     Value1 = Entry.Value0;
236     break;
237   case dwarf::DW_LLE_offset_pair:
238     Value0 = Entry.Value0;
239     Value1 = Entry.Value1;
240     break;
241   case dwarf::DW_LLE_end_of_list:
242     Value0 = Value1 = 0;
243     return;
244   default:
245     llvm_unreachable("Not possible in DWARF4!");
246   }
247   OS << '\n';
248   OS.indent(Indent);
249   OS << '(' << format_hex(Value0, 2 + Data.getAddressSize() * 2) << ", "
250      << format_hex(Value1, 2 + Data.getAddressSize() * 2) << ')';
251 }
252 
253 Error DWARFDebugLoclists::visitLocationList(
254     uint64_t *Offset, function_ref<bool(const DWARFLocationEntry &)> F) const {
255 
256   DataExtractor::Cursor C(*Offset);
257   bool Continue = true;
258   while (Continue) {
259     DWARFLocationEntry E;
260     E.Kind = Data.getU8(C);
261     switch (E.Kind) {
262     case dwarf::DW_LLE_end_of_list:
263       break;
264     case dwarf::DW_LLE_base_addressx:
265       E.Value0 = Data.getULEB128(C);
266       break;
267     case dwarf::DW_LLE_startx_length:
268       E.Value0 = Data.getULEB128(C);
269       // Pre-DWARF 5 has different interpretation of the length field. We have
270       // to support both pre- and standartized styles for the compatibility.
271       if (Version < 5)
272         E.Value1 = Data.getU32(C);
273       else
274         E.Value1 = Data.getULEB128(C);
275       break;
276     case dwarf::DW_LLE_offset_pair:
277       E.Value0 = Data.getULEB128(C);
278       E.Value1 = Data.getULEB128(C);
279       break;
280     case dwarf::DW_LLE_base_address:
281       E.Value0 = Data.getRelocatedAddress(C);
282       break;
283     case dwarf::DW_LLE_start_length:
284       E.Value0 = Data.getRelocatedAddress(C);
285       E.Value1 = Data.getULEB128(C);
286       break;
287     case dwarf::DW_LLE_startx_endx:
288     case dwarf::DW_LLE_default_location:
289     case dwarf::DW_LLE_start_end:
290     default:
291       cantFail(C.takeError());
292       return createStringError(errc::illegal_byte_sequence,
293                                "LLE of kind %x not supported", (int)E.Kind);
294     }
295 
296     if (E.Kind != dwarf::DW_LLE_base_address &&
297         E.Kind != dwarf::DW_LLE_base_addressx &&
298         E.Kind != dwarf::DW_LLE_end_of_list) {
299       unsigned Bytes = Version >= 5 ? Data.getULEB128(C) : Data.getU16(C);
300       // A single location description describing the location of the object...
301       Data.getU8(C, E.Loc, Bytes);
302     }
303 
304     if (!C)
305       return C.takeError();
306     Continue = F(E) && E.Kind != dwarf::DW_LLE_end_of_list;
307   }
308   *Offset = C.tell();
309   return Error::success();
310 }
311 
312 void DWARFDebugLoclists::dumpRawEntry(const DWARFLocationEntry &Entry,
313                                       raw_ostream &OS, unsigned Indent) const {
314   size_t MaxEncodingStringLength = 0;
315 #define HANDLE_DW_LLE(ID, NAME)                                                \
316   MaxEncodingStringLength = std::max(MaxEncodingStringLength,                  \
317                                      dwarf::LocListEncodingString(ID).size());
318 #include "llvm/BinaryFormat/Dwarf.def"
319 
320   OS << "\n";
321   OS.indent(Indent);
322   StringRef EncodingString = dwarf::LocListEncodingString(Entry.Kind);
323   // Unsupported encodings should have been reported during parsing.
324   assert(!EncodingString.empty() && "Unknown loclist entry encoding");
325   OS << format("%-*s(", MaxEncodingStringLength, EncodingString.data());
326   unsigned FieldSize = 2 + 2 * Data.getAddressSize();
327   switch (Entry.Kind) {
328   case dwarf::DW_LLE_startx_length:
329   case dwarf::DW_LLE_start_length:
330   case dwarf::DW_LLE_offset_pair:
331     OS << format_hex(Entry.Value0, FieldSize) << ", "
332        << format_hex(Entry.Value1, FieldSize);
333     break;
334   case dwarf::DW_LLE_base_addressx:
335   case dwarf::DW_LLE_base_address:
336     OS << format_hex(Entry.Value0, FieldSize);
337     break;
338   case dwarf::DW_LLE_end_of_list:
339     break;
340   }
341   OS << ')';
342 }
343 
344 void DWARFDebugLoclists::dumpRange(uint64_t StartOffset, uint64_t Size,
345                                    raw_ostream &OS, const MCRegisterInfo *MRI,
346                                    DIDumpOptions DumpOpts) {
347   if (!Data.isValidOffsetForDataOfSize(StartOffset, Size))  {
348     OS << "Invalid dump range\n";
349     return;
350   }
351   uint64_t Offset = StartOffset;
352   StringRef Separator;
353   bool CanContinue = true;
354   while (CanContinue && Offset < StartOffset + Size) {
355     OS << Separator;
356     Separator = "\n";
357 
358     CanContinue = dumpLocationList(&Offset, OS, /*BaseAddr=*/None, MRI, nullptr,
359                                    DumpOpts, /*Indent=*/12);
360     OS << '\n';
361   }
362 }
363