blob: 21d7a215fcfcd792d3d9954dd89d8f222bcf6adb [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
Benjamin Kramer43a772e2011-09-19 17:56:04 +000070static cl::list<std::string>
71InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
Michael J. Spencer2670c252011-01-20 06:39:06 +000072
Kevin Enderbye2297dd2015-01-07 21:02:18 +000073cl::opt<bool>
74llvm::Disassemble("disassemble",
Benjamin Kramer43a772e2011-09-19 17:56:04 +000075 cl::desc("Display assembler mnemonics for the machine instructions"));
76static cl::alias
77Disassembled("d", cl::desc("Alias for --disassemble"),
Colin LeMahieu77804be2015-07-29 15:45:39 +000078 cl::aliasopt(Disassemble));
79
80cl::opt<bool>
81llvm::DisassembleAll("disassemble-all",
82 cl::desc("Display assembler mnemonics for the machine instructions"));
83static cl::alias
84DisassembleAlld("D", cl::desc("Alias for --disassemble-all"),
Colin LeMahieuf34933e2015-07-23 20:58:49 +000085 cl::aliasopt(DisassembleAll));
Michael J. Spencer2670c252011-01-20 06:39:06 +000086
Rafael Aulerb0e4b912018-03-09 19:13:44 +000087static cl::list<std::string>
88DisassembleFunctions("df",
89 cl::CommaSeparated,
90 cl::desc("List of functions to disassemble"));
91static StringSet<> DisasmFuncsSet;
92
Kevin Enderby98da6132015-01-20 21:47:46 +000093cl::opt<bool>
94llvm::Relocations("r", cl::desc("Display the relocation entries in the file"));
Michael J. Spencerba4a3622011-10-08 00:18:30 +000095
Kevin Enderby98da6132015-01-20 21:47:46 +000096cl::opt<bool>
Paul Semelcb0f0432018-06-07 13:30:55 +000097llvm::DynamicRelocations("dynamic-reloc",
98 cl::desc("Display the dynamic relocation entries in the file"));
99static cl::alias
100DynamicRelocationsd("R", cl::desc("Alias for --dynamic-reloc"),
101 cl::aliasopt(DynamicRelocations));
102
103cl::opt<bool>
Kevin Enderby98da6132015-01-20 21:47:46 +0000104llvm::SectionContents("s", cl::desc("Display the content of each section"));
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000105
Kevin Enderby98da6132015-01-20 21:47:46 +0000106cl::opt<bool>
107llvm::SymbolTable("t", cl::desc("Display the symbol table"));
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000108
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000109cl::opt<bool>
110llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
Nick Kledzikd04bc352014-08-30 00:20:14 +0000111
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000112cl::opt<bool>
113llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
Nick Kledzikac431442014-09-12 21:34:15 +0000114
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000115cl::opt<bool>
116llvm::Bind("bind", cl::desc("Display mach-o binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000117
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000118cl::opt<bool>
119llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000120
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000121cl::opt<bool>
122llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000123
Adrian Prantl437105a2015-07-08 02:04:15 +0000124cl::opt<bool>
125llvm::RawClangAST("raw-clang-ast",
126 cl::desc("Dump the raw binary contents of the clang AST section"));
127
Nick Kledzik56ebef42014-09-16 01:41:51 +0000128static cl::opt<bool>
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000129MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000130static cl::alias
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000131MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
Benjamin Kramer87ee76c2011-07-20 19:37:35 +0000132
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000133cl::opt<std::string>
134llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
135 "see -version for available targets"));
136
137cl::opt<std::string>
Kevin Enderbyc9595622014-08-06 23:24:41 +0000138llvm::MCPU("mcpu",
139 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
140 cl::value_desc("cpu-name"),
141 cl::init(""));
142
143cl::opt<std::string>
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000144llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
Michael J. Spencer2670c252011-01-20 06:39:06 +0000145 "see -version for available targets"));
146
Kevin Enderby98da6132015-01-20 21:47:46 +0000147cl::opt<bool>
148llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
149 "headers for each section."));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000150static cl::alias
151SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
152 cl::aliasopt(SectionHeaders));
153static cl::alias
154SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
155 cl::aliasopt(SectionHeaders));
Colin LeMahieufcc32762015-07-29 19:08:10 +0000156
Colin LeMahieu77804be2015-07-29 15:45:39 +0000157cl::list<std::string>
Colin LeMahieufcc32762015-07-29 19:08:10 +0000158llvm::FilterSections("section", cl::desc("Operate on the specified sections only. "
159 "With -macho dump segment,section"));
160cl::alias
161static FilterSectionsj("j", cl::desc("Alias for --section"),
162 cl::aliasopt(llvm::FilterSections));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000163
Kevin Enderbyc9595622014-08-06 23:24:41 +0000164cl::list<std::string>
165llvm::MAttrs("mattr",
Jack Carter551efd72012-08-28 19:24:49 +0000166 cl::CommaSeparated,
167 cl::desc("Target specific attributes"),
168 cl::value_desc("a1,+a2,-a3,..."));
169
Kevin Enderbybf246f52014-09-24 23:08:22 +0000170cl::opt<bool>
171llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
172 "instructions, do not print "
173 "the instruction bytes."));
Saleem Abdulrasooldea14b22017-02-08 18:11:31 +0000174cl::opt<bool>
175llvm::NoLeadingAddr("no-leading-addr", cl::desc("Print no leading address"));
Eli Bendersky3a6808c2012-11-20 22:57:02 +0000176
Kevin Enderby98da6132015-01-20 21:47:46 +0000177cl::opt<bool>
178llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000179
180static cl::alias
181UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
182 cl::aliasopt(UnwindInfo));
183
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000184cl::opt<bool>
185llvm::PrivateHeaders("private-headers",
186 cl::desc("Display format specific file headers"));
Michael J. Spencer209565db2013-01-06 03:56:49 +0000187
Kevin Enderby0ae163f2016-01-13 00:25:36 +0000188cl::opt<bool>
189llvm::FirstPrivateHeader("private-header",
190 cl::desc("Display only the first format specific file "
191 "header"));
192
Michael J. Spencer209565db2013-01-06 03:56:49 +0000193static cl::alias
194PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
195 cl::aliasopt(PrivateHeaders));
196
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000197cl::opt<bool>
198 llvm::PrintImmHex("print-imm-hex",
Colin LeMahieuefe37322016-04-08 18:15:37 +0000199 cl::desc("Use hex format for immediate values"));
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000200
Sanjoy Das6f567a42015-06-22 18:03:02 +0000201cl::opt<bool> PrintFaultMaps("fault-map-section",
202 cl::desc("Display contents of faultmap section"));
203
Igor Laevsky03a670c2016-01-26 15:09:42 +0000204cl::opt<DIDumpType> llvm::DwarfDumpType(
205 "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"),
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000206 cl::values(clEnumValN(DIDT_DebugFrame, "frames", ".debug_frame")));
Igor Laevsky03a670c2016-01-26 15:09:42 +0000207
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000208cl::opt<bool> PrintSource(
209 "source",
210 cl::desc(
Alex Denisova07169e2018-02-02 19:20:37 +0000211 "Display source inlined with disassembly. Implies disassemble object"));
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000212
213cl::alias PrintSourceShort("S", cl::desc("Alias for -source"),
214 cl::aliasopt(PrintSource));
215
216cl::opt<bool> PrintLines("line-numbers",
217 cl::desc("Display source line numbers with "
218 "disassembly. Implies disassemble object"));
219
220cl::alias PrintLinesShort("l", cl::desc("Alias for -line-numbers"),
221 cl::aliasopt(PrintLines));
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +0000222
223cl::opt<unsigned long long>
224 StartAddress("start-address", cl::desc("Disassemble beginning at address"),
225 cl::value_desc("address"), cl::init(0));
226cl::opt<unsigned long long>
227 StopAddress("stop-address", cl::desc("Stop disassembly at address"),
228 cl::value_desc("address"), cl::init(UINT64_MAX));
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000229static StringRef ToolName;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000230
Sam Parker5fba45a2017-02-08 09:44:18 +0000231typedef std::vector<std::tuple<uint64_t, StringRef, uint8_t>> SectionSymbolsTy;
232
Colin LeMahieu77804be2015-07-29 15:45:39 +0000233namespace {
Colin LeMahieufcc32762015-07-29 19:08:10 +0000234typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate;
Colin LeMahieu77804be2015-07-29 15:45:39 +0000235
236class SectionFilterIterator {
237public:
238 SectionFilterIterator(FilterPredicate P,
239 llvm::object::section_iterator const &I,
240 llvm::object::section_iterator const &E)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000241 : Predicate(std::move(P)), Iterator(I), End(E) {
Colin LeMahieu77804be2015-07-29 15:45:39 +0000242 ScanPredicate();
243 }
Benjamin Kramerac9257b2015-09-24 14:52:52 +0000244 const llvm::object::SectionRef &operator*() const { return *Iterator; }
Colin LeMahieu77804be2015-07-29 15:45:39 +0000245 SectionFilterIterator &operator++() {
246 ++Iterator;
247 ScanPredicate();
248 return *this;
249 }
250 bool operator!=(SectionFilterIterator const &Other) const {
251 return Iterator != Other.Iterator;
252 }
253
254private:
255 void ScanPredicate() {
Colin LeMahieuda1723f2015-07-29 19:21:13 +0000256 while (Iterator != End && !Predicate(*Iterator)) {
Colin LeMahieu77804be2015-07-29 15:45:39 +0000257 ++Iterator;
258 }
259 }
260 FilterPredicate Predicate;
261 llvm::object::section_iterator Iterator;
262 llvm::object::section_iterator End;
263};
264
265class SectionFilter {
266public:
267 SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000268 : Predicate(std::move(P)), Object(O) {}
Colin LeMahieu77804be2015-07-29 15:45:39 +0000269 SectionFilterIterator begin() {
270 return SectionFilterIterator(Predicate, Object.section_begin(),
271 Object.section_end());
272 }
273 SectionFilterIterator end() {
274 return SectionFilterIterator(Predicate, Object.section_end(),
275 Object.section_end());
276 }
277
278private:
279 FilterPredicate Predicate;
280 llvm::object::ObjectFile const &Object;
281};
282SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) {
David Majnemer42531262016-08-12 03:55:06 +0000283 return SectionFilter(
284 [](llvm::object::SectionRef const &S) {
285 if (FilterSections.empty())
286 return true;
287 llvm::StringRef String;
288 std::error_code error = S.getName(String);
289 if (error)
290 return false;
291 return is_contained(FilterSections, String);
292 },
293 O);
Colin LeMahieu77804be2015-07-29 15:45:39 +0000294}
295}
296
Davide Italianoccd53fe2015-08-05 07:18:31 +0000297void llvm::error(std::error_code EC) {
Mark Seaborneb03ac52014-01-25 00:32:01 +0000298 if (!EC)
Davide Italianoccd53fe2015-08-05 07:18:31 +0000299 return;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000300
Davide Italiano140af642015-12-25 18:16:45 +0000301 errs() << ToolName << ": error reading file: " << EC.message() << ".\n";
302 errs().flush();
Davide Italiano7f6c3012015-08-06 00:18:52 +0000303 exit(1);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000304}
305
Kevin Enderby42398052016-06-28 23:16:13 +0000306LLVM_ATTRIBUTE_NORETURN void llvm::error(Twine Message) {
307 errs() << ToolName << ": " << Message << ".\n";
308 errs().flush();
309 exit(1);
310}
311
Davide Italianoed9d95b2015-12-29 13:41:02 +0000312LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000313 Twine Message) {
314 errs() << ToolName << ": '" << File << "': " << Message << ".\n";
315 exit(1);
316}
317
318LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
Davide Italianoed9d95b2015-12-29 13:41:02 +0000319 std::error_code EC) {
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000320 assert(EC);
321 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
Davide Italianoccd53fe2015-08-05 07:18:31 +0000322 exit(1);
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000323}
324
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000325LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
326 llvm::Error E) {
327 assert(E);
328 std::string Buf;
329 raw_string_ostream OS(Buf);
330 logAllUnhandledErrors(std::move(E), OS, "");
331 OS.flush();
Kevin Enderbyb34e3a12016-05-05 17:43:35 +0000332 errs() << ToolName << ": '" << File << "': " << Buf;
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000333 exit(1);
334}
335
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000336LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
337 StringRef FileName,
Kevin Enderby9acb1092016-05-31 20:35:34 +0000338 llvm::Error E,
339 StringRef ArchitectureName) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000340 assert(E);
341 errs() << ToolName << ": ";
342 if (ArchiveName != "")
343 errs() << ArchiveName << "(" << FileName << ")";
344 else
Justin Bogner31d8b7d2016-10-26 22:37:52 +0000345 errs() << "'" << FileName << "'";
Kevin Enderby9acb1092016-05-31 20:35:34 +0000346 if (!ArchitectureName.empty())
347 errs() << " (for architecture " << ArchitectureName << ")";
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000348 std::string Buf;
349 raw_string_ostream OS(Buf);
350 logAllUnhandledErrors(std::move(E), OS, "");
351 OS.flush();
Justin Bogner31d8b7d2016-10-26 22:37:52 +0000352 errs() << ": " << Buf;
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000353 exit(1);
354}
355
356LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
357 const object::Archive::Child &C,
Kevin Enderby9acb1092016-05-31 20:35:34 +0000358 llvm::Error E,
359 StringRef ArchitectureName) {
Kevin Enderbyf4586032016-07-29 17:44:13 +0000360 Expected<StringRef> NameOrErr = C.getName();
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000361 // TODO: if we have a error getting the name then it would be nice to print
362 // the index of which archive member this is and or its offset in the
363 // archive instead of "???" as the name.
Kevin Enderbyf4586032016-07-29 17:44:13 +0000364 if (!NameOrErr) {
365 consumeError(NameOrErr.takeError());
Kevin Enderby9acb1092016-05-31 20:35:34 +0000366 llvm::report_error(ArchiveName, "???", std::move(E), ArchitectureName);
Kevin Enderbyf4586032016-07-29 17:44:13 +0000367 } else
Kevin Enderby9acb1092016-05-31 20:35:34 +0000368 llvm::report_error(ArchiveName, NameOrErr.get(), std::move(E),
369 ArchitectureName);
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000370}
371
Craig Toppere6cb63e2014-04-25 04:24:47 +0000372static const Target *getTarget(const ObjectFile *Obj = nullptr) {
Michael J. Spencer2670c252011-01-20 06:39:06 +0000373 // Figure out the target triple.
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000374 llvm::Triple TheTriple("unknown-unknown-unknown");
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000375 if (TripleName.empty()) {
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000376 if (Obj) {
Vlad Tsyrklevichde620462017-09-19 02:22:48 +0000377 TheTriple = Obj->makeTriple();
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000378 }
Sam Parkerdf7c6ef2017-01-18 13:52:12 +0000379 } else {
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000380 TheTriple.setTriple(Triple::normalize(TripleName));
Vlad Tsyrklevichde620462017-09-19 02:22:48 +0000381
Sam Parkerdf7c6ef2017-01-18 13:52:12 +0000382 // Use the triple, but also try to combine with ARM build attributes.
383 if (Obj) {
384 auto Arch = Obj->getArch();
385 if (Arch == Triple::arm || Arch == Triple::armeb) {
386 Obj->setARMSubArch(TheTriple);
387 }
388 }
389 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000390
391 // Get the target specific parser.
392 std::string Error;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000393 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
394 Error);
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000395 if (!TheTarget) {
396 if (Obj)
397 report_error(Obj->getFileName(), "can't find target: " + Error);
398 else
399 error("can't find target: " + Error);
400 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000401
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000402 // Update the triple name and return the found target.
403 TripleName = TheTriple.getTriple();
404 return TheTarget;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000405}
406
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000407bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
Rafael Espindola704cd842015-07-06 15:47:43 +0000408 return a.getOffset() < b.getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +0000409}
410
Rafael Espindola37070a52015-06-03 04:48:06 +0000411template <class ELFT>
Rafael Espindola37070a52015-06-03 04:48:06 +0000412static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000413 const RelocationRef &RelRef,
Rafael Espindola37070a52015-06-03 04:48:06 +0000414 SmallVectorImpl<char> &Result) {
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000415 DataRefImpl Rel = RelRef.getRawDataRefImpl();
416
Rafael Espindola37070a52015-06-03 04:48:06 +0000417 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
418 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000419 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
420
Rafael Espindola37070a52015-06-03 04:48:06 +0000421 const ELFFile<ELFT> &EF = *Obj->getELFFile();
422
Davide Italiano6cf09262016-11-16 05:10:28 +0000423 auto SecOrErr = EF.getSection(Rel.d.a);
424 if (!SecOrErr)
425 return errorToErrorCode(SecOrErr.takeError());
Rafael Espindola6def3042015-07-01 12:56:27 +0000426 const Elf_Shdr *Sec = *SecOrErr;
Davide Italiano6cf09262016-11-16 05:10:28 +0000427 auto SymTabOrErr = EF.getSection(Sec->sh_link);
428 if (!SymTabOrErr)
429 return errorToErrorCode(SymTabOrErr.takeError());
Rafael Espindola6def3042015-07-01 12:56:27 +0000430 const Elf_Shdr *SymTab = *SymTabOrErr;
Rafael Espindola719dc7c2015-06-29 12:38:31 +0000431 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
432 SymTab->sh_type == ELF::SHT_DYNSYM);
Davide Italiano6cf09262016-11-16 05:10:28 +0000433 auto StrTabSec = EF.getSection(SymTab->sh_link);
434 if (!StrTabSec)
435 return errorToErrorCode(StrTabSec.takeError());
436 auto StrTabOrErr = EF.getStringTable(*StrTabSec);
437 if (!StrTabOrErr)
438 return errorToErrorCode(StrTabOrErr.takeError());
Rafael Espindola6a1bfb22015-06-29 14:39:25 +0000439 StringRef StrTab = *StrTabOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000440 int64_t addend = 0;
Paul Semelcb0f0432018-06-07 13:30:55 +0000441 // If there is no Symbol associated with the relocation, we set the undef
442 // boolean value to 'true'. This will prevent us from calling functions that
443 // requires the relocation to be associated with a symbol.
444 bool undef = false;
Rafael Espindola6def3042015-07-01 12:56:27 +0000445 switch (Sec->sh_type) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000446 default:
447 return object_error::parse_failed;
448 case ELF::SHT_REL: {
Rafael Espindola37070a52015-06-03 04:48:06 +0000449 // TODO: Read implicit addend from section data.
450 break;
451 }
452 case ELF::SHT_RELA: {
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000453 const Elf_Rela *ERela = Obj->getRela(Rel);
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000454 addend = ERela->r_addend;
Paul Semelcb0f0432018-06-07 13:30:55 +0000455 undef = ERela->getSymbol(false) == 0;
Rafael Espindola37070a52015-06-03 04:48:06 +0000456 break;
457 }
458 }
Rafael Espindola75d5b542015-06-03 05:14:22 +0000459 StringRef Target;
Paul Semelcb0f0432018-06-07 13:30:55 +0000460 if (!undef) {
461 symbol_iterator SI = RelRef.getSymbol();
462 const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
463 if (symb->getType() == ELF::STT_SECTION) {
464 Expected<section_iterator> SymSI = SI->getSection();
465 if (!SymSI)
466 return errorToErrorCode(SymSI.takeError());
467 const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
468 auto SecName = EF.getSectionName(SymSec);
469 if (!SecName)
470 return errorToErrorCode(SecName.takeError());
471 Target = *SecName;
472 } else {
473 Expected<StringRef> SymName = symb->getName(StrTab);
474 if (!SymName)
475 return errorToErrorCode(SymName.takeError());
476 Target = *SymName;
477 }
478 } else
479 Target = "*ABS*";
Daniel Cedermand72b9fd2018-06-01 05:31:58 +0000480
481 // Default scheme is to print Target, as well as "+ <addend>" for nonzero
482 // addend. Should be acceptable for all normal purposes.
483 std::string fmtbuf;
484 raw_string_ostream fmt(fmtbuf);
485 fmt << Target;
486 if (addend != 0)
487 fmt << (addend < 0 ? "" : "+") << addend;
488 fmt.flush();
489 Result.append(fmtbuf.begin(), fmtbuf.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000490 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000491}
492
493static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000494 const RelocationRef &Rel,
Rafael Espindola37070a52015-06-03 04:48:06 +0000495 SmallVectorImpl<char> &Result) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000496 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
497 return getRelocationValueString(ELF32LE, Rel, Result);
498 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
499 return getRelocationValueString(ELF64LE, Rel, Result);
500 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
501 return getRelocationValueString(ELF32BE, Rel, Result);
502 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
503 return getRelocationValueString(ELF64BE, Rel, Result);
504}
505
506static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
507 const RelocationRef &Rel,
508 SmallVectorImpl<char> &Result) {
509 symbol_iterator SymI = Rel.getSymbol();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000510 Expected<StringRef> SymNameOrErr = SymI->getName();
511 if (!SymNameOrErr)
512 return errorToErrorCode(SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000513 StringRef SymName = *SymNameOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000514 Result.append(SymName.begin(), SymName.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000515 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000516}
517
518static void printRelocationTargetName(const MachOObjectFile *O,
519 const MachO::any_relocation_info &RE,
520 raw_string_ostream &fmt) {
521 bool IsScattered = O->isRelocationScattered(RE);
522
523 // Target of a scattered relocation is an address. In the interest of
524 // generating pretty output, scan through the symbol table looking for a
525 // symbol that aligns with that address. If we find one, print it.
526 // Otherwise, we just print the hex address of the target.
527 if (IsScattered) {
528 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
529
530 for (const SymbolRef &Symbol : O->symbols()) {
531 std::error_code ec;
Kevin Enderby931cb652016-06-24 18:24:42 +0000532 Expected<uint64_t> Addr = Symbol.getAddress();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000533 if (!Addr)
534 report_error(O->getFileName(), Addr.takeError());
Rafael Espindolaed067c42015-07-03 18:19:00 +0000535 if (*Addr != Val)
Rafael Espindola37070a52015-06-03 04:48:06 +0000536 continue;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000537 Expected<StringRef> Name = Symbol.getName();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000538 if (!Name)
539 report_error(O->getFileName(), Name.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000540 fmt << *Name;
Rafael Espindola37070a52015-06-03 04:48:06 +0000541 return;
542 }
543
544 // If we couldn't find a symbol that this relocation refers to, try
545 // to find a section beginning instead.
Colin LeMahieu77804be2015-07-29 15:45:39 +0000546 for (const SectionRef &Section : ToolSectionFilter(*O)) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000547 std::error_code ec;
548
549 StringRef Name;
550 uint64_t Addr = Section.getAddress();
551 if (Addr != Val)
552 continue;
553 if ((ec = Section.getName(Name)))
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000554 report_error(O->getFileName(), ec);
Rafael Espindola37070a52015-06-03 04:48:06 +0000555 fmt << Name;
556 return;
557 }
558
559 fmt << format("0x%x", Val);
560 return;
561 }
562
563 StringRef S;
564 bool isExtern = O->getPlainRelocationExternal(RE);
565 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
566
Martin Storsjo8c0317d2017-07-13 17:03:02 +0000567 if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND) {
Simon Dardis38867052017-08-07 12:29:38 +0000568 fmt << format("0x%0" PRIx64, Val);
Martin Storsjo8c0317d2017-07-13 17:03:02 +0000569 return;
570 } else if (isExtern) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000571 symbol_iterator SI = O->symbol_begin();
572 advance(SI, Val);
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000573 Expected<StringRef> SOrErr = SI->getName();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000574 if (!SOrErr)
575 report_error(O->getFileName(), SOrErr.takeError());
Davide Italianoccd53fe2015-08-05 07:18:31 +0000576 S = *SOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000577 } else {
578 section_iterator SI = O->section_begin();
579 // Adjust for the fact that sections are 1-indexed.
Kevin Enderby3fc91882017-11-03 21:32:44 +0000580 if (Val == 0) {
581 fmt << "0 (?,?)";
582 return;
583 }
584 uint32_t i = Val - 1;
585 while (i != 0 && SI != O->section_end()) {
586 i--;
587 advance(SI, 1);
588 }
589 if (SI == O->section_end())
590 fmt << Val << " (?,?)";
591 else
592 SI->getName(S);
Rafael Espindola37070a52015-06-03 04:48:06 +0000593 }
594
595 fmt << S;
596}
597
Sam Clegg4df5d762017-06-27 20:40:53 +0000598static std::error_code getRelocationValueString(const WasmObjectFile *Obj,
599 const RelocationRef &RelRef,
600 SmallVectorImpl<char> &Result) {
601 const wasm::WasmRelocation& Rel = Obj->getWasmRelocation(RelRef);
Sam Cleggf676cdd2018-04-26 16:41:51 +0000602 symbol_iterator SI = RelRef.getSymbol();
Sam Clegg4df5d762017-06-27 20:40:53 +0000603 std::string fmtbuf;
604 raw_string_ostream fmt(fmtbuf);
Sam Clegg8c4b0ce2018-04-26 17:05:04 +0000605 if (SI == Obj->symbol_end()) {
606 // Not all wasm relocations have symbols associated with them.
607 // In particular R_WEBASSEMBLY_TYPE_INDEX_LEB.
Sam Cleggf676cdd2018-04-26 16:41:51 +0000608 fmt << Rel.Index;
609 } else {
Sam Clegg8c4b0ce2018-04-26 17:05:04 +0000610 Expected<StringRef> SymNameOrErr = SI->getName();
611 if (!SymNameOrErr)
612 return errorToErrorCode(SymNameOrErr.takeError());
Sam Cleggf676cdd2018-04-26 16:41:51 +0000613 StringRef SymName = *SymNameOrErr;
614 Result.append(SymName.begin(), SymName.end());
615 }
616 fmt << (Rel.Addend < 0 ? "" : "+") << Rel.Addend;
Sam Clegg4df5d762017-06-27 20:40:53 +0000617 fmt.flush();
618 Result.append(fmtbuf.begin(), fmtbuf.end());
619 return std::error_code();
620}
621
Rafael Espindola37070a52015-06-03 04:48:06 +0000622static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
623 const RelocationRef &RelRef,
624 SmallVectorImpl<char> &Result) {
625 DataRefImpl Rel = RelRef.getRawDataRefImpl();
626 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
627
628 unsigned Arch = Obj->getArch();
629
630 std::string fmtbuf;
631 raw_string_ostream fmt(fmtbuf);
632 unsigned Type = Obj->getAnyRelocationType(RE);
633 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
634
635 // Determine any addends that should be displayed with the relocation.
636 // These require decoding the relocation type, which is triple-specific.
637
638 // X86_64 has entirely custom relocation types.
639 if (Arch == Triple::x86_64) {
640 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
641
642 switch (Type) {
643 case MachO::X86_64_RELOC_GOT_LOAD:
644 case MachO::X86_64_RELOC_GOT: {
645 printRelocationTargetName(Obj, RE, fmt);
646 fmt << "@GOT";
647 if (isPCRel)
648 fmt << "PCREL";
649 break;
650 }
651 case MachO::X86_64_RELOC_SUBTRACTOR: {
652 DataRefImpl RelNext = Rel;
653 Obj->moveRelocationNext(RelNext);
654 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
655
656 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
657 // X86_64_RELOC_UNSIGNED.
658 // NOTE: Scattered relocations don't exist on x86_64.
659 unsigned RType = Obj->getAnyRelocationType(RENext);
660 if (RType != MachO::X86_64_RELOC_UNSIGNED)
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000661 report_error(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
662 "X86_64_RELOC_SUBTRACTOR.");
Rafael Espindola37070a52015-06-03 04:48:06 +0000663
664 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
665 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
666 printRelocationTargetName(Obj, RENext, fmt);
667 fmt << "-";
668 printRelocationTargetName(Obj, RE, fmt);
669 break;
670 }
671 case MachO::X86_64_RELOC_TLV:
672 printRelocationTargetName(Obj, RE, fmt);
673 fmt << "@TLV";
674 if (isPCRel)
675 fmt << "P";
676 break;
677 case MachO::X86_64_RELOC_SIGNED_1:
678 printRelocationTargetName(Obj, RE, fmt);
679 fmt << "-1";
680 break;
681 case MachO::X86_64_RELOC_SIGNED_2:
682 printRelocationTargetName(Obj, RE, fmt);
683 fmt << "-2";
684 break;
685 case MachO::X86_64_RELOC_SIGNED_4:
686 printRelocationTargetName(Obj, RE, fmt);
687 fmt << "-4";
688 break;
689 default:
690 printRelocationTargetName(Obj, RE, fmt);
691 break;
692 }
693 // X86 and ARM share some relocation types in common.
694 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
695 Arch == Triple::ppc) {
696 // Generic relocation types...
697 switch (Type) {
698 case MachO::GENERIC_RELOC_PAIR: // prints no info
Rui Ueyama7d099192015-06-09 15:20:42 +0000699 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000700 case MachO::GENERIC_RELOC_SECTDIFF: {
701 DataRefImpl RelNext = Rel;
702 Obj->moveRelocationNext(RelNext);
703 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
704
705 // X86 sect diff's must be followed by a relocation of type
706 // GENERIC_RELOC_PAIR.
707 unsigned RType = Obj->getAnyRelocationType(RENext);
708
709 if (RType != MachO::GENERIC_RELOC_PAIR)
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000710 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
711 "GENERIC_RELOC_SECTDIFF.");
Rafael Espindola37070a52015-06-03 04:48:06 +0000712
713 printRelocationTargetName(Obj, RE, fmt);
714 fmt << "-";
715 printRelocationTargetName(Obj, RENext, fmt);
716 break;
717 }
718 }
719
720 if (Arch == Triple::x86 || Arch == Triple::ppc) {
721 switch (Type) {
722 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
723 DataRefImpl RelNext = Rel;
724 Obj->moveRelocationNext(RelNext);
725 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
726
727 // X86 sect diff's must be followed by a relocation of type
728 // GENERIC_RELOC_PAIR.
729 unsigned RType = Obj->getAnyRelocationType(RENext);
730 if (RType != MachO::GENERIC_RELOC_PAIR)
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000731 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
732 "GENERIC_RELOC_LOCAL_SECTDIFF.");
Rafael Espindola37070a52015-06-03 04:48:06 +0000733
734 printRelocationTargetName(Obj, RE, fmt);
735 fmt << "-";
736 printRelocationTargetName(Obj, RENext, fmt);
737 break;
738 }
739 case MachO::GENERIC_RELOC_TLV: {
740 printRelocationTargetName(Obj, RE, fmt);
741 fmt << "@TLV";
742 if (IsPCRel)
743 fmt << "P";
744 break;
745 }
746 default:
747 printRelocationTargetName(Obj, RE, fmt);
748 }
749 } else { // ARM-specific relocations
750 switch (Type) {
751 case MachO::ARM_RELOC_HALF:
752 case MachO::ARM_RELOC_HALF_SECTDIFF: {
753 // Half relocations steal a bit from the length field to encode
754 // whether this is an upper16 or a lower16 relocation.
Martin Storsjofa5183b2017-07-13 05:54:08 +0000755 bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
Rafael Espindola37070a52015-06-03 04:48:06 +0000756
757 if (isUpper)
758 fmt << ":upper16:(";
759 else
760 fmt << ":lower16:(";
761 printRelocationTargetName(Obj, RE, fmt);
762
763 DataRefImpl RelNext = Rel;
764 Obj->moveRelocationNext(RelNext);
765 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
766
767 // ARM half relocs must be followed by a relocation of type
768 // ARM_RELOC_PAIR.
769 unsigned RType = Obj->getAnyRelocationType(RENext);
770 if (RType != MachO::ARM_RELOC_PAIR)
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000771 report_error(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
772 "ARM_RELOC_HALF");
Rafael Espindola37070a52015-06-03 04:48:06 +0000773
774 // NOTE: The half of the target virtual address is stashed in the
775 // address field of the secondary relocation, but we can't reverse
776 // engineer the constant offset from it without decoding the movw/movt
777 // instruction to find the other half in its immediate field.
778
779 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
780 // symbol/section pointer of the follow-on relocation.
781 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
782 fmt << "-";
783 printRelocationTargetName(Obj, RENext, fmt);
784 }
785
786 fmt << ")";
787 break;
788 }
789 default: { printRelocationTargetName(Obj, RE, fmt); }
790 }
791 }
792 } else
793 printRelocationTargetName(Obj, RE, fmt);
794
795 fmt.flush();
796 Result.append(fmtbuf.begin(), fmtbuf.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000797 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000798}
799
800static std::error_code getRelocationValueString(const RelocationRef &Rel,
801 SmallVectorImpl<char> &Result) {
Rafael Espindola854038e2015-06-26 14:51:16 +0000802 const ObjectFile *Obj = Rel.getObject();
Rafael Espindola37070a52015-06-03 04:48:06 +0000803 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
804 return getRelocationValueString(ELF, Rel, Result);
805 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
806 return getRelocationValueString(COFF, Rel, Result);
Sam Clegg4df5d762017-06-27 20:40:53 +0000807 if (auto *Wasm = dyn_cast<WasmObjectFile>(Obj))
808 return getRelocationValueString(Wasm, Rel, Result);
809 if (auto *MachO = dyn_cast<MachOObjectFile>(Obj))
810 return getRelocationValueString(MachO, Rel, Result);
811 llvm_unreachable("unknown object file format");
Rafael Espindola37070a52015-06-03 04:48:06 +0000812}
813
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000814/// Indicates whether this relocation should hidden when listing
Rafael Espindola0ad71d92015-06-30 03:41:26 +0000815/// relocations, usually because it is the trailing part of a multipart
816/// relocation that will be printed as part of the leading relocation.
817static bool getHidden(RelocationRef RelRef) {
818 const ObjectFile *Obj = RelRef.getObject();
819 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
820 if (!MachO)
821 return false;
822
823 unsigned Arch = MachO->getArch();
824 DataRefImpl Rel = RelRef.getRawDataRefImpl();
825 uint64_t Type = MachO->getRelocationType(Rel);
826
827 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
828 // is always hidden.
829 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
830 if (Type == MachO::GENERIC_RELOC_PAIR)
831 return true;
832 } else if (Arch == Triple::x86_64) {
833 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
834 // an X86_64_RELOC_SUBTRACTOR.
835 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
836 DataRefImpl RelPrev = Rel;
837 RelPrev.d.a--;
838 uint64_t PrevType = MachO->getRelocationType(RelPrev);
839 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
840 return true;
841 }
842 }
843
844 return false;
845}
846
Sid Manningd9f28732018-05-14 19:46:08 +0000847namespace {
848class SourcePrinter {
849protected:
850 DILineInfo OldLineInfo;
851 const ObjectFile *Obj = nullptr;
852 std::unique_ptr<symbolize::LLVMSymbolizer> Symbolizer;
853 // File name to file contents of source
854 std::unordered_map<std::string, std::unique_ptr<MemoryBuffer>> SourceCache;
855 // Mark the line endings of the cached source
856 std::unordered_map<std::string, std::vector<StringRef>> LineCache;
857
858private:
859 bool cacheSource(const DILineInfo& LineInfoFile);
860
861public:
862 SourcePrinter() = default;
863 SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch) : Obj(Obj) {
864 symbolize::LLVMSymbolizer::Options SymbolizerOpts(
865 DILineInfoSpecifier::FunctionNameKind::None, true, false, false,
866 DefaultArch);
867 Symbolizer.reset(new symbolize::LLVMSymbolizer(SymbolizerOpts));
868 }
869 virtual ~SourcePrinter() = default;
870 virtual void printSourceLine(raw_ostream &OS, uint64_t Address,
871 StringRef Delimiter = "; ");
872};
873
874bool SourcePrinter::cacheSource(const DILineInfo &LineInfo) {
875 std::unique_ptr<MemoryBuffer> Buffer;
876 if (LineInfo.Source) {
877 Buffer = MemoryBuffer::getMemBuffer(*LineInfo.Source);
878 } else {
879 auto BufferOrError = MemoryBuffer::getFile(LineInfo.FileName);
880 if (!BufferOrError)
881 return false;
882 Buffer = std::move(*BufferOrError);
883 }
884 // Chomp the file to get lines
885 size_t BufferSize = Buffer->getBufferSize();
886 const char *BufferStart = Buffer->getBufferStart();
887 for (const char *Start = BufferStart, *End = BufferStart;
888 End < BufferStart + BufferSize; End++)
889 if (*End == '\n' || End == BufferStart + BufferSize - 1 ||
890 (*End == '\r' && *(End + 1) == '\n')) {
891 LineCache[LineInfo.FileName].push_back(StringRef(Start, End - Start));
892 if (*End == '\r')
893 End++;
894 Start = End + 1;
895 }
896 SourceCache[LineInfo.FileName] = std::move(Buffer);
897 return true;
898}
899
900void SourcePrinter::printSourceLine(raw_ostream &OS, uint64_t Address,
901 StringRef Delimiter) {
902 if (!Symbolizer)
903 return;
904 DILineInfo LineInfo = DILineInfo();
905 auto ExpectecLineInfo =
906 Symbolizer->symbolizeCode(Obj->getFileName(), Address);
907 if (!ExpectecLineInfo)
908 consumeError(ExpectecLineInfo.takeError());
909 else
910 LineInfo = *ExpectecLineInfo;
911
912 if ((LineInfo.FileName == "<invalid>") || OldLineInfo.Line == LineInfo.Line ||
913 LineInfo.Line == 0)
914 return;
915
916 if (PrintLines)
917 OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line << "\n";
918 if (PrintSource) {
919 if (SourceCache.find(LineInfo.FileName) == SourceCache.end())
920 if (!cacheSource(LineInfo))
921 return;
922 auto FileBuffer = SourceCache.find(LineInfo.FileName);
923 if (FileBuffer != SourceCache.end()) {
924 auto LineBuffer = LineCache.find(LineInfo.FileName);
925 if (LineBuffer != LineCache.end()) {
926 if (LineInfo.Line > LineBuffer->second.size())
927 return;
928 // Vector begins at 0, line numbers are non-zero
929 OS << Delimiter << LineBuffer->second[LineInfo.Line - 1].ltrim()
930 << "\n";
931 }
932 }
933 }
934 OldLineInfo = LineInfo;
935}
936
937static bool isArmElf(const ObjectFile *Obj) {
938 return (Obj->isELF() &&
939 (Obj->getArch() == Triple::aarch64 ||
940 Obj->getArch() == Triple::aarch64_be ||
941 Obj->getArch() == Triple::arm || Obj->getArch() == Triple::armeb ||
942 Obj->getArch() == Triple::thumb ||
943 Obj->getArch() == Triple::thumbeb));
944}
945
946class PrettyPrinter {
947public:
948 virtual ~PrettyPrinter() = default;
949 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
950 ArrayRef<uint8_t> Bytes, uint64_t Address,
951 raw_ostream &OS, StringRef Annot,
952 MCSubtargetInfo const &STI, SourcePrinter *SP,
953 std::vector<RelocationRef> *Rels = nullptr) {
954 if (SP && (PrintSource || PrintLines))
955 SP->printSourceLine(OS, Address);
956 if (!NoLeadingAddr)
957 OS << format("%8" PRIx64 ":", Address);
958 if (!NoShowRawInsn) {
959 OS << "\t";
960 dumpBytes(Bytes, OS);
961 }
962 if (MI)
963 IP.printInst(MI, OS, "", STI);
964 else
965 OS << " <unknown>";
966 }
967};
968PrettyPrinter PrettyPrinterInst;
969class HexagonPrettyPrinter : public PrettyPrinter {
970public:
971 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
972 raw_ostream &OS) {
973 uint32_t opcode =
974 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
975 if (!NoLeadingAddr)
976 OS << format("%8" PRIx64 ":", Address);
977 if (!NoShowRawInsn) {
978 OS << "\t";
979 dumpBytes(Bytes.slice(0, 4), OS);
980 OS << format("%08" PRIx32, opcode);
981 }
982 }
983 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
984 uint64_t Address, raw_ostream &OS, StringRef Annot,
985 MCSubtargetInfo const &STI, SourcePrinter *SP,
986 std::vector<RelocationRef> *Rels) override {
987 if (SP && (PrintSource || PrintLines))
988 SP->printSourceLine(OS, Address, "");
989 if (!MI) {
990 printLead(Bytes, Address, OS);
991 OS << " <unknown>";
992 return;
993 }
994 std::string Buffer;
995 {
996 raw_string_ostream TempStream(Buffer);
997 IP.printInst(MI, TempStream, "", STI);
998 }
999 StringRef Contents(Buffer);
1000 // Split off bundle attributes
1001 auto PacketBundle = Contents.rsplit('\n');
1002 // Split off first instruction from the rest
1003 auto HeadTail = PacketBundle.first.split('\n');
1004 auto Preamble = " { ";
1005 auto Separator = "";
1006 StringRef Fmt = "\t\t\t%08" PRIx64 ": ";
1007 std::vector<RelocationRef>::const_iterator rel_cur = Rels->begin();
1008 std::vector<RelocationRef>::const_iterator rel_end = Rels->end();
1009
1010 // Hexagon's packets require relocations to be inline rather than
1011 // clustered at the end of the packet.
1012 auto PrintReloc = [&]() -> void {
1013 while ((rel_cur != rel_end) && (rel_cur->getOffset() <= Address)) {
1014 if (rel_cur->getOffset() == Address) {
1015 SmallString<16> name;
1016 SmallString<32> val;
1017 rel_cur->getTypeName(name);
1018 error(getRelocationValueString(*rel_cur, val));
1019 OS << Separator << format(Fmt.data(), Address) << name << "\t" << val
1020 << "\n";
1021 return;
1022 }
1023 rel_cur++;
1024 }
1025 };
1026
1027 while(!HeadTail.first.empty()) {
1028 OS << Separator;
1029 Separator = "\n";
1030 if (SP && (PrintSource || PrintLines))
1031 SP->printSourceLine(OS, Address, "");
1032 printLead(Bytes, Address, OS);
1033 OS << Preamble;
1034 Preamble = " ";
1035 StringRef Inst;
1036 auto Duplex = HeadTail.first.split('\v');
1037 if(!Duplex.second.empty()){
1038 OS << Duplex.first;
1039 OS << "; ";
1040 Inst = Duplex.second;
1041 }
1042 else
1043 Inst = HeadTail.first;
1044 OS << Inst;
1045 HeadTail = HeadTail.second.split('\n');
1046 if (HeadTail.first.empty())
1047 OS << " } " << PacketBundle.second;
1048 PrintReloc();
1049 Bytes = Bytes.slice(4);
1050 Address += 4;
1051 }
1052 }
1053};
1054HexagonPrettyPrinter HexagonPrettyPrinterInst;
1055
1056class AMDGCNPrettyPrinter : public PrettyPrinter {
1057public:
1058 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1059 uint64_t Address, raw_ostream &OS, StringRef Annot,
1060 MCSubtargetInfo const &STI, SourcePrinter *SP,
1061 std::vector<RelocationRef> *Rels) override {
1062 if (SP && (PrintSource || PrintLines))
1063 SP->printSourceLine(OS, Address);
1064
1065 typedef support::ulittle32_t U32;
1066
1067 if (MI) {
1068 SmallString<40> InstStr;
1069 raw_svector_ostream IS(InstStr);
1070
1071 IP.printInst(MI, IS, "", STI);
1072
1073 OS << left_justify(IS.str(), 60);
1074 } else {
1075 // an unrecognized encoding - this is probably data so represent it
1076 // using the .long directive, or .byte directive if fewer than 4 bytes
1077 // remaining
1078 if (Bytes.size() >= 4) {
1079 OS << format("\t.long 0x%08" PRIx32 " ",
1080 static_cast<uint32_t>(*reinterpret_cast<const U32*>(Bytes.data())));
1081 OS.indent(42);
1082 } else {
1083 OS << format("\t.byte 0x%02" PRIx8, Bytes[0]);
1084 for (unsigned int i = 1; i < Bytes.size(); i++)
1085 OS << format(", 0x%02" PRIx8, Bytes[i]);
1086 OS.indent(55 - (6 * Bytes.size()));
1087 }
1088 }
1089
1090 OS << format("// %012" PRIX64 ": ", Address);
1091 if (Bytes.size() >=4) {
1092 for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
1093 Bytes.size() / sizeof(U32)))
1094 // D should be explicitly casted to uint32_t here as it is passed
1095 // by format to snprintf as vararg.
1096 OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D));
1097 } else {
1098 for (unsigned int i = 0; i < Bytes.size(); i++)
1099 OS << format("%02" PRIX8 " ", Bytes[i]);
1100 }
1101
1102 if (!Annot.empty())
1103 OS << "// " << Annot;
1104 }
1105};
1106AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
1107
1108class BPFPrettyPrinter : public PrettyPrinter {
1109public:
1110 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1111 uint64_t Address, raw_ostream &OS, StringRef Annot,
1112 MCSubtargetInfo const &STI, SourcePrinter *SP,
1113 std::vector<RelocationRef> *Rels) override {
1114 if (SP && (PrintSource || PrintLines))
1115 SP->printSourceLine(OS, Address);
1116 if (!NoLeadingAddr)
1117 OS << format("%8" PRId64 ":", Address / 8);
1118 if (!NoShowRawInsn) {
1119 OS << "\t";
1120 dumpBytes(Bytes, OS);
1121 }
1122 if (MI)
1123 IP.printInst(MI, OS, "", STI);
1124 else
1125 OS << " <unknown>";
1126 }
1127};
1128BPFPrettyPrinter BPFPrettyPrinterInst;
1129
1130PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
1131 switch(Triple.getArch()) {
1132 default:
1133 return PrettyPrinterInst;
1134 case Triple::hexagon:
1135 return HexagonPrettyPrinterInst;
1136 case Triple::amdgcn:
1137 return AMDGCNPrettyPrinterInst;
1138 case Triple::bpfel:
1139 case Triple::bpfeb:
1140 return BPFPrettyPrinterInst;
1141 }
1142}
1143}
1144
Sam Koltonc05d7782016-08-17 10:17:57 +00001145static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) {
1146 assert(Obj->isELF());
1147 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1148 return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1149 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1150 return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1151 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1152 return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1153 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1154 return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1155 llvm_unreachable("Unsupported binary format");
1156}
1157
Sam Parker5fba45a2017-02-08 09:44:18 +00001158template <class ELFT> static void
1159addDynamicElfSymbols(const ELFObjectFile<ELFT> *Obj,
1160 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1161 for (auto Symbol : Obj->getDynamicSymbolIterators()) {
1162 uint8_t SymbolType = Symbol.getELFType();
1163 if (SymbolType != ELF::STT_FUNC || Symbol.getSize() == 0)
1164 continue;
1165
1166 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
1167 if (!AddressOrErr)
1168 report_error(Obj->getFileName(), AddressOrErr.takeError());
1169 uint64_t Address = *AddressOrErr;
1170
1171 Expected<StringRef> Name = Symbol.getName();
1172 if (!Name)
1173 report_error(Obj->getFileName(), Name.takeError());
1174 if (Name->empty())
1175 continue;
1176
1177 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1178 if (!SectionOrErr)
1179 report_error(Obj->getFileName(), SectionOrErr.takeError());
1180 section_iterator SecI = *SectionOrErr;
1181 if (SecI == Obj->section_end())
1182 continue;
1183
1184 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1185 }
1186}
1187
1188static void
1189addDynamicElfSymbols(const ObjectFile *Obj,
1190 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1191 assert(Obj->isELF());
1192 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1193 addDynamicElfSymbols(Elf32LEObj, AllSymbols);
1194 else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1195 addDynamicElfSymbols(Elf64LEObj, AllSymbols);
1196 else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1197 addDynamicElfSymbols(Elf32BEObj, AllSymbols);
1198 else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1199 addDynamicElfSymbols(Elf64BEObj, AllSymbols);
1200 else
1201 llvm_unreachable("Unsupported binary format");
1202}
1203
Michael J. Spencer51862b32011-10-13 22:17:18 +00001204static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001205 if (StartAddress > StopAddress)
1206 error("Start address should be less than stop address");
1207
Jim Grosbachaf9aec02012-08-07 17:53:14 +00001208 const Target *TheTarget = getTarget(Obj);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001209
Jack Carter551efd72012-08-28 19:24:49 +00001210 // Package up features to be passed to target/subtarget
Daniel Sanders1d148642016-06-16 09:17:03 +00001211 SubtargetFeatures Features = Obj->getFeatures();
Jack Carter551efd72012-08-28 19:24:49 +00001212 if (MAttrs.size()) {
Jack Carter551efd72012-08-28 19:24:49 +00001213 for (unsigned i = 0; i != MAttrs.size(); ++i)
1214 Features.AddFeature(MAttrs[i]);
Jack Carter551efd72012-08-28 19:24:49 +00001215 }
1216
Ahmed Charles56440fd2014-03-06 05:51:42 +00001217 std::unique_ptr<const MCRegisterInfo> MRI(
1218 TheTarget->createMCRegInfo(TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +00001219 if (!MRI)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001220 report_error(Obj->getFileName(), "no register info for target " +
1221 TripleName);
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001222
1223 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00001224 std::unique_ptr<const MCAsmInfo> AsmInfo(
1225 TheTarget->createMCAsmInfo(*MRI, TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +00001226 if (!AsmInfo)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001227 report_error(Obj->getFileName(), "no assembly info for target " +
1228 TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +00001229 std::unique_ptr<const MCSubtargetInfo> STI(
Daniel Sanders1d148642016-06-16 09:17:03 +00001230 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
Davide Italiano711e4952015-12-17 01:59:50 +00001231 if (!STI)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001232 report_error(Obj->getFileName(), "no subtarget info for target " +
1233 TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +00001234 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
Davide Italiano711e4952015-12-17 01:59:50 +00001235 if (!MII)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001236 report_error(Obj->getFileName(), "no instruction info for target " +
1237 TripleName);
Sam Kolton3381d7a2016-10-06 13:46:08 +00001238 MCObjectFileInfo MOFI;
1239 MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI);
1240 // FIXME: for now initialize MCObjectFileInfo with default values
Rafael Espindola9f929952017-08-02 20:32:26 +00001241 MOFI.InitMCObjectFileInfo(Triple(TripleName), false, Ctx);
Lang Hamesa1bc0f52014-04-15 04:40:56 +00001242
1243 std::unique_ptr<MCDisassembler> DisAsm(
1244 TheTarget->createMCDisassembler(*STI, Ctx));
Davide Italiano711e4952015-12-17 01:59:50 +00001245 if (!DisAsm)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001246 report_error(Obj->getFileName(), "no disassembler for target " +
1247 TripleName);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001248
Ahmed Charles56440fd2014-03-06 05:51:42 +00001249 std::unique_ptr<const MCInstrAnalysis> MIA(
1250 TheTarget->createMCInstrAnalysis(MII.get()));
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001251
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001252 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Daniel Sanders50f17232015-09-15 16:17:27 +00001253 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1254 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
Davide Italiano711e4952015-12-17 01:59:50 +00001255 if (!IP)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001256 report_error(Obj->getFileName(), "no instruction printer for target " +
1257 TripleName);
Colin LeMahieu14ec76e2015-06-07 21:07:17 +00001258 IP->setPrintImmHex(PrintImmHex);
Colin LeMahieu35436a22015-05-29 14:48:25 +00001259 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001260
Greg Fitzgerald18432272014-03-20 22:55:15 +00001261 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
1262 "\t\t\t%08" PRIx64 ": ";
1263
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001264 SourcePrinter SP(Obj, TheTarget->getName());
1265
Mark Seaborn0929d3d2014-01-25 17:38:19 +00001266 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
1267 // in RelocSecs contain the relocations for section S.
Rafael Espindola4453e42942014-06-13 03:07:50 +00001268 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +00001269 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001270 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001271 section_iterator Sec2 = Section.getRelocatedSection();
Rafael Espindolab5155a52014-02-10 20:24:04 +00001272 if (Sec2 != Obj->section_end())
Alexey Samsonov48803e52014-03-13 14:37:36 +00001273 SectionRelocMap[*Sec2].push_back(Section);
Mark Seaborn0929d3d2014-01-25 17:38:19 +00001274 }
1275
David Majnemer81afca62015-07-07 22:06:59 +00001276 // Create a mapping from virtual address to symbol name. This is used to
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001277 // pretty print the symbols while disassembling.
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001278 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
1279 for (const SymbolRef &Symbol : Obj->symbols()) {
Kevin Enderby931cb652016-06-24 18:24:42 +00001280 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001281 if (!AddressOrErr)
1282 report_error(Obj->getFileName(), AddressOrErr.takeError());
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001283 uint64_t Address = *AddressOrErr;
David Majnemer2603a8fa2015-07-09 18:11:40 +00001284
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001285 Expected<StringRef> Name = Symbol.getName();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001286 if (!Name)
1287 report_error(Obj->getFileName(), Name.takeError());
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001288 if (Name->empty())
1289 continue;
David Majnemer81afca62015-07-07 22:06:59 +00001290
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001291 Expected<section_iterator> SectionOrErr = Symbol.getSection();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001292 if (!SectionOrErr)
1293 report_error(Obj->getFileName(), SectionOrErr.takeError());
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001294 section_iterator SecI = *SectionOrErr;
1295 if (SecI == Obj->section_end())
1296 continue;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001297
Sam Koltonc05d7782016-08-17 10:17:57 +00001298 uint8_t SymbolType = ELF::STT_NOTYPE;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001299 if (Obj->isELF())
Sam Koltonc05d7782016-08-17 10:17:57 +00001300 SymbolType = getElfSymbolType(Obj, Symbol);
David Majnemer81afca62015-07-07 22:06:59 +00001301
Sam Koltonc05d7782016-08-17 10:17:57 +00001302 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1303
David Majnemer81afca62015-07-07 22:06:59 +00001304 }
Sam Parker5fba45a2017-02-08 09:44:18 +00001305 if (AllSymbols.empty() && Obj->isELF())
1306 addDynamicElfSymbols(Obj, AllSymbols);
David Majnemer81afca62015-07-07 22:06:59 +00001307
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001308 // Create a mapping from virtual address to section.
1309 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1310 for (SectionRef Sec : Obj->sections())
1311 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1312 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
1313
1314 // Linked executables (.exe and .dll files) typically don't include a real
1315 // symbol table but they might contain an export table.
1316 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
1317 for (const auto &ExportEntry : COFFObj->export_directories()) {
1318 StringRef Name;
1319 error(ExportEntry.getSymbolName(Name));
1320 if (Name.empty())
1321 continue;
1322 uint32_t RVA;
1323 error(ExportEntry.getExportRVA(RVA));
1324
1325 uint64_t VA = COFFObj->getImageBase() + RVA;
1326 auto Sec = std::upper_bound(
1327 SectionAddresses.begin(), SectionAddresses.end(), VA,
1328 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
1329 return LHS < RHS.first;
1330 });
1331 if (Sec != SectionAddresses.begin())
1332 --Sec;
1333 else
1334 Sec = SectionAddresses.end();
1335
1336 if (Sec != SectionAddresses.end())
Sam Koltonc05d7782016-08-17 10:17:57 +00001337 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001338 }
1339 }
1340
1341 // Sort all the symbols, this allows us to use a simple binary search to find
1342 // a symbol near an address.
1343 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1344 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
1345
Colin LeMahieu77804be2015-07-29 15:45:39 +00001346 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Colin LeMahieuf34933e2015-07-23 20:58:49 +00001347 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
Mark Seaborneb03ac52014-01-25 00:32:01 +00001348 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +00001349
Rafael Espindola80291272014-10-08 15:28:58 +00001350 uint64_t SectionAddr = Section.getAddress();
1351 uint64_t SectSize = Section.getSize();
David Majnemer185b5b12014-11-11 09:58:25 +00001352 if (!SectSize)
1353 continue;
Simon Atanasyan2b614e12014-02-24 22:12:11 +00001354
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001355 // Get the list of all the symbols in this section.
1356 SectionSymbolsTy &Symbols = AllSymbols[Section];
Davide Italianof0706882015-10-01 21:57:09 +00001357 std::vector<uint64_t> DataMappingSymsAddr;
1358 std::vector<uint64_t> TextMappingSymsAddr;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001359 if (isArmElf(Obj)) {
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001360 for (const auto &Symb : Symbols) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001361 uint64_t Address = std::get<0>(Symb);
1362 StringRef Name = std::get<1>(Symb);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001363 if (Name.startswith("$d"))
David Majnemer153722d2015-11-18 04:35:32 +00001364 DataMappingSymsAddr.push_back(Address - SectionAddr);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001365 if (Name.startswith("$x"))
David Majnemer153722d2015-11-18 04:35:32 +00001366 TextMappingSymsAddr.push_back(Address - SectionAddr);
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001367 if (Name.startswith("$a"))
1368 TextMappingSymsAddr.push_back(Address - SectionAddr);
1369 if (Name.startswith("$t"))
1370 TextMappingSymsAddr.push_back(Address - SectionAddr);
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001371 }
1372 }
1373
Mandeep Singh Grang8db564e2018-04-01 21:24:53 +00001374 llvm::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end());
1375 llvm::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end());
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001376
Sam Kolton3381d7a2016-10-06 13:46:08 +00001377 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1378 // AMDGPU disassembler uses symbolizer for printing labels
1379 std::unique_ptr<MCRelocationInfo> RelInfo(
1380 TheTarget->createMCRelocationInfo(TripleName, Ctx));
1381 if (RelInfo) {
1382 std::unique_ptr<MCSymbolizer> Symbolizer(
1383 TheTarget->createMCSymbolizer(
1384 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1385 DisAsm->setSymbolizer(std::move(Symbolizer));
1386 }
1387 }
1388
Michael J. Spencer51862b32011-10-13 22:17:18 +00001389 // Make a list of all the relocations for this section.
1390 std::vector<RelocationRef> Rels;
1391 if (InlineRelocs) {
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001392 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
1393 for (const RelocationRef &Reloc : RelocSec.relocations()) {
1394 Rels.push_back(Reloc);
1395 }
Michael J. Spencer51862b32011-10-13 22:17:18 +00001396 }
1397 }
1398
1399 // Sort relocations by address.
Mandeep Singh Grang8db564e2018-04-01 21:24:53 +00001400 llvm::sort(Rels.begin(), Rels.end(), RelocAddressLess);
Michael J. Spencer51862b32011-10-13 22:17:18 +00001401
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001402 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +00001403 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001404 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +00001405 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001406 }
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001407 StringRef SectionName;
1408 error(Section.getName(SectionName));
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001409
Rafael Espindola7884c952015-06-04 15:01:05 +00001410 // If the section has no symbol at the start, just insert a dummy one.
Sam Koltonc05d7782016-08-17 10:17:57 +00001411 if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) {
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001412 Symbols.insert(
1413 Symbols.begin(),
1414 std::make_tuple(SectionAddr, SectionName,
1415 Section.isText() ? ELF::STT_FUNC : ELF::STT_OBJECT));
Sam Koltonc05d7782016-08-17 10:17:57 +00001416 }
Alp Tokere69170a2014-06-26 22:52:05 +00001417
1418 SmallString<40> Comments;
1419 raw_svector_ostream CommentStream(Comments);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001420
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001421 StringRef BytesStr;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001422 error(Section.getContents(BytesStr));
Aaron Ballman106fd7b2014-11-12 14:01:17 +00001423 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1424 BytesStr.size());
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001425
Michael J. Spencer2670c252011-01-20 06:39:06 +00001426 uint64_t Size;
1427 uint64_t Index;
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001428 bool PrintedSection = false;
Michael J. Spencer2670c252011-01-20 06:39:06 +00001429
Michael J. Spencer51862b32011-10-13 22:17:18 +00001430 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
1431 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001432 // Disassemble symbol by symbol.
1433 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001434 uint64_t Start = std::get<0>(Symbols[si]) - SectionAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001435 // The end is either the section end or the beginning of the next
1436 // symbol.
1437 uint64_t End =
Sam Koltonc05d7782016-08-17 10:17:57 +00001438 (si == se - 1) ? SectSize : std::get<0>(Symbols[si + 1]) - SectionAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001439 // Don't try to disassemble beyond the end of section contents.
1440 if (End > SectSize)
1441 End = SectSize;
Rafael Espindolae45c7402014-08-17 16:31:39 +00001442 // If this symbol has the same address as the next symbol, then skip it.
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001443 if (Start >= End)
Michael J. Spenceree84f642011-10-13 20:37:08 +00001444 continue;
1445
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001446 // Check if we need to skip symbol
1447 // Skip if the symbol's data is not between StartAddress and StopAddress
1448 if (End + SectionAddr < StartAddress ||
1449 Start + SectionAddr > StopAddress) {
1450 continue;
1451 }
1452
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001453 /// Skip if user requested specific symbols and this is not in the list
1454 if (!DisasmFuncsSet.empty() &&
1455 !DisasmFuncsSet.count(std::get<1>(Symbols[si])))
1456 continue;
1457
1458 if (!PrintedSection) {
1459 PrintedSection = true;
1460 outs() << "Disassembly of section ";
1461 if (!SegmentName.empty())
1462 outs() << SegmentName << ",";
1463 outs() << SectionName << ':';
1464 }
1465
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001466 // Stop disassembly at the stop address specified
1467 if (End + SectionAddr > StopAddress)
1468 End = StopAddress - SectionAddr;
1469
Valery Pykhtinde048052016-04-07 07:24:01 +00001470 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001471 if (std::get<2>(Symbols[si]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1472 // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)
1473 Start += 256;
1474 }
1475 if (si == se - 1 ||
1476 std::get<2>(Symbols[si + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1477 // cut trailing zeroes at the end of kernel
1478 // cut up to 256 bytes
1479 const uint64_t EndAlign = 256;
1480 const auto Limit = End - (std::min)(EndAlign, End - Start);
1481 while (End > Limit &&
1482 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1483 End -= 4;
1484 }
Valery Pykhtinde048052016-04-07 07:24:01 +00001485 }
1486
Sam Koltonc05d7782016-08-17 10:17:57 +00001487 outs() << '\n' << std::get<1>(Symbols[si]) << ":\n";
Michael J. Spencer2670c252011-01-20 06:39:06 +00001488
Francis Visoiu Mistrih18346822018-04-19 17:02:57 +00001489 // Don't print raw contents of a virtual section. A virtual section
1490 // doesn't have any contents in the file.
1491 if (Section.isVirtual()) {
1492 outs() << "...\n";
1493 continue;
1494 }
1495
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001496#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +00001497 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001498#else
Mark Seaborneb03ac52014-01-25 00:32:01 +00001499 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001500#endif
1501
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001502 for (Index = Start; Index < End; Index += Size) {
1503 MCInst Inst;
Owen Andersona0c3b972011-09-15 23:38:46 +00001504
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001505 if (Index + SectionAddr < StartAddress ||
1506 Index + SectionAddr > StopAddress) {
1507 // skip byte by byte till StartAddress is reached
1508 Size = 1;
1509 continue;
1510 }
Davide Italianof0706882015-10-01 21:57:09 +00001511 // AArch64 ELF binaries can interleave data and text in the
1512 // same section. We rely on the markers introduced to
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001513 // understand what we need to dump. If the data marker is within a
1514 // function, it is denoted as a word/short etc
1515 if (isArmElf(Obj) && std::get<2>(Symbols[si]) != ELF::STT_OBJECT &&
1516 !DisassembleAll) {
Davide Italianof0706882015-10-01 21:57:09 +00001517 uint64_t Stride = 0;
1518
1519 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1520 DataMappingSymsAddr.end(), Index);
1521 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1522 // Switch to data.
1523 while (Index < End) {
1524 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1525 outs() << "\t";
1526 if (Index + 4 <= End) {
1527 Stride = 4;
1528 dumpBytes(Bytes.slice(Index, 4), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001529 outs() << "\t.word\t";
1530 uint32_t Data = 0;
1531 if (Obj->isLittleEndian()) {
1532 const auto Word =
1533 reinterpret_cast<const support::ulittle32_t *>(
1534 Bytes.data() + Index);
1535 Data = *Word;
1536 } else {
1537 const auto Word = reinterpret_cast<const support::ubig32_t *>(
1538 Bytes.data() + Index);
1539 Data = *Word;
1540 }
1541 outs() << "0x" << format("%08" PRIx32, Data);
Davide Italianof0706882015-10-01 21:57:09 +00001542 } else if (Index + 2 <= End) {
1543 Stride = 2;
1544 dumpBytes(Bytes.slice(Index, 2), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001545 outs() << "\t\t.short\t";
1546 uint16_t Data = 0;
1547 if (Obj->isLittleEndian()) {
1548 const auto Short =
1549 reinterpret_cast<const support::ulittle16_t *>(
1550 Bytes.data() + Index);
1551 Data = *Short;
1552 } else {
1553 const auto Short =
1554 reinterpret_cast<const support::ubig16_t *>(Bytes.data() +
1555 Index);
1556 Data = *Short;
1557 }
1558 outs() << "0x" << format("%04" PRIx16, Data);
Davide Italianof0706882015-10-01 21:57:09 +00001559 } else {
1560 Stride = 1;
1561 dumpBytes(Bytes.slice(Index, 1), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001562 outs() << "\t\t.byte\t";
1563 outs() << "0x" << format("%02" PRIx8, Bytes.slice(Index, 1)[0]);
Davide Italianof0706882015-10-01 21:57:09 +00001564 }
1565 Index += Stride;
1566 outs() << "\n";
1567 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1568 TextMappingSymsAddr.end(), Index);
1569 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1570 break;
1571 }
1572 }
1573 }
1574
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001575 // If there is a data symbol inside an ELF text section and we are only
1576 // disassembling text (applicable all architectures),
1577 // we are in a situation where we must print the data and not
1578 // disassemble it.
1579 if (Obj->isELF() && std::get<2>(Symbols[si]) == ELF::STT_OBJECT &&
1580 !DisassembleAll && Section.isText()) {
1581 // print out data up to 8 bytes at a time in hex and ascii
1582 uint8_t AsciiData[9] = {'\0'};
1583 uint8_t Byte;
1584 int NumBytes = 0;
1585
1586 for (Index = Start; Index < End; Index += 1) {
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001587 if (((SectionAddr + Index) < StartAddress) ||
1588 ((SectionAddr + Index) > StopAddress))
1589 continue;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001590 if (NumBytes == 0) {
1591 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1592 outs() << "\t";
1593 }
1594 Byte = Bytes.slice(Index)[0];
1595 outs() << format(" %02x", Byte);
1596 AsciiData[NumBytes] = isprint(Byte) ? Byte : '.';
1597
1598 uint8_t IndentOffset = 0;
1599 NumBytes++;
1600 if (Index == End - 1 || NumBytes > 8) {
1601 // Indent the space for less than 8 bytes data.
1602 // 2 spaces for byte and one for space between bytes
1603 IndentOffset = 3 * (8 - NumBytes);
1604 for (int Excess = 8 - NumBytes; Excess < 8; Excess++)
1605 AsciiData[Excess] = '\0';
1606 NumBytes = 8;
1607 }
1608 if (NumBytes == 8) {
1609 AsciiData[8] = '\0';
1610 outs() << std::string(IndentOffset, ' ') << " ";
1611 outs() << reinterpret_cast<char *>(AsciiData);
1612 outs() << '\n';
1613 NumBytes = 0;
1614 }
1615 }
1616 }
Davide Italianof0706882015-10-01 21:57:09 +00001617 if (Index >= End)
1618 break;
1619
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001620 // Disassemble a real instruction or a data when disassemble all is
1621 // provided
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001622 bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1623 SectionAddr + Index, DebugOut,
1624 CommentStream);
1625 if (Size == 0)
1626 Size = 1;
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001627
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001628 PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001629 Bytes.slice(Index, Size), SectionAddr + Index, outs(), "",
Sid Manningd9f28732018-05-14 19:46:08 +00001630 *STI, &SP, &Rels);
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001631 outs() << CommentStream.str();
1632 Comments.clear();
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001633
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001634 // Try to resolve the target of a call, tail call, etc. to a specific
1635 // symbol.
1636 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1637 MIA->isConditionalBranch(Inst))) {
1638 uint64_t Target;
1639 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1640 // In a relocatable object, the target's section must reside in
1641 // the same section as the call instruction or it is accessed
1642 // through a relocation.
1643 //
1644 // In a non-relocatable object, the target may be in any section.
1645 //
1646 // N.B. We don't walk the relocations in the relocatable case yet.
1647 auto *TargetSectionSymbols = &Symbols;
1648 if (!Obj->isRelocatableObject()) {
1649 auto SectionAddress = std::upper_bound(
1650 SectionAddresses.begin(), SectionAddresses.end(), Target,
1651 [](uint64_t LHS,
1652 const std::pair<uint64_t, SectionRef> &RHS) {
1653 return LHS < RHS.first;
1654 });
1655 if (SectionAddress != SectionAddresses.begin()) {
1656 --SectionAddress;
1657 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1658 } else {
1659 TargetSectionSymbols = nullptr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001660 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001661 }
David Majnemer2603a8fa2015-07-09 18:11:40 +00001662
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001663 // Find the first symbol in the section whose offset is less than
1664 // or equal to the target.
1665 if (TargetSectionSymbols) {
1666 auto TargetSym = std::upper_bound(
1667 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1668 Target, [](uint64_t LHS,
Sam Koltonc05d7782016-08-17 10:17:57 +00001669 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1670 return LHS < std::get<0>(RHS);
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001671 });
1672 if (TargetSym != TargetSectionSymbols->begin()) {
1673 --TargetSym;
1674 uint64_t TargetAddress = std::get<0>(*TargetSym);
1675 StringRef TargetName = std::get<1>(*TargetSym);
1676 outs() << " <" << TargetName;
1677 uint64_t Disp = Target - TargetAddress;
1678 if (Disp)
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00001679 outs() << "+0x" << Twine::utohexstr(Disp);
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001680 outs() << '>';
David Majnemer81afca62015-07-07 22:06:59 +00001681 }
1682 }
1683 }
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001684 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001685 outs() << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001686
Sid Manningd9f28732018-05-14 19:46:08 +00001687 // Hexagon does this in pretty printer
1688 if (Obj->getArch() != Triple::hexagon)
1689 // Print relocation for instruction.
1690 while (rel_cur != rel_end) {
1691 bool hidden = getHidden(*rel_cur);
1692 uint64_t addr = rel_cur->getOffset();
1693 SmallString<16> name;
1694 SmallString<32> val;
Owen Andersonfa3e5202011-10-25 20:35:53 +00001695
Sid Manningd9f28732018-05-14 19:46:08 +00001696 // If this relocation is hidden, skip it.
1697 if (hidden || ((SectionAddr + addr) < StartAddress)) {
1698 ++rel_cur;
1699 continue;
1700 }
1701
1702 // Stop when rel_cur's address is past the current instruction.
1703 if (addr >= Index + Size) break;
1704 rel_cur->getTypeName(name);
1705 error(getRelocationValueString(*rel_cur, val));
1706 outs() << format(Fmt.data(), SectionAddr + addr) << name
1707 << "\t" << val << "\n";
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001708 ++rel_cur;
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001709 }
Benjamin Kramer87ee76c2011-07-20 19:37:35 +00001710 }
Michael J. Spencer2670c252011-01-20 06:39:06 +00001711 }
1712 }
1713}
1714
Kevin Enderby98da6132015-01-20 21:47:46 +00001715void llvm::PrintRelocations(const ObjectFile *Obj) {
Greg Fitzgerald18432272014-03-20 22:55:15 +00001716 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1717 "%08" PRIx64;
Rafael Espindola9219fe72016-03-21 20:59:15 +00001718 // Regular objdump doesn't print relocations in non-relocatable object
1719 // files.
1720 if (!Obj->isRelocatableObject())
1721 return;
Rafael Espindolac66d7612014-08-17 19:09:37 +00001722
Colin LeMahieu77804be2015-07-29 15:45:39 +00001723 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001724 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001725 continue;
1726 StringRef secname;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001727 error(Section.getName(secname));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001728 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001729 for (const RelocationRef &Reloc : Section.relocations()) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001730 bool hidden = getHidden(Reloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001731 uint64_t address = Reloc.getOffset();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001732 SmallString<32> relocname;
1733 SmallString<32> valuestr;
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001734 if (address < StartAddress || address > StopAddress || hidden)
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001735 continue;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001736 Reloc.getTypeName(relocname);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001737 error(getRelocationValueString(Reloc, valuestr));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001738 outs() << format(Fmt.data(), address) << " " << relocname << " "
1739 << valuestr << "\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001740 }
1741 outs() << "\n";
1742 }
1743}
1744
Paul Semelcb0f0432018-06-07 13:30:55 +00001745void llvm::PrintDynamicRelocations(const ObjectFile *Obj) {
1746
1747 // For the moment, this option is for ELF only
1748 if (!Obj->isELF())
1749 return;
1750
1751 const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj);
1752
1753 if (!Elf || Elf->getEType() != ELF::ET_DYN) {
1754 error("not a dynamic object");
1755 return;
1756 }
1757
1758 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
1759
1760 std::vector<SectionRef> DynRelSec = Obj->dynamic_relocation_sections();
1761 if (DynRelSec.empty())
1762 return;
1763
1764 outs() << "DYNAMIC RELOCATION RECORDS\n";
1765 for (const SectionRef &Section : DynRelSec) {
1766 if (Section.relocation_begin() == Section.relocation_end())
1767 continue;
1768 for (const RelocationRef &Reloc : Section.relocations()) {
1769 uint64_t address = Reloc.getOffset();
1770 SmallString<32> relocname;
1771 SmallString<32> valuestr;
1772 Reloc.getTypeName(relocname);
1773 error(getRelocationValueString(Reloc, valuestr));
1774 outs() << format(Fmt.data(), address) << " " << relocname << " "
1775 << valuestr << "\n";
1776 }
1777 }
1778}
1779
Kevin Enderby98da6132015-01-20 21:47:46 +00001780void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001781 outs() << "Sections:\n"
1782 "Idx Name Size Address Type\n";
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001783 unsigned i = 0;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001784 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001785 StringRef Name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001786 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001787 uint64_t Address = Section.getAddress();
1788 uint64_t Size = Section.getSize();
1789 bool Text = Section.isText();
1790 bool Data = Section.isData();
1791 bool BSS = Section.isBSS();
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001792 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +00001793 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
Alexey Samsonov48803e52014-03-13 14:37:36 +00001794 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1795 Name.str().c_str(), Size, Address, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001796 ++i;
1797 }
1798}
1799
Kevin Enderby98da6132015-01-20 21:47:46 +00001800void llvm::PrintSectionContents(const ObjectFile *Obj) {
Rafael Espindola4453e42942014-06-13 03:07:50 +00001801 std::error_code EC;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001802 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001803 StringRef Name;
1804 StringRef Contents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001805 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001806 uint64_t BaseAddr = Section.getAddress();
David Majnemer185b5b12014-11-11 09:58:25 +00001807 uint64_t Size = Section.getSize();
1808 if (!Size)
1809 continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001810
1811 outs() << "Contents of section " << Name << ":\n";
David Majnemer185b5b12014-11-11 09:58:25 +00001812 if (Section.isBSS()) {
Alexey Samsonov209095c2013-04-16 10:53:11 +00001813 outs() << format("<skipping contents of bss section at [%04" PRIx64
David Majnemer8f6b04c2014-07-14 16:20:14 +00001814 ", %04" PRIx64 ")>\n",
1815 BaseAddr, BaseAddr + Size);
Alexey Samsonov209095c2013-04-16 10:53:11 +00001816 continue;
1817 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001818
Davide Italianoccd53fe2015-08-05 07:18:31 +00001819 error(Section.getContents(Contents));
David Majnemer8f6b04c2014-07-14 16:20:14 +00001820
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001821 // Dump out the content as hex and printable ascii characters.
1822 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer82803112012-03-10 02:04:38 +00001823 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001824 // Dump line of hex.
1825 for (std::size_t i = 0; i < 16; ++i) {
1826 if (i != 0 && i % 4 == 0)
1827 outs() << ' ';
1828 if (addr + i < end)
1829 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1830 << hexdigit(Contents[addr + i] & 0xF, true);
1831 else
1832 outs() << " ";
1833 }
1834 // Print ascii.
1835 outs() << " ";
1836 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
Guy Benyei83c74e92013-02-12 21:21:59 +00001837 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001838 outs() << Contents[addr + i];
1839 else
1840 outs() << ".";
1841 }
1842 outs() << "\n";
1843 }
1844 }
1845}
1846
Kevin Enderby9acb1092016-05-31 20:35:34 +00001847void llvm::PrintSymbolTable(const ObjectFile *o, StringRef ArchiveName,
1848 StringRef ArchitectureName) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001849 outs() << "SYMBOL TABLE:\n";
1850
Rui Ueyama4e39f712014-03-18 18:58:51 +00001851 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
Davide Italianoe85abf72015-12-20 09:54:34 +00001852 printCOFFSymbolTable(coff);
Rui Ueyama4e39f712014-03-18 18:58:51 +00001853 return;
1854 }
1855 for (const SymbolRef &Symbol : o->symbols()) {
Kevin Enderby931cb652016-06-24 18:24:42 +00001856 Expected<uint64_t> AddressOrError = Symbol.getAddress();
1857 if (!AddressOrError)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001858 report_error(ArchiveName, o->getFileName(), AddressOrError.takeError(),
1859 ArchitectureName);
Rafael Espindolaed067c42015-07-03 18:19:00 +00001860 uint64_t Address = *AddressOrError;
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001861 if ((Address < StartAddress) || (Address > StopAddress))
1862 continue;
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001863 Expected<SymbolRef::Type> TypeOrError = Symbol.getType();
1864 if (!TypeOrError)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001865 report_error(ArchiveName, o->getFileName(), TypeOrError.takeError(),
1866 ArchitectureName);
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00001867 SymbolRef::Type Type = *TypeOrError;
Rui Ueyama4e39f712014-03-18 18:58:51 +00001868 uint32_t Flags = Symbol.getFlags();
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001869 Expected<section_iterator> SectionOrErr = Symbol.getSection();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001870 if (!SectionOrErr)
1871 report_error(ArchiveName, o->getFileName(), SectionOrErr.takeError(),
1872 ArchitectureName);
Rafael Espindola8bab8892015-08-07 23:27:14 +00001873 section_iterator Section = *SectionOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001874 StringRef Name;
1875 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1876 Section->getName(Name);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001877 } else {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001878 Expected<StringRef> NameOrErr = Symbol.getName();
1879 if (!NameOrErr)
Kevin Enderby9acb1092016-05-31 20:35:34 +00001880 report_error(ArchiveName, o->getFileName(), NameOrErr.takeError(),
1881 ArchitectureName);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001882 Name = *NameOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001883 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001884
Rui Ueyama4e39f712014-03-18 18:58:51 +00001885 bool Global = Flags & SymbolRef::SF_Global;
1886 bool Weak = Flags & SymbolRef::SF_Weak;
1887 bool Absolute = Flags & SymbolRef::SF_Absolute;
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001888 bool Common = Flags & SymbolRef::SF_Common;
Davide Italianocd2514d2015-04-30 23:08:53 +00001889 bool Hidden = Flags & SymbolRef::SF_Hidden;
David Meyer1df4b842012-02-28 23:47:53 +00001890
Rui Ueyama4e39f712014-03-18 18:58:51 +00001891 char GlobLoc = ' ';
1892 if (Type != SymbolRef::ST_Unknown)
1893 GlobLoc = Global ? 'g' : 'l';
1894 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1895 ? 'd' : ' ';
1896 char FileFunc = ' ';
1897 if (Type == SymbolRef::ST_File)
1898 FileFunc = 'f';
1899 else if (Type == SymbolRef::ST_Function)
1900 FileFunc = 'F';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001901
Rui Ueyama4e39f712014-03-18 18:58:51 +00001902 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1903 "%08" PRIx64;
Michael J. Spencerd857c1c2013-01-10 22:40:50 +00001904
Rui Ueyama4e39f712014-03-18 18:58:51 +00001905 outs() << format(Fmt, Address) << " "
1906 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1907 << (Weak ? 'w' : ' ') // Weak?
1908 << ' ' // Constructor. Not supported yet.
1909 << ' ' // Warning. Not supported yet.
1910 << ' ' // Indirect reference to another symbol.
1911 << Debug // Debugging (d) or dynamic (D) symbol.
1912 << FileFunc // Name of function (F), file (f) or object (O).
1913 << ' ';
1914 if (Absolute) {
1915 outs() << "*ABS*";
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001916 } else if (Common) {
1917 outs() << "*COM*";
Rui Ueyama4e39f712014-03-18 18:58:51 +00001918 } else if (Section == o->section_end()) {
1919 outs() << "*UND*";
1920 } else {
1921 if (const MachOObjectFile *MachO =
1922 dyn_cast<const MachOObjectFile>(o)) {
1923 DataRefImpl DR = Section->getRawDataRefImpl();
1924 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1925 outs() << SegmentName << ",";
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001926 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00001927 StringRef SectionName;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001928 error(Section->getName(SectionName));
Rui Ueyama4e39f712014-03-18 18:58:51 +00001929 outs() << SectionName;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001930 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001931
1932 outs() << '\t';
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001933 if (Common || isa<ELFObjectFileBase>(o)) {
Rafael Espindoladbb6bd32015-06-25 22:10:04 +00001934 uint64_t Val =
1935 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001936 outs() << format("\t %08" PRIx64 " ", Val);
1937 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001938
Davide Italianocd2514d2015-04-30 23:08:53 +00001939 if (Hidden) {
1940 outs() << ".hidden ";
1941 }
1942 outs() << Name
Rui Ueyama4e39f712014-03-18 18:58:51 +00001943 << '\n';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001944 }
1945}
1946
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001947static void PrintUnwindInfo(const ObjectFile *o) {
1948 outs() << "Unwind info:\n\n";
1949
1950 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1951 printCOFFUnwindInfo(coff);
Tim Northover4bd286a2014-08-01 13:07:19 +00001952 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1953 printMachOUnwindInfo(MachO);
1954 else {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001955 // TODO: Extract DWARF dump tool to objdump.
1956 errs() << "This operation is only currently supported "
Tim Northover4bd286a2014-08-01 13:07:19 +00001957 "for COFF and MachO object files.\n";
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001958 return;
1959 }
1960}
1961
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001962void llvm::printExportsTrie(const ObjectFile *o) {
Nick Kledzikd04bc352014-08-30 00:20:14 +00001963 outs() << "Exports trie:\n";
1964 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1965 printMachOExportsTrie(MachO);
1966 else {
1967 errs() << "This operation is only currently supported "
1968 "for Mach-O executable files.\n";
1969 return;
1970 }
1971}
1972
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001973void llvm::printRebaseTable(ObjectFile *o) {
Nick Kledzikac431442014-09-12 21:34:15 +00001974 outs() << "Rebase table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001975 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzikac431442014-09-12 21:34:15 +00001976 printMachORebaseTable(MachO);
1977 else {
1978 errs() << "This operation is only currently supported "
1979 "for Mach-O executable files.\n";
1980 return;
1981 }
1982}
1983
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001984void llvm::printBindTable(ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001985 outs() << "Bind table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001986 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzik56ebef42014-09-16 01:41:51 +00001987 printMachOBindTable(MachO);
1988 else {
1989 errs() << "This operation is only currently supported "
1990 "for Mach-O executable files.\n";
1991 return;
1992 }
1993}
1994
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001995void llvm::printLazyBindTable(ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001996 outs() << "Lazy bind table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001997 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzik56ebef42014-09-16 01:41:51 +00001998 printMachOLazyBindTable(MachO);
1999 else {
2000 errs() << "This operation is only currently supported "
2001 "for Mach-O executable files.\n";
2002 return;
2003 }
2004}
2005
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002006void llvm::printWeakBindTable(ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00002007 outs() << "Weak bind table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002008 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzik56ebef42014-09-16 01:41:51 +00002009 printMachOWeakBindTable(MachO);
2010 else {
2011 errs() << "This operation is only currently supported "
2012 "for Mach-O executable files.\n";
2013 return;
2014 }
2015}
Nick Kledzikac431442014-09-12 21:34:15 +00002016
Adrian Prantl437105a2015-07-08 02:04:15 +00002017/// Dump the raw contents of the __clangast section so the output can be piped
2018/// into llvm-bcanalyzer.
2019void llvm::printRawClangAST(const ObjectFile *Obj) {
2020 if (outs().is_displayed()) {
2021 errs() << "The -raw-clang-ast option will dump the raw binary contents of "
2022 "the clang ast section.\n"
2023 "Please redirect the output to a file or another program such as "
2024 "llvm-bcanalyzer.\n";
2025 return;
2026 }
2027
2028 StringRef ClangASTSectionName("__clangast");
2029 if (isa<COFFObjectFile>(Obj)) {
2030 ClangASTSectionName = "clangast";
2031 }
2032
2033 Optional<object::SectionRef> ClangASTSection;
Colin LeMahieu77804be2015-07-29 15:45:39 +00002034 for (auto Sec : ToolSectionFilter(*Obj)) {
Adrian Prantl437105a2015-07-08 02:04:15 +00002035 StringRef Name;
2036 Sec.getName(Name);
2037 if (Name == ClangASTSectionName) {
2038 ClangASTSection = Sec;
2039 break;
2040 }
2041 }
2042 if (!ClangASTSection)
2043 return;
2044
2045 StringRef ClangASTContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00002046 error(ClangASTSection.getValue().getContents(ClangASTContents));
Adrian Prantl437105a2015-07-08 02:04:15 +00002047 outs().write(ClangASTContents.data(), ClangASTContents.size());
2048}
2049
Sanjoy Das6f567a42015-06-22 18:03:02 +00002050static void printFaultMaps(const ObjectFile *Obj) {
2051 const char *FaultMapSectionName = nullptr;
2052
2053 if (isa<ELFObjectFileBase>(Obj)) {
2054 FaultMapSectionName = ".llvm_faultmaps";
2055 } else if (isa<MachOObjectFile>(Obj)) {
2056 FaultMapSectionName = "__llvm_faultmaps";
2057 } else {
2058 errs() << "This operation is only currently supported "
2059 "for ELF and Mach-O executable files.\n";
2060 return;
2061 }
2062
2063 Optional<object::SectionRef> FaultMapSection;
2064
Colin LeMahieu77804be2015-07-29 15:45:39 +00002065 for (auto Sec : ToolSectionFilter(*Obj)) {
Sanjoy Das6f567a42015-06-22 18:03:02 +00002066 StringRef Name;
2067 Sec.getName(Name);
2068 if (Name == FaultMapSectionName) {
2069 FaultMapSection = Sec;
2070 break;
2071 }
2072 }
2073
2074 outs() << "FaultMap table:\n";
2075
2076 if (!FaultMapSection.hasValue()) {
2077 outs() << "<not found>\n";
2078 return;
2079 }
2080
2081 StringRef FaultMapContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00002082 error(FaultMapSection.getValue().getContents(FaultMapContents));
Sanjoy Das6f567a42015-06-22 18:03:02 +00002083
2084 FaultMapParser FMP(FaultMapContents.bytes_begin(),
2085 FaultMapContents.bytes_end());
2086
2087 outs() << FMP;
2088}
2089
Davide Italiano1bdaa202016-09-18 04:39:15 +00002090static void printPrivateFileHeaders(const ObjectFile *o, bool onlyFirst) {
Kevin Enderby0ae163f2016-01-13 00:25:36 +00002091 if (o->isELF())
Davide Italiano1bdaa202016-09-18 04:39:15 +00002092 return printELFFileHeader(o);
2093 if (o->isCOFF())
2094 return printCOFFFileHeader(o);
Derek Schuff2c6f75d2016-11-30 16:49:11 +00002095 if (o->isWasm())
2096 return printWasmFileHeader(o);
Davide Italiano1bdaa202016-09-18 04:39:15 +00002097 if (o->isMachO()) {
Kevin Enderby0ae163f2016-01-13 00:25:36 +00002098 printMachOFileHeader(o);
Davide Italiano1bdaa202016-09-18 04:39:15 +00002099 if (!onlyFirst)
2100 printMachOLoadCommands(o);
2101 return;
2102 }
Kevin Enderby7fa40c92016-11-16 22:17:38 +00002103 report_error(o->getFileName(), "Invalid/Unsupported object file format");
Rui Ueyamac2bed422013-09-27 21:04:00 +00002104}
2105
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002106static void DumpObject(ObjectFile *o, const Archive *a = nullptr) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002107 StringRef ArchiveName = a != nullptr ? a->getFileName() : "";
Adrian Prantl437105a2015-07-08 02:04:15 +00002108 // Avoid other output when using a raw option.
2109 if (!RawClangAST) {
2110 outs() << '\n';
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002111 if (a)
2112 outs() << a->getFileName() << "(" << o->getFileName() << ")";
2113 else
2114 outs() << o->getFileName();
2115 outs() << ":\tfile format " << o->getFileFormatName() << "\n\n";
Adrian Prantl437105a2015-07-08 02:04:15 +00002116 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00002117
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002118 if (Disassemble)
Michael J. Spencer51862b32011-10-13 22:17:18 +00002119 DisassembleObject(o, Relocations);
2120 if (Relocations && !Disassemble)
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002121 PrintRelocations(o);
Paul Semelcb0f0432018-06-07 13:30:55 +00002122 if (DynamicRelocations)
2123 PrintDynamicRelocations(o);
Nick Lewyckyfcf84622011-10-10 21:21:34 +00002124 if (SectionHeaders)
2125 PrintSectionHeaders(o);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00002126 if (SectionContents)
2127 PrintSectionContents(o);
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002128 if (SymbolTable)
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002129 PrintSymbolTable(o, ArchiveName);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00002130 if (UnwindInfo)
2131 PrintUnwindInfo(o);
Davide Italiano1bdaa202016-09-18 04:39:15 +00002132 if (PrivateHeaders || FirstPrivateHeader)
2133 printPrivateFileHeaders(o, FirstPrivateHeader);
Nick Kledzikd04bc352014-08-30 00:20:14 +00002134 if (ExportsTrie)
2135 printExportsTrie(o);
Nick Kledzikac431442014-09-12 21:34:15 +00002136 if (Rebase)
2137 printRebaseTable(o);
Nick Kledzik56ebef42014-09-16 01:41:51 +00002138 if (Bind)
2139 printBindTable(o);
2140 if (LazyBind)
2141 printLazyBindTable(o);
2142 if (WeakBind)
2143 printWeakBindTable(o);
Adrian Prantl437105a2015-07-08 02:04:15 +00002144 if (RawClangAST)
2145 printRawClangAST(o);
Sanjoy Das6f567a42015-06-22 18:03:02 +00002146 if (PrintFaultMaps)
2147 printFaultMaps(o);
Igor Laevsky03a670c2016-01-26 15:09:42 +00002148 if (DwarfDumpType != DIDT_Null) {
Rafael Espindolac398e672017-07-19 22:27:28 +00002149 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*o);
Igor Laevsky03a670c2016-01-26 15:09:42 +00002150 // Dump the complete DWARF structure.
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00002151 DIDumpOptions DumpOpts;
2152 DumpOpts.DumpType = DwarfDumpType;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00002153 DICtx->dump(outs(), DumpOpts);
Igor Laevsky03a670c2016-01-26 15:09:42 +00002154 }
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002155}
2156
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00002157static void DumpObject(const COFFImportFile *I, const Archive *A) {
2158 StringRef ArchiveName = A ? A->getFileName() : "";
2159
2160 // Avoid other output when using a raw option.
2161 if (!RawClangAST)
2162 outs() << '\n'
2163 << ArchiveName << "(" << I->getFileName() << ")"
2164 << ":\tfile format COFF-import-file"
2165 << "\n\n";
2166
2167 if (SymbolTable)
2168 printCOFFSymbolTable(I);
2169}
2170
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +00002171/// Dump each object file in \a a;
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002172static void DumpArchive(const Archive *a) {
Mehdi Amini41af4302016-11-11 04:28:40 +00002173 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00002174 for (auto &C : a->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002175 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2176 if (!ChildOrErr) {
2177 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2178 report_error(a->getFileName(), C, std::move(E));
2179 continue;
2180 }
Rafael Espindolaae460022014-06-16 16:08:36 +00002181 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002182 DumpObject(o, a);
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00002183 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
2184 DumpObject(I, a);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002185 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00002186 report_error(a->getFileName(), object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002187 }
Lang Hamesfc209622016-07-14 02:24:01 +00002188 if (Err)
2189 report_error(a->getFileName(), std::move(Err));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002190}
2191
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +00002192/// Open file and figure out how to dump it.
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002193static void DumpInput(StringRef file) {
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002194
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002195 // If we are using the Mach-O specific object file parser, then let it parse
2196 // the file and process the command line options. So the -arch flags can
2197 // be used to select specific slices, etc.
2198 if (MachOOpt) {
2199 ParseInputMachO(file);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002200 return;
2201 }
2202
2203 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00002204 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
2205 if (!BinaryOrErr)
Kevin Enderbyb34e3a12016-05-05 17:43:35 +00002206 report_error(file, BinaryOrErr.takeError());
Rafael Espindola48af1c22014-08-19 18:44:46 +00002207 Binary &Binary = *BinaryOrErr.get().getBinary();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002208
Rafael Espindola3f6481d2014-08-01 14:31:55 +00002209 if (Archive *a = dyn_cast<Archive>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002210 DumpArchive(a);
Rafael Espindola3f6481d2014-08-01 14:31:55 +00002211 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002212 DumpObject(o);
Jim Grosbachaf9aec02012-08-07 17:53:14 +00002213 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00002214 report_error(file, object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002215}
2216
Michael J. Spencer2670c252011-01-20 06:39:06 +00002217int main(int argc, char **argv) {
Rui Ueyama197194b2018-04-13 18:26:06 +00002218 InitLLVM X(argc, argv);
Michael J. Spencer2670c252011-01-20 06:39:06 +00002219
2220 // Initialize targets and assembly printers/parsers.
2221 llvm::InitializeAllTargetInfos();
Evan Cheng8c886a42011-07-22 21:58:54 +00002222 llvm::InitializeAllTargetMCs();
Michael J. Spencer2670c252011-01-20 06:39:06 +00002223 llvm::InitializeAllDisassemblers();
2224
Pete Cooper28fb4fc2012-05-03 23:20:10 +00002225 // Register the target printer for --version.
2226 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
2227
Michael J. Spencer2670c252011-01-20 06:39:06 +00002228 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
2229 TripleName = Triple::normalize(TripleName);
2230
2231 ToolName = argv[0];
2232
2233 // Defaults to a.out if no filenames specified.
2234 if (InputFilenames.size() == 0)
2235 InputFilenames.push_back("a.out");
2236
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00002237 if (DisassembleAll || PrintSource || PrintLines)
Colin LeMahieuf34933e2015-07-23 20:58:49 +00002238 Disassemble = true;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002239 if (!Disassemble
2240 && !Relocations
Paul Semelcb0f0432018-06-07 13:30:55 +00002241 && !DynamicRelocations
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002242 && !SectionHeaders
2243 && !SectionContents
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00002244 && !SymbolTable
Michael J. Spencer209565db2013-01-06 03:56:49 +00002245 && !UnwindInfo
Nick Kledzikd04bc352014-08-30 00:20:14 +00002246 && !PrivateHeaders
Kevin Enderby0ae163f2016-01-13 00:25:36 +00002247 && !FirstPrivateHeader
Nick Kledzikac431442014-09-12 21:34:15 +00002248 && !ExportsTrie
Nick Kledzik56ebef42014-09-16 01:41:51 +00002249 && !Rebase
2250 && !Bind
2251 && !LazyBind
Kevin Enderby131d1772015-01-09 19:22:37 +00002252 && !WeakBind
Adrian Prantl437105a2015-07-08 02:04:15 +00002253 && !RawClangAST
Kevin Enderby13023a12015-01-15 23:19:11 +00002254 && !(UniversalHeaders && MachOOpt)
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00002255 && !(ArchiveHeaders && MachOOpt)
Kevin Enderby69fe98d2015-01-23 18:52:17 +00002256 && !(IndirectSymbols && MachOOpt)
Kevin Enderby9a509442015-01-27 21:28:24 +00002257 && !(DataInCode && MachOOpt)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002258 && !(LinkOptHints && MachOOpt)
Kevin Enderbycd66be52015-03-11 22:06:32 +00002259 && !(InfoPlist && MachOOpt)
Kevin Enderbybc847fa2015-03-16 20:08:09 +00002260 && !(DylibsUsed && MachOOpt)
2261 && !(DylibId && MachOOpt)
Kevin Enderby0fc11822015-04-01 20:57:01 +00002262 && !(ObjcMetaData && MachOOpt)
Colin LeMahieufcc32762015-07-29 19:08:10 +00002263 && !(FilterSections.size() != 0 && MachOOpt)
Igor Laevsky03a670c2016-01-26 15:09:42 +00002264 && !PrintFaultMaps
2265 && DwarfDumpType == DIDT_Null) {
Michael J. Spencer2670c252011-01-20 06:39:06 +00002266 cl::PrintHelpMessage();
Dimitry Andrice4f5d012017-12-18 19:46:56 +00002267 return 2;
2268 }
2269
Rafael Aulerb0e4b912018-03-09 19:13:44 +00002270 DisasmFuncsSet.insert(DisassembleFunctions.begin(),
2271 DisassembleFunctions.end());
2272
Dimitry Andrice4f5d012017-12-18 19:46:56 +00002273 llvm::for_each(InputFilenames, DumpInput);
2274
2275 return EXIT_SUCCESS;
2276}