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