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/DIContext.h"
13#include "llvm/DebugInfo/DWARF/DWARFAddressRange.h"
14#include "llvm/DebugInfo/DWARF/DWARFExpressionPrinter.h"
15#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
16#include "llvm/DebugInfo/DWARF/DWARFLocationExpression.h"
17#include "llvm/DebugInfo/DWARF/DWARFUnit.h"
18#include "llvm/DebugInfo/DWARF/LowLevel/DWARFExpression.h"
19#include "llvm/Support/Format.h"
20#include "llvm/Support/FormatAdapters.h"
21#include "llvm/Support/FormatVariadic.h"
22#include "llvm/Support/raw_ostream.h"
23#include <algorithm>
24#include <cinttypes>
25#include <cstdint>
26
27using namespace llvm;
28using object::SectionedAddress;
29
30namespace llvm {
31class DWARFObject;
32}
33
34namespace {
35class DWARFLocationInterpreter {
36 std::optional<object::SectionedAddress> Base;
37 std::function<std::optional<object::SectionedAddress>(uint32_t)> LookupAddr;
38
39public:
40 DWARFLocationInterpreter(
41 std::optional<object::SectionedAddress> Base,
42 std::function<std::optional<object::SectionedAddress>(uint32_t)>
43 LookupAddr)
44 : Base(Base), LookupAddr(std::move(LookupAddr)) {}
45
46 Expected<std::optional<DWARFLocationExpression>>
47 Interpret(const DWARFLocationEntry &E);
48};
49} // namespace
50
51static Error createResolverError(uint32_t Index, unsigned Kind) {
52 return make_error<ResolverError>(Args&: Index, Args: (dwarf::LoclistEntries)Kind);
53}
54
55Expected<std::optional<DWARFLocationExpression>>
56DWARFLocationInterpreter::Interpret(const DWARFLocationEntry &E) {
57 switch (E.Kind) {
58 case dwarf::DW_LLE_end_of_list:
59 return std::nullopt;
60 case dwarf::DW_LLE_base_addressx: {
61 Base = LookupAddr(E.Value0);
62 if (!Base)
63 return createResolverError(Index: E.Value0, Kind: E.Kind);
64 return std::nullopt;
65 }
66 case dwarf::DW_LLE_startx_endx: {
67 std::optional<SectionedAddress> LowPC = LookupAddr(E.Value0);
68 if (!LowPC)
69 return createResolverError(Index: E.Value0, Kind: E.Kind);
70 std::optional<SectionedAddress> HighPC = LookupAddr(E.Value1);
71 if (!HighPC)
72 return createResolverError(Index: E.Value1, Kind: E.Kind);
73 return DWARFLocationExpression{
74 .Range: DWARFAddressRange{LowPC->Address, HighPC->Address, LowPC->SectionIndex},
75 .Expr: E.Loc};
76 }
77 case dwarf::DW_LLE_startx_length: {
78 std::optional<SectionedAddress> LowPC = LookupAddr(E.Value0);
79 if (!LowPC)
80 return createResolverError(Index: E.Value0, Kind: E.Kind);
81 return DWARFLocationExpression{.Range: DWARFAddressRange{LowPC->Address,
82 LowPC->Address + E.Value1,
83 LowPC->SectionIndex},
84 .Expr: E.Loc};
85 }
86 case dwarf::DW_LLE_offset_pair: {
87 if (!Base) {
88 return createStringError(EC: inconvertibleErrorCode(),
89 S: "Unable to resolve location list offset pair: "
90 "Base address not defined");
91 }
92 DWARFAddressRange Range{Base->Address + E.Value0, Base->Address + E.Value1,
93 Base->SectionIndex};
94 if (Range.SectionIndex == SectionedAddress::UndefSection)
95 Range.SectionIndex = E.SectionIndex;
96 return DWARFLocationExpression{.Range: Range, .Expr: E.Loc};
97 }
98 case dwarf::DW_LLE_default_location:
99 return DWARFLocationExpression{.Range: std::nullopt, .Expr: E.Loc};
100 case dwarf::DW_LLE_base_address:
101 Base = SectionedAddress{.Address: E.Value0, .SectionIndex: E.SectionIndex};
102 return std::nullopt;
103 case dwarf::DW_LLE_start_end:
104 return DWARFLocationExpression{
105 .Range: DWARFAddressRange{E.Value0, E.Value1, E.SectionIndex}, .Expr: E.Loc};
106 case dwarf::DW_LLE_start_length:
107 return DWARFLocationExpression{
108 .Range: DWARFAddressRange{E.Value0, E.Value0 + E.Value1, E.SectionIndex},
109 .Expr: E.Loc};
110 default:
111 llvm_unreachable("unreachable locations list kind");
112 }
113}
114
115static void dumpExpression(raw_ostream &OS, DIDumpOptions DumpOpts,
116 ArrayRef<uint8_t> Data, bool IsLittleEndian,
117 unsigned AddressSize, DWARFUnit *U) {
118 DWARFDataExtractor Extractor(Data, IsLittleEndian, AddressSize);
119 std::optional<dwarf::DwarfFormat> Format;
120 if (U)
121 Format = U->getFormat();
122 DWARFExpression E(Extractor, AddressSize, Format);
123 printDwarfExpression(E: &E, OS, DumpOpts, U);
124}
125
126bool DWARFLocationTable::dumpLocationList(
127 uint64_t *Offset, raw_ostream &OS, std::optional<SectionedAddress> BaseAddr,
128 const DWARFObject &Obj, DWARFUnit *U, DIDumpOptions DumpOpts,
129 unsigned Indent) const {
130 DWARFLocationInterpreter Interp(
131 BaseAddr, [U](uint32_t Index) -> std::optional<SectionedAddress> {
132 if (U)
133 return U->getAddrOffsetSectionItem(Index);
134 return std::nullopt;
135 });
136 OS << formatv(Fmt: "{0:x+8}: ", Vals&: *Offset);
137 Error E = visitLocationList(Offset, Callback: [&](const DWARFLocationEntry &E) {
138 Expected<std::optional<DWARFLocationExpression>> Loc = Interp.Interpret(E);
139 if (!Loc || DumpOpts.DisplayRawContents)
140 dumpRawEntry(Entry: E, OS, Indent, DumpOpts, Obj);
141 if (Loc && *Loc) {
142 OS << "\n";
143 OS.indent(NumSpaces: Indent);
144 if (DumpOpts.DisplayRawContents)
145 OS << " => ";
146
147 DIDumpOptions RangeDumpOpts(DumpOpts);
148 RangeDumpOpts.DisplayRawContents = false;
149 if (Loc.get()->Range)
150 Loc.get()->Range->dump(OS, AddressSize: Data.getAddressSize(), DumpOpts: RangeDumpOpts, Obj: &Obj);
151 else
152 OS << "<default>";
153 }
154 if (!Loc)
155 consumeError(Err: Loc.takeError());
156
157 if (E.Kind != dwarf::DW_LLE_base_address &&
158 E.Kind != dwarf::DW_LLE_base_addressx &&
159 E.Kind != dwarf::DW_LLE_end_of_list) {
160 OS << ": ";
161 dumpExpression(OS, DumpOpts, Data: E.Loc, IsLittleEndian: Data.isLittleEndian(),
162 AddressSize: Data.getAddressSize(), U);
163 }
164 return true;
165 });
166 if (E) {
167 DumpOpts.RecoverableErrorHandler(std::move(E));
168 return false;
169 }
170 return true;
171}
172
173Error DWARFLocationTable::visitAbsoluteLocationList(
174 uint64_t Offset, std::optional<SectionedAddress> BaseAddr,
175 std::function<std::optional<SectionedAddress>(uint32_t)> LookupAddr,
176 function_ref<bool(Expected<DWARFLocationExpression>)> Callback) const {
177 DWARFLocationInterpreter Interp(BaseAddr, std::move(LookupAddr));
178 return visitLocationList(Offset: &Offset, Callback: [&](const DWARFLocationEntry &E) {
179 Expected<std::optional<DWARFLocationExpression>> Loc = Interp.Interpret(E);
180 if (!Loc)
181 return Callback(Loc.takeError());
182 if (*Loc)
183 return Callback(**Loc);
184 return true;
185 });
186}
187
188void DWARFDebugLoc::dump(raw_ostream &OS, const DWARFObject &Obj,
189 DIDumpOptions DumpOpts,
190 std::optional<uint64_t> DumpOffset) const {
191 auto BaseAddr = std::nullopt;
192 unsigned Indent = 12;
193 if (DumpOffset) {
194 dumpLocationList(Offset: &*DumpOffset, OS, BaseAddr, Obj, U: nullptr, DumpOpts,
195 Indent);
196 } else {
197 uint64_t Offset = 0;
198 StringRef Separator;
199 bool CanContinue = true;
200 while (CanContinue && Data.isValidOffset(offset: Offset)) {
201 OS << Separator;
202 Separator = "\n";
203
204 CanContinue = dumpLocationList(Offset: &Offset, OS, BaseAddr, Obj, U: nullptr,
205 DumpOpts, Indent);
206 OS << '\n';
207 }
208 }
209}
210
211Error DWARFDebugLoc::visitLocationList(
212 uint64_t *Offset,
213 function_ref<bool(const DWARFLocationEntry &)> Callback) const {
214 DataExtractor::Cursor C(*Offset);
215 while (true) {
216 uint64_t SectionIndex;
217 uint64_t Value0 = Data.getRelocatedAddress(C);
218 uint64_t Value1 = Data.getRelocatedAddress(C, SecIx: &SectionIndex);
219
220 DWARFLocationEntry E;
221
222 // The end of any given location list is marked by an end of list entry,
223 // which consists of a 0 for the beginning address offset and a 0 for the
224 // ending address offset. A beginning offset of 0xff...f marks the base
225 // address selection entry.
226 if (Value0 == 0 && Value1 == 0) {
227 E.Kind = dwarf::DW_LLE_end_of_list;
228 } else if (Value0 == (Data.getAddressSize() == 4 ? -1U : -1ULL)) {
229 E.Kind = dwarf::DW_LLE_base_address;
230 E.Value0 = Value1;
231 E.SectionIndex = SectionIndex;
232 } else {
233 E.Kind = dwarf::DW_LLE_offset_pair;
234 E.Value0 = Value0;
235 E.Value1 = Value1;
236 E.SectionIndex = SectionIndex;
237 unsigned Bytes = Data.getU16(C);
238 // A single location description describing the location of the object...
239 Data.getU8(C, Dst&: E.Loc, Count: Bytes);
240 }
241
242 if (!C)
243 return C.takeError();
244 if (!Callback(E) || E.Kind == dwarf::DW_LLE_end_of_list)
245 break;
246 }
247 *Offset = C.tell();
248 return Error::success();
249}
250
251void DWARFDebugLoc::dumpRawEntry(const DWARFLocationEntry &Entry,
252 raw_ostream &OS, unsigned Indent,
253 DIDumpOptions DumpOpts,
254 const DWARFObject &Obj) const {
255 uint64_t Value0, Value1;
256 switch (Entry.Kind) {
257 case dwarf::DW_LLE_base_address:
258 Value0 = Data.getAddressSize() == 4 ? -1U : -1ULL;
259 Value1 = Entry.Value0;
260 break;
261 case dwarf::DW_LLE_offset_pair:
262 Value0 = Entry.Value0;
263 Value1 = Entry.Value1;
264 break;
265 case dwarf::DW_LLE_end_of_list:
266 return;
267 default:
268 llvm_unreachable("Not possible in DWARF4!");
269 }
270 OS << '\n';
271 OS.indent(NumSpaces: Indent);
272 OS << '(' << format_hex(N: Value0, Width: 2 + Data.getAddressSize() * 2) << ", "
273 << format_hex(N: Value1, Width: 2 + Data.getAddressSize() * 2) << ')';
274 DWARFFormValue::dumpAddressSection(Obj, OS, DumpOpts, SectionIndex: Entry.SectionIndex);
275}
276
277Error DWARFDebugLoclists::visitLocationList(
278 uint64_t *Offset, function_ref<bool(const DWARFLocationEntry &)> F) const {
279
280 DataExtractor::Cursor C(*Offset);
281 bool Continue = true;
282 while (Continue) {
283 DWARFLocationEntry E;
284 E.Kind = Data.getU8(C);
285 switch (E.Kind) {
286 case dwarf::DW_LLE_end_of_list:
287 break;
288 case dwarf::DW_LLE_base_addressx:
289 E.Value0 = Data.getULEB128(C);
290 break;
291 case dwarf::DW_LLE_startx_endx:
292 E.Value0 = Data.getULEB128(C);
293 E.Value1 = Data.getULEB128(C);
294 break;
295 case dwarf::DW_LLE_startx_length:
296 E.Value0 = Data.getULEB128(C);
297 // Pre-DWARF 5 has different interpretation of the length field. We have
298 // to support both pre- and standartized styles for the compatibility.
299 if (Version < 5)
300 E.Value1 = Data.getU32(C);
301 else
302 E.Value1 = Data.getULEB128(C);
303 break;
304 case dwarf::DW_LLE_offset_pair:
305 E.Value0 = Data.getULEB128(C);
306 E.Value1 = Data.getULEB128(C);
307 E.SectionIndex = SectionedAddress::UndefSection;
308 break;
309 case dwarf::DW_LLE_default_location:
310 break;
311 case dwarf::DW_LLE_base_address:
312 E.Value0 = Data.getRelocatedAddress(C, SecIx: &E.SectionIndex);
313 break;
314 case dwarf::DW_LLE_start_end:
315 E.Value0 = Data.getRelocatedAddress(C, SecIx: &E.SectionIndex);
316 E.Value1 = Data.getRelocatedAddress(C);
317 break;
318 case dwarf::DW_LLE_start_length:
319 E.Value0 = Data.getRelocatedAddress(C, SecIx: &E.SectionIndex);
320 E.Value1 = Data.getULEB128(C);
321 break;
322 default:
323 cantFail(Err: C.takeError());
324 return createStringError(EC: errc::illegal_byte_sequence,
325 Fmt: "LLE of kind %x not supported", Vals: (int)E.Kind);
326 }
327
328 if (E.Kind != dwarf::DW_LLE_base_address &&
329 E.Kind != dwarf::DW_LLE_base_addressx &&
330 E.Kind != dwarf::DW_LLE_end_of_list) {
331 unsigned Bytes = Version >= 5 ? Data.getULEB128(C) : Data.getU16(C);
332 // A single location description describing the location of the object...
333 Data.getU8(C, Dst&: E.Loc, Count: Bytes);
334 }
335
336 if (!C)
337 return C.takeError();
338 Continue = F(E) && E.Kind != dwarf::DW_LLE_end_of_list;
339 }
340 *Offset = C.tell();
341 return Error::success();
342}
343
344void DWARFDebugLoclists::dumpRawEntry(const DWARFLocationEntry &Entry,
345 raw_ostream &OS, unsigned Indent,
346 DIDumpOptions DumpOpts,
347 const DWARFObject &Obj) const {
348 size_t MaxEncodingStringLength = 0;
349#define HANDLE_DW_LLE(ID, NAME) \
350 MaxEncodingStringLength = std::max(MaxEncodingStringLength, \
351 dwarf::LocListEncodingString(ID).size());
352#include "llvm/BinaryFormat/Dwarf.def"
353
354 OS << "\n";
355 OS.indent(NumSpaces: Indent);
356 StringRef EncodingString = dwarf::LocListEncodingString(Encoding: Entry.Kind);
357 // Unsupported encodings should have been reported during parsing.
358 assert(!EncodingString.empty() && "Unknown loclist entry encoding");
359 OS << formatv(Fmt: "{0}(", Vals: fmt_align(Item&: EncodingString, Where: AlignStyle::Left,
360 Amount: MaxEncodingStringLength));
361 unsigned FieldSize = 2 + 2 * Data.getAddressSize();
362 switch (Entry.Kind) {
363 case dwarf::DW_LLE_end_of_list:
364 case dwarf::DW_LLE_default_location:
365 break;
366 case dwarf::DW_LLE_startx_endx:
367 case dwarf::DW_LLE_startx_length:
368 case dwarf::DW_LLE_offset_pair:
369 case dwarf::DW_LLE_start_end:
370 case dwarf::DW_LLE_start_length:
371 OS << format_hex(N: Entry.Value0, Width: FieldSize) << ", "
372 << format_hex(N: Entry.Value1, Width: FieldSize);
373 break;
374 case dwarf::DW_LLE_base_addressx:
375 case dwarf::DW_LLE_base_address:
376 OS << format_hex(N: Entry.Value0, Width: FieldSize);
377 break;
378 }
379 OS << ')';
380 switch (Entry.Kind) {
381 case dwarf::DW_LLE_base_address:
382 case dwarf::DW_LLE_start_end:
383 case dwarf::DW_LLE_start_length:
384 DWARFFormValue::dumpAddressSection(Obj, OS, DumpOpts, SectionIndex: Entry.SectionIndex);
385 break;
386 default:
387 break;
388 }
389}
390
391void DWARFDebugLoclists::dumpRange(uint64_t StartOffset, uint64_t Size,
392 raw_ostream &OS, const DWARFObject &Obj,
393 DIDumpOptions DumpOpts) {
394 if (!Data.isValidOffsetForDataOfSize(offset: StartOffset, length: Size)) {
395 OS << "Invalid dump range\n";
396 return;
397 }
398 uint64_t Offset = StartOffset;
399 StringRef Separator;
400 bool CanContinue = true;
401 while (CanContinue && Offset < StartOffset + Size) {
402 OS << Separator;
403 Separator = "\n";
404
405 CanContinue = dumpLocationList(Offset: &Offset, OS, /*BaseAddr=*/std::nullopt, Obj,
406 U: nullptr, DumpOpts, /*Indent=*/12);
407 OS << '\n';
408 }
409}
410
411void llvm::ResolverError::log(raw_ostream &OS) const {
412 OS << formatv(Fmt: "unable to resolve indirect address {0} for: {1}", Vals: Index,
413 Vals: dwarf::LocListEncodingString(Encoding: Kind).data());
414}
415
416char llvm::ResolverError::ID;
417