blob: e639fd94abb76f9a85cf997e46fd296c13545bf5 [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
Paul Semeld2af4d62018-07-04 15:25:03 +0000203cl::opt<bool> llvm::FileHeaders(
204 "file-headers",
205 cl::desc("Display the contents of the overall file header"));
206
207static cl::alias FileHeadersShort("f", cl::desc("Alias for --file-headers"),
208 cl::aliasopt(FileHeaders));
209
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000210cl::opt<bool>
211 llvm::PrintImmHex("print-imm-hex",
Colin LeMahieuefe37322016-04-08 18:15:37 +0000212 cl::desc("Use hex format for immediate values"));
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000213
Sanjoy Das6f567a42015-06-22 18:03:02 +0000214cl::opt<bool> PrintFaultMaps("fault-map-section",
215 cl::desc("Display contents of faultmap section"));
216
Igor Laevsky03a670c2016-01-26 15:09:42 +0000217cl::opt<DIDumpType> llvm::DwarfDumpType(
218 "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"),
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000219 cl::values(clEnumValN(DIDT_DebugFrame, "frames", ".debug_frame")));
Igor Laevsky03a670c2016-01-26 15:09:42 +0000220
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000221cl::opt<bool> PrintSource(
222 "source",
223 cl::desc(
Alex Denisova07169e2018-02-02 19:20:37 +0000224 "Display source inlined with disassembly. Implies disassemble object"));
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000225
226cl::alias PrintSourceShort("S", cl::desc("Alias for -source"),
227 cl::aliasopt(PrintSource));
228
229cl::opt<bool> PrintLines("line-numbers",
230 cl::desc("Display source line numbers with "
231 "disassembly. Implies disassemble object"));
232
233cl::alias PrintLinesShort("l", cl::desc("Alias for -line-numbers"),
234 cl::aliasopt(PrintLines));
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +0000235
236cl::opt<unsigned long long>
237 StartAddress("start-address", cl::desc("Disassemble beginning at address"),
238 cl::value_desc("address"), cl::init(0));
239cl::opt<unsigned long long>
240 StopAddress("stop-address", cl::desc("Stop disassembly at address"),
241 cl::value_desc("address"), cl::init(UINT64_MAX));
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000242static StringRef ToolName;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000243
Sam Parker5fba45a2017-02-08 09:44:18 +0000244typedef std::vector<std::tuple<uint64_t, StringRef, uint8_t>> SectionSymbolsTy;
245
Colin LeMahieu77804be2015-07-29 15:45:39 +0000246namespace {
Colin LeMahieufcc32762015-07-29 19:08:10 +0000247typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate;
Colin LeMahieu77804be2015-07-29 15:45:39 +0000248
249class SectionFilterIterator {
250public:
251 SectionFilterIterator(FilterPredicate P,
252 llvm::object::section_iterator const &I,
253 llvm::object::section_iterator const &E)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000254 : Predicate(std::move(P)), Iterator(I), End(E) {
Colin LeMahieu77804be2015-07-29 15:45:39 +0000255 ScanPredicate();
256 }
Benjamin Kramerac9257b2015-09-24 14:52:52 +0000257 const llvm::object::SectionRef &operator*() const { return *Iterator; }
Colin LeMahieu77804be2015-07-29 15:45:39 +0000258 SectionFilterIterator &operator++() {
259 ++Iterator;
260 ScanPredicate();
261 return *this;
262 }
263 bool operator!=(SectionFilterIterator const &Other) const {
264 return Iterator != Other.Iterator;
265 }
266
267private:
268 void ScanPredicate() {
Colin LeMahieuda1723f2015-07-29 19:21:13 +0000269 while (Iterator != End && !Predicate(*Iterator)) {
Colin LeMahieu77804be2015-07-29 15:45:39 +0000270 ++Iterator;
271 }
272 }
273 FilterPredicate Predicate;
274 llvm::object::section_iterator Iterator;
275 llvm::object::section_iterator End;
276};
277
278class SectionFilter {
279public:
280 SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000281 : Predicate(std::move(P)), Object(O) {}
Colin LeMahieu77804be2015-07-29 15:45:39 +0000282 SectionFilterIterator begin() {
283 return SectionFilterIterator(Predicate, Object.section_begin(),
284 Object.section_end());
285 }
286 SectionFilterIterator end() {
287 return SectionFilterIterator(Predicate, Object.section_end(),
288 Object.section_end());
289 }
290
291private:
292 FilterPredicate Predicate;
293 llvm::object::ObjectFile const &Object;
294};
295SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) {
David Majnemer42531262016-08-12 03:55:06 +0000296 return SectionFilter(
297 [](llvm::object::SectionRef const &S) {
298 if (FilterSections.empty())
299 return true;
300 llvm::StringRef String;
301 std::error_code error = S.getName(String);
302 if (error)
303 return false;
304 return is_contained(FilterSections, String);
305 },
306 O);
Colin LeMahieu77804be2015-07-29 15:45:39 +0000307}
308}
309
Davide Italianoccd53fe2015-08-05 07:18:31 +0000310void llvm::error(std::error_code EC) {
Mark Seaborneb03ac52014-01-25 00:32:01 +0000311 if (!EC)
Davide Italianoccd53fe2015-08-05 07:18:31 +0000312 return;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000313
Davide Italiano140af642015-12-25 18:16:45 +0000314 errs() << ToolName << ": error reading file: " << EC.message() << ".\n";
315 errs().flush();
Davide Italiano7f6c3012015-08-06 00:18:52 +0000316 exit(1);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000317}
318
Kevin Enderby42398052016-06-28 23:16:13 +0000319LLVM_ATTRIBUTE_NORETURN void llvm::error(Twine Message) {
320 errs() << ToolName << ": " << Message << ".\n";
321 errs().flush();
322 exit(1);
323}
324
Davide Italianoed9d95b2015-12-29 13:41:02 +0000325LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000326 Twine Message) {
327 errs() << ToolName << ": '" << File << "': " << Message << ".\n";
328 exit(1);
329}
330
331LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
Davide Italianoed9d95b2015-12-29 13:41:02 +0000332 std::error_code EC) {
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000333 assert(EC);
334 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
Davide Italianoccd53fe2015-08-05 07:18:31 +0000335 exit(1);
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000336}
337
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000338LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
339 llvm::Error E) {
340 assert(E);
341 std::string Buf;
342 raw_string_ostream OS(Buf);
343 logAllUnhandledErrors(std::move(E), OS, "");
344 OS.flush();
Kevin Enderbyb34e3a12016-05-05 17:43:35 +0000345 errs() << ToolName << ": '" << File << "': " << Buf;
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000346 exit(1);
347}
348
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000349LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
350 StringRef FileName,
Kevin Enderby9acb1092016-05-31 20:35:34 +0000351 llvm::Error E,
352 StringRef ArchitectureName) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000353 assert(E);
354 errs() << ToolName << ": ";
355 if (ArchiveName != "")
356 errs() << ArchiveName << "(" << FileName << ")";
357 else
Justin Bogner31d8b7d2016-10-26 22:37:52 +0000358 errs() << "'" << FileName << "'";
Kevin Enderby9acb1092016-05-31 20:35:34 +0000359 if (!ArchitectureName.empty())
360 errs() << " (for architecture " << ArchitectureName << ")";
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000361 std::string Buf;
362 raw_string_ostream OS(Buf);
363 logAllUnhandledErrors(std::move(E), OS, "");
364 OS.flush();
Justin Bogner31d8b7d2016-10-26 22:37:52 +0000365 errs() << ": " << Buf;
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000366 exit(1);
367}
368
369LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
370 const object::Archive::Child &C,
Kevin Enderby9acb1092016-05-31 20:35:34 +0000371 llvm::Error E,
372 StringRef ArchitectureName) {
Kevin Enderbyf4586032016-07-29 17:44:13 +0000373 Expected<StringRef> NameOrErr = C.getName();
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000374 // TODO: if we have a error getting the name then it would be nice to print
375 // the index of which archive member this is and or its offset in the
376 // archive instead of "???" as the name.
Kevin Enderbyf4586032016-07-29 17:44:13 +0000377 if (!NameOrErr) {
378 consumeError(NameOrErr.takeError());
Kevin Enderby9acb1092016-05-31 20:35:34 +0000379 llvm::report_error(ArchiveName, "???", std::move(E), ArchitectureName);
Kevin Enderbyf4586032016-07-29 17:44:13 +0000380 } else
Kevin Enderby9acb1092016-05-31 20:35:34 +0000381 llvm::report_error(ArchiveName, NameOrErr.get(), std::move(E),
382 ArchitectureName);
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000383}
384
Craig Toppere6cb63e2014-04-25 04:24:47 +0000385static const Target *getTarget(const ObjectFile *Obj = nullptr) {
Michael J. Spencer2670c252011-01-20 06:39:06 +0000386 // Figure out the target triple.
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000387 llvm::Triple TheTriple("unknown-unknown-unknown");
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000388 if (TripleName.empty()) {
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000389 if (Obj) {
Vlad Tsyrklevichde620462017-09-19 02:22:48 +0000390 TheTriple = Obj->makeTriple();
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000391 }
Sam Parkerdf7c6ef2017-01-18 13:52:12 +0000392 } else {
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000393 TheTriple.setTriple(Triple::normalize(TripleName));
Vlad Tsyrklevichde620462017-09-19 02:22:48 +0000394
Sam Parkerdf7c6ef2017-01-18 13:52:12 +0000395 // Use the triple, but also try to combine with ARM build attributes.
396 if (Obj) {
397 auto Arch = Obj->getArch();
398 if (Arch == Triple::arm || Arch == Triple::armeb) {
399 Obj->setARMSubArch(TheTriple);
400 }
401 }
402 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000403
404 // Get the target specific parser.
405 std::string Error;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000406 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
407 Error);
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000408 if (!TheTarget) {
409 if (Obj)
410 report_error(Obj->getFileName(), "can't find target: " + Error);
411 else
412 error("can't find target: " + Error);
413 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000414
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000415 // Update the triple name and return the found target.
416 TripleName = TheTriple.getTriple();
417 return TheTarget;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000418}
419
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000420bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
Rafael Espindola704cd842015-07-06 15:47:43 +0000421 return a.getOffset() < b.getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +0000422}
423
Rafael Espindola37070a52015-06-03 04:48:06 +0000424template <class ELFT>
Rafael Espindola37070a52015-06-03 04:48:06 +0000425static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000426 const RelocationRef &RelRef,
Rafael Espindola37070a52015-06-03 04:48:06 +0000427 SmallVectorImpl<char> &Result) {
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000428 DataRefImpl Rel = RelRef.getRawDataRefImpl();
429
Rafael Espindola37070a52015-06-03 04:48:06 +0000430 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
431 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000432 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
433
Rafael Espindola37070a52015-06-03 04:48:06 +0000434 const ELFFile<ELFT> &EF = *Obj->getELFFile();
435
Davide Italiano6cf09262016-11-16 05:10:28 +0000436 auto SecOrErr = EF.getSection(Rel.d.a);
437 if (!SecOrErr)
438 return errorToErrorCode(SecOrErr.takeError());
Rafael Espindola6def3042015-07-01 12:56:27 +0000439 const Elf_Shdr *Sec = *SecOrErr;
Davide Italiano6cf09262016-11-16 05:10:28 +0000440 auto SymTabOrErr = EF.getSection(Sec->sh_link);
441 if (!SymTabOrErr)
442 return errorToErrorCode(SymTabOrErr.takeError());
Rafael Espindola6def3042015-07-01 12:56:27 +0000443 const Elf_Shdr *SymTab = *SymTabOrErr;
Rafael Espindola719dc7c2015-06-29 12:38:31 +0000444 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
445 SymTab->sh_type == ELF::SHT_DYNSYM);
Davide Italiano6cf09262016-11-16 05:10:28 +0000446 auto StrTabSec = EF.getSection(SymTab->sh_link);
447 if (!StrTabSec)
448 return errorToErrorCode(StrTabSec.takeError());
449 auto StrTabOrErr = EF.getStringTable(*StrTabSec);
450 if (!StrTabOrErr)
451 return errorToErrorCode(StrTabOrErr.takeError());
Rafael Espindola6a1bfb22015-06-29 14:39:25 +0000452 StringRef StrTab = *StrTabOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000453 int64_t addend = 0;
Paul Semelcb0f0432018-06-07 13:30:55 +0000454 // If there is no Symbol associated with the relocation, we set the undef
455 // boolean value to 'true'. This will prevent us from calling functions that
456 // requires the relocation to be associated with a symbol.
457 bool undef = false;
Rafael Espindola6def3042015-07-01 12:56:27 +0000458 switch (Sec->sh_type) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000459 default:
460 return object_error::parse_failed;
461 case ELF::SHT_REL: {
Rafael Espindola37070a52015-06-03 04:48:06 +0000462 // TODO: Read implicit addend from section data.
463 break;
464 }
465 case ELF::SHT_RELA: {
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000466 const Elf_Rela *ERela = Obj->getRela(Rel);
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000467 addend = ERela->r_addend;
Paul Semelcb0f0432018-06-07 13:30:55 +0000468 undef = ERela->getSymbol(false) == 0;
Rafael Espindola37070a52015-06-03 04:48:06 +0000469 break;
470 }
471 }
Rafael Espindola75d5b542015-06-03 05:14:22 +0000472 StringRef Target;
Paul Semelcb0f0432018-06-07 13:30:55 +0000473 if (!undef) {
474 symbol_iterator SI = RelRef.getSymbol();
475 const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
476 if (symb->getType() == ELF::STT_SECTION) {
477 Expected<section_iterator> SymSI = SI->getSection();
478 if (!SymSI)
479 return errorToErrorCode(SymSI.takeError());
480 const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
481 auto SecName = EF.getSectionName(SymSec);
482 if (!SecName)
483 return errorToErrorCode(SecName.takeError());
484 Target = *SecName;
485 } else {
486 Expected<StringRef> SymName = symb->getName(StrTab);
487 if (!SymName)
488 return errorToErrorCode(SymName.takeError());
489 Target = *SymName;
490 }
491 } else
492 Target = "*ABS*";
Daniel Cedermand72b9fd2018-06-01 05:31:58 +0000493
494 // Default scheme is to print Target, as well as "+ <addend>" for nonzero
495 // addend. Should be acceptable for all normal purposes.
496 std::string fmtbuf;
497 raw_string_ostream fmt(fmtbuf);
498 fmt << Target;
499 if (addend != 0)
500 fmt << (addend < 0 ? "" : "+") << addend;
501 fmt.flush();
502 Result.append(fmtbuf.begin(), fmtbuf.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000503 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000504}
505
506static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000507 const RelocationRef &Rel,
Rafael Espindola37070a52015-06-03 04:48:06 +0000508 SmallVectorImpl<char> &Result) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000509 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
510 return getRelocationValueString(ELF32LE, Rel, Result);
511 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
512 return getRelocationValueString(ELF64LE, Rel, Result);
513 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
514 return getRelocationValueString(ELF32BE, Rel, Result);
515 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
516 return getRelocationValueString(ELF64BE, Rel, Result);
517}
518
519static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
520 const RelocationRef &Rel,
521 SmallVectorImpl<char> &Result) {
522 symbol_iterator SymI = Rel.getSymbol();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000523 Expected<StringRef> SymNameOrErr = SymI->getName();
524 if (!SymNameOrErr)
525 return errorToErrorCode(SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000526 StringRef SymName = *SymNameOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000527 Result.append(SymName.begin(), SymName.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000528 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000529}
530
531static void printRelocationTargetName(const MachOObjectFile *O,
532 const MachO::any_relocation_info &RE,
533 raw_string_ostream &fmt) {
534 bool IsScattered = O->isRelocationScattered(RE);
535
536 // Target of a scattered relocation is an address. In the interest of
537 // generating pretty output, scan through the symbol table looking for a
538 // symbol that aligns with that address. If we find one, print it.
539 // Otherwise, we just print the hex address of the target.
540 if (IsScattered) {
541 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
542
543 for (const SymbolRef &Symbol : O->symbols()) {
544 std::error_code ec;
Kevin Enderby931cb652016-06-24 18:24:42 +0000545 Expected<uint64_t> Addr = Symbol.getAddress();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000546 if (!Addr)
547 report_error(O->getFileName(), Addr.takeError());
Rafael Espindolaed067c42015-07-03 18:19:00 +0000548 if (*Addr != Val)
Rafael Espindola37070a52015-06-03 04:48:06 +0000549 continue;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000550 Expected<StringRef> Name = Symbol.getName();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000551 if (!Name)
552 report_error(O->getFileName(), Name.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000553 fmt << *Name;
Rafael Espindola37070a52015-06-03 04:48:06 +0000554 return;
555 }
556
557 // If we couldn't find a symbol that this relocation refers to, try
558 // to find a section beginning instead.
Colin LeMahieu77804be2015-07-29 15:45:39 +0000559 for (const SectionRef &Section : ToolSectionFilter(*O)) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000560 std::error_code ec;
561
562 StringRef Name;
563 uint64_t Addr = Section.getAddress();
564 if (Addr != Val)
565 continue;
566 if ((ec = Section.getName(Name)))
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000567 report_error(O->getFileName(), ec);
Rafael Espindola37070a52015-06-03 04:48:06 +0000568 fmt << Name;
569 return;
570 }
571
572 fmt << format("0x%x", Val);
573 return;
574 }
575
576 StringRef S;
577 bool isExtern = O->getPlainRelocationExternal(RE);
578 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
579
Martin Storsjo8c0317d2017-07-13 17:03:02 +0000580 if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND) {
Simon Dardis38867052017-08-07 12:29:38 +0000581 fmt << format("0x%0" PRIx64, Val);
Martin Storsjo8c0317d2017-07-13 17:03:02 +0000582 return;
583 } else if (isExtern) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000584 symbol_iterator SI = O->symbol_begin();
585 advance(SI, Val);
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000586 Expected<StringRef> SOrErr = SI->getName();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000587 if (!SOrErr)
588 report_error(O->getFileName(), SOrErr.takeError());
Davide Italianoccd53fe2015-08-05 07:18:31 +0000589 S = *SOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000590 } else {
591 section_iterator SI = O->section_begin();
592 // Adjust for the fact that sections are 1-indexed.
Kevin Enderby3fc91882017-11-03 21:32:44 +0000593 if (Val == 0) {
594 fmt << "0 (?,?)";
595 return;
596 }
597 uint32_t i = Val - 1;
598 while (i != 0 && SI != O->section_end()) {
599 i--;
600 advance(SI, 1);
601 }
602 if (SI == O->section_end())
603 fmt << Val << " (?,?)";
604 else
605 SI->getName(S);
Rafael Espindola37070a52015-06-03 04:48:06 +0000606 }
607
608 fmt << S;
609}
610
Sam Clegg4df5d762017-06-27 20:40:53 +0000611static std::error_code getRelocationValueString(const WasmObjectFile *Obj,
612 const RelocationRef &RelRef,
613 SmallVectorImpl<char> &Result) {
614 const wasm::WasmRelocation& Rel = Obj->getWasmRelocation(RelRef);
Sam Cleggf676cdd2018-04-26 16:41:51 +0000615 symbol_iterator SI = RelRef.getSymbol();
Sam Clegg4df5d762017-06-27 20:40:53 +0000616 std::string fmtbuf;
617 raw_string_ostream fmt(fmtbuf);
Sam Clegg8c4b0ce2018-04-26 17:05:04 +0000618 if (SI == Obj->symbol_end()) {
619 // Not all wasm relocations have symbols associated with them.
620 // In particular R_WEBASSEMBLY_TYPE_INDEX_LEB.
Sam Cleggf676cdd2018-04-26 16:41:51 +0000621 fmt << Rel.Index;
622 } else {
Sam Clegg8c4b0ce2018-04-26 17:05:04 +0000623 Expected<StringRef> SymNameOrErr = SI->getName();
624 if (!SymNameOrErr)
625 return errorToErrorCode(SymNameOrErr.takeError());
Sam Cleggf676cdd2018-04-26 16:41:51 +0000626 StringRef SymName = *SymNameOrErr;
627 Result.append(SymName.begin(), SymName.end());
628 }
629 fmt << (Rel.Addend < 0 ? "" : "+") << Rel.Addend;
Sam Clegg4df5d762017-06-27 20:40:53 +0000630 fmt.flush();
631 Result.append(fmtbuf.begin(), fmtbuf.end());
632 return std::error_code();
633}
634
Rafael Espindola37070a52015-06-03 04:48:06 +0000635static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
636 const RelocationRef &RelRef,
637 SmallVectorImpl<char> &Result) {
638 DataRefImpl Rel = RelRef.getRawDataRefImpl();
639 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
640
641 unsigned Arch = Obj->getArch();
642
643 std::string fmtbuf;
644 raw_string_ostream fmt(fmtbuf);
645 unsigned Type = Obj->getAnyRelocationType(RE);
646 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
647
648 // Determine any addends that should be displayed with the relocation.
649 // These require decoding the relocation type, which is triple-specific.
650
651 // X86_64 has entirely custom relocation types.
652 if (Arch == Triple::x86_64) {
653 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
654
655 switch (Type) {
656 case MachO::X86_64_RELOC_GOT_LOAD:
657 case MachO::X86_64_RELOC_GOT: {
658 printRelocationTargetName(Obj, RE, fmt);
659 fmt << "@GOT";
660 if (isPCRel)
661 fmt << "PCREL";
662 break;
663 }
664 case MachO::X86_64_RELOC_SUBTRACTOR: {
665 DataRefImpl RelNext = Rel;
666 Obj->moveRelocationNext(RelNext);
667 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
668
669 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
670 // X86_64_RELOC_UNSIGNED.
671 // NOTE: Scattered relocations don't exist on x86_64.
672 unsigned RType = Obj->getAnyRelocationType(RENext);
673 if (RType != MachO::X86_64_RELOC_UNSIGNED)
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000674 report_error(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
675 "X86_64_RELOC_SUBTRACTOR.");
Rafael Espindola37070a52015-06-03 04:48:06 +0000676
677 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
678 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
679 printRelocationTargetName(Obj, RENext, fmt);
680 fmt << "-";
681 printRelocationTargetName(Obj, RE, fmt);
682 break;
683 }
684 case MachO::X86_64_RELOC_TLV:
685 printRelocationTargetName(Obj, RE, fmt);
686 fmt << "@TLV";
687 if (isPCRel)
688 fmt << "P";
689 break;
690 case MachO::X86_64_RELOC_SIGNED_1:
691 printRelocationTargetName(Obj, RE, fmt);
692 fmt << "-1";
693 break;
694 case MachO::X86_64_RELOC_SIGNED_2:
695 printRelocationTargetName(Obj, RE, fmt);
696 fmt << "-2";
697 break;
698 case MachO::X86_64_RELOC_SIGNED_4:
699 printRelocationTargetName(Obj, RE, fmt);
700 fmt << "-4";
701 break;
702 default:
703 printRelocationTargetName(Obj, RE, fmt);
704 break;
705 }
706 // X86 and ARM share some relocation types in common.
707 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
708 Arch == Triple::ppc) {
709 // Generic relocation types...
710 switch (Type) {
711 case MachO::GENERIC_RELOC_PAIR: // prints no info
Rui Ueyama7d099192015-06-09 15:20:42 +0000712 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000713 case MachO::GENERIC_RELOC_SECTDIFF: {
714 DataRefImpl RelNext = Rel;
715 Obj->moveRelocationNext(RelNext);
716 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
717
718 // X86 sect diff's must be followed by a relocation of type
719 // GENERIC_RELOC_PAIR.
720 unsigned RType = Obj->getAnyRelocationType(RENext);
721
722 if (RType != MachO::GENERIC_RELOC_PAIR)
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000723 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
724 "GENERIC_RELOC_SECTDIFF.");
Rafael Espindola37070a52015-06-03 04:48:06 +0000725
726 printRelocationTargetName(Obj, RE, fmt);
727 fmt << "-";
728 printRelocationTargetName(Obj, RENext, fmt);
729 break;
730 }
731 }
732
733 if (Arch == Triple::x86 || Arch == Triple::ppc) {
734 switch (Type) {
735 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
736 DataRefImpl RelNext = Rel;
737 Obj->moveRelocationNext(RelNext);
738 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
739
740 // X86 sect diff's must be followed by a relocation of type
741 // GENERIC_RELOC_PAIR.
742 unsigned RType = Obj->getAnyRelocationType(RENext);
743 if (RType != MachO::GENERIC_RELOC_PAIR)
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000744 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
745 "GENERIC_RELOC_LOCAL_SECTDIFF.");
Rafael Espindola37070a52015-06-03 04:48:06 +0000746
747 printRelocationTargetName(Obj, RE, fmt);
748 fmt << "-";
749 printRelocationTargetName(Obj, RENext, fmt);
750 break;
751 }
752 case MachO::GENERIC_RELOC_TLV: {
753 printRelocationTargetName(Obj, RE, fmt);
754 fmt << "@TLV";
755 if (IsPCRel)
756 fmt << "P";
757 break;
758 }
759 default:
760 printRelocationTargetName(Obj, RE, fmt);
761 }
762 } else { // ARM-specific relocations
763 switch (Type) {
764 case MachO::ARM_RELOC_HALF:
765 case MachO::ARM_RELOC_HALF_SECTDIFF: {
766 // Half relocations steal a bit from the length field to encode
767 // whether this is an upper16 or a lower16 relocation.
Martin Storsjofa5183b2017-07-13 05:54:08 +0000768 bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
Rafael Espindola37070a52015-06-03 04:48:06 +0000769
770 if (isUpper)
771 fmt << ":upper16:(";
772 else
773 fmt << ":lower16:(";
774 printRelocationTargetName(Obj, RE, fmt);
775
776 DataRefImpl RelNext = Rel;
777 Obj->moveRelocationNext(RelNext);
778 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
779
780 // ARM half relocs must be followed by a relocation of type
781 // ARM_RELOC_PAIR.
782 unsigned RType = Obj->getAnyRelocationType(RENext);
783 if (RType != MachO::ARM_RELOC_PAIR)
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000784 report_error(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
785 "ARM_RELOC_HALF");
Rafael Espindola37070a52015-06-03 04:48:06 +0000786
787 // NOTE: The half of the target virtual address is stashed in the
788 // address field of the secondary relocation, but we can't reverse
789 // engineer the constant offset from it without decoding the movw/movt
790 // instruction to find the other half in its immediate field.
791
792 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
793 // symbol/section pointer of the follow-on relocation.
794 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
795 fmt << "-";
796 printRelocationTargetName(Obj, RENext, fmt);
797 }
798
799 fmt << ")";
800 break;
801 }
802 default: { printRelocationTargetName(Obj, RE, fmt); }
803 }
804 }
805 } else
806 printRelocationTargetName(Obj, RE, fmt);
807
808 fmt.flush();
809 Result.append(fmtbuf.begin(), fmtbuf.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000810 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000811}
812
813static std::error_code getRelocationValueString(const RelocationRef &Rel,
814 SmallVectorImpl<char> &Result) {
Rafael Espindola854038e2015-06-26 14:51:16 +0000815 const ObjectFile *Obj = Rel.getObject();
Rafael Espindola37070a52015-06-03 04:48:06 +0000816 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
817 return getRelocationValueString(ELF, Rel, Result);
818 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
819 return getRelocationValueString(COFF, Rel, Result);
Sam Clegg4df5d762017-06-27 20:40:53 +0000820 if (auto *Wasm = dyn_cast<WasmObjectFile>(Obj))
821 return getRelocationValueString(Wasm, Rel, Result);
822 if (auto *MachO = dyn_cast<MachOObjectFile>(Obj))
823 return getRelocationValueString(MachO, Rel, Result);
824 llvm_unreachable("unknown object file format");
Rafael Espindola37070a52015-06-03 04:48:06 +0000825}
826
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000827/// Indicates whether this relocation should hidden when listing
Rafael Espindola0ad71d92015-06-30 03:41:26 +0000828/// relocations, usually because it is the trailing part of a multipart
829/// relocation that will be printed as part of the leading relocation.
830static bool getHidden(RelocationRef RelRef) {
831 const ObjectFile *Obj = RelRef.getObject();
832 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
833 if (!MachO)
834 return false;
835
836 unsigned Arch = MachO->getArch();
837 DataRefImpl Rel = RelRef.getRawDataRefImpl();
838 uint64_t Type = MachO->getRelocationType(Rel);
839
840 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
841 // is always hidden.
842 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
843 if (Type == MachO::GENERIC_RELOC_PAIR)
844 return true;
845 } else if (Arch == Triple::x86_64) {
846 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
847 // an X86_64_RELOC_SUBTRACTOR.
848 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
849 DataRefImpl RelPrev = Rel;
850 RelPrev.d.a--;
851 uint64_t PrevType = MachO->getRelocationType(RelPrev);
852 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
853 return true;
854 }
855 }
856
857 return false;
858}
859
Sid Manningd9f28732018-05-14 19:46:08 +0000860namespace {
861class SourcePrinter {
862protected:
863 DILineInfo OldLineInfo;
864 const ObjectFile *Obj = nullptr;
865 std::unique_ptr<symbolize::LLVMSymbolizer> Symbolizer;
866 // File name to file contents of source
867 std::unordered_map<std::string, std::unique_ptr<MemoryBuffer>> SourceCache;
868 // Mark the line endings of the cached source
869 std::unordered_map<std::string, std::vector<StringRef>> LineCache;
870
871private:
872 bool cacheSource(const DILineInfo& LineInfoFile);
873
874public:
875 SourcePrinter() = default;
876 SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch) : Obj(Obj) {
877 symbolize::LLVMSymbolizer::Options SymbolizerOpts(
878 DILineInfoSpecifier::FunctionNameKind::None, true, false, false,
879 DefaultArch);
880 Symbolizer.reset(new symbolize::LLVMSymbolizer(SymbolizerOpts));
881 }
882 virtual ~SourcePrinter() = default;
883 virtual void printSourceLine(raw_ostream &OS, uint64_t Address,
884 StringRef Delimiter = "; ");
885};
886
887bool SourcePrinter::cacheSource(const DILineInfo &LineInfo) {
888 std::unique_ptr<MemoryBuffer> Buffer;
889 if (LineInfo.Source) {
890 Buffer = MemoryBuffer::getMemBuffer(*LineInfo.Source);
891 } else {
892 auto BufferOrError = MemoryBuffer::getFile(LineInfo.FileName);
893 if (!BufferOrError)
894 return false;
895 Buffer = std::move(*BufferOrError);
896 }
897 // Chomp the file to get lines
898 size_t BufferSize = Buffer->getBufferSize();
899 const char *BufferStart = Buffer->getBufferStart();
900 for (const char *Start = BufferStart, *End = BufferStart;
901 End < BufferStart + BufferSize; End++)
902 if (*End == '\n' || End == BufferStart + BufferSize - 1 ||
903 (*End == '\r' && *(End + 1) == '\n')) {
904 LineCache[LineInfo.FileName].push_back(StringRef(Start, End - Start));
905 if (*End == '\r')
906 End++;
907 Start = End + 1;
908 }
909 SourceCache[LineInfo.FileName] = std::move(Buffer);
910 return true;
911}
912
913void SourcePrinter::printSourceLine(raw_ostream &OS, uint64_t Address,
914 StringRef Delimiter) {
915 if (!Symbolizer)
916 return;
917 DILineInfo LineInfo = DILineInfo();
918 auto ExpectecLineInfo =
919 Symbolizer->symbolizeCode(Obj->getFileName(), Address);
920 if (!ExpectecLineInfo)
921 consumeError(ExpectecLineInfo.takeError());
922 else
923 LineInfo = *ExpectecLineInfo;
924
925 if ((LineInfo.FileName == "<invalid>") || OldLineInfo.Line == LineInfo.Line ||
926 LineInfo.Line == 0)
927 return;
928
929 if (PrintLines)
930 OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line << "\n";
931 if (PrintSource) {
932 if (SourceCache.find(LineInfo.FileName) == SourceCache.end())
933 if (!cacheSource(LineInfo))
934 return;
935 auto FileBuffer = SourceCache.find(LineInfo.FileName);
936 if (FileBuffer != SourceCache.end()) {
937 auto LineBuffer = LineCache.find(LineInfo.FileName);
938 if (LineBuffer != LineCache.end()) {
939 if (LineInfo.Line > LineBuffer->second.size())
940 return;
941 // Vector begins at 0, line numbers are non-zero
942 OS << Delimiter << LineBuffer->second[LineInfo.Line - 1].ltrim()
943 << "\n";
944 }
945 }
946 }
947 OldLineInfo = LineInfo;
948}
949
950static bool isArmElf(const ObjectFile *Obj) {
951 return (Obj->isELF() &&
952 (Obj->getArch() == Triple::aarch64 ||
953 Obj->getArch() == Triple::aarch64_be ||
954 Obj->getArch() == Triple::arm || Obj->getArch() == Triple::armeb ||
955 Obj->getArch() == Triple::thumb ||
956 Obj->getArch() == Triple::thumbeb));
957}
958
959class PrettyPrinter {
960public:
961 virtual ~PrettyPrinter() = default;
962 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
963 ArrayRef<uint8_t> Bytes, uint64_t Address,
964 raw_ostream &OS, StringRef Annot,
965 MCSubtargetInfo const &STI, SourcePrinter *SP,
966 std::vector<RelocationRef> *Rels = nullptr) {
967 if (SP && (PrintSource || PrintLines))
968 SP->printSourceLine(OS, Address);
969 if (!NoLeadingAddr)
970 OS << format("%8" PRIx64 ":", Address);
971 if (!NoShowRawInsn) {
972 OS << "\t";
973 dumpBytes(Bytes, OS);
974 }
975 if (MI)
976 IP.printInst(MI, OS, "", STI);
977 else
978 OS << " <unknown>";
979 }
980};
981PrettyPrinter PrettyPrinterInst;
982class HexagonPrettyPrinter : public PrettyPrinter {
983public:
984 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
985 raw_ostream &OS) {
986 uint32_t opcode =
987 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
988 if (!NoLeadingAddr)
989 OS << format("%8" PRIx64 ":", Address);
990 if (!NoShowRawInsn) {
991 OS << "\t";
992 dumpBytes(Bytes.slice(0, 4), OS);
993 OS << format("%08" PRIx32, opcode);
994 }
995 }
996 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
997 uint64_t Address, raw_ostream &OS, StringRef Annot,
998 MCSubtargetInfo const &STI, SourcePrinter *SP,
999 std::vector<RelocationRef> *Rels) override {
1000 if (SP && (PrintSource || PrintLines))
1001 SP->printSourceLine(OS, Address, "");
1002 if (!MI) {
1003 printLead(Bytes, Address, OS);
1004 OS << " <unknown>";
1005 return;
1006 }
1007 std::string Buffer;
1008 {
1009 raw_string_ostream TempStream(Buffer);
1010 IP.printInst(MI, TempStream, "", STI);
1011 }
1012 StringRef Contents(Buffer);
1013 // Split off bundle attributes
1014 auto PacketBundle = Contents.rsplit('\n');
1015 // Split off first instruction from the rest
1016 auto HeadTail = PacketBundle.first.split('\n');
1017 auto Preamble = " { ";
1018 auto Separator = "";
1019 StringRef Fmt = "\t\t\t%08" PRIx64 ": ";
1020 std::vector<RelocationRef>::const_iterator rel_cur = Rels->begin();
1021 std::vector<RelocationRef>::const_iterator rel_end = Rels->end();
1022
1023 // Hexagon's packets require relocations to be inline rather than
1024 // clustered at the end of the packet.
1025 auto PrintReloc = [&]() -> void {
1026 while ((rel_cur != rel_end) && (rel_cur->getOffset() <= Address)) {
1027 if (rel_cur->getOffset() == Address) {
1028 SmallString<16> name;
1029 SmallString<32> val;
1030 rel_cur->getTypeName(name);
1031 error(getRelocationValueString(*rel_cur, val));
1032 OS << Separator << format(Fmt.data(), Address) << name << "\t" << val
1033 << "\n";
1034 return;
1035 }
1036 rel_cur++;
1037 }
1038 };
1039
1040 while(!HeadTail.first.empty()) {
1041 OS << Separator;
1042 Separator = "\n";
1043 if (SP && (PrintSource || PrintLines))
1044 SP->printSourceLine(OS, Address, "");
1045 printLead(Bytes, Address, OS);
1046 OS << Preamble;
1047 Preamble = " ";
1048 StringRef Inst;
1049 auto Duplex = HeadTail.first.split('\v');
1050 if(!Duplex.second.empty()){
1051 OS << Duplex.first;
1052 OS << "; ";
1053 Inst = Duplex.second;
1054 }
1055 else
1056 Inst = HeadTail.first;
1057 OS << Inst;
1058 HeadTail = HeadTail.second.split('\n');
1059 if (HeadTail.first.empty())
1060 OS << " } " << PacketBundle.second;
1061 PrintReloc();
1062 Bytes = Bytes.slice(4);
1063 Address += 4;
1064 }
1065 }
1066};
1067HexagonPrettyPrinter HexagonPrettyPrinterInst;
1068
1069class AMDGCNPrettyPrinter : public PrettyPrinter {
1070public:
1071 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1072 uint64_t Address, raw_ostream &OS, StringRef Annot,
1073 MCSubtargetInfo const &STI, SourcePrinter *SP,
1074 std::vector<RelocationRef> *Rels) override {
1075 if (SP && (PrintSource || PrintLines))
1076 SP->printSourceLine(OS, Address);
1077
1078 typedef support::ulittle32_t U32;
1079
1080 if (MI) {
1081 SmallString<40> InstStr;
1082 raw_svector_ostream IS(InstStr);
1083
1084 IP.printInst(MI, IS, "", STI);
1085
1086 OS << left_justify(IS.str(), 60);
1087 } else {
1088 // an unrecognized encoding - this is probably data so represent it
1089 // using the .long directive, or .byte directive if fewer than 4 bytes
1090 // remaining
1091 if (Bytes.size() >= 4) {
1092 OS << format("\t.long 0x%08" PRIx32 " ",
1093 static_cast<uint32_t>(*reinterpret_cast<const U32*>(Bytes.data())));
1094 OS.indent(42);
1095 } else {
1096 OS << format("\t.byte 0x%02" PRIx8, Bytes[0]);
1097 for (unsigned int i = 1; i < Bytes.size(); i++)
1098 OS << format(", 0x%02" PRIx8, Bytes[i]);
1099 OS.indent(55 - (6 * Bytes.size()));
1100 }
1101 }
1102
1103 OS << format("// %012" PRIX64 ": ", Address);
1104 if (Bytes.size() >=4) {
1105 for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
1106 Bytes.size() / sizeof(U32)))
1107 // D should be explicitly casted to uint32_t here as it is passed
1108 // by format to snprintf as vararg.
1109 OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D));
1110 } else {
1111 for (unsigned int i = 0; i < Bytes.size(); i++)
1112 OS << format("%02" PRIX8 " ", Bytes[i]);
1113 }
1114
1115 if (!Annot.empty())
1116 OS << "// " << Annot;
1117 }
1118};
1119AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
1120
1121class BPFPrettyPrinter : public PrettyPrinter {
1122public:
1123 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1124 uint64_t Address, raw_ostream &OS, StringRef Annot,
1125 MCSubtargetInfo const &STI, SourcePrinter *SP,
1126 std::vector<RelocationRef> *Rels) override {
1127 if (SP && (PrintSource || PrintLines))
1128 SP->printSourceLine(OS, Address);
1129 if (!NoLeadingAddr)
1130 OS << format("%8" PRId64 ":", Address / 8);
1131 if (!NoShowRawInsn) {
1132 OS << "\t";
1133 dumpBytes(Bytes, OS);
1134 }
1135 if (MI)
1136 IP.printInst(MI, OS, "", STI);
1137 else
1138 OS << " <unknown>";
1139 }
1140};
1141BPFPrettyPrinter BPFPrettyPrinterInst;
1142
1143PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
1144 switch(Triple.getArch()) {
1145 default:
1146 return PrettyPrinterInst;
1147 case Triple::hexagon:
1148 return HexagonPrettyPrinterInst;
1149 case Triple::amdgcn:
1150 return AMDGCNPrettyPrinterInst;
1151 case Triple::bpfel:
1152 case Triple::bpfeb:
1153 return BPFPrettyPrinterInst;
1154 }
1155}
1156}
1157
Sam Koltonc05d7782016-08-17 10:17:57 +00001158static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) {
1159 assert(Obj->isELF());
1160 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1161 return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1162 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1163 return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1164 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1165 return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1166 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1167 return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1168 llvm_unreachable("Unsupported binary format");
1169}
1170
Sam Parker5fba45a2017-02-08 09:44:18 +00001171template <class ELFT> static void
1172addDynamicElfSymbols(const ELFObjectFile<ELFT> *Obj,
1173 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1174 for (auto Symbol : Obj->getDynamicSymbolIterators()) {
1175 uint8_t SymbolType = Symbol.getELFType();
1176 if (SymbolType != ELF::STT_FUNC || Symbol.getSize() == 0)
1177 continue;
1178
1179 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
1180 if (!AddressOrErr)
1181 report_error(Obj->getFileName(), AddressOrErr.takeError());
1182 uint64_t Address = *AddressOrErr;
1183
1184 Expected<StringRef> Name = Symbol.getName();
1185 if (!Name)
1186 report_error(Obj->getFileName(), Name.takeError());
1187 if (Name->empty())
1188 continue;
1189
1190 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1191 if (!SectionOrErr)
1192 report_error(Obj->getFileName(), SectionOrErr.takeError());
1193 section_iterator SecI = *SectionOrErr;
1194 if (SecI == Obj->section_end())
1195 continue;
1196
1197 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1198 }
1199}
1200
1201static void
1202addDynamicElfSymbols(const ObjectFile *Obj,
1203 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1204 assert(Obj->isELF());
1205 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1206 addDynamicElfSymbols(Elf32LEObj, AllSymbols);
1207 else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1208 addDynamicElfSymbols(Elf64LEObj, AllSymbols);
1209 else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1210 addDynamicElfSymbols(Elf32BEObj, AllSymbols);
1211 else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1212 addDynamicElfSymbols(Elf64BEObj, AllSymbols);
1213 else
1214 llvm_unreachable("Unsupported binary format");
1215}
1216
Michael J. Spencer51862b32011-10-13 22:17:18 +00001217static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001218 if (StartAddress > StopAddress)
1219 error("Start address should be less than stop address");
1220
Jim Grosbachaf9aec02012-08-07 17:53:14 +00001221 const Target *TheTarget = getTarget(Obj);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001222
Jack Carter551efd72012-08-28 19:24:49 +00001223 // Package up features to be passed to target/subtarget
Daniel Sanders1d148642016-06-16 09:17:03 +00001224 SubtargetFeatures Features = Obj->getFeatures();
Jack Carter551efd72012-08-28 19:24:49 +00001225 if (MAttrs.size()) {
Jack Carter551efd72012-08-28 19:24:49 +00001226 for (unsigned i = 0; i != MAttrs.size(); ++i)
1227 Features.AddFeature(MAttrs[i]);
Jack Carter551efd72012-08-28 19:24:49 +00001228 }
1229
Ahmed Charles56440fd2014-03-06 05:51:42 +00001230 std::unique_ptr<const MCRegisterInfo> MRI(
1231 TheTarget->createMCRegInfo(TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +00001232 if (!MRI)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001233 report_error(Obj->getFileName(), "no register info for target " +
1234 TripleName);
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001235
1236 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00001237 std::unique_ptr<const MCAsmInfo> AsmInfo(
1238 TheTarget->createMCAsmInfo(*MRI, TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +00001239 if (!AsmInfo)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001240 report_error(Obj->getFileName(), "no assembly info for target " +
1241 TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +00001242 std::unique_ptr<const MCSubtargetInfo> STI(
Daniel Sanders1d148642016-06-16 09:17:03 +00001243 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
Davide Italiano711e4952015-12-17 01:59:50 +00001244 if (!STI)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001245 report_error(Obj->getFileName(), "no subtarget info for target " +
1246 TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +00001247 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
Davide Italiano711e4952015-12-17 01:59:50 +00001248 if (!MII)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001249 report_error(Obj->getFileName(), "no instruction info for target " +
1250 TripleName);
Sam Kolton3381d7a2016-10-06 13:46:08 +00001251 MCObjectFileInfo MOFI;
1252 MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI);
1253 // FIXME: for now initialize MCObjectFileInfo with default values
Rafael Espindola9f929952017-08-02 20:32:26 +00001254 MOFI.InitMCObjectFileInfo(Triple(TripleName), false, Ctx);
Lang Hamesa1bc0f52014-04-15 04:40:56 +00001255
1256 std::unique_ptr<MCDisassembler> DisAsm(
1257 TheTarget->createMCDisassembler(*STI, Ctx));
Davide Italiano711e4952015-12-17 01:59:50 +00001258 if (!DisAsm)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001259 report_error(Obj->getFileName(), "no disassembler for target " +
1260 TripleName);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001261
Ahmed Charles56440fd2014-03-06 05:51:42 +00001262 std::unique_ptr<const MCInstrAnalysis> MIA(
1263 TheTarget->createMCInstrAnalysis(MII.get()));
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001264
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001265 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Daniel Sanders50f17232015-09-15 16:17:27 +00001266 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1267 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
Davide Italiano711e4952015-12-17 01:59:50 +00001268 if (!IP)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001269 report_error(Obj->getFileName(), "no instruction printer for target " +
1270 TripleName);
Colin LeMahieu14ec76e2015-06-07 21:07:17 +00001271 IP->setPrintImmHex(PrintImmHex);
Colin LeMahieu35436a22015-05-29 14:48:25 +00001272 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001273
Greg Fitzgerald18432272014-03-20 22:55:15 +00001274 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
1275 "\t\t\t%08" PRIx64 ": ";
1276
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001277 SourcePrinter SP(Obj, TheTarget->getName());
1278
Mark Seaborn0929d3d2014-01-25 17:38:19 +00001279 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
1280 // in RelocSecs contain the relocations for section S.
Rafael Espindola4453e42942014-06-13 03:07:50 +00001281 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +00001282 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001283 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001284 section_iterator Sec2 = Section.getRelocatedSection();
Rafael Espindolab5155a52014-02-10 20:24:04 +00001285 if (Sec2 != Obj->section_end())
Alexey Samsonov48803e52014-03-13 14:37:36 +00001286 SectionRelocMap[*Sec2].push_back(Section);
Mark Seaborn0929d3d2014-01-25 17:38:19 +00001287 }
1288
David Majnemer81afca62015-07-07 22:06:59 +00001289 // Create a mapping from virtual address to symbol name. This is used to
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001290 // pretty print the symbols while disassembling.
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001291 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
Sterling Augustinebc78b622018-06-28 18:57:13 +00001292 SectionSymbolsTy AbsoluteSymbols;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001293 for (const SymbolRef &Symbol : Obj->symbols()) {
Kevin Enderby931cb652016-06-24 18:24:42 +00001294 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001295 if (!AddressOrErr)
1296 report_error(Obj->getFileName(), AddressOrErr.takeError());
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001297 uint64_t Address = *AddressOrErr;
David Majnemer2603a8fa2015-07-09 18:11:40 +00001298
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001299 Expected<StringRef> Name = Symbol.getName();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001300 if (!Name)
1301 report_error(Obj->getFileName(), Name.takeError());
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001302 if (Name->empty())
1303 continue;
David Majnemer81afca62015-07-07 22:06:59 +00001304
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001305 Expected<section_iterator> SectionOrErr = Symbol.getSection();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001306 if (!SectionOrErr)
1307 report_error(Obj->getFileName(), SectionOrErr.takeError());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001308
Sam Koltonc05d7782016-08-17 10:17:57 +00001309 uint8_t SymbolType = ELF::STT_NOTYPE;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001310 if (Obj->isELF())
Sam Koltonc05d7782016-08-17 10:17:57 +00001311 SymbolType = getElfSymbolType(Obj, Symbol);
David Majnemer81afca62015-07-07 22:06:59 +00001312
Sterling Augustinebc78b622018-06-28 18:57:13 +00001313 section_iterator SecI = *SectionOrErr;
1314 if (SecI != Obj->section_end())
1315 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1316 else
1317 AbsoluteSymbols.emplace_back(Address, *Name, SymbolType);
1318
Sam Koltonc05d7782016-08-17 10:17:57 +00001319
David Majnemer81afca62015-07-07 22:06:59 +00001320 }
Sam Parker5fba45a2017-02-08 09:44:18 +00001321 if (AllSymbols.empty() && Obj->isELF())
1322 addDynamicElfSymbols(Obj, AllSymbols);
David Majnemer81afca62015-07-07 22:06:59 +00001323
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001324 // Create a mapping from virtual address to section.
1325 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1326 for (SectionRef Sec : Obj->sections())
1327 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1328 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
1329
1330 // Linked executables (.exe and .dll files) typically don't include a real
1331 // symbol table but they might contain an export table.
1332 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
1333 for (const auto &ExportEntry : COFFObj->export_directories()) {
1334 StringRef Name;
1335 error(ExportEntry.getSymbolName(Name));
1336 if (Name.empty())
1337 continue;
1338 uint32_t RVA;
1339 error(ExportEntry.getExportRVA(RVA));
1340
1341 uint64_t VA = COFFObj->getImageBase() + RVA;
1342 auto Sec = std::upper_bound(
1343 SectionAddresses.begin(), SectionAddresses.end(), VA,
1344 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
1345 return LHS < RHS.first;
1346 });
1347 if (Sec != SectionAddresses.begin())
1348 --Sec;
1349 else
1350 Sec = SectionAddresses.end();
1351
1352 if (Sec != SectionAddresses.end())
Sam Koltonc05d7782016-08-17 10:17:57 +00001353 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
Sterling Augustinebc78b622018-06-28 18:57:13 +00001354 else
1355 AbsoluteSymbols.emplace_back(VA, Name, ELF::STT_NOTYPE);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001356 }
1357 }
1358
1359 // Sort all the symbols, this allows us to use a simple binary search to find
1360 // a symbol near an address.
1361 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1362 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
Sterling Augustinebc78b622018-06-28 18:57:13 +00001363 array_pod_sort(AbsoluteSymbols.begin(), AbsoluteSymbols.end());
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001364
Colin LeMahieu77804be2015-07-29 15:45:39 +00001365 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Colin LeMahieuf34933e2015-07-23 20:58:49 +00001366 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
Mark Seaborneb03ac52014-01-25 00:32:01 +00001367 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +00001368
Rafael Espindola80291272014-10-08 15:28:58 +00001369 uint64_t SectionAddr = Section.getAddress();
1370 uint64_t SectSize = Section.getSize();
David Majnemer185b5b12014-11-11 09:58:25 +00001371 if (!SectSize)
1372 continue;
Simon Atanasyan2b614e12014-02-24 22:12:11 +00001373
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001374 // Get the list of all the symbols in this section.
1375 SectionSymbolsTy &Symbols = AllSymbols[Section];
Davide Italianof0706882015-10-01 21:57:09 +00001376 std::vector<uint64_t> DataMappingSymsAddr;
1377 std::vector<uint64_t> TextMappingSymsAddr;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001378 if (isArmElf(Obj)) {
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001379 for (const auto &Symb : Symbols) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001380 uint64_t Address = std::get<0>(Symb);
1381 StringRef Name = std::get<1>(Symb);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001382 if (Name.startswith("$d"))
David Majnemer153722d2015-11-18 04:35:32 +00001383 DataMappingSymsAddr.push_back(Address - SectionAddr);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001384 if (Name.startswith("$x"))
David Majnemer153722d2015-11-18 04:35:32 +00001385 TextMappingSymsAddr.push_back(Address - SectionAddr);
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001386 if (Name.startswith("$a"))
1387 TextMappingSymsAddr.push_back(Address - SectionAddr);
1388 if (Name.startswith("$t"))
1389 TextMappingSymsAddr.push_back(Address - SectionAddr);
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001390 }
1391 }
1392
Mandeep Singh Grang8db564e2018-04-01 21:24:53 +00001393 llvm::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end());
1394 llvm::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end());
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001395
Sam Kolton3381d7a2016-10-06 13:46:08 +00001396 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1397 // AMDGPU disassembler uses symbolizer for printing labels
1398 std::unique_ptr<MCRelocationInfo> RelInfo(
1399 TheTarget->createMCRelocationInfo(TripleName, Ctx));
1400 if (RelInfo) {
1401 std::unique_ptr<MCSymbolizer> Symbolizer(
1402 TheTarget->createMCSymbolizer(
1403 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1404 DisAsm->setSymbolizer(std::move(Symbolizer));
1405 }
1406 }
1407
Michael J. Spencer51862b32011-10-13 22:17:18 +00001408 // Make a list of all the relocations for this section.
1409 std::vector<RelocationRef> Rels;
1410 if (InlineRelocs) {
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001411 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
1412 for (const RelocationRef &Reloc : RelocSec.relocations()) {
1413 Rels.push_back(Reloc);
1414 }
Michael J. Spencer51862b32011-10-13 22:17:18 +00001415 }
1416 }
1417
1418 // Sort relocations by address.
Mandeep Singh Grang8db564e2018-04-01 21:24:53 +00001419 llvm::sort(Rels.begin(), Rels.end(), RelocAddressLess);
Michael J. Spencer51862b32011-10-13 22:17:18 +00001420
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001421 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +00001422 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001423 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +00001424 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001425 }
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001426 StringRef SectionName;
1427 error(Section.getName(SectionName));
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001428
Rafael Espindola7884c952015-06-04 15:01:05 +00001429 // If the section has no symbol at the start, just insert a dummy one.
Sam Koltonc05d7782016-08-17 10:17:57 +00001430 if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) {
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001431 Symbols.insert(
1432 Symbols.begin(),
1433 std::make_tuple(SectionAddr, SectionName,
1434 Section.isText() ? ELF::STT_FUNC : ELF::STT_OBJECT));
Sam Koltonc05d7782016-08-17 10:17:57 +00001435 }
Alp Tokere69170a2014-06-26 22:52:05 +00001436
1437 SmallString<40> Comments;
1438 raw_svector_ostream CommentStream(Comments);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001439
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001440 StringRef BytesStr;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001441 error(Section.getContents(BytesStr));
Aaron Ballman106fd7b2014-11-12 14:01:17 +00001442 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1443 BytesStr.size());
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001444
Michael J. Spencer2670c252011-01-20 06:39:06 +00001445 uint64_t Size;
1446 uint64_t Index;
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001447 bool PrintedSection = false;
Michael J. Spencer2670c252011-01-20 06:39:06 +00001448
Michael J. Spencer51862b32011-10-13 22:17:18 +00001449 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
1450 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001451 // Disassemble symbol by symbol.
1452 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001453 uint64_t Start = std::get<0>(Symbols[si]) - SectionAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001454 // The end is either the section end or the beginning of the next
1455 // symbol.
1456 uint64_t End =
Sam Koltonc05d7782016-08-17 10:17:57 +00001457 (si == se - 1) ? SectSize : std::get<0>(Symbols[si + 1]) - SectionAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001458 // Don't try to disassemble beyond the end of section contents.
1459 if (End > SectSize)
1460 End = SectSize;
Rafael Espindolae45c7402014-08-17 16:31:39 +00001461 // If this symbol has the same address as the next symbol, then skip it.
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001462 if (Start >= End)
Michael J. Spenceree84f642011-10-13 20:37:08 +00001463 continue;
1464
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001465 // Check if we need to skip symbol
1466 // Skip if the symbol's data is not between StartAddress and StopAddress
1467 if (End + SectionAddr < StartAddress ||
1468 Start + SectionAddr > StopAddress) {
1469 continue;
1470 }
1471
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001472 /// Skip if user requested specific symbols and this is not in the list
1473 if (!DisasmFuncsSet.empty() &&
1474 !DisasmFuncsSet.count(std::get<1>(Symbols[si])))
1475 continue;
1476
1477 if (!PrintedSection) {
1478 PrintedSection = true;
1479 outs() << "Disassembly of section ";
1480 if (!SegmentName.empty())
1481 outs() << SegmentName << ",";
1482 outs() << SectionName << ':';
1483 }
1484
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001485 // Stop disassembly at the stop address specified
1486 if (End + SectionAddr > StopAddress)
1487 End = StopAddress - SectionAddr;
1488
Valery Pykhtinde048052016-04-07 07:24:01 +00001489 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001490 if (std::get<2>(Symbols[si]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1491 // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)
1492 Start += 256;
1493 }
1494 if (si == se - 1 ||
1495 std::get<2>(Symbols[si + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1496 // cut trailing zeroes at the end of kernel
1497 // cut up to 256 bytes
1498 const uint64_t EndAlign = 256;
1499 const auto Limit = End - (std::min)(EndAlign, End - Start);
1500 while (End > Limit &&
1501 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1502 End -= 4;
1503 }
Valery Pykhtinde048052016-04-07 07:24:01 +00001504 }
1505
Sam Koltonc05d7782016-08-17 10:17:57 +00001506 outs() << '\n' << std::get<1>(Symbols[si]) << ":\n";
Michael J. Spencer2670c252011-01-20 06:39:06 +00001507
Francis Visoiu Mistrih18346822018-04-19 17:02:57 +00001508 // Don't print raw contents of a virtual section. A virtual section
1509 // doesn't have any contents in the file.
1510 if (Section.isVirtual()) {
1511 outs() << "...\n";
1512 continue;
1513 }
1514
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001515#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +00001516 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001517#else
Mark Seaborneb03ac52014-01-25 00:32:01 +00001518 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001519#endif
1520
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001521 for (Index = Start; Index < End; Index += Size) {
1522 MCInst Inst;
Owen Andersona0c3b972011-09-15 23:38:46 +00001523
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001524 if (Index + SectionAddr < StartAddress ||
1525 Index + SectionAddr > StopAddress) {
1526 // skip byte by byte till StartAddress is reached
1527 Size = 1;
1528 continue;
1529 }
Davide Italianof0706882015-10-01 21:57:09 +00001530 // AArch64 ELF binaries can interleave data and text in the
1531 // same section. We rely on the markers introduced to
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001532 // understand what we need to dump. If the data marker is within a
1533 // function, it is denoted as a word/short etc
1534 if (isArmElf(Obj) && std::get<2>(Symbols[si]) != ELF::STT_OBJECT &&
1535 !DisassembleAll) {
Davide Italianof0706882015-10-01 21:57:09 +00001536 uint64_t Stride = 0;
1537
1538 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1539 DataMappingSymsAddr.end(), Index);
1540 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1541 // Switch to data.
1542 while (Index < End) {
1543 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1544 outs() << "\t";
1545 if (Index + 4 <= End) {
1546 Stride = 4;
1547 dumpBytes(Bytes.slice(Index, 4), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001548 outs() << "\t.word\t";
1549 uint32_t Data = 0;
1550 if (Obj->isLittleEndian()) {
1551 const auto Word =
1552 reinterpret_cast<const support::ulittle32_t *>(
1553 Bytes.data() + Index);
1554 Data = *Word;
1555 } else {
1556 const auto Word = reinterpret_cast<const support::ubig32_t *>(
1557 Bytes.data() + Index);
1558 Data = *Word;
1559 }
1560 outs() << "0x" << format("%08" PRIx32, Data);
Davide Italianof0706882015-10-01 21:57:09 +00001561 } else if (Index + 2 <= End) {
1562 Stride = 2;
1563 dumpBytes(Bytes.slice(Index, 2), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001564 outs() << "\t\t.short\t";
1565 uint16_t Data = 0;
1566 if (Obj->isLittleEndian()) {
1567 const auto Short =
1568 reinterpret_cast<const support::ulittle16_t *>(
1569 Bytes.data() + Index);
1570 Data = *Short;
1571 } else {
1572 const auto Short =
1573 reinterpret_cast<const support::ubig16_t *>(Bytes.data() +
1574 Index);
1575 Data = *Short;
1576 }
1577 outs() << "0x" << format("%04" PRIx16, Data);
Davide Italianof0706882015-10-01 21:57:09 +00001578 } else {
1579 Stride = 1;
1580 dumpBytes(Bytes.slice(Index, 1), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001581 outs() << "\t\t.byte\t";
1582 outs() << "0x" << format("%02" PRIx8, Bytes.slice(Index, 1)[0]);
Davide Italianof0706882015-10-01 21:57:09 +00001583 }
1584 Index += Stride;
1585 outs() << "\n";
1586 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1587 TextMappingSymsAddr.end(), Index);
1588 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1589 break;
1590 }
1591 }
1592 }
1593
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001594 // If there is a data symbol inside an ELF text section and we are only
1595 // disassembling text (applicable all architectures),
1596 // we are in a situation where we must print the data and not
1597 // disassemble it.
1598 if (Obj->isELF() && std::get<2>(Symbols[si]) == ELF::STT_OBJECT &&
1599 !DisassembleAll && Section.isText()) {
1600 // print out data up to 8 bytes at a time in hex and ascii
1601 uint8_t AsciiData[9] = {'\0'};
1602 uint8_t Byte;
1603 int NumBytes = 0;
1604
1605 for (Index = Start; Index < End; Index += 1) {
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001606 if (((SectionAddr + Index) < StartAddress) ||
1607 ((SectionAddr + Index) > StopAddress))
1608 continue;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001609 if (NumBytes == 0) {
1610 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1611 outs() << "\t";
1612 }
1613 Byte = Bytes.slice(Index)[0];
1614 outs() << format(" %02x", Byte);
1615 AsciiData[NumBytes] = isprint(Byte) ? Byte : '.';
1616
1617 uint8_t IndentOffset = 0;
1618 NumBytes++;
1619 if (Index == End - 1 || NumBytes > 8) {
1620 // Indent the space for less than 8 bytes data.
1621 // 2 spaces for byte and one for space between bytes
1622 IndentOffset = 3 * (8 - NumBytes);
1623 for (int Excess = 8 - NumBytes; Excess < 8; Excess++)
1624 AsciiData[Excess] = '\0';
1625 NumBytes = 8;
1626 }
1627 if (NumBytes == 8) {
1628 AsciiData[8] = '\0';
1629 outs() << std::string(IndentOffset, ' ') << " ";
1630 outs() << reinterpret_cast<char *>(AsciiData);
1631 outs() << '\n';
1632 NumBytes = 0;
1633 }
1634 }
1635 }
Davide Italianof0706882015-10-01 21:57:09 +00001636 if (Index >= End)
1637 break;
1638
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001639 // Disassemble a real instruction or a data when disassemble all is
1640 // provided
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001641 bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1642 SectionAddr + Index, DebugOut,
1643 CommentStream);
1644 if (Size == 0)
1645 Size = 1;
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001646
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001647 PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001648 Bytes.slice(Index, Size), SectionAddr + Index, outs(), "",
Sid Manningd9f28732018-05-14 19:46:08 +00001649 *STI, &SP, &Rels);
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001650 outs() << CommentStream.str();
1651 Comments.clear();
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001652
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001653 // Try to resolve the target of a call, tail call, etc. to a specific
1654 // symbol.
1655 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1656 MIA->isConditionalBranch(Inst))) {
1657 uint64_t Target;
1658 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1659 // In a relocatable object, the target's section must reside in
1660 // the same section as the call instruction or it is accessed
1661 // through a relocation.
1662 //
1663 // In a non-relocatable object, the target may be in any section.
1664 //
1665 // N.B. We don't walk the relocations in the relocatable case yet.
1666 auto *TargetSectionSymbols = &Symbols;
1667 if (!Obj->isRelocatableObject()) {
1668 auto SectionAddress = std::upper_bound(
1669 SectionAddresses.begin(), SectionAddresses.end(), Target,
1670 [](uint64_t LHS,
1671 const std::pair<uint64_t, SectionRef> &RHS) {
1672 return LHS < RHS.first;
1673 });
1674 if (SectionAddress != SectionAddresses.begin()) {
1675 --SectionAddress;
1676 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1677 } else {
Sterling Augustinebc78b622018-06-28 18:57:13 +00001678 TargetSectionSymbols = &AbsoluteSymbols;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001679 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001680 }
David Majnemer2603a8fa2015-07-09 18:11:40 +00001681
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001682 // Find the first symbol in the section whose offset is less than
Sterling Augustinebc78b622018-06-28 18:57:13 +00001683 // or equal to the target. If there isn't a section that contains
1684 // the target, find the nearest preceding absolute symbol.
1685 auto TargetSym = std::upper_bound(
1686 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1687 Target, [](uint64_t LHS,
1688 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1689 return LHS < std::get<0>(RHS);
1690 });
1691 if (TargetSym == TargetSectionSymbols->begin()) {
1692 TargetSectionSymbols = &AbsoluteSymbols;
1693 TargetSym = std::upper_bound(
1694 AbsoluteSymbols.begin(), AbsoluteSymbols.end(),
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001695 Target, [](uint64_t LHS,
Sam Koltonc05d7782016-08-17 10:17:57 +00001696 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
Sterling Augustinebc78b622018-06-28 18:57:13 +00001697 return LHS < std::get<0>(RHS);
1698 });
1699 }
1700 if (TargetSym != TargetSectionSymbols->begin()) {
1701 --TargetSym;
1702 uint64_t TargetAddress = std::get<0>(*TargetSym);
1703 StringRef TargetName = std::get<1>(*TargetSym);
1704 outs() << " <" << TargetName;
1705 uint64_t Disp = Target - TargetAddress;
1706 if (Disp)
1707 outs() << "+0x" << Twine::utohexstr(Disp);
1708 outs() << '>';
David Majnemer81afca62015-07-07 22:06:59 +00001709 }
1710 }
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001711 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001712 outs() << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001713
Sid Manningd9f28732018-05-14 19:46:08 +00001714 // Hexagon does this in pretty printer
1715 if (Obj->getArch() != Triple::hexagon)
1716 // Print relocation for instruction.
1717 while (rel_cur != rel_end) {
1718 bool hidden = getHidden(*rel_cur);
1719 uint64_t addr = rel_cur->getOffset();
1720 SmallString<16> name;
1721 SmallString<32> val;
Owen Andersonfa3e5202011-10-25 20:35:53 +00001722
Sid Manningd9f28732018-05-14 19:46:08 +00001723 // If this relocation is hidden, skip it.
1724 if (hidden || ((SectionAddr + addr) < StartAddress)) {
1725 ++rel_cur;
1726 continue;
1727 }
1728
1729 // Stop when rel_cur's address is past the current instruction.
1730 if (addr >= Index + Size) break;
1731 rel_cur->getTypeName(name);
1732 error(getRelocationValueString(*rel_cur, val));
1733 outs() << format(Fmt.data(), SectionAddr + addr) << name
1734 << "\t" << val << "\n";
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001735 ++rel_cur;
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001736 }
Benjamin Kramer87ee76c2011-07-20 19:37:35 +00001737 }
Michael J. Spencer2670c252011-01-20 06:39:06 +00001738 }
1739 }
1740}
1741
Kevin Enderby98da6132015-01-20 21:47:46 +00001742void llvm::PrintRelocations(const ObjectFile *Obj) {
Greg Fitzgerald18432272014-03-20 22:55:15 +00001743 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1744 "%08" PRIx64;
Rafael Espindola9219fe72016-03-21 20:59:15 +00001745 // Regular objdump doesn't print relocations in non-relocatable object
1746 // files.
1747 if (!Obj->isRelocatableObject())
1748 return;
Rafael Espindolac66d7612014-08-17 19:09:37 +00001749
Colin LeMahieu77804be2015-07-29 15:45:39 +00001750 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001751 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001752 continue;
1753 StringRef secname;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001754 error(Section.getName(secname));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001755 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001756 for (const RelocationRef &Reloc : Section.relocations()) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001757 bool hidden = getHidden(Reloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001758 uint64_t address = Reloc.getOffset();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001759 SmallString<32> relocname;
1760 SmallString<32> valuestr;
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001761 if (address < StartAddress || address > StopAddress || hidden)
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001762 continue;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001763 Reloc.getTypeName(relocname);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001764 error(getRelocationValueString(Reloc, valuestr));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001765 outs() << format(Fmt.data(), address) << " " << relocname << " "
1766 << valuestr << "\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001767 }
1768 outs() << "\n";
1769 }
1770}
1771
Paul Semelcb0f0432018-06-07 13:30:55 +00001772void llvm::PrintDynamicRelocations(const ObjectFile *Obj) {
1773
1774 // For the moment, this option is for ELF only
1775 if (!Obj->isELF())
1776 return;
1777
1778 const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj);
1779
1780 if (!Elf || Elf->getEType() != ELF::ET_DYN) {
1781 error("not a dynamic object");
1782 return;
1783 }
1784
1785 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
1786
1787 std::vector<SectionRef> DynRelSec = Obj->dynamic_relocation_sections();
1788 if (DynRelSec.empty())
1789 return;
1790
1791 outs() << "DYNAMIC RELOCATION RECORDS\n";
1792 for (const SectionRef &Section : DynRelSec) {
1793 if (Section.relocation_begin() == Section.relocation_end())
1794 continue;
1795 for (const RelocationRef &Reloc : Section.relocations()) {
1796 uint64_t address = Reloc.getOffset();
1797 SmallString<32> relocname;
1798 SmallString<32> valuestr;
1799 Reloc.getTypeName(relocname);
1800 error(getRelocationValueString(Reloc, valuestr));
1801 outs() << format(Fmt.data(), address) << " " << relocname << " "
1802 << valuestr << "\n";
1803 }
1804 }
1805}
1806
Kevin Enderby98da6132015-01-20 21:47:46 +00001807void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001808 outs() << "Sections:\n"
1809 "Idx Name Size Address Type\n";
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001810 unsigned i = 0;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001811 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001812 StringRef Name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001813 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001814 uint64_t Address = Section.getAddress();
1815 uint64_t Size = Section.getSize();
1816 bool Text = Section.isText();
1817 bool Data = Section.isData();
1818 bool BSS = Section.isBSS();
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001819 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +00001820 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
Alexey Samsonov48803e52014-03-13 14:37:36 +00001821 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1822 Name.str().c_str(), Size, Address, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001823 ++i;
1824 }
1825}
1826
Kevin Enderby98da6132015-01-20 21:47:46 +00001827void llvm::PrintSectionContents(const ObjectFile *Obj) {
Rafael Espindola4453e42942014-06-13 03:07:50 +00001828 std::error_code EC;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001829 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001830 StringRef Name;
1831 StringRef Contents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001832 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001833 uint64_t BaseAddr = Section.getAddress();
David Majnemer185b5b12014-11-11 09:58:25 +00001834 uint64_t Size = Section.getSize();
1835 if (!Size)
1836 continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001837
1838 outs() << "Contents of section " << Name << ":\n";
David Majnemer185b5b12014-11-11 09:58:25 +00001839 if (Section.isBSS()) {
Alexey Samsonov209095c2013-04-16 10:53:11 +00001840 outs() << format("<skipping contents of bss section at [%04" PRIx64
David Majnemer8f6b04c2014-07-14 16:20:14 +00001841 ", %04" PRIx64 ")>\n",
1842 BaseAddr, BaseAddr + Size);
Alexey Samsonov209095c2013-04-16 10:53:11 +00001843 continue;
1844 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001845
Davide Italianoccd53fe2015-08-05 07:18:31 +00001846 error(Section.getContents(Contents));
David Majnemer8f6b04c2014-07-14 16:20:14 +00001847
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001848 // Dump out the content as hex and printable ascii characters.
1849 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer82803112012-03-10 02:04:38 +00001850 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001851 // Dump line of hex.
1852 for (std::size_t i = 0; i < 16; ++i) {
1853 if (i != 0 && i % 4 == 0)
1854 outs() << ' ';
1855 if (addr + i < end)
1856 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1857 << hexdigit(Contents[addr + i] & 0xF, true);
1858 else
1859 outs() << " ";
1860 }
1861 // Print ascii.
1862 outs() << " ";
1863 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
Guy Benyei83c74e92013-02-12 21:21:59 +00001864 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001865 outs() << Contents[addr + i];
1866 else
1867 outs() << ".";
1868 }
1869 outs() << "\n";
1870 }
1871 }
1872}
1873
Kevin Enderby9acb1092016-05-31 20:35:34 +00001874void llvm::PrintSymbolTable(const ObjectFile *o, StringRef ArchiveName,
1875 StringRef ArchitectureName) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001876 outs() << "SYMBOL TABLE:\n";
1877
Rui Ueyama4e39f712014-03-18 18:58:51 +00001878 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
Davide Italianoe85abf72015-12-20 09:54:34 +00001879 printCOFFSymbolTable(coff);
Rui Ueyama4e39f712014-03-18 18:58:51 +00001880 return;
1881 }
1882 for (const SymbolRef &Symbol : o->symbols()) {
Kevin Enderby931cb652016-06-24 18:24:42 +00001883 Expected<uint64_t> AddressOrError = Symbol.getAddress();
1884 if (!AddressOrError)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001885 report_error(ArchiveName, o->getFileName(), AddressOrError.takeError(),
1886 ArchitectureName);
Rafael Espindolaed067c42015-07-03 18:19:00 +00001887 uint64_t Address = *AddressOrError;
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001888 if ((Address < StartAddress) || (Address > StopAddress))
1889 continue;
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001890 Expected<SymbolRef::Type> TypeOrError = Symbol.getType();
1891 if (!TypeOrError)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001892 report_error(ArchiveName, o->getFileName(), TypeOrError.takeError(),
1893 ArchitectureName);
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00001894 SymbolRef::Type Type = *TypeOrError;
Rui Ueyama4e39f712014-03-18 18:58:51 +00001895 uint32_t Flags = Symbol.getFlags();
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001896 Expected<section_iterator> SectionOrErr = Symbol.getSection();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001897 if (!SectionOrErr)
1898 report_error(ArchiveName, o->getFileName(), SectionOrErr.takeError(),
1899 ArchitectureName);
Rafael Espindola8bab8892015-08-07 23:27:14 +00001900 section_iterator Section = *SectionOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001901 StringRef Name;
1902 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1903 Section->getName(Name);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001904 } else {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001905 Expected<StringRef> NameOrErr = Symbol.getName();
1906 if (!NameOrErr)
Kevin Enderby9acb1092016-05-31 20:35:34 +00001907 report_error(ArchiveName, o->getFileName(), NameOrErr.takeError(),
1908 ArchitectureName);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001909 Name = *NameOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001910 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001911
Rui Ueyama4e39f712014-03-18 18:58:51 +00001912 bool Global = Flags & SymbolRef::SF_Global;
1913 bool Weak = Flags & SymbolRef::SF_Weak;
1914 bool Absolute = Flags & SymbolRef::SF_Absolute;
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001915 bool Common = Flags & SymbolRef::SF_Common;
Davide Italianocd2514d2015-04-30 23:08:53 +00001916 bool Hidden = Flags & SymbolRef::SF_Hidden;
David Meyer1df4b842012-02-28 23:47:53 +00001917
Rui Ueyama4e39f712014-03-18 18:58:51 +00001918 char GlobLoc = ' ';
1919 if (Type != SymbolRef::ST_Unknown)
1920 GlobLoc = Global ? 'g' : 'l';
1921 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1922 ? 'd' : ' ';
1923 char FileFunc = ' ';
1924 if (Type == SymbolRef::ST_File)
1925 FileFunc = 'f';
1926 else if (Type == SymbolRef::ST_Function)
1927 FileFunc = 'F';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001928
Rui Ueyama4e39f712014-03-18 18:58:51 +00001929 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1930 "%08" PRIx64;
Michael J. Spencerd857c1c2013-01-10 22:40:50 +00001931
Rui Ueyama4e39f712014-03-18 18:58:51 +00001932 outs() << format(Fmt, Address) << " "
1933 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1934 << (Weak ? 'w' : ' ') // Weak?
1935 << ' ' // Constructor. Not supported yet.
1936 << ' ' // Warning. Not supported yet.
1937 << ' ' // Indirect reference to another symbol.
1938 << Debug // Debugging (d) or dynamic (D) symbol.
1939 << FileFunc // Name of function (F), file (f) or object (O).
1940 << ' ';
1941 if (Absolute) {
1942 outs() << "*ABS*";
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001943 } else if (Common) {
1944 outs() << "*COM*";
Rui Ueyama4e39f712014-03-18 18:58:51 +00001945 } else if (Section == o->section_end()) {
1946 outs() << "*UND*";
1947 } else {
1948 if (const MachOObjectFile *MachO =
1949 dyn_cast<const MachOObjectFile>(o)) {
1950 DataRefImpl DR = Section->getRawDataRefImpl();
1951 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1952 outs() << SegmentName << ",";
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001953 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00001954 StringRef SectionName;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001955 error(Section->getName(SectionName));
Rui Ueyama4e39f712014-03-18 18:58:51 +00001956 outs() << SectionName;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001957 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001958
1959 outs() << '\t';
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001960 if (Common || isa<ELFObjectFileBase>(o)) {
Rafael Espindoladbb6bd32015-06-25 22:10:04 +00001961 uint64_t Val =
1962 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001963 outs() << format("\t %08" PRIx64 " ", Val);
1964 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001965
Davide Italianocd2514d2015-04-30 23:08:53 +00001966 if (Hidden) {
1967 outs() << ".hidden ";
1968 }
1969 outs() << Name
Rui Ueyama4e39f712014-03-18 18:58:51 +00001970 << '\n';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001971 }
1972}
1973
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001974static void PrintUnwindInfo(const ObjectFile *o) {
1975 outs() << "Unwind info:\n\n";
1976
1977 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1978 printCOFFUnwindInfo(coff);
Tim Northover4bd286a2014-08-01 13:07:19 +00001979 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1980 printMachOUnwindInfo(MachO);
1981 else {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001982 // TODO: Extract DWARF dump tool to objdump.
1983 errs() << "This operation is only currently supported "
Tim Northover4bd286a2014-08-01 13:07:19 +00001984 "for COFF and MachO object files.\n";
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001985 return;
1986 }
1987}
1988
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001989void llvm::printExportsTrie(const ObjectFile *o) {
Nick Kledzikd04bc352014-08-30 00:20:14 +00001990 outs() << "Exports trie:\n";
1991 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1992 printMachOExportsTrie(MachO);
1993 else {
1994 errs() << "This operation is only currently supported "
1995 "for Mach-O executable files.\n";
1996 return;
1997 }
1998}
1999
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002000void llvm::printRebaseTable(ObjectFile *o) {
Nick Kledzikac431442014-09-12 21:34:15 +00002001 outs() << "Rebase table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002002 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzikac431442014-09-12 21:34:15 +00002003 printMachORebaseTable(MachO);
2004 else {
2005 errs() << "This operation is only currently supported "
2006 "for Mach-O executable files.\n";
2007 return;
2008 }
2009}
2010
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002011void llvm::printBindTable(ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00002012 outs() << "Bind table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002013 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzik56ebef42014-09-16 01:41:51 +00002014 printMachOBindTable(MachO);
2015 else {
2016 errs() << "This operation is only currently supported "
2017 "for Mach-O executable files.\n";
2018 return;
2019 }
2020}
2021
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002022void llvm::printLazyBindTable(ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00002023 outs() << "Lazy bind table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002024 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzik56ebef42014-09-16 01:41:51 +00002025 printMachOLazyBindTable(MachO);
2026 else {
2027 errs() << "This operation is only currently supported "
2028 "for Mach-O executable files.\n";
2029 return;
2030 }
2031}
2032
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002033void llvm::printWeakBindTable(ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00002034 outs() << "Weak bind table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002035 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzik56ebef42014-09-16 01:41:51 +00002036 printMachOWeakBindTable(MachO);
2037 else {
2038 errs() << "This operation is only currently supported "
2039 "for Mach-O executable files.\n";
2040 return;
2041 }
2042}
Nick Kledzikac431442014-09-12 21:34:15 +00002043
Adrian Prantl437105a2015-07-08 02:04:15 +00002044/// Dump the raw contents of the __clangast section so the output can be piped
2045/// into llvm-bcanalyzer.
2046void llvm::printRawClangAST(const ObjectFile *Obj) {
2047 if (outs().is_displayed()) {
2048 errs() << "The -raw-clang-ast option will dump the raw binary contents of "
2049 "the clang ast section.\n"
2050 "Please redirect the output to a file or another program such as "
2051 "llvm-bcanalyzer.\n";
2052 return;
2053 }
2054
2055 StringRef ClangASTSectionName("__clangast");
2056 if (isa<COFFObjectFile>(Obj)) {
2057 ClangASTSectionName = "clangast";
2058 }
2059
2060 Optional<object::SectionRef> ClangASTSection;
Colin LeMahieu77804be2015-07-29 15:45:39 +00002061 for (auto Sec : ToolSectionFilter(*Obj)) {
Adrian Prantl437105a2015-07-08 02:04:15 +00002062 StringRef Name;
2063 Sec.getName(Name);
2064 if (Name == ClangASTSectionName) {
2065 ClangASTSection = Sec;
2066 break;
2067 }
2068 }
2069 if (!ClangASTSection)
2070 return;
2071
2072 StringRef ClangASTContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00002073 error(ClangASTSection.getValue().getContents(ClangASTContents));
Adrian Prantl437105a2015-07-08 02:04:15 +00002074 outs().write(ClangASTContents.data(), ClangASTContents.size());
2075}
2076
Sanjoy Das6f567a42015-06-22 18:03:02 +00002077static void printFaultMaps(const ObjectFile *Obj) {
2078 const char *FaultMapSectionName = nullptr;
2079
2080 if (isa<ELFObjectFileBase>(Obj)) {
2081 FaultMapSectionName = ".llvm_faultmaps";
2082 } else if (isa<MachOObjectFile>(Obj)) {
2083 FaultMapSectionName = "__llvm_faultmaps";
2084 } else {
2085 errs() << "This operation is only currently supported "
2086 "for ELF and Mach-O executable files.\n";
2087 return;
2088 }
2089
2090 Optional<object::SectionRef> FaultMapSection;
2091
Colin LeMahieu77804be2015-07-29 15:45:39 +00002092 for (auto Sec : ToolSectionFilter(*Obj)) {
Sanjoy Das6f567a42015-06-22 18:03:02 +00002093 StringRef Name;
2094 Sec.getName(Name);
2095 if (Name == FaultMapSectionName) {
2096 FaultMapSection = Sec;
2097 break;
2098 }
2099 }
2100
2101 outs() << "FaultMap table:\n";
2102
2103 if (!FaultMapSection.hasValue()) {
2104 outs() << "<not found>\n";
2105 return;
2106 }
2107
2108 StringRef FaultMapContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00002109 error(FaultMapSection.getValue().getContents(FaultMapContents));
Sanjoy Das6f567a42015-06-22 18:03:02 +00002110
2111 FaultMapParser FMP(FaultMapContents.bytes_begin(),
2112 FaultMapContents.bytes_end());
2113
2114 outs() << FMP;
2115}
2116
Davide Italiano1bdaa202016-09-18 04:39:15 +00002117static void printPrivateFileHeaders(const ObjectFile *o, bool onlyFirst) {
Kevin Enderby0ae163f2016-01-13 00:25:36 +00002118 if (o->isELF())
Davide Italiano1bdaa202016-09-18 04:39:15 +00002119 return printELFFileHeader(o);
2120 if (o->isCOFF())
2121 return printCOFFFileHeader(o);
Derek Schuff2c6f75d2016-11-30 16:49:11 +00002122 if (o->isWasm())
2123 return printWasmFileHeader(o);
Davide Italiano1bdaa202016-09-18 04:39:15 +00002124 if (o->isMachO()) {
Kevin Enderby0ae163f2016-01-13 00:25:36 +00002125 printMachOFileHeader(o);
Davide Italiano1bdaa202016-09-18 04:39:15 +00002126 if (!onlyFirst)
2127 printMachOLoadCommands(o);
2128 return;
2129 }
Kevin Enderby7fa40c92016-11-16 22:17:38 +00002130 report_error(o->getFileName(), "Invalid/Unsupported object file format");
Rui Ueyamac2bed422013-09-27 21:04:00 +00002131}
2132
Paul Semeld2af4d62018-07-04 15:25:03 +00002133static void printFileHeaders(const ObjectFile *o) {
2134 if (!o->isELF() && !o->isCOFF())
2135 report_error(o->getFileName(), "Invalid/Unsupported object file format");
2136
2137 Triple::ArchType AT = o->getArch();
2138 outs() << "architecture: " << Triple::getArchTypeName(AT) << "\n";
2139 Expected<uint64_t> StartAddrOrErr = o->getStartAddress();
2140 if (!StartAddrOrErr)
2141 report_error(o->getFileName(), StartAddrOrErr.takeError());
2142 outs() << "start address: "
2143 << format("0x%0*x", o->getBytesInAddress(), StartAddrOrErr.get())
2144 << "\n";
2145}
2146
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002147static void DumpObject(ObjectFile *o, const Archive *a = nullptr) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002148 StringRef ArchiveName = a != nullptr ? a->getFileName() : "";
Adrian Prantl437105a2015-07-08 02:04:15 +00002149 // Avoid other output when using a raw option.
2150 if (!RawClangAST) {
2151 outs() << '\n';
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002152 if (a)
2153 outs() << a->getFileName() << "(" << o->getFileName() << ")";
2154 else
2155 outs() << o->getFileName();
2156 outs() << ":\tfile format " << o->getFileFormatName() << "\n\n";
Adrian Prantl437105a2015-07-08 02:04:15 +00002157 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00002158
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002159 if (Disassemble)
Michael J. Spencer51862b32011-10-13 22:17:18 +00002160 DisassembleObject(o, Relocations);
2161 if (Relocations && !Disassemble)
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002162 PrintRelocations(o);
Paul Semelcb0f0432018-06-07 13:30:55 +00002163 if (DynamicRelocations)
2164 PrintDynamicRelocations(o);
Nick Lewyckyfcf84622011-10-10 21:21:34 +00002165 if (SectionHeaders)
2166 PrintSectionHeaders(o);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00002167 if (SectionContents)
2168 PrintSectionContents(o);
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002169 if (SymbolTable)
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002170 PrintSymbolTable(o, ArchiveName);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00002171 if (UnwindInfo)
2172 PrintUnwindInfo(o);
Davide Italiano1bdaa202016-09-18 04:39:15 +00002173 if (PrivateHeaders || FirstPrivateHeader)
2174 printPrivateFileHeaders(o, FirstPrivateHeader);
Paul Semeld2af4d62018-07-04 15:25:03 +00002175 if (FileHeaders)
2176 printFileHeaders(o);
Nick Kledzikd04bc352014-08-30 00:20:14 +00002177 if (ExportsTrie)
2178 printExportsTrie(o);
Nick Kledzikac431442014-09-12 21:34:15 +00002179 if (Rebase)
2180 printRebaseTable(o);
Nick Kledzik56ebef42014-09-16 01:41:51 +00002181 if (Bind)
2182 printBindTable(o);
2183 if (LazyBind)
2184 printLazyBindTable(o);
2185 if (WeakBind)
2186 printWeakBindTable(o);
Adrian Prantl437105a2015-07-08 02:04:15 +00002187 if (RawClangAST)
2188 printRawClangAST(o);
Sanjoy Das6f567a42015-06-22 18:03:02 +00002189 if (PrintFaultMaps)
2190 printFaultMaps(o);
Igor Laevsky03a670c2016-01-26 15:09:42 +00002191 if (DwarfDumpType != DIDT_Null) {
Rafael Espindolac398e672017-07-19 22:27:28 +00002192 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*o);
Igor Laevsky03a670c2016-01-26 15:09:42 +00002193 // Dump the complete DWARF structure.
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00002194 DIDumpOptions DumpOpts;
2195 DumpOpts.DumpType = DwarfDumpType;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00002196 DICtx->dump(outs(), DumpOpts);
Igor Laevsky03a670c2016-01-26 15:09:42 +00002197 }
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002198}
2199
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00002200static void DumpObject(const COFFImportFile *I, const Archive *A) {
2201 StringRef ArchiveName = A ? A->getFileName() : "";
2202
2203 // Avoid other output when using a raw option.
2204 if (!RawClangAST)
2205 outs() << '\n'
2206 << ArchiveName << "(" << I->getFileName() << ")"
2207 << ":\tfile format COFF-import-file"
2208 << "\n\n";
2209
2210 if (SymbolTable)
2211 printCOFFSymbolTable(I);
2212}
2213
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +00002214/// Dump each object file in \a a;
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002215static void DumpArchive(const Archive *a) {
Mehdi Amini41af4302016-11-11 04:28:40 +00002216 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00002217 for (auto &C : a->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002218 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2219 if (!ChildOrErr) {
2220 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2221 report_error(a->getFileName(), C, std::move(E));
2222 continue;
2223 }
Rafael Espindolaae460022014-06-16 16:08:36 +00002224 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002225 DumpObject(o, a);
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00002226 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
2227 DumpObject(I, a);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002228 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00002229 report_error(a->getFileName(), object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002230 }
Lang Hamesfc209622016-07-14 02:24:01 +00002231 if (Err)
2232 report_error(a->getFileName(), std::move(Err));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002233}
2234
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +00002235/// Open file and figure out how to dump it.
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002236static void DumpInput(StringRef file) {
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002237
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002238 // If we are using the Mach-O specific object file parser, then let it parse
2239 // the file and process the command line options. So the -arch flags can
2240 // be used to select specific slices, etc.
2241 if (MachOOpt) {
2242 ParseInputMachO(file);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002243 return;
2244 }
2245
2246 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00002247 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
2248 if (!BinaryOrErr)
Kevin Enderbyb34e3a12016-05-05 17:43:35 +00002249 report_error(file, BinaryOrErr.takeError());
Rafael Espindola48af1c22014-08-19 18:44:46 +00002250 Binary &Binary = *BinaryOrErr.get().getBinary();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002251
Rafael Espindola3f6481d2014-08-01 14:31:55 +00002252 if (Archive *a = dyn_cast<Archive>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002253 DumpArchive(a);
Rafael Espindola3f6481d2014-08-01 14:31:55 +00002254 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002255 DumpObject(o);
Jim Grosbachaf9aec02012-08-07 17:53:14 +00002256 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00002257 report_error(file, object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002258}
2259
Michael J. Spencer2670c252011-01-20 06:39:06 +00002260int main(int argc, char **argv) {
Rui Ueyama197194b2018-04-13 18:26:06 +00002261 InitLLVM X(argc, argv);
Michael J. Spencer2670c252011-01-20 06:39:06 +00002262
2263 // Initialize targets and assembly printers/parsers.
2264 llvm::InitializeAllTargetInfos();
Evan Cheng8c886a42011-07-22 21:58:54 +00002265 llvm::InitializeAllTargetMCs();
Michael J. Spencer2670c252011-01-20 06:39:06 +00002266 llvm::InitializeAllDisassemblers();
2267
Pete Cooper28fb4fc2012-05-03 23:20:10 +00002268 // Register the target printer for --version.
2269 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
2270
Michael J. Spencer2670c252011-01-20 06:39:06 +00002271 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
2272 TripleName = Triple::normalize(TripleName);
2273
2274 ToolName = argv[0];
2275
2276 // Defaults to a.out if no filenames specified.
2277 if (InputFilenames.size() == 0)
2278 InputFilenames.push_back("a.out");
2279
Fangrui Song8513cd42018-06-27 20:45:11 +00002280 if (AllHeaders)
2281 PrivateHeaders = Relocations = SectionHeaders = SymbolTable = true;
2282
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00002283 if (DisassembleAll || PrintSource || PrintLines)
Colin LeMahieuf34933e2015-07-23 20:58:49 +00002284 Disassemble = true;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002285 if (!Disassemble
2286 && !Relocations
Paul Semelcb0f0432018-06-07 13:30:55 +00002287 && !DynamicRelocations
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002288 && !SectionHeaders
2289 && !SectionContents
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00002290 && !SymbolTable
Michael J. Spencer209565db2013-01-06 03:56:49 +00002291 && !UnwindInfo
Nick Kledzikd04bc352014-08-30 00:20:14 +00002292 && !PrivateHeaders
Paul Semeld2af4d62018-07-04 15:25:03 +00002293 && !FileHeaders
Kevin Enderby0ae163f2016-01-13 00:25:36 +00002294 && !FirstPrivateHeader
Nick Kledzikac431442014-09-12 21:34:15 +00002295 && !ExportsTrie
Nick Kledzik56ebef42014-09-16 01:41:51 +00002296 && !Rebase
2297 && !Bind
2298 && !LazyBind
Kevin Enderby131d1772015-01-09 19:22:37 +00002299 && !WeakBind
Adrian Prantl437105a2015-07-08 02:04:15 +00002300 && !RawClangAST
Kevin Enderby13023a12015-01-15 23:19:11 +00002301 && !(UniversalHeaders && MachOOpt)
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00002302 && !(ArchiveHeaders && MachOOpt)
Kevin Enderby69fe98d2015-01-23 18:52:17 +00002303 && !(IndirectSymbols && MachOOpt)
Kevin Enderby9a509442015-01-27 21:28:24 +00002304 && !(DataInCode && MachOOpt)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002305 && !(LinkOptHints && MachOOpt)
Kevin Enderbycd66be52015-03-11 22:06:32 +00002306 && !(InfoPlist && MachOOpt)
Kevin Enderbybc847fa2015-03-16 20:08:09 +00002307 && !(DylibsUsed && MachOOpt)
2308 && !(DylibId && MachOOpt)
Kevin Enderby0fc11822015-04-01 20:57:01 +00002309 && !(ObjcMetaData && MachOOpt)
Colin LeMahieufcc32762015-07-29 19:08:10 +00002310 && !(FilterSections.size() != 0 && MachOOpt)
Igor Laevsky03a670c2016-01-26 15:09:42 +00002311 && !PrintFaultMaps
2312 && DwarfDumpType == DIDT_Null) {
Michael J. Spencer2670c252011-01-20 06:39:06 +00002313 cl::PrintHelpMessage();
Dimitry Andrice4f5d012017-12-18 19:46:56 +00002314 return 2;
2315 }
2316
Rafael Aulerb0e4b912018-03-09 19:13:44 +00002317 DisasmFuncsSet.insert(DisassembleFunctions.begin(),
2318 DisassembleFunctions.end());
2319
Dimitry Andrice4f5d012017-12-18 19:46:56 +00002320 llvm::for_each(InputFilenames, DumpInput);
2321
2322 return EXIT_SUCCESS;
2323}