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: 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;
320 getSectionsAndSymbols(Header, MachOOF, Sections, Symbols, FoundFns,
323 // Sort the symbols by address, just in case they didn't come in that way.
324 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
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);
331 BaseAddress = BaseSegmentAddress;
333 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
336 DI->getOffset(Offset);
337 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
339 array_pod_sort(Dices.begin(), Dices.end());
342 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
344 raw_ostream &DebugOut = nulls();
347 std::unique_ptr<DIContext> diContext;
348 ObjectFile *DbgObj = MachOOF;
349 // Try to find debug info and set up the DIContext for it.
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';
361 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
366 // Setup the DIContext
367 diContext.reset(DIContext::getDWARFContext(*DbgObj));
370 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
372 bool SectIsText = false;
373 Sections[SectIdx].isText(SectIsText);
374 if (SectIsText == false)
378 if (Sections[SectIdx].getName(SectName) ||
379 SectName != "__text")
380 continue; // Skip non-text sections
382 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
384 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
385 if (SegmentName != "__TEXT")
389 Sections[SectIdx].getContents(Bytes);
390 StringRefMemoryObject memoryObject(Bytes);
391 bool symbolTableWorked = false;
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;
401 symbol_iterator RelocSym = Reloc.getSymbol();
403 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
405 array_pod_sort(Relocs.begin(), Relocs.end());
407 // Disassemble symbol by symbol.
408 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
410 Symbols[SymIdx].getName(SymName);
413 Symbols[SymIdx].getType(ST);
414 if (ST != SymbolRef::ST_Function)
417 // Make sure the symbol is defined in this section.
418 bool containsSym = false;
419 Sections[SectIdx].containsSymbol(Symbols[SymIdx], containsSym);
423 // Start at the address of the symbol relative to the section's address.
424 uint64_t SectionAddress = 0;
426 Sections[SectIdx].getAddress(SectionAddress);
427 Symbols[SymIdx].getAddress(Start);
428 Start -= SectionAddress;
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],
441 Symbols[NextSymIdx].getAddress(NextSym);
442 NextSym -= SectionAddress;
449 Sections[SectIdx].getSize(SectSize);
450 uint64_t End = containsNextSym ? NextSym : SectSize;
453 symbolTableWorked = true;
455 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
457 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
459 outs() << SymName << ":\n";
461 for (uint64_t Index = Start; Index < End; Index += Size) {
464 uint64_t SectAddress = 0;
465 Sections[SectIdx].getAddress(SectAddress);
466 outs() << format("%8" PRIx64 ":\t", SectAddress + Index);
468 // Check the data in code table here to see if this is data not an
469 // instruction to be disassembled.
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()){
477 DTI->second.getLength(Length);
478 DumpBytes(StringRef(Bytes.data() + Index, Length));
480 DTI->second.getKind(Kind);
481 DumpDataInCode(Bytes.data() + Index, Length, Kind);
487 gotInst = ThumbDisAsm->getInstruction(Inst, Size, memoryObject, Index,
490 gotInst = DisAsm->getInstruction(Inst, Size, memoryObject, Index,
493 DumpBytes(StringRef(Bytes.data() + Index, Size));
495 ThumbIP->printInst(&Inst, outs(), "");
497 IP->printInst(&Inst, outs(), "");
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 << ':'
511 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
513 Size = 1; // skip illegible bytes
517 if (!symbolTableWorked) {
518 // Reading the symbol table didn't work, disassemble the whole section.
519 uint64_t SectAddress;
520 Sections[SectIdx].getAddress(SectAddress);
522 Sections[SectIdx].getSize(SectSize);
524 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
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(), "");
534 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
536 InstSize = 1; // skip illegible bytes
544 //===----------------------------------------------------------------------===//
545 // __compact_unwind section dumping
546 //===----------------------------------------------------------------------===//
550 template <typename T> static uint64_t readNext(const char *&Buf) {
551 using llvm::support::little;
552 using llvm::support::unaligned;
554 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
559 struct CompactUnwindEntry {
560 uint32_t OffsetInSection;
562 uint64_t FunctionAddr;
564 uint32_t CompactEncoding;
565 uint64_t PersonalityAddr;
568 RelocationRef FunctionReloc;
569 RelocationRef PersonalityReloc;
570 RelocationRef LSDAReloc;
572 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
573 : OffsetInSection(Offset) {
575 read<uint64_t>(Contents.data() + Offset);
577 read<uint32_t>(Contents.data() + Offset);
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);
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.
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,
606 StringRef &Name, uint64_t &Addend) {
607 if (Reloc.getSymbol() != Obj->symbol_end()) {
608 Reloc.getSymbol()->getName(Name);
613 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
614 SectionRef RelocSection = Obj->getRelocationSection(RE);
616 uint64_t SectionAddr;
617 RelocSection.getAddress(SectionAddr);
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;
628 // Go back one so that SymbolAddress <= Addr.
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;
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;
646 static void printUnwindRelocDest(const MachOObjectFile *Obj,
647 std::map<uint64_t, SymbolRef> &Symbols,
648 const RelocationRef &Reloc,
653 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
657 outs() << " + " << format("0x%" PRIx64, Addend);
661 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
662 std::map<uint64_t, SymbolRef> &Symbols,
663 const SectionRef &CompactUnwind) {
665 assert(Obj->isLittleEndian() &&
666 "There should not be a big-endian .o with __compact_unwind");
668 bool Is64 = Obj->is64Bit();
669 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
670 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
673 CompactUnwind.getContents(Contents);
675 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
677 // First populate the initial raw offsets, encodings and so on from the entry.
678 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
679 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
680 CompactUnwinds.push_back(Entry);
683 // Next we need to look at the relocations to find out what objects are
684 // actually being referred to.
685 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
686 uint64_t RelocAddress;
687 Reloc.getOffset(RelocAddress);
689 uint32_t EntryIdx = RelocAddress / EntrySize;
690 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
691 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
693 if (OffsetInEntry == 0)
694 Entry.FunctionReloc = Reloc;
695 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
696 Entry.PersonalityReloc = Reloc;
697 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
698 Entry.LSDAReloc = Reloc;
700 llvm_unreachable("Unexpected relocation in __compact_unwind section");
703 // Finally, we're ready to print the data we've gathered.
704 outs() << "Contents of __compact_unwind section:\n";
705 for (auto &Entry : CompactUnwinds) {
706 outs() << " Entry at offset "
707 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
709 // 1. Start of the region this entry applies to.
711 << format("0x%" PRIx64, Entry.FunctionAddr) << ' ';
712 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc,
716 // 2. Length of the region this entry applies to.
717 outs() << " length: "
718 << format("0x%" PRIx32, Entry.Length) << '\n';
719 // 3. The 32-bit compact encoding.
720 outs() << " compact encoding: "
721 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
723 // 4. The personality function, if present.
724 if (Entry.PersonalityReloc.getObjectFile()) {
725 outs() << " personality function: "
726 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
727 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
728 Entry.PersonalityAddr);
732 // 5. This entry's language-specific data area.
733 if (Entry.LSDAReloc.getObjectFile()) {
735 << format("0x%" PRIx64, Entry.LSDAAddr) << ' ';
736 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
742 //===----------------------------------------------------------------------===//
743 // __unwind_info section dumping
744 //===----------------------------------------------------------------------===//
746 static void printRegularSecondLevelUnwindPage(const char *PageStart) {
747 const char *Pos = PageStart;
748 uint32_t Kind = readNext<uint32_t>(Pos);
750 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
752 uint16_t EntriesStart = readNext<uint16_t>(Pos);
753 uint16_t NumEntries = readNext<uint16_t>(Pos);
755 Pos = PageStart + EntriesStart;
756 for (unsigned i = 0; i < NumEntries; ++i) {
757 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
758 uint32_t Encoding = readNext<uint32_t>(Pos);
760 outs() << " [" << i << "]: "
761 << "function offset="
762 << format("0x%08" PRIx32, FunctionOffset) << ", "
764 << format("0x%08" PRIx32, Encoding)
769 static void printCompressedSecondLevelUnwindPage(
770 const char *PageStart, uint32_t FunctionBase,
771 const SmallVectorImpl<uint32_t> &CommonEncodings) {
772 const char *Pos = PageStart;
773 uint32_t Kind = readNext<uint32_t>(Pos);
775 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
777 uint16_t EntriesStart = readNext<uint16_t>(Pos);
778 uint16_t NumEntries = readNext<uint16_t>(Pos);
780 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
781 readNext<uint16_t>(Pos);
782 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
783 PageStart + EncodingsStart);
785 Pos = PageStart + EntriesStart;
786 for (unsigned i = 0; i < NumEntries; ++i) {
787 uint32_t Entry = readNext<uint32_t>(Pos);
788 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
789 uint32_t EncodingIdx = Entry >> 24;
792 if (EncodingIdx < CommonEncodings.size())
793 Encoding = CommonEncodings[EncodingIdx];
795 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
797 outs() << " [" << i << "]: "
798 << "function offset="
799 << format("0x%08" PRIx32, FunctionOffset) << ", "
800 << "encoding[" << EncodingIdx << "]="
801 << format("0x%08" PRIx32, Encoding)
807 printMachOUnwindInfoSection(const MachOObjectFile *Obj,
808 std::map<uint64_t, SymbolRef> &Symbols,
809 const SectionRef &UnwindInfo) {
811 assert(Obj->isLittleEndian() &&
812 "There should not be a big-endian .o with __unwind_info");
814 outs() << "Contents of __unwind_info section:\n";
817 UnwindInfo.getContents(Contents);
818 const char *Pos = Contents.data();
820 //===----------------------------------
822 //===----------------------------------
824 uint32_t Version = readNext<uint32_t>(Pos);
825 outs() << " Version: "
826 << format("0x%" PRIx32, Version) << '\n';
827 assert(Version == 1 && "only understand version 1");
829 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
830 outs() << " Common encodings array section offset: "
831 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
832 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
833 outs() << " Number of common encodings in array: "
834 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
836 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
837 outs() << " Personality function array section offset: "
838 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
839 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
840 outs() << " Number of personality functions in array: "
841 << format("0x%" PRIx32, NumPersonalities) << '\n';
843 uint32_t IndicesStart = readNext<uint32_t>(Pos);
844 outs() << " Index array section offset: "
845 << format("0x%" PRIx32, IndicesStart) << '\n';
846 uint32_t NumIndices = readNext<uint32_t>(Pos);
847 outs() << " Number of indices in array: "
848 << format("0x%" PRIx32, NumIndices) << '\n';
850 //===----------------------------------
851 // A shared list of common encodings
852 //===----------------------------------
854 // These occupy indices in the range [0, N] whenever an encoding is referenced
855 // from a compressed 2nd level index table. In practice the linker only
856 // creates ~128 of these, so that indices are available to embed encodings in
857 // the 2nd level index.
859 SmallVector<uint32_t, 64> CommonEncodings;
860 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
861 Pos = Contents.data() + CommonEncodingsStart;
862 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
863 uint32_t Encoding = readNext<uint32_t>(Pos);
864 CommonEncodings.push_back(Encoding);
866 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
871 //===----------------------------------
872 // Personality functions used in this executable
873 //===----------------------------------
875 // There should be only a handful of these (one per source language,
876 // roughly). Particularly since they only get 2 bits in the compact encoding.
878 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
879 Pos = Contents.data() + PersonalitiesStart;
880 for (unsigned i = 0; i < NumPersonalities; ++i) {
881 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
882 outs() << " personality[" << i + 1
883 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
886 //===----------------------------------
887 // The level 1 index entries
888 //===----------------------------------
890 // These specify an approximate place to start searching for the more detailed
891 // information, sorted by PC.
894 uint32_t FunctionOffset;
895 uint32_t SecondLevelPageStart;
899 SmallVector<IndexEntry, 4> IndexEntries;
901 outs() << " Top level indices: (count = " << NumIndices << ")\n";
902 Pos = Contents.data() + IndicesStart;
903 for (unsigned i = 0; i < NumIndices; ++i) {
906 Entry.FunctionOffset = readNext<uint32_t>(Pos);
907 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
908 Entry.LSDAStart = readNext<uint32_t>(Pos);
909 IndexEntries.push_back(Entry);
911 outs() << " [" << i << "]: "
912 << "function offset="
913 << format("0x%08" PRIx32, Entry.FunctionOffset) << ", "
914 << "2nd level page offset="
915 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
917 << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
921 //===----------------------------------
922 // Next come the LSDA tables
923 //===----------------------------------
925 // The LSDA layout is rather implicit: it's a contiguous array of entries from
926 // the first top-level index's LSDAOffset to the last (sentinel).
928 outs() << " LSDA descriptors:\n";
929 Pos = Contents.data() + IndexEntries[0].LSDAStart;
930 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
931 (2 * sizeof(uint32_t));
932 for (int i = 0; i < NumLSDAs; ++i) {
933 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
934 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
935 outs() << " [" << i << "]: "
936 << "function offset="
937 << format("0x%08" PRIx32, FunctionOffset) << ", "
939 << format("0x%08" PRIx32, LSDAOffset) << '\n';
942 //===----------------------------------
943 // Finally, the 2nd level indices
944 //===----------------------------------
946 // Generally these are 4K in size, and have 2 possible forms:
947 // + Regular stores up to 511 entries with disparate encodings
948 // + Compressed stores up to 1021 entries if few enough compact encoding
950 outs() << " Second level indices:\n";
951 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
952 // The final sentinel top-level index has no associated 2nd level page
953 if (IndexEntries[i].SecondLevelPageStart == 0)
956 outs() << " Second level index[" << i << "]: "
957 << "offset in section="
958 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
960 << "base function offset="
961 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
963 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
964 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
966 printRegularSecondLevelUnwindPage(Pos);
968 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
971 llvm_unreachable("Do not know how to print this kind of 2nd level page");
976 void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
977 std::map<uint64_t, SymbolRef> Symbols;
978 for (const SymbolRef &SymRef : Obj->symbols()) {
979 // Discard any undefined or absolute symbols. They're not going to take part
980 // in the convenience lookup for unwind info and just take up resources.
981 section_iterator Section = Obj->section_end();
982 SymRef.getSection(Section);
983 if (Section == Obj->section_end())
987 SymRef.getAddress(Addr);
988 Symbols.insert(std::make_pair(Addr, SymRef));
991 for (const SectionRef &Section : Obj->sections()) {
993 Section.getName(SectName);
994 if (SectName == "__compact_unwind")
995 printMachOCompactUnwindSection(Obj, Symbols, Section);
996 else if (SectName == "__unwind_info")
997 printMachOUnwindInfoSection(Obj, Symbols, Section);
998 else if (SectName == "__eh_frame")
999 outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
1004 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
1005 uint32_t cpusubtype, uint32_t filetype,
1006 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
1008 outs() << "Mach header\n";
1009 outs() << " magic cputype cpusubtype caps filetype ncmds "
1010 "sizeofcmds flags\n";
1012 if (magic == MachO::MH_MAGIC)
1013 outs() << " MH_MAGIC";
1014 else if (magic == MachO::MH_MAGIC_64)
1015 outs() << "MH_MAGIC_64";
1017 outs() << format(" 0x%08" PRIx32, magic);
1019 case MachO::CPU_TYPE_I386:
1021 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1022 case MachO::CPU_SUBTYPE_I386_ALL:
1026 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1030 case MachO::CPU_TYPE_X86_64:
1031 outs() << " X86_64";
1032 case MachO::CPU_SUBTYPE_X86_64_ALL:
1035 case MachO::CPU_SUBTYPE_X86_64_H:
1036 outs() << " Haswell";
1037 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1039 case MachO::CPU_TYPE_ARM:
1041 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1042 case MachO::CPU_SUBTYPE_ARM_ALL:
1045 case MachO::CPU_SUBTYPE_ARM_V4T:
1048 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1051 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1052 outs() << " XSCALE";
1054 case MachO::CPU_SUBTYPE_ARM_V6:
1057 case MachO::CPU_SUBTYPE_ARM_V6M:
1060 case MachO::CPU_SUBTYPE_ARM_V7:
1063 case MachO::CPU_SUBTYPE_ARM_V7EM:
1066 case MachO::CPU_SUBTYPE_ARM_V7K:
1069 case MachO::CPU_SUBTYPE_ARM_V7M:
1072 case MachO::CPU_SUBTYPE_ARM_V7S:
1076 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1080 case MachO::CPU_TYPE_ARM64:
1082 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1083 case MachO::CPU_SUBTYPE_ARM64_ALL:
1087 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1091 case MachO::CPU_TYPE_POWERPC:
1093 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1094 case MachO::CPU_SUBTYPE_POWERPC_ALL:
1098 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1102 case MachO::CPU_TYPE_POWERPC64:
1104 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1105 case MachO::CPU_SUBTYPE_POWERPC_ALL:
1109 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1114 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
1115 outs() << " LIB64 ";
1117 outs() << format(" 0x%02" PRIx32,
1118 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
1121 case MachO::MH_OBJECT:
1122 outs() << " OBJECT";
1124 case MachO::MH_EXECUTE:
1125 outs() << " EXECUTE";
1127 case MachO::MH_FVMLIB:
1128 outs() << " FVMLIB";
1130 case MachO::MH_CORE:
1133 case MachO::MH_PRELOAD:
1134 outs() << " PRELOAD";
1136 case MachO::MH_DYLIB:
1139 case MachO::MH_DYLIB_STUB:
1140 outs() << " DYLIB_STUB";
1142 case MachO::MH_DYLINKER:
1143 outs() << " DYLINKER";
1145 case MachO::MH_BUNDLE:
1146 outs() << " BUNDLE";
1148 case MachO::MH_DSYM:
1151 case MachO::MH_KEXT_BUNDLE:
1152 outs() << " KEXTBUNDLE";
1155 outs() << format(" %10u", filetype);
1158 outs() << format(" %5u", ncmds);
1159 outs() << format(" %10u", sizeofcmds);
1161 if (f & MachO::MH_NOUNDEFS) {
1162 outs() << " NOUNDEFS";
1163 f &= ~MachO::MH_NOUNDEFS;
1165 if (f & MachO::MH_INCRLINK) {
1166 outs() << " INCRLINK";
1167 f &= ~MachO::MH_INCRLINK;
1169 if (f & MachO::MH_DYLDLINK) {
1170 outs() << " DYLDLINK";
1171 f &= ~MachO::MH_DYLDLINK;
1173 if (f & MachO::MH_BINDATLOAD) {
1174 outs() << " BINDATLOAD";
1175 f &= ~MachO::MH_BINDATLOAD;
1177 if (f & MachO::MH_PREBOUND) {
1178 outs() << " PREBOUND";
1179 f &= ~MachO::MH_PREBOUND;
1181 if (f & MachO::MH_SPLIT_SEGS) {
1182 outs() << " SPLIT_SEGS";
1183 f &= ~MachO::MH_SPLIT_SEGS;
1185 if (f & MachO::MH_LAZY_INIT) {
1186 outs() << " LAZY_INIT";
1187 f &= ~MachO::MH_LAZY_INIT;
1189 if (f & MachO::MH_TWOLEVEL) {
1190 outs() << " TWOLEVEL";
1191 f &= ~MachO::MH_TWOLEVEL;
1193 if (f & MachO::MH_FORCE_FLAT) {
1194 outs() << " FORCE_FLAT";
1195 f &= ~MachO::MH_FORCE_FLAT;
1197 if (f & MachO::MH_NOMULTIDEFS) {
1198 outs() << " NOMULTIDEFS";
1199 f &= ~MachO::MH_NOMULTIDEFS;
1201 if (f & MachO::MH_NOFIXPREBINDING) {
1202 outs() << " NOFIXPREBINDING";
1203 f &= ~MachO::MH_NOFIXPREBINDING;
1205 if (f & MachO::MH_PREBINDABLE) {
1206 outs() << " PREBINDABLE";
1207 f &= ~MachO::MH_PREBINDABLE;
1209 if (f & MachO::MH_ALLMODSBOUND) {
1210 outs() << " ALLMODSBOUND";
1211 f &= ~MachO::MH_ALLMODSBOUND;
1213 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
1214 outs() << " SUBSECTIONS_VIA_SYMBOLS";
1215 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
1217 if (f & MachO::MH_CANONICAL) {
1218 outs() << " CANONICAL";
1219 f &= ~MachO::MH_CANONICAL;
1221 if (f & MachO::MH_WEAK_DEFINES) {
1222 outs() << " WEAK_DEFINES";
1223 f &= ~MachO::MH_WEAK_DEFINES;
1225 if (f & MachO::MH_BINDS_TO_WEAK) {
1226 outs() << " BINDS_TO_WEAK";
1227 f &= ~MachO::MH_BINDS_TO_WEAK;
1229 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
1230 outs() << " ALLOW_STACK_EXECUTION";
1231 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
1233 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
1234 outs() << " DEAD_STRIPPABLE_DYLIB";
1235 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
1237 if (f & MachO::MH_PIE) {
1239 f &= ~MachO::MH_PIE;
1241 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
1242 outs() << " NO_REEXPORTED_DYLIBS";
1243 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
1245 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
1246 outs() << " MH_HAS_TLV_DESCRIPTORS";
1247 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
1249 if (f & MachO::MH_NO_HEAP_EXECUTION) {
1250 outs() << " MH_NO_HEAP_EXECUTION";
1251 f &= ~MachO::MH_NO_HEAP_EXECUTION;
1253 if (f & MachO::MH_APP_EXTENSION_SAFE) {
1254 outs() << " APP_EXTENSION_SAFE";
1255 f &= ~MachO::MH_APP_EXTENSION_SAFE;
1257 if (f != 0 || flags == 0)
1258 outs() << format(" 0x%08" PRIx32, f);
1260 outs() << format(" 0x%08" PRIx32, magic);
1261 outs() << format(" %7d", cputype);
1262 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1263 outs() << format(" 0x%02" PRIx32,
1264 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
1265 outs() << format(" %10u", filetype);
1266 outs() << format(" %5u", ncmds);
1267 outs() << format(" %10u", sizeofcmds);
1268 outs() << format(" 0x%08" PRIx32, flags);
1273 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
1274 StringRef SegName, uint64_t vmaddr,
1275 uint64_t vmsize, uint64_t fileoff,
1276 uint64_t filesize, uint32_t maxprot,
1277 uint32_t initprot, uint32_t nsects,
1278 uint32_t flags, uint32_t object_size,
1280 uint64_t expected_cmdsize;
1281 if (cmd == MachO::LC_SEGMENT) {
1282 outs() << " cmd LC_SEGMENT\n";
1283 expected_cmdsize = nsects;
1284 expected_cmdsize *= sizeof(struct MachO::section);
1285 expected_cmdsize += sizeof(struct MachO::segment_command);
1287 outs() << " cmd LC_SEGMENT_64\n";
1288 expected_cmdsize = nsects;
1289 expected_cmdsize *= sizeof(struct MachO::section_64);
1290 expected_cmdsize += sizeof(struct MachO::segment_command_64);
1292 outs() << " cmdsize " << cmdsize;
1293 if (cmdsize != expected_cmdsize)
1294 outs() << " Inconsistent size\n";
1297 outs() << " segname " << SegName << "\n";
1298 if (cmd == MachO::LC_SEGMENT_64) {
1299 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
1300 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
1302 outs() << " vmaddr " << format("0x%08" PRIx32, vmaddr) << "\n";
1303 outs() << " vmsize " << format("0x%08" PRIx32, vmsize) << "\n";
1305 outs() << " fileoff " << fileoff;
1306 if (fileoff > object_size)
1307 outs() << " (past end of file)\n";
1310 outs() << " filesize " << filesize;
1311 if (fileoff + filesize > object_size)
1312 outs() << " (past end of file)\n";
1317 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
1318 MachO::VM_PROT_EXECUTE)) != 0)
1319 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
1321 if (maxprot & MachO::VM_PROT_READ)
1322 outs() << " maxprot r";
1324 outs() << " maxprot -";
1325 if (maxprot & MachO::VM_PROT_WRITE)
1329 if (maxprot & MachO::VM_PROT_EXECUTE)
1335 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
1336 MachO::VM_PROT_EXECUTE)) != 0)
1337 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
1339 if (initprot & MachO::VM_PROT_READ)
1340 outs() << " initprot r";
1342 outs() << " initprot -";
1343 if (initprot & MachO::VM_PROT_WRITE)
1347 if (initprot & MachO::VM_PROT_EXECUTE)
1353 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
1354 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
1356 outs() << " nsects " << nsects << "\n";
1360 outs() << " (none)\n";
1362 if (flags & MachO::SG_HIGHVM) {
1363 outs() << " HIGHVM";
1364 flags &= ~MachO::SG_HIGHVM;
1366 if (flags & MachO::SG_FVMLIB) {
1367 outs() << " FVMLIB";
1368 flags &= ~MachO::SG_FVMLIB;
1370 if (flags & MachO::SG_NORELOC) {
1371 outs() << " NORELOC";
1372 flags &= ~MachO::SG_NORELOC;
1374 if (flags & MachO::SG_PROTECTED_VERSION_1) {
1375 outs() << " PROTECTED_VERSION_1";
1376 flags &= ~MachO::SG_PROTECTED_VERSION_1;
1379 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
1384 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
1388 static void PrintSection(const char *sectname, const char *segname,
1389 uint64_t addr, uint64_t size, uint32_t offset,
1390 uint32_t align, uint32_t reloff, uint32_t nreloc,
1391 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
1392 uint32_t cmd, const char *sg_segname,
1393 uint32_t filetype, uint32_t object_size,
1395 outs() << "Section\n";
1396 outs() << " sectname " << format("%.16s\n", sectname);
1397 outs() << " segname " << format("%.16s", segname);
1398 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
1399 outs() << " (does not match segment)\n";
1402 if (cmd == MachO::LC_SEGMENT_64) {
1403 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
1404 outs() << " size " << format("0x%016" PRIx64, size);
1406 outs() << " addr " << format("0x%08" PRIx32, addr) << "\n";
1407 outs() << " size " << format("0x%08" PRIx32, size);
1409 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
1410 outs() << " (past end of file)\n";
1413 outs() << " offset " << offset;
1414 if (offset > object_size)
1415 outs() << " (past end of file)\n";
1418 uint32_t align_shifted = 1 << align;
1419 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
1420 outs() << " reloff " << reloff;
1421 if (reloff > object_size)
1422 outs() << " (past end of file)\n";
1425 outs() << " nreloc " << nreloc;
1426 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
1427 outs() << " (past end of file)\n";
1430 uint32_t section_type = flags & MachO::SECTION_TYPE;
1433 if (section_type == MachO::S_REGULAR)
1434 outs() << " S_REGULAR\n";
1435 else if (section_type == MachO::S_ZEROFILL)
1436 outs() << " S_ZEROFILL\n";
1437 else if (section_type == MachO::S_CSTRING_LITERALS)
1438 outs() << " S_CSTRING_LITERALS\n";
1439 else if (section_type == MachO::S_4BYTE_LITERALS)
1440 outs() << " S_4BYTE_LITERALS\n";
1441 else if (section_type == MachO::S_8BYTE_LITERALS)
1442 outs() << " S_8BYTE_LITERALS\n";
1443 else if (section_type == MachO::S_16BYTE_LITERALS)
1444 outs() << " S_16BYTE_LITERALS\n";
1445 else if (section_type == MachO::S_LITERAL_POINTERS)
1446 outs() << " S_LITERAL_POINTERS\n";
1447 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
1448 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
1449 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
1450 outs() << " S_LAZY_SYMBOL_POINTERS\n";
1451 else if (section_type == MachO::S_SYMBOL_STUBS)
1452 outs() << " S_SYMBOL_STUBS\n";
1453 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
1454 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
1455 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
1456 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
1457 else if (section_type == MachO::S_COALESCED)
1458 outs() << " S_COALESCED\n";
1459 else if (section_type == MachO::S_INTERPOSING)
1460 outs() << " S_INTERPOSING\n";
1461 else if (section_type == MachO::S_DTRACE_DOF)
1462 outs() << " S_DTRACE_DOF\n";
1463 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
1464 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
1465 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
1466 outs() << " S_THREAD_LOCAL_REGULAR\n";
1467 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
1468 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
1469 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
1470 outs() << " S_THREAD_LOCAL_VARIABLES\n";
1471 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
1472 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
1473 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
1474 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
1476 outs() << format("0x%08" PRIx32, section_type) << "\n";
1477 outs() << "attributes";
1478 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
1479 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
1480 outs() << " PURE_INSTRUCTIONS";
1481 if (section_attributes & MachO::S_ATTR_NO_TOC)
1482 outs() << " NO_TOC";
1483 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
1484 outs() << " STRIP_STATIC_SYMS";
1485 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
1486 outs() << " NO_DEAD_STRIP";
1487 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
1488 outs() << " LIVE_SUPPORT";
1489 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
1490 outs() << " SELF_MODIFYING_CODE";
1491 if (section_attributes & MachO::S_ATTR_DEBUG)
1493 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
1494 outs() << " SOME_INSTRUCTIONS";
1495 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
1496 outs() << " EXT_RELOC";
1497 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
1498 outs() << " LOC_RELOC";
1499 if (section_attributes == 0)
1500 outs() << " (none)";
1503 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
1504 outs() << " reserved1 " << reserved1;
1505 if (section_type == MachO::S_SYMBOL_STUBS ||
1506 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
1507 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
1508 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
1509 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
1510 outs() << " (index into indirect symbol table)\n";
1513 outs() << " reserved2 " << reserved2;
1514 if (section_type == MachO::S_SYMBOL_STUBS)
1515 outs() << " (size of stubs)\n";
1520 static void PrintSymtabLoadCommand(MachO::symtab_command st, uint32_t cputype,
1521 uint32_t object_size) {
1522 outs() << " cmd LC_SYMTAB\n";
1523 outs() << " cmdsize " << st.cmdsize;
1524 if (st.cmdsize != sizeof(struct MachO::symtab_command))
1525 outs() << " Incorrect size\n";
1528 outs() << " symoff " << st.symoff;
1529 if (st.symoff > object_size)
1530 outs() << " (past end of file)\n";
1533 outs() << " nsyms " << st.nsyms;
1535 if (cputype & MachO::CPU_ARCH_ABI64) {
1536 big_size = st.nsyms;
1537 big_size *= sizeof(struct MachO::nlist_64);
1538 big_size += st.symoff;
1539 if (big_size > object_size)
1540 outs() << " (past end of file)\n";
1544 big_size = st.nsyms;
1545 big_size *= sizeof(struct MachO::nlist);
1546 big_size += st.symoff;
1547 if (big_size > object_size)
1548 outs() << " (past end of file)\n";
1552 outs() << " stroff " << st.stroff;
1553 if (st.stroff > object_size)
1554 outs() << " (past end of file)\n";
1557 outs() << " strsize " << st.strsize;
1558 big_size = st.stroff;
1559 big_size += st.strsize;
1560 if (big_size > object_size)
1561 outs() << " (past end of file)\n";
1566 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
1567 uint32_t nsyms, uint32_t object_size,
1569 outs() << " cmd LC_DYSYMTAB\n";
1570 outs() << " cmdsize " << dyst.cmdsize;
1571 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
1572 outs() << " Incorrect size\n";
1575 outs() << " ilocalsym " << dyst.ilocalsym;
1576 if (dyst.ilocalsym > nsyms)
1577 outs() << " (greater than the number of symbols)\n";
1580 outs() << " nlocalsym " << dyst.nlocalsym;
1582 big_size = dyst.ilocalsym;
1583 big_size += dyst.nlocalsym;
1584 if (big_size > nsyms)
1585 outs() << " (past the end of the symbol table)\n";
1588 outs() << " iextdefsym " << dyst.iextdefsym;
1589 if (dyst.iextdefsym > nsyms)
1590 outs() << " (greater than the number of symbols)\n";
1593 outs() << " nextdefsym " << dyst.nextdefsym;
1594 big_size = dyst.iextdefsym;
1595 big_size += dyst.nextdefsym;
1596 if (big_size > nsyms)
1597 outs() << " (past the end of the symbol table)\n";
1600 outs() << " iundefsym " << dyst.iundefsym;
1601 if (dyst.iundefsym > nsyms)
1602 outs() << " (greater than the number of symbols)\n";
1605 outs() << " nundefsym " << dyst.nundefsym;
1606 big_size = dyst.iundefsym;
1607 big_size += dyst.nundefsym;
1608 if (big_size > nsyms)
1609 outs() << " (past the end of the symbol table)\n";
1612 outs() << " tocoff " << dyst.tocoff;
1613 if (dyst.tocoff > object_size)
1614 outs() << " (past end of file)\n";
1617 outs() << " ntoc " << dyst.ntoc;
1618 big_size = dyst.ntoc;
1619 big_size *= sizeof(struct MachO::dylib_table_of_contents);
1620 big_size += dyst.tocoff;
1621 if (big_size > object_size)
1622 outs() << " (past end of file)\n";
1625 outs() << " modtaboff " << dyst.modtaboff;
1626 if (dyst.modtaboff > object_size)
1627 outs() << " (past end of file)\n";
1630 outs() << " nmodtab " << dyst.nmodtab;
1632 if (cputype & MachO::CPU_ARCH_ABI64) {
1633 modtabend = dyst.nmodtab;
1634 modtabend *= sizeof(struct MachO::dylib_module_64);
1635 modtabend += dyst.modtaboff;
1637 modtabend = dyst.nmodtab;
1638 modtabend *= sizeof(struct MachO::dylib_module);
1639 modtabend += dyst.modtaboff;
1641 if (modtabend > object_size)
1642 outs() << " (past end of file)\n";
1645 outs() << " extrefsymoff " << dyst.extrefsymoff;
1646 if (dyst.extrefsymoff > object_size)
1647 outs() << " (past end of file)\n";
1650 outs() << " nextrefsyms " << dyst.nextrefsyms;
1651 big_size = dyst.nextrefsyms;
1652 big_size *= sizeof(struct MachO::dylib_reference);
1653 big_size += dyst.extrefsymoff;
1654 if (big_size > object_size)
1655 outs() << " (past end of file)\n";
1658 outs() << " indirectsymoff " << dyst.indirectsymoff;
1659 if (dyst.indirectsymoff > object_size)
1660 outs() << " (past end of file)\n";
1663 outs() << " nindirectsyms " << dyst.nindirectsyms;
1664 big_size = dyst.nindirectsyms;
1665 big_size *= sizeof(uint32_t);
1666 big_size += dyst.indirectsymoff;
1667 if (big_size > object_size)
1668 outs() << " (past end of file)\n";
1671 outs() << " extreloff " << dyst.extreloff;
1672 if (dyst.extreloff > object_size)
1673 outs() << " (past end of file)\n";
1676 outs() << " nextrel " << dyst.nextrel;
1677 big_size = dyst.nextrel;
1678 big_size *= sizeof(struct MachO::relocation_info);
1679 big_size += dyst.extreloff;
1680 if (big_size > object_size)
1681 outs() << " (past end of file)\n";
1684 outs() << " locreloff " << dyst.locreloff;
1685 if (dyst.locreloff > object_size)
1686 outs() << " (past end of file)\n";
1689 outs() << " nlocrel " << dyst.nlocrel;
1690 big_size = dyst.nlocrel;
1691 big_size *= sizeof(struct MachO::relocation_info);
1692 big_size += dyst.locreloff;
1693 if (big_size > object_size)
1694 outs() << " (past end of file)\n";
1699 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t ncmds,
1700 uint32_t filetype, uint32_t cputype,
1702 StringRef Buf = Obj->getData();
1703 MachOObjectFile::LoadCommandInfo Command = Obj->getFirstLoadCommandInfo();
1704 for (unsigned i = 0;; ++i) {
1705 outs() << "Load command " << i << "\n";
1706 if (Command.C.cmd == MachO::LC_SEGMENT) {
1707 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
1708 const char *sg_segname = SLC.segname;
1709 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
1710 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
1711 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
1713 for (unsigned j = 0; j < SLC.nsects; j++) {
1714 MachO::section_64 S = Obj->getSection64(Command, j);
1715 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
1716 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
1717 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
1719 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
1720 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
1721 const char *sg_segname = SLC_64.segname;
1722 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
1723 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
1724 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
1725 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
1726 for (unsigned j = 0; j < SLC_64.nsects; j++) {
1727 MachO::section_64 S_64 = Obj->getSection64(Command, j);
1728 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
1729 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
1730 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
1731 sg_segname, filetype, Buf.size(), verbose);
1733 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
1734 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
1735 PrintSymtabLoadCommand(Symtab, cputype, Buf.size());
1736 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
1737 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
1738 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
1739 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(), cputype);
1741 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
1743 outs() << " cmdsize " << Command.C.cmdsize << "\n";
1744 // TODO: get and print the raw bytes of the load command.
1746 // TODO: print all the other kinds of load commands.
1750 Command = Obj->getNextLoadCommandInfo(Command);
1754 static void getAndPrintMachHeader(const MachOObjectFile *Obj, uint32_t &ncmds,
1755 uint32_t &filetype, uint32_t &cputype,
1757 if (Obj->is64Bit()) {
1758 MachO::mach_header_64 H_64;
1759 H_64 = Obj->getHeader64();
1760 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
1761 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
1763 filetype = H_64.filetype;
1764 cputype = H_64.cputype;
1766 MachO::mach_header H;
1767 H = Obj->getHeader();
1768 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
1769 H.sizeofcmds, H.flags, verbose);
1771 filetype = H.filetype;
1772 cputype = H.cputype;
1776 void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
1777 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
1779 uint32_t filetype = 0;
1780 uint32_t cputype = 0;
1781 getAndPrintMachHeader(file, ncmds, filetype, cputype, true);
1782 PrintLoadCommands(file, ncmds, filetype, cputype, true);
1785 //===----------------------------------------------------------------------===//
1786 // export trie dumping
1787 //===----------------------------------------------------------------------===//
1789 void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
1790 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
1791 uint64_t Flags = Entry.flags();
1792 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
1793 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
1794 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
1795 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
1796 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
1797 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
1798 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
1800 outs() << "[re-export] ";
1803 << format("0x%08llX ", Entry.address()); // FIXME:add in base address
1804 outs() << Entry.name();
1805 if (WeakDef || ThreadLocal || Resolver || Abs) {
1806 bool NeedsComma = false;
1809 outs() << "weak_def";
1815 outs() << "per-thread";
1821 outs() << "absolute";
1827 outs() << format("resolver=0x%08llX", Entry.other());
1833 StringRef DylibName = "unknown";
1834 int Ordinal = Entry.other() - 1;
1835 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
1836 if (Entry.otherName().empty())
1837 outs() << " (from " << DylibName << ")";
1839 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";