blob: 22eaab7de03fcf8493799617641cc3c922d12198 [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;
Benjamin Kramerb5b8d202011-09-21 04:01:19 +0000349 OwningPtr<MachOObject> DSYMObj;
Benjamin Kramer91c603b2011-09-21 18:18:53 +0000350 MachOObject *DbgInfoObj = MachOObj.get();
Benjamin Kramer8c930972011-09-21 01:13:19 +0000351 // Try to find debug info and set up the DIContext for it.
352 if (UseDbg) {
353 ArrayRef<Section> DebugSections = Sections;
354 std::vector<Section> DSYMSections;
Benjamin Kramer8c930972011-09-21 01:13:19 +0000355
356 // A separate DSym file path was specified, parse it as a macho file,
357 // get the sections and supply it to the section name parsing machinery.
358 if (!DSYMFile.empty()) {
359 OwningPtr<MemoryBuffer> Buf;
360 if (error_code ec = MemoryBuffer::getFileOrSTDIN(DSYMFile.c_str(), Buf)) {
361 errs() << "llvm-objdump: " << Filename << ": " << ec.message() << '\n';
362 return;
363 }
364 DSYMObj.reset(MachOObject::LoadFromBuffer(Buf.take()));
365 const macho::Header &Header = DSYMObj->getHeader();
366
367 std::vector<Symbol> Symbols;
368 SmallVector<uint64_t, 8> FoundFns;
369 getSectionsAndSymbols(Header, DSYMObj.get(), 0, DSYMSections, Symbols,
370 FoundFns);
371 DebugSections = DSYMSections;
Benjamin Kramer91c603b2011-09-21 18:18:53 +0000372 DbgInfoObj = DSYMObj.get();
Benjamin Kramer8c930972011-09-21 01:13:19 +0000373 }
374
375 // Find the named debug info sections.
376 for (unsigned SectIdx = 0; SectIdx != DebugSections.size(); SectIdx++) {
377 if (!strcmp(DebugSections[SectIdx].Name, "__debug_abbrev"))
Benjamin Kramer91c603b2011-09-21 18:18:53 +0000378 DebugAbbrevSection = DbgInfoObj->getData(DebugSections[SectIdx].Offset,
379 DebugSections[SectIdx].Size);
Benjamin Kramer8c930972011-09-21 01:13:19 +0000380 else if (!strcmp(DebugSections[SectIdx].Name, "__debug_info"))
Benjamin Kramer91c603b2011-09-21 18:18:53 +0000381 DebugInfoSection = DbgInfoObj->getData(DebugSections[SectIdx].Offset,
Benjamin Kramer8c930972011-09-21 01:13:19 +0000382 DebugSections[SectIdx].Size);
Benjamin Kramer91c603b2011-09-21 18:18:53 +0000383 else if (!strcmp(DebugSections[SectIdx].Name, "__debug_aranges"))
384 DebugArangesSection = DbgInfoObj->getData(DebugSections[SectIdx].Offset,
385 DebugSections[SectIdx].Size);
Benjamin Kramer8c930972011-09-21 01:13:19 +0000386 else if (!strcmp(DebugSections[SectIdx].Name, "__debug_line"))
Benjamin Kramer91c603b2011-09-21 18:18:53 +0000387 DebugLineSection = DbgInfoObj->getData(DebugSections[SectIdx].Offset,
388 DebugSections[SectIdx].Size);
Benjamin Kramer8c930972011-09-21 01:13:19 +0000389 else if (!strcmp(DebugSections[SectIdx].Name, "__debug_str"))
Benjamin Kramer91c603b2011-09-21 18:18:53 +0000390 DebugStrSection = DbgInfoObj->getData(DebugSections[SectIdx].Offset,
391 DebugSections[SectIdx].Size);
Benjamin Kramer8c930972011-09-21 01:13:19 +0000392 }
393
394 // Setup the DIContext.
Benjamin Kramer91c603b2011-09-21 18:18:53 +0000395 diContext.reset(DIContext::getDWARFContext(DbgInfoObj->isLittleEndian(),
Benjamin Kramer8c930972011-09-21 01:13:19 +0000396 DebugInfoSection,
397 DebugAbbrevSection,
398 DebugArangesSection,
399 DebugLineSection,
400 DebugStrSection));
401 }
402
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000403 FunctionMapTy FunctionMap;
404 FunctionListTy Functions;
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000405
406 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
407 if (strcmp(Sections[SectIdx].Name, "__text"))
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000408 continue; // Skip non-text sections
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000409
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000410 // Insert the functions from the function starts segment into our map.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000411 uint64_t VMAddr = Sections[SectIdx].Address - Sections[SectIdx].Offset;
412 for (unsigned i = 0, e = FoundFns.size(); i != e; ++i)
Benjamin Kramer4d906382011-09-19 20:08:52 +0000413 FunctionMap.insert(std::make_pair(FoundFns[i]+VMAddr, (MCFunction*)0));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000414
415 StringRef Bytes = MachOObj->getData(Sections[SectIdx].Offset,
416 Sections[SectIdx].Size);
417 StringRefMemoryObject memoryObject(Bytes);
418 bool symbolTableWorked = false;
419
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000420 // Parse relocations.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000421 std::vector<std::pair<uint64_t, uint32_t> > Relocs;
422 for (unsigned j = 0; j != Sections[SectIdx].NumRelocs; ++j) {
423 InMemoryStruct<macho::RelocationEntry> RE;
424 MachOObj->ReadRelocationEntry(Sections[SectIdx].RelocTableOffset, j, RE);
425 Relocs.push_back(std::make_pair(RE->Word0, RE->Word1 & 0xffffff));
426 }
427 array_pod_sort(Relocs.begin(), Relocs.end());
428
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000429 // Disassemble symbol by symbol.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000430 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000431 // Make sure the symbol is defined in this section.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000432 if ((unsigned)Symbols[SymIdx].SectionIndex - 1 != SectIdx)
433 continue;
434
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000435 // Start at the address of the symbol relative to the section's address.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000436 uint64_t Start = Symbols[SymIdx].Value - Sections[SectIdx].Address;
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000437 // Stop disassembling either at the beginning of the next symbol or at
438 // the end of the section.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000439 uint64_t End = (SymIdx+1 == Symbols.size() ||
440 Symbols[SymIdx].SectionIndex != Symbols[SymIdx+1].SectionIndex) ?
441 Sections[SectIdx].Size :
442 Symbols[SymIdx+1].Value - Sections[SectIdx].Address;
443 uint64_t Size;
444
445 if (Start >= End)
446 continue;
447
448 symbolTableWorked = true;
449
450 if (!CFG) {
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000451 // Normal disassembly, print addresses, bytes and mnemonic form.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000452 outs() << MachOObj->getStringAtIndex(Symbols[SymIdx].StringIndex)
453 << ":\n";
Benjamin Kramer8c930972011-09-21 01:13:19 +0000454 DILineInfo lastLine;
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000455 for (uint64_t Index = Start; Index < End; Index += Size) {
456 MCInst Inst;
457
458 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
459 DebugOut, nulls())) {
460 outs() << format("%8llx:\t", Sections[SectIdx].Address + Index);
461 DumpBytes(StringRef(Bytes.data() + Index, Size));
462 IP->printInst(&Inst, outs(), "");
Benjamin Kramer8c930972011-09-21 01:13:19 +0000463
464 // Print debug info.
465 if (diContext) {
466 DILineInfo dli =
467 diContext->getLineInfoForAddress(Sections[SectIdx].Address +
468 Index);
469 // Print valid line info if it changed.
470 if (dli != lastLine && dli.getLine() != 0)
471 outs() << "\t## " << dli.getFileName() << ':'
472 << dli.getLine() << ':' << dli.getColumn();
473 lastLine = dli;
474 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000475 outs() << "\n";
476 } else {
477 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
478 if (Size == 0)
479 Size = 1; // skip illegible bytes
480 }
481 }
482 } else {
483 // Create CFG and use it for disassembly.
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000484 createMCFunctionAndSaveCalls(
485 MachOObj->getStringAtIndex(Symbols[SymIdx].StringIndex),
486 DisAsm.get(), memoryObject, Start, End, InstrAnalysis.get(),
487 Start, DebugOut, FunctionMap, Functions);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000488 }
489 }
490
491 if (CFG) {
492 if (!symbolTableWorked) {
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000493 // Reading the symbol table didn't work, create a big __TEXT symbol.
494 createMCFunctionAndSaveCalls("__TEXT", DisAsm.get(), memoryObject,
495 0, Sections[SectIdx].Size,
496 InstrAnalysis.get(),
497 Sections[SectIdx].Offset, DebugOut,
498 FunctionMap, Functions);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000499 }
500 for (std::map<uint64_t, MCFunction*>::iterator mi = FunctionMap.begin(),
501 me = FunctionMap.end(); mi != me; ++mi)
502 if (mi->second == 0) {
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000503 // Create functions for the remaining callees we have gathered,
504 // but we didn't find a name for them.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000505 SmallVector<uint64_t, 16> Calls;
506 MCFunction f =
507 MCFunction::createFunctionFromMC("unknown", DisAsm.get(),
508 memoryObject, mi->first,
509 Sections[SectIdx].Size,
510 InstrAnalysis.get(), DebugOut,
511 Calls);
512 Functions.push_back(f);
513 mi->second = &Functions.back();
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000514 for (unsigned i = 0, e = Calls.size(); i != e; ++i) {
515 std::pair<uint64_t, MCFunction*> p(Calls[i], (MCFunction*)0);
516 if (FunctionMap.insert(p).second)
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000517 mi = FunctionMap.begin();
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000518 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000519 }
520
521 DenseSet<uint64_t> PrintedBlocks;
522 for (unsigned ffi = 0, ffe = Functions.size(); ffi != ffe; ++ffi) {
523 MCFunction &f = Functions[ffi];
524 for (MCFunction::iterator fi = f.begin(), fe = f.end(); fi != fe; ++fi){
525 if (!PrintedBlocks.insert(fi->first).second)
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000526 continue; // We already printed this block.
527
528 // We assume a block has predecessors when it's the first block after
529 // a symbol.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000530 bool hasPreds = FunctionMap.find(fi->first) != FunctionMap.end();
531
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000532 // See if this block has predecessors.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000533 // FIXME: Slow.
534 for (MCFunction::iterator pi = f.begin(), pe = f.end(); pi != pe;
535 ++pi)
536 if (pi->second.contains(fi->first)) {
537 hasPreds = true;
538 break;
539 }
540
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000541 // No predecessors, this is a data block. Print as .byte directives.
542 if (!hasPreds) {
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000543 uint64_t End = llvm::next(fi) == fe ? Sections[SectIdx].Size :
544 llvm::next(fi)->first;
545 outs() << "# " << End-fi->first << " bytes of data:\n";
546 for (unsigned pos = fi->first; pos != End; ++pos) {
547 outs() << format("%8x:\t", Sections[SectIdx].Address + pos);
548 DumpBytes(StringRef(Bytes.data() + pos, 1));
549 outs() << format("\t.byte 0x%02x\n", (uint8_t)Bytes[pos]);
550 }
551 continue;
552 }
553
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000554 if (fi->second.contains(fi->first)) // Print a header for simple loops
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000555 outs() << "# Loop begin:\n";
556
Benjamin Kramer8c930972011-09-21 01:13:19 +0000557 DILineInfo lastLine;
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000558 // Walk over the instructions and print them.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000559 for (unsigned ii = 0, ie = fi->second.getInsts().size(); ii != ie;
560 ++ii) {
561 const MCDecodedInst &Inst = fi->second.getInsts()[ii];
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000562
563 // If there's a symbol at this address, print its name.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000564 if (FunctionMap.find(Sections[SectIdx].Address + Inst.Address) !=
565 FunctionMap.end())
566 outs() << FunctionMap[Sections[SectIdx].Address + Inst.Address]->
567 getName() << ":\n";
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000568
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000569 outs() << format("%8llx:\t", Sections[SectIdx].Address +
570 Inst.Address);
571 DumpBytes(StringRef(Bytes.data() + Inst.Address, Inst.Size));
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000572
573 if (fi->second.contains(fi->first)) // Indent simple loops.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000574 outs() << '\t';
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000575
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000576 IP->printInst(&Inst.Inst, outs(), "");
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000577
578 // Look for relocations inside this instructions, if there is one
579 // print its target and additional information if availbable.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000580 for (unsigned j = 0; j != Relocs.size(); ++j)
581 if (Relocs[j].first >= Sections[SectIdx].Address + Inst.Address &&
582 Relocs[j].first < Sections[SectIdx].Address + Inst.Address +
583 Inst.Size) {
584 outs() << "\t# "
585 << MachOObj->getStringAtIndex(
586 UnsortedSymbols[Relocs[j].second].StringIndex)
587 << ' ';
588 DumpAddress(UnsortedSymbols[Relocs[j].second].Value, Sections,
589 MachOObj.get(), outs());
590 }
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000591
592 // If this instructions contains an address, see if we can evaluate
593 // it and print additional information.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000594 uint64_t targ = InstrAnalysis->evaluateBranch(Inst.Inst,
595 Inst.Address,
596 Inst.Size);
597 if (targ != -1ULL)
598 DumpAddress(targ, Sections, MachOObj.get(), outs());
599
Benjamin Kramer8c930972011-09-21 01:13:19 +0000600 // Print debug info.
601 if (diContext) {
602 DILineInfo dli =
603 diContext->getLineInfoForAddress(Sections[SectIdx].Address +
604 Inst.Address);
605 // Print valid line info if it changed.
606 if (dli != lastLine && dli.getLine() != 0)
607 outs() << "\t## " << dli.getFileName() << ':'
608 << dli.getLine() << ':' << dli.getColumn();
609 lastLine = dli;
610 }
611
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000612 outs() << '\n';
613 }
614 }
615
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000616 emitDOTFile((f.getName().str() + ".dot").c_str(), f, IP.get());
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000617 }
618 }
619 }
620}