blob: dfdb4ba7d7c2a05bfa8c47fb148aea073e0b13b0 [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();
Kevin Enderbyb34e3a12016-05-05 17:43:35 +0000280 errs() << ToolName << ": '" << File << "': " << Buf;
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000281 exit(1);
282}
283
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000284LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
285 StringRef FileName,
286 llvm::Error E) {
287 assert(E);
288 errs() << ToolName << ": ";
289 if (ArchiveName != "")
290 errs() << ArchiveName << "(" << FileName << ")";
291 else
292 errs() << FileName;
293 std::string Buf;
294 raw_string_ostream OS(Buf);
295 logAllUnhandledErrors(std::move(E), OS, "");
296 OS.flush();
297 errs() << " " << Buf;
298 exit(1);
299}
300
301LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
302 const object::Archive::Child &C,
303 llvm::Error E) {
304 ErrorOr<StringRef> NameOrErr = C.getName();
305 // TODO: if we have a error getting the name then it would be nice to print
306 // the index of which archive member this is and or its offset in the
307 // archive instead of "???" as the name.
308 if (NameOrErr.getError())
309 llvm::report_error(ArchiveName, "???", std::move(E));
310 else
311 llvm::report_error(ArchiveName, NameOrErr.get(), std::move(E));
312}
313
Craig Toppere6cb63e2014-04-25 04:24:47 +0000314static const Target *getTarget(const ObjectFile *Obj = nullptr) {
Michael J. Spencer2670c252011-01-20 06:39:06 +0000315 // Figure out the target triple.
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000316 llvm::Triple TheTriple("unknown-unknown-unknown");
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000317 if (TripleName.empty()) {
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000318 if (Obj) {
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000319 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000320 // TheTriple defaults to ELF, and COFF doesn't have an environment:
321 // the best we can do here is indicate that it is mach-o.
322 if (Obj->isMachO())
Saleem Abdulrasool35476332014-03-06 20:47:11 +0000323 TheTriple.setObjectFormat(Triple::MachO);
Saleem Abdulrasool98938f12014-04-17 06:17:23 +0000324
325 if (Obj->isCOFF()) {
326 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
327 if (COFFObj->getArch() == Triple::thumb)
328 TheTriple.setTriple("thumbv7-windows");
329 }
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000330 }
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000331 } else
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000332 TheTriple.setTriple(Triple::normalize(TripleName));
Michael J. Spencer2670c252011-01-20 06:39:06 +0000333
334 // Get the target specific parser.
335 std::string Error;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000336 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
337 Error);
Davide Italianobb599e32015-12-03 22:13:40 +0000338 if (!TheTarget)
339 report_fatal_error("can't find target: " + Error);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000340
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000341 // Update the triple name and return the found target.
342 TripleName = TheTriple.getTriple();
343 return TheTarget;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000344}
345
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000346bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
Rafael Espindola704cd842015-07-06 15:47:43 +0000347 return a.getOffset() < b.getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +0000348}
349
Colin LeMahieufb76b002015-05-28 19:07:14 +0000350namespace {
351class PrettyPrinter {
352public:
Colin LeMahieu0b5890d2015-05-28 20:59:08 +0000353 virtual ~PrettyPrinter(){}
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000354 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
Colin LeMahieufb76b002015-05-28 19:07:14 +0000355 ArrayRef<uint8_t> Bytes, uint64_t Address,
356 raw_ostream &OS, StringRef Annot,
357 MCSubtargetInfo const &STI) {
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000358 OS << format("%8" PRIx64 ":", Address);
Colin LeMahieufb76b002015-05-28 19:07:14 +0000359 if (!NoShowRawInsn) {
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000360 OS << "\t";
361 dumpBytes(Bytes, OS);
Colin LeMahieufb76b002015-05-28 19:07:14 +0000362 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000363 if (MI)
364 IP.printInst(MI, OS, "", STI);
365 else
366 OS << " <unknown>";
Colin LeMahieufb76b002015-05-28 19:07:14 +0000367 }
368};
369PrettyPrinter PrettyPrinterInst;
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000370class HexagonPrettyPrinter : public PrettyPrinter {
371public:
372 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
373 raw_ostream &OS) {
374 uint32_t opcode =
375 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
376 OS << format("%8" PRIx64 ":", Address);
377 if (!NoShowRawInsn) {
378 OS << "\t";
379 dumpBytes(Bytes.slice(0, 4), OS);
380 OS << format("%08" PRIx32, opcode);
381 }
382 }
383 void printInst(MCInstPrinter &IP, const MCInst *MI,
384 ArrayRef<uint8_t> Bytes, uint64_t Address,
385 raw_ostream &OS, StringRef Annot,
386 MCSubtargetInfo const &STI) override {
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000387 if (!MI) {
388 printLead(Bytes, Address, OS);
389 OS << " <unknown>";
390 return;
391 }
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000392 std::string Buffer;
393 {
394 raw_string_ostream TempStream(Buffer);
395 IP.printInst(MI, TempStream, "", STI);
396 }
397 StringRef Contents(Buffer);
398 // Split off bundle attributes
399 auto PacketBundle = Contents.rsplit('\n');
400 // Split off first instruction from the rest
401 auto HeadTail = PacketBundle.first.split('\n');
402 auto Preamble = " { ";
403 auto Separator = "";
404 while(!HeadTail.first.empty()) {
405 OS << Separator;
406 Separator = "\n";
407 printLead(Bytes, Address, OS);
408 OS << Preamble;
409 Preamble = " ";
410 StringRef Inst;
411 auto Duplex = HeadTail.first.split('\v');
412 if(!Duplex.second.empty()){
413 OS << Duplex.first;
414 OS << "; ";
415 Inst = Duplex.second;
416 }
417 else
418 Inst = HeadTail.first;
419 OS << Inst;
420 Bytes = Bytes.slice(4);
421 Address += 4;
422 HeadTail = HeadTail.second.split('\n');
423 }
424 OS << " } " << PacketBundle.second;
425 }
426};
427HexagonPrettyPrinter HexagonPrettyPrinterInst;
Valery Pykhtinde048052016-04-07 07:24:01 +0000428
429class AMDGCNPrettyPrinter : public PrettyPrinter {
430public:
431 void printInst(MCInstPrinter &IP,
432 const MCInst *MI,
433 ArrayRef<uint8_t> Bytes,
434 uint64_t Address,
435 raw_ostream &OS,
436 StringRef Annot,
437 MCSubtargetInfo const &STI) override {
Matt Arsenault87d80db2016-04-22 21:23:41 +0000438 if (!MI) {
439 OS << " <unknown>";
440 return;
441 }
442
Valery Pykhtinde048052016-04-07 07:24:01 +0000443 SmallString<40> InstStr;
444 raw_svector_ostream IS(InstStr);
445
446 IP.printInst(MI, IS, "", STI);
447
Valery Pykhtin8e79f5b2016-04-07 08:38:20 +0000448 OS << left_justify(IS.str(), 60) << format("// %012" PRIX64 ": ", Address);
Valery Pykhtinde048052016-04-07 07:24:01 +0000449 typedef support::ulittle32_t U32;
450 for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
451 Bytes.size() / sizeof(U32)))
452 // D should be explicitly casted to uint32_t here as it is passed
453 // by format to snprintf as vararg.
Valery Pykhtin8e79f5b2016-04-07 08:38:20 +0000454 OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D));
Valery Pykhtinde048052016-04-07 07:24:01 +0000455
456 if (!Annot.empty())
457 OS << "// " << Annot;
458 }
459};
460AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
461
Colin LeMahieu35436a22015-05-29 14:48:25 +0000462PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000463 switch(Triple.getArch()) {
464 default:
465 return PrettyPrinterInst;
466 case Triple::hexagon:
467 return HexagonPrettyPrinterInst;
Valery Pykhtinde048052016-04-07 07:24:01 +0000468 case Triple::amdgcn:
469 return AMDGCNPrettyPrinterInst;
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000470 }
Colin LeMahieufb76b002015-05-28 19:07:14 +0000471}
472}
473
Rafael Espindola37070a52015-06-03 04:48:06 +0000474template <class ELFT>
Rafael Espindola37070a52015-06-03 04:48:06 +0000475static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000476 const RelocationRef &RelRef,
Rafael Espindola37070a52015-06-03 04:48:06 +0000477 SmallVectorImpl<char> &Result) {
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000478 DataRefImpl Rel = RelRef.getRawDataRefImpl();
479
Rafael Espindola37070a52015-06-03 04:48:06 +0000480 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
481 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000482 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
483
Rafael Espindola37070a52015-06-03 04:48:06 +0000484 const ELFFile<ELFT> &EF = *Obj->getELFFile();
485
Rafael Espindola6def3042015-07-01 12:56:27 +0000486 ErrorOr<const Elf_Shdr *> SecOrErr = EF.getSection(Rel.d.a);
487 if (std::error_code EC = SecOrErr.getError())
488 return EC;
489 const Elf_Shdr *Sec = *SecOrErr;
490 ErrorOr<const Elf_Shdr *> SymTabOrErr = EF.getSection(Sec->sh_link);
491 if (std::error_code EC = SymTabOrErr.getError())
492 return EC;
493 const Elf_Shdr *SymTab = *SymTabOrErr;
Rafael Espindola719dc7c2015-06-29 12:38:31 +0000494 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
495 SymTab->sh_type == ELF::SHT_DYNSYM);
Rafael Espindola6def3042015-07-01 12:56:27 +0000496 ErrorOr<const Elf_Shdr *> StrTabSec = EF.getSection(SymTab->sh_link);
497 if (std::error_code EC = StrTabSec.getError())
498 return EC;
499 ErrorOr<StringRef> StrTabOrErr = EF.getStringTable(*StrTabSec);
Rafael Espindola6a1bfb22015-06-29 14:39:25 +0000500 if (std::error_code EC = StrTabOrErr.getError())
501 return EC;
502 StringRef StrTab = *StrTabOrErr;
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000503 uint8_t type = RelRef.getType();
Rafael Espindola37070a52015-06-03 04:48:06 +0000504 StringRef res;
505 int64_t addend = 0;
Rafael Espindola6def3042015-07-01 12:56:27 +0000506 switch (Sec->sh_type) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000507 default:
508 return object_error::parse_failed;
509 case ELF::SHT_REL: {
Rafael Espindola37070a52015-06-03 04:48:06 +0000510 // TODO: Read implicit addend from section data.
511 break;
512 }
513 case ELF::SHT_RELA: {
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000514 const Elf_Rela *ERela = Obj->getRela(Rel);
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000515 addend = ERela->r_addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000516 break;
517 }
518 }
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000519 symbol_iterator SI = RelRef.getSymbol();
520 const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
Rafael Espindola75d5b542015-06-03 05:14:22 +0000521 StringRef Target;
Rafael Espindola75d5b542015-06-03 05:14:22 +0000522 if (symb->getType() == ELF::STT_SECTION) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000523 Expected<section_iterator> SymSI = SI->getSection();
524 if (!SymSI)
525 return errorToErrorCode(SymSI.takeError());
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000526 const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
527 ErrorOr<StringRef> SecName = EF.getSectionName(SymSec);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000528 if (std::error_code EC = SecName.getError())
529 return EC;
530 Target = *SecName;
531 } else {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000532 Expected<StringRef> SymName = symb->getName(StrTab);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000533 if (!SymName)
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000534 return errorToErrorCode(SymName.takeError());
Rafael Espindola75d5b542015-06-03 05:14:22 +0000535 Target = *SymName;
536 }
Rafael Espindola37070a52015-06-03 04:48:06 +0000537 switch (EF.getHeader()->e_machine) {
538 case ELF::EM_X86_64:
539 switch (type) {
540 case ELF::R_X86_64_PC8:
541 case ELF::R_X86_64_PC16:
542 case ELF::R_X86_64_PC32: {
543 std::string fmtbuf;
544 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000545 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
Rafael Espindola37070a52015-06-03 04:48:06 +0000546 fmt.flush();
547 Result.append(fmtbuf.begin(), fmtbuf.end());
548 } break;
549 case ELF::R_X86_64_8:
550 case ELF::R_X86_64_16:
551 case ELF::R_X86_64_32:
552 case ELF::R_X86_64_32S:
553 case ELF::R_X86_64_64: {
554 std::string fmtbuf;
555 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000556 fmt << Target << (addend < 0 ? "" : "+") << addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000557 fmt.flush();
558 Result.append(fmtbuf.begin(), fmtbuf.end());
559 } break;
560 default:
561 res = "Unknown";
562 }
563 break;
Jacques Pienaarea9f25a2016-03-01 21:21:42 +0000564 case ELF::EM_LANAI:
Rafael Espindola37070a52015-06-03 04:48:06 +0000565 case ELF::EM_AARCH64: {
566 std::string fmtbuf;
567 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000568 fmt << Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000569 if (addend != 0)
570 fmt << (addend < 0 ? "" : "+") << addend;
571 fmt.flush();
572 Result.append(fmtbuf.begin(), fmtbuf.end());
573 break;
574 }
575 case ELF::EM_386:
Michael Kupersteina3b79dd2015-11-04 11:21:50 +0000576 case ELF::EM_IAMCU:
Rafael Espindola37070a52015-06-03 04:48:06 +0000577 case ELF::EM_ARM:
578 case ELF::EM_HEXAGON:
579 case ELF::EM_MIPS:
Rafael Espindola75d5b542015-06-03 05:14:22 +0000580 res = Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000581 break;
Dan Gohman46350172016-01-12 20:56:01 +0000582 case ELF::EM_WEBASSEMBLY:
583 switch (type) {
584 case ELF::R_WEBASSEMBLY_DATA: {
585 std::string fmtbuf;
586 raw_string_ostream fmt(fmtbuf);
587 fmt << Target << (addend < 0 ? "" : "+") << addend;
588 fmt.flush();
589 Result.append(fmtbuf.begin(), fmtbuf.end());
590 break;
591 }
592 case ELF::R_WEBASSEMBLY_FUNCTION:
593 res = Target;
594 break;
595 default:
596 res = "Unknown";
597 }
598 break;
Rafael Espindola37070a52015-06-03 04:48:06 +0000599 default:
600 res = "Unknown";
601 }
602 if (Result.empty())
603 Result.append(res.begin(), res.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000604 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000605}
606
607static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000608 const RelocationRef &Rel,
Rafael Espindola37070a52015-06-03 04:48:06 +0000609 SmallVectorImpl<char> &Result) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000610 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
611 return getRelocationValueString(ELF32LE, Rel, Result);
612 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
613 return getRelocationValueString(ELF64LE, Rel, Result);
614 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
615 return getRelocationValueString(ELF32BE, Rel, Result);
616 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
617 return getRelocationValueString(ELF64BE, Rel, Result);
618}
619
620static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
621 const RelocationRef &Rel,
622 SmallVectorImpl<char> &Result) {
623 symbol_iterator SymI = Rel.getSymbol();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000624 Expected<StringRef> SymNameOrErr = SymI->getName();
625 if (!SymNameOrErr)
626 return errorToErrorCode(SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000627 StringRef SymName = *SymNameOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000628 Result.append(SymName.begin(), SymName.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000629 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000630}
631
632static void printRelocationTargetName(const MachOObjectFile *O,
633 const MachO::any_relocation_info &RE,
634 raw_string_ostream &fmt) {
635 bool IsScattered = O->isRelocationScattered(RE);
636
637 // Target of a scattered relocation is an address. In the interest of
638 // generating pretty output, scan through the symbol table looking for a
639 // symbol that aligns with that address. If we find one, print it.
640 // Otherwise, we just print the hex address of the target.
641 if (IsScattered) {
642 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
643
644 for (const SymbolRef &Symbol : O->symbols()) {
645 std::error_code ec;
Rafael Espindolaed067c42015-07-03 18:19:00 +0000646 ErrorOr<uint64_t> Addr = Symbol.getAddress();
647 if ((ec = Addr.getError()))
Rafael Espindola37070a52015-06-03 04:48:06 +0000648 report_fatal_error(ec.message());
Rafael Espindolaed067c42015-07-03 18:19:00 +0000649 if (*Addr != Val)
Rafael Espindola37070a52015-06-03 04:48:06 +0000650 continue;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000651 Expected<StringRef> Name = Symbol.getName();
652 if (!Name) {
653 std::string Buf;
654 raw_string_ostream OS(Buf);
655 logAllUnhandledErrors(Name.takeError(), OS, "");
656 OS.flush();
657 report_fatal_error(Buf);
658 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000659 fmt << *Name;
Rafael Espindola37070a52015-06-03 04:48:06 +0000660 return;
661 }
662
663 // If we couldn't find a symbol that this relocation refers to, try
664 // to find a section beginning instead.
Colin LeMahieu77804be2015-07-29 15:45:39 +0000665 for (const SectionRef &Section : ToolSectionFilter(*O)) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000666 std::error_code ec;
667
668 StringRef Name;
669 uint64_t Addr = Section.getAddress();
670 if (Addr != Val)
671 continue;
672 if ((ec = Section.getName(Name)))
673 report_fatal_error(ec.message());
674 fmt << Name;
675 return;
676 }
677
678 fmt << format("0x%x", Val);
679 return;
680 }
681
682 StringRef S;
683 bool isExtern = O->getPlainRelocationExternal(RE);
684 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
685
686 if (isExtern) {
687 symbol_iterator SI = O->symbol_begin();
688 advance(SI, Val);
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000689 Expected<StringRef> SOrErr = SI->getName();
690 error(errorToErrorCode(SOrErr.takeError()));
Davide Italianoccd53fe2015-08-05 07:18:31 +0000691 S = *SOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000692 } else {
693 section_iterator SI = O->section_begin();
694 // Adjust for the fact that sections are 1-indexed.
695 advance(SI, Val - 1);
696 SI->getName(S);
697 }
698
699 fmt << S;
700}
701
702static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
703 const RelocationRef &RelRef,
704 SmallVectorImpl<char> &Result) {
705 DataRefImpl Rel = RelRef.getRawDataRefImpl();
706 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
707
708 unsigned Arch = Obj->getArch();
709
710 std::string fmtbuf;
711 raw_string_ostream fmt(fmtbuf);
712 unsigned Type = Obj->getAnyRelocationType(RE);
713 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
714
715 // Determine any addends that should be displayed with the relocation.
716 // These require decoding the relocation type, which is triple-specific.
717
718 // X86_64 has entirely custom relocation types.
719 if (Arch == Triple::x86_64) {
720 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
721
722 switch (Type) {
723 case MachO::X86_64_RELOC_GOT_LOAD:
724 case MachO::X86_64_RELOC_GOT: {
725 printRelocationTargetName(Obj, RE, fmt);
726 fmt << "@GOT";
727 if (isPCRel)
728 fmt << "PCREL";
729 break;
730 }
731 case MachO::X86_64_RELOC_SUBTRACTOR: {
732 DataRefImpl RelNext = Rel;
733 Obj->moveRelocationNext(RelNext);
734 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
735
736 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
737 // X86_64_RELOC_UNSIGNED.
738 // NOTE: Scattered relocations don't exist on x86_64.
739 unsigned RType = Obj->getAnyRelocationType(RENext);
740 if (RType != MachO::X86_64_RELOC_UNSIGNED)
741 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
742 "X86_64_RELOC_SUBTRACTOR.");
743
744 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
745 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
746 printRelocationTargetName(Obj, RENext, fmt);
747 fmt << "-";
748 printRelocationTargetName(Obj, RE, fmt);
749 break;
750 }
751 case MachO::X86_64_RELOC_TLV:
752 printRelocationTargetName(Obj, RE, fmt);
753 fmt << "@TLV";
754 if (isPCRel)
755 fmt << "P";
756 break;
757 case MachO::X86_64_RELOC_SIGNED_1:
758 printRelocationTargetName(Obj, RE, fmt);
759 fmt << "-1";
760 break;
761 case MachO::X86_64_RELOC_SIGNED_2:
762 printRelocationTargetName(Obj, RE, fmt);
763 fmt << "-2";
764 break;
765 case MachO::X86_64_RELOC_SIGNED_4:
766 printRelocationTargetName(Obj, RE, fmt);
767 fmt << "-4";
768 break;
769 default:
770 printRelocationTargetName(Obj, RE, fmt);
771 break;
772 }
773 // X86 and ARM share some relocation types in common.
774 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
775 Arch == Triple::ppc) {
776 // Generic relocation types...
777 switch (Type) {
778 case MachO::GENERIC_RELOC_PAIR: // prints no info
Rui Ueyama7d099192015-06-09 15:20:42 +0000779 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000780 case MachO::GENERIC_RELOC_SECTDIFF: {
781 DataRefImpl RelNext = Rel;
782 Obj->moveRelocationNext(RelNext);
783 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
784
785 // X86 sect diff's must be followed by a relocation of type
786 // GENERIC_RELOC_PAIR.
787 unsigned RType = Obj->getAnyRelocationType(RENext);
788
789 if (RType != MachO::GENERIC_RELOC_PAIR)
790 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
791 "GENERIC_RELOC_SECTDIFF.");
792
793 printRelocationTargetName(Obj, RE, fmt);
794 fmt << "-";
795 printRelocationTargetName(Obj, RENext, fmt);
796 break;
797 }
798 }
799
800 if (Arch == Triple::x86 || Arch == Triple::ppc) {
801 switch (Type) {
802 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
803 DataRefImpl RelNext = Rel;
804 Obj->moveRelocationNext(RelNext);
805 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
806
807 // X86 sect diff's must be followed by a relocation of type
808 // GENERIC_RELOC_PAIR.
809 unsigned RType = Obj->getAnyRelocationType(RENext);
810 if (RType != MachO::GENERIC_RELOC_PAIR)
811 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
812 "GENERIC_RELOC_LOCAL_SECTDIFF.");
813
814 printRelocationTargetName(Obj, RE, fmt);
815 fmt << "-";
816 printRelocationTargetName(Obj, RENext, fmt);
817 break;
818 }
819 case MachO::GENERIC_RELOC_TLV: {
820 printRelocationTargetName(Obj, RE, fmt);
821 fmt << "@TLV";
822 if (IsPCRel)
823 fmt << "P";
824 break;
825 }
826 default:
827 printRelocationTargetName(Obj, RE, fmt);
828 }
829 } else { // ARM-specific relocations
830 switch (Type) {
831 case MachO::ARM_RELOC_HALF:
832 case MachO::ARM_RELOC_HALF_SECTDIFF: {
833 // Half relocations steal a bit from the length field to encode
834 // whether this is an upper16 or a lower16 relocation.
835 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
836
837 if (isUpper)
838 fmt << ":upper16:(";
839 else
840 fmt << ":lower16:(";
841 printRelocationTargetName(Obj, RE, fmt);
842
843 DataRefImpl RelNext = Rel;
844 Obj->moveRelocationNext(RelNext);
845 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
846
847 // ARM half relocs must be followed by a relocation of type
848 // ARM_RELOC_PAIR.
849 unsigned RType = Obj->getAnyRelocationType(RENext);
850 if (RType != MachO::ARM_RELOC_PAIR)
851 report_fatal_error("Expected ARM_RELOC_PAIR after "
852 "ARM_RELOC_HALF");
853
854 // NOTE: The half of the target virtual address is stashed in the
855 // address field of the secondary relocation, but we can't reverse
856 // engineer the constant offset from it without decoding the movw/movt
857 // instruction to find the other half in its immediate field.
858
859 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
860 // symbol/section pointer of the follow-on relocation.
861 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
862 fmt << "-";
863 printRelocationTargetName(Obj, RENext, fmt);
864 }
865
866 fmt << ")";
867 break;
868 }
869 default: { printRelocationTargetName(Obj, RE, fmt); }
870 }
871 }
872 } else
873 printRelocationTargetName(Obj, RE, fmt);
874
875 fmt.flush();
876 Result.append(fmtbuf.begin(), fmtbuf.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000877 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000878}
879
880static std::error_code getRelocationValueString(const RelocationRef &Rel,
881 SmallVectorImpl<char> &Result) {
Rafael Espindola854038e2015-06-26 14:51:16 +0000882 const ObjectFile *Obj = Rel.getObject();
Rafael Espindola37070a52015-06-03 04:48:06 +0000883 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
884 return getRelocationValueString(ELF, Rel, Result);
885 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
886 return getRelocationValueString(COFF, Rel, Result);
887 auto *MachO = cast<MachOObjectFile>(Obj);
888 return getRelocationValueString(MachO, Rel, Result);
889}
890
Rafael Espindola0ad71d92015-06-30 03:41:26 +0000891/// @brief Indicates whether this relocation should hidden when listing
892/// relocations, usually because it is the trailing part of a multipart
893/// relocation that will be printed as part of the leading relocation.
894static bool getHidden(RelocationRef RelRef) {
895 const ObjectFile *Obj = RelRef.getObject();
896 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
897 if (!MachO)
898 return false;
899
900 unsigned Arch = MachO->getArch();
901 DataRefImpl Rel = RelRef.getRawDataRefImpl();
902 uint64_t Type = MachO->getRelocationType(Rel);
903
904 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
905 // is always hidden.
906 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
907 if (Type == MachO::GENERIC_RELOC_PAIR)
908 return true;
909 } else if (Arch == Triple::x86_64) {
910 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
911 // an X86_64_RELOC_SUBTRACTOR.
912 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
913 DataRefImpl RelPrev = Rel;
914 RelPrev.d.a--;
915 uint64_t PrevType = MachO->getRelocationType(RelPrev);
916 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
917 return true;
918 }
919 }
920
921 return false;
922}
923
Michael J. Spencer51862b32011-10-13 22:17:18 +0000924static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Jim Grosbachaf9aec02012-08-07 17:53:14 +0000925 const Target *TheTarget = getTarget(Obj);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000926
Jack Carter551efd72012-08-28 19:24:49 +0000927 // Package up features to be passed to target/subtarget
928 std::string FeaturesStr;
929 if (MAttrs.size()) {
930 SubtargetFeatures Features;
931 for (unsigned i = 0; i != MAttrs.size(); ++i)
932 Features.AddFeature(MAttrs[i]);
933 FeaturesStr = Features.getString();
934 }
935
Ahmed Charles56440fd2014-03-06 05:51:42 +0000936 std::unique_ptr<const MCRegisterInfo> MRI(
937 TheTarget->createMCRegInfo(TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +0000938 if (!MRI)
939 report_fatal_error("error: no register info for target " + TripleName);
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000940
941 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000942 std::unique_ptr<const MCAsmInfo> AsmInfo(
943 TheTarget->createMCAsmInfo(*MRI, TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +0000944 if (!AsmInfo)
945 report_fatal_error("error: no assembly info for target " + TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +0000946 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +0000947 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Davide Italiano711e4952015-12-17 01:59:50 +0000948 if (!STI)
949 report_fatal_error("error: no subtarget info for target " + TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +0000950 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
Davide Italiano711e4952015-12-17 01:59:50 +0000951 if (!MII)
952 report_fatal_error("error: no instruction info for target " + TripleName);
Lang Hamesa1bc0f52014-04-15 04:40:56 +0000953 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
954 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
955
956 std::unique_ptr<MCDisassembler> DisAsm(
957 TheTarget->createMCDisassembler(*STI, Ctx));
Davide Italiano711e4952015-12-17 01:59:50 +0000958 if (!DisAsm)
959 report_fatal_error("error: no disassembler for target " + TripleName);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000960
Ahmed Charles56440fd2014-03-06 05:51:42 +0000961 std::unique_ptr<const MCInstrAnalysis> MIA(
962 TheTarget->createMCInstrAnalysis(MII.get()));
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000963
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000964 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Daniel Sanders50f17232015-09-15 16:17:27 +0000965 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
966 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
Davide Italiano711e4952015-12-17 01:59:50 +0000967 if (!IP)
968 report_fatal_error("error: no instruction printer for target " +
969 TripleName);
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000970 IP->setPrintImmHex(PrintImmHex);
Colin LeMahieu35436a22015-05-29 14:48:25 +0000971 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000972
Greg Fitzgerald18432272014-03-20 22:55:15 +0000973 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
974 "\t\t\t%08" PRIx64 ": ";
975
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000976 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
977 // in RelocSecs contain the relocations for section S.
Rafael Espindola4453e42942014-06-13 03:07:50 +0000978 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000979 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
Colin LeMahieu77804be2015-07-29 15:45:39 +0000980 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +0000981 section_iterator Sec2 = Section.getRelocatedSection();
Rafael Espindolab5155a52014-02-10 20:24:04 +0000982 if (Sec2 != Obj->section_end())
Alexey Samsonov48803e52014-03-13 14:37:36 +0000983 SectionRelocMap[*Sec2].push_back(Section);
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000984 }
985
David Majnemer81afca62015-07-07 22:06:59 +0000986 // Create a mapping from virtual address to symbol name. This is used to
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000987 // pretty print the symbols while disassembling.
988 typedef std::vector<std::pair<uint64_t, StringRef>> SectionSymbolsTy;
989 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
990 for (const SymbolRef &Symbol : Obj->symbols()) {
991 ErrorOr<uint64_t> AddressOrErr = Symbol.getAddress();
992 error(AddressOrErr.getError());
993 uint64_t Address = *AddressOrErr;
David Majnemer2603a8fa2015-07-09 18:11:40 +0000994
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000995 Expected<StringRef> Name = Symbol.getName();
996 error(errorToErrorCode(Name.takeError()));
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000997 if (Name->empty())
998 continue;
David Majnemer81afca62015-07-07 22:06:59 +0000999
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001000 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1001 error(errorToErrorCode(SectionOrErr.takeError()));
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001002 section_iterator SecI = *SectionOrErr;
1003 if (SecI == Obj->section_end())
1004 continue;
David Majnemer81afca62015-07-07 22:06:59 +00001005
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001006 AllSymbols[*SecI].emplace_back(Address, *Name);
David Majnemer81afca62015-07-07 22:06:59 +00001007 }
1008
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001009 // Create a mapping from virtual address to section.
1010 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1011 for (SectionRef Sec : Obj->sections())
1012 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1013 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
1014
1015 // Linked executables (.exe and .dll files) typically don't include a real
1016 // symbol table but they might contain an export table.
1017 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
1018 for (const auto &ExportEntry : COFFObj->export_directories()) {
1019 StringRef Name;
1020 error(ExportEntry.getSymbolName(Name));
1021 if (Name.empty())
1022 continue;
1023 uint32_t RVA;
1024 error(ExportEntry.getExportRVA(RVA));
1025
1026 uint64_t VA = COFFObj->getImageBase() + RVA;
1027 auto Sec = std::upper_bound(
1028 SectionAddresses.begin(), SectionAddresses.end(), VA,
1029 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
1030 return LHS < RHS.first;
1031 });
1032 if (Sec != SectionAddresses.begin())
1033 --Sec;
1034 else
1035 Sec = SectionAddresses.end();
1036
1037 if (Sec != SectionAddresses.end())
1038 AllSymbols[Sec->second].emplace_back(VA, Name);
1039 }
1040 }
1041
1042 // Sort all the symbols, this allows us to use a simple binary search to find
1043 // a symbol near an address.
1044 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1045 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
1046
Colin LeMahieu77804be2015-07-29 15:45:39 +00001047 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Colin LeMahieuf34933e2015-07-23 20:58:49 +00001048 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
Mark Seaborneb03ac52014-01-25 00:32:01 +00001049 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +00001050
Rafael Espindola80291272014-10-08 15:28:58 +00001051 uint64_t SectionAddr = Section.getAddress();
1052 uint64_t SectSize = Section.getSize();
David Majnemer185b5b12014-11-11 09:58:25 +00001053 if (!SectSize)
1054 continue;
Simon Atanasyan2b614e12014-02-24 22:12:11 +00001055
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001056 // Get the list of all the symbols in this section.
1057 SectionSymbolsTy &Symbols = AllSymbols[Section];
Davide Italianof0706882015-10-01 21:57:09 +00001058 std::vector<uint64_t> DataMappingSymsAddr;
1059 std::vector<uint64_t> TextMappingSymsAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001060 if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
1061 for (const auto &Symb : Symbols) {
1062 uint64_t Address = Symb.first;
1063 StringRef Name = Symb.second;
1064 if (Name.startswith("$d"))
David Majnemer153722d2015-11-18 04:35:32 +00001065 DataMappingSymsAddr.push_back(Address - SectionAddr);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001066 if (Name.startswith("$x"))
David Majnemer153722d2015-11-18 04:35:32 +00001067 TextMappingSymsAddr.push_back(Address - SectionAddr);
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001068 }
1069 }
1070
Davide Italianof0706882015-10-01 21:57:09 +00001071 std::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end());
1072 std::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end());
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001073
Michael J. Spencer51862b32011-10-13 22:17:18 +00001074 // Make a list of all the relocations for this section.
1075 std::vector<RelocationRef> Rels;
1076 if (InlineRelocs) {
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001077 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
1078 for (const RelocationRef &Reloc : RelocSec.relocations()) {
1079 Rels.push_back(Reloc);
1080 }
Michael J. Spencer51862b32011-10-13 22:17:18 +00001081 }
1082 }
1083
1084 // Sort relocations by address.
1085 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
1086
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001087 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +00001088 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001089 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +00001090 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001091 }
Michael J. Spencer1d6167f2011-06-25 17:55:23 +00001092 StringRef name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001093 error(Section.getName(name));
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001094 outs() << "Disassembly of section ";
1095 if (!SegmentName.empty())
1096 outs() << SegmentName << ",";
1097 outs() << name << ':';
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001098
Rafael Espindola7884c952015-06-04 15:01:05 +00001099 // If the section has no symbol at the start, just insert a dummy one.
1100 if (Symbols.empty() || Symbols[0].first != 0)
David Majnemer153722d2015-11-18 04:35:32 +00001101 Symbols.insert(Symbols.begin(), std::make_pair(SectionAddr, name));
Alp Tokere69170a2014-06-26 22:52:05 +00001102
1103 SmallString<40> Comments;
1104 raw_svector_ostream CommentStream(Comments);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001105
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001106 StringRef BytesStr;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001107 error(Section.getContents(BytesStr));
Aaron Ballman106fd7b2014-11-12 14:01:17 +00001108 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1109 BytesStr.size());
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001110
Michael J. Spencer2670c252011-01-20 06:39:06 +00001111 uint64_t Size;
1112 uint64_t Index;
1113
Michael J. Spencer51862b32011-10-13 22:17:18 +00001114 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
1115 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001116 // Disassemble symbol by symbol.
1117 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
Rafael Espindolae45c7402014-08-17 16:31:39 +00001118
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001119 uint64_t Start = Symbols[si].first - SectionAddr;
1120 // The end is either the section end or the beginning of the next
1121 // symbol.
1122 uint64_t End =
1123 (si == se - 1) ? SectSize : Symbols[si + 1].first - SectionAddr;
1124 // Don't try to disassemble beyond the end of section contents.
1125 if (End > SectSize)
1126 End = SectSize;
Rafael Espindolae45c7402014-08-17 16:31:39 +00001127 // If this symbol has the same address as the next symbol, then skip it.
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001128 if (Start >= End)
Michael J. Spenceree84f642011-10-13 20:37:08 +00001129 continue;
1130
Valery Pykhtinde048052016-04-07 07:24:01 +00001131 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1132 // make size 4 bytes folded
1133 End = Start + ((End - Start) & ~0x3ull);
1134 Start += 256; // add sizeof(amd_kernel_code_t)
1135 // cut trailing zeroes - up to 256 bytes (align)
1136 const uint64_t EndAlign = 256;
1137 const auto Limit = End - (std::min)(EndAlign, End - Start);
1138 while (End > Limit &&
1139 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1140 End -= 4;
1141 }
1142
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001143 outs() << '\n' << Symbols[si].second << ":\n";
Michael J. Spencer2670c252011-01-20 06:39:06 +00001144
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001145#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +00001146 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001147#else
Mark Seaborneb03ac52014-01-25 00:32:01 +00001148 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001149#endif
1150
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001151 for (Index = Start; Index < End; Index += Size) {
1152 MCInst Inst;
Owen Andersona0c3b972011-09-15 23:38:46 +00001153
Davide Italianof0706882015-10-01 21:57:09 +00001154 // AArch64 ELF binaries can interleave data and text in the
1155 // same section. We rely on the markers introduced to
1156 // understand what we need to dump.
1157 if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
1158 uint64_t Stride = 0;
1159
1160 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1161 DataMappingSymsAddr.end(), Index);
1162 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1163 // Switch to data.
1164 while (Index < End) {
1165 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1166 outs() << "\t";
1167 if (Index + 4 <= End) {
1168 Stride = 4;
1169 dumpBytes(Bytes.slice(Index, 4), outs());
1170 outs() << "\t.word";
1171 } else if (Index + 2 <= End) {
1172 Stride = 2;
1173 dumpBytes(Bytes.slice(Index, 2), outs());
1174 outs() << "\t.short";
1175 } else {
1176 Stride = 1;
1177 dumpBytes(Bytes.slice(Index, 1), outs());
1178 outs() << "\t.byte";
1179 }
1180 Index += Stride;
1181 outs() << "\n";
1182 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1183 TextMappingSymsAddr.end(), Index);
1184 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1185 break;
1186 }
1187 }
1188 }
1189
1190 if (Index >= End)
1191 break;
1192
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001193 bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1194 SectionAddr + Index, DebugOut,
1195 CommentStream);
1196 if (Size == 0)
1197 Size = 1;
1198 PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
1199 Bytes.slice(Index, Size),
1200 SectionAddr + Index, outs(), "", *STI);
1201 outs() << CommentStream.str();
1202 Comments.clear();
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001203
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001204 // Try to resolve the target of a call, tail call, etc. to a specific
1205 // symbol.
1206 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1207 MIA->isConditionalBranch(Inst))) {
1208 uint64_t Target;
1209 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1210 // In a relocatable object, the target's section must reside in
1211 // the same section as the call instruction or it is accessed
1212 // through a relocation.
1213 //
1214 // In a non-relocatable object, the target may be in any section.
1215 //
1216 // N.B. We don't walk the relocations in the relocatable case yet.
1217 auto *TargetSectionSymbols = &Symbols;
1218 if (!Obj->isRelocatableObject()) {
1219 auto SectionAddress = std::upper_bound(
1220 SectionAddresses.begin(), SectionAddresses.end(), Target,
1221 [](uint64_t LHS,
1222 const std::pair<uint64_t, SectionRef> &RHS) {
1223 return LHS < RHS.first;
1224 });
1225 if (SectionAddress != SectionAddresses.begin()) {
1226 --SectionAddress;
1227 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1228 } else {
1229 TargetSectionSymbols = nullptr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001230 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001231 }
David Majnemer2603a8fa2015-07-09 18:11:40 +00001232
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001233 // Find the first symbol in the section whose offset is less than
1234 // or equal to the target.
1235 if (TargetSectionSymbols) {
1236 auto TargetSym = std::upper_bound(
1237 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1238 Target, [](uint64_t LHS,
1239 const std::pair<uint64_t, StringRef> &RHS) {
1240 return LHS < RHS.first;
1241 });
1242 if (TargetSym != TargetSectionSymbols->begin()) {
1243 --TargetSym;
1244 uint64_t TargetAddress = std::get<0>(*TargetSym);
1245 StringRef TargetName = std::get<1>(*TargetSym);
1246 outs() << " <" << TargetName;
1247 uint64_t Disp = Target - TargetAddress;
1248 if (Disp)
1249 outs() << "+0x" << utohexstr(Disp);
1250 outs() << '>';
David Majnemer81afca62015-07-07 22:06:59 +00001251 }
1252 }
1253 }
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001254 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001255 outs() << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001256
1257 // Print relocation for instruction.
1258 while (rel_cur != rel_end) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001259 bool hidden = getHidden(*rel_cur);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001260 uint64_t addr = rel_cur->getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +00001261 SmallString<16> name;
1262 SmallString<32> val;
Owen Andersonfa3e5202011-10-25 20:35:53 +00001263
1264 // If this relocation is hidden, skip it.
Owen Andersonfa3e5202011-10-25 20:35:53 +00001265 if (hidden) goto skip_print_rel;
1266
Michael J. Spencer51862b32011-10-13 22:17:18 +00001267 // Stop when rel_cur's address is past the current instruction.
Owen Andersonf20e3e52011-10-25 20:15:39 +00001268 if (addr >= Index + Size) break;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001269 rel_cur->getTypeName(name);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001270 error(getRelocationValueString(*rel_cur, val));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001271 outs() << format(Fmt.data(), SectionAddr + addr) << name
Benjamin Kramer82803112012-03-10 02:04:38 +00001272 << "\t" << val << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001273
1274 skip_print_rel:
1275 ++rel_cur;
1276 }
Benjamin Kramer87ee76c2011-07-20 19:37:35 +00001277 }
Michael J. Spencer2670c252011-01-20 06:39:06 +00001278 }
1279 }
1280}
1281
Kevin Enderby98da6132015-01-20 21:47:46 +00001282void llvm::PrintRelocations(const ObjectFile *Obj) {
Greg Fitzgerald18432272014-03-20 22:55:15 +00001283 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1284 "%08" PRIx64;
Rafael Espindola9219fe72016-03-21 20:59:15 +00001285 // Regular objdump doesn't print relocations in non-relocatable object
1286 // files.
1287 if (!Obj->isRelocatableObject())
1288 return;
Rafael Espindolac66d7612014-08-17 19:09:37 +00001289
Colin LeMahieu77804be2015-07-29 15:45:39 +00001290 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001291 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001292 continue;
1293 StringRef secname;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001294 error(Section.getName(secname));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001295 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001296 for (const RelocationRef &Reloc : Section.relocations()) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001297 bool hidden = getHidden(Reloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001298 uint64_t address = Reloc.getOffset();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001299 SmallString<32> relocname;
1300 SmallString<32> valuestr;
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001301 if (hidden)
1302 continue;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001303 Reloc.getTypeName(relocname);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001304 error(getRelocationValueString(Reloc, valuestr));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001305 outs() << format(Fmt.data(), address) << " " << relocname << " "
1306 << valuestr << "\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001307 }
1308 outs() << "\n";
1309 }
1310}
1311
Kevin Enderby98da6132015-01-20 21:47:46 +00001312void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001313 outs() << "Sections:\n"
1314 "Idx Name Size Address Type\n";
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001315 unsigned i = 0;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001316 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001317 StringRef Name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001318 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001319 uint64_t Address = Section.getAddress();
1320 uint64_t Size = Section.getSize();
1321 bool Text = Section.isText();
1322 bool Data = Section.isData();
1323 bool BSS = Section.isBSS();
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001324 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +00001325 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
Alexey Samsonov48803e52014-03-13 14:37:36 +00001326 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1327 Name.str().c_str(), Size, Address, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001328 ++i;
1329 }
1330}
1331
Kevin Enderby98da6132015-01-20 21:47:46 +00001332void llvm::PrintSectionContents(const ObjectFile *Obj) {
Rafael Espindola4453e42942014-06-13 03:07:50 +00001333 std::error_code EC;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001334 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001335 StringRef Name;
1336 StringRef Contents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001337 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001338 uint64_t BaseAddr = Section.getAddress();
David Majnemer185b5b12014-11-11 09:58:25 +00001339 uint64_t Size = Section.getSize();
1340 if (!Size)
1341 continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001342
1343 outs() << "Contents of section " << Name << ":\n";
David Majnemer185b5b12014-11-11 09:58:25 +00001344 if (Section.isBSS()) {
Alexey Samsonov209095c2013-04-16 10:53:11 +00001345 outs() << format("<skipping contents of bss section at [%04" PRIx64
David Majnemer8f6b04c2014-07-14 16:20:14 +00001346 ", %04" PRIx64 ")>\n",
1347 BaseAddr, BaseAddr + Size);
Alexey Samsonov209095c2013-04-16 10:53:11 +00001348 continue;
1349 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001350
Davide Italianoccd53fe2015-08-05 07:18:31 +00001351 error(Section.getContents(Contents));
David Majnemer8f6b04c2014-07-14 16:20:14 +00001352
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001353 // Dump out the content as hex and printable ascii characters.
1354 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer82803112012-03-10 02:04:38 +00001355 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001356 // Dump line of hex.
1357 for (std::size_t i = 0; i < 16; ++i) {
1358 if (i != 0 && i % 4 == 0)
1359 outs() << ' ';
1360 if (addr + i < end)
1361 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1362 << hexdigit(Contents[addr + i] & 0xF, true);
1363 else
1364 outs() << " ";
1365 }
1366 // Print ascii.
1367 outs() << " ";
1368 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
Guy Benyei83c74e92013-02-12 21:21:59 +00001369 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001370 outs() << Contents[addr + i];
1371 else
1372 outs() << ".";
1373 }
1374 outs() << "\n";
1375 }
1376 }
1377}
1378
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001379void llvm::PrintSymbolTable(const ObjectFile *o, StringRef ArchiveName) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001380 outs() << "SYMBOL TABLE:\n";
1381
Rui Ueyama4e39f712014-03-18 18:58:51 +00001382 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
Davide Italianoe85abf72015-12-20 09:54:34 +00001383 printCOFFSymbolTable(coff);
Rui Ueyama4e39f712014-03-18 18:58:51 +00001384 return;
1385 }
1386 for (const SymbolRef &Symbol : o->symbols()) {
Rafael Espindolaed067c42015-07-03 18:19:00 +00001387 ErrorOr<uint64_t> AddressOrError = Symbol.getAddress();
Davide Italianoccd53fe2015-08-05 07:18:31 +00001388 error(AddressOrError.getError());
Rafael Espindolaed067c42015-07-03 18:19:00 +00001389 uint64_t Address = *AddressOrError;
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001390 Expected<SymbolRef::Type> TypeOrError = Symbol.getType();
1391 if (!TypeOrError)
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001392 report_error(ArchiveName, o->getFileName(), TypeOrError.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00001393 SymbolRef::Type Type = *TypeOrError;
Rui Ueyama4e39f712014-03-18 18:58:51 +00001394 uint32_t Flags = Symbol.getFlags();
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001395 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1396 error(errorToErrorCode(SectionOrErr.takeError()));
Rafael Espindola8bab8892015-08-07 23:27:14 +00001397 section_iterator Section = *SectionOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001398 StringRef Name;
1399 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1400 Section->getName(Name);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001401 } else {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001402 Expected<StringRef> NameOrErr = Symbol.getName();
1403 if (!NameOrErr)
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001404 report_error(ArchiveName, o->getFileName(), NameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001405 Name = *NameOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001406 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001407
Rui Ueyama4e39f712014-03-18 18:58:51 +00001408 bool Global = Flags & SymbolRef::SF_Global;
1409 bool Weak = Flags & SymbolRef::SF_Weak;
1410 bool Absolute = Flags & SymbolRef::SF_Absolute;
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001411 bool Common = Flags & SymbolRef::SF_Common;
Davide Italianocd2514d2015-04-30 23:08:53 +00001412 bool Hidden = Flags & SymbolRef::SF_Hidden;
David Meyer1df4b842012-02-28 23:47:53 +00001413
Rui Ueyama4e39f712014-03-18 18:58:51 +00001414 char GlobLoc = ' ';
1415 if (Type != SymbolRef::ST_Unknown)
1416 GlobLoc = Global ? 'g' : 'l';
1417 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1418 ? 'd' : ' ';
1419 char FileFunc = ' ';
1420 if (Type == SymbolRef::ST_File)
1421 FileFunc = 'f';
1422 else if (Type == SymbolRef::ST_Function)
1423 FileFunc = 'F';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001424
Rui Ueyama4e39f712014-03-18 18:58:51 +00001425 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1426 "%08" PRIx64;
Michael J. Spencerd857c1c2013-01-10 22:40:50 +00001427
Rui Ueyama4e39f712014-03-18 18:58:51 +00001428 outs() << format(Fmt, Address) << " "
1429 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1430 << (Weak ? 'w' : ' ') // Weak?
1431 << ' ' // Constructor. Not supported yet.
1432 << ' ' // Warning. Not supported yet.
1433 << ' ' // Indirect reference to another symbol.
1434 << Debug // Debugging (d) or dynamic (D) symbol.
1435 << FileFunc // Name of function (F), file (f) or object (O).
1436 << ' ';
1437 if (Absolute) {
1438 outs() << "*ABS*";
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001439 } else if (Common) {
1440 outs() << "*COM*";
Rui Ueyama4e39f712014-03-18 18:58:51 +00001441 } else if (Section == o->section_end()) {
1442 outs() << "*UND*";
1443 } else {
1444 if (const MachOObjectFile *MachO =
1445 dyn_cast<const MachOObjectFile>(o)) {
1446 DataRefImpl DR = Section->getRawDataRefImpl();
1447 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1448 outs() << SegmentName << ",";
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001449 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00001450 StringRef SectionName;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001451 error(Section->getName(SectionName));
Rui Ueyama4e39f712014-03-18 18:58:51 +00001452 outs() << SectionName;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001453 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001454
1455 outs() << '\t';
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001456 if (Common || isa<ELFObjectFileBase>(o)) {
Rafael Espindoladbb6bd32015-06-25 22:10:04 +00001457 uint64_t Val =
1458 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001459 outs() << format("\t %08" PRIx64 " ", Val);
1460 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001461
Davide Italianocd2514d2015-04-30 23:08:53 +00001462 if (Hidden) {
1463 outs() << ".hidden ";
1464 }
1465 outs() << Name
Rui Ueyama4e39f712014-03-18 18:58:51 +00001466 << '\n';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001467 }
1468}
1469
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001470static void PrintUnwindInfo(const ObjectFile *o) {
1471 outs() << "Unwind info:\n\n";
1472
1473 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1474 printCOFFUnwindInfo(coff);
Tim Northover4bd286a2014-08-01 13:07:19 +00001475 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1476 printMachOUnwindInfo(MachO);
1477 else {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001478 // TODO: Extract DWARF dump tool to objdump.
1479 errs() << "This operation is only currently supported "
Tim Northover4bd286a2014-08-01 13:07:19 +00001480 "for COFF and MachO object files.\n";
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001481 return;
1482 }
1483}
1484
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001485void llvm::printExportsTrie(const ObjectFile *o) {
Nick Kledzikd04bc352014-08-30 00:20:14 +00001486 outs() << "Exports trie:\n";
1487 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1488 printMachOExportsTrie(MachO);
1489 else {
1490 errs() << "This operation is only currently supported "
1491 "for Mach-O executable files.\n";
1492 return;
1493 }
1494}
1495
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001496void llvm::printRebaseTable(const ObjectFile *o) {
Nick Kledzikac431442014-09-12 21:34:15 +00001497 outs() << "Rebase table:\n";
1498 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1499 printMachORebaseTable(MachO);
1500 else {
1501 errs() << "This operation is only currently supported "
1502 "for Mach-O executable files.\n";
1503 return;
1504 }
1505}
1506
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001507void llvm::printBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001508 outs() << "Bind table:\n";
1509 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1510 printMachOBindTable(MachO);
1511 else {
1512 errs() << "This operation is only currently supported "
1513 "for Mach-O executable files.\n";
1514 return;
1515 }
1516}
1517
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001518void llvm::printLazyBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001519 outs() << "Lazy bind table:\n";
1520 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1521 printMachOLazyBindTable(MachO);
1522 else {
1523 errs() << "This operation is only currently supported "
1524 "for Mach-O executable files.\n";
1525 return;
1526 }
1527}
1528
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001529void llvm::printWeakBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001530 outs() << "Weak bind table:\n";
1531 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1532 printMachOWeakBindTable(MachO);
1533 else {
1534 errs() << "This operation is only currently supported "
1535 "for Mach-O executable files.\n";
1536 return;
1537 }
1538}
Nick Kledzikac431442014-09-12 21:34:15 +00001539
Adrian Prantl437105a2015-07-08 02:04:15 +00001540/// Dump the raw contents of the __clangast section so the output can be piped
1541/// into llvm-bcanalyzer.
1542void llvm::printRawClangAST(const ObjectFile *Obj) {
1543 if (outs().is_displayed()) {
1544 errs() << "The -raw-clang-ast option will dump the raw binary contents of "
1545 "the clang ast section.\n"
1546 "Please redirect the output to a file or another program such as "
1547 "llvm-bcanalyzer.\n";
1548 return;
1549 }
1550
1551 StringRef ClangASTSectionName("__clangast");
1552 if (isa<COFFObjectFile>(Obj)) {
1553 ClangASTSectionName = "clangast";
1554 }
1555
1556 Optional<object::SectionRef> ClangASTSection;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001557 for (auto Sec : ToolSectionFilter(*Obj)) {
Adrian Prantl437105a2015-07-08 02:04:15 +00001558 StringRef Name;
1559 Sec.getName(Name);
1560 if (Name == ClangASTSectionName) {
1561 ClangASTSection = Sec;
1562 break;
1563 }
1564 }
1565 if (!ClangASTSection)
1566 return;
1567
1568 StringRef ClangASTContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001569 error(ClangASTSection.getValue().getContents(ClangASTContents));
Adrian Prantl437105a2015-07-08 02:04:15 +00001570 outs().write(ClangASTContents.data(), ClangASTContents.size());
1571}
1572
Sanjoy Das6f567a42015-06-22 18:03:02 +00001573static void printFaultMaps(const ObjectFile *Obj) {
1574 const char *FaultMapSectionName = nullptr;
1575
1576 if (isa<ELFObjectFileBase>(Obj)) {
1577 FaultMapSectionName = ".llvm_faultmaps";
1578 } else if (isa<MachOObjectFile>(Obj)) {
1579 FaultMapSectionName = "__llvm_faultmaps";
1580 } else {
1581 errs() << "This operation is only currently supported "
1582 "for ELF and Mach-O executable files.\n";
1583 return;
1584 }
1585
1586 Optional<object::SectionRef> FaultMapSection;
1587
Colin LeMahieu77804be2015-07-29 15:45:39 +00001588 for (auto Sec : ToolSectionFilter(*Obj)) {
Sanjoy Das6f567a42015-06-22 18:03:02 +00001589 StringRef Name;
1590 Sec.getName(Name);
1591 if (Name == FaultMapSectionName) {
1592 FaultMapSection = Sec;
1593 break;
1594 }
1595 }
1596
1597 outs() << "FaultMap table:\n";
1598
1599 if (!FaultMapSection.hasValue()) {
1600 outs() << "<not found>\n";
1601 return;
1602 }
1603
1604 StringRef FaultMapContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001605 error(FaultMapSection.getValue().getContents(FaultMapContents));
Sanjoy Das6f567a42015-06-22 18:03:02 +00001606
1607 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1608 FaultMapContents.bytes_end());
1609
1610 outs() << FMP;
1611}
1612
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001613static void printPrivateFileHeaders(const ObjectFile *o) {
1614 if (o->isELF())
1615 printELFFileHeader(o);
1616 else if (o->isCOFF())
1617 printCOFFFileHeader(o);
1618 else if (o->isMachO()) {
1619 printMachOFileHeader(o);
1620 printMachOLoadCommands(o);
1621 } else
1622 report_fatal_error("Invalid/Unsupported object file format");
1623}
1624
1625static void printFirstPrivateFileHeader(const ObjectFile *o) {
Davide Italiano540e9212015-12-19 22:09:40 +00001626 if (o->isELF())
Rui Ueyamac2bed422013-09-27 21:04:00 +00001627 printELFFileHeader(o);
Davide Italiano540e9212015-12-19 22:09:40 +00001628 else if (o->isCOFF())
Rui Ueyamac2bed422013-09-27 21:04:00 +00001629 printCOFFFileHeader(o);
Davide Italiano540e9212015-12-19 22:09:40 +00001630 else if (o->isMachO())
Kevin Enderbyb76d3862014-08-22 20:35:18 +00001631 printMachOFileHeader(o);
Davide Italiano540e9212015-12-19 22:09:40 +00001632 else
1633 report_fatal_error("Invalid/Unsupported object file format");
Rui Ueyamac2bed422013-09-27 21:04:00 +00001634}
1635
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001636static void DumpObject(const ObjectFile *o, const Archive *a = nullptr) {
1637 StringRef ArchiveName = a != nullptr ? a->getFileName() : "";
Adrian Prantl437105a2015-07-08 02:04:15 +00001638 // Avoid other output when using a raw option.
1639 if (!RawClangAST) {
1640 outs() << '\n';
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001641 if (a)
1642 outs() << a->getFileName() << "(" << o->getFileName() << ")";
1643 else
1644 outs() << o->getFileName();
1645 outs() << ":\tfile format " << o->getFileFormatName() << "\n\n";
Adrian Prantl437105a2015-07-08 02:04:15 +00001646 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001647
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001648 if (Disassemble)
Michael J. Spencer51862b32011-10-13 22:17:18 +00001649 DisassembleObject(o, Relocations);
1650 if (Relocations && !Disassemble)
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001651 PrintRelocations(o);
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001652 if (SectionHeaders)
1653 PrintSectionHeaders(o);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001654 if (SectionContents)
1655 PrintSectionContents(o);
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001656 if (SymbolTable)
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001657 PrintSymbolTable(o, ArchiveName);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001658 if (UnwindInfo)
1659 PrintUnwindInfo(o);
Rui Ueyamac2bed422013-09-27 21:04:00 +00001660 if (PrivateHeaders)
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001661 printPrivateFileHeaders(o);
1662 if (FirstPrivateHeader)
1663 printFirstPrivateFileHeader(o);
Nick Kledzikd04bc352014-08-30 00:20:14 +00001664 if (ExportsTrie)
1665 printExportsTrie(o);
Nick Kledzikac431442014-09-12 21:34:15 +00001666 if (Rebase)
1667 printRebaseTable(o);
Nick Kledzik56ebef42014-09-16 01:41:51 +00001668 if (Bind)
1669 printBindTable(o);
1670 if (LazyBind)
1671 printLazyBindTable(o);
1672 if (WeakBind)
1673 printWeakBindTable(o);
Adrian Prantl437105a2015-07-08 02:04:15 +00001674 if (RawClangAST)
1675 printRawClangAST(o);
Sanjoy Das6f567a42015-06-22 18:03:02 +00001676 if (PrintFaultMaps)
1677 printFaultMaps(o);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001678 if (DwarfDumpType != DIDT_Null) {
1679 std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*o));
1680 // Dump the complete DWARF structure.
1681 DICtx->dump(outs(), DwarfDumpType, true /* DumpEH */);
1682 }
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001683}
1684
1685/// @brief Dump each object file in \a a;
1686static void DumpArchive(const Archive *a) {
Kevin Enderby7a969422015-11-05 19:24:56 +00001687 for (auto &ErrorOrChild : a->children()) {
1688 if (std::error_code EC = ErrorOrChild.getError())
1689 report_error(a->getFileName(), EC);
1690 const Archive::Child &C = *ErrorOrChild;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001691 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1692 if (!ChildOrErr) {
1693 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1694 report_error(a->getFileName(), C, std::move(E));
1695 continue;
1696 }
Rafael Espindolaae460022014-06-16 16:08:36 +00001697 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001698 DumpObject(o, a);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001699 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001700 report_error(a->getFileName(), object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001701 }
1702}
1703
1704/// @brief Open file and figure out how to dump it.
1705static void DumpInput(StringRef file) {
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001706
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001707 // If we are using the Mach-O specific object file parser, then let it parse
1708 // the file and process the command line options. So the -arch flags can
1709 // be used to select specific slices, etc.
1710 if (MachOOpt) {
1711 ParseInputMachO(file);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001712 return;
1713 }
1714
1715 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00001716 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
1717 if (!BinaryOrErr)
Kevin Enderbyb34e3a12016-05-05 17:43:35 +00001718 report_error(file, BinaryOrErr.takeError());
Rafael Espindola48af1c22014-08-19 18:44:46 +00001719 Binary &Binary = *BinaryOrErr.get().getBinary();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001720
Rafael Espindola3f6481d2014-08-01 14:31:55 +00001721 if (Archive *a = dyn_cast<Archive>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001722 DumpArchive(a);
Rafael Espindola3f6481d2014-08-01 14:31:55 +00001723 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001724 DumpObject(o);
Jim Grosbachaf9aec02012-08-07 17:53:14 +00001725 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001726 report_error(file, object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001727}
1728
Michael J. Spencer2670c252011-01-20 06:39:06 +00001729int main(int argc, char **argv) {
1730 // Print a stack trace if we signal out.
1731 sys::PrintStackTraceOnErrorSignal();
1732 PrettyStackTraceProgram X(argc, argv);
1733 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1734
1735 // Initialize targets and assembly printers/parsers.
1736 llvm::InitializeAllTargetInfos();
Evan Cheng8c886a42011-07-22 21:58:54 +00001737 llvm::InitializeAllTargetMCs();
Michael J. Spencer2670c252011-01-20 06:39:06 +00001738 llvm::InitializeAllDisassemblers();
1739
Pete Cooper28fb4fc2012-05-03 23:20:10 +00001740 // Register the target printer for --version.
1741 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
1742
Michael J. Spencer2670c252011-01-20 06:39:06 +00001743 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
1744 TripleName = Triple::normalize(TripleName);
1745
1746 ToolName = argv[0];
1747
1748 // Defaults to a.out if no filenames specified.
1749 if (InputFilenames.size() == 0)
1750 InputFilenames.push_back("a.out");
1751
Colin LeMahieuf34933e2015-07-23 20:58:49 +00001752 if (DisassembleAll)
1753 Disassemble = true;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001754 if (!Disassemble
1755 && !Relocations
1756 && !SectionHeaders
1757 && !SectionContents
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001758 && !SymbolTable
Michael J. Spencer209565db2013-01-06 03:56:49 +00001759 && !UnwindInfo
Nick Kledzikd04bc352014-08-30 00:20:14 +00001760 && !PrivateHeaders
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001761 && !FirstPrivateHeader
Nick Kledzikac431442014-09-12 21:34:15 +00001762 && !ExportsTrie
Nick Kledzik56ebef42014-09-16 01:41:51 +00001763 && !Rebase
1764 && !Bind
1765 && !LazyBind
Kevin Enderby131d1772015-01-09 19:22:37 +00001766 && !WeakBind
Adrian Prantl437105a2015-07-08 02:04:15 +00001767 && !RawClangAST
Kevin Enderby13023a12015-01-15 23:19:11 +00001768 && !(UniversalHeaders && MachOOpt)
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001769 && !(ArchiveHeaders && MachOOpt)
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001770 && !(IndirectSymbols && MachOOpt)
Kevin Enderby9a509442015-01-27 21:28:24 +00001771 && !(DataInCode && MachOOpt)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001772 && !(LinkOptHints && MachOOpt)
Kevin Enderbycd66be52015-03-11 22:06:32 +00001773 && !(InfoPlist && MachOOpt)
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001774 && !(DylibsUsed && MachOOpt)
1775 && !(DylibId && MachOOpt)
Kevin Enderby0fc11822015-04-01 20:57:01 +00001776 && !(ObjcMetaData && MachOOpt)
Colin LeMahieufcc32762015-07-29 19:08:10 +00001777 && !(FilterSections.size() != 0 && MachOOpt)
Igor Laevsky03a670c2016-01-26 15:09:42 +00001778 && !PrintFaultMaps
1779 && DwarfDumpType == DIDT_Null) {
Michael J. Spencer2670c252011-01-20 06:39:06 +00001780 cl::PrintHelpMessage();
1781 return 2;
1782 }
1783
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001784 std::for_each(InputFilenames.begin(), InputFilenames.end(),
1785 DumpInput);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001786
Davide Italianoccd53fe2015-08-05 07:18:31 +00001787 return EXIT_SUCCESS;
Michael J. Spencer2670c252011-01-20 06:39:06 +00001788}