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 const Target *GetTarget(const MachOObjectFile *MachOObj) {
54 // Figure out the target triple.
55 if (TripleName.empty()) {
56 llvm::Triple TT("unknown-unknown-unknown");
57 TT.setArch(Triple::ArchType(MachOObj->getArch()));
58 TripleName = TT.str();
61 // Get the target specific parser.
63 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
67 errs() << "llvm-objdump: error: unable to get target for '" << TripleName
68 << "', see --version and --triple.\n";
73 bool operator()(const SymbolRef &A, const SymbolRef &B) {
74 SymbolRef::Type AType, BType;
78 uint64_t AAddr, BAddr;
79 if (AType != SymbolRef::ST_Function)
83 if (BType != SymbolRef::ST_Function)
91 // Types for the storted data in code table that is built before disassembly
92 // and the predicate function to sort them.
93 typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
94 typedef std::vector<DiceTableEntry> DiceTable;
95 typedef DiceTable::iterator dice_table_iterator;
98 compareDiceTableEntries(const DiceTableEntry i,
99 const DiceTableEntry j) {
100 return i.first == j.first;
103 static void DumpDataInCode(const char *bytes, uint64_t Size,
104 unsigned short Kind) {
108 case MachO::DICE_KIND_DATA:
111 Value = bytes[3] << 24 |
115 outs() << "\t.long " << Value;
118 Value = bytes[1] << 8 |
120 outs() << "\t.short " << Value;
124 outs() << "\t.byte " << Value;
127 outs() << "\t@ KIND_DATA\n";
129 case MachO::DICE_KIND_JUMP_TABLE8:
131 outs() << "\t.byte " << Value << "\t@ KIND_JUMP_TABLE8";
133 case MachO::DICE_KIND_JUMP_TABLE16:
134 Value = bytes[1] << 8 |
136 outs() << "\t.short " << Value << "\t@ KIND_JUMP_TABLE16";
138 case MachO::DICE_KIND_JUMP_TABLE32:
139 Value = bytes[3] << 24 |
143 outs() << "\t.long " << Value << "\t@ KIND_JUMP_TABLE32";
146 outs() << "\t@ data in code kind = " << Kind << "\n";
151 static void getSectionsAndSymbols(const MachO::mach_header Header,
152 MachOObjectFile *MachOObj,
153 std::vector<SectionRef> &Sections,
154 std::vector<SymbolRef> &Symbols,
155 SmallVectorImpl<uint64_t> &FoundFns,
156 uint64_t &BaseSegmentAddress) {
157 for (const SymbolRef &Symbol : MachOObj->symbols())
158 Symbols.push_back(Symbol);
160 for (const SectionRef &Section : MachOObj->sections()) {
162 Section.getName(SectName);
163 Sections.push_back(Section);
166 MachOObjectFile::LoadCommandInfo Command =
167 MachOObj->getFirstLoadCommandInfo();
168 bool BaseSegmentAddressSet = false;
169 for (unsigned i = 0; ; ++i) {
170 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
171 // We found a function starts segment, parse the addresses for later
173 MachO::linkedit_data_command LLC =
174 MachOObj->getLinkeditDataLoadCommand(Command);
176 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
178 else if (Command.C.cmd == MachO::LC_SEGMENT) {
179 MachO::segment_command SLC =
180 MachOObj->getSegmentLoadCommand(Command);
181 StringRef SegName = SLC.segname;
182 if(!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
183 BaseSegmentAddressSet = true;
184 BaseSegmentAddress = SLC.vmaddr;
188 if (i == Header.ncmds - 1)
191 Command = MachOObj->getNextLoadCommandInfo(Command);
195 static void DisassembleInputMachO2(StringRef Filename,
196 MachOObjectFile *MachOOF);
198 void llvm::DisassembleInputMachO(StringRef Filename) {
199 ErrorOr<std::unique_ptr<MemoryBuffer>> Buff =
200 MemoryBuffer::getFileOrSTDIN(Filename);
201 if (std::error_code EC = Buff.getError()) {
202 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << "\n";
206 std::unique_ptr<MachOObjectFile> MachOOF =
207 std::move(ObjectFile::createMachOObjectFile(Buff.get()).get());
209 DisassembleInputMachO2(Filename, MachOOF.get());
212 static void DisassembleInputMachO2(StringRef Filename,
213 MachOObjectFile *MachOOF) {
214 const Target *TheTarget = GetTarget(MachOOF);
216 // GetTarget prints out stuff.
219 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
220 std::unique_ptr<MCInstrAnalysis> InstrAnalysis(
221 TheTarget->createMCInstrAnalysis(InstrInfo.get()));
223 // Set up disassembler.
224 std::unique_ptr<const MCRegisterInfo> MRI(
225 TheTarget->createMCRegInfo(TripleName));
226 std::unique_ptr<const MCAsmInfo> AsmInfo(
227 TheTarget->createMCAsmInfo(*MRI, TripleName));
228 std::unique_ptr<const MCSubtargetInfo> STI(
229 TheTarget->createMCSubtargetInfo(TripleName, "", ""));
230 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
231 std::unique_ptr<const MCDisassembler> DisAsm(
232 TheTarget->createMCDisassembler(*STI, Ctx));
233 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
234 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
235 AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI, *STI));
237 if (!InstrAnalysis || !AsmInfo || !STI || !DisAsm || !IP) {
238 errs() << "error: couldn't initialize disassembler for target "
239 << TripleName << '\n';
243 outs() << '\n' << Filename << ":\n\n";
245 MachO::mach_header Header = MachOOF->getHeader();
247 // FIXME: FoundFns isn't used anymore. Using symbols/LC_FUNCTION_STARTS to
248 // determine function locations will eventually go in MCObjectDisassembler.
249 // FIXME: Using the -cfg command line option, this code used to be able to
250 // annotate relocations with the referenced symbol's name, and if this was
251 // inside a __[cf]string section, the data it points to. This is now replaced
252 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
253 std::vector<SectionRef> Sections;
254 std::vector<SymbolRef> Symbols;
255 SmallVector<uint64_t, 8> FoundFns;
256 uint64_t BaseSegmentAddress;
258 getSectionsAndSymbols(Header, MachOOF, Sections, Symbols, FoundFns,
261 // Sort the symbols by address, just in case they didn't come in that way.
262 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
264 // Build a data in code table that is sorted on by the address of each entry.
265 uint64_t BaseAddress = 0;
266 if (Header.filetype == MachO::MH_OBJECT)
267 Sections[0].getAddress(BaseAddress);
269 BaseAddress = BaseSegmentAddress;
271 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
274 DI->getOffset(Offset);
275 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
277 array_pod_sort(Dices.begin(), Dices.end());
280 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
282 raw_ostream &DebugOut = nulls();
285 std::unique_ptr<DIContext> diContext;
286 ObjectFile *DbgObj = MachOOF;
287 // Try to find debug info and set up the DIContext for it.
289 // A separate DSym file path was specified, parse it as a macho file,
290 // get the sections and supply it to the section name parsing machinery.
291 if (!DSYMFile.empty()) {
292 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
293 MemoryBuffer::getFileOrSTDIN(DSYMFile);
294 if (std::error_code EC = Buf.getError()) {
295 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
298 DbgObj = ObjectFile::createMachOObjectFile(Buf.get()).get().release();
301 // Setup the DIContext
302 diContext.reset(DIContext::getDWARFContext(*DbgObj));
305 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
307 bool SectIsText = false;
308 Sections[SectIdx].isText(SectIsText);
309 if (SectIsText == false)
313 if (Sections[SectIdx].getName(SectName) ||
314 SectName != "__text")
315 continue; // Skip non-text sections
317 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
319 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
320 if (SegmentName != "__TEXT")
324 Sections[SectIdx].getContents(Bytes);
325 StringRefMemoryObject memoryObject(Bytes);
326 bool symbolTableWorked = false;
328 // Parse relocations.
329 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
330 for (const RelocationRef &Reloc : Sections[SectIdx].relocations()) {
331 uint64_t RelocOffset, SectionAddress;
332 Reloc.getOffset(RelocOffset);
333 Sections[SectIdx].getAddress(SectionAddress);
334 RelocOffset -= SectionAddress;
336 symbol_iterator RelocSym = Reloc.getSymbol();
338 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
340 array_pod_sort(Relocs.begin(), Relocs.end());
342 // Disassemble symbol by symbol.
343 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
345 Symbols[SymIdx].getName(SymName);
348 Symbols[SymIdx].getType(ST);
349 if (ST != SymbolRef::ST_Function)
352 // Make sure the symbol is defined in this section.
353 bool containsSym = false;
354 Sections[SectIdx].containsSymbol(Symbols[SymIdx], containsSym);
358 // Start at the address of the symbol relative to the section's address.
359 uint64_t SectionAddress = 0;
361 Sections[SectIdx].getAddress(SectionAddress);
362 Symbols[SymIdx].getAddress(Start);
363 Start -= SectionAddress;
365 // Stop disassembling either at the beginning of the next symbol or at
366 // the end of the section.
367 bool containsNextSym = false;
368 uint64_t NextSym = 0;
369 uint64_t NextSymIdx = SymIdx+1;
370 while (Symbols.size() > NextSymIdx) {
371 SymbolRef::Type NextSymType;
372 Symbols[NextSymIdx].getType(NextSymType);
373 if (NextSymType == SymbolRef::ST_Function) {
374 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx],
376 Symbols[NextSymIdx].getAddress(NextSym);
377 NextSym -= SectionAddress;
384 Sections[SectIdx].getSize(SectSize);
385 uint64_t End = containsNextSym ? NextSym : SectSize;
388 symbolTableWorked = true;
390 outs() << SymName << ":\n";
392 for (uint64_t Index = Start; Index < End; Index += Size) {
395 uint64_t SectAddress = 0;
396 Sections[SectIdx].getAddress(SectAddress);
397 outs() << format("%8" PRIx64 ":\t", SectAddress + Index);
399 // Check the data in code table here to see if this is data not an
400 // instruction to be disassembled.
402 Dice.push_back(std::make_pair(SectAddress + Index, DiceRef()));
403 dice_table_iterator DTI = std::search(Dices.begin(), Dices.end(),
404 Dice.begin(), Dice.end(),
405 compareDiceTableEntries);
406 if (DTI != Dices.end()){
408 DTI->second.getLength(Length);
409 DumpBytes(StringRef(Bytes.data() + Index, Length));
411 DTI->second.getKind(Kind);
412 DumpDataInCode(Bytes.data() + Index, Length, Kind);
416 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
417 DebugOut, nulls())) {
418 DumpBytes(StringRef(Bytes.data() + Index, Size));
419 IP->printInst(&Inst, outs(), "");
424 diContext->getLineInfoForAddress(SectAddress + Index);
425 // Print valid line info if it changed.
426 if (dli != lastLine && dli.Line != 0)
427 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
433 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
435 Size = 1; // skip illegible bytes
439 if (!symbolTableWorked) {
440 // Reading the symbol table didn't work, disassemble the whole section.
441 uint64_t SectAddress;
442 Sections[SectIdx].getAddress(SectAddress);
444 Sections[SectIdx].getSize(SectSize);
446 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
449 if (DisAsm->getInstruction(Inst, InstSize, memoryObject, Index,
450 DebugOut, nulls())) {
451 outs() << format("%8" PRIx64 ":\t", SectAddress + Index);
452 DumpBytes(StringRef(Bytes.data() + Index, InstSize));
453 IP->printInst(&Inst, outs(), "");
456 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
458 InstSize = 1; // skip illegible bytes
466 struct CompactUnwindEntry {
467 uint32_t OffsetInSection;
469 uint64_t FunctionAddr;
471 uint32_t CompactEncoding;
472 uint64_t PersonalityAddr;
475 RelocationRef FunctionReloc;
476 RelocationRef PersonalityReloc;
477 RelocationRef LSDAReloc;
479 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
480 : OffsetInSection(Offset) {
482 read<uint64_t>(Contents.data() + Offset);
484 read<uint32_t>(Contents.data() + Offset);
489 static uint64_t readNext(const char *&Buf) {
490 using llvm::support::little;
491 using llvm::support::unaligned;
493 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
498 template<typename UIntPtr>
499 void read(const char *Buf) {
500 FunctionAddr = readNext<UIntPtr>(Buf);
501 Length = readNext<uint32_t>(Buf);
502 CompactEncoding = readNext<uint32_t>(Buf);
503 PersonalityAddr = readNext<UIntPtr>(Buf);
504 LSDAAddr = readNext<UIntPtr>(Buf);
509 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
510 /// and data being relocated, determine the best base Name and Addend to use for
511 /// display purposes.
513 /// 1. An Extern relocation will directly reference a symbol (and the data is
514 /// then already an addend), so use that.
515 /// 2. Otherwise the data is an offset in the object file's layout; try to find
516 // a symbol before it in the same section, and use the offset from there.
517 /// 3. Finally, if all that fails, fall back to an offset from the start of the
518 /// referenced section.
519 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
520 std::map<uint64_t, SymbolRef> &Symbols,
521 const RelocationRef &Reloc,
523 StringRef &Name, uint64_t &Addend) {
524 if (Reloc.getSymbol() != Obj->symbol_end()) {
525 Reloc.getSymbol()->getName(Name);
530 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
531 SectionRef RelocSection = Obj->getRelocationSection(RE);
533 uint64_t SectionAddr;
534 RelocSection.getAddress(SectionAddr);
536 auto Sym = Symbols.upper_bound(Addr);
537 if (Sym == Symbols.begin()) {
538 // The first symbol in the object is after this reference, the best we can
539 // do is section-relative notation.
540 RelocSection.getName(Name);
541 Addend = Addr - SectionAddr;
545 // Go back one so that SymbolAddress <= Addr.
548 section_iterator SymSection = Obj->section_end();
549 Sym->second.getSection(SymSection);
550 if (RelocSection == *SymSection) {
551 // There's a valid symbol in the same section before this reference.
552 Sym->second.getName(Name);
553 Addend = Addr - Sym->first;
557 // There is a symbol before this reference, but it's in a different
558 // section. Probably not helpful to mention it, so use the section name.
559 RelocSection.getName(Name);
560 Addend = Addr - SectionAddr;
563 static void printUnwindRelocDest(const MachOObjectFile *Obj,
564 std::map<uint64_t, SymbolRef> &Symbols,
565 const RelocationRef &Reloc,
570 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
574 outs() << " + " << format("0x%x", Addend);
578 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
579 std::map<uint64_t, SymbolRef> &Symbols,
580 const SectionRef &CompactUnwind) {
582 assert(Obj->isLittleEndian() &&
583 "There should not be a big-endian .o with __compact_unwind");
585 bool Is64 = Obj->is64Bit();
586 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
587 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
590 CompactUnwind.getContents(Contents);
592 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
594 // First populate the initial raw offsets, encodings and so on from the entry.
595 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
596 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
597 CompactUnwinds.push_back(Entry);
600 // Next we need to look at the relocations to find out what objects are
601 // actually being referred to.
602 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
603 uint64_t RelocAddress;
604 Reloc.getOffset(RelocAddress);
606 uint32_t EntryIdx = RelocAddress / EntrySize;
607 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
608 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
610 if (OffsetInEntry == 0)
611 Entry.FunctionReloc = Reloc;
612 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
613 Entry.PersonalityReloc = Reloc;
614 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
615 Entry.LSDAReloc = Reloc;
617 llvm_unreachable("Unexpected relocation in __compact_unwind section");
620 // Finally, we're ready to print the data we've gathered.
621 outs() << "Contents of __compact_unwind section:\n";
622 for (auto &Entry : CompactUnwinds) {
623 outs() << " Entry at offset " << format("0x%x", Entry.OffsetInSection)
626 // 1. Start of the region this entry applies to.
628 << format("0x%x", Entry.FunctionAddr) << ' ';
629 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc,
633 // 2. Length of the region this entry applies to.
634 outs() << " length: "
635 << format("0x%x", Entry.Length) << '\n';
636 // 3. The 32-bit compact encoding.
637 outs() << " compact encoding: "
638 << format("0x%08x", Entry.CompactEncoding) << '\n';
640 // 4. The personality function, if present.
641 if (Entry.PersonalityReloc.getObjectFile()) {
642 outs() << " personality function: "
643 << format("0x%x", Entry.PersonalityAddr) << ' ';
644 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
645 Entry.PersonalityAddr);
649 // 5. This entry's language-specific data area.
650 if (Entry.LSDAReloc.getObjectFile()) {
652 << format("0x%x", Entry.LSDAAddr) << ' ';
653 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
659 void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
660 std::map<uint64_t, SymbolRef> Symbols;
661 for (const SymbolRef &SymRef : Obj->symbols()) {
662 // Discard any undefined or absolute symbols. They're not going to take part
663 // in the convenience lookup for unwind info and just take up resources.
664 section_iterator Section = Obj->section_end();
665 SymRef.getSection(Section);
666 if (Section == Obj->section_end())
670 SymRef.getAddress(Addr);
671 Symbols.insert(std::make_pair(Addr, SymRef));
674 for (const SectionRef &Section : Obj->sections()) {
676 Section.getName(SectName);
677 if (SectName == "__compact_unwind")
678 printMachOCompactUnwindSection(Obj, Symbols, Section);
679 else if (SectName == "__unwind_info")
680 outs() << "llvm-objdump: warning: unhandled __unwind_info section\n";
681 else if (SectName == "__eh_frame")
682 outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";