blob: ebcee3b7f632768ae696136961e06a9ff166908f [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"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000020#include "llvm/ADT/STLExtras.h"
Michael J. Spencer4e25c022011-10-17 17:13:22 +000021#include "llvm/ADT/StringExtras.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000022#include "llvm/ADT/Triple.h"
Rafael Espindolacbc5ac72014-07-02 19:49:34 +000023#include "llvm/MC/MCAnalysis/MCAtom.h"
24#include "llvm/MC/MCAnalysis/MCFunction.h"
25#include "llvm/MC/MCAnalysis/MCModule.h"
26#include "llvm/MC/MCAnalysis/MCModuleYAML.h"
Rafael Espindola3f0549f2014-07-31 19:29:23 +000027#include "llvm/MC/MCAnalysis/MCObjectSymbolizer.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000028#include "llvm/MC/MCAsmInfo.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000029#include "llvm/MC/MCContext.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000030#include "llvm/MC/MCDisassembler.h"
31#include "llvm/MC/MCInst.h"
32#include "llvm/MC/MCInstPrinter.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000033#include "llvm/MC/MCInstrAnalysis.h"
Craig Topper54bfde72012-04-02 06:09:36 +000034#include "llvm/MC/MCInstrInfo.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"
Jim Grosbachfd93a592012-03-05 19:33:20 +000037#include "llvm/MC/MCRegisterInfo.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000038#include "llvm/MC/MCRelocationInfo.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000039#include "llvm/MC/MCSubtargetInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000040#include "llvm/Object/Archive.h"
41#include "llvm/Object/COFF.h"
Rafael Espindolaa9f810b2012-12-21 03:47:03 +000042#include "llvm/Object/MachO.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000043#include "llvm/Object/ObjectFile.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000044#include "llvm/Support/Casting.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000045#include "llvm/Support/CommandLine.h"
46#include "llvm/Support/Debug.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000047#include "llvm/Support/FileSystem.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000048#include "llvm/Support/Format.h"
Benjamin Kramerbf115312011-07-25 23:04:36 +000049#include "llvm/Support/GraphWriter.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000050#include "llvm/Support/Host.h"
51#include "llvm/Support/ManagedStatic.h"
52#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000053#include "llvm/Support/MemoryObject.h"
54#include "llvm/Support/PrettyStackTrace.h"
55#include "llvm/Support/Signals.h"
56#include "llvm/Support/SourceMgr.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000057#include "llvm/Support/TargetRegistry.h"
58#include "llvm/Support/TargetSelect.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000059#include "llvm/Support/raw_ostream.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000060#include <algorithm>
Benjamin Kramera5177e62012-03-23 11:49:32 +000061#include <cctype>
Michael J. Spencer2670c252011-01-20 06:39:06 +000062#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000063#include <system_error>
Ahmed Bougacha17926472013-08-21 07:29:02 +000064
Michael J. Spencer2670c252011-01-20 06:39:06 +000065using namespace llvm;
66using namespace object;
67
Benjamin Kramer43a772e2011-09-19 17:56:04 +000068static cl::list<std::string>
69InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
Michael J. Spencer2670c252011-01-20 06:39:06 +000070
Benjamin Kramer43a772e2011-09-19 17:56:04 +000071static cl::opt<bool>
72Disassemble("disassemble",
73 cl::desc("Display assembler mnemonics for the machine instructions"));
74static cl::alias
75Disassembled("d", cl::desc("Alias for --disassemble"),
76 cl::aliasopt(Disassemble));
Michael J. Spencer2670c252011-01-20 06:39:06 +000077
Benjamin Kramer43a772e2011-09-19 17:56:04 +000078static cl::opt<bool>
Michael J. Spencerba4a3622011-10-08 00:18:30 +000079Relocations("r", cl::desc("Display the relocation entries in the file"));
80
81static cl::opt<bool>
Michael J. Spencer4e25c022011-10-17 17:13:22 +000082SectionContents("s", cl::desc("Display the content of each section"));
83
84static cl::opt<bool>
Michael J. Spencerbfa06782011-10-18 19:32:17 +000085SymbolTable("t", cl::desc("Display the symbol table"));
86
87static cl::opt<bool>
Rafael Espindolaa9f810b2012-12-21 03:47:03 +000088MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
Benjamin Kramer43a772e2011-09-19 17:56:04 +000089static cl::alias
Rafael Espindolaa9f810b2012-12-21 03:47:03 +000090MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
Benjamin Kramer87ee76c2011-07-20 19:37:35 +000091
Benjamin Kramer43a772e2011-09-19 17:56:04 +000092cl::opt<std::string>
93llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
94 "see -version for available targets"));
95
96cl::opt<std::string>
Kevin Enderbyc9595622014-08-06 23:24:41 +000097llvm::MCPU("mcpu",
98 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
99 cl::value_desc("cpu-name"),
100 cl::init(""));
101
102cl::opt<std::string>
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000103llvm::ArchName("arch", cl::desc("Target arch to disassemble for, "
Michael J. Spencer2670c252011-01-20 06:39:06 +0000104 "see -version for available targets"));
105
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000106static cl::opt<bool>
107SectionHeaders("section-headers", cl::desc("Display summaries of the headers "
108 "for each section."));
109static cl::alias
110SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
111 cl::aliasopt(SectionHeaders));
112static cl::alias
113SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
114 cl::aliasopt(SectionHeaders));
115
Kevin Enderbyc9595622014-08-06 23:24:41 +0000116cl::list<std::string>
117llvm::MAttrs("mattr",
Jack Carter551efd72012-08-28 19:24:49 +0000118 cl::CommaSeparated,
119 cl::desc("Target specific attributes"),
120 cl::value_desc("a1,+a2,-a3,..."));
121
Eli Bendersky3a6808c2012-11-20 22:57:02 +0000122static cl::opt<bool>
123NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling instructions, "
124 "do not print the instruction bytes."));
125
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000126static cl::opt<bool>
127UnwindInfo("unwind-info", cl::desc("Display unwind information"));
128
129static cl::alias
130UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
131 cl::aliasopt(UnwindInfo));
132
Michael J. Spencer209565db2013-01-06 03:56:49 +0000133static cl::opt<bool>
134PrivateHeaders("private-headers",
135 cl::desc("Display format specific file headers"));
136
137static cl::alias
138PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
139 cl::aliasopt(PrivateHeaders));
140
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000141static cl::opt<bool>
142Symbolize("symbolize", cl::desc("When disassembling instructions, "
143 "try to symbolize operands."));
144
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000145static cl::opt<bool>
146CFG("cfg", cl::desc("Create a CFG for every function found in the object"
147 " and write it to a graphviz file"));
148
Ahmed Bougacha17926472013-08-21 07:29:02 +0000149// FIXME: Does it make sense to have a dedicated tool for yaml cfg output?
150static cl::opt<std::string>
151YAMLCFG("yaml-cfg",
152 cl::desc("Create a CFG and write it as a YAML MCModule."),
153 cl::value_desc("yaml output file"));
154
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000155static StringRef ToolName;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000156
Rafael Espindola4453e42942014-06-13 03:07:50 +0000157bool llvm::error(std::error_code EC) {
Mark Seaborneb03ac52014-01-25 00:32:01 +0000158 if (!EC)
159 return false;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000160
Mark Seaborneb03ac52014-01-25 00:32:01 +0000161 outs() << ToolName << ": error reading file: " << EC.message() << ".\n";
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000162 outs().flush();
163 return true;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000164}
165
Craig Toppere6cb63e2014-04-25 04:24:47 +0000166static const Target *getTarget(const ObjectFile *Obj = nullptr) {
Michael J. Spencer2670c252011-01-20 06:39:06 +0000167 // Figure out the target triple.
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000168 llvm::Triple TheTriple("unknown-unknown-unknown");
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000169 if (TripleName.empty()) {
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000170 if (Obj) {
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000171 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000172 // TheTriple defaults to ELF, and COFF doesn't have an environment:
173 // the best we can do here is indicate that it is mach-o.
174 if (Obj->isMachO())
Saleem Abdulrasool35476332014-03-06 20:47:11 +0000175 TheTriple.setObjectFormat(Triple::MachO);
Saleem Abdulrasool98938f12014-04-17 06:17:23 +0000176
177 if (Obj->isCOFF()) {
178 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
179 if (COFFObj->getArch() == Triple::thumb)
180 TheTriple.setTriple("thumbv7-windows");
181 }
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000182 }
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000183 } else
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000184 TheTriple.setTriple(Triple::normalize(TripleName));
Michael J. Spencer2670c252011-01-20 06:39:06 +0000185
186 // Get the target specific parser.
187 std::string Error;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000188 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
189 Error);
190 if (!TheTarget) {
191 errs() << ToolName << ": " << Error;
Craig Toppere6cb63e2014-04-25 04:24:47 +0000192 return nullptr;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000193 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000194
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000195 // Update the triple name and return the found target.
196 TripleName = TheTriple.getTriple();
197 return TheTarget;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000198}
199
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000200// Write a graphviz file for the CFG inside an MCFunction.
Ahmed Bougacha17926472013-08-21 07:29:02 +0000201// FIXME: Use GraphWriter
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000202static void emitDOTFile(const char *FileName, const MCFunction &f,
203 MCInstPrinter *IP) {
204 // Start a new dot file.
205 std::string Error;
Rafael Espindola90c7f1c2014-02-24 18:20:12 +0000206 raw_fd_ostream Out(FileName, Error, sys::fs::F_Text);
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000207 if (!Error.empty()) {
208 errs() << "llvm-objdump: warning: " << Error << '\n';
209 return;
210 }
211
212 Out << "digraph \"" << f.getName() << "\" {\n";
213 Out << "graph [ rankdir = \"LR\" ];\n";
214 for (MCFunction::const_iterator i = f.begin(), e = f.end(); i != e; ++i) {
215 // Only print blocks that have predecessors.
216 bool hasPreds = (*i)->pred_begin() != (*i)->pred_end();
217
218 if (!hasPreds && i != f.begin())
219 continue;
220
221 Out << '"' << (*i)->getInsts()->getBeginAddr() << "\" [ label=\"<a>";
222 // Print instructions.
223 for (unsigned ii = 0, ie = (*i)->getInsts()->size(); ii != ie;
224 ++ii) {
225 if (ii != 0) // Not the first line, start a new row.
226 Out << '|';
227 if (ii + 1 == ie) // Last line, add an end id.
228 Out << "<o>";
229
230 // Escape special chars and print the instruction in mnemonic form.
Alp Tokere69170a2014-06-26 22:52:05 +0000231 std::string Str;
232 raw_string_ostream OS(Str);
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000233 IP->printInst(&(*i)->getInsts()->at(ii).Inst, OS, "");
234 Out << DOT::EscapeString(OS.str());
235 }
236 Out << "\" shape=\"record\" ];\n";
237
238 // Add edges.
239 for (MCBasicBlock::succ_const_iterator si = (*i)->succ_begin(),
240 se = (*i)->succ_end(); si != se; ++si)
241 Out << (*i)->getInsts()->getBeginAddr() << ":o -> "
242 << (*si)->getInsts()->getBeginAddr() << ":a\n";
243 }
244 Out << "}\n";
245}
David Blaikiea379b1812011-12-20 02:50:00 +0000246
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000247void llvm::DumpBytes(StringRef bytes) {
248 static const char hex_rep[] = "0123456789abcdef";
Michael J. Spencer2670c252011-01-20 06:39:06 +0000249 // FIXME: The real way to do this is to figure out the longest instruction
250 // and align to that size before printing. I'll fix this when I get
251 // around to outputting relocations.
252 // 15 is the longest x86 instruction
253 // 3 is for the hex rep of a byte + a space.
254 // 1 is for the null terminator.
255 enum { OutputSize = (15 * 3) + 1 };
256 char output[OutputSize];
257
258 assert(bytes.size() <= 15
259 && "DumpBytes only supports instructions of up to 15 bytes");
260 memset(output, ' ', sizeof(output));
261 unsigned index = 0;
262 for (StringRef::iterator i = bytes.begin(),
263 e = bytes.end(); i != e; ++i) {
264 output[index] = hex_rep[(*i & 0xF0) >> 4];
265 output[index + 1] = hex_rep[*i & 0xF];
266 index += 3;
267 }
268
269 output[sizeof(output) - 1] = 0;
270 outs() << output;
271}
272
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000273bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
Michael J. Spencer51862b32011-10-13 22:17:18 +0000274 uint64_t a_addr, b_addr;
Rafael Espindola1e483872013-04-25 12:28:45 +0000275 if (error(a.getOffset(a_addr))) return false;
276 if (error(b.getOffset(b_addr))) return false;
Michael J. Spencer51862b32011-10-13 22:17:18 +0000277 return a_addr < b_addr;
278}
279
280static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Jim Grosbachaf9aec02012-08-07 17:53:14 +0000281 const Target *TheTarget = getTarget(Obj);
282 // getTarget() will have already issued a diagnostic if necessary, so
283 // just bail here if it failed.
284 if (!TheTarget)
Michael J. Spencer2670c252011-01-20 06:39:06 +0000285 return;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000286
Jack Carter551efd72012-08-28 19:24:49 +0000287 // Package up features to be passed to target/subtarget
288 std::string FeaturesStr;
289 if (MAttrs.size()) {
290 SubtargetFeatures Features;
291 for (unsigned i = 0; i != MAttrs.size(); ++i)
292 Features.AddFeature(MAttrs[i]);
293 FeaturesStr = Features.getString();
294 }
295
Ahmed Charles56440fd2014-03-06 05:51:42 +0000296 std::unique_ptr<const MCRegisterInfo> MRI(
297 TheTarget->createMCRegInfo(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000298 if (!MRI) {
299 errs() << "error: no register info for target " << TripleName << "\n";
300 return;
301 }
302
303 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000304 std::unique_ptr<const MCAsmInfo> AsmInfo(
305 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000306 if (!AsmInfo) {
307 errs() << "error: no assembly info for target " << TripleName << "\n";
308 return;
309 }
310
Ahmed Charles56440fd2014-03-06 05:51:42 +0000311 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +0000312 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000313 if (!STI) {
314 errs() << "error: no subtarget info for target " << TripleName << "\n";
315 return;
316 }
317
Ahmed Charles56440fd2014-03-06 05:51:42 +0000318 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000319 if (!MII) {
320 errs() << "error: no instruction info for target " << TripleName << "\n";
321 return;
322 }
323
Lang Hamesa1bc0f52014-04-15 04:40:56 +0000324 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
325 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
326
327 std::unique_ptr<MCDisassembler> DisAsm(
328 TheTarget->createMCDisassembler(*STI, Ctx));
329
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000330 if (!DisAsm) {
331 errs() << "error: no disassembler for target " << TripleName << "\n";
332 return;
333 }
334
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000335
336 if (Symbolize) {
Ahmed Charles56440fd2014-03-06 05:51:42 +0000337 std::unique_ptr<MCRelocationInfo> RelInfo(
Lang Hamesa1bc0f52014-04-15 04:40:56 +0000338 TheTarget->createMCRelocationInfo(TripleName, Ctx));
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000339 if (RelInfo) {
Ahmed Charles56440fd2014-03-06 05:51:42 +0000340 std::unique_ptr<MCSymbolizer> Symzer(
Lang Hamesa1bc0f52014-04-15 04:40:56 +0000341 MCObjectSymbolizer::createObjectSymbolizer(Ctx, std::move(RelInfo),
342 Obj));
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000343 if (Symzer)
Ahmed Charlesdf17c832014-03-07 09:38:02 +0000344 DisAsm->setSymbolizer(std::move(Symzer));
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000345 }
346 }
347
Ahmed Charles56440fd2014-03-06 05:51:42 +0000348 std::unique_ptr<const MCInstrAnalysis> MIA(
349 TheTarget->createMCInstrAnalysis(MII.get()));
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000350
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000351 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +0000352 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000353 AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
354 if (!IP) {
355 errs() << "error: no instruction printer for target " << TripleName
356 << '\n';
357 return;
358 }
359
Ahmed Bougacha17926472013-08-21 07:29:02 +0000360 if (CFG || !YAMLCFG.empty()) {
Ahmed Charles56440fd2014-03-06 05:51:42 +0000361 std::unique_ptr<MCObjectDisassembler> OD(
362 new MCObjectDisassembler(*Obj, *DisAsm, *MIA));
363 std::unique_ptr<MCModule> Mod(OD->buildModule(/* withCFG */ true));
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000364 for (MCModule::const_atom_iterator AI = Mod->atom_begin(),
365 AE = Mod->atom_end();
366 AI != AE; ++AI) {
367 outs() << "Atom " << (*AI)->getName() << ": \n";
368 if (const MCTextAtom *TA = dyn_cast<MCTextAtom>(*AI)) {
369 for (MCTextAtom::const_iterator II = TA->begin(), IE = TA->end();
370 II != IE;
371 ++II) {
372 IP->printInst(&II->Inst, outs(), "");
373 outs() << "\n";
374 }
375 }
376 }
Ahmed Bougacha17926472013-08-21 07:29:02 +0000377 if (CFG) {
378 for (MCModule::const_func_iterator FI = Mod->func_begin(),
379 FE = Mod->func_end();
380 FI != FE; ++FI) {
381 static int filenum = 0;
382 emitDOTFile((Twine((*FI)->getName()) + "_" +
383 utostr(filenum) + ".dot").str().c_str(),
384 **FI, IP.get());
385 ++filenum;
386 }
387 }
388 if (!YAMLCFG.empty()) {
389 std::string Error;
Rafael Espindola90c7f1c2014-02-24 18:20:12 +0000390 raw_fd_ostream YAMLOut(YAMLCFG.c_str(), Error, sys::fs::F_Text);
Ahmed Bougacha17926472013-08-21 07:29:02 +0000391 if (!Error.empty()) {
Ahmed Bougachad56f7052013-08-21 16:13:25 +0000392 errs() << ToolName << ": warning: " << Error << '\n';
Ahmed Bougacha17926472013-08-21 07:29:02 +0000393 return;
394 }
395 mcmodule2yaml(YAMLOut, *Mod, *MII, *MRI);
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000396 }
397 }
398
Greg Fitzgerald18432272014-03-20 22:55:15 +0000399 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
400 "\t\t\t%08" PRIx64 ": ";
401
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000402 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
403 // in RelocSecs contain the relocations for section S.
Rafael Espindola4453e42942014-06-13 03:07:50 +0000404 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000405 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
406 for (const SectionRef &Section : Obj->sections()) {
407 section_iterator Sec2 = Section.getRelocatedSection();
Rafael Espindolab5155a52014-02-10 20:24:04 +0000408 if (Sec2 != Obj->section_end())
Alexey Samsonov48803e52014-03-13 14:37:36 +0000409 SectionRelocMap[*Sec2].push_back(Section);
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000410 }
411
Alexey Samsonov48803e52014-03-13 14:37:36 +0000412 for (const SectionRef &Section : Obj->sections()) {
Mark Seaborneb03ac52014-01-25 00:32:01 +0000413 bool Text;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000414 if (error(Section.isText(Text)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000415 break;
416 if (!Text)
417 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000418
Michael J. Spencer51862b32011-10-13 22:17:18 +0000419 uint64_t SectionAddr;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000420 if (error(Section.getAddress(SectionAddr)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000421 break;
Michael J. Spencer51862b32011-10-13 22:17:18 +0000422
Simon Atanasyan2b614e12014-02-24 22:12:11 +0000423 uint64_t SectSize;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000424 if (error(Section.getSize(SectSize)))
Simon Atanasyan2b614e12014-02-24 22:12:11 +0000425 break;
426
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000427 // Make a list of all the symbols in this section.
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000428 std::vector<std::pair<uint64_t, StringRef>> Symbols;
429 for (const SymbolRef &Symbol : Obj->symbols()) {
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000430 bool contains;
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000431 if (!error(Section.containsSymbol(Symbol, contains)) && contains) {
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000432 uint64_t Address;
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000433 if (error(Symbol.getAddress(Address)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000434 break;
435 if (Address == UnknownAddressOrSize)
436 continue;
Cameron Zwarich07f0f772012-02-03 04:13:37 +0000437 Address -= SectionAddr;
Simon Atanasyan2b614e12014-02-24 22:12:11 +0000438 if (Address >= SectSize)
439 continue;
Cameron Zwarich07f0f772012-02-03 04:13:37 +0000440
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000441 StringRef Name;
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000442 if (error(Symbol.getName(Name)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000443 break;
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000444 Symbols.push_back(std::make_pair(Address, Name));
445 }
446 }
447
448 // Sort the symbols by address, just in case they didn't come in that way.
449 array_pod_sort(Symbols.begin(), Symbols.end());
450
Michael J. Spencer51862b32011-10-13 22:17:18 +0000451 // Make a list of all the relocations for this section.
452 std::vector<RelocationRef> Rels;
453 if (InlineRelocs) {
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000454 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
455 for (const RelocationRef &Reloc : RelocSec.relocations()) {
456 Rels.push_back(Reloc);
457 }
Michael J. Spencer51862b32011-10-13 22:17:18 +0000458 }
459 }
460
461 // Sort relocations by address.
462 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
463
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000464 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +0000465 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +0000466 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +0000467 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000468 }
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000469 StringRef name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000470 if (error(Section.getName(name)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000471 break;
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000472 outs() << "Disassembly of section ";
473 if (!SegmentName.empty())
474 outs() << SegmentName << ",";
475 outs() << name << ':';
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000476
477 // If the section has no symbols just insert a dummy one and disassemble
478 // the whole section.
479 if (Symbols.empty())
480 Symbols.push_back(std::make_pair(0, name));
Michael J. Spencer2670c252011-01-20 06:39:06 +0000481
Alp Tokere69170a2014-06-26 22:52:05 +0000482
483 SmallString<40> Comments;
484 raw_svector_ostream CommentStream(Comments);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000485
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000486 StringRef Bytes;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000487 if (error(Section.getContents(Bytes)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000488 break;
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000489 StringRefMemoryObject memoryObject(Bytes, SectionAddr);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000490 uint64_t Size;
491 uint64_t Index;
492
Michael J. Spencer51862b32011-10-13 22:17:18 +0000493 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
494 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000495 // Disassemble symbol by symbol.
496 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
497 uint64_t Start = Symbols[si].first;
Michael J. Spenceree84f642011-10-13 20:37:08 +0000498 uint64_t End;
499 // The end is either the size of the section or the beginning of the next
500 // symbol.
501 if (si == se - 1)
502 End = SectSize;
503 // Make sure this symbol takes up space.
504 else if (Symbols[si + 1].first != Start)
505 End = Symbols[si + 1].first - 1;
506 else
507 // This symbol has the same address as the next symbol. Skip it.
508 continue;
509
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000510 outs() << '\n' << Symbols[si].second << ":\n";
Michael J. Spencer2670c252011-01-20 06:39:06 +0000511
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000512#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +0000513 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000514#else
Mark Seaborneb03ac52014-01-25 00:32:01 +0000515 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000516#endif
517
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000518 for (Index = Start; Index < End; Index += Size) {
519 MCInst Inst;
Owen Andersona0c3b972011-09-15 23:38:46 +0000520
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000521 if (DisAsm->getInstruction(Inst, Size, memoryObject,
Alp Tokere69170a2014-06-26 22:52:05 +0000522 SectionAddr + Index,
523 DebugOut, CommentStream)) {
Eli Bendersky3a6808c2012-11-20 22:57:02 +0000524 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
525 if (!NoShowRawInsn) {
526 outs() << "\t";
527 DumpBytes(StringRef(Bytes.data() + Index, Size));
528 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000529 IP->printInst(&Inst, outs(), "");
Alp Tokere69170a2014-06-26 22:52:05 +0000530 outs() << CommentStream.str();
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000531 Comments.clear();
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000532 outs() << "\n";
533 } else {
534 errs() << ToolName << ": warning: invalid instruction encoding\n";
535 if (Size == 0)
536 Size = 1; // skip illegible bytes
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000537 }
Michael J. Spencer51862b32011-10-13 22:17:18 +0000538
539 // Print relocation for instruction.
540 while (rel_cur != rel_end) {
Owen Andersonfa3e5202011-10-25 20:35:53 +0000541 bool hidden = false;
Michael J. Spencer51862b32011-10-13 22:17:18 +0000542 uint64_t addr;
543 SmallString<16> name;
544 SmallString<32> val;
Owen Andersonfa3e5202011-10-25 20:35:53 +0000545
546 // If this relocation is hidden, skip it.
547 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
548 if (hidden) goto skip_print_rel;
549
Rafael Espindola1e483872013-04-25 12:28:45 +0000550 if (error(rel_cur->getOffset(addr))) goto skip_print_rel;
Michael J. Spencer51862b32011-10-13 22:17:18 +0000551 // Stop when rel_cur's address is past the current instruction.
Owen Andersonf20e3e52011-10-25 20:15:39 +0000552 if (addr >= Index + Size) break;
Michael J. Spencer51862b32011-10-13 22:17:18 +0000553 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
554 if (error(rel_cur->getValueString(val))) goto skip_print_rel;
555
Greg Fitzgerald18432272014-03-20 22:55:15 +0000556 outs() << format(Fmt.data(), SectionAddr + addr) << name
Benjamin Kramer82803112012-03-10 02:04:38 +0000557 << "\t" << val << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +0000558
559 skip_print_rel:
560 ++rel_cur;
561 }
Benjamin Kramer87ee76c2011-07-20 19:37:35 +0000562 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000563 }
564 }
565}
566
Alexey Samsonov48803e52014-03-13 14:37:36 +0000567static void PrintRelocations(const ObjectFile *Obj) {
Greg Fitzgerald18432272014-03-20 22:55:15 +0000568 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
569 "%08" PRIx64;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000570 for (const SectionRef &Section : Obj->sections()) {
571 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000572 continue;
573 StringRef secname;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000574 if (error(Section.getName(secname)))
575 continue;
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000576 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000577 for (const RelocationRef &Reloc : Section.relocations()) {
Owen Andersonfa3e5202011-10-25 20:35:53 +0000578 bool hidden;
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000579 uint64_t address;
580 SmallString<32> relocname;
581 SmallString<32> valuestr;
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000582 if (error(Reloc.getHidden(hidden)))
583 continue;
584 if (hidden)
585 continue;
586 if (error(Reloc.getTypeName(relocname)))
587 continue;
588 if (error(Reloc.getOffset(address)))
589 continue;
590 if (error(Reloc.getValueString(valuestr)))
591 continue;
Greg Fitzgerald18432272014-03-20 22:55:15 +0000592 outs() << format(Fmt.data(), address) << " " << relocname << " "
593 << valuestr << "\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000594 }
595 outs() << "\n";
596 }
597}
598
Alexey Samsonov48803e52014-03-13 14:37:36 +0000599static void PrintSectionHeaders(const ObjectFile *Obj) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000600 outs() << "Sections:\n"
601 "Idx Name Size Address Type\n";
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000602 unsigned i = 0;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000603 for (const SectionRef &Section : Obj->sections()) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000604 StringRef Name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000605 if (error(Section.getName(Name)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000606 return;
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000607 uint64_t Address;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000608 if (error(Section.getAddress(Address)))
609 return;
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000610 uint64_t Size;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000611 if (error(Section.getSize(Size)))
612 return;
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000613 bool Text, Data, BSS;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000614 if (error(Section.isText(Text)))
615 return;
616 if (error(Section.isData(Data)))
617 return;
618 if (error(Section.isBSS(BSS)))
619 return;
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000620 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +0000621 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
Alexey Samsonov48803e52014-03-13 14:37:36 +0000622 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
623 Name.str().c_str(), Size, Address, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000624 ++i;
625 }
626}
627
Alexey Samsonov48803e52014-03-13 14:37:36 +0000628static void PrintSectionContents(const ObjectFile *Obj) {
Rafael Espindola4453e42942014-06-13 03:07:50 +0000629 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000630 for (const SectionRef &Section : Obj->sections()) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000631 StringRef Name;
632 StringRef Contents;
633 uint64_t BaseAddr;
Alexey Samsonov209095c2013-04-16 10:53:11 +0000634 bool BSS;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000635 if (error(Section.getName(Name)))
636 continue;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000637 if (error(Section.getAddress(BaseAddr)))
638 continue;
639 if (error(Section.isBSS(BSS)))
640 continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000641
642 outs() << "Contents of section " << Name << ":\n";
Alexey Samsonov209095c2013-04-16 10:53:11 +0000643 if (BSS) {
David Majnemer8f6b04c2014-07-14 16:20:14 +0000644 uint64_t Size;
645 if (error(Section.getSize(Size)))
646 continue;
Alexey Samsonov209095c2013-04-16 10:53:11 +0000647 outs() << format("<skipping contents of bss section at [%04" PRIx64
David Majnemer8f6b04c2014-07-14 16:20:14 +0000648 ", %04" PRIx64 ")>\n",
649 BaseAddr, BaseAddr + Size);
Alexey Samsonov209095c2013-04-16 10:53:11 +0000650 continue;
651 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000652
David Majnemer8f6b04c2014-07-14 16:20:14 +0000653 if (error(Section.getContents(Contents)))
654 continue;
655
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000656 // Dump out the content as hex and printable ascii characters.
657 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer82803112012-03-10 02:04:38 +0000658 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000659 // Dump line of hex.
660 for (std::size_t i = 0; i < 16; ++i) {
661 if (i != 0 && i % 4 == 0)
662 outs() << ' ';
663 if (addr + i < end)
664 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
665 << hexdigit(Contents[addr + i] & 0xF, true);
666 else
667 outs() << " ";
668 }
669 // Print ascii.
670 outs() << " ";
671 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
Guy Benyei83c74e92013-02-12 21:21:59 +0000672 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000673 outs() << Contents[addr + i];
674 else
675 outs() << ".";
676 }
677 outs() << "\n";
678 }
679 }
680}
681
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000682static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
683 const coff_file_header *header;
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +0000684 if (error(coff->getHeader(header)))
685 return;
686
687 for (unsigned SI = 0, SE = header->NumberOfSymbols; SI != SE; ++SI) {
688 const coff_symbol *Symbol;
689 StringRef Name;
690 if (error(coff->getSymbol(SI, Symbol)))
691 return;
692
693 if (error(coff->getSymbolName(Symbol, Name)))
694 return;
695
696 outs() << "[" << format("%2d", SI) << "]"
697 << "(sec " << format("%2d", int(Symbol->SectionNumber)) << ")"
698 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
699 << "(ty " << format("%3x", unsigned(Symbol->Type)) << ")"
700 << "(scl " << format("%3x", unsigned(Symbol->StorageClass)) << ") "
701 << "(nx " << unsigned(Symbol->NumberOfAuxSymbols) << ") "
702 << "0x" << format("%08x", unsigned(Symbol->Value)) << " "
703 << Name << "\n";
704
705 for (unsigned AI = 0, AE = Symbol->NumberOfAuxSymbols; AI < AE; ++AI, ++SI) {
706 if (Symbol->isSectionDefinition()) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000707 const coff_aux_section_definition *asd;
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +0000708 if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd)))
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000709 return;
Saleem Abdulrasool9ede5c72014-04-13 03:11:08 +0000710
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000711 outs() << "AUX "
712 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
713 , unsigned(asd->Length)
714 , unsigned(asd->NumberOfRelocations)
715 , unsigned(asd->NumberOfLinenumbers)
716 , unsigned(asd->CheckSum))
717 << format("assoc %d comdat %d\n"
718 , unsigned(asd->Number)
719 , unsigned(asd->Selection));
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +0000720 } else if (Symbol->isFileRecord()) {
Saleem Abdulrasool63a0dd62014-04-13 22:54:11 +0000721 const coff_aux_file *AF;
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +0000722 if (error(coff->getAuxSymbol<coff_aux_file>(SI + 1, AF)))
Saleem Abdulrasool63a0dd62014-04-13 22:54:11 +0000723 return;
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +0000724
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +0000725 StringRef Name(AF->FileName,
726 Symbol->NumberOfAuxSymbols * COFF::SymbolSize);
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +0000727 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
Saleem Abdulrasool13a3f692014-04-14 16:38:25 +0000728
729 SI = SI + Symbol->NumberOfAuxSymbols;
730 break;
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +0000731 } else {
732 outs() << "AUX Unknown\n";
Saleem Abdulrasool9ede5c72014-04-13 03:11:08 +0000733 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000734 }
735 }
736}
737
738static void PrintSymbolTable(const ObjectFile *o) {
739 outs() << "SYMBOL TABLE:\n";
740
Rui Ueyama4e39f712014-03-18 18:58:51 +0000741 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000742 PrintCOFFSymbolTable(coff);
Rui Ueyama4e39f712014-03-18 18:58:51 +0000743 return;
744 }
745 for (const SymbolRef &Symbol : o->symbols()) {
746 StringRef Name;
747 uint64_t Address;
748 SymbolRef::Type Type;
749 uint64_t Size;
750 uint32_t Flags = Symbol.getFlags();
751 section_iterator Section = o->section_end();
752 if (error(Symbol.getName(Name)))
753 continue;
754 if (error(Symbol.getAddress(Address)))
755 continue;
756 if (error(Symbol.getType(Type)))
757 continue;
758 if (error(Symbol.getSize(Size)))
759 continue;
760 if (error(Symbol.getSection(Section)))
761 continue;
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000762
Rui Ueyama4e39f712014-03-18 18:58:51 +0000763 bool Global = Flags & SymbolRef::SF_Global;
764 bool Weak = Flags & SymbolRef::SF_Weak;
765 bool Absolute = Flags & SymbolRef::SF_Absolute;
David Meyer1df4b842012-02-28 23:47:53 +0000766
Rui Ueyama4e39f712014-03-18 18:58:51 +0000767 if (Address == UnknownAddressOrSize)
768 Address = 0;
769 if (Size == UnknownAddressOrSize)
770 Size = 0;
771 char GlobLoc = ' ';
772 if (Type != SymbolRef::ST_Unknown)
773 GlobLoc = Global ? 'g' : 'l';
774 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
775 ? 'd' : ' ';
776 char FileFunc = ' ';
777 if (Type == SymbolRef::ST_File)
778 FileFunc = 'f';
779 else if (Type == SymbolRef::ST_Function)
780 FileFunc = 'F';
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000781
Rui Ueyama4e39f712014-03-18 18:58:51 +0000782 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
783 "%08" PRIx64;
Michael J. Spencerd857c1c2013-01-10 22:40:50 +0000784
Rui Ueyama4e39f712014-03-18 18:58:51 +0000785 outs() << format(Fmt, Address) << " "
786 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
787 << (Weak ? 'w' : ' ') // Weak?
788 << ' ' // Constructor. Not supported yet.
789 << ' ' // Warning. Not supported yet.
790 << ' ' // Indirect reference to another symbol.
791 << Debug // Debugging (d) or dynamic (D) symbol.
792 << FileFunc // Name of function (F), file (f) or object (O).
793 << ' ';
794 if (Absolute) {
795 outs() << "*ABS*";
796 } else if (Section == o->section_end()) {
797 outs() << "*UND*";
798 } else {
799 if (const MachOObjectFile *MachO =
800 dyn_cast<const MachOObjectFile>(o)) {
801 DataRefImpl DR = Section->getRawDataRefImpl();
802 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
803 outs() << SegmentName << ",";
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000804 }
Rui Ueyama4e39f712014-03-18 18:58:51 +0000805 StringRef SectionName;
806 if (error(Section->getName(SectionName)))
807 SectionName = "";
808 outs() << SectionName;
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000809 }
Rui Ueyama4e39f712014-03-18 18:58:51 +0000810 outs() << '\t'
811 << format("%08" PRIx64 " ", Size)
812 << Name
813 << '\n';
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000814 }
815}
816
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000817static void PrintUnwindInfo(const ObjectFile *o) {
818 outs() << "Unwind info:\n\n";
819
820 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
821 printCOFFUnwindInfo(coff);
Tim Northover4bd286a2014-08-01 13:07:19 +0000822 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
823 printMachOUnwindInfo(MachO);
824 else {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000825 // TODO: Extract DWARF dump tool to objdump.
826 errs() << "This operation is only currently supported "
Tim Northover4bd286a2014-08-01 13:07:19 +0000827 "for COFF and MachO object files.\n";
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000828 return;
829 }
830}
831
Rui Ueyamac2bed422013-09-27 21:04:00 +0000832static void printPrivateFileHeader(const ObjectFile *o) {
833 if (o->isELF()) {
834 printELFFileHeader(o);
835 } else if (o->isCOFF()) {
836 printCOFFFileHeader(o);
837 }
838}
839
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000840static void DumpObject(const ObjectFile *o) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000841 outs() << '\n';
842 outs() << o->getFileName()
843 << ":\tfile format " << o->getFileFormatName() << "\n\n";
844
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000845 if (Disassemble)
Michael J. Spencer51862b32011-10-13 22:17:18 +0000846 DisassembleObject(o, Relocations);
847 if (Relocations && !Disassemble)
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000848 PrintRelocations(o);
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000849 if (SectionHeaders)
850 PrintSectionHeaders(o);
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000851 if (SectionContents)
852 PrintSectionContents(o);
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000853 if (SymbolTable)
854 PrintSymbolTable(o);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000855 if (UnwindInfo)
856 PrintUnwindInfo(o);
Rui Ueyamac2bed422013-09-27 21:04:00 +0000857 if (PrivateHeaders)
858 printPrivateFileHeader(o);
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000859}
860
861/// @brief Dump each object file in \a a;
862static void DumpArchive(const Archive *a) {
Mark Seaborneb03ac52014-01-25 00:32:01 +0000863 for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
864 ++i) {
Rafael Espindolaae460022014-06-16 16:08:36 +0000865 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
866 if (std::error_code EC = ChildOrErr.getError()) {
Michael J. Spencer53723de2011-11-16 01:24:41 +0000867 // Ignore non-object files.
Mark Seaborneb03ac52014-01-25 00:32:01 +0000868 if (EC != object_error::invalid_file_type)
869 errs() << ToolName << ": '" << a->getFileName() << "': " << EC.message()
Michael J. Spencer53723de2011-11-16 01:24:41 +0000870 << ".\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000871 continue;
872 }
Rafael Espindolaae460022014-06-16 16:08:36 +0000873 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000874 DumpObject(o);
875 else
876 errs() << ToolName << ": '" << a->getFileName() << "': "
877 << "Unrecognized file type.\n";
878 }
879}
880
881/// @brief Open file and figure out how to dump it.
882static void DumpInput(StringRef file) {
883 // If file isn't stdin, check that it exists.
884 if (file != "-" && !sys::fs::exists(file)) {
885 errs() << ToolName << ": '" << file << "': " << "No such file\n";
886 return;
887 }
888
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000889 if (MachOOpt && Disassemble) {
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000890 DisassembleInputMachO(file);
891 return;
892 }
893
894 // Attempt to open the binary.
Rafael Espindola437b0d52014-07-31 03:12:45 +0000895 ErrorOr<std::unique_ptr<Binary>> BinaryOrErr = createBinary(file);
Rafael Espindola4453e42942014-06-13 03:07:50 +0000896 if (std::error_code EC = BinaryOrErr.getError()) {
Rafael Espindola63da2952014-01-15 19:37:43 +0000897 errs() << ToolName << ": '" << file << "': " << EC.message() << ".\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000898 return;
899 }
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000900 Binary &Binary = *BinaryOrErr.get();
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000901
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000902 if (Archive *a = dyn_cast<Archive>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000903 DumpArchive(a);
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000904 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000905 DumpObject(o);
Jim Grosbachaf9aec02012-08-07 17:53:14 +0000906 else
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000907 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000908}
909
Michael J. Spencer2670c252011-01-20 06:39:06 +0000910int main(int argc, char **argv) {
911 // Print a stack trace if we signal out.
912 sys::PrintStackTraceOnErrorSignal();
913 PrettyStackTraceProgram X(argc, argv);
914 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
915
916 // Initialize targets and assembly printers/parsers.
917 llvm::InitializeAllTargetInfos();
Evan Cheng8c886a42011-07-22 21:58:54 +0000918 llvm::InitializeAllTargetMCs();
Michael J. Spencer2670c252011-01-20 06:39:06 +0000919 llvm::InitializeAllAsmParsers();
920 llvm::InitializeAllDisassemblers();
921
Pete Cooper28fb4fc2012-05-03 23:20:10 +0000922 // Register the target printer for --version.
923 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
924
Michael J. Spencer2670c252011-01-20 06:39:06 +0000925 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
926 TripleName = Triple::normalize(TripleName);
927
928 ToolName = argv[0];
929
930 // Defaults to a.out if no filenames specified.
931 if (InputFilenames.size() == 0)
932 InputFilenames.push_back("a.out");
933
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000934 if (!Disassemble
935 && !Relocations
936 && !SectionHeaders
937 && !SectionContents
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000938 && !SymbolTable
Michael J. Spencer209565db2013-01-06 03:56:49 +0000939 && !UnwindInfo
940 && !PrivateHeaders) {
Michael J. Spencer2670c252011-01-20 06:39:06 +0000941 cl::PrintHelpMessage();
942 return 2;
943 }
944
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000945 std::for_each(InputFilenames.begin(), InputFilenames.end(),
946 DumpInput);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000947
948 return 0;
949}