blob: 3057a1d099ec003efd7cd7da20e453a41ab81095 [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));
Davide Italiano711e4952015-12-17 01:59:50 +0000818 if (!MRI)
819 report_fatal_error("error: no register info for target " + TripleName);
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000820
821 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000822 std::unique_ptr<const MCAsmInfo> AsmInfo(
823 TheTarget->createMCAsmInfo(*MRI, TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +0000824 if (!AsmInfo)
825 report_fatal_error("error: no assembly info for target " + TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +0000826 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +0000827 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Davide Italiano711e4952015-12-17 01:59:50 +0000828 if (!STI)
829 report_fatal_error("error: no subtarget info for target " + TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +0000830 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
Davide Italiano711e4952015-12-17 01:59:50 +0000831 if (!MII)
832 report_fatal_error("error: no instruction info for target " + TripleName);
Lang Hamesa1bc0f52014-04-15 04:40:56 +0000833 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
834 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
835
836 std::unique_ptr<MCDisassembler> DisAsm(
837 TheTarget->createMCDisassembler(*STI, Ctx));
Davide Italiano711e4952015-12-17 01:59:50 +0000838 if (!DisAsm)
839 report_fatal_error("error: no disassembler for target " + TripleName);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000840
Ahmed Charles56440fd2014-03-06 05:51:42 +0000841 std::unique_ptr<const MCInstrAnalysis> MIA(
842 TheTarget->createMCInstrAnalysis(MII.get()));
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000843
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000844 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Daniel Sanders50f17232015-09-15 16:17:27 +0000845 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
846 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
Davide Italiano711e4952015-12-17 01:59:50 +0000847 if (!IP)
848 report_fatal_error("error: no instruction printer for target " +
849 TripleName);
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000850 IP->setPrintImmHex(PrintImmHex);
Colin LeMahieu35436a22015-05-29 14:48:25 +0000851 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000852
Greg Fitzgerald18432272014-03-20 22:55:15 +0000853 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
854 "\t\t\t%08" PRIx64 ": ";
855
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000856 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
857 // in RelocSecs contain the relocations for section S.
Rafael Espindola4453e42942014-06-13 03:07:50 +0000858 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000859 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
Colin LeMahieu77804be2015-07-29 15:45:39 +0000860 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +0000861 section_iterator Sec2 = Section.getRelocatedSection();
Rafael Espindolab5155a52014-02-10 20:24:04 +0000862 if (Sec2 != Obj->section_end())
Alexey Samsonov48803e52014-03-13 14:37:36 +0000863 SectionRelocMap[*Sec2].push_back(Section);
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000864 }
865
David Majnemer81afca62015-07-07 22:06:59 +0000866 // Create a mapping from virtual address to symbol name. This is used to
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000867 // pretty print the symbols while disassembling.
868 typedef std::vector<std::pair<uint64_t, StringRef>> SectionSymbolsTy;
869 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
870 for (const SymbolRef &Symbol : Obj->symbols()) {
871 ErrorOr<uint64_t> AddressOrErr = Symbol.getAddress();
872 error(AddressOrErr.getError());
873 uint64_t Address = *AddressOrErr;
David Majnemer2603a8fa2015-07-09 18:11:40 +0000874
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000875 ErrorOr<StringRef> Name = Symbol.getName();
876 error(Name.getError());
877 if (Name->empty())
878 continue;
David Majnemer81afca62015-07-07 22:06:59 +0000879
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000880 ErrorOr<section_iterator> SectionOrErr = Symbol.getSection();
881 error(SectionOrErr.getError());
882 section_iterator SecI = *SectionOrErr;
883 if (SecI == Obj->section_end())
884 continue;
David Majnemer81afca62015-07-07 22:06:59 +0000885
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000886 AllSymbols[*SecI].emplace_back(Address, *Name);
David Majnemer81afca62015-07-07 22:06:59 +0000887 }
888
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000889 // Create a mapping from virtual address to section.
890 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
891 for (SectionRef Sec : Obj->sections())
892 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
893 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
894
895 // Linked executables (.exe and .dll files) typically don't include a real
896 // symbol table but they might contain an export table.
897 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
898 for (const auto &ExportEntry : COFFObj->export_directories()) {
899 StringRef Name;
900 error(ExportEntry.getSymbolName(Name));
901 if (Name.empty())
902 continue;
903 uint32_t RVA;
904 error(ExportEntry.getExportRVA(RVA));
905
906 uint64_t VA = COFFObj->getImageBase() + RVA;
907 auto Sec = std::upper_bound(
908 SectionAddresses.begin(), SectionAddresses.end(), VA,
909 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
910 return LHS < RHS.first;
911 });
912 if (Sec != SectionAddresses.begin())
913 --Sec;
914 else
915 Sec = SectionAddresses.end();
916
917 if (Sec != SectionAddresses.end())
918 AllSymbols[Sec->second].emplace_back(VA, Name);
919 }
920 }
921
922 // Sort all the symbols, this allows us to use a simple binary search to find
923 // a symbol near an address.
924 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
925 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
926
Colin LeMahieu77804be2015-07-29 15:45:39 +0000927 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Colin LeMahieuf34933e2015-07-23 20:58:49 +0000928 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000929 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000930
Rafael Espindola80291272014-10-08 15:28:58 +0000931 uint64_t SectionAddr = Section.getAddress();
932 uint64_t SectSize = Section.getSize();
David Majnemer185b5b12014-11-11 09:58:25 +0000933 if (!SectSize)
934 continue;
Simon Atanasyan2b614e12014-02-24 22:12:11 +0000935
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000936 // Get the list of all the symbols in this section.
937 SectionSymbolsTy &Symbols = AllSymbols[Section];
Davide Italianof0706882015-10-01 21:57:09 +0000938 std::vector<uint64_t> DataMappingSymsAddr;
939 std::vector<uint64_t> TextMappingSymsAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000940 if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
941 for (const auto &Symb : Symbols) {
942 uint64_t Address = Symb.first;
943 StringRef Name = Symb.second;
944 if (Name.startswith("$d"))
David Majnemer153722d2015-11-18 04:35:32 +0000945 DataMappingSymsAddr.push_back(Address - SectionAddr);
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000946 if (Name.startswith("$x"))
David Majnemer153722d2015-11-18 04:35:32 +0000947 TextMappingSymsAddr.push_back(Address - SectionAddr);
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000948 }
949 }
950
Davide Italianof0706882015-10-01 21:57:09 +0000951 std::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end());
952 std::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end());
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000953
Michael J. Spencer51862b32011-10-13 22:17:18 +0000954 // Make a list of all the relocations for this section.
955 std::vector<RelocationRef> Rels;
956 if (InlineRelocs) {
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000957 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
958 for (const RelocationRef &Reloc : RelocSec.relocations()) {
959 Rels.push_back(Reloc);
960 }
Michael J. Spencer51862b32011-10-13 22:17:18 +0000961 }
962 }
963
964 // Sort relocations by address.
965 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
966
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000967 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +0000968 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +0000969 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +0000970 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000971 }
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000972 StringRef name;
Davide Italianoccd53fe2015-08-05 07:18:31 +0000973 error(Section.getName(name));
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000974 outs() << "Disassembly of section ";
975 if (!SegmentName.empty())
976 outs() << SegmentName << ",";
977 outs() << name << ':';
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000978
Rafael Espindola7884c952015-06-04 15:01:05 +0000979 // If the section has no symbol at the start, just insert a dummy one.
980 if (Symbols.empty() || Symbols[0].first != 0)
David Majnemer153722d2015-11-18 04:35:32 +0000981 Symbols.insert(Symbols.begin(), std::make_pair(SectionAddr, name));
Alp Tokere69170a2014-06-26 22:52:05 +0000982
983 SmallString<40> Comments;
984 raw_svector_ostream CommentStream(Comments);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000985
Rafael Espindola7fc5b872014-11-12 02:04:27 +0000986 StringRef BytesStr;
Davide Italianoccd53fe2015-08-05 07:18:31 +0000987 error(Section.getContents(BytesStr));
Aaron Ballman106fd7b2014-11-12 14:01:17 +0000988 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
989 BytesStr.size());
Rafael Espindola7fc5b872014-11-12 02:04:27 +0000990
Michael J. Spencer2670c252011-01-20 06:39:06 +0000991 uint64_t Size;
992 uint64_t Index;
993
Michael J. Spencer51862b32011-10-13 22:17:18 +0000994 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
995 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000996 // Disassemble symbol by symbol.
997 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
Rafael Espindolae45c7402014-08-17 16:31:39 +0000998
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000999 uint64_t Start = Symbols[si].first - SectionAddr;
1000 // The end is either the section end or the beginning of the next
1001 // symbol.
1002 uint64_t End =
1003 (si == se - 1) ? SectSize : Symbols[si + 1].first - SectionAddr;
1004 // Don't try to disassemble beyond the end of section contents.
1005 if (End > SectSize)
1006 End = SectSize;
Rafael Espindolae45c7402014-08-17 16:31:39 +00001007 // If this symbol has the same address as the next symbol, then skip it.
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001008 if (Start >= End)
Michael J. Spenceree84f642011-10-13 20:37:08 +00001009 continue;
1010
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001011 outs() << '\n' << Symbols[si].second << ":\n";
Michael J. Spencer2670c252011-01-20 06:39:06 +00001012
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001013#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +00001014 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001015#else
Mark Seaborneb03ac52014-01-25 00:32:01 +00001016 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001017#endif
1018
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001019 for (Index = Start; Index < End; Index += Size) {
1020 MCInst Inst;
Owen Andersona0c3b972011-09-15 23:38:46 +00001021
Davide Italianof0706882015-10-01 21:57:09 +00001022 // AArch64 ELF binaries can interleave data and text in the
1023 // same section. We rely on the markers introduced to
1024 // understand what we need to dump.
1025 if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
1026 uint64_t Stride = 0;
1027
1028 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1029 DataMappingSymsAddr.end(), Index);
1030 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1031 // Switch to data.
1032 while (Index < End) {
1033 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1034 outs() << "\t";
1035 if (Index + 4 <= End) {
1036 Stride = 4;
1037 dumpBytes(Bytes.slice(Index, 4), outs());
1038 outs() << "\t.word";
1039 } else if (Index + 2 <= End) {
1040 Stride = 2;
1041 dumpBytes(Bytes.slice(Index, 2), outs());
1042 outs() << "\t.short";
1043 } else {
1044 Stride = 1;
1045 dumpBytes(Bytes.slice(Index, 1), outs());
1046 outs() << "\t.byte";
1047 }
1048 Index += Stride;
1049 outs() << "\n";
1050 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1051 TextMappingSymsAddr.end(), Index);
1052 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1053 break;
1054 }
1055 }
1056 }
1057
1058 if (Index >= End)
1059 break;
1060
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001061 if (DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1062 SectionAddr + Index, DebugOut,
1063 CommentStream)) {
Colin LeMahieu68d967d2015-05-29 14:44:13 +00001064 PIP.printInst(*IP, &Inst,
Colin LeMahieufb76b002015-05-28 19:07:14 +00001065 Bytes.slice(Index, Size),
1066 SectionAddr + Index, outs(), "", *STI);
Alp Tokere69170a2014-06-26 22:52:05 +00001067 outs() << CommentStream.str();
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001068 Comments.clear();
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001069
1070 // Try to resolve the target of a call, tail call, etc. to a specific
1071 // symbol.
David Majnemer2603a8fa2015-07-09 18:11:40 +00001072 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1073 MIA->isConditionalBranch(Inst))) {
David Majnemer81afca62015-07-07 22:06:59 +00001074 uint64_t Target;
1075 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001076 // In a relocatable object, the target's section must reside in
1077 // the same section as the call instruction or it is accessed
1078 // through a relocation.
1079 //
1080 // In a non-relocatable object, the target may be in any section.
1081 //
1082 // N.B. We don't walk the relocations in the relocatable case yet.
1083 auto *TargetSectionSymbols = &Symbols;
1084 if (!Obj->isRelocatableObject()) {
1085 auto SectionAddress = std::upper_bound(
1086 SectionAddresses.begin(), SectionAddresses.end(), Target,
1087 [](uint64_t LHS,
1088 const std::pair<uint64_t, SectionRef> &RHS) {
1089 return LHS < RHS.first;
1090 });
1091 if (SectionAddress != SectionAddresses.begin()) {
1092 --SectionAddress;
1093 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1094 } else {
1095 TargetSectionSymbols = nullptr;
1096 }
1097 }
David Majnemer2603a8fa2015-07-09 18:11:40 +00001098
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001099 // Find the first symbol in the section whose offset is less than
1100 // or equal to the target.
1101 if (TargetSectionSymbols) {
1102 auto TargetSym = std::upper_bound(
1103 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1104 Target, [](uint64_t LHS,
1105 const std::pair<uint64_t, StringRef> &RHS) {
1106 return LHS < RHS.first;
1107 });
David Majnemer153722d2015-11-18 04:35:32 +00001108 if (TargetSym != TargetSectionSymbols->begin()) {
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001109 --TargetSym;
1110 uint64_t TargetAddress = std::get<0>(*TargetSym);
1111 StringRef TargetName = std::get<1>(*TargetSym);
1112 outs() << " <" << TargetName;
1113 uint64_t Disp = Target - TargetAddress;
1114 if (Disp)
1115 outs() << '+' << utohexstr(Disp);
1116 outs() << '>';
1117 }
David Majnemer81afca62015-07-07 22:06:59 +00001118 }
1119 }
1120 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001121 outs() << "\n";
1122 } else {
1123 errs() << ToolName << ": warning: invalid instruction encoding\n";
1124 if (Size == 0)
1125 Size = 1; // skip illegible bytes
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001126 }
Michael J. Spencer51862b32011-10-13 22:17:18 +00001127
1128 // Print relocation for instruction.
1129 while (rel_cur != rel_end) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001130 bool hidden = getHidden(*rel_cur);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001131 uint64_t addr = rel_cur->getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +00001132 SmallString<16> name;
1133 SmallString<32> val;
Owen Andersonfa3e5202011-10-25 20:35:53 +00001134
1135 // If this relocation is hidden, skip it.
Owen Andersonfa3e5202011-10-25 20:35:53 +00001136 if (hidden) goto skip_print_rel;
1137
Michael J. Spencer51862b32011-10-13 22:17:18 +00001138 // Stop when rel_cur's address is past the current instruction.
Owen Andersonf20e3e52011-10-25 20:15:39 +00001139 if (addr >= Index + Size) break;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001140 rel_cur->getTypeName(name);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001141 error(getRelocationValueString(*rel_cur, val));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001142 outs() << format(Fmt.data(), SectionAddr + addr) << name
Benjamin Kramer82803112012-03-10 02:04:38 +00001143 << "\t" << val << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001144
1145 skip_print_rel:
1146 ++rel_cur;
1147 }
Benjamin Kramer87ee76c2011-07-20 19:37:35 +00001148 }
Michael J. Spencer2670c252011-01-20 06:39:06 +00001149 }
1150 }
1151}
1152
Kevin Enderby98da6132015-01-20 21:47:46 +00001153void llvm::PrintRelocations(const ObjectFile *Obj) {
Greg Fitzgerald18432272014-03-20 22:55:15 +00001154 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1155 "%08" PRIx64;
Rafael Espindolac66d7612014-08-17 19:09:37 +00001156 // Regular objdump doesn't print relocations in non-relocatable object
1157 // files.
1158 if (!Obj->isRelocatableObject())
1159 return;
1160
Colin LeMahieu77804be2015-07-29 15:45:39 +00001161 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001162 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001163 continue;
1164 StringRef secname;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001165 error(Section.getName(secname));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001166 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001167 for (const RelocationRef &Reloc : Section.relocations()) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001168 bool hidden = getHidden(Reloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001169 uint64_t address = Reloc.getOffset();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001170 SmallString<32> relocname;
1171 SmallString<32> valuestr;
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001172 if (hidden)
1173 continue;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001174 Reloc.getTypeName(relocname);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001175 error(getRelocationValueString(Reloc, valuestr));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001176 outs() << format(Fmt.data(), address) << " " << relocname << " "
1177 << valuestr << "\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001178 }
1179 outs() << "\n";
1180 }
1181}
1182
Kevin Enderby98da6132015-01-20 21:47:46 +00001183void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001184 outs() << "Sections:\n"
1185 "Idx Name Size Address Type\n";
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001186 unsigned i = 0;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001187 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001188 StringRef Name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001189 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001190 uint64_t Address = Section.getAddress();
1191 uint64_t Size = Section.getSize();
1192 bool Text = Section.isText();
1193 bool Data = Section.isData();
1194 bool BSS = Section.isBSS();
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001195 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +00001196 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
Alexey Samsonov48803e52014-03-13 14:37:36 +00001197 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1198 Name.str().c_str(), Size, Address, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001199 ++i;
1200 }
1201}
1202
Kevin Enderby98da6132015-01-20 21:47:46 +00001203void llvm::PrintSectionContents(const ObjectFile *Obj) {
Rafael Espindola4453e42942014-06-13 03:07:50 +00001204 std::error_code EC;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001205 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001206 StringRef Name;
1207 StringRef Contents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001208 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001209 uint64_t BaseAddr = Section.getAddress();
David Majnemer185b5b12014-11-11 09:58:25 +00001210 uint64_t Size = Section.getSize();
1211 if (!Size)
1212 continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001213
1214 outs() << "Contents of section " << Name << ":\n";
David Majnemer185b5b12014-11-11 09:58:25 +00001215 if (Section.isBSS()) {
Alexey Samsonov209095c2013-04-16 10:53:11 +00001216 outs() << format("<skipping contents of bss section at [%04" PRIx64
David Majnemer8f6b04c2014-07-14 16:20:14 +00001217 ", %04" PRIx64 ")>\n",
1218 BaseAddr, BaseAddr + Size);
Alexey Samsonov209095c2013-04-16 10:53:11 +00001219 continue;
1220 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001221
Davide Italianoccd53fe2015-08-05 07:18:31 +00001222 error(Section.getContents(Contents));
David Majnemer8f6b04c2014-07-14 16:20:14 +00001223
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001224 // Dump out the content as hex and printable ascii characters.
1225 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer82803112012-03-10 02:04:38 +00001226 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001227 // Dump line of hex.
1228 for (std::size_t i = 0; i < 16; ++i) {
1229 if (i != 0 && i % 4 == 0)
1230 outs() << ' ';
1231 if (addr + i < end)
1232 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1233 << hexdigit(Contents[addr + i] & 0xF, true);
1234 else
1235 outs() << " ";
1236 }
1237 // Print ascii.
1238 outs() << " ";
1239 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
Guy Benyei83c74e92013-02-12 21:21:59 +00001240 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001241 outs() << Contents[addr + i];
1242 else
1243 outs() << ".";
1244 }
1245 outs() << "\n";
1246 }
1247 }
1248}
1249
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001250static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
David Majnemer44f51e52014-09-10 12:51:52 +00001251 for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
1252 ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI);
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001253 StringRef Name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001254 error(Symbol.getError());
1255 error(coff->getSymbolName(*Symbol, Name));
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001256
1257 outs() << "[" << format("%2d", SI) << "]"
David Majnemer44f51e52014-09-10 12:51:52 +00001258 << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001259 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
David Majnemer44f51e52014-09-10 12:51:52 +00001260 << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
1261 << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") "
1262 << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
1263 << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001264 << Name << "\n";
1265
David Majnemer44f51e52014-09-10 12:51:52 +00001266 for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001267 if (Symbol->isSectionDefinition()) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001268 const coff_aux_section_definition *asd;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001269 error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd));
Saleem Abdulrasool9ede5c72014-04-13 03:11:08 +00001270
David Majnemer4d571592014-09-15 19:42:42 +00001271 int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
1272
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001273 outs() << "AUX "
1274 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
1275 , unsigned(asd->Length)
1276 , unsigned(asd->NumberOfRelocations)
1277 , unsigned(asd->NumberOfLinenumbers)
1278 , unsigned(asd->CheckSum))
1279 << format("assoc %d comdat %d\n"
David Majnemer4d571592014-09-15 19:42:42 +00001280 , unsigned(AuxNumber)
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001281 , unsigned(asd->Selection));
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001282 } else if (Symbol->isFileRecord()) {
David Majnemer44f51e52014-09-10 12:51:52 +00001283 const char *FileName;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001284 error(coff->getAuxSymbol<char>(SI + 1, FileName));
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +00001285
David Majnemer44f51e52014-09-10 12:51:52 +00001286 StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
1287 coff->getSymbolTableEntrySize());
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +00001288 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
Saleem Abdulrasool13a3f692014-04-14 16:38:25 +00001289
David Majnemer44f51e52014-09-10 12:51:52 +00001290 SI = SI + Symbol->getNumberOfAuxSymbols();
Saleem Abdulrasool13a3f692014-04-14 16:38:25 +00001291 break;
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +00001292 } else {
1293 outs() << "AUX Unknown\n";
Saleem Abdulrasool9ede5c72014-04-13 03:11:08 +00001294 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001295 }
1296 }
1297}
1298
Kevin Enderby98da6132015-01-20 21:47:46 +00001299void llvm::PrintSymbolTable(const ObjectFile *o) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001300 outs() << "SYMBOL TABLE:\n";
1301
Rui Ueyama4e39f712014-03-18 18:58:51 +00001302 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001303 PrintCOFFSymbolTable(coff);
Rui Ueyama4e39f712014-03-18 18:58:51 +00001304 return;
1305 }
1306 for (const SymbolRef &Symbol : o->symbols()) {
Rafael Espindolaed067c42015-07-03 18:19:00 +00001307 ErrorOr<uint64_t> AddressOrError = Symbol.getAddress();
Davide Italianoccd53fe2015-08-05 07:18:31 +00001308 error(AddressOrError.getError());
Rafael Espindolaed067c42015-07-03 18:19:00 +00001309 uint64_t Address = *AddressOrError;
Rafael Espindola2fa80cc2015-06-26 12:18:49 +00001310 SymbolRef::Type Type = Symbol.getType();
Rui Ueyama4e39f712014-03-18 18:58:51 +00001311 uint32_t Flags = Symbol.getFlags();
Rafael Espindola8bab8892015-08-07 23:27:14 +00001312 ErrorOr<section_iterator> SectionOrErr = Symbol.getSection();
1313 error(SectionOrErr.getError());
1314 section_iterator Section = *SectionOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001315 StringRef Name;
1316 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1317 Section->getName(Name);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001318 } else {
1319 ErrorOr<StringRef> NameOrErr = Symbol.getName();
Davide Italianoccd53fe2015-08-05 07:18:31 +00001320 error(NameOrErr.getError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001321 Name = *NameOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001322 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001323
Rui Ueyama4e39f712014-03-18 18:58:51 +00001324 bool Global = Flags & SymbolRef::SF_Global;
1325 bool Weak = Flags & SymbolRef::SF_Weak;
1326 bool Absolute = Flags & SymbolRef::SF_Absolute;
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001327 bool Common = Flags & SymbolRef::SF_Common;
Davide Italianocd2514d2015-04-30 23:08:53 +00001328 bool Hidden = Flags & SymbolRef::SF_Hidden;
David Meyer1df4b842012-02-28 23:47:53 +00001329
Rui Ueyama4e39f712014-03-18 18:58:51 +00001330 char GlobLoc = ' ';
1331 if (Type != SymbolRef::ST_Unknown)
1332 GlobLoc = Global ? 'g' : 'l';
1333 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1334 ? 'd' : ' ';
1335 char FileFunc = ' ';
1336 if (Type == SymbolRef::ST_File)
1337 FileFunc = 'f';
1338 else if (Type == SymbolRef::ST_Function)
1339 FileFunc = 'F';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001340
Rui Ueyama4e39f712014-03-18 18:58:51 +00001341 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1342 "%08" PRIx64;
Michael J. Spencerd857c1c2013-01-10 22:40:50 +00001343
Rui Ueyama4e39f712014-03-18 18:58:51 +00001344 outs() << format(Fmt, Address) << " "
1345 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1346 << (Weak ? 'w' : ' ') // Weak?
1347 << ' ' // Constructor. Not supported yet.
1348 << ' ' // Warning. Not supported yet.
1349 << ' ' // Indirect reference to another symbol.
1350 << Debug // Debugging (d) or dynamic (D) symbol.
1351 << FileFunc // Name of function (F), file (f) or object (O).
1352 << ' ';
1353 if (Absolute) {
1354 outs() << "*ABS*";
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001355 } else if (Common) {
1356 outs() << "*COM*";
Rui Ueyama4e39f712014-03-18 18:58:51 +00001357 } else if (Section == o->section_end()) {
1358 outs() << "*UND*";
1359 } else {
1360 if (const MachOObjectFile *MachO =
1361 dyn_cast<const MachOObjectFile>(o)) {
1362 DataRefImpl DR = Section->getRawDataRefImpl();
1363 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1364 outs() << SegmentName << ",";
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001365 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00001366 StringRef SectionName;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001367 error(Section->getName(SectionName));
Rui Ueyama4e39f712014-03-18 18:58:51 +00001368 outs() << SectionName;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001369 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001370
1371 outs() << '\t';
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001372 if (Common || isa<ELFObjectFileBase>(o)) {
Rafael Espindoladbb6bd32015-06-25 22:10:04 +00001373 uint64_t Val =
1374 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001375 outs() << format("\t %08" PRIx64 " ", Val);
1376 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001377
Davide Italianocd2514d2015-04-30 23:08:53 +00001378 if (Hidden) {
1379 outs() << ".hidden ";
1380 }
1381 outs() << Name
Rui Ueyama4e39f712014-03-18 18:58:51 +00001382 << '\n';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001383 }
1384}
1385
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001386static void PrintUnwindInfo(const ObjectFile *o) {
1387 outs() << "Unwind info:\n\n";
1388
1389 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1390 printCOFFUnwindInfo(coff);
Tim Northover4bd286a2014-08-01 13:07:19 +00001391 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1392 printMachOUnwindInfo(MachO);
1393 else {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001394 // TODO: Extract DWARF dump tool to objdump.
1395 errs() << "This operation is only currently supported "
Tim Northover4bd286a2014-08-01 13:07:19 +00001396 "for COFF and MachO object files.\n";
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001397 return;
1398 }
1399}
1400
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001401void llvm::printExportsTrie(const ObjectFile *o) {
Nick Kledzikd04bc352014-08-30 00:20:14 +00001402 outs() << "Exports trie:\n";
1403 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1404 printMachOExportsTrie(MachO);
1405 else {
1406 errs() << "This operation is only currently supported "
1407 "for Mach-O executable files.\n";
1408 return;
1409 }
1410}
1411
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001412void llvm::printRebaseTable(const ObjectFile *o) {
Nick Kledzikac431442014-09-12 21:34:15 +00001413 outs() << "Rebase table:\n";
1414 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1415 printMachORebaseTable(MachO);
1416 else {
1417 errs() << "This operation is only currently supported "
1418 "for Mach-O executable files.\n";
1419 return;
1420 }
1421}
1422
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001423void llvm::printBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001424 outs() << "Bind table:\n";
1425 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1426 printMachOBindTable(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::printLazyBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001435 outs() << "Lazy bind table:\n";
1436 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1437 printMachOLazyBindTable(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::printWeakBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001446 outs() << "Weak bind table:\n";
1447 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1448 printMachOWeakBindTable(MachO);
1449 else {
1450 errs() << "This operation is only currently supported "
1451 "for Mach-O executable files.\n";
1452 return;
1453 }
1454}
Nick Kledzikac431442014-09-12 21:34:15 +00001455
Adrian Prantl437105a2015-07-08 02:04:15 +00001456/// Dump the raw contents of the __clangast section so the output can be piped
1457/// into llvm-bcanalyzer.
1458void llvm::printRawClangAST(const ObjectFile *Obj) {
1459 if (outs().is_displayed()) {
1460 errs() << "The -raw-clang-ast option will dump the raw binary contents of "
1461 "the clang ast section.\n"
1462 "Please redirect the output to a file or another program such as "
1463 "llvm-bcanalyzer.\n";
1464 return;
1465 }
1466
1467 StringRef ClangASTSectionName("__clangast");
1468 if (isa<COFFObjectFile>(Obj)) {
1469 ClangASTSectionName = "clangast";
1470 }
1471
1472 Optional<object::SectionRef> ClangASTSection;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001473 for (auto Sec : ToolSectionFilter(*Obj)) {
Adrian Prantl437105a2015-07-08 02:04:15 +00001474 StringRef Name;
1475 Sec.getName(Name);
1476 if (Name == ClangASTSectionName) {
1477 ClangASTSection = Sec;
1478 break;
1479 }
1480 }
1481 if (!ClangASTSection)
1482 return;
1483
1484 StringRef ClangASTContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001485 error(ClangASTSection.getValue().getContents(ClangASTContents));
Adrian Prantl437105a2015-07-08 02:04:15 +00001486 outs().write(ClangASTContents.data(), ClangASTContents.size());
1487}
1488
Sanjoy Das6f567a42015-06-22 18:03:02 +00001489static void printFaultMaps(const ObjectFile *Obj) {
1490 const char *FaultMapSectionName = nullptr;
1491
1492 if (isa<ELFObjectFileBase>(Obj)) {
1493 FaultMapSectionName = ".llvm_faultmaps";
1494 } else if (isa<MachOObjectFile>(Obj)) {
1495 FaultMapSectionName = "__llvm_faultmaps";
1496 } else {
1497 errs() << "This operation is only currently supported "
1498 "for ELF and Mach-O executable files.\n";
1499 return;
1500 }
1501
1502 Optional<object::SectionRef> FaultMapSection;
1503
Colin LeMahieu77804be2015-07-29 15:45:39 +00001504 for (auto Sec : ToolSectionFilter(*Obj)) {
Sanjoy Das6f567a42015-06-22 18:03:02 +00001505 StringRef Name;
1506 Sec.getName(Name);
1507 if (Name == FaultMapSectionName) {
1508 FaultMapSection = Sec;
1509 break;
1510 }
1511 }
1512
1513 outs() << "FaultMap table:\n";
1514
1515 if (!FaultMapSection.hasValue()) {
1516 outs() << "<not found>\n";
1517 return;
1518 }
1519
1520 StringRef FaultMapContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001521 error(FaultMapSection.getValue().getContents(FaultMapContents));
Sanjoy Das6f567a42015-06-22 18:03:02 +00001522
1523 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1524 FaultMapContents.bytes_end());
1525
1526 outs() << FMP;
1527}
1528
Rui Ueyamac2bed422013-09-27 21:04:00 +00001529static void printPrivateFileHeader(const ObjectFile *o) {
Davide Italiano540e9212015-12-19 22:09:40 +00001530 if (o->isELF())
Rui Ueyamac2bed422013-09-27 21:04:00 +00001531 printELFFileHeader(o);
Davide Italiano540e9212015-12-19 22:09:40 +00001532 else if (o->isCOFF())
Rui Ueyamac2bed422013-09-27 21:04:00 +00001533 printCOFFFileHeader(o);
Davide Italiano540e9212015-12-19 22:09:40 +00001534 else if (o->isMachO())
Kevin Enderbyb76d3862014-08-22 20:35:18 +00001535 printMachOFileHeader(o);
Davide Italiano540e9212015-12-19 22:09:40 +00001536 else
1537 report_fatal_error("Invalid/Unsupported object file format");
Rui Ueyamac2bed422013-09-27 21:04:00 +00001538}
1539
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001540static void DumpObject(const ObjectFile *o) {
Adrian Prantl437105a2015-07-08 02:04:15 +00001541 // Avoid other output when using a raw option.
1542 if (!RawClangAST) {
1543 outs() << '\n';
1544 outs() << o->getFileName()
1545 << ":\tfile format " << o->getFileFormatName() << "\n\n";
1546 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001547
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001548 if (Disassemble)
Michael J. Spencer51862b32011-10-13 22:17:18 +00001549 DisassembleObject(o, Relocations);
1550 if (Relocations && !Disassemble)
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001551 PrintRelocations(o);
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001552 if (SectionHeaders)
1553 PrintSectionHeaders(o);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001554 if (SectionContents)
1555 PrintSectionContents(o);
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001556 if (SymbolTable)
1557 PrintSymbolTable(o);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001558 if (UnwindInfo)
1559 PrintUnwindInfo(o);
Rui Ueyamac2bed422013-09-27 21:04:00 +00001560 if (PrivateHeaders)
1561 printPrivateFileHeader(o);
Nick Kledzikd04bc352014-08-30 00:20:14 +00001562 if (ExportsTrie)
1563 printExportsTrie(o);
Nick Kledzikac431442014-09-12 21:34:15 +00001564 if (Rebase)
1565 printRebaseTable(o);
Nick Kledzik56ebef42014-09-16 01:41:51 +00001566 if (Bind)
1567 printBindTable(o);
1568 if (LazyBind)
1569 printLazyBindTable(o);
1570 if (WeakBind)
1571 printWeakBindTable(o);
Adrian Prantl437105a2015-07-08 02:04:15 +00001572 if (RawClangAST)
1573 printRawClangAST(o);
Sanjoy Das6f567a42015-06-22 18:03:02 +00001574 if (PrintFaultMaps)
1575 printFaultMaps(o);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001576}
1577
1578/// @brief Dump each object file in \a a;
1579static void DumpArchive(const Archive *a) {
Kevin Enderby7a969422015-11-05 19:24:56 +00001580 for (auto &ErrorOrChild : a->children()) {
1581 if (std::error_code EC = ErrorOrChild.getError())
1582 report_error(a->getFileName(), EC);
1583 const Archive::Child &C = *ErrorOrChild;
Davide Italiano95dd3cb2015-08-03 21:46:32 +00001584 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Davide Italianoccd53fe2015-08-05 07:18:31 +00001585 if (std::error_code EC = ChildOrErr.getError())
Mark Seaborneb03ac52014-01-25 00:32:01 +00001586 if (EC != object_error::invalid_file_type)
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001587 report_error(a->getFileName(), EC);
Rafael Espindolaae460022014-06-16 16:08:36 +00001588 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001589 DumpObject(o);
1590 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001591 report_error(a->getFileName(), object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001592 }
1593}
1594
1595/// @brief Open file and figure out how to dump it.
1596static void DumpInput(StringRef file) {
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001597
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001598 // If we are using the Mach-O specific object file parser, then let it parse
1599 // the file and process the command line options. So the -arch flags can
1600 // be used to select specific slices, etc.
1601 if (MachOOpt) {
1602 ParseInputMachO(file);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001603 return;
1604 }
1605
1606 // Attempt to open the binary.
Rafael Espindola48af1c22014-08-19 18:44:46 +00001607 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001608 if (std::error_code EC = BinaryOrErr.getError())
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001609 report_error(file, EC);
Rafael Espindola48af1c22014-08-19 18:44:46 +00001610 Binary &Binary = *BinaryOrErr.get().getBinary();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001611
Rafael Espindola3f6481d2014-08-01 14:31:55 +00001612 if (Archive *a = dyn_cast<Archive>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001613 DumpArchive(a);
Rafael Espindola3f6481d2014-08-01 14:31:55 +00001614 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001615 DumpObject(o);
Jim Grosbachaf9aec02012-08-07 17:53:14 +00001616 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001617 report_error(file, object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001618}
1619
Michael J. Spencer2670c252011-01-20 06:39:06 +00001620int main(int argc, char **argv) {
1621 // Print a stack trace if we signal out.
1622 sys::PrintStackTraceOnErrorSignal();
1623 PrettyStackTraceProgram X(argc, argv);
1624 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1625
1626 // Initialize targets and assembly printers/parsers.
1627 llvm::InitializeAllTargetInfos();
Evan Cheng8c886a42011-07-22 21:58:54 +00001628 llvm::InitializeAllTargetMCs();
Michael J. Spencer2670c252011-01-20 06:39:06 +00001629 llvm::InitializeAllDisassemblers();
1630
Pete Cooper28fb4fc2012-05-03 23:20:10 +00001631 // Register the target printer for --version.
1632 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
1633
Michael J. Spencer2670c252011-01-20 06:39:06 +00001634 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
1635 TripleName = Triple::normalize(TripleName);
1636
1637 ToolName = argv[0];
1638
1639 // Defaults to a.out if no filenames specified.
1640 if (InputFilenames.size() == 0)
1641 InputFilenames.push_back("a.out");
1642
Colin LeMahieuf34933e2015-07-23 20:58:49 +00001643 if (DisassembleAll)
1644 Disassemble = true;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001645 if (!Disassemble
1646 && !Relocations
1647 && !SectionHeaders
1648 && !SectionContents
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001649 && !SymbolTable
Michael J. Spencer209565db2013-01-06 03:56:49 +00001650 && !UnwindInfo
Nick Kledzikd04bc352014-08-30 00:20:14 +00001651 && !PrivateHeaders
Nick Kledzikac431442014-09-12 21:34:15 +00001652 && !ExportsTrie
Nick Kledzik56ebef42014-09-16 01:41:51 +00001653 && !Rebase
1654 && !Bind
1655 && !LazyBind
Kevin Enderby131d1772015-01-09 19:22:37 +00001656 && !WeakBind
Adrian Prantl437105a2015-07-08 02:04:15 +00001657 && !RawClangAST
Kevin Enderby13023a12015-01-15 23:19:11 +00001658 && !(UniversalHeaders && MachOOpt)
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001659 && !(ArchiveHeaders && MachOOpt)
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001660 && !(IndirectSymbols && MachOOpt)
Kevin Enderby9a509442015-01-27 21:28:24 +00001661 && !(DataInCode && MachOOpt)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001662 && !(LinkOptHints && MachOOpt)
Kevin Enderbycd66be52015-03-11 22:06:32 +00001663 && !(InfoPlist && MachOOpt)
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001664 && !(DylibsUsed && MachOOpt)
1665 && !(DylibId && MachOOpt)
Kevin Enderby0fc11822015-04-01 20:57:01 +00001666 && !(ObjcMetaData && MachOOpt)
Colin LeMahieufcc32762015-07-29 19:08:10 +00001667 && !(FilterSections.size() != 0 && MachOOpt)
Pete Cooper98052532015-12-18 19:45:38 +00001668 && !PrintFaultMaps) {
Michael J. Spencer2670c252011-01-20 06:39:06 +00001669 cl::PrintHelpMessage();
1670 return 2;
1671 }
1672
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001673 std::for_each(InputFilenames.begin(), InputFilenames.end(),
1674 DumpInput);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001675
Davide Italianoccd53fe2015-08-05 07:18:31 +00001676 return EXIT_SUCCESS;
Michael J. Spencer2670c252011-01-20 06:39:06 +00001677}