Fixed ObjectFile functions:
[oota-llvm.git] / tools / llvm-objdump / llvm-objdump.cpp
1 //===-- llvm-objdump.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 program is a utility that works like binutils "objdump", that is, it
11 // dumps out a plethora of information about an object file depending on the
12 // flags.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm-objdump.h"
17 #include "MCFunction.h"
18 #include "llvm/Object/Archive.h"
19 #include "llvm/Object/COFF.h"
20 #include "llvm/Object/ObjectFile.h"
21 #include "llvm/ADT/OwningPtr.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCDisassembler.h"
27 #include "llvm/MC/MCInst.h"
28 #include "llvm/MC/MCInstPrinter.h"
29 #include "llvm/MC/MCSubtargetInfo.h"
30 #include "llvm/Support/Casting.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/FileSystem.h"
34 #include "llvm/Support/Format.h"
35 #include "llvm/Support/GraphWriter.h"
36 #include "llvm/Support/Host.h"
37 #include "llvm/Support/ManagedStatic.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/MemoryObject.h"
40 #include "llvm/Support/PrettyStackTrace.h"
41 #include "llvm/Support/Signals.h"
42 #include "llvm/Support/SourceMgr.h"
43 #include "llvm/Support/TargetRegistry.h"
44 #include "llvm/Support/TargetSelect.h"
45 #include "llvm/Support/raw_ostream.h"
46 #include "llvm/Support/system_error.h"
47 #include <algorithm>
48 #include <cstring>
49 using namespace llvm;
50 using namespace object;
51
52 static cl::list<std::string>
53 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
54
55 static cl::opt<bool>
56 Disassemble("disassemble",
57   cl::desc("Display assembler mnemonics for the machine instructions"));
58 static cl::alias
59 Disassembled("d", cl::desc("Alias for --disassemble"),
60              cl::aliasopt(Disassemble));
61
62 static cl::opt<bool>
63 Relocations("r", cl::desc("Display the relocation entries in the file"));
64
65 static cl::opt<bool>
66 SectionContents("s", cl::desc("Display the content of each section"));
67
68 static cl::opt<bool>
69 SymbolTable("t", cl::desc("Display the symbol table"));
70
71 static cl::opt<bool>
72 MachO("macho", cl::desc("Use MachO specific object file parser"));
73 static cl::alias
74 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachO));
75
76 cl::opt<std::string>
77 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
78                                     "see -version for available targets"));
79
80 cl::opt<std::string>
81 llvm::ArchName("arch", cl::desc("Target arch to disassemble for, "
82                                 "see -version for available targets"));
83
84 static cl::opt<bool>
85 SectionHeaders("section-headers", cl::desc("Display summaries of the headers "
86                                            "for each section."));
87 static cl::alias
88 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
89                     cl::aliasopt(SectionHeaders));
90 static cl::alias
91 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
92                       cl::aliasopt(SectionHeaders));
93
94 static StringRef ToolName;
95
96 static bool error(error_code ec) {
97   if (!ec) return false;
98
99   outs() << ToolName << ": error reading file: " << ec.message() << ".\n";
100   outs().flush();
101   return true;
102 }
103
104 static const Target *GetTarget(const ObjectFile *Obj = NULL) {
105   // Figure out the target triple.
106   llvm::Triple TT("unknown-unknown-unknown");
107   if (TripleName.empty()) {
108     if (Obj)
109       TT.setArch(Triple::ArchType(Obj->getArch()));
110   } else
111     TT.setTriple(Triple::normalize(TripleName));
112
113   if (!ArchName.empty())
114     TT.setArchName(ArchName);
115
116   TripleName = TT.str();
117
118   // Get the target specific parser.
119   std::string Error;
120   const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
121   if (TheTarget)
122     return TheTarget;
123
124   errs() << ToolName << ": error: unable to get target for '" << TripleName
125          << "', see --version and --triple.\n";
126   return 0;
127 }
128
129 void llvm::DumpBytes(StringRef bytes) {
130   static const char hex_rep[] = "0123456789abcdef";
131   // FIXME: The real way to do this is to figure out the longest instruction
132   //        and align to that size before printing. I'll fix this when I get
133   //        around to outputting relocations.
134   // 15 is the longest x86 instruction
135   // 3 is for the hex rep of a byte + a space.
136   // 1 is for the null terminator.
137   enum { OutputSize = (15 * 3) + 1 };
138   char output[OutputSize];
139
140   assert(bytes.size() <= 15
141     && "DumpBytes only supports instructions of up to 15 bytes");
142   memset(output, ' ', sizeof(output));
143   unsigned index = 0;
144   for (StringRef::iterator i = bytes.begin(),
145                            e = bytes.end(); i != e; ++i) {
146     output[index] = hex_rep[(*i & 0xF0) >> 4];
147     output[index + 1] = hex_rep[*i & 0xF];
148     index += 3;
149   }
150
151   output[sizeof(output) - 1] = 0;
152   outs() << output;
153 }
154
155 static bool RelocAddressLess(RelocationRef a, RelocationRef b) {
156   uint64_t a_addr, b_addr;
157   if (error(a.getAddress(a_addr))) return false;
158   if (error(b.getAddress(b_addr))) return false;
159   return a_addr < b_addr;
160 }
161
162 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
163   const Target *TheTarget = GetTarget(Obj);
164   if (!TheTarget) {
165     // GetTarget prints out stuff.
166     return;
167   }
168
169   error_code ec;
170   for (section_iterator i = Obj->begin_sections(),
171                         e = Obj->end_sections();
172                         i != e; i.increment(ec)) {
173     if (error(ec)) break;
174     bool text;
175     if (error(i->isText(text))) break;
176     if (!text) continue;
177
178     uint64_t SectionAddr;
179     if (error(i->getAddress(SectionAddr))) break;
180
181     // Make a list of all the symbols in this section.
182     std::vector<std::pair<uint64_t, StringRef> > Symbols;
183     for (symbol_iterator si = Obj->begin_symbols(),
184                          se = Obj->end_symbols();
185                          si != se; si.increment(ec)) {
186       bool contains;
187       if (!error(i->containsSymbol(*si, contains)) && contains) {
188         uint64_t Address;
189         if (error(si->getAddress(Address))) break;
190         StringRef Name;
191         if (error(si->getName(Name))) break;
192         Symbols.push_back(std::make_pair(Address, Name));
193       }
194     }
195
196     // Sort the symbols by address, just in case they didn't come in that way.
197     array_pod_sort(Symbols.begin(), Symbols.end());
198
199     // Make a list of all the relocations for this section.
200     std::vector<RelocationRef> Rels;
201     if (InlineRelocs) {
202       for (relocation_iterator ri = i->begin_relocations(),
203                                re = i->end_relocations();
204                               ri != re; ri.increment(ec)) {
205         if (error(ec)) break;
206         Rels.push_back(*ri);
207       }
208     }
209
210     // Sort relocations by address.
211     std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
212
213     StringRef name;
214     if (error(i->getName(name))) break;
215     outs() << "Disassembly of section " << name << ':';
216
217     // If the section has no symbols just insert a dummy one and disassemble
218     // the whole section.
219     if (Symbols.empty())
220       Symbols.push_back(std::make_pair(0, name));
221
222     // Set up disassembler.
223     OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
224
225     if (!AsmInfo) {
226       errs() << "error: no assembly info for target " << TripleName << "\n";
227       return;
228     }
229
230     OwningPtr<const MCSubtargetInfo> STI(
231       TheTarget->createMCSubtargetInfo(TripleName, "", ""));
232
233     if (!STI) {
234       errs() << "error: no subtarget info for target " << TripleName << "\n";
235       return;
236     }
237
238     OwningPtr<const MCDisassembler> DisAsm(
239       TheTarget->createMCDisassembler(*STI));
240     if (!DisAsm) {
241       errs() << "error: no disassembler for target " << TripleName << "\n";
242       return;
243     }
244
245     int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
246     OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
247                                 AsmPrinterVariant, *AsmInfo, *STI));
248     if (!IP) {
249       errs() << "error: no instruction printer for target " << TripleName
250              << '\n';
251       return;
252     }
253
254     StringRef Bytes;
255     if (error(i->getContents(Bytes))) break;
256     StringRefMemoryObject memoryObject(Bytes);
257     uint64_t Size;
258     uint64_t Index;
259     uint64_t SectSize;
260     if (error(i->getSize(SectSize))) break;
261
262     std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
263     std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
264     // Disassemble symbol by symbol.
265     for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
266       uint64_t Start = Symbols[si].first;
267       uint64_t End;
268       // The end is either the size of the section or the beginning of the next
269       // symbol.
270       if (si == se - 1)
271         End = SectSize;
272       // Make sure this symbol takes up space.
273       else if (Symbols[si + 1].first != Start)
274         End = Symbols[si + 1].first - 1;
275       else
276         // This symbol has the same address as the next symbol. Skip it.
277         continue;
278
279       outs() << '\n' << Symbols[si].second << ":\n";
280
281 #ifndef NDEBUG
282         raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
283 #else
284         raw_ostream &DebugOut = nulls();
285 #endif
286
287       for (Index = Start; Index < End; Index += Size) {
288         MCInst Inst;
289
290         if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
291                                    DebugOut, nulls())) {
292           outs() << format("%8"PRIx64":\t", SectionAddr + Index);
293           DumpBytes(StringRef(Bytes.data() + Index, Size));
294           IP->printInst(&Inst, outs(), "");
295           outs() << "\n";
296         } else {
297           errs() << ToolName << ": warning: invalid instruction encoding\n";
298           if (Size == 0)
299             Size = 1; // skip illegible bytes
300         }
301
302         // Print relocation for instruction.
303         while (rel_cur != rel_end) {
304           bool hidden = false;
305           uint64_t addr;
306           SmallString<16> name;
307           SmallString<32> val;
308
309           // If this relocation is hidden, skip it.
310           if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
311           if (hidden) goto skip_print_rel;
312
313           if (error(rel_cur->getAddress(addr))) goto skip_print_rel;
314           // Stop when rel_cur's address is past the current instruction.
315           if (addr >= Index + Size) break;
316           if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
317           if (error(rel_cur->getValueString(val))) goto skip_print_rel;
318
319           outs() << format("\t\t\t%8"PRIx64": ", SectionAddr + addr) << name << "\t"
320                  << val << "\n";
321
322         skip_print_rel:
323           ++rel_cur;
324         }
325       }
326     }
327   }
328 }
329
330 static void PrintRelocations(const ObjectFile *o) {
331   error_code ec;
332   for (section_iterator si = o->begin_sections(), se = o->end_sections();
333                                                   si != se; si.increment(ec)){
334     if (error(ec)) return;
335     if (si->begin_relocations() == si->end_relocations())
336       continue;
337     StringRef secname;
338     if (error(si->getName(secname))) continue;
339     outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
340     for (relocation_iterator ri = si->begin_relocations(),
341                              re = si->end_relocations();
342                              ri != re; ri.increment(ec)) {
343       if (error(ec)) return;
344
345       bool hidden;
346       uint64_t address;
347       SmallString<32> relocname;
348       SmallString<32> valuestr;
349       if (error(ri->getHidden(hidden))) continue;
350       if (hidden) continue;
351       if (error(ri->getTypeName(relocname))) continue;
352       if (error(ri->getAddress(address))) continue;
353       if (error(ri->getValueString(valuestr))) continue;
354       outs() << address << " " << relocname << " " << valuestr << "\n";
355     }
356     outs() << "\n";
357   }
358 }
359
360 static void PrintSectionHeaders(const ObjectFile *o) {
361   outs() << "Sections:\n"
362             "Idx Name          Size      Address          Type\n";
363   error_code ec;
364   unsigned i = 0;
365   for (section_iterator si = o->begin_sections(), se = o->end_sections();
366                                                   si != se; si.increment(ec)) {
367     if (error(ec)) return;
368     StringRef Name;
369     if (error(si->getName(Name))) return;
370     uint64_t Address;
371     if (error(si->getAddress(Address))) return;
372     uint64_t Size;
373     if (error(si->getSize(Size))) return;
374     bool Text, Data, BSS;
375     if (error(si->isText(Text))) return;
376     if (error(si->isData(Data))) return;
377     if (error(si->isBSS(BSS))) return;
378     std::string Type = (std::string(Text ? "TEXT " : "") +
379                         (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
380     outs() << format("%3d %-13s %09"PRIx64" %017"PRIx64" %s\n", i, Name.str().c_str(), Size,
381                      Address, Type.c_str());
382     ++i;
383   }
384 }
385
386 static void PrintSectionContents(const ObjectFile *o) {
387   error_code ec;
388   for (section_iterator si = o->begin_sections(),
389                         se = o->end_sections();
390                         si != se; si.increment(ec)) {
391     if (error(ec)) return;
392     StringRef Name;
393     StringRef Contents;
394     uint64_t BaseAddr;
395     if (error(si->getName(Name))) continue;
396     if (error(si->getContents(Contents))) continue;
397     if (error(si->getAddress(BaseAddr))) continue;
398
399     outs() << "Contents of section " << Name << ":\n";
400
401     // Dump out the content as hex and printable ascii characters.
402     for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
403       outs() << format(" %04"PRIx64" ", BaseAddr + addr);
404       // Dump line of hex.
405       for (std::size_t i = 0; i < 16; ++i) {
406         if (i != 0 && i % 4 == 0)
407           outs() << ' ';
408         if (addr + i < end)
409           outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
410                  << hexdigit(Contents[addr + i] & 0xF, true);
411         else
412           outs() << "  ";
413       }
414       // Print ascii.
415       outs() << "  ";
416       for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
417         if (std::isprint(Contents[addr + i] & 0xFF))
418           outs() << Contents[addr + i];
419         else
420           outs() << ".";
421       }
422       outs() << "\n";
423     }
424   }
425 }
426
427 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
428   const coff_file_header *header;
429   if (error(coff->getHeader(header))) return;
430   int aux_count = 0;
431   const coff_symbol *symbol = 0;
432   for (int i = 0, e = header->NumberOfSymbols; i != e; ++i) {
433     if (aux_count--) {
434       // Figure out which type of aux this is.
435       if (symbol->StorageClass == COFF::IMAGE_SYM_CLASS_STATIC
436           && symbol->Value == 0) { // Section definition.
437         const coff_aux_section_definition *asd;
438         if (error(coff->getAuxSymbol<coff_aux_section_definition>(i, asd)))
439           return;
440         outs() << "AUX "
441                << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
442                          , unsigned(asd->Length)
443                          , unsigned(asd->NumberOfRelocations)
444                          , unsigned(asd->NumberOfLinenumbers)
445                          , unsigned(asd->CheckSum))
446                << format("assoc %d comdat %d\n"
447                          , unsigned(asd->Number)
448                          , unsigned(asd->Selection));
449       } else {
450         outs() << "AUX Unknown\n";
451       }
452     } else {
453       StringRef name;
454       if (error(coff->getSymbol(i, symbol))) return;
455       if (error(coff->getSymbolName(symbol, name))) return;
456       outs() << "[" << format("%2d", i) << "]"
457              << "(sec " << format("%2d", int(symbol->SectionNumber)) << ")"
458              << "(fl 0x00)" // Flag bits, which COFF doesn't have.
459              << "(ty " << format("%3x", unsigned(symbol->Type)) << ")"
460              << "(scl " << format("%3x", unsigned(symbol->StorageClass)) << ") "
461              << "(nx " << unsigned(symbol->NumberOfAuxSymbols) << ") "
462              << "0x" << format("%08x", unsigned(symbol->Value)) << " "
463              << name << "\n";
464       aux_count = symbol->NumberOfAuxSymbols;
465     }
466   }
467 }
468
469 static void PrintSymbolTable(const ObjectFile *o) {
470   outs() << "SYMBOL TABLE:\n";
471
472   if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o))
473     PrintCOFFSymbolTable(coff);
474   else {
475     error_code ec;
476     for (symbol_iterator si = o->begin_symbols(),
477                          se = o->end_symbols(); si != se; si.increment(ec)) {
478       if (error(ec)) return;
479       StringRef Name;
480       uint64_t Address;
481       bool Global;
482       SymbolRef::Type Type;
483       bool Weak;
484       bool Absolute;
485       uint64_t Size;
486       section_iterator Section = o->end_sections();
487       if (error(si->getName(Name))) continue;
488       if (error(si->getAddress(Address))) continue;
489       if (error(si->isGlobal(Global))) continue;
490       if (error(si->getType(Type))) continue;
491       if (error(si->isWeak(Weak))) continue;
492       if (error(si->isAbsolute(Absolute))) continue;
493       if (error(si->getSize(Size))) continue;
494       if (error(si->getSection(Section))) continue;
495
496       if (Address == UnknownAddressOrSize)
497         Address = 0;
498       if (Size == UnknownAddressOrSize)
499         Size = 0;
500       char GlobLoc = ' ';
501       if (Type != SymbolRef::ST_External)
502         GlobLoc = Global ? 'g' : 'l';
503       char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
504                    ? 'd' : ' ';
505       char FileFunc = ' ';
506       if (Type == SymbolRef::ST_File)
507         FileFunc = 'f';
508       else if (Type == SymbolRef::ST_Function)
509         FileFunc = 'F';
510
511       outs() << format("%08"PRIx64, Address) << " "
512              << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
513              << (Weak ? 'w' : ' ') // Weak?
514              << ' ' // Constructor. Not supported yet.
515              << ' ' // Warning. Not supported yet.
516              << ' ' // Indirect reference to another symbol.
517              << Debug // Debugging (d) or dynamic (D) symbol.
518              << FileFunc // Name of function (F), file (f) or object (O).
519              << ' ';
520       if (Absolute)
521         outs() << "*ABS*";
522       else if (Section == o->end_sections())
523         outs() << "*UND*";
524       else {
525         StringRef SectionName;
526         if (error(Section->getName(SectionName)))
527           SectionName = "";
528         outs() << SectionName;
529       }
530       outs() << '\t'
531              << format("%08"PRIx64" ", Size)
532              << Name
533              << '\n';
534     }
535   }
536 }
537
538 static void DumpObject(const ObjectFile *o) {
539   outs() << '\n';
540   outs() << o->getFileName()
541          << ":\tfile format " << o->getFileFormatName() << "\n\n";
542
543   if (Disassemble)
544     DisassembleObject(o, Relocations);
545   if (Relocations && !Disassemble)
546     PrintRelocations(o);
547   if (SectionHeaders)
548     PrintSectionHeaders(o);
549   if (SectionContents)
550     PrintSectionContents(o);
551   if (SymbolTable)
552     PrintSymbolTable(o);
553 }
554
555 /// @brief Dump each object file in \a a;
556 static void DumpArchive(const Archive *a) {
557   for (Archive::child_iterator i = a->begin_children(),
558                                e = a->end_children(); i != e; ++i) {
559     OwningPtr<Binary> child;
560     if (error_code ec = i->getAsBinary(child)) {
561       // Ignore non-object files.
562       if (ec != object_error::invalid_file_type)
563         errs() << ToolName << ": '" << a->getFileName() << "': " << ec.message()
564                << ".\n";
565       continue;
566     }
567     if (ObjectFile *o = dyn_cast<ObjectFile>(child.get()))
568       DumpObject(o);
569     else
570       errs() << ToolName << ": '" << a->getFileName() << "': "
571               << "Unrecognized file type.\n";
572   }
573 }
574
575 /// @brief Open file and figure out how to dump it.
576 static void DumpInput(StringRef file) {
577   // If file isn't stdin, check that it exists.
578   if (file != "-" && !sys::fs::exists(file)) {
579     errs() << ToolName << ": '" << file << "': " << "No such file\n";
580     return;
581   }
582
583   if (MachO && Disassemble) {
584     DisassembleInputMachO(file);
585     return;
586   }
587
588   // Attempt to open the binary.
589   OwningPtr<Binary> binary;
590   if (error_code ec = createBinary(file, binary)) {
591     errs() << ToolName << ": '" << file << "': " << ec.message() << ".\n";
592     return;
593   }
594
595   if (Archive *a = dyn_cast<Archive>(binary.get())) {
596     DumpArchive(a);
597   } else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get())) {
598     DumpObject(o);
599   } else {
600     errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
601   }
602 }
603
604 int main(int argc, char **argv) {
605   // Print a stack trace if we signal out.
606   sys::PrintStackTraceOnErrorSignal();
607   PrettyStackTraceProgram X(argc, argv);
608   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
609
610   // Initialize targets and assembly printers/parsers.
611   llvm::InitializeAllTargetInfos();
612   llvm::InitializeAllTargetMCs();
613   llvm::InitializeAllAsmParsers();
614   llvm::InitializeAllDisassemblers();
615
616   cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
617   TripleName = Triple::normalize(TripleName);
618
619   ToolName = argv[0];
620
621   // Defaults to a.out if no filenames specified.
622   if (InputFilenames.size() == 0)
623     InputFilenames.push_back("a.out");
624
625   if (!Disassemble
626       && !Relocations
627       && !SectionHeaders
628       && !SectionContents
629       && !SymbolTable) {
630     cl::PrintHelpMessage();
631     return 2;
632   }
633
634   std::for_each(InputFilenames.begin(), InputFilenames.end(),
635                 DumpInput);
636
637   return 0;
638 }