[llvm-objdump] for mach-o add -bind, -lazy-bind, and -weak-bind options
[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 std::string ThumbTripleName;
54
55 static const Target *GetTarget(const MachOObjectFile *MachOObj,
56                                const char **McpuDefault,
57                                const Target **ThumbTarget) {
58   // Figure out the target triple.
59   if (TripleName.empty()) {
60     llvm::Triple TT("unknown-unknown-unknown");
61     llvm::Triple ThumbTriple = Triple();
62     TT = MachOObj->getArch(McpuDefault, &ThumbTriple);
63     TripleName = TT.str();
64     ThumbTripleName = ThumbTriple.str();
65   }
66
67   // Get the target specific parser.
68   std::string Error;
69   const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
70   if (TheTarget && ThumbTripleName.empty())
71     return TheTarget;
72
73   *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
74   if (*ThumbTarget)
75     return TheTarget;
76
77   errs() << "llvm-objdump: error: unable to get target for '";
78   if (!TheTarget)
79     errs() << TripleName;
80   else
81     errs() << ThumbTripleName;
82   errs() << "', see --version and --triple.\n";
83   return nullptr;
84 }
85
86 struct SymbolSorter {
87   bool operator()(const SymbolRef &A, const SymbolRef &B) {
88     SymbolRef::Type AType, BType;
89     A.getType(AType);
90     B.getType(BType);
91
92     uint64_t AAddr, BAddr;
93     if (AType != SymbolRef::ST_Function)
94       AAddr = 0;
95     else
96       A.getAddress(AAddr);
97     if (BType != SymbolRef::ST_Function)
98       BAddr = 0;
99     else
100       B.getAddress(BAddr);
101     return AAddr < BAddr;
102   }
103 };
104
105 // Types for the storted data in code table that is built before disassembly
106 // and the predicate function to sort them.
107 typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
108 typedef std::vector<DiceTableEntry> DiceTable;
109 typedef DiceTable::iterator dice_table_iterator;
110
111 static bool
112 compareDiceTableEntries(const DiceTableEntry i,
113                         const DiceTableEntry j) {
114   return i.first == j.first;
115 }
116
117 static void DumpDataInCode(const char *bytes, uint64_t Size,
118                            unsigned short Kind) {
119   uint64_t Value;
120
121   switch (Kind) {
122   case MachO::DICE_KIND_DATA:
123     switch (Size) {
124     case 4:
125       Value = bytes[3] << 24 |
126               bytes[2] << 16 |
127               bytes[1] << 8 |
128               bytes[0];
129       outs() << "\t.long " << Value;
130       break;
131     case 2:
132       Value = bytes[1] << 8 |
133               bytes[0];
134       outs() << "\t.short " << Value;
135       break;
136     case 1:
137       Value = bytes[0];
138       outs() << "\t.byte " << Value;
139       break;
140     }
141     outs() << "\t@ KIND_DATA\n";
142     break;
143   case MachO::DICE_KIND_JUMP_TABLE8:
144     Value = bytes[0];
145     outs() << "\t.byte " << Value << "\t@ KIND_JUMP_TABLE8";
146     break;
147   case MachO::DICE_KIND_JUMP_TABLE16:
148     Value = bytes[1] << 8 |
149             bytes[0];
150     outs() << "\t.short " << Value << "\t@ KIND_JUMP_TABLE16";
151     break;
152   case MachO::DICE_KIND_JUMP_TABLE32:
153     Value = bytes[3] << 24 |
154             bytes[2] << 16 |
155             bytes[1] << 8 |
156             bytes[0];
157     outs() << "\t.long " << Value << "\t@ KIND_JUMP_TABLE32";
158     break;
159   default:
160     outs() << "\t@ data in code kind = " << Kind << "\n";
161     break;
162   }
163 }
164
165 static void getSectionsAndSymbols(const MachO::mach_header Header,
166                                   MachOObjectFile *MachOObj,
167                                   std::vector<SectionRef> &Sections,
168                                   std::vector<SymbolRef> &Symbols,
169                                   SmallVectorImpl<uint64_t> &FoundFns,
170                                   uint64_t &BaseSegmentAddress) {
171   for (const SymbolRef &Symbol : MachOObj->symbols())
172     Symbols.push_back(Symbol);
173
174   for (const SectionRef &Section : MachOObj->sections()) {
175     StringRef SectName;
176     Section.getName(SectName);
177     Sections.push_back(Section);
178   }
179
180   MachOObjectFile::LoadCommandInfo Command =
181       MachOObj->getFirstLoadCommandInfo();
182   bool BaseSegmentAddressSet = false;
183   for (unsigned i = 0; ; ++i) {
184     if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
185       // We found a function starts segment, parse the addresses for later
186       // consumption.
187       MachO::linkedit_data_command LLC =
188         MachOObj->getLinkeditDataLoadCommand(Command);
189
190       MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
191     }
192     else if (Command.C.cmd == MachO::LC_SEGMENT) {
193       MachO::segment_command SLC =
194         MachOObj->getSegmentLoadCommand(Command);
195       StringRef SegName = SLC.segname;
196       if(!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
197         BaseSegmentAddressSet = true;
198         BaseSegmentAddress = SLC.vmaddr;
199       }
200     }
201
202     if (i == Header.ncmds - 1)
203       break;
204     else
205       Command = MachOObj->getNextLoadCommandInfo(Command);
206   }
207 }
208
209 static void DisassembleInputMachO2(StringRef Filename,
210                                    MachOObjectFile *MachOOF);
211
212 void llvm::DisassembleInputMachO(StringRef Filename) {
213   ErrorOr<std::unique_ptr<MemoryBuffer>> BuffOrErr =
214       MemoryBuffer::getFileOrSTDIN(Filename);
215   if (std::error_code EC = BuffOrErr.getError()) {
216     errs() << "llvm-objdump: " << Filename << ": " << EC.message() << "\n";
217     return;
218   }
219   std::unique_ptr<MemoryBuffer> Buff = std::move(BuffOrErr.get());
220
221   std::unique_ptr<MachOObjectFile> MachOOF = std::move(
222       ObjectFile::createMachOObjectFile(Buff.get()->getMemBufferRef()).get());
223
224   DisassembleInputMachO2(Filename, MachOOF.get());
225 }
226
227 static void DisassembleInputMachO2(StringRef Filename,
228                                    MachOObjectFile *MachOOF) {
229   const char *McpuDefault = nullptr;
230   const Target *ThumbTarget = nullptr;
231   const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
232   if (!TheTarget) {
233     // GetTarget prints out stuff.
234     return;
235   }
236   if (MCPU.empty() && McpuDefault)
237     MCPU = McpuDefault;
238
239   std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
240   std::unique_ptr<MCInstrAnalysis> InstrAnalysis(
241       TheTarget->createMCInstrAnalysis(InstrInfo.get()));
242   std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
243   std::unique_ptr<MCInstrAnalysis> ThumbInstrAnalysis;
244   if (ThumbTarget) {
245     ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
246     ThumbInstrAnalysis.reset(
247         ThumbTarget->createMCInstrAnalysis(ThumbInstrInfo.get()));
248   }
249
250   // Package up features to be passed to target/subtarget
251   std::string FeaturesStr;
252   if (MAttrs.size()) {
253     SubtargetFeatures Features;
254     for (unsigned i = 0; i != MAttrs.size(); ++i)
255       Features.AddFeature(MAttrs[i]);
256     FeaturesStr = Features.getString();
257   }
258
259   // Set up disassembler.
260   std::unique_ptr<const MCRegisterInfo> MRI(
261       TheTarget->createMCRegInfo(TripleName));
262   std::unique_ptr<const MCAsmInfo> AsmInfo(
263       TheTarget->createMCAsmInfo(*MRI, TripleName));
264   std::unique_ptr<const MCSubtargetInfo> STI(
265       TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
266   MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
267   std::unique_ptr<const MCDisassembler> DisAsm(
268       TheTarget->createMCDisassembler(*STI, Ctx));
269   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
270   std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
271       AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI, *STI));
272
273   if (!InstrAnalysis || !AsmInfo || !STI || !DisAsm || !IP) {
274     errs() << "error: couldn't initialize disassembler for target "
275            << TripleName << '\n';
276     return;
277   }
278
279   // Set up thumb disassembler.
280   std::unique_ptr<const MCRegisterInfo> ThumbMRI;
281   std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
282   std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
283   std::unique_ptr<const MCDisassembler> ThumbDisAsm;
284   std::unique_ptr<MCInstPrinter> ThumbIP;
285   std::unique_ptr<MCContext> ThumbCtx;
286   if (ThumbTarget) {
287     ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
288     ThumbAsmInfo.reset(
289         ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
290     ThumbSTI.reset(
291         ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
292     ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
293     ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
294     int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
295     ThumbIP.reset(ThumbTarget->createMCInstPrinter(
296         ThumbAsmPrinterVariant, *ThumbAsmInfo, *ThumbInstrInfo, *ThumbMRI,
297         *ThumbSTI));
298   }
299
300   if (ThumbTarget && (!ThumbInstrAnalysis || !ThumbAsmInfo || !ThumbSTI ||
301                       !ThumbDisAsm || !ThumbIP)) {
302     errs() << "error: couldn't initialize disassembler for target "
303            << ThumbTripleName << '\n';
304     return;
305   }
306
307   outs() << '\n' << Filename << ":\n\n";
308
309   MachO::mach_header Header = MachOOF->getHeader();
310
311   // FIXME: Using the -cfg command line option, this code used to be able to
312   // annotate relocations with the referenced symbol's name, and if this was
313   // inside a __[cf]string section, the data it points to. This is now replaced
314   // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
315   std::vector<SectionRef> Sections;
316   std::vector<SymbolRef> Symbols;
317   SmallVector<uint64_t, 8> FoundFns;
318   uint64_t BaseSegmentAddress;
319
320   getSectionsAndSymbols(Header, MachOOF, Sections, Symbols, FoundFns,
321                         BaseSegmentAddress);
322
323   // Sort the symbols by address, just in case they didn't come in that way.
324   std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
325
326   // Build a data in code table that is sorted on by the address of each entry.
327   uint64_t BaseAddress = 0;
328   if (Header.filetype == MachO::MH_OBJECT)
329     Sections[0].getAddress(BaseAddress);
330   else
331     BaseAddress = BaseSegmentAddress;
332   DiceTable Dices;
333   for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
334        DI != DE; ++DI) {
335     uint32_t Offset;
336     DI->getOffset(Offset);
337     Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
338   }
339   array_pod_sort(Dices.begin(), Dices.end());
340
341 #ifndef NDEBUG
342   raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
343 #else
344   raw_ostream &DebugOut = nulls();
345 #endif
346
347   std::unique_ptr<DIContext> diContext;
348   ObjectFile *DbgObj = MachOOF;
349   // Try to find debug info and set up the DIContext for it.
350   if (UseDbg) {
351     // A separate DSym file path was specified, parse it as a macho file,
352     // get the sections and supply it to the section name parsing machinery.
353     if (!DSYMFile.empty()) {
354       ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
355           MemoryBuffer::getFileOrSTDIN(DSYMFile);
356       if (std::error_code EC = BufOrErr.getError()) {
357         errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
358         return;
359       }
360       DbgObj =
361           ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
362               .get()
363               .release();
364     }
365
366     // Setup the DIContext
367     diContext.reset(DIContext::getDWARFContext(*DbgObj));
368   }
369
370   for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
371
372     bool SectIsText = false;
373     Sections[SectIdx].isText(SectIsText);
374     if (SectIsText == false)
375       continue;
376
377     StringRef SectName;
378     if (Sections[SectIdx].getName(SectName) ||
379         SectName != "__text")
380       continue; // Skip non-text sections
381
382     DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
383
384     StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
385     if (SegmentName != "__TEXT")
386       continue;
387
388     StringRef Bytes;
389     Sections[SectIdx].getContents(Bytes);
390     StringRefMemoryObject memoryObject(Bytes);
391     bool symbolTableWorked = false;
392
393     // Parse relocations.
394     std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
395     for (const RelocationRef &Reloc : Sections[SectIdx].relocations()) {
396       uint64_t RelocOffset, SectionAddress;
397       Reloc.getOffset(RelocOffset);
398       Sections[SectIdx].getAddress(SectionAddress);
399       RelocOffset -= SectionAddress;
400
401       symbol_iterator RelocSym = Reloc.getSymbol();
402
403       Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
404     }
405     array_pod_sort(Relocs.begin(), Relocs.end());
406
407     // Disassemble symbol by symbol.
408     for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
409       StringRef SymName;
410       Symbols[SymIdx].getName(SymName);
411
412       SymbolRef::Type ST;
413       Symbols[SymIdx].getType(ST);
414       if (ST != SymbolRef::ST_Function)
415         continue;
416
417       // Make sure the symbol is defined in this section.
418       bool containsSym = false;
419       Sections[SectIdx].containsSymbol(Symbols[SymIdx], containsSym);
420       if (!containsSym)
421         continue;
422
423       // Start at the address of the symbol relative to the section's address.
424       uint64_t SectionAddress = 0;
425       uint64_t Start = 0;
426       Sections[SectIdx].getAddress(SectionAddress);
427       Symbols[SymIdx].getAddress(Start);
428       Start -= SectionAddress;
429
430       // Stop disassembling either at the beginning of the next symbol or at
431       // the end of the section.
432       bool containsNextSym = false;
433       uint64_t NextSym = 0;
434       uint64_t NextSymIdx = SymIdx+1;
435       while (Symbols.size() > NextSymIdx) {
436         SymbolRef::Type NextSymType;
437         Symbols[NextSymIdx].getType(NextSymType);
438         if (NextSymType == SymbolRef::ST_Function) {
439           Sections[SectIdx].containsSymbol(Symbols[NextSymIdx],
440                                            containsNextSym);
441           Symbols[NextSymIdx].getAddress(NextSym);
442           NextSym -= SectionAddress;
443           break;
444         }
445         ++NextSymIdx;
446       }
447
448       uint64_t SectSize;
449       Sections[SectIdx].getSize(SectSize);
450       uint64_t End = containsNextSym ?  NextSym : SectSize;
451       uint64_t Size;
452
453       symbolTableWorked = true;
454
455       DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
456       bool isThumb =
457           (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
458
459       outs() << SymName << ":\n";
460       DILineInfo lastLine;
461       for (uint64_t Index = Start; Index < End; Index += Size) {
462         MCInst Inst;
463
464         uint64_t SectAddress = 0;
465         Sections[SectIdx].getAddress(SectAddress);
466         outs() << format("%8" PRIx64 ":\t", SectAddress + Index);
467
468         // Check the data in code table here to see if this is data not an
469         // instruction to be disassembled.
470         DiceTable Dice;
471         Dice.push_back(std::make_pair(SectAddress + Index, DiceRef()));
472         dice_table_iterator DTI = std::search(Dices.begin(), Dices.end(),
473                                               Dice.begin(), Dice.end(),
474                                               compareDiceTableEntries);
475         if (DTI != Dices.end()){
476           uint16_t Length;
477           DTI->second.getLength(Length);
478           DumpBytes(StringRef(Bytes.data() + Index, Length));
479           uint16_t Kind;
480           DTI->second.getKind(Kind);
481           DumpDataInCode(Bytes.data() + Index, Length, Kind);
482           continue;
483         }
484
485         bool gotInst;
486         if (isThumb)
487           gotInst = ThumbDisAsm->getInstruction(Inst, Size, memoryObject, Index,
488                                      DebugOut, nulls());
489         else
490           gotInst = DisAsm->getInstruction(Inst, Size, memoryObject, Index,
491                                      DebugOut, nulls());
492         if (gotInst) {
493           DumpBytes(StringRef(Bytes.data() + Index, Size));
494           if (isThumb)
495             ThumbIP->printInst(&Inst, outs(), "");
496           else
497             IP->printInst(&Inst, outs(), "");
498
499           // Print debug info.
500           if (diContext) {
501             DILineInfo dli =
502               diContext->getLineInfoForAddress(SectAddress + Index);
503             // Print valid line info if it changed.
504             if (dli != lastLine && dli.Line != 0)
505               outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
506                      << dli.Column;
507             lastLine = dli;
508           }
509           outs() << "\n";
510         } else {
511           errs() << "llvm-objdump: warning: invalid instruction encoding\n";
512           if (Size == 0)
513             Size = 1; // skip illegible bytes
514         }
515       }
516     }
517     if (!symbolTableWorked) {
518       // Reading the symbol table didn't work, disassemble the whole section. 
519       uint64_t SectAddress;
520       Sections[SectIdx].getAddress(SectAddress);
521       uint64_t SectSize;
522       Sections[SectIdx].getSize(SectSize);
523       uint64_t InstSize;
524       for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
525         MCInst Inst;
526
527         if (DisAsm->getInstruction(Inst, InstSize, memoryObject, Index,
528                                    DebugOut, nulls())) {
529           outs() << format("%8" PRIx64 ":\t", SectAddress + Index);
530           DumpBytes(StringRef(Bytes.data() + Index, InstSize));
531           IP->printInst(&Inst, outs(), "");
532           outs() << "\n";
533         } else {
534           errs() << "llvm-objdump: warning: invalid instruction encoding\n";
535           if (InstSize == 0)
536             InstSize = 1; // skip illegible bytes
537         }
538       }
539     }
540   }
541 }
542
543
544 //===----------------------------------------------------------------------===//
545 // __compact_unwind section dumping
546 //===----------------------------------------------------------------------===//
547
548 namespace {
549
550 template <typename T> static uint64_t readNext(const char *&Buf) {
551     using llvm::support::little;
552     using llvm::support::unaligned;
553
554     uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
555     Buf += sizeof(T);
556     return Val;
557   }
558
559 struct CompactUnwindEntry {
560   uint32_t OffsetInSection;
561
562   uint64_t FunctionAddr;
563   uint32_t Length;
564   uint32_t CompactEncoding;
565   uint64_t PersonalityAddr;
566   uint64_t LSDAAddr;
567
568   RelocationRef FunctionReloc;
569   RelocationRef PersonalityReloc;
570   RelocationRef LSDAReloc;
571
572   CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
573     : OffsetInSection(Offset) {
574     if (Is64)
575       read<uint64_t>(Contents.data() + Offset);
576     else
577       read<uint32_t>(Contents.data() + Offset);
578   }
579
580 private:
581   template<typename UIntPtr>
582   void read(const char *Buf) {
583     FunctionAddr = readNext<UIntPtr>(Buf);
584     Length = readNext<uint32_t>(Buf);
585     CompactEncoding = readNext<uint32_t>(Buf);
586     PersonalityAddr = readNext<UIntPtr>(Buf);
587     LSDAAddr = readNext<UIntPtr>(Buf);
588   }
589 };
590 }
591
592 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
593 /// and data being relocated, determine the best base Name and Addend to use for
594 /// display purposes.
595 ///
596 /// 1. An Extern relocation will directly reference a symbol (and the data is
597 ///    then already an addend), so use that.
598 /// 2. Otherwise the data is an offset in the object file's layout; try to find
599 //     a symbol before it in the same section, and use the offset from there.
600 /// 3. Finally, if all that fails, fall back to an offset from the start of the
601 ///    referenced section.
602 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
603                                       std::map<uint64_t, SymbolRef> &Symbols,
604                                       const RelocationRef &Reloc,
605                                       uint64_t Addr,
606                                       StringRef &Name, uint64_t &Addend) {
607   if (Reloc.getSymbol() != Obj->symbol_end()) {
608     Reloc.getSymbol()->getName(Name);
609     Addend = Addr;
610     return;
611   }
612
613   auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
614   SectionRef RelocSection = Obj->getRelocationSection(RE);
615
616   uint64_t SectionAddr;
617   RelocSection.getAddress(SectionAddr);
618
619   auto Sym = Symbols.upper_bound(Addr);
620   if (Sym == Symbols.begin()) {
621     // The first symbol in the object is after this reference, the best we can
622     // do is section-relative notation.
623     RelocSection.getName(Name);
624     Addend = Addr - SectionAddr;
625     return;
626   }
627
628   // Go back one so that SymbolAddress <= Addr.
629   --Sym;
630
631   section_iterator SymSection = Obj->section_end();
632   Sym->second.getSection(SymSection);
633   if (RelocSection == *SymSection) {
634     // There's a valid symbol in the same section before this reference.
635     Sym->second.getName(Name);
636     Addend = Addr - Sym->first;
637     return;
638   }
639
640   // There is a symbol before this reference, but it's in a different
641   // section. Probably not helpful to mention it, so use the section name.
642   RelocSection.getName(Name);
643   Addend = Addr - SectionAddr;
644 }
645
646 static void printUnwindRelocDest(const MachOObjectFile *Obj,
647                                  std::map<uint64_t, SymbolRef> &Symbols,
648                                  const RelocationRef &Reloc,
649                                  uint64_t Addr) {
650   StringRef Name;
651   uint64_t Addend;
652
653   if (!Reloc.getObjectFile())
654     return;
655
656   findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
657
658   outs() << Name;
659   if (Addend)
660     outs() << " + " << format("0x%" PRIx64, Addend);
661 }
662
663 static void
664 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
665                                std::map<uint64_t, SymbolRef> &Symbols,
666                                const SectionRef &CompactUnwind) {
667
668   assert(Obj->isLittleEndian() &&
669          "There should not be a big-endian .o with __compact_unwind");
670
671   bool Is64 = Obj->is64Bit();
672   uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
673   uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
674
675   StringRef Contents;
676   CompactUnwind.getContents(Contents);
677
678   SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
679
680   // First populate the initial raw offsets, encodings and so on from the entry.
681   for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
682     CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
683     CompactUnwinds.push_back(Entry);
684   }
685
686   // Next we need to look at the relocations to find out what objects are
687   // actually being referred to.
688   for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
689     uint64_t RelocAddress;
690     Reloc.getOffset(RelocAddress);
691
692     uint32_t EntryIdx = RelocAddress / EntrySize;
693     uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
694     CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
695
696     if (OffsetInEntry == 0)
697       Entry.FunctionReloc = Reloc;
698     else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
699       Entry.PersonalityReloc = Reloc;
700     else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
701       Entry.LSDAReloc = Reloc;
702     else
703       llvm_unreachable("Unexpected relocation in __compact_unwind section");
704   }
705
706   // Finally, we're ready to print the data we've gathered.
707   outs() << "Contents of __compact_unwind section:\n";
708   for (auto &Entry : CompactUnwinds) {
709     outs() << "  Entry at offset "
710            << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
711
712     // 1. Start of the region this entry applies to.
713     outs() << "    start:                "
714            << format("0x%" PRIx64, Entry.FunctionAddr) << ' ';
715     printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc,
716                          Entry.FunctionAddr);
717     outs() << '\n';
718
719     // 2. Length of the region this entry applies to.
720     outs() << "    length:               "
721            << format("0x%" PRIx32, Entry.Length) << '\n';
722     // 3. The 32-bit compact encoding.
723     outs() << "    compact encoding:     "
724            << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
725
726     // 4. The personality function, if present.
727     if (Entry.PersonalityReloc.getObjectFile()) {
728       outs() << "    personality function: "
729              << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
730       printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
731                            Entry.PersonalityAddr);
732       outs() << '\n';
733     }
734
735     // 5. This entry's language-specific data area.
736     if (Entry.LSDAReloc.getObjectFile()) {
737       outs() << "    LSDA:                 "
738              << format("0x%" PRIx64, Entry.LSDAAddr) << ' ';
739       printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
740       outs() << '\n';
741     }
742   }
743 }
744
745 //===----------------------------------------------------------------------===//
746 // __unwind_info section dumping
747 //===----------------------------------------------------------------------===//
748
749 static void printRegularSecondLevelUnwindPage(const char *PageStart) {
750   const char *Pos = PageStart;
751   uint32_t Kind = readNext<uint32_t>(Pos);
752   (void)Kind;
753   assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
754
755   uint16_t EntriesStart = readNext<uint16_t>(Pos);
756   uint16_t NumEntries = readNext<uint16_t>(Pos);
757
758   Pos = PageStart + EntriesStart;
759   for (unsigned i = 0; i < NumEntries; ++i) {
760     uint32_t FunctionOffset = readNext<uint32_t>(Pos);
761     uint32_t Encoding = readNext<uint32_t>(Pos);
762
763     outs() << "      [" << i << "]: "
764            << "function offset="
765            << format("0x%08" PRIx32, FunctionOffset) << ", "
766            << "encoding="
767            << format("0x%08" PRIx32, Encoding)
768            << '\n';
769   }
770 }
771
772 static void printCompressedSecondLevelUnwindPage(
773     const char *PageStart, uint32_t FunctionBase,
774     const SmallVectorImpl<uint32_t> &CommonEncodings) {
775   const char *Pos = PageStart;
776   uint32_t Kind = readNext<uint32_t>(Pos);
777   (void)Kind;
778   assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
779
780   uint16_t EntriesStart = readNext<uint16_t>(Pos);
781   uint16_t NumEntries = readNext<uint16_t>(Pos);
782
783   uint16_t EncodingsStart = readNext<uint16_t>(Pos);
784   readNext<uint16_t>(Pos);
785   const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
786       PageStart + EncodingsStart);
787
788   Pos = PageStart + EntriesStart;
789   for (unsigned i = 0; i < NumEntries; ++i) {
790     uint32_t Entry = readNext<uint32_t>(Pos);
791     uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
792     uint32_t EncodingIdx = Entry >> 24;
793
794     uint32_t Encoding;
795     if (EncodingIdx < CommonEncodings.size())
796       Encoding = CommonEncodings[EncodingIdx];
797     else
798       Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
799
800     outs() << "      [" << i << "]: "
801            << "function offset="
802            << format("0x%08" PRIx32, FunctionOffset) << ", "
803            << "encoding[" << EncodingIdx << "]="
804            << format("0x%08" PRIx32, Encoding)
805            << '\n';
806   }
807 }
808
809 static void
810 printMachOUnwindInfoSection(const MachOObjectFile *Obj,
811                             std::map<uint64_t, SymbolRef> &Symbols,
812                             const SectionRef &UnwindInfo) {
813
814   assert(Obj->isLittleEndian() &&
815          "There should not be a big-endian .o with __unwind_info");
816
817   outs() << "Contents of __unwind_info section:\n";
818
819   StringRef Contents;
820   UnwindInfo.getContents(Contents);
821   const char *Pos = Contents.data();
822
823   //===----------------------------------
824   // Section header
825   //===----------------------------------
826
827   uint32_t Version = readNext<uint32_t>(Pos);
828   outs() << "  Version:                                   "
829          << format("0x%" PRIx32, Version) << '\n';
830   assert(Version == 1 && "only understand version 1");
831
832   uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
833   outs() << "  Common encodings array section offset:     "
834          << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
835   uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
836   outs() << "  Number of common encodings in array:       "
837          << format("0x%" PRIx32, NumCommonEncodings) << '\n';
838
839   uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
840   outs() << "  Personality function array section offset: "
841          << format("0x%" PRIx32, PersonalitiesStart) << '\n';
842   uint32_t NumPersonalities = readNext<uint32_t>(Pos);
843   outs() << "  Number of personality functions in array:  "
844          << format("0x%" PRIx32, NumPersonalities) << '\n';
845
846   uint32_t IndicesStart = readNext<uint32_t>(Pos);
847   outs() << "  Index array section offset:                "
848          << format("0x%" PRIx32, IndicesStart) << '\n';
849   uint32_t NumIndices = readNext<uint32_t>(Pos);
850   outs() << "  Number of indices in array:                "
851          << format("0x%" PRIx32, NumIndices) << '\n';
852
853   //===----------------------------------
854   // A shared list of common encodings
855   //===----------------------------------
856
857   // These occupy indices in the range [0, N] whenever an encoding is referenced
858   // from a compressed 2nd level index table. In practice the linker only
859   // creates ~128 of these, so that indices are available to embed encodings in
860   // the 2nd level index.
861
862   SmallVector<uint32_t, 64> CommonEncodings;
863   outs() << "  Common encodings: (count = " << NumCommonEncodings << ")\n";
864   Pos = Contents.data() + CommonEncodingsStart;
865   for (unsigned i = 0; i < NumCommonEncodings; ++i) {
866     uint32_t Encoding = readNext<uint32_t>(Pos);
867     CommonEncodings.push_back(Encoding);
868
869     outs() << "    encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
870            << '\n';
871   }
872
873
874   //===----------------------------------
875   // Personality functions used in this executable
876   //===----------------------------------
877
878   // There should be only a handful of these (one per source language,
879   // roughly). Particularly since they only get 2 bits in the compact encoding.
880
881   outs() << "  Personality functions: (count = " << NumPersonalities << ")\n";
882   Pos = Contents.data() + PersonalitiesStart;
883   for (unsigned i = 0; i < NumPersonalities; ++i) {
884     uint32_t PersonalityFn = readNext<uint32_t>(Pos);
885     outs() << "    personality[" << i + 1
886            << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
887   }
888
889   //===----------------------------------
890   // The level 1 index entries
891   //===----------------------------------
892
893   // These specify an approximate place to start searching for the more detailed
894   // information, sorted by PC.
895
896   struct IndexEntry {
897     uint32_t FunctionOffset;
898     uint32_t SecondLevelPageStart;
899     uint32_t LSDAStart;
900   };
901
902   SmallVector<IndexEntry, 4> IndexEntries;
903
904   outs() << "  Top level indices: (count = " << NumIndices << ")\n";
905   Pos = Contents.data() + IndicesStart;
906   for (unsigned i = 0; i < NumIndices; ++i) {
907     IndexEntry Entry;
908
909     Entry.FunctionOffset = readNext<uint32_t>(Pos);
910     Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
911     Entry.LSDAStart = readNext<uint32_t>(Pos);
912     IndexEntries.push_back(Entry);
913
914     outs() << "    [" << i << "]: "
915            << "function offset="
916            << format("0x%08" PRIx32, Entry.FunctionOffset) << ", "
917            << "2nd level page offset="
918            << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
919            << "LSDA offset="
920            << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
921   }
922
923
924   //===----------------------------------
925   // Next come the LSDA tables
926   //===----------------------------------
927
928   // The LSDA layout is rather implicit: it's a contiguous array of entries from
929   // the first top-level index's LSDAOffset to the last (sentinel).
930
931   outs() << "  LSDA descriptors:\n";
932   Pos = Contents.data() + IndexEntries[0].LSDAStart;
933   int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
934                  (2 * sizeof(uint32_t));
935   for (int i = 0; i < NumLSDAs; ++i) {
936     uint32_t FunctionOffset = readNext<uint32_t>(Pos);
937     uint32_t LSDAOffset = readNext<uint32_t>(Pos);
938     outs() << "    [" << i << "]: "
939            << "function offset="
940            << format("0x%08" PRIx32, FunctionOffset) << ", "
941            << "LSDA offset="
942            << format("0x%08" PRIx32, LSDAOffset) << '\n';
943   }
944
945   //===----------------------------------
946   // Finally, the 2nd level indices
947   //===----------------------------------
948
949   // Generally these are 4K in size, and have 2 possible forms:
950   //   + Regular stores up to 511 entries with disparate encodings
951   //   + Compressed stores up to 1021 entries if few enough compact encoding
952   //     values are used.
953   outs() << "  Second level indices:\n";
954   for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
955     // The final sentinel top-level index has no associated 2nd level page
956     if (IndexEntries[i].SecondLevelPageStart == 0)
957       break;
958
959     outs() << "    Second level index[" << i << "]: "
960            << "offset in section="
961            << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
962            << ", "
963            << "base function offset="
964            << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
965
966     Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
967     uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
968     if (Kind == 2)
969       printRegularSecondLevelUnwindPage(Pos);
970     else if (Kind == 3)
971       printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
972                                            CommonEncodings);
973     else
974       llvm_unreachable("Do not know how to print this kind of 2nd level page");
975
976   }
977 }
978
979 void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
980   std::map<uint64_t, SymbolRef> Symbols;
981   for (const SymbolRef &SymRef : Obj->symbols()) {
982     // Discard any undefined or absolute symbols. They're not going to take part
983     // in the convenience lookup for unwind info and just take up resources.
984     section_iterator Section = Obj->section_end();
985     SymRef.getSection(Section);
986     if (Section == Obj->section_end())
987       continue;
988
989     uint64_t Addr;
990     SymRef.getAddress(Addr);
991     Symbols.insert(std::make_pair(Addr, SymRef));
992   }
993
994   for (const SectionRef &Section : Obj->sections()) {
995     StringRef SectName;
996     Section.getName(SectName);
997     if (SectName == "__compact_unwind")
998       printMachOCompactUnwindSection(Obj, Symbols, Section);
999     else if (SectName == "__unwind_info")
1000       printMachOUnwindInfoSection(Obj, Symbols, Section);
1001     else if (SectName == "__eh_frame")
1002       outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
1003
1004   }
1005 }
1006
1007 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
1008                             uint32_t cpusubtype, uint32_t filetype,
1009                             uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
1010                             bool verbose) {
1011   outs() << "Mach header\n";
1012   outs() << "      magic cputype cpusubtype  caps    filetype ncmds "
1013             "sizeofcmds      flags\n";
1014   if (verbose) {
1015     if (magic == MachO::MH_MAGIC)
1016       outs() << "   MH_MAGIC";
1017     else if (magic == MachO::MH_MAGIC_64)
1018       outs() << "MH_MAGIC_64";
1019     else
1020       outs() << format(" 0x%08" PRIx32, magic);
1021     switch (cputype) {
1022     case MachO::CPU_TYPE_I386:
1023       outs() << "    I386";
1024       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1025       case MachO::CPU_SUBTYPE_I386_ALL:
1026         outs() << "        ALL";
1027         break;
1028       default:
1029         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1030         break;
1031       }
1032       break;
1033     case MachO::CPU_TYPE_X86_64:
1034       outs() << "  X86_64";
1035     case MachO::CPU_SUBTYPE_X86_64_ALL:
1036       outs() << "        ALL";
1037       break;
1038     case MachO::CPU_SUBTYPE_X86_64_H:
1039       outs() << "    Haswell";
1040       outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1041       break;
1042     case MachO::CPU_TYPE_ARM:
1043       outs() << "     ARM";
1044       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1045       case MachO::CPU_SUBTYPE_ARM_ALL:
1046         outs() << "        ALL";
1047         break;
1048       case MachO::CPU_SUBTYPE_ARM_V4T:
1049         outs() << "        V4T";
1050         break;
1051       case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1052         outs() << "      V5TEJ";
1053         break;
1054       case MachO::CPU_SUBTYPE_ARM_XSCALE:
1055         outs() << "     XSCALE";
1056         break;
1057       case MachO::CPU_SUBTYPE_ARM_V6:
1058         outs() << "         V6";
1059         break;
1060       case MachO::CPU_SUBTYPE_ARM_V6M:
1061         outs() << "        V6M";
1062         break;
1063       case MachO::CPU_SUBTYPE_ARM_V7:
1064         outs() << "         V7";
1065         break;
1066       case MachO::CPU_SUBTYPE_ARM_V7EM:
1067         outs() << "       V7EM";
1068         break;
1069       case MachO::CPU_SUBTYPE_ARM_V7K:
1070         outs() << "        V7K";
1071         break;
1072       case MachO::CPU_SUBTYPE_ARM_V7M:
1073         outs() << "        V7M";
1074         break;
1075       case MachO::CPU_SUBTYPE_ARM_V7S:
1076         outs() << "        V7S";
1077         break;
1078       default:
1079         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1080         break;
1081       }
1082       break;
1083     case MachO::CPU_TYPE_ARM64:
1084       outs() << "   ARM64";
1085       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1086       case MachO::CPU_SUBTYPE_ARM64_ALL:
1087         outs() << "        ALL";
1088         break;
1089       default:
1090         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1091         break;
1092       }
1093       break;
1094     case MachO::CPU_TYPE_POWERPC:
1095       outs() << "     PPC";
1096       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1097       case MachO::CPU_SUBTYPE_POWERPC_ALL:
1098         outs() << "        ALL";
1099         break;
1100       default:
1101         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1102         break;
1103       }
1104       break;
1105     case MachO::CPU_TYPE_POWERPC64:
1106       outs() << "   PPC64";
1107       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1108       case MachO::CPU_SUBTYPE_POWERPC_ALL:
1109         outs() << "        ALL";
1110         break;
1111       default:
1112         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1113         break;
1114       }
1115       break;
1116     }
1117     if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
1118       outs() << " LIB64";
1119     } else {
1120       outs() << format("  0x%02" PRIx32,
1121                        (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
1122     }
1123     switch (filetype) {
1124     case MachO::MH_OBJECT:
1125       outs() << "      OBJECT";
1126       break;
1127     case MachO::MH_EXECUTE:
1128       outs() << "     EXECUTE";
1129       break;
1130     case MachO::MH_FVMLIB:
1131       outs() << "      FVMLIB";
1132       break;
1133     case MachO::MH_CORE:
1134       outs() << "        CORE";
1135       break;
1136     case MachO::MH_PRELOAD:
1137       outs() << "     PRELOAD";
1138       break;
1139     case MachO::MH_DYLIB:
1140       outs() << "       DYLIB";
1141       break;
1142     case MachO::MH_DYLIB_STUB:
1143       outs() << "  DYLIB_STUB";
1144       break;
1145     case MachO::MH_DYLINKER:
1146       outs() << "    DYLINKER";
1147       break;
1148     case MachO::MH_BUNDLE:
1149       outs() << "      BUNDLE";
1150       break;
1151     case MachO::MH_DSYM:
1152       outs() << "        DSYM";
1153       break;
1154     case MachO::MH_KEXT_BUNDLE:
1155       outs() << "  KEXTBUNDLE";
1156       break;
1157     default:
1158       outs() << format("  %10u", filetype);
1159       break;
1160     }
1161     outs() << format(" %5u", ncmds);
1162     outs() << format(" %10u", sizeofcmds);
1163     uint32_t f = flags;
1164     if (f & MachO::MH_NOUNDEFS) {
1165       outs() << "   NOUNDEFS";
1166       f &= ~MachO::MH_NOUNDEFS;
1167     }
1168     if (f & MachO::MH_INCRLINK) {
1169       outs() << " INCRLINK";
1170       f &= ~MachO::MH_INCRLINK;
1171     }
1172     if (f & MachO::MH_DYLDLINK) {
1173       outs() << " DYLDLINK";
1174       f &= ~MachO::MH_DYLDLINK;
1175     }
1176     if (f & MachO::MH_BINDATLOAD) {
1177       outs() << " BINDATLOAD";
1178       f &= ~MachO::MH_BINDATLOAD;
1179     }
1180     if (f & MachO::MH_PREBOUND) {
1181       outs() << " PREBOUND";
1182       f &= ~MachO::MH_PREBOUND;
1183     }
1184     if (f & MachO::MH_SPLIT_SEGS) {
1185       outs() << " SPLIT_SEGS";
1186       f &= ~MachO::MH_SPLIT_SEGS;
1187     }
1188     if (f & MachO::MH_LAZY_INIT) {
1189       outs() << " LAZY_INIT";
1190       f &= ~MachO::MH_LAZY_INIT;
1191     }
1192     if (f & MachO::MH_TWOLEVEL) {
1193       outs() << " TWOLEVEL";
1194       f &= ~MachO::MH_TWOLEVEL;
1195     }
1196     if (f & MachO::MH_FORCE_FLAT) {
1197       outs() << " FORCE_FLAT";
1198       f &= ~MachO::MH_FORCE_FLAT;
1199     }
1200     if (f & MachO::MH_NOMULTIDEFS) {
1201       outs() << " NOMULTIDEFS";
1202       f &= ~MachO::MH_NOMULTIDEFS;
1203     }
1204     if (f & MachO::MH_NOFIXPREBINDING) {
1205       outs() << " NOFIXPREBINDING";
1206       f &= ~MachO::MH_NOFIXPREBINDING;
1207     }
1208     if (f & MachO::MH_PREBINDABLE) {
1209       outs() << " PREBINDABLE";
1210       f &= ~MachO::MH_PREBINDABLE;
1211     }
1212     if (f & MachO::MH_ALLMODSBOUND) {
1213       outs() << " ALLMODSBOUND";
1214       f &= ~MachO::MH_ALLMODSBOUND;
1215     }
1216     if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
1217       outs() << " SUBSECTIONS_VIA_SYMBOLS";
1218       f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
1219     }
1220     if (f & MachO::MH_CANONICAL) {
1221       outs() << " CANONICAL";
1222       f &= ~MachO::MH_CANONICAL;
1223     }
1224     if (f & MachO::MH_WEAK_DEFINES) {
1225       outs() << " WEAK_DEFINES";
1226       f &= ~MachO::MH_WEAK_DEFINES;
1227     }
1228     if (f & MachO::MH_BINDS_TO_WEAK) {
1229       outs() << " BINDS_TO_WEAK";
1230       f &= ~MachO::MH_BINDS_TO_WEAK;
1231     }
1232     if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
1233       outs() << " ALLOW_STACK_EXECUTION";
1234       f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
1235     }
1236     if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
1237       outs() << " DEAD_STRIPPABLE_DYLIB";
1238       f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
1239     }
1240     if (f & MachO::MH_PIE) {
1241       outs() << " PIE";
1242       f &= ~MachO::MH_PIE;
1243     }
1244     if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
1245       outs() << " NO_REEXPORTED_DYLIBS";
1246       f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
1247     }
1248     if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
1249       outs() << " MH_HAS_TLV_DESCRIPTORS";
1250       f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
1251     }
1252     if (f & MachO::MH_NO_HEAP_EXECUTION) {
1253       outs() << " MH_NO_HEAP_EXECUTION";
1254       f &= ~MachO::MH_NO_HEAP_EXECUTION;
1255     }
1256     if (f & MachO::MH_APP_EXTENSION_SAFE) {
1257       outs() << " APP_EXTENSION_SAFE";
1258       f &= ~MachO::MH_APP_EXTENSION_SAFE;
1259     }
1260     if (f != 0 || flags == 0)
1261       outs() << format(" 0x%08" PRIx32, f);
1262   } else {
1263     outs() << format(" 0x%08" PRIx32, magic);
1264     outs() << format(" %7d", cputype);
1265     outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1266     outs() << format("  0x%02" PRIx32,
1267                      (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
1268     outs() << format("  %10u", filetype);
1269     outs() << format(" %5u", ncmds);
1270     outs() << format(" %10u", sizeofcmds);
1271     outs() << format(" 0x%08" PRIx32, flags);
1272   }
1273   outs() << "\n";
1274 }
1275
1276 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
1277                                 StringRef SegName, uint64_t vmaddr,
1278                                 uint64_t vmsize, uint64_t fileoff,
1279                                 uint64_t filesize, uint32_t maxprot,
1280                                 uint32_t initprot, uint32_t nsects,
1281                                 uint32_t flags, uint32_t object_size,
1282                                 bool verbose) {
1283   uint64_t expected_cmdsize;
1284   if (cmd == MachO::LC_SEGMENT) {
1285     outs() << "      cmd LC_SEGMENT\n";
1286     expected_cmdsize = nsects;
1287     expected_cmdsize *= sizeof(struct MachO::section);
1288     expected_cmdsize += sizeof(struct MachO::segment_command);
1289   } else {
1290     outs() << "      cmd LC_SEGMENT_64\n";
1291     expected_cmdsize = nsects;
1292     expected_cmdsize *= sizeof(struct MachO::section_64);
1293     expected_cmdsize += sizeof(struct MachO::segment_command_64);
1294   }
1295   outs() << "  cmdsize " << cmdsize;
1296   if (cmdsize != expected_cmdsize)
1297     outs() << " Inconsistent size\n";
1298   else
1299     outs() << "\n";
1300   outs() << "  segname " << SegName << "\n";
1301   if (cmd == MachO::LC_SEGMENT_64) {
1302     outs() << "   vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
1303     outs() << "   vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
1304   } else {
1305     outs() << "   vmaddr " << format("0x%08" PRIx32, vmaddr) << "\n";
1306     outs() << "   vmsize " << format("0x%08" PRIx32, vmsize) << "\n";
1307   }
1308   outs() << "  fileoff " << fileoff;
1309   if (fileoff > object_size)
1310     outs() << " (past end of file)\n";
1311   else
1312     outs() << "\n";
1313   outs() << " filesize " << filesize;
1314   if (fileoff + filesize > object_size)
1315     outs() << " (past end of file)\n";
1316   else
1317     outs() << "\n";
1318   if (verbose) {
1319     if ((maxprot &
1320          ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
1321            MachO::VM_PROT_EXECUTE)) != 0)
1322       outs() << "  maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
1323     else {
1324       if (maxprot & MachO::VM_PROT_READ)
1325         outs() << "  maxprot r";
1326       else
1327         outs() << "  maxprot -";
1328       if (maxprot & MachO::VM_PROT_WRITE)
1329         outs() << "w";
1330       else
1331         outs() << "-";
1332       if (maxprot & MachO::VM_PROT_EXECUTE)
1333         outs() << "x\n";
1334       else
1335         outs() << "-\n";
1336     }
1337     if ((initprot &
1338          ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
1339            MachO::VM_PROT_EXECUTE)) != 0)
1340       outs() << "  initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
1341     else {
1342       if (initprot & MachO::VM_PROT_READ)
1343         outs() << " initprot r";
1344       else
1345         outs() << " initprot -";
1346       if (initprot & MachO::VM_PROT_WRITE)
1347         outs() << "w";
1348       else
1349         outs() << "-";
1350       if (initprot & MachO::VM_PROT_EXECUTE)
1351         outs() << "x\n";
1352       else
1353         outs() << "-\n";
1354     }
1355   } else {
1356     outs() << "  maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
1357     outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
1358   }
1359   outs() << "   nsects " << nsects << "\n";
1360   if (verbose) {
1361     outs() << "    flags";
1362     if (flags == 0)
1363       outs() << " (none)\n";
1364     else {
1365       if (flags & MachO::SG_HIGHVM) {
1366         outs() << " HIGHVM";
1367         flags &= ~MachO::SG_HIGHVM;
1368       }
1369       if (flags & MachO::SG_FVMLIB) {
1370         outs() << " FVMLIB";
1371         flags &= ~MachO::SG_FVMLIB;
1372       }
1373       if (flags & MachO::SG_NORELOC) {
1374         outs() << " NORELOC";
1375         flags &= ~MachO::SG_NORELOC;
1376       }
1377       if (flags & MachO::SG_PROTECTED_VERSION_1) {
1378         outs() << " PROTECTED_VERSION_1";
1379         flags &= ~MachO::SG_PROTECTED_VERSION_1;
1380       }
1381       if (flags)
1382         outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
1383       else
1384         outs() << "\n";
1385     }
1386   } else {
1387     outs() << "    flags " << format("0x%" PRIx32, flags) << "\n";
1388   }
1389 }
1390
1391 static void PrintSection(const char *sectname, const char *segname,
1392                          uint64_t addr, uint64_t size, uint32_t offset,
1393                          uint32_t align, uint32_t reloff, uint32_t nreloc,
1394                          uint32_t flags, uint32_t reserved1, uint32_t reserved2,
1395                          uint32_t cmd, const char *sg_segname,
1396                          uint32_t filetype, uint32_t object_size,
1397                          bool verbose) {
1398   outs() << "Section\n";
1399   outs() << "  sectname " << format("%.16s\n", sectname);
1400   outs() << "   segname " << format("%.16s", segname);
1401   if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
1402     outs() << " (does not match segment)\n";
1403   else
1404     outs() << "\n";
1405   if (cmd == MachO::LC_SEGMENT_64) {
1406     outs() << "      addr " << format("0x%016" PRIx64, addr) << "\n";
1407     outs() << "      size " << format("0x%016" PRIx64, size);
1408   } else {
1409     outs() << "      addr " << format("0x%08" PRIx32, addr) << "\n";
1410     outs() << "      size " << format("0x%08" PRIx32, size);
1411   }
1412   if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
1413     outs() << " (past end of file)\n";
1414   else
1415     outs() << "\n";
1416   outs() << "    offset " << offset;
1417   if (offset > object_size)
1418     outs() << " (past end of file)\n";
1419   else
1420     outs() << "\n";
1421   uint32_t align_shifted = 1 << align;
1422   outs() << "     align 2^" << align << " (" << align_shifted << ")\n";
1423   outs() << "    reloff " << reloff;
1424   if (reloff > object_size)
1425     outs() << " (past end of file)\n";
1426   else
1427     outs() << "\n";
1428   outs() << "    nreloc " << nreloc;
1429   if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
1430     outs() << " (past end of file)\n";
1431   else
1432     outs() << "\n";
1433   uint32_t section_type = flags & MachO::SECTION_TYPE;
1434   if (verbose) {
1435     outs() << "      type";
1436     if (section_type == MachO::S_REGULAR)
1437       outs() << " S_REGULAR\n";
1438     else if (section_type == MachO::S_ZEROFILL)
1439       outs() << " S_ZEROFILL\n";
1440     else if (section_type == MachO::S_CSTRING_LITERALS)
1441       outs() << " S_CSTRING_LITERALS\n";
1442     else if (section_type == MachO::S_4BYTE_LITERALS)
1443       outs() << " S_4BYTE_LITERALS\n";
1444     else if (section_type == MachO::S_8BYTE_LITERALS)
1445       outs() << " S_8BYTE_LITERALS\n";
1446     else if (section_type == MachO::S_16BYTE_LITERALS)
1447       outs() << " S_16BYTE_LITERALS\n";
1448     else if (section_type == MachO::S_LITERAL_POINTERS)
1449       outs() << " S_LITERAL_POINTERS\n";
1450     else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
1451       outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
1452     else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
1453       outs() << " S_LAZY_SYMBOL_POINTERS\n";
1454     else if (section_type == MachO::S_SYMBOL_STUBS)
1455       outs() << " S_SYMBOL_STUBS\n";
1456     else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
1457       outs() << " S_MOD_INIT_FUNC_POINTERS\n";
1458     else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
1459       outs() << " S_MOD_TERM_FUNC_POINTERS\n";
1460     else if (section_type == MachO::S_COALESCED)
1461       outs() << " S_COALESCED\n";
1462     else if (section_type == MachO::S_INTERPOSING)
1463       outs() << " S_INTERPOSING\n";
1464     else if (section_type == MachO::S_DTRACE_DOF)
1465       outs() << " S_DTRACE_DOF\n";
1466     else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
1467       outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
1468     else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
1469       outs() << " S_THREAD_LOCAL_REGULAR\n";
1470     else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
1471       outs() << " S_THREAD_LOCAL_ZEROFILL\n";
1472     else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
1473       outs() << " S_THREAD_LOCAL_VARIABLES\n";
1474     else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
1475       outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
1476     else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
1477       outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
1478     else
1479       outs() << format("0x%08" PRIx32, section_type) << "\n";
1480     outs() << "attributes";
1481     uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
1482     if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
1483       outs() << " PURE_INSTRUCTIONS";
1484     if (section_attributes & MachO::S_ATTR_NO_TOC)
1485       outs() << " NO_TOC";
1486     if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
1487       outs() << " STRIP_STATIC_SYMS";
1488     if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
1489       outs() << " NO_DEAD_STRIP";
1490     if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
1491       outs() << " LIVE_SUPPORT";
1492     if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
1493       outs() << " SELF_MODIFYING_CODE";
1494     if (section_attributes & MachO::S_ATTR_DEBUG)
1495       outs() << " DEBUG";
1496     if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
1497       outs() << " SOME_INSTRUCTIONS";
1498     if (section_attributes & MachO::S_ATTR_EXT_RELOC)
1499       outs() << " EXT_RELOC";
1500     if (section_attributes & MachO::S_ATTR_LOC_RELOC)
1501       outs() << " LOC_RELOC";
1502     if (section_attributes == 0)
1503       outs() << " (none)";
1504     outs() << "\n";
1505   } else
1506     outs() << "     flags " << format("0x%08" PRIx32, flags) << "\n";
1507   outs() << " reserved1 " << reserved1;
1508   if (section_type == MachO::S_SYMBOL_STUBS ||
1509       section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
1510       section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
1511       section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
1512       section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
1513     outs() << " (index into indirect symbol table)\n";
1514   else
1515     outs() << "\n";
1516   outs() << " reserved2 " << reserved2;
1517   if (section_type == MachO::S_SYMBOL_STUBS)
1518     outs() << " (size of stubs)\n";
1519   else
1520     outs() << "\n";
1521 }
1522
1523 static void PrintSymtabLoadCommand(MachO::symtab_command st, uint32_t cputype,
1524                                    uint32_t object_size) {
1525   outs() << "     cmd LC_SYMTAB\n";
1526   outs() << " cmdsize " << st.cmdsize;
1527   if (st.cmdsize != sizeof(struct MachO::symtab_command))
1528     outs() << " Incorrect size\n";
1529   else
1530     outs() << "\n";
1531   outs() << "  symoff " << st.symoff;
1532   if (st.symoff > object_size)
1533     outs() << " (past end of file)\n";
1534   else
1535     outs() << "\n";
1536   outs() << "   nsyms " << st.nsyms;
1537   uint64_t big_size;
1538   if (cputype & MachO::CPU_ARCH_ABI64) {
1539     big_size = st.nsyms;
1540     big_size *= sizeof(struct MachO::nlist_64);
1541     big_size += st.symoff;
1542     if (big_size > object_size)
1543       outs() << " (past end of file)\n";
1544     else
1545       outs() << "\n";
1546   } else {
1547     big_size = st.nsyms;
1548     big_size *= sizeof(struct MachO::nlist);
1549     big_size += st.symoff;
1550     if (big_size > object_size)
1551       outs() << " (past end of file)\n";
1552     else
1553       outs() << "\n";
1554   }
1555   outs() << "  stroff " << st.stroff;
1556   if (st.stroff > object_size)
1557     outs() << " (past end of file)\n";
1558   else
1559     outs() << "\n";
1560   outs() << " strsize " << st.strsize;
1561   big_size = st.stroff;
1562   big_size += st.strsize;
1563   if (big_size > object_size)
1564     outs() << " (past end of file)\n";
1565   else
1566     outs() << "\n";
1567 }
1568
1569 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
1570                                      uint32_t nsyms, uint32_t object_size,
1571                                      uint32_t cputype) {
1572   outs() << "            cmd LC_DYSYMTAB\n";
1573   outs() << "        cmdsize " << dyst.cmdsize;
1574   if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
1575     outs() << " Incorrect size\n";
1576   else
1577     outs() << "\n";
1578   outs() << "      ilocalsym " << dyst.ilocalsym;
1579   if (dyst.ilocalsym > nsyms)
1580     outs() << " (greater than the number of symbols)\n";
1581   else
1582     outs() << "\n";
1583   outs() << "      nlocalsym " << dyst.nlocalsym;
1584   uint64_t big_size;
1585   big_size = dyst.ilocalsym;
1586   big_size += dyst.nlocalsym;
1587   if (big_size > nsyms)
1588     outs() << " (past the end of the symbol table)\n";
1589   else
1590     outs() << "\n";
1591   outs() << "     iextdefsym " << dyst.iextdefsym;
1592   if (dyst.iextdefsym > nsyms)
1593     outs() << " (greater than the number of symbols)\n";
1594   else
1595     outs() << "\n";
1596   outs() << "     nextdefsym " << dyst.nextdefsym;
1597   big_size = dyst.iextdefsym;
1598   big_size += dyst.nextdefsym;
1599   if (big_size > nsyms)
1600     outs() << " (past the end of the symbol table)\n";
1601   else
1602     outs() << "\n";
1603   outs() << "      iundefsym " << dyst.iundefsym;
1604   if (dyst.iundefsym > nsyms)
1605     outs() << " (greater than the number of symbols)\n";
1606   else
1607     outs() << "\n";
1608   outs() << "      nundefsym " << dyst.nundefsym;
1609   big_size = dyst.iundefsym;
1610   big_size += dyst.nundefsym;
1611   if (big_size > nsyms)
1612     outs() << " (past the end of the symbol table)\n";
1613   else
1614     outs() << "\n";
1615   outs() << "         tocoff " << dyst.tocoff;
1616   if (dyst.tocoff > object_size)
1617     outs() << " (past end of file)\n";
1618   else
1619     outs() << "\n";
1620   outs() << "           ntoc " << dyst.ntoc;
1621   big_size = dyst.ntoc;
1622   big_size *= sizeof(struct MachO::dylib_table_of_contents);
1623   big_size += dyst.tocoff;
1624   if (big_size > object_size)
1625     outs() << " (past end of file)\n";
1626   else
1627     outs() << "\n";
1628   outs() << "      modtaboff " << dyst.modtaboff;
1629   if (dyst.modtaboff > object_size)
1630     outs() << " (past end of file)\n";
1631   else
1632     outs() << "\n";
1633   outs() << "        nmodtab " << dyst.nmodtab;
1634   uint64_t modtabend;
1635   if (cputype & MachO::CPU_ARCH_ABI64) {
1636     modtabend = dyst.nmodtab;
1637     modtabend *= sizeof(struct MachO::dylib_module_64);
1638     modtabend += dyst.modtaboff;
1639   } else {
1640     modtabend = dyst.nmodtab;
1641     modtabend *= sizeof(struct MachO::dylib_module);
1642     modtabend += dyst.modtaboff;
1643   }
1644   if (modtabend > object_size)
1645     outs() << " (past end of file)\n";
1646   else
1647     outs() << "\n";
1648   outs() << "   extrefsymoff " << dyst.extrefsymoff;
1649   if (dyst.extrefsymoff > object_size)
1650     outs() << " (past end of file)\n";
1651   else
1652     outs() << "\n";
1653   outs() << "    nextrefsyms " << dyst.nextrefsyms;
1654   big_size = dyst.nextrefsyms;
1655   big_size *= sizeof(struct MachO::dylib_reference);
1656   big_size += dyst.extrefsymoff;
1657   if (big_size > object_size)
1658     outs() << " (past end of file)\n";
1659   else
1660     outs() << "\n";
1661   outs() << " indirectsymoff " << dyst.indirectsymoff;
1662   if (dyst.indirectsymoff > object_size)
1663     outs() << " (past end of file)\n";
1664   else
1665     outs() << "\n";
1666   outs() << "  nindirectsyms " << dyst.nindirectsyms;
1667   big_size = dyst.nindirectsyms;
1668   big_size *= sizeof(uint32_t);
1669   big_size += dyst.indirectsymoff;
1670   if (big_size > object_size)
1671     outs() << " (past end of file)\n";
1672   else
1673     outs() << "\n";
1674   outs() << "      extreloff " << dyst.extreloff;
1675   if (dyst.extreloff > object_size)
1676     outs() << " (past end of file)\n";
1677   else
1678     outs() << "\n";
1679   outs() << "        nextrel " << dyst.nextrel;
1680   big_size = dyst.nextrel;
1681   big_size *= sizeof(struct MachO::relocation_info);
1682   big_size += dyst.extreloff;
1683   if (big_size > object_size)
1684     outs() << " (past end of file)\n";
1685   else
1686     outs() << "\n";
1687   outs() << "      locreloff " << dyst.locreloff;
1688   if (dyst.locreloff > object_size)
1689     outs() << " (past end of file)\n";
1690   else
1691     outs() << "\n";
1692   outs() << "        nlocrel " << dyst.nlocrel;
1693   big_size = dyst.nlocrel;
1694   big_size *= sizeof(struct MachO::relocation_info);
1695   big_size += dyst.locreloff;
1696   if (big_size > object_size)
1697     outs() << " (past end of file)\n";
1698   else
1699     outs() << "\n";
1700 }
1701
1702 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
1703                                      uint32_t object_size) {
1704   if (dc.cmd == MachO::LC_DYLD_INFO)
1705     outs() << "            cmd LC_DYLD_INFO\n";
1706   else
1707     outs() << "            cmd LC_DYLD_INFO_ONLY\n";
1708   outs() << "        cmdsize " << dc.cmdsize;
1709   if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
1710     outs() << " Incorrect size\n";
1711   else
1712     outs() << "\n";
1713   outs() << "     rebase_off " << dc.rebase_off;
1714   if (dc.rebase_off > object_size)
1715     outs() << " (past end of file)\n";
1716   else
1717     outs() << "\n";
1718   outs() << "    rebase_size " << dc.rebase_size;
1719   uint64_t big_size;
1720   big_size = dc.rebase_off;
1721   big_size += dc.rebase_size;
1722   if (big_size > object_size)
1723     outs() << " (past end of file)\n";
1724   else
1725     outs() << "\n";
1726   outs() << "       bind_off " << dc.bind_off;
1727   if (dc.bind_off > object_size)
1728     outs() << " (past end of file)\n";
1729   else
1730     outs() << "\n";
1731   outs() << "      bind_size " << dc.bind_size;
1732   big_size = dc.bind_off;
1733   big_size += dc.bind_size;
1734   if (big_size > object_size)
1735     outs() << " (past end of file)\n";
1736   else
1737     outs() << "\n";
1738   outs() << "  weak_bind_off " << dc.weak_bind_off;
1739   if (dc.weak_bind_off > object_size)
1740     outs() << " (past end of file)\n";
1741   else
1742     outs() << "\n";
1743   outs() << " weak_bind_size " << dc.weak_bind_size;
1744   big_size = dc.weak_bind_off;
1745   big_size += dc.weak_bind_size;
1746   if (big_size > object_size)
1747     outs() << " (past end of file)\n";
1748   else
1749     outs() << "\n";
1750   outs() << "  lazy_bind_off " << dc.lazy_bind_off;
1751   if (dc.lazy_bind_off > object_size)
1752     outs() << " (past end of file)\n";
1753   else
1754     outs() << "\n";
1755   outs() << " lazy_bind_size " << dc.lazy_bind_size;
1756   big_size = dc.lazy_bind_off;
1757   big_size += dc.lazy_bind_size;
1758   if (big_size > object_size)
1759     outs() << " (past end of file)\n";
1760   else
1761     outs() << "\n";
1762   outs() << "     export_off " << dc.export_off;
1763   if (dc.export_off > object_size)
1764     outs() << " (past end of file)\n";
1765   else
1766     outs() << "\n";
1767   outs() << "    export_size " << dc.export_size;
1768   big_size = dc.export_off;
1769   big_size += dc.export_size;
1770   if (big_size > object_size)
1771     outs() << " (past end of file)\n";
1772   else
1773     outs() << "\n";
1774 }
1775
1776 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
1777                                  const char *Ptr) {
1778   if (dyld.cmd == MachO::LC_ID_DYLINKER)
1779     outs() << "          cmd LC_ID_DYLINKER\n";
1780   else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
1781     outs() << "          cmd LC_LOAD_DYLINKER\n";
1782   else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
1783     outs() << "          cmd LC_DYLD_ENVIRONMENT\n";
1784   else
1785     outs() << "          cmd ?(" << dyld.cmd << ")\n";
1786   outs() << "      cmdsize " << dyld.cmdsize;
1787   if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
1788     outs() << " Incorrect size\n";
1789   else
1790     outs() << "\n";
1791   if (dyld.name >= dyld.cmdsize)
1792     outs() << "         name ?(bad offset " << dyld.name << ")\n";
1793   else {
1794     const char *P = (const char *)(Ptr)+dyld.name;
1795     outs() << "         name " << P << " (offset " << dyld.name << ")\n";
1796   }
1797 }
1798
1799 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
1800   outs() << "     cmd LC_UUID\n";
1801   outs() << " cmdsize " << uuid.cmdsize;
1802   if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
1803     outs() << " Incorrect size\n";
1804   else
1805     outs() << "\n";
1806   outs() << "    uuid ";
1807   outs() << format("%02" PRIX32, uuid.uuid[0]);
1808   outs() << format("%02" PRIX32, uuid.uuid[1]);
1809   outs() << format("%02" PRIX32, uuid.uuid[2]);
1810   outs() << format("%02" PRIX32, uuid.uuid[3]);
1811   outs() << "-";
1812   outs() << format("%02" PRIX32, uuid.uuid[4]);
1813   outs() << format("%02" PRIX32, uuid.uuid[5]);
1814   outs() << "-";
1815   outs() << format("%02" PRIX32, uuid.uuid[6]);
1816   outs() << format("%02" PRIX32, uuid.uuid[7]);
1817   outs() << "-";
1818   outs() << format("%02" PRIX32, uuid.uuid[8]);
1819   outs() << format("%02" PRIX32, uuid.uuid[9]);
1820   outs() << "-";
1821   outs() << format("%02" PRIX32, uuid.uuid[10]);
1822   outs() << format("%02" PRIX32, uuid.uuid[11]);
1823   outs() << format("%02" PRIX32, uuid.uuid[12]);
1824   outs() << format("%02" PRIX32, uuid.uuid[13]);
1825   outs() << format("%02" PRIX32, uuid.uuid[14]);
1826   outs() << format("%02" PRIX32, uuid.uuid[15]);
1827   outs() << "\n";
1828 }
1829
1830 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
1831   if (vd.cmd == MachO::LC_VERSION_MIN_MACOSX)
1832     outs() << "      cmd LC_VERSION_MIN_MACOSX\n";
1833   else if (vd.cmd == MachO::LC_VERSION_MIN_IPHONEOS)
1834     outs() << "      cmd LC_VERSION_MIN_IPHONEOS\n";
1835   else
1836     outs() << "      cmd " << vd.cmd << " (?)\n";
1837   outs() << "  cmdsize " << vd.cmdsize;
1838   if (vd.cmdsize != sizeof(struct MachO::version_min_command))
1839     outs() << " Incorrect size\n";
1840   else
1841     outs() << "\n";
1842   outs() << "  version " << ((vd.version >> 16) & 0xffff) << "."
1843          << ((vd.version >> 8) & 0xff);
1844   if ((vd.version & 0xff) != 0)
1845     outs() << "." << (vd.version & 0xff);
1846   outs() << "\n";
1847   if (vd.sdk == 0)
1848     outs() << "      sdk n/a\n";
1849   else {
1850     outs() << "      sdk " << ((vd.sdk >> 16) & 0xffff) << "."
1851            << ((vd.sdk >> 8) & 0xff);
1852   }
1853   if ((vd.sdk & 0xff) != 0)
1854     outs() << "." << (vd.sdk & 0xff);
1855   outs() << "\n";
1856 }
1857
1858 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
1859   outs() << "      cmd LC_SOURCE_VERSION\n";
1860   outs() << "  cmdsize " << sd.cmdsize;
1861   if (sd.cmdsize != sizeof(struct MachO::source_version_command))
1862     outs() << " Incorrect size\n";
1863   else
1864     outs() << "\n";
1865   uint64_t a = (sd.version >> 40) & 0xffffff;
1866   uint64_t b = (sd.version >> 30) & 0x3ff;
1867   uint64_t c = (sd.version >> 20) & 0x3ff;
1868   uint64_t d = (sd.version >> 10) & 0x3ff;
1869   uint64_t e = sd.version & 0x3ff;
1870   outs() << "  version " << a << "." << b;
1871   if (e != 0)
1872     outs() << "." << c << "." << d << "." << e;
1873   else if (d != 0)
1874     outs() << "." << c << "." << d;
1875   else if (c != 0)
1876     outs() << "." << c;
1877   outs() << "\n";
1878 }
1879
1880 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
1881   outs() << "       cmd LC_MAIN\n";
1882   outs() << "   cmdsize " << ep.cmdsize;
1883   if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
1884     outs() << " Incorrect size\n";
1885   else
1886     outs() << "\n";
1887   outs() << "  entryoff " << ep.entryoff << "\n";
1888   outs() << " stacksize " << ep.stacksize << "\n";
1889 }
1890
1891 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
1892   if (dl.cmd == MachO::LC_ID_DYLIB)
1893     outs() << "          cmd LC_ID_DYLIB\n";
1894   else if (dl.cmd == MachO::LC_LOAD_DYLIB)
1895     outs() << "          cmd LC_LOAD_DYLIB\n";
1896   else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1897     outs() << "          cmd LC_LOAD_WEAK_DYLIB\n";
1898   else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
1899     outs() << "          cmd LC_REEXPORT_DYLIB\n";
1900   else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1901     outs() << "          cmd LC_LAZY_LOAD_DYLIB\n";
1902   else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1903     outs() << "          cmd LC_LOAD_UPWARD_DYLIB\n";
1904   else
1905     outs() << "          cmd " << dl.cmd << " (unknown)\n";
1906   outs() << "      cmdsize " << dl.cmdsize;
1907   if (dl.cmdsize < sizeof(struct MachO::dylib_command))
1908     outs() << " Incorrect size\n";
1909   else
1910     outs() << "\n";
1911   if (dl.dylib.name < dl.cmdsize) {
1912     const char *P = (const char *)(Ptr)+dl.dylib.name;
1913     outs() << "         name " << P << " (offset " << dl.dylib.name << ")\n";
1914   } else {
1915     outs() << "         name ?(bad offset " << dl.dylib.name << ")\n";
1916   }
1917   outs() << "   time stamp " << dl.dylib.timestamp << " ";
1918   time_t t = dl.dylib.timestamp;
1919   outs() << ctime(&t);
1920   outs() << "      current version ";
1921   if (dl.dylib.current_version == 0xffffffff)
1922     outs() << "n/a\n";
1923   else
1924     outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
1925            << ((dl.dylib.current_version >> 8) & 0xff) << "."
1926            << (dl.dylib.current_version & 0xff) << "\n";
1927   outs() << "compatibility version ";
1928   if (dl.dylib.compatibility_version == 0xffffffff)
1929     outs() << "n/a\n";
1930   else
1931     outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
1932            << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
1933            << (dl.dylib.compatibility_version & 0xff) << "\n";
1934 }
1935
1936 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
1937                                      uint32_t object_size) {
1938   if (ld.cmd == MachO::LC_CODE_SIGNATURE)
1939     outs() << "      cmd LC_FUNCTION_STARTS\n";
1940   else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
1941     outs() << "      cmd LC_SEGMENT_SPLIT_INFO\n";
1942   else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
1943     outs() << "      cmd LC_FUNCTION_STARTS\n";
1944   else if (ld.cmd == MachO::LC_DATA_IN_CODE)
1945     outs() << "      cmd LC_DATA_IN_CODE\n";
1946   else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
1947     outs() << "      cmd LC_DYLIB_CODE_SIGN_DRS\n";
1948   else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
1949     outs() << "      cmd LC_LINKER_OPTIMIZATION_HINT\n";
1950   else
1951     outs() << "      cmd " << ld.cmd << " (?)\n";
1952   outs() << "  cmdsize " << ld.cmdsize;
1953   if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
1954     outs() << " Incorrect size\n";
1955   else
1956     outs() << "\n";
1957   outs() << "  dataoff " << ld.dataoff;
1958   if (ld.dataoff > object_size)
1959     outs() << " (past end of file)\n";
1960   else
1961     outs() << "\n";
1962   outs() << " datasize " << ld.datasize;
1963   uint64_t big_size = ld.dataoff;
1964   big_size += ld.datasize;
1965   if (big_size > object_size)
1966     outs() << " (past end of file)\n";
1967   else
1968     outs() << "\n";
1969 }
1970
1971 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t ncmds,
1972                               uint32_t filetype, uint32_t cputype,
1973                               bool verbose) {
1974   StringRef Buf = Obj->getData();
1975   MachOObjectFile::LoadCommandInfo Command = Obj->getFirstLoadCommandInfo();
1976   for (unsigned i = 0;; ++i) {
1977     outs() << "Load command " << i << "\n";
1978     if (Command.C.cmd == MachO::LC_SEGMENT) {
1979       MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
1980       const char *sg_segname = SLC.segname;
1981       PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
1982                           SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
1983                           SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
1984                           verbose);
1985       for (unsigned j = 0; j < SLC.nsects; j++) {
1986         MachO::section_64 S = Obj->getSection64(Command, j);
1987         PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
1988                      S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
1989                      SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
1990       }
1991     } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
1992       MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
1993       const char *sg_segname = SLC_64.segname;
1994       PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
1995                           SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
1996                           SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
1997                           SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
1998       for (unsigned j = 0; j < SLC_64.nsects; j++) {
1999         MachO::section_64 S_64 = Obj->getSection64(Command, j);
2000         PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
2001                      S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
2002                      S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
2003                      sg_segname, filetype, Buf.size(), verbose);
2004       }
2005     } else if (Command.C.cmd == MachO::LC_SYMTAB) {
2006       MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
2007       PrintSymtabLoadCommand(Symtab, cputype, Buf.size());
2008     } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
2009       MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
2010       MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
2011       PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(), cputype);
2012     } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
2013                Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
2014       MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
2015       PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
2016     } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
2017                Command.C.cmd == MachO::LC_ID_DYLINKER ||
2018                Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
2019       MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
2020       PrintDyldLoadCommand(Dyld, Command.Ptr);
2021     } else if (Command.C.cmd == MachO::LC_UUID) {
2022       MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
2023       PrintUuidLoadCommand(Uuid);
2024     } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX) {
2025       MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
2026       PrintVersionMinLoadCommand(Vd);
2027     } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
2028       MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
2029       PrintSourceVersionCommand(Sd);
2030     } else if (Command.C.cmd == MachO::LC_MAIN) {
2031       MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
2032       PrintEntryPointCommand(Ep);
2033     } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB) {
2034       MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
2035       PrintDylibCommand(Dl, Command.Ptr);
2036     } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
2037                Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
2038                Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
2039                Command.C.cmd == MachO::LC_DATA_IN_CODE ||
2040                Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
2041                Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
2042       MachO::linkedit_data_command Ld =
2043           Obj->getLinkeditDataLoadCommand(Command);
2044       PrintLinkEditDataCommand(Ld, Buf.size());
2045     } else {
2046       outs() << "      cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
2047              << ")\n";
2048       outs() << "  cmdsize " << Command.C.cmdsize << "\n";
2049       // TODO: get and print the raw bytes of the load command.
2050     }
2051     // TODO: print all the other kinds of load commands.
2052     if (i == ncmds - 1)
2053       break;
2054     else
2055       Command = Obj->getNextLoadCommandInfo(Command);
2056   }
2057 }
2058
2059 static void getAndPrintMachHeader(const MachOObjectFile *Obj, uint32_t &ncmds,
2060                                   uint32_t &filetype, uint32_t &cputype,
2061                                   bool verbose) {
2062   if (Obj->is64Bit()) {
2063     MachO::mach_header_64 H_64;
2064     H_64 = Obj->getHeader64();
2065     PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
2066                     H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
2067     ncmds = H_64.ncmds;
2068     filetype = H_64.filetype;
2069     cputype = H_64.cputype;
2070   } else {
2071     MachO::mach_header H;
2072     H = Obj->getHeader();
2073     PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
2074                     H.sizeofcmds, H.flags, verbose);
2075     ncmds = H.ncmds;
2076     filetype = H.filetype;
2077     cputype = H.cputype;
2078   }
2079 }
2080
2081 void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
2082   const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
2083   uint32_t ncmds = 0;
2084   uint32_t filetype = 0;
2085   uint32_t cputype = 0;
2086   getAndPrintMachHeader(file, ncmds, filetype, cputype, true);
2087   PrintLoadCommands(file, ncmds, filetype, cputype, true);
2088 }
2089
2090 //===----------------------------------------------------------------------===//
2091 // export trie dumping
2092 //===----------------------------------------------------------------------===//
2093
2094 void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
2095   for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
2096     uint64_t Flags = Entry.flags();
2097     bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
2098     bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
2099     bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
2100                         MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
2101     bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
2102                 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
2103     bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
2104     if (ReExport)
2105       outs() << "[re-export] ";
2106     else
2107       outs()
2108           << format("0x%08llX  ", Entry.address()); // FIXME:add in base address
2109     outs() << Entry.name();
2110     if (WeakDef || ThreadLocal || Resolver || Abs) {
2111       bool NeedsComma = false;
2112       outs() << " [";
2113       if (WeakDef) {
2114         outs() << "weak_def";
2115         NeedsComma = true;
2116       }
2117       if (ThreadLocal) {
2118         if (NeedsComma)
2119           outs() << ", ";
2120         outs() << "per-thread";
2121         NeedsComma = true;
2122       }
2123       if (Abs) {
2124         if (NeedsComma)
2125           outs() << ", ";
2126         outs() << "absolute";
2127         NeedsComma = true;
2128       }
2129       if (Resolver) {
2130         if (NeedsComma)
2131           outs() << ", ";
2132         outs() << format("resolver=0x%08llX", Entry.other());
2133         NeedsComma = true;
2134       }
2135       outs() << "]";
2136     }
2137     if (ReExport) {
2138       StringRef DylibName = "unknown";
2139       int Ordinal = Entry.other() - 1;
2140       Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
2141       if (Entry.otherName().empty())
2142         outs() << " (from " << DylibName << ")";
2143       else
2144         outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
2145     }
2146     outs() << "\n";
2147   }
2148 }
2149
2150
2151 //===----------------------------------------------------------------------===//
2152 // rebase table dumping
2153 //===----------------------------------------------------------------------===//
2154
2155 namespace {
2156 class SegInfo {
2157 public:
2158   SegInfo(const object::MachOObjectFile *Obj);
2159
2160   StringRef segmentName(uint32_t SegIndex);
2161   StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
2162   uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
2163
2164 private:
2165   struct SectionInfo {
2166     uint64_t Address;
2167     uint64_t Size;
2168     StringRef SectionName;
2169     StringRef SegmentName;
2170     uint64_t OffsetInSegment;
2171     uint64_t SegmentStartAddress;
2172     uint32_t SegmentIndex;
2173   };
2174   const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
2175   SmallVector<SectionInfo, 32> Sections;
2176 };
2177 }
2178
2179 SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
2180   // Build table of sections so segIndex/offset pairs can be translated.
2181   uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
2182   StringRef CurSegName;
2183   uint64_t CurSegAddress;
2184   for (const SectionRef &Section : Obj->sections()) {
2185     SectionInfo Info;
2186     if (error(Section.getName(Info.SectionName)))
2187       return;
2188     if (error(Section.getAddress(Info.Address)))
2189       return;
2190     if (error(Section.getSize(Info.Size)))
2191       return;
2192     Info.SegmentName =
2193         Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
2194     if (!Info.SegmentName.equals(CurSegName)) {
2195       ++CurSegIndex;
2196       CurSegName = Info.SegmentName;
2197       CurSegAddress = Info.Address;
2198     }
2199     Info.SegmentIndex = CurSegIndex - 1;
2200     Info.OffsetInSegment = Info.Address - CurSegAddress;
2201     Info.SegmentStartAddress = CurSegAddress;
2202     Sections.push_back(Info);
2203   }
2204 }
2205
2206 StringRef SegInfo::segmentName(uint32_t SegIndex) {
2207   for (const SectionInfo &SI : Sections) {
2208     if (SI.SegmentIndex == SegIndex)
2209       return SI.SegmentName;
2210   }
2211   llvm_unreachable("invalid segIndex");
2212 }
2213
2214 const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
2215                                                  uint64_t OffsetInSeg) {
2216   for (const SectionInfo &SI : Sections) {
2217     if (SI.SegmentIndex != SegIndex)
2218       continue;
2219     if (SI.OffsetInSegment > OffsetInSeg)
2220       continue;
2221     if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
2222       continue;
2223     return SI;
2224   }
2225   llvm_unreachable("segIndex and offset not in any section");
2226 }
2227
2228 StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
2229   return findSection(SegIndex, OffsetInSeg).SectionName;
2230 }
2231
2232 uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
2233   const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
2234   return SI.SegmentStartAddress + OffsetInSeg;
2235 }
2236
2237 void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
2238   // Build table of sections so names can used in final output.
2239   SegInfo sectionTable(Obj);
2240
2241   outs() << "segment  section            address     type\n";
2242   for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
2243     uint32_t SegIndex = Entry.segmentIndex();
2244     uint64_t OffsetInSeg = Entry.segmentOffset();
2245     StringRef SegmentName = sectionTable.segmentName(SegIndex);
2246     StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
2247     uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
2248
2249     // Table lines look like: __DATA  __nl_symbol_ptr  0x0000F00C  pointer
2250     outs() << format("%-8s %-18s 0x%08" PRIX64 "  %s\n", 
2251                      SegmentName.str().c_str(),
2252                      SectionName.str().c_str(), Address,
2253                      Entry.typeName().str().c_str());
2254   }
2255 }
2256
2257 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
2258   StringRef DylibName;
2259   switch (Ordinal) {
2260   case MachO::BIND_SPECIAL_DYLIB_SELF:
2261     return "this-image";
2262   case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
2263     return "main-executable";
2264   case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
2265     return "flat-namespace";
2266   default:
2267     Obj->getLibraryShortNameByIndex(Ordinal-1, DylibName);
2268     return DylibName;
2269   }
2270 }
2271
2272 //===----------------------------------------------------------------------===//
2273 // bind table dumping
2274 //===----------------------------------------------------------------------===//
2275
2276 void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
2277   // Build table of sections so names can used in final output.
2278   SegInfo sectionTable(Obj);
2279
2280   outs() << "segment  section            address     type     "
2281             "addend   dylib               symbol\n";
2282   for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
2283     uint32_t SegIndex = Entry.segmentIndex();
2284     uint64_t OffsetInSeg = Entry.segmentOffset();
2285     StringRef SegmentName = sectionTable.segmentName(SegIndex);
2286     StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
2287     uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
2288
2289     // Table lines look like:
2290     //  __DATA  __got  0x00012010    pointer   0 libSystem ___stack_chk_guard
2291     outs() << format("%-8s %-18s 0x%08" PRIX64 "  %-8s %-8" PRId64 " %-20s",
2292                      SegmentName.str().c_str(),
2293                      SectionName.str().c_str(),
2294                      Address,
2295                      Entry.typeName().str().c_str(),
2296                      Entry.addend(),
2297                      ordinalName(Obj, Entry.ordinal()))
2298            << Entry.symbolName();
2299     if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
2300       outs() << " (weak_import)\n";
2301     else
2302       outs() << "\n";
2303   }
2304 }
2305
2306 //===----------------------------------------------------------------------===//
2307 // lazy bind table dumping
2308 //===----------------------------------------------------------------------===//
2309
2310 void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
2311   // Build table of sections so names can used in final output.
2312   SegInfo sectionTable(Obj);
2313
2314   outs() << "segment  section            address      "
2315             "dylib               symbol\n";
2316   for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
2317     uint32_t SegIndex = Entry.segmentIndex();
2318     uint64_t OffsetInSeg = Entry.segmentOffset();
2319     StringRef SegmentName = sectionTable.segmentName(SegIndex);
2320     StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
2321     uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
2322
2323     // Table lines look like:
2324     //  __DATA  __got  0x00012010 libSystem ___stack_chk_guard
2325     outs() << format("%-8s %-18s 0x%08" PRIX64 "   %-20s",
2326                      SegmentName.str().c_str(),
2327                      SectionName.str().c_str(),
2328                      Address,
2329                      ordinalName(Obj, Entry.ordinal()))
2330            << Entry.symbolName() << "\n";
2331   }
2332 }
2333
2334
2335 //===----------------------------------------------------------------------===//
2336 // weak bind table dumping
2337 //===----------------------------------------------------------------------===//
2338
2339 void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
2340   // Build table of sections so names can used in final output.
2341   SegInfo sectionTable(Obj);
2342
2343   outs() << "segment  section            address      "
2344             "type     addend   symbol\n";
2345   for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
2346     // Strong symbols don't have a location to update.
2347     if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
2348       outs() << "                                          strong            "
2349              << Entry.symbolName() << "\n";
2350       continue;
2351     }
2352     uint32_t SegIndex = Entry.segmentIndex();
2353     uint64_t OffsetInSeg = Entry.segmentOffset();
2354     StringRef SegmentName = sectionTable.segmentName(SegIndex);
2355     StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
2356     uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
2357
2358     // Table lines look like:
2359     // __DATA  __data  0x00001000  pointer    0   _foo
2360     outs() << format("%-8s %-18s 0x%08" PRIX64 "   %-8s %-8" PRId64 " ",
2361                      SegmentName.str().c_str(),
2362                      SectionName.str().c_str(),
2363                      Address,
2364                      Entry.typeName().str().c_str(),
2365                      Entry.addend())
2366            << Entry.symbolName() << "\n";
2367   }
2368 }
2369
2370