blob: 2598d9304177868a97c01efa4ec95e8420d07305 [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"
Michael J. Spencer2670c252011-01-20 06:39:06 +000028#include "llvm/MC/MCAsmInfo.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000029#include "llvm/MC/MCContext.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000030#include "llvm/MC/MCDisassembler/MCDisassembler.h"
31#include "llvm/MC/MCDisassembler/MCRelocationInfo.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000032#include "llvm/MC/MCInst.h"
33#include "llvm/MC/MCInstPrinter.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000034#include "llvm/MC/MCInstrAnalysis.h"
Craig Topper54bfde72012-04-02 06:09:36 +000035#include "llvm/MC/MCInstrInfo.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000036#include "llvm/MC/MCObjectFileInfo.h"
Jim Grosbachfd93a592012-03-05 19:33:20 +000037#include "llvm/MC/MCRegisterInfo.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000038#include "llvm/MC/MCSubtargetInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000039#include "llvm/Object/Archive.h"
40#include "llvm/Object/COFF.h"
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +000041#include "llvm/Object/COFFImportFile.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000042#include "llvm/Object/ELFObjectFile.h"
Rafael Espindolaa9f810b2012-12-21 03:47:03 +000043#include "llvm/Object/MachO.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000044#include "llvm/Object/ObjectFile.h"
Sam Clegg4df5d762017-06-27 20:40:53 +000045#include "llvm/Object/Wasm.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000046#include "llvm/Support/Casting.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000047#include "llvm/Support/CommandLine.h"
48#include "llvm/Support/Debug.h"
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +000049#include "llvm/Support/Errc.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000050#include "llvm/Support/FileSystem.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000051#include "llvm/Support/Format.h"
Benjamin Kramerbf115312011-07-25 23:04:36 +000052#include "llvm/Support/GraphWriter.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000053#include "llvm/Support/Host.h"
Rui Ueyama197194b2018-04-13 18:26:06 +000054#include "llvm/Support/InitLLVM.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000055#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000056#include "llvm/Support/SourceMgr.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000057#include "llvm/Support/TargetRegistry.h"
58#include "llvm/Support/TargetSelect.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000059#include "llvm/Support/raw_ostream.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000060#include <algorithm>
Benjamin Kramera5177e62012-03-23 11:49:32 +000061#include <cctype>
Michael J. Spencer2670c252011-01-20 06:39:06 +000062#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000063#include <system_error>
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +000064#include <unordered_map>
Rafael Espindolac398e672017-07-19 22:27:28 +000065#include <utility>
Ahmed Bougacha17926472013-08-21 07:29:02 +000066
Michael J. Spencer2670c252011-01-20 06:39:06 +000067using namespace llvm;
68using namespace object;
69
Fangrui Song8513cd42018-06-27 20:45:11 +000070cl::opt<bool>
71 llvm::AllHeaders("all-headers",
72 cl::desc("Display all available header information"));
73static cl::alias AllHeadersShort("x", cl::desc("Alias for --all-headers"),
74 cl::aliasopt(AllHeaders));
75
Benjamin Kramer43a772e2011-09-19 17:56:04 +000076static cl::list<std::string>
77InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
Michael J. Spencer2670c252011-01-20 06:39:06 +000078
Kevin Enderbye2297dd2015-01-07 21:02:18 +000079cl::opt<bool>
80llvm::Disassemble("disassemble",
Benjamin Kramer43a772e2011-09-19 17:56:04 +000081 cl::desc("Display assembler mnemonics for the machine instructions"));
82static cl::alias
83Disassembled("d", cl::desc("Alias for --disassemble"),
Colin LeMahieu77804be2015-07-29 15:45:39 +000084 cl::aliasopt(Disassemble));
85
86cl::opt<bool>
87llvm::DisassembleAll("disassemble-all",
88 cl::desc("Display assembler mnemonics for the machine instructions"));
89static cl::alias
90DisassembleAlld("D", cl::desc("Alias for --disassemble-all"),
Colin LeMahieuf34933e2015-07-23 20:58:49 +000091 cl::aliasopt(DisassembleAll));
Michael J. Spencer2670c252011-01-20 06:39:06 +000092
Rafael Aulerb0e4b912018-03-09 19:13:44 +000093static cl::list<std::string>
94DisassembleFunctions("df",
95 cl::CommaSeparated,
96 cl::desc("List of functions to disassemble"));
97static StringSet<> DisasmFuncsSet;
98
Kevin Enderby98da6132015-01-20 21:47:46 +000099cl::opt<bool>
100llvm::Relocations("r", cl::desc("Display the relocation entries in the file"));
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000101
Kevin Enderby98da6132015-01-20 21:47:46 +0000102cl::opt<bool>
Paul Semelcb0f0432018-06-07 13:30:55 +0000103llvm::DynamicRelocations("dynamic-reloc",
104 cl::desc("Display the dynamic relocation entries in the file"));
105static cl::alias
106DynamicRelocationsd("R", cl::desc("Alias for --dynamic-reloc"),
107 cl::aliasopt(DynamicRelocations));
108
109cl::opt<bool>
Kevin Enderby98da6132015-01-20 21:47:46 +0000110llvm::SectionContents("s", cl::desc("Display the content of each section"));
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000111
Kevin Enderby98da6132015-01-20 21:47:46 +0000112cl::opt<bool>
113llvm::SymbolTable("t", cl::desc("Display the symbol table"));
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000114
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000115cl::opt<bool>
116llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
Nick Kledzikd04bc352014-08-30 00:20:14 +0000117
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000118cl::opt<bool>
119llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
Nick Kledzikac431442014-09-12 21:34:15 +0000120
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000121cl::opt<bool>
122llvm::Bind("bind", cl::desc("Display mach-o binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000123
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000124cl::opt<bool>
125llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000126
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000127cl::opt<bool>
128llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000129
Adrian Prantl437105a2015-07-08 02:04:15 +0000130cl::opt<bool>
131llvm::RawClangAST("raw-clang-ast",
132 cl::desc("Dump the raw binary contents of the clang AST section"));
133
Nick Kledzik56ebef42014-09-16 01:41:51 +0000134static cl::opt<bool>
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000135MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000136static cl::alias
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000137MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
Benjamin Kramer87ee76c2011-07-20 19:37:35 +0000138
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000139cl::opt<std::string>
140llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
141 "see -version for available targets"));
142
143cl::opt<std::string>
Kevin Enderbyc9595622014-08-06 23:24:41 +0000144llvm::MCPU("mcpu",
145 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
146 cl::value_desc("cpu-name"),
147 cl::init(""));
148
149cl::opt<std::string>
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000150llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
Michael J. Spencer2670c252011-01-20 06:39:06 +0000151 "see -version for available targets"));
152
Kevin Enderby98da6132015-01-20 21:47:46 +0000153cl::opt<bool>
154llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
155 "headers for each section."));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000156static cl::alias
157SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
158 cl::aliasopt(SectionHeaders));
159static cl::alias
160SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
161 cl::aliasopt(SectionHeaders));
Colin LeMahieufcc32762015-07-29 19:08:10 +0000162
Colin LeMahieu77804be2015-07-29 15:45:39 +0000163cl::list<std::string>
Colin LeMahieufcc32762015-07-29 19:08:10 +0000164llvm::FilterSections("section", cl::desc("Operate on the specified sections only. "
165 "With -macho dump segment,section"));
166cl::alias
167static FilterSectionsj("j", cl::desc("Alias for --section"),
168 cl::aliasopt(llvm::FilterSections));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000169
Kevin Enderbyc9595622014-08-06 23:24:41 +0000170cl::list<std::string>
171llvm::MAttrs("mattr",
Jack Carter551efd72012-08-28 19:24:49 +0000172 cl::CommaSeparated,
173 cl::desc("Target specific attributes"),
174 cl::value_desc("a1,+a2,-a3,..."));
175
Kevin Enderbybf246f52014-09-24 23:08:22 +0000176cl::opt<bool>
177llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
178 "instructions, do not print "
179 "the instruction bytes."));
Saleem Abdulrasooldea14b22017-02-08 18:11:31 +0000180cl::opt<bool>
181llvm::NoLeadingAddr("no-leading-addr", cl::desc("Print no leading address"));
Eli Bendersky3a6808c2012-11-20 22:57:02 +0000182
Kevin Enderby98da6132015-01-20 21:47:46 +0000183cl::opt<bool>
184llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000185
186static cl::alias
187UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
188 cl::aliasopt(UnwindInfo));
189
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000190cl::opt<bool>
191llvm::PrivateHeaders("private-headers",
192 cl::desc("Display format specific file headers"));
Michael J. Spencer209565db2013-01-06 03:56:49 +0000193
Kevin Enderby0ae163f2016-01-13 00:25:36 +0000194cl::opt<bool>
195llvm::FirstPrivateHeader("private-header",
196 cl::desc("Display only the first format specific file "
197 "header"));
198
Michael J. Spencer209565db2013-01-06 03:56:49 +0000199static cl::alias
200PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
201 cl::aliasopt(PrivateHeaders));
202
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000203cl::opt<bool>
204 llvm::PrintImmHex("print-imm-hex",
Colin LeMahieuefe37322016-04-08 18:15:37 +0000205 cl::desc("Use hex format for immediate values"));
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000206
Sanjoy Das6f567a42015-06-22 18:03:02 +0000207cl::opt<bool> PrintFaultMaps("fault-map-section",
208 cl::desc("Display contents of faultmap section"));
209
Igor Laevsky03a670c2016-01-26 15:09:42 +0000210cl::opt<DIDumpType> llvm::DwarfDumpType(
211 "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"),
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000212 cl::values(clEnumValN(DIDT_DebugFrame, "frames", ".debug_frame")));
Igor Laevsky03a670c2016-01-26 15:09:42 +0000213
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000214cl::opt<bool> PrintSource(
215 "source",
216 cl::desc(
Alex Denisova07169e2018-02-02 19:20:37 +0000217 "Display source inlined with disassembly. Implies disassemble object"));
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000218
219cl::alias PrintSourceShort("S", cl::desc("Alias for -source"),
220 cl::aliasopt(PrintSource));
221
222cl::opt<bool> PrintLines("line-numbers",
223 cl::desc("Display source line numbers with "
224 "disassembly. Implies disassemble object"));
225
226cl::alias PrintLinesShort("l", cl::desc("Alias for -line-numbers"),
227 cl::aliasopt(PrintLines));
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +0000228
229cl::opt<unsigned long long>
230 StartAddress("start-address", cl::desc("Disassemble beginning at address"),
231 cl::value_desc("address"), cl::init(0));
232cl::opt<unsigned long long>
233 StopAddress("stop-address", cl::desc("Stop disassembly at address"),
234 cl::value_desc("address"), cl::init(UINT64_MAX));
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000235static StringRef ToolName;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000236
Sam Parker5fba45a2017-02-08 09:44:18 +0000237typedef std::vector<std::tuple<uint64_t, StringRef, uint8_t>> SectionSymbolsTy;
238
Colin LeMahieu77804be2015-07-29 15:45:39 +0000239namespace {
Colin LeMahieufcc32762015-07-29 19:08:10 +0000240typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate;
Colin LeMahieu77804be2015-07-29 15:45:39 +0000241
242class SectionFilterIterator {
243public:
244 SectionFilterIterator(FilterPredicate P,
245 llvm::object::section_iterator const &I,
246 llvm::object::section_iterator const &E)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000247 : Predicate(std::move(P)), Iterator(I), End(E) {
Colin LeMahieu77804be2015-07-29 15:45:39 +0000248 ScanPredicate();
249 }
Benjamin Kramerac9257b2015-09-24 14:52:52 +0000250 const llvm::object::SectionRef &operator*() const { return *Iterator; }
Colin LeMahieu77804be2015-07-29 15:45:39 +0000251 SectionFilterIterator &operator++() {
252 ++Iterator;
253 ScanPredicate();
254 return *this;
255 }
256 bool operator!=(SectionFilterIterator const &Other) const {
257 return Iterator != Other.Iterator;
258 }
259
260private:
261 void ScanPredicate() {
Colin LeMahieuda1723f2015-07-29 19:21:13 +0000262 while (Iterator != End && !Predicate(*Iterator)) {
Colin LeMahieu77804be2015-07-29 15:45:39 +0000263 ++Iterator;
264 }
265 }
266 FilterPredicate Predicate;
267 llvm::object::section_iterator Iterator;
268 llvm::object::section_iterator End;
269};
270
271class SectionFilter {
272public:
273 SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000274 : Predicate(std::move(P)), Object(O) {}
Colin LeMahieu77804be2015-07-29 15:45:39 +0000275 SectionFilterIterator begin() {
276 return SectionFilterIterator(Predicate, Object.section_begin(),
277 Object.section_end());
278 }
279 SectionFilterIterator end() {
280 return SectionFilterIterator(Predicate, Object.section_end(),
281 Object.section_end());
282 }
283
284private:
285 FilterPredicate Predicate;
286 llvm::object::ObjectFile const &Object;
287};
288SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) {
David Majnemer42531262016-08-12 03:55:06 +0000289 return SectionFilter(
290 [](llvm::object::SectionRef const &S) {
291 if (FilterSections.empty())
292 return true;
293 llvm::StringRef String;
294 std::error_code error = S.getName(String);
295 if (error)
296 return false;
297 return is_contained(FilterSections, String);
298 },
299 O);
Colin LeMahieu77804be2015-07-29 15:45:39 +0000300}
301}
302
Davide Italianoccd53fe2015-08-05 07:18:31 +0000303void llvm::error(std::error_code EC) {
Mark Seaborneb03ac52014-01-25 00:32:01 +0000304 if (!EC)
Davide Italianoccd53fe2015-08-05 07:18:31 +0000305 return;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000306
Davide Italiano140af642015-12-25 18:16:45 +0000307 errs() << ToolName << ": error reading file: " << EC.message() << ".\n";
308 errs().flush();
Davide Italiano7f6c3012015-08-06 00:18:52 +0000309 exit(1);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000310}
311
Kevin Enderby42398052016-06-28 23:16:13 +0000312LLVM_ATTRIBUTE_NORETURN void llvm::error(Twine Message) {
313 errs() << ToolName << ": " << Message << ".\n";
314 errs().flush();
315 exit(1);
316}
317
Davide Italianoed9d95b2015-12-29 13:41:02 +0000318LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000319 Twine Message) {
320 errs() << ToolName << ": '" << File << "': " << Message << ".\n";
321 exit(1);
322}
323
324LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
Davide Italianoed9d95b2015-12-29 13:41:02 +0000325 std::error_code EC) {
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000326 assert(EC);
327 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
Davide Italianoccd53fe2015-08-05 07:18:31 +0000328 exit(1);
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000329}
330
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000331LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
332 llvm::Error E) {
333 assert(E);
334 std::string Buf;
335 raw_string_ostream OS(Buf);
336 logAllUnhandledErrors(std::move(E), OS, "");
337 OS.flush();
Kevin Enderbyb34e3a12016-05-05 17:43:35 +0000338 errs() << ToolName << ": '" << File << "': " << Buf;
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000339 exit(1);
340}
341
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000342LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
343 StringRef FileName,
Kevin Enderby9acb1092016-05-31 20:35:34 +0000344 llvm::Error E,
345 StringRef ArchitectureName) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000346 assert(E);
347 errs() << ToolName << ": ";
348 if (ArchiveName != "")
349 errs() << ArchiveName << "(" << FileName << ")";
350 else
Justin Bogner31d8b7d2016-10-26 22:37:52 +0000351 errs() << "'" << FileName << "'";
Kevin Enderby9acb1092016-05-31 20:35:34 +0000352 if (!ArchitectureName.empty())
353 errs() << " (for architecture " << ArchitectureName << ")";
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000354 std::string Buf;
355 raw_string_ostream OS(Buf);
356 logAllUnhandledErrors(std::move(E), OS, "");
357 OS.flush();
Justin Bogner31d8b7d2016-10-26 22:37:52 +0000358 errs() << ": " << Buf;
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000359 exit(1);
360}
361
362LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
363 const object::Archive::Child &C,
Kevin Enderby9acb1092016-05-31 20:35:34 +0000364 llvm::Error E,
365 StringRef ArchitectureName) {
Kevin Enderbyf4586032016-07-29 17:44:13 +0000366 Expected<StringRef> NameOrErr = C.getName();
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000367 // TODO: if we have a error getting the name then it would be nice to print
368 // the index of which archive member this is and or its offset in the
369 // archive instead of "???" as the name.
Kevin Enderbyf4586032016-07-29 17:44:13 +0000370 if (!NameOrErr) {
371 consumeError(NameOrErr.takeError());
Kevin Enderby9acb1092016-05-31 20:35:34 +0000372 llvm::report_error(ArchiveName, "???", std::move(E), ArchitectureName);
Kevin Enderbyf4586032016-07-29 17:44:13 +0000373 } else
Kevin Enderby9acb1092016-05-31 20:35:34 +0000374 llvm::report_error(ArchiveName, NameOrErr.get(), std::move(E),
375 ArchitectureName);
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000376}
377
Craig Toppere6cb63e2014-04-25 04:24:47 +0000378static const Target *getTarget(const ObjectFile *Obj = nullptr) {
Michael J. Spencer2670c252011-01-20 06:39:06 +0000379 // Figure out the target triple.
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000380 llvm::Triple TheTriple("unknown-unknown-unknown");
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000381 if (TripleName.empty()) {
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000382 if (Obj) {
Vlad Tsyrklevichde620462017-09-19 02:22:48 +0000383 TheTriple = Obj->makeTriple();
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000384 }
Sam Parkerdf7c6ef2017-01-18 13:52:12 +0000385 } else {
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000386 TheTriple.setTriple(Triple::normalize(TripleName));
Vlad Tsyrklevichde620462017-09-19 02:22:48 +0000387
Sam Parkerdf7c6ef2017-01-18 13:52:12 +0000388 // Use the triple, but also try to combine with ARM build attributes.
389 if (Obj) {
390 auto Arch = Obj->getArch();
391 if (Arch == Triple::arm || Arch == Triple::armeb) {
392 Obj->setARMSubArch(TheTriple);
393 }
394 }
395 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000396
397 // Get the target specific parser.
398 std::string Error;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000399 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
400 Error);
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000401 if (!TheTarget) {
402 if (Obj)
403 report_error(Obj->getFileName(), "can't find target: " + Error);
404 else
405 error("can't find target: " + Error);
406 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000407
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000408 // Update the triple name and return the found target.
409 TripleName = TheTriple.getTriple();
410 return TheTarget;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000411}
412
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000413bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
Rafael Espindola704cd842015-07-06 15:47:43 +0000414 return a.getOffset() < b.getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +0000415}
416
Rafael Espindola37070a52015-06-03 04:48:06 +0000417template <class ELFT>
Rafael Espindola37070a52015-06-03 04:48:06 +0000418static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000419 const RelocationRef &RelRef,
Rafael Espindola37070a52015-06-03 04:48:06 +0000420 SmallVectorImpl<char> &Result) {
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000421 DataRefImpl Rel = RelRef.getRawDataRefImpl();
422
Rafael Espindola37070a52015-06-03 04:48:06 +0000423 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
424 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000425 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
426
Rafael Espindola37070a52015-06-03 04:48:06 +0000427 const ELFFile<ELFT> &EF = *Obj->getELFFile();
428
Davide Italiano6cf09262016-11-16 05:10:28 +0000429 auto SecOrErr = EF.getSection(Rel.d.a);
430 if (!SecOrErr)
431 return errorToErrorCode(SecOrErr.takeError());
Rafael Espindola6def3042015-07-01 12:56:27 +0000432 const Elf_Shdr *Sec = *SecOrErr;
Davide Italiano6cf09262016-11-16 05:10:28 +0000433 auto SymTabOrErr = EF.getSection(Sec->sh_link);
434 if (!SymTabOrErr)
435 return errorToErrorCode(SymTabOrErr.takeError());
Rafael Espindola6def3042015-07-01 12:56:27 +0000436 const Elf_Shdr *SymTab = *SymTabOrErr;
Rafael Espindola719dc7c2015-06-29 12:38:31 +0000437 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
438 SymTab->sh_type == ELF::SHT_DYNSYM);
Davide Italiano6cf09262016-11-16 05:10:28 +0000439 auto StrTabSec = EF.getSection(SymTab->sh_link);
440 if (!StrTabSec)
441 return errorToErrorCode(StrTabSec.takeError());
442 auto StrTabOrErr = EF.getStringTable(*StrTabSec);
443 if (!StrTabOrErr)
444 return errorToErrorCode(StrTabOrErr.takeError());
Rafael Espindola6a1bfb22015-06-29 14:39:25 +0000445 StringRef StrTab = *StrTabOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000446 int64_t addend = 0;
Paul Semelcb0f0432018-06-07 13:30:55 +0000447 // If there is no Symbol associated with the relocation, we set the undef
448 // boolean value to 'true'. This will prevent us from calling functions that
449 // requires the relocation to be associated with a symbol.
450 bool undef = false;
Rafael Espindola6def3042015-07-01 12:56:27 +0000451 switch (Sec->sh_type) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000452 default:
453 return object_error::parse_failed;
454 case ELF::SHT_REL: {
Rafael Espindola37070a52015-06-03 04:48:06 +0000455 // TODO: Read implicit addend from section data.
456 break;
457 }
458 case ELF::SHT_RELA: {
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000459 const Elf_Rela *ERela = Obj->getRela(Rel);
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000460 addend = ERela->r_addend;
Paul Semelcb0f0432018-06-07 13:30:55 +0000461 undef = ERela->getSymbol(false) == 0;
Rafael Espindola37070a52015-06-03 04:48:06 +0000462 break;
463 }
464 }
Rafael Espindola75d5b542015-06-03 05:14:22 +0000465 StringRef Target;
Paul Semelcb0f0432018-06-07 13:30:55 +0000466 if (!undef) {
467 symbol_iterator SI = RelRef.getSymbol();
468 const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
469 if (symb->getType() == ELF::STT_SECTION) {
470 Expected<section_iterator> SymSI = SI->getSection();
471 if (!SymSI)
472 return errorToErrorCode(SymSI.takeError());
473 const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
474 auto SecName = EF.getSectionName(SymSec);
475 if (!SecName)
476 return errorToErrorCode(SecName.takeError());
477 Target = *SecName;
478 } else {
479 Expected<StringRef> SymName = symb->getName(StrTab);
480 if (!SymName)
481 return errorToErrorCode(SymName.takeError());
482 Target = *SymName;
483 }
484 } else
485 Target = "*ABS*";
Daniel Cedermand72b9fd2018-06-01 05:31:58 +0000486
487 // Default scheme is to print Target, as well as "+ <addend>" for nonzero
488 // addend. Should be acceptable for all normal purposes.
489 std::string fmtbuf;
490 raw_string_ostream fmt(fmtbuf);
491 fmt << Target;
492 if (addend != 0)
493 fmt << (addend < 0 ? "" : "+") << addend;
494 fmt.flush();
495 Result.append(fmtbuf.begin(), fmtbuf.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000496 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000497}
498
499static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000500 const RelocationRef &Rel,
Rafael Espindola37070a52015-06-03 04:48:06 +0000501 SmallVectorImpl<char> &Result) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000502 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
503 return getRelocationValueString(ELF32LE, Rel, Result);
504 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
505 return getRelocationValueString(ELF64LE, Rel, Result);
506 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
507 return getRelocationValueString(ELF32BE, Rel, Result);
508 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
509 return getRelocationValueString(ELF64BE, Rel, Result);
510}
511
512static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
513 const RelocationRef &Rel,
514 SmallVectorImpl<char> &Result) {
515 symbol_iterator SymI = Rel.getSymbol();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000516 Expected<StringRef> SymNameOrErr = SymI->getName();
517 if (!SymNameOrErr)
518 return errorToErrorCode(SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000519 StringRef SymName = *SymNameOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000520 Result.append(SymName.begin(), SymName.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000521 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000522}
523
524static void printRelocationTargetName(const MachOObjectFile *O,
525 const MachO::any_relocation_info &RE,
526 raw_string_ostream &fmt) {
527 bool IsScattered = O->isRelocationScattered(RE);
528
529 // Target of a scattered relocation is an address. In the interest of
530 // generating pretty output, scan through the symbol table looking for a
531 // symbol that aligns with that address. If we find one, print it.
532 // Otherwise, we just print the hex address of the target.
533 if (IsScattered) {
534 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
535
536 for (const SymbolRef &Symbol : O->symbols()) {
537 std::error_code ec;
Kevin Enderby931cb652016-06-24 18:24:42 +0000538 Expected<uint64_t> Addr = Symbol.getAddress();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000539 if (!Addr)
540 report_error(O->getFileName(), Addr.takeError());
Rafael Espindolaed067c42015-07-03 18:19:00 +0000541 if (*Addr != Val)
Rafael Espindola37070a52015-06-03 04:48:06 +0000542 continue;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000543 Expected<StringRef> Name = Symbol.getName();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000544 if (!Name)
545 report_error(O->getFileName(), Name.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000546 fmt << *Name;
Rafael Espindola37070a52015-06-03 04:48:06 +0000547 return;
548 }
549
550 // If we couldn't find a symbol that this relocation refers to, try
551 // to find a section beginning instead.
Colin LeMahieu77804be2015-07-29 15:45:39 +0000552 for (const SectionRef &Section : ToolSectionFilter(*O)) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000553 std::error_code ec;
554
555 StringRef Name;
556 uint64_t Addr = Section.getAddress();
557 if (Addr != Val)
558 continue;
559 if ((ec = Section.getName(Name)))
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000560 report_error(O->getFileName(), ec);
Rafael Espindola37070a52015-06-03 04:48:06 +0000561 fmt << Name;
562 return;
563 }
564
565 fmt << format("0x%x", Val);
566 return;
567 }
568
569 StringRef S;
570 bool isExtern = O->getPlainRelocationExternal(RE);
571 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
572
Martin Storsjo8c0317d2017-07-13 17:03:02 +0000573 if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND) {
Simon Dardis38867052017-08-07 12:29:38 +0000574 fmt << format("0x%0" PRIx64, Val);
Martin Storsjo8c0317d2017-07-13 17:03:02 +0000575 return;
576 } else if (isExtern) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000577 symbol_iterator SI = O->symbol_begin();
578 advance(SI, Val);
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000579 Expected<StringRef> SOrErr = SI->getName();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000580 if (!SOrErr)
581 report_error(O->getFileName(), SOrErr.takeError());
Davide Italianoccd53fe2015-08-05 07:18:31 +0000582 S = *SOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000583 } else {
584 section_iterator SI = O->section_begin();
585 // Adjust for the fact that sections are 1-indexed.
Kevin Enderby3fc91882017-11-03 21:32:44 +0000586 if (Val == 0) {
587 fmt << "0 (?,?)";
588 return;
589 }
590 uint32_t i = Val - 1;
591 while (i != 0 && SI != O->section_end()) {
592 i--;
593 advance(SI, 1);
594 }
595 if (SI == O->section_end())
596 fmt << Val << " (?,?)";
597 else
598 SI->getName(S);
Rafael Espindola37070a52015-06-03 04:48:06 +0000599 }
600
601 fmt << S;
602}
603
Sam Clegg4df5d762017-06-27 20:40:53 +0000604static std::error_code getRelocationValueString(const WasmObjectFile *Obj,
605 const RelocationRef &RelRef,
606 SmallVectorImpl<char> &Result) {
607 const wasm::WasmRelocation& Rel = Obj->getWasmRelocation(RelRef);
Sam Cleggf676cdd2018-04-26 16:41:51 +0000608 symbol_iterator SI = RelRef.getSymbol();
Sam Clegg4df5d762017-06-27 20:40:53 +0000609 std::string fmtbuf;
610 raw_string_ostream fmt(fmtbuf);
Sam Clegg8c4b0ce2018-04-26 17:05:04 +0000611 if (SI == Obj->symbol_end()) {
612 // Not all wasm relocations have symbols associated with them.
613 // In particular R_WEBASSEMBLY_TYPE_INDEX_LEB.
Sam Cleggf676cdd2018-04-26 16:41:51 +0000614 fmt << Rel.Index;
615 } else {
Sam Clegg8c4b0ce2018-04-26 17:05:04 +0000616 Expected<StringRef> SymNameOrErr = SI->getName();
617 if (!SymNameOrErr)
618 return errorToErrorCode(SymNameOrErr.takeError());
Sam Cleggf676cdd2018-04-26 16:41:51 +0000619 StringRef SymName = *SymNameOrErr;
620 Result.append(SymName.begin(), SymName.end());
621 }
622 fmt << (Rel.Addend < 0 ? "" : "+") << Rel.Addend;
Sam Clegg4df5d762017-06-27 20:40:53 +0000623 fmt.flush();
624 Result.append(fmtbuf.begin(), fmtbuf.end());
625 return std::error_code();
626}
627
Rafael Espindola37070a52015-06-03 04:48:06 +0000628static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
629 const RelocationRef &RelRef,
630 SmallVectorImpl<char> &Result) {
631 DataRefImpl Rel = RelRef.getRawDataRefImpl();
632 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
633
634 unsigned Arch = Obj->getArch();
635
636 std::string fmtbuf;
637 raw_string_ostream fmt(fmtbuf);
638 unsigned Type = Obj->getAnyRelocationType(RE);
639 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
640
641 // Determine any addends that should be displayed with the relocation.
642 // These require decoding the relocation type, which is triple-specific.
643
644 // X86_64 has entirely custom relocation types.
645 if (Arch == Triple::x86_64) {
646 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
647
648 switch (Type) {
649 case MachO::X86_64_RELOC_GOT_LOAD:
650 case MachO::X86_64_RELOC_GOT: {
651 printRelocationTargetName(Obj, RE, fmt);
652 fmt << "@GOT";
653 if (isPCRel)
654 fmt << "PCREL";
655 break;
656 }
657 case MachO::X86_64_RELOC_SUBTRACTOR: {
658 DataRefImpl RelNext = Rel;
659 Obj->moveRelocationNext(RelNext);
660 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
661
662 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
663 // X86_64_RELOC_UNSIGNED.
664 // NOTE: Scattered relocations don't exist on x86_64.
665 unsigned RType = Obj->getAnyRelocationType(RENext);
666 if (RType != MachO::X86_64_RELOC_UNSIGNED)
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000667 report_error(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
668 "X86_64_RELOC_SUBTRACTOR.");
Rafael Espindola37070a52015-06-03 04:48:06 +0000669
670 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
671 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
672 printRelocationTargetName(Obj, RENext, fmt);
673 fmt << "-";
674 printRelocationTargetName(Obj, RE, fmt);
675 break;
676 }
677 case MachO::X86_64_RELOC_TLV:
678 printRelocationTargetName(Obj, RE, fmt);
679 fmt << "@TLV";
680 if (isPCRel)
681 fmt << "P";
682 break;
683 case MachO::X86_64_RELOC_SIGNED_1:
684 printRelocationTargetName(Obj, RE, fmt);
685 fmt << "-1";
686 break;
687 case MachO::X86_64_RELOC_SIGNED_2:
688 printRelocationTargetName(Obj, RE, fmt);
689 fmt << "-2";
690 break;
691 case MachO::X86_64_RELOC_SIGNED_4:
692 printRelocationTargetName(Obj, RE, fmt);
693 fmt << "-4";
694 break;
695 default:
696 printRelocationTargetName(Obj, RE, fmt);
697 break;
698 }
699 // X86 and ARM share some relocation types in common.
700 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
701 Arch == Triple::ppc) {
702 // Generic relocation types...
703 switch (Type) {
704 case MachO::GENERIC_RELOC_PAIR: // prints no info
Rui Ueyama7d099192015-06-09 15:20:42 +0000705 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000706 case MachO::GENERIC_RELOC_SECTDIFF: {
707 DataRefImpl RelNext = Rel;
708 Obj->moveRelocationNext(RelNext);
709 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
710
711 // X86 sect diff's must be followed by a relocation of type
712 // GENERIC_RELOC_PAIR.
713 unsigned RType = Obj->getAnyRelocationType(RENext);
714
715 if (RType != MachO::GENERIC_RELOC_PAIR)
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000716 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
717 "GENERIC_RELOC_SECTDIFF.");
Rafael Espindola37070a52015-06-03 04:48:06 +0000718
719 printRelocationTargetName(Obj, RE, fmt);
720 fmt << "-";
721 printRelocationTargetName(Obj, RENext, fmt);
722 break;
723 }
724 }
725
726 if (Arch == Triple::x86 || Arch == Triple::ppc) {
727 switch (Type) {
728 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
729 DataRefImpl RelNext = Rel;
730 Obj->moveRelocationNext(RelNext);
731 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
732
733 // X86 sect diff's must be followed by a relocation of type
734 // GENERIC_RELOC_PAIR.
735 unsigned RType = Obj->getAnyRelocationType(RENext);
736 if (RType != MachO::GENERIC_RELOC_PAIR)
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000737 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
738 "GENERIC_RELOC_LOCAL_SECTDIFF.");
Rafael Espindola37070a52015-06-03 04:48:06 +0000739
740 printRelocationTargetName(Obj, RE, fmt);
741 fmt << "-";
742 printRelocationTargetName(Obj, RENext, fmt);
743 break;
744 }
745 case MachO::GENERIC_RELOC_TLV: {
746 printRelocationTargetName(Obj, RE, fmt);
747 fmt << "@TLV";
748 if (IsPCRel)
749 fmt << "P";
750 break;
751 }
752 default:
753 printRelocationTargetName(Obj, RE, fmt);
754 }
755 } else { // ARM-specific relocations
756 switch (Type) {
757 case MachO::ARM_RELOC_HALF:
758 case MachO::ARM_RELOC_HALF_SECTDIFF: {
759 // Half relocations steal a bit from the length field to encode
760 // whether this is an upper16 or a lower16 relocation.
Martin Storsjofa5183b2017-07-13 05:54:08 +0000761 bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
Rafael Espindola37070a52015-06-03 04:48:06 +0000762
763 if (isUpper)
764 fmt << ":upper16:(";
765 else
766 fmt << ":lower16:(";
767 printRelocationTargetName(Obj, RE, fmt);
768
769 DataRefImpl RelNext = Rel;
770 Obj->moveRelocationNext(RelNext);
771 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
772
773 // ARM half relocs must be followed by a relocation of type
774 // ARM_RELOC_PAIR.
775 unsigned RType = Obj->getAnyRelocationType(RENext);
776 if (RType != MachO::ARM_RELOC_PAIR)
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000777 report_error(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
778 "ARM_RELOC_HALF");
Rafael Espindola37070a52015-06-03 04:48:06 +0000779
780 // NOTE: The half of the target virtual address is stashed in the
781 // address field of the secondary relocation, but we can't reverse
782 // engineer the constant offset from it without decoding the movw/movt
783 // instruction to find the other half in its immediate field.
784
785 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
786 // symbol/section pointer of the follow-on relocation.
787 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
788 fmt << "-";
789 printRelocationTargetName(Obj, RENext, fmt);
790 }
791
792 fmt << ")";
793 break;
794 }
795 default: { printRelocationTargetName(Obj, RE, fmt); }
796 }
797 }
798 } else
799 printRelocationTargetName(Obj, RE, fmt);
800
801 fmt.flush();
802 Result.append(fmtbuf.begin(), fmtbuf.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000803 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000804}
805
806static std::error_code getRelocationValueString(const RelocationRef &Rel,
807 SmallVectorImpl<char> &Result) {
Rafael Espindola854038e2015-06-26 14:51:16 +0000808 const ObjectFile *Obj = Rel.getObject();
Rafael Espindola37070a52015-06-03 04:48:06 +0000809 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
810 return getRelocationValueString(ELF, Rel, Result);
811 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
812 return getRelocationValueString(COFF, Rel, Result);
Sam Clegg4df5d762017-06-27 20:40:53 +0000813 if (auto *Wasm = dyn_cast<WasmObjectFile>(Obj))
814 return getRelocationValueString(Wasm, Rel, Result);
815 if (auto *MachO = dyn_cast<MachOObjectFile>(Obj))
816 return getRelocationValueString(MachO, Rel, Result);
817 llvm_unreachable("unknown object file format");
Rafael Espindola37070a52015-06-03 04:48:06 +0000818}
819
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000820/// Indicates whether this relocation should hidden when listing
Rafael Espindola0ad71d92015-06-30 03:41:26 +0000821/// relocations, usually because it is the trailing part of a multipart
822/// relocation that will be printed as part of the leading relocation.
823static bool getHidden(RelocationRef RelRef) {
824 const ObjectFile *Obj = RelRef.getObject();
825 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
826 if (!MachO)
827 return false;
828
829 unsigned Arch = MachO->getArch();
830 DataRefImpl Rel = RelRef.getRawDataRefImpl();
831 uint64_t Type = MachO->getRelocationType(Rel);
832
833 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
834 // is always hidden.
835 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
836 if (Type == MachO::GENERIC_RELOC_PAIR)
837 return true;
838 } else if (Arch == Triple::x86_64) {
839 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
840 // an X86_64_RELOC_SUBTRACTOR.
841 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
842 DataRefImpl RelPrev = Rel;
843 RelPrev.d.a--;
844 uint64_t PrevType = MachO->getRelocationType(RelPrev);
845 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
846 return true;
847 }
848 }
849
850 return false;
851}
852
Sid Manningd9f28732018-05-14 19:46:08 +0000853namespace {
854class SourcePrinter {
855protected:
856 DILineInfo OldLineInfo;
857 const ObjectFile *Obj = nullptr;
858 std::unique_ptr<symbolize::LLVMSymbolizer> Symbolizer;
859 // File name to file contents of source
860 std::unordered_map<std::string, std::unique_ptr<MemoryBuffer>> SourceCache;
861 // Mark the line endings of the cached source
862 std::unordered_map<std::string, std::vector<StringRef>> LineCache;
863
864private:
865 bool cacheSource(const DILineInfo& LineInfoFile);
866
867public:
868 SourcePrinter() = default;
869 SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch) : Obj(Obj) {
870 symbolize::LLVMSymbolizer::Options SymbolizerOpts(
871 DILineInfoSpecifier::FunctionNameKind::None, true, false, false,
872 DefaultArch);
873 Symbolizer.reset(new symbolize::LLVMSymbolizer(SymbolizerOpts));
874 }
875 virtual ~SourcePrinter() = default;
876 virtual void printSourceLine(raw_ostream &OS, uint64_t Address,
877 StringRef Delimiter = "; ");
878};
879
880bool SourcePrinter::cacheSource(const DILineInfo &LineInfo) {
881 std::unique_ptr<MemoryBuffer> Buffer;
882 if (LineInfo.Source) {
883 Buffer = MemoryBuffer::getMemBuffer(*LineInfo.Source);
884 } else {
885 auto BufferOrError = MemoryBuffer::getFile(LineInfo.FileName);
886 if (!BufferOrError)
887 return false;
888 Buffer = std::move(*BufferOrError);
889 }
890 // Chomp the file to get lines
891 size_t BufferSize = Buffer->getBufferSize();
892 const char *BufferStart = Buffer->getBufferStart();
893 for (const char *Start = BufferStart, *End = BufferStart;
894 End < BufferStart + BufferSize; End++)
895 if (*End == '\n' || End == BufferStart + BufferSize - 1 ||
896 (*End == '\r' && *(End + 1) == '\n')) {
897 LineCache[LineInfo.FileName].push_back(StringRef(Start, End - Start));
898 if (*End == '\r')
899 End++;
900 Start = End + 1;
901 }
902 SourceCache[LineInfo.FileName] = std::move(Buffer);
903 return true;
904}
905
906void SourcePrinter::printSourceLine(raw_ostream &OS, uint64_t Address,
907 StringRef Delimiter) {
908 if (!Symbolizer)
909 return;
910 DILineInfo LineInfo = DILineInfo();
911 auto ExpectecLineInfo =
912 Symbolizer->symbolizeCode(Obj->getFileName(), Address);
913 if (!ExpectecLineInfo)
914 consumeError(ExpectecLineInfo.takeError());
915 else
916 LineInfo = *ExpectecLineInfo;
917
918 if ((LineInfo.FileName == "<invalid>") || OldLineInfo.Line == LineInfo.Line ||
919 LineInfo.Line == 0)
920 return;
921
922 if (PrintLines)
923 OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line << "\n";
924 if (PrintSource) {
925 if (SourceCache.find(LineInfo.FileName) == SourceCache.end())
926 if (!cacheSource(LineInfo))
927 return;
928 auto FileBuffer = SourceCache.find(LineInfo.FileName);
929 if (FileBuffer != SourceCache.end()) {
930 auto LineBuffer = LineCache.find(LineInfo.FileName);
931 if (LineBuffer != LineCache.end()) {
932 if (LineInfo.Line > LineBuffer->second.size())
933 return;
934 // Vector begins at 0, line numbers are non-zero
935 OS << Delimiter << LineBuffer->second[LineInfo.Line - 1].ltrim()
936 << "\n";
937 }
938 }
939 }
940 OldLineInfo = LineInfo;
941}
942
943static bool isArmElf(const ObjectFile *Obj) {
944 return (Obj->isELF() &&
945 (Obj->getArch() == Triple::aarch64 ||
946 Obj->getArch() == Triple::aarch64_be ||
947 Obj->getArch() == Triple::arm || Obj->getArch() == Triple::armeb ||
948 Obj->getArch() == Triple::thumb ||
949 Obj->getArch() == Triple::thumbeb));
950}
951
952class PrettyPrinter {
953public:
954 virtual ~PrettyPrinter() = default;
955 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
956 ArrayRef<uint8_t> Bytes, uint64_t Address,
957 raw_ostream &OS, StringRef Annot,
958 MCSubtargetInfo const &STI, SourcePrinter *SP,
959 std::vector<RelocationRef> *Rels = nullptr) {
960 if (SP && (PrintSource || PrintLines))
961 SP->printSourceLine(OS, Address);
962 if (!NoLeadingAddr)
963 OS << format("%8" PRIx64 ":", Address);
964 if (!NoShowRawInsn) {
965 OS << "\t";
966 dumpBytes(Bytes, OS);
967 }
968 if (MI)
969 IP.printInst(MI, OS, "", STI);
970 else
971 OS << " <unknown>";
972 }
973};
974PrettyPrinter PrettyPrinterInst;
975class HexagonPrettyPrinter : public PrettyPrinter {
976public:
977 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
978 raw_ostream &OS) {
979 uint32_t opcode =
980 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
981 if (!NoLeadingAddr)
982 OS << format("%8" PRIx64 ":", Address);
983 if (!NoShowRawInsn) {
984 OS << "\t";
985 dumpBytes(Bytes.slice(0, 4), OS);
986 OS << format("%08" PRIx32, opcode);
987 }
988 }
989 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
990 uint64_t Address, raw_ostream &OS, StringRef Annot,
991 MCSubtargetInfo const &STI, SourcePrinter *SP,
992 std::vector<RelocationRef> *Rels) override {
993 if (SP && (PrintSource || PrintLines))
994 SP->printSourceLine(OS, Address, "");
995 if (!MI) {
996 printLead(Bytes, Address, OS);
997 OS << " <unknown>";
998 return;
999 }
1000 std::string Buffer;
1001 {
1002 raw_string_ostream TempStream(Buffer);
1003 IP.printInst(MI, TempStream, "", STI);
1004 }
1005 StringRef Contents(Buffer);
1006 // Split off bundle attributes
1007 auto PacketBundle = Contents.rsplit('\n');
1008 // Split off first instruction from the rest
1009 auto HeadTail = PacketBundle.first.split('\n');
1010 auto Preamble = " { ";
1011 auto Separator = "";
1012 StringRef Fmt = "\t\t\t%08" PRIx64 ": ";
1013 std::vector<RelocationRef>::const_iterator rel_cur = Rels->begin();
1014 std::vector<RelocationRef>::const_iterator rel_end = Rels->end();
1015
1016 // Hexagon's packets require relocations to be inline rather than
1017 // clustered at the end of the packet.
1018 auto PrintReloc = [&]() -> void {
1019 while ((rel_cur != rel_end) && (rel_cur->getOffset() <= Address)) {
1020 if (rel_cur->getOffset() == Address) {
1021 SmallString<16> name;
1022 SmallString<32> val;
1023 rel_cur->getTypeName(name);
1024 error(getRelocationValueString(*rel_cur, val));
1025 OS << Separator << format(Fmt.data(), Address) << name << "\t" << val
1026 << "\n";
1027 return;
1028 }
1029 rel_cur++;
1030 }
1031 };
1032
1033 while(!HeadTail.first.empty()) {
1034 OS << Separator;
1035 Separator = "\n";
1036 if (SP && (PrintSource || PrintLines))
1037 SP->printSourceLine(OS, Address, "");
1038 printLead(Bytes, Address, OS);
1039 OS << Preamble;
1040 Preamble = " ";
1041 StringRef Inst;
1042 auto Duplex = HeadTail.first.split('\v');
1043 if(!Duplex.second.empty()){
1044 OS << Duplex.first;
1045 OS << "; ";
1046 Inst = Duplex.second;
1047 }
1048 else
1049 Inst = HeadTail.first;
1050 OS << Inst;
1051 HeadTail = HeadTail.second.split('\n');
1052 if (HeadTail.first.empty())
1053 OS << " } " << PacketBundle.second;
1054 PrintReloc();
1055 Bytes = Bytes.slice(4);
1056 Address += 4;
1057 }
1058 }
1059};
1060HexagonPrettyPrinter HexagonPrettyPrinterInst;
1061
1062class AMDGCNPrettyPrinter : public PrettyPrinter {
1063public:
1064 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1065 uint64_t Address, raw_ostream &OS, StringRef Annot,
1066 MCSubtargetInfo const &STI, SourcePrinter *SP,
1067 std::vector<RelocationRef> *Rels) override {
1068 if (SP && (PrintSource || PrintLines))
1069 SP->printSourceLine(OS, Address);
1070
1071 typedef support::ulittle32_t U32;
1072
1073 if (MI) {
1074 SmallString<40> InstStr;
1075 raw_svector_ostream IS(InstStr);
1076
1077 IP.printInst(MI, IS, "", STI);
1078
1079 OS << left_justify(IS.str(), 60);
1080 } else {
1081 // an unrecognized encoding - this is probably data so represent it
1082 // using the .long directive, or .byte directive if fewer than 4 bytes
1083 // remaining
1084 if (Bytes.size() >= 4) {
1085 OS << format("\t.long 0x%08" PRIx32 " ",
1086 static_cast<uint32_t>(*reinterpret_cast<const U32*>(Bytes.data())));
1087 OS.indent(42);
1088 } else {
1089 OS << format("\t.byte 0x%02" PRIx8, Bytes[0]);
1090 for (unsigned int i = 1; i < Bytes.size(); i++)
1091 OS << format(", 0x%02" PRIx8, Bytes[i]);
1092 OS.indent(55 - (6 * Bytes.size()));
1093 }
1094 }
1095
1096 OS << format("// %012" PRIX64 ": ", Address);
1097 if (Bytes.size() >=4) {
1098 for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
1099 Bytes.size() / sizeof(U32)))
1100 // D should be explicitly casted to uint32_t here as it is passed
1101 // by format to snprintf as vararg.
1102 OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D));
1103 } else {
1104 for (unsigned int i = 0; i < Bytes.size(); i++)
1105 OS << format("%02" PRIX8 " ", Bytes[i]);
1106 }
1107
1108 if (!Annot.empty())
1109 OS << "// " << Annot;
1110 }
1111};
1112AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
1113
1114class BPFPrettyPrinter : public PrettyPrinter {
1115public:
1116 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1117 uint64_t Address, raw_ostream &OS, StringRef Annot,
1118 MCSubtargetInfo const &STI, SourcePrinter *SP,
1119 std::vector<RelocationRef> *Rels) override {
1120 if (SP && (PrintSource || PrintLines))
1121 SP->printSourceLine(OS, Address);
1122 if (!NoLeadingAddr)
1123 OS << format("%8" PRId64 ":", Address / 8);
1124 if (!NoShowRawInsn) {
1125 OS << "\t";
1126 dumpBytes(Bytes, OS);
1127 }
1128 if (MI)
1129 IP.printInst(MI, OS, "", STI);
1130 else
1131 OS << " <unknown>";
1132 }
1133};
1134BPFPrettyPrinter BPFPrettyPrinterInst;
1135
1136PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
1137 switch(Triple.getArch()) {
1138 default:
1139 return PrettyPrinterInst;
1140 case Triple::hexagon:
1141 return HexagonPrettyPrinterInst;
1142 case Triple::amdgcn:
1143 return AMDGCNPrettyPrinterInst;
1144 case Triple::bpfel:
1145 case Triple::bpfeb:
1146 return BPFPrettyPrinterInst;
1147 }
1148}
1149}
1150
Sam Koltonc05d7782016-08-17 10:17:57 +00001151static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) {
1152 assert(Obj->isELF());
1153 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1154 return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1155 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1156 return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1157 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1158 return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1159 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1160 return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1161 llvm_unreachable("Unsupported binary format");
1162}
1163
Sam Parker5fba45a2017-02-08 09:44:18 +00001164template <class ELFT> static void
1165addDynamicElfSymbols(const ELFObjectFile<ELFT> *Obj,
1166 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1167 for (auto Symbol : Obj->getDynamicSymbolIterators()) {
1168 uint8_t SymbolType = Symbol.getELFType();
1169 if (SymbolType != ELF::STT_FUNC || Symbol.getSize() == 0)
1170 continue;
1171
1172 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
1173 if (!AddressOrErr)
1174 report_error(Obj->getFileName(), AddressOrErr.takeError());
1175 uint64_t Address = *AddressOrErr;
1176
1177 Expected<StringRef> Name = Symbol.getName();
1178 if (!Name)
1179 report_error(Obj->getFileName(), Name.takeError());
1180 if (Name->empty())
1181 continue;
1182
1183 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1184 if (!SectionOrErr)
1185 report_error(Obj->getFileName(), SectionOrErr.takeError());
1186 section_iterator SecI = *SectionOrErr;
1187 if (SecI == Obj->section_end())
1188 continue;
1189
1190 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1191 }
1192}
1193
1194static void
1195addDynamicElfSymbols(const ObjectFile *Obj,
1196 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1197 assert(Obj->isELF());
1198 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1199 addDynamicElfSymbols(Elf32LEObj, AllSymbols);
1200 else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1201 addDynamicElfSymbols(Elf64LEObj, AllSymbols);
1202 else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1203 addDynamicElfSymbols(Elf32BEObj, AllSymbols);
1204 else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1205 addDynamicElfSymbols(Elf64BEObj, AllSymbols);
1206 else
1207 llvm_unreachable("Unsupported binary format");
1208}
1209
Michael J. Spencer51862b32011-10-13 22:17:18 +00001210static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001211 if (StartAddress > StopAddress)
1212 error("Start address should be less than stop address");
1213
Jim Grosbachaf9aec02012-08-07 17:53:14 +00001214 const Target *TheTarget = getTarget(Obj);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001215
Jack Carter551efd72012-08-28 19:24:49 +00001216 // Package up features to be passed to target/subtarget
Daniel Sanders1d148642016-06-16 09:17:03 +00001217 SubtargetFeatures Features = Obj->getFeatures();
Jack Carter551efd72012-08-28 19:24:49 +00001218 if (MAttrs.size()) {
Jack Carter551efd72012-08-28 19:24:49 +00001219 for (unsigned i = 0; i != MAttrs.size(); ++i)
1220 Features.AddFeature(MAttrs[i]);
Jack Carter551efd72012-08-28 19:24:49 +00001221 }
1222
Ahmed Charles56440fd2014-03-06 05:51:42 +00001223 std::unique_ptr<const MCRegisterInfo> MRI(
1224 TheTarget->createMCRegInfo(TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +00001225 if (!MRI)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001226 report_error(Obj->getFileName(), "no register info for target " +
1227 TripleName);
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001228
1229 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00001230 std::unique_ptr<const MCAsmInfo> AsmInfo(
1231 TheTarget->createMCAsmInfo(*MRI, TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +00001232 if (!AsmInfo)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001233 report_error(Obj->getFileName(), "no assembly info for target " +
1234 TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +00001235 std::unique_ptr<const MCSubtargetInfo> STI(
Daniel Sanders1d148642016-06-16 09:17:03 +00001236 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
Davide Italiano711e4952015-12-17 01:59:50 +00001237 if (!STI)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001238 report_error(Obj->getFileName(), "no subtarget info for target " +
1239 TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +00001240 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
Davide Italiano711e4952015-12-17 01:59:50 +00001241 if (!MII)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001242 report_error(Obj->getFileName(), "no instruction info for target " +
1243 TripleName);
Sam Kolton3381d7a2016-10-06 13:46:08 +00001244 MCObjectFileInfo MOFI;
1245 MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI);
1246 // FIXME: for now initialize MCObjectFileInfo with default values
Rafael Espindola9f929952017-08-02 20:32:26 +00001247 MOFI.InitMCObjectFileInfo(Triple(TripleName), false, Ctx);
Lang Hamesa1bc0f52014-04-15 04:40:56 +00001248
1249 std::unique_ptr<MCDisassembler> DisAsm(
1250 TheTarget->createMCDisassembler(*STI, Ctx));
Davide Italiano711e4952015-12-17 01:59:50 +00001251 if (!DisAsm)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001252 report_error(Obj->getFileName(), "no disassembler for target " +
1253 TripleName);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001254
Ahmed Charles56440fd2014-03-06 05:51:42 +00001255 std::unique_ptr<const MCInstrAnalysis> MIA(
1256 TheTarget->createMCInstrAnalysis(MII.get()));
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001257
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001258 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Daniel Sanders50f17232015-09-15 16:17:27 +00001259 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1260 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
Davide Italiano711e4952015-12-17 01:59:50 +00001261 if (!IP)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001262 report_error(Obj->getFileName(), "no instruction printer for target " +
1263 TripleName);
Colin LeMahieu14ec76e2015-06-07 21:07:17 +00001264 IP->setPrintImmHex(PrintImmHex);
Colin LeMahieu35436a22015-05-29 14:48:25 +00001265 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001266
Greg Fitzgerald18432272014-03-20 22:55:15 +00001267 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
1268 "\t\t\t%08" PRIx64 ": ";
1269
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001270 SourcePrinter SP(Obj, TheTarget->getName());
1271
Mark Seaborn0929d3d2014-01-25 17:38:19 +00001272 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
1273 // in RelocSecs contain the relocations for section S.
Rafael Espindola4453e42942014-06-13 03:07:50 +00001274 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +00001275 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001276 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001277 section_iterator Sec2 = Section.getRelocatedSection();
Rafael Espindolab5155a52014-02-10 20:24:04 +00001278 if (Sec2 != Obj->section_end())
Alexey Samsonov48803e52014-03-13 14:37:36 +00001279 SectionRelocMap[*Sec2].push_back(Section);
Mark Seaborn0929d3d2014-01-25 17:38:19 +00001280 }
1281
David Majnemer81afca62015-07-07 22:06:59 +00001282 // Create a mapping from virtual address to symbol name. This is used to
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001283 // pretty print the symbols while disassembling.
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001284 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
Sterling Augustinebc78b622018-06-28 18:57:13 +00001285 SectionSymbolsTy AbsoluteSymbols;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001286 for (const SymbolRef &Symbol : Obj->symbols()) {
Kevin Enderby931cb652016-06-24 18:24:42 +00001287 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001288 if (!AddressOrErr)
1289 report_error(Obj->getFileName(), AddressOrErr.takeError());
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001290 uint64_t Address = *AddressOrErr;
David Majnemer2603a8fa2015-07-09 18:11:40 +00001291
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001292 Expected<StringRef> Name = Symbol.getName();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001293 if (!Name)
1294 report_error(Obj->getFileName(), Name.takeError());
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001295 if (Name->empty())
1296 continue;
David Majnemer81afca62015-07-07 22:06:59 +00001297
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001298 Expected<section_iterator> SectionOrErr = Symbol.getSection();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001299 if (!SectionOrErr)
1300 report_error(Obj->getFileName(), SectionOrErr.takeError());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001301
Sam Koltonc05d7782016-08-17 10:17:57 +00001302 uint8_t SymbolType = ELF::STT_NOTYPE;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001303 if (Obj->isELF())
Sam Koltonc05d7782016-08-17 10:17:57 +00001304 SymbolType = getElfSymbolType(Obj, Symbol);
David Majnemer81afca62015-07-07 22:06:59 +00001305
Sterling Augustinebc78b622018-06-28 18:57:13 +00001306 section_iterator SecI = *SectionOrErr;
1307 if (SecI != Obj->section_end())
1308 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1309 else
1310 AbsoluteSymbols.emplace_back(Address, *Name, SymbolType);
1311
Sam Koltonc05d7782016-08-17 10:17:57 +00001312
David Majnemer81afca62015-07-07 22:06:59 +00001313 }
Sam Parker5fba45a2017-02-08 09:44:18 +00001314 if (AllSymbols.empty() && Obj->isELF())
1315 addDynamicElfSymbols(Obj, AllSymbols);
David Majnemer81afca62015-07-07 22:06:59 +00001316
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001317 // Create a mapping from virtual address to section.
1318 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1319 for (SectionRef Sec : Obj->sections())
1320 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1321 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
1322
1323 // Linked executables (.exe and .dll files) typically don't include a real
1324 // symbol table but they might contain an export table.
1325 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
1326 for (const auto &ExportEntry : COFFObj->export_directories()) {
1327 StringRef Name;
1328 error(ExportEntry.getSymbolName(Name));
1329 if (Name.empty())
1330 continue;
1331 uint32_t RVA;
1332 error(ExportEntry.getExportRVA(RVA));
1333
1334 uint64_t VA = COFFObj->getImageBase() + RVA;
1335 auto Sec = std::upper_bound(
1336 SectionAddresses.begin(), SectionAddresses.end(), VA,
1337 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
1338 return LHS < RHS.first;
1339 });
1340 if (Sec != SectionAddresses.begin())
1341 --Sec;
1342 else
1343 Sec = SectionAddresses.end();
1344
1345 if (Sec != SectionAddresses.end())
Sam Koltonc05d7782016-08-17 10:17:57 +00001346 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
Sterling Augustinebc78b622018-06-28 18:57:13 +00001347 else
1348 AbsoluteSymbols.emplace_back(VA, Name, ELF::STT_NOTYPE);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001349 }
1350 }
1351
1352 // Sort all the symbols, this allows us to use a simple binary search to find
1353 // a symbol near an address.
1354 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1355 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
Sterling Augustinebc78b622018-06-28 18:57:13 +00001356 array_pod_sort(AbsoluteSymbols.begin(), AbsoluteSymbols.end());
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001357
Colin LeMahieu77804be2015-07-29 15:45:39 +00001358 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Colin LeMahieuf34933e2015-07-23 20:58:49 +00001359 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
Mark Seaborneb03ac52014-01-25 00:32:01 +00001360 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +00001361
Rafael Espindola80291272014-10-08 15:28:58 +00001362 uint64_t SectionAddr = Section.getAddress();
1363 uint64_t SectSize = Section.getSize();
David Majnemer185b5b12014-11-11 09:58:25 +00001364 if (!SectSize)
1365 continue;
Simon Atanasyan2b614e12014-02-24 22:12:11 +00001366
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001367 // Get the list of all the symbols in this section.
1368 SectionSymbolsTy &Symbols = AllSymbols[Section];
Davide Italianof0706882015-10-01 21:57:09 +00001369 std::vector<uint64_t> DataMappingSymsAddr;
1370 std::vector<uint64_t> TextMappingSymsAddr;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001371 if (isArmElf(Obj)) {
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001372 for (const auto &Symb : Symbols) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001373 uint64_t Address = std::get<0>(Symb);
1374 StringRef Name = std::get<1>(Symb);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001375 if (Name.startswith("$d"))
David Majnemer153722d2015-11-18 04:35:32 +00001376 DataMappingSymsAddr.push_back(Address - SectionAddr);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001377 if (Name.startswith("$x"))
David Majnemer153722d2015-11-18 04:35:32 +00001378 TextMappingSymsAddr.push_back(Address - SectionAddr);
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001379 if (Name.startswith("$a"))
1380 TextMappingSymsAddr.push_back(Address - SectionAddr);
1381 if (Name.startswith("$t"))
1382 TextMappingSymsAddr.push_back(Address - SectionAddr);
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001383 }
1384 }
1385
Mandeep Singh Grang8db564e2018-04-01 21:24:53 +00001386 llvm::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end());
1387 llvm::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end());
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001388
Sam Kolton3381d7a2016-10-06 13:46:08 +00001389 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1390 // AMDGPU disassembler uses symbolizer for printing labels
1391 std::unique_ptr<MCRelocationInfo> RelInfo(
1392 TheTarget->createMCRelocationInfo(TripleName, Ctx));
1393 if (RelInfo) {
1394 std::unique_ptr<MCSymbolizer> Symbolizer(
1395 TheTarget->createMCSymbolizer(
1396 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1397 DisAsm->setSymbolizer(std::move(Symbolizer));
1398 }
1399 }
1400
Michael J. Spencer51862b32011-10-13 22:17:18 +00001401 // Make a list of all the relocations for this section.
1402 std::vector<RelocationRef> Rels;
1403 if (InlineRelocs) {
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001404 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
1405 for (const RelocationRef &Reloc : RelocSec.relocations()) {
1406 Rels.push_back(Reloc);
1407 }
Michael J. Spencer51862b32011-10-13 22:17:18 +00001408 }
1409 }
1410
1411 // Sort relocations by address.
Mandeep Singh Grang8db564e2018-04-01 21:24:53 +00001412 llvm::sort(Rels.begin(), Rels.end(), RelocAddressLess);
Michael J. Spencer51862b32011-10-13 22:17:18 +00001413
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001414 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +00001415 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001416 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +00001417 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001418 }
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001419 StringRef SectionName;
1420 error(Section.getName(SectionName));
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001421
Rafael Espindola7884c952015-06-04 15:01:05 +00001422 // If the section has no symbol at the start, just insert a dummy one.
Sam Koltonc05d7782016-08-17 10:17:57 +00001423 if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) {
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001424 Symbols.insert(
1425 Symbols.begin(),
1426 std::make_tuple(SectionAddr, SectionName,
1427 Section.isText() ? ELF::STT_FUNC : ELF::STT_OBJECT));
Sam Koltonc05d7782016-08-17 10:17:57 +00001428 }
Alp Tokere69170a2014-06-26 22:52:05 +00001429
1430 SmallString<40> Comments;
1431 raw_svector_ostream CommentStream(Comments);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001432
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001433 StringRef BytesStr;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001434 error(Section.getContents(BytesStr));
Aaron Ballman106fd7b2014-11-12 14:01:17 +00001435 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1436 BytesStr.size());
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001437
Michael J. Spencer2670c252011-01-20 06:39:06 +00001438 uint64_t Size;
1439 uint64_t Index;
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001440 bool PrintedSection = false;
Michael J. Spencer2670c252011-01-20 06:39:06 +00001441
Michael J. Spencer51862b32011-10-13 22:17:18 +00001442 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
1443 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001444 // Disassemble symbol by symbol.
1445 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001446 uint64_t Start = std::get<0>(Symbols[si]) - SectionAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001447 // The end is either the section end or the beginning of the next
1448 // symbol.
1449 uint64_t End =
Sam Koltonc05d7782016-08-17 10:17:57 +00001450 (si == se - 1) ? SectSize : std::get<0>(Symbols[si + 1]) - SectionAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001451 // Don't try to disassemble beyond the end of section contents.
1452 if (End > SectSize)
1453 End = SectSize;
Rafael Espindolae45c7402014-08-17 16:31:39 +00001454 // If this symbol has the same address as the next symbol, then skip it.
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001455 if (Start >= End)
Michael J. Spenceree84f642011-10-13 20:37:08 +00001456 continue;
1457
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001458 // Check if we need to skip symbol
1459 // Skip if the symbol's data is not between StartAddress and StopAddress
1460 if (End + SectionAddr < StartAddress ||
1461 Start + SectionAddr > StopAddress) {
1462 continue;
1463 }
1464
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001465 /// Skip if user requested specific symbols and this is not in the list
1466 if (!DisasmFuncsSet.empty() &&
1467 !DisasmFuncsSet.count(std::get<1>(Symbols[si])))
1468 continue;
1469
1470 if (!PrintedSection) {
1471 PrintedSection = true;
1472 outs() << "Disassembly of section ";
1473 if (!SegmentName.empty())
1474 outs() << SegmentName << ",";
1475 outs() << SectionName << ':';
1476 }
1477
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001478 // Stop disassembly at the stop address specified
1479 if (End + SectionAddr > StopAddress)
1480 End = StopAddress - SectionAddr;
1481
Valery Pykhtinde048052016-04-07 07:24:01 +00001482 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001483 if (std::get<2>(Symbols[si]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1484 // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)
1485 Start += 256;
1486 }
1487 if (si == se - 1 ||
1488 std::get<2>(Symbols[si + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1489 // cut trailing zeroes at the end of kernel
1490 // cut up to 256 bytes
1491 const uint64_t EndAlign = 256;
1492 const auto Limit = End - (std::min)(EndAlign, End - Start);
1493 while (End > Limit &&
1494 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1495 End -= 4;
1496 }
Valery Pykhtinde048052016-04-07 07:24:01 +00001497 }
1498
Sam Koltonc05d7782016-08-17 10:17:57 +00001499 outs() << '\n' << std::get<1>(Symbols[si]) << ":\n";
Michael J. Spencer2670c252011-01-20 06:39:06 +00001500
Francis Visoiu Mistrih18346822018-04-19 17:02:57 +00001501 // Don't print raw contents of a virtual section. A virtual section
1502 // doesn't have any contents in the file.
1503 if (Section.isVirtual()) {
1504 outs() << "...\n";
1505 continue;
1506 }
1507
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001508#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +00001509 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001510#else
Mark Seaborneb03ac52014-01-25 00:32:01 +00001511 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001512#endif
1513
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001514 for (Index = Start; Index < End; Index += Size) {
1515 MCInst Inst;
Owen Andersona0c3b972011-09-15 23:38:46 +00001516
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001517 if (Index + SectionAddr < StartAddress ||
1518 Index + SectionAddr > StopAddress) {
1519 // skip byte by byte till StartAddress is reached
1520 Size = 1;
1521 continue;
1522 }
Davide Italianof0706882015-10-01 21:57:09 +00001523 // AArch64 ELF binaries can interleave data and text in the
1524 // same section. We rely on the markers introduced to
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001525 // understand what we need to dump. If the data marker is within a
1526 // function, it is denoted as a word/short etc
1527 if (isArmElf(Obj) && std::get<2>(Symbols[si]) != ELF::STT_OBJECT &&
1528 !DisassembleAll) {
Davide Italianof0706882015-10-01 21:57:09 +00001529 uint64_t Stride = 0;
1530
1531 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1532 DataMappingSymsAddr.end(), Index);
1533 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1534 // Switch to data.
1535 while (Index < End) {
1536 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1537 outs() << "\t";
1538 if (Index + 4 <= End) {
1539 Stride = 4;
1540 dumpBytes(Bytes.slice(Index, 4), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001541 outs() << "\t.word\t";
1542 uint32_t Data = 0;
1543 if (Obj->isLittleEndian()) {
1544 const auto Word =
1545 reinterpret_cast<const support::ulittle32_t *>(
1546 Bytes.data() + Index);
1547 Data = *Word;
1548 } else {
1549 const auto Word = reinterpret_cast<const support::ubig32_t *>(
1550 Bytes.data() + Index);
1551 Data = *Word;
1552 }
1553 outs() << "0x" << format("%08" PRIx32, Data);
Davide Italianof0706882015-10-01 21:57:09 +00001554 } else if (Index + 2 <= End) {
1555 Stride = 2;
1556 dumpBytes(Bytes.slice(Index, 2), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001557 outs() << "\t\t.short\t";
1558 uint16_t Data = 0;
1559 if (Obj->isLittleEndian()) {
1560 const auto Short =
1561 reinterpret_cast<const support::ulittle16_t *>(
1562 Bytes.data() + Index);
1563 Data = *Short;
1564 } else {
1565 const auto Short =
1566 reinterpret_cast<const support::ubig16_t *>(Bytes.data() +
1567 Index);
1568 Data = *Short;
1569 }
1570 outs() << "0x" << format("%04" PRIx16, Data);
Davide Italianof0706882015-10-01 21:57:09 +00001571 } else {
1572 Stride = 1;
1573 dumpBytes(Bytes.slice(Index, 1), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001574 outs() << "\t\t.byte\t";
1575 outs() << "0x" << format("%02" PRIx8, Bytes.slice(Index, 1)[0]);
Davide Italianof0706882015-10-01 21:57:09 +00001576 }
1577 Index += Stride;
1578 outs() << "\n";
1579 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1580 TextMappingSymsAddr.end(), Index);
1581 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1582 break;
1583 }
1584 }
1585 }
1586
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001587 // If there is a data symbol inside an ELF text section and we are only
1588 // disassembling text (applicable all architectures),
1589 // we are in a situation where we must print the data and not
1590 // disassemble it.
1591 if (Obj->isELF() && std::get<2>(Symbols[si]) == ELF::STT_OBJECT &&
1592 !DisassembleAll && Section.isText()) {
1593 // print out data up to 8 bytes at a time in hex and ascii
1594 uint8_t AsciiData[9] = {'\0'};
1595 uint8_t Byte;
1596 int NumBytes = 0;
1597
1598 for (Index = Start; Index < End; Index += 1) {
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001599 if (((SectionAddr + Index) < StartAddress) ||
1600 ((SectionAddr + Index) > StopAddress))
1601 continue;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001602 if (NumBytes == 0) {
1603 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1604 outs() << "\t";
1605 }
1606 Byte = Bytes.slice(Index)[0];
1607 outs() << format(" %02x", Byte);
1608 AsciiData[NumBytes] = isprint(Byte) ? Byte : '.';
1609
1610 uint8_t IndentOffset = 0;
1611 NumBytes++;
1612 if (Index == End - 1 || NumBytes > 8) {
1613 // Indent the space for less than 8 bytes data.
1614 // 2 spaces for byte and one for space between bytes
1615 IndentOffset = 3 * (8 - NumBytes);
1616 for (int Excess = 8 - NumBytes; Excess < 8; Excess++)
1617 AsciiData[Excess] = '\0';
1618 NumBytes = 8;
1619 }
1620 if (NumBytes == 8) {
1621 AsciiData[8] = '\0';
1622 outs() << std::string(IndentOffset, ' ') << " ";
1623 outs() << reinterpret_cast<char *>(AsciiData);
1624 outs() << '\n';
1625 NumBytes = 0;
1626 }
1627 }
1628 }
Davide Italianof0706882015-10-01 21:57:09 +00001629 if (Index >= End)
1630 break;
1631
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001632 // Disassemble a real instruction or a data when disassemble all is
1633 // provided
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001634 bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1635 SectionAddr + Index, DebugOut,
1636 CommentStream);
1637 if (Size == 0)
1638 Size = 1;
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001639
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001640 PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001641 Bytes.slice(Index, Size), SectionAddr + Index, outs(), "",
Sid Manningd9f28732018-05-14 19:46:08 +00001642 *STI, &SP, &Rels);
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001643 outs() << CommentStream.str();
1644 Comments.clear();
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001645
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001646 // Try to resolve the target of a call, tail call, etc. to a specific
1647 // symbol.
1648 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1649 MIA->isConditionalBranch(Inst))) {
1650 uint64_t Target;
1651 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1652 // In a relocatable object, the target's section must reside in
1653 // the same section as the call instruction or it is accessed
1654 // through a relocation.
1655 //
1656 // In a non-relocatable object, the target may be in any section.
1657 //
1658 // N.B. We don't walk the relocations in the relocatable case yet.
1659 auto *TargetSectionSymbols = &Symbols;
1660 if (!Obj->isRelocatableObject()) {
1661 auto SectionAddress = std::upper_bound(
1662 SectionAddresses.begin(), SectionAddresses.end(), Target,
1663 [](uint64_t LHS,
1664 const std::pair<uint64_t, SectionRef> &RHS) {
1665 return LHS < RHS.first;
1666 });
1667 if (SectionAddress != SectionAddresses.begin()) {
1668 --SectionAddress;
1669 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1670 } else {
Sterling Augustinebc78b622018-06-28 18:57:13 +00001671 TargetSectionSymbols = &AbsoluteSymbols;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001672 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001673 }
David Majnemer2603a8fa2015-07-09 18:11:40 +00001674
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001675 // Find the first symbol in the section whose offset is less than
Sterling Augustinebc78b622018-06-28 18:57:13 +00001676 // or equal to the target. If there isn't a section that contains
1677 // the target, find the nearest preceding absolute symbol.
1678 auto TargetSym = std::upper_bound(
1679 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1680 Target, [](uint64_t LHS,
1681 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1682 return LHS < std::get<0>(RHS);
1683 });
1684 if (TargetSym == TargetSectionSymbols->begin()) {
1685 TargetSectionSymbols = &AbsoluteSymbols;
1686 TargetSym = std::upper_bound(
1687 AbsoluteSymbols.begin(), AbsoluteSymbols.end(),
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001688 Target, [](uint64_t LHS,
Sam Koltonc05d7782016-08-17 10:17:57 +00001689 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
Sterling Augustinebc78b622018-06-28 18:57:13 +00001690 return LHS < std::get<0>(RHS);
1691 });
1692 }
1693 if (TargetSym != TargetSectionSymbols->begin()) {
1694 --TargetSym;
1695 uint64_t TargetAddress = std::get<0>(*TargetSym);
1696 StringRef TargetName = std::get<1>(*TargetSym);
1697 outs() << " <" << TargetName;
1698 uint64_t Disp = Target - TargetAddress;
1699 if (Disp)
1700 outs() << "+0x" << Twine::utohexstr(Disp);
1701 outs() << '>';
David Majnemer81afca62015-07-07 22:06:59 +00001702 }
1703 }
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001704 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001705 outs() << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001706
Sid Manningd9f28732018-05-14 19:46:08 +00001707 // Hexagon does this in pretty printer
1708 if (Obj->getArch() != Triple::hexagon)
1709 // Print relocation for instruction.
1710 while (rel_cur != rel_end) {
1711 bool hidden = getHidden(*rel_cur);
1712 uint64_t addr = rel_cur->getOffset();
1713 SmallString<16> name;
1714 SmallString<32> val;
Owen Andersonfa3e5202011-10-25 20:35:53 +00001715
Sid Manningd9f28732018-05-14 19:46:08 +00001716 // If this relocation is hidden, skip it.
1717 if (hidden || ((SectionAddr + addr) < StartAddress)) {
1718 ++rel_cur;
1719 continue;
1720 }
1721
1722 // Stop when rel_cur's address is past the current instruction.
1723 if (addr >= Index + Size) break;
1724 rel_cur->getTypeName(name);
1725 error(getRelocationValueString(*rel_cur, val));
1726 outs() << format(Fmt.data(), SectionAddr + addr) << name
1727 << "\t" << val << "\n";
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001728 ++rel_cur;
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001729 }
Benjamin Kramer87ee76c2011-07-20 19:37:35 +00001730 }
Michael J. Spencer2670c252011-01-20 06:39:06 +00001731 }
1732 }
1733}
1734
Kevin Enderby98da6132015-01-20 21:47:46 +00001735void llvm::PrintRelocations(const ObjectFile *Obj) {
Greg Fitzgerald18432272014-03-20 22:55:15 +00001736 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1737 "%08" PRIx64;
Rafael Espindola9219fe72016-03-21 20:59:15 +00001738 // Regular objdump doesn't print relocations in non-relocatable object
1739 // files.
1740 if (!Obj->isRelocatableObject())
1741 return;
Rafael Espindolac66d7612014-08-17 19:09:37 +00001742
Colin LeMahieu77804be2015-07-29 15:45:39 +00001743 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001744 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001745 continue;
1746 StringRef secname;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001747 error(Section.getName(secname));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001748 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001749 for (const RelocationRef &Reloc : Section.relocations()) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001750 bool hidden = getHidden(Reloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001751 uint64_t address = Reloc.getOffset();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001752 SmallString<32> relocname;
1753 SmallString<32> valuestr;
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001754 if (address < StartAddress || address > StopAddress || hidden)
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001755 continue;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001756 Reloc.getTypeName(relocname);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001757 error(getRelocationValueString(Reloc, valuestr));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001758 outs() << format(Fmt.data(), address) << " " << relocname << " "
1759 << valuestr << "\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001760 }
1761 outs() << "\n";
1762 }
1763}
1764
Paul Semelcb0f0432018-06-07 13:30:55 +00001765void llvm::PrintDynamicRelocations(const ObjectFile *Obj) {
1766
1767 // For the moment, this option is for ELF only
1768 if (!Obj->isELF())
1769 return;
1770
1771 const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj);
1772
1773 if (!Elf || Elf->getEType() != ELF::ET_DYN) {
1774 error("not a dynamic object");
1775 return;
1776 }
1777
1778 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
1779
1780 std::vector<SectionRef> DynRelSec = Obj->dynamic_relocation_sections();
1781 if (DynRelSec.empty())
1782 return;
1783
1784 outs() << "DYNAMIC RELOCATION RECORDS\n";
1785 for (const SectionRef &Section : DynRelSec) {
1786 if (Section.relocation_begin() == Section.relocation_end())
1787 continue;
1788 for (const RelocationRef &Reloc : Section.relocations()) {
1789 uint64_t address = Reloc.getOffset();
1790 SmallString<32> relocname;
1791 SmallString<32> valuestr;
1792 Reloc.getTypeName(relocname);
1793 error(getRelocationValueString(Reloc, valuestr));
1794 outs() << format(Fmt.data(), address) << " " << relocname << " "
1795 << valuestr << "\n";
1796 }
1797 }
1798}
1799
Kevin Enderby98da6132015-01-20 21:47:46 +00001800void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001801 outs() << "Sections:\n"
1802 "Idx Name Size Address Type\n";
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001803 unsigned i = 0;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001804 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001805 StringRef Name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001806 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001807 uint64_t Address = Section.getAddress();
1808 uint64_t Size = Section.getSize();
1809 bool Text = Section.isText();
1810 bool Data = Section.isData();
1811 bool BSS = Section.isBSS();
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001812 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +00001813 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
Alexey Samsonov48803e52014-03-13 14:37:36 +00001814 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1815 Name.str().c_str(), Size, Address, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001816 ++i;
1817 }
1818}
1819
Kevin Enderby98da6132015-01-20 21:47:46 +00001820void llvm::PrintSectionContents(const ObjectFile *Obj) {
Rafael Espindola4453e42942014-06-13 03:07:50 +00001821 std::error_code EC;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001822 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001823 StringRef Name;
1824 StringRef Contents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001825 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001826 uint64_t BaseAddr = Section.getAddress();
David Majnemer185b5b12014-11-11 09:58:25 +00001827 uint64_t Size = Section.getSize();
1828 if (!Size)
1829 continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001830
1831 outs() << "Contents of section " << Name << ":\n";
David Majnemer185b5b12014-11-11 09:58:25 +00001832 if (Section.isBSS()) {
Alexey Samsonov209095c2013-04-16 10:53:11 +00001833 outs() << format("<skipping contents of bss section at [%04" PRIx64
David Majnemer8f6b04c2014-07-14 16:20:14 +00001834 ", %04" PRIx64 ")>\n",
1835 BaseAddr, BaseAddr + Size);
Alexey Samsonov209095c2013-04-16 10:53:11 +00001836 continue;
1837 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001838
Davide Italianoccd53fe2015-08-05 07:18:31 +00001839 error(Section.getContents(Contents));
David Majnemer8f6b04c2014-07-14 16:20:14 +00001840
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001841 // Dump out the content as hex and printable ascii characters.
1842 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer82803112012-03-10 02:04:38 +00001843 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001844 // Dump line of hex.
1845 for (std::size_t i = 0; i < 16; ++i) {
1846 if (i != 0 && i % 4 == 0)
1847 outs() << ' ';
1848 if (addr + i < end)
1849 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1850 << hexdigit(Contents[addr + i] & 0xF, true);
1851 else
1852 outs() << " ";
1853 }
1854 // Print ascii.
1855 outs() << " ";
1856 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
Guy Benyei83c74e92013-02-12 21:21:59 +00001857 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001858 outs() << Contents[addr + i];
1859 else
1860 outs() << ".";
1861 }
1862 outs() << "\n";
1863 }
1864 }
1865}
1866
Kevin Enderby9acb1092016-05-31 20:35:34 +00001867void llvm::PrintSymbolTable(const ObjectFile *o, StringRef ArchiveName,
1868 StringRef ArchitectureName) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001869 outs() << "SYMBOL TABLE:\n";
1870
Rui Ueyama4e39f712014-03-18 18:58:51 +00001871 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
Davide Italianoe85abf72015-12-20 09:54:34 +00001872 printCOFFSymbolTable(coff);
Rui Ueyama4e39f712014-03-18 18:58:51 +00001873 return;
1874 }
1875 for (const SymbolRef &Symbol : o->symbols()) {
Kevin Enderby931cb652016-06-24 18:24:42 +00001876 Expected<uint64_t> AddressOrError = Symbol.getAddress();
1877 if (!AddressOrError)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001878 report_error(ArchiveName, o->getFileName(), AddressOrError.takeError(),
1879 ArchitectureName);
Rafael Espindolaed067c42015-07-03 18:19:00 +00001880 uint64_t Address = *AddressOrError;
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001881 if ((Address < StartAddress) || (Address > StopAddress))
1882 continue;
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001883 Expected<SymbolRef::Type> TypeOrError = Symbol.getType();
1884 if (!TypeOrError)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001885 report_error(ArchiveName, o->getFileName(), TypeOrError.takeError(),
1886 ArchitectureName);
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00001887 SymbolRef::Type Type = *TypeOrError;
Rui Ueyama4e39f712014-03-18 18:58:51 +00001888 uint32_t Flags = Symbol.getFlags();
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001889 Expected<section_iterator> SectionOrErr = Symbol.getSection();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001890 if (!SectionOrErr)
1891 report_error(ArchiveName, o->getFileName(), SectionOrErr.takeError(),
1892 ArchitectureName);
Rafael Espindola8bab8892015-08-07 23:27:14 +00001893 section_iterator Section = *SectionOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001894 StringRef Name;
1895 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1896 Section->getName(Name);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001897 } else {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001898 Expected<StringRef> NameOrErr = Symbol.getName();
1899 if (!NameOrErr)
Kevin Enderby9acb1092016-05-31 20:35:34 +00001900 report_error(ArchiveName, o->getFileName(), NameOrErr.takeError(),
1901 ArchitectureName);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001902 Name = *NameOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001903 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001904
Rui Ueyama4e39f712014-03-18 18:58:51 +00001905 bool Global = Flags & SymbolRef::SF_Global;
1906 bool Weak = Flags & SymbolRef::SF_Weak;
1907 bool Absolute = Flags & SymbolRef::SF_Absolute;
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001908 bool Common = Flags & SymbolRef::SF_Common;
Davide Italianocd2514d2015-04-30 23:08:53 +00001909 bool Hidden = Flags & SymbolRef::SF_Hidden;
David Meyer1df4b842012-02-28 23:47:53 +00001910
Rui Ueyama4e39f712014-03-18 18:58:51 +00001911 char GlobLoc = ' ';
1912 if (Type != SymbolRef::ST_Unknown)
1913 GlobLoc = Global ? 'g' : 'l';
1914 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1915 ? 'd' : ' ';
1916 char FileFunc = ' ';
1917 if (Type == SymbolRef::ST_File)
1918 FileFunc = 'f';
1919 else if (Type == SymbolRef::ST_Function)
1920 FileFunc = 'F';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001921
Rui Ueyama4e39f712014-03-18 18:58:51 +00001922 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1923 "%08" PRIx64;
Michael J. Spencerd857c1c2013-01-10 22:40:50 +00001924
Rui Ueyama4e39f712014-03-18 18:58:51 +00001925 outs() << format(Fmt, Address) << " "
1926 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1927 << (Weak ? 'w' : ' ') // Weak?
1928 << ' ' // Constructor. Not supported yet.
1929 << ' ' // Warning. Not supported yet.
1930 << ' ' // Indirect reference to another symbol.
1931 << Debug // Debugging (d) or dynamic (D) symbol.
1932 << FileFunc // Name of function (F), file (f) or object (O).
1933 << ' ';
1934 if (Absolute) {
1935 outs() << "*ABS*";
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001936 } else if (Common) {
1937 outs() << "*COM*";
Rui Ueyama4e39f712014-03-18 18:58:51 +00001938 } else if (Section == o->section_end()) {
1939 outs() << "*UND*";
1940 } else {
1941 if (const MachOObjectFile *MachO =
1942 dyn_cast<const MachOObjectFile>(o)) {
1943 DataRefImpl DR = Section->getRawDataRefImpl();
1944 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1945 outs() << SegmentName << ",";
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001946 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00001947 StringRef SectionName;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001948 error(Section->getName(SectionName));
Rui Ueyama4e39f712014-03-18 18:58:51 +00001949 outs() << SectionName;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001950 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001951
1952 outs() << '\t';
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001953 if (Common || isa<ELFObjectFileBase>(o)) {
Rafael Espindoladbb6bd32015-06-25 22:10:04 +00001954 uint64_t Val =
1955 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001956 outs() << format("\t %08" PRIx64 " ", Val);
1957 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001958
Davide Italianocd2514d2015-04-30 23:08:53 +00001959 if (Hidden) {
1960 outs() << ".hidden ";
1961 }
1962 outs() << Name
Rui Ueyama4e39f712014-03-18 18:58:51 +00001963 << '\n';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001964 }
1965}
1966
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001967static void PrintUnwindInfo(const ObjectFile *o) {
1968 outs() << "Unwind info:\n\n";
1969
1970 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1971 printCOFFUnwindInfo(coff);
Tim Northover4bd286a2014-08-01 13:07:19 +00001972 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1973 printMachOUnwindInfo(MachO);
1974 else {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001975 // TODO: Extract DWARF dump tool to objdump.
1976 errs() << "This operation is only currently supported "
Tim Northover4bd286a2014-08-01 13:07:19 +00001977 "for COFF and MachO object files.\n";
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001978 return;
1979 }
1980}
1981
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001982void llvm::printExportsTrie(const ObjectFile *o) {
Nick Kledzikd04bc352014-08-30 00:20:14 +00001983 outs() << "Exports trie:\n";
1984 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1985 printMachOExportsTrie(MachO);
1986 else {
1987 errs() << "This operation is only currently supported "
1988 "for Mach-O executable files.\n";
1989 return;
1990 }
1991}
1992
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001993void llvm::printRebaseTable(ObjectFile *o) {
Nick Kledzikac431442014-09-12 21:34:15 +00001994 outs() << "Rebase table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001995 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzikac431442014-09-12 21:34:15 +00001996 printMachORebaseTable(MachO);
1997 else {
1998 errs() << "This operation is only currently supported "
1999 "for Mach-O executable files.\n";
2000 return;
2001 }
2002}
2003
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002004void llvm::printBindTable(ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00002005 outs() << "Bind table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002006 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzik56ebef42014-09-16 01:41:51 +00002007 printMachOBindTable(MachO);
2008 else {
2009 errs() << "This operation is only currently supported "
2010 "for Mach-O executable files.\n";
2011 return;
2012 }
2013}
2014
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002015void llvm::printLazyBindTable(ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00002016 outs() << "Lazy bind table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002017 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzik56ebef42014-09-16 01:41:51 +00002018 printMachOLazyBindTable(MachO);
2019 else {
2020 errs() << "This operation is only currently supported "
2021 "for Mach-O executable files.\n";
2022 return;
2023 }
2024}
2025
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002026void llvm::printWeakBindTable(ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00002027 outs() << "Weak bind table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002028 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzik56ebef42014-09-16 01:41:51 +00002029 printMachOWeakBindTable(MachO);
2030 else {
2031 errs() << "This operation is only currently supported "
2032 "for Mach-O executable files.\n";
2033 return;
2034 }
2035}
Nick Kledzikac431442014-09-12 21:34:15 +00002036
Adrian Prantl437105a2015-07-08 02:04:15 +00002037/// Dump the raw contents of the __clangast section so the output can be piped
2038/// into llvm-bcanalyzer.
2039void llvm::printRawClangAST(const ObjectFile *Obj) {
2040 if (outs().is_displayed()) {
2041 errs() << "The -raw-clang-ast option will dump the raw binary contents of "
2042 "the clang ast section.\n"
2043 "Please redirect the output to a file or another program such as "
2044 "llvm-bcanalyzer.\n";
2045 return;
2046 }
2047
2048 StringRef ClangASTSectionName("__clangast");
2049 if (isa<COFFObjectFile>(Obj)) {
2050 ClangASTSectionName = "clangast";
2051 }
2052
2053 Optional<object::SectionRef> ClangASTSection;
Colin LeMahieu77804be2015-07-29 15:45:39 +00002054 for (auto Sec : ToolSectionFilter(*Obj)) {
Adrian Prantl437105a2015-07-08 02:04:15 +00002055 StringRef Name;
2056 Sec.getName(Name);
2057 if (Name == ClangASTSectionName) {
2058 ClangASTSection = Sec;
2059 break;
2060 }
2061 }
2062 if (!ClangASTSection)
2063 return;
2064
2065 StringRef ClangASTContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00002066 error(ClangASTSection.getValue().getContents(ClangASTContents));
Adrian Prantl437105a2015-07-08 02:04:15 +00002067 outs().write(ClangASTContents.data(), ClangASTContents.size());
2068}
2069
Sanjoy Das6f567a42015-06-22 18:03:02 +00002070static void printFaultMaps(const ObjectFile *Obj) {
2071 const char *FaultMapSectionName = nullptr;
2072
2073 if (isa<ELFObjectFileBase>(Obj)) {
2074 FaultMapSectionName = ".llvm_faultmaps";
2075 } else if (isa<MachOObjectFile>(Obj)) {
2076 FaultMapSectionName = "__llvm_faultmaps";
2077 } else {
2078 errs() << "This operation is only currently supported "
2079 "for ELF and Mach-O executable files.\n";
2080 return;
2081 }
2082
2083 Optional<object::SectionRef> FaultMapSection;
2084
Colin LeMahieu77804be2015-07-29 15:45:39 +00002085 for (auto Sec : ToolSectionFilter(*Obj)) {
Sanjoy Das6f567a42015-06-22 18:03:02 +00002086 StringRef Name;
2087 Sec.getName(Name);
2088 if (Name == FaultMapSectionName) {
2089 FaultMapSection = Sec;
2090 break;
2091 }
2092 }
2093
2094 outs() << "FaultMap table:\n";
2095
2096 if (!FaultMapSection.hasValue()) {
2097 outs() << "<not found>\n";
2098 return;
2099 }
2100
2101 StringRef FaultMapContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00002102 error(FaultMapSection.getValue().getContents(FaultMapContents));
Sanjoy Das6f567a42015-06-22 18:03:02 +00002103
2104 FaultMapParser FMP(FaultMapContents.bytes_begin(),
2105 FaultMapContents.bytes_end());
2106
2107 outs() << FMP;
2108}
2109
Davide Italiano1bdaa202016-09-18 04:39:15 +00002110static void printPrivateFileHeaders(const ObjectFile *o, bool onlyFirst) {
Kevin Enderby0ae163f2016-01-13 00:25:36 +00002111 if (o->isELF())
Davide Italiano1bdaa202016-09-18 04:39:15 +00002112 return printELFFileHeader(o);
2113 if (o->isCOFF())
2114 return printCOFFFileHeader(o);
Derek Schuff2c6f75d2016-11-30 16:49:11 +00002115 if (o->isWasm())
2116 return printWasmFileHeader(o);
Davide Italiano1bdaa202016-09-18 04:39:15 +00002117 if (o->isMachO()) {
Kevin Enderby0ae163f2016-01-13 00:25:36 +00002118 printMachOFileHeader(o);
Davide Italiano1bdaa202016-09-18 04:39:15 +00002119 if (!onlyFirst)
2120 printMachOLoadCommands(o);
2121 return;
2122 }
Kevin Enderby7fa40c92016-11-16 22:17:38 +00002123 report_error(o->getFileName(), "Invalid/Unsupported object file format");
Rui Ueyamac2bed422013-09-27 21:04:00 +00002124}
2125
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002126static void DumpObject(ObjectFile *o, const Archive *a = nullptr) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002127 StringRef ArchiveName = a != nullptr ? a->getFileName() : "";
Adrian Prantl437105a2015-07-08 02:04:15 +00002128 // Avoid other output when using a raw option.
2129 if (!RawClangAST) {
2130 outs() << '\n';
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002131 if (a)
2132 outs() << a->getFileName() << "(" << o->getFileName() << ")";
2133 else
2134 outs() << o->getFileName();
2135 outs() << ":\tfile format " << o->getFileFormatName() << "\n\n";
Adrian Prantl437105a2015-07-08 02:04:15 +00002136 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00002137
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002138 if (Disassemble)
Michael J. Spencer51862b32011-10-13 22:17:18 +00002139 DisassembleObject(o, Relocations);
2140 if (Relocations && !Disassemble)
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002141 PrintRelocations(o);
Paul Semelcb0f0432018-06-07 13:30:55 +00002142 if (DynamicRelocations)
2143 PrintDynamicRelocations(o);
Nick Lewyckyfcf84622011-10-10 21:21:34 +00002144 if (SectionHeaders)
2145 PrintSectionHeaders(o);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00002146 if (SectionContents)
2147 PrintSectionContents(o);
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002148 if (SymbolTable)
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002149 PrintSymbolTable(o, ArchiveName);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00002150 if (UnwindInfo)
2151 PrintUnwindInfo(o);
Davide Italiano1bdaa202016-09-18 04:39:15 +00002152 if (PrivateHeaders || FirstPrivateHeader)
2153 printPrivateFileHeaders(o, FirstPrivateHeader);
Nick Kledzikd04bc352014-08-30 00:20:14 +00002154 if (ExportsTrie)
2155 printExportsTrie(o);
Nick Kledzikac431442014-09-12 21:34:15 +00002156 if (Rebase)
2157 printRebaseTable(o);
Nick Kledzik56ebef42014-09-16 01:41:51 +00002158 if (Bind)
2159 printBindTable(o);
2160 if (LazyBind)
2161 printLazyBindTable(o);
2162 if (WeakBind)
2163 printWeakBindTable(o);
Adrian Prantl437105a2015-07-08 02:04:15 +00002164 if (RawClangAST)
2165 printRawClangAST(o);
Sanjoy Das6f567a42015-06-22 18:03:02 +00002166 if (PrintFaultMaps)
2167 printFaultMaps(o);
Igor Laevsky03a670c2016-01-26 15:09:42 +00002168 if (DwarfDumpType != DIDT_Null) {
Rafael Espindolac398e672017-07-19 22:27:28 +00002169 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*o);
Igor Laevsky03a670c2016-01-26 15:09:42 +00002170 // Dump the complete DWARF structure.
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00002171 DIDumpOptions DumpOpts;
2172 DumpOpts.DumpType = DwarfDumpType;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00002173 DICtx->dump(outs(), DumpOpts);
Igor Laevsky03a670c2016-01-26 15:09:42 +00002174 }
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002175}
2176
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00002177static void DumpObject(const COFFImportFile *I, const Archive *A) {
2178 StringRef ArchiveName = A ? A->getFileName() : "";
2179
2180 // Avoid other output when using a raw option.
2181 if (!RawClangAST)
2182 outs() << '\n'
2183 << ArchiveName << "(" << I->getFileName() << ")"
2184 << ":\tfile format COFF-import-file"
2185 << "\n\n";
2186
2187 if (SymbolTable)
2188 printCOFFSymbolTable(I);
2189}
2190
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +00002191/// Dump each object file in \a a;
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002192static void DumpArchive(const Archive *a) {
Mehdi Amini41af4302016-11-11 04:28:40 +00002193 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00002194 for (auto &C : a->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002195 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2196 if (!ChildOrErr) {
2197 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2198 report_error(a->getFileName(), C, std::move(E));
2199 continue;
2200 }
Rafael Espindolaae460022014-06-16 16:08:36 +00002201 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002202 DumpObject(o, a);
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00002203 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
2204 DumpObject(I, a);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002205 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00002206 report_error(a->getFileName(), object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002207 }
Lang Hamesfc209622016-07-14 02:24:01 +00002208 if (Err)
2209 report_error(a->getFileName(), std::move(Err));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002210}
2211
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +00002212/// Open file and figure out how to dump it.
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002213static void DumpInput(StringRef file) {
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002214
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002215 // If we are using the Mach-O specific object file parser, then let it parse
2216 // the file and process the command line options. So the -arch flags can
2217 // be used to select specific slices, etc.
2218 if (MachOOpt) {
2219 ParseInputMachO(file);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002220 return;
2221 }
2222
2223 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00002224 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
2225 if (!BinaryOrErr)
Kevin Enderbyb34e3a12016-05-05 17:43:35 +00002226 report_error(file, BinaryOrErr.takeError());
Rafael Espindola48af1c22014-08-19 18:44:46 +00002227 Binary &Binary = *BinaryOrErr.get().getBinary();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002228
Rafael Espindola3f6481d2014-08-01 14:31:55 +00002229 if (Archive *a = dyn_cast<Archive>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002230 DumpArchive(a);
Rafael Espindola3f6481d2014-08-01 14:31:55 +00002231 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002232 DumpObject(o);
Jim Grosbachaf9aec02012-08-07 17:53:14 +00002233 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00002234 report_error(file, object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002235}
2236
Michael J. Spencer2670c252011-01-20 06:39:06 +00002237int main(int argc, char **argv) {
Rui Ueyama197194b2018-04-13 18:26:06 +00002238 InitLLVM X(argc, argv);
Michael J. Spencer2670c252011-01-20 06:39:06 +00002239
2240 // Initialize targets and assembly printers/parsers.
2241 llvm::InitializeAllTargetInfos();
Evan Cheng8c886a42011-07-22 21:58:54 +00002242 llvm::InitializeAllTargetMCs();
Michael J. Spencer2670c252011-01-20 06:39:06 +00002243 llvm::InitializeAllDisassemblers();
2244
Pete Cooper28fb4fc2012-05-03 23:20:10 +00002245 // Register the target printer for --version.
2246 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
2247
Michael J. Spencer2670c252011-01-20 06:39:06 +00002248 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
2249 TripleName = Triple::normalize(TripleName);
2250
2251 ToolName = argv[0];
2252
2253 // Defaults to a.out if no filenames specified.
2254 if (InputFilenames.size() == 0)
2255 InputFilenames.push_back("a.out");
2256
Fangrui Song8513cd42018-06-27 20:45:11 +00002257 if (AllHeaders)
2258 PrivateHeaders = Relocations = SectionHeaders = SymbolTable = true;
2259
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00002260 if (DisassembleAll || PrintSource || PrintLines)
Colin LeMahieuf34933e2015-07-23 20:58:49 +00002261 Disassemble = true;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002262 if (!Disassemble
2263 && !Relocations
Paul Semelcb0f0432018-06-07 13:30:55 +00002264 && !DynamicRelocations
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002265 && !SectionHeaders
2266 && !SectionContents
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00002267 && !SymbolTable
Michael J. Spencer209565db2013-01-06 03:56:49 +00002268 && !UnwindInfo
Nick Kledzikd04bc352014-08-30 00:20:14 +00002269 && !PrivateHeaders
Kevin Enderby0ae163f2016-01-13 00:25:36 +00002270 && !FirstPrivateHeader
Nick Kledzikac431442014-09-12 21:34:15 +00002271 && !ExportsTrie
Nick Kledzik56ebef42014-09-16 01:41:51 +00002272 && !Rebase
2273 && !Bind
2274 && !LazyBind
Kevin Enderby131d1772015-01-09 19:22:37 +00002275 && !WeakBind
Adrian Prantl437105a2015-07-08 02:04:15 +00002276 && !RawClangAST
Kevin Enderby13023a12015-01-15 23:19:11 +00002277 && !(UniversalHeaders && MachOOpt)
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00002278 && !(ArchiveHeaders && MachOOpt)
Kevin Enderby69fe98d2015-01-23 18:52:17 +00002279 && !(IndirectSymbols && MachOOpt)
Kevin Enderby9a509442015-01-27 21:28:24 +00002280 && !(DataInCode && MachOOpt)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002281 && !(LinkOptHints && MachOOpt)
Kevin Enderbycd66be52015-03-11 22:06:32 +00002282 && !(InfoPlist && MachOOpt)
Kevin Enderbybc847fa2015-03-16 20:08:09 +00002283 && !(DylibsUsed && MachOOpt)
2284 && !(DylibId && MachOOpt)
Kevin Enderby0fc11822015-04-01 20:57:01 +00002285 && !(ObjcMetaData && MachOOpt)
Colin LeMahieufcc32762015-07-29 19:08:10 +00002286 && !(FilterSections.size() != 0 && MachOOpt)
Igor Laevsky03a670c2016-01-26 15:09:42 +00002287 && !PrintFaultMaps
2288 && DwarfDumpType == DIDT_Null) {
Michael J. Spencer2670c252011-01-20 06:39:06 +00002289 cl::PrintHelpMessage();
Dimitry Andrice4f5d012017-12-18 19:46:56 +00002290 return 2;
2291 }
2292
Rafael Aulerb0e4b912018-03-09 19:13:44 +00002293 DisasmFuncsSet.insert(DisassembleFunctions.begin(),
2294 DisassembleFunctions.end());
2295
Dimitry Andrice4f5d012017-12-18 19:46:56 +00002296 llvm::for_each(InputFilenames, DumpInput);
2297
2298 return EXIT_SUCCESS;
2299}