blob: 1eb9f61c6ac90c6c24baf8d7f8154a10d7c89c7d [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 {
Matt Arsenault87d80db2016-04-22 21:23:41 +0000408 if (!MI) {
409 OS << " <unknown>";
410 return;
411 }
412
Valery Pykhtinde048052016-04-07 07:24:01 +0000413 SmallString<40> InstStr;
414 raw_svector_ostream IS(InstStr);
415
416 IP.printInst(MI, IS, "", STI);
417
Valery Pykhtin8e79f5b2016-04-07 08:38:20 +0000418 OS << left_justify(IS.str(), 60) << format("// %012" PRIX64 ": ", Address);
Valery Pykhtinde048052016-04-07 07:24:01 +0000419 typedef support::ulittle32_t U32;
420 for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
421 Bytes.size() / sizeof(U32)))
422 // D should be explicitly casted to uint32_t here as it is passed
423 // by format to snprintf as vararg.
Valery Pykhtin8e79f5b2016-04-07 08:38:20 +0000424 OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D));
Valery Pykhtinde048052016-04-07 07:24:01 +0000425
426 if (!Annot.empty())
427 OS << "// " << Annot;
428 }
429};
430AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
431
Colin LeMahieu35436a22015-05-29 14:48:25 +0000432PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000433 switch(Triple.getArch()) {
434 default:
435 return PrettyPrinterInst;
436 case Triple::hexagon:
437 return HexagonPrettyPrinterInst;
Valery Pykhtinde048052016-04-07 07:24:01 +0000438 case Triple::amdgcn:
439 return AMDGCNPrettyPrinterInst;
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000440 }
Colin LeMahieufb76b002015-05-28 19:07:14 +0000441}
442}
443
Rafael Espindola37070a52015-06-03 04:48:06 +0000444template <class ELFT>
Rafael Espindola37070a52015-06-03 04:48:06 +0000445static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000446 const RelocationRef &RelRef,
Rafael Espindola37070a52015-06-03 04:48:06 +0000447 SmallVectorImpl<char> &Result) {
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000448 DataRefImpl Rel = RelRef.getRawDataRefImpl();
449
Rafael Espindola37070a52015-06-03 04:48:06 +0000450 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
451 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000452 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
453
Rafael Espindola37070a52015-06-03 04:48:06 +0000454 const ELFFile<ELFT> &EF = *Obj->getELFFile();
455
Rafael Espindola6def3042015-07-01 12:56:27 +0000456 ErrorOr<const Elf_Shdr *> SecOrErr = EF.getSection(Rel.d.a);
457 if (std::error_code EC = SecOrErr.getError())
458 return EC;
459 const Elf_Shdr *Sec = *SecOrErr;
460 ErrorOr<const Elf_Shdr *> SymTabOrErr = EF.getSection(Sec->sh_link);
461 if (std::error_code EC = SymTabOrErr.getError())
462 return EC;
463 const Elf_Shdr *SymTab = *SymTabOrErr;
Rafael Espindola719dc7c2015-06-29 12:38:31 +0000464 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
465 SymTab->sh_type == ELF::SHT_DYNSYM);
Rafael Espindola6def3042015-07-01 12:56:27 +0000466 ErrorOr<const Elf_Shdr *> StrTabSec = EF.getSection(SymTab->sh_link);
467 if (std::error_code EC = StrTabSec.getError())
468 return EC;
469 ErrorOr<StringRef> StrTabOrErr = EF.getStringTable(*StrTabSec);
Rafael Espindola6a1bfb22015-06-29 14:39:25 +0000470 if (std::error_code EC = StrTabOrErr.getError())
471 return EC;
472 StringRef StrTab = *StrTabOrErr;
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000473 uint8_t type = RelRef.getType();
Rafael Espindola37070a52015-06-03 04:48:06 +0000474 StringRef res;
475 int64_t addend = 0;
Rafael Espindola6def3042015-07-01 12:56:27 +0000476 switch (Sec->sh_type) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000477 default:
478 return object_error::parse_failed;
479 case ELF::SHT_REL: {
Rafael Espindola37070a52015-06-03 04:48:06 +0000480 // TODO: Read implicit addend from section data.
481 break;
482 }
483 case ELF::SHT_RELA: {
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000484 const Elf_Rela *ERela = Obj->getRela(Rel);
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000485 addend = ERela->r_addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000486 break;
487 }
488 }
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000489 symbol_iterator SI = RelRef.getSymbol();
490 const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
Rafael Espindola75d5b542015-06-03 05:14:22 +0000491 StringRef Target;
Rafael Espindola75d5b542015-06-03 05:14:22 +0000492 if (symb->getType() == ELF::STT_SECTION) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000493 Expected<section_iterator> SymSI = SI->getSection();
494 if (!SymSI)
495 return errorToErrorCode(SymSI.takeError());
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000496 const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
497 ErrorOr<StringRef> SecName = EF.getSectionName(SymSec);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000498 if (std::error_code EC = SecName.getError())
499 return EC;
500 Target = *SecName;
501 } else {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000502 Expected<StringRef> SymName = symb->getName(StrTab);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000503 if (!SymName)
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000504 return errorToErrorCode(SymName.takeError());
Rafael Espindola75d5b542015-06-03 05:14:22 +0000505 Target = *SymName;
506 }
Rafael Espindola37070a52015-06-03 04:48:06 +0000507 switch (EF.getHeader()->e_machine) {
508 case ELF::EM_X86_64:
509 switch (type) {
510 case ELF::R_X86_64_PC8:
511 case ELF::R_X86_64_PC16:
512 case ELF::R_X86_64_PC32: {
513 std::string fmtbuf;
514 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000515 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
Rafael Espindola37070a52015-06-03 04:48:06 +0000516 fmt.flush();
517 Result.append(fmtbuf.begin(), fmtbuf.end());
518 } break;
519 case ELF::R_X86_64_8:
520 case ELF::R_X86_64_16:
521 case ELF::R_X86_64_32:
522 case ELF::R_X86_64_32S:
523 case ELF::R_X86_64_64: {
524 std::string fmtbuf;
525 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000526 fmt << Target << (addend < 0 ? "" : "+") << addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000527 fmt.flush();
528 Result.append(fmtbuf.begin(), fmtbuf.end());
529 } break;
530 default:
531 res = "Unknown";
532 }
533 break;
Jacques Pienaarea9f25a2016-03-01 21:21:42 +0000534 case ELF::EM_LANAI:
Rafael Espindola37070a52015-06-03 04:48:06 +0000535 case ELF::EM_AARCH64: {
536 std::string fmtbuf;
537 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000538 fmt << Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000539 if (addend != 0)
540 fmt << (addend < 0 ? "" : "+") << addend;
541 fmt.flush();
542 Result.append(fmtbuf.begin(), fmtbuf.end());
543 break;
544 }
545 case ELF::EM_386:
Michael Kupersteina3b79dd2015-11-04 11:21:50 +0000546 case ELF::EM_IAMCU:
Rafael Espindola37070a52015-06-03 04:48:06 +0000547 case ELF::EM_ARM:
548 case ELF::EM_HEXAGON:
549 case ELF::EM_MIPS:
Rafael Espindola75d5b542015-06-03 05:14:22 +0000550 res = Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000551 break;
Dan Gohman46350172016-01-12 20:56:01 +0000552 case ELF::EM_WEBASSEMBLY:
553 switch (type) {
554 case ELF::R_WEBASSEMBLY_DATA: {
555 std::string fmtbuf;
556 raw_string_ostream fmt(fmtbuf);
557 fmt << Target << (addend < 0 ? "" : "+") << addend;
558 fmt.flush();
559 Result.append(fmtbuf.begin(), fmtbuf.end());
560 break;
561 }
562 case ELF::R_WEBASSEMBLY_FUNCTION:
563 res = Target;
564 break;
565 default:
566 res = "Unknown";
567 }
568 break;
Rafael Espindola37070a52015-06-03 04:48:06 +0000569 default:
570 res = "Unknown";
571 }
572 if (Result.empty())
573 Result.append(res.begin(), res.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000574 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000575}
576
577static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000578 const RelocationRef &Rel,
Rafael Espindola37070a52015-06-03 04:48:06 +0000579 SmallVectorImpl<char> &Result) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000580 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
581 return getRelocationValueString(ELF32LE, Rel, Result);
582 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
583 return getRelocationValueString(ELF64LE, Rel, Result);
584 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
585 return getRelocationValueString(ELF32BE, Rel, Result);
586 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
587 return getRelocationValueString(ELF64BE, Rel, Result);
588}
589
590static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
591 const RelocationRef &Rel,
592 SmallVectorImpl<char> &Result) {
593 symbol_iterator SymI = Rel.getSymbol();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000594 Expected<StringRef> SymNameOrErr = SymI->getName();
595 if (!SymNameOrErr)
596 return errorToErrorCode(SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000597 StringRef SymName = *SymNameOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000598 Result.append(SymName.begin(), SymName.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000599 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000600}
601
602static void printRelocationTargetName(const MachOObjectFile *O,
603 const MachO::any_relocation_info &RE,
604 raw_string_ostream &fmt) {
605 bool IsScattered = O->isRelocationScattered(RE);
606
607 // Target of a scattered relocation is an address. In the interest of
608 // generating pretty output, scan through the symbol table looking for a
609 // symbol that aligns with that address. If we find one, print it.
610 // Otherwise, we just print the hex address of the target.
611 if (IsScattered) {
612 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
613
614 for (const SymbolRef &Symbol : O->symbols()) {
615 std::error_code ec;
Rafael Espindolaed067c42015-07-03 18:19:00 +0000616 ErrorOr<uint64_t> Addr = Symbol.getAddress();
617 if ((ec = Addr.getError()))
Rafael Espindola37070a52015-06-03 04:48:06 +0000618 report_fatal_error(ec.message());
Rafael Espindolaed067c42015-07-03 18:19:00 +0000619 if (*Addr != Val)
Rafael Espindola37070a52015-06-03 04:48:06 +0000620 continue;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000621 Expected<StringRef> Name = Symbol.getName();
622 if (!Name) {
623 std::string Buf;
624 raw_string_ostream OS(Buf);
625 logAllUnhandledErrors(Name.takeError(), OS, "");
626 OS.flush();
627 report_fatal_error(Buf);
628 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000629 fmt << *Name;
Rafael Espindola37070a52015-06-03 04:48:06 +0000630 return;
631 }
632
633 // If we couldn't find a symbol that this relocation refers to, try
634 // to find a section beginning instead.
Colin LeMahieu77804be2015-07-29 15:45:39 +0000635 for (const SectionRef &Section : ToolSectionFilter(*O)) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000636 std::error_code ec;
637
638 StringRef Name;
639 uint64_t Addr = Section.getAddress();
640 if (Addr != Val)
641 continue;
642 if ((ec = Section.getName(Name)))
643 report_fatal_error(ec.message());
644 fmt << Name;
645 return;
646 }
647
648 fmt << format("0x%x", Val);
649 return;
650 }
651
652 StringRef S;
653 bool isExtern = O->getPlainRelocationExternal(RE);
654 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
655
656 if (isExtern) {
657 symbol_iterator SI = O->symbol_begin();
658 advance(SI, Val);
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000659 Expected<StringRef> SOrErr = SI->getName();
660 error(errorToErrorCode(SOrErr.takeError()));
Davide Italianoccd53fe2015-08-05 07:18:31 +0000661 S = *SOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000662 } else {
663 section_iterator SI = O->section_begin();
664 // Adjust for the fact that sections are 1-indexed.
665 advance(SI, Val - 1);
666 SI->getName(S);
667 }
668
669 fmt << S;
670}
671
672static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
673 const RelocationRef &RelRef,
674 SmallVectorImpl<char> &Result) {
675 DataRefImpl Rel = RelRef.getRawDataRefImpl();
676 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
677
678 unsigned Arch = Obj->getArch();
679
680 std::string fmtbuf;
681 raw_string_ostream fmt(fmtbuf);
682 unsigned Type = Obj->getAnyRelocationType(RE);
683 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
684
685 // Determine any addends that should be displayed with the relocation.
686 // These require decoding the relocation type, which is triple-specific.
687
688 // X86_64 has entirely custom relocation types.
689 if (Arch == Triple::x86_64) {
690 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
691
692 switch (Type) {
693 case MachO::X86_64_RELOC_GOT_LOAD:
694 case MachO::X86_64_RELOC_GOT: {
695 printRelocationTargetName(Obj, RE, fmt);
696 fmt << "@GOT";
697 if (isPCRel)
698 fmt << "PCREL";
699 break;
700 }
701 case MachO::X86_64_RELOC_SUBTRACTOR: {
702 DataRefImpl RelNext = Rel;
703 Obj->moveRelocationNext(RelNext);
704 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
705
706 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
707 // X86_64_RELOC_UNSIGNED.
708 // NOTE: Scattered relocations don't exist on x86_64.
709 unsigned RType = Obj->getAnyRelocationType(RENext);
710 if (RType != MachO::X86_64_RELOC_UNSIGNED)
711 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
712 "X86_64_RELOC_SUBTRACTOR.");
713
714 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
715 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
716 printRelocationTargetName(Obj, RENext, fmt);
717 fmt << "-";
718 printRelocationTargetName(Obj, RE, fmt);
719 break;
720 }
721 case MachO::X86_64_RELOC_TLV:
722 printRelocationTargetName(Obj, RE, fmt);
723 fmt << "@TLV";
724 if (isPCRel)
725 fmt << "P";
726 break;
727 case MachO::X86_64_RELOC_SIGNED_1:
728 printRelocationTargetName(Obj, RE, fmt);
729 fmt << "-1";
730 break;
731 case MachO::X86_64_RELOC_SIGNED_2:
732 printRelocationTargetName(Obj, RE, fmt);
733 fmt << "-2";
734 break;
735 case MachO::X86_64_RELOC_SIGNED_4:
736 printRelocationTargetName(Obj, RE, fmt);
737 fmt << "-4";
738 break;
739 default:
740 printRelocationTargetName(Obj, RE, fmt);
741 break;
742 }
743 // X86 and ARM share some relocation types in common.
744 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
745 Arch == Triple::ppc) {
746 // Generic relocation types...
747 switch (Type) {
748 case MachO::GENERIC_RELOC_PAIR: // prints no info
Rui Ueyama7d099192015-06-09 15:20:42 +0000749 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000750 case MachO::GENERIC_RELOC_SECTDIFF: {
751 DataRefImpl RelNext = Rel;
752 Obj->moveRelocationNext(RelNext);
753 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
754
755 // X86 sect diff's must be followed by a relocation of type
756 // GENERIC_RELOC_PAIR.
757 unsigned RType = Obj->getAnyRelocationType(RENext);
758
759 if (RType != MachO::GENERIC_RELOC_PAIR)
760 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
761 "GENERIC_RELOC_SECTDIFF.");
762
763 printRelocationTargetName(Obj, RE, fmt);
764 fmt << "-";
765 printRelocationTargetName(Obj, RENext, fmt);
766 break;
767 }
768 }
769
770 if (Arch == Triple::x86 || Arch == Triple::ppc) {
771 switch (Type) {
772 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
773 DataRefImpl RelNext = Rel;
774 Obj->moveRelocationNext(RelNext);
775 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
776
777 // X86 sect diff's must be followed by a relocation of type
778 // GENERIC_RELOC_PAIR.
779 unsigned RType = Obj->getAnyRelocationType(RENext);
780 if (RType != MachO::GENERIC_RELOC_PAIR)
781 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
782 "GENERIC_RELOC_LOCAL_SECTDIFF.");
783
784 printRelocationTargetName(Obj, RE, fmt);
785 fmt << "-";
786 printRelocationTargetName(Obj, RENext, fmt);
787 break;
788 }
789 case MachO::GENERIC_RELOC_TLV: {
790 printRelocationTargetName(Obj, RE, fmt);
791 fmt << "@TLV";
792 if (IsPCRel)
793 fmt << "P";
794 break;
795 }
796 default:
797 printRelocationTargetName(Obj, RE, fmt);
798 }
799 } else { // ARM-specific relocations
800 switch (Type) {
801 case MachO::ARM_RELOC_HALF:
802 case MachO::ARM_RELOC_HALF_SECTDIFF: {
803 // Half relocations steal a bit from the length field to encode
804 // whether this is an upper16 or a lower16 relocation.
805 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
806
807 if (isUpper)
808 fmt << ":upper16:(";
809 else
810 fmt << ":lower16:(";
811 printRelocationTargetName(Obj, RE, fmt);
812
813 DataRefImpl RelNext = Rel;
814 Obj->moveRelocationNext(RelNext);
815 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
816
817 // ARM half relocs must be followed by a relocation of type
818 // ARM_RELOC_PAIR.
819 unsigned RType = Obj->getAnyRelocationType(RENext);
820 if (RType != MachO::ARM_RELOC_PAIR)
821 report_fatal_error("Expected ARM_RELOC_PAIR after "
822 "ARM_RELOC_HALF");
823
824 // NOTE: The half of the target virtual address is stashed in the
825 // address field of the secondary relocation, but we can't reverse
826 // engineer the constant offset from it without decoding the movw/movt
827 // instruction to find the other half in its immediate field.
828
829 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
830 // symbol/section pointer of the follow-on relocation.
831 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
832 fmt << "-";
833 printRelocationTargetName(Obj, RENext, fmt);
834 }
835
836 fmt << ")";
837 break;
838 }
839 default: { printRelocationTargetName(Obj, RE, fmt); }
840 }
841 }
842 } else
843 printRelocationTargetName(Obj, RE, fmt);
844
845 fmt.flush();
846 Result.append(fmtbuf.begin(), fmtbuf.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000847 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000848}
849
850static std::error_code getRelocationValueString(const RelocationRef &Rel,
851 SmallVectorImpl<char> &Result) {
Rafael Espindola854038e2015-06-26 14:51:16 +0000852 const ObjectFile *Obj = Rel.getObject();
Rafael Espindola37070a52015-06-03 04:48:06 +0000853 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
854 return getRelocationValueString(ELF, Rel, Result);
855 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
856 return getRelocationValueString(COFF, Rel, Result);
857 auto *MachO = cast<MachOObjectFile>(Obj);
858 return getRelocationValueString(MachO, Rel, Result);
859}
860
Rafael Espindola0ad71d92015-06-30 03:41:26 +0000861/// @brief Indicates whether this relocation should hidden when listing
862/// relocations, usually because it is the trailing part of a multipart
863/// relocation that will be printed as part of the leading relocation.
864static bool getHidden(RelocationRef RelRef) {
865 const ObjectFile *Obj = RelRef.getObject();
866 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
867 if (!MachO)
868 return false;
869
870 unsigned Arch = MachO->getArch();
871 DataRefImpl Rel = RelRef.getRawDataRefImpl();
872 uint64_t Type = MachO->getRelocationType(Rel);
873
874 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
875 // is always hidden.
876 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
877 if (Type == MachO::GENERIC_RELOC_PAIR)
878 return true;
879 } else if (Arch == Triple::x86_64) {
880 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
881 // an X86_64_RELOC_SUBTRACTOR.
882 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
883 DataRefImpl RelPrev = Rel;
884 RelPrev.d.a--;
885 uint64_t PrevType = MachO->getRelocationType(RelPrev);
886 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
887 return true;
888 }
889 }
890
891 return false;
892}
893
Michael J. Spencer51862b32011-10-13 22:17:18 +0000894static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Jim Grosbachaf9aec02012-08-07 17:53:14 +0000895 const Target *TheTarget = getTarget(Obj);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000896
Jack Carter551efd72012-08-28 19:24:49 +0000897 // Package up features to be passed to target/subtarget
898 std::string FeaturesStr;
899 if (MAttrs.size()) {
900 SubtargetFeatures Features;
901 for (unsigned i = 0; i != MAttrs.size(); ++i)
902 Features.AddFeature(MAttrs[i]);
903 FeaturesStr = Features.getString();
904 }
905
Ahmed Charles56440fd2014-03-06 05:51:42 +0000906 std::unique_ptr<const MCRegisterInfo> MRI(
907 TheTarget->createMCRegInfo(TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +0000908 if (!MRI)
909 report_fatal_error("error: no register info for target " + TripleName);
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000910
911 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000912 std::unique_ptr<const MCAsmInfo> AsmInfo(
913 TheTarget->createMCAsmInfo(*MRI, TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +0000914 if (!AsmInfo)
915 report_fatal_error("error: no assembly info for target " + TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +0000916 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +0000917 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Davide Italiano711e4952015-12-17 01:59:50 +0000918 if (!STI)
919 report_fatal_error("error: no subtarget info for target " + TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +0000920 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
Davide Italiano711e4952015-12-17 01:59:50 +0000921 if (!MII)
922 report_fatal_error("error: no instruction info for target " + TripleName);
Lang Hamesa1bc0f52014-04-15 04:40:56 +0000923 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
924 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
925
926 std::unique_ptr<MCDisassembler> DisAsm(
927 TheTarget->createMCDisassembler(*STI, Ctx));
Davide Italiano711e4952015-12-17 01:59:50 +0000928 if (!DisAsm)
929 report_fatal_error("error: no disassembler for target " + TripleName);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000930
Ahmed Charles56440fd2014-03-06 05:51:42 +0000931 std::unique_ptr<const MCInstrAnalysis> MIA(
932 TheTarget->createMCInstrAnalysis(MII.get()));
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000933
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000934 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Daniel Sanders50f17232015-09-15 16:17:27 +0000935 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
936 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
Davide Italiano711e4952015-12-17 01:59:50 +0000937 if (!IP)
938 report_fatal_error("error: no instruction printer for target " +
939 TripleName);
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000940 IP->setPrintImmHex(PrintImmHex);
Colin LeMahieu35436a22015-05-29 14:48:25 +0000941 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000942
Greg Fitzgerald18432272014-03-20 22:55:15 +0000943 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
944 "\t\t\t%08" PRIx64 ": ";
945
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000946 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
947 // in RelocSecs contain the relocations for section S.
Rafael Espindola4453e42942014-06-13 03:07:50 +0000948 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000949 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
Colin LeMahieu77804be2015-07-29 15:45:39 +0000950 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +0000951 section_iterator Sec2 = Section.getRelocatedSection();
Rafael Espindolab5155a52014-02-10 20:24:04 +0000952 if (Sec2 != Obj->section_end())
Alexey Samsonov48803e52014-03-13 14:37:36 +0000953 SectionRelocMap[*Sec2].push_back(Section);
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000954 }
955
David Majnemer81afca62015-07-07 22:06:59 +0000956 // Create a mapping from virtual address to symbol name. This is used to
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000957 // pretty print the symbols while disassembling.
958 typedef std::vector<std::pair<uint64_t, StringRef>> SectionSymbolsTy;
959 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
960 for (const SymbolRef &Symbol : Obj->symbols()) {
961 ErrorOr<uint64_t> AddressOrErr = Symbol.getAddress();
962 error(AddressOrErr.getError());
963 uint64_t Address = *AddressOrErr;
David Majnemer2603a8fa2015-07-09 18:11:40 +0000964
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000965 Expected<StringRef> Name = Symbol.getName();
966 error(errorToErrorCode(Name.takeError()));
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000967 if (Name->empty())
968 continue;
David Majnemer81afca62015-07-07 22:06:59 +0000969
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000970 Expected<section_iterator> SectionOrErr = Symbol.getSection();
971 error(errorToErrorCode(SectionOrErr.takeError()));
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000972 section_iterator SecI = *SectionOrErr;
973 if (SecI == Obj->section_end())
974 continue;
David Majnemer81afca62015-07-07 22:06:59 +0000975
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000976 AllSymbols[*SecI].emplace_back(Address, *Name);
David Majnemer81afca62015-07-07 22:06:59 +0000977 }
978
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000979 // Create a mapping from virtual address to section.
980 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
981 for (SectionRef Sec : Obj->sections())
982 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
983 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
984
985 // Linked executables (.exe and .dll files) typically don't include a real
986 // symbol table but they might contain an export table.
987 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
988 for (const auto &ExportEntry : COFFObj->export_directories()) {
989 StringRef Name;
990 error(ExportEntry.getSymbolName(Name));
991 if (Name.empty())
992 continue;
993 uint32_t RVA;
994 error(ExportEntry.getExportRVA(RVA));
995
996 uint64_t VA = COFFObj->getImageBase() + RVA;
997 auto Sec = std::upper_bound(
998 SectionAddresses.begin(), SectionAddresses.end(), VA,
999 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
1000 return LHS < RHS.first;
1001 });
1002 if (Sec != SectionAddresses.begin())
1003 --Sec;
1004 else
1005 Sec = SectionAddresses.end();
1006
1007 if (Sec != SectionAddresses.end())
1008 AllSymbols[Sec->second].emplace_back(VA, Name);
1009 }
1010 }
1011
1012 // Sort all the symbols, this allows us to use a simple binary search to find
1013 // a symbol near an address.
1014 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1015 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
1016
Colin LeMahieu77804be2015-07-29 15:45:39 +00001017 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Colin LeMahieuf34933e2015-07-23 20:58:49 +00001018 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
Mark Seaborneb03ac52014-01-25 00:32:01 +00001019 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +00001020
Rafael Espindola80291272014-10-08 15:28:58 +00001021 uint64_t SectionAddr = Section.getAddress();
1022 uint64_t SectSize = Section.getSize();
David Majnemer185b5b12014-11-11 09:58:25 +00001023 if (!SectSize)
1024 continue;
Simon Atanasyan2b614e12014-02-24 22:12:11 +00001025
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001026 // Get the list of all the symbols in this section.
1027 SectionSymbolsTy &Symbols = AllSymbols[Section];
Davide Italianof0706882015-10-01 21:57:09 +00001028 std::vector<uint64_t> DataMappingSymsAddr;
1029 std::vector<uint64_t> TextMappingSymsAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001030 if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
1031 for (const auto &Symb : Symbols) {
1032 uint64_t Address = Symb.first;
1033 StringRef Name = Symb.second;
1034 if (Name.startswith("$d"))
David Majnemer153722d2015-11-18 04:35:32 +00001035 DataMappingSymsAddr.push_back(Address - SectionAddr);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001036 if (Name.startswith("$x"))
David Majnemer153722d2015-11-18 04:35:32 +00001037 TextMappingSymsAddr.push_back(Address - SectionAddr);
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001038 }
1039 }
1040
Davide Italianof0706882015-10-01 21:57:09 +00001041 std::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end());
1042 std::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end());
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001043
Michael J. Spencer51862b32011-10-13 22:17:18 +00001044 // Make a list of all the relocations for this section.
1045 std::vector<RelocationRef> Rels;
1046 if (InlineRelocs) {
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001047 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
1048 for (const RelocationRef &Reloc : RelocSec.relocations()) {
1049 Rels.push_back(Reloc);
1050 }
Michael J. Spencer51862b32011-10-13 22:17:18 +00001051 }
1052 }
1053
1054 // Sort relocations by address.
1055 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
1056
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001057 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +00001058 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001059 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +00001060 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001061 }
Michael J. Spencer1d6167f2011-06-25 17:55:23 +00001062 StringRef name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001063 error(Section.getName(name));
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001064 outs() << "Disassembly of section ";
1065 if (!SegmentName.empty())
1066 outs() << SegmentName << ",";
1067 outs() << name << ':';
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001068
Rafael Espindola7884c952015-06-04 15:01:05 +00001069 // If the section has no symbol at the start, just insert a dummy one.
1070 if (Symbols.empty() || Symbols[0].first != 0)
David Majnemer153722d2015-11-18 04:35:32 +00001071 Symbols.insert(Symbols.begin(), std::make_pair(SectionAddr, name));
Alp Tokere69170a2014-06-26 22:52:05 +00001072
1073 SmallString<40> Comments;
1074 raw_svector_ostream CommentStream(Comments);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001075
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001076 StringRef BytesStr;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001077 error(Section.getContents(BytesStr));
Aaron Ballman106fd7b2014-11-12 14:01:17 +00001078 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1079 BytesStr.size());
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001080
Michael J. Spencer2670c252011-01-20 06:39:06 +00001081 uint64_t Size;
1082 uint64_t Index;
1083
Michael J. Spencer51862b32011-10-13 22:17:18 +00001084 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
1085 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001086 // Disassemble symbol by symbol.
1087 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
Rafael Espindolae45c7402014-08-17 16:31:39 +00001088
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001089 uint64_t Start = Symbols[si].first - SectionAddr;
1090 // The end is either the section end or the beginning of the next
1091 // symbol.
1092 uint64_t End =
1093 (si == se - 1) ? SectSize : Symbols[si + 1].first - SectionAddr;
1094 // Don't try to disassemble beyond the end of section contents.
1095 if (End > SectSize)
1096 End = SectSize;
Rafael Espindolae45c7402014-08-17 16:31:39 +00001097 // If this symbol has the same address as the next symbol, then skip it.
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001098 if (Start >= End)
Michael J. Spenceree84f642011-10-13 20:37:08 +00001099 continue;
1100
Valery Pykhtinde048052016-04-07 07:24:01 +00001101 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1102 // make size 4 bytes folded
1103 End = Start + ((End - Start) & ~0x3ull);
1104 Start += 256; // add sizeof(amd_kernel_code_t)
1105 // cut trailing zeroes - up to 256 bytes (align)
1106 const uint64_t EndAlign = 256;
1107 const auto Limit = End - (std::min)(EndAlign, End - Start);
1108 while (End > Limit &&
1109 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1110 End -= 4;
1111 }
1112
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001113 outs() << '\n' << Symbols[si].second << ":\n";
Michael J. Spencer2670c252011-01-20 06:39:06 +00001114
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001115#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +00001116 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001117#else
Mark Seaborneb03ac52014-01-25 00:32:01 +00001118 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001119#endif
1120
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001121 for (Index = Start; Index < End; Index += Size) {
1122 MCInst Inst;
Owen Andersona0c3b972011-09-15 23:38:46 +00001123
Davide Italianof0706882015-10-01 21:57:09 +00001124 // AArch64 ELF binaries can interleave data and text in the
1125 // same section. We rely on the markers introduced to
1126 // understand what we need to dump.
1127 if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
1128 uint64_t Stride = 0;
1129
1130 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1131 DataMappingSymsAddr.end(), Index);
1132 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1133 // Switch to data.
1134 while (Index < End) {
1135 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1136 outs() << "\t";
1137 if (Index + 4 <= End) {
1138 Stride = 4;
1139 dumpBytes(Bytes.slice(Index, 4), outs());
1140 outs() << "\t.word";
1141 } else if (Index + 2 <= End) {
1142 Stride = 2;
1143 dumpBytes(Bytes.slice(Index, 2), outs());
1144 outs() << "\t.short";
1145 } else {
1146 Stride = 1;
1147 dumpBytes(Bytes.slice(Index, 1), outs());
1148 outs() << "\t.byte";
1149 }
1150 Index += Stride;
1151 outs() << "\n";
1152 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1153 TextMappingSymsAddr.end(), Index);
1154 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1155 break;
1156 }
1157 }
1158 }
1159
1160 if (Index >= End)
1161 break;
1162
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001163 bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1164 SectionAddr + Index, DebugOut,
1165 CommentStream);
1166 if (Size == 0)
1167 Size = 1;
1168 PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
1169 Bytes.slice(Index, Size),
1170 SectionAddr + Index, outs(), "", *STI);
1171 outs() << CommentStream.str();
1172 Comments.clear();
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001173
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001174 // Try to resolve the target of a call, tail call, etc. to a specific
1175 // symbol.
1176 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1177 MIA->isConditionalBranch(Inst))) {
1178 uint64_t Target;
1179 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1180 // In a relocatable object, the target's section must reside in
1181 // the same section as the call instruction or it is accessed
1182 // through a relocation.
1183 //
1184 // In a non-relocatable object, the target may be in any section.
1185 //
1186 // N.B. We don't walk the relocations in the relocatable case yet.
1187 auto *TargetSectionSymbols = &Symbols;
1188 if (!Obj->isRelocatableObject()) {
1189 auto SectionAddress = std::upper_bound(
1190 SectionAddresses.begin(), SectionAddresses.end(), Target,
1191 [](uint64_t LHS,
1192 const std::pair<uint64_t, SectionRef> &RHS) {
1193 return LHS < RHS.first;
1194 });
1195 if (SectionAddress != SectionAddresses.begin()) {
1196 --SectionAddress;
1197 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1198 } else {
1199 TargetSectionSymbols = nullptr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001200 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001201 }
David Majnemer2603a8fa2015-07-09 18:11:40 +00001202
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001203 // Find the first symbol in the section whose offset is less than
1204 // or equal to the target.
1205 if (TargetSectionSymbols) {
1206 auto TargetSym = std::upper_bound(
1207 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1208 Target, [](uint64_t LHS,
1209 const std::pair<uint64_t, StringRef> &RHS) {
1210 return LHS < RHS.first;
1211 });
1212 if (TargetSym != TargetSectionSymbols->begin()) {
1213 --TargetSym;
1214 uint64_t TargetAddress = std::get<0>(*TargetSym);
1215 StringRef TargetName = std::get<1>(*TargetSym);
1216 outs() << " <" << TargetName;
1217 uint64_t Disp = Target - TargetAddress;
1218 if (Disp)
1219 outs() << "+0x" << utohexstr(Disp);
1220 outs() << '>';
David Majnemer81afca62015-07-07 22:06:59 +00001221 }
1222 }
1223 }
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001224 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001225 outs() << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001226
1227 // Print relocation for instruction.
1228 while (rel_cur != rel_end) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001229 bool hidden = getHidden(*rel_cur);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001230 uint64_t addr = rel_cur->getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +00001231 SmallString<16> name;
1232 SmallString<32> val;
Owen Andersonfa3e5202011-10-25 20:35:53 +00001233
1234 // If this relocation is hidden, skip it.
Owen Andersonfa3e5202011-10-25 20:35:53 +00001235 if (hidden) goto skip_print_rel;
1236
Michael J. Spencer51862b32011-10-13 22:17:18 +00001237 // Stop when rel_cur's address is past the current instruction.
Owen Andersonf20e3e52011-10-25 20:15:39 +00001238 if (addr >= Index + Size) break;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001239 rel_cur->getTypeName(name);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001240 error(getRelocationValueString(*rel_cur, val));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001241 outs() << format(Fmt.data(), SectionAddr + addr) << name
Benjamin Kramer82803112012-03-10 02:04:38 +00001242 << "\t" << val << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001243
1244 skip_print_rel:
1245 ++rel_cur;
1246 }
Benjamin Kramer87ee76c2011-07-20 19:37:35 +00001247 }
Michael J. Spencer2670c252011-01-20 06:39:06 +00001248 }
1249 }
1250}
1251
Kevin Enderby98da6132015-01-20 21:47:46 +00001252void llvm::PrintRelocations(const ObjectFile *Obj) {
Greg Fitzgerald18432272014-03-20 22:55:15 +00001253 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1254 "%08" PRIx64;
Rafael Espindola9219fe72016-03-21 20:59:15 +00001255 // Regular objdump doesn't print relocations in non-relocatable object
1256 // files.
1257 if (!Obj->isRelocatableObject())
1258 return;
Rafael Espindolac66d7612014-08-17 19:09:37 +00001259
Colin LeMahieu77804be2015-07-29 15:45:39 +00001260 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001261 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001262 continue;
1263 StringRef secname;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001264 error(Section.getName(secname));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001265 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001266 for (const RelocationRef &Reloc : Section.relocations()) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001267 bool hidden = getHidden(Reloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001268 uint64_t address = Reloc.getOffset();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001269 SmallString<32> relocname;
1270 SmallString<32> valuestr;
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001271 if (hidden)
1272 continue;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001273 Reloc.getTypeName(relocname);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001274 error(getRelocationValueString(Reloc, valuestr));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001275 outs() << format(Fmt.data(), address) << " " << relocname << " "
1276 << valuestr << "\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001277 }
1278 outs() << "\n";
1279 }
1280}
1281
Kevin Enderby98da6132015-01-20 21:47:46 +00001282void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001283 outs() << "Sections:\n"
1284 "Idx Name Size Address Type\n";
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001285 unsigned i = 0;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001286 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001287 StringRef Name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001288 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001289 uint64_t Address = Section.getAddress();
1290 uint64_t Size = Section.getSize();
1291 bool Text = Section.isText();
1292 bool Data = Section.isData();
1293 bool BSS = Section.isBSS();
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001294 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +00001295 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
Alexey Samsonov48803e52014-03-13 14:37:36 +00001296 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1297 Name.str().c_str(), Size, Address, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001298 ++i;
1299 }
1300}
1301
Kevin Enderby98da6132015-01-20 21:47:46 +00001302void llvm::PrintSectionContents(const ObjectFile *Obj) {
Rafael Espindola4453e42942014-06-13 03:07:50 +00001303 std::error_code EC;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001304 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001305 StringRef Name;
1306 StringRef Contents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001307 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001308 uint64_t BaseAddr = Section.getAddress();
David Majnemer185b5b12014-11-11 09:58:25 +00001309 uint64_t Size = Section.getSize();
1310 if (!Size)
1311 continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001312
1313 outs() << "Contents of section " << Name << ":\n";
David Majnemer185b5b12014-11-11 09:58:25 +00001314 if (Section.isBSS()) {
Alexey Samsonov209095c2013-04-16 10:53:11 +00001315 outs() << format("<skipping contents of bss section at [%04" PRIx64
David Majnemer8f6b04c2014-07-14 16:20:14 +00001316 ", %04" PRIx64 ")>\n",
1317 BaseAddr, BaseAddr + Size);
Alexey Samsonov209095c2013-04-16 10:53:11 +00001318 continue;
1319 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001320
Davide Italianoccd53fe2015-08-05 07:18:31 +00001321 error(Section.getContents(Contents));
David Majnemer8f6b04c2014-07-14 16:20:14 +00001322
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001323 // Dump out the content as hex and printable ascii characters.
1324 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer82803112012-03-10 02:04:38 +00001325 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001326 // Dump line of hex.
1327 for (std::size_t i = 0; i < 16; ++i) {
1328 if (i != 0 && i % 4 == 0)
1329 outs() << ' ';
1330 if (addr + i < end)
1331 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1332 << hexdigit(Contents[addr + i] & 0xF, true);
1333 else
1334 outs() << " ";
1335 }
1336 // Print ascii.
1337 outs() << " ";
1338 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
Guy Benyei83c74e92013-02-12 21:21:59 +00001339 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001340 outs() << Contents[addr + i];
1341 else
1342 outs() << ".";
1343 }
1344 outs() << "\n";
1345 }
1346 }
1347}
1348
Kevin Enderby98da6132015-01-20 21:47:46 +00001349void llvm::PrintSymbolTable(const ObjectFile *o) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001350 outs() << "SYMBOL TABLE:\n";
1351
Rui Ueyama4e39f712014-03-18 18:58:51 +00001352 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
Davide Italianoe85abf72015-12-20 09:54:34 +00001353 printCOFFSymbolTable(coff);
Rui Ueyama4e39f712014-03-18 18:58:51 +00001354 return;
1355 }
1356 for (const SymbolRef &Symbol : o->symbols()) {
Rafael Espindolaed067c42015-07-03 18:19:00 +00001357 ErrorOr<uint64_t> AddressOrError = Symbol.getAddress();
Davide Italianoccd53fe2015-08-05 07:18:31 +00001358 error(AddressOrError.getError());
Rafael Espindolaed067c42015-07-03 18:19:00 +00001359 uint64_t Address = *AddressOrError;
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001360 Expected<SymbolRef::Type> TypeOrError = Symbol.getType();
1361 if (!TypeOrError)
1362 report_error(o->getFileName(), TypeOrError.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00001363 SymbolRef::Type Type = *TypeOrError;
Rui Ueyama4e39f712014-03-18 18:58:51 +00001364 uint32_t Flags = Symbol.getFlags();
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001365 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1366 error(errorToErrorCode(SectionOrErr.takeError()));
Rafael Espindola8bab8892015-08-07 23:27:14 +00001367 section_iterator Section = *SectionOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001368 StringRef Name;
1369 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1370 Section->getName(Name);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001371 } else {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001372 Expected<StringRef> NameOrErr = Symbol.getName();
1373 if (!NameOrErr)
1374 report_error(o->getFileName(), NameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001375 Name = *NameOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001376 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001377
Rui Ueyama4e39f712014-03-18 18:58:51 +00001378 bool Global = Flags & SymbolRef::SF_Global;
1379 bool Weak = Flags & SymbolRef::SF_Weak;
1380 bool Absolute = Flags & SymbolRef::SF_Absolute;
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001381 bool Common = Flags & SymbolRef::SF_Common;
Davide Italianocd2514d2015-04-30 23:08:53 +00001382 bool Hidden = Flags & SymbolRef::SF_Hidden;
David Meyer1df4b842012-02-28 23:47:53 +00001383
Rui Ueyama4e39f712014-03-18 18:58:51 +00001384 char GlobLoc = ' ';
1385 if (Type != SymbolRef::ST_Unknown)
1386 GlobLoc = Global ? 'g' : 'l';
1387 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1388 ? 'd' : ' ';
1389 char FileFunc = ' ';
1390 if (Type == SymbolRef::ST_File)
1391 FileFunc = 'f';
1392 else if (Type == SymbolRef::ST_Function)
1393 FileFunc = 'F';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001394
Rui Ueyama4e39f712014-03-18 18:58:51 +00001395 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1396 "%08" PRIx64;
Michael J. Spencerd857c1c2013-01-10 22:40:50 +00001397
Rui Ueyama4e39f712014-03-18 18:58:51 +00001398 outs() << format(Fmt, Address) << " "
1399 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1400 << (Weak ? 'w' : ' ') // Weak?
1401 << ' ' // Constructor. Not supported yet.
1402 << ' ' // Warning. Not supported yet.
1403 << ' ' // Indirect reference to another symbol.
1404 << Debug // Debugging (d) or dynamic (D) symbol.
1405 << FileFunc // Name of function (F), file (f) or object (O).
1406 << ' ';
1407 if (Absolute) {
1408 outs() << "*ABS*";
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001409 } else if (Common) {
1410 outs() << "*COM*";
Rui Ueyama4e39f712014-03-18 18:58:51 +00001411 } else if (Section == o->section_end()) {
1412 outs() << "*UND*";
1413 } else {
1414 if (const MachOObjectFile *MachO =
1415 dyn_cast<const MachOObjectFile>(o)) {
1416 DataRefImpl DR = Section->getRawDataRefImpl();
1417 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1418 outs() << SegmentName << ",";
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001419 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00001420 StringRef SectionName;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001421 error(Section->getName(SectionName));
Rui Ueyama4e39f712014-03-18 18:58:51 +00001422 outs() << SectionName;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001423 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001424
1425 outs() << '\t';
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001426 if (Common || isa<ELFObjectFileBase>(o)) {
Rafael Espindoladbb6bd32015-06-25 22:10:04 +00001427 uint64_t Val =
1428 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001429 outs() << format("\t %08" PRIx64 " ", Val);
1430 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001431
Davide Italianocd2514d2015-04-30 23:08:53 +00001432 if (Hidden) {
1433 outs() << ".hidden ";
1434 }
1435 outs() << Name
Rui Ueyama4e39f712014-03-18 18:58:51 +00001436 << '\n';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001437 }
1438}
1439
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001440static void PrintUnwindInfo(const ObjectFile *o) {
1441 outs() << "Unwind info:\n\n";
1442
1443 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1444 printCOFFUnwindInfo(coff);
Tim Northover4bd286a2014-08-01 13:07:19 +00001445 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1446 printMachOUnwindInfo(MachO);
1447 else {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001448 // TODO: Extract DWARF dump tool to objdump.
1449 errs() << "This operation is only currently supported "
Tim Northover4bd286a2014-08-01 13:07:19 +00001450 "for COFF and MachO object files.\n";
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001451 return;
1452 }
1453}
1454
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001455void llvm::printExportsTrie(const ObjectFile *o) {
Nick Kledzikd04bc352014-08-30 00:20:14 +00001456 outs() << "Exports trie:\n";
1457 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1458 printMachOExportsTrie(MachO);
1459 else {
1460 errs() << "This operation is only currently supported "
1461 "for Mach-O executable files.\n";
1462 return;
1463 }
1464}
1465
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001466void llvm::printRebaseTable(const ObjectFile *o) {
Nick Kledzikac431442014-09-12 21:34:15 +00001467 outs() << "Rebase table:\n";
1468 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1469 printMachORebaseTable(MachO);
1470 else {
1471 errs() << "This operation is only currently supported "
1472 "for Mach-O executable files.\n";
1473 return;
1474 }
1475}
1476
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001477void llvm::printBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001478 outs() << "Bind table:\n";
1479 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1480 printMachOBindTable(MachO);
1481 else {
1482 errs() << "This operation is only currently supported "
1483 "for Mach-O executable files.\n";
1484 return;
1485 }
1486}
1487
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001488void llvm::printLazyBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001489 outs() << "Lazy bind table:\n";
1490 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1491 printMachOLazyBindTable(MachO);
1492 else {
1493 errs() << "This operation is only currently supported "
1494 "for Mach-O executable files.\n";
1495 return;
1496 }
1497}
1498
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001499void llvm::printWeakBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001500 outs() << "Weak bind table:\n";
1501 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1502 printMachOWeakBindTable(MachO);
1503 else {
1504 errs() << "This operation is only currently supported "
1505 "for Mach-O executable files.\n";
1506 return;
1507 }
1508}
Nick Kledzikac431442014-09-12 21:34:15 +00001509
Adrian Prantl437105a2015-07-08 02:04:15 +00001510/// Dump the raw contents of the __clangast section so the output can be piped
1511/// into llvm-bcanalyzer.
1512void llvm::printRawClangAST(const ObjectFile *Obj) {
1513 if (outs().is_displayed()) {
1514 errs() << "The -raw-clang-ast option will dump the raw binary contents of "
1515 "the clang ast section.\n"
1516 "Please redirect the output to a file or another program such as "
1517 "llvm-bcanalyzer.\n";
1518 return;
1519 }
1520
1521 StringRef ClangASTSectionName("__clangast");
1522 if (isa<COFFObjectFile>(Obj)) {
1523 ClangASTSectionName = "clangast";
1524 }
1525
1526 Optional<object::SectionRef> ClangASTSection;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001527 for (auto Sec : ToolSectionFilter(*Obj)) {
Adrian Prantl437105a2015-07-08 02:04:15 +00001528 StringRef Name;
1529 Sec.getName(Name);
1530 if (Name == ClangASTSectionName) {
1531 ClangASTSection = Sec;
1532 break;
1533 }
1534 }
1535 if (!ClangASTSection)
1536 return;
1537
1538 StringRef ClangASTContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001539 error(ClangASTSection.getValue().getContents(ClangASTContents));
Adrian Prantl437105a2015-07-08 02:04:15 +00001540 outs().write(ClangASTContents.data(), ClangASTContents.size());
1541}
1542
Sanjoy Das6f567a42015-06-22 18:03:02 +00001543static void printFaultMaps(const ObjectFile *Obj) {
1544 const char *FaultMapSectionName = nullptr;
1545
1546 if (isa<ELFObjectFileBase>(Obj)) {
1547 FaultMapSectionName = ".llvm_faultmaps";
1548 } else if (isa<MachOObjectFile>(Obj)) {
1549 FaultMapSectionName = "__llvm_faultmaps";
1550 } else {
1551 errs() << "This operation is only currently supported "
1552 "for ELF and Mach-O executable files.\n";
1553 return;
1554 }
1555
1556 Optional<object::SectionRef> FaultMapSection;
1557
Colin LeMahieu77804be2015-07-29 15:45:39 +00001558 for (auto Sec : ToolSectionFilter(*Obj)) {
Sanjoy Das6f567a42015-06-22 18:03:02 +00001559 StringRef Name;
1560 Sec.getName(Name);
1561 if (Name == FaultMapSectionName) {
1562 FaultMapSection = Sec;
1563 break;
1564 }
1565 }
1566
1567 outs() << "FaultMap table:\n";
1568
1569 if (!FaultMapSection.hasValue()) {
1570 outs() << "<not found>\n";
1571 return;
1572 }
1573
1574 StringRef FaultMapContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001575 error(FaultMapSection.getValue().getContents(FaultMapContents));
Sanjoy Das6f567a42015-06-22 18:03:02 +00001576
1577 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1578 FaultMapContents.bytes_end());
1579
1580 outs() << FMP;
1581}
1582
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001583static void printPrivateFileHeaders(const ObjectFile *o) {
1584 if (o->isELF())
1585 printELFFileHeader(o);
1586 else if (o->isCOFF())
1587 printCOFFFileHeader(o);
1588 else if (o->isMachO()) {
1589 printMachOFileHeader(o);
1590 printMachOLoadCommands(o);
1591 } else
1592 report_fatal_error("Invalid/Unsupported object file format");
1593}
1594
1595static void printFirstPrivateFileHeader(const ObjectFile *o) {
Davide Italiano540e9212015-12-19 22:09:40 +00001596 if (o->isELF())
Rui Ueyamac2bed422013-09-27 21:04:00 +00001597 printELFFileHeader(o);
Davide Italiano540e9212015-12-19 22:09:40 +00001598 else if (o->isCOFF())
Rui Ueyamac2bed422013-09-27 21:04:00 +00001599 printCOFFFileHeader(o);
Davide Italiano540e9212015-12-19 22:09:40 +00001600 else if (o->isMachO())
Kevin Enderbyb76d3862014-08-22 20:35:18 +00001601 printMachOFileHeader(o);
Davide Italiano540e9212015-12-19 22:09:40 +00001602 else
1603 report_fatal_error("Invalid/Unsupported object file format");
Rui Ueyamac2bed422013-09-27 21:04:00 +00001604}
1605
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001606static void DumpObject(const ObjectFile *o) {
Adrian Prantl437105a2015-07-08 02:04:15 +00001607 // Avoid other output when using a raw option.
1608 if (!RawClangAST) {
1609 outs() << '\n';
1610 outs() << o->getFileName()
1611 << ":\tfile format " << o->getFileFormatName() << "\n\n";
1612 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001613
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001614 if (Disassemble)
Michael J. Spencer51862b32011-10-13 22:17:18 +00001615 DisassembleObject(o, Relocations);
1616 if (Relocations && !Disassemble)
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001617 PrintRelocations(o);
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001618 if (SectionHeaders)
1619 PrintSectionHeaders(o);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001620 if (SectionContents)
1621 PrintSectionContents(o);
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001622 if (SymbolTable)
1623 PrintSymbolTable(o);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001624 if (UnwindInfo)
1625 PrintUnwindInfo(o);
Rui Ueyamac2bed422013-09-27 21:04:00 +00001626 if (PrivateHeaders)
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001627 printPrivateFileHeaders(o);
1628 if (FirstPrivateHeader)
1629 printFirstPrivateFileHeader(o);
Nick Kledzikd04bc352014-08-30 00:20:14 +00001630 if (ExportsTrie)
1631 printExportsTrie(o);
Nick Kledzikac431442014-09-12 21:34:15 +00001632 if (Rebase)
1633 printRebaseTable(o);
Nick Kledzik56ebef42014-09-16 01:41:51 +00001634 if (Bind)
1635 printBindTable(o);
1636 if (LazyBind)
1637 printLazyBindTable(o);
1638 if (WeakBind)
1639 printWeakBindTable(o);
Adrian Prantl437105a2015-07-08 02:04:15 +00001640 if (RawClangAST)
1641 printRawClangAST(o);
Sanjoy Das6f567a42015-06-22 18:03:02 +00001642 if (PrintFaultMaps)
1643 printFaultMaps(o);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001644 if (DwarfDumpType != DIDT_Null) {
1645 std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*o));
1646 // Dump the complete DWARF structure.
1647 DICtx->dump(outs(), DwarfDumpType, true /* DumpEH */);
1648 }
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001649}
1650
1651/// @brief Dump each object file in \a a;
1652static void DumpArchive(const Archive *a) {
Kevin Enderby7a969422015-11-05 19:24:56 +00001653 for (auto &ErrorOrChild : a->children()) {
1654 if (std::error_code EC = ErrorOrChild.getError())
1655 report_error(a->getFileName(), EC);
1656 const Archive::Child &C = *ErrorOrChild;
Davide Italiano95dd3cb2015-08-03 21:46:32 +00001657 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Davide Italianoccd53fe2015-08-05 07:18:31 +00001658 if (std::error_code EC = ChildOrErr.getError())
Mark Seaborneb03ac52014-01-25 00:32:01 +00001659 if (EC != object_error::invalid_file_type)
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001660 report_error(a->getFileName(), EC);
Rafael Espindolaae460022014-06-16 16:08:36 +00001661 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001662 DumpObject(o);
1663 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001664 report_error(a->getFileName(), object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001665 }
1666}
1667
1668/// @brief Open file and figure out how to dump it.
1669static void DumpInput(StringRef file) {
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001670
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001671 // If we are using the Mach-O specific object file parser, then let it parse
1672 // the file and process the command line options. So the -arch flags can
1673 // be used to select specific slices, etc.
1674 if (MachOOpt) {
1675 ParseInputMachO(file);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001676 return;
1677 }
1678
1679 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00001680 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
1681 if (!BinaryOrErr)
1682 report_error(file, errorToErrorCode(BinaryOrErr.takeError()));
Rafael Espindola48af1c22014-08-19 18:44:46 +00001683 Binary &Binary = *BinaryOrErr.get().getBinary();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001684
Rafael Espindola3f6481d2014-08-01 14:31:55 +00001685 if (Archive *a = dyn_cast<Archive>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001686 DumpArchive(a);
Rafael Espindola3f6481d2014-08-01 14:31:55 +00001687 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001688 DumpObject(o);
Jim Grosbachaf9aec02012-08-07 17:53:14 +00001689 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001690 report_error(file, object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001691}
1692
Michael J. Spencer2670c252011-01-20 06:39:06 +00001693int main(int argc, char **argv) {
1694 // Print a stack trace if we signal out.
1695 sys::PrintStackTraceOnErrorSignal();
1696 PrettyStackTraceProgram X(argc, argv);
1697 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1698
1699 // Initialize targets and assembly printers/parsers.
1700 llvm::InitializeAllTargetInfos();
Evan Cheng8c886a42011-07-22 21:58:54 +00001701 llvm::InitializeAllTargetMCs();
Michael J. Spencer2670c252011-01-20 06:39:06 +00001702 llvm::InitializeAllDisassemblers();
1703
Pete Cooper28fb4fc2012-05-03 23:20:10 +00001704 // Register the target printer for --version.
1705 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
1706
Michael J. Spencer2670c252011-01-20 06:39:06 +00001707 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
1708 TripleName = Triple::normalize(TripleName);
1709
1710 ToolName = argv[0];
1711
1712 // Defaults to a.out if no filenames specified.
1713 if (InputFilenames.size() == 0)
1714 InputFilenames.push_back("a.out");
1715
Colin LeMahieuf34933e2015-07-23 20:58:49 +00001716 if (DisassembleAll)
1717 Disassemble = true;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001718 if (!Disassemble
1719 && !Relocations
1720 && !SectionHeaders
1721 && !SectionContents
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001722 && !SymbolTable
Michael J. Spencer209565db2013-01-06 03:56:49 +00001723 && !UnwindInfo
Nick Kledzikd04bc352014-08-30 00:20:14 +00001724 && !PrivateHeaders
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001725 && !FirstPrivateHeader
Nick Kledzikac431442014-09-12 21:34:15 +00001726 && !ExportsTrie
Nick Kledzik56ebef42014-09-16 01:41:51 +00001727 && !Rebase
1728 && !Bind
1729 && !LazyBind
Kevin Enderby131d1772015-01-09 19:22:37 +00001730 && !WeakBind
Adrian Prantl437105a2015-07-08 02:04:15 +00001731 && !RawClangAST
Kevin Enderby13023a12015-01-15 23:19:11 +00001732 && !(UniversalHeaders && MachOOpt)
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001733 && !(ArchiveHeaders && MachOOpt)
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001734 && !(IndirectSymbols && MachOOpt)
Kevin Enderby9a509442015-01-27 21:28:24 +00001735 && !(DataInCode && MachOOpt)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001736 && !(LinkOptHints && MachOOpt)
Kevin Enderbycd66be52015-03-11 22:06:32 +00001737 && !(InfoPlist && MachOOpt)
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001738 && !(DylibsUsed && MachOOpt)
1739 && !(DylibId && MachOOpt)
Kevin Enderby0fc11822015-04-01 20:57:01 +00001740 && !(ObjcMetaData && MachOOpt)
Colin LeMahieufcc32762015-07-29 19:08:10 +00001741 && !(FilterSections.size() != 0 && MachOOpt)
Igor Laevsky03a670c2016-01-26 15:09:42 +00001742 && !PrintFaultMaps
1743 && DwarfDumpType == DIDT_Null) {
Michael J. Spencer2670c252011-01-20 06:39:06 +00001744 cl::PrintHelpMessage();
1745 return 2;
1746 }
1747
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001748 std::for_each(InputFilenames.begin(), InputFilenames.end(),
1749 DumpInput);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001750
Davide Italianoccd53fe2015-08-05 07:18:31 +00001751 return EXIT_SUCCESS;
Michael J. Spencer2670c252011-01-20 06:39:06 +00001752}