blob: 6eab69c1b2ec432d0f8d0e64afb73949edb40330 [file] [log] [blame]
Michael J. Spencer2670c252011-01-20 06:39:06 +00001//===-- llvm-objdump.cpp - Object file dumping utility for llvm -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This program is a utility that works like binutils "objdump", that is, it
11// dumps out a plethora of information about an object file depending on the
12// flags.
13//
Michael J. Spencerd7e70032013-02-05 20:27:22 +000014// The flags and output of this program should be near identical to those of
15// binutils objdump.
16//
Michael J. Spencer2670c252011-01-20 06:39:06 +000017//===----------------------------------------------------------------------===//
18
Benjamin Kramer43a772e2011-09-19 17:56:04 +000019#include "llvm-objdump.h"
Sanjoy Das6f567a42015-06-22 18:03:02 +000020#include "llvm/ADT/Optional.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000021#include "llvm/ADT/STLExtras.h"
Michael J. Spencer4e25c022011-10-17 17:13:22 +000022#include "llvm/ADT/StringExtras.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000023#include "llvm/ADT/Triple.h"
Sanjoy Das3f1bc3b2015-06-23 20:09:03 +000024#include "llvm/CodeGen/FaultMaps.h"
Igor Laevsky03a670c2016-01-26 15:09:42 +000025#include "llvm/DebugInfo/DWARF/DWARFContext.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000026#include "llvm/MC/MCAsmInfo.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000027#include "llvm/MC/MCContext.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000028#include "llvm/MC/MCDisassembler/MCDisassembler.h"
29#include "llvm/MC/MCDisassembler/MCRelocationInfo.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000030#include "llvm/MC/MCInst.h"
31#include "llvm/MC/MCInstPrinter.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000032#include "llvm/MC/MCInstrAnalysis.h"
Craig Topper54bfde72012-04-02 06:09:36 +000033#include "llvm/MC/MCInstrInfo.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000034#include "llvm/MC/MCObjectFileInfo.h"
Jim Grosbachfd93a592012-03-05 19:33:20 +000035#include "llvm/MC/MCRegisterInfo.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000036#include "llvm/MC/MCSubtargetInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000037#include "llvm/Object/Archive.h"
38#include "llvm/Object/COFF.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000039#include "llvm/Object/ELFObjectFile.h"
Rafael Espindolaa9f810b2012-12-21 03:47:03 +000040#include "llvm/Object/MachO.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000041#include "llvm/Object/ObjectFile.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000042#include "llvm/Support/Casting.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000043#include "llvm/Support/CommandLine.h"
44#include "llvm/Support/Debug.h"
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +000045#include "llvm/Support/Errc.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000046#include "llvm/Support/FileSystem.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000047#include "llvm/Support/Format.h"
Benjamin Kramerbf115312011-07-25 23:04:36 +000048#include "llvm/Support/GraphWriter.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000049#include "llvm/Support/Host.h"
50#include "llvm/Support/ManagedStatic.h"
51#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000052#include "llvm/Support/PrettyStackTrace.h"
53#include "llvm/Support/Signals.h"
54#include "llvm/Support/SourceMgr.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000055#include "llvm/Support/TargetRegistry.h"
56#include "llvm/Support/TargetSelect.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000057#include "llvm/Support/raw_ostream.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000058#include <algorithm>
Benjamin Kramera5177e62012-03-23 11:49:32 +000059#include <cctype>
Michael J. Spencer2670c252011-01-20 06:39:06 +000060#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000061#include <system_error>
Ahmed Bougacha17926472013-08-21 07:29:02 +000062
Michael J. Spencer2670c252011-01-20 06:39:06 +000063using namespace llvm;
64using namespace object;
65
Benjamin Kramer43a772e2011-09-19 17:56:04 +000066static cl::list<std::string>
67InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
Michael J. Spencer2670c252011-01-20 06:39:06 +000068
Kevin Enderbye2297dd2015-01-07 21:02:18 +000069cl::opt<bool>
70llvm::Disassemble("disassemble",
Benjamin Kramer43a772e2011-09-19 17:56:04 +000071 cl::desc("Display assembler mnemonics for the machine instructions"));
72static cl::alias
73Disassembled("d", cl::desc("Alias for --disassemble"),
Colin LeMahieu77804be2015-07-29 15:45:39 +000074 cl::aliasopt(Disassemble));
75
76cl::opt<bool>
77llvm::DisassembleAll("disassemble-all",
78 cl::desc("Display assembler mnemonics for the machine instructions"));
79static cl::alias
80DisassembleAlld("D", cl::desc("Alias for --disassemble-all"),
Colin LeMahieuf34933e2015-07-23 20:58:49 +000081 cl::aliasopt(DisassembleAll));
Michael J. Spencer2670c252011-01-20 06:39:06 +000082
Kevin Enderby98da6132015-01-20 21:47:46 +000083cl::opt<bool>
84llvm::Relocations("r", cl::desc("Display the relocation entries in the file"));
Michael J. Spencerba4a3622011-10-08 00:18:30 +000085
Kevin Enderby98da6132015-01-20 21:47:46 +000086cl::opt<bool>
87llvm::SectionContents("s", cl::desc("Display the content of each section"));
Michael J. Spencer4e25c022011-10-17 17:13:22 +000088
Kevin Enderby98da6132015-01-20 21:47:46 +000089cl::opt<bool>
90llvm::SymbolTable("t", cl::desc("Display the symbol table"));
Michael J. Spencerbfa06782011-10-18 19:32:17 +000091
Kevin Enderbye2297dd2015-01-07 21:02:18 +000092cl::opt<bool>
93llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
Nick Kledzikd04bc352014-08-30 00:20:14 +000094
Kevin Enderbye2297dd2015-01-07 21:02:18 +000095cl::opt<bool>
96llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
Nick Kledzikac431442014-09-12 21:34:15 +000097
Kevin Enderbye2297dd2015-01-07 21:02:18 +000098cl::opt<bool>
99llvm::Bind("bind", cl::desc("Display mach-o binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000100
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000101cl::opt<bool>
102llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000103
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000104cl::opt<bool>
105llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000106
Adrian Prantl437105a2015-07-08 02:04:15 +0000107cl::opt<bool>
108llvm::RawClangAST("raw-clang-ast",
109 cl::desc("Dump the raw binary contents of the clang AST section"));
110
Nick Kledzik56ebef42014-09-16 01:41:51 +0000111static cl::opt<bool>
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000112MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000113static cl::alias
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000114MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
Benjamin Kramer87ee76c2011-07-20 19:37:35 +0000115
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000116cl::opt<std::string>
117llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
118 "see -version for available targets"));
119
120cl::opt<std::string>
Kevin Enderbyc9595622014-08-06 23:24:41 +0000121llvm::MCPU("mcpu",
122 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
123 cl::value_desc("cpu-name"),
124 cl::init(""));
125
126cl::opt<std::string>
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000127llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
Michael J. Spencer2670c252011-01-20 06:39:06 +0000128 "see -version for available targets"));
129
Kevin Enderby98da6132015-01-20 21:47:46 +0000130cl::opt<bool>
131llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
132 "headers for each section."));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000133static cl::alias
134SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
135 cl::aliasopt(SectionHeaders));
136static cl::alias
137SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
138 cl::aliasopt(SectionHeaders));
Colin LeMahieufcc32762015-07-29 19:08:10 +0000139
Colin LeMahieu77804be2015-07-29 15:45:39 +0000140cl::list<std::string>
Colin LeMahieufcc32762015-07-29 19:08:10 +0000141llvm::FilterSections("section", cl::desc("Operate on the specified sections only. "
142 "With -macho dump segment,section"));
143cl::alias
144static FilterSectionsj("j", cl::desc("Alias for --section"),
145 cl::aliasopt(llvm::FilterSections));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000146
Kevin Enderbyc9595622014-08-06 23:24:41 +0000147cl::list<std::string>
148llvm::MAttrs("mattr",
Jack Carter551efd72012-08-28 19:24:49 +0000149 cl::CommaSeparated,
150 cl::desc("Target specific attributes"),
151 cl::value_desc("a1,+a2,-a3,..."));
152
Kevin Enderbybf246f52014-09-24 23:08:22 +0000153cl::opt<bool>
154llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
155 "instructions, do not print "
156 "the instruction bytes."));
Eli Bendersky3a6808c2012-11-20 22:57:02 +0000157
Kevin Enderby98da6132015-01-20 21:47:46 +0000158cl::opt<bool>
159llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000160
161static cl::alias
162UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
163 cl::aliasopt(UnwindInfo));
164
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000165cl::opt<bool>
166llvm::PrivateHeaders("private-headers",
167 cl::desc("Display format specific file headers"));
Michael J. Spencer209565db2013-01-06 03:56:49 +0000168
Kevin Enderby0ae163f2016-01-13 00:25:36 +0000169cl::opt<bool>
170llvm::FirstPrivateHeader("private-header",
171 cl::desc("Display only the first format specific file "
172 "header"));
173
Michael J. Spencer209565db2013-01-06 03:56:49 +0000174static cl::alias
175PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
176 cl::aliasopt(PrivateHeaders));
177
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000178cl::opt<bool>
179 llvm::PrintImmHex("print-imm-hex",
Colin LeMahieuefe37322016-04-08 18:15:37 +0000180 cl::desc("Use hex format for immediate values"));
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000181
Sanjoy Das6f567a42015-06-22 18:03:02 +0000182cl::opt<bool> PrintFaultMaps("fault-map-section",
183 cl::desc("Display contents of faultmap section"));
184
Igor Laevsky03a670c2016-01-26 15:09:42 +0000185cl::opt<DIDumpType> llvm::DwarfDumpType(
186 "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"),
187 cl::values(clEnumValN(DIDT_Frames, "frames", ".debug_frame"),
188 clEnumValEnd));
189
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000190static StringRef ToolName;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000191
Colin LeMahieu77804be2015-07-29 15:45:39 +0000192namespace {
Colin LeMahieufcc32762015-07-29 19:08:10 +0000193typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate;
Colin LeMahieu77804be2015-07-29 15:45:39 +0000194
195class SectionFilterIterator {
196public:
197 SectionFilterIterator(FilterPredicate P,
198 llvm::object::section_iterator const &I,
199 llvm::object::section_iterator const &E)
200 : Predicate(P), Iterator(I), End(E) {
201 ScanPredicate();
202 }
Benjamin Kramerac9257b2015-09-24 14:52:52 +0000203 const llvm::object::SectionRef &operator*() const { return *Iterator; }
Colin LeMahieu77804be2015-07-29 15:45:39 +0000204 SectionFilterIterator &operator++() {
205 ++Iterator;
206 ScanPredicate();
207 return *this;
208 }
209 bool operator!=(SectionFilterIterator const &Other) const {
210 return Iterator != Other.Iterator;
211 }
212
213private:
214 void ScanPredicate() {
Colin LeMahieuda1723f2015-07-29 19:21:13 +0000215 while (Iterator != End && !Predicate(*Iterator)) {
Colin LeMahieu77804be2015-07-29 15:45:39 +0000216 ++Iterator;
217 }
218 }
219 FilterPredicate Predicate;
220 llvm::object::section_iterator Iterator;
221 llvm::object::section_iterator End;
222};
223
224class SectionFilter {
225public:
226 SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O)
227 : Predicate(P), Object(O) {}
228 SectionFilterIterator begin() {
229 return SectionFilterIterator(Predicate, Object.section_begin(),
230 Object.section_end());
231 }
232 SectionFilterIterator end() {
233 return SectionFilterIterator(Predicate, Object.section_end(),
234 Object.section_end());
235 }
236
237private:
238 FilterPredicate Predicate;
239 llvm::object::ObjectFile const &Object;
240};
241SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) {
Colin LeMahieu77804be2015-07-29 15:45:39 +0000242 return SectionFilter([](llvm::object::SectionRef const &S) {
Colin LeMahieufcc32762015-07-29 19:08:10 +0000243 if(FilterSections.empty())
Colin LeMahieuda1723f2015-07-29 19:21:13 +0000244 return true;
Colin LeMahieu77804be2015-07-29 15:45:39 +0000245 llvm::StringRef String;
246 std::error_code error = S.getName(String);
Colin LeMahieufcc32762015-07-29 19:08:10 +0000247 if (error)
Colin LeMahieuda1723f2015-07-29 19:21:13 +0000248 return false;
Colin LeMahieufcc32762015-07-29 19:08:10 +0000249 return std::find(FilterSections.begin(),
250 FilterSections.end(),
Colin LeMahieuda1723f2015-07-29 19:21:13 +0000251 String) != FilterSections.end();
Colin LeMahieu77804be2015-07-29 15:45:39 +0000252 },
253 O);
254}
255}
256
Davide Italianoccd53fe2015-08-05 07:18:31 +0000257void llvm::error(std::error_code EC) {
Mark Seaborneb03ac52014-01-25 00:32:01 +0000258 if (!EC)
Davide Italianoccd53fe2015-08-05 07:18:31 +0000259 return;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000260
Davide Italiano140af642015-12-25 18:16:45 +0000261 errs() << ToolName << ": error reading file: " << EC.message() << ".\n";
262 errs().flush();
Davide Italiano7f6c3012015-08-06 00:18:52 +0000263 exit(1);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000264}
265
Davide Italianoed9d95b2015-12-29 13:41:02 +0000266LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
267 std::error_code EC) {
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000268 assert(EC);
269 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
Davide Italianoccd53fe2015-08-05 07:18:31 +0000270 exit(1);
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000271}
272
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000273LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
274 llvm::Error E) {
275 assert(E);
276 std::string Buf;
277 raw_string_ostream OS(Buf);
278 logAllUnhandledErrors(std::move(E), OS, "");
279 OS.flush();
280 errs() << ToolName << ": " << Buf;
281 exit(1);
282}
283
Craig Toppere6cb63e2014-04-25 04:24:47 +0000284static const Target *getTarget(const ObjectFile *Obj = nullptr) {
Michael J. Spencer2670c252011-01-20 06:39:06 +0000285 // Figure out the target triple.
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000286 llvm::Triple TheTriple("unknown-unknown-unknown");
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000287 if (TripleName.empty()) {
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000288 if (Obj) {
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000289 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000290 // TheTriple defaults to ELF, and COFF doesn't have an environment:
291 // the best we can do here is indicate that it is mach-o.
292 if (Obj->isMachO())
Saleem Abdulrasool35476332014-03-06 20:47:11 +0000293 TheTriple.setObjectFormat(Triple::MachO);
Saleem Abdulrasool98938f12014-04-17 06:17:23 +0000294
295 if (Obj->isCOFF()) {
296 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
297 if (COFFObj->getArch() == Triple::thumb)
298 TheTriple.setTriple("thumbv7-windows");
299 }
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000300 }
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000301 } else
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000302 TheTriple.setTriple(Triple::normalize(TripleName));
Michael J. Spencer2670c252011-01-20 06:39:06 +0000303
304 // Get the target specific parser.
305 std::string Error;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000306 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
307 Error);
Davide Italianobb599e32015-12-03 22:13:40 +0000308 if (!TheTarget)
309 report_fatal_error("can't find target: " + Error);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000310
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000311 // Update the triple name and return the found target.
312 TripleName = TheTriple.getTriple();
313 return TheTarget;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000314}
315
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000316bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
Rafael Espindola704cd842015-07-06 15:47:43 +0000317 return a.getOffset() < b.getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +0000318}
319
Colin LeMahieufb76b002015-05-28 19:07:14 +0000320namespace {
321class PrettyPrinter {
322public:
Colin LeMahieu0b5890d2015-05-28 20:59:08 +0000323 virtual ~PrettyPrinter(){}
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000324 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
Colin LeMahieufb76b002015-05-28 19:07:14 +0000325 ArrayRef<uint8_t> Bytes, uint64_t Address,
326 raw_ostream &OS, StringRef Annot,
327 MCSubtargetInfo const &STI) {
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000328 OS << format("%8" PRIx64 ":", Address);
Colin LeMahieufb76b002015-05-28 19:07:14 +0000329 if (!NoShowRawInsn) {
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000330 OS << "\t";
331 dumpBytes(Bytes, OS);
Colin LeMahieufb76b002015-05-28 19:07:14 +0000332 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000333 if (MI)
334 IP.printInst(MI, OS, "", STI);
335 else
336 OS << " <unknown>";
Colin LeMahieufb76b002015-05-28 19:07:14 +0000337 }
338};
339PrettyPrinter PrettyPrinterInst;
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000340class HexagonPrettyPrinter : public PrettyPrinter {
341public:
342 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
343 raw_ostream &OS) {
344 uint32_t opcode =
345 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
346 OS << format("%8" PRIx64 ":", Address);
347 if (!NoShowRawInsn) {
348 OS << "\t";
349 dumpBytes(Bytes.slice(0, 4), OS);
350 OS << format("%08" PRIx32, opcode);
351 }
352 }
353 void printInst(MCInstPrinter &IP, const MCInst *MI,
354 ArrayRef<uint8_t> Bytes, uint64_t Address,
355 raw_ostream &OS, StringRef Annot,
356 MCSubtargetInfo const &STI) override {
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000357 if (!MI) {
358 printLead(Bytes, Address, OS);
359 OS << " <unknown>";
360 return;
361 }
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000362 std::string Buffer;
363 {
364 raw_string_ostream TempStream(Buffer);
365 IP.printInst(MI, TempStream, "", STI);
366 }
367 StringRef Contents(Buffer);
368 // Split off bundle attributes
369 auto PacketBundle = Contents.rsplit('\n');
370 // Split off first instruction from the rest
371 auto HeadTail = PacketBundle.first.split('\n');
372 auto Preamble = " { ";
373 auto Separator = "";
374 while(!HeadTail.first.empty()) {
375 OS << Separator;
376 Separator = "\n";
377 printLead(Bytes, Address, OS);
378 OS << Preamble;
379 Preamble = " ";
380 StringRef Inst;
381 auto Duplex = HeadTail.first.split('\v');
382 if(!Duplex.second.empty()){
383 OS << Duplex.first;
384 OS << "; ";
385 Inst = Duplex.second;
386 }
387 else
388 Inst = HeadTail.first;
389 OS << Inst;
390 Bytes = Bytes.slice(4);
391 Address += 4;
392 HeadTail = HeadTail.second.split('\n');
393 }
394 OS << " } " << PacketBundle.second;
395 }
396};
397HexagonPrettyPrinter HexagonPrettyPrinterInst;
Valery Pykhtinde048052016-04-07 07:24:01 +0000398
399class AMDGCNPrettyPrinter : public PrettyPrinter {
400public:
401 void printInst(MCInstPrinter &IP,
402 const MCInst *MI,
403 ArrayRef<uint8_t> Bytes,
404 uint64_t Address,
405 raw_ostream &OS,
406 StringRef Annot,
407 MCSubtargetInfo const &STI) override {
408 SmallString<40> InstStr;
409 raw_svector_ostream IS(InstStr);
410
411 IP.printInst(MI, IS, "", STI);
412
Valery Pykhtin8e79f5b2016-04-07 08:38:20 +0000413 OS << left_justify(IS.str(), 60) << format("// %012" PRIX64 ": ", Address);
Valery Pykhtinde048052016-04-07 07:24:01 +0000414 typedef support::ulittle32_t U32;
415 for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
416 Bytes.size() / sizeof(U32)))
417 // D should be explicitly casted to uint32_t here as it is passed
418 // by format to snprintf as vararg.
Valery Pykhtin8e79f5b2016-04-07 08:38:20 +0000419 OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D));
Valery Pykhtinde048052016-04-07 07:24:01 +0000420
421 if (!Annot.empty())
422 OS << "// " << Annot;
423 }
424};
425AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
426
Colin LeMahieu35436a22015-05-29 14:48:25 +0000427PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000428 switch(Triple.getArch()) {
429 default:
430 return PrettyPrinterInst;
431 case Triple::hexagon:
432 return HexagonPrettyPrinterInst;
Valery Pykhtinde048052016-04-07 07:24:01 +0000433 case Triple::amdgcn:
434 return AMDGCNPrettyPrinterInst;
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000435 }
Colin LeMahieufb76b002015-05-28 19:07:14 +0000436}
437}
438
Rafael Espindola37070a52015-06-03 04:48:06 +0000439template <class ELFT>
Rafael Espindola37070a52015-06-03 04:48:06 +0000440static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000441 const RelocationRef &RelRef,
Rafael Espindola37070a52015-06-03 04:48:06 +0000442 SmallVectorImpl<char> &Result) {
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000443 DataRefImpl Rel = RelRef.getRawDataRefImpl();
444
Rafael Espindola37070a52015-06-03 04:48:06 +0000445 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
446 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000447 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
448
Rafael Espindola37070a52015-06-03 04:48:06 +0000449 const ELFFile<ELFT> &EF = *Obj->getELFFile();
450
Rafael Espindola6def3042015-07-01 12:56:27 +0000451 ErrorOr<const Elf_Shdr *> SecOrErr = EF.getSection(Rel.d.a);
452 if (std::error_code EC = SecOrErr.getError())
453 return EC;
454 const Elf_Shdr *Sec = *SecOrErr;
455 ErrorOr<const Elf_Shdr *> SymTabOrErr = EF.getSection(Sec->sh_link);
456 if (std::error_code EC = SymTabOrErr.getError())
457 return EC;
458 const Elf_Shdr *SymTab = *SymTabOrErr;
Rafael Espindola719dc7c2015-06-29 12:38:31 +0000459 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
460 SymTab->sh_type == ELF::SHT_DYNSYM);
Rafael Espindola6def3042015-07-01 12:56:27 +0000461 ErrorOr<const Elf_Shdr *> StrTabSec = EF.getSection(SymTab->sh_link);
462 if (std::error_code EC = StrTabSec.getError())
463 return EC;
464 ErrorOr<StringRef> StrTabOrErr = EF.getStringTable(*StrTabSec);
Rafael Espindola6a1bfb22015-06-29 14:39:25 +0000465 if (std::error_code EC = StrTabOrErr.getError())
466 return EC;
467 StringRef StrTab = *StrTabOrErr;
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000468 uint8_t type = RelRef.getType();
Rafael Espindola37070a52015-06-03 04:48:06 +0000469 StringRef res;
470 int64_t addend = 0;
Rafael Espindola6def3042015-07-01 12:56:27 +0000471 switch (Sec->sh_type) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000472 default:
473 return object_error::parse_failed;
474 case ELF::SHT_REL: {
Rafael Espindola37070a52015-06-03 04:48:06 +0000475 // TODO: Read implicit addend from section data.
476 break;
477 }
478 case ELF::SHT_RELA: {
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000479 const Elf_Rela *ERela = Obj->getRela(Rel);
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000480 addend = ERela->r_addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000481 break;
482 }
483 }
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000484 symbol_iterator SI = RelRef.getSymbol();
485 const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
Rafael Espindola75d5b542015-06-03 05:14:22 +0000486 StringRef Target;
Rafael Espindola75d5b542015-06-03 05:14:22 +0000487 if (symb->getType() == ELF::STT_SECTION) {
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000488 ErrorOr<section_iterator> SymSI = SI->getSection();
489 if (std::error_code EC = SymSI.getError())
490 return EC;
491 const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
492 ErrorOr<StringRef> SecName = EF.getSectionName(SymSec);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000493 if (std::error_code EC = SecName.getError())
494 return EC;
495 Target = *SecName;
496 } else {
Rafael Espindola44c28712015-06-29 21:24:55 +0000497 ErrorOr<StringRef> SymName = symb->getName(StrTab);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000498 if (!SymName)
499 return SymName.getError();
500 Target = *SymName;
501 }
Rafael Espindola37070a52015-06-03 04:48:06 +0000502 switch (EF.getHeader()->e_machine) {
503 case ELF::EM_X86_64:
504 switch (type) {
505 case ELF::R_X86_64_PC8:
506 case ELF::R_X86_64_PC16:
507 case ELF::R_X86_64_PC32: {
508 std::string fmtbuf;
509 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000510 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
Rafael Espindola37070a52015-06-03 04:48:06 +0000511 fmt.flush();
512 Result.append(fmtbuf.begin(), fmtbuf.end());
513 } break;
514 case ELF::R_X86_64_8:
515 case ELF::R_X86_64_16:
516 case ELF::R_X86_64_32:
517 case ELF::R_X86_64_32S:
518 case ELF::R_X86_64_64: {
519 std::string fmtbuf;
520 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000521 fmt << Target << (addend < 0 ? "" : "+") << addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000522 fmt.flush();
523 Result.append(fmtbuf.begin(), fmtbuf.end());
524 } break;
525 default:
526 res = "Unknown";
527 }
528 break;
Jacques Pienaarea9f25a2016-03-01 21:21:42 +0000529 case ELF::EM_LANAI:
Rafael Espindola37070a52015-06-03 04:48:06 +0000530 case ELF::EM_AARCH64: {
531 std::string fmtbuf;
532 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000533 fmt << Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000534 if (addend != 0)
535 fmt << (addend < 0 ? "" : "+") << addend;
536 fmt.flush();
537 Result.append(fmtbuf.begin(), fmtbuf.end());
538 break;
539 }
540 case ELF::EM_386:
Michael Kupersteina3b79dd2015-11-04 11:21:50 +0000541 case ELF::EM_IAMCU:
Rafael Espindola37070a52015-06-03 04:48:06 +0000542 case ELF::EM_ARM:
543 case ELF::EM_HEXAGON:
544 case ELF::EM_MIPS:
Rafael Espindola75d5b542015-06-03 05:14:22 +0000545 res = Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000546 break;
Dan Gohman46350172016-01-12 20:56:01 +0000547 case ELF::EM_WEBASSEMBLY:
548 switch (type) {
549 case ELF::R_WEBASSEMBLY_DATA: {
550 std::string fmtbuf;
551 raw_string_ostream fmt(fmtbuf);
552 fmt << Target << (addend < 0 ? "" : "+") << addend;
553 fmt.flush();
554 Result.append(fmtbuf.begin(), fmtbuf.end());
555 break;
556 }
557 case ELF::R_WEBASSEMBLY_FUNCTION:
558 res = Target;
559 break;
560 default:
561 res = "Unknown";
562 }
563 break;
Rafael Espindola37070a52015-06-03 04:48:06 +0000564 default:
565 res = "Unknown";
566 }
567 if (Result.empty())
568 Result.append(res.begin(), res.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000569 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000570}
571
572static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000573 const RelocationRef &Rel,
Rafael Espindola37070a52015-06-03 04:48:06 +0000574 SmallVectorImpl<char> &Result) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000575 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
576 return getRelocationValueString(ELF32LE, Rel, Result);
577 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
578 return getRelocationValueString(ELF64LE, Rel, Result);
579 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
580 return getRelocationValueString(ELF32BE, Rel, Result);
581 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
582 return getRelocationValueString(ELF64BE, Rel, Result);
583}
584
585static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
586 const RelocationRef &Rel,
587 SmallVectorImpl<char> &Result) {
588 symbol_iterator SymI = Rel.getSymbol();
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000589 ErrorOr<StringRef> SymNameOrErr = SymI->getName();
590 if (std::error_code EC = SymNameOrErr.getError())
Rafael Espindola37070a52015-06-03 04:48:06 +0000591 return EC;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000592 StringRef SymName = *SymNameOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000593 Result.append(SymName.begin(), SymName.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000594 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000595}
596
597static void printRelocationTargetName(const MachOObjectFile *O,
598 const MachO::any_relocation_info &RE,
599 raw_string_ostream &fmt) {
600 bool IsScattered = O->isRelocationScattered(RE);
601
602 // Target of a scattered relocation is an address. In the interest of
603 // generating pretty output, scan through the symbol table looking for a
604 // symbol that aligns with that address. If we find one, print it.
605 // Otherwise, we just print the hex address of the target.
606 if (IsScattered) {
607 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
608
609 for (const SymbolRef &Symbol : O->symbols()) {
610 std::error_code ec;
Rafael Espindolaed067c42015-07-03 18:19:00 +0000611 ErrorOr<uint64_t> Addr = Symbol.getAddress();
612 if ((ec = Addr.getError()))
Rafael Espindola37070a52015-06-03 04:48:06 +0000613 report_fatal_error(ec.message());
Rafael Espindolaed067c42015-07-03 18:19:00 +0000614 if (*Addr != Val)
Rafael Espindola37070a52015-06-03 04:48:06 +0000615 continue;
Rafael Espindolaed067c42015-07-03 18:19:00 +0000616 ErrorOr<StringRef> Name = Symbol.getName();
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000617 if (std::error_code EC = Name.getError())
618 report_fatal_error(EC.message());
619 fmt << *Name;
Rafael Espindola37070a52015-06-03 04:48:06 +0000620 return;
621 }
622
623 // If we couldn't find a symbol that this relocation refers to, try
624 // to find a section beginning instead.
Colin LeMahieu77804be2015-07-29 15:45:39 +0000625 for (const SectionRef &Section : ToolSectionFilter(*O)) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000626 std::error_code ec;
627
628 StringRef Name;
629 uint64_t Addr = Section.getAddress();
630 if (Addr != Val)
631 continue;
632 if ((ec = Section.getName(Name)))
633 report_fatal_error(ec.message());
634 fmt << Name;
635 return;
636 }
637
638 fmt << format("0x%x", Val);
639 return;
640 }
641
642 StringRef S;
643 bool isExtern = O->getPlainRelocationExternal(RE);
644 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
645
646 if (isExtern) {
647 symbol_iterator SI = O->symbol_begin();
648 advance(SI, Val);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000649 ErrorOr<StringRef> SOrErr = SI->getName();
Davide Italianoccd53fe2015-08-05 07:18:31 +0000650 error(SOrErr.getError());
651 S = *SOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000652 } else {
653 section_iterator SI = O->section_begin();
654 // Adjust for the fact that sections are 1-indexed.
655 advance(SI, Val - 1);
656 SI->getName(S);
657 }
658
659 fmt << S;
660}
661
662static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
663 const RelocationRef &RelRef,
664 SmallVectorImpl<char> &Result) {
665 DataRefImpl Rel = RelRef.getRawDataRefImpl();
666 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
667
668 unsigned Arch = Obj->getArch();
669
670 std::string fmtbuf;
671 raw_string_ostream fmt(fmtbuf);
672 unsigned Type = Obj->getAnyRelocationType(RE);
673 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
674
675 // Determine any addends that should be displayed with the relocation.
676 // These require decoding the relocation type, which is triple-specific.
677
678 // X86_64 has entirely custom relocation types.
679 if (Arch == Triple::x86_64) {
680 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
681
682 switch (Type) {
683 case MachO::X86_64_RELOC_GOT_LOAD:
684 case MachO::X86_64_RELOC_GOT: {
685 printRelocationTargetName(Obj, RE, fmt);
686 fmt << "@GOT";
687 if (isPCRel)
688 fmt << "PCREL";
689 break;
690 }
691 case MachO::X86_64_RELOC_SUBTRACTOR: {
692 DataRefImpl RelNext = Rel;
693 Obj->moveRelocationNext(RelNext);
694 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
695
696 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
697 // X86_64_RELOC_UNSIGNED.
698 // NOTE: Scattered relocations don't exist on x86_64.
699 unsigned RType = Obj->getAnyRelocationType(RENext);
700 if (RType != MachO::X86_64_RELOC_UNSIGNED)
701 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
702 "X86_64_RELOC_SUBTRACTOR.");
703
704 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
705 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
706 printRelocationTargetName(Obj, RENext, fmt);
707 fmt << "-";
708 printRelocationTargetName(Obj, RE, fmt);
709 break;
710 }
711 case MachO::X86_64_RELOC_TLV:
712 printRelocationTargetName(Obj, RE, fmt);
713 fmt << "@TLV";
714 if (isPCRel)
715 fmt << "P";
716 break;
717 case MachO::X86_64_RELOC_SIGNED_1:
718 printRelocationTargetName(Obj, RE, fmt);
719 fmt << "-1";
720 break;
721 case MachO::X86_64_RELOC_SIGNED_2:
722 printRelocationTargetName(Obj, RE, fmt);
723 fmt << "-2";
724 break;
725 case MachO::X86_64_RELOC_SIGNED_4:
726 printRelocationTargetName(Obj, RE, fmt);
727 fmt << "-4";
728 break;
729 default:
730 printRelocationTargetName(Obj, RE, fmt);
731 break;
732 }
733 // X86 and ARM share some relocation types in common.
734 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
735 Arch == Triple::ppc) {
736 // Generic relocation types...
737 switch (Type) {
738 case MachO::GENERIC_RELOC_PAIR: // prints no info
Rui Ueyama7d099192015-06-09 15:20:42 +0000739 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000740 case MachO::GENERIC_RELOC_SECTDIFF: {
741 DataRefImpl RelNext = Rel;
742 Obj->moveRelocationNext(RelNext);
743 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
744
745 // X86 sect diff's must be followed by a relocation of type
746 // GENERIC_RELOC_PAIR.
747 unsigned RType = Obj->getAnyRelocationType(RENext);
748
749 if (RType != MachO::GENERIC_RELOC_PAIR)
750 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
751 "GENERIC_RELOC_SECTDIFF.");
752
753 printRelocationTargetName(Obj, RE, fmt);
754 fmt << "-";
755 printRelocationTargetName(Obj, RENext, fmt);
756 break;
757 }
758 }
759
760 if (Arch == Triple::x86 || Arch == Triple::ppc) {
761 switch (Type) {
762 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
763 DataRefImpl RelNext = Rel;
764 Obj->moveRelocationNext(RelNext);
765 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
766
767 // X86 sect diff's must be followed by a relocation of type
768 // GENERIC_RELOC_PAIR.
769 unsigned RType = Obj->getAnyRelocationType(RENext);
770 if (RType != MachO::GENERIC_RELOC_PAIR)
771 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
772 "GENERIC_RELOC_LOCAL_SECTDIFF.");
773
774 printRelocationTargetName(Obj, RE, fmt);
775 fmt << "-";
776 printRelocationTargetName(Obj, RENext, fmt);
777 break;
778 }
779 case MachO::GENERIC_RELOC_TLV: {
780 printRelocationTargetName(Obj, RE, fmt);
781 fmt << "@TLV";
782 if (IsPCRel)
783 fmt << "P";
784 break;
785 }
786 default:
787 printRelocationTargetName(Obj, RE, fmt);
788 }
789 } else { // ARM-specific relocations
790 switch (Type) {
791 case MachO::ARM_RELOC_HALF:
792 case MachO::ARM_RELOC_HALF_SECTDIFF: {
793 // Half relocations steal a bit from the length field to encode
794 // whether this is an upper16 or a lower16 relocation.
795 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
796
797 if (isUpper)
798 fmt << ":upper16:(";
799 else
800 fmt << ":lower16:(";
801 printRelocationTargetName(Obj, RE, fmt);
802
803 DataRefImpl RelNext = Rel;
804 Obj->moveRelocationNext(RelNext);
805 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
806
807 // ARM half relocs must be followed by a relocation of type
808 // ARM_RELOC_PAIR.
809 unsigned RType = Obj->getAnyRelocationType(RENext);
810 if (RType != MachO::ARM_RELOC_PAIR)
811 report_fatal_error("Expected ARM_RELOC_PAIR after "
812 "ARM_RELOC_HALF");
813
814 // NOTE: The half of the target virtual address is stashed in the
815 // address field of the secondary relocation, but we can't reverse
816 // engineer the constant offset from it without decoding the movw/movt
817 // instruction to find the other half in its immediate field.
818
819 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
820 // symbol/section pointer of the follow-on relocation.
821 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
822 fmt << "-";
823 printRelocationTargetName(Obj, RENext, fmt);
824 }
825
826 fmt << ")";
827 break;
828 }
829 default: { printRelocationTargetName(Obj, RE, fmt); }
830 }
831 }
832 } else
833 printRelocationTargetName(Obj, RE, fmt);
834
835 fmt.flush();
836 Result.append(fmtbuf.begin(), fmtbuf.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000837 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000838}
839
840static std::error_code getRelocationValueString(const RelocationRef &Rel,
841 SmallVectorImpl<char> &Result) {
Rafael Espindola854038e2015-06-26 14:51:16 +0000842 const ObjectFile *Obj = Rel.getObject();
Rafael Espindola37070a52015-06-03 04:48:06 +0000843 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
844 return getRelocationValueString(ELF, Rel, Result);
845 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
846 return getRelocationValueString(COFF, Rel, Result);
847 auto *MachO = cast<MachOObjectFile>(Obj);
848 return getRelocationValueString(MachO, Rel, Result);
849}
850
Rafael Espindola0ad71d92015-06-30 03:41:26 +0000851/// @brief Indicates whether this relocation should hidden when listing
852/// relocations, usually because it is the trailing part of a multipart
853/// relocation that will be printed as part of the leading relocation.
854static bool getHidden(RelocationRef RelRef) {
855 const ObjectFile *Obj = RelRef.getObject();
856 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
857 if (!MachO)
858 return false;
859
860 unsigned Arch = MachO->getArch();
861 DataRefImpl Rel = RelRef.getRawDataRefImpl();
862 uint64_t Type = MachO->getRelocationType(Rel);
863
864 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
865 // is always hidden.
866 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
867 if (Type == MachO::GENERIC_RELOC_PAIR)
868 return true;
869 } else if (Arch == Triple::x86_64) {
870 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
871 // an X86_64_RELOC_SUBTRACTOR.
872 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
873 DataRefImpl RelPrev = Rel;
874 RelPrev.d.a--;
875 uint64_t PrevType = MachO->getRelocationType(RelPrev);
876 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
877 return true;
878 }
879 }
880
881 return false;
882}
883
Michael J. Spencer51862b32011-10-13 22:17:18 +0000884static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Jim Grosbachaf9aec02012-08-07 17:53:14 +0000885 const Target *TheTarget = getTarget(Obj);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000886
Jack Carter551efd72012-08-28 19:24:49 +0000887 // Package up features to be passed to target/subtarget
888 std::string FeaturesStr;
889 if (MAttrs.size()) {
890 SubtargetFeatures Features;
891 for (unsigned i = 0; i != MAttrs.size(); ++i)
892 Features.AddFeature(MAttrs[i]);
893 FeaturesStr = Features.getString();
894 }
895
Ahmed Charles56440fd2014-03-06 05:51:42 +0000896 std::unique_ptr<const MCRegisterInfo> MRI(
897 TheTarget->createMCRegInfo(TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +0000898 if (!MRI)
899 report_fatal_error("error: no register info for target " + TripleName);
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000900
901 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000902 std::unique_ptr<const MCAsmInfo> AsmInfo(
903 TheTarget->createMCAsmInfo(*MRI, TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +0000904 if (!AsmInfo)
905 report_fatal_error("error: no assembly info for target " + TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +0000906 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +0000907 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Davide Italiano711e4952015-12-17 01:59:50 +0000908 if (!STI)
909 report_fatal_error("error: no subtarget info for target " + TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +0000910 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
Davide Italiano711e4952015-12-17 01:59:50 +0000911 if (!MII)
912 report_fatal_error("error: no instruction info for target " + TripleName);
Lang Hamesa1bc0f52014-04-15 04:40:56 +0000913 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
914 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
915
916 std::unique_ptr<MCDisassembler> DisAsm(
917 TheTarget->createMCDisassembler(*STI, Ctx));
Davide Italiano711e4952015-12-17 01:59:50 +0000918 if (!DisAsm)
919 report_fatal_error("error: no disassembler for target " + TripleName);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000920
Ahmed Charles56440fd2014-03-06 05:51:42 +0000921 std::unique_ptr<const MCInstrAnalysis> MIA(
922 TheTarget->createMCInstrAnalysis(MII.get()));
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000923
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000924 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Daniel Sanders50f17232015-09-15 16:17:27 +0000925 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
926 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
Davide Italiano711e4952015-12-17 01:59:50 +0000927 if (!IP)
928 report_fatal_error("error: no instruction printer for target " +
929 TripleName);
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000930 IP->setPrintImmHex(PrintImmHex);
Colin LeMahieu35436a22015-05-29 14:48:25 +0000931 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000932
Greg Fitzgerald18432272014-03-20 22:55:15 +0000933 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
934 "\t\t\t%08" PRIx64 ": ";
935
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000936 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
937 // in RelocSecs contain the relocations for section S.
Rafael Espindola4453e42942014-06-13 03:07:50 +0000938 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000939 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
Colin LeMahieu77804be2015-07-29 15:45:39 +0000940 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +0000941 section_iterator Sec2 = Section.getRelocatedSection();
Rafael Espindolab5155a52014-02-10 20:24:04 +0000942 if (Sec2 != Obj->section_end())
Alexey Samsonov48803e52014-03-13 14:37:36 +0000943 SectionRelocMap[*Sec2].push_back(Section);
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000944 }
945
David Majnemer81afca62015-07-07 22:06:59 +0000946 // Create a mapping from virtual address to symbol name. This is used to
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000947 // pretty print the symbols while disassembling.
948 typedef std::vector<std::pair<uint64_t, StringRef>> SectionSymbolsTy;
949 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
950 for (const SymbolRef &Symbol : Obj->symbols()) {
951 ErrorOr<uint64_t> AddressOrErr = Symbol.getAddress();
952 error(AddressOrErr.getError());
953 uint64_t Address = *AddressOrErr;
David Majnemer2603a8fa2015-07-09 18:11:40 +0000954
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000955 ErrorOr<StringRef> Name = Symbol.getName();
956 error(Name.getError());
957 if (Name->empty())
958 continue;
David Majnemer81afca62015-07-07 22:06:59 +0000959
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000960 ErrorOr<section_iterator> SectionOrErr = Symbol.getSection();
961 error(SectionOrErr.getError());
962 section_iterator SecI = *SectionOrErr;
963 if (SecI == Obj->section_end())
964 continue;
David Majnemer81afca62015-07-07 22:06:59 +0000965
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000966 AllSymbols[*SecI].emplace_back(Address, *Name);
David Majnemer81afca62015-07-07 22:06:59 +0000967 }
968
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000969 // Create a mapping from virtual address to section.
970 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
971 for (SectionRef Sec : Obj->sections())
972 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
973 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
974
975 // Linked executables (.exe and .dll files) typically don't include a real
976 // symbol table but they might contain an export table.
977 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
978 for (const auto &ExportEntry : COFFObj->export_directories()) {
979 StringRef Name;
980 error(ExportEntry.getSymbolName(Name));
981 if (Name.empty())
982 continue;
983 uint32_t RVA;
984 error(ExportEntry.getExportRVA(RVA));
985
986 uint64_t VA = COFFObj->getImageBase() + RVA;
987 auto Sec = std::upper_bound(
988 SectionAddresses.begin(), SectionAddresses.end(), VA,
989 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
990 return LHS < RHS.first;
991 });
992 if (Sec != SectionAddresses.begin())
993 --Sec;
994 else
995 Sec = SectionAddresses.end();
996
997 if (Sec != SectionAddresses.end())
998 AllSymbols[Sec->second].emplace_back(VA, Name);
999 }
1000 }
1001
1002 // Sort all the symbols, this allows us to use a simple binary search to find
1003 // a symbol near an address.
1004 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1005 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
1006
Colin LeMahieu77804be2015-07-29 15:45:39 +00001007 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Colin LeMahieuf34933e2015-07-23 20:58:49 +00001008 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
Mark Seaborneb03ac52014-01-25 00:32:01 +00001009 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +00001010
Rafael Espindola80291272014-10-08 15:28:58 +00001011 uint64_t SectionAddr = Section.getAddress();
1012 uint64_t SectSize = Section.getSize();
David Majnemer185b5b12014-11-11 09:58:25 +00001013 if (!SectSize)
1014 continue;
Simon Atanasyan2b614e12014-02-24 22:12:11 +00001015
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001016 // Get the list of all the symbols in this section.
1017 SectionSymbolsTy &Symbols = AllSymbols[Section];
Davide Italianof0706882015-10-01 21:57:09 +00001018 std::vector<uint64_t> DataMappingSymsAddr;
1019 std::vector<uint64_t> TextMappingSymsAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001020 if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
1021 for (const auto &Symb : Symbols) {
1022 uint64_t Address = Symb.first;
1023 StringRef Name = Symb.second;
1024 if (Name.startswith("$d"))
David Majnemer153722d2015-11-18 04:35:32 +00001025 DataMappingSymsAddr.push_back(Address - SectionAddr);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001026 if (Name.startswith("$x"))
David Majnemer153722d2015-11-18 04:35:32 +00001027 TextMappingSymsAddr.push_back(Address - SectionAddr);
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001028 }
1029 }
1030
Davide Italianof0706882015-10-01 21:57:09 +00001031 std::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end());
1032 std::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end());
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001033
Michael J. Spencer51862b32011-10-13 22:17:18 +00001034 // Make a list of all the relocations for this section.
1035 std::vector<RelocationRef> Rels;
1036 if (InlineRelocs) {
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001037 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
1038 for (const RelocationRef &Reloc : RelocSec.relocations()) {
1039 Rels.push_back(Reloc);
1040 }
Michael J. Spencer51862b32011-10-13 22:17:18 +00001041 }
1042 }
1043
1044 // Sort relocations by address.
1045 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
1046
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001047 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +00001048 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001049 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +00001050 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001051 }
Michael J. Spencer1d6167f2011-06-25 17:55:23 +00001052 StringRef name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001053 error(Section.getName(name));
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001054 outs() << "Disassembly of section ";
1055 if (!SegmentName.empty())
1056 outs() << SegmentName << ",";
1057 outs() << name << ':';
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001058
Rafael Espindola7884c952015-06-04 15:01:05 +00001059 // If the section has no symbol at the start, just insert a dummy one.
1060 if (Symbols.empty() || Symbols[0].first != 0)
David Majnemer153722d2015-11-18 04:35:32 +00001061 Symbols.insert(Symbols.begin(), std::make_pair(SectionAddr, name));
Alp Tokere69170a2014-06-26 22:52:05 +00001062
1063 SmallString<40> Comments;
1064 raw_svector_ostream CommentStream(Comments);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001065
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001066 StringRef BytesStr;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001067 error(Section.getContents(BytesStr));
Aaron Ballman106fd7b2014-11-12 14:01:17 +00001068 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1069 BytesStr.size());
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001070
Michael J. Spencer2670c252011-01-20 06:39:06 +00001071 uint64_t Size;
1072 uint64_t Index;
1073
Michael J. Spencer51862b32011-10-13 22:17:18 +00001074 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
1075 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001076 // Disassemble symbol by symbol.
1077 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
Rafael Espindolae45c7402014-08-17 16:31:39 +00001078
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001079 uint64_t Start = Symbols[si].first - SectionAddr;
1080 // The end is either the section end or the beginning of the next
1081 // symbol.
1082 uint64_t End =
1083 (si == se - 1) ? SectSize : Symbols[si + 1].first - SectionAddr;
1084 // Don't try to disassemble beyond the end of section contents.
1085 if (End > SectSize)
1086 End = SectSize;
Rafael Espindolae45c7402014-08-17 16:31:39 +00001087 // If this symbol has the same address as the next symbol, then skip it.
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001088 if (Start >= End)
Michael J. Spenceree84f642011-10-13 20:37:08 +00001089 continue;
1090
Valery Pykhtinde048052016-04-07 07:24:01 +00001091 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1092 // make size 4 bytes folded
1093 End = Start + ((End - Start) & ~0x3ull);
1094 Start += 256; // add sizeof(amd_kernel_code_t)
1095 // cut trailing zeroes - up to 256 bytes (align)
1096 const uint64_t EndAlign = 256;
1097 const auto Limit = End - (std::min)(EndAlign, End - Start);
1098 while (End > Limit &&
1099 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1100 End -= 4;
1101 }
1102
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001103 outs() << '\n' << Symbols[si].second << ":\n";
Michael J. Spencer2670c252011-01-20 06:39:06 +00001104
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001105#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +00001106 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001107#else
Mark Seaborneb03ac52014-01-25 00:32:01 +00001108 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001109#endif
1110
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001111 for (Index = Start; Index < End; Index += Size) {
1112 MCInst Inst;
Owen Andersona0c3b972011-09-15 23:38:46 +00001113
Davide Italianof0706882015-10-01 21:57:09 +00001114 // AArch64 ELF binaries can interleave data and text in the
1115 // same section. We rely on the markers introduced to
1116 // understand what we need to dump.
1117 if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
1118 uint64_t Stride = 0;
1119
1120 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1121 DataMappingSymsAddr.end(), Index);
1122 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1123 // Switch to data.
1124 while (Index < End) {
1125 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1126 outs() << "\t";
1127 if (Index + 4 <= End) {
1128 Stride = 4;
1129 dumpBytes(Bytes.slice(Index, 4), outs());
1130 outs() << "\t.word";
1131 } else if (Index + 2 <= End) {
1132 Stride = 2;
1133 dumpBytes(Bytes.slice(Index, 2), outs());
1134 outs() << "\t.short";
1135 } else {
1136 Stride = 1;
1137 dumpBytes(Bytes.slice(Index, 1), outs());
1138 outs() << "\t.byte";
1139 }
1140 Index += Stride;
1141 outs() << "\n";
1142 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1143 TextMappingSymsAddr.end(), Index);
1144 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1145 break;
1146 }
1147 }
1148 }
1149
1150 if (Index >= End)
1151 break;
1152
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001153 bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1154 SectionAddr + Index, DebugOut,
1155 CommentStream);
1156 if (Size == 0)
1157 Size = 1;
1158 PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
1159 Bytes.slice(Index, Size),
1160 SectionAddr + Index, outs(), "", *STI);
1161 outs() << CommentStream.str();
1162 Comments.clear();
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001163
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001164 // Try to resolve the target of a call, tail call, etc. to a specific
1165 // symbol.
1166 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1167 MIA->isConditionalBranch(Inst))) {
1168 uint64_t Target;
1169 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1170 // In a relocatable object, the target's section must reside in
1171 // the same section as the call instruction or it is accessed
1172 // through a relocation.
1173 //
1174 // In a non-relocatable object, the target may be in any section.
1175 //
1176 // N.B. We don't walk the relocations in the relocatable case yet.
1177 auto *TargetSectionSymbols = &Symbols;
1178 if (!Obj->isRelocatableObject()) {
1179 auto SectionAddress = std::upper_bound(
1180 SectionAddresses.begin(), SectionAddresses.end(), Target,
1181 [](uint64_t LHS,
1182 const std::pair<uint64_t, SectionRef> &RHS) {
1183 return LHS < RHS.first;
1184 });
1185 if (SectionAddress != SectionAddresses.begin()) {
1186 --SectionAddress;
1187 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1188 } else {
1189 TargetSectionSymbols = nullptr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001190 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001191 }
David Majnemer2603a8fa2015-07-09 18:11:40 +00001192
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001193 // Find the first symbol in the section whose offset is less than
1194 // or equal to the target.
1195 if (TargetSectionSymbols) {
1196 auto TargetSym = std::upper_bound(
1197 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1198 Target, [](uint64_t LHS,
1199 const std::pair<uint64_t, StringRef> &RHS) {
1200 return LHS < RHS.first;
1201 });
1202 if (TargetSym != TargetSectionSymbols->begin()) {
1203 --TargetSym;
1204 uint64_t TargetAddress = std::get<0>(*TargetSym);
1205 StringRef TargetName = std::get<1>(*TargetSym);
1206 outs() << " <" << TargetName;
1207 uint64_t Disp = Target - TargetAddress;
1208 if (Disp)
1209 outs() << "+0x" << utohexstr(Disp);
1210 outs() << '>';
David Majnemer81afca62015-07-07 22:06:59 +00001211 }
1212 }
1213 }
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001214 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001215 outs() << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001216
1217 // Print relocation for instruction.
1218 while (rel_cur != rel_end) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001219 bool hidden = getHidden(*rel_cur);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001220 uint64_t addr = rel_cur->getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +00001221 SmallString<16> name;
1222 SmallString<32> val;
Owen Andersonfa3e5202011-10-25 20:35:53 +00001223
1224 // If this relocation is hidden, skip it.
Owen Andersonfa3e5202011-10-25 20:35:53 +00001225 if (hidden) goto skip_print_rel;
1226
Michael J. Spencer51862b32011-10-13 22:17:18 +00001227 // Stop when rel_cur's address is past the current instruction.
Owen Andersonf20e3e52011-10-25 20:15:39 +00001228 if (addr >= Index + Size) break;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001229 rel_cur->getTypeName(name);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001230 error(getRelocationValueString(*rel_cur, val));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001231 outs() << format(Fmt.data(), SectionAddr + addr) << name
Benjamin Kramer82803112012-03-10 02:04:38 +00001232 << "\t" << val << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001233
1234 skip_print_rel:
1235 ++rel_cur;
1236 }
Benjamin Kramer87ee76c2011-07-20 19:37:35 +00001237 }
Michael J. Spencer2670c252011-01-20 06:39:06 +00001238 }
1239 }
1240}
1241
Kevin Enderby98da6132015-01-20 21:47:46 +00001242void llvm::PrintRelocations(const ObjectFile *Obj) {
Greg Fitzgerald18432272014-03-20 22:55:15 +00001243 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1244 "%08" PRIx64;
Rafael Espindola9219fe72016-03-21 20:59:15 +00001245 // Regular objdump doesn't print relocations in non-relocatable object
1246 // files.
1247 if (!Obj->isRelocatableObject())
1248 return;
Rafael Espindolac66d7612014-08-17 19:09:37 +00001249
Colin LeMahieu77804be2015-07-29 15:45:39 +00001250 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001251 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001252 continue;
1253 StringRef secname;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001254 error(Section.getName(secname));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001255 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001256 for (const RelocationRef &Reloc : Section.relocations()) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001257 bool hidden = getHidden(Reloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001258 uint64_t address = Reloc.getOffset();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001259 SmallString<32> relocname;
1260 SmallString<32> valuestr;
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001261 if (hidden)
1262 continue;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001263 Reloc.getTypeName(relocname);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001264 error(getRelocationValueString(Reloc, valuestr));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001265 outs() << format(Fmt.data(), address) << " " << relocname << " "
1266 << valuestr << "\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001267 }
1268 outs() << "\n";
1269 }
1270}
1271
Kevin Enderby98da6132015-01-20 21:47:46 +00001272void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001273 outs() << "Sections:\n"
1274 "Idx Name Size Address Type\n";
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001275 unsigned i = 0;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001276 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001277 StringRef Name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001278 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001279 uint64_t Address = Section.getAddress();
1280 uint64_t Size = Section.getSize();
1281 bool Text = Section.isText();
1282 bool Data = Section.isData();
1283 bool BSS = Section.isBSS();
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001284 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +00001285 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
Alexey Samsonov48803e52014-03-13 14:37:36 +00001286 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1287 Name.str().c_str(), Size, Address, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001288 ++i;
1289 }
1290}
1291
Kevin Enderby98da6132015-01-20 21:47:46 +00001292void llvm::PrintSectionContents(const ObjectFile *Obj) {
Rafael Espindola4453e42942014-06-13 03:07:50 +00001293 std::error_code EC;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001294 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001295 StringRef Name;
1296 StringRef Contents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001297 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001298 uint64_t BaseAddr = Section.getAddress();
David Majnemer185b5b12014-11-11 09:58:25 +00001299 uint64_t Size = Section.getSize();
1300 if (!Size)
1301 continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001302
1303 outs() << "Contents of section " << Name << ":\n";
David Majnemer185b5b12014-11-11 09:58:25 +00001304 if (Section.isBSS()) {
Alexey Samsonov209095c2013-04-16 10:53:11 +00001305 outs() << format("<skipping contents of bss section at [%04" PRIx64
David Majnemer8f6b04c2014-07-14 16:20:14 +00001306 ", %04" PRIx64 ")>\n",
1307 BaseAddr, BaseAddr + Size);
Alexey Samsonov209095c2013-04-16 10:53:11 +00001308 continue;
1309 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001310
Davide Italianoccd53fe2015-08-05 07:18:31 +00001311 error(Section.getContents(Contents));
David Majnemer8f6b04c2014-07-14 16:20:14 +00001312
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001313 // Dump out the content as hex and printable ascii characters.
1314 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer82803112012-03-10 02:04:38 +00001315 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001316 // Dump line of hex.
1317 for (std::size_t i = 0; i < 16; ++i) {
1318 if (i != 0 && i % 4 == 0)
1319 outs() << ' ';
1320 if (addr + i < end)
1321 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1322 << hexdigit(Contents[addr + i] & 0xF, true);
1323 else
1324 outs() << " ";
1325 }
1326 // Print ascii.
1327 outs() << " ";
1328 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
Guy Benyei83c74e92013-02-12 21:21:59 +00001329 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001330 outs() << Contents[addr + i];
1331 else
1332 outs() << ".";
1333 }
1334 outs() << "\n";
1335 }
1336 }
1337}
1338
Kevin Enderby98da6132015-01-20 21:47:46 +00001339void llvm::PrintSymbolTable(const ObjectFile *o) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001340 outs() << "SYMBOL TABLE:\n";
1341
Rui Ueyama4e39f712014-03-18 18:58:51 +00001342 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
Davide Italianoe85abf72015-12-20 09:54:34 +00001343 printCOFFSymbolTable(coff);
Rui Ueyama4e39f712014-03-18 18:58:51 +00001344 return;
1345 }
1346 for (const SymbolRef &Symbol : o->symbols()) {
Rafael Espindolaed067c42015-07-03 18:19:00 +00001347 ErrorOr<uint64_t> AddressOrError = Symbol.getAddress();
Davide Italianoccd53fe2015-08-05 07:18:31 +00001348 error(AddressOrError.getError());
Rafael Espindolaed067c42015-07-03 18:19:00 +00001349 uint64_t Address = *AddressOrError;
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00001350 ErrorOr<SymbolRef::Type> TypeOrError = Symbol.getType();
1351 error(TypeOrError.getError());
1352 SymbolRef::Type Type = *TypeOrError;
Rui Ueyama4e39f712014-03-18 18:58:51 +00001353 uint32_t Flags = Symbol.getFlags();
Rafael Espindola8bab8892015-08-07 23:27:14 +00001354 ErrorOr<section_iterator> SectionOrErr = Symbol.getSection();
1355 error(SectionOrErr.getError());
1356 section_iterator Section = *SectionOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001357 StringRef Name;
1358 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1359 Section->getName(Name);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001360 } else {
1361 ErrorOr<StringRef> NameOrErr = Symbol.getName();
Davide Italianoccd53fe2015-08-05 07:18:31 +00001362 error(NameOrErr.getError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001363 Name = *NameOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001364 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001365
Rui Ueyama4e39f712014-03-18 18:58:51 +00001366 bool Global = Flags & SymbolRef::SF_Global;
1367 bool Weak = Flags & SymbolRef::SF_Weak;
1368 bool Absolute = Flags & SymbolRef::SF_Absolute;
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001369 bool Common = Flags & SymbolRef::SF_Common;
Davide Italianocd2514d2015-04-30 23:08:53 +00001370 bool Hidden = Flags & SymbolRef::SF_Hidden;
David Meyer1df4b842012-02-28 23:47:53 +00001371
Rui Ueyama4e39f712014-03-18 18:58:51 +00001372 char GlobLoc = ' ';
1373 if (Type != SymbolRef::ST_Unknown)
1374 GlobLoc = Global ? 'g' : 'l';
1375 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1376 ? 'd' : ' ';
1377 char FileFunc = ' ';
1378 if (Type == SymbolRef::ST_File)
1379 FileFunc = 'f';
1380 else if (Type == SymbolRef::ST_Function)
1381 FileFunc = 'F';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001382
Rui Ueyama4e39f712014-03-18 18:58:51 +00001383 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1384 "%08" PRIx64;
Michael J. Spencerd857c1c2013-01-10 22:40:50 +00001385
Rui Ueyama4e39f712014-03-18 18:58:51 +00001386 outs() << format(Fmt, Address) << " "
1387 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1388 << (Weak ? 'w' : ' ') // Weak?
1389 << ' ' // Constructor. Not supported yet.
1390 << ' ' // Warning. Not supported yet.
1391 << ' ' // Indirect reference to another symbol.
1392 << Debug // Debugging (d) or dynamic (D) symbol.
1393 << FileFunc // Name of function (F), file (f) or object (O).
1394 << ' ';
1395 if (Absolute) {
1396 outs() << "*ABS*";
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001397 } else if (Common) {
1398 outs() << "*COM*";
Rui Ueyama4e39f712014-03-18 18:58:51 +00001399 } else if (Section == o->section_end()) {
1400 outs() << "*UND*";
1401 } else {
1402 if (const MachOObjectFile *MachO =
1403 dyn_cast<const MachOObjectFile>(o)) {
1404 DataRefImpl DR = Section->getRawDataRefImpl();
1405 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1406 outs() << SegmentName << ",";
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001407 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00001408 StringRef SectionName;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001409 error(Section->getName(SectionName));
Rui Ueyama4e39f712014-03-18 18:58:51 +00001410 outs() << SectionName;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001411 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001412
1413 outs() << '\t';
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001414 if (Common || isa<ELFObjectFileBase>(o)) {
Rafael Espindoladbb6bd32015-06-25 22:10:04 +00001415 uint64_t Val =
1416 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001417 outs() << format("\t %08" PRIx64 " ", Val);
1418 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001419
Davide Italianocd2514d2015-04-30 23:08:53 +00001420 if (Hidden) {
1421 outs() << ".hidden ";
1422 }
1423 outs() << Name
Rui Ueyama4e39f712014-03-18 18:58:51 +00001424 << '\n';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001425 }
1426}
1427
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001428static void PrintUnwindInfo(const ObjectFile *o) {
1429 outs() << "Unwind info:\n\n";
1430
1431 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1432 printCOFFUnwindInfo(coff);
Tim Northover4bd286a2014-08-01 13:07:19 +00001433 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1434 printMachOUnwindInfo(MachO);
1435 else {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001436 // TODO: Extract DWARF dump tool to objdump.
1437 errs() << "This operation is only currently supported "
Tim Northover4bd286a2014-08-01 13:07:19 +00001438 "for COFF and MachO object files.\n";
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001439 return;
1440 }
1441}
1442
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001443void llvm::printExportsTrie(const ObjectFile *o) {
Nick Kledzikd04bc352014-08-30 00:20:14 +00001444 outs() << "Exports trie:\n";
1445 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1446 printMachOExportsTrie(MachO);
1447 else {
1448 errs() << "This operation is only currently supported "
1449 "for Mach-O executable files.\n";
1450 return;
1451 }
1452}
1453
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001454void llvm::printRebaseTable(const ObjectFile *o) {
Nick Kledzikac431442014-09-12 21:34:15 +00001455 outs() << "Rebase table:\n";
1456 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1457 printMachORebaseTable(MachO);
1458 else {
1459 errs() << "This operation is only currently supported "
1460 "for Mach-O executable files.\n";
1461 return;
1462 }
1463}
1464
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001465void llvm::printBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001466 outs() << "Bind table:\n";
1467 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1468 printMachOBindTable(MachO);
1469 else {
1470 errs() << "This operation is only currently supported "
1471 "for Mach-O executable files.\n";
1472 return;
1473 }
1474}
1475
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001476void llvm::printLazyBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001477 outs() << "Lazy bind table:\n";
1478 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1479 printMachOLazyBindTable(MachO);
1480 else {
1481 errs() << "This operation is only currently supported "
1482 "for Mach-O executable files.\n";
1483 return;
1484 }
1485}
1486
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001487void llvm::printWeakBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001488 outs() << "Weak bind table:\n";
1489 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1490 printMachOWeakBindTable(MachO);
1491 else {
1492 errs() << "This operation is only currently supported "
1493 "for Mach-O executable files.\n";
1494 return;
1495 }
1496}
Nick Kledzikac431442014-09-12 21:34:15 +00001497
Adrian Prantl437105a2015-07-08 02:04:15 +00001498/// Dump the raw contents of the __clangast section so the output can be piped
1499/// into llvm-bcanalyzer.
1500void llvm::printRawClangAST(const ObjectFile *Obj) {
1501 if (outs().is_displayed()) {
1502 errs() << "The -raw-clang-ast option will dump the raw binary contents of "
1503 "the clang ast section.\n"
1504 "Please redirect the output to a file or another program such as "
1505 "llvm-bcanalyzer.\n";
1506 return;
1507 }
1508
1509 StringRef ClangASTSectionName("__clangast");
1510 if (isa<COFFObjectFile>(Obj)) {
1511 ClangASTSectionName = "clangast";
1512 }
1513
1514 Optional<object::SectionRef> ClangASTSection;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001515 for (auto Sec : ToolSectionFilter(*Obj)) {
Adrian Prantl437105a2015-07-08 02:04:15 +00001516 StringRef Name;
1517 Sec.getName(Name);
1518 if (Name == ClangASTSectionName) {
1519 ClangASTSection = Sec;
1520 break;
1521 }
1522 }
1523 if (!ClangASTSection)
1524 return;
1525
1526 StringRef ClangASTContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001527 error(ClangASTSection.getValue().getContents(ClangASTContents));
Adrian Prantl437105a2015-07-08 02:04:15 +00001528 outs().write(ClangASTContents.data(), ClangASTContents.size());
1529}
1530
Sanjoy Das6f567a42015-06-22 18:03:02 +00001531static void printFaultMaps(const ObjectFile *Obj) {
1532 const char *FaultMapSectionName = nullptr;
1533
1534 if (isa<ELFObjectFileBase>(Obj)) {
1535 FaultMapSectionName = ".llvm_faultmaps";
1536 } else if (isa<MachOObjectFile>(Obj)) {
1537 FaultMapSectionName = "__llvm_faultmaps";
1538 } else {
1539 errs() << "This operation is only currently supported "
1540 "for ELF and Mach-O executable files.\n";
1541 return;
1542 }
1543
1544 Optional<object::SectionRef> FaultMapSection;
1545
Colin LeMahieu77804be2015-07-29 15:45:39 +00001546 for (auto Sec : ToolSectionFilter(*Obj)) {
Sanjoy Das6f567a42015-06-22 18:03:02 +00001547 StringRef Name;
1548 Sec.getName(Name);
1549 if (Name == FaultMapSectionName) {
1550 FaultMapSection = Sec;
1551 break;
1552 }
1553 }
1554
1555 outs() << "FaultMap table:\n";
1556
1557 if (!FaultMapSection.hasValue()) {
1558 outs() << "<not found>\n";
1559 return;
1560 }
1561
1562 StringRef FaultMapContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001563 error(FaultMapSection.getValue().getContents(FaultMapContents));
Sanjoy Das6f567a42015-06-22 18:03:02 +00001564
1565 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1566 FaultMapContents.bytes_end());
1567
1568 outs() << FMP;
1569}
1570
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001571static void printPrivateFileHeaders(const ObjectFile *o) {
1572 if (o->isELF())
1573 printELFFileHeader(o);
1574 else if (o->isCOFF())
1575 printCOFFFileHeader(o);
1576 else if (o->isMachO()) {
1577 printMachOFileHeader(o);
1578 printMachOLoadCommands(o);
1579 } else
1580 report_fatal_error("Invalid/Unsupported object file format");
1581}
1582
1583static void printFirstPrivateFileHeader(const ObjectFile *o) {
Davide Italiano540e9212015-12-19 22:09:40 +00001584 if (o->isELF())
Rui Ueyamac2bed422013-09-27 21:04:00 +00001585 printELFFileHeader(o);
Davide Italiano540e9212015-12-19 22:09:40 +00001586 else if (o->isCOFF())
Rui Ueyamac2bed422013-09-27 21:04:00 +00001587 printCOFFFileHeader(o);
Davide Italiano540e9212015-12-19 22:09:40 +00001588 else if (o->isMachO())
Kevin Enderbyb76d3862014-08-22 20:35:18 +00001589 printMachOFileHeader(o);
Davide Italiano540e9212015-12-19 22:09:40 +00001590 else
1591 report_fatal_error("Invalid/Unsupported object file format");
Rui Ueyamac2bed422013-09-27 21:04:00 +00001592}
1593
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001594static void DumpObject(const ObjectFile *o) {
Adrian Prantl437105a2015-07-08 02:04:15 +00001595 // Avoid other output when using a raw option.
1596 if (!RawClangAST) {
1597 outs() << '\n';
1598 outs() << o->getFileName()
1599 << ":\tfile format " << o->getFileFormatName() << "\n\n";
1600 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001601
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001602 if (Disassemble)
Michael J. Spencer51862b32011-10-13 22:17:18 +00001603 DisassembleObject(o, Relocations);
1604 if (Relocations && !Disassemble)
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001605 PrintRelocations(o);
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001606 if (SectionHeaders)
1607 PrintSectionHeaders(o);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001608 if (SectionContents)
1609 PrintSectionContents(o);
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001610 if (SymbolTable)
1611 PrintSymbolTable(o);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001612 if (UnwindInfo)
1613 PrintUnwindInfo(o);
Rui Ueyamac2bed422013-09-27 21:04:00 +00001614 if (PrivateHeaders)
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001615 printPrivateFileHeaders(o);
1616 if (FirstPrivateHeader)
1617 printFirstPrivateFileHeader(o);
Nick Kledzikd04bc352014-08-30 00:20:14 +00001618 if (ExportsTrie)
1619 printExportsTrie(o);
Nick Kledzikac431442014-09-12 21:34:15 +00001620 if (Rebase)
1621 printRebaseTable(o);
Nick Kledzik56ebef42014-09-16 01:41:51 +00001622 if (Bind)
1623 printBindTable(o);
1624 if (LazyBind)
1625 printLazyBindTable(o);
1626 if (WeakBind)
1627 printWeakBindTable(o);
Adrian Prantl437105a2015-07-08 02:04:15 +00001628 if (RawClangAST)
1629 printRawClangAST(o);
Sanjoy Das6f567a42015-06-22 18:03:02 +00001630 if (PrintFaultMaps)
1631 printFaultMaps(o);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001632 if (DwarfDumpType != DIDT_Null) {
1633 std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*o));
1634 // Dump the complete DWARF structure.
1635 DICtx->dump(outs(), DwarfDumpType, true /* DumpEH */);
1636 }
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001637}
1638
1639/// @brief Dump each object file in \a a;
1640static void DumpArchive(const Archive *a) {
Kevin Enderby7a969422015-11-05 19:24:56 +00001641 for (auto &ErrorOrChild : a->children()) {
1642 if (std::error_code EC = ErrorOrChild.getError())
1643 report_error(a->getFileName(), EC);
1644 const Archive::Child &C = *ErrorOrChild;
Davide Italiano95dd3cb2015-08-03 21:46:32 +00001645 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Davide Italianoccd53fe2015-08-05 07:18:31 +00001646 if (std::error_code EC = ChildOrErr.getError())
Mark Seaborneb03ac52014-01-25 00:32:01 +00001647 if (EC != object_error::invalid_file_type)
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001648 report_error(a->getFileName(), EC);
Rafael Espindolaae460022014-06-16 16:08:36 +00001649 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001650 DumpObject(o);
1651 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001652 report_error(a->getFileName(), object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001653 }
1654}
1655
1656/// @brief Open file and figure out how to dump it.
1657static void DumpInput(StringRef file) {
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001658
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001659 // If we are using the Mach-O specific object file parser, then let it parse
1660 // the file and process the command line options. So the -arch flags can
1661 // be used to select specific slices, etc.
1662 if (MachOOpt) {
1663 ParseInputMachO(file);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001664 return;
1665 }
1666
1667 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00001668 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
1669 if (!BinaryOrErr)
1670 report_error(file, errorToErrorCode(BinaryOrErr.takeError()));
Rafael Espindola48af1c22014-08-19 18:44:46 +00001671 Binary &Binary = *BinaryOrErr.get().getBinary();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001672
Rafael Espindola3f6481d2014-08-01 14:31:55 +00001673 if (Archive *a = dyn_cast<Archive>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001674 DumpArchive(a);
Rafael Espindola3f6481d2014-08-01 14:31:55 +00001675 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001676 DumpObject(o);
Jim Grosbachaf9aec02012-08-07 17:53:14 +00001677 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001678 report_error(file, object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001679}
1680
Michael J. Spencer2670c252011-01-20 06:39:06 +00001681int main(int argc, char **argv) {
1682 // Print a stack trace if we signal out.
1683 sys::PrintStackTraceOnErrorSignal();
1684 PrettyStackTraceProgram X(argc, argv);
1685 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1686
1687 // Initialize targets and assembly printers/parsers.
1688 llvm::InitializeAllTargetInfos();
Evan Cheng8c886a42011-07-22 21:58:54 +00001689 llvm::InitializeAllTargetMCs();
Michael J. Spencer2670c252011-01-20 06:39:06 +00001690 llvm::InitializeAllDisassemblers();
1691
Pete Cooper28fb4fc2012-05-03 23:20:10 +00001692 // Register the target printer for --version.
1693 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
1694
Michael J. Spencer2670c252011-01-20 06:39:06 +00001695 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
1696 TripleName = Triple::normalize(TripleName);
1697
1698 ToolName = argv[0];
1699
1700 // Defaults to a.out if no filenames specified.
1701 if (InputFilenames.size() == 0)
1702 InputFilenames.push_back("a.out");
1703
Colin LeMahieuf34933e2015-07-23 20:58:49 +00001704 if (DisassembleAll)
1705 Disassemble = true;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001706 if (!Disassemble
1707 && !Relocations
1708 && !SectionHeaders
1709 && !SectionContents
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001710 && !SymbolTable
Michael J. Spencer209565db2013-01-06 03:56:49 +00001711 && !UnwindInfo
Nick Kledzikd04bc352014-08-30 00:20:14 +00001712 && !PrivateHeaders
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001713 && !FirstPrivateHeader
Nick Kledzikac431442014-09-12 21:34:15 +00001714 && !ExportsTrie
Nick Kledzik56ebef42014-09-16 01:41:51 +00001715 && !Rebase
1716 && !Bind
1717 && !LazyBind
Kevin Enderby131d1772015-01-09 19:22:37 +00001718 && !WeakBind
Adrian Prantl437105a2015-07-08 02:04:15 +00001719 && !RawClangAST
Kevin Enderby13023a12015-01-15 23:19:11 +00001720 && !(UniversalHeaders && MachOOpt)
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001721 && !(ArchiveHeaders && MachOOpt)
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001722 && !(IndirectSymbols && MachOOpt)
Kevin Enderby9a509442015-01-27 21:28:24 +00001723 && !(DataInCode && MachOOpt)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001724 && !(LinkOptHints && MachOOpt)
Kevin Enderbycd66be52015-03-11 22:06:32 +00001725 && !(InfoPlist && MachOOpt)
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001726 && !(DylibsUsed && MachOOpt)
1727 && !(DylibId && MachOOpt)
Kevin Enderby0fc11822015-04-01 20:57:01 +00001728 && !(ObjcMetaData && MachOOpt)
Colin LeMahieufcc32762015-07-29 19:08:10 +00001729 && !(FilterSections.size() != 0 && MachOOpt)
Igor Laevsky03a670c2016-01-26 15:09:42 +00001730 && !PrintFaultMaps
1731 && DwarfDumpType == DIDT_Null) {
Michael J. Spencer2670c252011-01-20 06:39:06 +00001732 cl::PrintHelpMessage();
1733 return 2;
1734 }
1735
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001736 std::for_each(InputFilenames.begin(), InputFilenames.end(),
1737 DumpInput);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001738
Davide Italianoccd53fe2015-08-05 07:18:31 +00001739 return EXIT_SUCCESS;
Michael J. Spencer2670c252011-01-20 06:39:06 +00001740}