blob: 7e3bb20d3e145ae17f9f7619a8f432bd46add8cd [file] [log] [blame]
Benjamin Kramer0b8b7712011-09-19 17:56:04 +00001//===-- MachODump.cpp - Object file dumping utility for llvm --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the MachO-specific dumper for llvm-objdump.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm-objdump.h"
15#include "MCFunction.h"
16#include "llvm/Support/MachO.h"
17#include "llvm/Object/MachOObject.h"
18#include "llvm/ADT/OwningPtr.h"
19#include "llvm/ADT/Triple.h"
20#include "llvm/ADT/STLExtras.h"
Benjamin Kramer8c930972011-09-21 01:13:19 +000021#include "llvm/DebugInfo/DIContext.h"
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000022#include "llvm/MC/MCAsmInfo.h"
23#include "llvm/MC/MCDisassembler.h"
24#include "llvm/MC/MCInst.h"
25#include "llvm/MC/MCInstPrinter.h"
26#include "llvm/MC/MCInstrAnalysis.h"
27#include "llvm/MC/MCInstrDesc.h"
28#include "llvm/MC/MCInstrInfo.h"
29#include "llvm/MC/MCSubtargetInfo.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/MemoryBuffer.h"
35#include "llvm/Support/TargetRegistry.h"
36#include "llvm/Support/TargetSelect.h"
37#include "llvm/Support/raw_ostream.h"
38#include "llvm/Support/system_error.h"
39#include <algorithm>
40#include <cstring>
41using namespace llvm;
42using namespace object;
43
44static cl::opt<bool>
45 CFG("cfg", cl::desc("Create a CFG for every symbol in the object file and"
46 "write it to a graphviz file (MachO-only)"));
47
Benjamin Kramer8c930972011-09-21 01:13:19 +000048static cl::opt<bool>
49 UseDbg("g", cl::desc("Print line information from debug info if available"));
50
51static cl::opt<std::string>
52 DSYMFile("dsym", cl::desc("Use .dSYM file for debug info"));
53
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000054static const Target *GetTarget(const MachOObject *MachOObj) {
55 // Figure out the target triple.
56 llvm::Triple TT("unknown-unknown-unknown");
57 switch (MachOObj->getHeader().CPUType) {
58 case llvm::MachO::CPUTypeI386:
59 TT.setArch(Triple::ArchType(Triple::x86));
60 break;
61 case llvm::MachO::CPUTypeX86_64:
62 TT.setArch(Triple::ArchType(Triple::x86_64));
63 break;
64 case llvm::MachO::CPUTypeARM:
65 TT.setArch(Triple::ArchType(Triple::arm));
66 break;
67 case llvm::MachO::CPUTypePowerPC:
68 TT.setArch(Triple::ArchType(Triple::ppc));
69 break;
70 case llvm::MachO::CPUTypePowerPC64:
71 TT.setArch(Triple::ArchType(Triple::ppc64));
72 break;
73 }
74
75 TripleName = TT.str();
76
77 // Get the target specific parser.
78 std::string Error;
79 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
80 if (TheTarget)
81 return TheTarget;
82
83 errs() << "llvm-objdump: error: unable to get target for '" << TripleName
84 << "', see --version and --triple.\n";
85 return 0;
86}
87
88struct Section {
89 char Name[16];
90 uint64_t Address;
91 uint64_t Size;
92 uint32_t Offset;
93 uint32_t NumRelocs;
94 uint64_t RelocTableOffset;
95};
96
97struct Symbol {
98 uint64_t Value;
99 uint32_t StringIndex;
100 uint8_t SectionIndex;
101 bool operator<(const Symbol &RHS) const { return Value < RHS.Value; }
102};
103
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000104template <typename T>
105static Section copySection(const T &Sect) {
106 Section S;
107 memcpy(S.Name, Sect->Name, 16);
108 S.Address = Sect->Address;
109 S.Size = Sect->Size;
110 S.Offset = Sect->Offset;
111 S.NumRelocs = Sect->NumRelocationTableEntries;
112 S.RelocTableOffset = Sect->RelocationTableOffset;
113 return S;
114}
115
116template <typename T>
117static Symbol copySymbol(const T &STE) {
118 Symbol S;
119 S.StringIndex = STE->StringIndex;
120 S.SectionIndex = STE->SectionIndex;
121 S.Value = STE->Value;
122 return S;
123}
124
125// Print addtitional information about an address, if available.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000126static void DumpAddress(uint64_t Address, ArrayRef<Section> Sections,
127 MachOObject *MachOObj, raw_ostream &OS) {
128 for (unsigned i = 0; i != Sections.size(); ++i) {
129 uint64_t addr = Address-Sections[i].Address;
130 if (Sections[i].Address <= Address &&
131 Sections[i].Address + Sections[i].Size > Address) {
132 StringRef bytes = MachOObj->getData(Sections[i].Offset,
133 Sections[i].Size);
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000134 // Print constant strings.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000135 if (!strcmp(Sections[i].Name, "__cstring"))
136 OS << '"' << bytes.substr(addr, bytes.find('\0', addr)) << '"';
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000137 // Print constant CFStrings.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000138 if (!strcmp(Sections[i].Name, "__cfstring"))
139 OS << "@\"" << bytes.substr(addr, bytes.find('\0', addr)) << '"';
140 }
141 }
142}
143
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000144typedef std::map<uint64_t, MCFunction*> FunctionMapTy;
145typedef SmallVector<MCFunction, 16> FunctionListTy;
146static void createMCFunctionAndSaveCalls(StringRef Name,
147 const MCDisassembler *DisAsm,
148 MemoryObject &Object, uint64_t Start,
149 uint64_t End,
150 MCInstrAnalysis *InstrAnalysis,
151 uint64_t Address,
152 raw_ostream &DebugOut,
153 FunctionMapTy &FunctionMap,
154 FunctionListTy &Functions) {
155 SmallVector<uint64_t, 16> Calls;
156 MCFunction f =
157 MCFunction::createFunctionFromMC(Name, DisAsm, Object, Start, End,
158 InstrAnalysis, DebugOut, Calls);
159 Functions.push_back(f);
160 FunctionMap[Address] = &Functions.back();
161
162 // Add the gathered callees to the map.
163 for (unsigned i = 0, e = Calls.size(); i != e; ++i)
164 FunctionMap.insert(std::make_pair(Calls[i], (MCFunction*)0));
165}
166
167// Write a graphviz file for the CFG inside an MCFunction.
168static void emitDOTFile(const char *FileName, const MCFunction &f,
169 MCInstPrinter *IP) {
170 // Start a new dot file.
171 std::string Error;
172 raw_fd_ostream Out(FileName, Error);
173 if (!Error.empty()) {
174 errs() << "llvm-objdump: warning: " << Error << '\n';
175 return;
176 }
177
178 Out << "digraph " << f.getName() << " {\n";
179 Out << "graph [ rankdir = \"LR\" ];\n";
180 for (MCFunction::iterator i = f.begin(), e = f.end(); i != e; ++i) {
181 bool hasPreds = false;
182 // Only print blocks that have predecessors.
183 // FIXME: Slow.
184 for (MCFunction::iterator pi = f.begin(), pe = f.end(); pi != pe;
185 ++pi)
186 if (pi->second.contains(i->first)) {
187 hasPreds = true;
188 break;
189 }
190
191 if (!hasPreds && i != f.begin())
192 continue;
193
194 Out << '"' << i->first << "\" [ label=\"<a>";
195 // Print instructions.
196 for (unsigned ii = 0, ie = i->second.getInsts().size(); ii != ie;
197 ++ii) {
198 // Escape special chars and print the instruction in mnemonic form.
199 std::string Str;
200 raw_string_ostream OS(Str);
201 IP->printInst(&i->second.getInsts()[ii].Inst, OS, "");
202 Out << DOT::EscapeString(OS.str()) << '|';
203 }
204 Out << "<o>\" shape=\"record\" ];\n";
205
206 // Add edges.
207 for (MCBasicBlock::succ_iterator si = i->second.succ_begin(),
208 se = i->second.succ_end(); si != se; ++si)
209 Out << i->first << ":o -> " << *si <<":a\n";
210 }
211 Out << "}\n";
212}
213
Benjamin Kramer8c930972011-09-21 01:13:19 +0000214static void getSectionsAndSymbols(const macho::Header &Header,
215 MachOObject *MachOObj,
216 InMemoryStruct<macho::SymtabLoadCommand> *SymtabLC,
217 std::vector<Section> &Sections,
218 std::vector<Symbol> &Symbols,
219 SmallVectorImpl<uint64_t> &FoundFns) {
220 // Make a list of all symbols in the object file.
221 for (unsigned i = 0; i != Header.NumLoadCommands; ++i) {
222 const MachOObject::LoadCommandInfo &LCI = MachOObj->getLoadCommandInfo(i);
223 if (LCI.Command.Type == macho::LCT_Segment) {
224 InMemoryStruct<macho::SegmentLoadCommand> SegmentLC;
225 MachOObj->ReadSegmentLoadCommand(LCI, SegmentLC);
226
227 // Store the sections in this segment.
228 for (unsigned SectNum = 0; SectNum != SegmentLC->NumSections; ++SectNum) {
229 InMemoryStruct<macho::Section> Sect;
230 MachOObj->ReadSection(LCI, SectNum, Sect);
231 Sections.push_back(copySection(Sect));
232
233 // Store the symbols in this section.
234 if (SymtabLC) {
235 for (unsigned i = 0; i != (*SymtabLC)->NumSymbolTableEntries; ++i) {
236 InMemoryStruct<macho::SymbolTableEntry> STE;
237 MachOObj->ReadSymbolTableEntry((*SymtabLC)->SymbolTableOffset, i,
238 STE);
239 Symbols.push_back(copySymbol(STE));
240 }
241 }
242 }
243 } else if (LCI.Command.Type == macho::LCT_Segment64) {
244 InMemoryStruct<macho::Segment64LoadCommand> Segment64LC;
245 MachOObj->ReadSegment64LoadCommand(LCI, Segment64LC);
246
247 // Store the sections in this segment.
248 for (unsigned SectNum = 0; SectNum != Segment64LC->NumSections;
249 ++SectNum) {
250 InMemoryStruct<macho::Section64> Sect64;
251 MachOObj->ReadSection64(LCI, SectNum, Sect64);
252 Sections.push_back(copySection(Sect64));
253
254 // Store the symbols in this section.
255 if (SymtabLC) {
256 for (unsigned i = 0; i != (*SymtabLC)->NumSymbolTableEntries; ++i) {
257 InMemoryStruct<macho::Symbol64TableEntry> STE;
258 MachOObj->ReadSymbol64TableEntry((*SymtabLC)->SymbolTableOffset, i,
259 STE);
260 Symbols.push_back(copySymbol(STE));
261 }
262 }
263 }
264 } else if (LCI.Command.Type == macho::LCT_FunctionStarts) {
265 // We found a function starts segment, parse the addresses for later
266 // consumption.
267 InMemoryStruct<macho::LinkeditDataLoadCommand> LLC;
268 MachOObj->ReadLinkeditDataLoadCommand(LCI, LLC);
269
270 MachOObj->ReadULEB128s(LLC->DataOffset, FoundFns);
271 }
272 }
273}
274
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000275void llvm::DisassembleInputMachO(StringRef Filename) {
276 OwningPtr<MemoryBuffer> Buff;
277
278 if (error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, Buff)) {
279 errs() << "llvm-objdump: " << Filename << ": " << ec.message() << "\n";
280 return;
281 }
282
283 OwningPtr<MachOObject> MachOObj(MachOObject::LoadFromBuffer(Buff.take()));
284
285 const Target *TheTarget = GetTarget(MachOObj.get());
286 if (!TheTarget) {
287 // GetTarget prints out stuff.
288 return;
289 }
290 const MCInstrInfo *InstrInfo = TheTarget->createMCInstrInfo();
291 OwningPtr<MCInstrAnalysis>
292 InstrAnalysis(TheTarget->createMCInstrAnalysis(InstrInfo));
293
294 // Set up disassembler.
295 OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000296 OwningPtr<const MCSubtargetInfo>
297 STI(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000298 OwningPtr<const MCDisassembler> DisAsm(TheTarget->createMCDisassembler(*STI));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000299 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
300 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000301 AsmPrinterVariant, *AsmInfo, *STI));
302
303 if (!InstrAnalysis || !AsmInfo || !STI || !DisAsm || !IP) {
304 errs() << "error: couldn't initialize disassmbler for target "
305 << TripleName << '\n';
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000306 return;
307 }
308
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000309 outs() << '\n' << Filename << ":\n\n";
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000310
311 const macho::Header &Header = MachOObj->getHeader();
312
313 const MachOObject::LoadCommandInfo *SymtabLCI = 0;
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000314 // First, find the symbol table segment.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000315 for (unsigned i = 0; i != Header.NumLoadCommands; ++i) {
316 const MachOObject::LoadCommandInfo &LCI = MachOObj->getLoadCommandInfo(i);
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000317 if (LCI.Command.Type == macho::LCT_Symtab) {
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000318 SymtabLCI = &LCI;
319 break;
320 }
321 }
322
323 // Read and register the symbol table data.
324 InMemoryStruct<macho::SymtabLoadCommand> SymtabLC;
325 MachOObj->ReadSymtabLoadCommand(*SymtabLCI, SymtabLC);
326 MachOObj->RegisterStringTable(*SymtabLC);
327
328 std::vector<Section> Sections;
329 std::vector<Symbol> Symbols;
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000330 SmallVector<uint64_t, 8> FoundFns;
331
Benjamin Kramer8c930972011-09-21 01:13:19 +0000332 getSectionsAndSymbols(Header, MachOObj.get(), &SymtabLC, Sections, Symbols,
333 FoundFns);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000334
Benjamin Kramer8c930972011-09-21 01:13:19 +0000335 // Make a copy of the unsorted symbol list. FIXME: duplication
336 std::vector<Symbol> UnsortedSymbols(Symbols);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000337 // Sort the symbols by address, just in case they didn't come in that way.
338 array_pod_sort(Symbols.begin(), Symbols.end());
339
340#ifndef NDEBUG
341 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
342#else
343 raw_ostream &DebugOut = nulls();
344#endif
345
Benjamin Kramer8c930972011-09-21 01:13:19 +0000346 StringRef DebugAbbrevSection, DebugInfoSection, DebugArangesSection,
347 DebugLineSection, DebugStrSection;
348 OwningPtr<DIContext> diContext;
349 // Try to find debug info and set up the DIContext for it.
350 if (UseDbg) {
351 ArrayRef<Section> DebugSections = Sections;
352 std::vector<Section> DSYMSections;
353 OwningPtr<MachOObject> DSYMObj;
354
355 // A separate DSym file path was specified, parse it as a macho file,
356 // get the sections and supply it to the section name parsing machinery.
357 if (!DSYMFile.empty()) {
358 OwningPtr<MemoryBuffer> Buf;
359 if (error_code ec = MemoryBuffer::getFileOrSTDIN(DSYMFile.c_str(), Buf)) {
360 errs() << "llvm-objdump: " << Filename << ": " << ec.message() << '\n';
361 return;
362 }
363 DSYMObj.reset(MachOObject::LoadFromBuffer(Buf.take()));
364 const macho::Header &Header = DSYMObj->getHeader();
365
366 std::vector<Symbol> Symbols;
367 SmallVector<uint64_t, 8> FoundFns;
368 getSectionsAndSymbols(Header, DSYMObj.get(), 0, DSYMSections, Symbols,
369 FoundFns);
370 DebugSections = DSYMSections;
371 }
372
373 // Find the named debug info sections.
374 for (unsigned SectIdx = 0; SectIdx != DebugSections.size(); SectIdx++) {
375 if (!strcmp(DebugSections[SectIdx].Name, "__debug_abbrev"))
376 DebugAbbrevSection = DSYMObj->getData(DebugSections[SectIdx].Offset,
377 DebugSections[SectIdx].Size);
378 else if (!strcmp(DebugSections[SectIdx].Name, "__debug_info"))
379 DebugInfoSection = DSYMObj->getData(DebugSections[SectIdx].Offset,
380 DebugSections[SectIdx].Size);
381 else if (!strcmp(DebugSections[SectIdx].Name, "__debug_aranges"))
382 DebugArangesSection = DSYMObj->getData(DebugSections[SectIdx].Offset,
383 DebugSections[SectIdx].Size);
384 else if (!strcmp(DebugSections[SectIdx].Name, "__debug_line"))
385 DebugLineSection = DSYMObj->getData(DebugSections[SectIdx].Offset,
386 DebugSections[SectIdx].Size);
387 else if (!strcmp(DebugSections[SectIdx].Name, "__debug_str"))
388 DebugStrSection = DSYMObj->getData(DebugSections[SectIdx].Offset,
389 DebugSections[SectIdx].Size);
390 }
391
392 // Setup the DIContext.
393 diContext.reset(DIContext::getDWARFContext(MachOObj->isLittleEndian(),
394 DebugInfoSection,
395 DebugAbbrevSection,
396 DebugArangesSection,
397 DebugLineSection,
398 DebugStrSection));
399 }
400
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000401 FunctionMapTy FunctionMap;
402 FunctionListTy Functions;
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000403
404 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
405 if (strcmp(Sections[SectIdx].Name, "__text"))
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000406 continue; // Skip non-text sections
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000407
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000408 // Insert the functions from the function starts segment into our map.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000409 uint64_t VMAddr = Sections[SectIdx].Address - Sections[SectIdx].Offset;
410 for (unsigned i = 0, e = FoundFns.size(); i != e; ++i)
Benjamin Kramer4d906382011-09-19 20:08:52 +0000411 FunctionMap.insert(std::make_pair(FoundFns[i]+VMAddr, (MCFunction*)0));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000412
413 StringRef Bytes = MachOObj->getData(Sections[SectIdx].Offset,
414 Sections[SectIdx].Size);
415 StringRefMemoryObject memoryObject(Bytes);
416 bool symbolTableWorked = false;
417
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000418 // Parse relocations.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000419 std::vector<std::pair<uint64_t, uint32_t> > Relocs;
420 for (unsigned j = 0; j != Sections[SectIdx].NumRelocs; ++j) {
421 InMemoryStruct<macho::RelocationEntry> RE;
422 MachOObj->ReadRelocationEntry(Sections[SectIdx].RelocTableOffset, j, RE);
423 Relocs.push_back(std::make_pair(RE->Word0, RE->Word1 & 0xffffff));
424 }
425 array_pod_sort(Relocs.begin(), Relocs.end());
426
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000427 // Disassemble symbol by symbol.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000428 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000429 // Make sure the symbol is defined in this section.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000430 if ((unsigned)Symbols[SymIdx].SectionIndex - 1 != SectIdx)
431 continue;
432
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000433 // Start at the address of the symbol relative to the section's address.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000434 uint64_t Start = Symbols[SymIdx].Value - Sections[SectIdx].Address;
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000435 // Stop disassembling either at the beginning of the next symbol or at
436 // the end of the section.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000437 uint64_t End = (SymIdx+1 == Symbols.size() ||
438 Symbols[SymIdx].SectionIndex != Symbols[SymIdx+1].SectionIndex) ?
439 Sections[SectIdx].Size :
440 Symbols[SymIdx+1].Value - Sections[SectIdx].Address;
441 uint64_t Size;
442
443 if (Start >= End)
444 continue;
445
446 symbolTableWorked = true;
447
448 if (!CFG) {
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000449 // Normal disassembly, print addresses, bytes and mnemonic form.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000450 outs() << MachOObj->getStringAtIndex(Symbols[SymIdx].StringIndex)
451 << ":\n";
Benjamin Kramer8c930972011-09-21 01:13:19 +0000452 DILineInfo lastLine;
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000453 for (uint64_t Index = Start; Index < End; Index += Size) {
454 MCInst Inst;
455
456 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
457 DebugOut, nulls())) {
458 outs() << format("%8llx:\t", Sections[SectIdx].Address + Index);
459 DumpBytes(StringRef(Bytes.data() + Index, Size));
460 IP->printInst(&Inst, outs(), "");
Benjamin Kramer8c930972011-09-21 01:13:19 +0000461
462 // Print debug info.
463 if (diContext) {
464 DILineInfo dli =
465 diContext->getLineInfoForAddress(Sections[SectIdx].Address +
466 Index);
467 // Print valid line info if it changed.
468 if (dli != lastLine && dli.getLine() != 0)
469 outs() << "\t## " << dli.getFileName() << ':'
470 << dli.getLine() << ':' << dli.getColumn();
471 lastLine = dli;
472 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000473 outs() << "\n";
474 } else {
475 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
476 if (Size == 0)
477 Size = 1; // skip illegible bytes
478 }
479 }
480 } else {
481 // Create CFG and use it for disassembly.
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000482 createMCFunctionAndSaveCalls(
483 MachOObj->getStringAtIndex(Symbols[SymIdx].StringIndex),
484 DisAsm.get(), memoryObject, Start, End, InstrAnalysis.get(),
485 Start, DebugOut, FunctionMap, Functions);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000486 }
487 }
488
489 if (CFG) {
490 if (!symbolTableWorked) {
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000491 // Reading the symbol table didn't work, create a big __TEXT symbol.
492 createMCFunctionAndSaveCalls("__TEXT", DisAsm.get(), memoryObject,
493 0, Sections[SectIdx].Size,
494 InstrAnalysis.get(),
495 Sections[SectIdx].Offset, DebugOut,
496 FunctionMap, Functions);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000497 }
498 for (std::map<uint64_t, MCFunction*>::iterator mi = FunctionMap.begin(),
499 me = FunctionMap.end(); mi != me; ++mi)
500 if (mi->second == 0) {
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000501 // Create functions for the remaining callees we have gathered,
502 // but we didn't find a name for them.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000503 SmallVector<uint64_t, 16> Calls;
504 MCFunction f =
505 MCFunction::createFunctionFromMC("unknown", DisAsm.get(),
506 memoryObject, mi->first,
507 Sections[SectIdx].Size,
508 InstrAnalysis.get(), DebugOut,
509 Calls);
510 Functions.push_back(f);
511 mi->second = &Functions.back();
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000512 for (unsigned i = 0, e = Calls.size(); i != e; ++i) {
513 std::pair<uint64_t, MCFunction*> p(Calls[i], (MCFunction*)0);
514 if (FunctionMap.insert(p).second)
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000515 mi = FunctionMap.begin();
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000516 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000517 }
518
519 DenseSet<uint64_t> PrintedBlocks;
520 for (unsigned ffi = 0, ffe = Functions.size(); ffi != ffe; ++ffi) {
521 MCFunction &f = Functions[ffi];
522 for (MCFunction::iterator fi = f.begin(), fe = f.end(); fi != fe; ++fi){
523 if (!PrintedBlocks.insert(fi->first).second)
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000524 continue; // We already printed this block.
525
526 // We assume a block has predecessors when it's the first block after
527 // a symbol.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000528 bool hasPreds = FunctionMap.find(fi->first) != FunctionMap.end();
529
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000530 // See if this block has predecessors.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000531 // FIXME: Slow.
532 for (MCFunction::iterator pi = f.begin(), pe = f.end(); pi != pe;
533 ++pi)
534 if (pi->second.contains(fi->first)) {
535 hasPreds = true;
536 break;
537 }
538
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000539 // No predecessors, this is a data block. Print as .byte directives.
540 if (!hasPreds) {
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000541 uint64_t End = llvm::next(fi) == fe ? Sections[SectIdx].Size :
542 llvm::next(fi)->first;
543 outs() << "# " << End-fi->first << " bytes of data:\n";
544 for (unsigned pos = fi->first; pos != End; ++pos) {
545 outs() << format("%8x:\t", Sections[SectIdx].Address + pos);
546 DumpBytes(StringRef(Bytes.data() + pos, 1));
547 outs() << format("\t.byte 0x%02x\n", (uint8_t)Bytes[pos]);
548 }
549 continue;
550 }
551
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000552 if (fi->second.contains(fi->first)) // Print a header for simple loops
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000553 outs() << "# Loop begin:\n";
554
Benjamin Kramer8c930972011-09-21 01:13:19 +0000555 DILineInfo lastLine;
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000556 // Walk over the instructions and print them.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000557 for (unsigned ii = 0, ie = fi->second.getInsts().size(); ii != ie;
558 ++ii) {
559 const MCDecodedInst &Inst = fi->second.getInsts()[ii];
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000560
561 // If there's a symbol at this address, print its name.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000562 if (FunctionMap.find(Sections[SectIdx].Address + Inst.Address) !=
563 FunctionMap.end())
564 outs() << FunctionMap[Sections[SectIdx].Address + Inst.Address]->
565 getName() << ":\n";
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000566
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000567 outs() << format("%8llx:\t", Sections[SectIdx].Address +
568 Inst.Address);
569 DumpBytes(StringRef(Bytes.data() + Inst.Address, Inst.Size));
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000570
571 if (fi->second.contains(fi->first)) // Indent simple loops.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000572 outs() << '\t';
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000573
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000574 IP->printInst(&Inst.Inst, outs(), "");
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000575
576 // Look for relocations inside this instructions, if there is one
577 // print its target and additional information if availbable.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000578 for (unsigned j = 0; j != Relocs.size(); ++j)
579 if (Relocs[j].first >= Sections[SectIdx].Address + Inst.Address &&
580 Relocs[j].first < Sections[SectIdx].Address + Inst.Address +
581 Inst.Size) {
582 outs() << "\t# "
583 << MachOObj->getStringAtIndex(
584 UnsortedSymbols[Relocs[j].second].StringIndex)
585 << ' ';
586 DumpAddress(UnsortedSymbols[Relocs[j].second].Value, Sections,
587 MachOObj.get(), outs());
588 }
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000589
590 // If this instructions contains an address, see if we can evaluate
591 // it and print additional information.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000592 uint64_t targ = InstrAnalysis->evaluateBranch(Inst.Inst,
593 Inst.Address,
594 Inst.Size);
595 if (targ != -1ULL)
596 DumpAddress(targ, Sections, MachOObj.get(), outs());
597
Benjamin Kramer8c930972011-09-21 01:13:19 +0000598 // Print debug info.
599 if (diContext) {
600 DILineInfo dli =
601 diContext->getLineInfoForAddress(Sections[SectIdx].Address +
602 Inst.Address);
603 // Print valid line info if it changed.
604 if (dli != lastLine && dli.getLine() != 0)
605 outs() << "\t## " << dli.getFileName() << ':'
606 << dli.getLine() << ':' << dli.getColumn();
607 lastLine = dli;
608 }
609
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000610 outs() << '\n';
611 }
612 }
613
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000614 emitDOTFile((f.getName().str() + ".dot").c_str(), f, IP.get());
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000615 }
616 }
617 }
618}