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/MCDisassembler.h"
21 #include "llvm/MC/MCInst.h"
22 #include "llvm/MC/MCInstPrinter.h"
23 #include "llvm/MC/MCInstrAnalysis.h"
24 #include "llvm/MC/MCInstrDesc.h"
25 #include "llvm/MC/MCInstrInfo.h"
26 #include "llvm/MC/MCRegisterInfo.h"
27 #include "llvm/MC/MCSubtargetInfo.h"
28 #include "llvm/Object/MachO.h"
29 #include "llvm/Support/Casting.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/Format.h"
33 #include "llvm/Support/GraphWriter.h"
34 #include "llvm/Support/MachO.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/TargetRegistry.h"
37 #include "llvm/Support/TargetSelect.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Support/system_error.h"
43 using namespace object;
46 UseDbg("g", cl::desc("Print line information from debug info if available"));
48 static cl::opt<std::string>
49 DSYMFile("dsym", cl::desc("Use .dSYM file for debug info"));
51 static const Target *GetTarget(const MachOObjectFile *MachOObj) {
52 // Figure out the target triple.
53 if (TripleName.empty()) {
54 llvm::Triple TT("unknown-unknown-unknown");
55 TT.setArch(Triple::ArchType(MachOObj->getArch()));
56 TripleName = TT.str();
59 // Get the target specific parser.
61 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
65 errs() << "llvm-objdump: error: unable to get target for '" << TripleName
66 << "', see --version and --triple.\n";
71 bool operator()(const SymbolRef &A, const SymbolRef &B) {
72 SymbolRef::Type AType, BType;
76 uint64_t AAddr, BAddr;
77 if (AType != SymbolRef::ST_Function)
81 if (BType != SymbolRef::ST_Function)
89 // Types for the storted data in code table that is built before disassembly
90 // and the predicate function to sort them.
91 typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
92 typedef std::vector<DiceTableEntry> DiceTable;
93 typedef DiceTable::iterator dice_table_iterator;
96 compareDiceTableEntries(const DiceTableEntry i,
97 const DiceTableEntry j) {
98 return i.first == j.first;
101 static void DumpDataInCode(const char *bytes, uint64_t Size,
102 unsigned short Kind) {
106 case MachO::DICE_KIND_DATA:
109 Value = bytes[3] << 24 |
113 outs() << "\t.long " << Value;
116 Value = bytes[1] << 8 |
118 outs() << "\t.short " << Value;
122 outs() << "\t.byte " << Value;
125 outs() << "\t@ KIND_DATA\n";
127 case MachO::DICE_KIND_JUMP_TABLE8:
129 outs() << "\t.byte " << Value << "\t@ KIND_JUMP_TABLE8";
131 case MachO::DICE_KIND_JUMP_TABLE16:
132 Value = bytes[1] << 8 |
134 outs() << "\t.short " << Value << "\t@ KIND_JUMP_TABLE16";
136 case MachO::DICE_KIND_JUMP_TABLE32:
137 Value = bytes[3] << 24 |
141 outs() << "\t.long " << Value << "\t@ KIND_JUMP_TABLE32";
144 outs() << "\t@ data in code kind = " << Kind << "\n";
150 getSectionsAndSymbols(const MachO::mach_header Header,
151 MachOObjectFile *MachOObj,
152 std::vector<SectionRef> &Sections,
153 std::vector<SymbolRef> &Symbols,
154 SmallVectorImpl<uint64_t> &FoundFns,
155 uint64_t &BaseSegmentAddress) {
156 for (symbol_iterator SI = MachOObj->symbol_begin(),
157 SE = MachOObj->symbol_end();
159 Symbols.push_back(*SI);
161 for (const SectionRef &Section : MachOObj->sections()) {
163 Section.getName(SectName);
164 Sections.push_back(Section);
167 MachOObjectFile::LoadCommandInfo Command =
168 MachOObj->getFirstLoadCommandInfo();
169 bool BaseSegmentAddressSet = false;
170 for (unsigned i = 0; ; ++i) {
171 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
172 // We found a function starts segment, parse the addresses for later
174 MachO::linkedit_data_command LLC =
175 MachOObj->getLinkeditDataLoadCommand(Command);
177 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
179 else if (Command.C.cmd == MachO::LC_SEGMENT) {
180 MachO::segment_command SLC =
181 MachOObj->getSegmentLoadCommand(Command);
182 StringRef SegName = SLC.segname;
183 if(!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
184 BaseSegmentAddressSet = true;
185 BaseSegmentAddress = SLC.vmaddr;
189 if (i == Header.ncmds - 1)
192 Command = MachOObj->getNextLoadCommandInfo(Command);
196 static void DisassembleInputMachO2(StringRef Filename,
197 MachOObjectFile *MachOOF);
199 void llvm::DisassembleInputMachO(StringRef Filename) {
200 std::unique_ptr<MemoryBuffer> Buff;
202 if (error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, Buff)) {
203 errs() << "llvm-objdump: " << Filename << ": " << ec.message() << "\n";
207 std::unique_ptr<MachOObjectFile> MachOOF(static_cast<MachOObjectFile *>(
208 ObjectFile::createMachOObjectFile(Buff.release()).get()));
210 DisassembleInputMachO2(Filename, MachOOF.get());
213 static void DisassembleInputMachO2(StringRef Filename,
214 MachOObjectFile *MachOOF) {
215 const Target *TheTarget = GetTarget(MachOOF);
217 // GetTarget prints out stuff.
220 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
221 std::unique_ptr<MCInstrAnalysis> InstrAnalysis(
222 TheTarget->createMCInstrAnalysis(InstrInfo.get()));
224 // Set up disassembler.
225 std::unique_ptr<const MCRegisterInfo> MRI(
226 TheTarget->createMCRegInfo(TripleName));
227 std::unique_ptr<const MCAsmInfo> AsmInfo(
228 TheTarget->createMCAsmInfo(*MRI, TripleName));
229 std::unique_ptr<const MCSubtargetInfo> STI(
230 TheTarget->createMCSubtargetInfo(TripleName, "", ""));
231 std::unique_ptr<const MCDisassembler> DisAsm(
232 TheTarget->createMCDisassembler(*STI));
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 std::unique_ptr<MemoryBuffer> Buf;
293 if (error_code ec = MemoryBuffer::getFileOrSTDIN(DSYMFile, Buf)) {
294 errs() << "llvm-objdump: " << Filename << ": " << ec.message() << '\n';
297 DbgObj = ObjectFile::createMachOObjectFile(Buf.release()).get();
300 // Setup the DIContext
301 diContext.reset(DIContext::getDWARFContext(DbgObj));
304 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
306 bool SectIsText = false;
307 Sections[SectIdx].isText(SectIsText);
308 if (SectIsText == false)
312 if (Sections[SectIdx].getName(SectName) ||
313 SectName != "__text")
314 continue; // Skip non-text sections
316 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
318 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
319 if (SegmentName != "__TEXT")
323 Sections[SectIdx].getContents(Bytes);
324 StringRefMemoryObject memoryObject(Bytes);
325 bool symbolTableWorked = false;
327 // Parse relocations.
328 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
329 for (const RelocationRef &Reloc : Sections[SectIdx].relocations()) {
330 uint64_t RelocOffset, SectionAddress;
331 Reloc.getOffset(RelocOffset);
332 Sections[SectIdx].getAddress(SectionAddress);
333 RelocOffset -= SectionAddress;
335 symbol_iterator RelocSym = Reloc.getSymbol();
337 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
339 array_pod_sort(Relocs.begin(), Relocs.end());
341 // Disassemble symbol by symbol.
342 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
344 Symbols[SymIdx].getName(SymName);
347 Symbols[SymIdx].getType(ST);
348 if (ST != SymbolRef::ST_Function)
351 // Make sure the symbol is defined in this section.
352 bool containsSym = false;
353 Sections[SectIdx].containsSymbol(Symbols[SymIdx], containsSym);
357 // Start at the address of the symbol relative to the section's address.
358 uint64_t SectionAddress = 0;
360 Sections[SectIdx].getAddress(SectionAddress);
361 Symbols[SymIdx].getAddress(Start);
362 Start -= SectionAddress;
364 // Stop disassembling either at the beginning of the next symbol or at
365 // the end of the section.
366 bool containsNextSym = false;
367 uint64_t NextSym = 0;
368 uint64_t NextSymIdx = SymIdx+1;
369 while (Symbols.size() > NextSymIdx) {
370 SymbolRef::Type NextSymType;
371 Symbols[NextSymIdx].getType(NextSymType);
372 if (NextSymType == SymbolRef::ST_Function) {
373 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx],
375 Symbols[NextSymIdx].getAddress(NextSym);
376 NextSym -= SectionAddress;
383 Sections[SectIdx].getSize(SectSize);
384 uint64_t End = containsNextSym ? NextSym : SectSize;
387 symbolTableWorked = true;
389 outs() << SymName << ":\n";
391 for (uint64_t Index = Start; Index < End; Index += Size) {
394 uint64_t SectAddress = 0;
395 Sections[SectIdx].getAddress(SectAddress);
396 outs() << format("%8" PRIx64 ":\t", SectAddress + Index);
398 // Check the data in code table here to see if this is data not an
399 // instruction to be disassembled.
401 Dice.push_back(std::make_pair(SectAddress + Index, DiceRef()));
402 dice_table_iterator DTI = std::search(Dices.begin(), Dices.end(),
403 Dice.begin(), Dice.end(),
404 compareDiceTableEntries);
405 if (DTI != Dices.end()){
407 DTI->second.getLength(Length);
408 DumpBytes(StringRef(Bytes.data() + Index, Length));
410 DTI->second.getKind(Kind);
411 DumpDataInCode(Bytes.data() + Index, Length, Kind);
415 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
416 DebugOut, nulls())) {
417 DumpBytes(StringRef(Bytes.data() + Index, Size));
418 IP->printInst(&Inst, outs(), "");
423 diContext->getLineInfoForAddress(SectAddress + Index);
424 // Print valid line info if it changed.
425 if (dli != lastLine && dli.getLine() != 0)
426 outs() << "\t## " << dli.getFileName() << ':'
427 << dli.getLine() << ':' << dli.getColumn();
432 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
434 Size = 1; // skip illegible bytes
438 if (!symbolTableWorked) {
439 // Reading the symbol table didn't work, disassemble the whole section.
440 uint64_t SectAddress;
441 Sections[SectIdx].getAddress(SectAddress);
443 Sections[SectIdx].getSize(SectSize);
445 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
448 if (DisAsm->getInstruction(Inst, InstSize, memoryObject, Index,
449 DebugOut, nulls())) {
450 outs() << format("%8" PRIx64 ":\t", SectAddress + Index);
451 DumpBytes(StringRef(Bytes.data() + Index, InstSize));
452 IP->printInst(&Inst, outs(), "");
455 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
457 InstSize = 1; // skip illegible bytes