blob: 28d667a486e70147416b368c26ee6ad3247c9176 [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"
Sanjoy Das6f567a42015-06-22 18:03:02 +000020#include "llvm/ADT/Optional.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000021#include "llvm/ADT/STLExtras.h"
Michael J. Spencer4e25c022011-10-17 17:13:22 +000022#include "llvm/ADT/StringExtras.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000023#include "llvm/ADT/Triple.h"
Sanjoy Das3f1bc3b2015-06-23 20:09:03 +000024#include "llvm/CodeGen/FaultMaps.h"
Igor Laevsky03a670c2016-01-26 15:09:42 +000025#include "llvm/DebugInfo/DWARF/DWARFContext.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000026#include "llvm/MC/MCAsmInfo.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000027#include "llvm/MC/MCContext.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000028#include "llvm/MC/MCDisassembler/MCDisassembler.h"
29#include "llvm/MC/MCDisassembler/MCRelocationInfo.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000030#include "llvm/MC/MCInst.h"
31#include "llvm/MC/MCInstPrinter.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000032#include "llvm/MC/MCInstrAnalysis.h"
Craig Topper54bfde72012-04-02 06:09:36 +000033#include "llvm/MC/MCInstrInfo.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000034#include "llvm/MC/MCObjectFileInfo.h"
Jim Grosbachfd93a592012-03-05 19:33:20 +000035#include "llvm/MC/MCRegisterInfo.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000036#include "llvm/MC/MCSubtargetInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000037#include "llvm/Object/Archive.h"
38#include "llvm/Object/COFF.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000039#include "llvm/Object/ELFObjectFile.h"
Rafael Espindolaa9f810b2012-12-21 03:47:03 +000040#include "llvm/Object/MachO.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000041#include "llvm/Object/ObjectFile.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000042#include "llvm/Support/Casting.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000043#include "llvm/Support/CommandLine.h"
44#include "llvm/Support/Debug.h"
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +000045#include "llvm/Support/Errc.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000046#include "llvm/Support/FileSystem.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000047#include "llvm/Support/Format.h"
Benjamin Kramerbf115312011-07-25 23:04:36 +000048#include "llvm/Support/GraphWriter.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000049#include "llvm/Support/Host.h"
50#include "llvm/Support/ManagedStatic.h"
51#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000052#include "llvm/Support/PrettyStackTrace.h"
53#include "llvm/Support/Signals.h"
54#include "llvm/Support/SourceMgr.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000055#include "llvm/Support/TargetRegistry.h"
56#include "llvm/Support/TargetSelect.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000057#include "llvm/Support/raw_ostream.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000058#include <algorithm>
Benjamin Kramera5177e62012-03-23 11:49:32 +000059#include <cctype>
Michael J. Spencer2670c252011-01-20 06:39:06 +000060#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000061#include <system_error>
Ahmed Bougacha17926472013-08-21 07:29:02 +000062
Michael J. Spencer2670c252011-01-20 06:39:06 +000063using namespace llvm;
64using namespace object;
65
Benjamin Kramer43a772e2011-09-19 17:56:04 +000066static cl::list<std::string>
67InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
Michael J. Spencer2670c252011-01-20 06:39:06 +000068
Kevin Enderbye2297dd2015-01-07 21:02:18 +000069cl::opt<bool>
70llvm::Disassemble("disassemble",
Benjamin Kramer43a772e2011-09-19 17:56:04 +000071 cl::desc("Display assembler mnemonics for the machine instructions"));
72static cl::alias
73Disassembled("d", cl::desc("Alias for --disassemble"),
Colin LeMahieu77804be2015-07-29 15:45:39 +000074 cl::aliasopt(Disassemble));
75
76cl::opt<bool>
77llvm::DisassembleAll("disassemble-all",
78 cl::desc("Display assembler mnemonics for the machine instructions"));
79static cl::alias
80DisassembleAlld("D", cl::desc("Alias for --disassemble-all"),
Colin LeMahieuf34933e2015-07-23 20:58:49 +000081 cl::aliasopt(DisassembleAll));
Michael J. Spencer2670c252011-01-20 06:39:06 +000082
Kevin Enderby98da6132015-01-20 21:47:46 +000083cl::opt<bool>
84llvm::Relocations("r", cl::desc("Display the relocation entries in the file"));
Michael J. Spencerba4a3622011-10-08 00:18:30 +000085
Kevin Enderby98da6132015-01-20 21:47:46 +000086cl::opt<bool>
87llvm::SectionContents("s", cl::desc("Display the content of each section"));
Michael J. Spencer4e25c022011-10-17 17:13:22 +000088
Kevin Enderby98da6132015-01-20 21:47:46 +000089cl::opt<bool>
90llvm::SymbolTable("t", cl::desc("Display the symbol table"));
Michael J. Spencerbfa06782011-10-18 19:32:17 +000091
Kevin Enderbye2297dd2015-01-07 21:02:18 +000092cl::opt<bool>
93llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
Nick Kledzikd04bc352014-08-30 00:20:14 +000094
Kevin Enderbye2297dd2015-01-07 21:02:18 +000095cl::opt<bool>
96llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
Nick Kledzikac431442014-09-12 21:34:15 +000097
Kevin Enderbye2297dd2015-01-07 21:02:18 +000098cl::opt<bool>
99llvm::Bind("bind", cl::desc("Display mach-o binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000100
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000101cl::opt<bool>
102llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000103
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000104cl::opt<bool>
105llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000106
Adrian Prantl437105a2015-07-08 02:04:15 +0000107cl::opt<bool>
108llvm::RawClangAST("raw-clang-ast",
109 cl::desc("Dump the raw binary contents of the clang AST section"));
110
Nick Kledzik56ebef42014-09-16 01:41:51 +0000111static cl::opt<bool>
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000112MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000113static cl::alias
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000114MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
Benjamin Kramer87ee76c2011-07-20 19:37:35 +0000115
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000116cl::opt<std::string>
117llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
118 "see -version for available targets"));
119
120cl::opt<std::string>
Kevin Enderbyc9595622014-08-06 23:24:41 +0000121llvm::MCPU("mcpu",
122 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
123 cl::value_desc("cpu-name"),
124 cl::init(""));
125
126cl::opt<std::string>
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000127llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
Michael J. Spencer2670c252011-01-20 06:39:06 +0000128 "see -version for available targets"));
129
Kevin Enderby98da6132015-01-20 21:47:46 +0000130cl::opt<bool>
131llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
132 "headers for each section."));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000133static cl::alias
134SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
135 cl::aliasopt(SectionHeaders));
136static cl::alias
137SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
138 cl::aliasopt(SectionHeaders));
Colin LeMahieufcc32762015-07-29 19:08:10 +0000139
Colin LeMahieu77804be2015-07-29 15:45:39 +0000140cl::list<std::string>
Colin LeMahieufcc32762015-07-29 19:08:10 +0000141llvm::FilterSections("section", cl::desc("Operate on the specified sections only. "
142 "With -macho dump segment,section"));
143cl::alias
144static FilterSectionsj("j", cl::desc("Alias for --section"),
145 cl::aliasopt(llvm::FilterSections));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000146
Kevin Enderbyc9595622014-08-06 23:24:41 +0000147cl::list<std::string>
148llvm::MAttrs("mattr",
Jack Carter551efd72012-08-28 19:24:49 +0000149 cl::CommaSeparated,
150 cl::desc("Target specific attributes"),
151 cl::value_desc("a1,+a2,-a3,..."));
152
Kevin Enderbybf246f52014-09-24 23:08:22 +0000153cl::opt<bool>
154llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
155 "instructions, do not print "
156 "the instruction bytes."));
Eli Bendersky3a6808c2012-11-20 22:57:02 +0000157
Kevin Enderby98da6132015-01-20 21:47:46 +0000158cl::opt<bool>
159llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000160
161static cl::alias
162UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
163 cl::aliasopt(UnwindInfo));
164
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000165cl::opt<bool>
166llvm::PrivateHeaders("private-headers",
167 cl::desc("Display format specific file headers"));
Michael J. Spencer209565db2013-01-06 03:56:49 +0000168
Kevin Enderby0ae163f2016-01-13 00:25:36 +0000169cl::opt<bool>
170llvm::FirstPrivateHeader("private-header",
171 cl::desc("Display only the first format specific file "
172 "header"));
173
Michael J. Spencer209565db2013-01-06 03:56:49 +0000174static cl::alias
175PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
176 cl::aliasopt(PrivateHeaders));
177
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000178cl::opt<bool>
179 llvm::PrintImmHex("print-imm-hex",
180 cl::desc("Use hex format for immediate values"));
181
Sanjoy Das6f567a42015-06-22 18:03:02 +0000182cl::opt<bool> PrintFaultMaps("fault-map-section",
183 cl::desc("Display contents of faultmap section"));
184
Igor Laevsky03a670c2016-01-26 15:09:42 +0000185cl::opt<DIDumpType> llvm::DwarfDumpType(
186 "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"),
187 cl::values(clEnumValN(DIDT_Frames, "frames", ".debug_frame"),
188 clEnumValEnd));
189
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000190static StringRef ToolName;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000191
Colin LeMahieu77804be2015-07-29 15:45:39 +0000192namespace {
Colin LeMahieufcc32762015-07-29 19:08:10 +0000193typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate;
Colin LeMahieu77804be2015-07-29 15:45:39 +0000194
195class SectionFilterIterator {
196public:
197 SectionFilterIterator(FilterPredicate P,
198 llvm::object::section_iterator const &I,
199 llvm::object::section_iterator const &E)
200 : Predicate(P), Iterator(I), End(E) {
201 ScanPredicate();
202 }
Benjamin Kramerac9257b2015-09-24 14:52:52 +0000203 const llvm::object::SectionRef &operator*() const { return *Iterator; }
Colin LeMahieu77804be2015-07-29 15:45:39 +0000204 SectionFilterIterator &operator++() {
205 ++Iterator;
206 ScanPredicate();
207 return *this;
208 }
209 bool operator!=(SectionFilterIterator const &Other) const {
210 return Iterator != Other.Iterator;
211 }
212
213private:
214 void ScanPredicate() {
Colin LeMahieuda1723f2015-07-29 19:21:13 +0000215 while (Iterator != End && !Predicate(*Iterator)) {
Colin LeMahieu77804be2015-07-29 15:45:39 +0000216 ++Iterator;
217 }
218 }
219 FilterPredicate Predicate;
220 llvm::object::section_iterator Iterator;
221 llvm::object::section_iterator End;
222};
223
224class SectionFilter {
225public:
226 SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O)
227 : Predicate(P), Object(O) {}
228 SectionFilterIterator begin() {
229 return SectionFilterIterator(Predicate, Object.section_begin(),
230 Object.section_end());
231 }
232 SectionFilterIterator end() {
233 return SectionFilterIterator(Predicate, Object.section_end(),
234 Object.section_end());
235 }
236
237private:
238 FilterPredicate Predicate;
239 llvm::object::ObjectFile const &Object;
240};
241SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) {
Colin LeMahieu77804be2015-07-29 15:45:39 +0000242 return SectionFilter([](llvm::object::SectionRef const &S) {
Colin LeMahieufcc32762015-07-29 19:08:10 +0000243 if(FilterSections.empty())
Colin LeMahieuda1723f2015-07-29 19:21:13 +0000244 return true;
Colin LeMahieu77804be2015-07-29 15:45:39 +0000245 llvm::StringRef String;
246 std::error_code error = S.getName(String);
Colin LeMahieufcc32762015-07-29 19:08:10 +0000247 if (error)
Colin LeMahieuda1723f2015-07-29 19:21:13 +0000248 return false;
Colin LeMahieufcc32762015-07-29 19:08:10 +0000249 return std::find(FilterSections.begin(),
250 FilterSections.end(),
Colin LeMahieuda1723f2015-07-29 19:21:13 +0000251 String) != FilterSections.end();
Colin LeMahieu77804be2015-07-29 15:45:39 +0000252 },
253 O);
254}
255}
256
Davide Italianoccd53fe2015-08-05 07:18:31 +0000257void llvm::error(std::error_code EC) {
Mark Seaborneb03ac52014-01-25 00:32:01 +0000258 if (!EC)
Davide Italianoccd53fe2015-08-05 07:18:31 +0000259 return;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000260
Davide Italiano140af642015-12-25 18:16:45 +0000261 errs() << ToolName << ": error reading file: " << EC.message() << ".\n";
262 errs().flush();
Davide Italiano7f6c3012015-08-06 00:18:52 +0000263 exit(1);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000264}
265
Davide Italianoed9d95b2015-12-29 13:41:02 +0000266LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
267 std::error_code EC) {
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000268 assert(EC);
269 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
Davide Italianoccd53fe2015-08-05 07:18:31 +0000270 exit(1);
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000271}
272
Craig Toppere6cb63e2014-04-25 04:24:47 +0000273static const Target *getTarget(const ObjectFile *Obj = nullptr) {
Michael J. Spencer2670c252011-01-20 06:39:06 +0000274 // Figure out the target triple.
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000275 llvm::Triple TheTriple("unknown-unknown-unknown");
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000276 if (TripleName.empty()) {
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000277 if (Obj) {
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000278 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000279 // TheTriple defaults to ELF, and COFF doesn't have an environment:
280 // the best we can do here is indicate that it is mach-o.
281 if (Obj->isMachO())
Saleem Abdulrasool35476332014-03-06 20:47:11 +0000282 TheTriple.setObjectFormat(Triple::MachO);
Saleem Abdulrasool98938f12014-04-17 06:17:23 +0000283
284 if (Obj->isCOFF()) {
285 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
286 if (COFFObj->getArch() == Triple::thumb)
287 TheTriple.setTriple("thumbv7-windows");
288 }
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000289 }
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000290 } else
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000291 TheTriple.setTriple(Triple::normalize(TripleName));
Michael J. Spencer2670c252011-01-20 06:39:06 +0000292
293 // Get the target specific parser.
294 std::string Error;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000295 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
296 Error);
Davide Italianobb599e32015-12-03 22:13:40 +0000297 if (!TheTarget)
298 report_fatal_error("can't find target: " + Error);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000299
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000300 // Update the triple name and return the found target.
301 TripleName = TheTriple.getTriple();
302 return TheTarget;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000303}
304
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000305bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
Rafael Espindola704cd842015-07-06 15:47:43 +0000306 return a.getOffset() < b.getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +0000307}
308
Colin LeMahieufb76b002015-05-28 19:07:14 +0000309namespace {
310class PrettyPrinter {
311public:
Colin LeMahieu0b5890d2015-05-28 20:59:08 +0000312 virtual ~PrettyPrinter(){}
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000313 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
Colin LeMahieufb76b002015-05-28 19:07:14 +0000314 ArrayRef<uint8_t> Bytes, uint64_t Address,
315 raw_ostream &OS, StringRef Annot,
316 MCSubtargetInfo const &STI) {
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000317 OS << format("%8" PRIx64 ":", Address);
Colin LeMahieufb76b002015-05-28 19:07:14 +0000318 if (!NoShowRawInsn) {
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000319 OS << "\t";
320 dumpBytes(Bytes, OS);
Colin LeMahieufb76b002015-05-28 19:07:14 +0000321 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000322 if (MI)
323 IP.printInst(MI, OS, "", STI);
324 else
325 OS << " <unknown>";
Colin LeMahieufb76b002015-05-28 19:07:14 +0000326 }
327};
328PrettyPrinter PrettyPrinterInst;
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000329class HexagonPrettyPrinter : public PrettyPrinter {
330public:
331 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
332 raw_ostream &OS) {
333 uint32_t opcode =
334 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
335 OS << format("%8" PRIx64 ":", Address);
336 if (!NoShowRawInsn) {
337 OS << "\t";
338 dumpBytes(Bytes.slice(0, 4), OS);
339 OS << format("%08" PRIx32, opcode);
340 }
341 }
342 void printInst(MCInstPrinter &IP, const MCInst *MI,
343 ArrayRef<uint8_t> Bytes, uint64_t Address,
344 raw_ostream &OS, StringRef Annot,
345 MCSubtargetInfo const &STI) override {
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000346 if (!MI) {
347 printLead(Bytes, Address, OS);
348 OS << " <unknown>";
349 return;
350 }
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000351 std::string Buffer;
352 {
353 raw_string_ostream TempStream(Buffer);
354 IP.printInst(MI, TempStream, "", STI);
355 }
356 StringRef Contents(Buffer);
357 // Split off bundle attributes
358 auto PacketBundle = Contents.rsplit('\n');
359 // Split off first instruction from the rest
360 auto HeadTail = PacketBundle.first.split('\n');
361 auto Preamble = " { ";
362 auto Separator = "";
363 while(!HeadTail.first.empty()) {
364 OS << Separator;
365 Separator = "\n";
366 printLead(Bytes, Address, OS);
367 OS << Preamble;
368 Preamble = " ";
369 StringRef Inst;
370 auto Duplex = HeadTail.first.split('\v');
371 if(!Duplex.second.empty()){
372 OS << Duplex.first;
373 OS << "; ";
374 Inst = Duplex.second;
375 }
376 else
377 Inst = HeadTail.first;
378 OS << Inst;
379 Bytes = Bytes.slice(4);
380 Address += 4;
381 HeadTail = HeadTail.second.split('\n');
382 }
383 OS << " } " << PacketBundle.second;
384 }
385};
386HexagonPrettyPrinter HexagonPrettyPrinterInst;
Colin LeMahieu35436a22015-05-29 14:48:25 +0000387PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000388 switch(Triple.getArch()) {
389 default:
390 return PrettyPrinterInst;
391 case Triple::hexagon:
392 return HexagonPrettyPrinterInst;
393 }
Colin LeMahieufb76b002015-05-28 19:07:14 +0000394}
395}
396
Rafael Espindola37070a52015-06-03 04:48:06 +0000397template <class ELFT>
Rafael Espindola37070a52015-06-03 04:48:06 +0000398static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000399 const RelocationRef &RelRef,
Rafael Espindola37070a52015-06-03 04:48:06 +0000400 SmallVectorImpl<char> &Result) {
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000401 DataRefImpl Rel = RelRef.getRawDataRefImpl();
402
Rafael Espindola37070a52015-06-03 04:48:06 +0000403 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
404 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000405 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
406
Rafael Espindola37070a52015-06-03 04:48:06 +0000407 const ELFFile<ELFT> &EF = *Obj->getELFFile();
408
Rafael Espindola6def3042015-07-01 12:56:27 +0000409 ErrorOr<const Elf_Shdr *> SecOrErr = EF.getSection(Rel.d.a);
410 if (std::error_code EC = SecOrErr.getError())
411 return EC;
412 const Elf_Shdr *Sec = *SecOrErr;
413 ErrorOr<const Elf_Shdr *> SymTabOrErr = EF.getSection(Sec->sh_link);
414 if (std::error_code EC = SymTabOrErr.getError())
415 return EC;
416 const Elf_Shdr *SymTab = *SymTabOrErr;
Rafael Espindola719dc7c2015-06-29 12:38:31 +0000417 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
418 SymTab->sh_type == ELF::SHT_DYNSYM);
Rafael Espindola6def3042015-07-01 12:56:27 +0000419 ErrorOr<const Elf_Shdr *> StrTabSec = EF.getSection(SymTab->sh_link);
420 if (std::error_code EC = StrTabSec.getError())
421 return EC;
422 ErrorOr<StringRef> StrTabOrErr = EF.getStringTable(*StrTabSec);
Rafael Espindola6a1bfb22015-06-29 14:39:25 +0000423 if (std::error_code EC = StrTabOrErr.getError())
424 return EC;
425 StringRef StrTab = *StrTabOrErr;
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000426 uint8_t type = RelRef.getType();
Rafael Espindola37070a52015-06-03 04:48:06 +0000427 StringRef res;
428 int64_t addend = 0;
Rafael Espindola6def3042015-07-01 12:56:27 +0000429 switch (Sec->sh_type) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000430 default:
431 return object_error::parse_failed;
432 case ELF::SHT_REL: {
Rafael Espindola37070a52015-06-03 04:48:06 +0000433 // TODO: Read implicit addend from section data.
434 break;
435 }
436 case ELF::SHT_RELA: {
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000437 const Elf_Rela *ERela = Obj->getRela(Rel);
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000438 addend = ERela->r_addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000439 break;
440 }
441 }
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000442 symbol_iterator SI = RelRef.getSymbol();
443 const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
Rafael Espindola75d5b542015-06-03 05:14:22 +0000444 StringRef Target;
Rafael Espindola75d5b542015-06-03 05:14:22 +0000445 if (symb->getType() == ELF::STT_SECTION) {
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000446 ErrorOr<section_iterator> SymSI = SI->getSection();
447 if (std::error_code EC = SymSI.getError())
448 return EC;
449 const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
450 ErrorOr<StringRef> SecName = EF.getSectionName(SymSec);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000451 if (std::error_code EC = SecName.getError())
452 return EC;
453 Target = *SecName;
454 } else {
Rafael Espindola44c28712015-06-29 21:24:55 +0000455 ErrorOr<StringRef> SymName = symb->getName(StrTab);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000456 if (!SymName)
457 return SymName.getError();
458 Target = *SymName;
459 }
Rafael Espindola37070a52015-06-03 04:48:06 +0000460 switch (EF.getHeader()->e_machine) {
461 case ELF::EM_X86_64:
462 switch (type) {
463 case ELF::R_X86_64_PC8:
464 case ELF::R_X86_64_PC16:
465 case ELF::R_X86_64_PC32: {
466 std::string fmtbuf;
467 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000468 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
Rafael Espindola37070a52015-06-03 04:48:06 +0000469 fmt.flush();
470 Result.append(fmtbuf.begin(), fmtbuf.end());
471 } break;
472 case ELF::R_X86_64_8:
473 case ELF::R_X86_64_16:
474 case ELF::R_X86_64_32:
475 case ELF::R_X86_64_32S:
476 case ELF::R_X86_64_64: {
477 std::string fmtbuf;
478 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000479 fmt << Target << (addend < 0 ? "" : "+") << addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000480 fmt.flush();
481 Result.append(fmtbuf.begin(), fmtbuf.end());
482 } break;
483 default:
484 res = "Unknown";
485 }
486 break;
Jacques Pienaarea9f25a2016-03-01 21:21:42 +0000487 case ELF::EM_LANAI:
Rafael Espindola37070a52015-06-03 04:48:06 +0000488 case ELF::EM_AARCH64: {
489 std::string fmtbuf;
490 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000491 fmt << Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000492 if (addend != 0)
493 fmt << (addend < 0 ? "" : "+") << addend;
494 fmt.flush();
495 Result.append(fmtbuf.begin(), fmtbuf.end());
496 break;
497 }
498 case ELF::EM_386:
Michael Kupersteina3b79dd2015-11-04 11:21:50 +0000499 case ELF::EM_IAMCU:
Rafael Espindola37070a52015-06-03 04:48:06 +0000500 case ELF::EM_ARM:
501 case ELF::EM_HEXAGON:
502 case ELF::EM_MIPS:
Rafael Espindola75d5b542015-06-03 05:14:22 +0000503 res = Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000504 break;
Dan Gohman46350172016-01-12 20:56:01 +0000505 case ELF::EM_WEBASSEMBLY:
506 switch (type) {
507 case ELF::R_WEBASSEMBLY_DATA: {
508 std::string fmtbuf;
509 raw_string_ostream fmt(fmtbuf);
510 fmt << Target << (addend < 0 ? "" : "+") << addend;
511 fmt.flush();
512 Result.append(fmtbuf.begin(), fmtbuf.end());
513 break;
514 }
515 case ELF::R_WEBASSEMBLY_FUNCTION:
516 res = Target;
517 break;
518 default:
519 res = "Unknown";
520 }
521 break;
Rafael Espindola37070a52015-06-03 04:48:06 +0000522 default:
523 res = "Unknown";
524 }
525 if (Result.empty())
526 Result.append(res.begin(), res.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000527 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000528}
529
530static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000531 const RelocationRef &Rel,
Rafael Espindola37070a52015-06-03 04:48:06 +0000532 SmallVectorImpl<char> &Result) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000533 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
534 return getRelocationValueString(ELF32LE, Rel, Result);
535 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
536 return getRelocationValueString(ELF64LE, Rel, Result);
537 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
538 return getRelocationValueString(ELF32BE, Rel, Result);
539 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
540 return getRelocationValueString(ELF64BE, Rel, Result);
541}
542
543static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
544 const RelocationRef &Rel,
545 SmallVectorImpl<char> &Result) {
546 symbol_iterator SymI = Rel.getSymbol();
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000547 ErrorOr<StringRef> SymNameOrErr = SymI->getName();
548 if (std::error_code EC = SymNameOrErr.getError())
Rafael Espindola37070a52015-06-03 04:48:06 +0000549 return EC;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000550 StringRef SymName = *SymNameOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000551 Result.append(SymName.begin(), SymName.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000552 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000553}
554
555static void printRelocationTargetName(const MachOObjectFile *O,
556 const MachO::any_relocation_info &RE,
557 raw_string_ostream &fmt) {
558 bool IsScattered = O->isRelocationScattered(RE);
559
560 // Target of a scattered relocation is an address. In the interest of
561 // generating pretty output, scan through the symbol table looking for a
562 // symbol that aligns with that address. If we find one, print it.
563 // Otherwise, we just print the hex address of the target.
564 if (IsScattered) {
565 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
566
567 for (const SymbolRef &Symbol : O->symbols()) {
568 std::error_code ec;
Rafael Espindolaed067c42015-07-03 18:19:00 +0000569 ErrorOr<uint64_t> Addr = Symbol.getAddress();
570 if ((ec = Addr.getError()))
Rafael Espindola37070a52015-06-03 04:48:06 +0000571 report_fatal_error(ec.message());
Rafael Espindolaed067c42015-07-03 18:19:00 +0000572 if (*Addr != Val)
Rafael Espindola37070a52015-06-03 04:48:06 +0000573 continue;
Rafael Espindolaed067c42015-07-03 18:19:00 +0000574 ErrorOr<StringRef> Name = Symbol.getName();
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000575 if (std::error_code EC = Name.getError())
576 report_fatal_error(EC.message());
577 fmt << *Name;
Rafael Espindola37070a52015-06-03 04:48:06 +0000578 return;
579 }
580
581 // If we couldn't find a symbol that this relocation refers to, try
582 // to find a section beginning instead.
Colin LeMahieu77804be2015-07-29 15:45:39 +0000583 for (const SectionRef &Section : ToolSectionFilter(*O)) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000584 std::error_code ec;
585
586 StringRef Name;
587 uint64_t Addr = Section.getAddress();
588 if (Addr != Val)
589 continue;
590 if ((ec = Section.getName(Name)))
591 report_fatal_error(ec.message());
592 fmt << Name;
593 return;
594 }
595
596 fmt << format("0x%x", Val);
597 return;
598 }
599
600 StringRef S;
601 bool isExtern = O->getPlainRelocationExternal(RE);
602 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
603
604 if (isExtern) {
605 symbol_iterator SI = O->symbol_begin();
606 advance(SI, Val);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000607 ErrorOr<StringRef> SOrErr = SI->getName();
Davide Italianoccd53fe2015-08-05 07:18:31 +0000608 error(SOrErr.getError());
609 S = *SOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000610 } else {
611 section_iterator SI = O->section_begin();
612 // Adjust for the fact that sections are 1-indexed.
613 advance(SI, Val - 1);
614 SI->getName(S);
615 }
616
617 fmt << S;
618}
619
620static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
621 const RelocationRef &RelRef,
622 SmallVectorImpl<char> &Result) {
623 DataRefImpl Rel = RelRef.getRawDataRefImpl();
624 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
625
626 unsigned Arch = Obj->getArch();
627
628 std::string fmtbuf;
629 raw_string_ostream fmt(fmtbuf);
630 unsigned Type = Obj->getAnyRelocationType(RE);
631 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
632
633 // Determine any addends that should be displayed with the relocation.
634 // These require decoding the relocation type, which is triple-specific.
635
636 // X86_64 has entirely custom relocation types.
637 if (Arch == Triple::x86_64) {
638 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
639
640 switch (Type) {
641 case MachO::X86_64_RELOC_GOT_LOAD:
642 case MachO::X86_64_RELOC_GOT: {
643 printRelocationTargetName(Obj, RE, fmt);
644 fmt << "@GOT";
645 if (isPCRel)
646 fmt << "PCREL";
647 break;
648 }
649 case MachO::X86_64_RELOC_SUBTRACTOR: {
650 DataRefImpl RelNext = Rel;
651 Obj->moveRelocationNext(RelNext);
652 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
653
654 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
655 // X86_64_RELOC_UNSIGNED.
656 // NOTE: Scattered relocations don't exist on x86_64.
657 unsigned RType = Obj->getAnyRelocationType(RENext);
658 if (RType != MachO::X86_64_RELOC_UNSIGNED)
659 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
660 "X86_64_RELOC_SUBTRACTOR.");
661
662 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
663 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
664 printRelocationTargetName(Obj, RENext, fmt);
665 fmt << "-";
666 printRelocationTargetName(Obj, RE, fmt);
667 break;
668 }
669 case MachO::X86_64_RELOC_TLV:
670 printRelocationTargetName(Obj, RE, fmt);
671 fmt << "@TLV";
672 if (isPCRel)
673 fmt << "P";
674 break;
675 case MachO::X86_64_RELOC_SIGNED_1:
676 printRelocationTargetName(Obj, RE, fmt);
677 fmt << "-1";
678 break;
679 case MachO::X86_64_RELOC_SIGNED_2:
680 printRelocationTargetName(Obj, RE, fmt);
681 fmt << "-2";
682 break;
683 case MachO::X86_64_RELOC_SIGNED_4:
684 printRelocationTargetName(Obj, RE, fmt);
685 fmt << "-4";
686 break;
687 default:
688 printRelocationTargetName(Obj, RE, fmt);
689 break;
690 }
691 // X86 and ARM share some relocation types in common.
692 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
693 Arch == Triple::ppc) {
694 // Generic relocation types...
695 switch (Type) {
696 case MachO::GENERIC_RELOC_PAIR: // prints no info
Rui Ueyama7d099192015-06-09 15:20:42 +0000697 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000698 case MachO::GENERIC_RELOC_SECTDIFF: {
699 DataRefImpl RelNext = Rel;
700 Obj->moveRelocationNext(RelNext);
701 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
702
703 // X86 sect diff's must be followed by a relocation of type
704 // GENERIC_RELOC_PAIR.
705 unsigned RType = Obj->getAnyRelocationType(RENext);
706
707 if (RType != MachO::GENERIC_RELOC_PAIR)
708 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
709 "GENERIC_RELOC_SECTDIFF.");
710
711 printRelocationTargetName(Obj, RE, fmt);
712 fmt << "-";
713 printRelocationTargetName(Obj, RENext, fmt);
714 break;
715 }
716 }
717
718 if (Arch == Triple::x86 || Arch == Triple::ppc) {
719 switch (Type) {
720 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
721 DataRefImpl RelNext = Rel;
722 Obj->moveRelocationNext(RelNext);
723 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
724
725 // X86 sect diff's must be followed by a relocation of type
726 // GENERIC_RELOC_PAIR.
727 unsigned RType = Obj->getAnyRelocationType(RENext);
728 if (RType != MachO::GENERIC_RELOC_PAIR)
729 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
730 "GENERIC_RELOC_LOCAL_SECTDIFF.");
731
732 printRelocationTargetName(Obj, RE, fmt);
733 fmt << "-";
734 printRelocationTargetName(Obj, RENext, fmt);
735 break;
736 }
737 case MachO::GENERIC_RELOC_TLV: {
738 printRelocationTargetName(Obj, RE, fmt);
739 fmt << "@TLV";
740 if (IsPCRel)
741 fmt << "P";
742 break;
743 }
744 default:
745 printRelocationTargetName(Obj, RE, fmt);
746 }
747 } else { // ARM-specific relocations
748 switch (Type) {
749 case MachO::ARM_RELOC_HALF:
750 case MachO::ARM_RELOC_HALF_SECTDIFF: {
751 // Half relocations steal a bit from the length field to encode
752 // whether this is an upper16 or a lower16 relocation.
753 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
754
755 if (isUpper)
756 fmt << ":upper16:(";
757 else
758 fmt << ":lower16:(";
759 printRelocationTargetName(Obj, RE, fmt);
760
761 DataRefImpl RelNext = Rel;
762 Obj->moveRelocationNext(RelNext);
763 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
764
765 // ARM half relocs must be followed by a relocation of type
766 // ARM_RELOC_PAIR.
767 unsigned RType = Obj->getAnyRelocationType(RENext);
768 if (RType != MachO::ARM_RELOC_PAIR)
769 report_fatal_error("Expected ARM_RELOC_PAIR after "
770 "ARM_RELOC_HALF");
771
772 // NOTE: The half of the target virtual address is stashed in the
773 // address field of the secondary relocation, but we can't reverse
774 // engineer the constant offset from it without decoding the movw/movt
775 // instruction to find the other half in its immediate field.
776
777 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
778 // symbol/section pointer of the follow-on relocation.
779 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
780 fmt << "-";
781 printRelocationTargetName(Obj, RENext, fmt);
782 }
783
784 fmt << ")";
785 break;
786 }
787 default: { printRelocationTargetName(Obj, RE, fmt); }
788 }
789 }
790 } else
791 printRelocationTargetName(Obj, RE, fmt);
792
793 fmt.flush();
794 Result.append(fmtbuf.begin(), fmtbuf.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000795 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000796}
797
798static std::error_code getRelocationValueString(const RelocationRef &Rel,
799 SmallVectorImpl<char> &Result) {
Rafael Espindola854038e2015-06-26 14:51:16 +0000800 const ObjectFile *Obj = Rel.getObject();
Rafael Espindola37070a52015-06-03 04:48:06 +0000801 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
802 return getRelocationValueString(ELF, Rel, Result);
803 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
804 return getRelocationValueString(COFF, Rel, Result);
805 auto *MachO = cast<MachOObjectFile>(Obj);
806 return getRelocationValueString(MachO, Rel, Result);
807}
808
Rafael Espindola0ad71d92015-06-30 03:41:26 +0000809/// @brief Indicates whether this relocation should hidden when listing
810/// relocations, usually because it is the trailing part of a multipart
811/// relocation that will be printed as part of the leading relocation.
812static bool getHidden(RelocationRef RelRef) {
813 const ObjectFile *Obj = RelRef.getObject();
814 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
815 if (!MachO)
816 return false;
817
818 unsigned Arch = MachO->getArch();
819 DataRefImpl Rel = RelRef.getRawDataRefImpl();
820 uint64_t Type = MachO->getRelocationType(Rel);
821
822 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
823 // is always hidden.
824 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
825 if (Type == MachO::GENERIC_RELOC_PAIR)
826 return true;
827 } else if (Arch == Triple::x86_64) {
828 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
829 // an X86_64_RELOC_SUBTRACTOR.
830 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
831 DataRefImpl RelPrev = Rel;
832 RelPrev.d.a--;
833 uint64_t PrevType = MachO->getRelocationType(RelPrev);
834 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
835 return true;
836 }
837 }
838
839 return false;
840}
841
Michael J. Spencer51862b32011-10-13 22:17:18 +0000842static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Jim Grosbachaf9aec02012-08-07 17:53:14 +0000843 const Target *TheTarget = getTarget(Obj);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000844
Jack Carter551efd72012-08-28 19:24:49 +0000845 // Package up features to be passed to target/subtarget
846 std::string FeaturesStr;
847 if (MAttrs.size()) {
848 SubtargetFeatures Features;
849 for (unsigned i = 0; i != MAttrs.size(); ++i)
850 Features.AddFeature(MAttrs[i]);
851 FeaturesStr = Features.getString();
852 }
853
Ahmed Charles56440fd2014-03-06 05:51:42 +0000854 std::unique_ptr<const MCRegisterInfo> MRI(
855 TheTarget->createMCRegInfo(TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +0000856 if (!MRI)
857 report_fatal_error("error: no register info for target " + TripleName);
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000858
859 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000860 std::unique_ptr<const MCAsmInfo> AsmInfo(
861 TheTarget->createMCAsmInfo(*MRI, TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +0000862 if (!AsmInfo)
863 report_fatal_error("error: no assembly info for target " + TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +0000864 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +0000865 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Davide Italiano711e4952015-12-17 01:59:50 +0000866 if (!STI)
867 report_fatal_error("error: no subtarget info for target " + TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +0000868 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
Davide Italiano711e4952015-12-17 01:59:50 +0000869 if (!MII)
870 report_fatal_error("error: no instruction info for target " + TripleName);
Lang Hamesa1bc0f52014-04-15 04:40:56 +0000871 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
872 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
873
874 std::unique_ptr<MCDisassembler> DisAsm(
875 TheTarget->createMCDisassembler(*STI, Ctx));
Davide Italiano711e4952015-12-17 01:59:50 +0000876 if (!DisAsm)
877 report_fatal_error("error: no disassembler for target " + TripleName);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000878
Ahmed Charles56440fd2014-03-06 05:51:42 +0000879 std::unique_ptr<const MCInstrAnalysis> MIA(
880 TheTarget->createMCInstrAnalysis(MII.get()));
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000881
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000882 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Daniel Sanders50f17232015-09-15 16:17:27 +0000883 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
884 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
Davide Italiano711e4952015-12-17 01:59:50 +0000885 if (!IP)
886 report_fatal_error("error: no instruction printer for target " +
887 TripleName);
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000888 IP->setPrintImmHex(PrintImmHex);
Colin LeMahieu35436a22015-05-29 14:48:25 +0000889 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000890
Greg Fitzgerald18432272014-03-20 22:55:15 +0000891 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
892 "\t\t\t%08" PRIx64 ": ";
893
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000894 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
895 // in RelocSecs contain the relocations for section S.
Rafael Espindola4453e42942014-06-13 03:07:50 +0000896 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000897 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
Colin LeMahieu77804be2015-07-29 15:45:39 +0000898 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +0000899 section_iterator Sec2 = Section.getRelocatedSection();
Rafael Espindolab5155a52014-02-10 20:24:04 +0000900 if (Sec2 != Obj->section_end())
Alexey Samsonov48803e52014-03-13 14:37:36 +0000901 SectionRelocMap[*Sec2].push_back(Section);
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000902 }
903
David Majnemer81afca62015-07-07 22:06:59 +0000904 // Create a mapping from virtual address to symbol name. This is used to
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000905 // pretty print the symbols while disassembling.
906 typedef std::vector<std::pair<uint64_t, StringRef>> SectionSymbolsTy;
907 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
908 for (const SymbolRef &Symbol : Obj->symbols()) {
909 ErrorOr<uint64_t> AddressOrErr = Symbol.getAddress();
910 error(AddressOrErr.getError());
911 uint64_t Address = *AddressOrErr;
David Majnemer2603a8fa2015-07-09 18:11:40 +0000912
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000913 ErrorOr<StringRef> Name = Symbol.getName();
914 error(Name.getError());
915 if (Name->empty())
916 continue;
David Majnemer81afca62015-07-07 22:06:59 +0000917
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000918 ErrorOr<section_iterator> SectionOrErr = Symbol.getSection();
919 error(SectionOrErr.getError());
920 section_iterator SecI = *SectionOrErr;
921 if (SecI == Obj->section_end())
922 continue;
David Majnemer81afca62015-07-07 22:06:59 +0000923
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000924 AllSymbols[*SecI].emplace_back(Address, *Name);
David Majnemer81afca62015-07-07 22:06:59 +0000925 }
926
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000927 // Create a mapping from virtual address to section.
928 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
929 for (SectionRef Sec : Obj->sections())
930 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
931 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
932
933 // Linked executables (.exe and .dll files) typically don't include a real
934 // symbol table but they might contain an export table.
935 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
936 for (const auto &ExportEntry : COFFObj->export_directories()) {
937 StringRef Name;
938 error(ExportEntry.getSymbolName(Name));
939 if (Name.empty())
940 continue;
941 uint32_t RVA;
942 error(ExportEntry.getExportRVA(RVA));
943
944 uint64_t VA = COFFObj->getImageBase() + RVA;
945 auto Sec = std::upper_bound(
946 SectionAddresses.begin(), SectionAddresses.end(), VA,
947 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
948 return LHS < RHS.first;
949 });
950 if (Sec != SectionAddresses.begin())
951 --Sec;
952 else
953 Sec = SectionAddresses.end();
954
955 if (Sec != SectionAddresses.end())
956 AllSymbols[Sec->second].emplace_back(VA, Name);
957 }
958 }
959
960 // Sort all the symbols, this allows us to use a simple binary search to find
961 // a symbol near an address.
962 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
963 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
964
Colin LeMahieu77804be2015-07-29 15:45:39 +0000965 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Colin LeMahieuf34933e2015-07-23 20:58:49 +0000966 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000967 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000968
Rafael Espindola80291272014-10-08 15:28:58 +0000969 uint64_t SectionAddr = Section.getAddress();
970 uint64_t SectSize = Section.getSize();
David Majnemer185b5b12014-11-11 09:58:25 +0000971 if (!SectSize)
972 continue;
Simon Atanasyan2b614e12014-02-24 22:12:11 +0000973
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000974 // Get the list of all the symbols in this section.
975 SectionSymbolsTy &Symbols = AllSymbols[Section];
Davide Italianof0706882015-10-01 21:57:09 +0000976 std::vector<uint64_t> DataMappingSymsAddr;
977 std::vector<uint64_t> TextMappingSymsAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000978 if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
979 for (const auto &Symb : Symbols) {
980 uint64_t Address = Symb.first;
981 StringRef Name = Symb.second;
982 if (Name.startswith("$d"))
David Majnemer153722d2015-11-18 04:35:32 +0000983 DataMappingSymsAddr.push_back(Address - SectionAddr);
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000984 if (Name.startswith("$x"))
David Majnemer153722d2015-11-18 04:35:32 +0000985 TextMappingSymsAddr.push_back(Address - SectionAddr);
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000986 }
987 }
988
Davide Italianof0706882015-10-01 21:57:09 +0000989 std::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end());
990 std::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end());
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000991
Michael J. Spencer51862b32011-10-13 22:17:18 +0000992 // Make a list of all the relocations for this section.
993 std::vector<RelocationRef> Rels;
994 if (InlineRelocs) {
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000995 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
996 for (const RelocationRef &Reloc : RelocSec.relocations()) {
997 Rels.push_back(Reloc);
998 }
Michael J. Spencer51862b32011-10-13 22:17:18 +0000999 }
1000 }
1001
1002 // Sort relocations by address.
1003 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
1004
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001005 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +00001006 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001007 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +00001008 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001009 }
Michael J. Spencer1d6167f2011-06-25 17:55:23 +00001010 StringRef name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001011 error(Section.getName(name));
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001012 outs() << "Disassembly of section ";
1013 if (!SegmentName.empty())
1014 outs() << SegmentName << ",";
1015 outs() << name << ':';
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001016
Rafael Espindola7884c952015-06-04 15:01:05 +00001017 // If the section has no symbol at the start, just insert a dummy one.
1018 if (Symbols.empty() || Symbols[0].first != 0)
David Majnemer153722d2015-11-18 04:35:32 +00001019 Symbols.insert(Symbols.begin(), std::make_pair(SectionAddr, name));
Alp Tokere69170a2014-06-26 22:52:05 +00001020
1021 SmallString<40> Comments;
1022 raw_svector_ostream CommentStream(Comments);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001023
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001024 StringRef BytesStr;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001025 error(Section.getContents(BytesStr));
Aaron Ballman106fd7b2014-11-12 14:01:17 +00001026 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1027 BytesStr.size());
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001028
Michael J. Spencer2670c252011-01-20 06:39:06 +00001029 uint64_t Size;
1030 uint64_t Index;
1031
Michael J. Spencer51862b32011-10-13 22:17:18 +00001032 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
1033 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001034 // Disassemble symbol by symbol.
1035 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
Rafael Espindolae45c7402014-08-17 16:31:39 +00001036
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001037 uint64_t Start = Symbols[si].first - SectionAddr;
1038 // The end is either the section end or the beginning of the next
1039 // symbol.
1040 uint64_t End =
1041 (si == se - 1) ? SectSize : Symbols[si + 1].first - SectionAddr;
1042 // Don't try to disassemble beyond the end of section contents.
1043 if (End > SectSize)
1044 End = SectSize;
Rafael Espindolae45c7402014-08-17 16:31:39 +00001045 // If this symbol has the same address as the next symbol, then skip it.
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001046 if (Start >= End)
Michael J. Spenceree84f642011-10-13 20:37:08 +00001047 continue;
1048
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001049 outs() << '\n' << Symbols[si].second << ":\n";
Michael J. Spencer2670c252011-01-20 06:39:06 +00001050
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001051#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +00001052 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001053#else
Mark Seaborneb03ac52014-01-25 00:32:01 +00001054 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001055#endif
1056
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001057 for (Index = Start; Index < End; Index += Size) {
1058 MCInst Inst;
Owen Andersona0c3b972011-09-15 23:38:46 +00001059
Davide Italianof0706882015-10-01 21:57:09 +00001060 // AArch64 ELF binaries can interleave data and text in the
1061 // same section. We rely on the markers introduced to
1062 // understand what we need to dump.
1063 if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
1064 uint64_t Stride = 0;
1065
1066 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1067 DataMappingSymsAddr.end(), Index);
1068 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1069 // Switch to data.
1070 while (Index < End) {
1071 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1072 outs() << "\t";
1073 if (Index + 4 <= End) {
1074 Stride = 4;
1075 dumpBytes(Bytes.slice(Index, 4), outs());
1076 outs() << "\t.word";
1077 } else if (Index + 2 <= End) {
1078 Stride = 2;
1079 dumpBytes(Bytes.slice(Index, 2), outs());
1080 outs() << "\t.short";
1081 } else {
1082 Stride = 1;
1083 dumpBytes(Bytes.slice(Index, 1), outs());
1084 outs() << "\t.byte";
1085 }
1086 Index += Stride;
1087 outs() << "\n";
1088 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1089 TextMappingSymsAddr.end(), Index);
1090 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1091 break;
1092 }
1093 }
1094 }
1095
1096 if (Index >= End)
1097 break;
1098
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001099 bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1100 SectionAddr + Index, DebugOut,
1101 CommentStream);
1102 if (Size == 0)
1103 Size = 1;
1104 PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
1105 Bytes.slice(Index, Size),
1106 SectionAddr + Index, outs(), "", *STI);
1107 outs() << CommentStream.str();
1108 Comments.clear();
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001109
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001110 // Try to resolve the target of a call, tail call, etc. to a specific
1111 // symbol.
1112 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1113 MIA->isConditionalBranch(Inst))) {
1114 uint64_t Target;
1115 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1116 // In a relocatable object, the target's section must reside in
1117 // the same section as the call instruction or it is accessed
1118 // through a relocation.
1119 //
1120 // In a non-relocatable object, the target may be in any section.
1121 //
1122 // N.B. We don't walk the relocations in the relocatable case yet.
1123 auto *TargetSectionSymbols = &Symbols;
1124 if (!Obj->isRelocatableObject()) {
1125 auto SectionAddress = std::upper_bound(
1126 SectionAddresses.begin(), SectionAddresses.end(), Target,
1127 [](uint64_t LHS,
1128 const std::pair<uint64_t, SectionRef> &RHS) {
1129 return LHS < RHS.first;
1130 });
1131 if (SectionAddress != SectionAddresses.begin()) {
1132 --SectionAddress;
1133 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1134 } else {
1135 TargetSectionSymbols = nullptr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001136 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001137 }
David Majnemer2603a8fa2015-07-09 18:11:40 +00001138
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001139 // Find the first symbol in the section whose offset is less than
1140 // or equal to the target.
1141 if (TargetSectionSymbols) {
1142 auto TargetSym = std::upper_bound(
1143 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1144 Target, [](uint64_t LHS,
1145 const std::pair<uint64_t, StringRef> &RHS) {
1146 return LHS < RHS.first;
1147 });
1148 if (TargetSym != TargetSectionSymbols->begin()) {
1149 --TargetSym;
1150 uint64_t TargetAddress = std::get<0>(*TargetSym);
1151 StringRef TargetName = std::get<1>(*TargetSym);
1152 outs() << " <" << TargetName;
1153 uint64_t Disp = Target - TargetAddress;
1154 if (Disp)
1155 outs() << "+0x" << utohexstr(Disp);
1156 outs() << '>';
David Majnemer81afca62015-07-07 22:06:59 +00001157 }
1158 }
1159 }
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001160 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001161 outs() << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001162
1163 // Print relocation for instruction.
1164 while (rel_cur != rel_end) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001165 bool hidden = getHidden(*rel_cur);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001166 uint64_t addr = rel_cur->getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +00001167 SmallString<16> name;
1168 SmallString<32> val;
Owen Andersonfa3e5202011-10-25 20:35:53 +00001169
1170 // If this relocation is hidden, skip it.
Owen Andersonfa3e5202011-10-25 20:35:53 +00001171 if (hidden) goto skip_print_rel;
1172
Michael J. Spencer51862b32011-10-13 22:17:18 +00001173 // Stop when rel_cur's address is past the current instruction.
Owen Andersonf20e3e52011-10-25 20:15:39 +00001174 if (addr >= Index + Size) break;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001175 rel_cur->getTypeName(name);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001176 error(getRelocationValueString(*rel_cur, val));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001177 outs() << format(Fmt.data(), SectionAddr + addr) << name
Benjamin Kramer82803112012-03-10 02:04:38 +00001178 << "\t" << val << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001179
1180 skip_print_rel:
1181 ++rel_cur;
1182 }
Benjamin Kramer87ee76c2011-07-20 19:37:35 +00001183 }
Michael J. Spencer2670c252011-01-20 06:39:06 +00001184 }
1185 }
1186}
1187
Kevin Enderby98da6132015-01-20 21:47:46 +00001188void llvm::PrintRelocations(const ObjectFile *Obj) {
Greg Fitzgerald18432272014-03-20 22:55:15 +00001189 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1190 "%08" PRIx64;
Rafael Espindola9219fe72016-03-21 20:59:15 +00001191 // Regular objdump doesn't print relocations in non-relocatable object
1192 // files.
1193 if (!Obj->isRelocatableObject())
1194 return;
Rafael Espindolac66d7612014-08-17 19:09:37 +00001195
Colin LeMahieu77804be2015-07-29 15:45:39 +00001196 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001197 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001198 continue;
1199 StringRef secname;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001200 error(Section.getName(secname));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001201 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001202 for (const RelocationRef &Reloc : Section.relocations()) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001203 bool hidden = getHidden(Reloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001204 uint64_t address = Reloc.getOffset();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001205 SmallString<32> relocname;
1206 SmallString<32> valuestr;
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001207 if (hidden)
1208 continue;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001209 Reloc.getTypeName(relocname);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001210 error(getRelocationValueString(Reloc, valuestr));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001211 outs() << format(Fmt.data(), address) << " " << relocname << " "
1212 << valuestr << "\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001213 }
1214 outs() << "\n";
1215 }
1216}
1217
Kevin Enderby98da6132015-01-20 21:47:46 +00001218void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001219 outs() << "Sections:\n"
1220 "Idx Name Size Address Type\n";
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001221 unsigned i = 0;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001222 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001223 StringRef Name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001224 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001225 uint64_t Address = Section.getAddress();
1226 uint64_t Size = Section.getSize();
1227 bool Text = Section.isText();
1228 bool Data = Section.isData();
1229 bool BSS = Section.isBSS();
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001230 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +00001231 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
Alexey Samsonov48803e52014-03-13 14:37:36 +00001232 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1233 Name.str().c_str(), Size, Address, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001234 ++i;
1235 }
1236}
1237
Kevin Enderby98da6132015-01-20 21:47:46 +00001238void llvm::PrintSectionContents(const ObjectFile *Obj) {
Rafael Espindola4453e42942014-06-13 03:07:50 +00001239 std::error_code EC;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001240 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001241 StringRef Name;
1242 StringRef Contents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001243 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001244 uint64_t BaseAddr = Section.getAddress();
David Majnemer185b5b12014-11-11 09:58:25 +00001245 uint64_t Size = Section.getSize();
1246 if (!Size)
1247 continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001248
1249 outs() << "Contents of section " << Name << ":\n";
David Majnemer185b5b12014-11-11 09:58:25 +00001250 if (Section.isBSS()) {
Alexey Samsonov209095c2013-04-16 10:53:11 +00001251 outs() << format("<skipping contents of bss section at [%04" PRIx64
David Majnemer8f6b04c2014-07-14 16:20:14 +00001252 ", %04" PRIx64 ")>\n",
1253 BaseAddr, BaseAddr + Size);
Alexey Samsonov209095c2013-04-16 10:53:11 +00001254 continue;
1255 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001256
Davide Italianoccd53fe2015-08-05 07:18:31 +00001257 error(Section.getContents(Contents));
David Majnemer8f6b04c2014-07-14 16:20:14 +00001258
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001259 // Dump out the content as hex and printable ascii characters.
1260 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer82803112012-03-10 02:04:38 +00001261 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001262 // Dump line of hex.
1263 for (std::size_t i = 0; i < 16; ++i) {
1264 if (i != 0 && i % 4 == 0)
1265 outs() << ' ';
1266 if (addr + i < end)
1267 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1268 << hexdigit(Contents[addr + i] & 0xF, true);
1269 else
1270 outs() << " ";
1271 }
1272 // Print ascii.
1273 outs() << " ";
1274 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
Guy Benyei83c74e92013-02-12 21:21:59 +00001275 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001276 outs() << Contents[addr + i];
1277 else
1278 outs() << ".";
1279 }
1280 outs() << "\n";
1281 }
1282 }
1283}
1284
Kevin Enderby98da6132015-01-20 21:47:46 +00001285void llvm::PrintSymbolTable(const ObjectFile *o) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001286 outs() << "SYMBOL TABLE:\n";
1287
Rui Ueyama4e39f712014-03-18 18:58:51 +00001288 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
Davide Italianoe85abf72015-12-20 09:54:34 +00001289 printCOFFSymbolTable(coff);
Rui Ueyama4e39f712014-03-18 18:58:51 +00001290 return;
1291 }
1292 for (const SymbolRef &Symbol : o->symbols()) {
Rafael Espindolaed067c42015-07-03 18:19:00 +00001293 ErrorOr<uint64_t> AddressOrError = Symbol.getAddress();
Davide Italianoccd53fe2015-08-05 07:18:31 +00001294 error(AddressOrError.getError());
Rafael Espindolaed067c42015-07-03 18:19:00 +00001295 uint64_t Address = *AddressOrError;
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00001296 ErrorOr<SymbolRef::Type> TypeOrError = Symbol.getType();
1297 error(TypeOrError.getError());
1298 SymbolRef::Type Type = *TypeOrError;
Rui Ueyama4e39f712014-03-18 18:58:51 +00001299 uint32_t Flags = Symbol.getFlags();
Rafael Espindola8bab8892015-08-07 23:27:14 +00001300 ErrorOr<section_iterator> SectionOrErr = Symbol.getSection();
1301 error(SectionOrErr.getError());
1302 section_iterator Section = *SectionOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001303 StringRef Name;
1304 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1305 Section->getName(Name);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001306 } else {
1307 ErrorOr<StringRef> NameOrErr = Symbol.getName();
Davide Italianoccd53fe2015-08-05 07:18:31 +00001308 error(NameOrErr.getError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001309 Name = *NameOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001310 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001311
Rui Ueyama4e39f712014-03-18 18:58:51 +00001312 bool Global = Flags & SymbolRef::SF_Global;
1313 bool Weak = Flags & SymbolRef::SF_Weak;
1314 bool Absolute = Flags & SymbolRef::SF_Absolute;
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001315 bool Common = Flags & SymbolRef::SF_Common;
Davide Italianocd2514d2015-04-30 23:08:53 +00001316 bool Hidden = Flags & SymbolRef::SF_Hidden;
David Meyer1df4b842012-02-28 23:47:53 +00001317
Rui Ueyama4e39f712014-03-18 18:58:51 +00001318 char GlobLoc = ' ';
1319 if (Type != SymbolRef::ST_Unknown)
1320 GlobLoc = Global ? 'g' : 'l';
1321 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1322 ? 'd' : ' ';
1323 char FileFunc = ' ';
1324 if (Type == SymbolRef::ST_File)
1325 FileFunc = 'f';
1326 else if (Type == SymbolRef::ST_Function)
1327 FileFunc = 'F';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001328
Rui Ueyama4e39f712014-03-18 18:58:51 +00001329 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1330 "%08" PRIx64;
Michael J. Spencerd857c1c2013-01-10 22:40:50 +00001331
Rui Ueyama4e39f712014-03-18 18:58:51 +00001332 outs() << format(Fmt, Address) << " "
1333 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1334 << (Weak ? 'w' : ' ') // Weak?
1335 << ' ' // Constructor. Not supported yet.
1336 << ' ' // Warning. Not supported yet.
1337 << ' ' // Indirect reference to another symbol.
1338 << Debug // Debugging (d) or dynamic (D) symbol.
1339 << FileFunc // Name of function (F), file (f) or object (O).
1340 << ' ';
1341 if (Absolute) {
1342 outs() << "*ABS*";
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001343 } else if (Common) {
1344 outs() << "*COM*";
Rui Ueyama4e39f712014-03-18 18:58:51 +00001345 } else if (Section == o->section_end()) {
1346 outs() << "*UND*";
1347 } else {
1348 if (const MachOObjectFile *MachO =
1349 dyn_cast<const MachOObjectFile>(o)) {
1350 DataRefImpl DR = Section->getRawDataRefImpl();
1351 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1352 outs() << SegmentName << ",";
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001353 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00001354 StringRef SectionName;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001355 error(Section->getName(SectionName));
Rui Ueyama4e39f712014-03-18 18:58:51 +00001356 outs() << SectionName;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001357 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001358
1359 outs() << '\t';
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001360 if (Common || isa<ELFObjectFileBase>(o)) {
Rafael Espindoladbb6bd32015-06-25 22:10:04 +00001361 uint64_t Val =
1362 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001363 outs() << format("\t %08" PRIx64 " ", Val);
1364 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001365
Davide Italianocd2514d2015-04-30 23:08:53 +00001366 if (Hidden) {
1367 outs() << ".hidden ";
1368 }
1369 outs() << Name
Rui Ueyama4e39f712014-03-18 18:58:51 +00001370 << '\n';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001371 }
1372}
1373
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001374static void PrintUnwindInfo(const ObjectFile *o) {
1375 outs() << "Unwind info:\n\n";
1376
1377 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1378 printCOFFUnwindInfo(coff);
Tim Northover4bd286a2014-08-01 13:07:19 +00001379 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1380 printMachOUnwindInfo(MachO);
1381 else {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001382 // TODO: Extract DWARF dump tool to objdump.
1383 errs() << "This operation is only currently supported "
Tim Northover4bd286a2014-08-01 13:07:19 +00001384 "for COFF and MachO object files.\n";
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001385 return;
1386 }
1387}
1388
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001389void llvm::printExportsTrie(const ObjectFile *o) {
Nick Kledzikd04bc352014-08-30 00:20:14 +00001390 outs() << "Exports trie:\n";
1391 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1392 printMachOExportsTrie(MachO);
1393 else {
1394 errs() << "This operation is only currently supported "
1395 "for Mach-O executable files.\n";
1396 return;
1397 }
1398}
1399
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001400void llvm::printRebaseTable(const ObjectFile *o) {
Nick Kledzikac431442014-09-12 21:34:15 +00001401 outs() << "Rebase table:\n";
1402 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1403 printMachORebaseTable(MachO);
1404 else {
1405 errs() << "This operation is only currently supported "
1406 "for Mach-O executable files.\n";
1407 return;
1408 }
1409}
1410
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001411void llvm::printBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001412 outs() << "Bind table:\n";
1413 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1414 printMachOBindTable(MachO);
1415 else {
1416 errs() << "This operation is only currently supported "
1417 "for Mach-O executable files.\n";
1418 return;
1419 }
1420}
1421
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001422void llvm::printLazyBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001423 outs() << "Lazy bind table:\n";
1424 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1425 printMachOLazyBindTable(MachO);
1426 else {
1427 errs() << "This operation is only currently supported "
1428 "for Mach-O executable files.\n";
1429 return;
1430 }
1431}
1432
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001433void llvm::printWeakBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001434 outs() << "Weak bind table:\n";
1435 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1436 printMachOWeakBindTable(MachO);
1437 else {
1438 errs() << "This operation is only currently supported "
1439 "for Mach-O executable files.\n";
1440 return;
1441 }
1442}
Nick Kledzikac431442014-09-12 21:34:15 +00001443
Adrian Prantl437105a2015-07-08 02:04:15 +00001444/// Dump the raw contents of the __clangast section so the output can be piped
1445/// into llvm-bcanalyzer.
1446void llvm::printRawClangAST(const ObjectFile *Obj) {
1447 if (outs().is_displayed()) {
1448 errs() << "The -raw-clang-ast option will dump the raw binary contents of "
1449 "the clang ast section.\n"
1450 "Please redirect the output to a file or another program such as "
1451 "llvm-bcanalyzer.\n";
1452 return;
1453 }
1454
1455 StringRef ClangASTSectionName("__clangast");
1456 if (isa<COFFObjectFile>(Obj)) {
1457 ClangASTSectionName = "clangast";
1458 }
1459
1460 Optional<object::SectionRef> ClangASTSection;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001461 for (auto Sec : ToolSectionFilter(*Obj)) {
Adrian Prantl437105a2015-07-08 02:04:15 +00001462 StringRef Name;
1463 Sec.getName(Name);
1464 if (Name == ClangASTSectionName) {
1465 ClangASTSection = Sec;
1466 break;
1467 }
1468 }
1469 if (!ClangASTSection)
1470 return;
1471
1472 StringRef ClangASTContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001473 error(ClangASTSection.getValue().getContents(ClangASTContents));
Adrian Prantl437105a2015-07-08 02:04:15 +00001474 outs().write(ClangASTContents.data(), ClangASTContents.size());
1475}
1476
Sanjoy Das6f567a42015-06-22 18:03:02 +00001477static void printFaultMaps(const ObjectFile *Obj) {
1478 const char *FaultMapSectionName = nullptr;
1479
1480 if (isa<ELFObjectFileBase>(Obj)) {
1481 FaultMapSectionName = ".llvm_faultmaps";
1482 } else if (isa<MachOObjectFile>(Obj)) {
1483 FaultMapSectionName = "__llvm_faultmaps";
1484 } else {
1485 errs() << "This operation is only currently supported "
1486 "for ELF and Mach-O executable files.\n";
1487 return;
1488 }
1489
1490 Optional<object::SectionRef> FaultMapSection;
1491
Colin LeMahieu77804be2015-07-29 15:45:39 +00001492 for (auto Sec : ToolSectionFilter(*Obj)) {
Sanjoy Das6f567a42015-06-22 18:03:02 +00001493 StringRef Name;
1494 Sec.getName(Name);
1495 if (Name == FaultMapSectionName) {
1496 FaultMapSection = Sec;
1497 break;
1498 }
1499 }
1500
1501 outs() << "FaultMap table:\n";
1502
1503 if (!FaultMapSection.hasValue()) {
1504 outs() << "<not found>\n";
1505 return;
1506 }
1507
1508 StringRef FaultMapContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001509 error(FaultMapSection.getValue().getContents(FaultMapContents));
Sanjoy Das6f567a42015-06-22 18:03:02 +00001510
1511 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1512 FaultMapContents.bytes_end());
1513
1514 outs() << FMP;
1515}
1516
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001517static void printPrivateFileHeaders(const ObjectFile *o) {
1518 if (o->isELF())
1519 printELFFileHeader(o);
1520 else if (o->isCOFF())
1521 printCOFFFileHeader(o);
1522 else if (o->isMachO()) {
1523 printMachOFileHeader(o);
1524 printMachOLoadCommands(o);
1525 } else
1526 report_fatal_error("Invalid/Unsupported object file format");
1527}
1528
1529static void printFirstPrivateFileHeader(const ObjectFile *o) {
Davide Italiano540e9212015-12-19 22:09:40 +00001530 if (o->isELF())
Rui Ueyamac2bed422013-09-27 21:04:00 +00001531 printELFFileHeader(o);
Davide Italiano540e9212015-12-19 22:09:40 +00001532 else if (o->isCOFF())
Rui Ueyamac2bed422013-09-27 21:04:00 +00001533 printCOFFFileHeader(o);
Davide Italiano540e9212015-12-19 22:09:40 +00001534 else if (o->isMachO())
Kevin Enderbyb76d3862014-08-22 20:35:18 +00001535 printMachOFileHeader(o);
Davide Italiano540e9212015-12-19 22:09:40 +00001536 else
1537 report_fatal_error("Invalid/Unsupported object file format");
Rui Ueyamac2bed422013-09-27 21:04:00 +00001538}
1539
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001540static void DumpObject(const ObjectFile *o) {
Adrian Prantl437105a2015-07-08 02:04:15 +00001541 // Avoid other output when using a raw option.
1542 if (!RawClangAST) {
1543 outs() << '\n';
1544 outs() << o->getFileName()
1545 << ":\tfile format " << o->getFileFormatName() << "\n\n";
1546 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001547
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001548 if (Disassemble)
Michael J. Spencer51862b32011-10-13 22:17:18 +00001549 DisassembleObject(o, Relocations);
1550 if (Relocations && !Disassemble)
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001551 PrintRelocations(o);
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001552 if (SectionHeaders)
1553 PrintSectionHeaders(o);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001554 if (SectionContents)
1555 PrintSectionContents(o);
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001556 if (SymbolTable)
1557 PrintSymbolTable(o);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001558 if (UnwindInfo)
1559 PrintUnwindInfo(o);
Rui Ueyamac2bed422013-09-27 21:04:00 +00001560 if (PrivateHeaders)
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001561 printPrivateFileHeaders(o);
1562 if (FirstPrivateHeader)
1563 printFirstPrivateFileHeader(o);
Nick Kledzikd04bc352014-08-30 00:20:14 +00001564 if (ExportsTrie)
1565 printExportsTrie(o);
Nick Kledzikac431442014-09-12 21:34:15 +00001566 if (Rebase)
1567 printRebaseTable(o);
Nick Kledzik56ebef42014-09-16 01:41:51 +00001568 if (Bind)
1569 printBindTable(o);
1570 if (LazyBind)
1571 printLazyBindTable(o);
1572 if (WeakBind)
1573 printWeakBindTable(o);
Adrian Prantl437105a2015-07-08 02:04:15 +00001574 if (RawClangAST)
1575 printRawClangAST(o);
Sanjoy Das6f567a42015-06-22 18:03:02 +00001576 if (PrintFaultMaps)
1577 printFaultMaps(o);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001578 if (DwarfDumpType != DIDT_Null) {
1579 std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*o));
1580 // Dump the complete DWARF structure.
1581 DICtx->dump(outs(), DwarfDumpType, true /* DumpEH */);
1582 }
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001583}
1584
1585/// @brief Dump each object file in \a a;
1586static void DumpArchive(const Archive *a) {
Kevin Enderby7a969422015-11-05 19:24:56 +00001587 for (auto &ErrorOrChild : a->children()) {
1588 if (std::error_code EC = ErrorOrChild.getError())
1589 report_error(a->getFileName(), EC);
1590 const Archive::Child &C = *ErrorOrChild;
Davide Italiano95dd3cb2015-08-03 21:46:32 +00001591 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Davide Italianoccd53fe2015-08-05 07:18:31 +00001592 if (std::error_code EC = ChildOrErr.getError())
Mark Seaborneb03ac52014-01-25 00:32:01 +00001593 if (EC != object_error::invalid_file_type)
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001594 report_error(a->getFileName(), EC);
Rafael Espindolaae460022014-06-16 16:08:36 +00001595 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001596 DumpObject(o);
1597 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001598 report_error(a->getFileName(), object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001599 }
1600}
1601
1602/// @brief Open file and figure out how to dump it.
1603static void DumpInput(StringRef file) {
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001604
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001605 // If we are using the Mach-O specific object file parser, then let it parse
1606 // the file and process the command line options. So the -arch flags can
1607 // be used to select specific slices, etc.
1608 if (MachOOpt) {
1609 ParseInputMachO(file);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001610 return;
1611 }
1612
1613 // Attempt to open the binary.
Rafael Espindola48af1c22014-08-19 18:44:46 +00001614 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001615 if (std::error_code EC = BinaryOrErr.getError())
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001616 report_error(file, EC);
Rafael Espindola48af1c22014-08-19 18:44:46 +00001617 Binary &Binary = *BinaryOrErr.get().getBinary();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001618
Rafael Espindola3f6481d2014-08-01 14:31:55 +00001619 if (Archive *a = dyn_cast<Archive>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001620 DumpArchive(a);
Rafael Espindola3f6481d2014-08-01 14:31:55 +00001621 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001622 DumpObject(o);
Jim Grosbachaf9aec02012-08-07 17:53:14 +00001623 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001624 report_error(file, object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001625}
1626
Michael J. Spencer2670c252011-01-20 06:39:06 +00001627int main(int argc, char **argv) {
1628 // Print a stack trace if we signal out.
1629 sys::PrintStackTraceOnErrorSignal();
1630 PrettyStackTraceProgram X(argc, argv);
1631 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1632
1633 // Initialize targets and assembly printers/parsers.
1634 llvm::InitializeAllTargetInfos();
Evan Cheng8c886a42011-07-22 21:58:54 +00001635 llvm::InitializeAllTargetMCs();
Michael J. Spencer2670c252011-01-20 06:39:06 +00001636 llvm::InitializeAllDisassemblers();
1637
Pete Cooper28fb4fc2012-05-03 23:20:10 +00001638 // Register the target printer for --version.
1639 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
1640
Michael J. Spencer2670c252011-01-20 06:39:06 +00001641 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
1642 TripleName = Triple::normalize(TripleName);
1643
1644 ToolName = argv[0];
1645
1646 // Defaults to a.out if no filenames specified.
1647 if (InputFilenames.size() == 0)
1648 InputFilenames.push_back("a.out");
1649
Colin LeMahieuf34933e2015-07-23 20:58:49 +00001650 if (DisassembleAll)
1651 Disassemble = true;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001652 if (!Disassemble
1653 && !Relocations
1654 && !SectionHeaders
1655 && !SectionContents
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001656 && !SymbolTable
Michael J. Spencer209565db2013-01-06 03:56:49 +00001657 && !UnwindInfo
Nick Kledzikd04bc352014-08-30 00:20:14 +00001658 && !PrivateHeaders
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001659 && !FirstPrivateHeader
Nick Kledzikac431442014-09-12 21:34:15 +00001660 && !ExportsTrie
Nick Kledzik56ebef42014-09-16 01:41:51 +00001661 && !Rebase
1662 && !Bind
1663 && !LazyBind
Kevin Enderby131d1772015-01-09 19:22:37 +00001664 && !WeakBind
Adrian Prantl437105a2015-07-08 02:04:15 +00001665 && !RawClangAST
Kevin Enderby13023a12015-01-15 23:19:11 +00001666 && !(UniversalHeaders && MachOOpt)
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001667 && !(ArchiveHeaders && MachOOpt)
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001668 && !(IndirectSymbols && MachOOpt)
Kevin Enderby9a509442015-01-27 21:28:24 +00001669 && !(DataInCode && MachOOpt)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001670 && !(LinkOptHints && MachOOpt)
Kevin Enderbycd66be52015-03-11 22:06:32 +00001671 && !(InfoPlist && MachOOpt)
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001672 && !(DylibsUsed && MachOOpt)
1673 && !(DylibId && MachOOpt)
Kevin Enderby0fc11822015-04-01 20:57:01 +00001674 && !(ObjcMetaData && MachOOpt)
Colin LeMahieufcc32762015-07-29 19:08:10 +00001675 && !(FilterSections.size() != 0 && MachOOpt)
Igor Laevsky03a670c2016-01-26 15:09:42 +00001676 && !PrintFaultMaps
1677 && DwarfDumpType == DIDT_Null) {
Michael J. Spencer2670c252011-01-20 06:39:06 +00001678 cl::PrintHelpMessage();
1679 return 2;
1680 }
1681
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001682 std::for_each(InputFilenames.begin(), InputFilenames.end(),
1683 DumpInput);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001684
Davide Italianoccd53fe2015-08-05 07:18:31 +00001685 return EXIT_SUCCESS;
Michael J. Spencer2670c252011-01-20 06:39:06 +00001686}