blob: 7107966b18d669d9b16ede716ba892ee97a49055 [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"
Rafael Aulerb0e4b912018-03-09 19:13:44 +000023#include "llvm/ADT/StringSet.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000024#include "llvm/ADT/Triple.h"
Sanjoy Das3f1bc3b2015-06-23 20:09:03 +000025#include "llvm/CodeGen/FaultMaps.h"
Igor Laevsky03a670c2016-01-26 15:09:42 +000026#include "llvm/DebugInfo/DWARF/DWARFContext.h"
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +000027#include "llvm/DebugInfo/Symbolize/Symbolize.h"
Paul Semel007dedb2018-07-18 16:39:21 +000028#include "llvm/Demangle/Demangle.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000029#include "llvm/MC/MCAsmInfo.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000030#include "llvm/MC/MCContext.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000031#include "llvm/MC/MCDisassembler/MCDisassembler.h"
32#include "llvm/MC/MCDisassembler/MCRelocationInfo.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000033#include "llvm/MC/MCInst.h"
34#include "llvm/MC/MCInstPrinter.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000035#include "llvm/MC/MCInstrAnalysis.h"
Craig Topper54bfde72012-04-02 06:09:36 +000036#include "llvm/MC/MCInstrInfo.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000037#include "llvm/MC/MCObjectFileInfo.h"
Jim Grosbachfd93a592012-03-05 19:33:20 +000038#include "llvm/MC/MCRegisterInfo.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000039#include "llvm/MC/MCSubtargetInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000040#include "llvm/Object/Archive.h"
41#include "llvm/Object/COFF.h"
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +000042#include "llvm/Object/COFFImportFile.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000043#include "llvm/Object/ELFObjectFile.h"
Rafael Espindolaa9f810b2012-12-21 03:47:03 +000044#include "llvm/Object/MachO.h"
Dave Lee3fb120f2018-08-03 00:06:38 +000045#include "llvm/Object/MachOUniversal.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000046#include "llvm/Object/ObjectFile.h"
Sam Clegg4df5d762017-06-27 20:40:53 +000047#include "llvm/Object/Wasm.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000048#include "llvm/Support/Casting.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000049#include "llvm/Support/CommandLine.h"
50#include "llvm/Support/Debug.h"
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +000051#include "llvm/Support/Errc.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000052#include "llvm/Support/FileSystem.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000053#include "llvm/Support/Format.h"
Benjamin Kramerbf115312011-07-25 23:04:36 +000054#include "llvm/Support/GraphWriter.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000055#include "llvm/Support/Host.h"
Rui Ueyama197194b2018-04-13 18:26:06 +000056#include "llvm/Support/InitLLVM.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000057#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000058#include "llvm/Support/SourceMgr.h"
Joel Galenson134cf472018-08-24 15:21:57 +000059#include "llvm/Support/StringSaver.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000060#include "llvm/Support/TargetRegistry.h"
61#include "llvm/Support/TargetSelect.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000062#include "llvm/Support/raw_ostream.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000063#include <algorithm>
Benjamin Kramera5177e62012-03-23 11:49:32 +000064#include <cctype>
Michael J. Spencer2670c252011-01-20 06:39:06 +000065#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000066#include <system_error>
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +000067#include <unordered_map>
Rafael Espindolac398e672017-07-19 22:27:28 +000068#include <utility>
Ahmed Bougacha17926472013-08-21 07:29:02 +000069
Michael J. Spencer2670c252011-01-20 06:39:06 +000070using namespace llvm;
71using namespace object;
72
Fangrui Song8513cd42018-06-27 20:45:11 +000073cl::opt<bool>
74 llvm::AllHeaders("all-headers",
75 cl::desc("Display all available header information"));
76static cl::alias AllHeadersShort("x", cl::desc("Alias for --all-headers"),
77 cl::aliasopt(AllHeaders));
78
Benjamin Kramer43a772e2011-09-19 17:56:04 +000079static cl::list<std::string>
80InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
Michael J. Spencer2670c252011-01-20 06:39:06 +000081
Kevin Enderbye2297dd2015-01-07 21:02:18 +000082cl::opt<bool>
83llvm::Disassemble("disassemble",
Benjamin Kramer43a772e2011-09-19 17:56:04 +000084 cl::desc("Display assembler mnemonics for the machine instructions"));
85static cl::alias
86Disassembled("d", cl::desc("Alias for --disassemble"),
Colin LeMahieu77804be2015-07-29 15:45:39 +000087 cl::aliasopt(Disassemble));
88
89cl::opt<bool>
90llvm::DisassembleAll("disassemble-all",
91 cl::desc("Display assembler mnemonics for the machine instructions"));
92static cl::alias
93DisassembleAlld("D", cl::desc("Alias for --disassemble-all"),
Colin LeMahieuf34933e2015-07-23 20:58:49 +000094 cl::aliasopt(DisassembleAll));
Michael J. Spencer2670c252011-01-20 06:39:06 +000095
Zachary Turner030ad372018-08-20 22:18:21 +000096cl::opt<bool> llvm::Demangle("demangle", cl::desc("Demangle symbols names"),
97 cl::init(false));
Paul Semel007dedb2018-07-18 16:39:21 +000098
99static cl::alias DemangleShort("C", cl::desc("Alias for --demangle"),
Zachary Turner030ad372018-08-20 22:18:21 +0000100 cl::aliasopt(llvm::Demangle));
Paul Semel007dedb2018-07-18 16:39:21 +0000101
Rafael Aulerb0e4b912018-03-09 19:13:44 +0000102static cl::list<std::string>
103DisassembleFunctions("df",
104 cl::CommaSeparated,
105 cl::desc("List of functions to disassemble"));
106static StringSet<> DisasmFuncsSet;
107
Kevin Enderby98da6132015-01-20 21:47:46 +0000108cl::opt<bool>
109llvm::Relocations("r", cl::desc("Display the relocation entries in the file"));
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000110
Kevin Enderby98da6132015-01-20 21:47:46 +0000111cl::opt<bool>
Paul Semelcb0f0432018-06-07 13:30:55 +0000112llvm::DynamicRelocations("dynamic-reloc",
113 cl::desc("Display the dynamic relocation entries in the file"));
114static cl::alias
115DynamicRelocationsd("R", cl::desc("Alias for --dynamic-reloc"),
116 cl::aliasopt(DynamicRelocations));
117
118cl::opt<bool>
Kevin Enderby98da6132015-01-20 21:47:46 +0000119llvm::SectionContents("s", cl::desc("Display the content of each section"));
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000120
Kevin Enderby98da6132015-01-20 21:47:46 +0000121cl::opt<bool>
122llvm::SymbolTable("t", cl::desc("Display the symbol table"));
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000123
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000124cl::opt<bool>
125llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
Nick Kledzikd04bc352014-08-30 00:20:14 +0000126
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000127cl::opt<bool>
128llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
Nick Kledzikac431442014-09-12 21:34:15 +0000129
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000130cl::opt<bool>
131llvm::Bind("bind", cl::desc("Display mach-o binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000132
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000133cl::opt<bool>
134llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000135
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000136cl::opt<bool>
137llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000138
Adrian Prantl437105a2015-07-08 02:04:15 +0000139cl::opt<bool>
140llvm::RawClangAST("raw-clang-ast",
141 cl::desc("Dump the raw binary contents of the clang AST section"));
142
Nick Kledzik56ebef42014-09-16 01:41:51 +0000143static cl::opt<bool>
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000144MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000145static cl::alias
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000146MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
Benjamin Kramer87ee76c2011-07-20 19:37:35 +0000147
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000148cl::opt<std::string>
149llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
150 "see -version for available targets"));
151
152cl::opt<std::string>
Kevin Enderbyc9595622014-08-06 23:24:41 +0000153llvm::MCPU("mcpu",
154 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
155 cl::value_desc("cpu-name"),
156 cl::init(""));
157
158cl::opt<std::string>
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000159llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
Michael J. Spencer2670c252011-01-20 06:39:06 +0000160 "see -version for available targets"));
161
Kevin Enderby98da6132015-01-20 21:47:46 +0000162cl::opt<bool>
163llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
164 "headers for each section."));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000165static cl::alias
166SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
167 cl::aliasopt(SectionHeaders));
168static cl::alias
169SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
170 cl::aliasopt(SectionHeaders));
Colin LeMahieufcc32762015-07-29 19:08:10 +0000171
Colin LeMahieu77804be2015-07-29 15:45:39 +0000172cl::list<std::string>
Colin LeMahieufcc32762015-07-29 19:08:10 +0000173llvm::FilterSections("section", cl::desc("Operate on the specified sections only. "
174 "With -macho dump segment,section"));
175cl::alias
176static FilterSectionsj("j", cl::desc("Alias for --section"),
177 cl::aliasopt(llvm::FilterSections));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000178
Kevin Enderbyc9595622014-08-06 23:24:41 +0000179cl::list<std::string>
180llvm::MAttrs("mattr",
Jack Carter551efd72012-08-28 19:24:49 +0000181 cl::CommaSeparated,
182 cl::desc("Target specific attributes"),
183 cl::value_desc("a1,+a2,-a3,..."));
184
Kevin Enderbybf246f52014-09-24 23:08:22 +0000185cl::opt<bool>
186llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
187 "instructions, do not print "
188 "the instruction bytes."));
Saleem Abdulrasooldea14b22017-02-08 18:11:31 +0000189cl::opt<bool>
190llvm::NoLeadingAddr("no-leading-addr", cl::desc("Print no leading address"));
Eli Bendersky3a6808c2012-11-20 22:57:02 +0000191
Kevin Enderby98da6132015-01-20 21:47:46 +0000192cl::opt<bool>
193llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000194
195static cl::alias
196UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
197 cl::aliasopt(UnwindInfo));
198
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000199cl::opt<bool>
200llvm::PrivateHeaders("private-headers",
201 cl::desc("Display format specific file headers"));
Michael J. Spencer209565db2013-01-06 03:56:49 +0000202
Kevin Enderby0ae163f2016-01-13 00:25:36 +0000203cl::opt<bool>
204llvm::FirstPrivateHeader("private-header",
205 cl::desc("Display only the first format specific file "
206 "header"));
207
Michael J. Spencer209565db2013-01-06 03:56:49 +0000208static cl::alias
209PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
210 cl::aliasopt(PrivateHeaders));
211
Paul Semeld2af4d62018-07-04 15:25:03 +0000212cl::opt<bool> llvm::FileHeaders(
213 "file-headers",
214 cl::desc("Display the contents of the overall file header"));
215
216static cl::alias FileHeadersShort("f", cl::desc("Alias for --file-headers"),
217 cl::aliasopt(FileHeaders));
218
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000219cl::opt<bool>
Paul Semel0dc92f62018-07-05 14:43:29 +0000220 llvm::ArchiveHeaders("archive-headers",
221 cl::desc("Display archive header information"));
222
223cl::alias
224ArchiveHeadersShort("a", cl::desc("Alias for --archive-headers"),
225 cl::aliasopt(ArchiveHeaders));
226
227cl::opt<bool>
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000228 llvm::PrintImmHex("print-imm-hex",
Colin LeMahieuefe37322016-04-08 18:15:37 +0000229 cl::desc("Use hex format for immediate values"));
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000230
Sanjoy Das6f567a42015-06-22 18:03:02 +0000231cl::opt<bool> PrintFaultMaps("fault-map-section",
232 cl::desc("Display contents of faultmap section"));
233
Igor Laevsky03a670c2016-01-26 15:09:42 +0000234cl::opt<DIDumpType> llvm::DwarfDumpType(
235 "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"),
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000236 cl::values(clEnumValN(DIDT_DebugFrame, "frames", ".debug_frame")));
Igor Laevsky03a670c2016-01-26 15:09:42 +0000237
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000238cl::opt<bool> PrintSource(
239 "source",
240 cl::desc(
Alex Denisova07169e2018-02-02 19:20:37 +0000241 "Display source inlined with disassembly. Implies disassemble object"));
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000242
243cl::alias PrintSourceShort("S", cl::desc("Alias for -source"),
244 cl::aliasopt(PrintSource));
245
246cl::opt<bool> PrintLines("line-numbers",
247 cl::desc("Display source line numbers with "
248 "disassembly. Implies disassemble object"));
249
250cl::alias PrintLinesShort("l", cl::desc("Alias for -line-numbers"),
251 cl::aliasopt(PrintLines));
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +0000252
253cl::opt<unsigned long long>
254 StartAddress("start-address", cl::desc("Disassemble beginning at address"),
255 cl::value_desc("address"), cl::init(0));
256cl::opt<unsigned long long>
257 StopAddress("stop-address", cl::desc("Stop disassembly at address"),
258 cl::value_desc("address"), cl::init(UINT64_MAX));
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000259static StringRef ToolName;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000260
Sam Parker5fba45a2017-02-08 09:44:18 +0000261typedef std::vector<std::tuple<uint64_t, StringRef, uint8_t>> SectionSymbolsTy;
262
Colin LeMahieu77804be2015-07-29 15:45:39 +0000263namespace {
Colin LeMahieufcc32762015-07-29 19:08:10 +0000264typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate;
Colin LeMahieu77804be2015-07-29 15:45:39 +0000265
266class SectionFilterIterator {
267public:
268 SectionFilterIterator(FilterPredicate P,
269 llvm::object::section_iterator const &I,
270 llvm::object::section_iterator const &E)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000271 : Predicate(std::move(P)), Iterator(I), End(E) {
Colin LeMahieu77804be2015-07-29 15:45:39 +0000272 ScanPredicate();
273 }
Benjamin Kramerac9257b2015-09-24 14:52:52 +0000274 const llvm::object::SectionRef &operator*() const { return *Iterator; }
Colin LeMahieu77804be2015-07-29 15:45:39 +0000275 SectionFilterIterator &operator++() {
276 ++Iterator;
277 ScanPredicate();
278 return *this;
279 }
280 bool operator!=(SectionFilterIterator const &Other) const {
281 return Iterator != Other.Iterator;
282 }
283
284private:
285 void ScanPredicate() {
Colin LeMahieuda1723f2015-07-29 19:21:13 +0000286 while (Iterator != End && !Predicate(*Iterator)) {
Colin LeMahieu77804be2015-07-29 15:45:39 +0000287 ++Iterator;
288 }
289 }
290 FilterPredicate Predicate;
291 llvm::object::section_iterator Iterator;
292 llvm::object::section_iterator End;
293};
294
295class SectionFilter {
296public:
297 SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000298 : Predicate(std::move(P)), Object(O) {}
Colin LeMahieu77804be2015-07-29 15:45:39 +0000299 SectionFilterIterator begin() {
300 return SectionFilterIterator(Predicate, Object.section_begin(),
301 Object.section_end());
302 }
303 SectionFilterIterator end() {
304 return SectionFilterIterator(Predicate, Object.section_end(),
305 Object.section_end());
306 }
307
308private:
309 FilterPredicate Predicate;
310 llvm::object::ObjectFile const &Object;
311};
312SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) {
David Majnemer42531262016-08-12 03:55:06 +0000313 return SectionFilter(
314 [](llvm::object::SectionRef const &S) {
315 if (FilterSections.empty())
316 return true;
317 llvm::StringRef String;
318 std::error_code error = S.getName(String);
319 if (error)
320 return false;
321 return is_contained(FilterSections, String);
322 },
323 O);
Colin LeMahieu77804be2015-07-29 15:45:39 +0000324}
325}
326
Davide Italianoccd53fe2015-08-05 07:18:31 +0000327void llvm::error(std::error_code EC) {
Mark Seaborneb03ac52014-01-25 00:32:01 +0000328 if (!EC)
Davide Italianoccd53fe2015-08-05 07:18:31 +0000329 return;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000330
Davide Italiano140af642015-12-25 18:16:45 +0000331 errs() << ToolName << ": error reading file: " << EC.message() << ".\n";
332 errs().flush();
Davide Italiano7f6c3012015-08-06 00:18:52 +0000333 exit(1);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000334}
335
Kevin Enderby42398052016-06-28 23:16:13 +0000336LLVM_ATTRIBUTE_NORETURN void llvm::error(Twine Message) {
337 errs() << ToolName << ": " << Message << ".\n";
338 errs().flush();
339 exit(1);
340}
341
Paul Semel007dedb2018-07-18 16:39:21 +0000342void llvm::warn(StringRef Message) {
343 errs() << ToolName << ": warning: " << Message << ".\n";
344 errs().flush();
345}
346
Davide Italianoed9d95b2015-12-29 13:41:02 +0000347LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000348 Twine Message) {
349 errs() << ToolName << ": '" << File << "': " << Message << ".\n";
350 exit(1);
351}
352
353LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
Davide Italianoed9d95b2015-12-29 13:41:02 +0000354 std::error_code EC) {
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000355 assert(EC);
356 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
Davide Italianoccd53fe2015-08-05 07:18:31 +0000357 exit(1);
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000358}
359
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000360LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
361 llvm::Error E) {
362 assert(E);
363 std::string Buf;
364 raw_string_ostream OS(Buf);
365 logAllUnhandledErrors(std::move(E), OS, "");
366 OS.flush();
Kevin Enderbyb34e3a12016-05-05 17:43:35 +0000367 errs() << ToolName << ": '" << File << "': " << Buf;
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000368 exit(1);
369}
370
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000371LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
372 StringRef FileName,
Kevin Enderby9acb1092016-05-31 20:35:34 +0000373 llvm::Error E,
374 StringRef ArchitectureName) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000375 assert(E);
376 errs() << ToolName << ": ";
377 if (ArchiveName != "")
378 errs() << ArchiveName << "(" << FileName << ")";
379 else
Justin Bogner31d8b7d2016-10-26 22:37:52 +0000380 errs() << "'" << FileName << "'";
Kevin Enderby9acb1092016-05-31 20:35:34 +0000381 if (!ArchitectureName.empty())
382 errs() << " (for architecture " << ArchitectureName << ")";
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000383 std::string Buf;
384 raw_string_ostream OS(Buf);
385 logAllUnhandledErrors(std::move(E), OS, "");
386 OS.flush();
Justin Bogner31d8b7d2016-10-26 22:37:52 +0000387 errs() << ": " << Buf;
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000388 exit(1);
389}
390
391LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
392 const object::Archive::Child &C,
Kevin Enderby9acb1092016-05-31 20:35:34 +0000393 llvm::Error E,
394 StringRef ArchitectureName) {
Kevin Enderbyf4586032016-07-29 17:44:13 +0000395 Expected<StringRef> NameOrErr = C.getName();
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000396 // TODO: if we have a error getting the name then it would be nice to print
397 // the index of which archive member this is and or its offset in the
398 // archive instead of "???" as the name.
Kevin Enderbyf4586032016-07-29 17:44:13 +0000399 if (!NameOrErr) {
400 consumeError(NameOrErr.takeError());
Kevin Enderby9acb1092016-05-31 20:35:34 +0000401 llvm::report_error(ArchiveName, "???", std::move(E), ArchitectureName);
Kevin Enderbyf4586032016-07-29 17:44:13 +0000402 } else
Kevin Enderby9acb1092016-05-31 20:35:34 +0000403 llvm::report_error(ArchiveName, NameOrErr.get(), std::move(E),
404 ArchitectureName);
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000405}
406
Craig Toppere6cb63e2014-04-25 04:24:47 +0000407static const Target *getTarget(const ObjectFile *Obj = nullptr) {
Michael J. Spencer2670c252011-01-20 06:39:06 +0000408 // Figure out the target triple.
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000409 llvm::Triple TheTriple("unknown-unknown-unknown");
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000410 if (TripleName.empty()) {
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000411 if (Obj) {
Vlad Tsyrklevichde620462017-09-19 02:22:48 +0000412 TheTriple = Obj->makeTriple();
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000413 }
Sam Parkerdf7c6ef2017-01-18 13:52:12 +0000414 } else {
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000415 TheTriple.setTriple(Triple::normalize(TripleName));
Vlad Tsyrklevichde620462017-09-19 02:22:48 +0000416
Sam Parkerdf7c6ef2017-01-18 13:52:12 +0000417 // Use the triple, but also try to combine with ARM build attributes.
418 if (Obj) {
419 auto Arch = Obj->getArch();
420 if (Arch == Triple::arm || Arch == Triple::armeb) {
421 Obj->setARMSubArch(TheTriple);
422 }
423 }
424 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000425
426 // Get the target specific parser.
427 std::string Error;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000428 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
429 Error);
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000430 if (!TheTarget) {
431 if (Obj)
432 report_error(Obj->getFileName(), "can't find target: " + Error);
433 else
434 error("can't find target: " + Error);
435 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000436
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000437 // Update the triple name and return the found target.
438 TripleName = TheTriple.getTriple();
439 return TheTarget;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000440}
441
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000442bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
Rafael Espindola704cd842015-07-06 15:47:43 +0000443 return a.getOffset() < b.getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +0000444}
445
Rafael Espindola37070a52015-06-03 04:48:06 +0000446template <class ELFT>
Rafael Espindola37070a52015-06-03 04:48:06 +0000447static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000448 const RelocationRef &RelRef,
Rafael Espindola37070a52015-06-03 04:48:06 +0000449 SmallVectorImpl<char> &Result) {
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000450 DataRefImpl Rel = RelRef.getRawDataRefImpl();
451
Rafael Espindola37070a52015-06-03 04:48:06 +0000452 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
453 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000454 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
455
Rafael Espindola37070a52015-06-03 04:48:06 +0000456 const ELFFile<ELFT> &EF = *Obj->getELFFile();
457
Davide Italiano6cf09262016-11-16 05:10:28 +0000458 auto SecOrErr = EF.getSection(Rel.d.a);
459 if (!SecOrErr)
460 return errorToErrorCode(SecOrErr.takeError());
Rafael Espindola6def3042015-07-01 12:56:27 +0000461 const Elf_Shdr *Sec = *SecOrErr;
Davide Italiano6cf09262016-11-16 05:10:28 +0000462 auto SymTabOrErr = EF.getSection(Sec->sh_link);
463 if (!SymTabOrErr)
464 return errorToErrorCode(SymTabOrErr.takeError());
Rafael Espindola6def3042015-07-01 12:56:27 +0000465 const Elf_Shdr *SymTab = *SymTabOrErr;
Rafael Espindola719dc7c2015-06-29 12:38:31 +0000466 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
467 SymTab->sh_type == ELF::SHT_DYNSYM);
Davide Italiano6cf09262016-11-16 05:10:28 +0000468 auto StrTabSec = EF.getSection(SymTab->sh_link);
469 if (!StrTabSec)
470 return errorToErrorCode(StrTabSec.takeError());
471 auto StrTabOrErr = EF.getStringTable(*StrTabSec);
472 if (!StrTabOrErr)
473 return errorToErrorCode(StrTabOrErr.takeError());
Rafael Espindola6a1bfb22015-06-29 14:39:25 +0000474 StringRef StrTab = *StrTabOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000475 int64_t addend = 0;
Paul Semelcb0f0432018-06-07 13:30:55 +0000476 // If there is no Symbol associated with the relocation, we set the undef
477 // boolean value to 'true'. This will prevent us from calling functions that
478 // requires the relocation to be associated with a symbol.
479 bool undef = false;
Rafael Espindola6def3042015-07-01 12:56:27 +0000480 switch (Sec->sh_type) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000481 default:
482 return object_error::parse_failed;
483 case ELF::SHT_REL: {
Rafael Espindola37070a52015-06-03 04:48:06 +0000484 // TODO: Read implicit addend from section data.
485 break;
486 }
487 case ELF::SHT_RELA: {
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000488 const Elf_Rela *ERela = Obj->getRela(Rel);
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000489 addend = ERela->r_addend;
Paul Semelcb0f0432018-06-07 13:30:55 +0000490 undef = ERela->getSymbol(false) == 0;
Rafael Espindola37070a52015-06-03 04:48:06 +0000491 break;
492 }
493 }
Rafael Espindola75d5b542015-06-03 05:14:22 +0000494 StringRef Target;
Paul Semelcb0f0432018-06-07 13:30:55 +0000495 if (!undef) {
496 symbol_iterator SI = RelRef.getSymbol();
497 const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
498 if (symb->getType() == ELF::STT_SECTION) {
499 Expected<section_iterator> SymSI = SI->getSection();
500 if (!SymSI)
501 return errorToErrorCode(SymSI.takeError());
502 const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
503 auto SecName = EF.getSectionName(SymSec);
504 if (!SecName)
505 return errorToErrorCode(SecName.takeError());
506 Target = *SecName;
507 } else {
508 Expected<StringRef> SymName = symb->getName(StrTab);
509 if (!SymName)
510 return errorToErrorCode(SymName.takeError());
511 Target = *SymName;
512 }
513 } else
514 Target = "*ABS*";
Daniel Cedermand72b9fd2018-06-01 05:31:58 +0000515
516 // Default scheme is to print Target, as well as "+ <addend>" for nonzero
517 // addend. Should be acceptable for all normal purposes.
518 std::string fmtbuf;
519 raw_string_ostream fmt(fmtbuf);
520 fmt << Target;
521 if (addend != 0)
522 fmt << (addend < 0 ? "" : "+") << addend;
523 fmt.flush();
524 Result.append(fmtbuf.begin(), fmtbuf.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000525 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000526}
527
528static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000529 const RelocationRef &Rel,
Rafael Espindola37070a52015-06-03 04:48:06 +0000530 SmallVectorImpl<char> &Result) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000531 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
532 return getRelocationValueString(ELF32LE, Rel, Result);
533 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
534 return getRelocationValueString(ELF64LE, Rel, Result);
535 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
536 return getRelocationValueString(ELF32BE, Rel, Result);
537 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
538 return getRelocationValueString(ELF64BE, Rel, Result);
539}
540
541static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
542 const RelocationRef &Rel,
543 SmallVectorImpl<char> &Result) {
544 symbol_iterator SymI = Rel.getSymbol();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000545 Expected<StringRef> SymNameOrErr = SymI->getName();
546 if (!SymNameOrErr)
547 return errorToErrorCode(SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000548 StringRef SymName = *SymNameOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000549 Result.append(SymName.begin(), SymName.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000550 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000551}
552
553static void printRelocationTargetName(const MachOObjectFile *O,
554 const MachO::any_relocation_info &RE,
555 raw_string_ostream &fmt) {
556 bool IsScattered = O->isRelocationScattered(RE);
557
558 // Target of a scattered relocation is an address. In the interest of
559 // generating pretty output, scan through the symbol table looking for a
560 // symbol that aligns with that address. If we find one, print it.
561 // Otherwise, we just print the hex address of the target.
562 if (IsScattered) {
563 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
564
565 for (const SymbolRef &Symbol : O->symbols()) {
566 std::error_code ec;
Kevin Enderby931cb652016-06-24 18:24:42 +0000567 Expected<uint64_t> Addr = Symbol.getAddress();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000568 if (!Addr)
569 report_error(O->getFileName(), Addr.takeError());
Rafael Espindolaed067c42015-07-03 18:19:00 +0000570 if (*Addr != Val)
Rafael Espindola37070a52015-06-03 04:48:06 +0000571 continue;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000572 Expected<StringRef> Name = Symbol.getName();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000573 if (!Name)
574 report_error(O->getFileName(), Name.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000575 fmt << *Name;
Rafael Espindola37070a52015-06-03 04:48:06 +0000576 return;
577 }
578
579 // If we couldn't find a symbol that this relocation refers to, try
580 // to find a section beginning instead.
Colin LeMahieu77804be2015-07-29 15:45:39 +0000581 for (const SectionRef &Section : ToolSectionFilter(*O)) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000582 std::error_code ec;
583
584 StringRef Name;
585 uint64_t Addr = Section.getAddress();
586 if (Addr != Val)
587 continue;
588 if ((ec = Section.getName(Name)))
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000589 report_error(O->getFileName(), ec);
Rafael Espindola37070a52015-06-03 04:48:06 +0000590 fmt << Name;
591 return;
592 }
593
594 fmt << format("0x%x", Val);
595 return;
596 }
597
598 StringRef S;
599 bool isExtern = O->getPlainRelocationExternal(RE);
600 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
601
Martin Storsjo8c0317d2017-07-13 17:03:02 +0000602 if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND) {
Simon Dardis38867052017-08-07 12:29:38 +0000603 fmt << format("0x%0" PRIx64, Val);
Martin Storsjo8c0317d2017-07-13 17:03:02 +0000604 return;
605 } else if (isExtern) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000606 symbol_iterator SI = O->symbol_begin();
607 advance(SI, Val);
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000608 Expected<StringRef> SOrErr = SI->getName();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000609 if (!SOrErr)
610 report_error(O->getFileName(), SOrErr.takeError());
Davide Italianoccd53fe2015-08-05 07:18:31 +0000611 S = *SOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000612 } else {
613 section_iterator SI = O->section_begin();
614 // Adjust for the fact that sections are 1-indexed.
Kevin Enderby3fc91882017-11-03 21:32:44 +0000615 if (Val == 0) {
616 fmt << "0 (?,?)";
617 return;
618 }
619 uint32_t i = Val - 1;
620 while (i != 0 && SI != O->section_end()) {
621 i--;
622 advance(SI, 1);
623 }
624 if (SI == O->section_end())
625 fmt << Val << " (?,?)";
626 else
627 SI->getName(S);
Rafael Espindola37070a52015-06-03 04:48:06 +0000628 }
629
630 fmt << S;
631}
632
Sam Clegg4df5d762017-06-27 20:40:53 +0000633static std::error_code getRelocationValueString(const WasmObjectFile *Obj,
634 const RelocationRef &RelRef,
635 SmallVectorImpl<char> &Result) {
636 const wasm::WasmRelocation& Rel = Obj->getWasmRelocation(RelRef);
Sam Cleggf676cdd2018-04-26 16:41:51 +0000637 symbol_iterator SI = RelRef.getSymbol();
Sam Clegg4df5d762017-06-27 20:40:53 +0000638 std::string fmtbuf;
639 raw_string_ostream fmt(fmtbuf);
Sam Clegg8c4b0ce2018-04-26 17:05:04 +0000640 if (SI == Obj->symbol_end()) {
641 // Not all wasm relocations have symbols associated with them.
642 // In particular R_WEBASSEMBLY_TYPE_INDEX_LEB.
Sam Cleggf676cdd2018-04-26 16:41:51 +0000643 fmt << Rel.Index;
644 } else {
Sam Clegg8c4b0ce2018-04-26 17:05:04 +0000645 Expected<StringRef> SymNameOrErr = SI->getName();
646 if (!SymNameOrErr)
647 return errorToErrorCode(SymNameOrErr.takeError());
Sam Cleggf676cdd2018-04-26 16:41:51 +0000648 StringRef SymName = *SymNameOrErr;
649 Result.append(SymName.begin(), SymName.end());
650 }
651 fmt << (Rel.Addend < 0 ? "" : "+") << Rel.Addend;
Sam Clegg4df5d762017-06-27 20:40:53 +0000652 fmt.flush();
653 Result.append(fmtbuf.begin(), fmtbuf.end());
654 return std::error_code();
655}
656
Rafael Espindola37070a52015-06-03 04:48:06 +0000657static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
658 const RelocationRef &RelRef,
659 SmallVectorImpl<char> &Result) {
660 DataRefImpl Rel = RelRef.getRawDataRefImpl();
661 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
662
663 unsigned Arch = Obj->getArch();
664
665 std::string fmtbuf;
666 raw_string_ostream fmt(fmtbuf);
667 unsigned Type = Obj->getAnyRelocationType(RE);
668 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
669
670 // Determine any addends that should be displayed with the relocation.
671 // These require decoding the relocation type, which is triple-specific.
672
673 // X86_64 has entirely custom relocation types.
674 if (Arch == Triple::x86_64) {
675 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
676
677 switch (Type) {
678 case MachO::X86_64_RELOC_GOT_LOAD:
679 case MachO::X86_64_RELOC_GOT: {
680 printRelocationTargetName(Obj, RE, fmt);
681 fmt << "@GOT";
682 if (isPCRel)
683 fmt << "PCREL";
684 break;
685 }
686 case MachO::X86_64_RELOC_SUBTRACTOR: {
687 DataRefImpl RelNext = Rel;
688 Obj->moveRelocationNext(RelNext);
689 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
690
691 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
692 // X86_64_RELOC_UNSIGNED.
693 // NOTE: Scattered relocations don't exist on x86_64.
694 unsigned RType = Obj->getAnyRelocationType(RENext);
695 if (RType != MachO::X86_64_RELOC_UNSIGNED)
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000696 report_error(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
697 "X86_64_RELOC_SUBTRACTOR.");
Rafael Espindola37070a52015-06-03 04:48:06 +0000698
699 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
700 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
701 printRelocationTargetName(Obj, RENext, fmt);
702 fmt << "-";
703 printRelocationTargetName(Obj, RE, fmt);
704 break;
705 }
706 case MachO::X86_64_RELOC_TLV:
707 printRelocationTargetName(Obj, RE, fmt);
708 fmt << "@TLV";
709 if (isPCRel)
710 fmt << "P";
711 break;
712 case MachO::X86_64_RELOC_SIGNED_1:
713 printRelocationTargetName(Obj, RE, fmt);
714 fmt << "-1";
715 break;
716 case MachO::X86_64_RELOC_SIGNED_2:
717 printRelocationTargetName(Obj, RE, fmt);
718 fmt << "-2";
719 break;
720 case MachO::X86_64_RELOC_SIGNED_4:
721 printRelocationTargetName(Obj, RE, fmt);
722 fmt << "-4";
723 break;
724 default:
725 printRelocationTargetName(Obj, RE, fmt);
726 break;
727 }
728 // X86 and ARM share some relocation types in common.
729 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
730 Arch == Triple::ppc) {
731 // Generic relocation types...
732 switch (Type) {
733 case MachO::GENERIC_RELOC_PAIR: // prints no info
Rui Ueyama7d099192015-06-09 15:20:42 +0000734 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000735 case MachO::GENERIC_RELOC_SECTDIFF: {
736 DataRefImpl RelNext = Rel;
737 Obj->moveRelocationNext(RelNext);
738 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
739
740 // X86 sect diff's must be followed by a relocation of type
741 // GENERIC_RELOC_PAIR.
742 unsigned RType = Obj->getAnyRelocationType(RENext);
743
744 if (RType != MachO::GENERIC_RELOC_PAIR)
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000745 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
746 "GENERIC_RELOC_SECTDIFF.");
Rafael Espindola37070a52015-06-03 04:48:06 +0000747
748 printRelocationTargetName(Obj, RE, fmt);
749 fmt << "-";
750 printRelocationTargetName(Obj, RENext, fmt);
751 break;
752 }
753 }
754
755 if (Arch == Triple::x86 || Arch == Triple::ppc) {
756 switch (Type) {
757 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
758 DataRefImpl RelNext = Rel;
759 Obj->moveRelocationNext(RelNext);
760 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
761
762 // X86 sect diff's must be followed by a relocation of type
763 // GENERIC_RELOC_PAIR.
764 unsigned RType = Obj->getAnyRelocationType(RENext);
765 if (RType != MachO::GENERIC_RELOC_PAIR)
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000766 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
767 "GENERIC_RELOC_LOCAL_SECTDIFF.");
Rafael Espindola37070a52015-06-03 04:48:06 +0000768
769 printRelocationTargetName(Obj, RE, fmt);
770 fmt << "-";
771 printRelocationTargetName(Obj, RENext, fmt);
772 break;
773 }
774 case MachO::GENERIC_RELOC_TLV: {
775 printRelocationTargetName(Obj, RE, fmt);
776 fmt << "@TLV";
777 if (IsPCRel)
778 fmt << "P";
779 break;
780 }
781 default:
782 printRelocationTargetName(Obj, RE, fmt);
783 }
784 } else { // ARM-specific relocations
785 switch (Type) {
786 case MachO::ARM_RELOC_HALF:
787 case MachO::ARM_RELOC_HALF_SECTDIFF: {
788 // Half relocations steal a bit from the length field to encode
789 // whether this is an upper16 or a lower16 relocation.
Martin Storsjofa5183b2017-07-13 05:54:08 +0000790 bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
Rafael Espindola37070a52015-06-03 04:48:06 +0000791
792 if (isUpper)
793 fmt << ":upper16:(";
794 else
795 fmt << ":lower16:(";
796 printRelocationTargetName(Obj, RE, fmt);
797
798 DataRefImpl RelNext = Rel;
799 Obj->moveRelocationNext(RelNext);
800 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
801
802 // ARM half relocs must be followed by a relocation of type
803 // ARM_RELOC_PAIR.
804 unsigned RType = Obj->getAnyRelocationType(RENext);
805 if (RType != MachO::ARM_RELOC_PAIR)
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000806 report_error(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
807 "ARM_RELOC_HALF");
Rafael Espindola37070a52015-06-03 04:48:06 +0000808
809 // NOTE: The half of the target virtual address is stashed in the
810 // address field of the secondary relocation, but we can't reverse
811 // engineer the constant offset from it without decoding the movw/movt
812 // instruction to find the other half in its immediate field.
813
814 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
815 // symbol/section pointer of the follow-on relocation.
816 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
817 fmt << "-";
818 printRelocationTargetName(Obj, RENext, fmt);
819 }
820
821 fmt << ")";
822 break;
823 }
824 default: { printRelocationTargetName(Obj, RE, fmt); }
825 }
826 }
827 } else
828 printRelocationTargetName(Obj, RE, fmt);
829
830 fmt.flush();
831 Result.append(fmtbuf.begin(), fmtbuf.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000832 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000833}
834
835static std::error_code getRelocationValueString(const RelocationRef &Rel,
836 SmallVectorImpl<char> &Result) {
Rafael Espindola854038e2015-06-26 14:51:16 +0000837 const ObjectFile *Obj = Rel.getObject();
Rafael Espindola37070a52015-06-03 04:48:06 +0000838 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
839 return getRelocationValueString(ELF, Rel, Result);
840 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
841 return getRelocationValueString(COFF, Rel, Result);
Sam Clegg4df5d762017-06-27 20:40:53 +0000842 if (auto *Wasm = dyn_cast<WasmObjectFile>(Obj))
843 return getRelocationValueString(Wasm, Rel, Result);
844 if (auto *MachO = dyn_cast<MachOObjectFile>(Obj))
845 return getRelocationValueString(MachO, Rel, Result);
846 llvm_unreachable("unknown object file format");
Rafael Espindola37070a52015-06-03 04:48:06 +0000847}
848
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000849/// Indicates whether this relocation should hidden when listing
Rafael Espindola0ad71d92015-06-30 03:41:26 +0000850/// relocations, usually because it is the trailing part of a multipart
851/// relocation that will be printed as part of the leading relocation.
852static bool getHidden(RelocationRef RelRef) {
853 const ObjectFile *Obj = RelRef.getObject();
854 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
855 if (!MachO)
856 return false;
857
858 unsigned Arch = MachO->getArch();
859 DataRefImpl Rel = RelRef.getRawDataRefImpl();
860 uint64_t Type = MachO->getRelocationType(Rel);
861
862 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
863 // is always hidden.
864 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
865 if (Type == MachO::GENERIC_RELOC_PAIR)
866 return true;
867 } else if (Arch == Triple::x86_64) {
868 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
869 // an X86_64_RELOC_SUBTRACTOR.
870 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
871 DataRefImpl RelPrev = Rel;
872 RelPrev.d.a--;
873 uint64_t PrevType = MachO->getRelocationType(RelPrev);
874 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
875 return true;
876 }
877 }
878
879 return false;
880}
881
Sid Manningd9f28732018-05-14 19:46:08 +0000882namespace {
883class SourcePrinter {
884protected:
885 DILineInfo OldLineInfo;
886 const ObjectFile *Obj = nullptr;
887 std::unique_ptr<symbolize::LLVMSymbolizer> Symbolizer;
888 // File name to file contents of source
889 std::unordered_map<std::string, std::unique_ptr<MemoryBuffer>> SourceCache;
890 // Mark the line endings of the cached source
891 std::unordered_map<std::string, std::vector<StringRef>> LineCache;
892
893private:
894 bool cacheSource(const DILineInfo& LineInfoFile);
895
896public:
897 SourcePrinter() = default;
898 SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch) : Obj(Obj) {
899 symbolize::LLVMSymbolizer::Options SymbolizerOpts(
900 DILineInfoSpecifier::FunctionNameKind::None, true, false, false,
901 DefaultArch);
902 Symbolizer.reset(new symbolize::LLVMSymbolizer(SymbolizerOpts));
903 }
904 virtual ~SourcePrinter() = default;
905 virtual void printSourceLine(raw_ostream &OS, uint64_t Address,
906 StringRef Delimiter = "; ");
907};
908
909bool SourcePrinter::cacheSource(const DILineInfo &LineInfo) {
910 std::unique_ptr<MemoryBuffer> Buffer;
911 if (LineInfo.Source) {
912 Buffer = MemoryBuffer::getMemBuffer(*LineInfo.Source);
913 } else {
914 auto BufferOrError = MemoryBuffer::getFile(LineInfo.FileName);
915 if (!BufferOrError)
916 return false;
917 Buffer = std::move(*BufferOrError);
918 }
919 // Chomp the file to get lines
920 size_t BufferSize = Buffer->getBufferSize();
921 const char *BufferStart = Buffer->getBufferStart();
922 for (const char *Start = BufferStart, *End = BufferStart;
923 End < BufferStart + BufferSize; End++)
924 if (*End == '\n' || End == BufferStart + BufferSize - 1 ||
925 (*End == '\r' && *(End + 1) == '\n')) {
926 LineCache[LineInfo.FileName].push_back(StringRef(Start, End - Start));
927 if (*End == '\r')
928 End++;
929 Start = End + 1;
930 }
931 SourceCache[LineInfo.FileName] = std::move(Buffer);
932 return true;
933}
934
935void SourcePrinter::printSourceLine(raw_ostream &OS, uint64_t Address,
936 StringRef Delimiter) {
937 if (!Symbolizer)
938 return;
939 DILineInfo LineInfo = DILineInfo();
940 auto ExpectecLineInfo =
941 Symbolizer->symbolizeCode(Obj->getFileName(), Address);
942 if (!ExpectecLineInfo)
943 consumeError(ExpectecLineInfo.takeError());
944 else
945 LineInfo = *ExpectecLineInfo;
946
947 if ((LineInfo.FileName == "<invalid>") || OldLineInfo.Line == LineInfo.Line ||
948 LineInfo.Line == 0)
949 return;
950
951 if (PrintLines)
952 OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line << "\n";
953 if (PrintSource) {
954 if (SourceCache.find(LineInfo.FileName) == SourceCache.end())
955 if (!cacheSource(LineInfo))
956 return;
957 auto FileBuffer = SourceCache.find(LineInfo.FileName);
958 if (FileBuffer != SourceCache.end()) {
959 auto LineBuffer = LineCache.find(LineInfo.FileName);
960 if (LineBuffer != LineCache.end()) {
961 if (LineInfo.Line > LineBuffer->second.size())
962 return;
963 // Vector begins at 0, line numbers are non-zero
964 OS << Delimiter << LineBuffer->second[LineInfo.Line - 1].ltrim()
965 << "\n";
966 }
967 }
968 }
969 OldLineInfo = LineInfo;
970}
971
972static bool isArmElf(const ObjectFile *Obj) {
973 return (Obj->isELF() &&
974 (Obj->getArch() == Triple::aarch64 ||
975 Obj->getArch() == Triple::aarch64_be ||
976 Obj->getArch() == Triple::arm || Obj->getArch() == Triple::armeb ||
977 Obj->getArch() == Triple::thumb ||
978 Obj->getArch() == Triple::thumbeb));
979}
980
981class PrettyPrinter {
982public:
983 virtual ~PrettyPrinter() = default;
984 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
985 ArrayRef<uint8_t> Bytes, uint64_t Address,
986 raw_ostream &OS, StringRef Annot,
987 MCSubtargetInfo const &STI, SourcePrinter *SP,
988 std::vector<RelocationRef> *Rels = nullptr) {
989 if (SP && (PrintSource || PrintLines))
990 SP->printSourceLine(OS, Address);
991 if (!NoLeadingAddr)
992 OS << format("%8" PRIx64 ":", Address);
993 if (!NoShowRawInsn) {
994 OS << "\t";
995 dumpBytes(Bytes, OS);
996 }
997 if (MI)
998 IP.printInst(MI, OS, "", STI);
999 else
1000 OS << " <unknown>";
1001 }
1002};
1003PrettyPrinter PrettyPrinterInst;
1004class HexagonPrettyPrinter : public PrettyPrinter {
1005public:
1006 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
1007 raw_ostream &OS) {
1008 uint32_t opcode =
1009 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
1010 if (!NoLeadingAddr)
1011 OS << format("%8" PRIx64 ":", Address);
1012 if (!NoShowRawInsn) {
1013 OS << "\t";
1014 dumpBytes(Bytes.slice(0, 4), OS);
1015 OS << format("%08" PRIx32, opcode);
1016 }
1017 }
1018 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1019 uint64_t Address, raw_ostream &OS, StringRef Annot,
1020 MCSubtargetInfo const &STI, SourcePrinter *SP,
1021 std::vector<RelocationRef> *Rels) override {
1022 if (SP && (PrintSource || PrintLines))
1023 SP->printSourceLine(OS, Address, "");
1024 if (!MI) {
1025 printLead(Bytes, Address, OS);
1026 OS << " <unknown>";
1027 return;
1028 }
1029 std::string Buffer;
1030 {
1031 raw_string_ostream TempStream(Buffer);
1032 IP.printInst(MI, TempStream, "", STI);
1033 }
1034 StringRef Contents(Buffer);
1035 // Split off bundle attributes
1036 auto PacketBundle = Contents.rsplit('\n');
1037 // Split off first instruction from the rest
1038 auto HeadTail = PacketBundle.first.split('\n');
1039 auto Preamble = " { ";
1040 auto Separator = "";
1041 StringRef Fmt = "\t\t\t%08" PRIx64 ": ";
1042 std::vector<RelocationRef>::const_iterator rel_cur = Rels->begin();
1043 std::vector<RelocationRef>::const_iterator rel_end = Rels->end();
1044
1045 // Hexagon's packets require relocations to be inline rather than
1046 // clustered at the end of the packet.
1047 auto PrintReloc = [&]() -> void {
1048 while ((rel_cur != rel_end) && (rel_cur->getOffset() <= Address)) {
1049 if (rel_cur->getOffset() == Address) {
1050 SmallString<16> name;
1051 SmallString<32> val;
1052 rel_cur->getTypeName(name);
1053 error(getRelocationValueString(*rel_cur, val));
1054 OS << Separator << format(Fmt.data(), Address) << name << "\t" << val
1055 << "\n";
1056 return;
1057 }
1058 rel_cur++;
1059 }
1060 };
1061
1062 while(!HeadTail.first.empty()) {
1063 OS << Separator;
1064 Separator = "\n";
1065 if (SP && (PrintSource || PrintLines))
1066 SP->printSourceLine(OS, Address, "");
1067 printLead(Bytes, Address, OS);
1068 OS << Preamble;
1069 Preamble = " ";
1070 StringRef Inst;
1071 auto Duplex = HeadTail.first.split('\v');
1072 if(!Duplex.second.empty()){
1073 OS << Duplex.first;
1074 OS << "; ";
1075 Inst = Duplex.second;
1076 }
1077 else
1078 Inst = HeadTail.first;
1079 OS << Inst;
1080 HeadTail = HeadTail.second.split('\n');
1081 if (HeadTail.first.empty())
1082 OS << " } " << PacketBundle.second;
1083 PrintReloc();
1084 Bytes = Bytes.slice(4);
1085 Address += 4;
1086 }
1087 }
1088};
1089HexagonPrettyPrinter HexagonPrettyPrinterInst;
1090
1091class AMDGCNPrettyPrinter : public PrettyPrinter {
1092public:
1093 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1094 uint64_t Address, raw_ostream &OS, StringRef Annot,
1095 MCSubtargetInfo const &STI, SourcePrinter *SP,
1096 std::vector<RelocationRef> *Rels) override {
1097 if (SP && (PrintSource || PrintLines))
1098 SP->printSourceLine(OS, Address);
1099
1100 typedef support::ulittle32_t U32;
1101
1102 if (MI) {
1103 SmallString<40> InstStr;
1104 raw_svector_ostream IS(InstStr);
1105
1106 IP.printInst(MI, IS, "", STI);
1107
1108 OS << left_justify(IS.str(), 60);
1109 } else {
1110 // an unrecognized encoding - this is probably data so represent it
1111 // using the .long directive, or .byte directive if fewer than 4 bytes
1112 // remaining
1113 if (Bytes.size() >= 4) {
1114 OS << format("\t.long 0x%08" PRIx32 " ",
1115 static_cast<uint32_t>(*reinterpret_cast<const U32*>(Bytes.data())));
1116 OS.indent(42);
1117 } else {
1118 OS << format("\t.byte 0x%02" PRIx8, Bytes[0]);
1119 for (unsigned int i = 1; i < Bytes.size(); i++)
1120 OS << format(", 0x%02" PRIx8, Bytes[i]);
1121 OS.indent(55 - (6 * Bytes.size()));
1122 }
1123 }
1124
1125 OS << format("// %012" PRIX64 ": ", Address);
1126 if (Bytes.size() >=4) {
1127 for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
1128 Bytes.size() / sizeof(U32)))
1129 // D should be explicitly casted to uint32_t here as it is passed
1130 // by format to snprintf as vararg.
1131 OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D));
1132 } else {
1133 for (unsigned int i = 0; i < Bytes.size(); i++)
1134 OS << format("%02" PRIX8 " ", Bytes[i]);
1135 }
1136
1137 if (!Annot.empty())
1138 OS << "// " << Annot;
1139 }
1140};
1141AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
1142
1143class BPFPrettyPrinter : public PrettyPrinter {
1144public:
1145 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1146 uint64_t Address, raw_ostream &OS, StringRef Annot,
1147 MCSubtargetInfo const &STI, SourcePrinter *SP,
1148 std::vector<RelocationRef> *Rels) override {
1149 if (SP && (PrintSource || PrintLines))
1150 SP->printSourceLine(OS, Address);
1151 if (!NoLeadingAddr)
1152 OS << format("%8" PRId64 ":", Address / 8);
1153 if (!NoShowRawInsn) {
1154 OS << "\t";
1155 dumpBytes(Bytes, OS);
1156 }
1157 if (MI)
1158 IP.printInst(MI, OS, "", STI);
1159 else
1160 OS << " <unknown>";
1161 }
1162};
1163BPFPrettyPrinter BPFPrettyPrinterInst;
1164
1165PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
1166 switch(Triple.getArch()) {
1167 default:
1168 return PrettyPrinterInst;
1169 case Triple::hexagon:
1170 return HexagonPrettyPrinterInst;
1171 case Triple::amdgcn:
1172 return AMDGCNPrettyPrinterInst;
1173 case Triple::bpfel:
1174 case Triple::bpfeb:
1175 return BPFPrettyPrinterInst;
1176 }
1177}
1178}
1179
Sam Koltonc05d7782016-08-17 10:17:57 +00001180static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) {
1181 assert(Obj->isELF());
1182 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1183 return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1184 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1185 return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1186 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1187 return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1188 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1189 return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1190 llvm_unreachable("Unsupported binary format");
1191}
1192
Sam Parker5fba45a2017-02-08 09:44:18 +00001193template <class ELFT> static void
1194addDynamicElfSymbols(const ELFObjectFile<ELFT> *Obj,
1195 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1196 for (auto Symbol : Obj->getDynamicSymbolIterators()) {
1197 uint8_t SymbolType = Symbol.getELFType();
1198 if (SymbolType != ELF::STT_FUNC || Symbol.getSize() == 0)
1199 continue;
1200
1201 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
1202 if (!AddressOrErr)
1203 report_error(Obj->getFileName(), AddressOrErr.takeError());
1204 uint64_t Address = *AddressOrErr;
1205
1206 Expected<StringRef> Name = Symbol.getName();
1207 if (!Name)
1208 report_error(Obj->getFileName(), Name.takeError());
1209 if (Name->empty())
1210 continue;
1211
1212 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1213 if (!SectionOrErr)
1214 report_error(Obj->getFileName(), SectionOrErr.takeError());
1215 section_iterator SecI = *SectionOrErr;
1216 if (SecI == Obj->section_end())
1217 continue;
1218
1219 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1220 }
1221}
1222
1223static void
1224addDynamicElfSymbols(const ObjectFile *Obj,
1225 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1226 assert(Obj->isELF());
1227 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1228 addDynamicElfSymbols(Elf32LEObj, AllSymbols);
1229 else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1230 addDynamicElfSymbols(Elf64LEObj, AllSymbols);
1231 else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1232 addDynamicElfSymbols(Elf32BEObj, AllSymbols);
1233 else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1234 addDynamicElfSymbols(Elf64BEObj, AllSymbols);
1235 else
1236 llvm_unreachable("Unsupported binary format");
1237}
1238
Joel Galenson134cf472018-08-24 15:21:57 +00001239static void addPltEntries(const ObjectFile *Obj,
1240 std::map<SectionRef, SectionSymbolsTy> &AllSymbols,
1241 StringSaver &Saver) {
1242 Optional<SectionRef> Plt = None;
1243 for (const SectionRef &Section : Obj->sections()) {
1244 StringRef Name;
1245 if (Section.getName(Name))
1246 continue;
1247 if (Name == ".plt")
1248 Plt = Section;
1249 }
1250 if (!Plt)
1251 return;
1252 if (auto *ElfObj = dyn_cast<ELFObjectFileBase>(Obj)) {
1253 for (auto PltEntry : ElfObj->getPltAddresses()) {
1254 SymbolRef Symbol(PltEntry.first, ElfObj);
1255
1256 uint8_t SymbolType = getElfSymbolType(Obj, Symbol);
1257
1258 Expected<StringRef> NameOrErr = Symbol.getName();
1259 if (!NameOrErr)
1260 report_error(Obj->getFileName(), NameOrErr.takeError());
1261 if (NameOrErr->empty())
1262 continue;
1263 StringRef Name = Saver.save((*NameOrErr + "@plt").str());
1264
1265 AllSymbols[*Plt].emplace_back(PltEntry.second, Name, SymbolType);
1266 }
1267 }
1268}
1269
Michael J. Spencer51862b32011-10-13 22:17:18 +00001270static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001271 if (StartAddress > StopAddress)
1272 error("Start address should be less than stop address");
1273
Jim Grosbachaf9aec02012-08-07 17:53:14 +00001274 const Target *TheTarget = getTarget(Obj);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001275
Jack Carter551efd72012-08-28 19:24:49 +00001276 // Package up features to be passed to target/subtarget
Daniel Sanders1d148642016-06-16 09:17:03 +00001277 SubtargetFeatures Features = Obj->getFeatures();
Jack Carter551efd72012-08-28 19:24:49 +00001278 if (MAttrs.size()) {
Jack Carter551efd72012-08-28 19:24:49 +00001279 for (unsigned i = 0; i != MAttrs.size(); ++i)
1280 Features.AddFeature(MAttrs[i]);
Jack Carter551efd72012-08-28 19:24:49 +00001281 }
1282
Ahmed Charles56440fd2014-03-06 05:51:42 +00001283 std::unique_ptr<const MCRegisterInfo> MRI(
1284 TheTarget->createMCRegInfo(TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +00001285 if (!MRI)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001286 report_error(Obj->getFileName(), "no register info for target " +
1287 TripleName);
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001288
1289 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00001290 std::unique_ptr<const MCAsmInfo> AsmInfo(
1291 TheTarget->createMCAsmInfo(*MRI, TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +00001292 if (!AsmInfo)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001293 report_error(Obj->getFileName(), "no assembly info for target " +
1294 TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +00001295 std::unique_ptr<const MCSubtargetInfo> STI(
Daniel Sanders1d148642016-06-16 09:17:03 +00001296 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
Davide Italiano711e4952015-12-17 01:59:50 +00001297 if (!STI)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001298 report_error(Obj->getFileName(), "no subtarget info for target " +
1299 TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +00001300 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
Davide Italiano711e4952015-12-17 01:59:50 +00001301 if (!MII)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001302 report_error(Obj->getFileName(), "no instruction info for target " +
1303 TripleName);
Sam Kolton3381d7a2016-10-06 13:46:08 +00001304 MCObjectFileInfo MOFI;
1305 MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI);
1306 // FIXME: for now initialize MCObjectFileInfo with default values
Rafael Espindola9f929952017-08-02 20:32:26 +00001307 MOFI.InitMCObjectFileInfo(Triple(TripleName), false, Ctx);
Lang Hamesa1bc0f52014-04-15 04:40:56 +00001308
1309 std::unique_ptr<MCDisassembler> DisAsm(
1310 TheTarget->createMCDisassembler(*STI, Ctx));
Davide Italiano711e4952015-12-17 01:59:50 +00001311 if (!DisAsm)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001312 report_error(Obj->getFileName(), "no disassembler for target " +
1313 TripleName);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001314
Ahmed Charles56440fd2014-03-06 05:51:42 +00001315 std::unique_ptr<const MCInstrAnalysis> MIA(
1316 TheTarget->createMCInstrAnalysis(MII.get()));
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001317
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001318 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Daniel Sanders50f17232015-09-15 16:17:27 +00001319 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1320 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
Davide Italiano711e4952015-12-17 01:59:50 +00001321 if (!IP)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001322 report_error(Obj->getFileName(), "no instruction printer for target " +
1323 TripleName);
Colin LeMahieu14ec76e2015-06-07 21:07:17 +00001324 IP->setPrintImmHex(PrintImmHex);
Colin LeMahieu35436a22015-05-29 14:48:25 +00001325 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001326
Greg Fitzgerald18432272014-03-20 22:55:15 +00001327 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
1328 "\t\t\t%08" PRIx64 ": ";
1329
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001330 SourcePrinter SP(Obj, TheTarget->getName());
1331
Mark Seaborn0929d3d2014-01-25 17:38:19 +00001332 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
1333 // in RelocSecs contain the relocations for section S.
Rafael Espindola4453e42942014-06-13 03:07:50 +00001334 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +00001335 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001336 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001337 section_iterator Sec2 = Section.getRelocatedSection();
Rafael Espindolab5155a52014-02-10 20:24:04 +00001338 if (Sec2 != Obj->section_end())
Alexey Samsonov48803e52014-03-13 14:37:36 +00001339 SectionRelocMap[*Sec2].push_back(Section);
Mark Seaborn0929d3d2014-01-25 17:38:19 +00001340 }
1341
David Majnemer81afca62015-07-07 22:06:59 +00001342 // Create a mapping from virtual address to symbol name. This is used to
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001343 // pretty print the symbols while disassembling.
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001344 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
Sterling Augustinebc78b622018-06-28 18:57:13 +00001345 SectionSymbolsTy AbsoluteSymbols;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001346 for (const SymbolRef &Symbol : Obj->symbols()) {
Kevin Enderby931cb652016-06-24 18:24:42 +00001347 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001348 if (!AddressOrErr)
1349 report_error(Obj->getFileName(), AddressOrErr.takeError());
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001350 uint64_t Address = *AddressOrErr;
David Majnemer2603a8fa2015-07-09 18:11:40 +00001351
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001352 Expected<StringRef> Name = Symbol.getName();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001353 if (!Name)
1354 report_error(Obj->getFileName(), Name.takeError());
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001355 if (Name->empty())
1356 continue;
David Majnemer81afca62015-07-07 22:06:59 +00001357
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001358 Expected<section_iterator> SectionOrErr = Symbol.getSection();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001359 if (!SectionOrErr)
1360 report_error(Obj->getFileName(), SectionOrErr.takeError());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001361
Sam Koltonc05d7782016-08-17 10:17:57 +00001362 uint8_t SymbolType = ELF::STT_NOTYPE;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001363 if (Obj->isELF())
Sam Koltonc05d7782016-08-17 10:17:57 +00001364 SymbolType = getElfSymbolType(Obj, Symbol);
David Majnemer81afca62015-07-07 22:06:59 +00001365
Sterling Augustinebc78b622018-06-28 18:57:13 +00001366 section_iterator SecI = *SectionOrErr;
1367 if (SecI != Obj->section_end())
1368 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1369 else
1370 AbsoluteSymbols.emplace_back(Address, *Name, SymbolType);
1371
Sam Koltonc05d7782016-08-17 10:17:57 +00001372
David Majnemer81afca62015-07-07 22:06:59 +00001373 }
Sam Parker5fba45a2017-02-08 09:44:18 +00001374 if (AllSymbols.empty() && Obj->isELF())
1375 addDynamicElfSymbols(Obj, AllSymbols);
David Majnemer81afca62015-07-07 22:06:59 +00001376
Joel Galenson134cf472018-08-24 15:21:57 +00001377 BumpPtrAllocator A;
1378 StringSaver Saver(A);
1379 addPltEntries(Obj, AllSymbols, Saver);
1380
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001381 // Create a mapping from virtual address to section.
1382 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1383 for (SectionRef Sec : Obj->sections())
1384 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1385 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
1386
1387 // Linked executables (.exe and .dll files) typically don't include a real
1388 // symbol table but they might contain an export table.
1389 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
1390 for (const auto &ExportEntry : COFFObj->export_directories()) {
1391 StringRef Name;
1392 error(ExportEntry.getSymbolName(Name));
1393 if (Name.empty())
1394 continue;
1395 uint32_t RVA;
1396 error(ExportEntry.getExportRVA(RVA));
1397
1398 uint64_t VA = COFFObj->getImageBase() + RVA;
1399 auto Sec = std::upper_bound(
1400 SectionAddresses.begin(), SectionAddresses.end(), VA,
1401 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
1402 return LHS < RHS.first;
1403 });
1404 if (Sec != SectionAddresses.begin())
1405 --Sec;
1406 else
1407 Sec = SectionAddresses.end();
1408
1409 if (Sec != SectionAddresses.end())
Sam Koltonc05d7782016-08-17 10:17:57 +00001410 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
Sterling Augustinebc78b622018-06-28 18:57:13 +00001411 else
1412 AbsoluteSymbols.emplace_back(VA, Name, ELF::STT_NOTYPE);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001413 }
1414 }
1415
1416 // Sort all the symbols, this allows us to use a simple binary search to find
1417 // a symbol near an address.
1418 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1419 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
Sterling Augustinebc78b622018-06-28 18:57:13 +00001420 array_pod_sort(AbsoluteSymbols.begin(), AbsoluteSymbols.end());
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001421
Colin LeMahieu77804be2015-07-29 15:45:39 +00001422 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Colin LeMahieuf34933e2015-07-23 20:58:49 +00001423 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
Mark Seaborneb03ac52014-01-25 00:32:01 +00001424 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +00001425
Rafael Espindola80291272014-10-08 15:28:58 +00001426 uint64_t SectionAddr = Section.getAddress();
1427 uint64_t SectSize = Section.getSize();
David Majnemer185b5b12014-11-11 09:58:25 +00001428 if (!SectSize)
1429 continue;
Simon Atanasyan2b614e12014-02-24 22:12:11 +00001430
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001431 // Get the list of all the symbols in this section.
1432 SectionSymbolsTy &Symbols = AllSymbols[Section];
Davide Italianof0706882015-10-01 21:57:09 +00001433 std::vector<uint64_t> DataMappingSymsAddr;
1434 std::vector<uint64_t> TextMappingSymsAddr;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001435 if (isArmElf(Obj)) {
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001436 for (const auto &Symb : Symbols) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001437 uint64_t Address = std::get<0>(Symb);
1438 StringRef Name = std::get<1>(Symb);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001439 if (Name.startswith("$d"))
David Majnemer153722d2015-11-18 04:35:32 +00001440 DataMappingSymsAddr.push_back(Address - SectionAddr);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001441 if (Name.startswith("$x"))
David Majnemer153722d2015-11-18 04:35:32 +00001442 TextMappingSymsAddr.push_back(Address - SectionAddr);
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001443 if (Name.startswith("$a"))
1444 TextMappingSymsAddr.push_back(Address - SectionAddr);
1445 if (Name.startswith("$t"))
1446 TextMappingSymsAddr.push_back(Address - SectionAddr);
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001447 }
1448 }
1449
Fangrui Song0cac7262018-09-27 02:13:45 +00001450 llvm::sort(DataMappingSymsAddr);
1451 llvm::sort(TextMappingSymsAddr);
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001452
Sam Kolton3381d7a2016-10-06 13:46:08 +00001453 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1454 // AMDGPU disassembler uses symbolizer for printing labels
1455 std::unique_ptr<MCRelocationInfo> RelInfo(
1456 TheTarget->createMCRelocationInfo(TripleName, Ctx));
1457 if (RelInfo) {
1458 std::unique_ptr<MCSymbolizer> Symbolizer(
1459 TheTarget->createMCSymbolizer(
1460 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1461 DisAsm->setSymbolizer(std::move(Symbolizer));
1462 }
1463 }
1464
Michael J. Spencer51862b32011-10-13 22:17:18 +00001465 // Make a list of all the relocations for this section.
1466 std::vector<RelocationRef> Rels;
1467 if (InlineRelocs) {
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001468 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
1469 for (const RelocationRef &Reloc : RelocSec.relocations()) {
1470 Rels.push_back(Reloc);
1471 }
Michael J. Spencer51862b32011-10-13 22:17:18 +00001472 }
1473 }
1474
1475 // Sort relocations by address.
Fangrui Song0cac7262018-09-27 02:13:45 +00001476 llvm::sort(Rels, RelocAddressLess);
Michael J. Spencer51862b32011-10-13 22:17:18 +00001477
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001478 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +00001479 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001480 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +00001481 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001482 }
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001483 StringRef SectionName;
1484 error(Section.getName(SectionName));
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001485
Rafael Espindola7884c952015-06-04 15:01:05 +00001486 // If the section has no symbol at the start, just insert a dummy one.
Sam Koltonc05d7782016-08-17 10:17:57 +00001487 if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) {
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001488 Symbols.insert(
1489 Symbols.begin(),
1490 std::make_tuple(SectionAddr, SectionName,
1491 Section.isText() ? ELF::STT_FUNC : ELF::STT_OBJECT));
Sam Koltonc05d7782016-08-17 10:17:57 +00001492 }
Alp Tokere69170a2014-06-26 22:52:05 +00001493
1494 SmallString<40> Comments;
1495 raw_svector_ostream CommentStream(Comments);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001496
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001497 StringRef BytesStr;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001498 error(Section.getContents(BytesStr));
Aaron Ballman106fd7b2014-11-12 14:01:17 +00001499 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1500 BytesStr.size());
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001501
Michael J. Spencer2670c252011-01-20 06:39:06 +00001502 uint64_t Size;
1503 uint64_t Index;
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001504 bool PrintedSection = false;
Michael J. Spencer2670c252011-01-20 06:39:06 +00001505
Michael J. Spencer51862b32011-10-13 22:17:18 +00001506 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
1507 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001508 // Disassemble symbol by symbol.
1509 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001510 uint64_t Start = std::get<0>(Symbols[si]) - SectionAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001511 // The end is either the section end or the beginning of the next
1512 // symbol.
1513 uint64_t End =
Sam Koltonc05d7782016-08-17 10:17:57 +00001514 (si == se - 1) ? SectSize : std::get<0>(Symbols[si + 1]) - SectionAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001515 // Don't try to disassemble beyond the end of section contents.
1516 if (End > SectSize)
1517 End = SectSize;
Rafael Espindolae45c7402014-08-17 16:31:39 +00001518 // If this symbol has the same address as the next symbol, then skip it.
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001519 if (Start >= End)
Michael J. Spenceree84f642011-10-13 20:37:08 +00001520 continue;
1521
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001522 // Check if we need to skip symbol
1523 // Skip if the symbol's data is not between StartAddress and StopAddress
1524 if (End + SectionAddr < StartAddress ||
1525 Start + SectionAddr > StopAddress) {
1526 continue;
1527 }
1528
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001529 /// Skip if user requested specific symbols and this is not in the list
1530 if (!DisasmFuncsSet.empty() &&
1531 !DisasmFuncsSet.count(std::get<1>(Symbols[si])))
1532 continue;
1533
1534 if (!PrintedSection) {
1535 PrintedSection = true;
1536 outs() << "Disassembly of section ";
1537 if (!SegmentName.empty())
1538 outs() << SegmentName << ",";
1539 outs() << SectionName << ':';
1540 }
1541
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001542 // Stop disassembly at the stop address specified
1543 if (End + SectionAddr > StopAddress)
1544 End = StopAddress - SectionAddr;
1545
Valery Pykhtinde048052016-04-07 07:24:01 +00001546 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001547 if (std::get<2>(Symbols[si]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1548 // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)
1549 Start += 256;
1550 }
1551 if (si == se - 1 ||
1552 std::get<2>(Symbols[si + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1553 // cut trailing zeroes at the end of kernel
1554 // cut up to 256 bytes
1555 const uint64_t EndAlign = 256;
1556 const auto Limit = End - (std::min)(EndAlign, End - Start);
1557 while (End > Limit &&
1558 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1559 End -= 4;
1560 }
Valery Pykhtinde048052016-04-07 07:24:01 +00001561 }
1562
Paul Semel007dedb2018-07-18 16:39:21 +00001563 auto PrintSymbol = [](StringRef Name) {
1564 outs() << '\n' << Name << ":\n";
1565 };
1566 StringRef SymbolName = std::get<1>(Symbols[si]);
Zachary Turner030ad372018-08-20 22:18:21 +00001567 if (Demangle) {
Paul Semel007dedb2018-07-18 16:39:21 +00001568 char *DemangledSymbol = nullptr;
1569 size_t Size = 0;
Zachary Turner030ad372018-08-20 22:18:21 +00001570 int Status = -1;
1571 if (SymbolName.startswith("_Z"))
1572 DemangledSymbol = itaniumDemangle(SymbolName.data(), DemangledSymbol,
1573 &Size, &Status);
1574 else if (SymbolName.startswith("?"))
1575 DemangledSymbol = microsoftDemangle(SymbolName.data(),
1576 DemangledSymbol, &Size, &Status);
1577
1578 if (Status == 0 && DemangledSymbol)
Paul Semel007dedb2018-07-18 16:39:21 +00001579 PrintSymbol(StringRef(DemangledSymbol));
1580 else
1581 PrintSymbol(SymbolName);
1582
Zachary Turner030ad372018-08-20 22:18:21 +00001583 if (DemangledSymbol)
Paul Semel007dedb2018-07-18 16:39:21 +00001584 free(DemangledSymbol);
1585 } else
1586 PrintSymbol(SymbolName);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001587
Francis Visoiu Mistrih18346822018-04-19 17:02:57 +00001588 // Don't print raw contents of a virtual section. A virtual section
1589 // doesn't have any contents in the file.
1590 if (Section.isVirtual()) {
1591 outs() << "...\n";
1592 continue;
1593 }
1594
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001595#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +00001596 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001597#else
Mark Seaborneb03ac52014-01-25 00:32:01 +00001598 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001599#endif
1600
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001601 for (Index = Start; Index < End; Index += Size) {
1602 MCInst Inst;
Owen Andersona0c3b972011-09-15 23:38:46 +00001603
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001604 if (Index + SectionAddr < StartAddress ||
1605 Index + SectionAddr > StopAddress) {
1606 // skip byte by byte till StartAddress is reached
1607 Size = 1;
1608 continue;
1609 }
Davide Italianof0706882015-10-01 21:57:09 +00001610 // AArch64 ELF binaries can interleave data and text in the
1611 // same section. We rely on the markers introduced to
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001612 // understand what we need to dump. If the data marker is within a
1613 // function, it is denoted as a word/short etc
1614 if (isArmElf(Obj) && std::get<2>(Symbols[si]) != ELF::STT_OBJECT &&
1615 !DisassembleAll) {
Davide Italianof0706882015-10-01 21:57:09 +00001616 uint64_t Stride = 0;
1617
1618 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1619 DataMappingSymsAddr.end(), Index);
1620 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1621 // Switch to data.
1622 while (Index < End) {
1623 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1624 outs() << "\t";
1625 if (Index + 4 <= End) {
1626 Stride = 4;
1627 dumpBytes(Bytes.slice(Index, 4), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001628 outs() << "\t.word\t";
1629 uint32_t Data = 0;
1630 if (Obj->isLittleEndian()) {
1631 const auto Word =
1632 reinterpret_cast<const support::ulittle32_t *>(
1633 Bytes.data() + Index);
1634 Data = *Word;
1635 } else {
1636 const auto Word = reinterpret_cast<const support::ubig32_t *>(
1637 Bytes.data() + Index);
1638 Data = *Word;
1639 }
1640 outs() << "0x" << format("%08" PRIx32, Data);
Davide Italianof0706882015-10-01 21:57:09 +00001641 } else if (Index + 2 <= End) {
1642 Stride = 2;
1643 dumpBytes(Bytes.slice(Index, 2), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001644 outs() << "\t\t.short\t";
1645 uint16_t Data = 0;
1646 if (Obj->isLittleEndian()) {
1647 const auto Short =
1648 reinterpret_cast<const support::ulittle16_t *>(
1649 Bytes.data() + Index);
1650 Data = *Short;
1651 } else {
1652 const auto Short =
1653 reinterpret_cast<const support::ubig16_t *>(Bytes.data() +
1654 Index);
1655 Data = *Short;
1656 }
1657 outs() << "0x" << format("%04" PRIx16, Data);
Davide Italianof0706882015-10-01 21:57:09 +00001658 } else {
1659 Stride = 1;
1660 dumpBytes(Bytes.slice(Index, 1), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001661 outs() << "\t\t.byte\t";
1662 outs() << "0x" << format("%02" PRIx8, Bytes.slice(Index, 1)[0]);
Davide Italianof0706882015-10-01 21:57:09 +00001663 }
1664 Index += Stride;
1665 outs() << "\n";
1666 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1667 TextMappingSymsAddr.end(), Index);
1668 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1669 break;
1670 }
1671 }
1672 }
1673
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001674 // If there is a data symbol inside an ELF text section and we are only
1675 // disassembling text (applicable all architectures),
1676 // we are in a situation where we must print the data and not
1677 // disassemble it.
1678 if (Obj->isELF() && std::get<2>(Symbols[si]) == ELF::STT_OBJECT &&
1679 !DisassembleAll && Section.isText()) {
1680 // print out data up to 8 bytes at a time in hex and ascii
1681 uint8_t AsciiData[9] = {'\0'};
1682 uint8_t Byte;
1683 int NumBytes = 0;
1684
1685 for (Index = Start; Index < End; Index += 1) {
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001686 if (((SectionAddr + Index) < StartAddress) ||
1687 ((SectionAddr + Index) > StopAddress))
1688 continue;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001689 if (NumBytes == 0) {
1690 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1691 outs() << "\t";
1692 }
1693 Byte = Bytes.slice(Index)[0];
1694 outs() << format(" %02x", Byte);
Michael Kruse6f1da6e2018-07-26 15:31:41 +00001695 AsciiData[NumBytes] = isPrint(Byte) ? Byte : '.';
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001696
1697 uint8_t IndentOffset = 0;
1698 NumBytes++;
1699 if (Index == End - 1 || NumBytes > 8) {
1700 // Indent the space for less than 8 bytes data.
1701 // 2 spaces for byte and one for space between bytes
1702 IndentOffset = 3 * (8 - NumBytes);
1703 for (int Excess = 8 - NumBytes; Excess < 8; Excess++)
1704 AsciiData[Excess] = '\0';
1705 NumBytes = 8;
1706 }
1707 if (NumBytes == 8) {
1708 AsciiData[8] = '\0';
1709 outs() << std::string(IndentOffset, ' ') << " ";
1710 outs() << reinterpret_cast<char *>(AsciiData);
1711 outs() << '\n';
1712 NumBytes = 0;
1713 }
1714 }
1715 }
Davide Italianof0706882015-10-01 21:57:09 +00001716 if (Index >= End)
1717 break;
1718
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001719 // Disassemble a real instruction or a data when disassemble all is
1720 // provided
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001721 bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1722 SectionAddr + Index, DebugOut,
1723 CommentStream);
1724 if (Size == 0)
1725 Size = 1;
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001726
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001727 PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001728 Bytes.slice(Index, Size), SectionAddr + Index, outs(), "",
Sid Manningd9f28732018-05-14 19:46:08 +00001729 *STI, &SP, &Rels);
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001730 outs() << CommentStream.str();
1731 Comments.clear();
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001732
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001733 // Try to resolve the target of a call, tail call, etc. to a specific
1734 // symbol.
1735 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1736 MIA->isConditionalBranch(Inst))) {
1737 uint64_t Target;
1738 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1739 // In a relocatable object, the target's section must reside in
1740 // the same section as the call instruction or it is accessed
1741 // through a relocation.
1742 //
1743 // In a non-relocatable object, the target may be in any section.
1744 //
1745 // N.B. We don't walk the relocations in the relocatable case yet.
1746 auto *TargetSectionSymbols = &Symbols;
1747 if (!Obj->isRelocatableObject()) {
1748 auto SectionAddress = std::upper_bound(
1749 SectionAddresses.begin(), SectionAddresses.end(), Target,
1750 [](uint64_t LHS,
1751 const std::pair<uint64_t, SectionRef> &RHS) {
1752 return LHS < RHS.first;
1753 });
1754 if (SectionAddress != SectionAddresses.begin()) {
1755 --SectionAddress;
1756 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1757 } else {
Sterling Augustinebc78b622018-06-28 18:57:13 +00001758 TargetSectionSymbols = &AbsoluteSymbols;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001759 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001760 }
David Majnemer2603a8fa2015-07-09 18:11:40 +00001761
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001762 // Find the first symbol in the section whose offset is less than
Sterling Augustinebc78b622018-06-28 18:57:13 +00001763 // or equal to the target. If there isn't a section that contains
1764 // the target, find the nearest preceding absolute symbol.
1765 auto TargetSym = std::upper_bound(
1766 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1767 Target, [](uint64_t LHS,
1768 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1769 return LHS < std::get<0>(RHS);
1770 });
1771 if (TargetSym == TargetSectionSymbols->begin()) {
1772 TargetSectionSymbols = &AbsoluteSymbols;
1773 TargetSym = std::upper_bound(
1774 AbsoluteSymbols.begin(), AbsoluteSymbols.end(),
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001775 Target, [](uint64_t LHS,
Sam Koltonc05d7782016-08-17 10:17:57 +00001776 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
Sterling Augustinebc78b622018-06-28 18:57:13 +00001777 return LHS < std::get<0>(RHS);
1778 });
1779 }
1780 if (TargetSym != TargetSectionSymbols->begin()) {
1781 --TargetSym;
1782 uint64_t TargetAddress = std::get<0>(*TargetSym);
1783 StringRef TargetName = std::get<1>(*TargetSym);
1784 outs() << " <" << TargetName;
1785 uint64_t Disp = Target - TargetAddress;
1786 if (Disp)
1787 outs() << "+0x" << Twine::utohexstr(Disp);
1788 outs() << '>';
David Majnemer81afca62015-07-07 22:06:59 +00001789 }
1790 }
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001791 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001792 outs() << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001793
Sid Manningd9f28732018-05-14 19:46:08 +00001794 // Hexagon does this in pretty printer
1795 if (Obj->getArch() != Triple::hexagon)
1796 // Print relocation for instruction.
1797 while (rel_cur != rel_end) {
1798 bool hidden = getHidden(*rel_cur);
1799 uint64_t addr = rel_cur->getOffset();
1800 SmallString<16> name;
1801 SmallString<32> val;
Owen Andersonfa3e5202011-10-25 20:35:53 +00001802
Sid Manningd9f28732018-05-14 19:46:08 +00001803 // If this relocation is hidden, skip it.
1804 if (hidden || ((SectionAddr + addr) < StartAddress)) {
1805 ++rel_cur;
1806 continue;
1807 }
1808
1809 // Stop when rel_cur's address is past the current instruction.
1810 if (addr >= Index + Size) break;
1811 rel_cur->getTypeName(name);
1812 error(getRelocationValueString(*rel_cur, val));
1813 outs() << format(Fmt.data(), SectionAddr + addr) << name
1814 << "\t" << val << "\n";
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001815 ++rel_cur;
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001816 }
Benjamin Kramer87ee76c2011-07-20 19:37:35 +00001817 }
Michael J. Spencer2670c252011-01-20 06:39:06 +00001818 }
1819 }
1820}
1821
Kevin Enderby98da6132015-01-20 21:47:46 +00001822void llvm::PrintRelocations(const ObjectFile *Obj) {
Greg Fitzgerald18432272014-03-20 22:55:15 +00001823 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1824 "%08" PRIx64;
Rafael Espindola9219fe72016-03-21 20:59:15 +00001825 // Regular objdump doesn't print relocations in non-relocatable object
1826 // files.
1827 if (!Obj->isRelocatableObject())
1828 return;
Rafael Espindolac66d7612014-08-17 19:09:37 +00001829
Colin LeMahieu77804be2015-07-29 15:45:39 +00001830 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001831 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001832 continue;
1833 StringRef secname;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001834 error(Section.getName(secname));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001835 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001836 for (const RelocationRef &Reloc : Section.relocations()) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001837 bool hidden = getHidden(Reloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001838 uint64_t address = Reloc.getOffset();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001839 SmallString<32> relocname;
1840 SmallString<32> valuestr;
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001841 if (address < StartAddress || address > StopAddress || hidden)
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001842 continue;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001843 Reloc.getTypeName(relocname);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001844 error(getRelocationValueString(Reloc, valuestr));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001845 outs() << format(Fmt.data(), address) << " " << relocname << " "
1846 << valuestr << "\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001847 }
1848 outs() << "\n";
1849 }
1850}
1851
Paul Semelcb0f0432018-06-07 13:30:55 +00001852void llvm::PrintDynamicRelocations(const ObjectFile *Obj) {
1853
1854 // For the moment, this option is for ELF only
1855 if (!Obj->isELF())
1856 return;
1857
1858 const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj);
1859
1860 if (!Elf || Elf->getEType() != ELF::ET_DYN) {
1861 error("not a dynamic object");
1862 return;
1863 }
1864
1865 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
1866
1867 std::vector<SectionRef> DynRelSec = Obj->dynamic_relocation_sections();
1868 if (DynRelSec.empty())
1869 return;
1870
1871 outs() << "DYNAMIC RELOCATION RECORDS\n";
1872 for (const SectionRef &Section : DynRelSec) {
1873 if (Section.relocation_begin() == Section.relocation_end())
1874 continue;
1875 for (const RelocationRef &Reloc : Section.relocations()) {
1876 uint64_t address = Reloc.getOffset();
1877 SmallString<32> relocname;
1878 SmallString<32> valuestr;
1879 Reloc.getTypeName(relocname);
1880 error(getRelocationValueString(Reloc, valuestr));
1881 outs() << format(Fmt.data(), address) << " " << relocname << " "
1882 << valuestr << "\n";
1883 }
1884 }
1885}
1886
Kevin Enderby98da6132015-01-20 21:47:46 +00001887void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001888 outs() << "Sections:\n"
1889 "Idx Name Size Address Type\n";
Colin LeMahieu77804be2015-07-29 15:45:39 +00001890 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001891 StringRef Name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001892 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001893 uint64_t Address = Section.getAddress();
1894 uint64_t Size = Section.getSize();
1895 bool Text = Section.isText();
1896 bool Data = Section.isData();
1897 bool BSS = Section.isBSS();
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001898 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +00001899 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
George Rimare35e6442018-07-18 08:34:35 +00001900 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n",
George Rimarc1090da2018-07-18 09:25:36 +00001901 (unsigned)Section.getIndex(), Name.str().c_str(), Size,
1902 Address, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001903 }
1904}
1905
Kevin Enderby98da6132015-01-20 21:47:46 +00001906void llvm::PrintSectionContents(const ObjectFile *Obj) {
Rafael Espindola4453e42942014-06-13 03:07:50 +00001907 std::error_code EC;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001908 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001909 StringRef Name;
1910 StringRef Contents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001911 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001912 uint64_t BaseAddr = Section.getAddress();
David Majnemer185b5b12014-11-11 09:58:25 +00001913 uint64_t Size = Section.getSize();
1914 if (!Size)
1915 continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001916
1917 outs() << "Contents of section " << Name << ":\n";
David Majnemer185b5b12014-11-11 09:58:25 +00001918 if (Section.isBSS()) {
Alexey Samsonov209095c2013-04-16 10:53:11 +00001919 outs() << format("<skipping contents of bss section at [%04" PRIx64
David Majnemer8f6b04c2014-07-14 16:20:14 +00001920 ", %04" PRIx64 ")>\n",
1921 BaseAddr, BaseAddr + Size);
Alexey Samsonov209095c2013-04-16 10:53:11 +00001922 continue;
1923 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001924
Davide Italianoccd53fe2015-08-05 07:18:31 +00001925 error(Section.getContents(Contents));
David Majnemer8f6b04c2014-07-14 16:20:14 +00001926
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001927 // Dump out the content as hex and printable ascii characters.
1928 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer82803112012-03-10 02:04:38 +00001929 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001930 // Dump line of hex.
1931 for (std::size_t i = 0; i < 16; ++i) {
1932 if (i != 0 && i % 4 == 0)
1933 outs() << ' ';
1934 if (addr + i < end)
1935 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1936 << hexdigit(Contents[addr + i] & 0xF, true);
1937 else
1938 outs() << " ";
1939 }
1940 // Print ascii.
1941 outs() << " ";
1942 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
Michael Kruse6f1da6e2018-07-26 15:31:41 +00001943 if (isPrint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001944 outs() << Contents[addr + i];
1945 else
1946 outs() << ".";
1947 }
1948 outs() << "\n";
1949 }
1950 }
1951}
1952
Kevin Enderby9acb1092016-05-31 20:35:34 +00001953void llvm::PrintSymbolTable(const ObjectFile *o, StringRef ArchiveName,
1954 StringRef ArchitectureName) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001955 outs() << "SYMBOL TABLE:\n";
1956
Rui Ueyama4e39f712014-03-18 18:58:51 +00001957 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
Davide Italianoe85abf72015-12-20 09:54:34 +00001958 printCOFFSymbolTable(coff);
Rui Ueyama4e39f712014-03-18 18:58:51 +00001959 return;
1960 }
1961 for (const SymbolRef &Symbol : o->symbols()) {
Kevin Enderby931cb652016-06-24 18:24:42 +00001962 Expected<uint64_t> AddressOrError = Symbol.getAddress();
1963 if (!AddressOrError)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001964 report_error(ArchiveName, o->getFileName(), AddressOrError.takeError(),
1965 ArchitectureName);
Rafael Espindolaed067c42015-07-03 18:19:00 +00001966 uint64_t Address = *AddressOrError;
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001967 if ((Address < StartAddress) || (Address > StopAddress))
1968 continue;
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001969 Expected<SymbolRef::Type> TypeOrError = Symbol.getType();
1970 if (!TypeOrError)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001971 report_error(ArchiveName, o->getFileName(), TypeOrError.takeError(),
1972 ArchitectureName);
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00001973 SymbolRef::Type Type = *TypeOrError;
Rui Ueyama4e39f712014-03-18 18:58:51 +00001974 uint32_t Flags = Symbol.getFlags();
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001975 Expected<section_iterator> SectionOrErr = Symbol.getSection();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001976 if (!SectionOrErr)
1977 report_error(ArchiveName, o->getFileName(), SectionOrErr.takeError(),
1978 ArchitectureName);
Rafael Espindola8bab8892015-08-07 23:27:14 +00001979 section_iterator Section = *SectionOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001980 StringRef Name;
1981 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1982 Section->getName(Name);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001983 } else {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001984 Expected<StringRef> NameOrErr = Symbol.getName();
1985 if (!NameOrErr)
Kevin Enderby9acb1092016-05-31 20:35:34 +00001986 report_error(ArchiveName, o->getFileName(), NameOrErr.takeError(),
1987 ArchitectureName);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001988 Name = *NameOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001989 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001990
Rui Ueyama4e39f712014-03-18 18:58:51 +00001991 bool Global = Flags & SymbolRef::SF_Global;
1992 bool Weak = Flags & SymbolRef::SF_Weak;
1993 bool Absolute = Flags & SymbolRef::SF_Absolute;
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001994 bool Common = Flags & SymbolRef::SF_Common;
Davide Italianocd2514d2015-04-30 23:08:53 +00001995 bool Hidden = Flags & SymbolRef::SF_Hidden;
David Meyer1df4b842012-02-28 23:47:53 +00001996
Rui Ueyama4e39f712014-03-18 18:58:51 +00001997 char GlobLoc = ' ';
1998 if (Type != SymbolRef::ST_Unknown)
1999 GlobLoc = Global ? 'g' : 'l';
2000 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
2001 ? 'd' : ' ';
2002 char FileFunc = ' ';
2003 if (Type == SymbolRef::ST_File)
2004 FileFunc = 'f';
2005 else if (Type == SymbolRef::ST_Function)
2006 FileFunc = 'F';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002007
Rui Ueyama4e39f712014-03-18 18:58:51 +00002008 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
2009 "%08" PRIx64;
Michael J. Spencerd857c1c2013-01-10 22:40:50 +00002010
Rui Ueyama4e39f712014-03-18 18:58:51 +00002011 outs() << format(Fmt, Address) << " "
2012 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
2013 << (Weak ? 'w' : ' ') // Weak?
2014 << ' ' // Constructor. Not supported yet.
2015 << ' ' // Warning. Not supported yet.
2016 << ' ' // Indirect reference to another symbol.
2017 << Debug // Debugging (d) or dynamic (D) symbol.
2018 << FileFunc // Name of function (F), file (f) or object (O).
2019 << ' ';
2020 if (Absolute) {
2021 outs() << "*ABS*";
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00002022 } else if (Common) {
2023 outs() << "*COM*";
Rui Ueyama4e39f712014-03-18 18:58:51 +00002024 } else if (Section == o->section_end()) {
2025 outs() << "*UND*";
2026 } else {
2027 if (const MachOObjectFile *MachO =
2028 dyn_cast<const MachOObjectFile>(o)) {
2029 DataRefImpl DR = Section->getRawDataRefImpl();
2030 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
2031 outs() << SegmentName << ",";
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002032 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00002033 StringRef SectionName;
Davide Italianoccd53fe2015-08-05 07:18:31 +00002034 error(Section->getName(SectionName));
Rui Ueyama4e39f712014-03-18 18:58:51 +00002035 outs() << SectionName;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002036 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00002037
2038 outs() << '\t';
Rafael Espindolaae3ac082015-06-23 18:34:25 +00002039 if (Common || isa<ELFObjectFileBase>(o)) {
Rafael Espindoladbb6bd32015-06-25 22:10:04 +00002040 uint64_t Val =
2041 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
Rafael Espindolaae3ac082015-06-23 18:34:25 +00002042 outs() << format("\t %08" PRIx64 " ", Val);
2043 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00002044
Davide Italianocd2514d2015-04-30 23:08:53 +00002045 if (Hidden) {
2046 outs() << ".hidden ";
2047 }
2048 outs() << Name
Rui Ueyama4e39f712014-03-18 18:58:51 +00002049 << '\n';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002050 }
2051}
2052
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00002053static void PrintUnwindInfo(const ObjectFile *o) {
2054 outs() << "Unwind info:\n\n";
2055
2056 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
2057 printCOFFUnwindInfo(coff);
Tim Northover4bd286a2014-08-01 13:07:19 +00002058 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
2059 printMachOUnwindInfo(MachO);
2060 else {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00002061 // TODO: Extract DWARF dump tool to objdump.
2062 errs() << "This operation is only currently supported "
Tim Northover4bd286a2014-08-01 13:07:19 +00002063 "for COFF and MachO object files.\n";
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00002064 return;
2065 }
2066}
2067
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002068void llvm::printExportsTrie(const ObjectFile *o) {
Nick Kledzikd04bc352014-08-30 00:20:14 +00002069 outs() << "Exports trie:\n";
2070 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
2071 printMachOExportsTrie(MachO);
2072 else {
2073 errs() << "This operation is only currently supported "
2074 "for Mach-O executable files.\n";
2075 return;
2076 }
2077}
2078
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002079void llvm::printRebaseTable(ObjectFile *o) {
Nick Kledzikac431442014-09-12 21:34:15 +00002080 outs() << "Rebase table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002081 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzikac431442014-09-12 21:34:15 +00002082 printMachORebaseTable(MachO);
2083 else {
2084 errs() << "This operation is only currently supported "
2085 "for Mach-O executable files.\n";
2086 return;
2087 }
2088}
2089
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002090void llvm::printBindTable(ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00002091 outs() << "Bind table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002092 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzik56ebef42014-09-16 01:41:51 +00002093 printMachOBindTable(MachO);
2094 else {
2095 errs() << "This operation is only currently supported "
2096 "for Mach-O executable files.\n";
2097 return;
2098 }
2099}
2100
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002101void llvm::printLazyBindTable(ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00002102 outs() << "Lazy bind table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002103 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzik56ebef42014-09-16 01:41:51 +00002104 printMachOLazyBindTable(MachO);
2105 else {
2106 errs() << "This operation is only currently supported "
2107 "for Mach-O executable files.\n";
2108 return;
2109 }
2110}
2111
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002112void llvm::printWeakBindTable(ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00002113 outs() << "Weak bind table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002114 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzik56ebef42014-09-16 01:41:51 +00002115 printMachOWeakBindTable(MachO);
2116 else {
2117 errs() << "This operation is only currently supported "
2118 "for Mach-O executable files.\n";
2119 return;
2120 }
2121}
Nick Kledzikac431442014-09-12 21:34:15 +00002122
Adrian Prantl437105a2015-07-08 02:04:15 +00002123/// Dump the raw contents of the __clangast section so the output can be piped
2124/// into llvm-bcanalyzer.
2125void llvm::printRawClangAST(const ObjectFile *Obj) {
2126 if (outs().is_displayed()) {
2127 errs() << "The -raw-clang-ast option will dump the raw binary contents of "
2128 "the clang ast section.\n"
2129 "Please redirect the output to a file or another program such as "
2130 "llvm-bcanalyzer.\n";
2131 return;
2132 }
2133
2134 StringRef ClangASTSectionName("__clangast");
2135 if (isa<COFFObjectFile>(Obj)) {
2136 ClangASTSectionName = "clangast";
2137 }
2138
2139 Optional<object::SectionRef> ClangASTSection;
Colin LeMahieu77804be2015-07-29 15:45:39 +00002140 for (auto Sec : ToolSectionFilter(*Obj)) {
Adrian Prantl437105a2015-07-08 02:04:15 +00002141 StringRef Name;
2142 Sec.getName(Name);
2143 if (Name == ClangASTSectionName) {
2144 ClangASTSection = Sec;
2145 break;
2146 }
2147 }
2148 if (!ClangASTSection)
2149 return;
2150
2151 StringRef ClangASTContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00002152 error(ClangASTSection.getValue().getContents(ClangASTContents));
Adrian Prantl437105a2015-07-08 02:04:15 +00002153 outs().write(ClangASTContents.data(), ClangASTContents.size());
2154}
2155
Sanjoy Das6f567a42015-06-22 18:03:02 +00002156static void printFaultMaps(const ObjectFile *Obj) {
2157 const char *FaultMapSectionName = nullptr;
2158
2159 if (isa<ELFObjectFileBase>(Obj)) {
2160 FaultMapSectionName = ".llvm_faultmaps";
2161 } else if (isa<MachOObjectFile>(Obj)) {
2162 FaultMapSectionName = "__llvm_faultmaps";
2163 } else {
2164 errs() << "This operation is only currently supported "
2165 "for ELF and Mach-O executable files.\n";
2166 return;
2167 }
2168
2169 Optional<object::SectionRef> FaultMapSection;
2170
Colin LeMahieu77804be2015-07-29 15:45:39 +00002171 for (auto Sec : ToolSectionFilter(*Obj)) {
Sanjoy Das6f567a42015-06-22 18:03:02 +00002172 StringRef Name;
2173 Sec.getName(Name);
2174 if (Name == FaultMapSectionName) {
2175 FaultMapSection = Sec;
2176 break;
2177 }
2178 }
2179
2180 outs() << "FaultMap table:\n";
2181
2182 if (!FaultMapSection.hasValue()) {
2183 outs() << "<not found>\n";
2184 return;
2185 }
2186
2187 StringRef FaultMapContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00002188 error(FaultMapSection.getValue().getContents(FaultMapContents));
Sanjoy Das6f567a42015-06-22 18:03:02 +00002189
2190 FaultMapParser FMP(FaultMapContents.bytes_begin(),
2191 FaultMapContents.bytes_end());
2192
2193 outs() << FMP;
2194}
2195
Davide Italiano1bdaa202016-09-18 04:39:15 +00002196static void printPrivateFileHeaders(const ObjectFile *o, bool onlyFirst) {
Paul Semel0913dcd2018-07-25 11:09:20 +00002197 if (o->isELF()) {
2198 printELFFileHeader(o);
2199 return printELFDynamicSection(o);
2200 }
Davide Italiano1bdaa202016-09-18 04:39:15 +00002201 if (o->isCOFF())
2202 return printCOFFFileHeader(o);
Derek Schuff2c6f75d2016-11-30 16:49:11 +00002203 if (o->isWasm())
2204 return printWasmFileHeader(o);
Davide Italiano1bdaa202016-09-18 04:39:15 +00002205 if (o->isMachO()) {
Kevin Enderby0ae163f2016-01-13 00:25:36 +00002206 printMachOFileHeader(o);
Davide Italiano1bdaa202016-09-18 04:39:15 +00002207 if (!onlyFirst)
2208 printMachOLoadCommands(o);
2209 return;
2210 }
Kevin Enderby7fa40c92016-11-16 22:17:38 +00002211 report_error(o->getFileName(), "Invalid/Unsupported object file format");
Rui Ueyamac2bed422013-09-27 21:04:00 +00002212}
2213
Paul Semeld2af4d62018-07-04 15:25:03 +00002214static void printFileHeaders(const ObjectFile *o) {
2215 if (!o->isELF() && !o->isCOFF())
2216 report_error(o->getFileName(), "Invalid/Unsupported object file format");
2217
2218 Triple::ArchType AT = o->getArch();
2219 outs() << "architecture: " << Triple::getArchTypeName(AT) << "\n";
2220 Expected<uint64_t> StartAddrOrErr = o->getStartAddress();
2221 if (!StartAddrOrErr)
2222 report_error(o->getFileName(), StartAddrOrErr.takeError());
Petar Jovanovic8d947ba2018-10-19 22:16:49 +00002223
2224 StringRef Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
2225 uint64_t Address = StartAddrOrErr.get();
Paul Semeld2af4d62018-07-04 15:25:03 +00002226 outs() << "start address: "
Petar Jovanovic8d947ba2018-10-19 22:16:49 +00002227 << "0x" << format(Fmt.data(), Address)
Paul Semeld2af4d62018-07-04 15:25:03 +00002228 << "\n";
2229}
2230
Paul Semel0dc92f62018-07-05 14:43:29 +00002231static void printArchiveChild(StringRef Filename, const Archive::Child &C) {
2232 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
2233 if (!ModeOrErr) {
2234 errs() << "ill-formed archive entry.\n";
2235 consumeError(ModeOrErr.takeError());
2236 return;
2237 }
2238 sys::fs::perms Mode = ModeOrErr.get();
2239 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
2240 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
2241 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
2242 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
2243 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
2244 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
2245 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
2246 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
2247 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
2248
2249 outs() << " ";
2250
2251 Expected<unsigned> UIDOrErr = C.getUID();
2252 if (!UIDOrErr)
2253 report_error(Filename, UIDOrErr.takeError());
2254 unsigned UID = UIDOrErr.get();
2255 outs() << format("%d/", UID);
2256
2257 Expected<unsigned> GIDOrErr = C.getGID();
2258 if (!GIDOrErr)
2259 report_error(Filename, GIDOrErr.takeError());
2260 unsigned GID = GIDOrErr.get();
2261 outs() << format("%-d ", GID);
2262
2263 Expected<uint64_t> Size = C.getRawSize();
2264 if (!Size)
2265 report_error(Filename, Size.takeError());
2266 outs() << format("%6" PRId64, Size.get()) << " ";
2267
2268 StringRef RawLastModified = C.getRawLastModified();
2269 unsigned Seconds;
2270 if (RawLastModified.getAsInteger(10, Seconds))
2271 outs() << "(date: \"" << RawLastModified
2272 << "\" contains non-decimal chars) ";
2273 else {
2274 // Since ctime(3) returns a 26 character string of the form:
2275 // "Sun Sep 16 01:03:52 1973\n\0"
2276 // just print 24 characters.
2277 time_t t = Seconds;
2278 outs() << format("%.24s ", ctime(&t));
2279 }
2280
2281 StringRef Name = "";
2282 Expected<StringRef> NameOrErr = C.getName();
2283 if (!NameOrErr) {
2284 consumeError(NameOrErr.takeError());
2285 Expected<StringRef> RawNameOrErr = C.getRawName();
2286 if (!RawNameOrErr)
2287 report_error(Filename, NameOrErr.takeError());
2288 Name = RawNameOrErr.get();
2289 } else {
2290 Name = NameOrErr.get();
2291 }
2292 outs() << Name << "\n";
2293}
2294
2295static void DumpObject(ObjectFile *o, const Archive *a = nullptr,
2296 const Archive::Child *c = nullptr) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002297 StringRef ArchiveName = a != nullptr ? a->getFileName() : "";
Adrian Prantl437105a2015-07-08 02:04:15 +00002298 // Avoid other output when using a raw option.
2299 if (!RawClangAST) {
2300 outs() << '\n';
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002301 if (a)
2302 outs() << a->getFileName() << "(" << o->getFileName() << ")";
2303 else
2304 outs() << o->getFileName();
2305 outs() << ":\tfile format " << o->getFileFormatName() << "\n\n";
Adrian Prantl437105a2015-07-08 02:04:15 +00002306 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00002307
Paul Semel0dc92f62018-07-05 14:43:29 +00002308 if (ArchiveHeaders && !MachOOpt)
2309 printArchiveChild(a->getFileName(), *c);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002310 if (Disassemble)
Michael J. Spencer51862b32011-10-13 22:17:18 +00002311 DisassembleObject(o, Relocations);
2312 if (Relocations && !Disassemble)
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002313 PrintRelocations(o);
Paul Semelcb0f0432018-06-07 13:30:55 +00002314 if (DynamicRelocations)
2315 PrintDynamicRelocations(o);
Nick Lewyckyfcf84622011-10-10 21:21:34 +00002316 if (SectionHeaders)
2317 PrintSectionHeaders(o);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00002318 if (SectionContents)
2319 PrintSectionContents(o);
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002320 if (SymbolTable)
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002321 PrintSymbolTable(o, ArchiveName);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00002322 if (UnwindInfo)
2323 PrintUnwindInfo(o);
Davide Italiano1bdaa202016-09-18 04:39:15 +00002324 if (PrivateHeaders || FirstPrivateHeader)
2325 printPrivateFileHeaders(o, FirstPrivateHeader);
Paul Semeld2af4d62018-07-04 15:25:03 +00002326 if (FileHeaders)
2327 printFileHeaders(o);
Nick Kledzikd04bc352014-08-30 00:20:14 +00002328 if (ExportsTrie)
2329 printExportsTrie(o);
Nick Kledzikac431442014-09-12 21:34:15 +00002330 if (Rebase)
2331 printRebaseTable(o);
Nick Kledzik56ebef42014-09-16 01:41:51 +00002332 if (Bind)
2333 printBindTable(o);
2334 if (LazyBind)
2335 printLazyBindTable(o);
2336 if (WeakBind)
2337 printWeakBindTable(o);
Adrian Prantl437105a2015-07-08 02:04:15 +00002338 if (RawClangAST)
2339 printRawClangAST(o);
Sanjoy Das6f567a42015-06-22 18:03:02 +00002340 if (PrintFaultMaps)
2341 printFaultMaps(o);
Igor Laevsky03a670c2016-01-26 15:09:42 +00002342 if (DwarfDumpType != DIDT_Null) {
Rafael Espindolac398e672017-07-19 22:27:28 +00002343 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*o);
Igor Laevsky03a670c2016-01-26 15:09:42 +00002344 // Dump the complete DWARF structure.
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00002345 DIDumpOptions DumpOpts;
2346 DumpOpts.DumpType = DwarfDumpType;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00002347 DICtx->dump(outs(), DumpOpts);
Igor Laevsky03a670c2016-01-26 15:09:42 +00002348 }
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002349}
2350
Paul Semel0dc92f62018-07-05 14:43:29 +00002351static void DumpObject(const COFFImportFile *I, const Archive *A,
2352 const Archive::Child *C = nullptr) {
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00002353 StringRef ArchiveName = A ? A->getFileName() : "";
2354
2355 // Avoid other output when using a raw option.
2356 if (!RawClangAST)
2357 outs() << '\n'
2358 << ArchiveName << "(" << I->getFileName() << ")"
2359 << ":\tfile format COFF-import-file"
2360 << "\n\n";
2361
Paul Semel0dc92f62018-07-05 14:43:29 +00002362 if (ArchiveHeaders && !MachOOpt)
2363 printArchiveChild(A->getFileName(), *C);
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00002364 if (SymbolTable)
2365 printCOFFSymbolTable(I);
2366}
2367
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +00002368/// Dump each object file in \a a;
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002369static void DumpArchive(const Archive *a) {
Mehdi Amini41af4302016-11-11 04:28:40 +00002370 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00002371 for (auto &C : a->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002372 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2373 if (!ChildOrErr) {
2374 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2375 report_error(a->getFileName(), C, std::move(E));
2376 continue;
2377 }
Rafael Espindolaae460022014-06-16 16:08:36 +00002378 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
Paul Semel0dc92f62018-07-05 14:43:29 +00002379 DumpObject(o, a, &C);
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00002380 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
Paul Semel0dc92f62018-07-05 14:43:29 +00002381 DumpObject(I, a, &C);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002382 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00002383 report_error(a->getFileName(), object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002384 }
Lang Hamesfc209622016-07-14 02:24:01 +00002385 if (Err)
2386 report_error(a->getFileName(), std::move(Err));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002387}
2388
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +00002389/// Open file and figure out how to dump it.
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002390static void DumpInput(StringRef file) {
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002391
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002392 // If we are using the Mach-O specific object file parser, then let it parse
2393 // the file and process the command line options. So the -arch flags can
2394 // be used to select specific slices, etc.
2395 if (MachOOpt) {
2396 ParseInputMachO(file);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002397 return;
2398 }
2399
2400 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00002401 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
2402 if (!BinaryOrErr)
Kevin Enderbyb34e3a12016-05-05 17:43:35 +00002403 report_error(file, BinaryOrErr.takeError());
Rafael Espindola48af1c22014-08-19 18:44:46 +00002404 Binary &Binary = *BinaryOrErr.get().getBinary();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002405
Rafael Espindola3f6481d2014-08-01 14:31:55 +00002406 if (Archive *a = dyn_cast<Archive>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002407 DumpArchive(a);
Rafael Espindola3f6481d2014-08-01 14:31:55 +00002408 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002409 DumpObject(o);
Dave Lee3fb120f2018-08-03 00:06:38 +00002410 else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Binary))
2411 ParseInputMachO(UB);
Jim Grosbachaf9aec02012-08-07 17:53:14 +00002412 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00002413 report_error(file, object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002414}
2415
Michael J. Spencer2670c252011-01-20 06:39:06 +00002416int main(int argc, char **argv) {
Rui Ueyama197194b2018-04-13 18:26:06 +00002417 InitLLVM X(argc, argv);
Michael J. Spencer2670c252011-01-20 06:39:06 +00002418
2419 // Initialize targets and assembly printers/parsers.
2420 llvm::InitializeAllTargetInfos();
Evan Cheng8c886a42011-07-22 21:58:54 +00002421 llvm::InitializeAllTargetMCs();
Michael J. Spencer2670c252011-01-20 06:39:06 +00002422 llvm::InitializeAllDisassemblers();
2423
Pete Cooper28fb4fc2012-05-03 23:20:10 +00002424 // Register the target printer for --version.
2425 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
2426
Michael J. Spencer2670c252011-01-20 06:39:06 +00002427 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
Michael J. Spencer2670c252011-01-20 06:39:06 +00002428
2429 ToolName = argv[0];
2430
2431 // Defaults to a.out if no filenames specified.
2432 if (InputFilenames.size() == 0)
2433 InputFilenames.push_back("a.out");
2434
Fangrui Song8513cd42018-06-27 20:45:11 +00002435 if (AllHeaders)
2436 PrivateHeaders = Relocations = SectionHeaders = SymbolTable = true;
2437
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00002438 if (DisassembleAll || PrintSource || PrintLines)
Colin LeMahieuf34933e2015-07-23 20:58:49 +00002439 Disassemble = true;
Paul Semel007dedb2018-07-18 16:39:21 +00002440
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002441 if (!Disassemble
2442 && !Relocations
Paul Semelcb0f0432018-06-07 13:30:55 +00002443 && !DynamicRelocations
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002444 && !SectionHeaders
2445 && !SectionContents
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00002446 && !SymbolTable
Michael J. Spencer209565db2013-01-06 03:56:49 +00002447 && !UnwindInfo
Nick Kledzikd04bc352014-08-30 00:20:14 +00002448 && !PrivateHeaders
Paul Semeld2af4d62018-07-04 15:25:03 +00002449 && !FileHeaders
Kevin Enderby0ae163f2016-01-13 00:25:36 +00002450 && !FirstPrivateHeader
Nick Kledzikac431442014-09-12 21:34:15 +00002451 && !ExportsTrie
Nick Kledzik56ebef42014-09-16 01:41:51 +00002452 && !Rebase
2453 && !Bind
2454 && !LazyBind
Kevin Enderby131d1772015-01-09 19:22:37 +00002455 && !WeakBind
Adrian Prantl437105a2015-07-08 02:04:15 +00002456 && !RawClangAST
Kevin Enderby13023a12015-01-15 23:19:11 +00002457 && !(UniversalHeaders && MachOOpt)
Paul Semel0dc92f62018-07-05 14:43:29 +00002458 && !ArchiveHeaders
Kevin Enderby69fe98d2015-01-23 18:52:17 +00002459 && !(IndirectSymbols && MachOOpt)
Kevin Enderby9a509442015-01-27 21:28:24 +00002460 && !(DataInCode && MachOOpt)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002461 && !(LinkOptHints && MachOOpt)
Kevin Enderbycd66be52015-03-11 22:06:32 +00002462 && !(InfoPlist && MachOOpt)
Kevin Enderbybc847fa2015-03-16 20:08:09 +00002463 && !(DylibsUsed && MachOOpt)
2464 && !(DylibId && MachOOpt)
Kevin Enderby0fc11822015-04-01 20:57:01 +00002465 && !(ObjcMetaData && MachOOpt)
Colin LeMahieufcc32762015-07-29 19:08:10 +00002466 && !(FilterSections.size() != 0 && MachOOpt)
Igor Laevsky03a670c2016-01-26 15:09:42 +00002467 && !PrintFaultMaps
2468 && DwarfDumpType == DIDT_Null) {
Michael J. Spencer2670c252011-01-20 06:39:06 +00002469 cl::PrintHelpMessage();
Dimitry Andrice4f5d012017-12-18 19:46:56 +00002470 return 2;
2471 }
2472
Rafael Aulerb0e4b912018-03-09 19:13:44 +00002473 DisasmFuncsSet.insert(DisassembleFunctions.begin(),
2474 DisassembleFunctions.end());
2475
Dimitry Andrice4f5d012017-12-18 19:46:56 +00002476 llvm::for_each(InputFilenames, DumpInput);
2477
2478 return EXIT_SUCCESS;
2479}