blob: f1749f031b3b46776ba3aedbe575349fcfffd26f [file] [log] [blame]
Michael J. Spencer92e1deb2011-01-20 06:39:06 +00001//===-- 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
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000016#include "llvm-objdump.h"
Benjamin Kramer685a2502011-07-20 19:37:35 +000017#include "MCFunction.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000018#include "llvm/ADT/OwningPtr.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000019#include "llvm/ADT/STLExtras.h"
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +000020#include "llvm/ADT/StringExtras.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000021#include "llvm/ADT/Triple.h"
22#include "llvm/MC/MCAsmInfo.h"
23#include "llvm/MC/MCDisassembler.h"
24#include "llvm/MC/MCInst.h"
25#include "llvm/MC/MCInstPrinter.h"
Craig Topper17463b32012-04-02 06:09:36 +000026#include "llvm/MC/MCInstrInfo.h"
Jim Grosbachc6449b62012-03-05 19:33:20 +000027#include "llvm/MC/MCRegisterInfo.h"
James Molloyb9505852011-09-07 17:24:38 +000028#include "llvm/MC/MCSubtargetInfo.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000029#include "llvm/Object/Archive.h"
30#include "llvm/Object/COFF.h"
31#include "llvm/Object/ObjectFile.h"
Michael J. Spencer27781b72011-10-08 00:18:30 +000032#include "llvm/Support/Casting.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000033#include "llvm/Support/CommandLine.h"
34#include "llvm/Support/Debug.h"
Michael J. Spencer27781b72011-10-08 00:18:30 +000035#include "llvm/Support/FileSystem.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000036#include "llvm/Support/Format.h"
Benjamin Kramer853b0fd2011-07-25 23:04:36 +000037#include "llvm/Support/GraphWriter.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000038#include "llvm/Support/Host.h"
39#include "llvm/Support/ManagedStatic.h"
40#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000041#include "llvm/Support/MemoryObject.h"
42#include "llvm/Support/PrettyStackTrace.h"
43#include "llvm/Support/Signals.h"
44#include "llvm/Support/SourceMgr.h"
Evan Cheng3e74d6f2011-08-24 18:08:43 +000045#include "llvm/Support/TargetRegistry.h"
46#include "llvm/Support/TargetSelect.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000047#include "llvm/Support/raw_ostream.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000048#include "llvm/Support/system_error.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000049#include <algorithm>
Benjamin Kramer81bbdfd2012-03-23 11:49:32 +000050#include <cctype>
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000051#include <cstring>
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000052using namespace llvm;
53using namespace object;
54
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000055static cl::list<std::string>
56InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000057
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000058static cl::opt<bool>
59Disassemble("disassemble",
60 cl::desc("Display assembler mnemonics for the machine instructions"));
61static cl::alias
62Disassembled("d", cl::desc("Alias for --disassemble"),
63 cl::aliasopt(Disassemble));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000064
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000065static cl::opt<bool>
Michael J. Spencer27781b72011-10-08 00:18:30 +000066Relocations("r", cl::desc("Display the relocation entries in the file"));
67
68static cl::opt<bool>
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +000069SectionContents("s", cl::desc("Display the content of each section"));
70
71static cl::opt<bool>
Michael J. Spencer22ff0f32011-10-18 19:32:17 +000072SymbolTable("t", cl::desc("Display the symbol table"));
73
74static cl::opt<bool>
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000075MachO("macho", cl::desc("Use MachO specific object file parser"));
76static cl::alias
77MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachO));
Benjamin Kramer685a2502011-07-20 19:37:35 +000078
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000079cl::opt<std::string>
80llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
81 "see -version for available targets"));
82
83cl::opt<std::string>
84llvm::ArchName("arch", cl::desc("Target arch to disassemble for, "
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000085 "see -version for available targets"));
86
Nick Lewycky023bb152011-10-10 21:21:34 +000087static cl::opt<bool>
88SectionHeaders("section-headers", cl::desc("Display summaries of the headers "
89 "for each section."));
90static cl::alias
91SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
92 cl::aliasopt(SectionHeaders));
93static cl::alias
94SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
95 cl::aliasopt(SectionHeaders));
96
Jack Carterfd6d1652012-08-28 19:24:49 +000097static cl::list<std::string>
98MAttrs("mattr",
99 cl::CommaSeparated,
100 cl::desc("Target specific attributes"),
101 cl::value_desc("a1,+a2,-a3,..."));
102
Eli Bendersky8b9da532012-11-20 22:57:02 +0000103static cl::opt<bool>
104NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling instructions, "
105 "do not print the instruction bytes."));
106
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000107static StringRef ToolName;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000108
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000109static bool error(error_code ec) {
110 if (!ec) return false;
Michael J. Spencer25b15772011-06-25 17:55:23 +0000111
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000112 outs() << ToolName << ": error reading file: " << ec.message() << ".\n";
113 outs().flush();
114 return true;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000115}
116
Jim Grosbach3f5d1a22012-08-07 17:53:14 +0000117static const Target *getTarget(const ObjectFile *Obj = NULL) {
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000118 // Figure out the target triple.
Kevin Enderby9ed9e5d2012-05-08 23:38:45 +0000119 llvm::Triple TheTriple("unknown-unknown-unknown");
Michael J. Spencerd11699d2011-01-20 07:22:04 +0000120 if (TripleName.empty()) {
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000121 if (Obj)
Kevin Enderby9ed9e5d2012-05-08 23:38:45 +0000122 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
Michael J. Spencerd11699d2011-01-20 07:22:04 +0000123 } else
Kevin Enderby9ed9e5d2012-05-08 23:38:45 +0000124 TheTriple.setTriple(Triple::normalize(TripleName));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000125
126 // Get the target specific parser.
127 std::string Error;
Kevin Enderby9ed9e5d2012-05-08 23:38:45 +0000128 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
129 Error);
130 if (!TheTarget) {
131 errs() << ToolName << ": " << Error;
132 return 0;
133 }
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000134
Kevin Enderby9ed9e5d2012-05-08 23:38:45 +0000135 // Update the triple name and return the found target.
136 TripleName = TheTriple.getTriple();
137 return TheTarget;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000138}
139
David Blaikie2d24e2a2011-12-20 02:50:00 +0000140void llvm::StringRefMemoryObject::anchor() { }
141
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000142void llvm::DumpBytes(StringRef bytes) {
143 static const char hex_rep[] = "0123456789abcdef";
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000144 // FIXME: The real way to do this is to figure out the longest instruction
145 // and align to that size before printing. I'll fix this when I get
146 // around to outputting relocations.
147 // 15 is the longest x86 instruction
148 // 3 is for the hex rep of a byte + a space.
149 // 1 is for the null terminator.
150 enum { OutputSize = (15 * 3) + 1 };
151 char output[OutputSize];
152
153 assert(bytes.size() <= 15
154 && "DumpBytes only supports instructions of up to 15 bytes");
155 memset(output, ' ', sizeof(output));
156 unsigned index = 0;
157 for (StringRef::iterator i = bytes.begin(),
158 e = bytes.end(); i != e; ++i) {
159 output[index] = hex_rep[(*i & 0xF0) >> 4];
160 output[index + 1] = hex_rep[*i & 0xF];
161 index += 3;
162 }
163
164 output[sizeof(output) - 1] = 0;
165 outs() << output;
166}
167
Michael J. Spencer942eb002011-10-13 22:17:18 +0000168static bool RelocAddressLess(RelocationRef a, RelocationRef b) {
169 uint64_t a_addr, b_addr;
170 if (error(a.getAddress(a_addr))) return false;
171 if (error(b.getAddress(b_addr))) return false;
172 return a_addr < b_addr;
173}
174
175static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Jim Grosbach3f5d1a22012-08-07 17:53:14 +0000176 const Target *TheTarget = getTarget(Obj);
177 // getTarget() will have already issued a diagnostic if necessary, so
178 // just bail here if it failed.
179 if (!TheTarget)
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000180 return;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000181
Jack Carterfd6d1652012-08-28 19:24:49 +0000182 // Package up features to be passed to target/subtarget
183 std::string FeaturesStr;
184 if (MAttrs.size()) {
185 SubtargetFeatures Features;
186 for (unsigned i = 0; i != MAttrs.size(); ++i)
187 Features.AddFeature(MAttrs[i]);
188 FeaturesStr = Features.getString();
189 }
190
Michael J. Spencer25b15772011-06-25 17:55:23 +0000191 error_code ec;
Michael J. Spencer4344b1e2011-10-07 19:25:32 +0000192 for (section_iterator i = Obj->begin_sections(),
Michael J. Spencer27781b72011-10-08 00:18:30 +0000193 e = Obj->end_sections();
194 i != e; i.increment(ec)) {
Michael J. Spencer25b15772011-06-25 17:55:23 +0000195 if (error(ec)) break;
196 bool text;
197 if (error(i->isText(text))) break;
198 if (!text) continue;
199
Michael J. Spencer942eb002011-10-13 22:17:18 +0000200 uint64_t SectionAddr;
201 if (error(i->getAddress(SectionAddr))) break;
202
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000203 // Make a list of all the symbols in this section.
204 std::vector<std::pair<uint64_t, StringRef> > Symbols;
Michael J. Spencer4344b1e2011-10-07 19:25:32 +0000205 for (symbol_iterator si = Obj->begin_symbols(),
Michael J. Spencer27781b72011-10-08 00:18:30 +0000206 se = Obj->end_symbols();
207 si != se; si.increment(ec)) {
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000208 bool contains;
209 if (!error(i->containsSymbol(*si, contains)) && contains) {
210 uint64_t Address;
Danil Malyshevb0436a72011-11-29 17:40:10 +0000211 if (error(si->getAddress(Address))) break;
Cameron Zwarichaab21912012-02-03 04:13:37 +0000212 Address -= SectionAddr;
213
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000214 StringRef Name;
215 if (error(si->getName(Name))) break;
216 Symbols.push_back(std::make_pair(Address, Name));
217 }
218 }
219
220 // Sort the symbols by address, just in case they didn't come in that way.
221 array_pod_sort(Symbols.begin(), Symbols.end());
222
Michael J. Spencer942eb002011-10-13 22:17:18 +0000223 // Make a list of all the relocations for this section.
224 std::vector<RelocationRef> Rels;
225 if (InlineRelocs) {
226 for (relocation_iterator ri = i->begin_relocations(),
227 re = i->end_relocations();
Jim Grosbach3f5d1a22012-08-07 17:53:14 +0000228 ri != re; ri.increment(ec)) {
Michael J. Spencer942eb002011-10-13 22:17:18 +0000229 if (error(ec)) break;
230 Rels.push_back(*ri);
231 }
232 }
233
234 // Sort relocations by address.
235 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
236
Michael J. Spencer25b15772011-06-25 17:55:23 +0000237 StringRef name;
238 if (error(i->getName(name))) break;
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000239 outs() << "Disassembly of section " << name << ':';
240
241 // If the section has no symbols just insert a dummy one and disassemble
242 // the whole section.
243 if (Symbols.empty())
244 Symbols.push_back(std::make_pair(0, name));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000245
246 // Set up disassembler.
Evan Cheng1abf2cb2011-07-14 23:50:31 +0000247 OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000248
249 if (!AsmInfo) {
250 errs() << "error: no assembly info for target " << TripleName << "\n";
251 return;
252 }
253
Michael J. Spencer27781b72011-10-08 00:18:30 +0000254 OwningPtr<const MCSubtargetInfo> STI(
Jack Carterfd6d1652012-08-28 19:24:49 +0000255 TheTarget->createMCSubtargetInfo(TripleName, "", FeaturesStr));
James Molloyb9505852011-09-07 17:24:38 +0000256
257 if (!STI) {
258 errs() << "error: no subtarget info for target " << TripleName << "\n";
259 return;
260 }
261
Owen Anderson10c044e2011-10-27 21:55:13 +0000262 OwningPtr<const MCDisassembler> DisAsm(
Michael J. Spencer27781b72011-10-08 00:18:30 +0000263 TheTarget->createMCDisassembler(*STI));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000264 if (!DisAsm) {
265 errs() << "error: no disassembler for target " << TripleName << "\n";
266 return;
267 }
268
Jim Grosbachc6449b62012-03-05 19:33:20 +0000269 OwningPtr<const MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
270 if (!MRI) {
271 errs() << "error: no register info for target " << TripleName << "\n";
272 return;
273 }
274
Craig Topper17463b32012-04-02 06:09:36 +0000275 OwningPtr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
276 if (!MII) {
277 errs() << "error: no instruction info for target " << TripleName << "\n";
278 return;
279 }
280
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000281 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
282 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Craig Topper17463b32012-04-02 06:09:36 +0000283 AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000284 if (!IP) {
Michael J. Spencer27781b72011-10-08 00:18:30 +0000285 errs() << "error: no instruction printer for target " << TripleName
286 << '\n';
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000287 return;
288 }
289
Michael J. Spencer25b15772011-06-25 17:55:23 +0000290 StringRef Bytes;
291 if (error(i->getContents(Bytes))) break;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000292 StringRefMemoryObject memoryObject(Bytes);
293 uint64_t Size;
294 uint64_t Index;
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000295 uint64_t SectSize;
296 if (error(i->getSize(SectSize))) break;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000297
Michael J. Spencer942eb002011-10-13 22:17:18 +0000298 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
299 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000300 // Disassemble symbol by symbol.
301 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
302 uint64_t Start = Symbols[si].first;
Michael J. Spencer178dbd42011-10-13 20:37:08 +0000303 uint64_t End;
304 // The end is either the size of the section or the beginning of the next
305 // symbol.
306 if (si == se - 1)
307 End = SectSize;
308 // Make sure this symbol takes up space.
309 else if (Symbols[si + 1].first != Start)
310 End = Symbols[si + 1].first - 1;
311 else
312 // This symbol has the same address as the next symbol. Skip it.
313 continue;
314
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000315 outs() << '\n' << Symbols[si].second << ":\n";
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000316
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000317#ifndef NDEBUG
318 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
319#else
320 raw_ostream &DebugOut = nulls();
321#endif
322
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000323 for (Index = Start; Index < End; Index += Size) {
324 MCInst Inst;
Owen Anderson98c5dda2011-09-15 23:38:46 +0000325
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000326 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
327 DebugOut, nulls())) {
Eli Bendersky8b9da532012-11-20 22:57:02 +0000328 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
329 if (!NoShowRawInsn) {
330 outs() << "\t";
331 DumpBytes(StringRef(Bytes.data() + Index, Size));
332 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000333 IP->printInst(&Inst, outs(), "");
334 outs() << "\n";
335 } else {
336 errs() << ToolName << ": warning: invalid instruction encoding\n";
337 if (Size == 0)
338 Size = 1; // skip illegible bytes
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000339 }
Michael J. Spencer942eb002011-10-13 22:17:18 +0000340
341 // Print relocation for instruction.
342 while (rel_cur != rel_end) {
Owen Anderson0685e942011-10-25 20:35:53 +0000343 bool hidden = false;
Michael J. Spencer942eb002011-10-13 22:17:18 +0000344 uint64_t addr;
345 SmallString<16> name;
346 SmallString<32> val;
Owen Anderson0685e942011-10-25 20:35:53 +0000347
348 // If this relocation is hidden, skip it.
349 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
350 if (hidden) goto skip_print_rel;
351
Michael J. Spencer942eb002011-10-13 22:17:18 +0000352 if (error(rel_cur->getAddress(addr))) goto skip_print_rel;
353 // Stop when rel_cur's address is past the current instruction.
Owen Anderson34749ce2011-10-25 20:15:39 +0000354 if (addr >= Index + Size) break;
Michael J. Spencer942eb002011-10-13 22:17:18 +0000355 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
356 if (error(rel_cur->getValueString(val))) goto skip_print_rel;
357
Benjamin Kramer51cf8662012-03-10 02:04:38 +0000358 outs() << format("\t\t\t%8" PRIx64 ": ", SectionAddr + addr) << name
359 << "\t" << val << "\n";
Michael J. Spencer942eb002011-10-13 22:17:18 +0000360
361 skip_print_rel:
362 ++rel_cur;
363 }
Benjamin Kramer685a2502011-07-20 19:37:35 +0000364 }
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000365 }
366 }
367}
368
Michael J. Spencer27781b72011-10-08 00:18:30 +0000369static void PrintRelocations(const ObjectFile *o) {
370 error_code ec;
371 for (section_iterator si = o->begin_sections(), se = o->end_sections();
372 si != se; si.increment(ec)){
373 if (error(ec)) return;
374 if (si->begin_relocations() == si->end_relocations())
375 continue;
376 StringRef secname;
377 if (error(si->getName(secname))) continue;
378 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
379 for (relocation_iterator ri = si->begin_relocations(),
380 re = si->end_relocations();
381 ri != re; ri.increment(ec)) {
382 if (error(ec)) return;
383
Owen Anderson0685e942011-10-25 20:35:53 +0000384 bool hidden;
Michael J. Spencer27781b72011-10-08 00:18:30 +0000385 uint64_t address;
386 SmallString<32> relocname;
387 SmallString<32> valuestr;
Owen Anderson0685e942011-10-25 20:35:53 +0000388 if (error(ri->getHidden(hidden))) continue;
389 if (hidden) continue;
Michael J. Spencer27781b72011-10-08 00:18:30 +0000390 if (error(ri->getTypeName(relocname))) continue;
391 if (error(ri->getAddress(address))) continue;
392 if (error(ri->getValueString(valuestr))) continue;
393 outs() << address << " " << relocname << " " << valuestr << "\n";
394 }
395 outs() << "\n";
396 }
397}
398
Nick Lewycky023bb152011-10-10 21:21:34 +0000399static void PrintSectionHeaders(const ObjectFile *o) {
400 outs() << "Sections:\n"
401 "Idx Name Size Address Type\n";
402 error_code ec;
403 unsigned i = 0;
404 for (section_iterator si = o->begin_sections(), se = o->end_sections();
405 si != se; si.increment(ec)) {
406 if (error(ec)) return;
407 StringRef Name;
408 if (error(si->getName(Name))) return;
409 uint64_t Address;
410 if (error(si->getAddress(Address))) return;
411 uint64_t Size;
412 if (error(si->getSize(Size))) return;
413 bool Text, Data, BSS;
414 if (error(si->isText(Text))) return;
415 if (error(si->isData(Data))) return;
416 if (error(si->isBSS(BSS))) return;
417 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer14a5f462011-10-13 20:37:20 +0000418 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
Benjamin Kramer51cf8662012-03-10 02:04:38 +0000419 outs() << format("%3d %-13s %09" PRIx64 " %017" PRIx64 " %s\n",
420 i, Name.str().c_str(), Size, Address, Type.c_str());
Nick Lewycky023bb152011-10-10 21:21:34 +0000421 ++i;
422 }
423}
424
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +0000425static void PrintSectionContents(const ObjectFile *o) {
426 error_code ec;
427 for (section_iterator si = o->begin_sections(),
428 se = o->end_sections();
429 si != se; si.increment(ec)) {
430 if (error(ec)) return;
431 StringRef Name;
432 StringRef Contents;
433 uint64_t BaseAddr;
434 if (error(si->getName(Name))) continue;
435 if (error(si->getContents(Contents))) continue;
436 if (error(si->getAddress(BaseAddr))) continue;
437
438 outs() << "Contents of section " << Name << ":\n";
439
440 // Dump out the content as hex and printable ascii characters.
441 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer51cf8662012-03-10 02:04:38 +0000442 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +0000443 // Dump line of hex.
444 for (std::size_t i = 0; i < 16; ++i) {
445 if (i != 0 && i % 4 == 0)
446 outs() << ' ';
447 if (addr + i < end)
448 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
449 << hexdigit(Contents[addr + i] & 0xF, true);
450 else
451 outs() << " ";
452 }
453 // Print ascii.
454 outs() << " ";
455 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
456 if (std::isprint(Contents[addr + i] & 0xFF))
457 outs() << Contents[addr + i];
458 else
459 outs() << ".";
460 }
461 outs() << "\n";
462 }
463 }
464}
465
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000466static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
467 const coff_file_header *header;
468 if (error(coff->getHeader(header))) return;
469 int aux_count = 0;
470 const coff_symbol *symbol = 0;
471 for (int i = 0, e = header->NumberOfSymbols; i != e; ++i) {
472 if (aux_count--) {
473 // Figure out which type of aux this is.
474 if (symbol->StorageClass == COFF::IMAGE_SYM_CLASS_STATIC
475 && symbol->Value == 0) { // Section definition.
476 const coff_aux_section_definition *asd;
477 if (error(coff->getAuxSymbol<coff_aux_section_definition>(i, asd)))
478 return;
479 outs() << "AUX "
480 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
481 , unsigned(asd->Length)
482 , unsigned(asd->NumberOfRelocations)
483 , unsigned(asd->NumberOfLinenumbers)
484 , unsigned(asd->CheckSum))
485 << format("assoc %d comdat %d\n"
486 , unsigned(asd->Number)
487 , unsigned(asd->Selection));
Jim Grosbach3f5d1a22012-08-07 17:53:14 +0000488 } else
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000489 outs() << "AUX Unknown\n";
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000490 } else {
491 StringRef name;
492 if (error(coff->getSymbol(i, symbol))) return;
493 if (error(coff->getSymbolName(symbol, name))) return;
494 outs() << "[" << format("%2d", i) << "]"
495 << "(sec " << format("%2d", int(symbol->SectionNumber)) << ")"
496 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
497 << "(ty " << format("%3x", unsigned(symbol->Type)) << ")"
498 << "(scl " << format("%3x", unsigned(symbol->StorageClass)) << ") "
499 << "(nx " << unsigned(symbol->NumberOfAuxSymbols) << ") "
500 << "0x" << format("%08x", unsigned(symbol->Value)) << " "
501 << name << "\n";
502 aux_count = symbol->NumberOfAuxSymbols;
503 }
504 }
505}
506
507static void PrintSymbolTable(const ObjectFile *o) {
508 outs() << "SYMBOL TABLE:\n";
509
510 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o))
511 PrintCOFFSymbolTable(coff);
512 else {
513 error_code ec;
514 for (symbol_iterator si = o->begin_symbols(),
515 se = o->end_symbols(); si != se; si.increment(ec)) {
516 if (error(ec)) return;
517 StringRef Name;
Danil Malyshevb0436a72011-11-29 17:40:10 +0000518 uint64_t Address;
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000519 SymbolRef::Type Type;
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000520 uint64_t Size;
David Meyerc46255a2012-02-28 23:47:53 +0000521 uint32_t Flags;
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000522 section_iterator Section = o->end_sections();
523 if (error(si->getName(Name))) continue;
Danil Malyshevb0436a72011-11-29 17:40:10 +0000524 if (error(si->getAddress(Address))) continue;
David Meyerc46255a2012-02-28 23:47:53 +0000525 if (error(si->getFlags(Flags))) continue;
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000526 if (error(si->getType(Type))) continue;
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000527 if (error(si->getSize(Size))) continue;
528 if (error(si->getSection(Section))) continue;
529
David Meyerc46255a2012-02-28 23:47:53 +0000530 bool Global = Flags & SymbolRef::SF_Global;
531 bool Weak = Flags & SymbolRef::SF_Weak;
532 bool Absolute = Flags & SymbolRef::SF_Absolute;
533
Danil Malyshevb0436a72011-11-29 17:40:10 +0000534 if (Address == UnknownAddressOrSize)
535 Address = 0;
536 if (Size == UnknownAddressOrSize)
537 Size = 0;
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000538 char GlobLoc = ' ';
David Meyer2c677272012-02-29 02:11:55 +0000539 if (Type != SymbolRef::ST_Unknown)
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000540 GlobLoc = Global ? 'g' : 'l';
541 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
542 ? 'd' : ' ';
543 char FileFunc = ' ';
544 if (Type == SymbolRef::ST_File)
545 FileFunc = 'f';
546 else if (Type == SymbolRef::ST_Function)
547 FileFunc = 'F';
548
Benjamin Kramer51cf8662012-03-10 02:04:38 +0000549 outs() << format("%08" PRIx64, Address) << " "
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000550 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
551 << (Weak ? 'w' : ' ') // Weak?
552 << ' ' // Constructor. Not supported yet.
553 << ' ' // Warning. Not supported yet.
554 << ' ' // Indirect reference to another symbol.
555 << Debug // Debugging (d) or dynamic (D) symbol.
556 << FileFunc // Name of function (F), file (f) or object (O).
557 << ' ';
558 if (Absolute)
559 outs() << "*ABS*";
560 else if (Section == o->end_sections())
561 outs() << "*UND*";
562 else {
563 StringRef SectionName;
564 if (error(Section->getName(SectionName)))
565 SectionName = "";
566 outs() << SectionName;
567 }
568 outs() << '\t'
Benjamin Kramer51cf8662012-03-10 02:04:38 +0000569 << format("%08" PRIx64 " ", Size)
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000570 << Name
571 << '\n';
572 }
573 }
574}
575
Michael J. Spencer27781b72011-10-08 00:18:30 +0000576static void DumpObject(const ObjectFile *o) {
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +0000577 outs() << '\n';
578 outs() << o->getFileName()
579 << ":\tfile format " << o->getFileFormatName() << "\n\n";
580
Michael J. Spencer27781b72011-10-08 00:18:30 +0000581 if (Disassemble)
Michael J. Spencer942eb002011-10-13 22:17:18 +0000582 DisassembleObject(o, Relocations);
583 if (Relocations && !Disassemble)
Michael J. Spencer27781b72011-10-08 00:18:30 +0000584 PrintRelocations(o);
Nick Lewycky023bb152011-10-10 21:21:34 +0000585 if (SectionHeaders)
586 PrintSectionHeaders(o);
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +0000587 if (SectionContents)
588 PrintSectionContents(o);
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000589 if (SymbolTable)
590 PrintSymbolTable(o);
Michael J. Spencer27781b72011-10-08 00:18:30 +0000591}
592
593/// @brief Dump each object file in \a a;
594static void DumpArchive(const Archive *a) {
595 for (Archive::child_iterator i = a->begin_children(),
596 e = a->end_children(); i != e; ++i) {
597 OwningPtr<Binary> child;
598 if (error_code ec = i->getAsBinary(child)) {
Michael J. Spencerf81285c2011-11-16 01:24:41 +0000599 // Ignore non-object files.
600 if (ec != object_error::invalid_file_type)
601 errs() << ToolName << ": '" << a->getFileName() << "': " << ec.message()
602 << ".\n";
Michael J. Spencer27781b72011-10-08 00:18:30 +0000603 continue;
604 }
605 if (ObjectFile *o = dyn_cast<ObjectFile>(child.get()))
606 DumpObject(o);
607 else
608 errs() << ToolName << ": '" << a->getFileName() << "': "
609 << "Unrecognized file type.\n";
610 }
611}
612
613/// @brief Open file and figure out how to dump it.
614static void DumpInput(StringRef file) {
615 // If file isn't stdin, check that it exists.
616 if (file != "-" && !sys::fs::exists(file)) {
617 errs() << ToolName << ": '" << file << "': " << "No such file\n";
618 return;
619 }
620
621 if (MachO && Disassemble) {
622 DisassembleInputMachO(file);
623 return;
624 }
625
626 // Attempt to open the binary.
627 OwningPtr<Binary> binary;
628 if (error_code ec = createBinary(file, binary)) {
629 errs() << ToolName << ": '" << file << "': " << ec.message() << ".\n";
630 return;
631 }
632
Jim Grosbach3f5d1a22012-08-07 17:53:14 +0000633 if (Archive *a = dyn_cast<Archive>(binary.get()))
Michael J. Spencer27781b72011-10-08 00:18:30 +0000634 DumpArchive(a);
Jim Grosbach3f5d1a22012-08-07 17:53:14 +0000635 else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get()))
Michael J. Spencer27781b72011-10-08 00:18:30 +0000636 DumpObject(o);
Jim Grosbach3f5d1a22012-08-07 17:53:14 +0000637 else
Michael J. Spencer27781b72011-10-08 00:18:30 +0000638 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
Michael J. Spencer27781b72011-10-08 00:18:30 +0000639}
640
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000641int main(int argc, char **argv) {
642 // Print a stack trace if we signal out.
643 sys::PrintStackTraceOnErrorSignal();
644 PrettyStackTraceProgram X(argc, argv);
645 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
646
647 // Initialize targets and assembly printers/parsers.
648 llvm::InitializeAllTargetInfos();
Evan Chenge78085a2011-07-22 21:58:54 +0000649 llvm::InitializeAllTargetMCs();
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000650 llvm::InitializeAllAsmParsers();
651 llvm::InitializeAllDisassemblers();
652
Pete Cooperff204962012-05-03 23:20:10 +0000653 // Register the target printer for --version.
654 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
655
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000656 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
657 TripleName = Triple::normalize(TripleName);
658
659 ToolName = argv[0];
660
661 // Defaults to a.out if no filenames specified.
662 if (InputFilenames.size() == 0)
663 InputFilenames.push_back("a.out");
664
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000665 if (!Disassemble
666 && !Relocations
667 && !SectionHeaders
668 && !SectionContents
669 && !SymbolTable) {
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000670 cl::PrintHelpMessage();
671 return 2;
672 }
673
Michael J. Spencer27781b72011-10-08 00:18:30 +0000674 std::for_each(InputFilenames.begin(), InputFilenames.end(),
675 DumpInput);
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000676
677 return 0;
678}