blob: df6e2a45862c2d57e42fd80488625b19f8962e97 [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
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000255static void report_error(StringRef File, std::error_code EC) {
256 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);
285 if (!TheTarget) {
286 errs() << ToolName << ": " << Error;
Craig Toppere6cb63e2014-04-25 04:24:47 +0000287 return nullptr;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000288 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000289
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000290 // Update the triple name and return the found target.
291 TripleName = TheTriple.getTriple();
292 return TheTarget;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000293}
294
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000295bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
Rafael Espindola704cd842015-07-06 15:47:43 +0000296 return a.getOffset() < b.getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +0000297}
298
Colin LeMahieufb76b002015-05-28 19:07:14 +0000299namespace {
300class PrettyPrinter {
301public:
Colin LeMahieu0b5890d2015-05-28 20:59:08 +0000302 virtual ~PrettyPrinter(){}
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000303 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
Colin LeMahieufb76b002015-05-28 19:07:14 +0000304 ArrayRef<uint8_t> Bytes, uint64_t Address,
305 raw_ostream &OS, StringRef Annot,
306 MCSubtargetInfo const &STI) {
307 outs() << format("%8" PRIx64 ":", Address);
308 if (!NoShowRawInsn) {
309 outs() << "\t";
310 dumpBytes(Bytes, outs());
311 }
312 IP.printInst(MI, outs(), "", STI);
313 }
314};
315PrettyPrinter PrettyPrinterInst;
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000316class HexagonPrettyPrinter : public PrettyPrinter {
317public:
318 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
319 raw_ostream &OS) {
320 uint32_t opcode =
321 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
322 OS << format("%8" PRIx64 ":", Address);
323 if (!NoShowRawInsn) {
324 OS << "\t";
325 dumpBytes(Bytes.slice(0, 4), OS);
326 OS << format("%08" PRIx32, opcode);
327 }
328 }
329 void printInst(MCInstPrinter &IP, const MCInst *MI,
330 ArrayRef<uint8_t> Bytes, uint64_t Address,
331 raw_ostream &OS, StringRef Annot,
332 MCSubtargetInfo const &STI) override {
333 std::string Buffer;
334 {
335 raw_string_ostream TempStream(Buffer);
336 IP.printInst(MI, TempStream, "", STI);
337 }
338 StringRef Contents(Buffer);
339 // Split off bundle attributes
340 auto PacketBundle = Contents.rsplit('\n');
341 // Split off first instruction from the rest
342 auto HeadTail = PacketBundle.first.split('\n');
343 auto Preamble = " { ";
344 auto Separator = "";
345 while(!HeadTail.first.empty()) {
346 OS << Separator;
347 Separator = "\n";
348 printLead(Bytes, Address, OS);
349 OS << Preamble;
350 Preamble = " ";
351 StringRef Inst;
352 auto Duplex = HeadTail.first.split('\v');
353 if(!Duplex.second.empty()){
354 OS << Duplex.first;
355 OS << "; ";
356 Inst = Duplex.second;
357 }
358 else
359 Inst = HeadTail.first;
360 OS << Inst;
361 Bytes = Bytes.slice(4);
362 Address += 4;
363 HeadTail = HeadTail.second.split('\n');
364 }
365 OS << " } " << PacketBundle.second;
366 }
367};
368HexagonPrettyPrinter HexagonPrettyPrinterInst;
Colin LeMahieu35436a22015-05-29 14:48:25 +0000369PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000370 switch(Triple.getArch()) {
371 default:
372 return PrettyPrinterInst;
373 case Triple::hexagon:
374 return HexagonPrettyPrinterInst;
375 }
Colin LeMahieufb76b002015-05-28 19:07:14 +0000376}
377}
378
Rafael Espindola37070a52015-06-03 04:48:06 +0000379template <class ELFT>
Rafael Espindola37070a52015-06-03 04:48:06 +0000380static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000381 const RelocationRef &RelRef,
Rafael Espindola37070a52015-06-03 04:48:06 +0000382 SmallVectorImpl<char> &Result) {
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000383 DataRefImpl Rel = RelRef.getRawDataRefImpl();
384
Rafael Espindola37070a52015-06-03 04:48:06 +0000385 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
386 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000387 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
388
Rafael Espindola37070a52015-06-03 04:48:06 +0000389 const ELFFile<ELFT> &EF = *Obj->getELFFile();
390
Rafael Espindola6def3042015-07-01 12:56:27 +0000391 ErrorOr<const Elf_Shdr *> SecOrErr = EF.getSection(Rel.d.a);
392 if (std::error_code EC = SecOrErr.getError())
393 return EC;
394 const Elf_Shdr *Sec = *SecOrErr;
395 ErrorOr<const Elf_Shdr *> SymTabOrErr = EF.getSection(Sec->sh_link);
396 if (std::error_code EC = SymTabOrErr.getError())
397 return EC;
398 const Elf_Shdr *SymTab = *SymTabOrErr;
Rafael Espindola719dc7c2015-06-29 12:38:31 +0000399 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
400 SymTab->sh_type == ELF::SHT_DYNSYM);
Rafael Espindola6def3042015-07-01 12:56:27 +0000401 ErrorOr<const Elf_Shdr *> StrTabSec = EF.getSection(SymTab->sh_link);
402 if (std::error_code EC = StrTabSec.getError())
403 return EC;
404 ErrorOr<StringRef> StrTabOrErr = EF.getStringTable(*StrTabSec);
Rafael Espindola6a1bfb22015-06-29 14:39:25 +0000405 if (std::error_code EC = StrTabOrErr.getError())
406 return EC;
407 StringRef StrTab = *StrTabOrErr;
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000408 uint8_t type = RelRef.getType();
Rafael Espindola37070a52015-06-03 04:48:06 +0000409 StringRef res;
410 int64_t addend = 0;
Rafael Espindola6def3042015-07-01 12:56:27 +0000411 switch (Sec->sh_type) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000412 default:
413 return object_error::parse_failed;
414 case ELF::SHT_REL: {
Rafael Espindola37070a52015-06-03 04:48:06 +0000415 // TODO: Read implicit addend from section data.
416 break;
417 }
418 case ELF::SHT_RELA: {
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000419 const Elf_Rela *ERela = Obj->getRela(Rel);
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000420 addend = ERela->r_addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000421 break;
422 }
423 }
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000424 symbol_iterator SI = RelRef.getSymbol();
425 const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
Rafael Espindola75d5b542015-06-03 05:14:22 +0000426 StringRef Target;
Rafael Espindola75d5b542015-06-03 05:14:22 +0000427 if (symb->getType() == ELF::STT_SECTION) {
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000428 ErrorOr<section_iterator> SymSI = SI->getSection();
429 if (std::error_code EC = SymSI.getError())
430 return EC;
431 const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
432 ErrorOr<StringRef> SecName = EF.getSectionName(SymSec);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000433 if (std::error_code EC = SecName.getError())
434 return EC;
435 Target = *SecName;
436 } else {
Rafael Espindola44c28712015-06-29 21:24:55 +0000437 ErrorOr<StringRef> SymName = symb->getName(StrTab);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000438 if (!SymName)
439 return SymName.getError();
440 Target = *SymName;
441 }
Rafael Espindola37070a52015-06-03 04:48:06 +0000442 switch (EF.getHeader()->e_machine) {
443 case ELF::EM_X86_64:
444 switch (type) {
445 case ELF::R_X86_64_PC8:
446 case ELF::R_X86_64_PC16:
447 case ELF::R_X86_64_PC32: {
448 std::string fmtbuf;
449 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000450 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
Rafael Espindola37070a52015-06-03 04:48:06 +0000451 fmt.flush();
452 Result.append(fmtbuf.begin(), fmtbuf.end());
453 } break;
454 case ELF::R_X86_64_8:
455 case ELF::R_X86_64_16:
456 case ELF::R_X86_64_32:
457 case ELF::R_X86_64_32S:
458 case ELF::R_X86_64_64: {
459 std::string fmtbuf;
460 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000461 fmt << Target << (addend < 0 ? "" : "+") << addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000462 fmt.flush();
463 Result.append(fmtbuf.begin(), fmtbuf.end());
464 } break;
465 default:
466 res = "Unknown";
467 }
468 break;
469 case ELF::EM_AARCH64: {
470 std::string fmtbuf;
471 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000472 fmt << Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000473 if (addend != 0)
474 fmt << (addend < 0 ? "" : "+") << addend;
475 fmt.flush();
476 Result.append(fmtbuf.begin(), fmtbuf.end());
477 break;
478 }
479 case ELF::EM_386:
Michael Kupersteina3b79dd2015-11-04 11:21:50 +0000480 case ELF::EM_IAMCU:
Rafael Espindola37070a52015-06-03 04:48:06 +0000481 case ELF::EM_ARM:
482 case ELF::EM_HEXAGON:
483 case ELF::EM_MIPS:
Rafael Espindola75d5b542015-06-03 05:14:22 +0000484 res = Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000485 break;
486 default:
487 res = "Unknown";
488 }
489 if (Result.empty())
490 Result.append(res.begin(), res.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000491 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000492}
493
494static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000495 const RelocationRef &Rel,
Rafael Espindola37070a52015-06-03 04:48:06 +0000496 SmallVectorImpl<char> &Result) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000497 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
498 return getRelocationValueString(ELF32LE, Rel, Result);
499 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
500 return getRelocationValueString(ELF64LE, Rel, Result);
501 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
502 return getRelocationValueString(ELF32BE, Rel, Result);
503 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
504 return getRelocationValueString(ELF64BE, Rel, Result);
505}
506
507static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
508 const RelocationRef &Rel,
509 SmallVectorImpl<char> &Result) {
510 symbol_iterator SymI = Rel.getSymbol();
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000511 ErrorOr<StringRef> SymNameOrErr = SymI->getName();
512 if (std::error_code EC = SymNameOrErr.getError())
Rafael Espindola37070a52015-06-03 04:48:06 +0000513 return EC;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000514 StringRef SymName = *SymNameOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000515 Result.append(SymName.begin(), SymName.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000516 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000517}
518
519static void printRelocationTargetName(const MachOObjectFile *O,
520 const MachO::any_relocation_info &RE,
521 raw_string_ostream &fmt) {
522 bool IsScattered = O->isRelocationScattered(RE);
523
524 // Target of a scattered relocation is an address. In the interest of
525 // generating pretty output, scan through the symbol table looking for a
526 // symbol that aligns with that address. If we find one, print it.
527 // Otherwise, we just print the hex address of the target.
528 if (IsScattered) {
529 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
530
531 for (const SymbolRef &Symbol : O->symbols()) {
532 std::error_code ec;
Rafael Espindolaed067c42015-07-03 18:19:00 +0000533 ErrorOr<uint64_t> Addr = Symbol.getAddress();
534 if ((ec = Addr.getError()))
Rafael Espindola37070a52015-06-03 04:48:06 +0000535 report_fatal_error(ec.message());
Rafael Espindolaed067c42015-07-03 18:19:00 +0000536 if (*Addr != Val)
Rafael Espindola37070a52015-06-03 04:48:06 +0000537 continue;
Rafael Espindolaed067c42015-07-03 18:19:00 +0000538 ErrorOr<StringRef> Name = Symbol.getName();
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000539 if (std::error_code EC = Name.getError())
540 report_fatal_error(EC.message());
541 fmt << *Name;
Rafael Espindola37070a52015-06-03 04:48:06 +0000542 return;
543 }
544
545 // If we couldn't find a symbol that this relocation refers to, try
546 // to find a section beginning instead.
Colin LeMahieu77804be2015-07-29 15:45:39 +0000547 for (const SectionRef &Section : ToolSectionFilter(*O)) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000548 std::error_code ec;
549
550 StringRef Name;
551 uint64_t Addr = Section.getAddress();
552 if (Addr != Val)
553 continue;
554 if ((ec = Section.getName(Name)))
555 report_fatal_error(ec.message());
556 fmt << Name;
557 return;
558 }
559
560 fmt << format("0x%x", Val);
561 return;
562 }
563
564 StringRef S;
565 bool isExtern = O->getPlainRelocationExternal(RE);
566 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
567
568 if (isExtern) {
569 symbol_iterator SI = O->symbol_begin();
570 advance(SI, Val);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000571 ErrorOr<StringRef> SOrErr = SI->getName();
Davide Italianoccd53fe2015-08-05 07:18:31 +0000572 error(SOrErr.getError());
573 S = *SOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000574 } else {
575 section_iterator SI = O->section_begin();
576 // Adjust for the fact that sections are 1-indexed.
577 advance(SI, Val - 1);
578 SI->getName(S);
579 }
580
581 fmt << S;
582}
583
584static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
585 const RelocationRef &RelRef,
586 SmallVectorImpl<char> &Result) {
587 DataRefImpl Rel = RelRef.getRawDataRefImpl();
588 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
589
590 unsigned Arch = Obj->getArch();
591
592 std::string fmtbuf;
593 raw_string_ostream fmt(fmtbuf);
594 unsigned Type = Obj->getAnyRelocationType(RE);
595 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
596
597 // Determine any addends that should be displayed with the relocation.
598 // These require decoding the relocation type, which is triple-specific.
599
600 // X86_64 has entirely custom relocation types.
601 if (Arch == Triple::x86_64) {
602 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
603
604 switch (Type) {
605 case MachO::X86_64_RELOC_GOT_LOAD:
606 case MachO::X86_64_RELOC_GOT: {
607 printRelocationTargetName(Obj, RE, fmt);
608 fmt << "@GOT";
609 if (isPCRel)
610 fmt << "PCREL";
611 break;
612 }
613 case MachO::X86_64_RELOC_SUBTRACTOR: {
614 DataRefImpl RelNext = Rel;
615 Obj->moveRelocationNext(RelNext);
616 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
617
618 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
619 // X86_64_RELOC_UNSIGNED.
620 // NOTE: Scattered relocations don't exist on x86_64.
621 unsigned RType = Obj->getAnyRelocationType(RENext);
622 if (RType != MachO::X86_64_RELOC_UNSIGNED)
623 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
624 "X86_64_RELOC_SUBTRACTOR.");
625
626 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
627 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
628 printRelocationTargetName(Obj, RENext, fmt);
629 fmt << "-";
630 printRelocationTargetName(Obj, RE, fmt);
631 break;
632 }
633 case MachO::X86_64_RELOC_TLV:
634 printRelocationTargetName(Obj, RE, fmt);
635 fmt << "@TLV";
636 if (isPCRel)
637 fmt << "P";
638 break;
639 case MachO::X86_64_RELOC_SIGNED_1:
640 printRelocationTargetName(Obj, RE, fmt);
641 fmt << "-1";
642 break;
643 case MachO::X86_64_RELOC_SIGNED_2:
644 printRelocationTargetName(Obj, RE, fmt);
645 fmt << "-2";
646 break;
647 case MachO::X86_64_RELOC_SIGNED_4:
648 printRelocationTargetName(Obj, RE, fmt);
649 fmt << "-4";
650 break;
651 default:
652 printRelocationTargetName(Obj, RE, fmt);
653 break;
654 }
655 // X86 and ARM share some relocation types in common.
656 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
657 Arch == Triple::ppc) {
658 // Generic relocation types...
659 switch (Type) {
660 case MachO::GENERIC_RELOC_PAIR: // prints no info
Rui Ueyama7d099192015-06-09 15:20:42 +0000661 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000662 case MachO::GENERIC_RELOC_SECTDIFF: {
663 DataRefImpl RelNext = Rel;
664 Obj->moveRelocationNext(RelNext);
665 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
666
667 // X86 sect diff's must be followed by a relocation of type
668 // GENERIC_RELOC_PAIR.
669 unsigned RType = Obj->getAnyRelocationType(RENext);
670
671 if (RType != MachO::GENERIC_RELOC_PAIR)
672 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
673 "GENERIC_RELOC_SECTDIFF.");
674
675 printRelocationTargetName(Obj, RE, fmt);
676 fmt << "-";
677 printRelocationTargetName(Obj, RENext, fmt);
678 break;
679 }
680 }
681
682 if (Arch == Triple::x86 || Arch == Triple::ppc) {
683 switch (Type) {
684 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
685 DataRefImpl RelNext = Rel;
686 Obj->moveRelocationNext(RelNext);
687 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
688
689 // X86 sect diff's must be followed by a relocation of type
690 // GENERIC_RELOC_PAIR.
691 unsigned RType = Obj->getAnyRelocationType(RENext);
692 if (RType != MachO::GENERIC_RELOC_PAIR)
693 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
694 "GENERIC_RELOC_LOCAL_SECTDIFF.");
695
696 printRelocationTargetName(Obj, RE, fmt);
697 fmt << "-";
698 printRelocationTargetName(Obj, RENext, fmt);
699 break;
700 }
701 case MachO::GENERIC_RELOC_TLV: {
702 printRelocationTargetName(Obj, RE, fmt);
703 fmt << "@TLV";
704 if (IsPCRel)
705 fmt << "P";
706 break;
707 }
708 default:
709 printRelocationTargetName(Obj, RE, fmt);
710 }
711 } else { // ARM-specific relocations
712 switch (Type) {
713 case MachO::ARM_RELOC_HALF:
714 case MachO::ARM_RELOC_HALF_SECTDIFF: {
715 // Half relocations steal a bit from the length field to encode
716 // whether this is an upper16 or a lower16 relocation.
717 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
718
719 if (isUpper)
720 fmt << ":upper16:(";
721 else
722 fmt << ":lower16:(";
723 printRelocationTargetName(Obj, RE, fmt);
724
725 DataRefImpl RelNext = Rel;
726 Obj->moveRelocationNext(RelNext);
727 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
728
729 // ARM half relocs must be followed by a relocation of type
730 // ARM_RELOC_PAIR.
731 unsigned RType = Obj->getAnyRelocationType(RENext);
732 if (RType != MachO::ARM_RELOC_PAIR)
733 report_fatal_error("Expected ARM_RELOC_PAIR after "
734 "ARM_RELOC_HALF");
735
736 // NOTE: The half of the target virtual address is stashed in the
737 // address field of the secondary relocation, but we can't reverse
738 // engineer the constant offset from it without decoding the movw/movt
739 // instruction to find the other half in its immediate field.
740
741 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
742 // symbol/section pointer of the follow-on relocation.
743 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
744 fmt << "-";
745 printRelocationTargetName(Obj, RENext, fmt);
746 }
747
748 fmt << ")";
749 break;
750 }
751 default: { printRelocationTargetName(Obj, RE, fmt); }
752 }
753 }
754 } else
755 printRelocationTargetName(Obj, RE, fmt);
756
757 fmt.flush();
758 Result.append(fmtbuf.begin(), fmtbuf.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000759 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000760}
761
762static std::error_code getRelocationValueString(const RelocationRef &Rel,
763 SmallVectorImpl<char> &Result) {
Rafael Espindola854038e2015-06-26 14:51:16 +0000764 const ObjectFile *Obj = Rel.getObject();
Rafael Espindola37070a52015-06-03 04:48:06 +0000765 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
766 return getRelocationValueString(ELF, Rel, Result);
767 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
768 return getRelocationValueString(COFF, Rel, Result);
769 auto *MachO = cast<MachOObjectFile>(Obj);
770 return getRelocationValueString(MachO, Rel, Result);
771}
772
Rafael Espindola0ad71d92015-06-30 03:41:26 +0000773/// @brief Indicates whether this relocation should hidden when listing
774/// relocations, usually because it is the trailing part of a multipart
775/// relocation that will be printed as part of the leading relocation.
776static bool getHidden(RelocationRef RelRef) {
777 const ObjectFile *Obj = RelRef.getObject();
778 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
779 if (!MachO)
780 return false;
781
782 unsigned Arch = MachO->getArch();
783 DataRefImpl Rel = RelRef.getRawDataRefImpl();
784 uint64_t Type = MachO->getRelocationType(Rel);
785
786 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
787 // is always hidden.
788 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
789 if (Type == MachO::GENERIC_RELOC_PAIR)
790 return true;
791 } else if (Arch == Triple::x86_64) {
792 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
793 // an X86_64_RELOC_SUBTRACTOR.
794 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
795 DataRefImpl RelPrev = Rel;
796 RelPrev.d.a--;
797 uint64_t PrevType = MachO->getRelocationType(RelPrev);
798 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
799 return true;
800 }
801 }
802
803 return false;
804}
805
Michael J. Spencer51862b32011-10-13 22:17:18 +0000806static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Jim Grosbachaf9aec02012-08-07 17:53:14 +0000807 const Target *TheTarget = getTarget(Obj);
808 // getTarget() will have already issued a diagnostic if necessary, so
809 // just bail here if it failed.
810 if (!TheTarget)
Michael J. Spencer2670c252011-01-20 06:39:06 +0000811 return;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000812
Jack Carter551efd72012-08-28 19:24:49 +0000813 // Package up features to be passed to target/subtarget
814 std::string FeaturesStr;
815 if (MAttrs.size()) {
816 SubtargetFeatures Features;
817 for (unsigned i = 0; i != MAttrs.size(); ++i)
818 Features.AddFeature(MAttrs[i]);
819 FeaturesStr = Features.getString();
820 }
821
Ahmed Charles56440fd2014-03-06 05:51:42 +0000822 std::unique_ptr<const MCRegisterInfo> MRI(
823 TheTarget->createMCRegInfo(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000824 if (!MRI) {
825 errs() << "error: no register info for target " << TripleName << "\n";
826 return;
827 }
828
829 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000830 std::unique_ptr<const MCAsmInfo> AsmInfo(
831 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000832 if (!AsmInfo) {
833 errs() << "error: no assembly info for target " << TripleName << "\n";
834 return;
835 }
836
Ahmed Charles56440fd2014-03-06 05:51:42 +0000837 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +0000838 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000839 if (!STI) {
840 errs() << "error: no subtarget info for target " << TripleName << "\n";
841 return;
842 }
843
Ahmed Charles56440fd2014-03-06 05:51:42 +0000844 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000845 if (!MII) {
846 errs() << "error: no instruction info for target " << TripleName << "\n";
847 return;
848 }
849
Lang Hamesa1bc0f52014-04-15 04:40:56 +0000850 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
851 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
852
853 std::unique_ptr<MCDisassembler> DisAsm(
854 TheTarget->createMCDisassembler(*STI, Ctx));
855
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000856 if (!DisAsm) {
857 errs() << "error: no disassembler for target " << TripleName << "\n";
858 return;
859 }
860
Ahmed Charles56440fd2014-03-06 05:51:42 +0000861 std::unique_ptr<const MCInstrAnalysis> MIA(
862 TheTarget->createMCInstrAnalysis(MII.get()));
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000863
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000864 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Daniel Sanders50f17232015-09-15 16:17:27 +0000865 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
866 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000867 if (!IP) {
868 errs() << "error: no instruction printer for target " << TripleName
869 << '\n';
870 return;
871 }
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000872 IP->setPrintImmHex(PrintImmHex);
Colin LeMahieu35436a22015-05-29 14:48:25 +0000873 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000874
Greg Fitzgerald18432272014-03-20 22:55:15 +0000875 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
876 "\t\t\t%08" PRIx64 ": ";
877
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000878 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
879 // in RelocSecs contain the relocations for section S.
Rafael Espindola4453e42942014-06-13 03:07:50 +0000880 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000881 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
Colin LeMahieu77804be2015-07-29 15:45:39 +0000882 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +0000883 section_iterator Sec2 = Section.getRelocatedSection();
Rafael Espindolab5155a52014-02-10 20:24:04 +0000884 if (Sec2 != Obj->section_end())
Alexey Samsonov48803e52014-03-13 14:37:36 +0000885 SectionRelocMap[*Sec2].push_back(Section);
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000886 }
887
David Majnemer81afca62015-07-07 22:06:59 +0000888 // Create a mapping from virtual address to symbol name. This is used to
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000889 // pretty print the symbols while disassembling.
890 typedef std::vector<std::pair<uint64_t, StringRef>> SectionSymbolsTy;
891 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
892 for (const SymbolRef &Symbol : Obj->symbols()) {
893 ErrorOr<uint64_t> AddressOrErr = Symbol.getAddress();
894 error(AddressOrErr.getError());
895 uint64_t Address = *AddressOrErr;
David Majnemer2603a8fa2015-07-09 18:11:40 +0000896
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000897 ErrorOr<StringRef> Name = Symbol.getName();
898 error(Name.getError());
899 if (Name->empty())
900 continue;
David Majnemer81afca62015-07-07 22:06:59 +0000901
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000902 ErrorOr<section_iterator> SectionOrErr = Symbol.getSection();
903 error(SectionOrErr.getError());
904 section_iterator SecI = *SectionOrErr;
905 if (SecI == Obj->section_end())
906 continue;
David Majnemer81afca62015-07-07 22:06:59 +0000907
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000908 AllSymbols[*SecI].emplace_back(Address, *Name);
David Majnemer81afca62015-07-07 22:06:59 +0000909 }
910
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000911 // Create a mapping from virtual address to section.
912 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
913 for (SectionRef Sec : Obj->sections())
914 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
915 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
916
917 // Linked executables (.exe and .dll files) typically don't include a real
918 // symbol table but they might contain an export table.
919 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
920 for (const auto &ExportEntry : COFFObj->export_directories()) {
921 StringRef Name;
922 error(ExportEntry.getSymbolName(Name));
923 if (Name.empty())
924 continue;
925 uint32_t RVA;
926 error(ExportEntry.getExportRVA(RVA));
927
928 uint64_t VA = COFFObj->getImageBase() + RVA;
929 auto Sec = std::upper_bound(
930 SectionAddresses.begin(), SectionAddresses.end(), VA,
931 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
932 return LHS < RHS.first;
933 });
934 if (Sec != SectionAddresses.begin())
935 --Sec;
936 else
937 Sec = SectionAddresses.end();
938
939 if (Sec != SectionAddresses.end())
940 AllSymbols[Sec->second].emplace_back(VA, Name);
941 }
942 }
943
944 // Sort all the symbols, this allows us to use a simple binary search to find
945 // a symbol near an address.
946 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
947 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
948
Colin LeMahieu77804be2015-07-29 15:45:39 +0000949 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Colin LeMahieuf34933e2015-07-23 20:58:49 +0000950 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000951 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000952
Rafael Espindola80291272014-10-08 15:28:58 +0000953 uint64_t SectionAddr = Section.getAddress();
954 uint64_t SectSize = Section.getSize();
David Majnemer185b5b12014-11-11 09:58:25 +0000955 if (!SectSize)
956 continue;
Simon Atanasyan2b614e12014-02-24 22:12:11 +0000957
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000958 // Get the list of all the symbols in this section.
959 SectionSymbolsTy &Symbols = AllSymbols[Section];
Davide Italianof0706882015-10-01 21:57:09 +0000960 std::vector<uint64_t> DataMappingSymsAddr;
961 std::vector<uint64_t> TextMappingSymsAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000962 if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
963 for (const auto &Symb : Symbols) {
964 uint64_t Address = Symb.first;
965 StringRef Name = Symb.second;
966 if (Name.startswith("$d"))
967 DataMappingSymsAddr.push_back(Address);
968 if (Name.startswith("$x"))
969 TextMappingSymsAddr.push_back(Address);
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000970 }
971 }
972
Davide Italianof0706882015-10-01 21:57:09 +0000973 std::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end());
974 std::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end());
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000975
Michael J. Spencer51862b32011-10-13 22:17:18 +0000976 // Make a list of all the relocations for this section.
977 std::vector<RelocationRef> Rels;
978 if (InlineRelocs) {
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000979 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
980 for (const RelocationRef &Reloc : RelocSec.relocations()) {
981 Rels.push_back(Reloc);
982 }
Michael J. Spencer51862b32011-10-13 22:17:18 +0000983 }
984 }
985
986 // Sort relocations by address.
987 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
988
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000989 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +0000990 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +0000991 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +0000992 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000993 }
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000994 StringRef name;
Davide Italianoccd53fe2015-08-05 07:18:31 +0000995 error(Section.getName(name));
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000996 outs() << "Disassembly of section ";
997 if (!SegmentName.empty())
998 outs() << SegmentName << ",";
999 outs() << name << ':';
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001000
Rafael Espindola7884c952015-06-04 15:01:05 +00001001 // If the section has no symbol at the start, just insert a dummy one.
1002 if (Symbols.empty() || Symbols[0].first != 0)
1003 Symbols.insert(Symbols.begin(), std::make_pair(0, name));
Alp Tokere69170a2014-06-26 22:52:05 +00001004
1005 SmallString<40> Comments;
1006 raw_svector_ostream CommentStream(Comments);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001007
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001008 StringRef BytesStr;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001009 error(Section.getContents(BytesStr));
Aaron Ballman106fd7b2014-11-12 14:01:17 +00001010 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1011 BytesStr.size());
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001012
Michael J. Spencer2670c252011-01-20 06:39:06 +00001013 uint64_t Size;
1014 uint64_t Index;
1015
Michael J. Spencer51862b32011-10-13 22:17:18 +00001016 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
1017 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001018 // Disassemble symbol by symbol.
1019 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
Rafael Espindolae45c7402014-08-17 16:31:39 +00001020
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001021 uint64_t Start = Symbols[si].first - SectionAddr;
1022 // The end is either the section end or the beginning of the next
1023 // symbol.
1024 uint64_t End =
1025 (si == se - 1) ? SectSize : Symbols[si + 1].first - SectionAddr;
1026 // Don't try to disassemble beyond the end of section contents.
1027 if (End > SectSize)
1028 End = SectSize;
Rafael Espindolae45c7402014-08-17 16:31:39 +00001029 // If this symbol has the same address as the next symbol, then skip it.
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001030 if (Start >= End)
Michael J. Spenceree84f642011-10-13 20:37:08 +00001031 continue;
1032
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001033 outs() << '\n' << Symbols[si].second << ":\n";
Michael J. Spencer2670c252011-01-20 06:39:06 +00001034
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001035#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +00001036 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001037#else
Mark Seaborneb03ac52014-01-25 00:32:01 +00001038 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001039#endif
1040
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001041 for (Index = Start; Index < End; Index += Size) {
1042 MCInst Inst;
Owen Andersona0c3b972011-09-15 23:38:46 +00001043
Davide Italianof0706882015-10-01 21:57:09 +00001044 // AArch64 ELF binaries can interleave data and text in the
1045 // same section. We rely on the markers introduced to
1046 // understand what we need to dump.
1047 if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
1048 uint64_t Stride = 0;
1049
1050 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1051 DataMappingSymsAddr.end(), Index);
1052 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1053 // Switch to data.
1054 while (Index < End) {
1055 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1056 outs() << "\t";
1057 if (Index + 4 <= End) {
1058 Stride = 4;
1059 dumpBytes(Bytes.slice(Index, 4), outs());
1060 outs() << "\t.word";
1061 } else if (Index + 2 <= End) {
1062 Stride = 2;
1063 dumpBytes(Bytes.slice(Index, 2), outs());
1064 outs() << "\t.short";
1065 } else {
1066 Stride = 1;
1067 dumpBytes(Bytes.slice(Index, 1), outs());
1068 outs() << "\t.byte";
1069 }
1070 Index += Stride;
1071 outs() << "\n";
1072 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1073 TextMappingSymsAddr.end(), Index);
1074 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1075 break;
1076 }
1077 }
1078 }
1079
1080 if (Index >= End)
1081 break;
1082
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001083 if (DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1084 SectionAddr + Index, DebugOut,
1085 CommentStream)) {
Colin LeMahieu68d967d2015-05-29 14:44:13 +00001086 PIP.printInst(*IP, &Inst,
Colin LeMahieufb76b002015-05-28 19:07:14 +00001087 Bytes.slice(Index, Size),
1088 SectionAddr + Index, outs(), "", *STI);
Alp Tokere69170a2014-06-26 22:52:05 +00001089 outs() << CommentStream.str();
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001090 Comments.clear();
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001091
1092 // Try to resolve the target of a call, tail call, etc. to a specific
1093 // symbol.
David Majnemer2603a8fa2015-07-09 18:11:40 +00001094 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1095 MIA->isConditionalBranch(Inst))) {
David Majnemer81afca62015-07-07 22:06:59 +00001096 uint64_t Target;
1097 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001098 // In a relocatable object, the target's section must reside in
1099 // the same section as the call instruction or it is accessed
1100 // through a relocation.
1101 //
1102 // In a non-relocatable object, the target may be in any section.
1103 //
1104 // N.B. We don't walk the relocations in the relocatable case yet.
1105 auto *TargetSectionSymbols = &Symbols;
1106 if (!Obj->isRelocatableObject()) {
1107 auto SectionAddress = std::upper_bound(
1108 SectionAddresses.begin(), SectionAddresses.end(), Target,
1109 [](uint64_t LHS,
1110 const std::pair<uint64_t, SectionRef> &RHS) {
1111 return LHS < RHS.first;
1112 });
1113 if (SectionAddress != SectionAddresses.begin()) {
1114 --SectionAddress;
1115 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1116 } else {
1117 TargetSectionSymbols = nullptr;
1118 }
1119 }
David Majnemer2603a8fa2015-07-09 18:11:40 +00001120
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001121 // Find the first symbol in the section whose offset is less than
1122 // or equal to the target.
1123 if (TargetSectionSymbols) {
1124 auto TargetSym = std::upper_bound(
1125 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1126 Target, [](uint64_t LHS,
1127 const std::pair<uint64_t, StringRef> &RHS) {
1128 return LHS < RHS.first;
1129 });
1130 if (TargetSym != Symbols.begin()) {
1131 --TargetSym;
1132 uint64_t TargetAddress = std::get<0>(*TargetSym);
1133 StringRef TargetName = std::get<1>(*TargetSym);
1134 outs() << " <" << TargetName;
1135 uint64_t Disp = Target - TargetAddress;
1136 if (Disp)
1137 outs() << '+' << utohexstr(Disp);
1138 outs() << '>';
1139 }
David Majnemer81afca62015-07-07 22:06:59 +00001140 }
1141 }
1142 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001143 outs() << "\n";
1144 } else {
1145 errs() << ToolName << ": warning: invalid instruction encoding\n";
1146 if (Size == 0)
1147 Size = 1; // skip illegible bytes
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001148 }
Michael J. Spencer51862b32011-10-13 22:17:18 +00001149
1150 // Print relocation for instruction.
1151 while (rel_cur != rel_end) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001152 bool hidden = getHidden(*rel_cur);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001153 uint64_t addr = rel_cur->getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +00001154 SmallString<16> name;
1155 SmallString<32> val;
Owen Andersonfa3e5202011-10-25 20:35:53 +00001156
1157 // If this relocation is hidden, skip it.
Owen Andersonfa3e5202011-10-25 20:35:53 +00001158 if (hidden) goto skip_print_rel;
1159
Michael J. Spencer51862b32011-10-13 22:17:18 +00001160 // Stop when rel_cur's address is past the current instruction.
Owen Andersonf20e3e52011-10-25 20:15:39 +00001161 if (addr >= Index + Size) break;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001162 rel_cur->getTypeName(name);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001163 error(getRelocationValueString(*rel_cur, val));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001164 outs() << format(Fmt.data(), SectionAddr + addr) << name
Benjamin Kramer82803112012-03-10 02:04:38 +00001165 << "\t" << val << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001166
1167 skip_print_rel:
1168 ++rel_cur;
1169 }
Benjamin Kramer87ee76c2011-07-20 19:37:35 +00001170 }
Michael J. Spencer2670c252011-01-20 06:39:06 +00001171 }
1172 }
1173}
1174
Kevin Enderby98da6132015-01-20 21:47:46 +00001175void llvm::PrintRelocations(const ObjectFile *Obj) {
Greg Fitzgerald18432272014-03-20 22:55:15 +00001176 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1177 "%08" PRIx64;
Rafael Espindolac66d7612014-08-17 19:09:37 +00001178 // Regular objdump doesn't print relocations in non-relocatable object
1179 // files.
1180 if (!Obj->isRelocatableObject())
1181 return;
1182
Colin LeMahieu77804be2015-07-29 15:45:39 +00001183 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001184 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001185 continue;
1186 StringRef secname;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001187 error(Section.getName(secname));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001188 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001189 for (const RelocationRef &Reloc : Section.relocations()) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001190 bool hidden = getHidden(Reloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001191 uint64_t address = Reloc.getOffset();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001192 SmallString<32> relocname;
1193 SmallString<32> valuestr;
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001194 if (hidden)
1195 continue;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001196 Reloc.getTypeName(relocname);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001197 error(getRelocationValueString(Reloc, valuestr));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001198 outs() << format(Fmt.data(), address) << " " << relocname << " "
1199 << valuestr << "\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001200 }
1201 outs() << "\n";
1202 }
1203}
1204
Kevin Enderby98da6132015-01-20 21:47:46 +00001205void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001206 outs() << "Sections:\n"
1207 "Idx Name Size Address Type\n";
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001208 unsigned i = 0;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001209 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001210 StringRef Name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001211 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001212 uint64_t Address = Section.getAddress();
1213 uint64_t Size = Section.getSize();
1214 bool Text = Section.isText();
1215 bool Data = Section.isData();
1216 bool BSS = Section.isBSS();
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001217 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +00001218 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
Alexey Samsonov48803e52014-03-13 14:37:36 +00001219 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1220 Name.str().c_str(), Size, Address, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001221 ++i;
1222 }
1223}
1224
Kevin Enderby98da6132015-01-20 21:47:46 +00001225void llvm::PrintSectionContents(const ObjectFile *Obj) {
Rafael Espindola4453e42942014-06-13 03:07:50 +00001226 std::error_code EC;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001227 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001228 StringRef Name;
1229 StringRef Contents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001230 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001231 uint64_t BaseAddr = Section.getAddress();
David Majnemer185b5b12014-11-11 09:58:25 +00001232 uint64_t Size = Section.getSize();
1233 if (!Size)
1234 continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001235
1236 outs() << "Contents of section " << Name << ":\n";
David Majnemer185b5b12014-11-11 09:58:25 +00001237 if (Section.isBSS()) {
Alexey Samsonov209095c2013-04-16 10:53:11 +00001238 outs() << format("<skipping contents of bss section at [%04" PRIx64
David Majnemer8f6b04c2014-07-14 16:20:14 +00001239 ", %04" PRIx64 ")>\n",
1240 BaseAddr, BaseAddr + Size);
Alexey Samsonov209095c2013-04-16 10:53:11 +00001241 continue;
1242 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001243
Davide Italianoccd53fe2015-08-05 07:18:31 +00001244 error(Section.getContents(Contents));
David Majnemer8f6b04c2014-07-14 16:20:14 +00001245
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001246 // Dump out the content as hex and printable ascii characters.
1247 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer82803112012-03-10 02:04:38 +00001248 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001249 // Dump line of hex.
1250 for (std::size_t i = 0; i < 16; ++i) {
1251 if (i != 0 && i % 4 == 0)
1252 outs() << ' ';
1253 if (addr + i < end)
1254 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1255 << hexdigit(Contents[addr + i] & 0xF, true);
1256 else
1257 outs() << " ";
1258 }
1259 // Print ascii.
1260 outs() << " ";
1261 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
Guy Benyei83c74e92013-02-12 21:21:59 +00001262 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001263 outs() << Contents[addr + i];
1264 else
1265 outs() << ".";
1266 }
1267 outs() << "\n";
1268 }
1269 }
1270}
1271
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001272static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
David Majnemer44f51e52014-09-10 12:51:52 +00001273 for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
1274 ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI);
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001275 StringRef Name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001276 error(Symbol.getError());
1277 error(coff->getSymbolName(*Symbol, Name));
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001278
1279 outs() << "[" << format("%2d", SI) << "]"
David Majnemer44f51e52014-09-10 12:51:52 +00001280 << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001281 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
David Majnemer44f51e52014-09-10 12:51:52 +00001282 << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
1283 << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") "
1284 << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
1285 << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001286 << Name << "\n";
1287
David Majnemer44f51e52014-09-10 12:51:52 +00001288 for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001289 if (Symbol->isSectionDefinition()) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001290 const coff_aux_section_definition *asd;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001291 error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd));
Saleem Abdulrasool9ede5c72014-04-13 03:11:08 +00001292
David Majnemer4d571592014-09-15 19:42:42 +00001293 int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
1294
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001295 outs() << "AUX "
1296 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
1297 , unsigned(asd->Length)
1298 , unsigned(asd->NumberOfRelocations)
1299 , unsigned(asd->NumberOfLinenumbers)
1300 , unsigned(asd->CheckSum))
1301 << format("assoc %d comdat %d\n"
David Majnemer4d571592014-09-15 19:42:42 +00001302 , unsigned(AuxNumber)
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001303 , unsigned(asd->Selection));
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001304 } else if (Symbol->isFileRecord()) {
David Majnemer44f51e52014-09-10 12:51:52 +00001305 const char *FileName;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001306 error(coff->getAuxSymbol<char>(SI + 1, FileName));
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +00001307
David Majnemer44f51e52014-09-10 12:51:52 +00001308 StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
1309 coff->getSymbolTableEntrySize());
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +00001310 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
Saleem Abdulrasool13a3f692014-04-14 16:38:25 +00001311
David Majnemer44f51e52014-09-10 12:51:52 +00001312 SI = SI + Symbol->getNumberOfAuxSymbols();
Saleem Abdulrasool13a3f692014-04-14 16:38:25 +00001313 break;
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +00001314 } else {
1315 outs() << "AUX Unknown\n";
Saleem Abdulrasool9ede5c72014-04-13 03:11:08 +00001316 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001317 }
1318 }
1319}
1320
Kevin Enderby98da6132015-01-20 21:47:46 +00001321void llvm::PrintSymbolTable(const ObjectFile *o) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001322 outs() << "SYMBOL TABLE:\n";
1323
Rui Ueyama4e39f712014-03-18 18:58:51 +00001324 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001325 PrintCOFFSymbolTable(coff);
Rui Ueyama4e39f712014-03-18 18:58:51 +00001326 return;
1327 }
1328 for (const SymbolRef &Symbol : o->symbols()) {
Rafael Espindolaed067c42015-07-03 18:19:00 +00001329 ErrorOr<uint64_t> AddressOrError = Symbol.getAddress();
Davide Italianoccd53fe2015-08-05 07:18:31 +00001330 error(AddressOrError.getError());
Rafael Espindolaed067c42015-07-03 18:19:00 +00001331 uint64_t Address = *AddressOrError;
Rafael Espindola2fa80cc2015-06-26 12:18:49 +00001332 SymbolRef::Type Type = Symbol.getType();
Rui Ueyama4e39f712014-03-18 18:58:51 +00001333 uint32_t Flags = Symbol.getFlags();
Rafael Espindola8bab8892015-08-07 23:27:14 +00001334 ErrorOr<section_iterator> SectionOrErr = Symbol.getSection();
1335 error(SectionOrErr.getError());
1336 section_iterator Section = *SectionOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001337 StringRef Name;
1338 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1339 Section->getName(Name);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001340 } else {
1341 ErrorOr<StringRef> NameOrErr = Symbol.getName();
Davide Italianoccd53fe2015-08-05 07:18:31 +00001342 error(NameOrErr.getError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001343 Name = *NameOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001344 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001345
Rui Ueyama4e39f712014-03-18 18:58:51 +00001346 bool Global = Flags & SymbolRef::SF_Global;
1347 bool Weak = Flags & SymbolRef::SF_Weak;
1348 bool Absolute = Flags & SymbolRef::SF_Absolute;
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001349 bool Common = Flags & SymbolRef::SF_Common;
Davide Italianocd2514d2015-04-30 23:08:53 +00001350 bool Hidden = Flags & SymbolRef::SF_Hidden;
David Meyer1df4b842012-02-28 23:47:53 +00001351
Rui Ueyama4e39f712014-03-18 18:58:51 +00001352 char GlobLoc = ' ';
1353 if (Type != SymbolRef::ST_Unknown)
1354 GlobLoc = Global ? 'g' : 'l';
1355 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1356 ? 'd' : ' ';
1357 char FileFunc = ' ';
1358 if (Type == SymbolRef::ST_File)
1359 FileFunc = 'f';
1360 else if (Type == SymbolRef::ST_Function)
1361 FileFunc = 'F';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001362
Rui Ueyama4e39f712014-03-18 18:58:51 +00001363 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1364 "%08" PRIx64;
Michael J. Spencerd857c1c2013-01-10 22:40:50 +00001365
Rui Ueyama4e39f712014-03-18 18:58:51 +00001366 outs() << format(Fmt, Address) << " "
1367 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1368 << (Weak ? 'w' : ' ') // Weak?
1369 << ' ' // Constructor. Not supported yet.
1370 << ' ' // Warning. Not supported yet.
1371 << ' ' // Indirect reference to another symbol.
1372 << Debug // Debugging (d) or dynamic (D) symbol.
1373 << FileFunc // Name of function (F), file (f) or object (O).
1374 << ' ';
1375 if (Absolute) {
1376 outs() << "*ABS*";
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001377 } else if (Common) {
1378 outs() << "*COM*";
Rui Ueyama4e39f712014-03-18 18:58:51 +00001379 } else if (Section == o->section_end()) {
1380 outs() << "*UND*";
1381 } else {
1382 if (const MachOObjectFile *MachO =
1383 dyn_cast<const MachOObjectFile>(o)) {
1384 DataRefImpl DR = Section->getRawDataRefImpl();
1385 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1386 outs() << SegmentName << ",";
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001387 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00001388 StringRef SectionName;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001389 error(Section->getName(SectionName));
Rui Ueyama4e39f712014-03-18 18:58:51 +00001390 outs() << SectionName;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001391 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001392
1393 outs() << '\t';
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001394 if (Common || isa<ELFObjectFileBase>(o)) {
Rafael Espindoladbb6bd32015-06-25 22:10:04 +00001395 uint64_t Val =
1396 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001397 outs() << format("\t %08" PRIx64 " ", Val);
1398 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001399
Davide Italianocd2514d2015-04-30 23:08:53 +00001400 if (Hidden) {
1401 outs() << ".hidden ";
1402 }
1403 outs() << Name
Rui Ueyama4e39f712014-03-18 18:58:51 +00001404 << '\n';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001405 }
1406}
1407
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001408static void PrintUnwindInfo(const ObjectFile *o) {
1409 outs() << "Unwind info:\n\n";
1410
1411 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1412 printCOFFUnwindInfo(coff);
Tim Northover4bd286a2014-08-01 13:07:19 +00001413 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1414 printMachOUnwindInfo(MachO);
1415 else {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001416 // TODO: Extract DWARF dump tool to objdump.
1417 errs() << "This operation is only currently supported "
Tim Northover4bd286a2014-08-01 13:07:19 +00001418 "for COFF and MachO object files.\n";
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001419 return;
1420 }
1421}
1422
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001423void llvm::printExportsTrie(const ObjectFile *o) {
Nick Kledzikd04bc352014-08-30 00:20:14 +00001424 outs() << "Exports trie:\n";
1425 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1426 printMachOExportsTrie(MachO);
1427 else {
1428 errs() << "This operation is only currently supported "
1429 "for Mach-O executable files.\n";
1430 return;
1431 }
1432}
1433
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001434void llvm::printRebaseTable(const ObjectFile *o) {
Nick Kledzikac431442014-09-12 21:34:15 +00001435 outs() << "Rebase table:\n";
1436 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1437 printMachORebaseTable(MachO);
1438 else {
1439 errs() << "This operation is only currently supported "
1440 "for Mach-O executable files.\n";
1441 return;
1442 }
1443}
1444
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001445void llvm::printBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001446 outs() << "Bind table:\n";
1447 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1448 printMachOBindTable(MachO);
1449 else {
1450 errs() << "This operation is only currently supported "
1451 "for Mach-O executable files.\n";
1452 return;
1453 }
1454}
1455
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001456void llvm::printLazyBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001457 outs() << "Lazy bind table:\n";
1458 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1459 printMachOLazyBindTable(MachO);
1460 else {
1461 errs() << "This operation is only currently supported "
1462 "for Mach-O executable files.\n";
1463 return;
1464 }
1465}
1466
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001467void llvm::printWeakBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001468 outs() << "Weak bind table:\n";
1469 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1470 printMachOWeakBindTable(MachO);
1471 else {
1472 errs() << "This operation is only currently supported "
1473 "for Mach-O executable files.\n";
1474 return;
1475 }
1476}
Nick Kledzikac431442014-09-12 21:34:15 +00001477
Adrian Prantl437105a2015-07-08 02:04:15 +00001478/// Dump the raw contents of the __clangast section so the output can be piped
1479/// into llvm-bcanalyzer.
1480void llvm::printRawClangAST(const ObjectFile *Obj) {
1481 if (outs().is_displayed()) {
1482 errs() << "The -raw-clang-ast option will dump the raw binary contents of "
1483 "the clang ast section.\n"
1484 "Please redirect the output to a file or another program such as "
1485 "llvm-bcanalyzer.\n";
1486 return;
1487 }
1488
1489 StringRef ClangASTSectionName("__clangast");
1490 if (isa<COFFObjectFile>(Obj)) {
1491 ClangASTSectionName = "clangast";
1492 }
1493
1494 Optional<object::SectionRef> ClangASTSection;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001495 for (auto Sec : ToolSectionFilter(*Obj)) {
Adrian Prantl437105a2015-07-08 02:04:15 +00001496 StringRef Name;
1497 Sec.getName(Name);
1498 if (Name == ClangASTSectionName) {
1499 ClangASTSection = Sec;
1500 break;
1501 }
1502 }
1503 if (!ClangASTSection)
1504 return;
1505
1506 StringRef ClangASTContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001507 error(ClangASTSection.getValue().getContents(ClangASTContents));
Adrian Prantl437105a2015-07-08 02:04:15 +00001508 outs().write(ClangASTContents.data(), ClangASTContents.size());
1509}
1510
Sanjoy Das6f567a42015-06-22 18:03:02 +00001511static void printFaultMaps(const ObjectFile *Obj) {
1512 const char *FaultMapSectionName = nullptr;
1513
1514 if (isa<ELFObjectFileBase>(Obj)) {
1515 FaultMapSectionName = ".llvm_faultmaps";
1516 } else if (isa<MachOObjectFile>(Obj)) {
1517 FaultMapSectionName = "__llvm_faultmaps";
1518 } else {
1519 errs() << "This operation is only currently supported "
1520 "for ELF and Mach-O executable files.\n";
1521 return;
1522 }
1523
1524 Optional<object::SectionRef> FaultMapSection;
1525
Colin LeMahieu77804be2015-07-29 15:45:39 +00001526 for (auto Sec : ToolSectionFilter(*Obj)) {
Sanjoy Das6f567a42015-06-22 18:03:02 +00001527 StringRef Name;
1528 Sec.getName(Name);
1529 if (Name == FaultMapSectionName) {
1530 FaultMapSection = Sec;
1531 break;
1532 }
1533 }
1534
1535 outs() << "FaultMap table:\n";
1536
1537 if (!FaultMapSection.hasValue()) {
1538 outs() << "<not found>\n";
1539 return;
1540 }
1541
1542 StringRef FaultMapContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001543 error(FaultMapSection.getValue().getContents(FaultMapContents));
Sanjoy Das6f567a42015-06-22 18:03:02 +00001544
1545 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1546 FaultMapContents.bytes_end());
1547
1548 outs() << FMP;
1549}
1550
Rui Ueyamac2bed422013-09-27 21:04:00 +00001551static void printPrivateFileHeader(const ObjectFile *o) {
1552 if (o->isELF()) {
1553 printELFFileHeader(o);
1554 } else if (o->isCOFF()) {
1555 printCOFFFileHeader(o);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00001556 } else if (o->isMachO()) {
1557 printMachOFileHeader(o);
Rui Ueyamac2bed422013-09-27 21:04:00 +00001558 }
1559}
1560
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001561static void DumpObject(const ObjectFile *o) {
Adrian Prantl437105a2015-07-08 02:04:15 +00001562 // Avoid other output when using a raw option.
1563 if (!RawClangAST) {
1564 outs() << '\n';
1565 outs() << o->getFileName()
1566 << ":\tfile format " << o->getFileFormatName() << "\n\n";
1567 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001568
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001569 if (Disassemble)
Michael J. Spencer51862b32011-10-13 22:17:18 +00001570 DisassembleObject(o, Relocations);
1571 if (Relocations && !Disassemble)
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001572 PrintRelocations(o);
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001573 if (SectionHeaders)
1574 PrintSectionHeaders(o);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001575 if (SectionContents)
1576 PrintSectionContents(o);
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001577 if (SymbolTable)
1578 PrintSymbolTable(o);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001579 if (UnwindInfo)
1580 PrintUnwindInfo(o);
Rui Ueyamac2bed422013-09-27 21:04:00 +00001581 if (PrivateHeaders)
1582 printPrivateFileHeader(o);
Nick Kledzikd04bc352014-08-30 00:20:14 +00001583 if (ExportsTrie)
1584 printExportsTrie(o);
Nick Kledzikac431442014-09-12 21:34:15 +00001585 if (Rebase)
1586 printRebaseTable(o);
Nick Kledzik56ebef42014-09-16 01:41:51 +00001587 if (Bind)
1588 printBindTable(o);
1589 if (LazyBind)
1590 printLazyBindTable(o);
1591 if (WeakBind)
1592 printWeakBindTable(o);
Adrian Prantl437105a2015-07-08 02:04:15 +00001593 if (RawClangAST)
1594 printRawClangAST(o);
Sanjoy Das6f567a42015-06-22 18:03:02 +00001595 if (PrintFaultMaps)
1596 printFaultMaps(o);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001597}
1598
1599/// @brief Dump each object file in \a a;
1600static void DumpArchive(const Archive *a) {
Kevin Enderby7a969422015-11-05 19:24:56 +00001601 for (auto &ErrorOrChild : a->children()) {
1602 if (std::error_code EC = ErrorOrChild.getError())
1603 report_error(a->getFileName(), EC);
1604 const Archive::Child &C = *ErrorOrChild;
Davide Italiano95dd3cb2015-08-03 21:46:32 +00001605 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Davide Italianoccd53fe2015-08-05 07:18:31 +00001606 if (std::error_code EC = ChildOrErr.getError())
Mark Seaborneb03ac52014-01-25 00:32:01 +00001607 if (EC != object_error::invalid_file_type)
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001608 report_error(a->getFileName(), EC);
Rafael Espindolaae460022014-06-16 16:08:36 +00001609 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001610 DumpObject(o);
1611 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001612 report_error(a->getFileName(), object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001613 }
1614}
1615
1616/// @brief Open file and figure out how to dump it.
1617static void DumpInput(StringRef file) {
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001618
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001619 // If we are using the Mach-O specific object file parser, then let it parse
1620 // the file and process the command line options. So the -arch flags can
1621 // be used to select specific slices, etc.
1622 if (MachOOpt) {
1623 ParseInputMachO(file);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001624 return;
1625 }
1626
1627 // Attempt to open the binary.
Rafael Espindola48af1c22014-08-19 18:44:46 +00001628 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001629 if (std::error_code EC = BinaryOrErr.getError())
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001630 report_error(file, EC);
Rafael Espindola48af1c22014-08-19 18:44:46 +00001631 Binary &Binary = *BinaryOrErr.get().getBinary();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001632
Rafael Espindola3f6481d2014-08-01 14:31:55 +00001633 if (Archive *a = dyn_cast<Archive>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001634 DumpArchive(a);
Rafael Espindola3f6481d2014-08-01 14:31:55 +00001635 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001636 DumpObject(o);
Jim Grosbachaf9aec02012-08-07 17:53:14 +00001637 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001638 report_error(file, object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001639}
1640
Michael J. Spencer2670c252011-01-20 06:39:06 +00001641int main(int argc, char **argv) {
1642 // Print a stack trace if we signal out.
1643 sys::PrintStackTraceOnErrorSignal();
1644 PrettyStackTraceProgram X(argc, argv);
1645 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1646
1647 // Initialize targets and assembly printers/parsers.
1648 llvm::InitializeAllTargetInfos();
Evan Cheng8c886a42011-07-22 21:58:54 +00001649 llvm::InitializeAllTargetMCs();
Michael J. Spencer2670c252011-01-20 06:39:06 +00001650 llvm::InitializeAllDisassemblers();
1651
Pete Cooper28fb4fc2012-05-03 23:20:10 +00001652 // Register the target printer for --version.
1653 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
1654
Michael J. Spencer2670c252011-01-20 06:39:06 +00001655 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
1656 TripleName = Triple::normalize(TripleName);
1657
1658 ToolName = argv[0];
1659
1660 // Defaults to a.out if no filenames specified.
1661 if (InputFilenames.size() == 0)
1662 InputFilenames.push_back("a.out");
1663
Colin LeMahieuf34933e2015-07-23 20:58:49 +00001664 if (DisassembleAll)
1665 Disassemble = true;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001666 if (!Disassemble
1667 && !Relocations
1668 && !SectionHeaders
1669 && !SectionContents
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001670 && !SymbolTable
Michael J. Spencer209565db2013-01-06 03:56:49 +00001671 && !UnwindInfo
Nick Kledzikd04bc352014-08-30 00:20:14 +00001672 && !PrivateHeaders
Nick Kledzikac431442014-09-12 21:34:15 +00001673 && !ExportsTrie
Nick Kledzik56ebef42014-09-16 01:41:51 +00001674 && !Rebase
1675 && !Bind
1676 && !LazyBind
Kevin Enderby131d1772015-01-09 19:22:37 +00001677 && !WeakBind
Adrian Prantl437105a2015-07-08 02:04:15 +00001678 && !RawClangAST
Kevin Enderby13023a12015-01-15 23:19:11 +00001679 && !(UniversalHeaders && MachOOpt)
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001680 && !(ArchiveHeaders && MachOOpt)
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001681 && !(IndirectSymbols && MachOOpt)
Kevin Enderby9a509442015-01-27 21:28:24 +00001682 && !(DataInCode && MachOOpt)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001683 && !(LinkOptHints && MachOOpt)
Kevin Enderbycd66be52015-03-11 22:06:32 +00001684 && !(InfoPlist && MachOOpt)
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001685 && !(DylibsUsed && MachOOpt)
1686 && !(DylibId && MachOOpt)
Kevin Enderby0fc11822015-04-01 20:57:01 +00001687 && !(ObjcMetaData && MachOOpt)
Colin LeMahieufcc32762015-07-29 19:08:10 +00001688 && !(FilterSections.size() != 0 && MachOOpt)
Sanjoy Das6f567a42015-06-22 18:03:02 +00001689 && !PrintFaultMaps) {
Michael J. Spencer2670c252011-01-20 06:39:06 +00001690 cl::PrintHelpMessage();
1691 return 2;
1692 }
1693
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001694 std::for_each(InputFilenames.begin(), InputFilenames.end(),
1695 DumpInput);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001696
Davide Italianoccd53fe2015-08-05 07:18:31 +00001697 return EXIT_SUCCESS;
Michael J. Spencer2670c252011-01-20 06:39:06 +00001698}