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