blob: 4572c9654812ca1080502710c5729a2641a1f275 [file] [log] [blame]
Michael J. Spencer2670c252011-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. Spencerd7e70032013-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. Spencer2670c252011-01-20 06:39:06 +000017//===----------------------------------------------------------------------===//
18
Benjamin Kramer43a772e2011-09-19 17:56:04 +000019#include "llvm-objdump.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000020#include "llvm/ADT/OwningPtr.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000021#include "llvm/ADT/STLExtras.h"
Michael J. Spencer4e25c022011-10-17 17:13:22 +000022#include "llvm/ADT/StringExtras.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000023#include "llvm/ADT/Triple.h"
24#include "llvm/MC/MCAsmInfo.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000025#include "llvm/MC/MCAtom.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000026#include "llvm/MC/MCContext.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000027#include "llvm/MC/MCDisassembler.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000028#include "llvm/MC/MCFunction.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000029#include "llvm/MC/MCInst.h"
30#include "llvm/MC/MCInstPrinter.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000031#include "llvm/MC/MCInstrAnalysis.h"
Craig Topper54bfde72012-04-02 06:09:36 +000032#include "llvm/MC/MCInstrInfo.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000033#include "llvm/MC/MCModule.h"
Ahmed Bougacha17926472013-08-21 07:29:02 +000034#include "llvm/MC/MCModuleYAML.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000035#include "llvm/MC/MCObjectDisassembler.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000036#include "llvm/MC/MCObjectFileInfo.h"
37#include "llvm/MC/MCObjectSymbolizer.h"
Jim Grosbachfd93a592012-03-05 19:33:20 +000038#include "llvm/MC/MCRegisterInfo.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000039#include "llvm/MC/MCRelocationInfo.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000040#include "llvm/MC/MCSubtargetInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000041#include "llvm/Object/Archive.h"
42#include "llvm/Object/COFF.h"
Rafael Espindolaa9f810b2012-12-21 03:47:03 +000043#include "llvm/Object/MachO.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000044#include "llvm/Object/ObjectFile.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000045#include "llvm/Support/Casting.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000046#include "llvm/Support/CommandLine.h"
47#include "llvm/Support/Debug.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000048#include "llvm/Support/FileSystem.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000049#include "llvm/Support/Format.h"
Benjamin Kramerbf115312011-07-25 23:04:36 +000050#include "llvm/Support/GraphWriter.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000051#include "llvm/Support/Host.h"
52#include "llvm/Support/ManagedStatic.h"
53#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000054#include "llvm/Support/MemoryObject.h"
55#include "llvm/Support/PrettyStackTrace.h"
56#include "llvm/Support/Signals.h"
57#include "llvm/Support/SourceMgr.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000058#include "llvm/Support/TargetRegistry.h"
59#include "llvm/Support/TargetSelect.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000060#include "llvm/Support/raw_ostream.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000061#include "llvm/Support/system_error.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000062#include <algorithm>
Benjamin Kramera5177e62012-03-23 11:49:32 +000063#include <cctype>
Michael J. Spencer2670c252011-01-20 06:39:06 +000064#include <cstring>
Ahmed Bougacha17926472013-08-21 07:29:02 +000065
Michael J. Spencer2670c252011-01-20 06:39:06 +000066using namespace llvm;
67using namespace object;
68
Benjamin Kramer43a772e2011-09-19 17:56:04 +000069static cl::list<std::string>
70InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
Michael J. Spencer2670c252011-01-20 06:39:06 +000071
Benjamin Kramer43a772e2011-09-19 17:56:04 +000072static cl::opt<bool>
73Disassemble("disassemble",
74 cl::desc("Display assembler mnemonics for the machine instructions"));
75static cl::alias
76Disassembled("d", cl::desc("Alias for --disassemble"),
77 cl::aliasopt(Disassemble));
Michael J. Spencer2670c252011-01-20 06:39:06 +000078
Benjamin Kramer43a772e2011-09-19 17:56:04 +000079static cl::opt<bool>
Michael J. Spencerba4a3622011-10-08 00:18:30 +000080Relocations("r", cl::desc("Display the relocation entries in the file"));
81
82static cl::opt<bool>
Michael J. Spencer4e25c022011-10-17 17:13:22 +000083SectionContents("s", cl::desc("Display the content of each section"));
84
85static cl::opt<bool>
Michael J. Spencerbfa06782011-10-18 19:32:17 +000086SymbolTable("t", cl::desc("Display the symbol table"));
87
88static cl::opt<bool>
Rafael Espindolaa9f810b2012-12-21 03:47:03 +000089MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
Benjamin Kramer43a772e2011-09-19 17:56:04 +000090static cl::alias
Rafael Espindolaa9f810b2012-12-21 03:47:03 +000091MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
Benjamin Kramer87ee76c2011-07-20 19:37:35 +000092
Benjamin Kramer43a772e2011-09-19 17:56:04 +000093cl::opt<std::string>
94llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
95 "see -version for available targets"));
96
97cl::opt<std::string>
98llvm::ArchName("arch", cl::desc("Target arch to disassemble for, "
Michael J. Spencer2670c252011-01-20 06:39:06 +000099 "see -version for available targets"));
100
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000101static cl::opt<bool>
102SectionHeaders("section-headers", cl::desc("Display summaries of the headers "
103 "for each section."));
104static cl::alias
105SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
106 cl::aliasopt(SectionHeaders));
107static cl::alias
108SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
109 cl::aliasopt(SectionHeaders));
110
Jack Carter551efd72012-08-28 19:24:49 +0000111static cl::list<std::string>
112MAttrs("mattr",
113 cl::CommaSeparated,
114 cl::desc("Target specific attributes"),
115 cl::value_desc("a1,+a2,-a3,..."));
116
Eli Bendersky3a6808c2012-11-20 22:57:02 +0000117static cl::opt<bool>
118NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling instructions, "
119 "do not print the instruction bytes."));
120
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000121static cl::opt<bool>
122UnwindInfo("unwind-info", cl::desc("Display unwind information"));
123
124static cl::alias
125UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
126 cl::aliasopt(UnwindInfo));
127
Michael J. Spencer209565db2013-01-06 03:56:49 +0000128static cl::opt<bool>
129PrivateHeaders("private-headers",
130 cl::desc("Display format specific file headers"));
131
132static cl::alias
133PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
134 cl::aliasopt(PrivateHeaders));
135
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000136static cl::opt<bool>
137Symbolize("symbolize", cl::desc("When disassembling instructions, "
138 "try to symbolize operands."));
139
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000140static cl::opt<bool>
141CFG("cfg", cl::desc("Create a CFG for every function found in the object"
142 " and write it to a graphviz file"));
143
Ahmed Bougacha17926472013-08-21 07:29:02 +0000144// FIXME: Does it make sense to have a dedicated tool for yaml cfg output?
145static cl::opt<std::string>
146YAMLCFG("yaml-cfg",
147 cl::desc("Create a CFG and write it as a YAML MCModule."),
148 cl::value_desc("yaml output file"));
149
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000150static StringRef ToolName;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000151
Mark Seaborneb03ac52014-01-25 00:32:01 +0000152bool llvm::error(error_code EC) {
153 if (!EC)
154 return false;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000155
Mark Seaborneb03ac52014-01-25 00:32:01 +0000156 outs() << ToolName << ": error reading file: " << EC.message() << ".\n";
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000157 outs().flush();
158 return true;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000159}
160
Jim Grosbachaf9aec02012-08-07 17:53:14 +0000161static const Target *getTarget(const ObjectFile *Obj = NULL) {
Michael J. Spencer2670c252011-01-20 06:39:06 +0000162 // Figure out the target triple.
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000163 llvm::Triple TheTriple("unknown-unknown-unknown");
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000164 if (TripleName.empty()) {
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000165 if (Obj) {
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000166 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000167 // TheTriple defaults to ELF, and COFF doesn't have an environment:
168 // the best we can do here is indicate that it is mach-o.
169 if (Obj->isMachO())
170 TheTriple.setEnvironment(Triple::MachO);
171 }
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000172 } else
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000173 TheTriple.setTriple(Triple::normalize(TripleName));
Michael J. Spencer2670c252011-01-20 06:39:06 +0000174
175 // Get the target specific parser.
176 std::string Error;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000177 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
178 Error);
179 if (!TheTarget) {
180 errs() << ToolName << ": " << Error;
181 return 0;
182 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000183
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000184 // Update the triple name and return the found target.
185 TripleName = TheTriple.getTriple();
186 return TheTarget;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000187}
188
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000189// Write a graphviz file for the CFG inside an MCFunction.
Ahmed Bougacha17926472013-08-21 07:29:02 +0000190// FIXME: Use GraphWriter
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000191static void emitDOTFile(const char *FileName, const MCFunction &f,
192 MCInstPrinter *IP) {
193 // Start a new dot file.
194 std::string Error;
195 raw_fd_ostream Out(FileName, Error);
196 if (!Error.empty()) {
197 errs() << "llvm-objdump: warning: " << Error << '\n';
198 return;
199 }
200
201 Out << "digraph \"" << f.getName() << "\" {\n";
202 Out << "graph [ rankdir = \"LR\" ];\n";
203 for (MCFunction::const_iterator i = f.begin(), e = f.end(); i != e; ++i) {
204 // Only print blocks that have predecessors.
205 bool hasPreds = (*i)->pred_begin() != (*i)->pred_end();
206
207 if (!hasPreds && i != f.begin())
208 continue;
209
210 Out << '"' << (*i)->getInsts()->getBeginAddr() << "\" [ label=\"<a>";
211 // Print instructions.
212 for (unsigned ii = 0, ie = (*i)->getInsts()->size(); ii != ie;
213 ++ii) {
214 if (ii != 0) // Not the first line, start a new row.
215 Out << '|';
216 if (ii + 1 == ie) // Last line, add an end id.
217 Out << "<o>";
218
219 // Escape special chars and print the instruction in mnemonic form.
220 std::string Str;
221 raw_string_ostream OS(Str);
222 IP->printInst(&(*i)->getInsts()->at(ii).Inst, OS, "");
223 Out << DOT::EscapeString(OS.str());
224 }
225 Out << "\" shape=\"record\" ];\n";
226
227 // Add edges.
228 for (MCBasicBlock::succ_const_iterator si = (*i)->succ_begin(),
229 se = (*i)->succ_end(); si != se; ++si)
230 Out << (*i)->getInsts()->getBeginAddr() << ":o -> "
231 << (*si)->getInsts()->getBeginAddr() << ":a\n";
232 }
233 Out << "}\n";
234}
David Blaikiea379b1812011-12-20 02:50:00 +0000235
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000236void llvm::DumpBytes(StringRef bytes) {
237 static const char hex_rep[] = "0123456789abcdef";
Michael J. Spencer2670c252011-01-20 06:39:06 +0000238 // FIXME: The real way to do this is to figure out the longest instruction
239 // and align to that size before printing. I'll fix this when I get
240 // around to outputting relocations.
241 // 15 is the longest x86 instruction
242 // 3 is for the hex rep of a byte + a space.
243 // 1 is for the null terminator.
244 enum { OutputSize = (15 * 3) + 1 };
245 char output[OutputSize];
246
247 assert(bytes.size() <= 15
248 && "DumpBytes only supports instructions of up to 15 bytes");
249 memset(output, ' ', sizeof(output));
250 unsigned index = 0;
251 for (StringRef::iterator i = bytes.begin(),
252 e = bytes.end(); i != e; ++i) {
253 output[index] = hex_rep[(*i & 0xF0) >> 4];
254 output[index + 1] = hex_rep[*i & 0xF];
255 index += 3;
256 }
257
258 output[sizeof(output) - 1] = 0;
259 outs() << output;
260}
261
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000262bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
Michael J. Spencer51862b32011-10-13 22:17:18 +0000263 uint64_t a_addr, b_addr;
Rafael Espindola1e483872013-04-25 12:28:45 +0000264 if (error(a.getOffset(a_addr))) return false;
265 if (error(b.getOffset(b_addr))) return false;
Michael J. Spencer51862b32011-10-13 22:17:18 +0000266 return a_addr < b_addr;
267}
268
269static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Jim Grosbachaf9aec02012-08-07 17:53:14 +0000270 const Target *TheTarget = getTarget(Obj);
271 // getTarget() will have already issued a diagnostic if necessary, so
272 // just bail here if it failed.
273 if (!TheTarget)
Michael J. Spencer2670c252011-01-20 06:39:06 +0000274 return;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000275
Jack Carter551efd72012-08-28 19:24:49 +0000276 // Package up features to be passed to target/subtarget
277 std::string FeaturesStr;
278 if (MAttrs.size()) {
279 SubtargetFeatures Features;
280 for (unsigned i = 0; i != MAttrs.size(); ++i)
281 Features.AddFeature(MAttrs[i]);
282 FeaturesStr = Features.getString();
283 }
284
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000285 OwningPtr<const MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
286 if (!MRI) {
287 errs() << "error: no register info for target " << TripleName << "\n";
288 return;
289 }
290
291 // Set up disassembler.
292 OwningPtr<const MCAsmInfo> AsmInfo(
293 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000294 if (!AsmInfo) {
295 errs() << "error: no assembly info for target " << TripleName << "\n";
296 return;
297 }
298
299 OwningPtr<const MCSubtargetInfo> STI(
300 TheTarget->createMCSubtargetInfo(TripleName, "", FeaturesStr));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000301 if (!STI) {
302 errs() << "error: no subtarget info for target " << TripleName << "\n";
303 return;
304 }
305
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000306 OwningPtr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
307 if (!MII) {
308 errs() << "error: no instruction info for target " << TripleName << "\n";
309 return;
310 }
311
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000312 OwningPtr<MCDisassembler> DisAsm(TheTarget->createMCDisassembler(*STI));
313 if (!DisAsm) {
314 errs() << "error: no disassembler for target " << TripleName << "\n";
315 return;
316 }
317
318 OwningPtr<const MCObjectFileInfo> MOFI;
319 OwningPtr<MCContext> Ctx;
320
321 if (Symbolize) {
322 MOFI.reset(new MCObjectFileInfo);
Bill Wendlingbc07a892013-06-18 07:20:20 +0000323 Ctx.reset(new MCContext(AsmInfo.get(), MRI.get(), MOFI.get()));
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000324 OwningPtr<MCRelocationInfo> RelInfo(
325 TheTarget->createMCRelocationInfo(TripleName, *Ctx.get()));
326 if (RelInfo) {
327 OwningPtr<MCSymbolizer> Symzer(
328 MCObjectSymbolizer::createObjectSymbolizer(*Ctx.get(), RelInfo, Obj));
329 if (Symzer)
330 DisAsm->setSymbolizer(Symzer);
331 }
332 }
333
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000334 OwningPtr<const MCInstrAnalysis>
335 MIA(TheTarget->createMCInstrAnalysis(MII.get()));
336
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000337 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
338 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
339 AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
340 if (!IP) {
341 errs() << "error: no instruction printer for target " << TripleName
342 << '\n';
343 return;
344 }
345
Ahmed Bougacha17926472013-08-21 07:29:02 +0000346 if (CFG || !YAMLCFG.empty()) {
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000347 OwningPtr<MCObjectDisassembler> OD(
348 new MCObjectDisassembler(*Obj, *DisAsm, *MIA));
349 OwningPtr<MCModule> Mod(OD->buildModule(/* withCFG */ true));
350 for (MCModule::const_atom_iterator AI = Mod->atom_begin(),
351 AE = Mod->atom_end();
352 AI != AE; ++AI) {
353 outs() << "Atom " << (*AI)->getName() << ": \n";
354 if (const MCTextAtom *TA = dyn_cast<MCTextAtom>(*AI)) {
355 for (MCTextAtom::const_iterator II = TA->begin(), IE = TA->end();
356 II != IE;
357 ++II) {
358 IP->printInst(&II->Inst, outs(), "");
359 outs() << "\n";
360 }
361 }
362 }
Ahmed Bougacha17926472013-08-21 07:29:02 +0000363 if (CFG) {
364 for (MCModule::const_func_iterator FI = Mod->func_begin(),
365 FE = Mod->func_end();
366 FI != FE; ++FI) {
367 static int filenum = 0;
368 emitDOTFile((Twine((*FI)->getName()) + "_" +
369 utostr(filenum) + ".dot").str().c_str(),
370 **FI, IP.get());
371 ++filenum;
372 }
373 }
374 if (!YAMLCFG.empty()) {
375 std::string Error;
376 raw_fd_ostream YAMLOut(YAMLCFG.c_str(), Error);
377 if (!Error.empty()) {
Ahmed Bougachad56f7052013-08-21 16:13:25 +0000378 errs() << ToolName << ": warning: " << Error << '\n';
Ahmed Bougacha17926472013-08-21 07:29:02 +0000379 return;
380 }
381 mcmodule2yaml(YAMLOut, *Mod, *MII, *MRI);
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000382 }
383 }
384
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000385 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
386 // in RelocSecs contain the relocations for section S.
Mark Seaborneb03ac52014-01-25 00:32:01 +0000387 error_code EC;
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000388 std::map<SectionRef, SmallVector<SectionRef, 1> > SectionRelocMap;
389 for (section_iterator I = Obj->begin_sections(), E = Obj->end_sections();
Rafael Espindola5e812af2014-01-30 02:49:50 +0000390 I != E; ++I) {
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000391 section_iterator Sec2 = I->getRelocatedSection();
392 if (Sec2 != Obj->end_sections())
393 SectionRelocMap[*Sec2].push_back(*I);
394 }
395
Mark Seaborneb03ac52014-01-25 00:32:01 +0000396 for (section_iterator I = Obj->begin_sections(), E = Obj->end_sections();
Rafael Espindola5e812af2014-01-30 02:49:50 +0000397 I != E; ++I) {
Mark Seaborneb03ac52014-01-25 00:32:01 +0000398 bool Text;
399 if (error(I->isText(Text)))
400 break;
401 if (!Text)
402 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000403
Michael J. Spencer51862b32011-10-13 22:17:18 +0000404 uint64_t SectionAddr;
Mark Seaborneb03ac52014-01-25 00:32:01 +0000405 if (error(I->getAddress(SectionAddr)))
406 break;
Michael J. Spencer51862b32011-10-13 22:17:18 +0000407
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000408 // Make a list of all the symbols in this section.
409 std::vector<std::pair<uint64_t, StringRef> > Symbols;
Mark Seaborneb03ac52014-01-25 00:32:01 +0000410 for (symbol_iterator SI = Obj->begin_symbols(), SE = Obj->end_symbols();
Rafael Espindola5e812af2014-01-30 02:49:50 +0000411 SI != SE; ++SI) {
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000412 bool contains;
Mark Seaborneb03ac52014-01-25 00:32:01 +0000413 if (!error(I->containsSymbol(*SI, contains)) && contains) {
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000414 uint64_t Address;
Mark Seaborneb03ac52014-01-25 00:32:01 +0000415 if (error(SI->getAddress(Address)))
416 break;
417 if (Address == UnknownAddressOrSize)
418 continue;
Cameron Zwarich07f0f772012-02-03 04:13:37 +0000419 Address -= SectionAddr;
420
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000421 StringRef Name;
Mark Seaborneb03ac52014-01-25 00:32:01 +0000422 if (error(SI->getName(Name)))
423 break;
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000424 Symbols.push_back(std::make_pair(Address, Name));
425 }
426 }
427
428 // Sort the symbols by address, just in case they didn't come in that way.
429 array_pod_sort(Symbols.begin(), Symbols.end());
430
Michael J. Spencer51862b32011-10-13 22:17:18 +0000431 // Make a list of all the relocations for this section.
432 std::vector<RelocationRef> Rels;
433 if (InlineRelocs) {
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000434 SmallVectorImpl<SectionRef> *RelocSecs = &SectionRelocMap[*I];
435 for (SmallVectorImpl<SectionRef>::iterator RelocSec = RelocSecs->begin(),
436 E = RelocSecs->end();
437 RelocSec != E; ++RelocSec) {
438 for (relocation_iterator RI = RelocSec->begin_relocations(),
439 RE = RelocSec->end_relocations();
Rafael Espindola5e812af2014-01-30 02:49:50 +0000440 RI != RE; ++RI)
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000441 Rels.push_back(*RI);
Michael J. Spencer51862b32011-10-13 22:17:18 +0000442 }
443 }
444
445 // Sort relocations by address.
446 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
447
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000448 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +0000449 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
450 DataRefImpl DR = I->getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +0000451 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000452 }
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000453 StringRef name;
Mark Seaborneb03ac52014-01-25 00:32:01 +0000454 if (error(I->getName(name)))
455 break;
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000456 outs() << "Disassembly of section ";
457 if (!SegmentName.empty())
458 outs() << SegmentName << ",";
459 outs() << name << ':';
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000460
461 // If the section has no symbols just insert a dummy one and disassemble
462 // the whole section.
463 if (Symbols.empty())
464 Symbols.push_back(std::make_pair(0, name));
Michael J. Spencer2670c252011-01-20 06:39:06 +0000465
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000466
467 SmallString<40> Comments;
468 raw_svector_ostream CommentStream(Comments);
469
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000470 StringRef Bytes;
Mark Seaborneb03ac52014-01-25 00:32:01 +0000471 if (error(I->getContents(Bytes)))
472 break;
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000473 StringRefMemoryObject memoryObject(Bytes, SectionAddr);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000474 uint64_t Size;
475 uint64_t Index;
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000476 uint64_t SectSize;
Mark Seaborneb03ac52014-01-25 00:32:01 +0000477 if (error(I->getSize(SectSize)))
478 break;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000479
Michael J. Spencer51862b32011-10-13 22:17:18 +0000480 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
481 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000482 // Disassemble symbol by symbol.
483 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
484 uint64_t Start = Symbols[si].first;
Michael J. Spenceree84f642011-10-13 20:37:08 +0000485 uint64_t End;
486 // The end is either the size of the section or the beginning of the next
487 // symbol.
488 if (si == se - 1)
489 End = SectSize;
490 // Make sure this symbol takes up space.
491 else if (Symbols[si + 1].first != Start)
492 End = Symbols[si + 1].first - 1;
493 else
494 // This symbol has the same address as the next symbol. Skip it.
495 continue;
496
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000497 outs() << '\n' << Symbols[si].second << ":\n";
Michael J. Spencer2670c252011-01-20 06:39:06 +0000498
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000499#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +0000500 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000501#else
Mark Seaborneb03ac52014-01-25 00:32:01 +0000502 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000503#endif
504
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000505 for (Index = Start; Index < End; Index += Size) {
506 MCInst Inst;
Owen Andersona0c3b972011-09-15 23:38:46 +0000507
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000508 if (DisAsm->getInstruction(Inst, Size, memoryObject,
509 SectionAddr + Index,
510 DebugOut, CommentStream)) {
Eli Bendersky3a6808c2012-11-20 22:57:02 +0000511 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
512 if (!NoShowRawInsn) {
513 outs() << "\t";
514 DumpBytes(StringRef(Bytes.data() + Index, Size));
515 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000516 IP->printInst(&Inst, outs(), "");
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000517 outs() << CommentStream.str();
518 Comments.clear();
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000519 outs() << "\n";
520 } else {
521 errs() << ToolName << ": warning: invalid instruction encoding\n";
522 if (Size == 0)
523 Size = 1; // skip illegible bytes
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000524 }
Michael J. Spencer51862b32011-10-13 22:17:18 +0000525
526 // Print relocation for instruction.
527 while (rel_cur != rel_end) {
Owen Andersonfa3e5202011-10-25 20:35:53 +0000528 bool hidden = false;
Michael J. Spencer51862b32011-10-13 22:17:18 +0000529 uint64_t addr;
530 SmallString<16> name;
531 SmallString<32> val;
Owen Andersonfa3e5202011-10-25 20:35:53 +0000532
533 // If this relocation is hidden, skip it.
534 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
535 if (hidden) goto skip_print_rel;
536
Rafael Espindola1e483872013-04-25 12:28:45 +0000537 if (error(rel_cur->getOffset(addr))) goto skip_print_rel;
Michael J. Spencer51862b32011-10-13 22:17:18 +0000538 // Stop when rel_cur's address is past the current instruction.
Owen Andersonf20e3e52011-10-25 20:15:39 +0000539 if (addr >= Index + Size) break;
Michael J. Spencer51862b32011-10-13 22:17:18 +0000540 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
541 if (error(rel_cur->getValueString(val))) goto skip_print_rel;
542
Benjamin Kramer82803112012-03-10 02:04:38 +0000543 outs() << format("\t\t\t%8" PRIx64 ": ", SectionAddr + addr) << name
544 << "\t" << val << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +0000545
546 skip_print_rel:
547 ++rel_cur;
548 }
Benjamin Kramer87ee76c2011-07-20 19:37:35 +0000549 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000550 }
551 }
552}
553
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000554static void PrintRelocations(const ObjectFile *o) {
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000555 for (section_iterator si = o->begin_sections(), se = o->end_sections();
Rafael Espindola5e812af2014-01-30 02:49:50 +0000556 si != se; ++si) {
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000557 if (si->begin_relocations() == si->end_relocations())
558 continue;
559 StringRef secname;
560 if (error(si->getName(secname))) continue;
561 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
562 for (relocation_iterator ri = si->begin_relocations(),
563 re = si->end_relocations();
Rafael Espindola5e812af2014-01-30 02:49:50 +0000564 ri != re; ++ri) {
Owen Andersonfa3e5202011-10-25 20:35:53 +0000565 bool hidden;
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000566 uint64_t address;
567 SmallString<32> relocname;
568 SmallString<32> valuestr;
Owen Andersonfa3e5202011-10-25 20:35:53 +0000569 if (error(ri->getHidden(hidden))) continue;
570 if (hidden) continue;
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000571 if (error(ri->getTypeName(relocname))) continue;
Rafael Espindola1e483872013-04-25 12:28:45 +0000572 if (error(ri->getOffset(address))) continue;
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000573 if (error(ri->getValueString(valuestr))) continue;
574 outs() << address << " " << relocname << " " << valuestr << "\n";
575 }
576 outs() << "\n";
577 }
578}
579
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000580static void PrintSectionHeaders(const ObjectFile *o) {
581 outs() << "Sections:\n"
582 "Idx Name Size Address Type\n";
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000583 unsigned i = 0;
584 for (section_iterator si = o->begin_sections(), se = o->end_sections();
Rafael Espindola5e812af2014-01-30 02:49:50 +0000585 si != se; ++si) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000586 StringRef Name;
Mark Seaborneb03ac52014-01-25 00:32:01 +0000587 if (error(si->getName(Name)))
588 return;
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000589 uint64_t Address;
590 if (error(si->getAddress(Address))) return;
591 uint64_t Size;
592 if (error(si->getSize(Size))) return;
593 bool Text, Data, BSS;
594 if (error(si->isText(Text))) return;
595 if (error(si->isData(Data))) return;
596 if (error(si->isBSS(BSS))) return;
597 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +0000598 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
Michael J. Spencerd857c1c2013-01-10 22:40:50 +0000599 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n",
Benjamin Kramer82803112012-03-10 02:04:38 +0000600 i, Name.str().c_str(), Size, Address, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000601 ++i;
602 }
603}
604
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000605static void PrintSectionContents(const ObjectFile *o) {
Mark Seaborneb03ac52014-01-25 00:32:01 +0000606 error_code EC;
607 for (section_iterator si = o->begin_sections(), se = o->end_sections();
Rafael Espindola5e812af2014-01-30 02:49:50 +0000608 si != se; ++si) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000609 StringRef Name;
610 StringRef Contents;
611 uint64_t BaseAddr;
Alexey Samsonov209095c2013-04-16 10:53:11 +0000612 bool BSS;
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000613 if (error(si->getName(Name))) continue;
614 if (error(si->getContents(Contents))) continue;
615 if (error(si->getAddress(BaseAddr))) continue;
Alexey Samsonov209095c2013-04-16 10:53:11 +0000616 if (error(si->isBSS(BSS))) continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000617
618 outs() << "Contents of section " << Name << ":\n";
Alexey Samsonov209095c2013-04-16 10:53:11 +0000619 if (BSS) {
620 outs() << format("<skipping contents of bss section at [%04" PRIx64
621 ", %04" PRIx64 ")>\n", BaseAddr,
622 BaseAddr + Contents.size());
623 continue;
624 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000625
626 // Dump out the content as hex and printable ascii characters.
627 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer82803112012-03-10 02:04:38 +0000628 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000629 // Dump line of hex.
630 for (std::size_t i = 0; i < 16; ++i) {
631 if (i != 0 && i % 4 == 0)
632 outs() << ' ';
633 if (addr + i < end)
634 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
635 << hexdigit(Contents[addr + i] & 0xF, true);
636 else
637 outs() << " ";
638 }
639 // Print ascii.
640 outs() << " ";
641 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
Guy Benyei83c74e92013-02-12 21:21:59 +0000642 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000643 outs() << Contents[addr + i];
644 else
645 outs() << ".";
646 }
647 outs() << "\n";
648 }
649 }
650}
651
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000652static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
653 const coff_file_header *header;
654 if (error(coff->getHeader(header))) return;
655 int aux_count = 0;
656 const coff_symbol *symbol = 0;
657 for (int i = 0, e = header->NumberOfSymbols; i != e; ++i) {
658 if (aux_count--) {
659 // Figure out which type of aux this is.
660 if (symbol->StorageClass == COFF::IMAGE_SYM_CLASS_STATIC
661 && symbol->Value == 0) { // Section definition.
662 const coff_aux_section_definition *asd;
663 if (error(coff->getAuxSymbol<coff_aux_section_definition>(i, asd)))
664 return;
665 outs() << "AUX "
666 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
667 , unsigned(asd->Length)
668 , unsigned(asd->NumberOfRelocations)
669 , unsigned(asd->NumberOfLinenumbers)
670 , unsigned(asd->CheckSum))
671 << format("assoc %d comdat %d\n"
672 , unsigned(asd->Number)
673 , unsigned(asd->Selection));
Jim Grosbachaf9aec02012-08-07 17:53:14 +0000674 } else
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000675 outs() << "AUX Unknown\n";
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000676 } else {
677 StringRef name;
678 if (error(coff->getSymbol(i, symbol))) return;
679 if (error(coff->getSymbolName(symbol, name))) return;
680 outs() << "[" << format("%2d", i) << "]"
681 << "(sec " << format("%2d", int(symbol->SectionNumber)) << ")"
682 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
683 << "(ty " << format("%3x", unsigned(symbol->Type)) << ")"
684 << "(scl " << format("%3x", unsigned(symbol->StorageClass)) << ") "
685 << "(nx " << unsigned(symbol->NumberOfAuxSymbols) << ") "
686 << "0x" << format("%08x", unsigned(symbol->Value)) << " "
687 << name << "\n";
688 aux_count = symbol->NumberOfAuxSymbols;
689 }
690 }
691}
692
693static void PrintSymbolTable(const ObjectFile *o) {
694 outs() << "SYMBOL TABLE:\n";
695
696 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o))
697 PrintCOFFSymbolTable(coff);
698 else {
Mark Seaborneb03ac52014-01-25 00:32:01 +0000699 for (symbol_iterator si = o->begin_symbols(), se = o->end_symbols();
Rafael Espindola5e812af2014-01-30 02:49:50 +0000700 si != se; ++si) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000701 StringRef Name;
Danil Malyshevcbe72fc2011-11-29 17:40:10 +0000702 uint64_t Address;
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000703 SymbolRef::Type Type;
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000704 uint64_t Size;
Rafael Espindola20122a42014-01-31 20:57:12 +0000705 uint32_t Flags = si->getFlags();
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000706 section_iterator Section = o->end_sections();
707 if (error(si->getName(Name))) continue;
Danil Malyshevcbe72fc2011-11-29 17:40:10 +0000708 if (error(si->getAddress(Address))) continue;
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000709 if (error(si->getType(Type))) continue;
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000710 if (error(si->getSize(Size))) continue;
711 if (error(si->getSection(Section))) continue;
712
David Meyer1df4b842012-02-28 23:47:53 +0000713 bool Global = Flags & SymbolRef::SF_Global;
714 bool Weak = Flags & SymbolRef::SF_Weak;
715 bool Absolute = Flags & SymbolRef::SF_Absolute;
716
Danil Malyshevcbe72fc2011-11-29 17:40:10 +0000717 if (Address == UnknownAddressOrSize)
718 Address = 0;
719 if (Size == UnknownAddressOrSize)
720 Size = 0;
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000721 char GlobLoc = ' ';
David Meyer7e4b9762012-02-29 02:11:55 +0000722 if (Type != SymbolRef::ST_Unknown)
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000723 GlobLoc = Global ? 'g' : 'l';
724 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
725 ? 'd' : ' ';
726 char FileFunc = ' ';
727 if (Type == SymbolRef::ST_File)
728 FileFunc = 'f';
729 else if (Type == SymbolRef::ST_Function)
730 FileFunc = 'F';
731
Michael J. Spencerd857c1c2013-01-10 22:40:50 +0000732 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
733 "%08" PRIx64;
734
735 outs() << format(Fmt, Address) << " "
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000736 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
737 << (Weak ? 'w' : ' ') // Weak?
738 << ' ' // Constructor. Not supported yet.
739 << ' ' // Warning. Not supported yet.
740 << ' ' // Indirect reference to another symbol.
741 << Debug // Debugging (d) or dynamic (D) symbol.
742 << FileFunc // Name of function (F), file (f) or object (O).
743 << ' ';
744 if (Absolute)
745 outs() << "*ABS*";
746 else if (Section == o->end_sections())
747 outs() << "*UND*";
748 else {
Rafael Espindola56f976f2013-04-18 18:08:55 +0000749 if (const MachOObjectFile *MachO =
750 dyn_cast<const MachOObjectFile>(o)) {
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000751 DataRefImpl DR = Section->getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +0000752 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000753 outs() << SegmentName << ",";
754 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000755 StringRef SectionName;
756 if (error(Section->getName(SectionName)))
757 SectionName = "";
758 outs() << SectionName;
759 }
760 outs() << '\t'
Benjamin Kramer82803112012-03-10 02:04:38 +0000761 << format("%08" PRIx64 " ", Size)
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000762 << Name
763 << '\n';
764 }
765 }
766}
767
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000768static void PrintUnwindInfo(const ObjectFile *o) {
769 outs() << "Unwind info:\n\n";
770
771 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
772 printCOFFUnwindInfo(coff);
773 } else {
774 // TODO: Extract DWARF dump tool to objdump.
775 errs() << "This operation is only currently supported "
776 "for COFF object files.\n";
777 return;
778 }
779}
780
Rui Ueyamac2bed422013-09-27 21:04:00 +0000781static void printPrivateFileHeader(const ObjectFile *o) {
782 if (o->isELF()) {
783 printELFFileHeader(o);
784 } else if (o->isCOFF()) {
785 printCOFFFileHeader(o);
786 }
787}
788
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000789static void DumpObject(const ObjectFile *o) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000790 outs() << '\n';
791 outs() << o->getFileName()
792 << ":\tfile format " << o->getFileFormatName() << "\n\n";
793
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000794 if (Disassemble)
Michael J. Spencer51862b32011-10-13 22:17:18 +0000795 DisassembleObject(o, Relocations);
796 if (Relocations && !Disassemble)
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000797 PrintRelocations(o);
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000798 if (SectionHeaders)
799 PrintSectionHeaders(o);
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000800 if (SectionContents)
801 PrintSectionContents(o);
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000802 if (SymbolTable)
803 PrintSymbolTable(o);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000804 if (UnwindInfo)
805 PrintUnwindInfo(o);
Rui Ueyamac2bed422013-09-27 21:04:00 +0000806 if (PrivateHeaders)
807 printPrivateFileHeader(o);
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000808}
809
810/// @brief Dump each object file in \a a;
811static void DumpArchive(const Archive *a) {
Mark Seaborneb03ac52014-01-25 00:32:01 +0000812 for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
813 ++i) {
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000814 OwningPtr<Binary> child;
Mark Seaborneb03ac52014-01-25 00:32:01 +0000815 if (error_code EC = i->getAsBinary(child)) {
Michael J. Spencer53723de2011-11-16 01:24:41 +0000816 // Ignore non-object files.
Mark Seaborneb03ac52014-01-25 00:32:01 +0000817 if (EC != object_error::invalid_file_type)
818 errs() << ToolName << ": '" << a->getFileName() << "': " << EC.message()
Michael J. Spencer53723de2011-11-16 01:24:41 +0000819 << ".\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000820 continue;
821 }
822 if (ObjectFile *o = dyn_cast<ObjectFile>(child.get()))
823 DumpObject(o);
824 else
825 errs() << ToolName << ": '" << a->getFileName() << "': "
826 << "Unrecognized file type.\n";
827 }
828}
829
830/// @brief Open file and figure out how to dump it.
831static void DumpInput(StringRef file) {
832 // If file isn't stdin, check that it exists.
833 if (file != "-" && !sys::fs::exists(file)) {
834 errs() << ToolName << ": '" << file << "': " << "No such file\n";
835 return;
836 }
837
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000838 if (MachOOpt && Disassemble) {
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000839 DisassembleInputMachO(file);
840 return;
841 }
842
843 // Attempt to open the binary.
Rafael Espindola63da2952014-01-15 19:37:43 +0000844 ErrorOr<Binary *> BinaryOrErr = createBinary(file);
845 if (error_code EC = BinaryOrErr.getError()) {
846 errs() << ToolName << ": '" << file << "': " << EC.message() << ".\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000847 return;
848 }
Rafael Espindola63da2952014-01-15 19:37:43 +0000849 OwningPtr<Binary> binary(BinaryOrErr.get());
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000850
Jim Grosbachaf9aec02012-08-07 17:53:14 +0000851 if (Archive *a = dyn_cast<Archive>(binary.get()))
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000852 DumpArchive(a);
Jim Grosbachaf9aec02012-08-07 17:53:14 +0000853 else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get()))
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000854 DumpObject(o);
Jim Grosbachaf9aec02012-08-07 17:53:14 +0000855 else
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000856 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000857}
858
Michael J. Spencer2670c252011-01-20 06:39:06 +0000859int main(int argc, char **argv) {
860 // Print a stack trace if we signal out.
861 sys::PrintStackTraceOnErrorSignal();
862 PrettyStackTraceProgram X(argc, argv);
863 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
864
865 // Initialize targets and assembly printers/parsers.
866 llvm::InitializeAllTargetInfos();
Evan Cheng8c886a42011-07-22 21:58:54 +0000867 llvm::InitializeAllTargetMCs();
Michael J. Spencer2670c252011-01-20 06:39:06 +0000868 llvm::InitializeAllAsmParsers();
869 llvm::InitializeAllDisassemblers();
870
Pete Cooper28fb4fc2012-05-03 23:20:10 +0000871 // Register the target printer for --version.
872 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
873
Michael J. Spencer2670c252011-01-20 06:39:06 +0000874 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
875 TripleName = Triple::normalize(TripleName);
876
877 ToolName = argv[0];
878
879 // Defaults to a.out if no filenames specified.
880 if (InputFilenames.size() == 0)
881 InputFilenames.push_back("a.out");
882
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000883 if (!Disassemble
884 && !Relocations
885 && !SectionHeaders
886 && !SectionContents
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000887 && !SymbolTable
Michael J. Spencer209565db2013-01-06 03:56:49 +0000888 && !UnwindInfo
889 && !PrivateHeaders) {
Michael J. Spencer2670c252011-01-20 06:39:06 +0000890 cl::PrintHelpMessage();
891 return 2;
892 }
893
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000894 std::for_each(InputFilenames.begin(), InputFilenames.end(),
895 DumpInput);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000896
897 return 0;
898}