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