blob: a2c43e11a78ed6e925ec55a53e44d33a7168817d [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"
Michael J. Spencer2670c252011-01-20 06:39:06 +000025#include "llvm/MC/MCAsmInfo.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000026#include "llvm/MC/MCContext.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000027#include "llvm/MC/MCDisassembler.h"
28#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 Bougachaad1084d2013-05-24 00:39:57 +000032#include "llvm/MC/MCObjectFileInfo.h"
Jim Grosbachfd93a592012-03-05 19:33:20 +000033#include "llvm/MC/MCRegisterInfo.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000034#include "llvm/MC/MCRelocationInfo.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000035#include "llvm/MC/MCSubtargetInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000036#include "llvm/Object/Archive.h"
Rafael Espindola37070a52015-06-03 04:48:06 +000037#include "llvm/Object/ELFObjectFile.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000038#include "llvm/Object/COFF.h"
Rafael Espindolaa9f810b2012-12-21 03:47:03 +000039#include "llvm/Object/MachO.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000040#include "llvm/Object/ObjectFile.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000041#include "llvm/Support/Casting.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000042#include "llvm/Support/CommandLine.h"
43#include "llvm/Support/Debug.h"
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +000044#include "llvm/Support/Errc.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000045#include "llvm/Support/FileSystem.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000046#include "llvm/Support/Format.h"
Benjamin Kramerbf115312011-07-25 23:04:36 +000047#include "llvm/Support/GraphWriter.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000048#include "llvm/Support/Host.h"
49#include "llvm/Support/ManagedStatic.h"
50#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000051#include "llvm/Support/PrettyStackTrace.h"
52#include "llvm/Support/Signals.h"
53#include "llvm/Support/SourceMgr.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000054#include "llvm/Support/TargetRegistry.h"
55#include "llvm/Support/TargetSelect.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000056#include "llvm/Support/raw_ostream.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000057#include <algorithm>
Benjamin Kramera5177e62012-03-23 11:49:32 +000058#include <cctype>
Michael J. Spencer2670c252011-01-20 06:39:06 +000059#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000060#include <system_error>
Ahmed Bougacha17926472013-08-21 07:29:02 +000061
Michael J. Spencer2670c252011-01-20 06:39:06 +000062using namespace llvm;
63using namespace object;
64
Benjamin Kramer43a772e2011-09-19 17:56:04 +000065static cl::list<std::string>
66InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
Michael J. Spencer2670c252011-01-20 06:39:06 +000067
Kevin Enderbye2297dd2015-01-07 21:02:18 +000068cl::opt<bool>
69llvm::Disassemble("disassemble",
Benjamin Kramer43a772e2011-09-19 17:56:04 +000070 cl::desc("Display assembler mnemonics for the machine instructions"));
71static cl::alias
72Disassembled("d", cl::desc("Alias for --disassemble"),
Colin LeMahieu77804be2015-07-29 15:45:39 +000073 cl::aliasopt(Disassemble));
74
75cl::opt<bool>
76llvm::DisassembleAll("disassemble-all",
77 cl::desc("Display assembler mnemonics for the machine instructions"));
78static cl::alias
79DisassembleAlld("D", cl::desc("Alias for --disassemble-all"),
Colin LeMahieuf34933e2015-07-23 20:58:49 +000080 cl::aliasopt(DisassembleAll));
Michael J. Spencer2670c252011-01-20 06:39:06 +000081
Kevin Enderby98da6132015-01-20 21:47:46 +000082cl::opt<bool>
83llvm::Relocations("r", cl::desc("Display the relocation entries in the file"));
Michael J. Spencerba4a3622011-10-08 00:18:30 +000084
Kevin Enderby98da6132015-01-20 21:47:46 +000085cl::opt<bool>
86llvm::SectionContents("s", cl::desc("Display the content of each section"));
Michael J. Spencer4e25c022011-10-17 17:13:22 +000087
Kevin Enderby98da6132015-01-20 21:47:46 +000088cl::opt<bool>
89llvm::SymbolTable("t", cl::desc("Display the symbol table"));
Michael J. Spencerbfa06782011-10-18 19:32:17 +000090
Kevin Enderbye2297dd2015-01-07 21:02:18 +000091cl::opt<bool>
92llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
Nick Kledzikd04bc352014-08-30 00:20:14 +000093
Kevin Enderbye2297dd2015-01-07 21:02:18 +000094cl::opt<bool>
95llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
Nick Kledzikac431442014-09-12 21:34:15 +000096
Kevin Enderbye2297dd2015-01-07 21:02:18 +000097cl::opt<bool>
98llvm::Bind("bind", cl::desc("Display mach-o binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +000099
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000100cl::opt<bool>
101llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000102
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000103cl::opt<bool>
104llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000105
Adrian Prantl437105a2015-07-08 02:04:15 +0000106cl::opt<bool>
107llvm::RawClangAST("raw-clang-ast",
108 cl::desc("Dump the raw binary contents of the clang AST section"));
109
Nick Kledzik56ebef42014-09-16 01:41:51 +0000110static cl::opt<bool>
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000111MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000112static cl::alias
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000113MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
Benjamin Kramer87ee76c2011-07-20 19:37:35 +0000114
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000115cl::opt<std::string>
116llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
117 "see -version for available targets"));
118
119cl::opt<std::string>
Kevin Enderbyc9595622014-08-06 23:24:41 +0000120llvm::MCPU("mcpu",
121 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
122 cl::value_desc("cpu-name"),
123 cl::init(""));
124
125cl::opt<std::string>
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000126llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
Michael J. Spencer2670c252011-01-20 06:39:06 +0000127 "see -version for available targets"));
128
Kevin Enderby98da6132015-01-20 21:47:46 +0000129cl::opt<bool>
130llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
131 "headers for each section."));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000132static cl::alias
133SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
134 cl::aliasopt(SectionHeaders));
135static cl::alias
136SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
137 cl::aliasopt(SectionHeaders));
Colin LeMahieufcc32762015-07-29 19:08:10 +0000138
Colin LeMahieu77804be2015-07-29 15:45:39 +0000139cl::list<std::string>
Colin LeMahieufcc32762015-07-29 19:08:10 +0000140llvm::FilterSections("section", cl::desc("Operate on the specified sections only. "
141 "With -macho dump segment,section"));
142cl::alias
143static FilterSectionsj("j", cl::desc("Alias for --section"),
144 cl::aliasopt(llvm::FilterSections));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000145
Kevin Enderbyc9595622014-08-06 23:24:41 +0000146cl::list<std::string>
147llvm::MAttrs("mattr",
Jack Carter551efd72012-08-28 19:24:49 +0000148 cl::CommaSeparated,
149 cl::desc("Target specific attributes"),
150 cl::value_desc("a1,+a2,-a3,..."));
151
Kevin Enderbybf246f52014-09-24 23:08:22 +0000152cl::opt<bool>
153llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
154 "instructions, do not print "
155 "the instruction bytes."));
Eli Bendersky3a6808c2012-11-20 22:57:02 +0000156
Kevin Enderby98da6132015-01-20 21:47:46 +0000157cl::opt<bool>
158llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000159
160static cl::alias
161UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
162 cl::aliasopt(UnwindInfo));
163
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000164cl::opt<bool>
165llvm::PrivateHeaders("private-headers",
166 cl::desc("Display format specific file headers"));
Michael J. Spencer209565db2013-01-06 03:56:49 +0000167
168static cl::alias
169PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
170 cl::aliasopt(PrivateHeaders));
171
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000172cl::opt<bool>
173 llvm::PrintImmHex("print-imm-hex",
174 cl::desc("Use hex format for immediate values"));
175
Sanjoy Das6f567a42015-06-22 18:03:02 +0000176cl::opt<bool> PrintFaultMaps("fault-map-section",
177 cl::desc("Display contents of faultmap section"));
178
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000179static StringRef ToolName;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000180
Colin LeMahieu77804be2015-07-29 15:45:39 +0000181namespace {
Colin LeMahieufcc32762015-07-29 19:08:10 +0000182typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate;
Colin LeMahieu77804be2015-07-29 15:45:39 +0000183
184class SectionFilterIterator {
185public:
186 SectionFilterIterator(FilterPredicate P,
187 llvm::object::section_iterator const &I,
188 llvm::object::section_iterator const &E)
189 : Predicate(P), Iterator(I), End(E) {
190 ScanPredicate();
191 }
Benjamin Kramerac9257b2015-09-24 14:52:52 +0000192 const llvm::object::SectionRef &operator*() const { return *Iterator; }
Colin LeMahieu77804be2015-07-29 15:45:39 +0000193 SectionFilterIterator &operator++() {
194 ++Iterator;
195 ScanPredicate();
196 return *this;
197 }
198 bool operator!=(SectionFilterIterator const &Other) const {
199 return Iterator != Other.Iterator;
200 }
201
202private:
203 void ScanPredicate() {
Colin LeMahieuda1723f2015-07-29 19:21:13 +0000204 while (Iterator != End && !Predicate(*Iterator)) {
Colin LeMahieu77804be2015-07-29 15:45:39 +0000205 ++Iterator;
206 }
207 }
208 FilterPredicate Predicate;
209 llvm::object::section_iterator Iterator;
210 llvm::object::section_iterator End;
211};
212
213class SectionFilter {
214public:
215 SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O)
216 : Predicate(P), Object(O) {}
217 SectionFilterIterator begin() {
218 return SectionFilterIterator(Predicate, Object.section_begin(),
219 Object.section_end());
220 }
221 SectionFilterIterator end() {
222 return SectionFilterIterator(Predicate, Object.section_end(),
223 Object.section_end());
224 }
225
226private:
227 FilterPredicate Predicate;
228 llvm::object::ObjectFile const &Object;
229};
230SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) {
Colin LeMahieu77804be2015-07-29 15:45:39 +0000231 return SectionFilter([](llvm::object::SectionRef const &S) {
Colin LeMahieufcc32762015-07-29 19:08:10 +0000232 if(FilterSections.empty())
Colin LeMahieuda1723f2015-07-29 19:21:13 +0000233 return true;
Colin LeMahieu77804be2015-07-29 15:45:39 +0000234 llvm::StringRef String;
235 std::error_code error = S.getName(String);
Colin LeMahieufcc32762015-07-29 19:08:10 +0000236 if (error)
Colin LeMahieuda1723f2015-07-29 19:21:13 +0000237 return false;
Colin LeMahieufcc32762015-07-29 19:08:10 +0000238 return std::find(FilterSections.begin(),
239 FilterSections.end(),
Colin LeMahieuda1723f2015-07-29 19:21:13 +0000240 String) != FilterSections.end();
Colin LeMahieu77804be2015-07-29 15:45:39 +0000241 },
242 O);
243}
244}
245
Davide Italianoccd53fe2015-08-05 07:18:31 +0000246void llvm::error(std::error_code EC) {
Mark Seaborneb03ac52014-01-25 00:32:01 +0000247 if (!EC)
Davide Italianoccd53fe2015-08-05 07:18:31 +0000248 return;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000249
Mark Seaborneb03ac52014-01-25 00:32:01 +0000250 outs() << ToolName << ": error reading file: " << EC.message() << ".\n";
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000251 outs().flush();
Davide Italiano7f6c3012015-08-06 00:18:52 +0000252 exit(1);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000253}
254
Davide Italianob13edeb2015-12-08 02:45:59 +0000255void llvm::report_error(StringRef File, std::error_code EC) {
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000256 assert(EC);
257 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
Davide Italianoccd53fe2015-08-05 07:18:31 +0000258 exit(1);
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000259}
260
Craig Toppere6cb63e2014-04-25 04:24:47 +0000261static const Target *getTarget(const ObjectFile *Obj = nullptr) {
Michael J. Spencer2670c252011-01-20 06:39:06 +0000262 // Figure out the target triple.
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000263 llvm::Triple TheTriple("unknown-unknown-unknown");
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000264 if (TripleName.empty()) {
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000265 if (Obj) {
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000266 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000267 // TheTriple defaults to ELF, and COFF doesn't have an environment:
268 // the best we can do here is indicate that it is mach-o.
269 if (Obj->isMachO())
Saleem Abdulrasool35476332014-03-06 20:47:11 +0000270 TheTriple.setObjectFormat(Triple::MachO);
Saleem Abdulrasool98938f12014-04-17 06:17:23 +0000271
272 if (Obj->isCOFF()) {
273 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
274 if (COFFObj->getArch() == Triple::thumb)
275 TheTriple.setTriple("thumbv7-windows");
276 }
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000277 }
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000278 } else
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000279 TheTriple.setTriple(Triple::normalize(TripleName));
Michael J. Spencer2670c252011-01-20 06:39:06 +0000280
281 // Get the target specific parser.
282 std::string Error;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000283 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
284 Error);
Davide Italianobb599e32015-12-03 22:13:40 +0000285 if (!TheTarget)
286 report_fatal_error("can't find target: " + Error);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000287
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000288 // Update the triple name and return the found target.
289 TripleName = TheTriple.getTriple();
290 return TheTarget;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000291}
292
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000293bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
Rafael Espindola704cd842015-07-06 15:47:43 +0000294 return a.getOffset() < b.getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +0000295}
296
Colin LeMahieufb76b002015-05-28 19:07:14 +0000297namespace {
298class PrettyPrinter {
299public:
Colin LeMahieu0b5890d2015-05-28 20:59:08 +0000300 virtual ~PrettyPrinter(){}
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000301 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
Colin LeMahieufb76b002015-05-28 19:07:14 +0000302 ArrayRef<uint8_t> Bytes, uint64_t Address,
303 raw_ostream &OS, StringRef Annot,
304 MCSubtargetInfo const &STI) {
305 outs() << format("%8" PRIx64 ":", Address);
306 if (!NoShowRawInsn) {
307 outs() << "\t";
308 dumpBytes(Bytes, outs());
309 }
310 IP.printInst(MI, outs(), "", STI);
311 }
312};
313PrettyPrinter PrettyPrinterInst;
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000314class HexagonPrettyPrinter : public PrettyPrinter {
315public:
316 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
317 raw_ostream &OS) {
318 uint32_t opcode =
319 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
320 OS << format("%8" PRIx64 ":", Address);
321 if (!NoShowRawInsn) {
322 OS << "\t";
323 dumpBytes(Bytes.slice(0, 4), OS);
324 OS << format("%08" PRIx32, opcode);
325 }
326 }
327 void printInst(MCInstPrinter &IP, const MCInst *MI,
328 ArrayRef<uint8_t> Bytes, uint64_t Address,
329 raw_ostream &OS, StringRef Annot,
330 MCSubtargetInfo const &STI) override {
331 std::string Buffer;
332 {
333 raw_string_ostream TempStream(Buffer);
334 IP.printInst(MI, TempStream, "", STI);
335 }
336 StringRef Contents(Buffer);
337 // Split off bundle attributes
338 auto PacketBundle = Contents.rsplit('\n');
339 // Split off first instruction from the rest
340 auto HeadTail = PacketBundle.first.split('\n');
341 auto Preamble = " { ";
342 auto Separator = "";
343 while(!HeadTail.first.empty()) {
344 OS << Separator;
345 Separator = "\n";
346 printLead(Bytes, Address, OS);
347 OS << Preamble;
348 Preamble = " ";
349 StringRef Inst;
350 auto Duplex = HeadTail.first.split('\v');
351 if(!Duplex.second.empty()){
352 OS << Duplex.first;
353 OS << "; ";
354 Inst = Duplex.second;
355 }
356 else
357 Inst = HeadTail.first;
358 OS << Inst;
359 Bytes = Bytes.slice(4);
360 Address += 4;
361 HeadTail = HeadTail.second.split('\n');
362 }
363 OS << " } " << PacketBundle.second;
364 }
365};
366HexagonPrettyPrinter HexagonPrettyPrinterInst;
Colin LeMahieu35436a22015-05-29 14:48:25 +0000367PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000368 switch(Triple.getArch()) {
369 default:
370 return PrettyPrinterInst;
371 case Triple::hexagon:
372 return HexagonPrettyPrinterInst;
373 }
Colin LeMahieufb76b002015-05-28 19:07:14 +0000374}
375}
376
Rafael Espindola37070a52015-06-03 04:48:06 +0000377template <class ELFT>
Rafael Espindola37070a52015-06-03 04:48:06 +0000378static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000379 const RelocationRef &RelRef,
Rafael Espindola37070a52015-06-03 04:48:06 +0000380 SmallVectorImpl<char> &Result) {
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000381 DataRefImpl Rel = RelRef.getRawDataRefImpl();
382
Rafael Espindola37070a52015-06-03 04:48:06 +0000383 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
384 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000385 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
386
Rafael Espindola37070a52015-06-03 04:48:06 +0000387 const ELFFile<ELFT> &EF = *Obj->getELFFile();
388
Rafael Espindola6def3042015-07-01 12:56:27 +0000389 ErrorOr<const Elf_Shdr *> SecOrErr = EF.getSection(Rel.d.a);
390 if (std::error_code EC = SecOrErr.getError())
391 return EC;
392 const Elf_Shdr *Sec = *SecOrErr;
393 ErrorOr<const Elf_Shdr *> SymTabOrErr = EF.getSection(Sec->sh_link);
394 if (std::error_code EC = SymTabOrErr.getError())
395 return EC;
396 const Elf_Shdr *SymTab = *SymTabOrErr;
Rafael Espindola719dc7c2015-06-29 12:38:31 +0000397 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
398 SymTab->sh_type == ELF::SHT_DYNSYM);
Rafael Espindola6def3042015-07-01 12:56:27 +0000399 ErrorOr<const Elf_Shdr *> StrTabSec = EF.getSection(SymTab->sh_link);
400 if (std::error_code EC = StrTabSec.getError())
401 return EC;
402 ErrorOr<StringRef> StrTabOrErr = EF.getStringTable(*StrTabSec);
Rafael Espindola6a1bfb22015-06-29 14:39:25 +0000403 if (std::error_code EC = StrTabOrErr.getError())
404 return EC;
405 StringRef StrTab = *StrTabOrErr;
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000406 uint8_t type = RelRef.getType();
Rafael Espindola37070a52015-06-03 04:48:06 +0000407 StringRef res;
408 int64_t addend = 0;
Rafael Espindola6def3042015-07-01 12:56:27 +0000409 switch (Sec->sh_type) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000410 default:
411 return object_error::parse_failed;
412 case ELF::SHT_REL: {
Rafael Espindola37070a52015-06-03 04:48:06 +0000413 // TODO: Read implicit addend from section data.
414 break;
415 }
416 case ELF::SHT_RELA: {
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000417 const Elf_Rela *ERela = Obj->getRela(Rel);
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000418 addend = ERela->r_addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000419 break;
420 }
421 }
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000422 symbol_iterator SI = RelRef.getSymbol();
423 const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
Rafael Espindola75d5b542015-06-03 05:14:22 +0000424 StringRef Target;
Rafael Espindola75d5b542015-06-03 05:14:22 +0000425 if (symb->getType() == ELF::STT_SECTION) {
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000426 ErrorOr<section_iterator> SymSI = SI->getSection();
427 if (std::error_code EC = SymSI.getError())
428 return EC;
429 const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
430 ErrorOr<StringRef> SecName = EF.getSectionName(SymSec);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000431 if (std::error_code EC = SecName.getError())
432 return EC;
433 Target = *SecName;
434 } else {
Rafael Espindola44c28712015-06-29 21:24:55 +0000435 ErrorOr<StringRef> SymName = symb->getName(StrTab);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000436 if (!SymName)
437 return SymName.getError();
438 Target = *SymName;
439 }
Rafael Espindola37070a52015-06-03 04:48:06 +0000440 switch (EF.getHeader()->e_machine) {
441 case ELF::EM_X86_64:
442 switch (type) {
443 case ELF::R_X86_64_PC8:
444 case ELF::R_X86_64_PC16:
445 case ELF::R_X86_64_PC32: {
446 std::string fmtbuf;
447 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000448 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
Rafael Espindola37070a52015-06-03 04:48:06 +0000449 fmt.flush();
450 Result.append(fmtbuf.begin(), fmtbuf.end());
451 } break;
452 case ELF::R_X86_64_8:
453 case ELF::R_X86_64_16:
454 case ELF::R_X86_64_32:
455 case ELF::R_X86_64_32S:
456 case ELF::R_X86_64_64: {
457 std::string fmtbuf;
458 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000459 fmt << Target << (addend < 0 ? "" : "+") << addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000460 fmt.flush();
461 Result.append(fmtbuf.begin(), fmtbuf.end());
462 } break;
463 default:
464 res = "Unknown";
465 }
466 break;
467 case ELF::EM_AARCH64: {
468 std::string fmtbuf;
469 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000470 fmt << Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000471 if (addend != 0)
472 fmt << (addend < 0 ? "" : "+") << addend;
473 fmt.flush();
474 Result.append(fmtbuf.begin(), fmtbuf.end());
475 break;
476 }
477 case ELF::EM_386:
Michael Kupersteina3b79dd2015-11-04 11:21:50 +0000478 case ELF::EM_IAMCU:
Rafael Espindola37070a52015-06-03 04:48:06 +0000479 case ELF::EM_ARM:
480 case ELF::EM_HEXAGON:
481 case ELF::EM_MIPS:
Rafael Espindola75d5b542015-06-03 05:14:22 +0000482 res = Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000483 break;
484 default:
485 res = "Unknown";
486 }
487 if (Result.empty())
488 Result.append(res.begin(), res.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000489 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000490}
491
492static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000493 const RelocationRef &Rel,
Rafael Espindola37070a52015-06-03 04:48:06 +0000494 SmallVectorImpl<char> &Result) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000495 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
496 return getRelocationValueString(ELF32LE, Rel, Result);
497 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
498 return getRelocationValueString(ELF64LE, Rel, Result);
499 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
500 return getRelocationValueString(ELF32BE, Rel, Result);
501 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
502 return getRelocationValueString(ELF64BE, Rel, Result);
503}
504
505static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
506 const RelocationRef &Rel,
507 SmallVectorImpl<char> &Result) {
508 symbol_iterator SymI = Rel.getSymbol();
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000509 ErrorOr<StringRef> SymNameOrErr = SymI->getName();
510 if (std::error_code EC = SymNameOrErr.getError())
Rafael Espindola37070a52015-06-03 04:48:06 +0000511 return EC;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000512 StringRef SymName = *SymNameOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000513 Result.append(SymName.begin(), SymName.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000514 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000515}
516
517static void printRelocationTargetName(const MachOObjectFile *O,
518 const MachO::any_relocation_info &RE,
519 raw_string_ostream &fmt) {
520 bool IsScattered = O->isRelocationScattered(RE);
521
522 // Target of a scattered relocation is an address. In the interest of
523 // generating pretty output, scan through the symbol table looking for a
524 // symbol that aligns with that address. If we find one, print it.
525 // Otherwise, we just print the hex address of the target.
526 if (IsScattered) {
527 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
528
529 for (const SymbolRef &Symbol : O->symbols()) {
530 std::error_code ec;
Rafael Espindolaed067c42015-07-03 18:19:00 +0000531 ErrorOr<uint64_t> Addr = Symbol.getAddress();
532 if ((ec = Addr.getError()))
Rafael Espindola37070a52015-06-03 04:48:06 +0000533 report_fatal_error(ec.message());
Rafael Espindolaed067c42015-07-03 18:19:00 +0000534 if (*Addr != Val)
Rafael Espindola37070a52015-06-03 04:48:06 +0000535 continue;
Rafael Espindolaed067c42015-07-03 18:19:00 +0000536 ErrorOr<StringRef> Name = Symbol.getName();
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000537 if (std::error_code EC = Name.getError())
538 report_fatal_error(EC.message());
539 fmt << *Name;
Rafael Espindola37070a52015-06-03 04:48:06 +0000540 return;
541 }
542
543 // If we couldn't find a symbol that this relocation refers to, try
544 // to find a section beginning instead.
Colin LeMahieu77804be2015-07-29 15:45:39 +0000545 for (const SectionRef &Section : ToolSectionFilter(*O)) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000546 std::error_code ec;
547
548 StringRef Name;
549 uint64_t Addr = Section.getAddress();
550 if (Addr != Val)
551 continue;
552 if ((ec = Section.getName(Name)))
553 report_fatal_error(ec.message());
554 fmt << Name;
555 return;
556 }
557
558 fmt << format("0x%x", Val);
559 return;
560 }
561
562 StringRef S;
563 bool isExtern = O->getPlainRelocationExternal(RE);
564 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
565
566 if (isExtern) {
567 symbol_iterator SI = O->symbol_begin();
568 advance(SI, Val);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000569 ErrorOr<StringRef> SOrErr = SI->getName();
Davide Italianoccd53fe2015-08-05 07:18:31 +0000570 error(SOrErr.getError());
571 S = *SOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000572 } else {
573 section_iterator SI = O->section_begin();
574 // Adjust for the fact that sections are 1-indexed.
575 advance(SI, Val - 1);
576 SI->getName(S);
577 }
578
579 fmt << S;
580}
581
582static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
583 const RelocationRef &RelRef,
584 SmallVectorImpl<char> &Result) {
585 DataRefImpl Rel = RelRef.getRawDataRefImpl();
586 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
587
588 unsigned Arch = Obj->getArch();
589
590 std::string fmtbuf;
591 raw_string_ostream fmt(fmtbuf);
592 unsigned Type = Obj->getAnyRelocationType(RE);
593 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
594
595 // Determine any addends that should be displayed with the relocation.
596 // These require decoding the relocation type, which is triple-specific.
597
598 // X86_64 has entirely custom relocation types.
599 if (Arch == Triple::x86_64) {
600 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
601
602 switch (Type) {
603 case MachO::X86_64_RELOC_GOT_LOAD:
604 case MachO::X86_64_RELOC_GOT: {
605 printRelocationTargetName(Obj, RE, fmt);
606 fmt << "@GOT";
607 if (isPCRel)
608 fmt << "PCREL";
609 break;
610 }
611 case MachO::X86_64_RELOC_SUBTRACTOR: {
612 DataRefImpl RelNext = Rel;
613 Obj->moveRelocationNext(RelNext);
614 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
615
616 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
617 // X86_64_RELOC_UNSIGNED.
618 // NOTE: Scattered relocations don't exist on x86_64.
619 unsigned RType = Obj->getAnyRelocationType(RENext);
620 if (RType != MachO::X86_64_RELOC_UNSIGNED)
621 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
622 "X86_64_RELOC_SUBTRACTOR.");
623
624 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
625 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
626 printRelocationTargetName(Obj, RENext, fmt);
627 fmt << "-";
628 printRelocationTargetName(Obj, RE, fmt);
629 break;
630 }
631 case MachO::X86_64_RELOC_TLV:
632 printRelocationTargetName(Obj, RE, fmt);
633 fmt << "@TLV";
634 if (isPCRel)
635 fmt << "P";
636 break;
637 case MachO::X86_64_RELOC_SIGNED_1:
638 printRelocationTargetName(Obj, RE, fmt);
639 fmt << "-1";
640 break;
641 case MachO::X86_64_RELOC_SIGNED_2:
642 printRelocationTargetName(Obj, RE, fmt);
643 fmt << "-2";
644 break;
645 case MachO::X86_64_RELOC_SIGNED_4:
646 printRelocationTargetName(Obj, RE, fmt);
647 fmt << "-4";
648 break;
649 default:
650 printRelocationTargetName(Obj, RE, fmt);
651 break;
652 }
653 // X86 and ARM share some relocation types in common.
654 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
655 Arch == Triple::ppc) {
656 // Generic relocation types...
657 switch (Type) {
658 case MachO::GENERIC_RELOC_PAIR: // prints no info
Rui Ueyama7d099192015-06-09 15:20:42 +0000659 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000660 case MachO::GENERIC_RELOC_SECTDIFF: {
661 DataRefImpl RelNext = Rel;
662 Obj->moveRelocationNext(RelNext);
663 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
664
665 // X86 sect diff's must be followed by a relocation of type
666 // GENERIC_RELOC_PAIR.
667 unsigned RType = Obj->getAnyRelocationType(RENext);
668
669 if (RType != MachO::GENERIC_RELOC_PAIR)
670 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
671 "GENERIC_RELOC_SECTDIFF.");
672
673 printRelocationTargetName(Obj, RE, fmt);
674 fmt << "-";
675 printRelocationTargetName(Obj, RENext, fmt);
676 break;
677 }
678 }
679
680 if (Arch == Triple::x86 || Arch == Triple::ppc) {
681 switch (Type) {
682 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
683 DataRefImpl RelNext = Rel;
684 Obj->moveRelocationNext(RelNext);
685 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
686
687 // X86 sect diff's must be followed by a relocation of type
688 // GENERIC_RELOC_PAIR.
689 unsigned RType = Obj->getAnyRelocationType(RENext);
690 if (RType != MachO::GENERIC_RELOC_PAIR)
691 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
692 "GENERIC_RELOC_LOCAL_SECTDIFF.");
693
694 printRelocationTargetName(Obj, RE, fmt);
695 fmt << "-";
696 printRelocationTargetName(Obj, RENext, fmt);
697 break;
698 }
699 case MachO::GENERIC_RELOC_TLV: {
700 printRelocationTargetName(Obj, RE, fmt);
701 fmt << "@TLV";
702 if (IsPCRel)
703 fmt << "P";
704 break;
705 }
706 default:
707 printRelocationTargetName(Obj, RE, fmt);
708 }
709 } else { // ARM-specific relocations
710 switch (Type) {
711 case MachO::ARM_RELOC_HALF:
712 case MachO::ARM_RELOC_HALF_SECTDIFF: {
713 // Half relocations steal a bit from the length field to encode
714 // whether this is an upper16 or a lower16 relocation.
715 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
716
717 if (isUpper)
718 fmt << ":upper16:(";
719 else
720 fmt << ":lower16:(";
721 printRelocationTargetName(Obj, RE, fmt);
722
723 DataRefImpl RelNext = Rel;
724 Obj->moveRelocationNext(RelNext);
725 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
726
727 // ARM half relocs must be followed by a relocation of type
728 // ARM_RELOC_PAIR.
729 unsigned RType = Obj->getAnyRelocationType(RENext);
730 if (RType != MachO::ARM_RELOC_PAIR)
731 report_fatal_error("Expected ARM_RELOC_PAIR after "
732 "ARM_RELOC_HALF");
733
734 // NOTE: The half of the target virtual address is stashed in the
735 // address field of the secondary relocation, but we can't reverse
736 // engineer the constant offset from it without decoding the movw/movt
737 // instruction to find the other half in its immediate field.
738
739 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
740 // symbol/section pointer of the follow-on relocation.
741 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
742 fmt << "-";
743 printRelocationTargetName(Obj, RENext, fmt);
744 }
745
746 fmt << ")";
747 break;
748 }
749 default: { printRelocationTargetName(Obj, RE, fmt); }
750 }
751 }
752 } else
753 printRelocationTargetName(Obj, RE, fmt);
754
755 fmt.flush();
756 Result.append(fmtbuf.begin(), fmtbuf.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000757 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000758}
759
760static std::error_code getRelocationValueString(const RelocationRef &Rel,
761 SmallVectorImpl<char> &Result) {
Rafael Espindola854038e2015-06-26 14:51:16 +0000762 const ObjectFile *Obj = Rel.getObject();
Rafael Espindola37070a52015-06-03 04:48:06 +0000763 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
764 return getRelocationValueString(ELF, Rel, Result);
765 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
766 return getRelocationValueString(COFF, Rel, Result);
767 auto *MachO = cast<MachOObjectFile>(Obj);
768 return getRelocationValueString(MachO, Rel, Result);
769}
770
Rafael Espindola0ad71d92015-06-30 03:41:26 +0000771/// @brief Indicates whether this relocation should hidden when listing
772/// relocations, usually because it is the trailing part of a multipart
773/// relocation that will be printed as part of the leading relocation.
774static bool getHidden(RelocationRef RelRef) {
775 const ObjectFile *Obj = RelRef.getObject();
776 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
777 if (!MachO)
778 return false;
779
780 unsigned Arch = MachO->getArch();
781 DataRefImpl Rel = RelRef.getRawDataRefImpl();
782 uint64_t Type = MachO->getRelocationType(Rel);
783
784 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
785 // is always hidden.
786 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
787 if (Type == MachO::GENERIC_RELOC_PAIR)
788 return true;
789 } else if (Arch == Triple::x86_64) {
790 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
791 // an X86_64_RELOC_SUBTRACTOR.
792 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
793 DataRefImpl RelPrev = Rel;
794 RelPrev.d.a--;
795 uint64_t PrevType = MachO->getRelocationType(RelPrev);
796 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
797 return true;
798 }
799 }
800
801 return false;
802}
803
Michael J. Spencer51862b32011-10-13 22:17:18 +0000804static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Jim Grosbachaf9aec02012-08-07 17:53:14 +0000805 const Target *TheTarget = getTarget(Obj);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000806
Jack Carter551efd72012-08-28 19:24:49 +0000807 // Package up features to be passed to target/subtarget
808 std::string FeaturesStr;
809 if (MAttrs.size()) {
810 SubtargetFeatures Features;
811 for (unsigned i = 0; i != MAttrs.size(); ++i)
812 Features.AddFeature(MAttrs[i]);
813 FeaturesStr = Features.getString();
814 }
815
Ahmed Charles56440fd2014-03-06 05:51:42 +0000816 std::unique_ptr<const MCRegisterInfo> MRI(
817 TheTarget->createMCRegInfo(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000818 if (!MRI) {
819 errs() << "error: no register info for target " << TripleName << "\n";
820 return;
821 }
822
823 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000824 std::unique_ptr<const MCAsmInfo> AsmInfo(
825 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000826 if (!AsmInfo) {
827 errs() << "error: no assembly info for target " << TripleName << "\n";
828 return;
829 }
830
Ahmed Charles56440fd2014-03-06 05:51:42 +0000831 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +0000832 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000833 if (!STI) {
834 errs() << "error: no subtarget info for target " << TripleName << "\n";
835 return;
836 }
837
Ahmed Charles56440fd2014-03-06 05:51:42 +0000838 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000839 if (!MII) {
840 errs() << "error: no instruction info for target " << TripleName << "\n";
841 return;
842 }
843
Lang Hamesa1bc0f52014-04-15 04:40:56 +0000844 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
845 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
846
847 std::unique_ptr<MCDisassembler> DisAsm(
848 TheTarget->createMCDisassembler(*STI, Ctx));
849
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000850 if (!DisAsm) {
851 errs() << "error: no disassembler for target " << TripleName << "\n";
852 return;
853 }
854
Ahmed Charles56440fd2014-03-06 05:51:42 +0000855 std::unique_ptr<const MCInstrAnalysis> MIA(
856 TheTarget->createMCInstrAnalysis(MII.get()));
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000857
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000858 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Daniel Sanders50f17232015-09-15 16:17:27 +0000859 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
860 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000861 if (!IP) {
862 errs() << "error: no instruction printer for target " << TripleName
863 << '\n';
864 return;
865 }
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000866 IP->setPrintImmHex(PrintImmHex);
Colin LeMahieu35436a22015-05-29 14:48:25 +0000867 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000868
Greg Fitzgerald18432272014-03-20 22:55:15 +0000869 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
870 "\t\t\t%08" PRIx64 ": ";
871
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000872 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
873 // in RelocSecs contain the relocations for section S.
Rafael Espindola4453e42942014-06-13 03:07:50 +0000874 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000875 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
Colin LeMahieu77804be2015-07-29 15:45:39 +0000876 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +0000877 section_iterator Sec2 = Section.getRelocatedSection();
Rafael Espindolab5155a52014-02-10 20:24:04 +0000878 if (Sec2 != Obj->section_end())
Alexey Samsonov48803e52014-03-13 14:37:36 +0000879 SectionRelocMap[*Sec2].push_back(Section);
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000880 }
881
David Majnemer81afca62015-07-07 22:06:59 +0000882 // Create a mapping from virtual address to symbol name. This is used to
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000883 // pretty print the symbols while disassembling.
884 typedef std::vector<std::pair<uint64_t, StringRef>> SectionSymbolsTy;
885 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
886 for (const SymbolRef &Symbol : Obj->symbols()) {
887 ErrorOr<uint64_t> AddressOrErr = Symbol.getAddress();
888 error(AddressOrErr.getError());
889 uint64_t Address = *AddressOrErr;
David Majnemer2603a8fa2015-07-09 18:11:40 +0000890
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000891 ErrorOr<StringRef> Name = Symbol.getName();
892 error(Name.getError());
893 if (Name->empty())
894 continue;
David Majnemer81afca62015-07-07 22:06:59 +0000895
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000896 ErrorOr<section_iterator> SectionOrErr = Symbol.getSection();
897 error(SectionOrErr.getError());
898 section_iterator SecI = *SectionOrErr;
899 if (SecI == Obj->section_end())
900 continue;
David Majnemer81afca62015-07-07 22:06:59 +0000901
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000902 AllSymbols[*SecI].emplace_back(Address, *Name);
David Majnemer81afca62015-07-07 22:06:59 +0000903 }
904
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000905 // Create a mapping from virtual address to section.
906 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
907 for (SectionRef Sec : Obj->sections())
908 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
909 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
910
911 // Linked executables (.exe and .dll files) typically don't include a real
912 // symbol table but they might contain an export table.
913 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
914 for (const auto &ExportEntry : COFFObj->export_directories()) {
915 StringRef Name;
916 error(ExportEntry.getSymbolName(Name));
917 if (Name.empty())
918 continue;
919 uint32_t RVA;
920 error(ExportEntry.getExportRVA(RVA));
921
922 uint64_t VA = COFFObj->getImageBase() + RVA;
923 auto Sec = std::upper_bound(
924 SectionAddresses.begin(), SectionAddresses.end(), VA,
925 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
926 return LHS < RHS.first;
927 });
928 if (Sec != SectionAddresses.begin())
929 --Sec;
930 else
931 Sec = SectionAddresses.end();
932
933 if (Sec != SectionAddresses.end())
934 AllSymbols[Sec->second].emplace_back(VA, Name);
935 }
936 }
937
938 // Sort all the symbols, this allows us to use a simple binary search to find
939 // a symbol near an address.
940 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
941 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
942
Colin LeMahieu77804be2015-07-29 15:45:39 +0000943 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Colin LeMahieuf34933e2015-07-23 20:58:49 +0000944 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000945 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000946
Rafael Espindola80291272014-10-08 15:28:58 +0000947 uint64_t SectionAddr = Section.getAddress();
948 uint64_t SectSize = Section.getSize();
David Majnemer185b5b12014-11-11 09:58:25 +0000949 if (!SectSize)
950 continue;
Simon Atanasyan2b614e12014-02-24 22:12:11 +0000951
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000952 // Get the list of all the symbols in this section.
953 SectionSymbolsTy &Symbols = AllSymbols[Section];
Davide Italianof0706882015-10-01 21:57:09 +0000954 std::vector<uint64_t> DataMappingSymsAddr;
955 std::vector<uint64_t> TextMappingSymsAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000956 if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
957 for (const auto &Symb : Symbols) {
958 uint64_t Address = Symb.first;
959 StringRef Name = Symb.second;
960 if (Name.startswith("$d"))
David Majnemer153722d2015-11-18 04:35:32 +0000961 DataMappingSymsAddr.push_back(Address - SectionAddr);
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000962 if (Name.startswith("$x"))
David Majnemer153722d2015-11-18 04:35:32 +0000963 TextMappingSymsAddr.push_back(Address - SectionAddr);
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000964 }
965 }
966
Davide Italianof0706882015-10-01 21:57:09 +0000967 std::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end());
968 std::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end());
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000969
Michael J. Spencer51862b32011-10-13 22:17:18 +0000970 // Make a list of all the relocations for this section.
971 std::vector<RelocationRef> Rels;
972 if (InlineRelocs) {
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000973 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
974 for (const RelocationRef &Reloc : RelocSec.relocations()) {
975 Rels.push_back(Reloc);
976 }
Michael J. Spencer51862b32011-10-13 22:17:18 +0000977 }
978 }
979
980 // Sort relocations by address.
981 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
982
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000983 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +0000984 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +0000985 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +0000986 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000987 }
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000988 StringRef name;
Davide Italianoccd53fe2015-08-05 07:18:31 +0000989 error(Section.getName(name));
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000990 outs() << "Disassembly of section ";
991 if (!SegmentName.empty())
992 outs() << SegmentName << ",";
993 outs() << name << ':';
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000994
Rafael Espindola7884c952015-06-04 15:01:05 +0000995 // If the section has no symbol at the start, just insert a dummy one.
996 if (Symbols.empty() || Symbols[0].first != 0)
David Majnemer153722d2015-11-18 04:35:32 +0000997 Symbols.insert(Symbols.begin(), std::make_pair(SectionAddr, name));
Alp Tokere69170a2014-06-26 22:52:05 +0000998
999 SmallString<40> Comments;
1000 raw_svector_ostream CommentStream(Comments);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001001
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001002 StringRef BytesStr;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001003 error(Section.getContents(BytesStr));
Aaron Ballman106fd7b2014-11-12 14:01:17 +00001004 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1005 BytesStr.size());
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001006
Michael J. Spencer2670c252011-01-20 06:39:06 +00001007 uint64_t Size;
1008 uint64_t Index;
1009
Michael J. Spencer51862b32011-10-13 22:17:18 +00001010 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
1011 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001012 // Disassemble symbol by symbol.
1013 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
Rafael Espindolae45c7402014-08-17 16:31:39 +00001014
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001015 uint64_t Start = Symbols[si].first - SectionAddr;
1016 // The end is either the section end or the beginning of the next
1017 // symbol.
1018 uint64_t End =
1019 (si == se - 1) ? SectSize : Symbols[si + 1].first - SectionAddr;
1020 // Don't try to disassemble beyond the end of section contents.
1021 if (End > SectSize)
1022 End = SectSize;
Rafael Espindolae45c7402014-08-17 16:31:39 +00001023 // If this symbol has the same address as the next symbol, then skip it.
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001024 if (Start >= End)
Michael J. Spenceree84f642011-10-13 20:37:08 +00001025 continue;
1026
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001027 outs() << '\n' << Symbols[si].second << ":\n";
Michael J. Spencer2670c252011-01-20 06:39:06 +00001028
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001029#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +00001030 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001031#else
Mark Seaborneb03ac52014-01-25 00:32:01 +00001032 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001033#endif
1034
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001035 for (Index = Start; Index < End; Index += Size) {
1036 MCInst Inst;
Owen Andersona0c3b972011-09-15 23:38:46 +00001037
Davide Italianof0706882015-10-01 21:57:09 +00001038 // AArch64 ELF binaries can interleave data and text in the
1039 // same section. We rely on the markers introduced to
1040 // understand what we need to dump.
1041 if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
1042 uint64_t Stride = 0;
1043
1044 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1045 DataMappingSymsAddr.end(), Index);
1046 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1047 // Switch to data.
1048 while (Index < End) {
1049 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1050 outs() << "\t";
1051 if (Index + 4 <= End) {
1052 Stride = 4;
1053 dumpBytes(Bytes.slice(Index, 4), outs());
1054 outs() << "\t.word";
1055 } else if (Index + 2 <= End) {
1056 Stride = 2;
1057 dumpBytes(Bytes.slice(Index, 2), outs());
1058 outs() << "\t.short";
1059 } else {
1060 Stride = 1;
1061 dumpBytes(Bytes.slice(Index, 1), outs());
1062 outs() << "\t.byte";
1063 }
1064 Index += Stride;
1065 outs() << "\n";
1066 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1067 TextMappingSymsAddr.end(), Index);
1068 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1069 break;
1070 }
1071 }
1072 }
1073
1074 if (Index >= End)
1075 break;
1076
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001077 if (DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1078 SectionAddr + Index, DebugOut,
1079 CommentStream)) {
Colin LeMahieu68d967d2015-05-29 14:44:13 +00001080 PIP.printInst(*IP, &Inst,
Colin LeMahieufb76b002015-05-28 19:07:14 +00001081 Bytes.slice(Index, Size),
1082 SectionAddr + Index, outs(), "", *STI);
Alp Tokere69170a2014-06-26 22:52:05 +00001083 outs() << CommentStream.str();
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001084 Comments.clear();
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001085
1086 // Try to resolve the target of a call, tail call, etc. to a specific
1087 // symbol.
David Majnemer2603a8fa2015-07-09 18:11:40 +00001088 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1089 MIA->isConditionalBranch(Inst))) {
David Majnemer81afca62015-07-07 22:06:59 +00001090 uint64_t Target;
1091 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001092 // In a relocatable object, the target's section must reside in
1093 // the same section as the call instruction or it is accessed
1094 // through a relocation.
1095 //
1096 // In a non-relocatable object, the target may be in any section.
1097 //
1098 // N.B. We don't walk the relocations in the relocatable case yet.
1099 auto *TargetSectionSymbols = &Symbols;
1100 if (!Obj->isRelocatableObject()) {
1101 auto SectionAddress = std::upper_bound(
1102 SectionAddresses.begin(), SectionAddresses.end(), Target,
1103 [](uint64_t LHS,
1104 const std::pair<uint64_t, SectionRef> &RHS) {
1105 return LHS < RHS.first;
1106 });
1107 if (SectionAddress != SectionAddresses.begin()) {
1108 --SectionAddress;
1109 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1110 } else {
1111 TargetSectionSymbols = nullptr;
1112 }
1113 }
David Majnemer2603a8fa2015-07-09 18:11:40 +00001114
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001115 // Find the first symbol in the section whose offset is less than
1116 // or equal to the target.
1117 if (TargetSectionSymbols) {
1118 auto TargetSym = std::upper_bound(
1119 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1120 Target, [](uint64_t LHS,
1121 const std::pair<uint64_t, StringRef> &RHS) {
1122 return LHS < RHS.first;
1123 });
David Majnemer153722d2015-11-18 04:35:32 +00001124 if (TargetSym != TargetSectionSymbols->begin()) {
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001125 --TargetSym;
1126 uint64_t TargetAddress = std::get<0>(*TargetSym);
1127 StringRef TargetName = std::get<1>(*TargetSym);
1128 outs() << " <" << TargetName;
1129 uint64_t Disp = Target - TargetAddress;
1130 if (Disp)
1131 outs() << '+' << utohexstr(Disp);
1132 outs() << '>';
1133 }
David Majnemer81afca62015-07-07 22:06:59 +00001134 }
1135 }
1136 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001137 outs() << "\n";
1138 } else {
1139 errs() << ToolName << ": warning: invalid instruction encoding\n";
1140 if (Size == 0)
1141 Size = 1; // skip illegible bytes
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001142 }
Michael J. Spencer51862b32011-10-13 22:17:18 +00001143
1144 // Print relocation for instruction.
1145 while (rel_cur != rel_end) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001146 bool hidden = getHidden(*rel_cur);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001147 uint64_t addr = rel_cur->getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +00001148 SmallString<16> name;
1149 SmallString<32> val;
Owen Andersonfa3e5202011-10-25 20:35:53 +00001150
1151 // If this relocation is hidden, skip it.
Owen Andersonfa3e5202011-10-25 20:35:53 +00001152 if (hidden) goto skip_print_rel;
1153
Michael J. Spencer51862b32011-10-13 22:17:18 +00001154 // Stop when rel_cur's address is past the current instruction.
Owen Andersonf20e3e52011-10-25 20:15:39 +00001155 if (addr >= Index + Size) break;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001156 rel_cur->getTypeName(name);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001157 error(getRelocationValueString(*rel_cur, val));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001158 outs() << format(Fmt.data(), SectionAddr + addr) << name
Benjamin Kramer82803112012-03-10 02:04:38 +00001159 << "\t" << val << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001160
1161 skip_print_rel:
1162 ++rel_cur;
1163 }
Benjamin Kramer87ee76c2011-07-20 19:37:35 +00001164 }
Michael J. Spencer2670c252011-01-20 06:39:06 +00001165 }
1166 }
1167}
1168
Kevin Enderby98da6132015-01-20 21:47:46 +00001169void llvm::PrintRelocations(const ObjectFile *Obj) {
Greg Fitzgerald18432272014-03-20 22:55:15 +00001170 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1171 "%08" PRIx64;
Rafael Espindolac66d7612014-08-17 19:09:37 +00001172 // Regular objdump doesn't print relocations in non-relocatable object
1173 // files.
1174 if (!Obj->isRelocatableObject())
1175 return;
1176
Colin LeMahieu77804be2015-07-29 15:45:39 +00001177 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001178 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001179 continue;
1180 StringRef secname;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001181 error(Section.getName(secname));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001182 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001183 for (const RelocationRef &Reloc : Section.relocations()) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001184 bool hidden = getHidden(Reloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001185 uint64_t address = Reloc.getOffset();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001186 SmallString<32> relocname;
1187 SmallString<32> valuestr;
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001188 if (hidden)
1189 continue;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001190 Reloc.getTypeName(relocname);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001191 error(getRelocationValueString(Reloc, valuestr));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001192 outs() << format(Fmt.data(), address) << " " << relocname << " "
1193 << valuestr << "\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001194 }
1195 outs() << "\n";
1196 }
1197}
1198
Kevin Enderby98da6132015-01-20 21:47:46 +00001199void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001200 outs() << "Sections:\n"
1201 "Idx Name Size Address Type\n";
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001202 unsigned i = 0;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001203 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001204 StringRef Name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001205 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001206 uint64_t Address = Section.getAddress();
1207 uint64_t Size = Section.getSize();
1208 bool Text = Section.isText();
1209 bool Data = Section.isData();
1210 bool BSS = Section.isBSS();
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001211 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +00001212 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
Alexey Samsonov48803e52014-03-13 14:37:36 +00001213 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1214 Name.str().c_str(), Size, Address, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001215 ++i;
1216 }
1217}
1218
Kevin Enderby98da6132015-01-20 21:47:46 +00001219void llvm::PrintSectionContents(const ObjectFile *Obj) {
Rafael Espindola4453e42942014-06-13 03:07:50 +00001220 std::error_code EC;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001221 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001222 StringRef Name;
1223 StringRef Contents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001224 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001225 uint64_t BaseAddr = Section.getAddress();
David Majnemer185b5b12014-11-11 09:58:25 +00001226 uint64_t Size = Section.getSize();
1227 if (!Size)
1228 continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001229
1230 outs() << "Contents of section " << Name << ":\n";
David Majnemer185b5b12014-11-11 09:58:25 +00001231 if (Section.isBSS()) {
Alexey Samsonov209095c2013-04-16 10:53:11 +00001232 outs() << format("<skipping contents of bss section at [%04" PRIx64
David Majnemer8f6b04c2014-07-14 16:20:14 +00001233 ", %04" PRIx64 ")>\n",
1234 BaseAddr, BaseAddr + Size);
Alexey Samsonov209095c2013-04-16 10:53:11 +00001235 continue;
1236 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001237
Davide Italianoccd53fe2015-08-05 07:18:31 +00001238 error(Section.getContents(Contents));
David Majnemer8f6b04c2014-07-14 16:20:14 +00001239
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001240 // Dump out the content as hex and printable ascii characters.
1241 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer82803112012-03-10 02:04:38 +00001242 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001243 // Dump line of hex.
1244 for (std::size_t i = 0; i < 16; ++i) {
1245 if (i != 0 && i % 4 == 0)
1246 outs() << ' ';
1247 if (addr + i < end)
1248 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1249 << hexdigit(Contents[addr + i] & 0xF, true);
1250 else
1251 outs() << " ";
1252 }
1253 // Print ascii.
1254 outs() << " ";
1255 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
Guy Benyei83c74e92013-02-12 21:21:59 +00001256 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001257 outs() << Contents[addr + i];
1258 else
1259 outs() << ".";
1260 }
1261 outs() << "\n";
1262 }
1263 }
1264}
1265
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001266static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
David Majnemer44f51e52014-09-10 12:51:52 +00001267 for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
1268 ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI);
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001269 StringRef Name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001270 error(Symbol.getError());
1271 error(coff->getSymbolName(*Symbol, Name));
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001272
1273 outs() << "[" << format("%2d", SI) << "]"
David Majnemer44f51e52014-09-10 12:51:52 +00001274 << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001275 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
David Majnemer44f51e52014-09-10 12:51:52 +00001276 << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
1277 << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") "
1278 << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
1279 << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001280 << Name << "\n";
1281
David Majnemer44f51e52014-09-10 12:51:52 +00001282 for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001283 if (Symbol->isSectionDefinition()) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001284 const coff_aux_section_definition *asd;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001285 error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd));
Saleem Abdulrasool9ede5c72014-04-13 03:11:08 +00001286
David Majnemer4d571592014-09-15 19:42:42 +00001287 int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
1288
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001289 outs() << "AUX "
1290 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
1291 , unsigned(asd->Length)
1292 , unsigned(asd->NumberOfRelocations)
1293 , unsigned(asd->NumberOfLinenumbers)
1294 , unsigned(asd->CheckSum))
1295 << format("assoc %d comdat %d\n"
David Majnemer4d571592014-09-15 19:42:42 +00001296 , unsigned(AuxNumber)
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001297 , unsigned(asd->Selection));
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001298 } else if (Symbol->isFileRecord()) {
David Majnemer44f51e52014-09-10 12:51:52 +00001299 const char *FileName;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001300 error(coff->getAuxSymbol<char>(SI + 1, FileName));
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +00001301
David Majnemer44f51e52014-09-10 12:51:52 +00001302 StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
1303 coff->getSymbolTableEntrySize());
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +00001304 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
Saleem Abdulrasool13a3f692014-04-14 16:38:25 +00001305
David Majnemer44f51e52014-09-10 12:51:52 +00001306 SI = SI + Symbol->getNumberOfAuxSymbols();
Saleem Abdulrasool13a3f692014-04-14 16:38:25 +00001307 break;
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +00001308 } else {
1309 outs() << "AUX Unknown\n";
Saleem Abdulrasool9ede5c72014-04-13 03:11:08 +00001310 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001311 }
1312 }
1313}
1314
Kevin Enderby98da6132015-01-20 21:47:46 +00001315void llvm::PrintSymbolTable(const ObjectFile *o) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001316 outs() << "SYMBOL TABLE:\n";
1317
Rui Ueyama4e39f712014-03-18 18:58:51 +00001318 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001319 PrintCOFFSymbolTable(coff);
Rui Ueyama4e39f712014-03-18 18:58:51 +00001320 return;
1321 }
1322 for (const SymbolRef &Symbol : o->symbols()) {
Rafael Espindolaed067c42015-07-03 18:19:00 +00001323 ErrorOr<uint64_t> AddressOrError = Symbol.getAddress();
Davide Italianoccd53fe2015-08-05 07:18:31 +00001324 error(AddressOrError.getError());
Rafael Espindolaed067c42015-07-03 18:19:00 +00001325 uint64_t Address = *AddressOrError;
Rafael Espindola2fa80cc2015-06-26 12:18:49 +00001326 SymbolRef::Type Type = Symbol.getType();
Rui Ueyama4e39f712014-03-18 18:58:51 +00001327 uint32_t Flags = Symbol.getFlags();
Rafael Espindola8bab8892015-08-07 23:27:14 +00001328 ErrorOr<section_iterator> SectionOrErr = Symbol.getSection();
1329 error(SectionOrErr.getError());
1330 section_iterator Section = *SectionOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001331 StringRef Name;
1332 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1333 Section->getName(Name);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001334 } else {
1335 ErrorOr<StringRef> NameOrErr = Symbol.getName();
Davide Italianoccd53fe2015-08-05 07:18:31 +00001336 error(NameOrErr.getError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001337 Name = *NameOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001338 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001339
Rui Ueyama4e39f712014-03-18 18:58:51 +00001340 bool Global = Flags & SymbolRef::SF_Global;
1341 bool Weak = Flags & SymbolRef::SF_Weak;
1342 bool Absolute = Flags & SymbolRef::SF_Absolute;
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001343 bool Common = Flags & SymbolRef::SF_Common;
Davide Italianocd2514d2015-04-30 23:08:53 +00001344 bool Hidden = Flags & SymbolRef::SF_Hidden;
David Meyer1df4b842012-02-28 23:47:53 +00001345
Rui Ueyama4e39f712014-03-18 18:58:51 +00001346 char GlobLoc = ' ';
1347 if (Type != SymbolRef::ST_Unknown)
1348 GlobLoc = Global ? 'g' : 'l';
1349 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1350 ? 'd' : ' ';
1351 char FileFunc = ' ';
1352 if (Type == SymbolRef::ST_File)
1353 FileFunc = 'f';
1354 else if (Type == SymbolRef::ST_Function)
1355 FileFunc = 'F';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001356
Rui Ueyama4e39f712014-03-18 18:58:51 +00001357 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1358 "%08" PRIx64;
Michael J. Spencerd857c1c2013-01-10 22:40:50 +00001359
Rui Ueyama4e39f712014-03-18 18:58:51 +00001360 outs() << format(Fmt, Address) << " "
1361 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1362 << (Weak ? 'w' : ' ') // Weak?
1363 << ' ' // Constructor. Not supported yet.
1364 << ' ' // Warning. Not supported yet.
1365 << ' ' // Indirect reference to another symbol.
1366 << Debug // Debugging (d) or dynamic (D) symbol.
1367 << FileFunc // Name of function (F), file (f) or object (O).
1368 << ' ';
1369 if (Absolute) {
1370 outs() << "*ABS*";
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001371 } else if (Common) {
1372 outs() << "*COM*";
Rui Ueyama4e39f712014-03-18 18:58:51 +00001373 } else if (Section == o->section_end()) {
1374 outs() << "*UND*";
1375 } else {
1376 if (const MachOObjectFile *MachO =
1377 dyn_cast<const MachOObjectFile>(o)) {
1378 DataRefImpl DR = Section->getRawDataRefImpl();
1379 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1380 outs() << SegmentName << ",";
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001381 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00001382 StringRef SectionName;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001383 error(Section->getName(SectionName));
Rui Ueyama4e39f712014-03-18 18:58:51 +00001384 outs() << SectionName;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001385 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001386
1387 outs() << '\t';
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001388 if (Common || isa<ELFObjectFileBase>(o)) {
Rafael Espindoladbb6bd32015-06-25 22:10:04 +00001389 uint64_t Val =
1390 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001391 outs() << format("\t %08" PRIx64 " ", Val);
1392 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001393
Davide Italianocd2514d2015-04-30 23:08:53 +00001394 if (Hidden) {
1395 outs() << ".hidden ";
1396 }
1397 outs() << Name
Rui Ueyama4e39f712014-03-18 18:58:51 +00001398 << '\n';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001399 }
1400}
1401
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001402static void PrintUnwindInfo(const ObjectFile *o) {
1403 outs() << "Unwind info:\n\n";
1404
1405 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1406 printCOFFUnwindInfo(coff);
Tim Northover4bd286a2014-08-01 13:07:19 +00001407 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1408 printMachOUnwindInfo(MachO);
1409 else {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001410 // TODO: Extract DWARF dump tool to objdump.
1411 errs() << "This operation is only currently supported "
Tim Northover4bd286a2014-08-01 13:07:19 +00001412 "for COFF and MachO object files.\n";
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001413 return;
1414 }
1415}
1416
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001417void llvm::printExportsTrie(const ObjectFile *o) {
Nick Kledzikd04bc352014-08-30 00:20:14 +00001418 outs() << "Exports trie:\n";
1419 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1420 printMachOExportsTrie(MachO);
1421 else {
1422 errs() << "This operation is only currently supported "
1423 "for Mach-O executable files.\n";
1424 return;
1425 }
1426}
1427
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001428void llvm::printRebaseTable(const ObjectFile *o) {
Nick Kledzikac431442014-09-12 21:34:15 +00001429 outs() << "Rebase table:\n";
1430 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1431 printMachORebaseTable(MachO);
1432 else {
1433 errs() << "This operation is only currently supported "
1434 "for Mach-O executable files.\n";
1435 return;
1436 }
1437}
1438
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001439void llvm::printBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001440 outs() << "Bind table:\n";
1441 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1442 printMachOBindTable(MachO);
1443 else {
1444 errs() << "This operation is only currently supported "
1445 "for Mach-O executable files.\n";
1446 return;
1447 }
1448}
1449
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001450void llvm::printLazyBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001451 outs() << "Lazy bind table:\n";
1452 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1453 printMachOLazyBindTable(MachO);
1454 else {
1455 errs() << "This operation is only currently supported "
1456 "for Mach-O executable files.\n";
1457 return;
1458 }
1459}
1460
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001461void llvm::printWeakBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001462 outs() << "Weak bind table:\n";
1463 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1464 printMachOWeakBindTable(MachO);
1465 else {
1466 errs() << "This operation is only currently supported "
1467 "for Mach-O executable files.\n";
1468 return;
1469 }
1470}
Nick Kledzikac431442014-09-12 21:34:15 +00001471
Adrian Prantl437105a2015-07-08 02:04:15 +00001472/// Dump the raw contents of the __clangast section so the output can be piped
1473/// into llvm-bcanalyzer.
1474void llvm::printRawClangAST(const ObjectFile *Obj) {
1475 if (outs().is_displayed()) {
1476 errs() << "The -raw-clang-ast option will dump the raw binary contents of "
1477 "the clang ast section.\n"
1478 "Please redirect the output to a file or another program such as "
1479 "llvm-bcanalyzer.\n";
1480 return;
1481 }
1482
1483 StringRef ClangASTSectionName("__clangast");
1484 if (isa<COFFObjectFile>(Obj)) {
1485 ClangASTSectionName = "clangast";
1486 }
1487
1488 Optional<object::SectionRef> ClangASTSection;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001489 for (auto Sec : ToolSectionFilter(*Obj)) {
Adrian Prantl437105a2015-07-08 02:04:15 +00001490 StringRef Name;
1491 Sec.getName(Name);
1492 if (Name == ClangASTSectionName) {
1493 ClangASTSection = Sec;
1494 break;
1495 }
1496 }
1497 if (!ClangASTSection)
1498 return;
1499
1500 StringRef ClangASTContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001501 error(ClangASTSection.getValue().getContents(ClangASTContents));
Adrian Prantl437105a2015-07-08 02:04:15 +00001502 outs().write(ClangASTContents.data(), ClangASTContents.size());
1503}
1504
Sanjoy Das6f567a42015-06-22 18:03:02 +00001505static void printFaultMaps(const ObjectFile *Obj) {
1506 const char *FaultMapSectionName = nullptr;
1507
1508 if (isa<ELFObjectFileBase>(Obj)) {
1509 FaultMapSectionName = ".llvm_faultmaps";
1510 } else if (isa<MachOObjectFile>(Obj)) {
1511 FaultMapSectionName = "__llvm_faultmaps";
1512 } else {
1513 errs() << "This operation is only currently supported "
1514 "for ELF and Mach-O executable files.\n";
1515 return;
1516 }
1517
1518 Optional<object::SectionRef> FaultMapSection;
1519
Colin LeMahieu77804be2015-07-29 15:45:39 +00001520 for (auto Sec : ToolSectionFilter(*Obj)) {
Sanjoy Das6f567a42015-06-22 18:03:02 +00001521 StringRef Name;
1522 Sec.getName(Name);
1523 if (Name == FaultMapSectionName) {
1524 FaultMapSection = Sec;
1525 break;
1526 }
1527 }
1528
1529 outs() << "FaultMap table:\n";
1530
1531 if (!FaultMapSection.hasValue()) {
1532 outs() << "<not found>\n";
1533 return;
1534 }
1535
1536 StringRef FaultMapContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001537 error(FaultMapSection.getValue().getContents(FaultMapContents));
Sanjoy Das6f567a42015-06-22 18:03:02 +00001538
1539 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1540 FaultMapContents.bytes_end());
1541
1542 outs() << FMP;
1543}
1544
Rui Ueyamac2bed422013-09-27 21:04:00 +00001545static void printPrivateFileHeader(const ObjectFile *o) {
1546 if (o->isELF()) {
1547 printELFFileHeader(o);
1548 } else if (o->isCOFF()) {
1549 printCOFFFileHeader(o);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00001550 } else if (o->isMachO()) {
1551 printMachOFileHeader(o);
Rui Ueyamac2bed422013-09-27 21:04:00 +00001552 }
1553}
1554
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001555static void DumpObject(const ObjectFile *o) {
Adrian Prantl437105a2015-07-08 02:04:15 +00001556 // Avoid other output when using a raw option.
1557 if (!RawClangAST) {
1558 outs() << '\n';
1559 outs() << o->getFileName()
1560 << ":\tfile format " << o->getFileFormatName() << "\n\n";
1561 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001562
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001563 if (Disassemble)
Michael J. Spencer51862b32011-10-13 22:17:18 +00001564 DisassembleObject(o, Relocations);
1565 if (Relocations && !Disassemble)
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001566 PrintRelocations(o);
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001567 if (SectionHeaders)
1568 PrintSectionHeaders(o);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001569 if (SectionContents)
1570 PrintSectionContents(o);
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001571 if (SymbolTable)
1572 PrintSymbolTable(o);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001573 if (UnwindInfo)
1574 PrintUnwindInfo(o);
Rui Ueyamac2bed422013-09-27 21:04:00 +00001575 if (PrivateHeaders)
1576 printPrivateFileHeader(o);
Nick Kledzikd04bc352014-08-30 00:20:14 +00001577 if (ExportsTrie)
1578 printExportsTrie(o);
Nick Kledzikac431442014-09-12 21:34:15 +00001579 if (Rebase)
1580 printRebaseTable(o);
Nick Kledzik56ebef42014-09-16 01:41:51 +00001581 if (Bind)
1582 printBindTable(o);
1583 if (LazyBind)
1584 printLazyBindTable(o);
1585 if (WeakBind)
1586 printWeakBindTable(o);
Adrian Prantl437105a2015-07-08 02:04:15 +00001587 if (RawClangAST)
1588 printRawClangAST(o);
Sanjoy Das6f567a42015-06-22 18:03:02 +00001589 if (PrintFaultMaps)
1590 printFaultMaps(o);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001591}
1592
1593/// @brief Dump each object file in \a a;
1594static void DumpArchive(const Archive *a) {
Kevin Enderby7a969422015-11-05 19:24:56 +00001595 for (auto &ErrorOrChild : a->children()) {
1596 if (std::error_code EC = ErrorOrChild.getError())
1597 report_error(a->getFileName(), EC);
1598 const Archive::Child &C = *ErrorOrChild;
Davide Italiano95dd3cb2015-08-03 21:46:32 +00001599 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Davide Italianoccd53fe2015-08-05 07:18:31 +00001600 if (std::error_code EC = ChildOrErr.getError())
Mark Seaborneb03ac52014-01-25 00:32:01 +00001601 if (EC != object_error::invalid_file_type)
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001602 report_error(a->getFileName(), EC);
Rafael Espindolaae460022014-06-16 16:08:36 +00001603 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001604 DumpObject(o);
1605 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001606 report_error(a->getFileName(), object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001607 }
1608}
1609
1610/// @brief Open file and figure out how to dump it.
1611static void DumpInput(StringRef file) {
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001612
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001613 // If we are using the Mach-O specific object file parser, then let it parse
1614 // the file and process the command line options. So the -arch flags can
1615 // be used to select specific slices, etc.
1616 if (MachOOpt) {
1617 ParseInputMachO(file);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001618 return;
1619 }
1620
1621 // Attempt to open the binary.
Rafael Espindola48af1c22014-08-19 18:44:46 +00001622 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001623 if (std::error_code EC = BinaryOrErr.getError())
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001624 report_error(file, EC);
Rafael Espindola48af1c22014-08-19 18:44:46 +00001625 Binary &Binary = *BinaryOrErr.get().getBinary();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001626
Rafael Espindola3f6481d2014-08-01 14:31:55 +00001627 if (Archive *a = dyn_cast<Archive>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001628 DumpArchive(a);
Rafael Espindola3f6481d2014-08-01 14:31:55 +00001629 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001630 DumpObject(o);
Jim Grosbachaf9aec02012-08-07 17:53:14 +00001631 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001632 report_error(file, object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001633}
1634
Michael J. Spencer2670c252011-01-20 06:39:06 +00001635int main(int argc, char **argv) {
1636 // Print a stack trace if we signal out.
1637 sys::PrintStackTraceOnErrorSignal();
1638 PrettyStackTraceProgram X(argc, argv);
1639 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1640
1641 // Initialize targets and assembly printers/parsers.
1642 llvm::InitializeAllTargetInfos();
Evan Cheng8c886a42011-07-22 21:58:54 +00001643 llvm::InitializeAllTargetMCs();
Michael J. Spencer2670c252011-01-20 06:39:06 +00001644 llvm::InitializeAllDisassemblers();
1645
Pete Cooper28fb4fc2012-05-03 23:20:10 +00001646 // Register the target printer for --version.
1647 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
1648
Michael J. Spencer2670c252011-01-20 06:39:06 +00001649 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
1650 TripleName = Triple::normalize(TripleName);
1651
1652 ToolName = argv[0];
1653
1654 // Defaults to a.out if no filenames specified.
1655 if (InputFilenames.size() == 0)
1656 InputFilenames.push_back("a.out");
1657
Colin LeMahieuf34933e2015-07-23 20:58:49 +00001658 if (DisassembleAll)
1659 Disassemble = true;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001660 if (!Disassemble
1661 && !Relocations
1662 && !SectionHeaders
1663 && !SectionContents
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001664 && !SymbolTable
Michael J. Spencer209565db2013-01-06 03:56:49 +00001665 && !UnwindInfo
Nick Kledzikd04bc352014-08-30 00:20:14 +00001666 && !PrivateHeaders
Nick Kledzikac431442014-09-12 21:34:15 +00001667 && !ExportsTrie
Nick Kledzik56ebef42014-09-16 01:41:51 +00001668 && !Rebase
1669 && !Bind
1670 && !LazyBind
Kevin Enderby131d1772015-01-09 19:22:37 +00001671 && !WeakBind
Adrian Prantl437105a2015-07-08 02:04:15 +00001672 && !RawClangAST
Kevin Enderby13023a12015-01-15 23:19:11 +00001673 && !(UniversalHeaders && MachOOpt)
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001674 && !(ArchiveHeaders && MachOOpt)
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001675 && !(IndirectSymbols && MachOOpt)
Kevin Enderby9a509442015-01-27 21:28:24 +00001676 && !(DataInCode && MachOOpt)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001677 && !(LinkOptHints && MachOOpt)
Kevin Enderbycd66be52015-03-11 22:06:32 +00001678 && !(InfoPlist && MachOOpt)
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001679 && !(DylibsUsed && MachOOpt)
1680 && !(DylibId && MachOOpt)
Kevin Enderby0fc11822015-04-01 20:57:01 +00001681 && !(ObjcMetaData && MachOOpt)
Colin LeMahieufcc32762015-07-29 19:08:10 +00001682 && !(FilterSections.size() != 0 && MachOOpt)
Sanjoy Das6f567a42015-06-22 18:03:02 +00001683 && !PrintFaultMaps) {
Michael J. Spencer2670c252011-01-20 06:39:06 +00001684 cl::PrintHelpMessage();
1685 return 2;
1686 }
1687
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001688 std::for_each(InputFilenames.begin(), InputFilenames.end(),
1689 DumpInput);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001690
Davide Italianoccd53fe2015-08-05 07:18:31 +00001691 return EXIT_SUCCESS;
Michael J. Spencer2670c252011-01-20 06:39:06 +00001692}