llvm-objdump: print contents of MachO __unwind_info sections
[oota-llvm.git] / tools / llvm-objdump / MachODump.cpp
1 //===-- MachODump.cpp - Object file dumping utility for llvm --------------===//
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 // This file implements the MachO-specific dumper for llvm-objdump.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm-objdump.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/DebugInfo/DIContext.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCDisassembler.h"
22 #include "llvm/MC/MCInst.h"
23 #include "llvm/MC/MCInstPrinter.h"
24 #include "llvm/MC/MCInstrAnalysis.h"
25 #include "llvm/MC/MCInstrDesc.h"
26 #include "llvm/MC/MCInstrInfo.h"
27 #include "llvm/MC/MCRegisterInfo.h"
28 #include "llvm/MC/MCSubtargetInfo.h"
29 #include "llvm/Object/MachO.h"
30 #include "llvm/Support/Casting.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/Endian.h"
34 #include "llvm/Support/Format.h"
35 #include "llvm/Support/GraphWriter.h"
36 #include "llvm/Support/MachO.h"
37 #include "llvm/Support/MemoryBuffer.h"
38 #include "llvm/Support/TargetRegistry.h"
39 #include "llvm/Support/TargetSelect.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include <algorithm>
42 #include <cstring>
43 #include <system_error>
44 using namespace llvm;
45 using namespace object;
46
47 static cl::opt<bool>
48   UseDbg("g", cl::desc("Print line information from debug info if available"));
49
50 static cl::opt<std::string>
51   DSYMFile("dsym", cl::desc("Use .dSYM file for debug info"));
52
53 static const Target *GetTarget(const MachOObjectFile *MachOObj) {
54   // Figure out the target triple.
55   if (TripleName.empty()) {
56     llvm::Triple TT("unknown-unknown-unknown");
57     TT.setArch(Triple::ArchType(MachOObj->getArch()));
58     TripleName = TT.str();
59   }
60
61   // Get the target specific parser.
62   std::string Error;
63   const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
64   if (TheTarget)
65     return TheTarget;
66
67   errs() << "llvm-objdump: error: unable to get target for '" << TripleName
68          << "', see --version and --triple.\n";
69   return nullptr;
70 }
71
72 struct SymbolSorter {
73   bool operator()(const SymbolRef &A, const SymbolRef &B) {
74     SymbolRef::Type AType, BType;
75     A.getType(AType);
76     B.getType(BType);
77
78     uint64_t AAddr, BAddr;
79     if (AType != SymbolRef::ST_Function)
80       AAddr = 0;
81     else
82       A.getAddress(AAddr);
83     if (BType != SymbolRef::ST_Function)
84       BAddr = 0;
85     else
86       B.getAddress(BAddr);
87     return AAddr < BAddr;
88   }
89 };
90
91 // Types for the storted data in code table that is built before disassembly
92 // and the predicate function to sort them.
93 typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
94 typedef std::vector<DiceTableEntry> DiceTable;
95 typedef DiceTable::iterator dice_table_iterator;
96
97 static bool
98 compareDiceTableEntries(const DiceTableEntry i,
99                         const DiceTableEntry j) {
100   return i.first == j.first;
101 }
102
103 static void DumpDataInCode(const char *bytes, uint64_t Size,
104                            unsigned short Kind) {
105   uint64_t Value;
106
107   switch (Kind) {
108   case MachO::DICE_KIND_DATA:
109     switch (Size) {
110     case 4:
111       Value = bytes[3] << 24 |
112               bytes[2] << 16 |
113               bytes[1] << 8 |
114               bytes[0];
115       outs() << "\t.long " << Value;
116       break;
117     case 2:
118       Value = bytes[1] << 8 |
119               bytes[0];
120       outs() << "\t.short " << Value;
121       break;
122     case 1:
123       Value = bytes[0];
124       outs() << "\t.byte " << Value;
125       break;
126     }
127     outs() << "\t@ KIND_DATA\n";
128     break;
129   case MachO::DICE_KIND_JUMP_TABLE8:
130     Value = bytes[0];
131     outs() << "\t.byte " << Value << "\t@ KIND_JUMP_TABLE8";
132     break;
133   case MachO::DICE_KIND_JUMP_TABLE16:
134     Value = bytes[1] << 8 |
135             bytes[0];
136     outs() << "\t.short " << Value << "\t@ KIND_JUMP_TABLE16";
137     break;
138   case MachO::DICE_KIND_JUMP_TABLE32:
139     Value = bytes[3] << 24 |
140             bytes[2] << 16 |
141             bytes[1] << 8 |
142             bytes[0];
143     outs() << "\t.long " << Value << "\t@ KIND_JUMP_TABLE32";
144     break;
145   default:
146     outs() << "\t@ data in code kind = " << Kind << "\n";
147     break;
148   }
149 }
150
151 static void getSectionsAndSymbols(const MachO::mach_header Header,
152                                   MachOObjectFile *MachOObj,
153                                   std::vector<SectionRef> &Sections,
154                                   std::vector<SymbolRef> &Symbols,
155                                   SmallVectorImpl<uint64_t> &FoundFns,
156                                   uint64_t &BaseSegmentAddress) {
157   for (const SymbolRef &Symbol : MachOObj->symbols())
158     Symbols.push_back(Symbol);
159
160   for (const SectionRef &Section : MachOObj->sections()) {
161     StringRef SectName;
162     Section.getName(SectName);
163     Sections.push_back(Section);
164   }
165
166   MachOObjectFile::LoadCommandInfo Command =
167       MachOObj->getFirstLoadCommandInfo();
168   bool BaseSegmentAddressSet = false;
169   for (unsigned i = 0; ; ++i) {
170     if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
171       // We found a function starts segment, parse the addresses for later
172       // consumption.
173       MachO::linkedit_data_command LLC =
174         MachOObj->getLinkeditDataLoadCommand(Command);
175
176       MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
177     }
178     else if (Command.C.cmd == MachO::LC_SEGMENT) {
179       MachO::segment_command SLC =
180         MachOObj->getSegmentLoadCommand(Command);
181       StringRef SegName = SLC.segname;
182       if(!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
183         BaseSegmentAddressSet = true;
184         BaseSegmentAddress = SLC.vmaddr;
185       }
186     }
187
188     if (i == Header.ncmds - 1)
189       break;
190     else
191       Command = MachOObj->getNextLoadCommandInfo(Command);
192   }
193 }
194
195 static void DisassembleInputMachO2(StringRef Filename,
196                                    MachOObjectFile *MachOOF);
197
198 void llvm::DisassembleInputMachO(StringRef Filename) {
199   ErrorOr<std::unique_ptr<MemoryBuffer>> Buff =
200       MemoryBuffer::getFileOrSTDIN(Filename);
201   if (std::error_code EC = Buff.getError()) {
202     errs() << "llvm-objdump: " << Filename << ": " << EC.message() << "\n";
203     return;
204   }
205
206   std::unique_ptr<MachOObjectFile> MachOOF =
207     std::move(ObjectFile::createMachOObjectFile(Buff.get()).get());
208
209   DisassembleInputMachO2(Filename, MachOOF.get());
210 }
211
212 static void DisassembleInputMachO2(StringRef Filename,
213                                    MachOObjectFile *MachOOF) {
214   const Target *TheTarget = GetTarget(MachOOF);
215   if (!TheTarget) {
216     // GetTarget prints out stuff.
217     return;
218   }
219   std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
220   std::unique_ptr<MCInstrAnalysis> InstrAnalysis(
221       TheTarget->createMCInstrAnalysis(InstrInfo.get()));
222
223   // Package up features to be passed to target/subtarget
224   std::string FeaturesStr;
225   if (MAttrs.size()) {
226     SubtargetFeatures Features;
227     for (unsigned i = 0; i != MAttrs.size(); ++i)
228       Features.AddFeature(MAttrs[i]);
229     FeaturesStr = Features.getString();
230   }
231
232   // Set up disassembler.
233   std::unique_ptr<const MCRegisterInfo> MRI(
234       TheTarget->createMCRegInfo(TripleName));
235   std::unique_ptr<const MCAsmInfo> AsmInfo(
236       TheTarget->createMCAsmInfo(*MRI, TripleName));
237   std::unique_ptr<const MCSubtargetInfo> STI(
238       TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
239   MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
240   std::unique_ptr<const MCDisassembler> DisAsm(
241     TheTarget->createMCDisassembler(*STI, Ctx));
242   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
243   std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
244       AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI, *STI));
245
246   if (!InstrAnalysis || !AsmInfo || !STI || !DisAsm || !IP) {
247     errs() << "error: couldn't initialize disassembler for target "
248            << TripleName << '\n';
249     return;
250   }
251
252   outs() << '\n' << Filename << ":\n\n";
253
254   MachO::mach_header Header = MachOOF->getHeader();
255
256   // FIXME: FoundFns isn't used anymore. Using symbols/LC_FUNCTION_STARTS to
257   // determine function locations will eventually go in MCObjectDisassembler.
258   // FIXME: Using the -cfg command line option, this code used to be able to
259   // annotate relocations with the referenced symbol's name, and if this was
260   // inside a __[cf]string section, the data it points to. This is now replaced
261   // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
262   std::vector<SectionRef> Sections;
263   std::vector<SymbolRef> Symbols;
264   SmallVector<uint64_t, 8> FoundFns;
265   uint64_t BaseSegmentAddress;
266
267   getSectionsAndSymbols(Header, MachOOF, Sections, Symbols, FoundFns,
268                         BaseSegmentAddress);
269
270   // Sort the symbols by address, just in case they didn't come in that way.
271   std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
272
273   // Build a data in code table that is sorted on by the address of each entry.
274   uint64_t BaseAddress = 0;
275   if (Header.filetype == MachO::MH_OBJECT)
276     Sections[0].getAddress(BaseAddress);
277   else
278     BaseAddress = BaseSegmentAddress;
279   DiceTable Dices;
280   for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
281        DI != DE; ++DI) {
282     uint32_t Offset;
283     DI->getOffset(Offset);
284     Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
285   }
286   array_pod_sort(Dices.begin(), Dices.end());
287
288 #ifndef NDEBUG
289   raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
290 #else
291   raw_ostream &DebugOut = nulls();
292 #endif
293
294   std::unique_ptr<DIContext> diContext;
295   ObjectFile *DbgObj = MachOOF;
296   // Try to find debug info and set up the DIContext for it.
297   if (UseDbg) {
298     // A separate DSym file path was specified, parse it as a macho file,
299     // get the sections and supply it to the section name parsing machinery.
300     if (!DSYMFile.empty()) {
301       ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
302           MemoryBuffer::getFileOrSTDIN(DSYMFile);
303       if (std::error_code EC = Buf.getError()) {
304         errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
305         return;
306       }
307       DbgObj = ObjectFile::createMachOObjectFile(Buf.get()).get().release();
308     }
309
310     // Setup the DIContext
311     diContext.reset(DIContext::getDWARFContext(*DbgObj));
312   }
313
314   for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
315
316     bool SectIsText = false;
317     Sections[SectIdx].isText(SectIsText);
318     if (SectIsText == false)
319       continue;
320
321     StringRef SectName;
322     if (Sections[SectIdx].getName(SectName) ||
323         SectName != "__text")
324       continue; // Skip non-text sections
325
326     DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
327
328     StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
329     if (SegmentName != "__TEXT")
330       continue;
331
332     StringRef Bytes;
333     Sections[SectIdx].getContents(Bytes);
334     StringRefMemoryObject memoryObject(Bytes);
335     bool symbolTableWorked = false;
336
337     // Parse relocations.
338     std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
339     for (const RelocationRef &Reloc : Sections[SectIdx].relocations()) {
340       uint64_t RelocOffset, SectionAddress;
341       Reloc.getOffset(RelocOffset);
342       Sections[SectIdx].getAddress(SectionAddress);
343       RelocOffset -= SectionAddress;
344
345       symbol_iterator RelocSym = Reloc.getSymbol();
346
347       Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
348     }
349     array_pod_sort(Relocs.begin(), Relocs.end());
350
351     // Disassemble symbol by symbol.
352     for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
353       StringRef SymName;
354       Symbols[SymIdx].getName(SymName);
355
356       SymbolRef::Type ST;
357       Symbols[SymIdx].getType(ST);
358       if (ST != SymbolRef::ST_Function)
359         continue;
360
361       // Make sure the symbol is defined in this section.
362       bool containsSym = false;
363       Sections[SectIdx].containsSymbol(Symbols[SymIdx], containsSym);
364       if (!containsSym)
365         continue;
366
367       // Start at the address of the symbol relative to the section's address.
368       uint64_t SectionAddress = 0;
369       uint64_t Start = 0;
370       Sections[SectIdx].getAddress(SectionAddress);
371       Symbols[SymIdx].getAddress(Start);
372       Start -= SectionAddress;
373
374       // Stop disassembling either at the beginning of the next symbol or at
375       // the end of the section.
376       bool containsNextSym = false;
377       uint64_t NextSym = 0;
378       uint64_t NextSymIdx = SymIdx+1;
379       while (Symbols.size() > NextSymIdx) {
380         SymbolRef::Type NextSymType;
381         Symbols[NextSymIdx].getType(NextSymType);
382         if (NextSymType == SymbolRef::ST_Function) {
383           Sections[SectIdx].containsSymbol(Symbols[NextSymIdx],
384                                            containsNextSym);
385           Symbols[NextSymIdx].getAddress(NextSym);
386           NextSym -= SectionAddress;
387           break;
388         }
389         ++NextSymIdx;
390       }
391
392       uint64_t SectSize;
393       Sections[SectIdx].getSize(SectSize);
394       uint64_t End = containsNextSym ?  NextSym : SectSize;
395       uint64_t Size;
396
397       symbolTableWorked = true;
398
399       outs() << SymName << ":\n";
400       DILineInfo lastLine;
401       for (uint64_t Index = Start; Index < End; Index += Size) {
402         MCInst Inst;
403
404         uint64_t SectAddress = 0;
405         Sections[SectIdx].getAddress(SectAddress);
406         outs() << format("%8" PRIx64 ":\t", SectAddress + Index);
407
408         // Check the data in code table here to see if this is data not an
409         // instruction to be disassembled.
410         DiceTable Dice;
411         Dice.push_back(std::make_pair(SectAddress + Index, DiceRef()));
412         dice_table_iterator DTI = std::search(Dices.begin(), Dices.end(),
413                                               Dice.begin(), Dice.end(),
414                                               compareDiceTableEntries);
415         if (DTI != Dices.end()){
416           uint16_t Length;
417           DTI->second.getLength(Length);
418           DumpBytes(StringRef(Bytes.data() + Index, Length));
419           uint16_t Kind;
420           DTI->second.getKind(Kind);
421           DumpDataInCode(Bytes.data() + Index, Length, Kind);
422           continue;
423         }
424
425         if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
426                                    DebugOut, nulls())) {
427           DumpBytes(StringRef(Bytes.data() + Index, Size));
428           IP->printInst(&Inst, outs(), "");
429
430           // Print debug info.
431           if (diContext) {
432             DILineInfo dli =
433               diContext->getLineInfoForAddress(SectAddress + Index);
434             // Print valid line info if it changed.
435             if (dli != lastLine && dli.Line != 0)
436               outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
437                      << dli.Column;
438             lastLine = dli;
439           }
440           outs() << "\n";
441         } else {
442           errs() << "llvm-objdump: warning: invalid instruction encoding\n";
443           if (Size == 0)
444             Size = 1; // skip illegible bytes
445         }
446       }
447     }
448     if (!symbolTableWorked) {
449       // Reading the symbol table didn't work, disassemble the whole section. 
450       uint64_t SectAddress;
451       Sections[SectIdx].getAddress(SectAddress);
452       uint64_t SectSize;
453       Sections[SectIdx].getSize(SectSize);
454       uint64_t InstSize;
455       for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
456         MCInst Inst;
457
458         if (DisAsm->getInstruction(Inst, InstSize, memoryObject, Index,
459                                    DebugOut, nulls())) {
460           outs() << format("%8" PRIx64 ":\t", SectAddress + Index);
461           DumpBytes(StringRef(Bytes.data() + Index, InstSize));
462           IP->printInst(&Inst, outs(), "");
463           outs() << "\n";
464         } else {
465           errs() << "llvm-objdump: warning: invalid instruction encoding\n";
466           if (InstSize == 0)
467             InstSize = 1; // skip illegible bytes
468         }
469       }
470     }
471   }
472 }
473
474
475 //===----------------------------------------------------------------------===//
476 // __compact_unwind section dumping
477 //===----------------------------------------------------------------------===//
478
479 namespace {
480
481 template <typename T> static uint64_t readNext(const char *&Buf) {
482     using llvm::support::little;
483     using llvm::support::unaligned;
484
485     uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
486     Buf += sizeof(T);
487     return Val;
488   }
489
490 struct CompactUnwindEntry {
491   uint32_t OffsetInSection;
492
493   uint64_t FunctionAddr;
494   uint32_t Length;
495   uint32_t CompactEncoding;
496   uint64_t PersonalityAddr;
497   uint64_t LSDAAddr;
498
499   RelocationRef FunctionReloc;
500   RelocationRef PersonalityReloc;
501   RelocationRef LSDAReloc;
502
503   CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
504     : OffsetInSection(Offset) {
505     if (Is64)
506       read<uint64_t>(Contents.data() + Offset);
507     else
508       read<uint32_t>(Contents.data() + Offset);
509   }
510
511 private:
512   template<typename UIntPtr>
513   void read(const char *Buf) {
514     FunctionAddr = readNext<UIntPtr>(Buf);
515     Length = readNext<uint32_t>(Buf);
516     CompactEncoding = readNext<uint32_t>(Buf);
517     PersonalityAddr = readNext<UIntPtr>(Buf);
518     LSDAAddr = readNext<UIntPtr>(Buf);
519   }
520 };
521 }
522
523 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
524 /// and data being relocated, determine the best base Name and Addend to use for
525 /// display purposes.
526 ///
527 /// 1. An Extern relocation will directly reference a symbol (and the data is
528 ///    then already an addend), so use that.
529 /// 2. Otherwise the data is an offset in the object file's layout; try to find
530 //     a symbol before it in the same section, and use the offset from there.
531 /// 3. Finally, if all that fails, fall back to an offset from the start of the
532 ///    referenced section.
533 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
534                                       std::map<uint64_t, SymbolRef> &Symbols,
535                                       const RelocationRef &Reloc,
536                                       uint64_t Addr,
537                                       StringRef &Name, uint64_t &Addend) {
538   if (Reloc.getSymbol() != Obj->symbol_end()) {
539     Reloc.getSymbol()->getName(Name);
540     Addend = Addr;
541     return;
542   }
543
544   auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
545   SectionRef RelocSection = Obj->getRelocationSection(RE);
546
547   uint64_t SectionAddr;
548   RelocSection.getAddress(SectionAddr);
549
550   auto Sym = Symbols.upper_bound(Addr);
551   if (Sym == Symbols.begin()) {
552     // The first symbol in the object is after this reference, the best we can
553     // do is section-relative notation.
554     RelocSection.getName(Name);
555     Addend = Addr - SectionAddr;
556     return;
557   }
558
559   // Go back one so that SymbolAddress <= Addr.
560   --Sym;
561
562   section_iterator SymSection = Obj->section_end();
563   Sym->second.getSection(SymSection);
564   if (RelocSection == *SymSection) {
565     // There's a valid symbol in the same section before this reference.
566     Sym->second.getName(Name);
567     Addend = Addr - Sym->first;
568     return;
569   }
570
571   // There is a symbol before this reference, but it's in a different
572   // section. Probably not helpful to mention it, so use the section name.
573   RelocSection.getName(Name);
574   Addend = Addr - SectionAddr;
575 }
576
577 static void printUnwindRelocDest(const MachOObjectFile *Obj,
578                                  std::map<uint64_t, SymbolRef> &Symbols,
579                                  const RelocationRef &Reloc,
580                                  uint64_t Addr) {
581   StringRef Name;
582   uint64_t Addend;
583
584   findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
585
586   outs() << Name;
587   if (Addend)
588     outs() << " + " << format("0x%" PRIx64, Addend);
589 }
590
591 static void
592 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
593                                std::map<uint64_t, SymbolRef> &Symbols,
594                                const SectionRef &CompactUnwind) {
595
596   assert(Obj->isLittleEndian() &&
597          "There should not be a big-endian .o with __compact_unwind");
598
599   bool Is64 = Obj->is64Bit();
600   uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
601   uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
602
603   StringRef Contents;
604   CompactUnwind.getContents(Contents);
605
606   SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
607
608   // First populate the initial raw offsets, encodings and so on from the entry.
609   for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
610     CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
611     CompactUnwinds.push_back(Entry);
612   }
613
614   // Next we need to look at the relocations to find out what objects are
615   // actually being referred to.
616   for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
617     uint64_t RelocAddress;
618     Reloc.getOffset(RelocAddress);
619
620     uint32_t EntryIdx = RelocAddress / EntrySize;
621     uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
622     CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
623
624     if (OffsetInEntry == 0)
625       Entry.FunctionReloc = Reloc;
626     else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
627       Entry.PersonalityReloc = Reloc;
628     else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
629       Entry.LSDAReloc = Reloc;
630     else
631       llvm_unreachable("Unexpected relocation in __compact_unwind section");
632   }
633
634   // Finally, we're ready to print the data we've gathered.
635   outs() << "Contents of __compact_unwind section:\n";
636   for (auto &Entry : CompactUnwinds) {
637     outs() << "  Entry at offset "
638            << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
639
640     // 1. Start of the region this entry applies to.
641     outs() << "    start:                "
642            << format("0x%" PRIx64, Entry.FunctionAddr) << ' ';
643     printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc,
644                          Entry.FunctionAddr);
645     outs() << '\n';
646
647     // 2. Length of the region this entry applies to.
648     outs() << "    length:               "
649            << format("0x%" PRIx32, Entry.Length) << '\n';
650     // 3. The 32-bit compact encoding.
651     outs() << "    compact encoding:     "
652            << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
653
654     // 4. The personality function, if present.
655     if (Entry.PersonalityReloc.getObjectFile()) {
656       outs() << "    personality function: "
657              << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
658       printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
659                            Entry.PersonalityAddr);
660       outs() << '\n';
661     }
662
663     // 5. This entry's language-specific data area.
664     if (Entry.LSDAReloc.getObjectFile()) {
665       outs() << "    LSDA:                 "
666              << format("0x%" PRIx64, Entry.LSDAAddr) << ' ';
667       printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
668       outs() << '\n';
669     }
670   }
671 }
672
673 //===----------------------------------------------------------------------===//
674 // __unwind_info section dumping
675 //===----------------------------------------------------------------------===//
676
677 static void printRegularSecondLevelUnwindPage(const char *PageStart) {
678   const char *Pos = PageStart;
679   uint32_t Kind = readNext<uint32_t>(Pos);
680   (void)Kind;
681   assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
682
683   uint16_t EntriesStart = readNext<uint16_t>(Pos);
684   uint16_t NumEntries = readNext<uint16_t>(Pos);
685
686   Pos = PageStart + EntriesStart;
687   for (unsigned i = 0; i < NumEntries; ++i) {
688     uint32_t FunctionOffset = readNext<uint32_t>(Pos);
689     uint32_t Encoding = readNext<uint32_t>(Pos);
690
691     outs() << "      [" << i << "]: "
692            << "function offset="
693            << format("0x%08" PRIx32, FunctionOffset) << ", "
694            << "encoding="
695            << format("0x%08" PRIx32, Encoding)
696            << '\n';
697   }
698 }
699
700 static void printCompressedSecondLevelUnwindPage(
701     const char *PageStart, uint32_t FunctionBase,
702     const SmallVectorImpl<uint32_t> &CommonEncodings) {
703   const char *Pos = PageStart;
704   uint32_t Kind = readNext<uint32_t>(Pos);
705   (void)Kind;
706   assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
707
708   uint16_t EntriesStart = readNext<uint16_t>(Pos);
709   uint16_t NumEntries = readNext<uint16_t>(Pos);
710
711   uint16_t EncodingsStart = readNext<uint16_t>(Pos);
712   readNext<uint16_t>(Pos);
713   auto PageEncodings = (support::ulittle32_t *)(PageStart + EncodingsStart);
714
715   Pos = PageStart + EntriesStart;
716   for (unsigned i = 0; i < NumEntries; ++i) {
717     uint32_t Entry = readNext<uint32_t>(Pos);
718     uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
719     uint32_t EncodingIdx = Entry >> 24;
720
721     uint32_t Encoding;
722     if (EncodingIdx < CommonEncodings.size())
723       Encoding = CommonEncodings[EncodingIdx];
724     else
725       Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
726
727     outs() << "      [" << i << "]: "
728            << "function offset="
729            << format("0x%08" PRIx32, FunctionOffset) << ", "
730            << "encoding[" << EncodingIdx << "]="
731            << format("0x%08" PRIx32, Encoding)
732            << '\n';
733   }
734 }
735
736 static void
737 printMachOUnwindInfoSection(const MachOObjectFile *Obj,
738                             std::map<uint64_t, SymbolRef> &Symbols,
739                             const SectionRef &UnwindInfo) {
740
741   assert(Obj->isLittleEndian() &&
742          "There should not be a big-endian .o with __unwind_info");
743
744   outs() << "Contents of __unwind_info section:\n";
745
746   StringRef Contents;
747   UnwindInfo.getContents(Contents);
748   const char *Pos = Contents.data();
749
750   //===----------------------------------
751   // Section header
752   //===----------------------------------
753
754   uint32_t Version = readNext<uint32_t>(Pos);
755   outs() << "  Version:                                   "
756          << format("0x%" PRIx32, Version) << '\n';
757   assert(Version == 1 && "only understand version 1");
758
759   uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
760   outs() << "  Common encodings array section offset:     "
761          << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
762   uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
763   outs() << "  Number of common encodings in array:       "
764          << format("0x%" PRIx32, NumCommonEncodings) << '\n';
765
766   uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
767   outs() << "  Personality function array section offset: "
768          << format("0x%" PRIx32, PersonalitiesStart) << '\n';
769   uint32_t NumPersonalities = readNext<uint32_t>(Pos);
770   outs() << "  Number of personality functions in array:  "
771          << format("0x%" PRIx32, NumPersonalities) << '\n';
772
773   uint32_t IndicesStart = readNext<uint32_t>(Pos);
774   outs() << "  Index array section offset:                "
775          << format("0x%" PRIx32, IndicesStart) << '\n';
776   uint32_t NumIndices = readNext<uint32_t>(Pos);
777   outs() << "  Number of indices in array:                "
778          << format("0x%" PRIx32, NumIndices) << '\n';
779
780   //===----------------------------------
781   // A shared list of common encodings
782   //===----------------------------------
783
784   // These occupy indices in the range [0, N] whenever an encoding is referenced
785   // from a compressed 2nd level index table. In practice the linker only
786   // creates ~128 of these, so that indices are available to embed encodings in
787   // the 2nd level index.
788
789   SmallVector<uint32_t, 64> CommonEncodings;
790   outs() << "  Common encodings: (count = " << NumCommonEncodings << ")\n";
791   Pos = Contents.data() + CommonEncodingsStart;
792   for (unsigned i = 0; i < NumCommonEncodings; ++i) {
793     uint32_t Encoding = readNext<uint32_t>(Pos);
794     CommonEncodings.push_back(Encoding);
795
796     outs() << "    encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
797            << '\n';
798   }
799
800
801   //===----------------------------------
802   // Personality functions used in this executable
803   //===----------------------------------
804
805   // There should be only a handful of these (one per source language,
806   // roughly). Particularly since they only get 2 bits in the compact encoding.
807
808   outs() << "  Personality functions: (count = " << NumPersonalities << ")\n";
809   Pos = Contents.data() + PersonalitiesStart;
810   for (unsigned i = 0; i < NumPersonalities; ++i) {
811     uint32_t PersonalityFn = readNext<uint32_t>(Pos);
812     outs() << "    personality[" << i + 1
813            << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
814   }
815
816   //===----------------------------------
817   // The level 1 index entries
818   //===----------------------------------
819
820   // These specify an approximate place to start searching for the more detailed
821   // information, sorted by PC.
822
823   struct IndexEntry {
824     uint32_t FunctionOffset;
825     uint32_t SecondLevelPageStart;
826     uint32_t LSDAStart;
827   };
828
829   SmallVector<IndexEntry, 4> IndexEntries;
830
831   outs() << "  Top level indices: (count = " << NumIndices << ")\n";
832   Pos = Contents.data() + IndicesStart;
833   for (unsigned i = 0; i < NumIndices; ++i) {
834     IndexEntry Entry;
835
836     Entry.FunctionOffset = readNext<uint32_t>(Pos);
837     Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
838     Entry.LSDAStart = readNext<uint32_t>(Pos);
839     IndexEntries.push_back(Entry);
840
841     outs() << "    [" << i << "]: "
842            << "function offset="
843            << format("0x%08" PRIx32, Entry.FunctionOffset) << ", "
844            << "2nd level page offset="
845            << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
846            << "LSDA offset="
847            << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
848   }
849
850
851   //===----------------------------------
852   // Next come the LSDA tables
853   //===----------------------------------
854
855   // The LSDA layout is rather implicit: it's a contiguous array of entries from
856   // the first top-level index's LSDAOffset to the last (sentinel).
857
858   outs() << "  LSDA descriptors:\n";
859   Pos = Contents.data() + IndexEntries[0].LSDAStart;
860   int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
861                  (2 * sizeof(uint32_t));
862   for (int i = 0; i < NumLSDAs; ++i) {
863     uint32_t FunctionOffset = readNext<uint32_t>(Pos);
864     uint32_t LSDAOffset = readNext<uint32_t>(Pos);
865     outs() << "    [" << i << "]: "
866            << "function offset="
867            << format("0x%08" PRIx32, FunctionOffset) << ", "
868            << "LSDA offset="
869            << format("0x%08" PRIx32, LSDAOffset) << '\n';
870   }
871
872   //===----------------------------------
873   // Finally, the 2nd level indices
874   //===----------------------------------
875
876   // Generally these are 4K in size, and have 2 possible forms:
877   //   + Regular stores up to 511 entries with disparate encodings
878   //   + Compressed stores up to 1021 entries if few enough compact encoding
879   //     values are used.
880   outs() << "  Second level indices:\n";
881   for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
882     // The final sentinel top-level index has no associated 2nd level page
883     if (IndexEntries[i].SecondLevelPageStart == 0)
884       break;
885
886     outs() << "    Second level index[" << i << "]: "
887            << "offset in section="
888            << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
889            << ", "
890            << "base function offset="
891            << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
892
893     Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
894     uint32_t Kind = *(support::ulittle32_t *)Pos;
895     if (Kind == 2)
896       printRegularSecondLevelUnwindPage(Pos);
897     else if (Kind == 3)
898       printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
899                                            CommonEncodings);
900     else
901       llvm_unreachable("Do not know how to print this kind of 2nd level page");
902
903   }
904 }
905
906 void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
907   std::map<uint64_t, SymbolRef> Symbols;
908   for (const SymbolRef &SymRef : Obj->symbols()) {
909     // Discard any undefined or absolute symbols. They're not going to take part
910     // in the convenience lookup for unwind info and just take up resources.
911     section_iterator Section = Obj->section_end();
912     SymRef.getSection(Section);
913     if (Section == Obj->section_end())
914       continue;
915
916     uint64_t Addr;
917     SymRef.getAddress(Addr);
918     Symbols.insert(std::make_pair(Addr, SymRef));
919   }
920
921   for (const SectionRef &Section : Obj->sections()) {
922     StringRef SectName;
923     Section.getName(SectName);
924     if (SectName == "__compact_unwind")
925       printMachOCompactUnwindSection(Obj, Symbols, Section);
926     else if (SectName == "__unwind_info")
927       printMachOUnwindInfoSection(Obj, Symbols, Section);
928     else if (SectName == "__eh_frame")
929       outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
930
931   }
932 }