blob: 7832cf0dff4c878677411551b15f105d89dea3a5 [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;
Eric Christopher99ff2ba2013-04-03 18:31:23 +0000231 if (Address == UnknownAddressOrSize) continue;
Cameron Zwarichaab21912012-02-03 04:13:37 +0000232 Address -= SectionAddr;
233
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000234 StringRef Name;
235 if (error(si->getName(Name))) break;
236 Symbols.push_back(std::make_pair(Address, Name));
237 }
238 }
239
240 // Sort the symbols by address, just in case they didn't come in that way.
241 array_pod_sort(Symbols.begin(), Symbols.end());
242
Michael J. Spencer942eb002011-10-13 22:17:18 +0000243 // Make a list of all the relocations for this section.
244 std::vector<RelocationRef> Rels;
245 if (InlineRelocs) {
246 for (relocation_iterator ri = i->begin_relocations(),
247 re = i->end_relocations();
Jim Grosbach3f5d1a22012-08-07 17:53:14 +0000248 ri != re; ri.increment(ec)) {
Michael J. Spencer942eb002011-10-13 22:17:18 +0000249 if (error(ec)) break;
250 Rels.push_back(*ri);
251 }
252 }
253
254 // Sort relocations by address.
255 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
256
Rafael Espindolacef81b32012-12-21 03:47:03 +0000257 StringRef SegmentName = "";
258 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
259 DataRefImpl DR = i->getRawDataRefImpl();
260 if (error(MachO->getSectionFinalSegmentName(DR, SegmentName)))
261 break;
262 }
Michael J. Spencer25b15772011-06-25 17:55:23 +0000263 StringRef name;
264 if (error(i->getName(name))) break;
Rafael Espindolacef81b32012-12-21 03:47:03 +0000265 outs() << "Disassembly of section ";
266 if (!SegmentName.empty())
267 outs() << SegmentName << ",";
268 outs() << name << ':';
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000269
270 // If the section has no symbols just insert a dummy one and disassemble
271 // the whole section.
272 if (Symbols.empty())
273 Symbols.push_back(std::make_pair(0, name));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000274
275 // Set up disassembler.
Evan Cheng1abf2cb2011-07-14 23:50:31 +0000276 OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000277
278 if (!AsmInfo) {
279 errs() << "error: no assembly info for target " << TripleName << "\n";
280 return;
281 }
282
Michael J. Spencer27781b72011-10-08 00:18:30 +0000283 OwningPtr<const MCSubtargetInfo> STI(
Jack Carterfd6d1652012-08-28 19:24:49 +0000284 TheTarget->createMCSubtargetInfo(TripleName, "", FeaturesStr));
James Molloyb9505852011-09-07 17:24:38 +0000285
286 if (!STI) {
287 errs() << "error: no subtarget info for target " << TripleName << "\n";
288 return;
289 }
290
Owen Anderson10c044e2011-10-27 21:55:13 +0000291 OwningPtr<const MCDisassembler> DisAsm(
Michael J. Spencer27781b72011-10-08 00:18:30 +0000292 TheTarget->createMCDisassembler(*STI));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000293 if (!DisAsm) {
294 errs() << "error: no disassembler for target " << TripleName << "\n";
295 return;
296 }
297
Jim Grosbachc6449b62012-03-05 19:33:20 +0000298 OwningPtr<const MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
299 if (!MRI) {
300 errs() << "error: no register info for target " << TripleName << "\n";
301 return;
302 }
303
Craig Topper17463b32012-04-02 06:09:36 +0000304 OwningPtr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
305 if (!MII) {
306 errs() << "error: no instruction info for target " << TripleName << "\n";
307 return;
308 }
309
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000310 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
311 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Craig Topper17463b32012-04-02 06:09:36 +0000312 AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000313 if (!IP) {
Michael J. Spencer27781b72011-10-08 00:18:30 +0000314 errs() << "error: no instruction printer for target " << TripleName
315 << '\n';
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000316 return;
317 }
318
Michael J. Spencer25b15772011-06-25 17:55:23 +0000319 StringRef Bytes;
320 if (error(i->getContents(Bytes))) break;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000321 StringRefMemoryObject memoryObject(Bytes);
322 uint64_t Size;
323 uint64_t Index;
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000324 uint64_t SectSize;
325 if (error(i->getSize(SectSize))) break;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000326
Michael J. Spencer942eb002011-10-13 22:17:18 +0000327 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
328 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000329 // Disassemble symbol by symbol.
330 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
331 uint64_t Start = Symbols[si].first;
Michael J. Spencer178dbd42011-10-13 20:37:08 +0000332 uint64_t End;
333 // The end is either the size of the section or the beginning of the next
334 // symbol.
335 if (si == se - 1)
336 End = SectSize;
337 // Make sure this symbol takes up space.
338 else if (Symbols[si + 1].first != Start)
339 End = Symbols[si + 1].first - 1;
340 else
341 // This symbol has the same address as the next symbol. Skip it.
342 continue;
343
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000344 outs() << '\n' << Symbols[si].second << ":\n";
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000345
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000346#ifndef NDEBUG
347 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
348#else
349 raw_ostream &DebugOut = nulls();
350#endif
351
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000352 for (Index = Start; Index < End; Index += Size) {
353 MCInst Inst;
Owen Anderson98c5dda2011-09-15 23:38:46 +0000354
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000355 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
356 DebugOut, nulls())) {
Eli Bendersky8b9da532012-11-20 22:57:02 +0000357 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
358 if (!NoShowRawInsn) {
359 outs() << "\t";
360 DumpBytes(StringRef(Bytes.data() + Index, Size));
361 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000362 IP->printInst(&Inst, outs(), "");
363 outs() << "\n";
364 } else {
365 errs() << ToolName << ": warning: invalid instruction encoding\n";
366 if (Size == 0)
367 Size = 1; // skip illegible bytes
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000368 }
Michael J. Spencer942eb002011-10-13 22:17:18 +0000369
370 // Print relocation for instruction.
371 while (rel_cur != rel_end) {
Owen Anderson0685e942011-10-25 20:35:53 +0000372 bool hidden = false;
Michael J. Spencer942eb002011-10-13 22:17:18 +0000373 uint64_t addr;
374 SmallString<16> name;
375 SmallString<32> val;
Owen Anderson0685e942011-10-25 20:35:53 +0000376
377 // If this relocation is hidden, skip it.
378 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
379 if (hidden) goto skip_print_rel;
380
Michael J. Spencer942eb002011-10-13 22:17:18 +0000381 if (error(rel_cur->getAddress(addr))) goto skip_print_rel;
382 // Stop when rel_cur's address is past the current instruction.
Owen Anderson34749ce2011-10-25 20:15:39 +0000383 if (addr >= Index + Size) break;
Michael J. Spencer942eb002011-10-13 22:17:18 +0000384 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
385 if (error(rel_cur->getValueString(val))) goto skip_print_rel;
386
Benjamin Kramer51cf8662012-03-10 02:04:38 +0000387 outs() << format("\t\t\t%8" PRIx64 ": ", SectionAddr + addr) << name
388 << "\t" << val << "\n";
Michael J. Spencer942eb002011-10-13 22:17:18 +0000389
390 skip_print_rel:
391 ++rel_cur;
392 }
Benjamin Kramer685a2502011-07-20 19:37:35 +0000393 }
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000394 }
395 }
396}
397
Michael J. Spencer27781b72011-10-08 00:18:30 +0000398static void PrintRelocations(const ObjectFile *o) {
399 error_code ec;
400 for (section_iterator si = o->begin_sections(), se = o->end_sections();
401 si != se; si.increment(ec)){
402 if (error(ec)) return;
403 if (si->begin_relocations() == si->end_relocations())
404 continue;
405 StringRef secname;
406 if (error(si->getName(secname))) continue;
407 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
408 for (relocation_iterator ri = si->begin_relocations(),
409 re = si->end_relocations();
410 ri != re; ri.increment(ec)) {
411 if (error(ec)) return;
412
Owen Anderson0685e942011-10-25 20:35:53 +0000413 bool hidden;
Michael J. Spencer27781b72011-10-08 00:18:30 +0000414 uint64_t address;
415 SmallString<32> relocname;
416 SmallString<32> valuestr;
Owen Anderson0685e942011-10-25 20:35:53 +0000417 if (error(ri->getHidden(hidden))) continue;
418 if (hidden) continue;
Michael J. Spencer27781b72011-10-08 00:18:30 +0000419 if (error(ri->getTypeName(relocname))) continue;
420 if (error(ri->getAddress(address))) continue;
421 if (error(ri->getValueString(valuestr))) continue;
422 outs() << address << " " << relocname << " " << valuestr << "\n";
423 }
424 outs() << "\n";
425 }
426}
427
Nick Lewycky023bb152011-10-10 21:21:34 +0000428static void PrintSectionHeaders(const ObjectFile *o) {
429 outs() << "Sections:\n"
430 "Idx Name Size Address Type\n";
431 error_code ec;
432 unsigned i = 0;
433 for (section_iterator si = o->begin_sections(), se = o->end_sections();
434 si != se; si.increment(ec)) {
435 if (error(ec)) return;
436 StringRef Name;
437 if (error(si->getName(Name))) return;
438 uint64_t Address;
439 if (error(si->getAddress(Address))) return;
440 uint64_t Size;
441 if (error(si->getSize(Size))) return;
442 bool Text, Data, BSS;
443 if (error(si->isText(Text))) return;
444 if (error(si->isData(Data))) return;
445 if (error(si->isBSS(BSS))) return;
446 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer14a5f462011-10-13 20:37:20 +0000447 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
Michael J. Spencer27b2b1b2013-01-10 22:40:50 +0000448 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n",
Benjamin Kramer51cf8662012-03-10 02:04:38 +0000449 i, Name.str().c_str(), Size, Address, Type.c_str());
Nick Lewycky023bb152011-10-10 21:21:34 +0000450 ++i;
451 }
452}
453
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +0000454static void PrintSectionContents(const ObjectFile *o) {
455 error_code ec;
456 for (section_iterator si = o->begin_sections(),
457 se = o->end_sections();
458 si != se; si.increment(ec)) {
459 if (error(ec)) return;
460 StringRef Name;
461 StringRef Contents;
462 uint64_t BaseAddr;
463 if (error(si->getName(Name))) continue;
464 if (error(si->getContents(Contents))) continue;
465 if (error(si->getAddress(BaseAddr))) continue;
466
467 outs() << "Contents of section " << Name << ":\n";
468
469 // Dump out the content as hex and printable ascii characters.
470 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer51cf8662012-03-10 02:04:38 +0000471 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +0000472 // Dump line of hex.
473 for (std::size_t i = 0; i < 16; ++i) {
474 if (i != 0 && i % 4 == 0)
475 outs() << ' ';
476 if (addr + i < end)
477 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
478 << hexdigit(Contents[addr + i] & 0xF, true);
479 else
480 outs() << " ";
481 }
482 // Print ascii.
483 outs() << " ";
484 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
Guy Benyei87d0b9e2013-02-12 21:21:59 +0000485 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +0000486 outs() << Contents[addr + i];
487 else
488 outs() << ".";
489 }
490 outs() << "\n";
491 }
492 }
493}
494
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000495static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
496 const coff_file_header *header;
497 if (error(coff->getHeader(header))) return;
498 int aux_count = 0;
499 const coff_symbol *symbol = 0;
500 for (int i = 0, e = header->NumberOfSymbols; i != e; ++i) {
501 if (aux_count--) {
502 // Figure out which type of aux this is.
503 if (symbol->StorageClass == COFF::IMAGE_SYM_CLASS_STATIC
504 && symbol->Value == 0) { // Section definition.
505 const coff_aux_section_definition *asd;
506 if (error(coff->getAuxSymbol<coff_aux_section_definition>(i, asd)))
507 return;
508 outs() << "AUX "
509 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
510 , unsigned(asd->Length)
511 , unsigned(asd->NumberOfRelocations)
512 , unsigned(asd->NumberOfLinenumbers)
513 , unsigned(asd->CheckSum))
514 << format("assoc %d comdat %d\n"
515 , unsigned(asd->Number)
516 , unsigned(asd->Selection));
Jim Grosbach3f5d1a22012-08-07 17:53:14 +0000517 } else
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000518 outs() << "AUX Unknown\n";
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000519 } else {
520 StringRef name;
521 if (error(coff->getSymbol(i, symbol))) return;
522 if (error(coff->getSymbolName(symbol, name))) return;
523 outs() << "[" << format("%2d", i) << "]"
524 << "(sec " << format("%2d", int(symbol->SectionNumber)) << ")"
525 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
526 << "(ty " << format("%3x", unsigned(symbol->Type)) << ")"
527 << "(scl " << format("%3x", unsigned(symbol->StorageClass)) << ") "
528 << "(nx " << unsigned(symbol->NumberOfAuxSymbols) << ") "
529 << "0x" << format("%08x", unsigned(symbol->Value)) << " "
530 << name << "\n";
531 aux_count = symbol->NumberOfAuxSymbols;
532 }
533 }
534}
535
536static void PrintSymbolTable(const ObjectFile *o) {
537 outs() << "SYMBOL TABLE:\n";
538
539 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o))
540 PrintCOFFSymbolTable(coff);
541 else {
542 error_code ec;
543 for (symbol_iterator si = o->begin_symbols(),
544 se = o->end_symbols(); si != se; si.increment(ec)) {
545 if (error(ec)) return;
546 StringRef Name;
Danil Malyshevb0436a72011-11-29 17:40:10 +0000547 uint64_t Address;
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000548 SymbolRef::Type Type;
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000549 uint64_t Size;
David Meyerc46255a2012-02-28 23:47:53 +0000550 uint32_t Flags;
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000551 section_iterator Section = o->end_sections();
552 if (error(si->getName(Name))) continue;
Danil Malyshevb0436a72011-11-29 17:40:10 +0000553 if (error(si->getAddress(Address))) continue;
David Meyerc46255a2012-02-28 23:47:53 +0000554 if (error(si->getFlags(Flags))) continue;
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000555 if (error(si->getType(Type))) continue;
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000556 if (error(si->getSize(Size))) continue;
557 if (error(si->getSection(Section))) continue;
558
David Meyerc46255a2012-02-28 23:47:53 +0000559 bool Global = Flags & SymbolRef::SF_Global;
560 bool Weak = Flags & SymbolRef::SF_Weak;
561 bool Absolute = Flags & SymbolRef::SF_Absolute;
562
Danil Malyshevb0436a72011-11-29 17:40:10 +0000563 if (Address == UnknownAddressOrSize)
564 Address = 0;
565 if (Size == UnknownAddressOrSize)
566 Size = 0;
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000567 char GlobLoc = ' ';
David Meyer2c677272012-02-29 02:11:55 +0000568 if (Type != SymbolRef::ST_Unknown)
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000569 GlobLoc = Global ? 'g' : 'l';
570 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
571 ? 'd' : ' ';
572 char FileFunc = ' ';
573 if (Type == SymbolRef::ST_File)
574 FileFunc = 'f';
575 else if (Type == SymbolRef::ST_Function)
576 FileFunc = 'F';
577
Michael J. Spencer27b2b1b2013-01-10 22:40:50 +0000578 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
579 "%08" PRIx64;
580
581 outs() << format(Fmt, Address) << " "
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000582 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
583 << (Weak ? 'w' : ' ') // Weak?
584 << ' ' // Constructor. Not supported yet.
585 << ' ' // Warning. Not supported yet.
586 << ' ' // Indirect reference to another symbol.
587 << Debug // Debugging (d) or dynamic (D) symbol.
588 << FileFunc // Name of function (F), file (f) or object (O).
589 << ' ';
590 if (Absolute)
591 outs() << "*ABS*";
592 else if (Section == o->end_sections())
593 outs() << "*UND*";
594 else {
Rafael Espindolacef81b32012-12-21 03:47:03 +0000595 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(o)) {
596 StringRef SegmentName;
597 DataRefImpl DR = Section->getRawDataRefImpl();
598 if (error(MachO->getSectionFinalSegmentName(DR, SegmentName)))
599 SegmentName = "";
600 outs() << SegmentName << ",";
601 }
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000602 StringRef SectionName;
603 if (error(Section->getName(SectionName)))
604 SectionName = "";
605 outs() << SectionName;
606 }
607 outs() << '\t'
Benjamin Kramer51cf8662012-03-10 02:04:38 +0000608 << format("%08" PRIx64 " ", Size)
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000609 << Name
610 << '\n';
611 }
612 }
613}
614
Michael J. Spencereef7b622012-12-05 20:12:35 +0000615static void PrintUnwindInfo(const ObjectFile *o) {
616 outs() << "Unwind info:\n\n";
617
618 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
619 printCOFFUnwindInfo(coff);
620 } else {
621 // TODO: Extract DWARF dump tool to objdump.
622 errs() << "This operation is only currently supported "
623 "for COFF object files.\n";
624 return;
625 }
626}
627
Michael J. Spencer27781b72011-10-08 00:18:30 +0000628static void DumpObject(const ObjectFile *o) {
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +0000629 outs() << '\n';
630 outs() << o->getFileName()
631 << ":\tfile format " << o->getFileFormatName() << "\n\n";
632
Michael J. Spencer27781b72011-10-08 00:18:30 +0000633 if (Disassemble)
Michael J. Spencer942eb002011-10-13 22:17:18 +0000634 DisassembleObject(o, Relocations);
635 if (Relocations && !Disassemble)
Michael J. Spencer27781b72011-10-08 00:18:30 +0000636 PrintRelocations(o);
Nick Lewycky023bb152011-10-10 21:21:34 +0000637 if (SectionHeaders)
638 PrintSectionHeaders(o);
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +0000639 if (SectionContents)
640 PrintSectionContents(o);
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000641 if (SymbolTable)
642 PrintSymbolTable(o);
Michael J. Spencereef7b622012-12-05 20:12:35 +0000643 if (UnwindInfo)
644 PrintUnwindInfo(o);
Michael J. Spencerb2c064c2013-01-06 03:56:49 +0000645 if (PrivateHeaders && o->isELF())
646 printELFFileHeader(o);
Michael J. Spencer27781b72011-10-08 00:18:30 +0000647}
648
649/// @brief Dump each object file in \a a;
650static void DumpArchive(const Archive *a) {
651 for (Archive::child_iterator i = a->begin_children(),
652 e = a->end_children(); i != e; ++i) {
653 OwningPtr<Binary> child;
654 if (error_code ec = i->getAsBinary(child)) {
Michael J. Spencerf81285c2011-11-16 01:24:41 +0000655 // Ignore non-object files.
656 if (ec != object_error::invalid_file_type)
657 errs() << ToolName << ": '" << a->getFileName() << "': " << ec.message()
658 << ".\n";
Michael J. Spencer27781b72011-10-08 00:18:30 +0000659 continue;
660 }
661 if (ObjectFile *o = dyn_cast<ObjectFile>(child.get()))
662 DumpObject(o);
663 else
664 errs() << ToolName << ": '" << a->getFileName() << "': "
665 << "Unrecognized file type.\n";
666 }
667}
668
669/// @brief Open file and figure out how to dump it.
670static void DumpInput(StringRef file) {
671 // If file isn't stdin, check that it exists.
672 if (file != "-" && !sys::fs::exists(file)) {
673 errs() << ToolName << ": '" << file << "': " << "No such file\n";
674 return;
675 }
676
Rafael Espindolacef81b32012-12-21 03:47:03 +0000677 if (MachOOpt && Disassemble) {
Michael J. Spencer27781b72011-10-08 00:18:30 +0000678 DisassembleInputMachO(file);
679 return;
680 }
681
682 // Attempt to open the binary.
683 OwningPtr<Binary> binary;
684 if (error_code ec = createBinary(file, binary)) {
685 errs() << ToolName << ": '" << file << "': " << ec.message() << ".\n";
686 return;
687 }
688
Jim Grosbach3f5d1a22012-08-07 17:53:14 +0000689 if (Archive *a = dyn_cast<Archive>(binary.get()))
Michael J. Spencer27781b72011-10-08 00:18:30 +0000690 DumpArchive(a);
Jim Grosbach3f5d1a22012-08-07 17:53:14 +0000691 else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get()))
Michael J. Spencer27781b72011-10-08 00:18:30 +0000692 DumpObject(o);
Jim Grosbach3f5d1a22012-08-07 17:53:14 +0000693 else
Michael J. Spencer27781b72011-10-08 00:18:30 +0000694 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
Michael J. Spencer27781b72011-10-08 00:18:30 +0000695}
696
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000697int main(int argc, char **argv) {
698 // Print a stack trace if we signal out.
699 sys::PrintStackTraceOnErrorSignal();
700 PrettyStackTraceProgram X(argc, argv);
701 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
702
703 // Initialize targets and assembly printers/parsers.
704 llvm::InitializeAllTargetInfos();
Evan Chenge78085a2011-07-22 21:58:54 +0000705 llvm::InitializeAllTargetMCs();
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000706 llvm::InitializeAllAsmParsers();
707 llvm::InitializeAllDisassemblers();
708
Pete Cooperff204962012-05-03 23:20:10 +0000709 // Register the target printer for --version.
710 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
711
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000712 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
713 TripleName = Triple::normalize(TripleName);
714
715 ToolName = argv[0];
716
717 // Defaults to a.out if no filenames specified.
718 if (InputFilenames.size() == 0)
719 InputFilenames.push_back("a.out");
720
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000721 if (!Disassemble
722 && !Relocations
723 && !SectionHeaders
724 && !SectionContents
Michael J. Spencereef7b622012-12-05 20:12:35 +0000725 && !SymbolTable
Michael J. Spencerb2c064c2013-01-06 03:56:49 +0000726 && !UnwindInfo
727 && !PrivateHeaders) {
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000728 cl::PrintHelpMessage();
729 return 2;
730 }
731
Michael J. Spencer27781b72011-10-08 00:18:30 +0000732 std::for_each(InputFilenames.begin(), InputFilenames.end(),
733 DumpInput);
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000734
735 return 0;
736}