blob: 322bd21b289dbeccba6a7bb64e778cd7495d73b2 [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//
Michael J. Spencerdd3aa9e2013-02-05 20:27:22 +000014// The flags and output of this program should be near identical to those of
15// binutils objdump.
16//
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000017//===----------------------------------------------------------------------===//
18
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000019#include "llvm-objdump.h"
Benjamin Kramer685a2502011-07-20 19:37:35 +000020#include "MCFunction.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000021#include "llvm/ADT/OwningPtr.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000022#include "llvm/ADT/STLExtras.h"
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +000023#include "llvm/ADT/StringExtras.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000024#include "llvm/ADT/Triple.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"
Craig Topper17463b32012-04-02 06:09:36 +000029#include "llvm/MC/MCInstrInfo.h"
Jim Grosbachc6449b62012-03-05 19:33:20 +000030#include "llvm/MC/MCRegisterInfo.h"
James Molloyb9505852011-09-07 17:24:38 +000031#include "llvm/MC/MCSubtargetInfo.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000032#include "llvm/Object/Archive.h"
33#include "llvm/Object/COFF.h"
Rafael Espindolacef81b32012-12-21 03:47:03 +000034#include "llvm/Object/MachO.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000035#include "llvm/Object/ObjectFile.h"
Michael J. Spencer27781b72011-10-08 00:18:30 +000036#include "llvm/Support/Casting.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000037#include "llvm/Support/CommandLine.h"
38#include "llvm/Support/Debug.h"
Michael J. Spencer27781b72011-10-08 00:18:30 +000039#include "llvm/Support/FileSystem.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000040#include "llvm/Support/Format.h"
Benjamin Kramer853b0fd2011-07-25 23:04:36 +000041#include "llvm/Support/GraphWriter.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000042#include "llvm/Support/Host.h"
43#include "llvm/Support/ManagedStatic.h"
44#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000045#include "llvm/Support/MemoryObject.h"
46#include "llvm/Support/PrettyStackTrace.h"
47#include "llvm/Support/Signals.h"
48#include "llvm/Support/SourceMgr.h"
Evan Cheng3e74d6f2011-08-24 18:08:43 +000049#include "llvm/Support/TargetRegistry.h"
50#include "llvm/Support/TargetSelect.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000051#include "llvm/Support/raw_ostream.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000052#include "llvm/Support/system_error.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000053#include <algorithm>
Benjamin Kramer81bbdfd2012-03-23 11:49:32 +000054#include <cctype>
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000055#include <cstring>
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000056using namespace llvm;
57using namespace object;
58
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000059static cl::list<std::string>
60InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000061
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000062static cl::opt<bool>
63Disassemble("disassemble",
64 cl::desc("Display assembler mnemonics for the machine instructions"));
65static cl::alias
66Disassembled("d", cl::desc("Alias for --disassemble"),
67 cl::aliasopt(Disassemble));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000068
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000069static cl::opt<bool>
Michael J. Spencer27781b72011-10-08 00:18:30 +000070Relocations("r", cl::desc("Display the relocation entries in the file"));
71
72static cl::opt<bool>
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +000073SectionContents("s", cl::desc("Display the content of each section"));
74
75static cl::opt<bool>
Michael J. Spencer22ff0f32011-10-18 19:32:17 +000076SymbolTable("t", cl::desc("Display the symbol table"));
77
78static cl::opt<bool>
Rafael Espindolacef81b32012-12-21 03:47:03 +000079MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000080static cl::alias
Rafael Espindolacef81b32012-12-21 03:47:03 +000081MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
Benjamin Kramer685a2502011-07-20 19:37:35 +000082
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000083cl::opt<std::string>
84llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
85 "see -version for available targets"));
86
87cl::opt<std::string>
88llvm::ArchName("arch", cl::desc("Target arch to disassemble for, "
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000089 "see -version for available targets"));
90
Nick Lewycky023bb152011-10-10 21:21:34 +000091static cl::opt<bool>
92SectionHeaders("section-headers", cl::desc("Display summaries of the headers "
93 "for each section."));
94static cl::alias
95SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
96 cl::aliasopt(SectionHeaders));
97static cl::alias
98SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
99 cl::aliasopt(SectionHeaders));
100
Jack Carterfd6d1652012-08-28 19:24:49 +0000101static cl::list<std::string>
102MAttrs("mattr",
103 cl::CommaSeparated,
104 cl::desc("Target specific attributes"),
105 cl::value_desc("a1,+a2,-a3,..."));
106
Eli Bendersky8b9da532012-11-20 22:57:02 +0000107static cl::opt<bool>
108NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling instructions, "
109 "do not print the instruction bytes."));
110
Michael J. Spencereef7b622012-12-05 20:12:35 +0000111static cl::opt<bool>
112UnwindInfo("unwind-info", cl::desc("Display unwind information"));
113
114static cl::alias
115UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
116 cl::aliasopt(UnwindInfo));
117
Michael J. Spencerb2c064c2013-01-06 03:56:49 +0000118static cl::opt<bool>
119PrivateHeaders("private-headers",
120 cl::desc("Display format specific file headers"));
121
122static cl::alias
123PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
124 cl::aliasopt(PrivateHeaders));
125
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000126static StringRef ToolName;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000127
Michael J. Spencereef7b622012-12-05 20:12:35 +0000128bool llvm::error(error_code ec) {
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000129 if (!ec) return false;
Michael J. Spencer25b15772011-06-25 17:55:23 +0000130
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000131 outs() << ToolName << ": error reading file: " << ec.message() << ".\n";
132 outs().flush();
133 return true;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000134}
135
Jim Grosbach3f5d1a22012-08-07 17:53:14 +0000136static const Target *getTarget(const ObjectFile *Obj = NULL) {
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000137 // Figure out the target triple.
Kevin Enderby9ed9e5d2012-05-08 23:38:45 +0000138 llvm::Triple TheTriple("unknown-unknown-unknown");
Michael J. Spencerd11699d2011-01-20 07:22:04 +0000139 if (TripleName.empty()) {
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000140 if (Obj)
Kevin Enderby9ed9e5d2012-05-08 23:38:45 +0000141 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
Michael J. Spencerd11699d2011-01-20 07:22:04 +0000142 } else
Kevin Enderby9ed9e5d2012-05-08 23:38:45 +0000143 TheTriple.setTriple(Triple::normalize(TripleName));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000144
145 // Get the target specific parser.
146 std::string Error;
Kevin Enderby9ed9e5d2012-05-08 23:38:45 +0000147 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
148 Error);
149 if (!TheTarget) {
150 errs() << ToolName << ": " << Error;
151 return 0;
152 }
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000153
Kevin Enderby9ed9e5d2012-05-08 23:38:45 +0000154 // Update the triple name and return the found target.
155 TripleName = TheTriple.getTriple();
156 return TheTarget;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000157}
158
David Blaikie2d24e2a2011-12-20 02:50:00 +0000159void llvm::StringRefMemoryObject::anchor() { }
160
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000161void llvm::DumpBytes(StringRef bytes) {
162 static const char hex_rep[] = "0123456789abcdef";
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000163 // FIXME: The real way to do this is to figure out the longest instruction
164 // and align to that size before printing. I'll fix this when I get
165 // around to outputting relocations.
166 // 15 is the longest x86 instruction
167 // 3 is for the hex rep of a byte + a space.
168 // 1 is for the null terminator.
169 enum { OutputSize = (15 * 3) + 1 };
170 char output[OutputSize];
171
172 assert(bytes.size() <= 15
173 && "DumpBytes only supports instructions of up to 15 bytes");
174 memset(output, ' ', sizeof(output));
175 unsigned index = 0;
176 for (StringRef::iterator i = bytes.begin(),
177 e = bytes.end(); i != e; ++i) {
178 output[index] = hex_rep[(*i & 0xF0) >> 4];
179 output[index + 1] = hex_rep[*i & 0xF];
180 index += 3;
181 }
182
183 output[sizeof(output) - 1] = 0;
184 outs() << output;
185}
186
Michael J. Spencereef7b622012-12-05 20:12:35 +0000187bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
Michael J. Spencer942eb002011-10-13 22:17:18 +0000188 uint64_t a_addr, b_addr;
189 if (error(a.getAddress(a_addr))) return false;
190 if (error(b.getAddress(b_addr))) return false;
191 return a_addr < b_addr;
192}
193
194static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Jim Grosbach3f5d1a22012-08-07 17:53:14 +0000195 const Target *TheTarget = getTarget(Obj);
196 // getTarget() will have already issued a diagnostic if necessary, so
197 // just bail here if it failed.
198 if (!TheTarget)
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000199 return;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000200
Jack Carterfd6d1652012-08-28 19:24:49 +0000201 // Package up features to be passed to target/subtarget
202 std::string FeaturesStr;
203 if (MAttrs.size()) {
204 SubtargetFeatures Features;
205 for (unsigned i = 0; i != MAttrs.size(); ++i)
206 Features.AddFeature(MAttrs[i]);
207 FeaturesStr = Features.getString();
208 }
209
Michael J. Spencer25b15772011-06-25 17:55:23 +0000210 error_code ec;
Michael J. Spencer4344b1e2011-10-07 19:25:32 +0000211 for (section_iterator i = Obj->begin_sections(),
Michael J. Spencer27781b72011-10-08 00:18:30 +0000212 e = Obj->end_sections();
213 i != e; i.increment(ec)) {
Michael J. Spencer25b15772011-06-25 17:55:23 +0000214 if (error(ec)) break;
215 bool text;
216 if (error(i->isText(text))) break;
217 if (!text) continue;
218
Michael J. Spencer942eb002011-10-13 22:17:18 +0000219 uint64_t SectionAddr;
220 if (error(i->getAddress(SectionAddr))) break;
221
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000222 // Make a list of all the symbols in this section.
223 std::vector<std::pair<uint64_t, StringRef> > Symbols;
Michael J. Spencer4344b1e2011-10-07 19:25:32 +0000224 for (symbol_iterator si = Obj->begin_symbols(),
Michael J. Spencer27781b72011-10-08 00:18:30 +0000225 se = Obj->end_symbols();
226 si != se; si.increment(ec)) {
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000227 bool contains;
228 if (!error(i->containsSymbol(*si, contains)) && contains) {
229 uint64_t Address;
Danil Malyshevb0436a72011-11-29 17:40:10 +0000230 if (error(si->getAddress(Address))) break;
Cameron Zwarichaab21912012-02-03 04:13:37 +0000231 Address -= SectionAddr;
232
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000233 StringRef Name;
234 if (error(si->getName(Name))) break;
235 Symbols.push_back(std::make_pair(Address, Name));
236 }
237 }
238
239 // Sort the symbols by address, just in case they didn't come in that way.
240 array_pod_sort(Symbols.begin(), Symbols.end());
241
Michael J. Spencer942eb002011-10-13 22:17:18 +0000242 // Make a list of all the relocations for this section.
243 std::vector<RelocationRef> Rels;
244 if (InlineRelocs) {
245 for (relocation_iterator ri = i->begin_relocations(),
246 re = i->end_relocations();
Jim Grosbach3f5d1a22012-08-07 17:53:14 +0000247 ri != re; ri.increment(ec)) {
Michael J. Spencer942eb002011-10-13 22:17:18 +0000248 if (error(ec)) break;
249 Rels.push_back(*ri);
250 }
251 }
252
253 // Sort relocations by address.
254 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
255
Rafael Espindolacef81b32012-12-21 03:47:03 +0000256 StringRef SegmentName = "";
257 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
258 DataRefImpl DR = i->getRawDataRefImpl();
259 if (error(MachO->getSectionFinalSegmentName(DR, SegmentName)))
260 break;
261 }
Michael J. Spencer25b15772011-06-25 17:55:23 +0000262 StringRef name;
263 if (error(i->getName(name))) break;
Rafael Espindolacef81b32012-12-21 03:47:03 +0000264 outs() << "Disassembly of section ";
265 if (!SegmentName.empty())
266 outs() << SegmentName << ",";
267 outs() << name << ':';
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000268
269 // If the section has no symbols just insert a dummy one and disassemble
270 // the whole section.
271 if (Symbols.empty())
272 Symbols.push_back(std::make_pair(0, name));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000273
274 // Set up disassembler.
Evan Cheng1abf2cb2011-07-14 23:50:31 +0000275 OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000276
277 if (!AsmInfo) {
278 errs() << "error: no assembly info for target " << TripleName << "\n";
279 return;
280 }
281
Michael J. Spencer27781b72011-10-08 00:18:30 +0000282 OwningPtr<const MCSubtargetInfo> STI(
Jack Carterfd6d1652012-08-28 19:24:49 +0000283 TheTarget->createMCSubtargetInfo(TripleName, "", FeaturesStr));
James Molloyb9505852011-09-07 17:24:38 +0000284
285 if (!STI) {
286 errs() << "error: no subtarget info for target " << TripleName << "\n";
287 return;
288 }
289
Owen Anderson10c044e2011-10-27 21:55:13 +0000290 OwningPtr<const MCDisassembler> DisAsm(
Michael J. Spencer27781b72011-10-08 00:18:30 +0000291 TheTarget->createMCDisassembler(*STI));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000292 if (!DisAsm) {
293 errs() << "error: no disassembler for target " << TripleName << "\n";
294 return;
295 }
296
Jim Grosbachc6449b62012-03-05 19:33:20 +0000297 OwningPtr<const MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
298 if (!MRI) {
299 errs() << "error: no register info for target " << TripleName << "\n";
300 return;
301 }
302
Craig Topper17463b32012-04-02 06:09:36 +0000303 OwningPtr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
304 if (!MII) {
305 errs() << "error: no instruction info for target " << TripleName << "\n";
306 return;
307 }
308
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000309 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
310 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Craig Topper17463b32012-04-02 06:09:36 +0000311 AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000312 if (!IP) {
Michael J. Spencer27781b72011-10-08 00:18:30 +0000313 errs() << "error: no instruction printer for target " << TripleName
314 << '\n';
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000315 return;
316 }
317
Michael J. Spencer25b15772011-06-25 17:55:23 +0000318 StringRef Bytes;
319 if (error(i->getContents(Bytes))) break;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000320 StringRefMemoryObject memoryObject(Bytes);
321 uint64_t Size;
322 uint64_t Index;
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000323 uint64_t SectSize;
324 if (error(i->getSize(SectSize))) break;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000325
Michael J. Spencer942eb002011-10-13 22:17:18 +0000326 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
327 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000328 // Disassemble symbol by symbol.
329 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
330 uint64_t Start = Symbols[si].first;
Michael J. Spencer178dbd42011-10-13 20:37:08 +0000331 uint64_t End;
332 // The end is either the size of the section or the beginning of the next
333 // symbol.
334 if (si == se - 1)
335 End = SectSize;
336 // Make sure this symbol takes up space.
337 else if (Symbols[si + 1].first != Start)
338 End = Symbols[si + 1].first - 1;
339 else
340 // This symbol has the same address as the next symbol. Skip it.
341 continue;
342
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000343 outs() << '\n' << Symbols[si].second << ":\n";
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000344
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000345#ifndef NDEBUG
346 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
347#else
348 raw_ostream &DebugOut = nulls();
349#endif
350
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000351 for (Index = Start; Index < End; Index += Size) {
352 MCInst Inst;
Owen Anderson98c5dda2011-09-15 23:38:46 +0000353
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000354 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
355 DebugOut, nulls())) {
Eli Bendersky8b9da532012-11-20 22:57:02 +0000356 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
357 if (!NoShowRawInsn) {
358 outs() << "\t";
359 DumpBytes(StringRef(Bytes.data() + Index, Size));
360 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000361 IP->printInst(&Inst, outs(), "");
362 outs() << "\n";
363 } else {
364 errs() << ToolName << ": warning: invalid instruction encoding\n";
365 if (Size == 0)
366 Size = 1; // skip illegible bytes
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000367 }
Michael J. Spencer942eb002011-10-13 22:17:18 +0000368
369 // Print relocation for instruction.
370 while (rel_cur != rel_end) {
Owen Anderson0685e942011-10-25 20:35:53 +0000371 bool hidden = false;
Michael J. Spencer942eb002011-10-13 22:17:18 +0000372 uint64_t addr;
373 SmallString<16> name;
374 SmallString<32> val;
Owen Anderson0685e942011-10-25 20:35:53 +0000375
376 // If this relocation is hidden, skip it.
377 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
378 if (hidden) goto skip_print_rel;
379
Michael J. Spencer942eb002011-10-13 22:17:18 +0000380 if (error(rel_cur->getAddress(addr))) goto skip_print_rel;
381 // Stop when rel_cur's address is past the current instruction.
Owen Anderson34749ce2011-10-25 20:15:39 +0000382 if (addr >= Index + Size) break;
Michael J. Spencer942eb002011-10-13 22:17:18 +0000383 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
384 if (error(rel_cur->getValueString(val))) goto skip_print_rel;
385
Benjamin Kramer51cf8662012-03-10 02:04:38 +0000386 outs() << format("\t\t\t%8" PRIx64 ": ", SectionAddr + addr) << name
387 << "\t" << val << "\n";
Michael J. Spencer942eb002011-10-13 22:17:18 +0000388
389 skip_print_rel:
390 ++rel_cur;
391 }
Benjamin Kramer685a2502011-07-20 19:37:35 +0000392 }
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000393 }
394 }
395}
396
Michael J. Spencer27781b72011-10-08 00:18:30 +0000397static void PrintRelocations(const ObjectFile *o) {
398 error_code ec;
399 for (section_iterator si = o->begin_sections(), se = o->end_sections();
400 si != se; si.increment(ec)){
401 if (error(ec)) return;
402 if (si->begin_relocations() == si->end_relocations())
403 continue;
404 StringRef secname;
405 if (error(si->getName(secname))) continue;
406 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
407 for (relocation_iterator ri = si->begin_relocations(),
408 re = si->end_relocations();
409 ri != re; ri.increment(ec)) {
410 if (error(ec)) return;
411
Owen Anderson0685e942011-10-25 20:35:53 +0000412 bool hidden;
Michael J. Spencer27781b72011-10-08 00:18:30 +0000413 uint64_t address;
414 SmallString<32> relocname;
415 SmallString<32> valuestr;
Owen Anderson0685e942011-10-25 20:35:53 +0000416 if (error(ri->getHidden(hidden))) continue;
417 if (hidden) continue;
Michael J. Spencer27781b72011-10-08 00:18:30 +0000418 if (error(ri->getTypeName(relocname))) continue;
419 if (error(ri->getAddress(address))) continue;
420 if (error(ri->getValueString(valuestr))) continue;
421 outs() << address << " " << relocname << " " << valuestr << "\n";
422 }
423 outs() << "\n";
424 }
425}
426
Nick Lewycky023bb152011-10-10 21:21:34 +0000427static void PrintSectionHeaders(const ObjectFile *o) {
428 outs() << "Sections:\n"
429 "Idx Name Size Address Type\n";
430 error_code ec;
431 unsigned i = 0;
432 for (section_iterator si = o->begin_sections(), se = o->end_sections();
433 si != se; si.increment(ec)) {
434 if (error(ec)) return;
435 StringRef Name;
436 if (error(si->getName(Name))) return;
437 uint64_t Address;
438 if (error(si->getAddress(Address))) return;
439 uint64_t Size;
440 if (error(si->getSize(Size))) return;
441 bool Text, Data, BSS;
442 if (error(si->isText(Text))) return;
443 if (error(si->isData(Data))) return;
444 if (error(si->isBSS(BSS))) return;
445 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer14a5f462011-10-13 20:37:20 +0000446 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
Michael J. Spencer27b2b1b2013-01-10 22:40:50 +0000447 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n",
Benjamin Kramer51cf8662012-03-10 02:04:38 +0000448 i, Name.str().c_str(), Size, Address, Type.c_str());
Nick Lewycky023bb152011-10-10 21:21:34 +0000449 ++i;
450 }
451}
452
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +0000453static void PrintSectionContents(const ObjectFile *o) {
454 error_code ec;
455 for (section_iterator si = o->begin_sections(),
456 se = o->end_sections();
457 si != se; si.increment(ec)) {
458 if (error(ec)) return;
459 StringRef Name;
460 StringRef Contents;
461 uint64_t BaseAddr;
462 if (error(si->getName(Name))) continue;
463 if (error(si->getContents(Contents))) continue;
464 if (error(si->getAddress(BaseAddr))) continue;
465
466 outs() << "Contents of section " << Name << ":\n";
467
468 // Dump out the content as hex and printable ascii characters.
469 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer51cf8662012-03-10 02:04:38 +0000470 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +0000471 // Dump line of hex.
472 for (std::size_t i = 0; i < 16; ++i) {
473 if (i != 0 && i % 4 == 0)
474 outs() << ' ';
475 if (addr + i < end)
476 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
477 << hexdigit(Contents[addr + i] & 0xF, true);
478 else
479 outs() << " ";
480 }
481 // Print ascii.
482 outs() << " ";
483 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
Guy Benyei87d0b9e2013-02-12 21:21:59 +0000484 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +0000485 outs() << Contents[addr + i];
486 else
487 outs() << ".";
488 }
489 outs() << "\n";
490 }
491 }
492}
493
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000494static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
495 const coff_file_header *header;
496 if (error(coff->getHeader(header))) return;
497 int aux_count = 0;
498 const coff_symbol *symbol = 0;
499 for (int i = 0, e = header->NumberOfSymbols; i != e; ++i) {
500 if (aux_count--) {
501 // Figure out which type of aux this is.
502 if (symbol->StorageClass == COFF::IMAGE_SYM_CLASS_STATIC
503 && symbol->Value == 0) { // Section definition.
504 const coff_aux_section_definition *asd;
505 if (error(coff->getAuxSymbol<coff_aux_section_definition>(i, asd)))
506 return;
507 outs() << "AUX "
508 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
509 , unsigned(asd->Length)
510 , unsigned(asd->NumberOfRelocations)
511 , unsigned(asd->NumberOfLinenumbers)
512 , unsigned(asd->CheckSum))
513 << format("assoc %d comdat %d\n"
514 , unsigned(asd->Number)
515 , unsigned(asd->Selection));
Jim Grosbach3f5d1a22012-08-07 17:53:14 +0000516 } else
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000517 outs() << "AUX Unknown\n";
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000518 } else {
519 StringRef name;
520 if (error(coff->getSymbol(i, symbol))) return;
521 if (error(coff->getSymbolName(symbol, name))) return;
522 outs() << "[" << format("%2d", i) << "]"
523 << "(sec " << format("%2d", int(symbol->SectionNumber)) << ")"
524 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
525 << "(ty " << format("%3x", unsigned(symbol->Type)) << ")"
526 << "(scl " << format("%3x", unsigned(symbol->StorageClass)) << ") "
527 << "(nx " << unsigned(symbol->NumberOfAuxSymbols) << ") "
528 << "0x" << format("%08x", unsigned(symbol->Value)) << " "
529 << name << "\n";
530 aux_count = symbol->NumberOfAuxSymbols;
531 }
532 }
533}
534
535static void PrintSymbolTable(const ObjectFile *o) {
536 outs() << "SYMBOL TABLE:\n";
537
538 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o))
539 PrintCOFFSymbolTable(coff);
540 else {
541 error_code ec;
542 for (symbol_iterator si = o->begin_symbols(),
543 se = o->end_symbols(); si != se; si.increment(ec)) {
544 if (error(ec)) return;
545 StringRef Name;
Danil Malyshevb0436a72011-11-29 17:40:10 +0000546 uint64_t Address;
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000547 SymbolRef::Type Type;
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000548 uint64_t Size;
David Meyerc46255a2012-02-28 23:47:53 +0000549 uint32_t Flags;
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000550 section_iterator Section = o->end_sections();
551 if (error(si->getName(Name))) continue;
Danil Malyshevb0436a72011-11-29 17:40:10 +0000552 if (error(si->getAddress(Address))) continue;
David Meyerc46255a2012-02-28 23:47:53 +0000553 if (error(si->getFlags(Flags))) continue;
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000554 if (error(si->getType(Type))) continue;
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000555 if (error(si->getSize(Size))) continue;
556 if (error(si->getSection(Section))) continue;
557
David Meyerc46255a2012-02-28 23:47:53 +0000558 bool Global = Flags & SymbolRef::SF_Global;
559 bool Weak = Flags & SymbolRef::SF_Weak;
560 bool Absolute = Flags & SymbolRef::SF_Absolute;
561
Danil Malyshevb0436a72011-11-29 17:40:10 +0000562 if (Address == UnknownAddressOrSize)
563 Address = 0;
564 if (Size == UnknownAddressOrSize)
565 Size = 0;
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000566 char GlobLoc = ' ';
David Meyer2c677272012-02-29 02:11:55 +0000567 if (Type != SymbolRef::ST_Unknown)
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000568 GlobLoc = Global ? 'g' : 'l';
569 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
570 ? 'd' : ' ';
571 char FileFunc = ' ';
572 if (Type == SymbolRef::ST_File)
573 FileFunc = 'f';
574 else if (Type == SymbolRef::ST_Function)
575 FileFunc = 'F';
576
Michael J. Spencer27b2b1b2013-01-10 22:40:50 +0000577 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
578 "%08" PRIx64;
579
580 outs() << format(Fmt, Address) << " "
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000581 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
582 << (Weak ? 'w' : ' ') // Weak?
583 << ' ' // Constructor. Not supported yet.
584 << ' ' // Warning. Not supported yet.
585 << ' ' // Indirect reference to another symbol.
586 << Debug // Debugging (d) or dynamic (D) symbol.
587 << FileFunc // Name of function (F), file (f) or object (O).
588 << ' ';
589 if (Absolute)
590 outs() << "*ABS*";
591 else if (Section == o->end_sections())
592 outs() << "*UND*";
593 else {
Rafael Espindolacef81b32012-12-21 03:47:03 +0000594 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(o)) {
595 StringRef SegmentName;
596 DataRefImpl DR = Section->getRawDataRefImpl();
597 if (error(MachO->getSectionFinalSegmentName(DR, SegmentName)))
598 SegmentName = "";
599 outs() << SegmentName << ",";
600 }
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000601 StringRef SectionName;
602 if (error(Section->getName(SectionName)))
603 SectionName = "";
604 outs() << SectionName;
605 }
606 outs() << '\t'
Benjamin Kramer51cf8662012-03-10 02:04:38 +0000607 << format("%08" PRIx64 " ", Size)
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000608 << Name
609 << '\n';
610 }
611 }
612}
613
Michael J. Spencereef7b622012-12-05 20:12:35 +0000614static void PrintUnwindInfo(const ObjectFile *o) {
615 outs() << "Unwind info:\n\n";
616
617 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
618 printCOFFUnwindInfo(coff);
619 } else {
620 // TODO: Extract DWARF dump tool to objdump.
621 errs() << "This operation is only currently supported "
622 "for COFF object files.\n";
623 return;
624 }
625}
626
Michael J. Spencer27781b72011-10-08 00:18:30 +0000627static void DumpObject(const ObjectFile *o) {
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +0000628 outs() << '\n';
629 outs() << o->getFileName()
630 << ":\tfile format " << o->getFileFormatName() << "\n\n";
631
Michael J. Spencer27781b72011-10-08 00:18:30 +0000632 if (Disassemble)
Michael J. Spencer942eb002011-10-13 22:17:18 +0000633 DisassembleObject(o, Relocations);
634 if (Relocations && !Disassemble)
Michael J. Spencer27781b72011-10-08 00:18:30 +0000635 PrintRelocations(o);
Nick Lewycky023bb152011-10-10 21:21:34 +0000636 if (SectionHeaders)
637 PrintSectionHeaders(o);
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +0000638 if (SectionContents)
639 PrintSectionContents(o);
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000640 if (SymbolTable)
641 PrintSymbolTable(o);
Michael J. Spencereef7b622012-12-05 20:12:35 +0000642 if (UnwindInfo)
643 PrintUnwindInfo(o);
Michael J. Spencerb2c064c2013-01-06 03:56:49 +0000644 if (PrivateHeaders && o->isELF())
645 printELFFileHeader(o);
Michael J. Spencer27781b72011-10-08 00:18:30 +0000646}
647
648/// @brief Dump each object file in \a a;
649static void DumpArchive(const Archive *a) {
650 for (Archive::child_iterator i = a->begin_children(),
651 e = a->end_children(); i != e; ++i) {
652 OwningPtr<Binary> child;
653 if (error_code ec = i->getAsBinary(child)) {
Michael J. Spencerf81285c2011-11-16 01:24:41 +0000654 // Ignore non-object files.
655 if (ec != object_error::invalid_file_type)
656 errs() << ToolName << ": '" << a->getFileName() << "': " << ec.message()
657 << ".\n";
Michael J. Spencer27781b72011-10-08 00:18:30 +0000658 continue;
659 }
660 if (ObjectFile *o = dyn_cast<ObjectFile>(child.get()))
661 DumpObject(o);
662 else
663 errs() << ToolName << ": '" << a->getFileName() << "': "
664 << "Unrecognized file type.\n";
665 }
666}
667
668/// @brief Open file and figure out how to dump it.
669static void DumpInput(StringRef file) {
670 // If file isn't stdin, check that it exists.
671 if (file != "-" && !sys::fs::exists(file)) {
672 errs() << ToolName << ": '" << file << "': " << "No such file\n";
673 return;
674 }
675
Rafael Espindolacef81b32012-12-21 03:47:03 +0000676 if (MachOOpt && Disassemble) {
Michael J. Spencer27781b72011-10-08 00:18:30 +0000677 DisassembleInputMachO(file);
678 return;
679 }
680
681 // Attempt to open the binary.
682 OwningPtr<Binary> binary;
683 if (error_code ec = createBinary(file, binary)) {
684 errs() << ToolName << ": '" << file << "': " << ec.message() << ".\n";
685 return;
686 }
687
Jim Grosbach3f5d1a22012-08-07 17:53:14 +0000688 if (Archive *a = dyn_cast<Archive>(binary.get()))
Michael J. Spencer27781b72011-10-08 00:18:30 +0000689 DumpArchive(a);
Jim Grosbach3f5d1a22012-08-07 17:53:14 +0000690 else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get()))
Michael J. Spencer27781b72011-10-08 00:18:30 +0000691 DumpObject(o);
Jim Grosbach3f5d1a22012-08-07 17:53:14 +0000692 else
Michael J. Spencer27781b72011-10-08 00:18:30 +0000693 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
Michael J. Spencer27781b72011-10-08 00:18:30 +0000694}
695
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000696int main(int argc, char **argv) {
697 // Print a stack trace if we signal out.
698 sys::PrintStackTraceOnErrorSignal();
699 PrettyStackTraceProgram X(argc, argv);
700 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
701
702 // Initialize targets and assembly printers/parsers.
703 llvm::InitializeAllTargetInfos();
Evan Chenge78085a2011-07-22 21:58:54 +0000704 llvm::InitializeAllTargetMCs();
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000705 llvm::InitializeAllAsmParsers();
706 llvm::InitializeAllDisassemblers();
707
Pete Cooperff204962012-05-03 23:20:10 +0000708 // Register the target printer for --version.
709 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
710
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000711 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
712 TripleName = Triple::normalize(TripleName);
713
714 ToolName = argv[0];
715
716 // Defaults to a.out if no filenames specified.
717 if (InputFilenames.size() == 0)
718 InputFilenames.push_back("a.out");
719
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000720 if (!Disassemble
721 && !Relocations
722 && !SectionHeaders
723 && !SectionContents
Michael J. Spencereef7b622012-12-05 20:12:35 +0000724 && !SymbolTable
Michael J. Spencerb2c064c2013-01-06 03:56:49 +0000725 && !UnwindInfo
726 && !PrivateHeaders) {
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000727 cl::PrintHelpMessage();
728 return 2;
729 }
730
Michael J. Spencer27781b72011-10-08 00:18:30 +0000731 std::for_each(InputFilenames.begin(), InputFilenames.end(),
732 DumpInput);
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000733
734 return 0;
735}