1 //===-- MachODump.cpp - Object file dumping utility for llvm --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the MachO-specific dumper for llvm-objdump.
12 //===----------------------------------------------------------------------===//
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"
43 #include <system_error>
45 using namespace object;
48 UseDbg("g", cl::desc("Print line information from debug info if available"));
50 static cl::opt<std::string>
51 DSYMFile("dsym", cl::desc("Use .dSYM file for debug info"));
53 static std::string ThumbTripleName;
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();
67 // Get the target specific parser.
69 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
70 if (TheTarget && ThumbTripleName.empty())
73 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
77 errs() << "llvm-objdump: error: unable to get target for '";
81 errs() << ThumbTripleName;
82 errs() << "', see --version and --triple.\n";
87 bool operator()(const SymbolRef &A, const SymbolRef &B) {
88 SymbolRef::Type AType, BType;
92 uint64_t AAddr, BAddr;
93 if (AType != SymbolRef::ST_Function)
97 if (BType != SymbolRef::ST_Function)
101 return AAddr < BAddr;
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;
112 compareDiceTableEntries(const DiceTableEntry i,
113 const DiceTableEntry j) {
114 return i.first == j.first;
117 static void DumpDataInCode(const char *bytes, uint64_t Size,
118 unsigned short Kind) {
122 case MachO::DICE_KIND_DATA:
125 Value = bytes[3] << 24 |
129 outs() << "\t.long " << Value;
132 Value = bytes[1] << 8 |
134 outs() << "\t.short " << Value;
138 outs() << "\t.byte " << Value;
141 outs() << "\t@ KIND_DATA\n";
143 case MachO::DICE_KIND_JUMP_TABLE8:
145 outs() << "\t.byte " << Value << "\t@ KIND_JUMP_TABLE8";
147 case MachO::DICE_KIND_JUMP_TABLE16:
148 Value = bytes[1] << 8 |
150 outs() << "\t.short " << Value << "\t@ KIND_JUMP_TABLE16";
152 case MachO::DICE_KIND_JUMP_TABLE32:
153 Value = bytes[3] << 24 |
157 outs() << "\t.long " << Value << "\t@ KIND_JUMP_TABLE32";
160 outs() << "\t@ data in code kind = " << Kind << "\n";
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);
174 for (const SectionRef &Section : MachOObj->sections()) {
176 Section.getName(SectName);
177 Sections.push_back(Section);
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
187 MachO::linkedit_data_command LLC =
188 MachOObj->getLinkeditDataLoadCommand(Command);
190 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
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;
202 if (i == Header.ncmds - 1)
205 Command = MachOObj->getNextLoadCommandInfo(Command);
209 static void DisassembleInputMachO2(StringRef Filename,
210 MachOObjectFile *MachOOF);
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";
219 std::unique_ptr<MemoryBuffer> Buff = std::move(BuffOrErr.get());
221 std::unique_ptr<MachOObjectFile> MachOOF = std::move(
222 ObjectFile::createMachOObjectFile(Buff.get()->getMemBufferRef()).get());
224 DisassembleInputMachO2(Filename, MachOOF.get());
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);
233 // GetTarget prints out stuff.
236 if (MCPU.empty() && McpuDefault)
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;
245 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
246 ThumbInstrAnalysis.reset(
247 ThumbTarget->createMCInstrAnalysis(ThumbInstrInfo.get()));
250 // Package up features to be passed to target/subtarget
251 std::string FeaturesStr;
253 SubtargetFeatures Features;
254 for (unsigned i = 0; i != MAttrs.size(); ++i)
255 Features.AddFeature(MAttrs[i]);
256 FeaturesStr = Features.getString();
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));
273 if (!InstrAnalysis || !AsmInfo || !STI || !DisAsm || !IP) {
274 errs() << "error: couldn't initialize disassembler for target "
275 << TripleName << '\n';
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;
287 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
289 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
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,
300 if (ThumbTarget && (!ThumbInstrAnalysis || !ThumbAsmInfo || !ThumbSTI ||
301 !ThumbDisAsm || !ThumbIP)) {
302 errs() << "error: couldn't initialize disassembler for target "
303 << ThumbTripleName << '\n';
307 outs() << '\n' << Filename << ":\n\n";
309 MachO::mach_header Header = MachOOF->getHeader();
311 // FIXME: FoundFns isn't used anymore. Using symbols/LC_FUNCTION_STARTS to
312 // determine function locations will eventually go in MCObjectDisassembler.
313 // FIXME: Using the -cfg command line option, this code used to be able to
314 // annotate relocations with the referenced symbol's name, and if this was
315 // inside a __[cf]string section, the data it points to. This is now replaced
316 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
317 std::vector<SectionRef> Sections;
318 std::vector<SymbolRef> Symbols;
319 SmallVector<uint64_t, 8> FoundFns;
320 uint64_t BaseSegmentAddress;
322 getSectionsAndSymbols(Header, MachOOF, Sections, Symbols, FoundFns,
325 // Sort the symbols by address, just in case they didn't come in that way.
326 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
328 // Build a data in code table that is sorted on by the address of each entry.
329 uint64_t BaseAddress = 0;
330 if (Header.filetype == MachO::MH_OBJECT)
331 Sections[0].getAddress(BaseAddress);
333 BaseAddress = BaseSegmentAddress;
335 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
338 DI->getOffset(Offset);
339 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
341 array_pod_sort(Dices.begin(), Dices.end());
344 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
346 raw_ostream &DebugOut = nulls();
349 std::unique_ptr<DIContext> diContext;
350 ObjectFile *DbgObj = MachOOF;
351 // Try to find debug info and set up the DIContext for it.
353 // A separate DSym file path was specified, parse it as a macho file,
354 // get the sections and supply it to the section name parsing machinery.
355 if (!DSYMFile.empty()) {
356 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
357 MemoryBuffer::getFileOrSTDIN(DSYMFile);
358 if (std::error_code EC = BufOrErr.getError()) {
359 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
363 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
368 // Setup the DIContext
369 diContext.reset(DIContext::getDWARFContext(*DbgObj));
372 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
374 bool SectIsText = false;
375 Sections[SectIdx].isText(SectIsText);
376 if (SectIsText == false)
380 if (Sections[SectIdx].getName(SectName) ||
381 SectName != "__text")
382 continue; // Skip non-text sections
384 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
386 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
387 if (SegmentName != "__TEXT")
391 Sections[SectIdx].getContents(Bytes);
392 StringRefMemoryObject memoryObject(Bytes);
393 bool symbolTableWorked = false;
395 // Parse relocations.
396 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
397 for (const RelocationRef &Reloc : Sections[SectIdx].relocations()) {
398 uint64_t RelocOffset, SectionAddress;
399 Reloc.getOffset(RelocOffset);
400 Sections[SectIdx].getAddress(SectionAddress);
401 RelocOffset -= SectionAddress;
403 symbol_iterator RelocSym = Reloc.getSymbol();
405 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
407 array_pod_sort(Relocs.begin(), Relocs.end());
409 // Disassemble symbol by symbol.
410 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
412 Symbols[SymIdx].getName(SymName);
415 Symbols[SymIdx].getType(ST);
416 if (ST != SymbolRef::ST_Function)
419 // Make sure the symbol is defined in this section.
420 bool containsSym = false;
421 Sections[SectIdx].containsSymbol(Symbols[SymIdx], containsSym);
425 // Start at the address of the symbol relative to the section's address.
426 uint64_t SectionAddress = 0;
428 Sections[SectIdx].getAddress(SectionAddress);
429 Symbols[SymIdx].getAddress(Start);
430 Start -= SectionAddress;
432 // Stop disassembling either at the beginning of the next symbol or at
433 // the end of the section.
434 bool containsNextSym = false;
435 uint64_t NextSym = 0;
436 uint64_t NextSymIdx = SymIdx+1;
437 while (Symbols.size() > NextSymIdx) {
438 SymbolRef::Type NextSymType;
439 Symbols[NextSymIdx].getType(NextSymType);
440 if (NextSymType == SymbolRef::ST_Function) {
441 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx],
443 Symbols[NextSymIdx].getAddress(NextSym);
444 NextSym -= SectionAddress;
451 Sections[SectIdx].getSize(SectSize);
452 uint64_t End = containsNextSym ? NextSym : SectSize;
455 symbolTableWorked = true;
457 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
459 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
461 outs() << SymName << ":\n";
463 for (uint64_t Index = Start; Index < End; Index += Size) {
466 uint64_t SectAddress = 0;
467 Sections[SectIdx].getAddress(SectAddress);
468 outs() << format("%8" PRIx64 ":\t", SectAddress + Index);
470 // Check the data in code table here to see if this is data not an
471 // instruction to be disassembled.
473 Dice.push_back(std::make_pair(SectAddress + Index, DiceRef()));
474 dice_table_iterator DTI = std::search(Dices.begin(), Dices.end(),
475 Dice.begin(), Dice.end(),
476 compareDiceTableEntries);
477 if (DTI != Dices.end()){
479 DTI->second.getLength(Length);
480 DumpBytes(StringRef(Bytes.data() + Index, Length));
482 DTI->second.getKind(Kind);
483 DumpDataInCode(Bytes.data() + Index, Length, Kind);
489 gotInst = ThumbDisAsm->getInstruction(Inst, Size, memoryObject, Index,
492 gotInst = DisAsm->getInstruction(Inst, Size, memoryObject, Index,
495 DumpBytes(StringRef(Bytes.data() + Index, Size));
497 ThumbIP->printInst(&Inst, outs(), "");
499 IP->printInst(&Inst, outs(), "");
504 diContext->getLineInfoForAddress(SectAddress + Index);
505 // Print valid line info if it changed.
506 if (dli != lastLine && dli.Line != 0)
507 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
513 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
515 Size = 1; // skip illegible bytes
519 if (!symbolTableWorked) {
520 // Reading the symbol table didn't work, disassemble the whole section.
521 uint64_t SectAddress;
522 Sections[SectIdx].getAddress(SectAddress);
524 Sections[SectIdx].getSize(SectSize);
526 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
529 if (DisAsm->getInstruction(Inst, InstSize, memoryObject, Index,
530 DebugOut, nulls())) {
531 outs() << format("%8" PRIx64 ":\t", SectAddress + Index);
532 DumpBytes(StringRef(Bytes.data() + Index, InstSize));
533 IP->printInst(&Inst, outs(), "");
536 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
538 InstSize = 1; // skip illegible bytes
546 //===----------------------------------------------------------------------===//
547 // __compact_unwind section dumping
548 //===----------------------------------------------------------------------===//
552 template <typename T> static uint64_t readNext(const char *&Buf) {
553 using llvm::support::little;
554 using llvm::support::unaligned;
556 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
561 struct CompactUnwindEntry {
562 uint32_t OffsetInSection;
564 uint64_t FunctionAddr;
566 uint32_t CompactEncoding;
567 uint64_t PersonalityAddr;
570 RelocationRef FunctionReloc;
571 RelocationRef PersonalityReloc;
572 RelocationRef LSDAReloc;
574 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
575 : OffsetInSection(Offset) {
577 read<uint64_t>(Contents.data() + Offset);
579 read<uint32_t>(Contents.data() + Offset);
583 template<typename UIntPtr>
584 void read(const char *Buf) {
585 FunctionAddr = readNext<UIntPtr>(Buf);
586 Length = readNext<uint32_t>(Buf);
587 CompactEncoding = readNext<uint32_t>(Buf);
588 PersonalityAddr = readNext<UIntPtr>(Buf);
589 LSDAAddr = readNext<UIntPtr>(Buf);
594 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
595 /// and data being relocated, determine the best base Name and Addend to use for
596 /// display purposes.
598 /// 1. An Extern relocation will directly reference a symbol (and the data is
599 /// then already an addend), so use that.
600 /// 2. Otherwise the data is an offset in the object file's layout; try to find
601 // a symbol before it in the same section, and use the offset from there.
602 /// 3. Finally, if all that fails, fall back to an offset from the start of the
603 /// referenced section.
604 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
605 std::map<uint64_t, SymbolRef> &Symbols,
606 const RelocationRef &Reloc,
608 StringRef &Name, uint64_t &Addend) {
609 if (Reloc.getSymbol() != Obj->symbol_end()) {
610 Reloc.getSymbol()->getName(Name);
615 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
616 SectionRef RelocSection = Obj->getRelocationSection(RE);
618 uint64_t SectionAddr;
619 RelocSection.getAddress(SectionAddr);
621 auto Sym = Symbols.upper_bound(Addr);
622 if (Sym == Symbols.begin()) {
623 // The first symbol in the object is after this reference, the best we can
624 // do is section-relative notation.
625 RelocSection.getName(Name);
626 Addend = Addr - SectionAddr;
630 // Go back one so that SymbolAddress <= Addr.
633 section_iterator SymSection = Obj->section_end();
634 Sym->second.getSection(SymSection);
635 if (RelocSection == *SymSection) {
636 // There's a valid symbol in the same section before this reference.
637 Sym->second.getName(Name);
638 Addend = Addr - Sym->first;
642 // There is a symbol before this reference, but it's in a different
643 // section. Probably not helpful to mention it, so use the section name.
644 RelocSection.getName(Name);
645 Addend = Addr - SectionAddr;
648 static void printUnwindRelocDest(const MachOObjectFile *Obj,
649 std::map<uint64_t, SymbolRef> &Symbols,
650 const RelocationRef &Reloc,
655 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
659 outs() << " + " << format("0x%" PRIx64, Addend);
663 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
664 std::map<uint64_t, SymbolRef> &Symbols,
665 const SectionRef &CompactUnwind) {
667 assert(Obj->isLittleEndian() &&
668 "There should not be a big-endian .o with __compact_unwind");
670 bool Is64 = Obj->is64Bit();
671 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
672 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
675 CompactUnwind.getContents(Contents);
677 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
679 // First populate the initial raw offsets, encodings and so on from the entry.
680 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
681 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
682 CompactUnwinds.push_back(Entry);
685 // Next we need to look at the relocations to find out what objects are
686 // actually being referred to.
687 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
688 uint64_t RelocAddress;
689 Reloc.getOffset(RelocAddress);
691 uint32_t EntryIdx = RelocAddress / EntrySize;
692 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
693 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
695 if (OffsetInEntry == 0)
696 Entry.FunctionReloc = Reloc;
697 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
698 Entry.PersonalityReloc = Reloc;
699 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
700 Entry.LSDAReloc = Reloc;
702 llvm_unreachable("Unexpected relocation in __compact_unwind section");
705 // Finally, we're ready to print the data we've gathered.
706 outs() << "Contents of __compact_unwind section:\n";
707 for (auto &Entry : CompactUnwinds) {
708 outs() << " Entry at offset "
709 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
711 // 1. Start of the region this entry applies to.
713 << format("0x%" PRIx64, Entry.FunctionAddr) << ' ';
714 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc,
718 // 2. Length of the region this entry applies to.
719 outs() << " length: "
720 << format("0x%" PRIx32, Entry.Length) << '\n';
721 // 3. The 32-bit compact encoding.
722 outs() << " compact encoding: "
723 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
725 // 4. The personality function, if present.
726 if (Entry.PersonalityReloc.getObjectFile()) {
727 outs() << " personality function: "
728 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
729 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
730 Entry.PersonalityAddr);
734 // 5. This entry's language-specific data area.
735 if (Entry.LSDAReloc.getObjectFile()) {
737 << format("0x%" PRIx64, Entry.LSDAAddr) << ' ';
738 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
744 //===----------------------------------------------------------------------===//
745 // __unwind_info section dumping
746 //===----------------------------------------------------------------------===//
748 static void printRegularSecondLevelUnwindPage(const char *PageStart) {
749 const char *Pos = PageStart;
750 uint32_t Kind = readNext<uint32_t>(Pos);
752 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
754 uint16_t EntriesStart = readNext<uint16_t>(Pos);
755 uint16_t NumEntries = readNext<uint16_t>(Pos);
757 Pos = PageStart + EntriesStart;
758 for (unsigned i = 0; i < NumEntries; ++i) {
759 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
760 uint32_t Encoding = readNext<uint32_t>(Pos);
762 outs() << " [" << i << "]: "
763 << "function offset="
764 << format("0x%08" PRIx32, FunctionOffset) << ", "
766 << format("0x%08" PRIx32, Encoding)
771 static void printCompressedSecondLevelUnwindPage(
772 const char *PageStart, uint32_t FunctionBase,
773 const SmallVectorImpl<uint32_t> &CommonEncodings) {
774 const char *Pos = PageStart;
775 uint32_t Kind = readNext<uint32_t>(Pos);
777 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
779 uint16_t EntriesStart = readNext<uint16_t>(Pos);
780 uint16_t NumEntries = readNext<uint16_t>(Pos);
782 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
783 readNext<uint16_t>(Pos);
784 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
785 PageStart + EncodingsStart);
787 Pos = PageStart + EntriesStart;
788 for (unsigned i = 0; i < NumEntries; ++i) {
789 uint32_t Entry = readNext<uint32_t>(Pos);
790 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
791 uint32_t EncodingIdx = Entry >> 24;
794 if (EncodingIdx < CommonEncodings.size())
795 Encoding = CommonEncodings[EncodingIdx];
797 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
799 outs() << " [" << i << "]: "
800 << "function offset="
801 << format("0x%08" PRIx32, FunctionOffset) << ", "
802 << "encoding[" << EncodingIdx << "]="
803 << format("0x%08" PRIx32, Encoding)
809 printMachOUnwindInfoSection(const MachOObjectFile *Obj,
810 std::map<uint64_t, SymbolRef> &Symbols,
811 const SectionRef &UnwindInfo) {
813 assert(Obj->isLittleEndian() &&
814 "There should not be a big-endian .o with __unwind_info");
816 outs() << "Contents of __unwind_info section:\n";
819 UnwindInfo.getContents(Contents);
820 const char *Pos = Contents.data();
822 //===----------------------------------
824 //===----------------------------------
826 uint32_t Version = readNext<uint32_t>(Pos);
827 outs() << " Version: "
828 << format("0x%" PRIx32, Version) << '\n';
829 assert(Version == 1 && "only understand version 1");
831 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
832 outs() << " Common encodings array section offset: "
833 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
834 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
835 outs() << " Number of common encodings in array: "
836 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
838 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
839 outs() << " Personality function array section offset: "
840 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
841 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
842 outs() << " Number of personality functions in array: "
843 << format("0x%" PRIx32, NumPersonalities) << '\n';
845 uint32_t IndicesStart = readNext<uint32_t>(Pos);
846 outs() << " Index array section offset: "
847 << format("0x%" PRIx32, IndicesStart) << '\n';
848 uint32_t NumIndices = readNext<uint32_t>(Pos);
849 outs() << " Number of indices in array: "
850 << format("0x%" PRIx32, NumIndices) << '\n';
852 //===----------------------------------
853 // A shared list of common encodings
854 //===----------------------------------
856 // These occupy indices in the range [0, N] whenever an encoding is referenced
857 // from a compressed 2nd level index table. In practice the linker only
858 // creates ~128 of these, so that indices are available to embed encodings in
859 // the 2nd level index.
861 SmallVector<uint32_t, 64> CommonEncodings;
862 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
863 Pos = Contents.data() + CommonEncodingsStart;
864 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
865 uint32_t Encoding = readNext<uint32_t>(Pos);
866 CommonEncodings.push_back(Encoding);
868 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
873 //===----------------------------------
874 // Personality functions used in this executable
875 //===----------------------------------
877 // There should be only a handful of these (one per source language,
878 // roughly). Particularly since they only get 2 bits in the compact encoding.
880 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
881 Pos = Contents.data() + PersonalitiesStart;
882 for (unsigned i = 0; i < NumPersonalities; ++i) {
883 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
884 outs() << " personality[" << i + 1
885 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
888 //===----------------------------------
889 // The level 1 index entries
890 //===----------------------------------
892 // These specify an approximate place to start searching for the more detailed
893 // information, sorted by PC.
896 uint32_t FunctionOffset;
897 uint32_t SecondLevelPageStart;
901 SmallVector<IndexEntry, 4> IndexEntries;
903 outs() << " Top level indices: (count = " << NumIndices << ")\n";
904 Pos = Contents.data() + IndicesStart;
905 for (unsigned i = 0; i < NumIndices; ++i) {
908 Entry.FunctionOffset = readNext<uint32_t>(Pos);
909 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
910 Entry.LSDAStart = readNext<uint32_t>(Pos);
911 IndexEntries.push_back(Entry);
913 outs() << " [" << i << "]: "
914 << "function offset="
915 << format("0x%08" PRIx32, Entry.FunctionOffset) << ", "
916 << "2nd level page offset="
917 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
919 << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
923 //===----------------------------------
924 // Next come the LSDA tables
925 //===----------------------------------
927 // The LSDA layout is rather implicit: it's a contiguous array of entries from
928 // the first top-level index's LSDAOffset to the last (sentinel).
930 outs() << " LSDA descriptors:\n";
931 Pos = Contents.data() + IndexEntries[0].LSDAStart;
932 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
933 (2 * sizeof(uint32_t));
934 for (int i = 0; i < NumLSDAs; ++i) {
935 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
936 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
937 outs() << " [" << i << "]: "
938 << "function offset="
939 << format("0x%08" PRIx32, FunctionOffset) << ", "
941 << format("0x%08" PRIx32, LSDAOffset) << '\n';
944 //===----------------------------------
945 // Finally, the 2nd level indices
946 //===----------------------------------
948 // Generally these are 4K in size, and have 2 possible forms:
949 // + Regular stores up to 511 entries with disparate encodings
950 // + Compressed stores up to 1021 entries if few enough compact encoding
952 outs() << " Second level indices:\n";
953 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
954 // The final sentinel top-level index has no associated 2nd level page
955 if (IndexEntries[i].SecondLevelPageStart == 0)
958 outs() << " Second level index[" << i << "]: "
959 << "offset in section="
960 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
962 << "base function offset="
963 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
965 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
966 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
968 printRegularSecondLevelUnwindPage(Pos);
970 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
973 llvm_unreachable("Do not know how to print this kind of 2nd level page");
978 void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
979 std::map<uint64_t, SymbolRef> Symbols;
980 for (const SymbolRef &SymRef : Obj->symbols()) {
981 // Discard any undefined or absolute symbols. They're not going to take part
982 // in the convenience lookup for unwind info and just take up resources.
983 section_iterator Section = Obj->section_end();
984 SymRef.getSection(Section);
985 if (Section == Obj->section_end())
989 SymRef.getAddress(Addr);
990 Symbols.insert(std::make_pair(Addr, SymRef));
993 for (const SectionRef &Section : Obj->sections()) {
995 Section.getName(SectName);
996 if (SectName == "__compact_unwind")
997 printMachOCompactUnwindSection(Obj, Symbols, Section);
998 else if (SectName == "__unwind_info")
999 printMachOUnwindInfoSection(Obj, Symbols, Section);
1000 else if (SectName == "__eh_frame")
1001 outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
1006 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
1007 uint32_t cpusubtype, uint32_t filetype,
1008 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
1010 outs() << "Mach header\n";
1011 outs() << " magic cputype cpusubtype caps filetype ncmds "
1012 "sizeofcmds flags\n";
1014 if (magic == MachO::MH_MAGIC)
1015 outs() << " MH_MAGIC";
1016 else if (magic == MachO::MH_MAGIC_64)
1017 outs() << "MH_MAGIC_64";
1019 outs() << format(" 0x%08" PRIx32, magic);
1021 case MachO::CPU_TYPE_I386:
1023 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1024 case MachO::CPU_SUBTYPE_I386_ALL:
1028 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1032 case MachO::CPU_TYPE_X86_64:
1033 outs() << " X86_64";
1034 case MachO::CPU_SUBTYPE_X86_64_ALL:
1037 case MachO::CPU_SUBTYPE_X86_64_H:
1038 outs() << " Haswell";
1039 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1041 case MachO::CPU_TYPE_ARM:
1043 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1044 case MachO::CPU_SUBTYPE_ARM_ALL:
1047 case MachO::CPU_SUBTYPE_ARM_V4T:
1050 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1053 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1054 outs() << " XSCALE";
1056 case MachO::CPU_SUBTYPE_ARM_V6:
1059 case MachO::CPU_SUBTYPE_ARM_V6M:
1062 case MachO::CPU_SUBTYPE_ARM_V7:
1065 case MachO::CPU_SUBTYPE_ARM_V7EM:
1068 case MachO::CPU_SUBTYPE_ARM_V7K:
1071 case MachO::CPU_SUBTYPE_ARM_V7M:
1074 case MachO::CPU_SUBTYPE_ARM_V7S:
1078 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1082 case MachO::CPU_TYPE_ARM64:
1084 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1085 case MachO::CPU_SUBTYPE_ARM64_ALL:
1089 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1093 case MachO::CPU_TYPE_POWERPC:
1095 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1096 case MachO::CPU_SUBTYPE_POWERPC_ALL:
1100 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1104 case MachO::CPU_TYPE_POWERPC64:
1106 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1107 case MachO::CPU_SUBTYPE_POWERPC_ALL:
1111 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1116 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
1117 outs() << " LIB64 ";
1119 outs() << format(" 0x%02" PRIx32,
1120 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
1123 case MachO::MH_OBJECT:
1124 outs() << " OBJECT";
1126 case MachO::MH_EXECUTE:
1127 outs() << " EXECUTE";
1129 case MachO::MH_FVMLIB:
1130 outs() << " FVMLIB";
1132 case MachO::MH_CORE:
1135 case MachO::MH_PRELOAD:
1136 outs() << " PRELOAD";
1138 case MachO::MH_DYLIB:
1141 case MachO::MH_DYLIB_STUB:
1142 outs() << " DYLIB_STUB";
1144 case MachO::MH_DYLINKER:
1145 outs() << " DYLINKER";
1147 case MachO::MH_BUNDLE:
1148 outs() << " BUNDLE";
1150 case MachO::MH_DSYM:
1153 case MachO::MH_KEXT_BUNDLE:
1154 outs() << " KEXTBUNDLE";
1157 outs() << format(" %10u", filetype);
1160 outs() << format(" %5u", ncmds);
1161 outs() << format(" %10u", sizeofcmds);
1163 if (f & MachO::MH_NOUNDEFS) {
1164 outs() << " NOUNDEFS";
1165 f &= ~MachO::MH_NOUNDEFS;
1167 if (f & MachO::MH_INCRLINK) {
1168 outs() << " INCRLINK";
1169 f &= ~MachO::MH_INCRLINK;
1171 if (f & MachO::MH_DYLDLINK) {
1172 outs() << " DYLDLINK";
1173 f &= ~MachO::MH_DYLDLINK;
1175 if (f & MachO::MH_BINDATLOAD) {
1176 outs() << " BINDATLOAD";
1177 f &= ~MachO::MH_BINDATLOAD;
1179 if (f & MachO::MH_PREBOUND) {
1180 outs() << " PREBOUND";
1181 f &= ~MachO::MH_PREBOUND;
1183 if (f & MachO::MH_SPLIT_SEGS) {
1184 outs() << " SPLIT_SEGS";
1185 f &= ~MachO::MH_SPLIT_SEGS;
1187 if (f & MachO::MH_LAZY_INIT) {
1188 outs() << " LAZY_INIT";
1189 f &= ~MachO::MH_LAZY_INIT;
1191 if (f & MachO::MH_TWOLEVEL) {
1192 outs() << " TWOLEVEL";
1193 f &= ~MachO::MH_TWOLEVEL;
1195 if (f & MachO::MH_FORCE_FLAT) {
1196 outs() << " FORCE_FLAT";
1197 f &= ~MachO::MH_FORCE_FLAT;
1199 if (f & MachO::MH_NOMULTIDEFS) {
1200 outs() << " NOMULTIDEFS";
1201 f &= ~MachO::MH_NOMULTIDEFS;
1203 if (f & MachO::MH_NOFIXPREBINDING) {
1204 outs() << " NOFIXPREBINDING";
1205 f &= ~MachO::MH_NOFIXPREBINDING;
1207 if (f & MachO::MH_PREBINDABLE) {
1208 outs() << " PREBINDABLE";
1209 f &= ~MachO::MH_PREBINDABLE;
1211 if (f & MachO::MH_ALLMODSBOUND) {
1212 outs() << " ALLMODSBOUND";
1213 f &= ~MachO::MH_ALLMODSBOUND;
1215 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
1216 outs() << " SUBSECTIONS_VIA_SYMBOLS";
1217 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
1219 if (f & MachO::MH_CANONICAL) {
1220 outs() << " CANONICAL";
1221 f &= ~MachO::MH_CANONICAL;
1223 if (f & MachO::MH_WEAK_DEFINES) {
1224 outs() << " WEAK_DEFINES";
1225 f &= ~MachO::MH_WEAK_DEFINES;
1227 if (f & MachO::MH_BINDS_TO_WEAK) {
1228 outs() << " BINDS_TO_WEAK";
1229 f &= ~MachO::MH_BINDS_TO_WEAK;
1231 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
1232 outs() << " ALLOW_STACK_EXECUTION";
1233 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
1235 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
1236 outs() << " DEAD_STRIPPABLE_DYLIB";
1237 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
1239 if (f & MachO::MH_PIE) {
1241 f &= ~MachO::MH_PIE;
1243 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
1244 outs() << " NO_REEXPORTED_DYLIBS";
1245 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
1247 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
1248 outs() << " MH_HAS_TLV_DESCRIPTORS";
1249 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
1251 if (f & MachO::MH_NO_HEAP_EXECUTION) {
1252 outs() << " MH_NO_HEAP_EXECUTION";
1253 f &= ~MachO::MH_NO_HEAP_EXECUTION;
1255 if (f & MachO::MH_APP_EXTENSION_SAFE) {
1256 outs() << " APP_EXTENSION_SAFE";
1257 f &= ~MachO::MH_APP_EXTENSION_SAFE;
1259 if (f != 0 || flags == 0)
1260 outs() << format(" 0x%08" PRIx32, f);
1262 outs() << format(" 0x%08" PRIx32, magic);
1263 outs() << format(" %7d", cputype);
1264 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1265 outs() << format(" 0x%02" PRIx32,
1266 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
1267 outs() << format(" %10u", filetype);
1268 outs() << format(" %5u", ncmds);
1269 outs() << format(" %10u", sizeofcmds);
1270 outs() << format(" 0x%08" PRIx32, flags);
1275 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
1276 StringRef SegName, uint64_t vmaddr,
1277 uint64_t vmsize, uint64_t fileoff,
1278 uint64_t filesize, uint32_t maxprot,
1279 uint32_t initprot, uint32_t nsects,
1280 uint32_t flags, uint32_t object_size,
1282 uint64_t expected_cmdsize;
1283 if (cmd == MachO::LC_SEGMENT) {
1284 outs() << " cmd LC_SEGMENT\n";
1285 expected_cmdsize = nsects;
1286 expected_cmdsize *= sizeof(struct MachO::section);
1287 expected_cmdsize += sizeof(struct MachO::segment_command);
1289 outs() << " cmd LC_SEGMENT_64\n";
1290 expected_cmdsize = nsects;
1291 expected_cmdsize *= sizeof(struct MachO::section_64);
1292 expected_cmdsize += sizeof(struct MachO::segment_command_64);
1294 outs() << " cmdsize " << cmdsize;
1295 if (cmdsize != expected_cmdsize)
1296 outs() << " Inconsistent size\n";
1299 outs() << " segname " << SegName << "\n";
1300 if (cmd == MachO::LC_SEGMENT_64) {
1301 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
1302 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
1304 outs() << " vmaddr " << format("0x%08" PRIx32, vmaddr) << "\n";
1305 outs() << " vmsize " << format("0x%08" PRIx32, vmsize) << "\n";
1307 outs() << " fileoff " << fileoff;
1308 if (fileoff > object_size)
1309 outs() << " (past end of file)\n";
1312 outs() << " filesize " << filesize;
1313 if (fileoff + filesize > object_size)
1314 outs() << " (past end of file)\n";
1319 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
1320 MachO::VM_PROT_EXECUTE)) != 0)
1321 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
1323 if (maxprot & MachO::VM_PROT_READ)
1324 outs() << " maxprot r";
1326 outs() << " maxprot -";
1327 if (maxprot & MachO::VM_PROT_WRITE)
1331 if (maxprot & MachO::VM_PROT_EXECUTE)
1337 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
1338 MachO::VM_PROT_EXECUTE)) != 0)
1339 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
1341 if (initprot & MachO::VM_PROT_READ)
1342 outs() << " initprot r";
1344 outs() << " initprot -";
1345 if (initprot & MachO::VM_PROT_WRITE)
1349 if (initprot & MachO::VM_PROT_EXECUTE)
1355 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
1356 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
1358 outs() << " nsects " << nsects << "\n";
1362 outs() << " (none)\n";
1364 if (flags & MachO::SG_HIGHVM) {
1365 outs() << " HIGHVM";
1366 flags &= ~MachO::SG_HIGHVM;
1368 if (flags & MachO::SG_FVMLIB) {
1369 outs() << " FVMLIB";
1370 flags &= ~MachO::SG_FVMLIB;
1372 if (flags & MachO::SG_NORELOC) {
1373 outs() << " NORELOC";
1374 flags &= ~MachO::SG_NORELOC;
1376 if (flags & MachO::SG_PROTECTED_VERSION_1) {
1377 outs() << " PROTECTED_VERSION_1";
1378 flags &= ~MachO::SG_PROTECTED_VERSION_1;
1381 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
1386 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
1390 static void PrintSection(const char *sectname, const char *segname,
1391 uint64_t addr, uint64_t size, uint32_t offset,
1392 uint32_t align, uint32_t reloff, uint32_t nreloc,
1393 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
1394 uint32_t cmd, const char *sg_segname,
1395 uint32_t filetype, uint32_t object_size,
1397 outs() << "Section\n";
1398 outs() << " sectname " << format("%.16s\n", sectname);
1399 outs() << " segname " << format("%.16s", segname);
1400 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
1401 outs() << " (does not match segment)\n";
1404 if (cmd == MachO::LC_SEGMENT_64) {
1405 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
1406 outs() << " size " << format("0x%016" PRIx64, size);
1408 outs() << " addr " << format("0x%08" PRIx32, addr) << "\n";
1409 outs() << " size " << format("0x%08" PRIx32, size);
1411 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
1412 outs() << " (past end of file)\n";
1415 outs() << " offset " << offset;
1416 if (offset > object_size)
1417 outs() << " (past end of file)\n";
1420 uint32_t align_shifted = 1 << align;
1421 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
1422 outs() << " reloff " << reloff;
1423 if (reloff > object_size)
1424 outs() << " (past end of file)\n";
1427 outs() << " nreloc " << nreloc;
1428 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
1429 outs() << " (past end of file)\n";
1432 uint32_t section_type = flags & MachO::SECTION_TYPE;
1435 if (section_type == MachO::S_REGULAR)
1436 outs() << " S_REGULAR\n";
1437 else if (section_type == MachO::S_ZEROFILL)
1438 outs() << " S_ZEROFILL\n";
1439 else if (section_type == MachO::S_CSTRING_LITERALS)
1440 outs() << " S_CSTRING_LITERALS\n";
1441 else if (section_type == MachO::S_4BYTE_LITERALS)
1442 outs() << " S_4BYTE_LITERALS\n";
1443 else if (section_type == MachO::S_8BYTE_LITERALS)
1444 outs() << " S_8BYTE_LITERALS\n";
1445 else if (section_type == MachO::S_16BYTE_LITERALS)
1446 outs() << " S_16BYTE_LITERALS\n";
1447 else if (section_type == MachO::S_LITERAL_POINTERS)
1448 outs() << " S_LITERAL_POINTERS\n";
1449 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
1450 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
1451 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
1452 outs() << " S_LAZY_SYMBOL_POINTERS\n";
1453 else if (section_type == MachO::S_SYMBOL_STUBS)
1454 outs() << " S_SYMBOL_STUBS\n";
1455 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
1456 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
1457 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
1458 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
1459 else if (section_type == MachO::S_COALESCED)
1460 outs() << " S_COALESCED\n";
1461 else if (section_type == MachO::S_INTERPOSING)
1462 outs() << " S_INTERPOSING\n";
1463 else if (section_type == MachO::S_DTRACE_DOF)
1464 outs() << " S_DTRACE_DOF\n";
1465 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
1466 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
1467 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
1468 outs() << " S_THREAD_LOCAL_REGULAR\n";
1469 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
1470 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
1471 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
1472 outs() << " S_THREAD_LOCAL_VARIABLES\n";
1473 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
1474 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
1475 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
1476 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
1478 outs() << format("0x%08" PRIx32, section_type) << "\n";
1479 outs() << "attributes";
1480 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
1481 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
1482 outs() << " PURE_INSTRUCTIONS";
1483 if (section_attributes & MachO::S_ATTR_NO_TOC)
1484 outs() << " NO_TOC";
1485 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
1486 outs() << " STRIP_STATIC_SYMS";
1487 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
1488 outs() << " NO_DEAD_STRIP";
1489 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
1490 outs() << " LIVE_SUPPORT";
1491 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
1492 outs() << " SELF_MODIFYING_CODE";
1493 if (section_attributes & MachO::S_ATTR_DEBUG)
1495 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
1496 outs() << " SOME_INSTRUCTIONS";
1497 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
1498 outs() << " EXT_RELOC";
1499 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
1500 outs() << " LOC_RELOC";
1501 if (section_attributes == 0)
1502 outs() << " (none)";
1505 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
1506 outs() << " reserved1 " << reserved1;
1507 if (section_type == MachO::S_SYMBOL_STUBS ||
1508 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
1509 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
1510 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
1511 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
1512 outs() << " (index into indirect symbol table)\n";
1515 outs() << " reserved2 " << reserved2;
1516 if (section_type == MachO::S_SYMBOL_STUBS)
1517 outs() << " (size of stubs)\n";
1522 static void PrintSymtabLoadCommand(MachO::symtab_command st, uint32_t cputype,
1523 uint32_t object_size) {
1524 outs() << " cmd LC_SYMTAB\n";
1525 outs() << " cmdsize " << st.cmdsize;
1526 if (st.cmdsize != sizeof(struct MachO::symtab_command))
1527 outs() << " Incorrect size\n";
1530 outs() << " symoff " << st.symoff;
1531 if (st.symoff > object_size)
1532 outs() << " (past end of file)\n";
1535 outs() << " nsyms " << st.nsyms;
1537 if (cputype & MachO::CPU_ARCH_ABI64) {
1538 big_size = st.nsyms;
1539 big_size *= sizeof(struct MachO::nlist_64);
1540 big_size += st.symoff;
1541 if (big_size > object_size)
1542 outs() << " (past end of file)\n";
1546 big_size = st.nsyms;
1547 big_size *= sizeof(struct MachO::nlist);
1548 big_size += st.symoff;
1549 if (big_size > object_size)
1550 outs() << " (past end of file)\n";
1554 outs() << " stroff " << st.stroff;
1555 if (st.stroff > object_size)
1556 outs() << " (past end of file)\n";
1559 outs() << " strsize " << st.strsize;
1560 big_size = st.stroff;
1561 big_size += st.strsize;
1562 if (big_size > object_size)
1563 outs() << " (past end of file)\n";
1568 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
1569 uint32_t nsyms, uint32_t object_size,
1571 outs() << " cmd LC_DYSYMTAB\n";
1572 outs() << " cmdsize " << dyst.cmdsize;
1573 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
1574 outs() << " Incorrect size\n";
1577 outs() << " ilocalsym " << dyst.ilocalsym;
1578 if (dyst.ilocalsym > nsyms)
1579 outs() << " (greater than the number of symbols)\n";
1582 outs() << " nlocalsym " << dyst.nlocalsym;
1584 big_size = dyst.ilocalsym;
1585 big_size += dyst.nlocalsym;
1586 if (big_size > nsyms)
1587 outs() << " (past the end of the symbol table)\n";
1590 outs() << " iextdefsym " << dyst.iextdefsym;
1591 if (dyst.iextdefsym > nsyms)
1592 outs() << " (greater than the number of symbols)\n";
1595 outs() << " nextdefsym " << dyst.nextdefsym;
1596 big_size = dyst.iextdefsym;
1597 big_size += dyst.nextdefsym;
1598 if (big_size > nsyms)
1599 outs() << " (past the end of the symbol table)\n";
1602 outs() << " iundefsym " << dyst.iundefsym;
1603 if (dyst.iundefsym > nsyms)
1604 outs() << " (greater than the number of symbols)\n";
1607 outs() << " nundefsym " << dyst.nundefsym;
1608 big_size = dyst.iundefsym;
1609 big_size += dyst.nundefsym;
1610 if (big_size > nsyms)
1611 outs() << " (past the end of the symbol table)\n";
1614 outs() << " tocoff " << dyst.tocoff;
1615 if (dyst.tocoff > object_size)
1616 outs() << " (past end of file)\n";
1619 outs() << " ntoc " << dyst.ntoc;
1620 big_size = dyst.ntoc;
1621 big_size *= sizeof(struct MachO::dylib_table_of_contents);
1622 big_size += dyst.tocoff;
1623 if (big_size > object_size)
1624 outs() << " (past end of file)\n";
1627 outs() << " modtaboff " << dyst.modtaboff;
1628 if (dyst.modtaboff > object_size)
1629 outs() << " (past end of file)\n";
1632 outs() << " nmodtab " << dyst.nmodtab;
1634 if (cputype & MachO::CPU_ARCH_ABI64) {
1635 modtabend = dyst.nmodtab;
1636 modtabend *= sizeof(struct MachO::dylib_module_64);
1637 modtabend += dyst.modtaboff;
1639 modtabend = dyst.nmodtab;
1640 modtabend *= sizeof(struct MachO::dylib_module);
1641 modtabend += dyst.modtaboff;
1643 if (modtabend > object_size)
1644 outs() << " (past end of file)\n";
1647 outs() << " extrefsymoff " << dyst.extrefsymoff;
1648 if (dyst.extrefsymoff > object_size)
1649 outs() << " (past end of file)\n";
1652 outs() << " nextrefsyms " << dyst.nextrefsyms;
1653 big_size = dyst.nextrefsyms;
1654 big_size *= sizeof(struct MachO::dylib_reference);
1655 big_size += dyst.extrefsymoff;
1656 if (big_size > object_size)
1657 outs() << " (past end of file)\n";
1660 outs() << " indirectsymoff " << dyst.indirectsymoff;
1661 if (dyst.indirectsymoff > object_size)
1662 outs() << " (past end of file)\n";
1665 outs() << " nindirectsyms " << dyst.nindirectsyms;
1666 big_size = dyst.nindirectsyms;
1667 big_size *= sizeof(uint32_t);
1668 big_size += dyst.indirectsymoff;
1669 if (big_size > object_size)
1670 outs() << " (past end of file)\n";
1673 outs() << " extreloff " << dyst.extreloff;
1674 if (dyst.extreloff > object_size)
1675 outs() << " (past end of file)\n";
1678 outs() << " nextrel " << dyst.nextrel;
1679 big_size = dyst.nextrel;
1680 big_size *= sizeof(struct MachO::relocation_info);
1681 big_size += dyst.extreloff;
1682 if (big_size > object_size)
1683 outs() << " (past end of file)\n";
1686 outs() << " locreloff " << dyst.locreloff;
1687 if (dyst.locreloff > object_size)
1688 outs() << " (past end of file)\n";
1691 outs() << " nlocrel " << dyst.nlocrel;
1692 big_size = dyst.nlocrel;
1693 big_size *= sizeof(struct MachO::relocation_info);
1694 big_size += dyst.locreloff;
1695 if (big_size > object_size)
1696 outs() << " (past end of file)\n";
1701 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t ncmds,
1702 uint32_t filetype, uint32_t cputype,
1704 StringRef Buf = Obj->getData();
1705 MachOObjectFile::LoadCommandInfo Command = Obj->getFirstLoadCommandInfo();
1706 for (unsigned i = 0;; ++i) {
1707 outs() << "Load command " << i << "\n";
1708 if (Command.C.cmd == MachO::LC_SEGMENT) {
1709 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
1710 const char *sg_segname = SLC.segname;
1711 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
1712 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
1713 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
1715 for (unsigned j = 0; j < SLC.nsects; j++) {
1716 MachO::section_64 S = Obj->getSection64(Command, j);
1717 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
1718 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
1719 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
1721 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
1722 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
1723 const char *sg_segname = SLC_64.segname;
1724 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
1725 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
1726 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
1727 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
1728 for (unsigned j = 0; j < SLC_64.nsects; j++) {
1729 MachO::section_64 S_64 = Obj->getSection64(Command, j);
1730 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
1731 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
1732 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
1733 sg_segname, filetype, Buf.size(), verbose);
1735 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
1736 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
1737 PrintSymtabLoadCommand(Symtab, cputype, Buf.size());
1738 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
1739 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
1740 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
1741 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(), cputype);
1743 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
1745 outs() << " cmdsize " << Command.C.cmdsize << "\n";
1746 // TODO: get and print the raw bytes of the load command.
1748 // TODO: print all the other kinds of load commands.
1752 Command = Obj->getNextLoadCommandInfo(Command);
1756 static void getAndPrintMachHeader(const MachOObjectFile *Obj, uint32_t &ncmds,
1757 uint32_t &filetype, uint32_t &cputype,
1759 if (Obj->is64Bit()) {
1760 MachO::mach_header_64 H_64;
1761 H_64 = Obj->getHeader64();
1762 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
1763 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
1765 filetype = H_64.filetype;
1766 cputype = H_64.cputype;
1768 MachO::mach_header H;
1769 H = Obj->getHeader();
1770 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
1771 H.sizeofcmds, H.flags, verbose);
1773 filetype = H.filetype;
1774 cputype = H.cputype;
1778 void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
1779 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
1781 uint32_t filetype = 0;
1782 uint32_t cputype = 0;
1783 getAndPrintMachHeader(file, ncmds, filetype, cputype, true);
1784 PrintLoadCommands(file, ncmds, filetype, cputype, true);
1787 //===----------------------------------------------------------------------===//
1788 // export trie dumping
1789 //===----------------------------------------------------------------------===//
1791 void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
1792 for (const llvm::object::ExportEntry &entry : Obj->exports()) {
1793 uint64_t Flags = entry.flags();
1794 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
1795 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
1796 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
1797 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
1798 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
1799 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
1800 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
1802 outs() << "[re-export] ";
1805 << format("0x%08llX ", entry.address()); // FIXME:add in base address
1806 outs() << entry.name();
1807 if (WeakDef || ThreadLocal || Resolver || Abs) {
1808 bool needComma = false;
1811 outs() << "weak_def";
1817 outs() << "per-thread";
1823 outs() << "absolute";
1829 outs() << format("resolver=0x%08llX", entry.other());
1835 StringRef DylibName = "unknown";
1836 int ordinal = entry.other() - 1;
1837 Obj->getLibraryShortNameByIndex(ordinal, DylibName);
1838 if (entry.otherName().empty())
1839 outs() << " (from " << DylibName << ")";
1841 outs() << " (" << entry.otherName() << " from " << DylibName << ")";