blob: 463408b60c5a0072940aad22374d4720d2f902b5 [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>
James Hendersonb55b6582018-10-29 10:05:39 +0000119 llvm::SectionContents("full-contents",
120 cl::desc("Display the content of each section"));
121static cl::alias SectionContentsShort("s",
122 cl::desc("Alias for --full-contents"),
123 cl::aliasopt(SectionContents));
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000124
Kevin Enderby98da6132015-01-20 21:47:46 +0000125cl::opt<bool>
126llvm::SymbolTable("t", cl::desc("Display the symbol table"));
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000127
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000128cl::opt<bool>
129llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
Nick Kledzikd04bc352014-08-30 00:20:14 +0000130
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000131cl::opt<bool>
132llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
Nick Kledzikac431442014-09-12 21:34:15 +0000133
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000134cl::opt<bool>
135llvm::Bind("bind", cl::desc("Display mach-o binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000136
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000137cl::opt<bool>
138llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000139
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000140cl::opt<bool>
141llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000142
Adrian Prantl437105a2015-07-08 02:04:15 +0000143cl::opt<bool>
144llvm::RawClangAST("raw-clang-ast",
145 cl::desc("Dump the raw binary contents of the clang AST section"));
146
Nick Kledzik56ebef42014-09-16 01:41:51 +0000147static cl::opt<bool>
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000148MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000149static cl::alias
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000150MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
Benjamin Kramer87ee76c2011-07-20 19:37:35 +0000151
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000152cl::opt<std::string>
153llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
154 "see -version for available targets"));
155
156cl::opt<std::string>
Kevin Enderbyc9595622014-08-06 23:24:41 +0000157llvm::MCPU("mcpu",
158 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
159 cl::value_desc("cpu-name"),
160 cl::init(""));
161
162cl::opt<std::string>
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000163llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
Michael J. Spencer2670c252011-01-20 06:39:06 +0000164 "see -version for available targets"));
165
Kevin Enderby98da6132015-01-20 21:47:46 +0000166cl::opt<bool>
167llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
168 "headers for each section."));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000169static cl::alias
170SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
171 cl::aliasopt(SectionHeaders));
172static cl::alias
173SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
174 cl::aliasopt(SectionHeaders));
Colin LeMahieufcc32762015-07-29 19:08:10 +0000175
Colin LeMahieu77804be2015-07-29 15:45:39 +0000176cl::list<std::string>
Colin LeMahieufcc32762015-07-29 19:08:10 +0000177llvm::FilterSections("section", cl::desc("Operate on the specified sections only. "
178 "With -macho dump segment,section"));
179cl::alias
180static FilterSectionsj("j", cl::desc("Alias for --section"),
181 cl::aliasopt(llvm::FilterSections));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000182
Kevin Enderbyc9595622014-08-06 23:24:41 +0000183cl::list<std::string>
184llvm::MAttrs("mattr",
Jack Carter551efd72012-08-28 19:24:49 +0000185 cl::CommaSeparated,
186 cl::desc("Target specific attributes"),
187 cl::value_desc("a1,+a2,-a3,..."));
188
Kevin Enderbybf246f52014-09-24 23:08:22 +0000189cl::opt<bool>
190llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
191 "instructions, do not print "
192 "the instruction bytes."));
Saleem Abdulrasooldea14b22017-02-08 18:11:31 +0000193cl::opt<bool>
194llvm::NoLeadingAddr("no-leading-addr", cl::desc("Print no leading address"));
Eli Bendersky3a6808c2012-11-20 22:57:02 +0000195
Kevin Enderby98da6132015-01-20 21:47:46 +0000196cl::opt<bool>
197llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000198
199static cl::alias
200UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
201 cl::aliasopt(UnwindInfo));
202
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000203cl::opt<bool>
204llvm::PrivateHeaders("private-headers",
205 cl::desc("Display format specific file headers"));
Michael J. Spencer209565db2013-01-06 03:56:49 +0000206
Kevin Enderby0ae163f2016-01-13 00:25:36 +0000207cl::opt<bool>
208llvm::FirstPrivateHeader("private-header",
209 cl::desc("Display only the first format specific file "
210 "header"));
211
Michael J. Spencer209565db2013-01-06 03:56:49 +0000212static cl::alias
213PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
214 cl::aliasopt(PrivateHeaders));
215
Paul Semeld2af4d62018-07-04 15:25:03 +0000216cl::opt<bool> llvm::FileHeaders(
217 "file-headers",
218 cl::desc("Display the contents of the overall file header"));
219
220static cl::alias FileHeadersShort("f", cl::desc("Alias for --file-headers"),
221 cl::aliasopt(FileHeaders));
222
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000223cl::opt<bool>
Paul Semel0dc92f62018-07-05 14:43:29 +0000224 llvm::ArchiveHeaders("archive-headers",
225 cl::desc("Display archive header information"));
226
227cl::alias
228ArchiveHeadersShort("a", cl::desc("Alias for --archive-headers"),
229 cl::aliasopt(ArchiveHeaders));
230
231cl::opt<bool>
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000232 llvm::PrintImmHex("print-imm-hex",
Colin LeMahieuefe37322016-04-08 18:15:37 +0000233 cl::desc("Use hex format for immediate values"));
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000234
Sanjoy Das6f567a42015-06-22 18:03:02 +0000235cl::opt<bool> PrintFaultMaps("fault-map-section",
236 cl::desc("Display contents of faultmap section"));
237
Igor Laevsky03a670c2016-01-26 15:09:42 +0000238cl::opt<DIDumpType> llvm::DwarfDumpType(
239 "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"),
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000240 cl::values(clEnumValN(DIDT_DebugFrame, "frames", ".debug_frame")));
Igor Laevsky03a670c2016-01-26 15:09:42 +0000241
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000242cl::opt<bool> PrintSource(
243 "source",
244 cl::desc(
Alex Denisova07169e2018-02-02 19:20:37 +0000245 "Display source inlined with disassembly. Implies disassemble object"));
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000246
247cl::alias PrintSourceShort("S", cl::desc("Alias for -source"),
248 cl::aliasopt(PrintSource));
249
250cl::opt<bool> PrintLines("line-numbers",
251 cl::desc("Display source line numbers with "
252 "disassembly. Implies disassemble object"));
253
254cl::alias PrintLinesShort("l", cl::desc("Alias for -line-numbers"),
255 cl::aliasopt(PrintLines));
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +0000256
257cl::opt<unsigned long long>
258 StartAddress("start-address", cl::desc("Disassemble beginning at address"),
259 cl::value_desc("address"), cl::init(0));
260cl::opt<unsigned long long>
261 StopAddress("stop-address", cl::desc("Stop disassembly at address"),
262 cl::value_desc("address"), cl::init(UINT64_MAX));
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000263static StringRef ToolName;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000264
Sam Parker5fba45a2017-02-08 09:44:18 +0000265typedef std::vector<std::tuple<uint64_t, StringRef, uint8_t>> SectionSymbolsTy;
266
Colin LeMahieu77804be2015-07-29 15:45:39 +0000267namespace {
Colin LeMahieufcc32762015-07-29 19:08:10 +0000268typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate;
Colin LeMahieu77804be2015-07-29 15:45:39 +0000269
270class SectionFilterIterator {
271public:
272 SectionFilterIterator(FilterPredicate P,
273 llvm::object::section_iterator const &I,
274 llvm::object::section_iterator const &E)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000275 : Predicate(std::move(P)), Iterator(I), End(E) {
Colin LeMahieu77804be2015-07-29 15:45:39 +0000276 ScanPredicate();
277 }
Benjamin Kramerac9257b2015-09-24 14:52:52 +0000278 const llvm::object::SectionRef &operator*() const { return *Iterator; }
Colin LeMahieu77804be2015-07-29 15:45:39 +0000279 SectionFilterIterator &operator++() {
280 ++Iterator;
281 ScanPredicate();
282 return *this;
283 }
284 bool operator!=(SectionFilterIterator const &Other) const {
285 return Iterator != Other.Iterator;
286 }
287
288private:
289 void ScanPredicate() {
Colin LeMahieuda1723f2015-07-29 19:21:13 +0000290 while (Iterator != End && !Predicate(*Iterator)) {
Colin LeMahieu77804be2015-07-29 15:45:39 +0000291 ++Iterator;
292 }
293 }
294 FilterPredicate Predicate;
295 llvm::object::section_iterator Iterator;
296 llvm::object::section_iterator End;
297};
298
299class SectionFilter {
300public:
301 SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000302 : Predicate(std::move(P)), Object(O) {}
Colin LeMahieu77804be2015-07-29 15:45:39 +0000303 SectionFilterIterator begin() {
304 return SectionFilterIterator(Predicate, Object.section_begin(),
305 Object.section_end());
306 }
307 SectionFilterIterator end() {
308 return SectionFilterIterator(Predicate, Object.section_end(),
309 Object.section_end());
310 }
311
312private:
313 FilterPredicate Predicate;
314 llvm::object::ObjectFile const &Object;
315};
316SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) {
David Majnemer42531262016-08-12 03:55:06 +0000317 return SectionFilter(
318 [](llvm::object::SectionRef const &S) {
319 if (FilterSections.empty())
320 return true;
321 llvm::StringRef String;
322 std::error_code error = S.getName(String);
323 if (error)
324 return false;
325 return is_contained(FilterSections, String);
326 },
327 O);
Colin LeMahieu77804be2015-07-29 15:45:39 +0000328}
329}
330
Davide Italianoccd53fe2015-08-05 07:18:31 +0000331void llvm::error(std::error_code EC) {
Mark Seaborneb03ac52014-01-25 00:32:01 +0000332 if (!EC)
Davide Italianoccd53fe2015-08-05 07:18:31 +0000333 return;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000334
Davide Italiano140af642015-12-25 18:16:45 +0000335 errs() << ToolName << ": error reading file: " << EC.message() << ".\n";
336 errs().flush();
Davide Italiano7f6c3012015-08-06 00:18:52 +0000337 exit(1);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000338}
339
Kevin Enderby42398052016-06-28 23:16:13 +0000340LLVM_ATTRIBUTE_NORETURN void llvm::error(Twine Message) {
341 errs() << ToolName << ": " << Message << ".\n";
342 errs().flush();
343 exit(1);
344}
345
Paul Semel007dedb2018-07-18 16:39:21 +0000346void llvm::warn(StringRef Message) {
347 errs() << ToolName << ": warning: " << Message << ".\n";
348 errs().flush();
349}
350
Davide Italianoed9d95b2015-12-29 13:41:02 +0000351LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000352 Twine Message) {
353 errs() << ToolName << ": '" << File << "': " << Message << ".\n";
354 exit(1);
355}
356
357LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
Davide Italianoed9d95b2015-12-29 13:41:02 +0000358 std::error_code EC) {
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000359 assert(EC);
360 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
Davide Italianoccd53fe2015-08-05 07:18:31 +0000361 exit(1);
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000362}
363
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000364LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
365 llvm::Error E) {
366 assert(E);
367 std::string Buf;
368 raw_string_ostream OS(Buf);
369 logAllUnhandledErrors(std::move(E), OS, "");
370 OS.flush();
Kevin Enderbyb34e3a12016-05-05 17:43:35 +0000371 errs() << ToolName << ": '" << File << "': " << Buf;
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000372 exit(1);
373}
374
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000375LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
376 StringRef FileName,
Kevin Enderby9acb1092016-05-31 20:35:34 +0000377 llvm::Error E,
378 StringRef ArchitectureName) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000379 assert(E);
380 errs() << ToolName << ": ";
381 if (ArchiveName != "")
382 errs() << ArchiveName << "(" << FileName << ")";
383 else
Justin Bogner31d8b7d2016-10-26 22:37:52 +0000384 errs() << "'" << FileName << "'";
Kevin Enderby9acb1092016-05-31 20:35:34 +0000385 if (!ArchitectureName.empty())
386 errs() << " (for architecture " << ArchitectureName << ")";
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000387 std::string Buf;
388 raw_string_ostream OS(Buf);
389 logAllUnhandledErrors(std::move(E), OS, "");
390 OS.flush();
Justin Bogner31d8b7d2016-10-26 22:37:52 +0000391 errs() << ": " << Buf;
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000392 exit(1);
393}
394
395LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
396 const object::Archive::Child &C,
Kevin Enderby9acb1092016-05-31 20:35:34 +0000397 llvm::Error E,
398 StringRef ArchitectureName) {
Kevin Enderbyf4586032016-07-29 17:44:13 +0000399 Expected<StringRef> NameOrErr = C.getName();
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000400 // TODO: if we have a error getting the name then it would be nice to print
401 // the index of which archive member this is and or its offset in the
402 // archive instead of "???" as the name.
Kevin Enderbyf4586032016-07-29 17:44:13 +0000403 if (!NameOrErr) {
404 consumeError(NameOrErr.takeError());
Kevin Enderby9acb1092016-05-31 20:35:34 +0000405 llvm::report_error(ArchiveName, "???", std::move(E), ArchitectureName);
Kevin Enderbyf4586032016-07-29 17:44:13 +0000406 } else
Kevin Enderby9acb1092016-05-31 20:35:34 +0000407 llvm::report_error(ArchiveName, NameOrErr.get(), std::move(E),
408 ArchitectureName);
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000409}
410
Craig Toppere6cb63e2014-04-25 04:24:47 +0000411static const Target *getTarget(const ObjectFile *Obj = nullptr) {
Michael J. Spencer2670c252011-01-20 06:39:06 +0000412 // Figure out the target triple.
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000413 llvm::Triple TheTriple("unknown-unknown-unknown");
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000414 if (TripleName.empty()) {
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000415 if (Obj) {
Vlad Tsyrklevichde620462017-09-19 02:22:48 +0000416 TheTriple = Obj->makeTriple();
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000417 }
Sam Parkerdf7c6ef2017-01-18 13:52:12 +0000418 } else {
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000419 TheTriple.setTriple(Triple::normalize(TripleName));
Vlad Tsyrklevichde620462017-09-19 02:22:48 +0000420
Sam Parkerdf7c6ef2017-01-18 13:52:12 +0000421 // Use the triple, but also try to combine with ARM build attributes.
422 if (Obj) {
423 auto Arch = Obj->getArch();
424 if (Arch == Triple::arm || Arch == Triple::armeb) {
425 Obj->setARMSubArch(TheTriple);
426 }
427 }
428 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000429
430 // Get the target specific parser.
431 std::string Error;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000432 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
433 Error);
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000434 if (!TheTarget) {
435 if (Obj)
436 report_error(Obj->getFileName(), "can't find target: " + Error);
437 else
438 error("can't find target: " + Error);
439 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000440
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000441 // Update the triple name and return the found target.
442 TripleName = TheTriple.getTriple();
443 return TheTarget;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000444}
445
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000446bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
Rafael Espindola704cd842015-07-06 15:47:43 +0000447 return a.getOffset() < b.getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +0000448}
449
Rafael Espindola37070a52015-06-03 04:48:06 +0000450template <class ELFT>
Rafael Espindola37070a52015-06-03 04:48:06 +0000451static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000452 const RelocationRef &RelRef,
Rafael Espindola37070a52015-06-03 04:48:06 +0000453 SmallVectorImpl<char> &Result) {
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000454 DataRefImpl Rel = RelRef.getRawDataRefImpl();
455
Rafael Espindola37070a52015-06-03 04:48:06 +0000456 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
457 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000458 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
459
Rafael Espindola37070a52015-06-03 04:48:06 +0000460 const ELFFile<ELFT> &EF = *Obj->getELFFile();
461
Davide Italiano6cf09262016-11-16 05:10:28 +0000462 auto SecOrErr = EF.getSection(Rel.d.a);
463 if (!SecOrErr)
464 return errorToErrorCode(SecOrErr.takeError());
Rafael Espindola6def3042015-07-01 12:56:27 +0000465 const Elf_Shdr *Sec = *SecOrErr;
Davide Italiano6cf09262016-11-16 05:10:28 +0000466 auto SymTabOrErr = EF.getSection(Sec->sh_link);
467 if (!SymTabOrErr)
468 return errorToErrorCode(SymTabOrErr.takeError());
Rafael Espindola6def3042015-07-01 12:56:27 +0000469 const Elf_Shdr *SymTab = *SymTabOrErr;
Rafael Espindola719dc7c2015-06-29 12:38:31 +0000470 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
471 SymTab->sh_type == ELF::SHT_DYNSYM);
Davide Italiano6cf09262016-11-16 05:10:28 +0000472 auto StrTabSec = EF.getSection(SymTab->sh_link);
473 if (!StrTabSec)
474 return errorToErrorCode(StrTabSec.takeError());
475 auto StrTabOrErr = EF.getStringTable(*StrTabSec);
476 if (!StrTabOrErr)
477 return errorToErrorCode(StrTabOrErr.takeError());
Rafael Espindola6a1bfb22015-06-29 14:39:25 +0000478 StringRef StrTab = *StrTabOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000479 int64_t addend = 0;
Paul Semelcb0f0432018-06-07 13:30:55 +0000480 // If there is no Symbol associated with the relocation, we set the undef
481 // boolean value to 'true'. This will prevent us from calling functions that
482 // requires the relocation to be associated with a symbol.
483 bool undef = false;
Rafael Espindola6def3042015-07-01 12:56:27 +0000484 switch (Sec->sh_type) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000485 default:
486 return object_error::parse_failed;
487 case ELF::SHT_REL: {
Rafael Espindola37070a52015-06-03 04:48:06 +0000488 // TODO: Read implicit addend from section data.
489 break;
490 }
491 case ELF::SHT_RELA: {
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000492 const Elf_Rela *ERela = Obj->getRela(Rel);
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000493 addend = ERela->r_addend;
Paul Semelcb0f0432018-06-07 13:30:55 +0000494 undef = ERela->getSymbol(false) == 0;
Rafael Espindola37070a52015-06-03 04:48:06 +0000495 break;
496 }
497 }
Rafael Espindola75d5b542015-06-03 05:14:22 +0000498 StringRef Target;
Paul Semelcb0f0432018-06-07 13:30:55 +0000499 if (!undef) {
500 symbol_iterator SI = RelRef.getSymbol();
501 const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
502 if (symb->getType() == ELF::STT_SECTION) {
503 Expected<section_iterator> SymSI = SI->getSection();
504 if (!SymSI)
505 return errorToErrorCode(SymSI.takeError());
506 const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
507 auto SecName = EF.getSectionName(SymSec);
508 if (!SecName)
509 return errorToErrorCode(SecName.takeError());
510 Target = *SecName;
511 } else {
512 Expected<StringRef> SymName = symb->getName(StrTab);
513 if (!SymName)
514 return errorToErrorCode(SymName.takeError());
515 Target = *SymName;
516 }
517 } else
518 Target = "*ABS*";
Daniel Cedermand72b9fd2018-06-01 05:31:58 +0000519
520 // Default scheme is to print Target, as well as "+ <addend>" for nonzero
521 // addend. Should be acceptable for all normal purposes.
522 std::string fmtbuf;
523 raw_string_ostream fmt(fmtbuf);
524 fmt << Target;
525 if (addend != 0)
526 fmt << (addend < 0 ? "" : "+") << addend;
527 fmt.flush();
528 Result.append(fmtbuf.begin(), fmtbuf.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000529 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000530}
531
532static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000533 const RelocationRef &Rel,
Rafael Espindola37070a52015-06-03 04:48:06 +0000534 SmallVectorImpl<char> &Result) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000535 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
536 return getRelocationValueString(ELF32LE, Rel, Result);
537 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
538 return getRelocationValueString(ELF64LE, Rel, Result);
539 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
540 return getRelocationValueString(ELF32BE, Rel, Result);
541 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
542 return getRelocationValueString(ELF64BE, Rel, Result);
543}
544
545static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
546 const RelocationRef &Rel,
547 SmallVectorImpl<char> &Result) {
548 symbol_iterator SymI = Rel.getSymbol();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000549 Expected<StringRef> SymNameOrErr = SymI->getName();
550 if (!SymNameOrErr)
551 return errorToErrorCode(SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000552 StringRef SymName = *SymNameOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000553 Result.append(SymName.begin(), SymName.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000554 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000555}
556
557static void printRelocationTargetName(const MachOObjectFile *O,
558 const MachO::any_relocation_info &RE,
559 raw_string_ostream &fmt) {
560 bool IsScattered = O->isRelocationScattered(RE);
561
562 // Target of a scattered relocation is an address. In the interest of
563 // generating pretty output, scan through the symbol table looking for a
564 // symbol that aligns with that address. If we find one, print it.
565 // Otherwise, we just print the hex address of the target.
566 if (IsScattered) {
567 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
568
569 for (const SymbolRef &Symbol : O->symbols()) {
570 std::error_code ec;
Kevin Enderby931cb652016-06-24 18:24:42 +0000571 Expected<uint64_t> Addr = Symbol.getAddress();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000572 if (!Addr)
573 report_error(O->getFileName(), Addr.takeError());
Rafael Espindolaed067c42015-07-03 18:19:00 +0000574 if (*Addr != Val)
Rafael Espindola37070a52015-06-03 04:48:06 +0000575 continue;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000576 Expected<StringRef> Name = Symbol.getName();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000577 if (!Name)
578 report_error(O->getFileName(), Name.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000579 fmt << *Name;
Rafael Espindola37070a52015-06-03 04:48:06 +0000580 return;
581 }
582
583 // If we couldn't find a symbol that this relocation refers to, try
584 // to find a section beginning instead.
Colin LeMahieu77804be2015-07-29 15:45:39 +0000585 for (const SectionRef &Section : ToolSectionFilter(*O)) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000586 std::error_code ec;
587
588 StringRef Name;
589 uint64_t Addr = Section.getAddress();
590 if (Addr != Val)
591 continue;
592 if ((ec = Section.getName(Name)))
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000593 report_error(O->getFileName(), ec);
Rafael Espindola37070a52015-06-03 04:48:06 +0000594 fmt << Name;
595 return;
596 }
597
598 fmt << format("0x%x", Val);
599 return;
600 }
601
602 StringRef S;
603 bool isExtern = O->getPlainRelocationExternal(RE);
604 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
605
Martin Storsjo8c0317d2017-07-13 17:03:02 +0000606 if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND) {
Simon Dardis38867052017-08-07 12:29:38 +0000607 fmt << format("0x%0" PRIx64, Val);
Martin Storsjo8c0317d2017-07-13 17:03:02 +0000608 return;
609 } else if (isExtern) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000610 symbol_iterator SI = O->symbol_begin();
611 advance(SI, Val);
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000612 Expected<StringRef> SOrErr = SI->getName();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000613 if (!SOrErr)
614 report_error(O->getFileName(), SOrErr.takeError());
Davide Italianoccd53fe2015-08-05 07:18:31 +0000615 S = *SOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000616 } else {
617 section_iterator SI = O->section_begin();
618 // Adjust for the fact that sections are 1-indexed.
Kevin Enderby3fc91882017-11-03 21:32:44 +0000619 if (Val == 0) {
620 fmt << "0 (?,?)";
621 return;
622 }
623 uint32_t i = Val - 1;
624 while (i != 0 && SI != O->section_end()) {
625 i--;
626 advance(SI, 1);
627 }
628 if (SI == O->section_end())
629 fmt << Val << " (?,?)";
630 else
631 SI->getName(S);
Rafael Espindola37070a52015-06-03 04:48:06 +0000632 }
633
634 fmt << S;
635}
636
Sam Clegg4df5d762017-06-27 20:40:53 +0000637static std::error_code getRelocationValueString(const WasmObjectFile *Obj,
638 const RelocationRef &RelRef,
639 SmallVectorImpl<char> &Result) {
640 const wasm::WasmRelocation& Rel = Obj->getWasmRelocation(RelRef);
Sam Cleggf676cdd2018-04-26 16:41:51 +0000641 symbol_iterator SI = RelRef.getSymbol();
Sam Clegg4df5d762017-06-27 20:40:53 +0000642 std::string fmtbuf;
643 raw_string_ostream fmt(fmtbuf);
Sam Clegg8c4b0ce2018-04-26 17:05:04 +0000644 if (SI == Obj->symbol_end()) {
645 // Not all wasm relocations have symbols associated with them.
646 // In particular R_WEBASSEMBLY_TYPE_INDEX_LEB.
Sam Cleggf676cdd2018-04-26 16:41:51 +0000647 fmt << Rel.Index;
648 } else {
Sam Clegg8c4b0ce2018-04-26 17:05:04 +0000649 Expected<StringRef> SymNameOrErr = SI->getName();
650 if (!SymNameOrErr)
651 return errorToErrorCode(SymNameOrErr.takeError());
Sam Cleggf676cdd2018-04-26 16:41:51 +0000652 StringRef SymName = *SymNameOrErr;
653 Result.append(SymName.begin(), SymName.end());
654 }
655 fmt << (Rel.Addend < 0 ? "" : "+") << Rel.Addend;
Sam Clegg4df5d762017-06-27 20:40:53 +0000656 fmt.flush();
657 Result.append(fmtbuf.begin(), fmtbuf.end());
658 return std::error_code();
659}
660
Rafael Espindola37070a52015-06-03 04:48:06 +0000661static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
662 const RelocationRef &RelRef,
663 SmallVectorImpl<char> &Result) {
664 DataRefImpl Rel = RelRef.getRawDataRefImpl();
665 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
666
667 unsigned Arch = Obj->getArch();
668
669 std::string fmtbuf;
670 raw_string_ostream fmt(fmtbuf);
671 unsigned Type = Obj->getAnyRelocationType(RE);
672 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
673
674 // Determine any addends that should be displayed with the relocation.
675 // These require decoding the relocation type, which is triple-specific.
676
677 // X86_64 has entirely custom relocation types.
678 if (Arch == Triple::x86_64) {
679 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
680
681 switch (Type) {
682 case MachO::X86_64_RELOC_GOT_LOAD:
683 case MachO::X86_64_RELOC_GOT: {
684 printRelocationTargetName(Obj, RE, fmt);
685 fmt << "@GOT";
686 if (isPCRel)
687 fmt << "PCREL";
688 break;
689 }
690 case MachO::X86_64_RELOC_SUBTRACTOR: {
691 DataRefImpl RelNext = Rel;
692 Obj->moveRelocationNext(RelNext);
693 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
694
695 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
696 // X86_64_RELOC_UNSIGNED.
697 // NOTE: Scattered relocations don't exist on x86_64.
698 unsigned RType = Obj->getAnyRelocationType(RENext);
699 if (RType != MachO::X86_64_RELOC_UNSIGNED)
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000700 report_error(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
701 "X86_64_RELOC_SUBTRACTOR.");
Rafael Espindola37070a52015-06-03 04:48:06 +0000702
703 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
704 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
705 printRelocationTargetName(Obj, RENext, fmt);
706 fmt << "-";
707 printRelocationTargetName(Obj, RE, fmt);
708 break;
709 }
710 case MachO::X86_64_RELOC_TLV:
711 printRelocationTargetName(Obj, RE, fmt);
712 fmt << "@TLV";
713 if (isPCRel)
714 fmt << "P";
715 break;
716 case MachO::X86_64_RELOC_SIGNED_1:
717 printRelocationTargetName(Obj, RE, fmt);
718 fmt << "-1";
719 break;
720 case MachO::X86_64_RELOC_SIGNED_2:
721 printRelocationTargetName(Obj, RE, fmt);
722 fmt << "-2";
723 break;
724 case MachO::X86_64_RELOC_SIGNED_4:
725 printRelocationTargetName(Obj, RE, fmt);
726 fmt << "-4";
727 break;
728 default:
729 printRelocationTargetName(Obj, RE, fmt);
730 break;
731 }
732 // X86 and ARM share some relocation types in common.
733 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
734 Arch == Triple::ppc) {
735 // Generic relocation types...
736 switch (Type) {
737 case MachO::GENERIC_RELOC_PAIR: // prints no info
Rui Ueyama7d099192015-06-09 15:20:42 +0000738 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000739 case MachO::GENERIC_RELOC_SECTDIFF: {
740 DataRefImpl RelNext = Rel;
741 Obj->moveRelocationNext(RelNext);
742 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
743
744 // X86 sect diff's must be followed by a relocation of type
745 // GENERIC_RELOC_PAIR.
746 unsigned RType = Obj->getAnyRelocationType(RENext);
747
748 if (RType != MachO::GENERIC_RELOC_PAIR)
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000749 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
750 "GENERIC_RELOC_SECTDIFF.");
Rafael Espindola37070a52015-06-03 04:48:06 +0000751
752 printRelocationTargetName(Obj, RE, fmt);
753 fmt << "-";
754 printRelocationTargetName(Obj, RENext, fmt);
755 break;
756 }
757 }
758
759 if (Arch == Triple::x86 || Arch == Triple::ppc) {
760 switch (Type) {
761 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
762 DataRefImpl RelNext = Rel;
763 Obj->moveRelocationNext(RelNext);
764 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
765
766 // X86 sect diff's must be followed by a relocation of type
767 // GENERIC_RELOC_PAIR.
768 unsigned RType = Obj->getAnyRelocationType(RENext);
769 if (RType != MachO::GENERIC_RELOC_PAIR)
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000770 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
771 "GENERIC_RELOC_LOCAL_SECTDIFF.");
Rafael Espindola37070a52015-06-03 04:48:06 +0000772
773 printRelocationTargetName(Obj, RE, fmt);
774 fmt << "-";
775 printRelocationTargetName(Obj, RENext, fmt);
776 break;
777 }
778 case MachO::GENERIC_RELOC_TLV: {
779 printRelocationTargetName(Obj, RE, fmt);
780 fmt << "@TLV";
781 if (IsPCRel)
782 fmt << "P";
783 break;
784 }
785 default:
786 printRelocationTargetName(Obj, RE, fmt);
787 }
788 } else { // ARM-specific relocations
789 switch (Type) {
790 case MachO::ARM_RELOC_HALF:
791 case MachO::ARM_RELOC_HALF_SECTDIFF: {
792 // Half relocations steal a bit from the length field to encode
793 // whether this is an upper16 or a lower16 relocation.
Martin Storsjofa5183b2017-07-13 05:54:08 +0000794 bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
Rafael Espindola37070a52015-06-03 04:48:06 +0000795
796 if (isUpper)
797 fmt << ":upper16:(";
798 else
799 fmt << ":lower16:(";
800 printRelocationTargetName(Obj, RE, fmt);
801
802 DataRefImpl RelNext = Rel;
803 Obj->moveRelocationNext(RelNext);
804 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
805
806 // ARM half relocs must be followed by a relocation of type
807 // ARM_RELOC_PAIR.
808 unsigned RType = Obj->getAnyRelocationType(RENext);
809 if (RType != MachO::ARM_RELOC_PAIR)
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000810 report_error(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
811 "ARM_RELOC_HALF");
Rafael Espindola37070a52015-06-03 04:48:06 +0000812
813 // NOTE: The half of the target virtual address is stashed in the
814 // address field of the secondary relocation, but we can't reverse
815 // engineer the constant offset from it without decoding the movw/movt
816 // instruction to find the other half in its immediate field.
817
818 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
819 // symbol/section pointer of the follow-on relocation.
820 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
821 fmt << "-";
822 printRelocationTargetName(Obj, RENext, fmt);
823 }
824
825 fmt << ")";
826 break;
827 }
828 default: { printRelocationTargetName(Obj, RE, fmt); }
829 }
830 }
831 } else
832 printRelocationTargetName(Obj, RE, fmt);
833
834 fmt.flush();
835 Result.append(fmtbuf.begin(), fmtbuf.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000836 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000837}
838
839static std::error_code getRelocationValueString(const RelocationRef &Rel,
840 SmallVectorImpl<char> &Result) {
Rafael Espindola854038e2015-06-26 14:51:16 +0000841 const ObjectFile *Obj = Rel.getObject();
Rafael Espindola37070a52015-06-03 04:48:06 +0000842 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
843 return getRelocationValueString(ELF, Rel, Result);
844 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
845 return getRelocationValueString(COFF, Rel, Result);
Sam Clegg4df5d762017-06-27 20:40:53 +0000846 if (auto *Wasm = dyn_cast<WasmObjectFile>(Obj))
847 return getRelocationValueString(Wasm, Rel, Result);
848 if (auto *MachO = dyn_cast<MachOObjectFile>(Obj))
849 return getRelocationValueString(MachO, Rel, Result);
850 llvm_unreachable("unknown object file format");
Rafael Espindola37070a52015-06-03 04:48:06 +0000851}
852
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000853/// Indicates whether this relocation should hidden when listing
Rafael Espindola0ad71d92015-06-30 03:41:26 +0000854/// relocations, usually because it is the trailing part of a multipart
855/// relocation that will be printed as part of the leading relocation.
856static bool getHidden(RelocationRef RelRef) {
857 const ObjectFile *Obj = RelRef.getObject();
858 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
859 if (!MachO)
860 return false;
861
862 unsigned Arch = MachO->getArch();
863 DataRefImpl Rel = RelRef.getRawDataRefImpl();
864 uint64_t Type = MachO->getRelocationType(Rel);
865
866 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
867 // is always hidden.
868 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
869 if (Type == MachO::GENERIC_RELOC_PAIR)
870 return true;
871 } else if (Arch == Triple::x86_64) {
872 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
873 // an X86_64_RELOC_SUBTRACTOR.
874 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
875 DataRefImpl RelPrev = Rel;
876 RelPrev.d.a--;
877 uint64_t PrevType = MachO->getRelocationType(RelPrev);
878 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
879 return true;
880 }
881 }
882
883 return false;
884}
885
Sid Manningd9f28732018-05-14 19:46:08 +0000886namespace {
887class SourcePrinter {
888protected:
889 DILineInfo OldLineInfo;
890 const ObjectFile *Obj = nullptr;
891 std::unique_ptr<symbolize::LLVMSymbolizer> Symbolizer;
892 // File name to file contents of source
893 std::unordered_map<std::string, std::unique_ptr<MemoryBuffer>> SourceCache;
894 // Mark the line endings of the cached source
895 std::unordered_map<std::string, std::vector<StringRef>> LineCache;
896
897private:
898 bool cacheSource(const DILineInfo& LineInfoFile);
899
900public:
901 SourcePrinter() = default;
902 SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch) : Obj(Obj) {
903 symbolize::LLVMSymbolizer::Options SymbolizerOpts(
904 DILineInfoSpecifier::FunctionNameKind::None, true, false, false,
905 DefaultArch);
906 Symbolizer.reset(new symbolize::LLVMSymbolizer(SymbolizerOpts));
907 }
908 virtual ~SourcePrinter() = default;
909 virtual void printSourceLine(raw_ostream &OS, uint64_t Address,
910 StringRef Delimiter = "; ");
911};
912
913bool SourcePrinter::cacheSource(const DILineInfo &LineInfo) {
914 std::unique_ptr<MemoryBuffer> Buffer;
915 if (LineInfo.Source) {
916 Buffer = MemoryBuffer::getMemBuffer(*LineInfo.Source);
917 } else {
918 auto BufferOrError = MemoryBuffer::getFile(LineInfo.FileName);
919 if (!BufferOrError)
920 return false;
921 Buffer = std::move(*BufferOrError);
922 }
923 // Chomp the file to get lines
924 size_t BufferSize = Buffer->getBufferSize();
925 const char *BufferStart = Buffer->getBufferStart();
926 for (const char *Start = BufferStart, *End = BufferStart;
927 End < BufferStart + BufferSize; End++)
928 if (*End == '\n' || End == BufferStart + BufferSize - 1 ||
929 (*End == '\r' && *(End + 1) == '\n')) {
930 LineCache[LineInfo.FileName].push_back(StringRef(Start, End - Start));
931 if (*End == '\r')
932 End++;
933 Start = End + 1;
934 }
935 SourceCache[LineInfo.FileName] = std::move(Buffer);
936 return true;
937}
938
939void SourcePrinter::printSourceLine(raw_ostream &OS, uint64_t Address,
940 StringRef Delimiter) {
941 if (!Symbolizer)
942 return;
943 DILineInfo LineInfo = DILineInfo();
944 auto ExpectecLineInfo =
945 Symbolizer->symbolizeCode(Obj->getFileName(), Address);
946 if (!ExpectecLineInfo)
947 consumeError(ExpectecLineInfo.takeError());
948 else
949 LineInfo = *ExpectecLineInfo;
950
951 if ((LineInfo.FileName == "<invalid>") || OldLineInfo.Line == LineInfo.Line ||
952 LineInfo.Line == 0)
953 return;
954
955 if (PrintLines)
956 OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line << "\n";
957 if (PrintSource) {
958 if (SourceCache.find(LineInfo.FileName) == SourceCache.end())
959 if (!cacheSource(LineInfo))
960 return;
961 auto FileBuffer = SourceCache.find(LineInfo.FileName);
962 if (FileBuffer != SourceCache.end()) {
963 auto LineBuffer = LineCache.find(LineInfo.FileName);
964 if (LineBuffer != LineCache.end()) {
965 if (LineInfo.Line > LineBuffer->second.size())
966 return;
967 // Vector begins at 0, line numbers are non-zero
968 OS << Delimiter << LineBuffer->second[LineInfo.Line - 1].ltrim()
969 << "\n";
970 }
971 }
972 }
973 OldLineInfo = LineInfo;
974}
975
976static bool isArmElf(const ObjectFile *Obj) {
977 return (Obj->isELF() &&
978 (Obj->getArch() == Triple::aarch64 ||
979 Obj->getArch() == Triple::aarch64_be ||
980 Obj->getArch() == Triple::arm || Obj->getArch() == Triple::armeb ||
981 Obj->getArch() == Triple::thumb ||
982 Obj->getArch() == Triple::thumbeb));
983}
984
985class PrettyPrinter {
986public:
987 virtual ~PrettyPrinter() = default;
988 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
989 ArrayRef<uint8_t> Bytes, uint64_t Address,
990 raw_ostream &OS, StringRef Annot,
991 MCSubtargetInfo const &STI, SourcePrinter *SP,
992 std::vector<RelocationRef> *Rels = nullptr) {
993 if (SP && (PrintSource || PrintLines))
994 SP->printSourceLine(OS, Address);
995 if (!NoLeadingAddr)
996 OS << format("%8" PRIx64 ":", Address);
997 if (!NoShowRawInsn) {
998 OS << "\t";
999 dumpBytes(Bytes, OS);
1000 }
1001 if (MI)
1002 IP.printInst(MI, OS, "", STI);
1003 else
1004 OS << " <unknown>";
1005 }
1006};
1007PrettyPrinter PrettyPrinterInst;
1008class HexagonPrettyPrinter : public PrettyPrinter {
1009public:
1010 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
1011 raw_ostream &OS) {
1012 uint32_t opcode =
1013 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
1014 if (!NoLeadingAddr)
1015 OS << format("%8" PRIx64 ":", Address);
1016 if (!NoShowRawInsn) {
1017 OS << "\t";
1018 dumpBytes(Bytes.slice(0, 4), OS);
1019 OS << format("%08" PRIx32, opcode);
1020 }
1021 }
1022 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1023 uint64_t Address, raw_ostream &OS, StringRef Annot,
1024 MCSubtargetInfo const &STI, SourcePrinter *SP,
1025 std::vector<RelocationRef> *Rels) override {
1026 if (SP && (PrintSource || PrintLines))
1027 SP->printSourceLine(OS, Address, "");
1028 if (!MI) {
1029 printLead(Bytes, Address, OS);
1030 OS << " <unknown>";
1031 return;
1032 }
1033 std::string Buffer;
1034 {
1035 raw_string_ostream TempStream(Buffer);
1036 IP.printInst(MI, TempStream, "", STI);
1037 }
1038 StringRef Contents(Buffer);
1039 // Split off bundle attributes
1040 auto PacketBundle = Contents.rsplit('\n');
1041 // Split off first instruction from the rest
1042 auto HeadTail = PacketBundle.first.split('\n');
1043 auto Preamble = " { ";
1044 auto Separator = "";
1045 StringRef Fmt = "\t\t\t%08" PRIx64 ": ";
1046 std::vector<RelocationRef>::const_iterator rel_cur = Rels->begin();
1047 std::vector<RelocationRef>::const_iterator rel_end = Rels->end();
1048
1049 // Hexagon's packets require relocations to be inline rather than
1050 // clustered at the end of the packet.
1051 auto PrintReloc = [&]() -> void {
1052 while ((rel_cur != rel_end) && (rel_cur->getOffset() <= Address)) {
1053 if (rel_cur->getOffset() == Address) {
1054 SmallString<16> name;
1055 SmallString<32> val;
1056 rel_cur->getTypeName(name);
1057 error(getRelocationValueString(*rel_cur, val));
1058 OS << Separator << format(Fmt.data(), Address) << name << "\t" << val
1059 << "\n";
1060 return;
1061 }
1062 rel_cur++;
1063 }
1064 };
1065
1066 while(!HeadTail.first.empty()) {
1067 OS << Separator;
1068 Separator = "\n";
1069 if (SP && (PrintSource || PrintLines))
1070 SP->printSourceLine(OS, Address, "");
1071 printLead(Bytes, Address, OS);
1072 OS << Preamble;
1073 Preamble = " ";
1074 StringRef Inst;
1075 auto Duplex = HeadTail.first.split('\v');
1076 if(!Duplex.second.empty()){
1077 OS << Duplex.first;
1078 OS << "; ";
1079 Inst = Duplex.second;
1080 }
1081 else
1082 Inst = HeadTail.first;
1083 OS << Inst;
1084 HeadTail = HeadTail.second.split('\n');
1085 if (HeadTail.first.empty())
1086 OS << " } " << PacketBundle.second;
1087 PrintReloc();
1088 Bytes = Bytes.slice(4);
1089 Address += 4;
1090 }
1091 }
1092};
1093HexagonPrettyPrinter HexagonPrettyPrinterInst;
1094
1095class AMDGCNPrettyPrinter : public PrettyPrinter {
1096public:
1097 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1098 uint64_t Address, raw_ostream &OS, StringRef Annot,
1099 MCSubtargetInfo const &STI, SourcePrinter *SP,
1100 std::vector<RelocationRef> *Rels) override {
1101 if (SP && (PrintSource || PrintLines))
1102 SP->printSourceLine(OS, Address);
1103
1104 typedef support::ulittle32_t U32;
1105
1106 if (MI) {
1107 SmallString<40> InstStr;
1108 raw_svector_ostream IS(InstStr);
1109
1110 IP.printInst(MI, IS, "", STI);
1111
1112 OS << left_justify(IS.str(), 60);
1113 } else {
1114 // an unrecognized encoding - this is probably data so represent it
1115 // using the .long directive, or .byte directive if fewer than 4 bytes
1116 // remaining
1117 if (Bytes.size() >= 4) {
1118 OS << format("\t.long 0x%08" PRIx32 " ",
1119 static_cast<uint32_t>(*reinterpret_cast<const U32*>(Bytes.data())));
1120 OS.indent(42);
1121 } else {
1122 OS << format("\t.byte 0x%02" PRIx8, Bytes[0]);
1123 for (unsigned int i = 1; i < Bytes.size(); i++)
1124 OS << format(", 0x%02" PRIx8, Bytes[i]);
1125 OS.indent(55 - (6 * Bytes.size()));
1126 }
1127 }
1128
1129 OS << format("// %012" PRIX64 ": ", Address);
1130 if (Bytes.size() >=4) {
1131 for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
1132 Bytes.size() / sizeof(U32)))
1133 // D should be explicitly casted to uint32_t here as it is passed
1134 // by format to snprintf as vararg.
1135 OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D));
1136 } else {
1137 for (unsigned int i = 0; i < Bytes.size(); i++)
1138 OS << format("%02" PRIX8 " ", Bytes[i]);
1139 }
1140
1141 if (!Annot.empty())
1142 OS << "// " << Annot;
1143 }
1144};
1145AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
1146
1147class BPFPrettyPrinter : public PrettyPrinter {
1148public:
1149 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1150 uint64_t Address, raw_ostream &OS, StringRef Annot,
1151 MCSubtargetInfo const &STI, SourcePrinter *SP,
1152 std::vector<RelocationRef> *Rels) override {
1153 if (SP && (PrintSource || PrintLines))
1154 SP->printSourceLine(OS, Address);
1155 if (!NoLeadingAddr)
1156 OS << format("%8" PRId64 ":", Address / 8);
1157 if (!NoShowRawInsn) {
1158 OS << "\t";
1159 dumpBytes(Bytes, OS);
1160 }
1161 if (MI)
1162 IP.printInst(MI, OS, "", STI);
1163 else
1164 OS << " <unknown>";
1165 }
1166};
1167BPFPrettyPrinter BPFPrettyPrinterInst;
1168
1169PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
1170 switch(Triple.getArch()) {
1171 default:
1172 return PrettyPrinterInst;
1173 case Triple::hexagon:
1174 return HexagonPrettyPrinterInst;
1175 case Triple::amdgcn:
1176 return AMDGCNPrettyPrinterInst;
1177 case Triple::bpfel:
1178 case Triple::bpfeb:
1179 return BPFPrettyPrinterInst;
1180 }
1181}
1182}
1183
Sam Koltonc05d7782016-08-17 10:17:57 +00001184static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) {
1185 assert(Obj->isELF());
1186 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1187 return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1188 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1189 return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1190 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1191 return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1192 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1193 return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1194 llvm_unreachable("Unsupported binary format");
1195}
1196
Sam Parker5fba45a2017-02-08 09:44:18 +00001197template <class ELFT> static void
1198addDynamicElfSymbols(const ELFObjectFile<ELFT> *Obj,
1199 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1200 for (auto Symbol : Obj->getDynamicSymbolIterators()) {
1201 uint8_t SymbolType = Symbol.getELFType();
1202 if (SymbolType != ELF::STT_FUNC || Symbol.getSize() == 0)
1203 continue;
1204
1205 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
1206 if (!AddressOrErr)
1207 report_error(Obj->getFileName(), AddressOrErr.takeError());
1208 uint64_t Address = *AddressOrErr;
1209
1210 Expected<StringRef> Name = Symbol.getName();
1211 if (!Name)
1212 report_error(Obj->getFileName(), Name.takeError());
1213 if (Name->empty())
1214 continue;
1215
1216 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1217 if (!SectionOrErr)
1218 report_error(Obj->getFileName(), SectionOrErr.takeError());
1219 section_iterator SecI = *SectionOrErr;
1220 if (SecI == Obj->section_end())
1221 continue;
1222
1223 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1224 }
1225}
1226
1227static void
1228addDynamicElfSymbols(const ObjectFile *Obj,
1229 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1230 assert(Obj->isELF());
1231 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1232 addDynamicElfSymbols(Elf32LEObj, AllSymbols);
1233 else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1234 addDynamicElfSymbols(Elf64LEObj, AllSymbols);
1235 else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1236 addDynamicElfSymbols(Elf32BEObj, AllSymbols);
1237 else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1238 addDynamicElfSymbols(Elf64BEObj, AllSymbols);
1239 else
1240 llvm_unreachable("Unsupported binary format");
1241}
1242
Joel Galenson134cf472018-08-24 15:21:57 +00001243static void addPltEntries(const ObjectFile *Obj,
1244 std::map<SectionRef, SectionSymbolsTy> &AllSymbols,
1245 StringSaver &Saver) {
1246 Optional<SectionRef> Plt = None;
1247 for (const SectionRef &Section : Obj->sections()) {
1248 StringRef Name;
1249 if (Section.getName(Name))
1250 continue;
1251 if (Name == ".plt")
1252 Plt = Section;
1253 }
1254 if (!Plt)
1255 return;
1256 if (auto *ElfObj = dyn_cast<ELFObjectFileBase>(Obj)) {
1257 for (auto PltEntry : ElfObj->getPltAddresses()) {
1258 SymbolRef Symbol(PltEntry.first, ElfObj);
1259
1260 uint8_t SymbolType = getElfSymbolType(Obj, Symbol);
1261
1262 Expected<StringRef> NameOrErr = Symbol.getName();
1263 if (!NameOrErr)
1264 report_error(Obj->getFileName(), NameOrErr.takeError());
1265 if (NameOrErr->empty())
1266 continue;
1267 StringRef Name = Saver.save((*NameOrErr + "@plt").str());
1268
1269 AllSymbols[*Plt].emplace_back(PltEntry.second, Name, SymbolType);
1270 }
1271 }
1272}
1273
Michael J. Spencer51862b32011-10-13 22:17:18 +00001274static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001275 if (StartAddress > StopAddress)
1276 error("Start address should be less than stop address");
1277
Jim Grosbachaf9aec02012-08-07 17:53:14 +00001278 const Target *TheTarget = getTarget(Obj);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001279
Jack Carter551efd72012-08-28 19:24:49 +00001280 // Package up features to be passed to target/subtarget
Daniel Sanders1d148642016-06-16 09:17:03 +00001281 SubtargetFeatures Features = Obj->getFeatures();
Jack Carter551efd72012-08-28 19:24:49 +00001282 if (MAttrs.size()) {
Jack Carter551efd72012-08-28 19:24:49 +00001283 for (unsigned i = 0; i != MAttrs.size(); ++i)
1284 Features.AddFeature(MAttrs[i]);
Jack Carter551efd72012-08-28 19:24:49 +00001285 }
1286
Ahmed Charles56440fd2014-03-06 05:51:42 +00001287 std::unique_ptr<const MCRegisterInfo> MRI(
1288 TheTarget->createMCRegInfo(TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +00001289 if (!MRI)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001290 report_error(Obj->getFileName(), "no register info for target " +
1291 TripleName);
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001292
1293 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00001294 std::unique_ptr<const MCAsmInfo> AsmInfo(
1295 TheTarget->createMCAsmInfo(*MRI, TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +00001296 if (!AsmInfo)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001297 report_error(Obj->getFileName(), "no assembly info for target " +
1298 TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +00001299 std::unique_ptr<const MCSubtargetInfo> STI(
Daniel Sanders1d148642016-06-16 09:17:03 +00001300 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
Davide Italiano711e4952015-12-17 01:59:50 +00001301 if (!STI)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001302 report_error(Obj->getFileName(), "no subtarget info for target " +
1303 TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +00001304 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
Davide Italiano711e4952015-12-17 01:59:50 +00001305 if (!MII)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001306 report_error(Obj->getFileName(), "no instruction info for target " +
1307 TripleName);
Sam Kolton3381d7a2016-10-06 13:46:08 +00001308 MCObjectFileInfo MOFI;
1309 MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI);
1310 // FIXME: for now initialize MCObjectFileInfo with default values
Rafael Espindola9f929952017-08-02 20:32:26 +00001311 MOFI.InitMCObjectFileInfo(Triple(TripleName), false, Ctx);
Lang Hamesa1bc0f52014-04-15 04:40:56 +00001312
1313 std::unique_ptr<MCDisassembler> DisAsm(
1314 TheTarget->createMCDisassembler(*STI, Ctx));
Davide Italiano711e4952015-12-17 01:59:50 +00001315 if (!DisAsm)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001316 report_error(Obj->getFileName(), "no disassembler for target " +
1317 TripleName);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001318
Ahmed Charles56440fd2014-03-06 05:51:42 +00001319 std::unique_ptr<const MCInstrAnalysis> MIA(
1320 TheTarget->createMCInstrAnalysis(MII.get()));
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001321
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001322 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Daniel Sanders50f17232015-09-15 16:17:27 +00001323 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1324 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
Davide Italiano711e4952015-12-17 01:59:50 +00001325 if (!IP)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001326 report_error(Obj->getFileName(), "no instruction printer for target " +
1327 TripleName);
Colin LeMahieu14ec76e2015-06-07 21:07:17 +00001328 IP->setPrintImmHex(PrintImmHex);
Colin LeMahieu35436a22015-05-29 14:48:25 +00001329 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001330
Greg Fitzgerald18432272014-03-20 22:55:15 +00001331 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
1332 "\t\t\t%08" PRIx64 ": ";
1333
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001334 SourcePrinter SP(Obj, TheTarget->getName());
1335
Mark Seaborn0929d3d2014-01-25 17:38:19 +00001336 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
1337 // in RelocSecs contain the relocations for section S.
Rafael Espindola4453e42942014-06-13 03:07:50 +00001338 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +00001339 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001340 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001341 section_iterator Sec2 = Section.getRelocatedSection();
Rafael Espindolab5155a52014-02-10 20:24:04 +00001342 if (Sec2 != Obj->section_end())
Alexey Samsonov48803e52014-03-13 14:37:36 +00001343 SectionRelocMap[*Sec2].push_back(Section);
Mark Seaborn0929d3d2014-01-25 17:38:19 +00001344 }
1345
David Majnemer81afca62015-07-07 22:06:59 +00001346 // Create a mapping from virtual address to symbol name. This is used to
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001347 // pretty print the symbols while disassembling.
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001348 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
Sterling Augustinebc78b622018-06-28 18:57:13 +00001349 SectionSymbolsTy AbsoluteSymbols;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001350 for (const SymbolRef &Symbol : Obj->symbols()) {
Kevin Enderby931cb652016-06-24 18:24:42 +00001351 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001352 if (!AddressOrErr)
1353 report_error(Obj->getFileName(), AddressOrErr.takeError());
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001354 uint64_t Address = *AddressOrErr;
David Majnemer2603a8fa2015-07-09 18:11:40 +00001355
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001356 Expected<StringRef> Name = Symbol.getName();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001357 if (!Name)
1358 report_error(Obj->getFileName(), Name.takeError());
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001359 if (Name->empty())
1360 continue;
David Majnemer81afca62015-07-07 22:06:59 +00001361
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001362 Expected<section_iterator> SectionOrErr = Symbol.getSection();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001363 if (!SectionOrErr)
1364 report_error(Obj->getFileName(), SectionOrErr.takeError());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001365
Sam Koltonc05d7782016-08-17 10:17:57 +00001366 uint8_t SymbolType = ELF::STT_NOTYPE;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001367 if (Obj->isELF())
Sam Koltonc05d7782016-08-17 10:17:57 +00001368 SymbolType = getElfSymbolType(Obj, Symbol);
David Majnemer81afca62015-07-07 22:06:59 +00001369
Sterling Augustinebc78b622018-06-28 18:57:13 +00001370 section_iterator SecI = *SectionOrErr;
1371 if (SecI != Obj->section_end())
1372 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1373 else
1374 AbsoluteSymbols.emplace_back(Address, *Name, SymbolType);
1375
Sam Koltonc05d7782016-08-17 10:17:57 +00001376
David Majnemer81afca62015-07-07 22:06:59 +00001377 }
Sam Parker5fba45a2017-02-08 09:44:18 +00001378 if (AllSymbols.empty() && Obj->isELF())
1379 addDynamicElfSymbols(Obj, AllSymbols);
David Majnemer81afca62015-07-07 22:06:59 +00001380
Joel Galenson134cf472018-08-24 15:21:57 +00001381 BumpPtrAllocator A;
1382 StringSaver Saver(A);
1383 addPltEntries(Obj, AllSymbols, Saver);
1384
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001385 // Create a mapping from virtual address to section.
1386 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1387 for (SectionRef Sec : Obj->sections())
1388 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1389 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
1390
1391 // Linked executables (.exe and .dll files) typically don't include a real
1392 // symbol table but they might contain an export table.
1393 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
1394 for (const auto &ExportEntry : COFFObj->export_directories()) {
1395 StringRef Name;
1396 error(ExportEntry.getSymbolName(Name));
1397 if (Name.empty())
1398 continue;
1399 uint32_t RVA;
1400 error(ExportEntry.getExportRVA(RVA));
1401
1402 uint64_t VA = COFFObj->getImageBase() + RVA;
1403 auto Sec = std::upper_bound(
1404 SectionAddresses.begin(), SectionAddresses.end(), VA,
1405 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
1406 return LHS < RHS.first;
1407 });
1408 if (Sec != SectionAddresses.begin())
1409 --Sec;
1410 else
1411 Sec = SectionAddresses.end();
1412
1413 if (Sec != SectionAddresses.end())
Sam Koltonc05d7782016-08-17 10:17:57 +00001414 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
Sterling Augustinebc78b622018-06-28 18:57:13 +00001415 else
1416 AbsoluteSymbols.emplace_back(VA, Name, ELF::STT_NOTYPE);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001417 }
1418 }
1419
1420 // Sort all the symbols, this allows us to use a simple binary search to find
1421 // a symbol near an address.
1422 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1423 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
Sterling Augustinebc78b622018-06-28 18:57:13 +00001424 array_pod_sort(AbsoluteSymbols.begin(), AbsoluteSymbols.end());
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001425
Colin LeMahieu77804be2015-07-29 15:45:39 +00001426 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Colin LeMahieuf34933e2015-07-23 20:58:49 +00001427 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
Mark Seaborneb03ac52014-01-25 00:32:01 +00001428 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +00001429
Rafael Espindola80291272014-10-08 15:28:58 +00001430 uint64_t SectionAddr = Section.getAddress();
1431 uint64_t SectSize = Section.getSize();
David Majnemer185b5b12014-11-11 09:58:25 +00001432 if (!SectSize)
1433 continue;
Simon Atanasyan2b614e12014-02-24 22:12:11 +00001434
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001435 // Get the list of all the symbols in this section.
1436 SectionSymbolsTy &Symbols = AllSymbols[Section];
Davide Italianof0706882015-10-01 21:57:09 +00001437 std::vector<uint64_t> DataMappingSymsAddr;
1438 std::vector<uint64_t> TextMappingSymsAddr;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001439 if (isArmElf(Obj)) {
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001440 for (const auto &Symb : Symbols) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001441 uint64_t Address = std::get<0>(Symb);
1442 StringRef Name = std::get<1>(Symb);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001443 if (Name.startswith("$d"))
David Majnemer153722d2015-11-18 04:35:32 +00001444 DataMappingSymsAddr.push_back(Address - SectionAddr);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001445 if (Name.startswith("$x"))
David Majnemer153722d2015-11-18 04:35:32 +00001446 TextMappingSymsAddr.push_back(Address - SectionAddr);
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001447 if (Name.startswith("$a"))
1448 TextMappingSymsAddr.push_back(Address - SectionAddr);
1449 if (Name.startswith("$t"))
1450 TextMappingSymsAddr.push_back(Address - SectionAddr);
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001451 }
1452 }
1453
Fangrui Song0cac7262018-09-27 02:13:45 +00001454 llvm::sort(DataMappingSymsAddr);
1455 llvm::sort(TextMappingSymsAddr);
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001456
Sam Kolton3381d7a2016-10-06 13:46:08 +00001457 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1458 // AMDGPU disassembler uses symbolizer for printing labels
1459 std::unique_ptr<MCRelocationInfo> RelInfo(
1460 TheTarget->createMCRelocationInfo(TripleName, Ctx));
1461 if (RelInfo) {
1462 std::unique_ptr<MCSymbolizer> Symbolizer(
1463 TheTarget->createMCSymbolizer(
1464 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1465 DisAsm->setSymbolizer(std::move(Symbolizer));
1466 }
1467 }
1468
Michael J. Spencer51862b32011-10-13 22:17:18 +00001469 // Make a list of all the relocations for this section.
1470 std::vector<RelocationRef> Rels;
1471 if (InlineRelocs) {
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001472 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
1473 for (const RelocationRef &Reloc : RelocSec.relocations()) {
1474 Rels.push_back(Reloc);
1475 }
Michael J. Spencer51862b32011-10-13 22:17:18 +00001476 }
1477 }
1478
1479 // Sort relocations by address.
Fangrui Song0cac7262018-09-27 02:13:45 +00001480 llvm::sort(Rels, RelocAddressLess);
Michael J. Spencer51862b32011-10-13 22:17:18 +00001481
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001482 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +00001483 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001484 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +00001485 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001486 }
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001487 StringRef SectionName;
1488 error(Section.getName(SectionName));
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001489
Rafael Espindola7884c952015-06-04 15:01:05 +00001490 // If the section has no symbol at the start, just insert a dummy one.
Sam Koltonc05d7782016-08-17 10:17:57 +00001491 if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) {
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001492 Symbols.insert(
1493 Symbols.begin(),
1494 std::make_tuple(SectionAddr, SectionName,
1495 Section.isText() ? ELF::STT_FUNC : ELF::STT_OBJECT));
Sam Koltonc05d7782016-08-17 10:17:57 +00001496 }
Alp Tokere69170a2014-06-26 22:52:05 +00001497
1498 SmallString<40> Comments;
1499 raw_svector_ostream CommentStream(Comments);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001500
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001501 StringRef BytesStr;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001502 error(Section.getContents(BytesStr));
Aaron Ballman106fd7b2014-11-12 14:01:17 +00001503 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1504 BytesStr.size());
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001505
Michael J. Spencer2670c252011-01-20 06:39:06 +00001506 uint64_t Size;
1507 uint64_t Index;
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001508 bool PrintedSection = false;
Michael J. Spencer2670c252011-01-20 06:39:06 +00001509
Michael J. Spencer51862b32011-10-13 22:17:18 +00001510 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
1511 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001512 // Disassemble symbol by symbol.
1513 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001514 uint64_t Start = std::get<0>(Symbols[si]) - SectionAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001515 // The end is either the section end or the beginning of the next
1516 // symbol.
1517 uint64_t End =
Sam Koltonc05d7782016-08-17 10:17:57 +00001518 (si == se - 1) ? SectSize : std::get<0>(Symbols[si + 1]) - SectionAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001519 // Don't try to disassemble beyond the end of section contents.
1520 if (End > SectSize)
1521 End = SectSize;
Rafael Espindolae45c7402014-08-17 16:31:39 +00001522 // If this symbol has the same address as the next symbol, then skip it.
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001523 if (Start >= End)
Michael J. Spenceree84f642011-10-13 20:37:08 +00001524 continue;
1525
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001526 // Check if we need to skip symbol
1527 // Skip if the symbol's data is not between StartAddress and StopAddress
1528 if (End + SectionAddr < StartAddress ||
1529 Start + SectionAddr > StopAddress) {
1530 continue;
1531 }
1532
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001533 /// Skip if user requested specific symbols and this is not in the list
1534 if (!DisasmFuncsSet.empty() &&
1535 !DisasmFuncsSet.count(std::get<1>(Symbols[si])))
1536 continue;
1537
1538 if (!PrintedSection) {
1539 PrintedSection = true;
1540 outs() << "Disassembly of section ";
1541 if (!SegmentName.empty())
1542 outs() << SegmentName << ",";
1543 outs() << SectionName << ':';
1544 }
1545
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001546 // Stop disassembly at the stop address specified
1547 if (End + SectionAddr > StopAddress)
1548 End = StopAddress - SectionAddr;
1549
Valery Pykhtinde048052016-04-07 07:24:01 +00001550 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001551 if (std::get<2>(Symbols[si]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1552 // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)
1553 Start += 256;
1554 }
1555 if (si == se - 1 ||
1556 std::get<2>(Symbols[si + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1557 // cut trailing zeroes at the end of kernel
1558 // cut up to 256 bytes
1559 const uint64_t EndAlign = 256;
1560 const auto Limit = End - (std::min)(EndAlign, End - Start);
1561 while (End > Limit &&
1562 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1563 End -= 4;
1564 }
Valery Pykhtinde048052016-04-07 07:24:01 +00001565 }
1566
Paul Semel007dedb2018-07-18 16:39:21 +00001567 auto PrintSymbol = [](StringRef Name) {
1568 outs() << '\n' << Name << ":\n";
1569 };
1570 StringRef SymbolName = std::get<1>(Symbols[si]);
Zachary Turner030ad372018-08-20 22:18:21 +00001571 if (Demangle) {
Paul Semel007dedb2018-07-18 16:39:21 +00001572 char *DemangledSymbol = nullptr;
1573 size_t Size = 0;
Zachary Turner030ad372018-08-20 22:18:21 +00001574 int Status = -1;
1575 if (SymbolName.startswith("_Z"))
1576 DemangledSymbol = itaniumDemangle(SymbolName.data(), DemangledSymbol,
1577 &Size, &Status);
1578 else if (SymbolName.startswith("?"))
1579 DemangledSymbol = microsoftDemangle(SymbolName.data(),
1580 DemangledSymbol, &Size, &Status);
1581
1582 if (Status == 0 && DemangledSymbol)
Paul Semel007dedb2018-07-18 16:39:21 +00001583 PrintSymbol(StringRef(DemangledSymbol));
1584 else
1585 PrintSymbol(SymbolName);
1586
Zachary Turner030ad372018-08-20 22:18:21 +00001587 if (DemangledSymbol)
Paul Semel007dedb2018-07-18 16:39:21 +00001588 free(DemangledSymbol);
1589 } else
1590 PrintSymbol(SymbolName);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001591
Francis Visoiu Mistrih18346822018-04-19 17:02:57 +00001592 // Don't print raw contents of a virtual section. A virtual section
1593 // doesn't have any contents in the file.
1594 if (Section.isVirtual()) {
1595 outs() << "...\n";
1596 continue;
1597 }
1598
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001599#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +00001600 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001601#else
Mark Seaborneb03ac52014-01-25 00:32:01 +00001602 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001603#endif
1604
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001605 for (Index = Start; Index < End; Index += Size) {
1606 MCInst Inst;
Owen Andersona0c3b972011-09-15 23:38:46 +00001607
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001608 if (Index + SectionAddr < StartAddress ||
1609 Index + SectionAddr > StopAddress) {
1610 // skip byte by byte till StartAddress is reached
1611 Size = 1;
1612 continue;
1613 }
Davide Italianof0706882015-10-01 21:57:09 +00001614 // AArch64 ELF binaries can interleave data and text in the
1615 // same section. We rely on the markers introduced to
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001616 // understand what we need to dump. If the data marker is within a
1617 // function, it is denoted as a word/short etc
1618 if (isArmElf(Obj) && std::get<2>(Symbols[si]) != ELF::STT_OBJECT &&
1619 !DisassembleAll) {
Davide Italianof0706882015-10-01 21:57:09 +00001620 uint64_t Stride = 0;
1621
1622 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1623 DataMappingSymsAddr.end(), Index);
1624 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1625 // Switch to data.
1626 while (Index < End) {
1627 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1628 outs() << "\t";
1629 if (Index + 4 <= End) {
1630 Stride = 4;
1631 dumpBytes(Bytes.slice(Index, 4), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001632 outs() << "\t.word\t";
1633 uint32_t Data = 0;
1634 if (Obj->isLittleEndian()) {
1635 const auto Word =
1636 reinterpret_cast<const support::ulittle32_t *>(
1637 Bytes.data() + Index);
1638 Data = *Word;
1639 } else {
1640 const auto Word = reinterpret_cast<const support::ubig32_t *>(
1641 Bytes.data() + Index);
1642 Data = *Word;
1643 }
1644 outs() << "0x" << format("%08" PRIx32, Data);
Davide Italianof0706882015-10-01 21:57:09 +00001645 } else if (Index + 2 <= End) {
1646 Stride = 2;
1647 dumpBytes(Bytes.slice(Index, 2), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001648 outs() << "\t\t.short\t";
1649 uint16_t Data = 0;
1650 if (Obj->isLittleEndian()) {
1651 const auto Short =
1652 reinterpret_cast<const support::ulittle16_t *>(
1653 Bytes.data() + Index);
1654 Data = *Short;
1655 } else {
1656 const auto Short =
1657 reinterpret_cast<const support::ubig16_t *>(Bytes.data() +
1658 Index);
1659 Data = *Short;
1660 }
1661 outs() << "0x" << format("%04" PRIx16, Data);
Davide Italianof0706882015-10-01 21:57:09 +00001662 } else {
1663 Stride = 1;
1664 dumpBytes(Bytes.slice(Index, 1), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001665 outs() << "\t\t.byte\t";
1666 outs() << "0x" << format("%02" PRIx8, Bytes.slice(Index, 1)[0]);
Davide Italianof0706882015-10-01 21:57:09 +00001667 }
1668 Index += Stride;
1669 outs() << "\n";
1670 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1671 TextMappingSymsAddr.end(), Index);
1672 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1673 break;
1674 }
1675 }
1676 }
1677
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001678 // If there is a data symbol inside an ELF text section and we are only
1679 // disassembling text (applicable all architectures),
1680 // we are in a situation where we must print the data and not
1681 // disassemble it.
1682 if (Obj->isELF() && std::get<2>(Symbols[si]) == ELF::STT_OBJECT &&
1683 !DisassembleAll && Section.isText()) {
1684 // print out data up to 8 bytes at a time in hex and ascii
1685 uint8_t AsciiData[9] = {'\0'};
1686 uint8_t Byte;
1687 int NumBytes = 0;
1688
1689 for (Index = Start; Index < End; Index += 1) {
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001690 if (((SectionAddr + Index) < StartAddress) ||
1691 ((SectionAddr + Index) > StopAddress))
1692 continue;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001693 if (NumBytes == 0) {
1694 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1695 outs() << "\t";
1696 }
1697 Byte = Bytes.slice(Index)[0];
1698 outs() << format(" %02x", Byte);
Michael Kruse6f1da6e2018-07-26 15:31:41 +00001699 AsciiData[NumBytes] = isPrint(Byte) ? Byte : '.';
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001700
1701 uint8_t IndentOffset = 0;
1702 NumBytes++;
1703 if (Index == End - 1 || NumBytes > 8) {
1704 // Indent the space for less than 8 bytes data.
1705 // 2 spaces for byte and one for space between bytes
1706 IndentOffset = 3 * (8 - NumBytes);
1707 for (int Excess = 8 - NumBytes; Excess < 8; Excess++)
1708 AsciiData[Excess] = '\0';
1709 NumBytes = 8;
1710 }
1711 if (NumBytes == 8) {
1712 AsciiData[8] = '\0';
1713 outs() << std::string(IndentOffset, ' ') << " ";
1714 outs() << reinterpret_cast<char *>(AsciiData);
1715 outs() << '\n';
1716 NumBytes = 0;
1717 }
1718 }
1719 }
Davide Italianof0706882015-10-01 21:57:09 +00001720 if (Index >= End)
1721 break;
1722
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001723 // Disassemble a real instruction or a data when disassemble all is
1724 // provided
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001725 bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1726 SectionAddr + Index, DebugOut,
1727 CommentStream);
1728 if (Size == 0)
1729 Size = 1;
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001730
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001731 PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001732 Bytes.slice(Index, Size), SectionAddr + Index, outs(), "",
Sid Manningd9f28732018-05-14 19:46:08 +00001733 *STI, &SP, &Rels);
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001734 outs() << CommentStream.str();
1735 Comments.clear();
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001736
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001737 // Try to resolve the target of a call, tail call, etc. to a specific
1738 // symbol.
1739 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1740 MIA->isConditionalBranch(Inst))) {
1741 uint64_t Target;
1742 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1743 // In a relocatable object, the target's section must reside in
1744 // the same section as the call instruction or it is accessed
1745 // through a relocation.
1746 //
1747 // In a non-relocatable object, the target may be in any section.
1748 //
1749 // N.B. We don't walk the relocations in the relocatable case yet.
1750 auto *TargetSectionSymbols = &Symbols;
1751 if (!Obj->isRelocatableObject()) {
1752 auto SectionAddress = std::upper_bound(
1753 SectionAddresses.begin(), SectionAddresses.end(), Target,
1754 [](uint64_t LHS,
1755 const std::pair<uint64_t, SectionRef> &RHS) {
1756 return LHS < RHS.first;
1757 });
1758 if (SectionAddress != SectionAddresses.begin()) {
1759 --SectionAddress;
1760 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1761 } else {
Sterling Augustinebc78b622018-06-28 18:57:13 +00001762 TargetSectionSymbols = &AbsoluteSymbols;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001763 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001764 }
David Majnemer2603a8fa2015-07-09 18:11:40 +00001765
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001766 // Find the first symbol in the section whose offset is less than
Sterling Augustinebc78b622018-06-28 18:57:13 +00001767 // or equal to the target. If there isn't a section that contains
1768 // the target, find the nearest preceding absolute symbol.
1769 auto TargetSym = std::upper_bound(
1770 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1771 Target, [](uint64_t LHS,
1772 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1773 return LHS < std::get<0>(RHS);
1774 });
1775 if (TargetSym == TargetSectionSymbols->begin()) {
1776 TargetSectionSymbols = &AbsoluteSymbols;
1777 TargetSym = std::upper_bound(
1778 AbsoluteSymbols.begin(), AbsoluteSymbols.end(),
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001779 Target, [](uint64_t LHS,
Sam Koltonc05d7782016-08-17 10:17:57 +00001780 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
Sterling Augustinebc78b622018-06-28 18:57:13 +00001781 return LHS < std::get<0>(RHS);
1782 });
1783 }
1784 if (TargetSym != TargetSectionSymbols->begin()) {
1785 --TargetSym;
1786 uint64_t TargetAddress = std::get<0>(*TargetSym);
1787 StringRef TargetName = std::get<1>(*TargetSym);
1788 outs() << " <" << TargetName;
1789 uint64_t Disp = Target - TargetAddress;
1790 if (Disp)
1791 outs() << "+0x" << Twine::utohexstr(Disp);
1792 outs() << '>';
David Majnemer81afca62015-07-07 22:06:59 +00001793 }
1794 }
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001795 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001796 outs() << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001797
Sid Manningd9f28732018-05-14 19:46:08 +00001798 // Hexagon does this in pretty printer
1799 if (Obj->getArch() != Triple::hexagon)
1800 // Print relocation for instruction.
1801 while (rel_cur != rel_end) {
1802 bool hidden = getHidden(*rel_cur);
1803 uint64_t addr = rel_cur->getOffset();
1804 SmallString<16> name;
1805 SmallString<32> val;
Owen Andersonfa3e5202011-10-25 20:35:53 +00001806
Sid Manningd9f28732018-05-14 19:46:08 +00001807 // If this relocation is hidden, skip it.
1808 if (hidden || ((SectionAddr + addr) < StartAddress)) {
1809 ++rel_cur;
1810 continue;
1811 }
1812
1813 // Stop when rel_cur's address is past the current instruction.
1814 if (addr >= Index + Size) break;
1815 rel_cur->getTypeName(name);
1816 error(getRelocationValueString(*rel_cur, val));
1817 outs() << format(Fmt.data(), SectionAddr + addr) << name
1818 << "\t" << val << "\n";
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001819 ++rel_cur;
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001820 }
Benjamin Kramer87ee76c2011-07-20 19:37:35 +00001821 }
Michael J. Spencer2670c252011-01-20 06:39:06 +00001822 }
1823 }
1824}
1825
Kevin Enderby98da6132015-01-20 21:47:46 +00001826void llvm::PrintRelocations(const ObjectFile *Obj) {
Greg Fitzgerald18432272014-03-20 22:55:15 +00001827 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1828 "%08" PRIx64;
Rafael Espindola9219fe72016-03-21 20:59:15 +00001829 // Regular objdump doesn't print relocations in non-relocatable object
1830 // files.
1831 if (!Obj->isRelocatableObject())
1832 return;
Rafael Espindolac66d7612014-08-17 19:09:37 +00001833
Colin LeMahieu77804be2015-07-29 15:45:39 +00001834 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001835 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001836 continue;
1837 StringRef secname;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001838 error(Section.getName(secname));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001839 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001840 for (const RelocationRef &Reloc : Section.relocations()) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001841 bool hidden = getHidden(Reloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001842 uint64_t address = Reloc.getOffset();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001843 SmallString<32> relocname;
1844 SmallString<32> valuestr;
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001845 if (address < StartAddress || address > StopAddress || hidden)
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001846 continue;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001847 Reloc.getTypeName(relocname);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001848 error(getRelocationValueString(Reloc, valuestr));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001849 outs() << format(Fmt.data(), address) << " " << relocname << " "
1850 << valuestr << "\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001851 }
1852 outs() << "\n";
1853 }
1854}
1855
Paul Semelcb0f0432018-06-07 13:30:55 +00001856void llvm::PrintDynamicRelocations(const ObjectFile *Obj) {
1857
1858 // For the moment, this option is for ELF only
1859 if (!Obj->isELF())
1860 return;
1861
1862 const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj);
1863
1864 if (!Elf || Elf->getEType() != ELF::ET_DYN) {
1865 error("not a dynamic object");
1866 return;
1867 }
1868
1869 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
1870
1871 std::vector<SectionRef> DynRelSec = Obj->dynamic_relocation_sections();
1872 if (DynRelSec.empty())
1873 return;
1874
1875 outs() << "DYNAMIC RELOCATION RECORDS\n";
1876 for (const SectionRef &Section : DynRelSec) {
1877 if (Section.relocation_begin() == Section.relocation_end())
1878 continue;
1879 for (const RelocationRef &Reloc : Section.relocations()) {
1880 uint64_t address = Reloc.getOffset();
1881 SmallString<32> relocname;
1882 SmallString<32> valuestr;
1883 Reloc.getTypeName(relocname);
1884 error(getRelocationValueString(Reloc, valuestr));
1885 outs() << format(Fmt.data(), address) << " " << relocname << " "
1886 << valuestr << "\n";
1887 }
1888 }
1889}
1890
Kevin Enderby98da6132015-01-20 21:47:46 +00001891void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001892 outs() << "Sections:\n"
1893 "Idx Name Size Address Type\n";
Colin LeMahieu77804be2015-07-29 15:45:39 +00001894 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001895 StringRef Name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001896 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001897 uint64_t Address = Section.getAddress();
1898 uint64_t Size = Section.getSize();
1899 bool Text = Section.isText();
1900 bool Data = Section.isData();
1901 bool BSS = Section.isBSS();
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001902 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +00001903 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
George Rimare35e6442018-07-18 08:34:35 +00001904 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n",
George Rimarc1090da2018-07-18 09:25:36 +00001905 (unsigned)Section.getIndex(), Name.str().c_str(), Size,
1906 Address, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001907 }
1908}
1909
Kevin Enderby98da6132015-01-20 21:47:46 +00001910void llvm::PrintSectionContents(const ObjectFile *Obj) {
Rafael Espindola4453e42942014-06-13 03:07:50 +00001911 std::error_code EC;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001912 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001913 StringRef Name;
1914 StringRef Contents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001915 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001916 uint64_t BaseAddr = Section.getAddress();
David Majnemer185b5b12014-11-11 09:58:25 +00001917 uint64_t Size = Section.getSize();
1918 if (!Size)
1919 continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001920
1921 outs() << "Contents of section " << Name << ":\n";
David Majnemer185b5b12014-11-11 09:58:25 +00001922 if (Section.isBSS()) {
Alexey Samsonov209095c2013-04-16 10:53:11 +00001923 outs() << format("<skipping contents of bss section at [%04" PRIx64
David Majnemer8f6b04c2014-07-14 16:20:14 +00001924 ", %04" PRIx64 ")>\n",
1925 BaseAddr, BaseAddr + Size);
Alexey Samsonov209095c2013-04-16 10:53:11 +00001926 continue;
1927 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001928
Davide Italianoccd53fe2015-08-05 07:18:31 +00001929 error(Section.getContents(Contents));
David Majnemer8f6b04c2014-07-14 16:20:14 +00001930
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001931 // Dump out the content as hex and printable ascii characters.
1932 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer82803112012-03-10 02:04:38 +00001933 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001934 // Dump line of hex.
1935 for (std::size_t i = 0; i < 16; ++i) {
1936 if (i != 0 && i % 4 == 0)
1937 outs() << ' ';
1938 if (addr + i < end)
1939 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1940 << hexdigit(Contents[addr + i] & 0xF, true);
1941 else
1942 outs() << " ";
1943 }
1944 // Print ascii.
1945 outs() << " ";
1946 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
Michael Kruse6f1da6e2018-07-26 15:31:41 +00001947 if (isPrint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001948 outs() << Contents[addr + i];
1949 else
1950 outs() << ".";
1951 }
1952 outs() << "\n";
1953 }
1954 }
1955}
1956
Kevin Enderby9acb1092016-05-31 20:35:34 +00001957void llvm::PrintSymbolTable(const ObjectFile *o, StringRef ArchiveName,
1958 StringRef ArchitectureName) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001959 outs() << "SYMBOL TABLE:\n";
1960
Rui Ueyama4e39f712014-03-18 18:58:51 +00001961 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
Davide Italianoe85abf72015-12-20 09:54:34 +00001962 printCOFFSymbolTable(coff);
Rui Ueyama4e39f712014-03-18 18:58:51 +00001963 return;
1964 }
1965 for (const SymbolRef &Symbol : o->symbols()) {
Kevin Enderby931cb652016-06-24 18:24:42 +00001966 Expected<uint64_t> AddressOrError = Symbol.getAddress();
1967 if (!AddressOrError)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001968 report_error(ArchiveName, o->getFileName(), AddressOrError.takeError(),
1969 ArchitectureName);
Rafael Espindolaed067c42015-07-03 18:19:00 +00001970 uint64_t Address = *AddressOrError;
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001971 if ((Address < StartAddress) || (Address > StopAddress))
1972 continue;
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001973 Expected<SymbolRef::Type> TypeOrError = Symbol.getType();
1974 if (!TypeOrError)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001975 report_error(ArchiveName, o->getFileName(), TypeOrError.takeError(),
1976 ArchitectureName);
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00001977 SymbolRef::Type Type = *TypeOrError;
Rui Ueyama4e39f712014-03-18 18:58:51 +00001978 uint32_t Flags = Symbol.getFlags();
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001979 Expected<section_iterator> SectionOrErr = Symbol.getSection();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001980 if (!SectionOrErr)
1981 report_error(ArchiveName, o->getFileName(), SectionOrErr.takeError(),
1982 ArchitectureName);
Rafael Espindola8bab8892015-08-07 23:27:14 +00001983 section_iterator Section = *SectionOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001984 StringRef Name;
1985 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1986 Section->getName(Name);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001987 } else {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001988 Expected<StringRef> NameOrErr = Symbol.getName();
1989 if (!NameOrErr)
Kevin Enderby9acb1092016-05-31 20:35:34 +00001990 report_error(ArchiveName, o->getFileName(), NameOrErr.takeError(),
1991 ArchitectureName);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001992 Name = *NameOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001993 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001994
Rui Ueyama4e39f712014-03-18 18:58:51 +00001995 bool Global = Flags & SymbolRef::SF_Global;
1996 bool Weak = Flags & SymbolRef::SF_Weak;
1997 bool Absolute = Flags & SymbolRef::SF_Absolute;
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001998 bool Common = Flags & SymbolRef::SF_Common;
Davide Italianocd2514d2015-04-30 23:08:53 +00001999 bool Hidden = Flags & SymbolRef::SF_Hidden;
David Meyer1df4b842012-02-28 23:47:53 +00002000
Rui Ueyama4e39f712014-03-18 18:58:51 +00002001 char GlobLoc = ' ';
2002 if (Type != SymbolRef::ST_Unknown)
2003 GlobLoc = Global ? 'g' : 'l';
2004 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
2005 ? 'd' : ' ';
2006 char FileFunc = ' ';
2007 if (Type == SymbolRef::ST_File)
2008 FileFunc = 'f';
2009 else if (Type == SymbolRef::ST_Function)
2010 FileFunc = 'F';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002011
Rui Ueyama4e39f712014-03-18 18:58:51 +00002012 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
2013 "%08" PRIx64;
Michael J. Spencerd857c1c2013-01-10 22:40:50 +00002014
Rui Ueyama4e39f712014-03-18 18:58:51 +00002015 outs() << format(Fmt, Address) << " "
2016 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
2017 << (Weak ? 'w' : ' ') // Weak?
2018 << ' ' // Constructor. Not supported yet.
2019 << ' ' // Warning. Not supported yet.
2020 << ' ' // Indirect reference to another symbol.
2021 << Debug // Debugging (d) or dynamic (D) symbol.
2022 << FileFunc // Name of function (F), file (f) or object (O).
2023 << ' ';
2024 if (Absolute) {
2025 outs() << "*ABS*";
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00002026 } else if (Common) {
2027 outs() << "*COM*";
Rui Ueyama4e39f712014-03-18 18:58:51 +00002028 } else if (Section == o->section_end()) {
2029 outs() << "*UND*";
2030 } else {
2031 if (const MachOObjectFile *MachO =
2032 dyn_cast<const MachOObjectFile>(o)) {
2033 DataRefImpl DR = Section->getRawDataRefImpl();
2034 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
2035 outs() << SegmentName << ",";
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002036 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00002037 StringRef SectionName;
Davide Italianoccd53fe2015-08-05 07:18:31 +00002038 error(Section->getName(SectionName));
Rui Ueyama4e39f712014-03-18 18:58:51 +00002039 outs() << SectionName;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002040 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00002041
2042 outs() << '\t';
Rafael Espindolaae3ac082015-06-23 18:34:25 +00002043 if (Common || isa<ELFObjectFileBase>(o)) {
Rafael Espindoladbb6bd32015-06-25 22:10:04 +00002044 uint64_t Val =
2045 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
Rafael Espindolaae3ac082015-06-23 18:34:25 +00002046 outs() << format("\t %08" PRIx64 " ", Val);
2047 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00002048
Davide Italianocd2514d2015-04-30 23:08:53 +00002049 if (Hidden) {
2050 outs() << ".hidden ";
2051 }
2052 outs() << Name
Rui Ueyama4e39f712014-03-18 18:58:51 +00002053 << '\n';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002054 }
2055}
2056
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00002057static void PrintUnwindInfo(const ObjectFile *o) {
2058 outs() << "Unwind info:\n\n";
2059
2060 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
2061 printCOFFUnwindInfo(coff);
Tim Northover4bd286a2014-08-01 13:07:19 +00002062 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
2063 printMachOUnwindInfo(MachO);
2064 else {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00002065 // TODO: Extract DWARF dump tool to objdump.
2066 errs() << "This operation is only currently supported "
Tim Northover4bd286a2014-08-01 13:07:19 +00002067 "for COFF and MachO object files.\n";
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00002068 return;
2069 }
2070}
2071
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002072void llvm::printExportsTrie(const ObjectFile *o) {
Nick Kledzikd04bc352014-08-30 00:20:14 +00002073 outs() << "Exports trie:\n";
2074 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
2075 printMachOExportsTrie(MachO);
2076 else {
2077 errs() << "This operation is only currently supported "
2078 "for Mach-O executable files.\n";
2079 return;
2080 }
2081}
2082
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002083void llvm::printRebaseTable(ObjectFile *o) {
Nick Kledzikac431442014-09-12 21:34:15 +00002084 outs() << "Rebase table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002085 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzikac431442014-09-12 21:34:15 +00002086 printMachORebaseTable(MachO);
2087 else {
2088 errs() << "This operation is only currently supported "
2089 "for Mach-O executable files.\n";
2090 return;
2091 }
2092}
2093
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002094void llvm::printBindTable(ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00002095 outs() << "Bind table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002096 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzik56ebef42014-09-16 01:41:51 +00002097 printMachOBindTable(MachO);
2098 else {
2099 errs() << "This operation is only currently supported "
2100 "for Mach-O executable files.\n";
2101 return;
2102 }
2103}
2104
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002105void llvm::printLazyBindTable(ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00002106 outs() << "Lazy bind table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002107 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzik56ebef42014-09-16 01:41:51 +00002108 printMachOLazyBindTable(MachO);
2109 else {
2110 errs() << "This operation is only currently supported "
2111 "for Mach-O executable files.\n";
2112 return;
2113 }
2114}
2115
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002116void llvm::printWeakBindTable(ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00002117 outs() << "Weak bind table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002118 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzik56ebef42014-09-16 01:41:51 +00002119 printMachOWeakBindTable(MachO);
2120 else {
2121 errs() << "This operation is only currently supported "
2122 "for Mach-O executable files.\n";
2123 return;
2124 }
2125}
Nick Kledzikac431442014-09-12 21:34:15 +00002126
Adrian Prantl437105a2015-07-08 02:04:15 +00002127/// Dump the raw contents of the __clangast section so the output can be piped
2128/// into llvm-bcanalyzer.
2129void llvm::printRawClangAST(const ObjectFile *Obj) {
2130 if (outs().is_displayed()) {
2131 errs() << "The -raw-clang-ast option will dump the raw binary contents of "
2132 "the clang ast section.\n"
2133 "Please redirect the output to a file or another program such as "
2134 "llvm-bcanalyzer.\n";
2135 return;
2136 }
2137
2138 StringRef ClangASTSectionName("__clangast");
2139 if (isa<COFFObjectFile>(Obj)) {
2140 ClangASTSectionName = "clangast";
2141 }
2142
2143 Optional<object::SectionRef> ClangASTSection;
Colin LeMahieu77804be2015-07-29 15:45:39 +00002144 for (auto Sec : ToolSectionFilter(*Obj)) {
Adrian Prantl437105a2015-07-08 02:04:15 +00002145 StringRef Name;
2146 Sec.getName(Name);
2147 if (Name == ClangASTSectionName) {
2148 ClangASTSection = Sec;
2149 break;
2150 }
2151 }
2152 if (!ClangASTSection)
2153 return;
2154
2155 StringRef ClangASTContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00002156 error(ClangASTSection.getValue().getContents(ClangASTContents));
Adrian Prantl437105a2015-07-08 02:04:15 +00002157 outs().write(ClangASTContents.data(), ClangASTContents.size());
2158}
2159
Sanjoy Das6f567a42015-06-22 18:03:02 +00002160static void printFaultMaps(const ObjectFile *Obj) {
2161 const char *FaultMapSectionName = nullptr;
2162
2163 if (isa<ELFObjectFileBase>(Obj)) {
2164 FaultMapSectionName = ".llvm_faultmaps";
2165 } else if (isa<MachOObjectFile>(Obj)) {
2166 FaultMapSectionName = "__llvm_faultmaps";
2167 } else {
2168 errs() << "This operation is only currently supported "
2169 "for ELF and Mach-O executable files.\n";
2170 return;
2171 }
2172
2173 Optional<object::SectionRef> FaultMapSection;
2174
Colin LeMahieu77804be2015-07-29 15:45:39 +00002175 for (auto Sec : ToolSectionFilter(*Obj)) {
Sanjoy Das6f567a42015-06-22 18:03:02 +00002176 StringRef Name;
2177 Sec.getName(Name);
2178 if (Name == FaultMapSectionName) {
2179 FaultMapSection = Sec;
2180 break;
2181 }
2182 }
2183
2184 outs() << "FaultMap table:\n";
2185
2186 if (!FaultMapSection.hasValue()) {
2187 outs() << "<not found>\n";
2188 return;
2189 }
2190
2191 StringRef FaultMapContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00002192 error(FaultMapSection.getValue().getContents(FaultMapContents));
Sanjoy Das6f567a42015-06-22 18:03:02 +00002193
2194 FaultMapParser FMP(FaultMapContents.bytes_begin(),
2195 FaultMapContents.bytes_end());
2196
2197 outs() << FMP;
2198}
2199
Davide Italiano1bdaa202016-09-18 04:39:15 +00002200static void printPrivateFileHeaders(const ObjectFile *o, bool onlyFirst) {
Paul Semel0913dcd2018-07-25 11:09:20 +00002201 if (o->isELF()) {
2202 printELFFileHeader(o);
2203 return printELFDynamicSection(o);
2204 }
Davide Italiano1bdaa202016-09-18 04:39:15 +00002205 if (o->isCOFF())
2206 return printCOFFFileHeader(o);
Derek Schuff2c6f75d2016-11-30 16:49:11 +00002207 if (o->isWasm())
2208 return printWasmFileHeader(o);
Davide Italiano1bdaa202016-09-18 04:39:15 +00002209 if (o->isMachO()) {
Kevin Enderby0ae163f2016-01-13 00:25:36 +00002210 printMachOFileHeader(o);
Davide Italiano1bdaa202016-09-18 04:39:15 +00002211 if (!onlyFirst)
2212 printMachOLoadCommands(o);
2213 return;
2214 }
Kevin Enderby7fa40c92016-11-16 22:17:38 +00002215 report_error(o->getFileName(), "Invalid/Unsupported object file format");
Rui Ueyamac2bed422013-09-27 21:04:00 +00002216}
2217
Paul Semeld2af4d62018-07-04 15:25:03 +00002218static void printFileHeaders(const ObjectFile *o) {
2219 if (!o->isELF() && !o->isCOFF())
2220 report_error(o->getFileName(), "Invalid/Unsupported object file format");
2221
2222 Triple::ArchType AT = o->getArch();
2223 outs() << "architecture: " << Triple::getArchTypeName(AT) << "\n";
2224 Expected<uint64_t> StartAddrOrErr = o->getStartAddress();
2225 if (!StartAddrOrErr)
2226 report_error(o->getFileName(), StartAddrOrErr.takeError());
Petar Jovanovic8d947ba2018-10-19 22:16:49 +00002227
2228 StringRef Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
2229 uint64_t Address = StartAddrOrErr.get();
Paul Semeld2af4d62018-07-04 15:25:03 +00002230 outs() << "start address: "
Petar Jovanovic8d947ba2018-10-19 22:16:49 +00002231 << "0x" << format(Fmt.data(), Address)
Paul Semeld2af4d62018-07-04 15:25:03 +00002232 << "\n";
2233}
2234
Paul Semel0dc92f62018-07-05 14:43:29 +00002235static void printArchiveChild(StringRef Filename, const Archive::Child &C) {
2236 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
2237 if (!ModeOrErr) {
2238 errs() << "ill-formed archive entry.\n";
2239 consumeError(ModeOrErr.takeError());
2240 return;
2241 }
2242 sys::fs::perms Mode = ModeOrErr.get();
2243 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
2244 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
2245 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
2246 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
2247 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
2248 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
2249 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
2250 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
2251 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
2252
2253 outs() << " ";
2254
2255 Expected<unsigned> UIDOrErr = C.getUID();
2256 if (!UIDOrErr)
2257 report_error(Filename, UIDOrErr.takeError());
2258 unsigned UID = UIDOrErr.get();
2259 outs() << format("%d/", UID);
2260
2261 Expected<unsigned> GIDOrErr = C.getGID();
2262 if (!GIDOrErr)
2263 report_error(Filename, GIDOrErr.takeError());
2264 unsigned GID = GIDOrErr.get();
2265 outs() << format("%-d ", GID);
2266
2267 Expected<uint64_t> Size = C.getRawSize();
2268 if (!Size)
2269 report_error(Filename, Size.takeError());
2270 outs() << format("%6" PRId64, Size.get()) << " ";
2271
2272 StringRef RawLastModified = C.getRawLastModified();
2273 unsigned Seconds;
2274 if (RawLastModified.getAsInteger(10, Seconds))
2275 outs() << "(date: \"" << RawLastModified
2276 << "\" contains non-decimal chars) ";
2277 else {
2278 // Since ctime(3) returns a 26 character string of the form:
2279 // "Sun Sep 16 01:03:52 1973\n\0"
2280 // just print 24 characters.
2281 time_t t = Seconds;
2282 outs() << format("%.24s ", ctime(&t));
2283 }
2284
2285 StringRef Name = "";
2286 Expected<StringRef> NameOrErr = C.getName();
2287 if (!NameOrErr) {
2288 consumeError(NameOrErr.takeError());
2289 Expected<StringRef> RawNameOrErr = C.getRawName();
2290 if (!RawNameOrErr)
2291 report_error(Filename, NameOrErr.takeError());
2292 Name = RawNameOrErr.get();
2293 } else {
2294 Name = NameOrErr.get();
2295 }
2296 outs() << Name << "\n";
2297}
2298
2299static void DumpObject(ObjectFile *o, const Archive *a = nullptr,
2300 const Archive::Child *c = nullptr) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002301 StringRef ArchiveName = a != nullptr ? a->getFileName() : "";
Adrian Prantl437105a2015-07-08 02:04:15 +00002302 // Avoid other output when using a raw option.
2303 if (!RawClangAST) {
2304 outs() << '\n';
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002305 if (a)
2306 outs() << a->getFileName() << "(" << o->getFileName() << ")";
2307 else
2308 outs() << o->getFileName();
2309 outs() << ":\tfile format " << o->getFileFormatName() << "\n\n";
Adrian Prantl437105a2015-07-08 02:04:15 +00002310 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00002311
James Hendersonc1608c92018-10-29 14:17:08 +00002312 if (ArchiveHeaders && !MachOOpt && c)
2313 printArchiveChild(ArchiveName, *c);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002314 if (Disassemble)
Michael J. Spencer51862b32011-10-13 22:17:18 +00002315 DisassembleObject(o, Relocations);
2316 if (Relocations && !Disassemble)
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002317 PrintRelocations(o);
Paul Semelcb0f0432018-06-07 13:30:55 +00002318 if (DynamicRelocations)
2319 PrintDynamicRelocations(o);
Nick Lewyckyfcf84622011-10-10 21:21:34 +00002320 if (SectionHeaders)
2321 PrintSectionHeaders(o);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00002322 if (SectionContents)
2323 PrintSectionContents(o);
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002324 if (SymbolTable)
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002325 PrintSymbolTable(o, ArchiveName);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00002326 if (UnwindInfo)
2327 PrintUnwindInfo(o);
Davide Italiano1bdaa202016-09-18 04:39:15 +00002328 if (PrivateHeaders || FirstPrivateHeader)
2329 printPrivateFileHeaders(o, FirstPrivateHeader);
Paul Semeld2af4d62018-07-04 15:25:03 +00002330 if (FileHeaders)
2331 printFileHeaders(o);
Nick Kledzikd04bc352014-08-30 00:20:14 +00002332 if (ExportsTrie)
2333 printExportsTrie(o);
Nick Kledzikac431442014-09-12 21:34:15 +00002334 if (Rebase)
2335 printRebaseTable(o);
Nick Kledzik56ebef42014-09-16 01:41:51 +00002336 if (Bind)
2337 printBindTable(o);
2338 if (LazyBind)
2339 printLazyBindTable(o);
2340 if (WeakBind)
2341 printWeakBindTable(o);
Adrian Prantl437105a2015-07-08 02:04:15 +00002342 if (RawClangAST)
2343 printRawClangAST(o);
Sanjoy Das6f567a42015-06-22 18:03:02 +00002344 if (PrintFaultMaps)
2345 printFaultMaps(o);
Igor Laevsky03a670c2016-01-26 15:09:42 +00002346 if (DwarfDumpType != DIDT_Null) {
Rafael Espindolac398e672017-07-19 22:27:28 +00002347 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*o);
Igor Laevsky03a670c2016-01-26 15:09:42 +00002348 // Dump the complete DWARF structure.
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00002349 DIDumpOptions DumpOpts;
2350 DumpOpts.DumpType = DwarfDumpType;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00002351 DICtx->dump(outs(), DumpOpts);
Igor Laevsky03a670c2016-01-26 15:09:42 +00002352 }
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002353}
2354
Paul Semel0dc92f62018-07-05 14:43:29 +00002355static void DumpObject(const COFFImportFile *I, const Archive *A,
2356 const Archive::Child *C = nullptr) {
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00002357 StringRef ArchiveName = A ? A->getFileName() : "";
2358
2359 // Avoid other output when using a raw option.
2360 if (!RawClangAST)
2361 outs() << '\n'
2362 << ArchiveName << "(" << I->getFileName() << ")"
2363 << ":\tfile format COFF-import-file"
2364 << "\n\n";
2365
James Hendersonc1608c92018-10-29 14:17:08 +00002366 if (ArchiveHeaders && !MachOOpt && C)
2367 printArchiveChild(ArchiveName, *C);
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00002368 if (SymbolTable)
2369 printCOFFSymbolTable(I);
2370}
2371
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +00002372/// Dump each object file in \a a;
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002373static void DumpArchive(const Archive *a) {
Mehdi Amini41af4302016-11-11 04:28:40 +00002374 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00002375 for (auto &C : a->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002376 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2377 if (!ChildOrErr) {
2378 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2379 report_error(a->getFileName(), C, std::move(E));
2380 continue;
2381 }
Rafael Espindolaae460022014-06-16 16:08:36 +00002382 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
Paul Semel0dc92f62018-07-05 14:43:29 +00002383 DumpObject(o, a, &C);
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00002384 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
Paul Semel0dc92f62018-07-05 14:43:29 +00002385 DumpObject(I, a, &C);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002386 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00002387 report_error(a->getFileName(), object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002388 }
Lang Hamesfc209622016-07-14 02:24:01 +00002389 if (Err)
2390 report_error(a->getFileName(), std::move(Err));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002391}
2392
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +00002393/// Open file and figure out how to dump it.
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002394static void DumpInput(StringRef file) {
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002395
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002396 // If we are using the Mach-O specific object file parser, then let it parse
2397 // the file and process the command line options. So the -arch flags can
2398 // be used to select specific slices, etc.
2399 if (MachOOpt) {
2400 ParseInputMachO(file);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002401 return;
2402 }
2403
2404 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00002405 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
2406 if (!BinaryOrErr)
Kevin Enderbyb34e3a12016-05-05 17:43:35 +00002407 report_error(file, BinaryOrErr.takeError());
Rafael Espindola48af1c22014-08-19 18:44:46 +00002408 Binary &Binary = *BinaryOrErr.get().getBinary();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002409
Rafael Espindola3f6481d2014-08-01 14:31:55 +00002410 if (Archive *a = dyn_cast<Archive>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002411 DumpArchive(a);
Rafael Espindola3f6481d2014-08-01 14:31:55 +00002412 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002413 DumpObject(o);
Dave Lee3fb120f2018-08-03 00:06:38 +00002414 else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Binary))
2415 ParseInputMachO(UB);
Jim Grosbachaf9aec02012-08-07 17:53:14 +00002416 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00002417 report_error(file, object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002418}
2419
Michael J. Spencer2670c252011-01-20 06:39:06 +00002420int main(int argc, char **argv) {
Rui Ueyama197194b2018-04-13 18:26:06 +00002421 InitLLVM X(argc, argv);
Michael J. Spencer2670c252011-01-20 06:39:06 +00002422
2423 // Initialize targets and assembly printers/parsers.
2424 llvm::InitializeAllTargetInfos();
Evan Cheng8c886a42011-07-22 21:58:54 +00002425 llvm::InitializeAllTargetMCs();
Michael J. Spencer2670c252011-01-20 06:39:06 +00002426 llvm::InitializeAllDisassemblers();
2427
Pete Cooper28fb4fc2012-05-03 23:20:10 +00002428 // Register the target printer for --version.
2429 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
2430
Michael J. Spencer2670c252011-01-20 06:39:06 +00002431 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
Michael J. Spencer2670c252011-01-20 06:39:06 +00002432
2433 ToolName = argv[0];
2434
2435 // Defaults to a.out if no filenames specified.
2436 if (InputFilenames.size() == 0)
2437 InputFilenames.push_back("a.out");
2438
Fangrui Song8513cd42018-06-27 20:45:11 +00002439 if (AllHeaders)
2440 PrivateHeaders = Relocations = SectionHeaders = SymbolTable = true;
2441
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00002442 if (DisassembleAll || PrintSource || PrintLines)
Colin LeMahieuf34933e2015-07-23 20:58:49 +00002443 Disassemble = true;
Paul Semel007dedb2018-07-18 16:39:21 +00002444
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002445 if (!Disassemble
2446 && !Relocations
Paul Semelcb0f0432018-06-07 13:30:55 +00002447 && !DynamicRelocations
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002448 && !SectionHeaders
2449 && !SectionContents
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00002450 && !SymbolTable
Michael J. Spencer209565db2013-01-06 03:56:49 +00002451 && !UnwindInfo
Nick Kledzikd04bc352014-08-30 00:20:14 +00002452 && !PrivateHeaders
Paul Semeld2af4d62018-07-04 15:25:03 +00002453 && !FileHeaders
Kevin Enderby0ae163f2016-01-13 00:25:36 +00002454 && !FirstPrivateHeader
Nick Kledzikac431442014-09-12 21:34:15 +00002455 && !ExportsTrie
Nick Kledzik56ebef42014-09-16 01:41:51 +00002456 && !Rebase
2457 && !Bind
2458 && !LazyBind
Kevin Enderby131d1772015-01-09 19:22:37 +00002459 && !WeakBind
Adrian Prantl437105a2015-07-08 02:04:15 +00002460 && !RawClangAST
Kevin Enderby13023a12015-01-15 23:19:11 +00002461 && !(UniversalHeaders && MachOOpt)
Paul Semel0dc92f62018-07-05 14:43:29 +00002462 && !ArchiveHeaders
Kevin Enderby69fe98d2015-01-23 18:52:17 +00002463 && !(IndirectSymbols && MachOOpt)
Kevin Enderby9a509442015-01-27 21:28:24 +00002464 && !(DataInCode && MachOOpt)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002465 && !(LinkOptHints && MachOOpt)
Kevin Enderbycd66be52015-03-11 22:06:32 +00002466 && !(InfoPlist && MachOOpt)
Kevin Enderbybc847fa2015-03-16 20:08:09 +00002467 && !(DylibsUsed && MachOOpt)
2468 && !(DylibId && MachOOpt)
Kevin Enderby0fc11822015-04-01 20:57:01 +00002469 && !(ObjcMetaData && MachOOpt)
Colin LeMahieufcc32762015-07-29 19:08:10 +00002470 && !(FilterSections.size() != 0 && MachOOpt)
Igor Laevsky03a670c2016-01-26 15:09:42 +00002471 && !PrintFaultMaps
2472 && DwarfDumpType == DIDT_Null) {
Michael J. Spencer2670c252011-01-20 06:39:06 +00002473 cl::PrintHelpMessage();
Dimitry Andrice4f5d012017-12-18 19:46:56 +00002474 return 2;
2475 }
2476
Rafael Aulerb0e4b912018-03-09 19:13:44 +00002477 DisasmFuncsSet.insert(DisassembleFunctions.begin(),
2478 DisassembleFunctions.end());
2479
Dimitry Andrice4f5d012017-12-18 19:46:56 +00002480 llvm::for_each(InputFilenames, DumpInput);
2481
2482 return EXIT_SUCCESS;
2483}