blob: 9958dad3d33babbe0eb867f0d9f33234e53f5560 [file] [log] [blame]
Michael J. Spencer92e1deb2011-01-20 06:39:06 +00001//===-- llvm-objdump.cpp - Object file dumping utility for llvm -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This program is a utility that works like binutils "objdump", that is, it
11// dumps out a plethora of information about an object file depending on the
12// flags.
13//
14//===----------------------------------------------------------------------===//
15
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000016#include "llvm-objdump.h"
Benjamin Kramer685a2502011-07-20 19:37:35 +000017#include "MCFunction.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000018#include "llvm/ADT/OwningPtr.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000019#include "llvm/ADT/STLExtras.h"
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +000020#include "llvm/ADT/StringExtras.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000021#include "llvm/ADT/Triple.h"
22#include "llvm/MC/MCAsmInfo.h"
23#include "llvm/MC/MCDisassembler.h"
24#include "llvm/MC/MCInst.h"
25#include "llvm/MC/MCInstPrinter.h"
Craig Topper17463b32012-04-02 06:09:36 +000026#include "llvm/MC/MCInstrInfo.h"
Jim Grosbachc6449b62012-03-05 19:33:20 +000027#include "llvm/MC/MCRegisterInfo.h"
James Molloyb9505852011-09-07 17:24:38 +000028#include "llvm/MC/MCSubtargetInfo.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000029#include "llvm/Object/Archive.h"
30#include "llvm/Object/COFF.h"
Michael J. Spencerb2c064c2013-01-06 03:56:49 +000031#include "llvm/Object/ELF.h"
Rafael Espindolacef81b32012-12-21 03:47:03 +000032#include "llvm/Object/MachO.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000033#include "llvm/Object/ObjectFile.h"
Michael J. Spencer27781b72011-10-08 00:18:30 +000034#include "llvm/Support/Casting.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000035#include "llvm/Support/CommandLine.h"
36#include "llvm/Support/Debug.h"
Michael J. Spencer27781b72011-10-08 00:18:30 +000037#include "llvm/Support/FileSystem.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000038#include "llvm/Support/Format.h"
Benjamin Kramer853b0fd2011-07-25 23:04:36 +000039#include "llvm/Support/GraphWriter.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000040#include "llvm/Support/Host.h"
41#include "llvm/Support/ManagedStatic.h"
42#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000043#include "llvm/Support/MemoryObject.h"
44#include "llvm/Support/PrettyStackTrace.h"
45#include "llvm/Support/Signals.h"
46#include "llvm/Support/SourceMgr.h"
Evan Cheng3e74d6f2011-08-24 18:08:43 +000047#include "llvm/Support/TargetRegistry.h"
48#include "llvm/Support/TargetSelect.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000049#include "llvm/Support/raw_ostream.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000050#include "llvm/Support/system_error.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000051#include <algorithm>
Benjamin Kramer81bbdfd2012-03-23 11:49:32 +000052#include <cctype>
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000053#include <cstring>
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000054using namespace llvm;
55using namespace object;
56
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000057static cl::list<std::string>
58InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000059
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000060static cl::opt<bool>
61Disassemble("disassemble",
62 cl::desc("Display assembler mnemonics for the machine instructions"));
63static cl::alias
64Disassembled("d", cl::desc("Alias for --disassemble"),
65 cl::aliasopt(Disassemble));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000066
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000067static cl::opt<bool>
Michael J. Spencer27781b72011-10-08 00:18:30 +000068Relocations("r", cl::desc("Display the relocation entries in the file"));
69
70static cl::opt<bool>
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +000071SectionContents("s", cl::desc("Display the content of each section"));
72
73static cl::opt<bool>
Michael J. Spencer22ff0f32011-10-18 19:32:17 +000074SymbolTable("t", cl::desc("Display the symbol table"));
75
76static cl::opt<bool>
Rafael Espindolacef81b32012-12-21 03:47:03 +000077MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000078static cl::alias
Rafael Espindolacef81b32012-12-21 03:47:03 +000079MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
Benjamin Kramer685a2502011-07-20 19:37:35 +000080
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000081cl::opt<std::string>
82llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
83 "see -version for available targets"));
84
85cl::opt<std::string>
86llvm::ArchName("arch", cl::desc("Target arch to disassemble for, "
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000087 "see -version for available targets"));
88
Nick Lewycky023bb152011-10-10 21:21:34 +000089static cl::opt<bool>
90SectionHeaders("section-headers", cl::desc("Display summaries of the headers "
91 "for each section."));
92static cl::alias
93SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
94 cl::aliasopt(SectionHeaders));
95static cl::alias
96SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
97 cl::aliasopt(SectionHeaders));
98
Jack Carterfd6d1652012-08-28 19:24:49 +000099static cl::list<std::string>
100MAttrs("mattr",
101 cl::CommaSeparated,
102 cl::desc("Target specific attributes"),
103 cl::value_desc("a1,+a2,-a3,..."));
104
Eli Bendersky8b9da532012-11-20 22:57:02 +0000105static cl::opt<bool>
106NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling instructions, "
107 "do not print the instruction bytes."));
108
Michael J. Spencereef7b622012-12-05 20:12:35 +0000109static cl::opt<bool>
110UnwindInfo("unwind-info", cl::desc("Display unwind information"));
111
112static cl::alias
113UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
114 cl::aliasopt(UnwindInfo));
115
Michael J. Spencerb2c064c2013-01-06 03:56:49 +0000116static cl::opt<bool>
117PrivateHeaders("private-headers",
118 cl::desc("Display format specific file headers"));
119
120static cl::alias
121PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
122 cl::aliasopt(PrivateHeaders));
123
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000124static StringRef ToolName;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000125
Michael J. Spencereef7b622012-12-05 20:12:35 +0000126bool llvm::error(error_code ec) {
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000127 if (!ec) return false;
Michael J. Spencer25b15772011-06-25 17:55:23 +0000128
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000129 outs() << ToolName << ": error reading file: " << ec.message() << ".\n";
130 outs().flush();
131 return true;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000132}
133
Jim Grosbach3f5d1a22012-08-07 17:53:14 +0000134static const Target *getTarget(const ObjectFile *Obj = NULL) {
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000135 // Figure out the target triple.
Kevin Enderby9ed9e5d2012-05-08 23:38:45 +0000136 llvm::Triple TheTriple("unknown-unknown-unknown");
Michael J. Spencerd11699d2011-01-20 07:22:04 +0000137 if (TripleName.empty()) {
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000138 if (Obj)
Kevin Enderby9ed9e5d2012-05-08 23:38:45 +0000139 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
Michael J. Spencerd11699d2011-01-20 07:22:04 +0000140 } else
Kevin Enderby9ed9e5d2012-05-08 23:38:45 +0000141 TheTriple.setTriple(Triple::normalize(TripleName));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000142
143 // Get the target specific parser.
144 std::string Error;
Kevin Enderby9ed9e5d2012-05-08 23:38:45 +0000145 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
146 Error);
147 if (!TheTarget) {
148 errs() << ToolName << ": " << Error;
149 return 0;
150 }
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000151
Kevin Enderby9ed9e5d2012-05-08 23:38:45 +0000152 // Update the triple name and return the found target.
153 TripleName = TheTriple.getTriple();
154 return TheTarget;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000155}
156
David Blaikie2d24e2a2011-12-20 02:50:00 +0000157void llvm::StringRefMemoryObject::anchor() { }
158
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000159void llvm::DumpBytes(StringRef bytes) {
160 static const char hex_rep[] = "0123456789abcdef";
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000161 // FIXME: The real way to do this is to figure out the longest instruction
162 // and align to that size before printing. I'll fix this when I get
163 // around to outputting relocations.
164 // 15 is the longest x86 instruction
165 // 3 is for the hex rep of a byte + a space.
166 // 1 is for the null terminator.
167 enum { OutputSize = (15 * 3) + 1 };
168 char output[OutputSize];
169
170 assert(bytes.size() <= 15
171 && "DumpBytes only supports instructions of up to 15 bytes");
172 memset(output, ' ', sizeof(output));
173 unsigned index = 0;
174 for (StringRef::iterator i = bytes.begin(),
175 e = bytes.end(); i != e; ++i) {
176 output[index] = hex_rep[(*i & 0xF0) >> 4];
177 output[index + 1] = hex_rep[*i & 0xF];
178 index += 3;
179 }
180
181 output[sizeof(output) - 1] = 0;
182 outs() << output;
183}
184
Michael J. Spencereef7b622012-12-05 20:12:35 +0000185bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
Michael J. Spencer942eb002011-10-13 22:17:18 +0000186 uint64_t a_addr, b_addr;
187 if (error(a.getAddress(a_addr))) return false;
188 if (error(b.getAddress(b_addr))) return false;
189 return a_addr < b_addr;
190}
191
192static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Jim Grosbach3f5d1a22012-08-07 17:53:14 +0000193 const Target *TheTarget = getTarget(Obj);
194 // getTarget() will have already issued a diagnostic if necessary, so
195 // just bail here if it failed.
196 if (!TheTarget)
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000197 return;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000198
Jack Carterfd6d1652012-08-28 19:24:49 +0000199 // Package up features to be passed to target/subtarget
200 std::string FeaturesStr;
201 if (MAttrs.size()) {
202 SubtargetFeatures Features;
203 for (unsigned i = 0; i != MAttrs.size(); ++i)
204 Features.AddFeature(MAttrs[i]);
205 FeaturesStr = Features.getString();
206 }
207
Michael J. Spencer25b15772011-06-25 17:55:23 +0000208 error_code ec;
Michael J. Spencer4344b1e2011-10-07 19:25:32 +0000209 for (section_iterator i = Obj->begin_sections(),
Michael J. Spencer27781b72011-10-08 00:18:30 +0000210 e = Obj->end_sections();
211 i != e; i.increment(ec)) {
Michael J. Spencer25b15772011-06-25 17:55:23 +0000212 if (error(ec)) break;
213 bool text;
214 if (error(i->isText(text))) break;
215 if (!text) continue;
216
Michael J. Spencer942eb002011-10-13 22:17:18 +0000217 uint64_t SectionAddr;
218 if (error(i->getAddress(SectionAddr))) break;
219
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000220 // Make a list of all the symbols in this section.
221 std::vector<std::pair<uint64_t, StringRef> > Symbols;
Michael J. Spencer4344b1e2011-10-07 19:25:32 +0000222 for (symbol_iterator si = Obj->begin_symbols(),
Michael J. Spencer27781b72011-10-08 00:18:30 +0000223 se = Obj->end_symbols();
224 si != se; si.increment(ec)) {
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000225 bool contains;
226 if (!error(i->containsSymbol(*si, contains)) && contains) {
227 uint64_t Address;
Danil Malyshevb0436a72011-11-29 17:40:10 +0000228 if (error(si->getAddress(Address))) break;
Cameron Zwarichaab21912012-02-03 04:13:37 +0000229 Address -= SectionAddr;
230
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000231 StringRef Name;
232 if (error(si->getName(Name))) break;
233 Symbols.push_back(std::make_pair(Address, Name));
234 }
235 }
236
237 // Sort the symbols by address, just in case they didn't come in that way.
238 array_pod_sort(Symbols.begin(), Symbols.end());
239
Michael J. Spencer942eb002011-10-13 22:17:18 +0000240 // Make a list of all the relocations for this section.
241 std::vector<RelocationRef> Rels;
242 if (InlineRelocs) {
243 for (relocation_iterator ri = i->begin_relocations(),
244 re = i->end_relocations();
Jim Grosbach3f5d1a22012-08-07 17:53:14 +0000245 ri != re; ri.increment(ec)) {
Michael J. Spencer942eb002011-10-13 22:17:18 +0000246 if (error(ec)) break;
247 Rels.push_back(*ri);
248 }
249 }
250
251 // Sort relocations by address.
252 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
253
Rafael Espindolacef81b32012-12-21 03:47:03 +0000254 StringRef SegmentName = "";
255 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
256 DataRefImpl DR = i->getRawDataRefImpl();
257 if (error(MachO->getSectionFinalSegmentName(DR, SegmentName)))
258 break;
259 }
Michael J. Spencer25b15772011-06-25 17:55:23 +0000260 StringRef name;
261 if (error(i->getName(name))) break;
Rafael Espindolacef81b32012-12-21 03:47:03 +0000262 outs() << "Disassembly of section ";
263 if (!SegmentName.empty())
264 outs() << SegmentName << ",";
265 outs() << name << ':';
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000266
267 // If the section has no symbols just insert a dummy one and disassemble
268 // the whole section.
269 if (Symbols.empty())
270 Symbols.push_back(std::make_pair(0, name));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000271
272 // Set up disassembler.
Evan Cheng1abf2cb2011-07-14 23:50:31 +0000273 OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000274
275 if (!AsmInfo) {
276 errs() << "error: no assembly info for target " << TripleName << "\n";
277 return;
278 }
279
Michael J. Spencer27781b72011-10-08 00:18:30 +0000280 OwningPtr<const MCSubtargetInfo> STI(
Jack Carterfd6d1652012-08-28 19:24:49 +0000281 TheTarget->createMCSubtargetInfo(TripleName, "", FeaturesStr));
James Molloyb9505852011-09-07 17:24:38 +0000282
283 if (!STI) {
284 errs() << "error: no subtarget info for target " << TripleName << "\n";
285 return;
286 }
287
Owen Anderson10c044e2011-10-27 21:55:13 +0000288 OwningPtr<const MCDisassembler> DisAsm(
Michael J. Spencer27781b72011-10-08 00:18:30 +0000289 TheTarget->createMCDisassembler(*STI));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000290 if (!DisAsm) {
291 errs() << "error: no disassembler for target " << TripleName << "\n";
292 return;
293 }
294
Jim Grosbachc6449b62012-03-05 19:33:20 +0000295 OwningPtr<const MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
296 if (!MRI) {
297 errs() << "error: no register info for target " << TripleName << "\n";
298 return;
299 }
300
Craig Topper17463b32012-04-02 06:09:36 +0000301 OwningPtr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
302 if (!MII) {
303 errs() << "error: no instruction info for target " << TripleName << "\n";
304 return;
305 }
306
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000307 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
308 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Craig Topper17463b32012-04-02 06:09:36 +0000309 AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000310 if (!IP) {
Michael J. Spencer27781b72011-10-08 00:18:30 +0000311 errs() << "error: no instruction printer for target " << TripleName
312 << '\n';
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000313 return;
314 }
315
Michael J. Spencer25b15772011-06-25 17:55:23 +0000316 StringRef Bytes;
317 if (error(i->getContents(Bytes))) break;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000318 StringRefMemoryObject memoryObject(Bytes);
319 uint64_t Size;
320 uint64_t Index;
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000321 uint64_t SectSize;
322 if (error(i->getSize(SectSize))) break;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000323
Michael J. Spencer942eb002011-10-13 22:17:18 +0000324 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
325 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000326 // Disassemble symbol by symbol.
327 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
328 uint64_t Start = Symbols[si].first;
Michael J. Spencer178dbd42011-10-13 20:37:08 +0000329 uint64_t End;
330 // The end is either the size of the section or the beginning of the next
331 // symbol.
332 if (si == se - 1)
333 End = SectSize;
334 // Make sure this symbol takes up space.
335 else if (Symbols[si + 1].first != Start)
336 End = Symbols[si + 1].first - 1;
337 else
338 // This symbol has the same address as the next symbol. Skip it.
339 continue;
340
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000341 outs() << '\n' << Symbols[si].second << ":\n";
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000342
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000343#ifndef NDEBUG
344 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
345#else
346 raw_ostream &DebugOut = nulls();
347#endif
348
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000349 for (Index = Start; Index < End; Index += Size) {
350 MCInst Inst;
Owen Anderson98c5dda2011-09-15 23:38:46 +0000351
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000352 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
353 DebugOut, nulls())) {
Eli Bendersky8b9da532012-11-20 22:57:02 +0000354 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
355 if (!NoShowRawInsn) {
356 outs() << "\t";
357 DumpBytes(StringRef(Bytes.data() + Index, Size));
358 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000359 IP->printInst(&Inst, outs(), "");
360 outs() << "\n";
361 } else {
362 errs() << ToolName << ": warning: invalid instruction encoding\n";
363 if (Size == 0)
364 Size = 1; // skip illegible bytes
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000365 }
Michael J. Spencer942eb002011-10-13 22:17:18 +0000366
367 // Print relocation for instruction.
368 while (rel_cur != rel_end) {
Owen Anderson0685e942011-10-25 20:35:53 +0000369 bool hidden = false;
Michael J. Spencer942eb002011-10-13 22:17:18 +0000370 uint64_t addr;
371 SmallString<16> name;
372 SmallString<32> val;
Owen Anderson0685e942011-10-25 20:35:53 +0000373
374 // If this relocation is hidden, skip it.
375 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
376 if (hidden) goto skip_print_rel;
377
Michael J. Spencer942eb002011-10-13 22:17:18 +0000378 if (error(rel_cur->getAddress(addr))) goto skip_print_rel;
379 // Stop when rel_cur's address is past the current instruction.
Owen Anderson34749ce2011-10-25 20:15:39 +0000380 if (addr >= Index + Size) break;
Michael J. Spencer942eb002011-10-13 22:17:18 +0000381 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
382 if (error(rel_cur->getValueString(val))) goto skip_print_rel;
383
Benjamin Kramer51cf8662012-03-10 02:04:38 +0000384 outs() << format("\t\t\t%8" PRIx64 ": ", SectionAddr + addr) << name
385 << "\t" << val << "\n";
Michael J. Spencer942eb002011-10-13 22:17:18 +0000386
387 skip_print_rel:
388 ++rel_cur;
389 }
Benjamin Kramer685a2502011-07-20 19:37:35 +0000390 }
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000391 }
392 }
393}
394
Michael J. Spencer27781b72011-10-08 00:18:30 +0000395static void PrintRelocations(const ObjectFile *o) {
396 error_code ec;
397 for (section_iterator si = o->begin_sections(), se = o->end_sections();
398 si != se; si.increment(ec)){
399 if (error(ec)) return;
400 if (si->begin_relocations() == si->end_relocations())
401 continue;
402 StringRef secname;
403 if (error(si->getName(secname))) continue;
404 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
405 for (relocation_iterator ri = si->begin_relocations(),
406 re = si->end_relocations();
407 ri != re; ri.increment(ec)) {
408 if (error(ec)) return;
409
Owen Anderson0685e942011-10-25 20:35:53 +0000410 bool hidden;
Michael J. Spencer27781b72011-10-08 00:18:30 +0000411 uint64_t address;
412 SmallString<32> relocname;
413 SmallString<32> valuestr;
Owen Anderson0685e942011-10-25 20:35:53 +0000414 if (error(ri->getHidden(hidden))) continue;
415 if (hidden) continue;
Michael J. Spencer27781b72011-10-08 00:18:30 +0000416 if (error(ri->getTypeName(relocname))) continue;
417 if (error(ri->getAddress(address))) continue;
418 if (error(ri->getValueString(valuestr))) continue;
419 outs() << address << " " << relocname << " " << valuestr << "\n";
420 }
421 outs() << "\n";
422 }
423}
424
Nick Lewycky023bb152011-10-10 21:21:34 +0000425static void PrintSectionHeaders(const ObjectFile *o) {
426 outs() << "Sections:\n"
427 "Idx Name Size Address Type\n";
428 error_code ec;
429 unsigned i = 0;
430 for (section_iterator si = o->begin_sections(), se = o->end_sections();
431 si != se; si.increment(ec)) {
432 if (error(ec)) return;
433 StringRef Name;
434 if (error(si->getName(Name))) return;
435 uint64_t Address;
436 if (error(si->getAddress(Address))) return;
437 uint64_t Size;
438 if (error(si->getSize(Size))) return;
439 bool Text, Data, BSS;
440 if (error(si->isText(Text))) return;
441 if (error(si->isData(Data))) return;
442 if (error(si->isBSS(BSS))) return;
443 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer14a5f462011-10-13 20:37:20 +0000444 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
Benjamin Kramer51cf8662012-03-10 02:04:38 +0000445 outs() << format("%3d %-13s %09" PRIx64 " %017" PRIx64 " %s\n",
446 i, Name.str().c_str(), Size, Address, Type.c_str());
Nick Lewycky023bb152011-10-10 21:21:34 +0000447 ++i;
448 }
449}
450
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +0000451static void PrintSectionContents(const ObjectFile *o) {
452 error_code ec;
453 for (section_iterator si = o->begin_sections(),
454 se = o->end_sections();
455 si != se; si.increment(ec)) {
456 if (error(ec)) return;
457 StringRef Name;
458 StringRef Contents;
459 uint64_t BaseAddr;
460 if (error(si->getName(Name))) continue;
461 if (error(si->getContents(Contents))) continue;
462 if (error(si->getAddress(BaseAddr))) continue;
463
464 outs() << "Contents of section " << Name << ":\n";
465
466 // Dump out the content as hex and printable ascii characters.
467 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer51cf8662012-03-10 02:04:38 +0000468 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +0000469 // Dump line of hex.
470 for (std::size_t i = 0; i < 16; ++i) {
471 if (i != 0 && i % 4 == 0)
472 outs() << ' ';
473 if (addr + i < end)
474 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
475 << hexdigit(Contents[addr + i] & 0xF, true);
476 else
477 outs() << " ";
478 }
479 // Print ascii.
480 outs() << " ";
481 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
482 if (std::isprint(Contents[addr + i] & 0xFF))
483 outs() << Contents[addr + i];
484 else
485 outs() << ".";
486 }
487 outs() << "\n";
488 }
489 }
490}
491
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000492static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
493 const coff_file_header *header;
494 if (error(coff->getHeader(header))) return;
495 int aux_count = 0;
496 const coff_symbol *symbol = 0;
497 for (int i = 0, e = header->NumberOfSymbols; i != e; ++i) {
498 if (aux_count--) {
499 // Figure out which type of aux this is.
500 if (symbol->StorageClass == COFF::IMAGE_SYM_CLASS_STATIC
501 && symbol->Value == 0) { // Section definition.
502 const coff_aux_section_definition *asd;
503 if (error(coff->getAuxSymbol<coff_aux_section_definition>(i, asd)))
504 return;
505 outs() << "AUX "
506 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
507 , unsigned(asd->Length)
508 , unsigned(asd->NumberOfRelocations)
509 , unsigned(asd->NumberOfLinenumbers)
510 , unsigned(asd->CheckSum))
511 << format("assoc %d comdat %d\n"
512 , unsigned(asd->Number)
513 , unsigned(asd->Selection));
Jim Grosbach3f5d1a22012-08-07 17:53:14 +0000514 } else
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000515 outs() << "AUX Unknown\n";
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000516 } else {
517 StringRef name;
518 if (error(coff->getSymbol(i, symbol))) return;
519 if (error(coff->getSymbolName(symbol, name))) return;
520 outs() << "[" << format("%2d", i) << "]"
521 << "(sec " << format("%2d", int(symbol->SectionNumber)) << ")"
522 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
523 << "(ty " << format("%3x", unsigned(symbol->Type)) << ")"
524 << "(scl " << format("%3x", unsigned(symbol->StorageClass)) << ") "
525 << "(nx " << unsigned(symbol->NumberOfAuxSymbols) << ") "
526 << "0x" << format("%08x", unsigned(symbol->Value)) << " "
527 << name << "\n";
528 aux_count = symbol->NumberOfAuxSymbols;
529 }
530 }
531}
532
533static void PrintSymbolTable(const ObjectFile *o) {
534 outs() << "SYMBOL TABLE:\n";
535
536 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o))
537 PrintCOFFSymbolTable(coff);
538 else {
539 error_code ec;
540 for (symbol_iterator si = o->begin_symbols(),
541 se = o->end_symbols(); si != se; si.increment(ec)) {
542 if (error(ec)) return;
543 StringRef Name;
Danil Malyshevb0436a72011-11-29 17:40:10 +0000544 uint64_t Address;
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000545 SymbolRef::Type Type;
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000546 uint64_t Size;
David Meyerc46255a2012-02-28 23:47:53 +0000547 uint32_t Flags;
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000548 section_iterator Section = o->end_sections();
549 if (error(si->getName(Name))) continue;
Danil Malyshevb0436a72011-11-29 17:40:10 +0000550 if (error(si->getAddress(Address))) continue;
David Meyerc46255a2012-02-28 23:47:53 +0000551 if (error(si->getFlags(Flags))) continue;
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000552 if (error(si->getType(Type))) continue;
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000553 if (error(si->getSize(Size))) continue;
554 if (error(si->getSection(Section))) continue;
555
David Meyerc46255a2012-02-28 23:47:53 +0000556 bool Global = Flags & SymbolRef::SF_Global;
557 bool Weak = Flags & SymbolRef::SF_Weak;
558 bool Absolute = Flags & SymbolRef::SF_Absolute;
559
Danil Malyshevb0436a72011-11-29 17:40:10 +0000560 if (Address == UnknownAddressOrSize)
561 Address = 0;
562 if (Size == UnknownAddressOrSize)
563 Size = 0;
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000564 char GlobLoc = ' ';
David Meyer2c677272012-02-29 02:11:55 +0000565 if (Type != SymbolRef::ST_Unknown)
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000566 GlobLoc = Global ? 'g' : 'l';
567 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
568 ? 'd' : ' ';
569 char FileFunc = ' ';
570 if (Type == SymbolRef::ST_File)
571 FileFunc = 'f';
572 else if (Type == SymbolRef::ST_Function)
573 FileFunc = 'F';
574
Benjamin Kramer51cf8662012-03-10 02:04:38 +0000575 outs() << format("%08" PRIx64, Address) << " "
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000576 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
577 << (Weak ? 'w' : ' ') // Weak?
578 << ' ' // Constructor. Not supported yet.
579 << ' ' // Warning. Not supported yet.
580 << ' ' // Indirect reference to another symbol.
581 << Debug // Debugging (d) or dynamic (D) symbol.
582 << FileFunc // Name of function (F), file (f) or object (O).
583 << ' ';
584 if (Absolute)
585 outs() << "*ABS*";
586 else if (Section == o->end_sections())
587 outs() << "*UND*";
588 else {
Rafael Espindolacef81b32012-12-21 03:47:03 +0000589 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(o)) {
590 StringRef SegmentName;
591 DataRefImpl DR = Section->getRawDataRefImpl();
592 if (error(MachO->getSectionFinalSegmentName(DR, SegmentName)))
593 SegmentName = "";
594 outs() << SegmentName << ",";
595 }
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000596 StringRef SectionName;
597 if (error(Section->getName(SectionName)))
598 SectionName = "";
599 outs() << SectionName;
600 }
601 outs() << '\t'
Benjamin Kramer51cf8662012-03-10 02:04:38 +0000602 << format("%08" PRIx64 " ", Size)
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000603 << Name
604 << '\n';
605 }
606 }
607}
608
Michael J. Spencereef7b622012-12-05 20:12:35 +0000609static void PrintUnwindInfo(const ObjectFile *o) {
610 outs() << "Unwind info:\n\n";
611
612 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
613 printCOFFUnwindInfo(coff);
614 } else {
615 // TODO: Extract DWARF dump tool to objdump.
616 errs() << "This operation is only currently supported "
617 "for COFF object files.\n";
618 return;
619 }
620}
621
Michael J. Spencer27781b72011-10-08 00:18:30 +0000622static void DumpObject(const ObjectFile *o) {
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +0000623 outs() << '\n';
624 outs() << o->getFileName()
625 << ":\tfile format " << o->getFileFormatName() << "\n\n";
626
Michael J. Spencer27781b72011-10-08 00:18:30 +0000627 if (Disassemble)
Michael J. Spencer942eb002011-10-13 22:17:18 +0000628 DisassembleObject(o, Relocations);
629 if (Relocations && !Disassemble)
Michael J. Spencer27781b72011-10-08 00:18:30 +0000630 PrintRelocations(o);
Nick Lewycky023bb152011-10-10 21:21:34 +0000631 if (SectionHeaders)
632 PrintSectionHeaders(o);
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +0000633 if (SectionContents)
634 PrintSectionContents(o);
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000635 if (SymbolTable)
636 PrintSymbolTable(o);
Michael J. Spencereef7b622012-12-05 20:12:35 +0000637 if (UnwindInfo)
638 PrintUnwindInfo(o);
Michael J. Spencerb2c064c2013-01-06 03:56:49 +0000639 if (PrivateHeaders && o->isELF())
640 printELFFileHeader(o);
Michael J. Spencer27781b72011-10-08 00:18:30 +0000641}
642
643/// @brief Dump each object file in \a a;
644static void DumpArchive(const Archive *a) {
645 for (Archive::child_iterator i = a->begin_children(),
646 e = a->end_children(); i != e; ++i) {
647 OwningPtr<Binary> child;
648 if (error_code ec = i->getAsBinary(child)) {
Michael J. Spencerf81285c2011-11-16 01:24:41 +0000649 // Ignore non-object files.
650 if (ec != object_error::invalid_file_type)
651 errs() << ToolName << ": '" << a->getFileName() << "': " << ec.message()
652 << ".\n";
Michael J. Spencer27781b72011-10-08 00:18:30 +0000653 continue;
654 }
655 if (ObjectFile *o = dyn_cast<ObjectFile>(child.get()))
656 DumpObject(o);
657 else
658 errs() << ToolName << ": '" << a->getFileName() << "': "
659 << "Unrecognized file type.\n";
660 }
661}
662
663/// @brief Open file and figure out how to dump it.
664static void DumpInput(StringRef file) {
665 // If file isn't stdin, check that it exists.
666 if (file != "-" && !sys::fs::exists(file)) {
667 errs() << ToolName << ": '" << file << "': " << "No such file\n";
668 return;
669 }
670
Rafael Espindolacef81b32012-12-21 03:47:03 +0000671 if (MachOOpt && Disassemble) {
Michael J. Spencer27781b72011-10-08 00:18:30 +0000672 DisassembleInputMachO(file);
673 return;
674 }
675
676 // Attempt to open the binary.
677 OwningPtr<Binary> binary;
678 if (error_code ec = createBinary(file, binary)) {
679 errs() << ToolName << ": '" << file << "': " << ec.message() << ".\n";
680 return;
681 }
682
Jim Grosbach3f5d1a22012-08-07 17:53:14 +0000683 if (Archive *a = dyn_cast<Archive>(binary.get()))
Michael J. Spencer27781b72011-10-08 00:18:30 +0000684 DumpArchive(a);
Jim Grosbach3f5d1a22012-08-07 17:53:14 +0000685 else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get()))
Michael J. Spencer27781b72011-10-08 00:18:30 +0000686 DumpObject(o);
Jim Grosbach3f5d1a22012-08-07 17:53:14 +0000687 else
Michael J. Spencer27781b72011-10-08 00:18:30 +0000688 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
Michael J. Spencer27781b72011-10-08 00:18:30 +0000689}
690
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000691int main(int argc, char **argv) {
692 // Print a stack trace if we signal out.
693 sys::PrintStackTraceOnErrorSignal();
694 PrettyStackTraceProgram X(argc, argv);
695 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
696
697 // Initialize targets and assembly printers/parsers.
698 llvm::InitializeAllTargetInfos();
Evan Chenge78085a2011-07-22 21:58:54 +0000699 llvm::InitializeAllTargetMCs();
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000700 llvm::InitializeAllAsmParsers();
701 llvm::InitializeAllDisassemblers();
702
Pete Cooperff204962012-05-03 23:20:10 +0000703 // Register the target printer for --version.
704 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
705
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000706 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
707 TripleName = Triple::normalize(TripleName);
708
709 ToolName = argv[0];
710
711 // Defaults to a.out if no filenames specified.
712 if (InputFilenames.size() == 0)
713 InputFilenames.push_back("a.out");
714
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000715 if (!Disassemble
716 && !Relocations
717 && !SectionHeaders
718 && !SectionContents
Michael J. Spencereef7b622012-12-05 20:12:35 +0000719 && !SymbolTable
Michael J. Spencerb2c064c2013-01-06 03:56:49 +0000720 && !UnwindInfo
721 && !PrivateHeaders) {
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000722 cl::PrintHelpMessage();
723 return 2;
724 }
725
Michael J. Spencer27781b72011-10-08 00:18:30 +0000726 std::for_each(InputFilenames.begin(), InputFilenames.end(),
727 DumpInput);
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000728
729 return 0;
730}