blob: d9886c10aeb5e9b932e9ccbcc451ecaeec3fb04a [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"
23#include "llvm/MC/MCAsmInfo.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000024#include "llvm/MC/MCAtom.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000025#include "llvm/MC/MCContext.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000026#include "llvm/MC/MCDisassembler.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000027#include "llvm/MC/MCFunction.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000028#include "llvm/MC/MCInst.h"
29#include "llvm/MC/MCInstPrinter.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000030#include "llvm/MC/MCInstrAnalysis.h"
Craig Topper54bfde72012-04-02 06:09:36 +000031#include "llvm/MC/MCInstrInfo.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000032#include "llvm/MC/MCModule.h"
Ahmed Bougacha17926472013-08-21 07:29:02 +000033#include "llvm/MC/MCModuleYAML.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000034#include "llvm/MC/MCObjectDisassembler.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000035#include "llvm/MC/MCObjectFileInfo.h"
36#include "llvm/MC/MCObjectSymbolizer.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>
97llvm::ArchName("arch", cl::desc("Target arch to disassemble for, "
Michael J. Spencer2670c252011-01-20 06:39:06 +000098 "see -version for available targets"));
99
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000100static cl::opt<bool>
101SectionHeaders("section-headers", cl::desc("Display summaries of the headers "
102 "for each section."));
103static cl::alias
104SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
105 cl::aliasopt(SectionHeaders));
106static cl::alias
107SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
108 cl::aliasopt(SectionHeaders));
109
Jack Carter551efd72012-08-28 19:24:49 +0000110static cl::list<std::string>
111MAttrs("mattr",
112 cl::CommaSeparated,
113 cl::desc("Target specific attributes"),
114 cl::value_desc("a1,+a2,-a3,..."));
115
Eli Bendersky3a6808c2012-11-20 22:57:02 +0000116static cl::opt<bool>
117NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling instructions, "
118 "do not print the instruction bytes."));
119
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000120static cl::opt<bool>
121UnwindInfo("unwind-info", cl::desc("Display unwind information"));
122
123static cl::alias
124UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
125 cl::aliasopt(UnwindInfo));
126
Michael J. Spencer209565db2013-01-06 03:56:49 +0000127static cl::opt<bool>
128PrivateHeaders("private-headers",
129 cl::desc("Display format specific file headers"));
130
131static cl::alias
132PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
133 cl::aliasopt(PrivateHeaders));
134
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000135static cl::opt<bool>
136Symbolize("symbolize", cl::desc("When disassembling instructions, "
137 "try to symbolize operands."));
138
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000139static cl::opt<bool>
140CFG("cfg", cl::desc("Create a CFG for every function found in the object"
141 " and write it to a graphviz file"));
142
Ahmed Bougacha17926472013-08-21 07:29:02 +0000143// FIXME: Does it make sense to have a dedicated tool for yaml cfg output?
144static cl::opt<std::string>
145YAMLCFG("yaml-cfg",
146 cl::desc("Create a CFG and write it as a YAML MCModule."),
147 cl::value_desc("yaml output file"));
148
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000149static StringRef ToolName;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000150
Rafael Espindola4453e42942014-06-13 03:07:50 +0000151bool llvm::error(std::error_code EC) {
Mark Seaborneb03ac52014-01-25 00:32:01 +0000152 if (!EC)
153 return false;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000154
Mark Seaborneb03ac52014-01-25 00:32:01 +0000155 outs() << ToolName << ": error reading file: " << EC.message() << ".\n";
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000156 outs().flush();
157 return true;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000158}
159
Craig Toppere6cb63e2014-04-25 04:24:47 +0000160static const Target *getTarget(const ObjectFile *Obj = nullptr) {
Michael J. Spencer2670c252011-01-20 06:39:06 +0000161 // Figure out the target triple.
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000162 llvm::Triple TheTriple("unknown-unknown-unknown");
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000163 if (TripleName.empty()) {
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000164 if (Obj) {
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000165 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000166 // TheTriple defaults to ELF, and COFF doesn't have an environment:
167 // the best we can do here is indicate that it is mach-o.
168 if (Obj->isMachO())
Saleem Abdulrasool35476332014-03-06 20:47:11 +0000169 TheTriple.setObjectFormat(Triple::MachO);
Saleem Abdulrasool98938f12014-04-17 06:17:23 +0000170
171 if (Obj->isCOFF()) {
172 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
173 if (COFFObj->getArch() == Triple::thumb)
174 TheTriple.setTriple("thumbv7-windows");
175 }
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000176 }
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000177 } else
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000178 TheTriple.setTriple(Triple::normalize(TripleName));
Michael J. Spencer2670c252011-01-20 06:39:06 +0000179
180 // Get the target specific parser.
181 std::string Error;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000182 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
183 Error);
184 if (!TheTarget) {
185 errs() << ToolName << ": " << Error;
Craig Toppere6cb63e2014-04-25 04:24:47 +0000186 return nullptr;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000187 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000188
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000189 // Update the triple name and return the found target.
190 TripleName = TheTriple.getTriple();
191 return TheTarget;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000192}
193
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000194// Write a graphviz file for the CFG inside an MCFunction.
Ahmed Bougacha17926472013-08-21 07:29:02 +0000195// FIXME: Use GraphWriter
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000196static void emitDOTFile(const char *FileName, const MCFunction &f,
197 MCInstPrinter *IP) {
198 // Start a new dot file.
199 std::string Error;
Rafael Espindola90c7f1c2014-02-24 18:20:12 +0000200 raw_fd_ostream Out(FileName, Error, sys::fs::F_Text);
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000201 if (!Error.empty()) {
202 errs() << "llvm-objdump: warning: " << Error << '\n';
203 return;
204 }
205
206 Out << "digraph \"" << f.getName() << "\" {\n";
207 Out << "graph [ rankdir = \"LR\" ];\n";
208 for (MCFunction::const_iterator i = f.begin(), e = f.end(); i != e; ++i) {
209 // Only print blocks that have predecessors.
210 bool hasPreds = (*i)->pred_begin() != (*i)->pred_end();
211
212 if (!hasPreds && i != f.begin())
213 continue;
214
215 Out << '"' << (*i)->getInsts()->getBeginAddr() << "\" [ label=\"<a>";
216 // Print instructions.
217 for (unsigned ii = 0, ie = (*i)->getInsts()->size(); ii != ie;
218 ++ii) {
219 if (ii != 0) // Not the first line, start a new row.
220 Out << '|';
221 if (ii + 1 == ie) // Last line, add an end id.
222 Out << "<o>";
223
224 // Escape special chars and print the instruction in mnemonic form.
Alp Toker61471732014-06-26 00:00:48 +0000225 string_ostream OS;
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000226 IP->printInst(&(*i)->getInsts()->at(ii).Inst, OS, "");
227 Out << DOT::EscapeString(OS.str());
228 }
229 Out << "\" shape=\"record\" ];\n";
230
231 // Add edges.
232 for (MCBasicBlock::succ_const_iterator si = (*i)->succ_begin(),
233 se = (*i)->succ_end(); si != se; ++si)
234 Out << (*i)->getInsts()->getBeginAddr() << ":o -> "
235 << (*si)->getInsts()->getBeginAddr() << ":a\n";
236 }
237 Out << "}\n";
238}
David Blaikiea379b1812011-12-20 02:50:00 +0000239
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000240void llvm::DumpBytes(StringRef bytes) {
241 static const char hex_rep[] = "0123456789abcdef";
Michael J. Spencer2670c252011-01-20 06:39:06 +0000242 // FIXME: The real way to do this is to figure out the longest instruction
243 // and align to that size before printing. I'll fix this when I get
244 // around to outputting relocations.
245 // 15 is the longest x86 instruction
246 // 3 is for the hex rep of a byte + a space.
247 // 1 is for the null terminator.
248 enum { OutputSize = (15 * 3) + 1 };
249 char output[OutputSize];
250
251 assert(bytes.size() <= 15
252 && "DumpBytes only supports instructions of up to 15 bytes");
253 memset(output, ' ', sizeof(output));
254 unsigned index = 0;
255 for (StringRef::iterator i = bytes.begin(),
256 e = bytes.end(); i != e; ++i) {
257 output[index] = hex_rep[(*i & 0xF0) >> 4];
258 output[index + 1] = hex_rep[*i & 0xF];
259 index += 3;
260 }
261
262 output[sizeof(output) - 1] = 0;
263 outs() << output;
264}
265
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000266bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
Michael J. Spencer51862b32011-10-13 22:17:18 +0000267 uint64_t a_addr, b_addr;
Rafael Espindola1e483872013-04-25 12:28:45 +0000268 if (error(a.getOffset(a_addr))) return false;
269 if (error(b.getOffset(b_addr))) return false;
Michael J. Spencer51862b32011-10-13 22:17:18 +0000270 return a_addr < b_addr;
271}
272
273static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Jim Grosbachaf9aec02012-08-07 17:53:14 +0000274 const Target *TheTarget = getTarget(Obj);
275 // getTarget() will have already issued a diagnostic if necessary, so
276 // just bail here if it failed.
277 if (!TheTarget)
Michael J. Spencer2670c252011-01-20 06:39:06 +0000278 return;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000279
Jack Carter551efd72012-08-28 19:24:49 +0000280 // Package up features to be passed to target/subtarget
281 std::string FeaturesStr;
282 if (MAttrs.size()) {
283 SubtargetFeatures Features;
284 for (unsigned i = 0; i != MAttrs.size(); ++i)
285 Features.AddFeature(MAttrs[i]);
286 FeaturesStr = Features.getString();
287 }
288
Ahmed Charles56440fd2014-03-06 05:51:42 +0000289 std::unique_ptr<const MCRegisterInfo> MRI(
290 TheTarget->createMCRegInfo(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000291 if (!MRI) {
292 errs() << "error: no register info for target " << TripleName << "\n";
293 return;
294 }
295
296 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000297 std::unique_ptr<const MCAsmInfo> AsmInfo(
298 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000299 if (!AsmInfo) {
300 errs() << "error: no assembly info for target " << TripleName << "\n";
301 return;
302 }
303
Ahmed Charles56440fd2014-03-06 05:51:42 +0000304 std::unique_ptr<const MCSubtargetInfo> STI(
305 TheTarget->createMCSubtargetInfo(TripleName, "", FeaturesStr));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000306 if (!STI) {
307 errs() << "error: no subtarget info for target " << TripleName << "\n";
308 return;
309 }
310
Ahmed Charles56440fd2014-03-06 05:51:42 +0000311 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000312 if (!MII) {
313 errs() << "error: no instruction info for target " << TripleName << "\n";
314 return;
315 }
316
Lang Hamesa1bc0f52014-04-15 04:40:56 +0000317 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
318 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
319
320 std::unique_ptr<MCDisassembler> DisAsm(
321 TheTarget->createMCDisassembler(*STI, Ctx));
322
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000323 if (!DisAsm) {
324 errs() << "error: no disassembler for target " << TripleName << "\n";
325 return;
326 }
327
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000328
329 if (Symbolize) {
Ahmed Charles56440fd2014-03-06 05:51:42 +0000330 std::unique_ptr<MCRelocationInfo> RelInfo(
Lang Hamesa1bc0f52014-04-15 04:40:56 +0000331 TheTarget->createMCRelocationInfo(TripleName, Ctx));
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000332 if (RelInfo) {
Ahmed Charles56440fd2014-03-06 05:51:42 +0000333 std::unique_ptr<MCSymbolizer> Symzer(
Lang Hamesa1bc0f52014-04-15 04:40:56 +0000334 MCObjectSymbolizer::createObjectSymbolizer(Ctx, std::move(RelInfo),
335 Obj));
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000336 if (Symzer)
Ahmed Charlesdf17c832014-03-07 09:38:02 +0000337 DisAsm->setSymbolizer(std::move(Symzer));
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000338 }
339 }
340
Ahmed Charles56440fd2014-03-06 05:51:42 +0000341 std::unique_ptr<const MCInstrAnalysis> MIA(
342 TheTarget->createMCInstrAnalysis(MII.get()));
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000343
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000344 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +0000345 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000346 AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
347 if (!IP) {
348 errs() << "error: no instruction printer for target " << TripleName
349 << '\n';
350 return;
351 }
352
Ahmed Bougacha17926472013-08-21 07:29:02 +0000353 if (CFG || !YAMLCFG.empty()) {
Ahmed Charles56440fd2014-03-06 05:51:42 +0000354 std::unique_ptr<MCObjectDisassembler> OD(
355 new MCObjectDisassembler(*Obj, *DisAsm, *MIA));
356 std::unique_ptr<MCModule> Mod(OD->buildModule(/* withCFG */ true));
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000357 for (MCModule::const_atom_iterator AI = Mod->atom_begin(),
358 AE = Mod->atom_end();
359 AI != AE; ++AI) {
360 outs() << "Atom " << (*AI)->getName() << ": \n";
361 if (const MCTextAtom *TA = dyn_cast<MCTextAtom>(*AI)) {
362 for (MCTextAtom::const_iterator II = TA->begin(), IE = TA->end();
363 II != IE;
364 ++II) {
365 IP->printInst(&II->Inst, outs(), "");
366 outs() << "\n";
367 }
368 }
369 }
Ahmed Bougacha17926472013-08-21 07:29:02 +0000370 if (CFG) {
371 for (MCModule::const_func_iterator FI = Mod->func_begin(),
372 FE = Mod->func_end();
373 FI != FE; ++FI) {
374 static int filenum = 0;
375 emitDOTFile((Twine((*FI)->getName()) + "_" +
376 utostr(filenum) + ".dot").str().c_str(),
377 **FI, IP.get());
378 ++filenum;
379 }
380 }
381 if (!YAMLCFG.empty()) {
382 std::string Error;
Rafael Espindola90c7f1c2014-02-24 18:20:12 +0000383 raw_fd_ostream YAMLOut(YAMLCFG.c_str(), Error, sys::fs::F_Text);
Ahmed Bougacha17926472013-08-21 07:29:02 +0000384 if (!Error.empty()) {
Ahmed Bougachad56f7052013-08-21 16:13:25 +0000385 errs() << ToolName << ": warning: " << Error << '\n';
Ahmed Bougacha17926472013-08-21 07:29:02 +0000386 return;
387 }
388 mcmodule2yaml(YAMLOut, *Mod, *MII, *MRI);
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000389 }
390 }
391
Greg Fitzgerald18432272014-03-20 22:55:15 +0000392 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
393 "\t\t\t%08" PRIx64 ": ";
394
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000395 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
396 // in RelocSecs contain the relocations for section S.
Rafael Espindola4453e42942014-06-13 03:07:50 +0000397 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000398 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
399 for (const SectionRef &Section : Obj->sections()) {
400 section_iterator Sec2 = Section.getRelocatedSection();
Rafael Espindolab5155a52014-02-10 20:24:04 +0000401 if (Sec2 != Obj->section_end())
Alexey Samsonov48803e52014-03-13 14:37:36 +0000402 SectionRelocMap[*Sec2].push_back(Section);
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000403 }
404
Alexey Samsonov48803e52014-03-13 14:37:36 +0000405 for (const SectionRef &Section : Obj->sections()) {
Mark Seaborneb03ac52014-01-25 00:32:01 +0000406 bool Text;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000407 if (error(Section.isText(Text)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000408 break;
409 if (!Text)
410 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000411
Michael J. Spencer51862b32011-10-13 22:17:18 +0000412 uint64_t SectionAddr;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000413 if (error(Section.getAddress(SectionAddr)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000414 break;
Michael J. Spencer51862b32011-10-13 22:17:18 +0000415
Simon Atanasyan2b614e12014-02-24 22:12:11 +0000416 uint64_t SectSize;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000417 if (error(Section.getSize(SectSize)))
Simon Atanasyan2b614e12014-02-24 22:12:11 +0000418 break;
419
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000420 // Make a list of all the symbols in this section.
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000421 std::vector<std::pair<uint64_t, StringRef>> Symbols;
422 for (const SymbolRef &Symbol : Obj->symbols()) {
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000423 bool contains;
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000424 if (!error(Section.containsSymbol(Symbol, contains)) && contains) {
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000425 uint64_t Address;
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000426 if (error(Symbol.getAddress(Address)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000427 break;
428 if (Address == UnknownAddressOrSize)
429 continue;
Cameron Zwarich07f0f772012-02-03 04:13:37 +0000430 Address -= SectionAddr;
Simon Atanasyan2b614e12014-02-24 22:12:11 +0000431 if (Address >= SectSize)
432 continue;
Cameron Zwarich07f0f772012-02-03 04:13:37 +0000433
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000434 StringRef Name;
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000435 if (error(Symbol.getName(Name)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000436 break;
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000437 Symbols.push_back(std::make_pair(Address, Name));
438 }
439 }
440
441 // Sort the symbols by address, just in case they didn't come in that way.
442 array_pod_sort(Symbols.begin(), Symbols.end());
443
Michael J. Spencer51862b32011-10-13 22:17:18 +0000444 // Make a list of all the relocations for this section.
445 std::vector<RelocationRef> Rels;
446 if (InlineRelocs) {
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000447 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
448 for (const RelocationRef &Reloc : RelocSec.relocations()) {
449 Rels.push_back(Reloc);
450 }
Michael J. Spencer51862b32011-10-13 22:17:18 +0000451 }
452 }
453
454 // Sort relocations by address.
455 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
456
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000457 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +0000458 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +0000459 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +0000460 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000461 }
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000462 StringRef name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000463 if (error(Section.getName(name)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000464 break;
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000465 outs() << "Disassembly of section ";
466 if (!SegmentName.empty())
467 outs() << SegmentName << ",";
468 outs() << name << ':';
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000469
470 // If the section has no symbols just insert a dummy one and disassemble
471 // the whole section.
472 if (Symbols.empty())
473 Symbols.push_back(std::make_pair(0, name));
Michael J. Spencer2670c252011-01-20 06:39:06 +0000474
Alp Toker61471732014-06-26 00:00:48 +0000475 small_string_ostream<40> Comments;
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000476
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000477 StringRef Bytes;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000478 if (error(Section.getContents(Bytes)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000479 break;
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000480 StringRefMemoryObject memoryObject(Bytes, SectionAddr);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000481 uint64_t Size;
482 uint64_t Index;
483
Michael J. Spencer51862b32011-10-13 22:17:18 +0000484 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
485 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000486 // Disassemble symbol by symbol.
487 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
488 uint64_t Start = Symbols[si].first;
Michael J. Spenceree84f642011-10-13 20:37:08 +0000489 uint64_t End;
490 // The end is either the size of the section or the beginning of the next
491 // symbol.
492 if (si == se - 1)
493 End = SectSize;
494 // Make sure this symbol takes up space.
495 else if (Symbols[si + 1].first != Start)
496 End = Symbols[si + 1].first - 1;
497 else
498 // This symbol has the same address as the next symbol. Skip it.
499 continue;
500
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000501 outs() << '\n' << Symbols[si].second << ":\n";
Michael J. Spencer2670c252011-01-20 06:39:06 +0000502
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000503#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +0000504 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000505#else
Mark Seaborneb03ac52014-01-25 00:32:01 +0000506 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000507#endif
508
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000509 for (Index = Start; Index < End; Index += Size) {
510 MCInst Inst;
Owen Andersona0c3b972011-09-15 23:38:46 +0000511
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000512 if (DisAsm->getInstruction(Inst, Size, memoryObject,
Alp Toker61471732014-06-26 00:00:48 +0000513 SectionAddr + Index, DebugOut, Comments)) {
Eli Bendersky3a6808c2012-11-20 22:57:02 +0000514 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
515 if (!NoShowRawInsn) {
516 outs() << "\t";
517 DumpBytes(StringRef(Bytes.data() + Index, Size));
518 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000519 IP->printInst(&Inst, outs(), "");
Alp Toker61471732014-06-26 00:00:48 +0000520 outs() << Comments.str();
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000521 Comments.clear();
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000522 outs() << "\n";
523 } else {
524 errs() << ToolName << ": warning: invalid instruction encoding\n";
525 if (Size == 0)
526 Size = 1; // skip illegible bytes
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000527 }
Michael J. Spencer51862b32011-10-13 22:17:18 +0000528
529 // Print relocation for instruction.
530 while (rel_cur != rel_end) {
Owen Andersonfa3e5202011-10-25 20:35:53 +0000531 bool hidden = false;
Michael J. Spencer51862b32011-10-13 22:17:18 +0000532 uint64_t addr;
533 SmallString<16> name;
534 SmallString<32> val;
Owen Andersonfa3e5202011-10-25 20:35:53 +0000535
536 // If this relocation is hidden, skip it.
537 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
538 if (hidden) goto skip_print_rel;
539
Rafael Espindola1e483872013-04-25 12:28:45 +0000540 if (error(rel_cur->getOffset(addr))) goto skip_print_rel;
Michael J. Spencer51862b32011-10-13 22:17:18 +0000541 // Stop when rel_cur's address is past the current instruction.
Owen Andersonf20e3e52011-10-25 20:15:39 +0000542 if (addr >= Index + Size) break;
Michael J. Spencer51862b32011-10-13 22:17:18 +0000543 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
544 if (error(rel_cur->getValueString(val))) goto skip_print_rel;
545
Greg Fitzgerald18432272014-03-20 22:55:15 +0000546 outs() << format(Fmt.data(), SectionAddr + addr) << name
Benjamin Kramer82803112012-03-10 02:04:38 +0000547 << "\t" << val << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +0000548
549 skip_print_rel:
550 ++rel_cur;
551 }
Benjamin Kramer87ee76c2011-07-20 19:37:35 +0000552 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000553 }
554 }
555}
556
Alexey Samsonov48803e52014-03-13 14:37:36 +0000557static void PrintRelocations(const ObjectFile *Obj) {
Greg Fitzgerald18432272014-03-20 22:55:15 +0000558 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
559 "%08" PRIx64;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000560 for (const SectionRef &Section : Obj->sections()) {
561 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000562 continue;
563 StringRef secname;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000564 if (error(Section.getName(secname)))
565 continue;
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000566 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000567 for (const RelocationRef &Reloc : Section.relocations()) {
Owen Andersonfa3e5202011-10-25 20:35:53 +0000568 bool hidden;
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000569 uint64_t address;
570 SmallString<32> relocname;
571 SmallString<32> valuestr;
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000572 if (error(Reloc.getHidden(hidden)))
573 continue;
574 if (hidden)
575 continue;
576 if (error(Reloc.getTypeName(relocname)))
577 continue;
578 if (error(Reloc.getOffset(address)))
579 continue;
580 if (error(Reloc.getValueString(valuestr)))
581 continue;
Greg Fitzgerald18432272014-03-20 22:55:15 +0000582 outs() << format(Fmt.data(), address) << " " << relocname << " "
583 << valuestr << "\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000584 }
585 outs() << "\n";
586 }
587}
588
Alexey Samsonov48803e52014-03-13 14:37:36 +0000589static void PrintSectionHeaders(const ObjectFile *Obj) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000590 outs() << "Sections:\n"
591 "Idx Name Size Address Type\n";
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000592 unsigned i = 0;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000593 for (const SectionRef &Section : Obj->sections()) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000594 StringRef Name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000595 if (error(Section.getName(Name)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000596 return;
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000597 uint64_t Address;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000598 if (error(Section.getAddress(Address)))
599 return;
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000600 uint64_t Size;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000601 if (error(Section.getSize(Size)))
602 return;
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000603 bool Text, Data, BSS;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000604 if (error(Section.isText(Text)))
605 return;
606 if (error(Section.isData(Data)))
607 return;
608 if (error(Section.isBSS(BSS)))
609 return;
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000610 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +0000611 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
Alexey Samsonov48803e52014-03-13 14:37:36 +0000612 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
613 Name.str().c_str(), Size, Address, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000614 ++i;
615 }
616}
617
Alexey Samsonov48803e52014-03-13 14:37:36 +0000618static void PrintSectionContents(const ObjectFile *Obj) {
Rafael Espindola4453e42942014-06-13 03:07:50 +0000619 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000620 for (const SectionRef &Section : Obj->sections()) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000621 StringRef Name;
622 StringRef Contents;
623 uint64_t BaseAddr;
Alexey Samsonov209095c2013-04-16 10:53:11 +0000624 bool BSS;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000625 if (error(Section.getName(Name)))
626 continue;
627 if (error(Section.getContents(Contents)))
628 continue;
629 if (error(Section.getAddress(BaseAddr)))
630 continue;
631 if (error(Section.isBSS(BSS)))
632 continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000633
634 outs() << "Contents of section " << Name << ":\n";
Alexey Samsonov209095c2013-04-16 10:53:11 +0000635 if (BSS) {
636 outs() << format("<skipping contents of bss section at [%04" PRIx64
637 ", %04" PRIx64 ")>\n", BaseAddr,
638 BaseAddr + Contents.size());
639 continue;
640 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000641
642 // Dump out the content as hex and printable ascii characters.
643 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer82803112012-03-10 02:04:38 +0000644 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000645 // Dump line of hex.
646 for (std::size_t i = 0; i < 16; ++i) {
647 if (i != 0 && i % 4 == 0)
648 outs() << ' ';
649 if (addr + i < end)
650 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
651 << hexdigit(Contents[addr + i] & 0xF, true);
652 else
653 outs() << " ";
654 }
655 // Print ascii.
656 outs() << " ";
657 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
Guy Benyei83c74e92013-02-12 21:21:59 +0000658 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000659 outs() << Contents[addr + i];
660 else
661 outs() << ".";
662 }
663 outs() << "\n";
664 }
665 }
666}
667
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000668static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
669 const coff_file_header *header;
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +0000670 if (error(coff->getHeader(header)))
671 return;
672
673 for (unsigned SI = 0, SE = header->NumberOfSymbols; SI != SE; ++SI) {
674 const coff_symbol *Symbol;
675 StringRef Name;
676 if (error(coff->getSymbol(SI, Symbol)))
677 return;
678
679 if (error(coff->getSymbolName(Symbol, Name)))
680 return;
681
682 outs() << "[" << format("%2d", SI) << "]"
683 << "(sec " << format("%2d", int(Symbol->SectionNumber)) << ")"
684 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
685 << "(ty " << format("%3x", unsigned(Symbol->Type)) << ")"
686 << "(scl " << format("%3x", unsigned(Symbol->StorageClass)) << ") "
687 << "(nx " << unsigned(Symbol->NumberOfAuxSymbols) << ") "
688 << "0x" << format("%08x", unsigned(Symbol->Value)) << " "
689 << Name << "\n";
690
691 for (unsigned AI = 0, AE = Symbol->NumberOfAuxSymbols; AI < AE; ++AI, ++SI) {
692 if (Symbol->isSectionDefinition()) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000693 const coff_aux_section_definition *asd;
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +0000694 if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd)))
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000695 return;
Saleem Abdulrasool9ede5c72014-04-13 03:11:08 +0000696
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000697 outs() << "AUX "
698 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
699 , unsigned(asd->Length)
700 , unsigned(asd->NumberOfRelocations)
701 , unsigned(asd->NumberOfLinenumbers)
702 , unsigned(asd->CheckSum))
703 << format("assoc %d comdat %d\n"
704 , unsigned(asd->Number)
705 , unsigned(asd->Selection));
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +0000706 } else if (Symbol->isFileRecord()) {
Saleem Abdulrasool63a0dd62014-04-13 22:54:11 +0000707 const coff_aux_file *AF;
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +0000708 if (error(coff->getAuxSymbol<coff_aux_file>(SI + 1, AF)))
Saleem Abdulrasool63a0dd62014-04-13 22:54:11 +0000709 return;
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +0000710
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +0000711 StringRef Name(AF->FileName,
712 Symbol->NumberOfAuxSymbols * COFF::SymbolSize);
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +0000713 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
Saleem Abdulrasool13a3f692014-04-14 16:38:25 +0000714
715 SI = SI + Symbol->NumberOfAuxSymbols;
716 break;
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +0000717 } else {
718 outs() << "AUX Unknown\n";
Saleem Abdulrasool9ede5c72014-04-13 03:11:08 +0000719 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000720 }
721 }
722}
723
724static void PrintSymbolTable(const ObjectFile *o) {
725 outs() << "SYMBOL TABLE:\n";
726
Rui Ueyama4e39f712014-03-18 18:58:51 +0000727 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000728 PrintCOFFSymbolTable(coff);
Rui Ueyama4e39f712014-03-18 18:58:51 +0000729 return;
730 }
731 for (const SymbolRef &Symbol : o->symbols()) {
732 StringRef Name;
733 uint64_t Address;
734 SymbolRef::Type Type;
735 uint64_t Size;
736 uint32_t Flags = Symbol.getFlags();
737 section_iterator Section = o->section_end();
738 if (error(Symbol.getName(Name)))
739 continue;
740 if (error(Symbol.getAddress(Address)))
741 continue;
742 if (error(Symbol.getType(Type)))
743 continue;
744 if (error(Symbol.getSize(Size)))
745 continue;
746 if (error(Symbol.getSection(Section)))
747 continue;
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000748
Rui Ueyama4e39f712014-03-18 18:58:51 +0000749 bool Global = Flags & SymbolRef::SF_Global;
750 bool Weak = Flags & SymbolRef::SF_Weak;
751 bool Absolute = Flags & SymbolRef::SF_Absolute;
David Meyer1df4b842012-02-28 23:47:53 +0000752
Rui Ueyama4e39f712014-03-18 18:58:51 +0000753 if (Address == UnknownAddressOrSize)
754 Address = 0;
755 if (Size == UnknownAddressOrSize)
756 Size = 0;
757 char GlobLoc = ' ';
758 if (Type != SymbolRef::ST_Unknown)
759 GlobLoc = Global ? 'g' : 'l';
760 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
761 ? 'd' : ' ';
762 char FileFunc = ' ';
763 if (Type == SymbolRef::ST_File)
764 FileFunc = 'f';
765 else if (Type == SymbolRef::ST_Function)
766 FileFunc = 'F';
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000767
Rui Ueyama4e39f712014-03-18 18:58:51 +0000768 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
769 "%08" PRIx64;
Michael J. Spencerd857c1c2013-01-10 22:40:50 +0000770
Rui Ueyama4e39f712014-03-18 18:58:51 +0000771 outs() << format(Fmt, Address) << " "
772 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
773 << (Weak ? 'w' : ' ') // Weak?
774 << ' ' // Constructor. Not supported yet.
775 << ' ' // Warning. Not supported yet.
776 << ' ' // Indirect reference to another symbol.
777 << Debug // Debugging (d) or dynamic (D) symbol.
778 << FileFunc // Name of function (F), file (f) or object (O).
779 << ' ';
780 if (Absolute) {
781 outs() << "*ABS*";
782 } else if (Section == o->section_end()) {
783 outs() << "*UND*";
784 } else {
785 if (const MachOObjectFile *MachO =
786 dyn_cast<const MachOObjectFile>(o)) {
787 DataRefImpl DR = Section->getRawDataRefImpl();
788 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
789 outs() << SegmentName << ",";
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000790 }
Rui Ueyama4e39f712014-03-18 18:58:51 +0000791 StringRef SectionName;
792 if (error(Section->getName(SectionName)))
793 SectionName = "";
794 outs() << SectionName;
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000795 }
Rui Ueyama4e39f712014-03-18 18:58:51 +0000796 outs() << '\t'
797 << format("%08" PRIx64 " ", Size)
798 << Name
799 << '\n';
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000800 }
801}
802
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000803static void PrintUnwindInfo(const ObjectFile *o) {
804 outs() << "Unwind info:\n\n";
805
806 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
807 printCOFFUnwindInfo(coff);
808 } else {
809 // TODO: Extract DWARF dump tool to objdump.
810 errs() << "This operation is only currently supported "
811 "for COFF object files.\n";
812 return;
813 }
814}
815
Rui Ueyamac2bed422013-09-27 21:04:00 +0000816static void printPrivateFileHeader(const ObjectFile *o) {
817 if (o->isELF()) {
818 printELFFileHeader(o);
819 } else if (o->isCOFF()) {
820 printCOFFFileHeader(o);
821 }
822}
823
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000824static void DumpObject(const ObjectFile *o) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000825 outs() << '\n';
826 outs() << o->getFileName()
827 << ":\tfile format " << o->getFileFormatName() << "\n\n";
828
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000829 if (Disassemble)
Michael J. Spencer51862b32011-10-13 22:17:18 +0000830 DisassembleObject(o, Relocations);
831 if (Relocations && !Disassemble)
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000832 PrintRelocations(o);
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000833 if (SectionHeaders)
834 PrintSectionHeaders(o);
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000835 if (SectionContents)
836 PrintSectionContents(o);
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000837 if (SymbolTable)
838 PrintSymbolTable(o);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000839 if (UnwindInfo)
840 PrintUnwindInfo(o);
Rui Ueyamac2bed422013-09-27 21:04:00 +0000841 if (PrivateHeaders)
842 printPrivateFileHeader(o);
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000843}
844
845/// @brief Dump each object file in \a a;
846static void DumpArchive(const Archive *a) {
Mark Seaborneb03ac52014-01-25 00:32:01 +0000847 for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
848 ++i) {
Rafael Espindolaae460022014-06-16 16:08:36 +0000849 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
850 if (std::error_code EC = ChildOrErr.getError()) {
Michael J. Spencer53723de2011-11-16 01:24:41 +0000851 // Ignore non-object files.
Mark Seaborneb03ac52014-01-25 00:32:01 +0000852 if (EC != object_error::invalid_file_type)
853 errs() << ToolName << ": '" << a->getFileName() << "': " << EC.message()
Michael J. Spencer53723de2011-11-16 01:24:41 +0000854 << ".\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000855 continue;
856 }
Rafael Espindolaae460022014-06-16 16:08:36 +0000857 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000858 DumpObject(o);
859 else
860 errs() << ToolName << ": '" << a->getFileName() << "': "
861 << "Unrecognized file type.\n";
862 }
863}
864
865/// @brief Open file and figure out how to dump it.
866static void DumpInput(StringRef file) {
867 // If file isn't stdin, check that it exists.
868 if (file != "-" && !sys::fs::exists(file)) {
869 errs() << ToolName << ": '" << file << "': " << "No such file\n";
870 return;
871 }
872
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000873 if (MachOOpt && Disassemble) {
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000874 DisassembleInputMachO(file);
875 return;
876 }
877
878 // Attempt to open the binary.
Rafael Espindola63da2952014-01-15 19:37:43 +0000879 ErrorOr<Binary *> BinaryOrErr = createBinary(file);
Rafael Espindola4453e42942014-06-13 03:07:50 +0000880 if (std::error_code EC = BinaryOrErr.getError()) {
Rafael Espindola63da2952014-01-15 19:37:43 +0000881 errs() << ToolName << ": '" << file << "': " << EC.message() << ".\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000882 return;
883 }
Ahmed Charles56440fd2014-03-06 05:51:42 +0000884 std::unique_ptr<Binary> binary(BinaryOrErr.get());
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000885
Jim Grosbachaf9aec02012-08-07 17:53:14 +0000886 if (Archive *a = dyn_cast<Archive>(binary.get()))
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000887 DumpArchive(a);
Jim Grosbachaf9aec02012-08-07 17:53:14 +0000888 else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get()))
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000889 DumpObject(o);
Jim Grosbachaf9aec02012-08-07 17:53:14 +0000890 else
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000891 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000892}
893
Michael J. Spencer2670c252011-01-20 06:39:06 +0000894int main(int argc, char **argv) {
895 // Print a stack trace if we signal out.
896 sys::PrintStackTraceOnErrorSignal();
897 PrettyStackTraceProgram X(argc, argv);
898 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
899
900 // Initialize targets and assembly printers/parsers.
901 llvm::InitializeAllTargetInfos();
Evan Cheng8c886a42011-07-22 21:58:54 +0000902 llvm::InitializeAllTargetMCs();
Michael J. Spencer2670c252011-01-20 06:39:06 +0000903 llvm::InitializeAllAsmParsers();
904 llvm::InitializeAllDisassemblers();
905
Pete Cooper28fb4fc2012-05-03 23:20:10 +0000906 // Register the target printer for --version.
907 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
908
Michael J. Spencer2670c252011-01-20 06:39:06 +0000909 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
910 TripleName = Triple::normalize(TripleName);
911
912 ToolName = argv[0];
913
914 // Defaults to a.out if no filenames specified.
915 if (InputFilenames.size() == 0)
916 InputFilenames.push_back("a.out");
917
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000918 if (!Disassemble
919 && !Relocations
920 && !SectionHeaders
921 && !SectionContents
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000922 && !SymbolTable
Michael J. Spencer209565db2013-01-06 03:56:49 +0000923 && !UnwindInfo
924 && !PrivateHeaders) {
Michael J. Spencer2670c252011-01-20 06:39:06 +0000925 cl::PrintHelpMessage();
926 return 2;
927 }
928
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000929 std::for_each(InputFilenames.begin(), InputFilenames.end(),
930 DumpInput);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000931
932 return 0;
933}