blob: 9d043f18c2e5ef4db7c71299d5e809527205ce6f [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 "llvm/Support/system_error.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000061#include <algorithm>
Benjamin Kramera5177e62012-03-23 11:49:32 +000062#include <cctype>
Michael J. Spencer2670c252011-01-20 06:39:06 +000063#include <cstring>
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
Mark Seaborneb03ac52014-01-25 00:32:01 +0000151bool llvm::error(error_code EC) {
152 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
Jim Grosbachaf9aec02012-08-07 17:53:14 +0000160static const Target *getTarget(const ObjectFile *Obj = NULL) {
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);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000170 }
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000171 } else
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000172 TheTriple.setTriple(Triple::normalize(TripleName));
Michael J. Spencer2670c252011-01-20 06:39:06 +0000173
174 // Get the target specific parser.
175 std::string Error;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000176 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
177 Error);
178 if (!TheTarget) {
179 errs() << ToolName << ": " << Error;
180 return 0;
181 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000182
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000183 // Update the triple name and return the found target.
184 TripleName = TheTriple.getTriple();
185 return TheTarget;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000186}
187
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000188// Write a graphviz file for the CFG inside an MCFunction.
Ahmed Bougacha17926472013-08-21 07:29:02 +0000189// FIXME: Use GraphWriter
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000190static void emitDOTFile(const char *FileName, const MCFunction &f,
191 MCInstPrinter *IP) {
192 // Start a new dot file.
193 std::string Error;
Rafael Espindola90c7f1c2014-02-24 18:20:12 +0000194 raw_fd_ostream Out(FileName, Error, sys::fs::F_Text);
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000195 if (!Error.empty()) {
196 errs() << "llvm-objdump: warning: " << Error << '\n';
197 return;
198 }
199
200 Out << "digraph \"" << f.getName() << "\" {\n";
201 Out << "graph [ rankdir = \"LR\" ];\n";
202 for (MCFunction::const_iterator i = f.begin(), e = f.end(); i != e; ++i) {
203 // Only print blocks that have predecessors.
204 bool hasPreds = (*i)->pred_begin() != (*i)->pred_end();
205
206 if (!hasPreds && i != f.begin())
207 continue;
208
209 Out << '"' << (*i)->getInsts()->getBeginAddr() << "\" [ label=\"<a>";
210 // Print instructions.
211 for (unsigned ii = 0, ie = (*i)->getInsts()->size(); ii != ie;
212 ++ii) {
213 if (ii != 0) // Not the first line, start a new row.
214 Out << '|';
215 if (ii + 1 == ie) // Last line, add an end id.
216 Out << "<o>";
217
218 // Escape special chars and print the instruction in mnemonic form.
219 std::string Str;
220 raw_string_ostream OS(Str);
221 IP->printInst(&(*i)->getInsts()->at(ii).Inst, OS, "");
222 Out << DOT::EscapeString(OS.str());
223 }
224 Out << "\" shape=\"record\" ];\n";
225
226 // Add edges.
227 for (MCBasicBlock::succ_const_iterator si = (*i)->succ_begin(),
228 se = (*i)->succ_end(); si != se; ++si)
229 Out << (*i)->getInsts()->getBeginAddr() << ":o -> "
230 << (*si)->getInsts()->getBeginAddr() << ":a\n";
231 }
232 Out << "}\n";
233}
David Blaikiea379b1812011-12-20 02:50:00 +0000234
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000235void llvm::DumpBytes(StringRef bytes) {
236 static const char hex_rep[] = "0123456789abcdef";
Michael J. Spencer2670c252011-01-20 06:39:06 +0000237 // FIXME: The real way to do this is to figure out the longest instruction
238 // and align to that size before printing. I'll fix this when I get
239 // around to outputting relocations.
240 // 15 is the longest x86 instruction
241 // 3 is for the hex rep of a byte + a space.
242 // 1 is for the null terminator.
243 enum { OutputSize = (15 * 3) + 1 };
244 char output[OutputSize];
245
246 assert(bytes.size() <= 15
247 && "DumpBytes only supports instructions of up to 15 bytes");
248 memset(output, ' ', sizeof(output));
249 unsigned index = 0;
250 for (StringRef::iterator i = bytes.begin(),
251 e = bytes.end(); i != e; ++i) {
252 output[index] = hex_rep[(*i & 0xF0) >> 4];
253 output[index + 1] = hex_rep[*i & 0xF];
254 index += 3;
255 }
256
257 output[sizeof(output) - 1] = 0;
258 outs() << output;
259}
260
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000261bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
Michael J. Spencer51862b32011-10-13 22:17:18 +0000262 uint64_t a_addr, b_addr;
Rafael Espindola1e483872013-04-25 12:28:45 +0000263 if (error(a.getOffset(a_addr))) return false;
264 if (error(b.getOffset(b_addr))) return false;
Michael J. Spencer51862b32011-10-13 22:17:18 +0000265 return a_addr < b_addr;
266}
267
268static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Jim Grosbachaf9aec02012-08-07 17:53:14 +0000269 const Target *TheTarget = getTarget(Obj);
270 // getTarget() will have already issued a diagnostic if necessary, so
271 // just bail here if it failed.
272 if (!TheTarget)
Michael J. Spencer2670c252011-01-20 06:39:06 +0000273 return;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000274
Jack Carter551efd72012-08-28 19:24:49 +0000275 // Package up features to be passed to target/subtarget
276 std::string FeaturesStr;
277 if (MAttrs.size()) {
278 SubtargetFeatures Features;
279 for (unsigned i = 0; i != MAttrs.size(); ++i)
280 Features.AddFeature(MAttrs[i]);
281 FeaturesStr = Features.getString();
282 }
283
Ahmed Charles56440fd2014-03-06 05:51:42 +0000284 std::unique_ptr<const MCRegisterInfo> MRI(
285 TheTarget->createMCRegInfo(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000286 if (!MRI) {
287 errs() << "error: no register info for target " << TripleName << "\n";
288 return;
289 }
290
291 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000292 std::unique_ptr<const MCAsmInfo> AsmInfo(
293 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000294 if (!AsmInfo) {
295 errs() << "error: no assembly info for target " << TripleName << "\n";
296 return;
297 }
298
Ahmed Charles56440fd2014-03-06 05:51:42 +0000299 std::unique_ptr<const MCSubtargetInfo> STI(
300 TheTarget->createMCSubtargetInfo(TripleName, "", FeaturesStr));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000301 if (!STI) {
302 errs() << "error: no subtarget info for target " << TripleName << "\n";
303 return;
304 }
305
Ahmed Charles56440fd2014-03-06 05:51:42 +0000306 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000307 if (!MII) {
308 errs() << "error: no instruction info for target " << TripleName << "\n";
309 return;
310 }
311
Lang Hamesa1bc0f52014-04-15 04:40:56 +0000312 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
313 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
314
315 std::unique_ptr<MCDisassembler> DisAsm(
316 TheTarget->createMCDisassembler(*STI, Ctx));
317
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000318 if (!DisAsm) {
319 errs() << "error: no disassembler for target " << TripleName << "\n";
320 return;
321 }
322
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000323
324 if (Symbolize) {
Ahmed Charles56440fd2014-03-06 05:51:42 +0000325 std::unique_ptr<MCRelocationInfo> RelInfo(
Lang Hamesa1bc0f52014-04-15 04:40:56 +0000326 TheTarget->createMCRelocationInfo(TripleName, Ctx));
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000327 if (RelInfo) {
Ahmed Charles56440fd2014-03-06 05:51:42 +0000328 std::unique_ptr<MCSymbolizer> Symzer(
Lang Hamesa1bc0f52014-04-15 04:40:56 +0000329 MCObjectSymbolizer::createObjectSymbolizer(Ctx, std::move(RelInfo),
330 Obj));
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000331 if (Symzer)
Ahmed Charlesdf17c832014-03-07 09:38:02 +0000332 DisAsm->setSymbolizer(std::move(Symzer));
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000333 }
334 }
335
Ahmed Charles56440fd2014-03-06 05:51:42 +0000336 std::unique_ptr<const MCInstrAnalysis> MIA(
337 TheTarget->createMCInstrAnalysis(MII.get()));
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000338
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000339 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +0000340 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000341 AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
342 if (!IP) {
343 errs() << "error: no instruction printer for target " << TripleName
344 << '\n';
345 return;
346 }
347
Ahmed Bougacha17926472013-08-21 07:29:02 +0000348 if (CFG || !YAMLCFG.empty()) {
Ahmed Charles56440fd2014-03-06 05:51:42 +0000349 std::unique_ptr<MCObjectDisassembler> OD(
350 new MCObjectDisassembler(*Obj, *DisAsm, *MIA));
351 std::unique_ptr<MCModule> Mod(OD->buildModule(/* withCFG */ true));
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000352 for (MCModule::const_atom_iterator AI = Mod->atom_begin(),
353 AE = Mod->atom_end();
354 AI != AE; ++AI) {
355 outs() << "Atom " << (*AI)->getName() << ": \n";
356 if (const MCTextAtom *TA = dyn_cast<MCTextAtom>(*AI)) {
357 for (MCTextAtom::const_iterator II = TA->begin(), IE = TA->end();
358 II != IE;
359 ++II) {
360 IP->printInst(&II->Inst, outs(), "");
361 outs() << "\n";
362 }
363 }
364 }
Ahmed Bougacha17926472013-08-21 07:29:02 +0000365 if (CFG) {
366 for (MCModule::const_func_iterator FI = Mod->func_begin(),
367 FE = Mod->func_end();
368 FI != FE; ++FI) {
369 static int filenum = 0;
370 emitDOTFile((Twine((*FI)->getName()) + "_" +
371 utostr(filenum) + ".dot").str().c_str(),
372 **FI, IP.get());
373 ++filenum;
374 }
375 }
376 if (!YAMLCFG.empty()) {
377 std::string Error;
Rafael Espindola90c7f1c2014-02-24 18:20:12 +0000378 raw_fd_ostream YAMLOut(YAMLCFG.c_str(), Error, sys::fs::F_Text);
Ahmed Bougacha17926472013-08-21 07:29:02 +0000379 if (!Error.empty()) {
Ahmed Bougachad56f7052013-08-21 16:13:25 +0000380 errs() << ToolName << ": warning: " << Error << '\n';
Ahmed Bougacha17926472013-08-21 07:29:02 +0000381 return;
382 }
383 mcmodule2yaml(YAMLOut, *Mod, *MII, *MRI);
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000384 }
385 }
386
Greg Fitzgerald18432272014-03-20 22:55:15 +0000387 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
388 "\t\t\t%08" PRIx64 ": ";
389
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000390 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
391 // in RelocSecs contain the relocations for section S.
Mark Seaborneb03ac52014-01-25 00:32:01 +0000392 error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000393 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
394 for (const SectionRef &Section : Obj->sections()) {
395 section_iterator Sec2 = Section.getRelocatedSection();
Rafael Espindolab5155a52014-02-10 20:24:04 +0000396 if (Sec2 != Obj->section_end())
Alexey Samsonov48803e52014-03-13 14:37:36 +0000397 SectionRelocMap[*Sec2].push_back(Section);
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000398 }
399
Alexey Samsonov48803e52014-03-13 14:37:36 +0000400 for (const SectionRef &Section : Obj->sections()) {
Mark Seaborneb03ac52014-01-25 00:32:01 +0000401 bool Text;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000402 if (error(Section.isText(Text)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000403 break;
404 if (!Text)
405 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000406
Michael J. Spencer51862b32011-10-13 22:17:18 +0000407 uint64_t SectionAddr;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000408 if (error(Section.getAddress(SectionAddr)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000409 break;
Michael J. Spencer51862b32011-10-13 22:17:18 +0000410
Simon Atanasyan2b614e12014-02-24 22:12:11 +0000411 uint64_t SectSize;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000412 if (error(Section.getSize(SectSize)))
Simon Atanasyan2b614e12014-02-24 22:12:11 +0000413 break;
414
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000415 // Make a list of all the symbols in this section.
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000416 std::vector<std::pair<uint64_t, StringRef>> Symbols;
417 for (const SymbolRef &Symbol : Obj->symbols()) {
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000418 bool contains;
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000419 if (!error(Section.containsSymbol(Symbol, contains)) && contains) {
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000420 uint64_t Address;
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000421 if (error(Symbol.getAddress(Address)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000422 break;
423 if (Address == UnknownAddressOrSize)
424 continue;
Cameron Zwarich07f0f772012-02-03 04:13:37 +0000425 Address -= SectionAddr;
Simon Atanasyan2b614e12014-02-24 22:12:11 +0000426 if (Address >= SectSize)
427 continue;
Cameron Zwarich07f0f772012-02-03 04:13:37 +0000428
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000429 StringRef Name;
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000430 if (error(Symbol.getName(Name)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000431 break;
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000432 Symbols.push_back(std::make_pair(Address, Name));
433 }
434 }
435
436 // Sort the symbols by address, just in case they didn't come in that way.
437 array_pod_sort(Symbols.begin(), Symbols.end());
438
Michael J. Spencer51862b32011-10-13 22:17:18 +0000439 // Make a list of all the relocations for this section.
440 std::vector<RelocationRef> Rels;
441 if (InlineRelocs) {
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000442 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
443 for (const RelocationRef &Reloc : RelocSec.relocations()) {
444 Rels.push_back(Reloc);
445 }
Michael J. Spencer51862b32011-10-13 22:17:18 +0000446 }
447 }
448
449 // Sort relocations by address.
450 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
451
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000452 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +0000453 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +0000454 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +0000455 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000456 }
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000457 StringRef name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000458 if (error(Section.getName(name)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000459 break;
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000460 outs() << "Disassembly of section ";
461 if (!SegmentName.empty())
462 outs() << SegmentName << ",";
463 outs() << name << ':';
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000464
465 // If the section has no symbols just insert a dummy one and disassemble
466 // the whole section.
467 if (Symbols.empty())
468 Symbols.push_back(std::make_pair(0, name));
Michael J. Spencer2670c252011-01-20 06:39:06 +0000469
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000470
471 SmallString<40> Comments;
472 raw_svector_ostream CommentStream(Comments);
473
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000474 StringRef Bytes;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000475 if (error(Section.getContents(Bytes)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000476 break;
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000477 StringRefMemoryObject memoryObject(Bytes, SectionAddr);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000478 uint64_t Size;
479 uint64_t Index;
480
Michael J. Spencer51862b32011-10-13 22:17:18 +0000481 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
482 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000483 // Disassemble symbol by symbol.
484 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
485 uint64_t Start = Symbols[si].first;
Michael J. Spenceree84f642011-10-13 20:37:08 +0000486 uint64_t End;
487 // The end is either the size of the section or the beginning of the next
488 // symbol.
489 if (si == se - 1)
490 End = SectSize;
491 // Make sure this symbol takes up space.
492 else if (Symbols[si + 1].first != Start)
493 End = Symbols[si + 1].first - 1;
494 else
495 // This symbol has the same address as the next symbol. Skip it.
496 continue;
497
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000498 outs() << '\n' << Symbols[si].second << ":\n";
Michael J. Spencer2670c252011-01-20 06:39:06 +0000499
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000500#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +0000501 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000502#else
Mark Seaborneb03ac52014-01-25 00:32:01 +0000503 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000504#endif
505
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000506 for (Index = Start; Index < End; Index += Size) {
507 MCInst Inst;
Owen Andersona0c3b972011-09-15 23:38:46 +0000508
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000509 if (DisAsm->getInstruction(Inst, Size, memoryObject,
510 SectionAddr + Index,
511 DebugOut, CommentStream)) {
Eli Bendersky3a6808c2012-11-20 22:57:02 +0000512 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
513 if (!NoShowRawInsn) {
514 outs() << "\t";
515 DumpBytes(StringRef(Bytes.data() + Index, Size));
516 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000517 IP->printInst(&Inst, outs(), "");
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000518 outs() << CommentStream.str();
519 Comments.clear();
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000520 outs() << "\n";
521 } else {
522 errs() << ToolName << ": warning: invalid instruction encoding\n";
523 if (Size == 0)
524 Size = 1; // skip illegible bytes
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000525 }
Michael J. Spencer51862b32011-10-13 22:17:18 +0000526
527 // Print relocation for instruction.
528 while (rel_cur != rel_end) {
Owen Andersonfa3e5202011-10-25 20:35:53 +0000529 bool hidden = false;
Michael J. Spencer51862b32011-10-13 22:17:18 +0000530 uint64_t addr;
531 SmallString<16> name;
532 SmallString<32> val;
Owen Andersonfa3e5202011-10-25 20:35:53 +0000533
534 // If this relocation is hidden, skip it.
535 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
536 if (hidden) goto skip_print_rel;
537
Rafael Espindola1e483872013-04-25 12:28:45 +0000538 if (error(rel_cur->getOffset(addr))) goto skip_print_rel;
Michael J. Spencer51862b32011-10-13 22:17:18 +0000539 // Stop when rel_cur's address is past the current instruction.
Owen Andersonf20e3e52011-10-25 20:15:39 +0000540 if (addr >= Index + Size) break;
Michael J. Spencer51862b32011-10-13 22:17:18 +0000541 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
542 if (error(rel_cur->getValueString(val))) goto skip_print_rel;
543
Greg Fitzgerald18432272014-03-20 22:55:15 +0000544 outs() << format(Fmt.data(), SectionAddr + addr) << name
Benjamin Kramer82803112012-03-10 02:04:38 +0000545 << "\t" << val << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +0000546
547 skip_print_rel:
548 ++rel_cur;
549 }
Benjamin Kramer87ee76c2011-07-20 19:37:35 +0000550 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000551 }
552 }
553}
554
Alexey Samsonov48803e52014-03-13 14:37:36 +0000555static void PrintRelocations(const ObjectFile *Obj) {
Greg Fitzgerald18432272014-03-20 22:55:15 +0000556 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
557 "%08" PRIx64;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000558 for (const SectionRef &Section : Obj->sections()) {
559 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000560 continue;
561 StringRef secname;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000562 if (error(Section.getName(secname)))
563 continue;
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000564 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000565 for (const RelocationRef &Reloc : Section.relocations()) {
Owen Andersonfa3e5202011-10-25 20:35:53 +0000566 bool hidden;
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000567 uint64_t address;
568 SmallString<32> relocname;
569 SmallString<32> valuestr;
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000570 if (error(Reloc.getHidden(hidden)))
571 continue;
572 if (hidden)
573 continue;
574 if (error(Reloc.getTypeName(relocname)))
575 continue;
576 if (error(Reloc.getOffset(address)))
577 continue;
578 if (error(Reloc.getValueString(valuestr)))
579 continue;
Greg Fitzgerald18432272014-03-20 22:55:15 +0000580 outs() << format(Fmt.data(), address) << " " << relocname << " "
581 << valuestr << "\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000582 }
583 outs() << "\n";
584 }
585}
586
Alexey Samsonov48803e52014-03-13 14:37:36 +0000587static void PrintSectionHeaders(const ObjectFile *Obj) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000588 outs() << "Sections:\n"
589 "Idx Name Size Address Type\n";
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000590 unsigned i = 0;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000591 for (const SectionRef &Section : Obj->sections()) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000592 StringRef Name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000593 if (error(Section.getName(Name)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000594 return;
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000595 uint64_t Address;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000596 if (error(Section.getAddress(Address)))
597 return;
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000598 uint64_t Size;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000599 if (error(Section.getSize(Size)))
600 return;
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000601 bool Text, Data, BSS;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000602 if (error(Section.isText(Text)))
603 return;
604 if (error(Section.isData(Data)))
605 return;
606 if (error(Section.isBSS(BSS)))
607 return;
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000608 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +0000609 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
Alexey Samsonov48803e52014-03-13 14:37:36 +0000610 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
611 Name.str().c_str(), Size, Address, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000612 ++i;
613 }
614}
615
Alexey Samsonov48803e52014-03-13 14:37:36 +0000616static void PrintSectionContents(const ObjectFile *Obj) {
Mark Seaborneb03ac52014-01-25 00:32:01 +0000617 error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000618 for (const SectionRef &Section : Obj->sections()) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000619 StringRef Name;
620 StringRef Contents;
621 uint64_t BaseAddr;
Alexey Samsonov209095c2013-04-16 10:53:11 +0000622 bool BSS;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000623 if (error(Section.getName(Name)))
624 continue;
625 if (error(Section.getContents(Contents)))
626 continue;
627 if (error(Section.getAddress(BaseAddr)))
628 continue;
629 if (error(Section.isBSS(BSS)))
630 continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000631
632 outs() << "Contents of section " << Name << ":\n";
Alexey Samsonov209095c2013-04-16 10:53:11 +0000633 if (BSS) {
634 outs() << format("<skipping contents of bss section at [%04" PRIx64
635 ", %04" PRIx64 ")>\n", BaseAddr,
636 BaseAddr + Contents.size());
637 continue;
638 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000639
640 // Dump out the content as hex and printable ascii characters.
641 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer82803112012-03-10 02:04:38 +0000642 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000643 // Dump line of hex.
644 for (std::size_t i = 0; i < 16; ++i) {
645 if (i != 0 && i % 4 == 0)
646 outs() << ' ';
647 if (addr + i < end)
648 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
649 << hexdigit(Contents[addr + i] & 0xF, true);
650 else
651 outs() << " ";
652 }
653 // Print ascii.
654 outs() << " ";
655 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
Guy Benyei83c74e92013-02-12 21:21:59 +0000656 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000657 outs() << Contents[addr + i];
658 else
659 outs() << ".";
660 }
661 outs() << "\n";
662 }
663 }
664}
665
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000666static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
667 const coff_file_header *header;
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +0000668 if (error(coff->getHeader(header)))
669 return;
670
671 for (unsigned SI = 0, SE = header->NumberOfSymbols; SI != SE; ++SI) {
672 const coff_symbol *Symbol;
673 StringRef Name;
674 if (error(coff->getSymbol(SI, Symbol)))
675 return;
676
677 if (error(coff->getSymbolName(Symbol, Name)))
678 return;
679
680 outs() << "[" << format("%2d", SI) << "]"
681 << "(sec " << format("%2d", int(Symbol->SectionNumber)) << ")"
682 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
683 << "(ty " << format("%3x", unsigned(Symbol->Type)) << ")"
684 << "(scl " << format("%3x", unsigned(Symbol->StorageClass)) << ") "
685 << "(nx " << unsigned(Symbol->NumberOfAuxSymbols) << ") "
686 << "0x" << format("%08x", unsigned(Symbol->Value)) << " "
687 << Name << "\n";
688
689 for (unsigned AI = 0, AE = Symbol->NumberOfAuxSymbols; AI < AE; ++AI, ++SI) {
690 if (Symbol->isSectionDefinition()) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000691 const coff_aux_section_definition *asd;
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +0000692 if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd)))
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000693 return;
Saleem Abdulrasool9ede5c72014-04-13 03:11:08 +0000694
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000695 outs() << "AUX "
696 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
697 , unsigned(asd->Length)
698 , unsigned(asd->NumberOfRelocations)
699 , unsigned(asd->NumberOfLinenumbers)
700 , unsigned(asd->CheckSum))
701 << format("assoc %d comdat %d\n"
702 , unsigned(asd->Number)
703 , unsigned(asd->Selection));
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +0000704 } else if (Symbol->isFileRecord()) {
Saleem Abdulrasool63a0dd62014-04-13 22:54:11 +0000705 const coff_aux_file *AF;
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +0000706 if (error(coff->getAuxSymbol<coff_aux_file>(SI + 1, AF)))
Saleem Abdulrasool63a0dd62014-04-13 22:54:11 +0000707 return;
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +0000708
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +0000709 StringRef Name(AF->FileName,
710 Symbol->NumberOfAuxSymbols * COFF::SymbolSize);
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +0000711 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
Saleem Abdulrasool13a3f692014-04-14 16:38:25 +0000712
713 SI = SI + Symbol->NumberOfAuxSymbols;
714 break;
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +0000715 } else {
716 outs() << "AUX Unknown\n";
Saleem Abdulrasool9ede5c72014-04-13 03:11:08 +0000717 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000718 }
719 }
720}
721
722static void PrintSymbolTable(const ObjectFile *o) {
723 outs() << "SYMBOL TABLE:\n";
724
Rui Ueyama4e39f712014-03-18 18:58:51 +0000725 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000726 PrintCOFFSymbolTable(coff);
Rui Ueyama4e39f712014-03-18 18:58:51 +0000727 return;
728 }
729 for (const SymbolRef &Symbol : o->symbols()) {
730 StringRef Name;
731 uint64_t Address;
732 SymbolRef::Type Type;
733 uint64_t Size;
734 uint32_t Flags = Symbol.getFlags();
735 section_iterator Section = o->section_end();
736 if (error(Symbol.getName(Name)))
737 continue;
738 if (error(Symbol.getAddress(Address)))
739 continue;
740 if (error(Symbol.getType(Type)))
741 continue;
742 if (error(Symbol.getSize(Size)))
743 continue;
744 if (error(Symbol.getSection(Section)))
745 continue;
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000746
Rui Ueyama4e39f712014-03-18 18:58:51 +0000747 bool Global = Flags & SymbolRef::SF_Global;
748 bool Weak = Flags & SymbolRef::SF_Weak;
749 bool Absolute = Flags & SymbolRef::SF_Absolute;
David Meyer1df4b842012-02-28 23:47:53 +0000750
Rui Ueyama4e39f712014-03-18 18:58:51 +0000751 if (Address == UnknownAddressOrSize)
752 Address = 0;
753 if (Size == UnknownAddressOrSize)
754 Size = 0;
755 char GlobLoc = ' ';
756 if (Type != SymbolRef::ST_Unknown)
757 GlobLoc = Global ? 'g' : 'l';
758 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
759 ? 'd' : ' ';
760 char FileFunc = ' ';
761 if (Type == SymbolRef::ST_File)
762 FileFunc = 'f';
763 else if (Type == SymbolRef::ST_Function)
764 FileFunc = 'F';
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000765
Rui Ueyama4e39f712014-03-18 18:58:51 +0000766 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
767 "%08" PRIx64;
Michael J. Spencerd857c1c2013-01-10 22:40:50 +0000768
Rui Ueyama4e39f712014-03-18 18:58:51 +0000769 outs() << format(Fmt, Address) << " "
770 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
771 << (Weak ? 'w' : ' ') // Weak?
772 << ' ' // Constructor. Not supported yet.
773 << ' ' // Warning. Not supported yet.
774 << ' ' // Indirect reference to another symbol.
775 << Debug // Debugging (d) or dynamic (D) symbol.
776 << FileFunc // Name of function (F), file (f) or object (O).
777 << ' ';
778 if (Absolute) {
779 outs() << "*ABS*";
780 } else if (Section == o->section_end()) {
781 outs() << "*UND*";
782 } else {
783 if (const MachOObjectFile *MachO =
784 dyn_cast<const MachOObjectFile>(o)) {
785 DataRefImpl DR = Section->getRawDataRefImpl();
786 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
787 outs() << SegmentName << ",";
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000788 }
Rui Ueyama4e39f712014-03-18 18:58:51 +0000789 StringRef SectionName;
790 if (error(Section->getName(SectionName)))
791 SectionName = "";
792 outs() << SectionName;
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000793 }
Rui Ueyama4e39f712014-03-18 18:58:51 +0000794 outs() << '\t'
795 << format("%08" PRIx64 " ", Size)
796 << Name
797 << '\n';
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000798 }
799}
800
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000801static void PrintUnwindInfo(const ObjectFile *o) {
802 outs() << "Unwind info:\n\n";
803
804 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
805 printCOFFUnwindInfo(coff);
806 } else {
807 // TODO: Extract DWARF dump tool to objdump.
808 errs() << "This operation is only currently supported "
809 "for COFF object files.\n";
810 return;
811 }
812}
813
Rui Ueyamac2bed422013-09-27 21:04:00 +0000814static void printPrivateFileHeader(const ObjectFile *o) {
815 if (o->isELF()) {
816 printELFFileHeader(o);
817 } else if (o->isCOFF()) {
818 printCOFFFileHeader(o);
819 }
820}
821
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000822static void DumpObject(const ObjectFile *o) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000823 outs() << '\n';
824 outs() << o->getFileName()
825 << ":\tfile format " << o->getFileFormatName() << "\n\n";
826
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000827 if (Disassemble)
Michael J. Spencer51862b32011-10-13 22:17:18 +0000828 DisassembleObject(o, Relocations);
829 if (Relocations && !Disassemble)
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000830 PrintRelocations(o);
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000831 if (SectionHeaders)
832 PrintSectionHeaders(o);
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000833 if (SectionContents)
834 PrintSectionContents(o);
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000835 if (SymbolTable)
836 PrintSymbolTable(o);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000837 if (UnwindInfo)
838 PrintUnwindInfo(o);
Rui Ueyamac2bed422013-09-27 21:04:00 +0000839 if (PrivateHeaders)
840 printPrivateFileHeader(o);
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000841}
842
843/// @brief Dump each object file in \a a;
844static void DumpArchive(const Archive *a) {
Mark Seaborneb03ac52014-01-25 00:32:01 +0000845 for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
846 ++i) {
Ahmed Charles56440fd2014-03-06 05:51:42 +0000847 std::unique_ptr<Binary> child;
Mark Seaborneb03ac52014-01-25 00:32:01 +0000848 if (error_code EC = i->getAsBinary(child)) {
Michael J. Spencer53723de2011-11-16 01:24:41 +0000849 // Ignore non-object files.
Mark Seaborneb03ac52014-01-25 00:32:01 +0000850 if (EC != object_error::invalid_file_type)
851 errs() << ToolName << ": '" << a->getFileName() << "': " << EC.message()
Michael J. Spencer53723de2011-11-16 01:24:41 +0000852 << ".\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000853 continue;
854 }
855 if (ObjectFile *o = dyn_cast<ObjectFile>(child.get()))
856 DumpObject(o);
857 else
858 errs() << ToolName << ": '" << a->getFileName() << "': "
859 << "Unrecognized file type.\n";
860 }
861}
862
863/// @brief Open file and figure out how to dump it.
864static void DumpInput(StringRef file) {
865 // If file isn't stdin, check that it exists.
866 if (file != "-" && !sys::fs::exists(file)) {
867 errs() << ToolName << ": '" << file << "': " << "No such file\n";
868 return;
869 }
870
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000871 if (MachOOpt && Disassemble) {
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000872 DisassembleInputMachO(file);
873 return;
874 }
875
876 // Attempt to open the binary.
Rafael Espindola63da2952014-01-15 19:37:43 +0000877 ErrorOr<Binary *> BinaryOrErr = createBinary(file);
878 if (error_code EC = BinaryOrErr.getError()) {
879 errs() << ToolName << ": '" << file << "': " << EC.message() << ".\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000880 return;
881 }
Ahmed Charles56440fd2014-03-06 05:51:42 +0000882 std::unique_ptr<Binary> binary(BinaryOrErr.get());
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000883
Jim Grosbachaf9aec02012-08-07 17:53:14 +0000884 if (Archive *a = dyn_cast<Archive>(binary.get()))
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000885 DumpArchive(a);
Jim Grosbachaf9aec02012-08-07 17:53:14 +0000886 else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get()))
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000887 DumpObject(o);
Jim Grosbachaf9aec02012-08-07 17:53:14 +0000888 else
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000889 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000890}
891
Michael J. Spencer2670c252011-01-20 06:39:06 +0000892int main(int argc, char **argv) {
893 // Print a stack trace if we signal out.
894 sys::PrintStackTraceOnErrorSignal();
895 PrettyStackTraceProgram X(argc, argv);
896 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
897
898 // Initialize targets and assembly printers/parsers.
899 llvm::InitializeAllTargetInfos();
Evan Cheng8c886a42011-07-22 21:58:54 +0000900 llvm::InitializeAllTargetMCs();
Michael J. Spencer2670c252011-01-20 06:39:06 +0000901 llvm::InitializeAllAsmParsers();
902 llvm::InitializeAllDisassemblers();
903
Pete Cooper28fb4fc2012-05-03 23:20:10 +0000904 // Register the target printer for --version.
905 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
906
Michael J. Spencer2670c252011-01-20 06:39:06 +0000907 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
908 TripleName = Triple::normalize(TripleName);
909
910 ToolName = argv[0];
911
912 // Defaults to a.out if no filenames specified.
913 if (InputFilenames.size() == 0)
914 InputFilenames.push_back("a.out");
915
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000916 if (!Disassemble
917 && !Relocations
918 && !SectionHeaders
919 && !SectionContents
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000920 && !SymbolTable
Michael J. Spencer209565db2013-01-06 03:56:49 +0000921 && !UnwindInfo
922 && !PrivateHeaders) {
Michael J. Spencer2670c252011-01-20 06:39:06 +0000923 cl::PrintHelpMessage();
924 return 2;
925 }
926
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000927 std::for_each(InputFilenames.begin(), InputFilenames.end(),
928 DumpInput);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000929
930 return 0;
931}