1//===- DWARFContext.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/DWARFContext.h"
10#include "llvm/ADT/MapVector.h"
11#include "llvm/ADT/STLExtras.h"
12#include "llvm/ADT/SmallString.h"
13#include "llvm/ADT/SmallVector.h"
14#include "llvm/ADT/StringRef.h"
15#include "llvm/ADT/StringSwitch.h"
16#include "llvm/BinaryFormat/Dwarf.h"
17#include "llvm/DebugInfo/DWARF/DWARFAcceleratorTable.h"
18#include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h"
19#include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h"
20#include "llvm/DebugInfo/DWARF/DWARFDebugAbbrev.h"
21#include "llvm/DebugInfo/DWARF/DWARFDebugAddr.h"
22#include "llvm/DebugInfo/DWARF/DWARFDebugArangeSet.h"
23#include "llvm/DebugInfo/DWARF/DWARFDebugAranges.h"
24#include "llvm/DebugInfo/DWARF/DWARFDebugFrame.h"
25#include "llvm/DebugInfo/DWARF/DWARFDebugLine.h"
26#include "llvm/DebugInfo/DWARF/DWARFDebugLoc.h"
27#include "llvm/DebugInfo/DWARF/DWARFDebugMacro.h"
28#include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h"
29#include "llvm/DebugInfo/DWARF/DWARFDebugRangeList.h"
30#include "llvm/DebugInfo/DWARF/DWARFDebugRnglists.h"
31#include "llvm/DebugInfo/DWARF/DWARFDie.h"
32#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
33#include "llvm/DebugInfo/DWARF/DWARFGdbIndex.h"
34#include "llvm/DebugInfo/DWARF/DWARFListTable.h"
35#include "llvm/DebugInfo/DWARF/DWARFLocationExpression.h"
36#include "llvm/DebugInfo/DWARF/DWARFRelocMap.h"
37#include "llvm/DebugInfo/DWARF/DWARFSection.h"
38#include "llvm/DebugInfo/DWARF/DWARFTypeUnit.h"
39#include "llvm/DebugInfo/DWARF/DWARFUnitIndex.h"
40#include "llvm/DebugInfo/DWARF/DWARFVerifier.h"
41#include "llvm/MC/TargetRegistry.h"
42#include "llvm/Object/Decompressor.h"
43#include "llvm/Object/MachO.h"
44#include "llvm/Object/ObjectFile.h"
45#include "llvm/Object/RelocationResolver.h"
46#include "llvm/Support/Casting.h"
47#include "llvm/Support/DataExtractor.h"
48#include "llvm/Support/Error.h"
49#include "llvm/Support/Format.h"
50#include "llvm/Support/FormatAdapters.h"
51#include "llvm/Support/FormatVariadic.h"
52#include "llvm/Support/LEB128.h"
53#include "llvm/Support/MemoryBuffer.h"
54#include "llvm/Support/Path.h"
55#include "llvm/Support/raw_ostream.h"
56#include <cstdint>
57#include <deque>
58#include <map>
59#include <string>
60#include <utility>
61#include <vector>
62
63using namespace llvm;
64using namespace dwarf;
65using namespace object;
66
67#define DEBUG_TYPE "dwarf"
68
69using DWARFLineTable = DWARFDebugLine::LineTable;
70using FileLineInfoKind = DILineInfoSpecifier::FileLineInfoKind;
71using FunctionNameKind = DILineInfoSpecifier::FunctionNameKind;
72
73
74void fixupIndexV4(DWARFContext &C, DWARFUnitIndex &Index) {
75 using EntryType = DWARFUnitIndex::Entry::SectionContribution;
76 using EntryMap = DenseMap<uint32_t, EntryType>;
77 EntryMap Map;
78 const auto &DObj = C.getDWARFObj();
79 if (DObj.getCUIndexSection().empty())
80 return;
81
82 uint64_t Offset = 0;
83 uint32_t TruncOffset = 0;
84 DObj.forEachInfoDWOSections(F: [&](const DWARFSection &S) {
85 if (!(C.getParseCUTUIndexManually() ||
86 S.Data.size() >= std::numeric_limits<uint32_t>::max()))
87 return;
88
89 DWARFDataExtractor Data(DObj, S, C.isLittleEndian(), 0);
90 while (Data.isValidOffset(offset: Offset)) {
91 DWARFUnitHeader Header;
92 if (Error ExtractionErr = Header.extract(
93 Context&: C, debug_info: Data, offset_ptr: &Offset, SectionKind: DWARFSectionKind::DW_SECT_INFO)) {
94 C.getWarningHandler()(
95 createError(Err: "Failed to parse CU header in DWP file: " +
96 toString(E: std::move(ExtractionErr))));
97 Map.clear();
98 break;
99 }
100
101 auto Iter = Map.insert(KV: {TruncOffset,
102 {Header.getOffset(), Header.getNextUnitOffset() -
103 Header.getOffset()}});
104 if (!Iter.second) {
105 logAllUnhandledErrors(
106 E: createError(Err: "Collision occurred between for truncated offset 0x" +
107 Twine::utohexstr(Val: TruncOffset)),
108 OS&: errs());
109 Map.clear();
110 return;
111 }
112
113 Offset = Header.getNextUnitOffset();
114 TruncOffset = Offset;
115 }
116 });
117
118 if (Map.empty())
119 return;
120
121 for (DWARFUnitIndex::Entry &E : Index.getMutableRows()) {
122 if (!E.isValid())
123 continue;
124 DWARFUnitIndex::Entry::SectionContribution &CUOff = E.getContribution();
125 auto Iter = Map.find(Val: CUOff.getOffset());
126 if (Iter == Map.end()) {
127 logAllUnhandledErrors(E: createError(Err: "Could not find CU offset 0x" +
128 Twine::utohexstr(Val: CUOff.getOffset()) +
129 " in the Map"),
130 OS&: errs());
131 break;
132 }
133 CUOff.setOffset(Iter->second.getOffset());
134 if (CUOff.getOffset() != Iter->second.getOffset())
135 logAllUnhandledErrors(E: createError(Err: "Length of CU in CU index doesn't "
136 "match calculated length at offset 0x" +
137 Twine::utohexstr(Val: CUOff.getOffset())),
138 OS&: errs());
139 }
140}
141
142void fixupIndexV5(DWARFContext &C, DWARFUnitIndex &Index) {
143 DenseMap<uint64_t, uint64_t> Map;
144
145 const auto &DObj = C.getDWARFObj();
146 DObj.forEachInfoDWOSections(F: [&](const DWARFSection &S) {
147 if (!(C.getParseCUTUIndexManually() ||
148 S.Data.size() >= std::numeric_limits<uint32_t>::max()))
149 return;
150 DWARFDataExtractor Data(DObj, S, C.isLittleEndian(), 0);
151 uint64_t Offset = 0;
152 while (Data.isValidOffset(offset: Offset)) {
153 DWARFUnitHeader Header;
154 if (Error ExtractionErr = Header.extract(
155 Context&: C, debug_info: Data, offset_ptr: &Offset, SectionKind: DWARFSectionKind::DW_SECT_INFO)) {
156 C.getWarningHandler()(
157 createError(Err: "Failed to parse CU header in DWP file: " +
158 toString(E: std::move(ExtractionErr))));
159 break;
160 }
161 bool CU = Header.getUnitType() == DW_UT_split_compile;
162 uint64_t Sig = CU ? *Header.getDWOId() : Header.getTypeHash();
163 Map[Sig] = Header.getOffset();
164 Offset = Header.getNextUnitOffset();
165 }
166 });
167 if (Map.empty())
168 return;
169 for (DWARFUnitIndex::Entry &E : Index.getMutableRows()) {
170 if (!E.isValid())
171 continue;
172 DWARFUnitIndex::Entry::SectionContribution &CUOff = E.getContribution();
173 auto Iter = Map.find(Val: E.getSignature());
174 if (Iter == Map.end()) {
175 logAllUnhandledErrors(
176 E: createError(Err: "Could not find unit with signature 0x" +
177 Twine::utohexstr(Val: E.getSignature()) + " in the Map"),
178 OS&: errs());
179 break;
180 }
181 CUOff.setOffset(Iter->second);
182 }
183}
184
185void fixupIndex(DWARFContext &C, DWARFUnitIndex &Index) {
186 if (Index.getVersion() < 5)
187 fixupIndexV4(C, Index);
188 else
189 fixupIndexV5(C, Index);
190}
191
192template <typename T>
193static T &getAccelTable(std::unique_ptr<T> &Cache, const DWARFObject &Obj,
194 const DWARFSection &Section, StringRef StringSection,
195 bool IsLittleEndian) {
196 if (Cache)
197 return *Cache;
198 DWARFDataExtractor AccelSection(Obj, Section, IsLittleEndian, 0);
199 DataExtractor StrData(StringSection, IsLittleEndian);
200 Cache = std::make_unique<T>(AccelSection, StrData);
201 if (Error E = Cache->extract())
202 llvm::consumeError(Err: std::move(E));
203 return *Cache;
204}
205
206
207std::unique_ptr<DWARFDebugMacro>
208DWARFContext::DWARFContextState::parseMacroOrMacinfo(MacroSecType SectionType) {
209 auto Macro = std::make_unique<DWARFDebugMacro>();
210 auto ParseAndDump = [&](DWARFDataExtractor &Data, bool IsMacro) {
211 if (Error Err = IsMacro ? Macro->parseMacro(Units: SectionType == MacroSection
212 ? D.compile_units()
213 : D.dwo_compile_units(),
214 StringExtractor: SectionType == MacroSection
215 ? D.getStringExtractor()
216 : D.getStringDWOExtractor(),
217 MacroData: Data)
218 : Macro->parseMacinfo(MacroData: Data)) {
219 D.getRecoverableErrorHandler()(std::move(Err));
220 Macro = nullptr;
221 }
222 };
223 const DWARFObject &DObj = D.getDWARFObj();
224 switch (SectionType) {
225 case MacinfoSection: {
226 DWARFDataExtractor Data(DObj.getMacinfoSection(), D.isLittleEndian(), 0);
227 ParseAndDump(Data, /*IsMacro=*/false);
228 break;
229 }
230 case MacinfoDwoSection: {
231 DWARFDataExtractor Data(DObj.getMacinfoDWOSection(), D.isLittleEndian(), 0);
232 ParseAndDump(Data, /*IsMacro=*/false);
233 break;
234 }
235 case MacroSection: {
236 DWARFDataExtractor Data(DObj, DObj.getMacroSection(), D.isLittleEndian(),
237 0);
238 ParseAndDump(Data, /*IsMacro=*/true);
239 break;
240 }
241 case MacroDwoSection: {
242 DWARFDataExtractor Data(DObj.getMacroDWOSection(), D.isLittleEndian(), 0);
243 ParseAndDump(Data, /*IsMacro=*/true);
244 break;
245 }
246 }
247 return Macro;
248}
249
250namespace {
251class ThreadUnsafeDWARFContextState : public DWARFContext::DWARFContextState {
252
253 DWARFUnitVector NormalUnits;
254 std::optional<DenseMap<uint64_t, DWARFTypeUnit *>> NormalTypeUnits;
255 std::unique_ptr<DWARFUnitIndex> CUIndex;
256 std::unique_ptr<DWARFGdbIndex> GdbIndex;
257 std::unique_ptr<DWARFUnitIndex> TUIndex;
258 std::unique_ptr<DWARFDebugAbbrev> Abbrev;
259 std::unique_ptr<DWARFDebugLoc> Loc;
260 std::unique_ptr<DWARFDebugAranges> Aranges;
261 std::unique_ptr<DWARFDebugLine> Line;
262 std::unique_ptr<DWARFDebugFrame> DebugFrame;
263 std::unique_ptr<DWARFDebugFrame> EHFrame;
264 std::unique_ptr<DWARFDebugMacro> Macro;
265 std::unique_ptr<DWARFDebugMacro> Macinfo;
266 std::unique_ptr<DWARFDebugNames> Names;
267 std::unique_ptr<AppleAcceleratorTable> AppleNames;
268 std::unique_ptr<AppleAcceleratorTable> AppleTypes;
269 std::unique_ptr<AppleAcceleratorTable> AppleNamespaces;
270 std::unique_ptr<AppleAcceleratorTable> AppleObjC;
271 DWARFUnitVector DWOUnits;
272 std::optional<DenseMap<uint64_t, DWARFTypeUnit *>> DWOTypeUnits;
273 std::unique_ptr<DWARFDebugAbbrev> AbbrevDWO;
274 std::unique_ptr<DWARFDebugMacro> MacinfoDWO;
275 std::unique_ptr<DWARFDebugMacro> MacroDWO;
276 struct DWOFile {
277 object::OwningBinary<object::ObjectFile> File;
278 std::unique_ptr<DWARFContext> Context;
279 };
280 StringMap<std::weak_ptr<DWOFile>> DWOFiles;
281 std::weak_ptr<DWOFile> DWP;
282 bool CheckedForDWP = false;
283 std::string DWPName;
284
285public:
286 ThreadUnsafeDWARFContextState(DWARFContext &DC, std::string &DWP) :
287 DWARFContext::DWARFContextState(DC),
288 DWPName(std::move(DWP)) {}
289
290 DWARFUnitVector &getNormalUnits() override {
291 if (NormalUnits.empty()) {
292 const DWARFObject &DObj = D.getDWARFObj();
293 DObj.forEachInfoSections(F: [&](const DWARFSection &S) {
294 NormalUnits.addUnitsForSection(C&: D, Section: S, SectionKind: DW_SECT_INFO);
295 });
296 NormalUnits.finishedInfoUnits();
297 DObj.forEachTypesSections(F: [&](const DWARFSection &S) {
298 NormalUnits.addUnitsForSection(C&: D, Section: S, SectionKind: DW_SECT_EXT_TYPES);
299 });
300 }
301 return NormalUnits;
302 }
303
304 DWARFUnitVector &getDWOUnits(bool Lazy) override {
305 if (DWOUnits.empty()) {
306 const DWARFObject &DObj = D.getDWARFObj();
307
308 DObj.forEachInfoDWOSections(F: [&](const DWARFSection &S) {
309 DWOUnits.addUnitsForDWOSection(C&: D, DWOSection: S, SectionKind: DW_SECT_INFO, Lazy);
310 });
311 DWOUnits.finishedInfoUnits();
312 DObj.forEachTypesDWOSections(F: [&](const DWARFSection &S) {
313 DWOUnits.addUnitsForDWOSection(C&: D, DWOSection: S, SectionKind: DW_SECT_EXT_TYPES, Lazy);
314 });
315 }
316 return DWOUnits;
317 }
318
319 const DWARFDebugAbbrev *getDebugAbbrevDWO() override {
320 if (AbbrevDWO)
321 return AbbrevDWO.get();
322 const DWARFObject &DObj = D.getDWARFObj();
323 DataExtractor abbrData(DObj.getAbbrevDWOSection(), D.isLittleEndian());
324 AbbrevDWO = std::make_unique<DWARFDebugAbbrev>(args&: abbrData);
325 return AbbrevDWO.get();
326 }
327
328 const DWARFUnitIndex &getCUIndex() override {
329 if (CUIndex)
330 return *CUIndex;
331
332 DataExtractor Data(D.getDWARFObj().getCUIndexSection(), D.isLittleEndian());
333 CUIndex = std::make_unique<DWARFUnitIndex>(args: DW_SECT_INFO);
334 if (CUIndex->parse(IndexData: Data))
335 fixupIndex(C&: D, Index&: *CUIndex);
336 return *CUIndex;
337 }
338 const DWARFUnitIndex &getTUIndex() override {
339 if (TUIndex)
340 return *TUIndex;
341
342 DataExtractor Data(D.getDWARFObj().getTUIndexSection(), D.isLittleEndian());
343 TUIndex = std::make_unique<DWARFUnitIndex>(args: DW_SECT_EXT_TYPES);
344 bool isParseSuccessful = TUIndex->parse(IndexData: Data);
345 // If we are parsing TU-index and for .debug_types section we don't need
346 // to do anything.
347 if (isParseSuccessful && TUIndex->getVersion() != 2)
348 fixupIndex(C&: D, Index&: *TUIndex);
349 return *TUIndex;
350 }
351
352 DWARFGdbIndex &getGdbIndex() override {
353 if (GdbIndex)
354 return *GdbIndex;
355
356 DataExtractor Data(D.getDWARFObj().getGdbIndexSection(),
357 /*IsLittleEndian=*/true);
358 GdbIndex = std::make_unique<DWARFGdbIndex>();
359 GdbIndex->parse(Data);
360 return *GdbIndex;
361 }
362
363 const DWARFDebugAbbrev *getDebugAbbrev() override {
364 if (Abbrev)
365 return Abbrev.get();
366
367 DataExtractor Data(D.getDWARFObj().getAbbrevSection(), D.isLittleEndian());
368 Abbrev = std::make_unique<DWARFDebugAbbrev>(args&: Data);
369 return Abbrev.get();
370 }
371
372 const DWARFDebugLoc *getDebugLoc() override {
373 if (Loc)
374 return Loc.get();
375
376 const DWARFObject &DObj = D.getDWARFObj();
377 // Assume all units have the same address byte size.
378 auto Data =
379 D.getNumCompileUnits()
380 ? DWARFDataExtractor(DObj, DObj.getLocSection(), D.isLittleEndian(),
381 D.getUnitAtIndex(index: 0)->getAddressByteSize())
382 : DWARFDataExtractor("", D.isLittleEndian(), 0);
383 Loc = std::make_unique<DWARFDebugLoc>(args: std::move(Data));
384 return Loc.get();
385 }
386
387 const DWARFDebugAranges *getDebugAranges() override {
388 if (Aranges)
389 return Aranges.get();
390
391 Aranges = std::make_unique<DWARFDebugAranges>();
392 Aranges->generate(CTX: &D);
393 return Aranges.get();
394 }
395
396 Expected<const DWARFDebugLine::LineTable *>
397 getLineTableForUnit(DWARFUnit *U, function_ref<void(Error)> RecoverableErrorHandler) override {
398 if (!Line)
399 Line = std::make_unique<DWARFDebugLine>();
400
401 auto UnitDIE = U->getUnitDIE();
402 if (!UnitDIE)
403 return nullptr;
404
405 auto Offset = toSectionOffset(V: UnitDIE.find(Attr: DW_AT_stmt_list));
406 if (!Offset)
407 return nullptr; // No line table for this compile unit.
408
409 uint64_t stmtOffset = *Offset + U->getLineTableOffset();
410 // See if the line table is cached.
411 if (const DWARFLineTable *lt = Line->getLineTable(Offset: stmtOffset))
412 return lt;
413
414 // Make sure the offset is good before we try to parse.
415 if (stmtOffset >= U->getLineSection().Data.size())
416 return nullptr;
417
418 // We have to parse it first.
419 DWARFDataExtractor Data(U->getContext().getDWARFObj(), U->getLineSection(),
420 U->isLittleEndian(), U->getAddressByteSize());
421 return Line->getOrParseLineTable(DebugLineData&: Data, Offset: stmtOffset, Ctx: U->getContext(), U,
422 RecoverableErrorHandler);
423
424 }
425
426 void clearLineTableForUnit(DWARFUnit *U) override {
427 if (!Line)
428 return;
429
430 auto UnitDIE = U->getUnitDIE();
431 if (!UnitDIE)
432 return;
433
434 auto Offset = toSectionOffset(V: UnitDIE.find(Attr: DW_AT_stmt_list));
435 if (!Offset)
436 return;
437
438 uint64_t stmtOffset = *Offset + U->getLineTableOffset();
439 Line->clearLineTable(Offset: stmtOffset);
440 }
441
442 Expected<const DWARFDebugFrame *> getDebugFrame() override {
443 if (DebugFrame)
444 return DebugFrame.get();
445 const DWARFObject &DObj = D.getDWARFObj();
446 const DWARFSection &DS = DObj.getFrameSection();
447
448 // There's a "bug" in the DWARFv3 standard with respect to the target address
449 // size within debug frame sections. While DWARF is supposed to be independent
450 // of its container, FDEs have fields with size being "target address size",
451 // which isn't specified in DWARF in general. It's only specified for CUs, but
452 // .eh_frame can appear without a .debug_info section. Follow the example of
453 // other tools (libdwarf) and extract this from the container (ObjectFile
454 // provides this information). This problem is fixed in DWARFv4
455 // See this dwarf-discuss discussion for more details:
456 // http://lists.dwarfstd.org/htdig.cgi/dwarf-discuss-dwarfstd.org/2011-December/001173.html
457 DWARFDataExtractor Data(DObj, DS, D.isLittleEndian(),
458 DObj.getAddressSize());
459 auto DF =
460 std::make_unique<DWARFDebugFrame>(args: D.getArch(), /*IsEH=*/args: false,
461 args: DS.Address);
462 if (Error E = DF->parse(Data))
463 return std::move(E);
464
465 DebugFrame.swap(u&: DF);
466 return DebugFrame.get();
467 }
468
469 Expected<const DWARFDebugFrame *> getEHFrame() override {
470 if (EHFrame)
471 return EHFrame.get();
472 const DWARFObject &DObj = D.getDWARFObj();
473
474 const DWARFSection &DS = DObj.getEHFrameSection();
475 DWARFDataExtractor Data(DObj, DS, D.isLittleEndian(),
476 DObj.getAddressSize());
477 auto DF =
478 std::make_unique<DWARFDebugFrame>(args: D.getArch(), /*IsEH=*/args: true,
479 args: DS.Address);
480 if (Error E = DF->parse(Data))
481 return std::move(E);
482 EHFrame.swap(u&: DF);
483 return EHFrame.get();
484 }
485
486 const DWARFDebugMacro *getDebugMacinfo() override {
487 if (!Macinfo)
488 Macinfo = parseMacroOrMacinfo(SectionType: MacinfoSection);
489 return Macinfo.get();
490 }
491 const DWARFDebugMacro *getDebugMacinfoDWO() override {
492 if (!MacinfoDWO)
493 MacinfoDWO = parseMacroOrMacinfo(SectionType: MacinfoDwoSection);
494 return MacinfoDWO.get();
495 }
496 const DWARFDebugMacro *getDebugMacro() override {
497 if (!Macro)
498 Macro = parseMacroOrMacinfo(SectionType: MacroSection);
499 return Macro.get();
500 }
501 const DWARFDebugMacro *getDebugMacroDWO() override {
502 if (!MacroDWO)
503 MacroDWO = parseMacroOrMacinfo(SectionType: MacroDwoSection);
504 return MacroDWO.get();
505 }
506 const DWARFDebugNames &getDebugNames() override {
507 const DWARFObject &DObj = D.getDWARFObj();
508 return getAccelTable(Cache&: Names, Obj: DObj, Section: DObj.getNamesSection(),
509 StringSection: DObj.getStrSection(), IsLittleEndian: D.isLittleEndian());
510 }
511 const AppleAcceleratorTable &getAppleNames() override {
512 const DWARFObject &DObj = D.getDWARFObj();
513 return getAccelTable(Cache&: AppleNames, Obj: DObj, Section: DObj.getAppleNamesSection(),
514 StringSection: DObj.getStrSection(), IsLittleEndian: D.isLittleEndian());
515
516 }
517 const AppleAcceleratorTable &getAppleTypes() override {
518 const DWARFObject &DObj = D.getDWARFObj();
519 return getAccelTable(Cache&: AppleTypes, Obj: DObj, Section: DObj.getAppleTypesSection(),
520 StringSection: DObj.getStrSection(), IsLittleEndian: D.isLittleEndian());
521
522 }
523 const AppleAcceleratorTable &getAppleNamespaces() override {
524 const DWARFObject &DObj = D.getDWARFObj();
525 return getAccelTable(Cache&: AppleNamespaces, Obj: DObj,
526 Section: DObj.getAppleNamespacesSection(),
527 StringSection: DObj.getStrSection(), IsLittleEndian: D.isLittleEndian());
528
529 }
530 const AppleAcceleratorTable &getAppleObjC() override {
531 const DWARFObject &DObj = D.getDWARFObj();
532 return getAccelTable(Cache&: AppleObjC, Obj: DObj, Section: DObj.getAppleObjCSection(),
533 StringSection: DObj.getStrSection(), IsLittleEndian: D.isLittleEndian());
534 }
535
536 std::shared_ptr<DWARFContext>
537 getDWOContext(StringRef AbsolutePath) override {
538 if (auto S = DWP.lock()) {
539 DWARFContext *Ctxt = S->Context.get();
540 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
541 }
542
543 std::weak_ptr<DWOFile> *Entry = &DWOFiles[AbsolutePath];
544
545 if (auto S = Entry->lock()) {
546 DWARFContext *Ctxt = S->Context.get();
547 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
548 }
549
550 const DWARFObject &DObj = D.getDWARFObj();
551
552 Expected<OwningBinary<ObjectFile>> Obj = [&] {
553 if (!CheckedForDWP) {
554 SmallString<128> DWPName;
555 auto Obj = object::ObjectFile::createObjectFile(
556 ObjectPath: this->DWPName.empty()
557 ? (DObj.getFileName() + ".dwp").toStringRef(Out&: DWPName)
558 : StringRef(this->DWPName));
559 if (Obj) {
560 Entry = &DWP;
561 return Obj;
562 } else {
563 CheckedForDWP = true;
564 // TODO: Should this error be handled (maybe in a high verbosity mode)
565 // before falling back to .dwo files?
566 consumeError(Err: Obj.takeError());
567 }
568 }
569
570 return object::ObjectFile::createObjectFile(ObjectPath: AbsolutePath);
571 }();
572
573 if (!Obj) {
574 // TODO: Actually report errors helpfully.
575 consumeError(Err: Obj.takeError());
576 return nullptr;
577 }
578
579 auto S = std::make_shared<DWOFile>();
580 S->File = std::move(Obj.get());
581 // Allow multi-threaded access if there is a .dwp file as the CU index and
582 // TU index might be accessed from multiple threads.
583 bool ThreadSafe = isThreadSafe();
584 S->Context = DWARFContext::create(
585 Obj: *S->File.getBinary(), RelocAction: DWARFContext::ProcessDebugRelocations::Ignore,
586 L: nullptr, DWPName: "", RecoverableErrorHandler: WithColor::defaultErrorHandler,
587 WarningHandler: WithColor::defaultWarningHandler, ThreadSafe);
588 *Entry = S;
589 auto *Ctxt = S->Context.get();
590 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
591 }
592
593 bool isThreadSafe() const override { return false; }
594
595 const DenseMap<uint64_t, DWARFTypeUnit *> &getNormalTypeUnitMap() {
596 if (!NormalTypeUnits) {
597 NormalTypeUnits.emplace();
598 for (const auto &U :D.normal_units()) {
599 if (DWARFTypeUnit *TU = dyn_cast<DWARFTypeUnit>(Val: U.get()))
600 (*NormalTypeUnits)[TU->getTypeHash()] = TU;
601 }
602 }
603 return *NormalTypeUnits;
604 }
605
606 const DenseMap<uint64_t, DWARFTypeUnit *> &getDWOTypeUnitMap() {
607 if (!DWOTypeUnits) {
608 DWOTypeUnits.emplace();
609 for (const auto &U :D.dwo_units()) {
610 if (DWARFTypeUnit *TU = dyn_cast<DWARFTypeUnit>(Val: U.get()))
611 (*DWOTypeUnits)[TU->getTypeHash()] = TU;
612 }
613 }
614 return *DWOTypeUnits;
615 }
616
617 const DenseMap<uint64_t, DWARFTypeUnit *> &
618 getTypeUnitMap(bool IsDWO) override {
619 if (IsDWO)
620 return getDWOTypeUnitMap();
621 else
622 return getNormalTypeUnitMap();
623 }
624};
625
626class ThreadSafeState : public ThreadUnsafeDWARFContextState {
627 std::recursive_mutex Mutex;
628
629public:
630 ThreadSafeState(DWARFContext &DC, std::string &DWP) :
631 ThreadUnsafeDWARFContextState(DC, DWP) {}
632
633 DWARFUnitVector &getNormalUnits() override {
634 std::unique_lock<std::recursive_mutex> LockGuard(Mutex);
635 return ThreadUnsafeDWARFContextState::getNormalUnits();
636 }
637 DWARFUnitVector &getDWOUnits(bool Lazy) override {
638 std::unique_lock<std::recursive_mutex> LockGuard(Mutex);
639 // We need to not do lazy parsing when we need thread safety as
640 // DWARFUnitVector, in lazy mode, will slowly add things to itself and
641 // will cause problems in a multi-threaded environment.
642 return ThreadUnsafeDWARFContextState::getDWOUnits(Lazy: false);
643 }
644 const DWARFUnitIndex &getCUIndex() override {
645 std::unique_lock<std::recursive_mutex> LockGuard(Mutex);
646 return ThreadUnsafeDWARFContextState::getCUIndex();
647 }
648 const DWARFDebugAbbrev *getDebugAbbrevDWO() override {
649 std::unique_lock<std::recursive_mutex> LockGuard(Mutex);
650 return ThreadUnsafeDWARFContextState::getDebugAbbrevDWO();
651 }
652
653 const DWARFUnitIndex &getTUIndex() override {
654 std::unique_lock<std::recursive_mutex> LockGuard(Mutex);
655 return ThreadUnsafeDWARFContextState::getTUIndex();
656 }
657 DWARFGdbIndex &getGdbIndex() override {
658 std::unique_lock<std::recursive_mutex> LockGuard(Mutex);
659 return ThreadUnsafeDWARFContextState::getGdbIndex();
660 }
661 const DWARFDebugAbbrev *getDebugAbbrev() override {
662 std::unique_lock<std::recursive_mutex> LockGuard(Mutex);
663 return ThreadUnsafeDWARFContextState::getDebugAbbrev();
664 }
665 const DWARFDebugLoc *getDebugLoc() override {
666 std::unique_lock<std::recursive_mutex> LockGuard(Mutex);
667 return ThreadUnsafeDWARFContextState::getDebugLoc();
668 }
669 const DWARFDebugAranges *getDebugAranges() override {
670 std::unique_lock<std::recursive_mutex> LockGuard(Mutex);
671 return ThreadUnsafeDWARFContextState::getDebugAranges();
672 }
673 Expected<const DWARFDebugLine::LineTable *>
674 getLineTableForUnit(DWARFUnit *U, function_ref<void(Error)> RecoverableErrorHandler) override {
675 std::unique_lock<std::recursive_mutex> LockGuard(Mutex);
676 return ThreadUnsafeDWARFContextState::getLineTableForUnit(U, RecoverableErrorHandler);
677 }
678 void clearLineTableForUnit(DWARFUnit *U) override {
679 std::unique_lock<std::recursive_mutex> LockGuard(Mutex);
680 return ThreadUnsafeDWARFContextState::clearLineTableForUnit(U);
681 }
682 Expected<const DWARFDebugFrame *> getDebugFrame() override {
683 std::unique_lock<std::recursive_mutex> LockGuard(Mutex);
684 return ThreadUnsafeDWARFContextState::getDebugFrame();
685 }
686 Expected<const DWARFDebugFrame *> getEHFrame() override {
687 std::unique_lock<std::recursive_mutex> LockGuard(Mutex);
688 return ThreadUnsafeDWARFContextState::getEHFrame();
689 }
690 const DWARFDebugMacro *getDebugMacinfo() override {
691 std::unique_lock<std::recursive_mutex> LockGuard(Mutex);
692 return ThreadUnsafeDWARFContextState::getDebugMacinfo();
693 }
694 const DWARFDebugMacro *getDebugMacinfoDWO() override {
695 std::unique_lock<std::recursive_mutex> LockGuard(Mutex);
696 return ThreadUnsafeDWARFContextState::getDebugMacinfoDWO();
697 }
698 const DWARFDebugMacro *getDebugMacro() override {
699 std::unique_lock<std::recursive_mutex> LockGuard(Mutex);
700 return ThreadUnsafeDWARFContextState::getDebugMacro();
701 }
702 const DWARFDebugMacro *getDebugMacroDWO() override {
703 std::unique_lock<std::recursive_mutex> LockGuard(Mutex);
704 return ThreadUnsafeDWARFContextState::getDebugMacroDWO();
705 }
706 const DWARFDebugNames &getDebugNames() override {
707 std::unique_lock<std::recursive_mutex> LockGuard(Mutex);
708 return ThreadUnsafeDWARFContextState::getDebugNames();
709 }
710 const AppleAcceleratorTable &getAppleNames() override {
711 std::unique_lock<std::recursive_mutex> LockGuard(Mutex);
712 return ThreadUnsafeDWARFContextState::getAppleNames();
713 }
714 const AppleAcceleratorTable &getAppleTypes() override {
715 std::unique_lock<std::recursive_mutex> LockGuard(Mutex);
716 return ThreadUnsafeDWARFContextState::getAppleTypes();
717 }
718 const AppleAcceleratorTable &getAppleNamespaces() override {
719 std::unique_lock<std::recursive_mutex> LockGuard(Mutex);
720 return ThreadUnsafeDWARFContextState::getAppleNamespaces();
721 }
722 const AppleAcceleratorTable &getAppleObjC() override {
723 std::unique_lock<std::recursive_mutex> LockGuard(Mutex);
724 return ThreadUnsafeDWARFContextState::getAppleObjC();
725 }
726 std::shared_ptr<DWARFContext>
727 getDWOContext(StringRef AbsolutePath) override {
728 std::unique_lock<std::recursive_mutex> LockGuard(Mutex);
729 return ThreadUnsafeDWARFContextState::getDWOContext(AbsolutePath);
730 }
731
732 bool isThreadSafe() const override { return true; }
733
734 const DenseMap<uint64_t, DWARFTypeUnit *> &
735 getTypeUnitMap(bool IsDWO) override {
736 std::unique_lock<std::recursive_mutex> LockGuard(Mutex);
737 return ThreadUnsafeDWARFContextState::getTypeUnitMap(IsDWO);
738 }
739};
740} // namespace
741
742DWARFContext::DWARFContext(std::unique_ptr<const DWARFObject> DObj,
743 std::string DWPName,
744 std::function<void(Error)> RecoverableErrorHandler,
745 std::function<void(Error)> WarningHandler,
746 bool ThreadSafe)
747 : DIContext(CK_DWARF),
748 RecoverableErrorHandler(RecoverableErrorHandler),
749 WarningHandler(WarningHandler), DObj(std::move(DObj)) {
750 if (ThreadSafe)
751 State = std::make_unique<ThreadSafeState>(args&: *this, args&: DWPName);
752 else
753 State = std::make_unique<ThreadUnsafeDWARFContextState>(args&: *this, args&: DWPName);
754 }
755
756DWARFContext::~DWARFContext() = default;
757
758/// Dump the UUID load command.
759static void dumpUUID(raw_ostream &OS, const ObjectFile &Obj) {
760 auto *MachO = dyn_cast<MachOObjectFile>(Val: &Obj);
761 if (!MachO)
762 return;
763 for (auto LC : MachO->load_commands()) {
764 raw_ostream::uuid_t UUID;
765 if (LC.C.cmd == MachO::LC_UUID) {
766 if (LC.C.cmdsize < sizeof(UUID) + sizeof(LC.C)) {
767 OS << "error: UUID load command is too short.\n";
768 return;
769 }
770 OS << "UUID: ";
771 memcpy(dest: &UUID, src: LC.Ptr+sizeof(LC.C), n: sizeof(UUID));
772 OS.write_uuid(UUID);
773 Triple T = MachO->getArchTriple();
774 OS << " (" << T.getArchName() << ')';
775 OS << ' ' << MachO->getFileName() << '\n';
776 }
777 }
778}
779
780using ContributionCollection =
781 std::vector<std::optional<StrOffsetsContributionDescriptor>>;
782
783// Collect all the contributions to the string offsets table from all units,
784// sort them by their starting offsets and remove duplicates.
785static ContributionCollection
786collectContributionData(DWARFContext::unit_iterator_range Units) {
787 ContributionCollection Contributions;
788 for (const auto &U : Units)
789 if (const auto &C = U->getStringOffsetsTableContribution())
790 Contributions.push_back(x: C);
791 // Sort the contributions so that any invalid ones are placed at
792 // the start of the contributions vector. This way they are reported
793 // first.
794 llvm::sort(C&: Contributions,
795 Comp: [](const std::optional<StrOffsetsContributionDescriptor> &L,
796 const std::optional<StrOffsetsContributionDescriptor> &R) {
797 if (L && R)
798 return L->Base < R->Base;
799 return R.has_value();
800 });
801
802 // Uniquify contributions, as it is possible that units (specifically
803 // type units in dwo or dwp files) share contributions. We don't want
804 // to report them more than once.
805 Contributions.erase(
806 first: llvm::unique(
807 R&: Contributions,
808 P: [](const std::optional<StrOffsetsContributionDescriptor> &L,
809 const std::optional<StrOffsetsContributionDescriptor> &R) {
810 if (L && R)
811 return L->Base == R->Base && L->Size == R->Size;
812 return false;
813 }),
814 last: Contributions.end());
815 return Contributions;
816}
817
818// Dump a DWARF string offsets section. This may be a DWARF v5 formatted
819// string offsets section, where each compile or type unit contributes a
820// number of entries (string offsets), with each contribution preceded by
821// a header containing size and version number. Alternatively, it may be a
822// monolithic series of string offsets, as generated by the pre-DWARF v5
823// implementation of split DWARF; however, in that case we still need to
824// collect contributions of units because the size of the offsets (4 or 8
825// bytes) depends on the format of the referencing unit (DWARF32 or DWARF64).
826static void dumpStringOffsetsSection(raw_ostream &OS, DIDumpOptions DumpOpts,
827 StringRef SectionName,
828 const DWARFObject &Obj,
829 const DWARFSection &StringOffsetsSection,
830 StringRef StringSection,
831 DWARFContext::unit_iterator_range Units,
832 bool LittleEndian) {
833 auto Contributions = collectContributionData(Units);
834 DWARFDataExtractor StrOffsetExt(Obj, StringOffsetsSection, LittleEndian, 0);
835 DataExtractor StrData(StringSection, LittleEndian);
836 uint64_t SectionSize = StringOffsetsSection.Data.size();
837 uint64_t Offset = 0;
838 for (auto &Contribution : Contributions) {
839 // Report an ill-formed contribution.
840 if (!Contribution) {
841 OS << "error: invalid contribution to string offsets table in section ."
842 << SectionName << ".\n";
843 return;
844 }
845
846 dwarf::DwarfFormat Format = Contribution->getFormat();
847 int OffsetDumpWidth = 2 * dwarf::getDwarfOffsetByteSize(Format);
848 uint16_t Version = Contribution->getVersion();
849 uint64_t ContributionHeader = Contribution->Base;
850 // In DWARF v5 there is a contribution header that immediately precedes
851 // the string offsets base (the location we have previously retrieved from
852 // the CU DIE's DW_AT_str_offsets attribute). The header is located either
853 // 8 or 16 bytes before the base, depending on the contribution's format.
854 if (Version >= 5)
855 ContributionHeader -= Format == DWARF32 ? 8 : 16;
856
857 // Detect overlapping contributions.
858 if (Offset > ContributionHeader) {
859 DumpOpts.RecoverableErrorHandler(createStringError(
860 EC: errc::invalid_argument,
861 Fmt: "overlapping contributions to string offsets table in section .%s.",
862 Vals: SectionName.data()));
863 }
864 // Report a gap in the table.
865 if (Offset < ContributionHeader) {
866 OS << formatv(Fmt: "{0:x8}: Gap, length = ", Vals&: Offset);
867 OS << (ContributionHeader - Offset) << "\n";
868 }
869 OS << formatv(Fmt: "{0:x8}: ", Vals&: ContributionHeader);
870 // In DWARF v5 the contribution size in the descriptor does not equal
871 // the originally encoded length (it does not contain the length of the
872 // version field and the padding, a total of 4 bytes). Add them back in
873 // for reporting.
874 OS << "Contribution size = " << (Contribution->Size + (Version < 5 ? 0 : 4))
875 << ", Format = " << dwarf::FormatString(Format)
876 << ", Version = " << Version << "\n";
877
878 Offset = Contribution->Base;
879 unsigned EntrySize = Contribution->getDwarfOffsetByteSize();
880 while (Offset - Contribution->Base < Contribution->Size) {
881 OS << formatv(Fmt: "{0:x8}: ", Vals&: Offset);
882 uint64_t StringOffset =
883 StrOffsetExt.getRelocatedValue(Size: EntrySize, Off: &Offset);
884 OS << formatv(Fmt: "{0:x-} ", Vals: fmt_align(Item&: StringOffset, Where: AlignStyle::Right,
885 Amount: OffsetDumpWidth, Fill: '0'));
886 const char *S = StrData.getCStr(OffsetPtr: &StringOffset);
887 if (S)
888 OS << formatv(Fmt: "\"{0}\"", Vals&: S);
889 OS << "\n";
890 }
891 }
892 // Report a gap at the end of the table.
893 if (Offset < SectionSize) {
894 OS << formatv(Fmt: "{0:x8}: Gap, length = ", Vals&: Offset);
895 OS << (SectionSize - Offset) << "\n";
896 }
897}
898
899// Dump the .debug_addr section.
900static void dumpAddrSection(raw_ostream &OS, DWARFDataExtractor &AddrData,
901 DIDumpOptions DumpOpts, uint16_t Version,
902 uint8_t AddrSize) {
903 uint64_t Offset = 0;
904 while (AddrData.isValidOffset(offset: Offset)) {
905 DWARFDebugAddrTable AddrTable;
906 uint64_t TableOffset = Offset;
907 if (Error Err = AddrTable.extract(Data: AddrData, OffsetPtr: &Offset, CUVersion: Version, CUAddrSize: AddrSize,
908 WarnCallback: DumpOpts.WarningHandler)) {
909 DumpOpts.RecoverableErrorHandler(std::move(Err));
910 // Keep going after an error, if we can, assuming that the length field
911 // could be read. If it couldn't, stop reading the section.
912 if (auto TableLength = AddrTable.getFullLength()) {
913 Offset = TableOffset + *TableLength;
914 continue;
915 }
916 break;
917 }
918 AddrTable.dump(OS, DumpOpts);
919 }
920}
921
922// Dump the .debug_rnglists or .debug_rnglists.dwo section (DWARF v5).
923static void dumpRnglistsSection(
924 raw_ostream &OS, DWARFDataExtractor &rnglistData,
925 llvm::function_ref<std::optional<object::SectionedAddress>(uint32_t)>
926 LookupPooledAddress,
927 DIDumpOptions DumpOpts) {
928 uint64_t Offset = 0;
929 while (rnglistData.isValidOffset(offset: Offset)) {
930 llvm::DWARFDebugRnglistTable Rnglists;
931 uint64_t TableOffset = Offset;
932 if (Error Err = Rnglists.extract(Data: rnglistData, OffsetPtr: &Offset)) {
933 DumpOpts.RecoverableErrorHandler(std::move(Err));
934 uint64_t Length = Rnglists.length();
935 // Keep going after an error, if we can, assuming that the length field
936 // could be read. If it couldn't, stop reading the section.
937 if (Length == 0)
938 break;
939 Offset = TableOffset + Length;
940 } else {
941 Rnglists.dump(Data: rnglistData, OS, LookupPooledAddress, DumpOpts);
942 }
943 }
944}
945
946
947static void dumpLoclistsSection(raw_ostream &OS, DIDumpOptions DumpOpts,
948 DWARFDataExtractor Data, const DWARFObject &Obj,
949 std::optional<uint64_t> DumpOffset) {
950 uint64_t Offset = 0;
951
952 while (Data.isValidOffset(offset: Offset)) {
953 DWARFListTableHeader Header(".debug_loclists", "locations");
954 if (Error E = Header.extract(Data, OffsetPtr: &Offset)) {
955 DumpOpts.RecoverableErrorHandler(std::move(E));
956 return;
957 }
958
959 Header.dump(Data, OS, DumpOpts);
960
961 uint64_t EndOffset = Header.length() + Header.getHeaderOffset();
962 Data.setAddressSize(Header.getAddrSize());
963 DWARFDebugLoclists Loc(Data, Header.getVersion());
964 if (DumpOffset) {
965 if (DumpOffset >= Offset && DumpOffset < EndOffset) {
966 Offset = *DumpOffset;
967 Loc.dumpLocationList(Offset: &Offset, OS, /*BaseAddr=*/std::nullopt, Obj,
968 U: nullptr, DumpOpts, /*Indent=*/0);
969 OS << "\n";
970 return;
971 }
972 } else {
973 Loc.dumpRange(StartOffset: Offset, Size: EndOffset - Offset, OS, Obj, DumpOpts);
974 }
975 Offset = EndOffset;
976 }
977}
978
979static void dumpPubTableSection(raw_ostream &OS, DIDumpOptions DumpOpts,
980 DWARFDataExtractor Data, bool GnuStyle) {
981 DWARFDebugPubTable Table;
982 Table.extract(Data, GnuStyle, RecoverableErrorHandler: DumpOpts.RecoverableErrorHandler);
983 Table.dump(OS);
984}
985
986void DWARFContext::dump(
987 raw_ostream &OS, DIDumpOptions DumpOpts,
988 std::array<std::optional<uint64_t>, DIDT_ID_Count> DumpOffsets) {
989 uint64_t DumpType = DumpOpts.DumpType;
990
991 StringRef Extension = sys::path::extension(path: DObj->getFileName());
992 bool IsDWO = (Extension == ".dwo") || (Extension == ".dwp");
993
994 // Print UUID header.
995 const auto *ObjFile = DObj->getFile();
996 if (DumpType & DIDT_UUID)
997 dumpUUID(OS, Obj: *ObjFile);
998
999 // Print a header for each explicitly-requested section.
1000 // Otherwise just print one for non-empty sections.
1001 // Only print empty .dwo section headers when dumping a .dwo file.
1002 bool Explicit = DumpType != DIDT_All && !IsDWO;
1003 bool ExplicitDWO = Explicit && IsDWO;
1004 auto shouldDump = [&](bool Explicit, const char *Name, unsigned ID,
1005 StringRef Section) -> std::optional<uint64_t> * {
1006 unsigned Mask = 1U << ID;
1007 bool Should = (DumpType & Mask) && (Explicit || !Section.empty());
1008 if (!Should)
1009 return nullptr;
1010 OS << "\n" << Name << " contents:\n";
1011 return &DumpOffsets[ID];
1012 };
1013
1014 // Dump individual sections.
1015 if (shouldDump(Explicit, ".debug_abbrev", DIDT_ID_DebugAbbrev,
1016 DObj->getAbbrevSection()))
1017 getDebugAbbrev()->dump(OS);
1018 if (shouldDump(ExplicitDWO, ".debug_abbrev.dwo", DIDT_ID_DebugAbbrev,
1019 DObj->getAbbrevDWOSection()))
1020 getDebugAbbrevDWO()->dump(OS);
1021
1022 auto dumpDebugInfo = [&](const char *Name, unit_iterator_range Units) {
1023 OS << '\n' << Name << " contents:\n";
1024 if (auto DumpOffset = DumpOffsets[DIDT_ID_DebugInfo])
1025 for (const auto &U : Units) {
1026 U->getDIEForOffset(Offset: *DumpOffset)
1027 .dump(OS, indent: 0, DumpOpts: DumpOpts.noImplicitRecursion());
1028 DWARFDie CUDie = U->getUnitDIE(ExtractUnitDIEOnly: false);
1029 DWARFDie CUNonSkeletonDie = U->getNonSkeletonUnitDIE(ExtractUnitDIEOnly: false);
1030 if (CUNonSkeletonDie && CUDie != CUNonSkeletonDie) {
1031 CUNonSkeletonDie.getDwarfUnit()
1032 ->getDIEForOffset(Offset: *DumpOffset)
1033 .dump(OS, indent: 0, DumpOpts: DumpOpts.noImplicitRecursion());
1034 }
1035 }
1036 else
1037 for (const auto &U : Units)
1038 U->dump(OS, DumpOpts);
1039 };
1040 if ((DumpType & DIDT_DebugInfo)) {
1041 if (Explicit || getNumCompileUnits())
1042 dumpDebugInfo(".debug_info", info_section_units());
1043 if (ExplicitDWO || getNumDWOCompileUnits())
1044 dumpDebugInfo(".debug_info.dwo", dwo_info_section_units());
1045 }
1046
1047 auto dumpDebugType = [&](const char *Name, unit_iterator_range Units) {
1048 OS << '\n' << Name << " contents:\n";
1049 for (const auto &U : Units)
1050 if (auto DumpOffset = DumpOffsets[DIDT_ID_DebugTypes])
1051 U->getDIEForOffset(Offset: *DumpOffset)
1052 .dump(OS, indent: 0, DumpOpts: DumpOpts.noImplicitRecursion());
1053 else
1054 U->dump(OS, DumpOpts);
1055 };
1056 if ((DumpType & DIDT_DebugTypes)) {
1057 if (Explicit || getNumTypeUnits())
1058 dumpDebugType(".debug_types", types_section_units());
1059 if (ExplicitDWO || getNumDWOTypeUnits())
1060 dumpDebugType(".debug_types.dwo", dwo_types_section_units());
1061 }
1062
1063 DIDumpOptions LLDumpOpts = DumpOpts;
1064 if (LLDumpOpts.Verbose)
1065 LLDumpOpts.DisplayRawContents = true;
1066
1067 if (const auto *Off = shouldDump(Explicit, ".debug_loc", DIDT_ID_DebugLoc,
1068 DObj->getLocSection().Data)) {
1069 getDebugLoc()->dump(OS, Obj: *DObj, DumpOpts: LLDumpOpts, Offset: *Off);
1070 }
1071 if (const auto *Off =
1072 shouldDump(Explicit, ".debug_loclists", DIDT_ID_DebugLoclists,
1073 DObj->getLoclistsSection().Data)) {
1074 DWARFDataExtractor Data(*DObj, DObj->getLoclistsSection(), isLittleEndian(),
1075 0);
1076 dumpLoclistsSection(OS, DumpOpts: LLDumpOpts, Data, Obj: *DObj, DumpOffset: *Off);
1077 }
1078 if (const auto *Off =
1079 shouldDump(ExplicitDWO, ".debug_loclists.dwo", DIDT_ID_DebugLoclists,
1080 DObj->getLoclistsDWOSection().Data)) {
1081 DWARFDataExtractor Data(*DObj, DObj->getLoclistsDWOSection(),
1082 isLittleEndian(), 0);
1083 dumpLoclistsSection(OS, DumpOpts: LLDumpOpts, Data, Obj: *DObj, DumpOffset: *Off);
1084 }
1085
1086 if (const auto *Off =
1087 shouldDump(ExplicitDWO, ".debug_loc.dwo", DIDT_ID_DebugLoc,
1088 DObj->getLocDWOSection().Data)) {
1089 DWARFDataExtractor Data(*DObj, DObj->getLocDWOSection(), isLittleEndian(),
1090 4);
1091 DWARFDebugLoclists Loc(Data, /*Version=*/4);
1092 if (*Off) {
1093 uint64_t Offset = **Off;
1094 Loc.dumpLocationList(Offset: &Offset, OS,
1095 /*BaseAddr=*/std::nullopt, Obj: *DObj, U: nullptr,
1096 DumpOpts: LLDumpOpts,
1097 /*Indent=*/0);
1098 OS << "\n";
1099 } else {
1100 Loc.dumpRange(StartOffset: 0, Size: Data.getData().size(), OS, Obj: *DObj, DumpOpts: LLDumpOpts);
1101 }
1102 }
1103
1104 if (const std::optional<uint64_t> *Off =
1105 shouldDump(Explicit, ".debug_frame", DIDT_ID_DebugFrame,
1106 DObj->getFrameSection().Data)) {
1107 if (Expected<const DWARFDebugFrame *> DF = getDebugFrame())
1108 (*DF)->dump(OS, DumpOpts, Offset: *Off);
1109 else
1110 RecoverableErrorHandler(DF.takeError());
1111 }
1112
1113 if (const std::optional<uint64_t> *Off =
1114 shouldDump(Explicit, ".eh_frame", DIDT_ID_DebugFrame,
1115 DObj->getEHFrameSection().Data)) {
1116 if (Expected<const DWARFDebugFrame *> DF = getEHFrame())
1117 (*DF)->dump(OS, DumpOpts, Offset: *Off);
1118 else
1119 RecoverableErrorHandler(DF.takeError());
1120 }
1121
1122 if (shouldDump(Explicit, ".debug_macro", DIDT_ID_DebugMacro,
1123 DObj->getMacroSection().Data)) {
1124 if (auto Macro = getDebugMacro())
1125 Macro->dump(OS);
1126 }
1127
1128 if (shouldDump(Explicit, ".debug_macro.dwo", DIDT_ID_DebugMacro,
1129 DObj->getMacroDWOSection())) {
1130 if (auto MacroDWO = getDebugMacroDWO())
1131 MacroDWO->dump(OS);
1132 }
1133
1134 if (shouldDump(Explicit, ".debug_macinfo", DIDT_ID_DebugMacro,
1135 DObj->getMacinfoSection())) {
1136 if (auto Macinfo = getDebugMacinfo())
1137 Macinfo->dump(OS);
1138 }
1139
1140 if (shouldDump(Explicit, ".debug_macinfo.dwo", DIDT_ID_DebugMacro,
1141 DObj->getMacinfoDWOSection())) {
1142 if (auto MacinfoDWO = getDebugMacinfoDWO())
1143 MacinfoDWO->dump(OS);
1144 }
1145
1146 if (shouldDump(Explicit, ".debug_aranges", DIDT_ID_DebugAranges,
1147 DObj->getArangesSection())) {
1148 uint64_t offset = 0;
1149 DWARFDataExtractor arangesData(DObj->getArangesSection(), isLittleEndian(),
1150 0);
1151 DWARFDebugArangeSet set;
1152 while (arangesData.isValidOffset(offset)) {
1153 if (Error E =
1154 set.extract(data: arangesData, offset_ptr: &offset, WarningHandler: DumpOpts.WarningHandler)) {
1155 RecoverableErrorHandler(std::move(E));
1156 break;
1157 }
1158 set.dump(OS);
1159 }
1160 }
1161
1162 auto DumpLineSection = [&](DWARFDebugLine::SectionParser Parser,
1163 DIDumpOptions DumpOpts,
1164 std::optional<uint64_t> DumpOffset) {
1165 while (!Parser.done()) {
1166 if (DumpOffset && Parser.getOffset() != *DumpOffset) {
1167 Parser.skip(RecoverableErrorHandler: DumpOpts.WarningHandler, UnrecoverableErrorHandler: DumpOpts.WarningHandler);
1168 continue;
1169 }
1170 OS << "debug_line[" << formatv(Fmt: "{0:x8}", Vals: Parser.getOffset()) << "]\n";
1171 Parser.parseNext(RecoverableErrorHandler: DumpOpts.WarningHandler, UnrecoverableErrorHandler: DumpOpts.WarningHandler, OS: &OS,
1172 Verbose: DumpOpts.Verbose);
1173 }
1174 };
1175
1176 auto DumpStrSection = [&](StringRef Section) {
1177 DataExtractor StrData(Section, isLittleEndian());
1178 uint64_t Offset = 0;
1179 uint64_t StrOffset = 0;
1180 while (StrData.isValidOffset(offset: Offset)) {
1181 Error Err = Error::success();
1182 const char *CStr = StrData.getCStr(OffsetPtr: &Offset, Err: &Err);
1183 if (Err) {
1184 DumpOpts.WarningHandler(std::move(Err));
1185 return;
1186 }
1187 OS << formatv(Fmt: "{0:x8}: \"", Vals&: StrOffset);
1188 OS.write_escaped(Str: CStr);
1189 OS << "\"\n";
1190 StrOffset = Offset;
1191 }
1192 };
1193
1194 if (const auto *Off = shouldDump(Explicit, ".debug_line", DIDT_ID_DebugLine,
1195 DObj->getLineSection().Data)) {
1196 DWARFDataExtractor LineData(*DObj, DObj->getLineSection(), isLittleEndian(),
1197 0);
1198 DWARFDebugLine::SectionParser Parser(LineData, *this, normal_units());
1199 DumpLineSection(Parser, DumpOpts, *Off);
1200 }
1201
1202 if (const auto *Off =
1203 shouldDump(ExplicitDWO, ".debug_line.dwo", DIDT_ID_DebugLine,
1204 DObj->getLineDWOSection().Data)) {
1205 DWARFDataExtractor LineData(*DObj, DObj->getLineDWOSection(),
1206 isLittleEndian(), 0);
1207 DWARFDebugLine::SectionParser Parser(LineData, *this, dwo_units());
1208 DumpLineSection(Parser, DumpOpts, *Off);
1209 }
1210
1211 if (shouldDump(Explicit, ".debug_cu_index", DIDT_ID_DebugCUIndex,
1212 DObj->getCUIndexSection())) {
1213 getCUIndex().dump(OS);
1214 }
1215
1216 if (shouldDump(Explicit, ".debug_tu_index", DIDT_ID_DebugTUIndex,
1217 DObj->getTUIndexSection())) {
1218 getTUIndex().dump(OS);
1219 }
1220
1221 if (shouldDump(Explicit, ".debug_str", DIDT_ID_DebugStr,
1222 DObj->getStrSection()))
1223 DumpStrSection(DObj->getStrSection());
1224
1225 if (shouldDump(ExplicitDWO, ".debug_str.dwo", DIDT_ID_DebugStr,
1226 DObj->getStrDWOSection()))
1227 DumpStrSection(DObj->getStrDWOSection());
1228
1229 if (shouldDump(Explicit, ".debug_line_str", DIDT_ID_DebugLineStr,
1230 DObj->getLineStrSection()))
1231 DumpStrSection(DObj->getLineStrSection());
1232
1233 if (shouldDump(Explicit, ".debug_addr", DIDT_ID_DebugAddr,
1234 DObj->getAddrSection().Data)) {
1235 DWARFDataExtractor AddrData(*DObj, DObj->getAddrSection(),
1236 isLittleEndian(), 0);
1237 dumpAddrSection(OS, AddrData, DumpOpts, Version: getMaxVersion(), AddrSize: getCUAddrSize());
1238 }
1239
1240 if (shouldDump(Explicit, ".debug_ranges", DIDT_ID_DebugRanges,
1241 DObj->getRangesSection().Data)) {
1242 uint8_t savedAddressByteSize = getCUAddrSize();
1243 DWARFDataExtractor rangesData(*DObj, DObj->getRangesSection(),
1244 isLittleEndian(), savedAddressByteSize);
1245 uint64_t offset = 0;
1246 DWARFDebugRangeList rangeList;
1247 while (rangesData.isValidOffset(offset)) {
1248 if (Error E = rangeList.extract(data: rangesData, offset_ptr: &offset)) {
1249 DumpOpts.RecoverableErrorHandler(std::move(E));
1250 break;
1251 }
1252 rangeList.dump(OS);
1253 }
1254 }
1255
1256 auto LookupPooledAddress =
1257 [&](uint32_t Index) -> std::optional<SectionedAddress> {
1258 const auto &CUs = compile_units();
1259 auto I = CUs.begin();
1260 if (I == CUs.end())
1261 return std::nullopt;
1262 return (*I)->getAddrOffsetSectionItem(Index);
1263 };
1264
1265 if (shouldDump(Explicit, ".debug_rnglists", DIDT_ID_DebugRnglists,
1266 DObj->getRnglistsSection().Data)) {
1267 DWARFDataExtractor RnglistData(*DObj, DObj->getRnglistsSection(),
1268 isLittleEndian(), 0);
1269 dumpRnglistsSection(OS, rnglistData&: RnglistData, LookupPooledAddress, DumpOpts);
1270 }
1271
1272 if (shouldDump(ExplicitDWO, ".debug_rnglists.dwo", DIDT_ID_DebugRnglists,
1273 DObj->getRnglistsDWOSection().Data)) {
1274 DWARFDataExtractor RnglistData(*DObj, DObj->getRnglistsDWOSection(),
1275 isLittleEndian(), 0);
1276 dumpRnglistsSection(OS, rnglistData&: RnglistData, LookupPooledAddress, DumpOpts);
1277 }
1278
1279 if (shouldDump(Explicit, ".debug_pubnames", DIDT_ID_DebugPubnames,
1280 DObj->getPubnamesSection().Data)) {
1281 DWARFDataExtractor PubTableData(*DObj, DObj->getPubnamesSection(),
1282 isLittleEndian(), 0);
1283 dumpPubTableSection(OS, DumpOpts, Data: PubTableData, /*GnuStyle=*/false);
1284 }
1285
1286 if (shouldDump(Explicit, ".debug_pubtypes", DIDT_ID_DebugPubtypes,
1287 DObj->getPubtypesSection().Data)) {
1288 DWARFDataExtractor PubTableData(*DObj, DObj->getPubtypesSection(),
1289 isLittleEndian(), 0);
1290 dumpPubTableSection(OS, DumpOpts, Data: PubTableData, /*GnuStyle=*/false);
1291 }
1292
1293 if (shouldDump(Explicit, ".debug_gnu_pubnames", DIDT_ID_DebugGnuPubnames,
1294 DObj->getGnuPubnamesSection().Data)) {
1295 DWARFDataExtractor PubTableData(*DObj, DObj->getGnuPubnamesSection(),
1296 isLittleEndian(), 0);
1297 dumpPubTableSection(OS, DumpOpts, Data: PubTableData, /*GnuStyle=*/true);
1298 }
1299
1300 if (shouldDump(Explicit, ".debug_gnu_pubtypes", DIDT_ID_DebugGnuPubtypes,
1301 DObj->getGnuPubtypesSection().Data)) {
1302 DWARFDataExtractor PubTableData(*DObj, DObj->getGnuPubtypesSection(),
1303 isLittleEndian(), 0);
1304 dumpPubTableSection(OS, DumpOpts, Data: PubTableData, /*GnuStyle=*/true);
1305 }
1306
1307 if (shouldDump(Explicit, ".debug_str_offsets", DIDT_ID_DebugStrOffsets,
1308 DObj->getStrOffsetsSection().Data))
1309 dumpStringOffsetsSection(
1310 OS, DumpOpts, SectionName: "debug_str_offsets", Obj: *DObj, StringOffsetsSection: DObj->getStrOffsetsSection(),
1311 StringSection: DObj->getStrSection(), Units: normal_units(), LittleEndian: isLittleEndian());
1312 if (shouldDump(ExplicitDWO, ".debug_str_offsets.dwo", DIDT_ID_DebugStrOffsets,
1313 DObj->getStrOffsetsDWOSection().Data))
1314 dumpStringOffsetsSection(OS, DumpOpts, SectionName: "debug_str_offsets.dwo", Obj: *DObj,
1315 StringOffsetsSection: DObj->getStrOffsetsDWOSection(),
1316 StringSection: DObj->getStrDWOSection(), Units: dwo_units(),
1317 LittleEndian: isLittleEndian());
1318
1319 if (shouldDump(Explicit, ".gdb_index", DIDT_ID_GdbIndex,
1320 DObj->getGdbIndexSection())) {
1321 getGdbIndex().dump(OS);
1322 }
1323
1324 if (shouldDump(Explicit, ".apple_names", DIDT_ID_AppleNames,
1325 DObj->getAppleNamesSection().Data))
1326 getAppleNames().dump(OS);
1327
1328 if (shouldDump(Explicit, ".apple_types", DIDT_ID_AppleTypes,
1329 DObj->getAppleTypesSection().Data))
1330 getAppleTypes().dump(OS);
1331
1332 if (shouldDump(Explicit, ".apple_namespaces", DIDT_ID_AppleNamespaces,
1333 DObj->getAppleNamespacesSection().Data))
1334 getAppleNamespaces().dump(OS);
1335
1336 if (shouldDump(Explicit, ".apple_objc", DIDT_ID_AppleObjC,
1337 DObj->getAppleObjCSection().Data))
1338 getAppleObjC().dump(OS);
1339 if (shouldDump(Explicit, ".debug_names", DIDT_ID_DebugNames,
1340 DObj->getNamesSection().Data))
1341 getDebugNames().dump(OS);
1342}
1343
1344DWARFTypeUnit *DWARFContext::getTypeUnitForHash(uint64_t Hash, bool IsDWO) {
1345 DWARFUnitVector &DWOUnits = State->getDWOUnits();
1346 if (const auto &TUI = getTUIndex()) {
1347 if (const auto *R = TUI.getFromHash(Offset: Hash)) {
1348 if (TUI.getVersion() >= 5) {
1349 return dyn_cast_or_null<DWARFTypeUnit>(
1350 Val: DWOUnits.getUnitForIndexEntry(E: *R, Sec: DW_SECT_INFO));
1351 } else {
1352 DWARFUnit *TypesUnit = nullptr;
1353 getDWARFObj().forEachTypesDWOSections(F: [&](const DWARFSection &S) {
1354 if (!TypesUnit)
1355 TypesUnit =
1356 DWOUnits.getUnitForIndexEntry(E: *R, Sec: DW_SECT_EXT_TYPES, Section: &S);
1357 });
1358 return dyn_cast_or_null<DWARFTypeUnit>(Val: TypesUnit);
1359 }
1360 }
1361 return nullptr;
1362 }
1363 return State->getTypeUnitMap(IsDWO).lookup(Val: Hash);
1364}
1365
1366DWARFCompileUnit *DWARFContext::getDWOCompileUnitForHash(uint64_t Hash) {
1367 DWARFUnitVector &DWOUnits = State->getDWOUnits(Lazy: LazyParse);
1368
1369 if (const auto &CUI = getCUIndex()) {
1370 if (const auto *R = CUI.getFromHash(Offset: Hash))
1371 return dyn_cast_or_null<DWARFCompileUnit>(
1372 Val: DWOUnits.getUnitForIndexEntry(E: *R, Sec: DW_SECT_INFO));
1373 return nullptr;
1374 }
1375
1376 // If there's no index, just search through the CUs in the DWO - there's
1377 // probably only one unless this is something like LTO - though an in-process
1378 // built/cached lookup table could be used in that case to improve repeated
1379 // lookups of different CUs in the DWO.
1380 for (const auto &DWOCU : dwo_compile_units()) {
1381 // Might not have parsed DWO ID yet.
1382 if (!DWOCU->getDWOId()) {
1383 if (std::optional<uint64_t> DWOId =
1384 toUnsigned(V: DWOCU->getUnitDIE().find(Attr: DW_AT_GNU_dwo_id)))
1385 DWOCU->setDWOId(*DWOId);
1386 else
1387 // No DWO ID?
1388 continue;
1389 }
1390 if (DWOCU->getDWOId() == Hash)
1391 return dyn_cast<DWARFCompileUnit>(Val: DWOCU.get());
1392 }
1393 return nullptr;
1394}
1395
1396DWARFDie DWARFContext::getDIEForOffset(uint64_t Offset) {
1397 if (auto *CU = State->getNormalUnits().getUnitForOffset(Offset))
1398 return CU->getDIEForOffset(Offset);
1399 return DWARFDie();
1400}
1401
1402bool DWARFContext::verify(raw_ostream &OS, DIDumpOptions DumpOpts) {
1403 bool Success = true;
1404 DWARFVerifier verifier(OS, *this, DumpOpts);
1405
1406 Success &= verifier.handleDebugAbbrev();
1407 if (DumpOpts.DumpType & DIDT_DebugCUIndex)
1408 Success &= verifier.handleDebugCUIndex();
1409 if (DumpOpts.DumpType & DIDT_DebugTUIndex)
1410 Success &= verifier.handleDebugTUIndex();
1411 if (DumpOpts.DumpType & DIDT_DebugInfo)
1412 Success &= verifier.handleDebugInfo();
1413 if (DumpOpts.DumpType & DIDT_DebugLine)
1414 Success &= verifier.handleDebugLine();
1415 if (DumpOpts.DumpType & DIDT_DebugStrOffsets)
1416 Success &= verifier.handleDebugStrOffsets();
1417 Success &= verifier.handleAccelTables();
1418 verifier.summarize();
1419 return Success;
1420}
1421
1422const DWARFUnitIndex &DWARFContext::getCUIndex() {
1423 return State->getCUIndex();
1424}
1425
1426const DWARFUnitIndex &DWARFContext::getTUIndex() {
1427 return State->getTUIndex();
1428}
1429
1430DWARFGdbIndex &DWARFContext::getGdbIndex() {
1431 return State->getGdbIndex();
1432}
1433
1434const DWARFDebugAbbrev *DWARFContext::getDebugAbbrev() {
1435 return State->getDebugAbbrev();
1436}
1437
1438const DWARFDebugAbbrev *DWARFContext::getDebugAbbrevDWO() {
1439 return State->getDebugAbbrevDWO();
1440}
1441
1442const DWARFDebugLoc *DWARFContext::getDebugLoc() {
1443 return State->getDebugLoc();
1444}
1445
1446const DWARFDebugAranges *DWARFContext::getDebugAranges() {
1447 return State->getDebugAranges();
1448}
1449
1450Expected<const DWARFDebugFrame *> DWARFContext::getDebugFrame() {
1451 return State->getDebugFrame();
1452}
1453
1454Expected<const DWARFDebugFrame *> DWARFContext::getEHFrame() {
1455 return State->getEHFrame();
1456}
1457
1458const DWARFDebugMacro *DWARFContext::getDebugMacro() {
1459 return State->getDebugMacro();
1460}
1461
1462const DWARFDebugMacro *DWARFContext::getDebugMacroDWO() {
1463 return State->getDebugMacroDWO();
1464}
1465
1466const DWARFDebugMacro *DWARFContext::getDebugMacinfo() {
1467 return State->getDebugMacinfo();
1468}
1469
1470const DWARFDebugMacro *DWARFContext::getDebugMacinfoDWO() {
1471 return State->getDebugMacinfoDWO();
1472}
1473
1474
1475const DWARFDebugNames &DWARFContext::getDebugNames() {
1476 return State->getDebugNames();
1477}
1478
1479const AppleAcceleratorTable &DWARFContext::getAppleNames() {
1480 return State->getAppleNames();
1481}
1482
1483const AppleAcceleratorTable &DWARFContext::getAppleTypes() {
1484 return State->getAppleTypes();
1485}
1486
1487const AppleAcceleratorTable &DWARFContext::getAppleNamespaces() {
1488 return State->getAppleNamespaces();
1489}
1490
1491const AppleAcceleratorTable &DWARFContext::getAppleObjC() {
1492 return State->getAppleObjC();
1493}
1494
1495const DWARFDebugLine::LineTable *
1496DWARFContext::getLineTableForUnit(DWARFUnit *U) {
1497 Expected<const DWARFDebugLine::LineTable *> ExpectedLineTable =
1498 getLineTableForUnit(U, RecoverableErrorHandler: WarningHandler);
1499 if (!ExpectedLineTable) {
1500 WarningHandler(ExpectedLineTable.takeError());
1501 return nullptr;
1502 }
1503 return *ExpectedLineTable;
1504}
1505
1506Expected<const DWARFDebugLine::LineTable *> DWARFContext::getLineTableForUnit(
1507 DWARFUnit *U, function_ref<void(Error)> RecoverableErrorHandler) {
1508 return State->getLineTableForUnit(U, RecoverableErrHandler: RecoverableErrorHandler);
1509}
1510
1511void DWARFContext::clearLineTableForUnit(DWARFUnit *U) {
1512 return State->clearLineTableForUnit(U);
1513}
1514
1515DWARFUnitVector &DWARFContext::getDWOUnits(bool Lazy) {
1516 return State->getDWOUnits(Lazy);
1517}
1518
1519DWARFUnit *DWARFContext::getUnitForOffset(uint64_t Offset) {
1520 return State->getNormalUnits().getUnitForOffset(Offset);
1521}
1522
1523DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint64_t Offset) {
1524 return dyn_cast_or_null<DWARFCompileUnit>(Val: getUnitForOffset(Offset));
1525}
1526
1527DWARFCompileUnit *DWARFContext::getCompileUnitForCodeAddress(uint64_t Address) {
1528 uint64_t CUOffset = getDebugAranges()->findAddress(Address);
1529 return getCompileUnitForOffset(Offset: CUOffset);
1530}
1531
1532DWARFCompileUnit *DWARFContext::getCompileUnitForDataAddress(uint64_t Address) {
1533 uint64_t CUOffset = getDebugAranges()->findAddress(Address);
1534 if (DWARFCompileUnit *OffsetCU = getCompileUnitForOffset(Offset: CUOffset))
1535 return OffsetCU;
1536
1537 // Global variables are often missed by the above search, for one of two
1538 // reasons:
1539 // 1. .debug_aranges may not include global variables. On clang, it seems we
1540 // put the globals in the aranges, but this isn't true for gcc.
1541 // 2. Even if the global variable is in a .debug_arange, global variables
1542 // may not be captured in the [start, end) addresses described by the
1543 // parent compile unit.
1544 //
1545 // So, we walk the CU's and their child DI's manually, looking for the
1546 // specific global variable.
1547 for (std::unique_ptr<DWARFUnit> &CU : compile_units()) {
1548 if (CU->getVariableForAddress(Address)) {
1549 return static_cast<DWARFCompileUnit *>(CU.get());
1550 }
1551 }
1552 return nullptr;
1553}
1554
1555DWARFContext::DIEsForAddress DWARFContext::getDIEsForAddress(uint64_t Address,
1556 bool CheckDWO) {
1557 DIEsForAddress Result;
1558
1559 DWARFCompileUnit *CU = getCompileUnitForCodeAddress(Address);
1560 if (!CU)
1561 return Result;
1562
1563 if (CheckDWO) {
1564 // We were asked to check the DWO file and this debug information is more
1565 // complete that any information in the skeleton compile unit, so search the
1566 // DWO first to see if we have a match.
1567 DWARFDie CUDie = CU->getUnitDIE(ExtractUnitDIEOnly: false);
1568 DWARFDie CUDwoDie = CU->getNonSkeletonUnitDIE(ExtractUnitDIEOnly: false);
1569 if (CheckDWO && CUDwoDie && CUDie != CUDwoDie) {
1570 // We have a DWO file, lets search it.
1571 DWARFCompileUnit *CUDwo =
1572 dyn_cast_or_null<DWARFCompileUnit>(Val: CUDwoDie.getDwarfUnit());
1573 if (CUDwo) {
1574 Result.FunctionDIE = CUDwo->getSubroutineForAddress(Address);
1575 if (Result.FunctionDIE)
1576 Result.CompileUnit = CUDwo;
1577 }
1578 }
1579 }
1580
1581 // Search the normal DWARF if we didn't find a match in the DWO file or if
1582 // we didn't check the DWO file above.
1583 if (!Result) {
1584 Result.CompileUnit = CU;
1585 Result.FunctionDIE = CU->getSubroutineForAddress(Address);
1586 }
1587
1588 std::vector<DWARFDie> Worklist;
1589 Worklist.push_back(x: Result.FunctionDIE);
1590 while (!Worklist.empty()) {
1591 DWARFDie DIE = Worklist.back();
1592 Worklist.pop_back();
1593
1594 if (!DIE.isValid())
1595 continue;
1596
1597 if (DIE.getTag() == DW_TAG_lexical_block &&
1598 DIE.addressRangeContainsAddress(Address)) {
1599 Result.BlockDIE = DIE;
1600 break;
1601 }
1602
1603 append_range(C&: Worklist, R&: DIE);
1604 }
1605
1606 return Result;
1607}
1608
1609/// TODO: change input parameter from "uint64_t Address"
1610/// into "SectionedAddress Address"
1611static bool getFunctionNameAndStartLineForAddress(
1612 DWARFCompileUnit *CU, uint64_t Address, FunctionNameKind Kind,
1613 DILineInfoSpecifier::FileLineInfoKind FileNameKind,
1614 std::string &FunctionName, std::string &StartFile, uint32_t &StartLine,
1615 std::optional<uint64_t> &StartAddress) {
1616 // The address may correspond to instruction in some inlined function,
1617 // so we have to build the chain of inlined functions and take the
1618 // name of the topmost function in it.
1619 SmallVector<DWARFDie, 4> InlinedChain;
1620 CU->getInlinedChainForAddress(Address, InlinedChain);
1621 if (InlinedChain.empty())
1622 return false;
1623
1624 const DWARFDie &DIE = InlinedChain[0];
1625 bool FoundResult = false;
1626 const char *Name = nullptr;
1627 if (Kind != FunctionNameKind::None && (Name = DIE.getSubroutineName(Kind))) {
1628 FunctionName = Name;
1629 FoundResult = true;
1630 }
1631 std::string DeclFile = DIE.getDeclFile(Kind: FileNameKind);
1632 if (!DeclFile.empty()) {
1633 StartFile = DeclFile;
1634 FoundResult = true;
1635 }
1636 if (auto DeclLineResult = DIE.getDeclLine()) {
1637 StartLine = DeclLineResult;
1638 FoundResult = true;
1639 }
1640 if (auto LowPcAddr = toSectionedAddress(V: DIE.find(Attr: DW_AT_low_pc)))
1641 StartAddress = LowPcAddr->Address;
1642 return FoundResult;
1643}
1644
1645static std::optional<int64_t>
1646getExpressionFrameOffset(ArrayRef<uint8_t> Expr,
1647 std::optional<unsigned> FrameBaseReg) {
1648 if (!Expr.empty() &&
1649 (Expr[0] == DW_OP_fbreg ||
1650 (FrameBaseReg && Expr[0] == DW_OP_breg0 + *FrameBaseReg))) {
1651 unsigned Count;
1652 int64_t Offset = decodeSLEB128(p: Expr.data() + 1, n: &Count, end: Expr.end());
1653 // A single DW_OP_fbreg or DW_OP_breg.
1654 if (Expr.size() == Count + 1)
1655 return Offset;
1656 // Same + DW_OP_deref (Fortran arrays look like this).
1657 if (Expr.size() == Count + 2 && Expr[Count + 1] == DW_OP_deref)
1658 return Offset;
1659 // Fallthrough. Do not accept ex. (DW_OP_breg W29, DW_OP_stack_value)
1660 }
1661 return std::nullopt;
1662}
1663
1664void DWARFContext::addLocalsForDie(DWARFCompileUnit *CU, DWARFDie Subprogram,
1665 DWARFDie Die, std::vector<DILocal> &Result) {
1666 if (Die.getTag() == DW_TAG_variable ||
1667 Die.getTag() == DW_TAG_formal_parameter) {
1668 DILocal Local;
1669 if (const char *Name = Subprogram.getSubroutineName(Kind: DINameKind::ShortName))
1670 Local.FunctionName = Name;
1671
1672 std::optional<unsigned> FrameBaseReg;
1673 if (auto FrameBase = Subprogram.find(Attr: DW_AT_frame_base))
1674 if (std::optional<ArrayRef<uint8_t>> Expr = FrameBase->getAsBlock())
1675 if (!Expr->empty() && (*Expr)[0] >= DW_OP_reg0 &&
1676 (*Expr)[0] <= DW_OP_reg31) {
1677 FrameBaseReg = (*Expr)[0] - DW_OP_reg0;
1678 }
1679
1680 if (Expected<std::vector<DWARFLocationExpression>> Loc =
1681 Die.getLocations(Attr: DW_AT_location)) {
1682 for (const auto &Entry : *Loc) {
1683 if (std::optional<int64_t> FrameOffset =
1684 getExpressionFrameOffset(Expr: Entry.Expr, FrameBaseReg)) {
1685 Local.FrameOffset = *FrameOffset;
1686 break;
1687 }
1688 }
1689 } else {
1690 // FIXME: missing DW_AT_location is OK here, but other errors should be
1691 // reported to the user.
1692 consumeError(Err: Loc.takeError());
1693 }
1694
1695 if (auto TagOffsetAttr = Die.find(Attr: DW_AT_LLVM_tag_offset))
1696 Local.TagOffset = TagOffsetAttr->getAsUnsignedConstant();
1697
1698 if (auto Origin =
1699 Die.getAttributeValueAsReferencedDie(Attr: DW_AT_abstract_origin))
1700 Die = Origin;
1701 if (auto NameAttr = Die.find(Attr: DW_AT_name))
1702 if (std::optional<const char *> Name = dwarf::toString(V: *NameAttr))
1703 Local.Name = *Name;
1704 if (auto Type = Die.getAttributeValueAsReferencedDie(Attr: DW_AT_type))
1705 Local.Size = Type.getTypeSize(PointerSize: getCUAddrSize());
1706 if (auto DeclFileAttr = Die.find(Attr: DW_AT_decl_file)) {
1707 if (const auto *LT = CU->getContext().getLineTableForUnit(U: CU))
1708 LT->getFileNameByIndex(
1709 FileIndex: *DeclFileAttr->getAsUnsignedConstant(), CompDir: CU->getCompilationDir(),
1710 Kind: DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
1711 Result&: Local.DeclFile);
1712 }
1713 if (auto DeclLineAttr = Die.find(Attr: DW_AT_decl_line))
1714 Local.DeclLine = *DeclLineAttr->getAsUnsignedConstant();
1715
1716 Result.push_back(x: Local);
1717 return;
1718 }
1719
1720 if (Die.getTag() == DW_TAG_inlined_subroutine)
1721 if (auto Origin =
1722 Die.getAttributeValueAsReferencedDie(Attr: DW_AT_abstract_origin))
1723 Subprogram = Origin;
1724
1725 for (auto Child : Die)
1726 addLocalsForDie(CU, Subprogram, Die: Child, Result);
1727}
1728
1729std::vector<DILocal>
1730DWARFContext::getLocalsForAddress(object::SectionedAddress Address) {
1731 std::vector<DILocal> Result;
1732 DWARFCompileUnit *CU = getCompileUnitForCodeAddress(Address: Address.Address);
1733 if (!CU)
1734 return Result;
1735
1736 DWARFDie Subprogram = CU->getSubroutineForAddress(Address: Address.Address);
1737 if (Subprogram.isValid())
1738 addLocalsForDie(CU, Subprogram, Die: Subprogram, Result);
1739 return Result;
1740}
1741
1742std::optional<DILineInfo>
1743DWARFContext::getLineInfoForAddress(object::SectionedAddress Address,
1744 DILineInfoSpecifier Spec) {
1745 DWARFCompileUnit *CU = getCompileUnitForCodeAddress(Address: Address.Address);
1746 if (!CU)
1747 return std::nullopt;
1748
1749 DILineInfo Result;
1750 getFunctionNameAndStartLineForAddress(
1751 CU, Address: Address.Address, Kind: Spec.FNKind, FileNameKind: Spec.FLIKind, FunctionName&: Result.FunctionName,
1752 StartFile&: Result.StartFileName, StartLine&: Result.StartLine, StartAddress&: Result.StartAddress);
1753 if (Spec.FLIKind != FileLineInfoKind::None) {
1754 if (const DWARFLineTable *LineTable = getLineTableForUnit(U: CU)) {
1755 LineTable->getFileLineInfoForAddress(
1756 Address: {.Address: Address.Address, .SectionIndex: Address.SectionIndex}, Approximate: Spec.ApproximateLine,
1757 CompDir: CU->getCompilationDir(), Kind: Spec.FLIKind, Result);
1758 }
1759 }
1760
1761 return Result;
1762}
1763
1764std::optional<DILineInfo>
1765DWARFContext::getLineInfoForDataAddress(object::SectionedAddress Address) {
1766 DILineInfo Result;
1767 DWARFCompileUnit *CU = getCompileUnitForDataAddress(Address: Address.Address);
1768 if (!CU)
1769 return Result;
1770
1771 if (DWARFDie Die = CU->getVariableForAddress(Address: Address.Address)) {
1772 Result.FileName = Die.getDeclFile(Kind: FileLineInfoKind::AbsoluteFilePath);
1773 Result.Line = Die.getDeclLine();
1774 }
1775
1776 return Result;
1777}
1778
1779DILineInfoTable DWARFContext::getLineInfoForAddressRange(
1780 object::SectionedAddress Address, uint64_t Size, DILineInfoSpecifier Spec) {
1781 DILineInfoTable Lines;
1782 DWARFCompileUnit *CU = getCompileUnitForCodeAddress(Address: Address.Address);
1783 if (!CU)
1784 return Lines;
1785
1786 uint32_t StartLine = 0;
1787 std::string StartFileName;
1788 std::string FunctionName(DILineInfo::BadString);
1789 std::optional<uint64_t> StartAddress;
1790 getFunctionNameAndStartLineForAddress(CU, Address: Address.Address, Kind: Spec.FNKind,
1791 FileNameKind: Spec.FLIKind, FunctionName,
1792 StartFile&: StartFileName, StartLine, StartAddress);
1793
1794 // If the Specifier says we don't need FileLineInfo, just
1795 // return the top-most function at the starting address.
1796 if (Spec.FLIKind == FileLineInfoKind::None) {
1797 DILineInfo Result;
1798 Result.FunctionName = FunctionName;
1799 Result.StartFileName = StartFileName;
1800 Result.StartLine = StartLine;
1801 Result.StartAddress = StartAddress;
1802 Lines.push_back(Elt: std::make_pair(x&: Address.Address, y&: Result));
1803 return Lines;
1804 }
1805
1806 const DWARFLineTable *LineTable = getLineTableForUnit(U: CU);
1807
1808 // Get the index of row we're looking for in the line table.
1809 std::vector<uint32_t> RowVector;
1810 if (!LineTable->lookupAddressRange(Address: {.Address: Address.Address, .SectionIndex: Address.SectionIndex},
1811 Size, Result&: RowVector)) {
1812 return Lines;
1813 }
1814
1815 for (uint32_t RowIndex : RowVector) {
1816 // Take file number and line/column from the row.
1817 const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
1818 DILineInfo Result;
1819 LineTable->getFileNameByIndex(FileIndex: Row.File, CompDir: CU->getCompilationDir(),
1820 Kind: Spec.FLIKind, Result&: Result.FileName);
1821 Result.FunctionName = FunctionName;
1822 Result.Line = Row.Line;
1823 Result.Column = Row.Column;
1824 Result.StartFileName = StartFileName;
1825 Result.StartLine = StartLine;
1826 Result.StartAddress = StartAddress;
1827 Lines.push_back(Elt: std::make_pair(x: Row.Address.Address, y&: Result));
1828 }
1829
1830 return Lines;
1831}
1832
1833DIInliningInfo
1834DWARFContext::getInliningInfoForAddress(object::SectionedAddress Address,
1835 DILineInfoSpecifier Spec) {
1836 DIInliningInfo InliningInfo;
1837
1838 DWARFCompileUnit *CU = getCompileUnitForCodeAddress(Address: Address.Address);
1839 if (!CU)
1840 return InliningInfo;
1841
1842 const DWARFLineTable *LineTable = nullptr;
1843 SmallVector<DWARFDie, 4> InlinedChain;
1844 CU->getInlinedChainForAddress(Address: Address.Address, InlinedChain);
1845 if (InlinedChain.size() == 0) {
1846 // If there is no DIE for address (e.g. it is in unavailable .dwo file),
1847 // try to at least get file/line info from symbol table.
1848 if (Spec.FLIKind != FileLineInfoKind::None) {
1849 DILineInfo Frame;
1850 LineTable = getLineTableForUnit(U: CU);
1851 if (LineTable &&
1852 LineTable->getFileLineInfoForAddress(
1853 Address: {.Address: Address.Address, .SectionIndex: Address.SectionIndex}, Approximate: Spec.ApproximateLine,
1854 CompDir: CU->getCompilationDir(), Kind: Spec.FLIKind, Result&: Frame))
1855 InliningInfo.addFrame(Frame);
1856 }
1857 return InliningInfo;
1858 }
1859
1860 uint32_t CallFile = 0, CallLine = 0, CallColumn = 0, CallDiscriminator = 0;
1861 for (uint32_t i = 0, n = InlinedChain.size(); i != n; i++) {
1862 DWARFDie &FunctionDIE = InlinedChain[i];
1863 DILineInfo Frame;
1864 // Get function name if necessary.
1865 if (const char *Name = FunctionDIE.getSubroutineName(Kind: Spec.FNKind))
1866 Frame.FunctionName = Name;
1867 if (auto DeclLineResult = FunctionDIE.getDeclLine())
1868 Frame.StartLine = DeclLineResult;
1869 Frame.StartFileName = FunctionDIE.getDeclFile(Kind: Spec.FLIKind);
1870 if (auto LowPcAddr = toSectionedAddress(V: FunctionDIE.find(Attr: DW_AT_low_pc)))
1871 Frame.StartAddress = LowPcAddr->Address;
1872 if (Spec.FLIKind != FileLineInfoKind::None) {
1873 if (i == 0) {
1874 // For the topmost frame, initialize the line table of this
1875 // compile unit and fetch file/line info from it.
1876 LineTable = getLineTableForUnit(U: CU);
1877 // For the topmost routine, get file/line info from line table.
1878 if (LineTable)
1879 LineTable->getFileLineInfoForAddress(
1880 Address: {.Address: Address.Address, .SectionIndex: Address.SectionIndex}, Approximate: Spec.ApproximateLine,
1881 CompDir: CU->getCompilationDir(), Kind: Spec.FLIKind, Result&: Frame);
1882 } else {
1883 // Otherwise, use call file, call line and call column from
1884 // previous DIE in inlined chain.
1885 if (LineTable)
1886 LineTable->getFileNameByIndex(FileIndex: CallFile, CompDir: CU->getCompilationDir(),
1887 Kind: Spec.FLIKind, Result&: Frame.FileName);
1888 Frame.Line = CallLine;
1889 Frame.Column = CallColumn;
1890 Frame.Discriminator = CallDiscriminator;
1891 }
1892 // Get call file/line/column of a current DIE.
1893 if (i + 1 < n) {
1894 FunctionDIE.getCallerFrame(CallFile, CallLine, CallColumn,
1895 CallDiscriminator);
1896 }
1897 }
1898 InliningInfo.addFrame(Frame);
1899 }
1900 return InliningInfo;
1901}
1902
1903std::shared_ptr<DWARFContext>
1904DWARFContext::getDWOContext(StringRef AbsolutePath) {
1905 return State->getDWOContext(AbsolutePath);
1906}
1907
1908static Error createError(const Twine &Reason, llvm::Error E) {
1909 return make_error<StringError>(Args: Reason + toString(E: std::move(E)),
1910 Args: inconvertibleErrorCode());
1911}
1912
1913/// SymInfo contains information about symbol: it's address
1914/// and section index which is -1LL for absolute symbols.
1915struct SymInfo {
1916 uint64_t Address = 0;
1917 uint64_t SectionIndex = 0;
1918};
1919
1920/// Returns the address of symbol relocation used against and a section index.
1921/// Used for futher relocations computation. Symbol's section load address is
1922static Expected<SymInfo> getSymbolInfo(const object::ObjectFile &Obj,
1923 const RelocationRef &Reloc,
1924 const LoadedObjectInfo *L,
1925 std::map<SymbolRef, SymInfo> &Cache) {
1926 SymInfo Ret = {.Address: 0, .SectionIndex: (uint64_t)-1LL};
1927 object::section_iterator RSec = Obj.section_end();
1928 object::symbol_iterator Sym = Reloc.getSymbol();
1929
1930 std::map<SymbolRef, SymInfo>::iterator CacheIt = Cache.end();
1931 // First calculate the address of the symbol or section as it appears
1932 // in the object file
1933 if (Sym != Obj.symbol_end()) {
1934 bool New;
1935 std::tie(args&: CacheIt, args&: New) = Cache.try_emplace(k: *Sym);
1936 if (!New)
1937 return CacheIt->second;
1938
1939 Expected<uint64_t> SymAddrOrErr = Sym->getAddress();
1940 if (!SymAddrOrErr)
1941 return createError(Reason: "failed to compute symbol address: ",
1942 E: SymAddrOrErr.takeError());
1943
1944 // Also remember what section this symbol is in for later
1945 auto SectOrErr = Sym->getSection();
1946 if (!SectOrErr)
1947 return createError(Reason: "failed to get symbol section: ",
1948 E: SectOrErr.takeError());
1949
1950 RSec = *SectOrErr;
1951 Ret.Address = *SymAddrOrErr;
1952 } else if (auto *MObj = dyn_cast<MachOObjectFile>(Val: &Obj)) {
1953 RSec = MObj->getRelocationSection(Rel: Reloc.getRawDataRefImpl());
1954 Ret.Address = RSec->getAddress();
1955 }
1956
1957 if (RSec != Obj.section_end())
1958 Ret.SectionIndex = RSec->getIndex();
1959
1960 // If we are given load addresses for the sections, we need to adjust:
1961 // SymAddr = (Address of Symbol Or Section in File) -
1962 // (Address of Section in File) +
1963 // (Load Address of Section)
1964 // RSec is now either the section being targeted or the section
1965 // containing the symbol being targeted. In either case,
1966 // we need to perform the same computation.
1967 if (L && RSec != Obj.section_end())
1968 if (uint64_t SectionLoadAddress = L->getSectionLoadAddress(Sec: *RSec))
1969 Ret.Address += SectionLoadAddress - RSec->getAddress();
1970
1971 if (CacheIt != Cache.end())
1972 CacheIt->second = Ret;
1973
1974 return Ret;
1975}
1976
1977static bool isRelocScattered(const object::ObjectFile &Obj,
1978 const RelocationRef &Reloc) {
1979 const MachOObjectFile *MachObj = dyn_cast<MachOObjectFile>(Val: &Obj);
1980 if (!MachObj)
1981 return false;
1982 // MachO also has relocations that point to sections and
1983 // scattered relocations.
1984 auto RelocInfo = MachObj->getRelocation(Rel: Reloc.getRawDataRefImpl());
1985 return MachObj->isRelocationScattered(RE: RelocInfo);
1986}
1987
1988namespace {
1989struct DWARFSectionMap final : public DWARFSection {
1990 RelocAddrMap Relocs;
1991};
1992
1993class DWARFObjInMemory final : public DWARFObject {
1994 bool IsLittleEndian;
1995 uint8_t AddressSize;
1996 StringRef FileName;
1997 const object::ObjectFile *Obj = nullptr;
1998 std::vector<SectionName> SectionNames;
1999
2000 using InfoSectionMap = MapVector<object::SectionRef, DWARFSectionMap,
2001 std::map<object::SectionRef, unsigned>>;
2002
2003 InfoSectionMap InfoSections;
2004 InfoSectionMap TypesSections;
2005 InfoSectionMap InfoDWOSections;
2006 InfoSectionMap TypesDWOSections;
2007
2008 DWARFSectionMap LocSection;
2009 DWARFSectionMap LoclistsSection;
2010 DWARFSectionMap LoclistsDWOSection;
2011 DWARFSectionMap LineSection;
2012 DWARFSectionMap RangesSection;
2013 DWARFSectionMap RnglistsSection;
2014 DWARFSectionMap StrOffsetsSection;
2015 DWARFSectionMap LineDWOSection;
2016 DWARFSectionMap FrameSection;
2017 DWARFSectionMap EHFrameSection;
2018 DWARFSectionMap LocDWOSection;
2019 DWARFSectionMap StrOffsetsDWOSection;
2020 DWARFSectionMap RangesDWOSection;
2021 DWARFSectionMap RnglistsDWOSection;
2022 DWARFSectionMap AddrSection;
2023 DWARFSectionMap AppleNamesSection;
2024 DWARFSectionMap AppleTypesSection;
2025 DWARFSectionMap AppleNamespacesSection;
2026 DWARFSectionMap AppleObjCSection;
2027 DWARFSectionMap NamesSection;
2028 DWARFSectionMap PubnamesSection;
2029 DWARFSectionMap PubtypesSection;
2030 DWARFSectionMap GnuPubnamesSection;
2031 DWARFSectionMap GnuPubtypesSection;
2032 DWARFSectionMap MacroSection;
2033
2034 DWARFSectionMap *mapNameToDWARFSection(StringRef Name) {
2035 return StringSwitch<DWARFSectionMap *>(Name)
2036 .Case(S: "debug_loc", Value: &LocSection)
2037 .Case(S: "debug_loclists", Value: &LoclistsSection)
2038 .Case(S: "debug_loclists.dwo", Value: &LoclistsDWOSection)
2039 .Case(S: "debug_line", Value: &LineSection)
2040 .Case(S: "debug_frame", Value: &FrameSection)
2041 .Case(S: "eh_frame", Value: &EHFrameSection)
2042 .Case(S: "debug_str_offsets", Value: &StrOffsetsSection)
2043 .Case(S: "debug_ranges", Value: &RangesSection)
2044 .Case(S: "debug_rnglists", Value: &RnglistsSection)
2045 .Case(S: "debug_loc.dwo", Value: &LocDWOSection)
2046 .Case(S: "debug_line.dwo", Value: &LineDWOSection)
2047 .Case(S: "debug_names", Value: &NamesSection)
2048 .Case(S: "debug_rnglists.dwo", Value: &RnglistsDWOSection)
2049 .Case(S: "debug_str_offsets.dwo", Value: &StrOffsetsDWOSection)
2050 .Case(S: "debug_addr", Value: &AddrSection)
2051 .Case(S: "apple_names", Value: &AppleNamesSection)
2052 .Case(S: "debug_pubnames", Value: &PubnamesSection)
2053 .Case(S: "debug_pubtypes", Value: &PubtypesSection)
2054 .Case(S: "debug_gnu_pubnames", Value: &GnuPubnamesSection)
2055 .Case(S: "debug_gnu_pubtypes", Value: &GnuPubtypesSection)
2056 .Case(S: "apple_types", Value: &AppleTypesSection)
2057 .Case(S: "apple_namespaces", Value: &AppleNamespacesSection)
2058 .Case(S: "apple_namespac", Value: &AppleNamespacesSection)
2059 .Case(S: "apple_objc", Value: &AppleObjCSection)
2060 .Case(S: "debug_macro", Value: &MacroSection)
2061 .Default(Value: nullptr);
2062 }
2063
2064 StringRef AbbrevSection;
2065 StringRef ArangesSection;
2066 StringRef StrSection;
2067 StringRef MacinfoSection;
2068 StringRef MacinfoDWOSection;
2069 StringRef MacroDWOSection;
2070 StringRef AbbrevDWOSection;
2071 StringRef StrDWOSection;
2072 StringRef CUIndexSection;
2073 StringRef GdbIndexSection;
2074 StringRef TUIndexSection;
2075 StringRef LineStrSection;
2076
2077 // A deque holding section data whose iterators are not invalidated when
2078 // new decompressed sections are inserted at the end.
2079 std::deque<SmallString<0>> UncompressedSections;
2080
2081 StringRef *mapSectionToMember(StringRef Name) {
2082 if (DWARFSection *Sec = mapNameToDWARFSection(Name))
2083 return &Sec->Data;
2084 return StringSwitch<StringRef *>(Name)
2085 .Case(S: "debug_abbrev", Value: &AbbrevSection)
2086 .Case(S: "debug_aranges", Value: &ArangesSection)
2087 .Case(S: "debug_str", Value: &StrSection)
2088 .Case(S: "debug_macinfo", Value: &MacinfoSection)
2089 .Case(S: "debug_macinfo.dwo", Value: &MacinfoDWOSection)
2090 .Case(S: "debug_macro.dwo", Value: &MacroDWOSection)
2091 .Case(S: "debug_abbrev.dwo", Value: &AbbrevDWOSection)
2092 .Case(S: "debug_str.dwo", Value: &StrDWOSection)
2093 .Case(S: "debug_cu_index", Value: &CUIndexSection)
2094 .Case(S: "debug_tu_index", Value: &TUIndexSection)
2095 .Case(S: "gdb_index", Value: &GdbIndexSection)
2096 .Case(S: "debug_line_str", Value: &LineStrSection)
2097 // Any more debug info sections go here.
2098 .Default(Value: nullptr);
2099 }
2100
2101 /// If Sec is compressed section, decompresses and updates its contents
2102 /// provided by Data. Otherwise leaves it unchanged.
2103 Error maybeDecompress(const object::SectionRef &Sec, StringRef Name,
2104 StringRef &Data) {
2105 if (!Sec.isCompressed())
2106 return Error::success();
2107
2108 Expected<Decompressor> Decompressor =
2109 Decompressor::create(Name, Data, IsLE: IsLittleEndian, Is64Bit: AddressSize == 8);
2110 if (!Decompressor)
2111 return Decompressor.takeError();
2112
2113 SmallString<0> Out;
2114 if (auto Err = Decompressor->resizeAndDecompress(Out))
2115 return Err;
2116
2117 UncompressedSections.push_back(x: std::move(Out));
2118 Data = UncompressedSections.back();
2119
2120 return Error::success();
2121 }
2122
2123public:
2124 DWARFObjInMemory(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
2125 uint8_t AddrSize, bool IsLittleEndian)
2126 : IsLittleEndian(IsLittleEndian) {
2127 for (const auto &SecIt : Sections) {
2128 if (StringRef *SectionData = mapSectionToMember(Name: SecIt.first()))
2129 *SectionData = SecIt.second->getBuffer();
2130 else if (SecIt.first() == "debug_info")
2131 // Find debug_info and debug_types data by section rather than name as
2132 // there are multiple, comdat grouped, of these sections.
2133 InfoSections[SectionRef()].Data = SecIt.second->getBuffer();
2134 else if (SecIt.first() == "debug_info.dwo")
2135 InfoDWOSections[SectionRef()].Data = SecIt.second->getBuffer();
2136 else if (SecIt.first() == "debug_types")
2137 TypesSections[SectionRef()].Data = SecIt.second->getBuffer();
2138 else if (SecIt.first() == "debug_types.dwo")
2139 TypesDWOSections[SectionRef()].Data = SecIt.second->getBuffer();
2140 }
2141 }
2142 DWARFObjInMemory(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
2143 function_ref<void(Error)> HandleError,
2144 function_ref<void(Error)> HandleWarning,
2145 DWARFContext::ProcessDebugRelocations RelocAction)
2146 : IsLittleEndian(Obj.isLittleEndian()),
2147 AddressSize(Obj.getBytesInAddress()), FileName(Obj.getFileName()),
2148 Obj(&Obj) {
2149
2150 StringMap<unsigned> SectionAmountMap;
2151 for (const SectionRef &Section : Obj.sections()) {
2152 StringRef Name;
2153 if (auto NameOrErr = Section.getName())
2154 Name = *NameOrErr;
2155 else
2156 consumeError(Err: NameOrErr.takeError());
2157
2158 ++SectionAmountMap[Name];
2159 SectionNames.push_back(x: { .Name: Name, .IsNameUnique: true });
2160
2161 // Skip BSS and Virtual sections, they aren't interesting.
2162 if (Section.isBSS() || Section.isVirtual())
2163 continue;
2164
2165 // Skip sections stripped by dsymutil.
2166 if (Section.isStripped())
2167 continue;
2168
2169 StringRef Data;
2170 Expected<section_iterator> SecOrErr = Section.getRelocatedSection();
2171 if (!SecOrErr) {
2172 HandleError(createError(Reason: "failed to get relocated section: ",
2173 E: SecOrErr.takeError()));
2174 continue;
2175 }
2176
2177 // Try to obtain an already relocated version of this section.
2178 // Else use the unrelocated section from the object file. We'll have to
2179 // apply relocations ourselves later.
2180 section_iterator RelocatedSection =
2181 Obj.isRelocatableObject() ? *SecOrErr : Obj.section_end();
2182 if (!L || !L->getLoadedSectionContents(Sec: *RelocatedSection, Data)) {
2183 Expected<StringRef> E = Section.getContents();
2184 if (E)
2185 Data = *E;
2186 else
2187 // maybeDecompress below will error.
2188 consumeError(Err: E.takeError());
2189 }
2190
2191 if (auto Err = maybeDecompress(Sec: Section, Name, Data)) {
2192 HandleError(createError(Reason: "failed to decompress '" + Name + "', ",
2193 E: std::move(Err)));
2194 continue;
2195 }
2196
2197 // Map platform specific debug section names to DWARF standard section
2198 // names.
2199 Name = Name.substr(Start: Name.find_first_not_of(Chars: "._"));
2200 Name = Obj.mapDebugSectionName(Name);
2201
2202 if (StringRef *SectionData = mapSectionToMember(Name)) {
2203 *SectionData = Data;
2204 if (Name == "debug_ranges") {
2205 // FIXME: Use the other dwo range section when we emit it.
2206 RangesDWOSection.Data = Data;
2207 } else if (Name == "debug_frame" || Name == "eh_frame") {
2208 if (DWARFSection *S = mapNameToDWARFSection(Name))
2209 S->Address = Section.getAddress();
2210 }
2211 } else if (InfoSectionMap *Sections =
2212 StringSwitch<InfoSectionMap *>(Name)
2213 .Case(S: "debug_info", Value: &InfoSections)
2214 .Case(S: "debug_info.dwo", Value: &InfoDWOSections)
2215 .Case(S: "debug_types", Value: &TypesSections)
2216 .Case(S: "debug_types.dwo", Value: &TypesDWOSections)
2217 .Default(Value: nullptr)) {
2218 // Find debug_info and debug_types data by section rather than name as
2219 // there are multiple, comdat grouped, of these sections.
2220 DWARFSectionMap &S = (*Sections)[Section];
2221 S.Data = Data;
2222 }
2223
2224 if (RelocatedSection == Obj.section_end() ||
2225 (RelocAction == DWARFContext::ProcessDebugRelocations::Ignore))
2226 continue;
2227
2228 StringRef RelSecName;
2229 if (auto NameOrErr = RelocatedSection->getName())
2230 RelSecName = *NameOrErr;
2231 else
2232 consumeError(Err: NameOrErr.takeError());
2233
2234 // If the section we're relocating was relocated already by the JIT,
2235 // then we used the relocated version above, so we do not need to process
2236 // relocations for it now.
2237 StringRef RelSecData;
2238 if (L && L->getLoadedSectionContents(Sec: *RelocatedSection, Data&: RelSecData))
2239 continue;
2240
2241 // In Mach-o files, the relocations do not need to be applied if
2242 // there is no load offset to apply. The value read at the
2243 // relocation point already factors in the section address
2244 // (actually applying the relocations will produce wrong results
2245 // as the section address will be added twice).
2246 if (!L && isa<MachOObjectFile>(Val: &Obj))
2247 continue;
2248
2249 if (!Section.relocations().empty() && Name.ends_with(Suffix: ".dwo") &&
2250 RelSecName.starts_with(Prefix: ".debug")) {
2251 HandleWarning(createError(Err: "unexpected relocations for dwo section '" +
2252 RelSecName + "'"));
2253 }
2254
2255 // TODO: Add support for relocations in other sections as needed.
2256 // Record relocations for the debug_info and debug_line sections.
2257 RelSecName = RelSecName.substr(Start: RelSecName.find_first_not_of(Chars: "._"));
2258 DWARFSectionMap *Sec = mapNameToDWARFSection(Name: RelSecName);
2259 RelocAddrMap *Map = Sec ? &Sec->Relocs : nullptr;
2260 if (!Map) {
2261 // Find debug_info and debug_types relocs by section rather than name
2262 // as there are multiple, comdat grouped, of these sections.
2263 if (RelSecName == "debug_info")
2264 Map = &static_cast<DWARFSectionMap &>(InfoSections[*RelocatedSection])
2265 .Relocs;
2266 else if (RelSecName == "debug_types")
2267 Map =
2268 &static_cast<DWARFSectionMap &>(TypesSections[*RelocatedSection])
2269 .Relocs;
2270 else
2271 continue;
2272 }
2273
2274 if (Section.relocations().empty())
2275 continue;
2276
2277 // Symbol to [address, section index] cache mapping.
2278 std::map<SymbolRef, SymInfo> AddrCache;
2279 SupportsRelocation Supports;
2280 RelocationResolver Resolver;
2281 std::tie(args&: Supports, args&: Resolver) = getRelocationResolver(Obj);
2282 for (const RelocationRef &Reloc : Section.relocations()) {
2283 // FIXME: it's not clear how to correctly handle scattered
2284 // relocations.
2285 if (isRelocScattered(Obj, Reloc))
2286 continue;
2287
2288 Expected<SymInfo> SymInfoOrErr =
2289 getSymbolInfo(Obj, Reloc, L, Cache&: AddrCache);
2290 if (!SymInfoOrErr) {
2291 HandleError(SymInfoOrErr.takeError());
2292 continue;
2293 }
2294
2295 // Check if Resolver can handle this relocation type early so as not to
2296 // handle invalid cases in DWARFDataExtractor.
2297 //
2298 // TODO Don't store Resolver in every RelocAddrEntry.
2299 if (Supports && Supports(Reloc.getType())) {
2300 auto I = Map->try_emplace(
2301 Key: Reloc.getOffset(),
2302 Args: RelocAddrEntry{
2303 .SectionIndex: SymInfoOrErr->SectionIndex, .Reloc: Reloc, .SymbolValue: SymInfoOrErr->Address,
2304 .Reloc2: std::optional<object::RelocationRef>(), .SymbolValue2: 0, .Resolver: Resolver});
2305 // If we didn't successfully insert that's because we already had a
2306 // relocation for that offset. Store it as a second relocation in the
2307 // same RelocAddrEntry instead.
2308 if (!I.second) {
2309 RelocAddrEntry &entry = I.first->getSecond();
2310 if (entry.Reloc2) {
2311 HandleError(createError(
2312 Err: "At most two relocations per offset are supported"));
2313 }
2314 entry.Reloc2 = Reloc;
2315 entry.SymbolValue2 = SymInfoOrErr->Address;
2316 }
2317 } else {
2318 SmallString<32> Type;
2319 Reloc.getTypeName(Result&: Type);
2320 // FIXME: Support more relocations & change this to an error
2321 HandleWarning(
2322 createError(Reason: "failed to compute relocation: " + Type + ", ",
2323 E: errorCodeToError(EC: object_error::parse_failed)));
2324 }
2325 }
2326 }
2327
2328 for (SectionName &S : SectionNames)
2329 if (SectionAmountMap[S.Name] > 1)
2330 S.IsNameUnique = false;
2331 }
2332
2333 std::optional<RelocAddrEntry> find(const DWARFSection &S,
2334 uint64_t Pos) const override {
2335 auto &Sec = static_cast<const DWARFSectionMap &>(S);
2336 RelocAddrMap::const_iterator AI = Sec.Relocs.find(Val: Pos);
2337 if (AI == Sec.Relocs.end())
2338 return std::nullopt;
2339 return AI->second;
2340 }
2341
2342 const object::ObjectFile *getFile() const override { return Obj; }
2343
2344 ArrayRef<SectionName> getSectionNames() const override {
2345 return SectionNames;
2346 }
2347
2348 bool isLittleEndian() const override { return IsLittleEndian; }
2349 StringRef getAbbrevDWOSection() const override { return AbbrevDWOSection; }
2350 const DWARFSection &getLineDWOSection() const override {
2351 return LineDWOSection;
2352 }
2353 const DWARFSection &getLocDWOSection() const override {
2354 return LocDWOSection;
2355 }
2356 StringRef getStrDWOSection() const override { return StrDWOSection; }
2357 const DWARFSection &getStrOffsetsDWOSection() const override {
2358 return StrOffsetsDWOSection;
2359 }
2360 const DWARFSection &getRangesDWOSection() const override {
2361 return RangesDWOSection;
2362 }
2363 const DWARFSection &getRnglistsDWOSection() const override {
2364 return RnglistsDWOSection;
2365 }
2366 const DWARFSection &getLoclistsDWOSection() const override {
2367 return LoclistsDWOSection;
2368 }
2369 const DWARFSection &getAddrSection() const override { return AddrSection; }
2370 StringRef getCUIndexSection() const override { return CUIndexSection; }
2371 StringRef getGdbIndexSection() const override { return GdbIndexSection; }
2372 StringRef getTUIndexSection() const override { return TUIndexSection; }
2373
2374 // DWARF v5
2375 const DWARFSection &getStrOffsetsSection() const override {
2376 return StrOffsetsSection;
2377 }
2378 StringRef getLineStrSection() const override { return LineStrSection; }
2379
2380 // Sections for DWARF5 split dwarf proposal.
2381 void forEachInfoDWOSections(
2382 function_ref<void(const DWARFSection &)> F) const override {
2383 for (auto &P : InfoDWOSections)
2384 F(P.second);
2385 }
2386 void forEachTypesDWOSections(
2387 function_ref<void(const DWARFSection &)> F) const override {
2388 for (auto &P : TypesDWOSections)
2389 F(P.second);
2390 }
2391
2392 StringRef getAbbrevSection() const override { return AbbrevSection; }
2393 const DWARFSection &getLocSection() const override { return LocSection; }
2394 const DWARFSection &getLoclistsSection() const override { return LoclistsSection; }
2395 StringRef getArangesSection() const override { return ArangesSection; }
2396 const DWARFSection &getFrameSection() const override {
2397 return FrameSection;
2398 }
2399 const DWARFSection &getEHFrameSection() const override {
2400 return EHFrameSection;
2401 }
2402 const DWARFSection &getLineSection() const override { return LineSection; }
2403 StringRef getStrSection() const override { return StrSection; }
2404 const DWARFSection &getRangesSection() const override { return RangesSection; }
2405 const DWARFSection &getRnglistsSection() const override {
2406 return RnglistsSection;
2407 }
2408 const DWARFSection &getMacroSection() const override { return MacroSection; }
2409 StringRef getMacroDWOSection() const override { return MacroDWOSection; }
2410 StringRef getMacinfoSection() const override { return MacinfoSection; }
2411 StringRef getMacinfoDWOSection() const override { return MacinfoDWOSection; }
2412 const DWARFSection &getPubnamesSection() const override { return PubnamesSection; }
2413 const DWARFSection &getPubtypesSection() const override { return PubtypesSection; }
2414 const DWARFSection &getGnuPubnamesSection() const override {
2415 return GnuPubnamesSection;
2416 }
2417 const DWARFSection &getGnuPubtypesSection() const override {
2418 return GnuPubtypesSection;
2419 }
2420 const DWARFSection &getAppleNamesSection() const override {
2421 return AppleNamesSection;
2422 }
2423 const DWARFSection &getAppleTypesSection() const override {
2424 return AppleTypesSection;
2425 }
2426 const DWARFSection &getAppleNamespacesSection() const override {
2427 return AppleNamespacesSection;
2428 }
2429 const DWARFSection &getAppleObjCSection() const override {
2430 return AppleObjCSection;
2431 }
2432 const DWARFSection &getNamesSection() const override {
2433 return NamesSection;
2434 }
2435
2436 StringRef getFileName() const override { return FileName; }
2437 uint8_t getAddressSize() const override { return AddressSize; }
2438 void forEachInfoSections(
2439 function_ref<void(const DWARFSection &)> F) const override {
2440 for (auto &P : InfoSections)
2441 F(P.second);
2442 }
2443 void forEachTypesSections(
2444 function_ref<void(const DWARFSection &)> F) const override {
2445 for (auto &P : TypesSections)
2446 F(P.second);
2447 }
2448};
2449} // namespace
2450
2451std::unique_ptr<DWARFContext>
2452DWARFContext::create(const object::ObjectFile &Obj,
2453 ProcessDebugRelocations RelocAction,
2454 const LoadedObjectInfo *L, std::string DWPName,
2455 std::function<void(Error)> RecoverableErrorHandler,
2456 std::function<void(Error)> WarningHandler,
2457 bool ThreadSafe) {
2458 auto DObj = std::make_unique<DWARFObjInMemory>(
2459 args: Obj, args&: L, args&: RecoverableErrorHandler, args&: WarningHandler, args&: RelocAction);
2460 return std::make_unique<DWARFContext>(args: std::move(DObj),
2461 args: std::move(DWPName),
2462 args&: RecoverableErrorHandler,
2463 args&: WarningHandler,
2464 args&: ThreadSafe);
2465}
2466
2467std::unique_ptr<DWARFContext>
2468DWARFContext::create(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
2469 uint8_t AddrSize, bool isLittleEndian,
2470 std::function<void(Error)> RecoverableErrorHandler,
2471 std::function<void(Error)> WarningHandler,
2472 bool ThreadSafe) {
2473 auto DObj =
2474 std::make_unique<DWARFObjInMemory>(args: Sections, args&: AddrSize, args&: isLittleEndian);
2475 return std::make_unique<DWARFContext>(
2476 args: std::move(DObj), args: "", args&: RecoverableErrorHandler, args&: WarningHandler, args&: ThreadSafe);
2477}
2478
2479uint8_t DWARFContext::getCUAddrSize() {
2480 // In theory, different compile units may have different address byte
2481 // sizes, but for simplicity we just use the address byte size of the
2482 // first compile unit. In practice the address size field is repeated across
2483 // various DWARF headers (at least in version 5) to make it easier to dump
2484 // them independently, not to enable varying the address size.
2485 auto CUs = compile_units();
2486 return CUs.empty() ? 0 : (*CUs.begin())->getAddressByteSize();
2487}
2488
2489bool DWARFContext::isDWP() const { return !DObj->getCUIndexSection().empty(); }
2490