dwarfdump: First piece of support for DWP dumping
[oota-llvm.git] / lib / DebugInfo / DWARF / DWARFContext.cpp
1 //===-- DWARFContext.cpp --------------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
11 #include "llvm/ADT/SmallString.h"
12 #include "llvm/ADT/StringSwitch.h"
13 #include "llvm/DebugInfo/DWARF/DWARFAcceleratorTable.h"
14 #include "llvm/DebugInfo/DWARF/DWARFDebugArangeSet.h"
15 #include "llvm/DebugInfo/DWARF/DWARFUnitIndex.h"
16 #include "llvm/Support/Compression.h"
17 #include "llvm/Support/Dwarf.h"
18 #include "llvm/Support/Format.h"
19 #include "llvm/Support/Path.h"
20 #include "llvm/Support/raw_ostream.h"
21 #include <algorithm>
22 using namespace llvm;
23 using namespace dwarf;
24 using namespace object;
25
26 #define DEBUG_TYPE "dwarf"
27
28 typedef DWARFDebugLine::LineTable DWARFLineTable;
29 typedef DILineInfoSpecifier::FileLineInfoKind FileLineInfoKind;
30 typedef DILineInfoSpecifier::FunctionNameKind FunctionNameKind;
31
32 static void dumpPubSection(raw_ostream &OS, StringRef Name, StringRef Data,
33                            bool LittleEndian, bool GnuStyle) {
34   OS << "\n." << Name << " contents:\n";
35   DataExtractor pubNames(Data, LittleEndian, 0);
36   uint32_t offset = 0;
37   while (pubNames.isValidOffset(offset)) {
38     OS << "length = " << format("0x%08x", pubNames.getU32(&offset));
39     OS << " version = " << format("0x%04x", pubNames.getU16(&offset));
40     OS << " unit_offset = " << format("0x%08x", pubNames.getU32(&offset));
41     OS << " unit_size = " << format("0x%08x", pubNames.getU32(&offset)) << '\n';
42     if (GnuStyle)
43       OS << "Offset     Linkage  Kind     Name\n";
44     else
45       OS << "Offset     Name\n";
46
47     while (offset < Data.size()) {
48       uint32_t dieRef = pubNames.getU32(&offset);
49       if (dieRef == 0)
50         break;
51       OS << format("0x%8.8x ", dieRef);
52       if (GnuStyle) {
53         PubIndexEntryDescriptor desc(pubNames.getU8(&offset));
54         OS << format("%-8s", dwarf::GDBIndexEntryLinkageString(desc.Linkage))
55            << ' ' << format("%-8s", dwarf::GDBIndexEntryKindString(desc.Kind))
56            << ' ';
57       }
58       OS << '\"' << pubNames.getCStr(&offset) << "\"\n";
59     }
60   }
61 }
62
63 static void dumpAccelSection(raw_ostream &OS, StringRef Name,
64                              const DWARFSection& Section, StringRef StringSection,
65                              bool LittleEndian) {
66   DataExtractor AccelSection(Section.Data, LittleEndian, 0);
67   DataExtractor StrData(StringSection, LittleEndian, 0);
68   OS << "\n." << Name << " contents:\n";
69   DWARFAcceleratorTable Accel(AccelSection, StrData, Section.Relocs);
70   if (!Accel.extract())
71     return;
72   Accel.dump(OS);
73 }
74
75 void DWARFContext::dump(raw_ostream &OS, DIDumpType DumpType) {
76   if (DumpType == DIDT_All || DumpType == DIDT_Abbrev) {
77     OS << ".debug_abbrev contents:\n";
78     getDebugAbbrev()->dump(OS);
79   }
80
81   if (DumpType == DIDT_All || DumpType == DIDT_AbbrevDwo)
82     if (const DWARFDebugAbbrev *D = getDebugAbbrevDWO()) {
83       OS << "\n.debug_abbrev.dwo contents:\n";
84       D->dump(OS);
85     }
86
87   if (DumpType == DIDT_All || DumpType == DIDT_Info) {
88     OS << "\n.debug_info contents:\n";
89     for (const auto &CU : compile_units())
90       CU->dump(OS);
91   }
92
93   if ((DumpType == DIDT_All || DumpType == DIDT_InfoDwo) &&
94       getNumDWOCompileUnits()) {
95     OS << "\n.debug_info.dwo contents:\n";
96     for (const auto &DWOCU : dwo_compile_units())
97       DWOCU->dump(OS);
98   }
99
100   if ((DumpType == DIDT_All || DumpType == DIDT_Types) && getNumTypeUnits()) {
101     OS << "\n.debug_types contents:\n";
102     for (const auto &TUS : type_unit_sections())
103       for (const auto &TU : TUS)
104         TU->dump(OS);
105   }
106
107   if ((DumpType == DIDT_All || DumpType == DIDT_TypesDwo) &&
108       getNumDWOTypeUnits()) {
109     OS << "\n.debug_types.dwo contents:\n";
110     for (const auto &DWOTUS : dwo_type_unit_sections())
111       for (const auto &DWOTU : DWOTUS)
112         DWOTU->dump(OS);
113   }
114
115   if (DumpType == DIDT_All || DumpType == DIDT_Loc) {
116     OS << "\n.debug_loc contents:\n";
117     getDebugLoc()->dump(OS);
118   }
119
120   if (DumpType == DIDT_All || DumpType == DIDT_LocDwo) {
121     OS << "\n.debug_loc.dwo contents:\n";
122     getDebugLocDWO()->dump(OS);
123   }
124
125   if (DumpType == DIDT_All || DumpType == DIDT_Frames) {
126     OS << "\n.debug_frame contents:\n";
127     getDebugFrame()->dump(OS);
128   }
129
130   uint32_t offset = 0;
131   if (DumpType == DIDT_All || DumpType == DIDT_Aranges) {
132     OS << "\n.debug_aranges contents:\n";
133     DataExtractor arangesData(getARangeSection(), isLittleEndian(), 0);
134     DWARFDebugArangeSet set;
135     while (set.extract(arangesData, &offset))
136       set.dump(OS);
137   }
138
139   uint8_t savedAddressByteSize = 0;
140   if (DumpType == DIDT_All || DumpType == DIDT_Line) {
141     OS << "\n.debug_line contents:\n";
142     for (const auto &CU : compile_units()) {
143       savedAddressByteSize = CU->getAddressByteSize();
144       const auto *CUDIE = CU->getUnitDIE();
145       if (CUDIE == nullptr)
146         continue;
147       unsigned stmtOffset = CUDIE->getAttributeValueAsSectionOffset(
148           CU.get(), DW_AT_stmt_list, -1U);
149       if (stmtOffset != -1U) {
150         DataExtractor lineData(getLineSection().Data, isLittleEndian(),
151                                savedAddressByteSize);
152         DWARFDebugLine::LineTable LineTable;
153         LineTable.parse(lineData, &getLineSection().Relocs, &stmtOffset);
154         LineTable.dump(OS);
155       }
156     }
157   }
158
159   if (DumpType == DIDT_All || DumpType == DIDT_CUIndex) {
160     OS << "\n.debug_cu_index contents:\n";
161     DataExtractor CUIndexData(getCUIndexSection(), isLittleEndian(), savedAddressByteSize);
162     DWARFUnitIndex CUIndex;
163     CUIndex.parse(CUIndexData);
164     CUIndex.dump(OS);
165   }
166
167   if (DumpType == DIDT_All || DumpType == DIDT_LineDwo) {
168     OS << "\n.debug_line.dwo contents:\n";
169     unsigned stmtOffset = 0;
170     DataExtractor lineData(getLineDWOSection().Data, isLittleEndian(),
171                            savedAddressByteSize);
172     DWARFDebugLine::LineTable LineTable;
173     while (LineTable.Prologue.parse(lineData, &stmtOffset)) {
174       LineTable.dump(OS);
175       LineTable.clear();
176     }
177   }
178
179   if (DumpType == DIDT_All || DumpType == DIDT_Str) {
180     OS << "\n.debug_str contents:\n";
181     DataExtractor strData(getStringSection(), isLittleEndian(), 0);
182     offset = 0;
183     uint32_t strOffset = 0;
184     while (const char *s = strData.getCStr(&offset)) {
185       OS << format("0x%8.8x: \"%s\"\n", strOffset, s);
186       strOffset = offset;
187     }
188   }
189
190   if ((DumpType == DIDT_All || DumpType == DIDT_StrDwo) &&
191       !getStringDWOSection().empty()) {
192     OS << "\n.debug_str.dwo contents:\n";
193     DataExtractor strDWOData(getStringDWOSection(), isLittleEndian(), 0);
194     offset = 0;
195     uint32_t strDWOOffset = 0;
196     while (const char *s = strDWOData.getCStr(&offset)) {
197       OS << format("0x%8.8x: \"%s\"\n", strDWOOffset, s);
198       strDWOOffset = offset;
199     }
200   }
201
202   if (DumpType == DIDT_All || DumpType == DIDT_Ranges) {
203     OS << "\n.debug_ranges contents:\n";
204     // In fact, different compile units may have different address byte
205     // sizes, but for simplicity we just use the address byte size of the last
206     // compile unit (there is no easy and fast way to associate address range
207     // list and the compile unit it describes).
208     DataExtractor rangesData(getRangeSection(), isLittleEndian(),
209                              savedAddressByteSize);
210     offset = 0;
211     DWARFDebugRangeList rangeList;
212     while (rangeList.extract(rangesData, &offset))
213       rangeList.dump(OS);
214   }
215
216   if (DumpType == DIDT_All || DumpType == DIDT_Pubnames)
217     dumpPubSection(OS, "debug_pubnames", getPubNamesSection(),
218                    isLittleEndian(), false);
219
220   if (DumpType == DIDT_All || DumpType == DIDT_Pubtypes)
221     dumpPubSection(OS, "debug_pubtypes", getPubTypesSection(),
222                    isLittleEndian(), false);
223
224   if (DumpType == DIDT_All || DumpType == DIDT_GnuPubnames)
225     dumpPubSection(OS, "debug_gnu_pubnames", getGnuPubNamesSection(),
226                    isLittleEndian(), true /* GnuStyle */);
227
228   if (DumpType == DIDT_All || DumpType == DIDT_GnuPubtypes)
229     dumpPubSection(OS, "debug_gnu_pubtypes", getGnuPubTypesSection(),
230                    isLittleEndian(), true /* GnuStyle */);
231
232   if ((DumpType == DIDT_All || DumpType == DIDT_StrOffsetsDwo) &&
233       !getStringOffsetDWOSection().empty()) {
234     OS << "\n.debug_str_offsets.dwo contents:\n";
235     DataExtractor strOffsetExt(getStringOffsetDWOSection(), isLittleEndian(),
236                                0);
237     offset = 0;
238     uint64_t size = getStringOffsetDWOSection().size();
239     while (offset < size) {
240       OS << format("0x%8.8x: ", offset);
241       OS << format("%8.8x\n", strOffsetExt.getU32(&offset));
242     }
243   }
244
245   if (DumpType == DIDT_All || DumpType == DIDT_AppleNames)
246     dumpAccelSection(OS, "apple_names", getAppleNamesSection(),
247                      getStringSection(), isLittleEndian());
248
249   if (DumpType == DIDT_All || DumpType == DIDT_AppleTypes)
250     dumpAccelSection(OS, "apple_types", getAppleTypesSection(),
251                      getStringSection(), isLittleEndian());
252
253   if (DumpType == DIDT_All || DumpType == DIDT_AppleNamespaces)
254     dumpAccelSection(OS, "apple_namespaces", getAppleNamespacesSection(),
255                      getStringSection(), isLittleEndian());
256
257   if (DumpType == DIDT_All || DumpType == DIDT_AppleObjC)
258     dumpAccelSection(OS, "apple_objc", getAppleObjCSection(),
259                      getStringSection(), isLittleEndian());
260 }
261
262 const DWARFDebugAbbrev *DWARFContext::getDebugAbbrev() {
263   if (Abbrev)
264     return Abbrev.get();
265
266   DataExtractor abbrData(getAbbrevSection(), isLittleEndian(), 0);
267
268   Abbrev.reset(new DWARFDebugAbbrev());
269   Abbrev->extract(abbrData);
270   return Abbrev.get();
271 }
272
273 const DWARFDebugAbbrev *DWARFContext::getDebugAbbrevDWO() {
274   if (AbbrevDWO)
275     return AbbrevDWO.get();
276
277   DataExtractor abbrData(getAbbrevDWOSection(), isLittleEndian(), 0);
278   AbbrevDWO.reset(new DWARFDebugAbbrev());
279   AbbrevDWO->extract(abbrData);
280   return AbbrevDWO.get();
281 }
282
283 const DWARFDebugLoc *DWARFContext::getDebugLoc() {
284   if (Loc)
285     return Loc.get();
286
287   DataExtractor LocData(getLocSection().Data, isLittleEndian(), 0);
288   Loc.reset(new DWARFDebugLoc(getLocSection().Relocs));
289   // assume all compile units have the same address byte size
290   if (getNumCompileUnits())
291     Loc->parse(LocData, getCompileUnitAtIndex(0)->getAddressByteSize());
292   return Loc.get();
293 }
294
295 const DWARFDebugLocDWO *DWARFContext::getDebugLocDWO() {
296   if (LocDWO)
297     return LocDWO.get();
298
299   DataExtractor LocData(getLocDWOSection().Data, isLittleEndian(), 0);
300   LocDWO.reset(new DWARFDebugLocDWO());
301   LocDWO->parse(LocData);
302   return LocDWO.get();
303 }
304
305 const DWARFDebugAranges *DWARFContext::getDebugAranges() {
306   if (Aranges)
307     return Aranges.get();
308
309   Aranges.reset(new DWARFDebugAranges());
310   Aranges->generate(this);
311   return Aranges.get();
312 }
313
314 const DWARFDebugFrame *DWARFContext::getDebugFrame() {
315   if (DebugFrame)
316     return DebugFrame.get();
317
318   // There's a "bug" in the DWARFv3 standard with respect to the target address
319   // size within debug frame sections. While DWARF is supposed to be independent
320   // of its container, FDEs have fields with size being "target address size",
321   // which isn't specified in DWARF in general. It's only specified for CUs, but
322   // .eh_frame can appear without a .debug_info section. Follow the example of
323   // other tools (libdwarf) and extract this from the container (ObjectFile
324   // provides this information). This problem is fixed in DWARFv4
325   // See this dwarf-discuss discussion for more details:
326   // http://lists.dwarfstd.org/htdig.cgi/dwarf-discuss-dwarfstd.org/2011-December/001173.html
327   DataExtractor debugFrameData(getDebugFrameSection(), isLittleEndian(),
328                                getAddressSize());
329   DebugFrame.reset(new DWARFDebugFrame());
330   DebugFrame->parse(debugFrameData);
331   return DebugFrame.get();
332 }
333
334 const DWARFLineTable *
335 DWARFContext::getLineTableForUnit(DWARFUnit *U) {
336   if (!Line)
337     Line.reset(new DWARFDebugLine(&getLineSection().Relocs));
338   const auto *UnitDIE = U->getUnitDIE();
339   if (UnitDIE == nullptr)
340     return nullptr;
341   unsigned stmtOffset =
342       UnitDIE->getAttributeValueAsSectionOffset(U, DW_AT_stmt_list, -1U);
343   if (stmtOffset == -1U)
344     return nullptr; // No line table for this compile unit.
345
346   // See if the line table is cached.
347   if (const DWARFLineTable *lt = Line->getLineTable(stmtOffset))
348     return lt;
349
350   // We have to parse it first.
351   DataExtractor lineData(getLineSection().Data, isLittleEndian(),
352                          U->getAddressByteSize());
353   return Line->getOrParseLineTable(lineData, stmtOffset);
354 }
355
356 void DWARFContext::parseCompileUnits() {
357   CUs.parse(*this, getInfoSection());
358 }
359
360 void DWARFContext::parseTypeUnits() {
361   if (!TUs.empty())
362     return;
363   for (const auto &I : getTypesSections()) {
364     TUs.emplace_back();
365     TUs.back().parse(*this, I.second);
366   }
367 }
368
369 void DWARFContext::parseDWOCompileUnits() {
370   DWOCUs.parseDWO(*this, getInfoDWOSection());
371 }
372
373 void DWARFContext::parseDWOTypeUnits() {
374   if (!DWOTUs.empty())
375     return;
376   for (const auto &I : getTypesDWOSections()) {
377     DWOTUs.emplace_back();
378     DWOTUs.back().parseDWO(*this, I.second);
379   }
380 }
381
382 DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint32_t Offset) {
383   parseCompileUnits();
384   return CUs.getUnitForOffset(Offset);
385 }
386
387 DWARFCompileUnit *DWARFContext::getCompileUnitForAddress(uint64_t Address) {
388   // First, get the offset of the compile unit.
389   uint32_t CUOffset = getDebugAranges()->findAddress(Address);
390   // Retrieve the compile unit.
391   return getCompileUnitForOffset(CUOffset);
392 }
393
394 static bool getFunctionNameForAddress(DWARFCompileUnit *CU, uint64_t Address,
395                                       FunctionNameKind Kind,
396                                       std::string &FunctionName) {
397   if (Kind == FunctionNameKind::None)
398     return false;
399   // The address may correspond to instruction in some inlined function,
400   // so we have to build the chain of inlined functions and take the
401   // name of the topmost function in it.
402   const DWARFDebugInfoEntryInlinedChain &InlinedChain =
403       CU->getInlinedChainForAddress(Address);
404   if (InlinedChain.DIEs.size() == 0)
405     return false;
406   const DWARFDebugInfoEntryMinimal &TopFunctionDIE = InlinedChain.DIEs[0];
407   if (const char *Name =
408           TopFunctionDIE.getSubroutineName(InlinedChain.U, Kind)) {
409     FunctionName = Name;
410     return true;
411   }
412   return false;
413 }
414
415 DILineInfo DWARFContext::getLineInfoForAddress(uint64_t Address,
416                                                DILineInfoSpecifier Spec) {
417   DILineInfo Result;
418
419   DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
420   if (!CU)
421     return Result;
422   getFunctionNameForAddress(CU, Address, Spec.FNKind, Result.FunctionName);
423   if (Spec.FLIKind != FileLineInfoKind::None) {
424     if (const DWARFLineTable *LineTable = getLineTableForUnit(CU))
425       LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
426                                            Spec.FLIKind, Result);
427   }
428   return Result;
429 }
430
431 DILineInfoTable
432 DWARFContext::getLineInfoForAddressRange(uint64_t Address, uint64_t Size,
433                                          DILineInfoSpecifier Spec) {
434   DILineInfoTable  Lines;
435   DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
436   if (!CU)
437     return Lines;
438
439   std::string FunctionName = "<invalid>";
440   getFunctionNameForAddress(CU, Address, Spec.FNKind, FunctionName);
441
442   // If the Specifier says we don't need FileLineInfo, just
443   // return the top-most function at the starting address.
444   if (Spec.FLIKind == FileLineInfoKind::None) {
445     DILineInfo Result;
446     Result.FunctionName = FunctionName;
447     Lines.push_back(std::make_pair(Address, Result));
448     return Lines;
449   }
450
451   const DWARFLineTable *LineTable = getLineTableForUnit(CU);
452
453   // Get the index of row we're looking for in the line table.
454   std::vector<uint32_t> RowVector;
455   if (!LineTable->lookupAddressRange(Address, Size, RowVector))
456     return Lines;
457
458   for (uint32_t RowIndex : RowVector) {
459     // Take file number and line/column from the row.
460     const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
461     DILineInfo Result;
462     LineTable->getFileNameByIndex(Row.File, CU->getCompilationDir(),
463                                   Spec.FLIKind, Result.FileName);
464     Result.FunctionName = FunctionName;
465     Result.Line = Row.Line;
466     Result.Column = Row.Column;
467     Lines.push_back(std::make_pair(Row.Address, Result));
468   }
469
470   return Lines;
471 }
472
473 DIInliningInfo
474 DWARFContext::getInliningInfoForAddress(uint64_t Address,
475                                         DILineInfoSpecifier Spec) {
476   DIInliningInfo InliningInfo;
477
478   DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
479   if (!CU)
480     return InliningInfo;
481
482   const DWARFLineTable *LineTable = nullptr;
483   const DWARFDebugInfoEntryInlinedChain &InlinedChain =
484       CU->getInlinedChainForAddress(Address);
485   if (InlinedChain.DIEs.size() == 0) {
486     // If there is no DIE for address (e.g. it is in unavailable .dwo file),
487     // try to at least get file/line info from symbol table.
488     if (Spec.FLIKind != FileLineInfoKind::None) {
489       DILineInfo Frame;
490       LineTable = getLineTableForUnit(CU);
491       if (LineTable &&
492           LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
493                                                Spec.FLIKind, Frame))
494         InliningInfo.addFrame(Frame);
495     }
496     return InliningInfo;
497   }
498
499   uint32_t CallFile = 0, CallLine = 0, CallColumn = 0;
500   for (uint32_t i = 0, n = InlinedChain.DIEs.size(); i != n; i++) {
501     const DWARFDebugInfoEntryMinimal &FunctionDIE = InlinedChain.DIEs[i];
502     DILineInfo Frame;
503     // Get function name if necessary.
504     if (const char *Name =
505             FunctionDIE.getSubroutineName(InlinedChain.U, Spec.FNKind))
506       Frame.FunctionName = Name;
507     if (Spec.FLIKind != FileLineInfoKind::None) {
508       if (i == 0) {
509         // For the topmost frame, initialize the line table of this
510         // compile unit and fetch file/line info from it.
511         LineTable = getLineTableForUnit(CU);
512         // For the topmost routine, get file/line info from line table.
513         if (LineTable)
514           LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
515                                                Spec.FLIKind, Frame);
516       } else {
517         // Otherwise, use call file, call line and call column from
518         // previous DIE in inlined chain.
519         if (LineTable)
520           LineTable->getFileNameByIndex(CallFile, CU->getCompilationDir(),
521                                         Spec.FLIKind, Frame.FileName);
522         Frame.Line = CallLine;
523         Frame.Column = CallColumn;
524       }
525       // Get call file/line/column of a current DIE.
526       if (i + 1 < n) {
527         FunctionDIE.getCallerFrame(InlinedChain.U, CallFile, CallLine,
528                                    CallColumn);
529       }
530     }
531     InliningInfo.addFrame(Frame);
532   }
533   return InliningInfo;
534 }
535
536 static bool consumeCompressedDebugSectionHeader(StringRef &data,
537                                                 uint64_t &OriginalSize) {
538   // Consume "ZLIB" prefix.
539   if (!data.startswith("ZLIB"))
540     return false;
541   data = data.substr(4);
542   // Consume uncompressed section size (big-endian 8 bytes).
543   DataExtractor extractor(data, false, 8);
544   uint32_t Offset = 0;
545   OriginalSize = extractor.getU64(&Offset);
546   if (Offset == 0)
547     return false;
548   data = data.substr(Offset);
549   return true;
550 }
551
552 DWARFContextInMemory::DWARFContextInMemory(const object::ObjectFile &Obj,
553     const LoadedObjectInfo *L)
554     : IsLittleEndian(Obj.isLittleEndian()),
555       AddressSize(Obj.getBytesInAddress()) {
556   for (const SectionRef &Section : Obj.sections()) {
557     StringRef name;
558     Section.getName(name);
559     // Skip BSS and Virtual sections, they aren't interesting.
560     bool IsBSS = Section.isBSS();
561     if (IsBSS)
562       continue;
563     bool IsVirtual = Section.isVirtual();
564     if (IsVirtual)
565       continue;
566     StringRef data;
567
568     section_iterator RelocatedSection = Section.getRelocatedSection();
569     // Try to obtain an already relocated version of this section.
570     // Else use the unrelocated section from the object file. We'll have to
571     // apply relocations ourselves later.
572     if (!L || !L->getLoadedSectionContents(*RelocatedSection,data))
573       Section.getContents(data);
574
575     name = name.substr(name.find_first_not_of("._")); // Skip . and _ prefixes.
576
577     // Check if debug info section is compressed with zlib.
578     if (name.startswith("zdebug_")) {
579       uint64_t OriginalSize;
580       if (!zlib::isAvailable() ||
581           !consumeCompressedDebugSectionHeader(data, OriginalSize))
582         continue;
583       UncompressedSections.resize(UncompressedSections.size() + 1);
584       if (zlib::uncompress(data, UncompressedSections.back(), OriginalSize) !=
585           zlib::StatusOK) {
586         UncompressedSections.pop_back();
587         continue;
588       }
589       // Make data point to uncompressed section contents and save its contents.
590       name = name.substr(1);
591       data = UncompressedSections.back();
592     }
593
594     StringRef *SectionData =
595         StringSwitch<StringRef *>(name)
596             .Case("debug_info", &InfoSection.Data)
597             .Case("debug_abbrev", &AbbrevSection)
598             .Case("debug_loc", &LocSection.Data)
599             .Case("debug_line", &LineSection.Data)
600             .Case("debug_aranges", &ARangeSection)
601             .Case("debug_frame", &DebugFrameSection)
602             .Case("debug_str", &StringSection)
603             .Case("debug_ranges", &RangeSection)
604             .Case("debug_pubnames", &PubNamesSection)
605             .Case("debug_pubtypes", &PubTypesSection)
606             .Case("debug_gnu_pubnames", &GnuPubNamesSection)
607             .Case("debug_gnu_pubtypes", &GnuPubTypesSection)
608             .Case("debug_info.dwo", &InfoDWOSection.Data)
609             .Case("debug_abbrev.dwo", &AbbrevDWOSection)
610             .Case("debug_loc.dwo", &LocDWOSection.Data)
611             .Case("debug_line.dwo", &LineDWOSection.Data)
612             .Case("debug_str.dwo", &StringDWOSection)
613             .Case("debug_str_offsets.dwo", &StringOffsetDWOSection)
614             .Case("debug_addr", &AddrSection)
615             .Case("apple_names", &AppleNamesSection.Data)
616             .Case("apple_types", &AppleTypesSection.Data)
617             .Case("apple_namespaces", &AppleNamespacesSection.Data)
618             .Case("apple_namespac", &AppleNamespacesSection.Data)
619             .Case("apple_objc", &AppleObjCSection.Data)
620             .Case("debug_cu_index", &CUIndexSection)
621             // Any more debug info sections go here.
622             .Default(nullptr);
623     if (SectionData) {
624       *SectionData = data;
625       if (name == "debug_ranges") {
626         // FIXME: Use the other dwo range section when we emit it.
627         RangeDWOSection = data;
628       }
629     } else if (name == "debug_types") {
630       // Find debug_types data by section rather than name as there are
631       // multiple, comdat grouped, debug_types sections.
632       TypesSections[Section].Data = data;
633     } else if (name == "debug_types.dwo") {
634       TypesDWOSections[Section].Data = data;
635     }
636
637     if (RelocatedSection == Obj.section_end())
638       continue;
639
640     StringRef RelSecName;
641     StringRef RelSecData;
642     RelocatedSection->getName(RelSecName);
643
644     // If the section we're relocating was relocated already by the JIT,
645     // then we used the relocated version above, so we do not need to process
646     // relocations for it now.
647     if (L && L->getLoadedSectionContents(*RelocatedSection,RelSecData))
648       continue;
649
650     // In Mach-o files, the relocations do not need to be applied if
651     // there is no load offset to apply. The value read at the
652     // relocation point already factors in the section address
653     // (actually applying the relocations will produce wrong results
654     // as the section address will be added twice).
655     if (!L && dyn_cast<MachOObjectFile>(&Obj))
656       continue;
657
658     RelSecName = RelSecName.substr(
659         RelSecName.find_first_not_of("._")); // Skip . and _ prefixes.
660
661     // TODO: Add support for relocations in other sections as needed.
662     // Record relocations for the debug_info and debug_line sections.
663     RelocAddrMap *Map = StringSwitch<RelocAddrMap*>(RelSecName)
664         .Case("debug_info", &InfoSection.Relocs)
665         .Case("debug_loc", &LocSection.Relocs)
666         .Case("debug_info.dwo", &InfoDWOSection.Relocs)
667         .Case("debug_line", &LineSection.Relocs)
668         .Case("apple_names", &AppleNamesSection.Relocs)
669         .Case("apple_types", &AppleTypesSection.Relocs)
670         .Case("apple_namespaces", &AppleNamespacesSection.Relocs)
671         .Case("apple_namespac", &AppleNamespacesSection.Relocs)
672         .Case("apple_objc", &AppleObjCSection.Relocs)
673         .Default(nullptr);
674     if (!Map) {
675       // Find debug_types relocs by section rather than name as there are
676       // multiple, comdat grouped, debug_types sections.
677       if (RelSecName == "debug_types")
678         Map = &TypesSections[*RelocatedSection].Relocs;
679       else if (RelSecName == "debug_types.dwo")
680         Map = &TypesDWOSections[*RelocatedSection].Relocs;
681       else
682         continue;
683     }
684
685     if (Section.relocation_begin() != Section.relocation_end()) {
686       uint64_t SectionSize = RelocatedSection->getSize();
687       for (const RelocationRef &Reloc : Section.relocations()) {
688         uint64_t Address = Reloc.getOffset();
689         uint64_t Type = Reloc.getType();
690         uint64_t SymAddr = 0;
691         uint64_t SectionLoadAddress = 0;
692         object::symbol_iterator Sym = Reloc.getSymbol();
693         object::section_iterator RSec = Obj.section_end();
694
695         // First calculate the address of the symbol or section as it appears
696         // in the objct file
697         if (Sym != Obj.symbol_end()) {
698           ErrorOr<uint64_t> SymAddrOrErr = Sym->getAddress();
699           if (std::error_code EC = SymAddrOrErr.getError()) {
700             errs() << "error: failed to compute symbol address: "
701                    << EC.message() << '\n';
702             continue;
703           }
704           SymAddr = *SymAddrOrErr;
705           // Also remember what section this symbol is in for later
706           RSec = *Sym->getSection();
707         } else if (auto *MObj = dyn_cast<MachOObjectFile>(&Obj)) {
708           // MachO also has relocations that point to sections and
709           // scattered relocations.
710           auto RelocInfo = MObj->getRelocation(Reloc.getRawDataRefImpl());
711           if (MObj->isRelocationScattered(RelocInfo)) {
712             // FIXME: it's not clear how to correctly handle scattered
713             // relocations.
714             continue;
715           } else {
716             RSec = MObj->getRelocationSection(Reloc.getRawDataRefImpl());
717             SymAddr = RSec->getAddress();
718           }
719         }
720
721         // If we are given load addresses for the sections, we need to adjust:
722         // SymAddr = (Address of Symbol Or Section in File) -
723         //           (Address of Section in File) +
724         //           (Load Address of Section)
725         if (L != nullptr && RSec != Obj.section_end()) {
726           // RSec is now either the section being targeted or the section
727           // containing the symbol being targeted. In either case,
728           // we need to perform the same computation.
729           StringRef SecName;
730           RSec->getName(SecName);
731 //           llvm::dbgs() << "Name: '" << SecName
732 //                        << "', RSec: " << RSec->getRawDataRefImpl()
733 //                        << ", Section: " << Section.getRawDataRefImpl() << "\n";
734           SectionLoadAddress = L->getSectionLoadAddress(*RSec);
735           if (SectionLoadAddress != 0)
736             SymAddr += SectionLoadAddress - RSec->getAddress();
737         }
738
739         object::RelocVisitor V(Obj);
740         object::RelocToApply R(V.visit(Type, Reloc, SymAddr));
741         if (V.error()) {
742           SmallString<32> Name;
743           Reloc.getTypeName(Name);
744           errs() << "error: failed to compute relocation: "
745                  << Name << "\n";
746           continue;
747         }
748
749         if (Address + R.Width > SectionSize) {
750           errs() << "error: " << R.Width << "-byte relocation starting "
751                  << Address << " bytes into section " << name << " which is "
752                  << SectionSize << " bytes long.\n";
753           continue;
754         }
755         if (R.Width > 8) {
756           errs() << "error: can't handle a relocation of more than 8 bytes at "
757                     "a time.\n";
758           continue;
759         }
760         DEBUG(dbgs() << "Writing " << format("%p", R.Value)
761                      << " at " << format("%p", Address)
762                      << " with width " << format("%d", R.Width)
763                      << "\n");
764         Map->insert(std::make_pair(Address, std::make_pair(R.Width, R.Value)));
765       }
766     }
767   }
768 }
769
770 void DWARFContextInMemory::anchor() { }