blob: 5a0519ddc11d9843fcfc3525d22cad1ab70a2b86 [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
Rafael Espindolada2a2372013-04-13 01:45:40 +0000194StringRef
195getSectionFinalSegmentName(const MachOObjectFileBase *MachO, DataRefImpl DR) {
196 if (const MachOObjectFileLE *O = dyn_cast<MachOObjectFileLE>(MachO))
197 return O->getSectionFinalSegmentName(DR);
198 const MachOObjectFileBE *O = dyn_cast<MachOObjectFileBE>(MachO);
199 return O->getSectionFinalSegmentName(DR);
200}
201
Michael J. Spencer942eb002011-10-13 22:17:18 +0000202static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Jim Grosbach3f5d1a22012-08-07 17:53:14 +0000203 const Target *TheTarget = getTarget(Obj);
204 // getTarget() will have already issued a diagnostic if necessary, so
205 // just bail here if it failed.
206 if (!TheTarget)
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000207 return;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000208
Jack Carterfd6d1652012-08-28 19:24:49 +0000209 // Package up features to be passed to target/subtarget
210 std::string FeaturesStr;
211 if (MAttrs.size()) {
212 SubtargetFeatures Features;
213 for (unsigned i = 0; i != MAttrs.size(); ++i)
214 Features.AddFeature(MAttrs[i]);
215 FeaturesStr = Features.getString();
216 }
217
Michael J. Spencer25b15772011-06-25 17:55:23 +0000218 error_code ec;
Michael J. Spencer4344b1e2011-10-07 19:25:32 +0000219 for (section_iterator i = Obj->begin_sections(),
Michael J. Spencer27781b72011-10-08 00:18:30 +0000220 e = Obj->end_sections();
221 i != e; i.increment(ec)) {
Michael J. Spencer25b15772011-06-25 17:55:23 +0000222 if (error(ec)) break;
223 bool text;
224 if (error(i->isText(text))) break;
225 if (!text) continue;
226
Michael J. Spencer942eb002011-10-13 22:17:18 +0000227 uint64_t SectionAddr;
228 if (error(i->getAddress(SectionAddr))) break;
229
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000230 // Make a list of all the symbols in this section.
231 std::vector<std::pair<uint64_t, StringRef> > Symbols;
Michael J. Spencer4344b1e2011-10-07 19:25:32 +0000232 for (symbol_iterator si = Obj->begin_symbols(),
Michael J. Spencer27781b72011-10-08 00:18:30 +0000233 se = Obj->end_symbols();
234 si != se; si.increment(ec)) {
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000235 bool contains;
236 if (!error(i->containsSymbol(*si, contains)) && contains) {
237 uint64_t Address;
Danil Malyshevb0436a72011-11-29 17:40:10 +0000238 if (error(si->getAddress(Address))) break;
Eric Christopher99ff2ba2013-04-03 18:31:23 +0000239 if (Address == UnknownAddressOrSize) continue;
Cameron Zwarichaab21912012-02-03 04:13:37 +0000240 Address -= SectionAddr;
241
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000242 StringRef Name;
243 if (error(si->getName(Name))) break;
244 Symbols.push_back(std::make_pair(Address, Name));
245 }
246 }
247
248 // Sort the symbols by address, just in case they didn't come in that way.
249 array_pod_sort(Symbols.begin(), Symbols.end());
250
Michael J. Spencer942eb002011-10-13 22:17:18 +0000251 // Make a list of all the relocations for this section.
252 std::vector<RelocationRef> Rels;
253 if (InlineRelocs) {
254 for (relocation_iterator ri = i->begin_relocations(),
255 re = i->end_relocations();
Jim Grosbach3f5d1a22012-08-07 17:53:14 +0000256 ri != re; ri.increment(ec)) {
Michael J. Spencer942eb002011-10-13 22:17:18 +0000257 if (error(ec)) break;
258 Rels.push_back(*ri);
259 }
260 }
261
262 // Sort relocations by address.
263 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
264
Rafael Espindolacef81b32012-12-21 03:47:03 +0000265 StringRef SegmentName = "";
Rafael Espindolada2a2372013-04-13 01:45:40 +0000266 if (const MachOObjectFileBase *MachO =
267 dyn_cast<const MachOObjectFileBase>(Obj)) {
Rafael Espindolacef81b32012-12-21 03:47:03 +0000268 DataRefImpl DR = i->getRawDataRefImpl();
Rafael Espindolada2a2372013-04-13 01:45:40 +0000269 SegmentName = getSectionFinalSegmentName(MachO, DR);
Rafael Espindolacef81b32012-12-21 03:47:03 +0000270 }
Michael J. Spencer25b15772011-06-25 17:55:23 +0000271 StringRef name;
272 if (error(i->getName(name))) break;
Rafael Espindolacef81b32012-12-21 03:47:03 +0000273 outs() << "Disassembly of section ";
274 if (!SegmentName.empty())
275 outs() << SegmentName << ",";
276 outs() << name << ':';
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000277
278 // If the section has no symbols just insert a dummy one and disassemble
279 // the whole section.
280 if (Symbols.empty())
281 Symbols.push_back(std::make_pair(0, name));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000282
283 // Set up disassembler.
Evan Cheng1abf2cb2011-07-14 23:50:31 +0000284 OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000285
286 if (!AsmInfo) {
287 errs() << "error: no assembly info for target " << TripleName << "\n";
288 return;
289 }
290
Michael J. Spencer27781b72011-10-08 00:18:30 +0000291 OwningPtr<const MCSubtargetInfo> STI(
Jack Carterfd6d1652012-08-28 19:24:49 +0000292 TheTarget->createMCSubtargetInfo(TripleName, "", FeaturesStr));
James Molloyb9505852011-09-07 17:24:38 +0000293
294 if (!STI) {
295 errs() << "error: no subtarget info for target " << TripleName << "\n";
296 return;
297 }
298
Owen Anderson10c044e2011-10-27 21:55:13 +0000299 OwningPtr<const MCDisassembler> DisAsm(
Michael J. Spencer27781b72011-10-08 00:18:30 +0000300 TheTarget->createMCDisassembler(*STI));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000301 if (!DisAsm) {
302 errs() << "error: no disassembler for target " << TripleName << "\n";
303 return;
304 }
305
Jim Grosbachc6449b62012-03-05 19:33:20 +0000306 OwningPtr<const MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
307 if (!MRI) {
308 errs() << "error: no register info for target " << TripleName << "\n";
309 return;
310 }
311
Craig Topper17463b32012-04-02 06:09:36 +0000312 OwningPtr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
313 if (!MII) {
314 errs() << "error: no instruction info for target " << TripleName << "\n";
315 return;
316 }
317
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000318 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
319 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Craig Topper17463b32012-04-02 06:09:36 +0000320 AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000321 if (!IP) {
Michael J. Spencer27781b72011-10-08 00:18:30 +0000322 errs() << "error: no instruction printer for target " << TripleName
323 << '\n';
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000324 return;
325 }
326
Michael J. Spencer25b15772011-06-25 17:55:23 +0000327 StringRef Bytes;
328 if (error(i->getContents(Bytes))) break;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000329 StringRefMemoryObject memoryObject(Bytes);
330 uint64_t Size;
331 uint64_t Index;
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000332 uint64_t SectSize;
333 if (error(i->getSize(SectSize))) break;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000334
Michael J. Spencer942eb002011-10-13 22:17:18 +0000335 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
336 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000337 // Disassemble symbol by symbol.
338 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
339 uint64_t Start = Symbols[si].first;
Michael J. Spencer178dbd42011-10-13 20:37:08 +0000340 uint64_t End;
341 // The end is either the size of the section or the beginning of the next
342 // symbol.
343 if (si == se - 1)
344 End = SectSize;
345 // Make sure this symbol takes up space.
346 else if (Symbols[si + 1].first != Start)
347 End = Symbols[si + 1].first - 1;
348 else
349 // This symbol has the same address as the next symbol. Skip it.
350 continue;
351
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000352 outs() << '\n' << Symbols[si].second << ":\n";
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000353
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000354#ifndef NDEBUG
355 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
356#else
357 raw_ostream &DebugOut = nulls();
358#endif
359
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000360 for (Index = Start; Index < End; Index += Size) {
361 MCInst Inst;
Owen Anderson98c5dda2011-09-15 23:38:46 +0000362
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000363 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
364 DebugOut, nulls())) {
Eli Bendersky8b9da532012-11-20 22:57:02 +0000365 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
366 if (!NoShowRawInsn) {
367 outs() << "\t";
368 DumpBytes(StringRef(Bytes.data() + Index, Size));
369 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000370 IP->printInst(&Inst, outs(), "");
371 outs() << "\n";
372 } else {
373 errs() << ToolName << ": warning: invalid instruction encoding\n";
374 if (Size == 0)
375 Size = 1; // skip illegible bytes
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000376 }
Michael J. Spencer942eb002011-10-13 22:17:18 +0000377
378 // Print relocation for instruction.
379 while (rel_cur != rel_end) {
Owen Anderson0685e942011-10-25 20:35:53 +0000380 bool hidden = false;
Michael J. Spencer942eb002011-10-13 22:17:18 +0000381 uint64_t addr;
382 SmallString<16> name;
383 SmallString<32> val;
Owen Anderson0685e942011-10-25 20:35:53 +0000384
385 // If this relocation is hidden, skip it.
386 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
387 if (hidden) goto skip_print_rel;
388
Michael J. Spencer942eb002011-10-13 22:17:18 +0000389 if (error(rel_cur->getAddress(addr))) goto skip_print_rel;
390 // Stop when rel_cur's address is past the current instruction.
Owen Anderson34749ce2011-10-25 20:15:39 +0000391 if (addr >= Index + Size) break;
Michael J. Spencer942eb002011-10-13 22:17:18 +0000392 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
393 if (error(rel_cur->getValueString(val))) goto skip_print_rel;
394
Benjamin Kramer51cf8662012-03-10 02:04:38 +0000395 outs() << format("\t\t\t%8" PRIx64 ": ", SectionAddr + addr) << name
396 << "\t" << val << "\n";
Michael J. Spencer942eb002011-10-13 22:17:18 +0000397
398 skip_print_rel:
399 ++rel_cur;
400 }
Benjamin Kramer685a2502011-07-20 19:37:35 +0000401 }
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000402 }
403 }
404}
405
Michael J. Spencer27781b72011-10-08 00:18:30 +0000406static void PrintRelocations(const ObjectFile *o) {
407 error_code ec;
408 for (section_iterator si = o->begin_sections(), se = o->end_sections();
409 si != se; si.increment(ec)){
410 if (error(ec)) return;
411 if (si->begin_relocations() == si->end_relocations())
412 continue;
413 StringRef secname;
414 if (error(si->getName(secname))) continue;
415 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
416 for (relocation_iterator ri = si->begin_relocations(),
417 re = si->end_relocations();
418 ri != re; ri.increment(ec)) {
419 if (error(ec)) return;
420
Owen Anderson0685e942011-10-25 20:35:53 +0000421 bool hidden;
Michael J. Spencer27781b72011-10-08 00:18:30 +0000422 uint64_t address;
423 SmallString<32> relocname;
424 SmallString<32> valuestr;
Owen Anderson0685e942011-10-25 20:35:53 +0000425 if (error(ri->getHidden(hidden))) continue;
426 if (hidden) continue;
Michael J. Spencer27781b72011-10-08 00:18:30 +0000427 if (error(ri->getTypeName(relocname))) continue;
428 if (error(ri->getAddress(address))) continue;
429 if (error(ri->getValueString(valuestr))) continue;
430 outs() << address << " " << relocname << " " << valuestr << "\n";
431 }
432 outs() << "\n";
433 }
434}
435
Nick Lewycky023bb152011-10-10 21:21:34 +0000436static void PrintSectionHeaders(const ObjectFile *o) {
437 outs() << "Sections:\n"
438 "Idx Name Size Address Type\n";
439 error_code ec;
440 unsigned i = 0;
441 for (section_iterator si = o->begin_sections(), se = o->end_sections();
442 si != se; si.increment(ec)) {
443 if (error(ec)) return;
444 StringRef Name;
445 if (error(si->getName(Name))) return;
446 uint64_t Address;
447 if (error(si->getAddress(Address))) return;
448 uint64_t Size;
449 if (error(si->getSize(Size))) return;
450 bool Text, Data, BSS;
451 if (error(si->isText(Text))) return;
452 if (error(si->isData(Data))) return;
453 if (error(si->isBSS(BSS))) return;
454 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer14a5f462011-10-13 20:37:20 +0000455 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
Michael J. Spencer27b2b1b2013-01-10 22:40:50 +0000456 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n",
Benjamin Kramer51cf8662012-03-10 02:04:38 +0000457 i, Name.str().c_str(), Size, Address, Type.c_str());
Nick Lewycky023bb152011-10-10 21:21:34 +0000458 ++i;
459 }
460}
461
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +0000462static void PrintSectionContents(const ObjectFile *o) {
463 error_code ec;
464 for (section_iterator si = o->begin_sections(),
465 se = o->end_sections();
466 si != se; si.increment(ec)) {
467 if (error(ec)) return;
468 StringRef Name;
469 StringRef Contents;
470 uint64_t BaseAddr;
471 if (error(si->getName(Name))) continue;
472 if (error(si->getContents(Contents))) continue;
473 if (error(si->getAddress(BaseAddr))) continue;
474
475 outs() << "Contents of section " << Name << ":\n";
476
477 // Dump out the content as hex and printable ascii characters.
478 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer51cf8662012-03-10 02:04:38 +0000479 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +0000480 // Dump line of hex.
481 for (std::size_t i = 0; i < 16; ++i) {
482 if (i != 0 && i % 4 == 0)
483 outs() << ' ';
484 if (addr + i < end)
485 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
486 << hexdigit(Contents[addr + i] & 0xF, true);
487 else
488 outs() << " ";
489 }
490 // Print ascii.
491 outs() << " ";
492 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
Guy Benyei87d0b9e2013-02-12 21:21:59 +0000493 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +0000494 outs() << Contents[addr + i];
495 else
496 outs() << ".";
497 }
498 outs() << "\n";
499 }
500 }
501}
502
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000503static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
504 const coff_file_header *header;
505 if (error(coff->getHeader(header))) return;
506 int aux_count = 0;
507 const coff_symbol *symbol = 0;
508 for (int i = 0, e = header->NumberOfSymbols; i != e; ++i) {
509 if (aux_count--) {
510 // Figure out which type of aux this is.
511 if (symbol->StorageClass == COFF::IMAGE_SYM_CLASS_STATIC
512 && symbol->Value == 0) { // Section definition.
513 const coff_aux_section_definition *asd;
514 if (error(coff->getAuxSymbol<coff_aux_section_definition>(i, asd)))
515 return;
516 outs() << "AUX "
517 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
518 , unsigned(asd->Length)
519 , unsigned(asd->NumberOfRelocations)
520 , unsigned(asd->NumberOfLinenumbers)
521 , unsigned(asd->CheckSum))
522 << format("assoc %d comdat %d\n"
523 , unsigned(asd->Number)
524 , unsigned(asd->Selection));
Jim Grosbach3f5d1a22012-08-07 17:53:14 +0000525 } else
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000526 outs() << "AUX Unknown\n";
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000527 } else {
528 StringRef name;
529 if (error(coff->getSymbol(i, symbol))) return;
530 if (error(coff->getSymbolName(symbol, name))) return;
531 outs() << "[" << format("%2d", i) << "]"
532 << "(sec " << format("%2d", int(symbol->SectionNumber)) << ")"
533 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
534 << "(ty " << format("%3x", unsigned(symbol->Type)) << ")"
535 << "(scl " << format("%3x", unsigned(symbol->StorageClass)) << ") "
536 << "(nx " << unsigned(symbol->NumberOfAuxSymbols) << ") "
537 << "0x" << format("%08x", unsigned(symbol->Value)) << " "
538 << name << "\n";
539 aux_count = symbol->NumberOfAuxSymbols;
540 }
541 }
542}
543
544static void PrintSymbolTable(const ObjectFile *o) {
545 outs() << "SYMBOL TABLE:\n";
546
547 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o))
548 PrintCOFFSymbolTable(coff);
549 else {
550 error_code ec;
551 for (symbol_iterator si = o->begin_symbols(),
552 se = o->end_symbols(); si != se; si.increment(ec)) {
553 if (error(ec)) return;
554 StringRef Name;
Danil Malyshevb0436a72011-11-29 17:40:10 +0000555 uint64_t Address;
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000556 SymbolRef::Type Type;
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000557 uint64_t Size;
David Meyerc46255a2012-02-28 23:47:53 +0000558 uint32_t Flags;
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000559 section_iterator Section = o->end_sections();
560 if (error(si->getName(Name))) continue;
Danil Malyshevb0436a72011-11-29 17:40:10 +0000561 if (error(si->getAddress(Address))) continue;
David Meyerc46255a2012-02-28 23:47:53 +0000562 if (error(si->getFlags(Flags))) continue;
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000563 if (error(si->getType(Type))) continue;
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000564 if (error(si->getSize(Size))) continue;
565 if (error(si->getSection(Section))) continue;
566
David Meyerc46255a2012-02-28 23:47:53 +0000567 bool Global = Flags & SymbolRef::SF_Global;
568 bool Weak = Flags & SymbolRef::SF_Weak;
569 bool Absolute = Flags & SymbolRef::SF_Absolute;
570
Danil Malyshevb0436a72011-11-29 17:40:10 +0000571 if (Address == UnknownAddressOrSize)
572 Address = 0;
573 if (Size == UnknownAddressOrSize)
574 Size = 0;
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000575 char GlobLoc = ' ';
David Meyer2c677272012-02-29 02:11:55 +0000576 if (Type != SymbolRef::ST_Unknown)
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000577 GlobLoc = Global ? 'g' : 'l';
578 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
579 ? 'd' : ' ';
580 char FileFunc = ' ';
581 if (Type == SymbolRef::ST_File)
582 FileFunc = 'f';
583 else if (Type == SymbolRef::ST_Function)
584 FileFunc = 'F';
585
Michael J. Spencer27b2b1b2013-01-10 22:40:50 +0000586 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
587 "%08" PRIx64;
588
589 outs() << format(Fmt, Address) << " "
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000590 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
591 << (Weak ? 'w' : ' ') // Weak?
592 << ' ' // Constructor. Not supported yet.
593 << ' ' // Warning. Not supported yet.
594 << ' ' // Indirect reference to another symbol.
595 << Debug // Debugging (d) or dynamic (D) symbol.
596 << FileFunc // Name of function (F), file (f) or object (O).
597 << ' ';
598 if (Absolute)
599 outs() << "*ABS*";
600 else if (Section == o->end_sections())
601 outs() << "*UND*";
602 else {
Rafael Espindolada2a2372013-04-13 01:45:40 +0000603 if (const MachOObjectFileBase *MachO =
604 dyn_cast<const MachOObjectFileBase>(o)) {
Rafael Espindolacef81b32012-12-21 03:47:03 +0000605 DataRefImpl DR = Section->getRawDataRefImpl();
Rafael Espindolada2a2372013-04-13 01:45:40 +0000606 StringRef SegmentName = getSectionFinalSegmentName(MachO, DR);
Rafael Espindolacef81b32012-12-21 03:47:03 +0000607 outs() << SegmentName << ",";
608 }
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000609 StringRef SectionName;
610 if (error(Section->getName(SectionName)))
611 SectionName = "";
612 outs() << SectionName;
613 }
614 outs() << '\t'
Benjamin Kramer51cf8662012-03-10 02:04:38 +0000615 << format("%08" PRIx64 " ", Size)
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000616 << Name
617 << '\n';
618 }
619 }
620}
621
Michael J. Spencereef7b622012-12-05 20:12:35 +0000622static void PrintUnwindInfo(const ObjectFile *o) {
623 outs() << "Unwind info:\n\n";
624
625 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
626 printCOFFUnwindInfo(coff);
627 } else {
628 // TODO: Extract DWARF dump tool to objdump.
629 errs() << "This operation is only currently supported "
630 "for COFF object files.\n";
631 return;
632 }
633}
634
Michael J. Spencer27781b72011-10-08 00:18:30 +0000635static void DumpObject(const ObjectFile *o) {
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +0000636 outs() << '\n';
637 outs() << o->getFileName()
638 << ":\tfile format " << o->getFileFormatName() << "\n\n";
639
Michael J. Spencer27781b72011-10-08 00:18:30 +0000640 if (Disassemble)
Michael J. Spencer942eb002011-10-13 22:17:18 +0000641 DisassembleObject(o, Relocations);
642 if (Relocations && !Disassemble)
Michael J. Spencer27781b72011-10-08 00:18:30 +0000643 PrintRelocations(o);
Nick Lewycky023bb152011-10-10 21:21:34 +0000644 if (SectionHeaders)
645 PrintSectionHeaders(o);
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +0000646 if (SectionContents)
647 PrintSectionContents(o);
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000648 if (SymbolTable)
649 PrintSymbolTable(o);
Michael J. Spencereef7b622012-12-05 20:12:35 +0000650 if (UnwindInfo)
651 PrintUnwindInfo(o);
Michael J. Spencerb2c064c2013-01-06 03:56:49 +0000652 if (PrivateHeaders && o->isELF())
653 printELFFileHeader(o);
Michael J. Spencer27781b72011-10-08 00:18:30 +0000654}
655
656/// @brief Dump each object file in \a a;
657static void DumpArchive(const Archive *a) {
658 for (Archive::child_iterator i = a->begin_children(),
659 e = a->end_children(); i != e; ++i) {
660 OwningPtr<Binary> child;
661 if (error_code ec = i->getAsBinary(child)) {
Michael J. Spencerf81285c2011-11-16 01:24:41 +0000662 // Ignore non-object files.
663 if (ec != object_error::invalid_file_type)
664 errs() << ToolName << ": '" << a->getFileName() << "': " << ec.message()
665 << ".\n";
Michael J. Spencer27781b72011-10-08 00:18:30 +0000666 continue;
667 }
668 if (ObjectFile *o = dyn_cast<ObjectFile>(child.get()))
669 DumpObject(o);
670 else
671 errs() << ToolName << ": '" << a->getFileName() << "': "
672 << "Unrecognized file type.\n";
673 }
674}
675
676/// @brief Open file and figure out how to dump it.
677static void DumpInput(StringRef file) {
678 // If file isn't stdin, check that it exists.
679 if (file != "-" && !sys::fs::exists(file)) {
680 errs() << ToolName << ": '" << file << "': " << "No such file\n";
681 return;
682 }
683
Rafael Espindolacef81b32012-12-21 03:47:03 +0000684 if (MachOOpt && Disassemble) {
Michael J. Spencer27781b72011-10-08 00:18:30 +0000685 DisassembleInputMachO(file);
686 return;
687 }
688
689 // Attempt to open the binary.
690 OwningPtr<Binary> binary;
691 if (error_code ec = createBinary(file, binary)) {
692 errs() << ToolName << ": '" << file << "': " << ec.message() << ".\n";
693 return;
694 }
695
Jim Grosbach3f5d1a22012-08-07 17:53:14 +0000696 if (Archive *a = dyn_cast<Archive>(binary.get()))
Michael J. Spencer27781b72011-10-08 00:18:30 +0000697 DumpArchive(a);
Jim Grosbach3f5d1a22012-08-07 17:53:14 +0000698 else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get()))
Michael J. Spencer27781b72011-10-08 00:18:30 +0000699 DumpObject(o);
Jim Grosbach3f5d1a22012-08-07 17:53:14 +0000700 else
Michael J. Spencer27781b72011-10-08 00:18:30 +0000701 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
Michael J. Spencer27781b72011-10-08 00:18:30 +0000702}
703
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000704int main(int argc, char **argv) {
705 // Print a stack trace if we signal out.
706 sys::PrintStackTraceOnErrorSignal();
707 PrettyStackTraceProgram X(argc, argv);
708 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
709
710 // Initialize targets and assembly printers/parsers.
711 llvm::InitializeAllTargetInfos();
Evan Chenge78085a2011-07-22 21:58:54 +0000712 llvm::InitializeAllTargetMCs();
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000713 llvm::InitializeAllAsmParsers();
714 llvm::InitializeAllDisassemblers();
715
Pete Cooperff204962012-05-03 23:20:10 +0000716 // Register the target printer for --version.
717 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
718
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000719 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
720 TripleName = Triple::normalize(TripleName);
721
722 ToolName = argv[0];
723
724 // Defaults to a.out if no filenames specified.
725 if (InputFilenames.size() == 0)
726 InputFilenames.push_back("a.out");
727
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000728 if (!Disassemble
729 && !Relocations
730 && !SectionHeaders
731 && !SectionContents
Michael J. Spencereef7b622012-12-05 20:12:35 +0000732 && !SymbolTable
Michael J. Spencerb2c064c2013-01-06 03:56:49 +0000733 && !UnwindInfo
734 && !PrivateHeaders) {
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000735 cl::PrintHelpMessage();
736 return 2;
737 }
738
Michael J. Spencer27781b72011-10-08 00:18:30 +0000739 std::for_each(InputFilenames.begin(), InputFilenames.end(),
740 DumpInput);
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000741
742 return 0;
743}