blob: 24dc9c91a3b0fcf66ee11771e527770f6fbdbc59 [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"
Rafael Espindolacef81b32012-12-21 03:47:03 +000031#include "llvm/Object/MachO.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000032#include "llvm/Object/ObjectFile.h"
Michael J. Spencer27781b72011-10-08 00:18:30 +000033#include "llvm/Support/Casting.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000034#include "llvm/Support/CommandLine.h"
35#include "llvm/Support/Debug.h"
Michael J. Spencer27781b72011-10-08 00:18:30 +000036#include "llvm/Support/FileSystem.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000037#include "llvm/Support/Format.h"
Benjamin Kramer853b0fd2011-07-25 23:04:36 +000038#include "llvm/Support/GraphWriter.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000039#include "llvm/Support/Host.h"
40#include "llvm/Support/ManagedStatic.h"
41#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000042#include "llvm/Support/MemoryObject.h"
43#include "llvm/Support/PrettyStackTrace.h"
44#include "llvm/Support/Signals.h"
45#include "llvm/Support/SourceMgr.h"
Evan Cheng3e74d6f2011-08-24 18:08:43 +000046#include "llvm/Support/TargetRegistry.h"
47#include "llvm/Support/TargetSelect.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000048#include "llvm/Support/raw_ostream.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000049#include "llvm/Support/system_error.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000050#include <algorithm>
Benjamin Kramer81bbdfd2012-03-23 11:49:32 +000051#include <cctype>
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000052#include <cstring>
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000053using namespace llvm;
54using namespace object;
55
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000056static cl::list<std::string>
57InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000058
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000059static cl::opt<bool>
60Disassemble("disassemble",
61 cl::desc("Display assembler mnemonics for the machine instructions"));
62static cl::alias
63Disassembled("d", cl::desc("Alias for --disassemble"),
64 cl::aliasopt(Disassemble));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000065
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000066static cl::opt<bool>
Michael J. Spencer27781b72011-10-08 00:18:30 +000067Relocations("r", cl::desc("Display the relocation entries in the file"));
68
69static cl::opt<bool>
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +000070SectionContents("s", cl::desc("Display the content of each section"));
71
72static cl::opt<bool>
Michael J. Spencer22ff0f32011-10-18 19:32:17 +000073SymbolTable("t", cl::desc("Display the symbol table"));
74
75static cl::opt<bool>
Rafael Espindolacef81b32012-12-21 03:47:03 +000076MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000077static cl::alias
Rafael Espindolacef81b32012-12-21 03:47:03 +000078MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
Benjamin Kramer685a2502011-07-20 19:37:35 +000079
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000080cl::opt<std::string>
81llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
82 "see -version for available targets"));
83
84cl::opt<std::string>
85llvm::ArchName("arch", cl::desc("Target arch to disassemble for, "
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000086 "see -version for available targets"));
87
Nick Lewycky023bb152011-10-10 21:21:34 +000088static cl::opt<bool>
89SectionHeaders("section-headers", cl::desc("Display summaries of the headers "
90 "for each section."));
91static cl::alias
92SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
93 cl::aliasopt(SectionHeaders));
94static cl::alias
95SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
96 cl::aliasopt(SectionHeaders));
97
Jack Carterfd6d1652012-08-28 19:24:49 +000098static cl::list<std::string>
99MAttrs("mattr",
100 cl::CommaSeparated,
101 cl::desc("Target specific attributes"),
102 cl::value_desc("a1,+a2,-a3,..."));
103
Eli Bendersky8b9da532012-11-20 22:57:02 +0000104static cl::opt<bool>
105NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling instructions, "
106 "do not print the instruction bytes."));
107
Michael J. Spencereef7b622012-12-05 20:12:35 +0000108static cl::opt<bool>
109UnwindInfo("unwind-info", cl::desc("Display unwind information"));
110
111static cl::alias
112UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
113 cl::aliasopt(UnwindInfo));
114
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000115static StringRef ToolName;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000116
Michael J. Spencereef7b622012-12-05 20:12:35 +0000117bool llvm::error(error_code ec) {
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000118 if (!ec) return false;
Michael J. Spencer25b15772011-06-25 17:55:23 +0000119
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000120 outs() << ToolName << ": error reading file: " << ec.message() << ".\n";
121 outs().flush();
122 return true;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000123}
124
Jim Grosbach3f5d1a22012-08-07 17:53:14 +0000125static const Target *getTarget(const ObjectFile *Obj = NULL) {
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000126 // Figure out the target triple.
Kevin Enderby9ed9e5d2012-05-08 23:38:45 +0000127 llvm::Triple TheTriple("unknown-unknown-unknown");
Michael J. Spencerd11699d2011-01-20 07:22:04 +0000128 if (TripleName.empty()) {
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000129 if (Obj)
Kevin Enderby9ed9e5d2012-05-08 23:38:45 +0000130 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
Michael J. Spencerd11699d2011-01-20 07:22:04 +0000131 } else
Kevin Enderby9ed9e5d2012-05-08 23:38:45 +0000132 TheTriple.setTriple(Triple::normalize(TripleName));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000133
134 // Get the target specific parser.
135 std::string Error;
Kevin Enderby9ed9e5d2012-05-08 23:38:45 +0000136 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
137 Error);
138 if (!TheTarget) {
139 errs() << ToolName << ": " << Error;
140 return 0;
141 }
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000142
Kevin Enderby9ed9e5d2012-05-08 23:38:45 +0000143 // Update the triple name and return the found target.
144 TripleName = TheTriple.getTriple();
145 return TheTarget;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000146}
147
David Blaikie2d24e2a2011-12-20 02:50:00 +0000148void llvm::StringRefMemoryObject::anchor() { }
149
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000150void llvm::DumpBytes(StringRef bytes) {
151 static const char hex_rep[] = "0123456789abcdef";
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000152 // FIXME: The real way to do this is to figure out the longest instruction
153 // and align to that size before printing. I'll fix this when I get
154 // around to outputting relocations.
155 // 15 is the longest x86 instruction
156 // 3 is for the hex rep of a byte + a space.
157 // 1 is for the null terminator.
158 enum { OutputSize = (15 * 3) + 1 };
159 char output[OutputSize];
160
161 assert(bytes.size() <= 15
162 && "DumpBytes only supports instructions of up to 15 bytes");
163 memset(output, ' ', sizeof(output));
164 unsigned index = 0;
165 for (StringRef::iterator i = bytes.begin(),
166 e = bytes.end(); i != e; ++i) {
167 output[index] = hex_rep[(*i & 0xF0) >> 4];
168 output[index + 1] = hex_rep[*i & 0xF];
169 index += 3;
170 }
171
172 output[sizeof(output) - 1] = 0;
173 outs() << output;
174}
175
Michael J. Spencereef7b622012-12-05 20:12:35 +0000176bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
Michael J. Spencer942eb002011-10-13 22:17:18 +0000177 uint64_t a_addr, b_addr;
178 if (error(a.getAddress(a_addr))) return false;
179 if (error(b.getAddress(b_addr))) return false;
180 return a_addr < b_addr;
181}
182
183static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Jim Grosbach3f5d1a22012-08-07 17:53:14 +0000184 const Target *TheTarget = getTarget(Obj);
185 // getTarget() will have already issued a diagnostic if necessary, so
186 // just bail here if it failed.
187 if (!TheTarget)
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000188 return;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000189
Jack Carterfd6d1652012-08-28 19:24:49 +0000190 // Package up features to be passed to target/subtarget
191 std::string FeaturesStr;
192 if (MAttrs.size()) {
193 SubtargetFeatures Features;
194 for (unsigned i = 0; i != MAttrs.size(); ++i)
195 Features.AddFeature(MAttrs[i]);
196 FeaturesStr = Features.getString();
197 }
198
Michael J. Spencer25b15772011-06-25 17:55:23 +0000199 error_code ec;
Michael J. Spencer4344b1e2011-10-07 19:25:32 +0000200 for (section_iterator i = Obj->begin_sections(),
Michael J. Spencer27781b72011-10-08 00:18:30 +0000201 e = Obj->end_sections();
202 i != e; i.increment(ec)) {
Michael J. Spencer25b15772011-06-25 17:55:23 +0000203 if (error(ec)) break;
204 bool text;
205 if (error(i->isText(text))) break;
206 if (!text) continue;
207
Michael J. Spencer942eb002011-10-13 22:17:18 +0000208 uint64_t SectionAddr;
209 if (error(i->getAddress(SectionAddr))) break;
210
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000211 // Make a list of all the symbols in this section.
212 std::vector<std::pair<uint64_t, StringRef> > Symbols;
Michael J. Spencer4344b1e2011-10-07 19:25:32 +0000213 for (symbol_iterator si = Obj->begin_symbols(),
Michael J. Spencer27781b72011-10-08 00:18:30 +0000214 se = Obj->end_symbols();
215 si != se; si.increment(ec)) {
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000216 bool contains;
217 if (!error(i->containsSymbol(*si, contains)) && contains) {
218 uint64_t Address;
Danil Malyshevb0436a72011-11-29 17:40:10 +0000219 if (error(si->getAddress(Address))) break;
Cameron Zwarichaab21912012-02-03 04:13:37 +0000220 Address -= SectionAddr;
221
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000222 StringRef Name;
223 if (error(si->getName(Name))) break;
224 Symbols.push_back(std::make_pair(Address, Name));
225 }
226 }
227
228 // Sort the symbols by address, just in case they didn't come in that way.
229 array_pod_sort(Symbols.begin(), Symbols.end());
230
Michael J. Spencer942eb002011-10-13 22:17:18 +0000231 // Make a list of all the relocations for this section.
232 std::vector<RelocationRef> Rels;
233 if (InlineRelocs) {
234 for (relocation_iterator ri = i->begin_relocations(),
235 re = i->end_relocations();
Jim Grosbach3f5d1a22012-08-07 17:53:14 +0000236 ri != re; ri.increment(ec)) {
Michael J. Spencer942eb002011-10-13 22:17:18 +0000237 if (error(ec)) break;
238 Rels.push_back(*ri);
239 }
240 }
241
242 // Sort relocations by address.
243 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
244
Rafael Espindolacef81b32012-12-21 03:47:03 +0000245 StringRef SegmentName = "";
246 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
247 DataRefImpl DR = i->getRawDataRefImpl();
248 if (error(MachO->getSectionFinalSegmentName(DR, SegmentName)))
249 break;
250 }
Michael J. Spencer25b15772011-06-25 17:55:23 +0000251 StringRef name;
252 if (error(i->getName(name))) break;
Rafael Espindolacef81b32012-12-21 03:47:03 +0000253 outs() << "Disassembly of section ";
254 if (!SegmentName.empty())
255 outs() << SegmentName << ",";
256 outs() << name << ':';
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000257
258 // If the section has no symbols just insert a dummy one and disassemble
259 // the whole section.
260 if (Symbols.empty())
261 Symbols.push_back(std::make_pair(0, name));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000262
263 // Set up disassembler.
Evan Cheng1abf2cb2011-07-14 23:50:31 +0000264 OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000265
266 if (!AsmInfo) {
267 errs() << "error: no assembly info for target " << TripleName << "\n";
268 return;
269 }
270
Michael J. Spencer27781b72011-10-08 00:18:30 +0000271 OwningPtr<const MCSubtargetInfo> STI(
Jack Carterfd6d1652012-08-28 19:24:49 +0000272 TheTarget->createMCSubtargetInfo(TripleName, "", FeaturesStr));
James Molloyb9505852011-09-07 17:24:38 +0000273
274 if (!STI) {
275 errs() << "error: no subtarget info for target " << TripleName << "\n";
276 return;
277 }
278
Owen Anderson10c044e2011-10-27 21:55:13 +0000279 OwningPtr<const MCDisassembler> DisAsm(
Michael J. Spencer27781b72011-10-08 00:18:30 +0000280 TheTarget->createMCDisassembler(*STI));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000281 if (!DisAsm) {
282 errs() << "error: no disassembler for target " << TripleName << "\n";
283 return;
284 }
285
Jim Grosbachc6449b62012-03-05 19:33:20 +0000286 OwningPtr<const MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
287 if (!MRI) {
288 errs() << "error: no register info for target " << TripleName << "\n";
289 return;
290 }
291
Craig Topper17463b32012-04-02 06:09:36 +0000292 OwningPtr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
293 if (!MII) {
294 errs() << "error: no instruction info for target " << TripleName << "\n";
295 return;
296 }
297
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000298 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
299 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Craig Topper17463b32012-04-02 06:09:36 +0000300 AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000301 if (!IP) {
Michael J. Spencer27781b72011-10-08 00:18:30 +0000302 errs() << "error: no instruction printer for target " << TripleName
303 << '\n';
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000304 return;
305 }
306
Michael J. Spencer25b15772011-06-25 17:55:23 +0000307 StringRef Bytes;
308 if (error(i->getContents(Bytes))) break;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000309 StringRefMemoryObject memoryObject(Bytes);
310 uint64_t Size;
311 uint64_t Index;
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000312 uint64_t SectSize;
313 if (error(i->getSize(SectSize))) break;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000314
Michael J. Spencer942eb002011-10-13 22:17:18 +0000315 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
316 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000317 // Disassemble symbol by symbol.
318 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
319 uint64_t Start = Symbols[si].first;
Michael J. Spencer178dbd42011-10-13 20:37:08 +0000320 uint64_t End;
321 // The end is either the size of the section or the beginning of the next
322 // symbol.
323 if (si == se - 1)
324 End = SectSize;
325 // Make sure this symbol takes up space.
326 else if (Symbols[si + 1].first != Start)
327 End = Symbols[si + 1].first - 1;
328 else
329 // This symbol has the same address as the next symbol. Skip it.
330 continue;
331
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000332 outs() << '\n' << Symbols[si].second << ":\n";
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000333
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000334#ifndef NDEBUG
335 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
336#else
337 raw_ostream &DebugOut = nulls();
338#endif
339
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000340 for (Index = Start; Index < End; Index += Size) {
341 MCInst Inst;
Owen Anderson98c5dda2011-09-15 23:38:46 +0000342
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000343 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
344 DebugOut, nulls())) {
Eli Bendersky8b9da532012-11-20 22:57:02 +0000345 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
346 if (!NoShowRawInsn) {
347 outs() << "\t";
348 DumpBytes(StringRef(Bytes.data() + Index, Size));
349 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000350 IP->printInst(&Inst, outs(), "");
351 outs() << "\n";
352 } else {
353 errs() << ToolName << ": warning: invalid instruction encoding\n";
354 if (Size == 0)
355 Size = 1; // skip illegible bytes
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000356 }
Michael J. Spencer942eb002011-10-13 22:17:18 +0000357
358 // Print relocation for instruction.
359 while (rel_cur != rel_end) {
Owen Anderson0685e942011-10-25 20:35:53 +0000360 bool hidden = false;
Michael J. Spencer942eb002011-10-13 22:17:18 +0000361 uint64_t addr;
362 SmallString<16> name;
363 SmallString<32> val;
Owen Anderson0685e942011-10-25 20:35:53 +0000364
365 // If this relocation is hidden, skip it.
366 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
367 if (hidden) goto skip_print_rel;
368
Michael J. Spencer942eb002011-10-13 22:17:18 +0000369 if (error(rel_cur->getAddress(addr))) goto skip_print_rel;
370 // Stop when rel_cur's address is past the current instruction.
Owen Anderson34749ce2011-10-25 20:15:39 +0000371 if (addr >= Index + Size) break;
Michael J. Spencer942eb002011-10-13 22:17:18 +0000372 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
373 if (error(rel_cur->getValueString(val))) goto skip_print_rel;
374
Benjamin Kramer51cf8662012-03-10 02:04:38 +0000375 outs() << format("\t\t\t%8" PRIx64 ": ", SectionAddr + addr) << name
376 << "\t" << val << "\n";
Michael J. Spencer942eb002011-10-13 22:17:18 +0000377
378 skip_print_rel:
379 ++rel_cur;
380 }
Benjamin Kramer685a2502011-07-20 19:37:35 +0000381 }
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000382 }
383 }
384}
385
Michael J. Spencer27781b72011-10-08 00:18:30 +0000386static void PrintRelocations(const ObjectFile *o) {
387 error_code ec;
388 for (section_iterator si = o->begin_sections(), se = o->end_sections();
389 si != se; si.increment(ec)){
390 if (error(ec)) return;
391 if (si->begin_relocations() == si->end_relocations())
392 continue;
393 StringRef secname;
394 if (error(si->getName(secname))) continue;
395 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
396 for (relocation_iterator ri = si->begin_relocations(),
397 re = si->end_relocations();
398 ri != re; ri.increment(ec)) {
399 if (error(ec)) return;
400
Owen Anderson0685e942011-10-25 20:35:53 +0000401 bool hidden;
Michael J. Spencer27781b72011-10-08 00:18:30 +0000402 uint64_t address;
403 SmallString<32> relocname;
404 SmallString<32> valuestr;
Owen Anderson0685e942011-10-25 20:35:53 +0000405 if (error(ri->getHidden(hidden))) continue;
406 if (hidden) continue;
Michael J. Spencer27781b72011-10-08 00:18:30 +0000407 if (error(ri->getTypeName(relocname))) continue;
408 if (error(ri->getAddress(address))) continue;
409 if (error(ri->getValueString(valuestr))) continue;
410 outs() << address << " " << relocname << " " << valuestr << "\n";
411 }
412 outs() << "\n";
413 }
414}
415
Nick Lewycky023bb152011-10-10 21:21:34 +0000416static void PrintSectionHeaders(const ObjectFile *o) {
417 outs() << "Sections:\n"
418 "Idx Name Size Address Type\n";
419 error_code ec;
420 unsigned i = 0;
421 for (section_iterator si = o->begin_sections(), se = o->end_sections();
422 si != se; si.increment(ec)) {
423 if (error(ec)) return;
424 StringRef Name;
425 if (error(si->getName(Name))) return;
426 uint64_t Address;
427 if (error(si->getAddress(Address))) return;
428 uint64_t Size;
429 if (error(si->getSize(Size))) return;
430 bool Text, Data, BSS;
431 if (error(si->isText(Text))) return;
432 if (error(si->isData(Data))) return;
433 if (error(si->isBSS(BSS))) return;
434 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer14a5f462011-10-13 20:37:20 +0000435 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
Benjamin Kramer51cf8662012-03-10 02:04:38 +0000436 outs() << format("%3d %-13s %09" PRIx64 " %017" PRIx64 " %s\n",
437 i, Name.str().c_str(), Size, Address, Type.c_str());
Nick Lewycky023bb152011-10-10 21:21:34 +0000438 ++i;
439 }
440}
441
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +0000442static void PrintSectionContents(const ObjectFile *o) {
443 error_code ec;
444 for (section_iterator si = o->begin_sections(),
445 se = o->end_sections();
446 si != se; si.increment(ec)) {
447 if (error(ec)) return;
448 StringRef Name;
449 StringRef Contents;
450 uint64_t BaseAddr;
451 if (error(si->getName(Name))) continue;
452 if (error(si->getContents(Contents))) continue;
453 if (error(si->getAddress(BaseAddr))) continue;
454
455 outs() << "Contents of section " << Name << ":\n";
456
457 // Dump out the content as hex and printable ascii characters.
458 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer51cf8662012-03-10 02:04:38 +0000459 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +0000460 // Dump line of hex.
461 for (std::size_t i = 0; i < 16; ++i) {
462 if (i != 0 && i % 4 == 0)
463 outs() << ' ';
464 if (addr + i < end)
465 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
466 << hexdigit(Contents[addr + i] & 0xF, true);
467 else
468 outs() << " ";
469 }
470 // Print ascii.
471 outs() << " ";
472 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
473 if (std::isprint(Contents[addr + i] & 0xFF))
474 outs() << Contents[addr + i];
475 else
476 outs() << ".";
477 }
478 outs() << "\n";
479 }
480 }
481}
482
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000483static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
484 const coff_file_header *header;
485 if (error(coff->getHeader(header))) return;
486 int aux_count = 0;
487 const coff_symbol *symbol = 0;
488 for (int i = 0, e = header->NumberOfSymbols; i != e; ++i) {
489 if (aux_count--) {
490 // Figure out which type of aux this is.
491 if (symbol->StorageClass == COFF::IMAGE_SYM_CLASS_STATIC
492 && symbol->Value == 0) { // Section definition.
493 const coff_aux_section_definition *asd;
494 if (error(coff->getAuxSymbol<coff_aux_section_definition>(i, asd)))
495 return;
496 outs() << "AUX "
497 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
498 , unsigned(asd->Length)
499 , unsigned(asd->NumberOfRelocations)
500 , unsigned(asd->NumberOfLinenumbers)
501 , unsigned(asd->CheckSum))
502 << format("assoc %d comdat %d\n"
503 , unsigned(asd->Number)
504 , unsigned(asd->Selection));
Jim Grosbach3f5d1a22012-08-07 17:53:14 +0000505 } else
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000506 outs() << "AUX Unknown\n";
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000507 } else {
508 StringRef name;
509 if (error(coff->getSymbol(i, symbol))) return;
510 if (error(coff->getSymbolName(symbol, name))) return;
511 outs() << "[" << format("%2d", i) << "]"
512 << "(sec " << format("%2d", int(symbol->SectionNumber)) << ")"
513 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
514 << "(ty " << format("%3x", unsigned(symbol->Type)) << ")"
515 << "(scl " << format("%3x", unsigned(symbol->StorageClass)) << ") "
516 << "(nx " << unsigned(symbol->NumberOfAuxSymbols) << ") "
517 << "0x" << format("%08x", unsigned(symbol->Value)) << " "
518 << name << "\n";
519 aux_count = symbol->NumberOfAuxSymbols;
520 }
521 }
522}
523
524static void PrintSymbolTable(const ObjectFile *o) {
525 outs() << "SYMBOL TABLE:\n";
526
527 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o))
528 PrintCOFFSymbolTable(coff);
529 else {
530 error_code ec;
531 for (symbol_iterator si = o->begin_symbols(),
532 se = o->end_symbols(); si != se; si.increment(ec)) {
533 if (error(ec)) return;
534 StringRef Name;
Danil Malyshevb0436a72011-11-29 17:40:10 +0000535 uint64_t Address;
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000536 SymbolRef::Type Type;
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000537 uint64_t Size;
David Meyerc46255a2012-02-28 23:47:53 +0000538 uint32_t Flags;
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000539 section_iterator Section = o->end_sections();
540 if (error(si->getName(Name))) continue;
Danil Malyshevb0436a72011-11-29 17:40:10 +0000541 if (error(si->getAddress(Address))) continue;
David Meyerc46255a2012-02-28 23:47:53 +0000542 if (error(si->getFlags(Flags))) continue;
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000543 if (error(si->getType(Type))) continue;
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000544 if (error(si->getSize(Size))) continue;
545 if (error(si->getSection(Section))) continue;
546
David Meyerc46255a2012-02-28 23:47:53 +0000547 bool Global = Flags & SymbolRef::SF_Global;
548 bool Weak = Flags & SymbolRef::SF_Weak;
549 bool Absolute = Flags & SymbolRef::SF_Absolute;
550
Danil Malyshevb0436a72011-11-29 17:40:10 +0000551 if (Address == UnknownAddressOrSize)
552 Address = 0;
553 if (Size == UnknownAddressOrSize)
554 Size = 0;
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000555 char GlobLoc = ' ';
David Meyer2c677272012-02-29 02:11:55 +0000556 if (Type != SymbolRef::ST_Unknown)
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000557 GlobLoc = Global ? 'g' : 'l';
558 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
559 ? 'd' : ' ';
560 char FileFunc = ' ';
561 if (Type == SymbolRef::ST_File)
562 FileFunc = 'f';
563 else if (Type == SymbolRef::ST_Function)
564 FileFunc = 'F';
565
Benjamin Kramer51cf8662012-03-10 02:04:38 +0000566 outs() << format("%08" PRIx64, Address) << " "
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000567 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
568 << (Weak ? 'w' : ' ') // Weak?
569 << ' ' // Constructor. Not supported yet.
570 << ' ' // Warning. Not supported yet.
571 << ' ' // Indirect reference to another symbol.
572 << Debug // Debugging (d) or dynamic (D) symbol.
573 << FileFunc // Name of function (F), file (f) or object (O).
574 << ' ';
575 if (Absolute)
576 outs() << "*ABS*";
577 else if (Section == o->end_sections())
578 outs() << "*UND*";
579 else {
Rafael Espindolacef81b32012-12-21 03:47:03 +0000580 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(o)) {
581 StringRef SegmentName;
582 DataRefImpl DR = Section->getRawDataRefImpl();
583 if (error(MachO->getSectionFinalSegmentName(DR, SegmentName)))
584 SegmentName = "";
585 outs() << SegmentName << ",";
586 }
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000587 StringRef SectionName;
588 if (error(Section->getName(SectionName)))
589 SectionName = "";
590 outs() << SectionName;
591 }
592 outs() << '\t'
Benjamin Kramer51cf8662012-03-10 02:04:38 +0000593 << format("%08" PRIx64 " ", Size)
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000594 << Name
595 << '\n';
596 }
597 }
598}
599
Michael J. Spencereef7b622012-12-05 20:12:35 +0000600static void PrintUnwindInfo(const ObjectFile *o) {
601 outs() << "Unwind info:\n\n";
602
603 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
604 printCOFFUnwindInfo(coff);
605 } else {
606 // TODO: Extract DWARF dump tool to objdump.
607 errs() << "This operation is only currently supported "
608 "for COFF object files.\n";
609 return;
610 }
611}
612
Michael J. Spencer27781b72011-10-08 00:18:30 +0000613static void DumpObject(const ObjectFile *o) {
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +0000614 outs() << '\n';
615 outs() << o->getFileName()
616 << ":\tfile format " << o->getFileFormatName() << "\n\n";
617
Michael J. Spencer27781b72011-10-08 00:18:30 +0000618 if (Disassemble)
Michael J. Spencer942eb002011-10-13 22:17:18 +0000619 DisassembleObject(o, Relocations);
620 if (Relocations && !Disassemble)
Michael J. Spencer27781b72011-10-08 00:18:30 +0000621 PrintRelocations(o);
Nick Lewycky023bb152011-10-10 21:21:34 +0000622 if (SectionHeaders)
623 PrintSectionHeaders(o);
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +0000624 if (SectionContents)
625 PrintSectionContents(o);
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000626 if (SymbolTable)
627 PrintSymbolTable(o);
Michael J. Spencereef7b622012-12-05 20:12:35 +0000628 if (UnwindInfo)
629 PrintUnwindInfo(o);
Michael J. Spencer27781b72011-10-08 00:18:30 +0000630}
631
632/// @brief Dump each object file in \a a;
633static void DumpArchive(const Archive *a) {
634 for (Archive::child_iterator i = a->begin_children(),
635 e = a->end_children(); i != e; ++i) {
636 OwningPtr<Binary> child;
637 if (error_code ec = i->getAsBinary(child)) {
Michael J. Spencerf81285c2011-11-16 01:24:41 +0000638 // Ignore non-object files.
639 if (ec != object_error::invalid_file_type)
640 errs() << ToolName << ": '" << a->getFileName() << "': " << ec.message()
641 << ".\n";
Michael J. Spencer27781b72011-10-08 00:18:30 +0000642 continue;
643 }
644 if (ObjectFile *o = dyn_cast<ObjectFile>(child.get()))
645 DumpObject(o);
646 else
647 errs() << ToolName << ": '" << a->getFileName() << "': "
648 << "Unrecognized file type.\n";
649 }
650}
651
652/// @brief Open file and figure out how to dump it.
653static void DumpInput(StringRef file) {
654 // If file isn't stdin, check that it exists.
655 if (file != "-" && !sys::fs::exists(file)) {
656 errs() << ToolName << ": '" << file << "': " << "No such file\n";
657 return;
658 }
659
Rafael Espindolacef81b32012-12-21 03:47:03 +0000660 if (MachOOpt && Disassemble) {
Michael J. Spencer27781b72011-10-08 00:18:30 +0000661 DisassembleInputMachO(file);
662 return;
663 }
664
665 // Attempt to open the binary.
666 OwningPtr<Binary> binary;
667 if (error_code ec = createBinary(file, binary)) {
668 errs() << ToolName << ": '" << file << "': " << ec.message() << ".\n";
669 return;
670 }
671
Jim Grosbach3f5d1a22012-08-07 17:53:14 +0000672 if (Archive *a = dyn_cast<Archive>(binary.get()))
Michael J. Spencer27781b72011-10-08 00:18:30 +0000673 DumpArchive(a);
Jim Grosbach3f5d1a22012-08-07 17:53:14 +0000674 else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get()))
Michael J. Spencer27781b72011-10-08 00:18:30 +0000675 DumpObject(o);
Jim Grosbach3f5d1a22012-08-07 17:53:14 +0000676 else
Michael J. Spencer27781b72011-10-08 00:18:30 +0000677 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
Michael J. Spencer27781b72011-10-08 00:18:30 +0000678}
679
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000680int main(int argc, char **argv) {
681 // Print a stack trace if we signal out.
682 sys::PrintStackTraceOnErrorSignal();
683 PrettyStackTraceProgram X(argc, argv);
684 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
685
686 // Initialize targets and assembly printers/parsers.
687 llvm::InitializeAllTargetInfos();
Evan Chenge78085a2011-07-22 21:58:54 +0000688 llvm::InitializeAllTargetMCs();
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000689 llvm::InitializeAllAsmParsers();
690 llvm::InitializeAllDisassemblers();
691
Pete Cooperff204962012-05-03 23:20:10 +0000692 // Register the target printer for --version.
693 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
694
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000695 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
696 TripleName = Triple::normalize(TripleName);
697
698 ToolName = argv[0];
699
700 // Defaults to a.out if no filenames specified.
701 if (InputFilenames.size() == 0)
702 InputFilenames.push_back("a.out");
703
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000704 if (!Disassemble
705 && !Relocations
706 && !SectionHeaders
707 && !SectionContents
Michael J. Spencereef7b622012-12-05 20:12:35 +0000708 && !SymbolTable
709 && !UnwindInfo) {
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000710 cl::PrintHelpMessage();
711 return 2;
712 }
713
Michael J. Spencer27781b72011-10-08 00:18:30 +0000714 std::for_each(InputFilenames.begin(), InputFilenames.end(),
715 DumpInput);
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000716
717 return 0;
718}