blob: 5bea3a7860bca03384388e20bc605ecd5d21a28a [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>
97llvm::SectionContents("s", cl::desc("Display the content of each section"));
Michael J. Spencer4e25c022011-10-17 17:13:22 +000098
Kevin Enderby98da6132015-01-20 21:47:46 +000099cl::opt<bool>
100llvm::SymbolTable("t", cl::desc("Display the symbol table"));
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000101
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000102cl::opt<bool>
103llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
Nick Kledzikd04bc352014-08-30 00:20:14 +0000104
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000105cl::opt<bool>
106llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
Nick Kledzikac431442014-09-12 21:34:15 +0000107
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000108cl::opt<bool>
109llvm::Bind("bind", cl::desc("Display mach-o binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000110
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000111cl::opt<bool>
112llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000113
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000114cl::opt<bool>
115llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000116
Adrian Prantl437105a2015-07-08 02:04:15 +0000117cl::opt<bool>
118llvm::RawClangAST("raw-clang-ast",
119 cl::desc("Dump the raw binary contents of the clang AST section"));
120
Nick Kledzik56ebef42014-09-16 01:41:51 +0000121static cl::opt<bool>
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000122MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000123static cl::alias
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000124MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
Benjamin Kramer87ee76c2011-07-20 19:37:35 +0000125
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000126cl::opt<std::string>
127llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
128 "see -version for available targets"));
129
130cl::opt<std::string>
Kevin Enderbyc9595622014-08-06 23:24:41 +0000131llvm::MCPU("mcpu",
132 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
133 cl::value_desc("cpu-name"),
134 cl::init(""));
135
136cl::opt<std::string>
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000137llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
Michael J. Spencer2670c252011-01-20 06:39:06 +0000138 "see -version for available targets"));
139
Kevin Enderby98da6132015-01-20 21:47:46 +0000140cl::opt<bool>
141llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
142 "headers for each section."));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000143static cl::alias
144SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
145 cl::aliasopt(SectionHeaders));
146static cl::alias
147SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
148 cl::aliasopt(SectionHeaders));
Colin LeMahieufcc32762015-07-29 19:08:10 +0000149
Colin LeMahieu77804be2015-07-29 15:45:39 +0000150cl::list<std::string>
Colin LeMahieufcc32762015-07-29 19:08:10 +0000151llvm::FilterSections("section", cl::desc("Operate on the specified sections only. "
152 "With -macho dump segment,section"));
153cl::alias
154static FilterSectionsj("j", cl::desc("Alias for --section"),
155 cl::aliasopt(llvm::FilterSections));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000156
Kevin Enderbyc9595622014-08-06 23:24:41 +0000157cl::list<std::string>
158llvm::MAttrs("mattr",
Jack Carter551efd72012-08-28 19:24:49 +0000159 cl::CommaSeparated,
160 cl::desc("Target specific attributes"),
161 cl::value_desc("a1,+a2,-a3,..."));
162
Kevin Enderbybf246f52014-09-24 23:08:22 +0000163cl::opt<bool>
164llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
165 "instructions, do not print "
166 "the instruction bytes."));
Saleem Abdulrasooldea14b22017-02-08 18:11:31 +0000167cl::opt<bool>
168llvm::NoLeadingAddr("no-leading-addr", cl::desc("Print no leading address"));
Eli Bendersky3a6808c2012-11-20 22:57:02 +0000169
Kevin Enderby98da6132015-01-20 21:47:46 +0000170cl::opt<bool>
171llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000172
173static cl::alias
174UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
175 cl::aliasopt(UnwindInfo));
176
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000177cl::opt<bool>
178llvm::PrivateHeaders("private-headers",
179 cl::desc("Display format specific file headers"));
Michael J. Spencer209565db2013-01-06 03:56:49 +0000180
Kevin Enderby0ae163f2016-01-13 00:25:36 +0000181cl::opt<bool>
182llvm::FirstPrivateHeader("private-header",
183 cl::desc("Display only the first format specific file "
184 "header"));
185
Michael J. Spencer209565db2013-01-06 03:56:49 +0000186static cl::alias
187PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
188 cl::aliasopt(PrivateHeaders));
189
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000190cl::opt<bool>
191 llvm::PrintImmHex("print-imm-hex",
Colin LeMahieuefe37322016-04-08 18:15:37 +0000192 cl::desc("Use hex format for immediate values"));
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000193
Sanjoy Das6f567a42015-06-22 18:03:02 +0000194cl::opt<bool> PrintFaultMaps("fault-map-section",
195 cl::desc("Display contents of faultmap section"));
196
Igor Laevsky03a670c2016-01-26 15:09:42 +0000197cl::opt<DIDumpType> llvm::DwarfDumpType(
198 "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"),
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000199 cl::values(clEnumValN(DIDT_DebugFrame, "frames", ".debug_frame")));
Igor Laevsky03a670c2016-01-26 15:09:42 +0000200
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000201cl::opt<bool> PrintSource(
202 "source",
203 cl::desc(
Alex Denisova07169e2018-02-02 19:20:37 +0000204 "Display source inlined with disassembly. Implies disassemble object"));
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000205
206cl::alias PrintSourceShort("S", cl::desc("Alias for -source"),
207 cl::aliasopt(PrintSource));
208
209cl::opt<bool> PrintLines("line-numbers",
210 cl::desc("Display source line numbers with "
211 "disassembly. Implies disassemble object"));
212
213cl::alias PrintLinesShort("l", cl::desc("Alias for -line-numbers"),
214 cl::aliasopt(PrintLines));
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +0000215
216cl::opt<unsigned long long>
217 StartAddress("start-address", cl::desc("Disassemble beginning at address"),
218 cl::value_desc("address"), cl::init(0));
219cl::opt<unsigned long long>
220 StopAddress("stop-address", cl::desc("Stop disassembly at address"),
221 cl::value_desc("address"), cl::init(UINT64_MAX));
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000222static StringRef ToolName;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000223
Sam Parker5fba45a2017-02-08 09:44:18 +0000224typedef std::vector<std::tuple<uint64_t, StringRef, uint8_t>> SectionSymbolsTy;
225
Colin LeMahieu77804be2015-07-29 15:45:39 +0000226namespace {
Colin LeMahieufcc32762015-07-29 19:08:10 +0000227typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate;
Colin LeMahieu77804be2015-07-29 15:45:39 +0000228
229class SectionFilterIterator {
230public:
231 SectionFilterIterator(FilterPredicate P,
232 llvm::object::section_iterator const &I,
233 llvm::object::section_iterator const &E)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000234 : Predicate(std::move(P)), Iterator(I), End(E) {
Colin LeMahieu77804be2015-07-29 15:45:39 +0000235 ScanPredicate();
236 }
Benjamin Kramerac9257b2015-09-24 14:52:52 +0000237 const llvm::object::SectionRef &operator*() const { return *Iterator; }
Colin LeMahieu77804be2015-07-29 15:45:39 +0000238 SectionFilterIterator &operator++() {
239 ++Iterator;
240 ScanPredicate();
241 return *this;
242 }
243 bool operator!=(SectionFilterIterator const &Other) const {
244 return Iterator != Other.Iterator;
245 }
246
247private:
248 void ScanPredicate() {
Colin LeMahieuda1723f2015-07-29 19:21:13 +0000249 while (Iterator != End && !Predicate(*Iterator)) {
Colin LeMahieu77804be2015-07-29 15:45:39 +0000250 ++Iterator;
251 }
252 }
253 FilterPredicate Predicate;
254 llvm::object::section_iterator Iterator;
255 llvm::object::section_iterator End;
256};
257
258class SectionFilter {
259public:
260 SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000261 : Predicate(std::move(P)), Object(O) {}
Colin LeMahieu77804be2015-07-29 15:45:39 +0000262 SectionFilterIterator begin() {
263 return SectionFilterIterator(Predicate, Object.section_begin(),
264 Object.section_end());
265 }
266 SectionFilterIterator end() {
267 return SectionFilterIterator(Predicate, Object.section_end(),
268 Object.section_end());
269 }
270
271private:
272 FilterPredicate Predicate;
273 llvm::object::ObjectFile const &Object;
274};
275SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) {
David Majnemer42531262016-08-12 03:55:06 +0000276 return SectionFilter(
277 [](llvm::object::SectionRef const &S) {
278 if (FilterSections.empty())
279 return true;
280 llvm::StringRef String;
281 std::error_code error = S.getName(String);
282 if (error)
283 return false;
284 return is_contained(FilterSections, String);
285 },
286 O);
Colin LeMahieu77804be2015-07-29 15:45:39 +0000287}
288}
289
Davide Italianoccd53fe2015-08-05 07:18:31 +0000290void llvm::error(std::error_code EC) {
Mark Seaborneb03ac52014-01-25 00:32:01 +0000291 if (!EC)
Davide Italianoccd53fe2015-08-05 07:18:31 +0000292 return;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000293
Davide Italiano140af642015-12-25 18:16:45 +0000294 errs() << ToolName << ": error reading file: " << EC.message() << ".\n";
295 errs().flush();
Davide Italiano7f6c3012015-08-06 00:18:52 +0000296 exit(1);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000297}
298
Kevin Enderby42398052016-06-28 23:16:13 +0000299LLVM_ATTRIBUTE_NORETURN void llvm::error(Twine Message) {
300 errs() << ToolName << ": " << Message << ".\n";
301 errs().flush();
302 exit(1);
303}
304
Davide Italianoed9d95b2015-12-29 13:41:02 +0000305LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000306 Twine Message) {
307 errs() << ToolName << ": '" << File << "': " << Message << ".\n";
308 exit(1);
309}
310
311LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
Davide Italianoed9d95b2015-12-29 13:41:02 +0000312 std::error_code EC) {
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000313 assert(EC);
314 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
Davide Italianoccd53fe2015-08-05 07:18:31 +0000315 exit(1);
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000316}
317
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000318LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
319 llvm::Error E) {
320 assert(E);
321 std::string Buf;
322 raw_string_ostream OS(Buf);
323 logAllUnhandledErrors(std::move(E), OS, "");
324 OS.flush();
Kevin Enderbyb34e3a12016-05-05 17:43:35 +0000325 errs() << ToolName << ": '" << File << "': " << Buf;
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000326 exit(1);
327}
328
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000329LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
330 StringRef FileName,
Kevin Enderby9acb1092016-05-31 20:35:34 +0000331 llvm::Error E,
332 StringRef ArchitectureName) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000333 assert(E);
334 errs() << ToolName << ": ";
335 if (ArchiveName != "")
336 errs() << ArchiveName << "(" << FileName << ")";
337 else
Justin Bogner31d8b7d2016-10-26 22:37:52 +0000338 errs() << "'" << FileName << "'";
Kevin Enderby9acb1092016-05-31 20:35:34 +0000339 if (!ArchitectureName.empty())
340 errs() << " (for architecture " << ArchitectureName << ")";
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000341 std::string Buf;
342 raw_string_ostream OS(Buf);
343 logAllUnhandledErrors(std::move(E), OS, "");
344 OS.flush();
Justin Bogner31d8b7d2016-10-26 22:37:52 +0000345 errs() << ": " << Buf;
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000346 exit(1);
347}
348
349LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
350 const object::Archive::Child &C,
Kevin Enderby9acb1092016-05-31 20:35:34 +0000351 llvm::Error E,
352 StringRef ArchitectureName) {
Kevin Enderbyf4586032016-07-29 17:44:13 +0000353 Expected<StringRef> NameOrErr = C.getName();
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000354 // TODO: if we have a error getting the name then it would be nice to print
355 // the index of which archive member this is and or its offset in the
356 // archive instead of "???" as the name.
Kevin Enderbyf4586032016-07-29 17:44:13 +0000357 if (!NameOrErr) {
358 consumeError(NameOrErr.takeError());
Kevin Enderby9acb1092016-05-31 20:35:34 +0000359 llvm::report_error(ArchiveName, "???", std::move(E), ArchitectureName);
Kevin Enderbyf4586032016-07-29 17:44:13 +0000360 } else
Kevin Enderby9acb1092016-05-31 20:35:34 +0000361 llvm::report_error(ArchiveName, NameOrErr.get(), std::move(E),
362 ArchitectureName);
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000363}
364
Craig Toppere6cb63e2014-04-25 04:24:47 +0000365static const Target *getTarget(const ObjectFile *Obj = nullptr) {
Michael J. Spencer2670c252011-01-20 06:39:06 +0000366 // Figure out the target triple.
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000367 llvm::Triple TheTriple("unknown-unknown-unknown");
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000368 if (TripleName.empty()) {
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000369 if (Obj) {
Vlad Tsyrklevichde620462017-09-19 02:22:48 +0000370 TheTriple = Obj->makeTriple();
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000371 }
Sam Parkerdf7c6ef2017-01-18 13:52:12 +0000372 } else {
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000373 TheTriple.setTriple(Triple::normalize(TripleName));
Vlad Tsyrklevichde620462017-09-19 02:22:48 +0000374
Sam Parkerdf7c6ef2017-01-18 13:52:12 +0000375 // Use the triple, but also try to combine with ARM build attributes.
376 if (Obj) {
377 auto Arch = Obj->getArch();
378 if (Arch == Triple::arm || Arch == Triple::armeb) {
379 Obj->setARMSubArch(TheTriple);
380 }
381 }
382 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000383
384 // Get the target specific parser.
385 std::string Error;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000386 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
387 Error);
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000388 if (!TheTarget) {
389 if (Obj)
390 report_error(Obj->getFileName(), "can't find target: " + Error);
391 else
392 error("can't find target: " + Error);
393 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000394
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000395 // Update the triple name and return the found target.
396 TripleName = TheTriple.getTriple();
397 return TheTarget;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000398}
399
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000400bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
Rafael Espindola704cd842015-07-06 15:47:43 +0000401 return a.getOffset() < b.getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +0000402}
403
Colin LeMahieufb76b002015-05-28 19:07:14 +0000404namespace {
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000405class SourcePrinter {
406protected:
407 DILineInfo OldLineInfo;
Vlad Tsyrklevichf1620132017-09-12 02:27:39 +0000408 const ObjectFile *Obj = nullptr;
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000409 std::unique_ptr<symbolize::LLVMSymbolizer> Symbolizer;
410 // File name to file contents of source
411 std::unordered_map<std::string, std::unique_ptr<MemoryBuffer>> SourceCache;
412 // Mark the line endings of the cached source
413 std::unordered_map<std::string, std::vector<StringRef>> LineCache;
414
415private:
Scott Linder16c7bda2018-02-23 23:01:06 +0000416 bool cacheSource(const DILineInfo& LineInfoFile);
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000417
418public:
Vlad Tsyrklevichf1620132017-09-12 02:27:39 +0000419 SourcePrinter() = default;
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000420 SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch) : Obj(Obj) {
421 symbolize::LLVMSymbolizer::Options SymbolizerOpts(
422 DILineInfoSpecifier::FunctionNameKind::None, true, false, false,
423 DefaultArch);
424 Symbolizer.reset(new symbolize::LLVMSymbolizer(SymbolizerOpts));
425 }
Vlad Tsyrklevichf1620132017-09-12 02:27:39 +0000426 virtual ~SourcePrinter() = default;
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000427 virtual void printSourceLine(raw_ostream &OS, uint64_t Address,
428 StringRef Delimiter = "; ");
429};
430
Scott Linder16c7bda2018-02-23 23:01:06 +0000431bool SourcePrinter::cacheSource(const DILineInfo &LineInfo) {
432 std::unique_ptr<MemoryBuffer> Buffer;
433 if (LineInfo.Source) {
434 Buffer = MemoryBuffer::getMemBuffer(*LineInfo.Source);
435 } else {
436 auto BufferOrError = MemoryBuffer::getFile(LineInfo.FileName);
437 if (!BufferOrError)
438 return false;
439 Buffer = std::move(*BufferOrError);
440 }
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000441 // Chomp the file to get lines
Scott Linder16c7bda2018-02-23 23:01:06 +0000442 size_t BufferSize = Buffer->getBufferSize();
443 const char *BufferStart = Buffer->getBufferStart();
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000444 for (const char *Start = BufferStart, *End = BufferStart;
445 End < BufferStart + BufferSize; End++)
446 if (*End == '\n' || End == BufferStart + BufferSize - 1 ||
447 (*End == '\r' && *(End + 1) == '\n')) {
Scott Linder16c7bda2018-02-23 23:01:06 +0000448 LineCache[LineInfo.FileName].push_back(StringRef(Start, End - Start));
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000449 if (*End == '\r')
450 End++;
451 Start = End + 1;
452 }
Scott Linder16c7bda2018-02-23 23:01:06 +0000453 SourceCache[LineInfo.FileName] = std::move(Buffer);
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000454 return true;
455}
456
457void SourcePrinter::printSourceLine(raw_ostream &OS, uint64_t Address,
458 StringRef Delimiter) {
459 if (!Symbolizer)
460 return;
461 DILineInfo LineInfo = DILineInfo();
462 auto ExpectecLineInfo =
463 Symbolizer->symbolizeCode(Obj->getFileName(), Address);
464 if (!ExpectecLineInfo)
465 consumeError(ExpectecLineInfo.takeError());
466 else
467 LineInfo = *ExpectecLineInfo;
468
469 if ((LineInfo.FileName == "<invalid>") || OldLineInfo.Line == LineInfo.Line ||
470 LineInfo.Line == 0)
471 return;
472
473 if (PrintLines)
474 OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line << "\n";
475 if (PrintSource) {
476 if (SourceCache.find(LineInfo.FileName) == SourceCache.end())
Scott Linder16c7bda2018-02-23 23:01:06 +0000477 if (!cacheSource(LineInfo))
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000478 return;
479 auto FileBuffer = SourceCache.find(LineInfo.FileName);
480 if (FileBuffer != SourceCache.end()) {
481 auto LineBuffer = LineCache.find(LineInfo.FileName);
Petr Hosek86611a02017-04-25 18:56:33 +0000482 if (LineBuffer != LineCache.end()) {
483 if (LineInfo.Line > LineBuffer->second.size())
484 return;
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000485 // Vector begins at 0, line numbers are non-zero
486 OS << Delimiter << LineBuffer->second[LineInfo.Line - 1].ltrim()
487 << "\n";
Petr Hosek86611a02017-04-25 18:56:33 +0000488 }
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000489 }
490 }
491 OldLineInfo = LineInfo;
492}
493
Hemant Kulkarni5b60f632016-08-25 19:41:08 +0000494static bool isArmElf(const ObjectFile *Obj) {
495 return (Obj->isELF() &&
496 (Obj->getArch() == Triple::aarch64 ||
497 Obj->getArch() == Triple::aarch64_be ||
498 Obj->getArch() == Triple::arm || Obj->getArch() == Triple::armeb ||
499 Obj->getArch() == Triple::thumb ||
500 Obj->getArch() == Triple::thumbeb));
501}
502
Colin LeMahieufb76b002015-05-28 19:07:14 +0000503class PrettyPrinter {
504public:
Vlad Tsyrklevichf1620132017-09-12 02:27:39 +0000505 virtual ~PrettyPrinter() = default;
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000506 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
Colin LeMahieufb76b002015-05-28 19:07:14 +0000507 ArrayRef<uint8_t> Bytes, uint64_t Address,
508 raw_ostream &OS, StringRef Annot,
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000509 MCSubtargetInfo const &STI, SourcePrinter *SP) {
510 if (SP && (PrintSource || PrintLines))
511 SP->printSourceLine(OS, Address);
Saleem Abdulrasooldea14b22017-02-08 18:11:31 +0000512 if (!NoLeadingAddr)
513 OS << format("%8" PRIx64 ":", Address);
Colin LeMahieufb76b002015-05-28 19:07:14 +0000514 if (!NoShowRawInsn) {
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000515 OS << "\t";
516 dumpBytes(Bytes, OS);
Colin LeMahieufb76b002015-05-28 19:07:14 +0000517 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000518 if (MI)
519 IP.printInst(MI, OS, "", STI);
520 else
521 OS << " <unknown>";
Colin LeMahieufb76b002015-05-28 19:07:14 +0000522 }
523};
524PrettyPrinter PrettyPrinterInst;
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000525class HexagonPrettyPrinter : public PrettyPrinter {
526public:
527 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
528 raw_ostream &OS) {
529 uint32_t opcode =
530 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
Saleem Abdulrasooldea14b22017-02-08 18:11:31 +0000531 if (!NoLeadingAddr)
532 OS << format("%8" PRIx64 ":", Address);
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000533 if (!NoShowRawInsn) {
534 OS << "\t";
535 dumpBytes(Bytes.slice(0, 4), OS);
536 OS << format("%08" PRIx32, opcode);
537 }
538 }
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000539 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
540 uint64_t Address, raw_ostream &OS, StringRef Annot,
541 MCSubtargetInfo const &STI, SourcePrinter *SP) override {
Hemant Kulkarnie77a0a92016-08-18 21:50:13 +0000542 if (SP && (PrintSource || PrintLines))
543 SP->printSourceLine(OS, Address, "");
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000544 if (!MI) {
545 printLead(Bytes, Address, OS);
546 OS << " <unknown>";
547 return;
548 }
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000549 std::string Buffer;
550 {
551 raw_string_ostream TempStream(Buffer);
552 IP.printInst(MI, TempStream, "", STI);
553 }
554 StringRef Contents(Buffer);
555 // Split off bundle attributes
556 auto PacketBundle = Contents.rsplit('\n');
557 // Split off first instruction from the rest
558 auto HeadTail = PacketBundle.first.split('\n');
559 auto Preamble = " { ";
560 auto Separator = "";
561 while(!HeadTail.first.empty()) {
562 OS << Separator;
563 Separator = "\n";
Hemant Kulkarnie77a0a92016-08-18 21:50:13 +0000564 if (SP && (PrintSource || PrintLines))
565 SP->printSourceLine(OS, Address, "");
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000566 printLead(Bytes, Address, OS);
567 OS << Preamble;
568 Preamble = " ";
569 StringRef Inst;
570 auto Duplex = HeadTail.first.split('\v');
571 if(!Duplex.second.empty()){
572 OS << Duplex.first;
573 OS << "; ";
574 Inst = Duplex.second;
575 }
576 else
577 Inst = HeadTail.first;
578 OS << Inst;
579 Bytes = Bytes.slice(4);
580 Address += 4;
581 HeadTail = HeadTail.second.split('\n');
582 }
583 OS << " } " << PacketBundle.second;
584 }
585};
586HexagonPrettyPrinter HexagonPrettyPrinterInst;
Valery Pykhtinde048052016-04-07 07:24:01 +0000587
588class AMDGCNPrettyPrinter : public PrettyPrinter {
589public:
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000590 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
591 uint64_t Address, raw_ostream &OS, StringRef Annot,
592 MCSubtargetInfo const &STI, SourcePrinter *SP) override {
Konstantin Zhuravlyovf895b202017-03-07 20:17:11 +0000593 if (SP && (PrintSource || PrintLines))
594 SP->printSourceLine(OS, Address);
595
Tim Corringham7116e892018-03-26 17:06:33 +0000596 typedef support::ulittle32_t U32;
597
598 if (MI) {
599 SmallString<40> InstStr;
600 raw_svector_ostream IS(InstStr);
601
602 IP.printInst(MI, IS, "", STI);
603
604 OS << left_justify(IS.str(), 60);
605 } else {
606 // an unrecognized encoding - this is probably data so represent it
607 // using the .long directive, or .byte directive if fewer than 4 bytes
608 // remaining
609 if (Bytes.size() >= 4) {
610 OS << format("\t.long 0x%08" PRIx32 " ",
611 static_cast<uint32_t>(*reinterpret_cast<const U32*>(Bytes.data())));
612 OS.indent(42);
613 } else {
614 OS << format("\t.byte 0x%02" PRIx8, Bytes[0]);
615 for (unsigned int i = 1; i < Bytes.size(); i++)
616 OS << format(", 0x%02" PRIx8, Bytes[i]);
617 OS.indent(55 - (6 * Bytes.size()));
618 }
Matt Arsenault87d80db2016-04-22 21:23:41 +0000619 }
620
Tim Corringham7116e892018-03-26 17:06:33 +0000621 OS << format("// %012" PRIX64 ": ", Address);
622 if (Bytes.size() >=4) {
623 for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
624 Bytes.size() / sizeof(U32)))
625 // D should be explicitly casted to uint32_t here as it is passed
626 // by format to snprintf as vararg.
627 OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D));
628 } else {
629 for (unsigned int i = 0; i < Bytes.size(); i++)
630 OS << format("%02" PRIX8 " ", Bytes[i]);
631 }
Valery Pykhtinde048052016-04-07 07:24:01 +0000632
633 if (!Annot.empty())
634 OS << "// " << Annot;
635 }
636};
637AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
638
Alexei Starovoitov3b9efca2016-12-13 19:07:08 +0000639class BPFPrettyPrinter : public PrettyPrinter {
640public:
641 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
642 uint64_t Address, raw_ostream &OS, StringRef Annot,
643 MCSubtargetInfo const &STI, SourcePrinter *SP) override {
644 if (SP && (PrintSource || PrintLines))
645 SP->printSourceLine(OS, Address);
Saleem Abdulrasooldea14b22017-02-08 18:11:31 +0000646 if (!NoLeadingAddr)
647 OS << format("%8" PRId64 ":", Address / 8);
Alexei Starovoitov3b9efca2016-12-13 19:07:08 +0000648 if (!NoShowRawInsn) {
649 OS << "\t";
650 dumpBytes(Bytes, OS);
651 }
652 if (MI)
653 IP.printInst(MI, OS, "", STI);
654 else
655 OS << " <unknown>";
656 }
657};
658BPFPrettyPrinter BPFPrettyPrinterInst;
659
Colin LeMahieu35436a22015-05-29 14:48:25 +0000660PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000661 switch(Triple.getArch()) {
662 default:
663 return PrettyPrinterInst;
664 case Triple::hexagon:
665 return HexagonPrettyPrinterInst;
Valery Pykhtinde048052016-04-07 07:24:01 +0000666 case Triple::amdgcn:
667 return AMDGCNPrettyPrinterInst;
Alexei Starovoitov3b9efca2016-12-13 19:07:08 +0000668 case Triple::bpfel:
669 case Triple::bpfeb:
670 return BPFPrettyPrinterInst;
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000671 }
Colin LeMahieufb76b002015-05-28 19:07:14 +0000672}
673}
674
Rafael Espindola37070a52015-06-03 04:48:06 +0000675template <class ELFT>
Rafael Espindola37070a52015-06-03 04:48:06 +0000676static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000677 const RelocationRef &RelRef,
Rafael Espindola37070a52015-06-03 04:48:06 +0000678 SmallVectorImpl<char> &Result) {
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000679 DataRefImpl Rel = RelRef.getRawDataRefImpl();
680
Rafael Espindola37070a52015-06-03 04:48:06 +0000681 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
682 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000683 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
684
Rafael Espindola37070a52015-06-03 04:48:06 +0000685 const ELFFile<ELFT> &EF = *Obj->getELFFile();
686
Davide Italiano6cf09262016-11-16 05:10:28 +0000687 auto SecOrErr = EF.getSection(Rel.d.a);
688 if (!SecOrErr)
689 return errorToErrorCode(SecOrErr.takeError());
Rafael Espindola6def3042015-07-01 12:56:27 +0000690 const Elf_Shdr *Sec = *SecOrErr;
Davide Italiano6cf09262016-11-16 05:10:28 +0000691 auto SymTabOrErr = EF.getSection(Sec->sh_link);
692 if (!SymTabOrErr)
693 return errorToErrorCode(SymTabOrErr.takeError());
Rafael Espindola6def3042015-07-01 12:56:27 +0000694 const Elf_Shdr *SymTab = *SymTabOrErr;
Rafael Espindola719dc7c2015-06-29 12:38:31 +0000695 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
696 SymTab->sh_type == ELF::SHT_DYNSYM);
Davide Italiano6cf09262016-11-16 05:10:28 +0000697 auto StrTabSec = EF.getSection(SymTab->sh_link);
698 if (!StrTabSec)
699 return errorToErrorCode(StrTabSec.takeError());
700 auto StrTabOrErr = EF.getStringTable(*StrTabSec);
701 if (!StrTabOrErr)
702 return errorToErrorCode(StrTabOrErr.takeError());
Rafael Espindola6a1bfb22015-06-29 14:39:25 +0000703 StringRef StrTab = *StrTabOrErr;
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000704 uint8_t type = RelRef.getType();
Rafael Espindola37070a52015-06-03 04:48:06 +0000705 StringRef res;
706 int64_t addend = 0;
Rafael Espindola6def3042015-07-01 12:56:27 +0000707 switch (Sec->sh_type) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000708 default:
709 return object_error::parse_failed;
710 case ELF::SHT_REL: {
Rafael Espindola37070a52015-06-03 04:48:06 +0000711 // TODO: Read implicit addend from section data.
712 break;
713 }
714 case ELF::SHT_RELA: {
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000715 const Elf_Rela *ERela = Obj->getRela(Rel);
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000716 addend = ERela->r_addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000717 break;
718 }
719 }
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000720 symbol_iterator SI = RelRef.getSymbol();
721 const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
Rafael Espindola75d5b542015-06-03 05:14:22 +0000722 StringRef Target;
Rafael Espindola75d5b542015-06-03 05:14:22 +0000723 if (symb->getType() == ELF::STT_SECTION) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000724 Expected<section_iterator> SymSI = SI->getSection();
725 if (!SymSI)
726 return errorToErrorCode(SymSI.takeError());
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000727 const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
Davide Italiano6cf09262016-11-16 05:10:28 +0000728 auto SecName = EF.getSectionName(SymSec);
729 if (!SecName)
730 return errorToErrorCode(SecName.takeError());
Rafael Espindola75d5b542015-06-03 05:14:22 +0000731 Target = *SecName;
732 } else {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000733 Expected<StringRef> SymName = symb->getName(StrTab);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000734 if (!SymName)
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000735 return errorToErrorCode(SymName.takeError());
Rafael Espindola75d5b542015-06-03 05:14:22 +0000736 Target = *SymName;
737 }
Rafael Espindola37070a52015-06-03 04:48:06 +0000738 switch (EF.getHeader()->e_machine) {
739 case ELF::EM_X86_64:
740 switch (type) {
741 case ELF::R_X86_64_PC8:
742 case ELF::R_X86_64_PC16:
743 case ELF::R_X86_64_PC32: {
744 std::string fmtbuf;
745 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000746 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
Rafael Espindola37070a52015-06-03 04:48:06 +0000747 fmt.flush();
748 Result.append(fmtbuf.begin(), fmtbuf.end());
749 } break;
750 case ELF::R_X86_64_8:
751 case ELF::R_X86_64_16:
752 case ELF::R_X86_64_32:
753 case ELF::R_X86_64_32S:
754 case ELF::R_X86_64_64: {
755 std::string fmtbuf;
756 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000757 fmt << Target << (addend < 0 ? "" : "+") << addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000758 fmt.flush();
759 Result.append(fmtbuf.begin(), fmtbuf.end());
760 } break;
761 default:
762 res = "Unknown";
763 }
764 break;
Jacques Pienaarea9f25a2016-03-01 21:21:42 +0000765 case ELF::EM_LANAI:
Dylan McKay11661122016-09-28 13:15:17 +0000766 case ELF::EM_AVR:
Rafael Espindola37070a52015-06-03 04:48:06 +0000767 case ELF::EM_AARCH64: {
768 std::string fmtbuf;
769 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000770 fmt << Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000771 if (addend != 0)
772 fmt << (addend < 0 ? "" : "+") << addend;
773 fmt.flush();
774 Result.append(fmtbuf.begin(), fmtbuf.end());
775 break;
776 }
777 case ELF::EM_386:
Michael Kupersteina3b79dd2015-11-04 11:21:50 +0000778 case ELF::EM_IAMCU:
Rafael Espindola37070a52015-06-03 04:48:06 +0000779 case ELF::EM_ARM:
780 case ELF::EM_HEXAGON:
781 case ELF::EM_MIPS:
Alexei Starovoitovcfb51f52016-07-15 22:27:55 +0000782 case ELF::EM_BPF:
Alex Bradbury1524f622016-11-01 16:59:37 +0000783 case ELF::EM_RISCV:
Rafael Espindola75d5b542015-06-03 05:14:22 +0000784 res = Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000785 break;
Dan Gohman46350172016-01-12 20:56:01 +0000786 case ELF::EM_WEBASSEMBLY:
787 switch (type) {
788 case ELF::R_WEBASSEMBLY_DATA: {
789 std::string fmtbuf;
790 raw_string_ostream fmt(fmtbuf);
791 fmt << Target << (addend < 0 ? "" : "+") << addend;
792 fmt.flush();
793 Result.append(fmtbuf.begin(), fmtbuf.end());
794 break;
795 }
796 case ELF::R_WEBASSEMBLY_FUNCTION:
797 res = Target;
798 break;
799 default:
800 res = "Unknown";
801 }
802 break;
Rafael Espindola37070a52015-06-03 04:48:06 +0000803 default:
804 res = "Unknown";
805 }
806 if (Result.empty())
807 Result.append(res.begin(), res.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000808 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000809}
810
811static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000812 const RelocationRef &Rel,
Rafael Espindola37070a52015-06-03 04:48:06 +0000813 SmallVectorImpl<char> &Result) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000814 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
815 return getRelocationValueString(ELF32LE, Rel, Result);
816 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
817 return getRelocationValueString(ELF64LE, Rel, Result);
818 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
819 return getRelocationValueString(ELF32BE, Rel, Result);
820 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
821 return getRelocationValueString(ELF64BE, Rel, Result);
822}
823
824static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
825 const RelocationRef &Rel,
826 SmallVectorImpl<char> &Result) {
827 symbol_iterator SymI = Rel.getSymbol();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000828 Expected<StringRef> SymNameOrErr = SymI->getName();
829 if (!SymNameOrErr)
830 return errorToErrorCode(SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000831 StringRef SymName = *SymNameOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000832 Result.append(SymName.begin(), SymName.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000833 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000834}
835
836static void printRelocationTargetName(const MachOObjectFile *O,
837 const MachO::any_relocation_info &RE,
838 raw_string_ostream &fmt) {
839 bool IsScattered = O->isRelocationScattered(RE);
840
841 // Target of a scattered relocation is an address. In the interest of
842 // generating pretty output, scan through the symbol table looking for a
843 // symbol that aligns with that address. If we find one, print it.
844 // Otherwise, we just print the hex address of the target.
845 if (IsScattered) {
846 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
847
848 for (const SymbolRef &Symbol : O->symbols()) {
849 std::error_code ec;
Kevin Enderby931cb652016-06-24 18:24:42 +0000850 Expected<uint64_t> Addr = Symbol.getAddress();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000851 if (!Addr)
852 report_error(O->getFileName(), Addr.takeError());
Rafael Espindolaed067c42015-07-03 18:19:00 +0000853 if (*Addr != Val)
Rafael Espindola37070a52015-06-03 04:48:06 +0000854 continue;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000855 Expected<StringRef> Name = Symbol.getName();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000856 if (!Name)
857 report_error(O->getFileName(), Name.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000858 fmt << *Name;
Rafael Espindola37070a52015-06-03 04:48:06 +0000859 return;
860 }
861
862 // If we couldn't find a symbol that this relocation refers to, try
863 // to find a section beginning instead.
Colin LeMahieu77804be2015-07-29 15:45:39 +0000864 for (const SectionRef &Section : ToolSectionFilter(*O)) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000865 std::error_code ec;
866
867 StringRef Name;
868 uint64_t Addr = Section.getAddress();
869 if (Addr != Val)
870 continue;
871 if ((ec = Section.getName(Name)))
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000872 report_error(O->getFileName(), ec);
Rafael Espindola37070a52015-06-03 04:48:06 +0000873 fmt << Name;
874 return;
875 }
876
877 fmt << format("0x%x", Val);
878 return;
879 }
880
881 StringRef S;
882 bool isExtern = O->getPlainRelocationExternal(RE);
883 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
884
Martin Storsjo8c0317d2017-07-13 17:03:02 +0000885 if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND) {
Simon Dardis38867052017-08-07 12:29:38 +0000886 fmt << format("0x%0" PRIx64, Val);
Martin Storsjo8c0317d2017-07-13 17:03:02 +0000887 return;
888 } else if (isExtern) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000889 symbol_iterator SI = O->symbol_begin();
890 advance(SI, Val);
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000891 Expected<StringRef> SOrErr = SI->getName();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000892 if (!SOrErr)
893 report_error(O->getFileName(), SOrErr.takeError());
Davide Italianoccd53fe2015-08-05 07:18:31 +0000894 S = *SOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000895 } else {
896 section_iterator SI = O->section_begin();
897 // Adjust for the fact that sections are 1-indexed.
Kevin Enderby3fc91882017-11-03 21:32:44 +0000898 if (Val == 0) {
899 fmt << "0 (?,?)";
900 return;
901 }
902 uint32_t i = Val - 1;
903 while (i != 0 && SI != O->section_end()) {
904 i--;
905 advance(SI, 1);
906 }
907 if (SI == O->section_end())
908 fmt << Val << " (?,?)";
909 else
910 SI->getName(S);
Rafael Espindola37070a52015-06-03 04:48:06 +0000911 }
912
913 fmt << S;
914}
915
Sam Clegg4df5d762017-06-27 20:40:53 +0000916static std::error_code getRelocationValueString(const WasmObjectFile *Obj,
917 const RelocationRef &RelRef,
918 SmallVectorImpl<char> &Result) {
919 const wasm::WasmRelocation& Rel = Obj->getWasmRelocation(RelRef);
920 std::string fmtbuf;
921 raw_string_ostream fmt(fmtbuf);
922 fmt << Rel.Index << (Rel.Addend < 0 ? "" : "+") << Rel.Addend;
923 fmt.flush();
924 Result.append(fmtbuf.begin(), fmtbuf.end());
925 return std::error_code();
926}
927
Rafael Espindola37070a52015-06-03 04:48:06 +0000928static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
929 const RelocationRef &RelRef,
930 SmallVectorImpl<char> &Result) {
931 DataRefImpl Rel = RelRef.getRawDataRefImpl();
932 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
933
934 unsigned Arch = Obj->getArch();
935
936 std::string fmtbuf;
937 raw_string_ostream fmt(fmtbuf);
938 unsigned Type = Obj->getAnyRelocationType(RE);
939 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
940
941 // Determine any addends that should be displayed with the relocation.
942 // These require decoding the relocation type, which is triple-specific.
943
944 // X86_64 has entirely custom relocation types.
945 if (Arch == Triple::x86_64) {
946 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
947
948 switch (Type) {
949 case MachO::X86_64_RELOC_GOT_LOAD:
950 case MachO::X86_64_RELOC_GOT: {
951 printRelocationTargetName(Obj, RE, fmt);
952 fmt << "@GOT";
953 if (isPCRel)
954 fmt << "PCREL";
955 break;
956 }
957 case MachO::X86_64_RELOC_SUBTRACTOR: {
958 DataRefImpl RelNext = Rel;
959 Obj->moveRelocationNext(RelNext);
960 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
961
962 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
963 // X86_64_RELOC_UNSIGNED.
964 // NOTE: Scattered relocations don't exist on x86_64.
965 unsigned RType = Obj->getAnyRelocationType(RENext);
966 if (RType != MachO::X86_64_RELOC_UNSIGNED)
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000967 report_error(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
968 "X86_64_RELOC_SUBTRACTOR.");
Rafael Espindola37070a52015-06-03 04:48:06 +0000969
970 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
971 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
972 printRelocationTargetName(Obj, RENext, fmt);
973 fmt << "-";
974 printRelocationTargetName(Obj, RE, fmt);
975 break;
976 }
977 case MachO::X86_64_RELOC_TLV:
978 printRelocationTargetName(Obj, RE, fmt);
979 fmt << "@TLV";
980 if (isPCRel)
981 fmt << "P";
982 break;
983 case MachO::X86_64_RELOC_SIGNED_1:
984 printRelocationTargetName(Obj, RE, fmt);
985 fmt << "-1";
986 break;
987 case MachO::X86_64_RELOC_SIGNED_2:
988 printRelocationTargetName(Obj, RE, fmt);
989 fmt << "-2";
990 break;
991 case MachO::X86_64_RELOC_SIGNED_4:
992 printRelocationTargetName(Obj, RE, fmt);
993 fmt << "-4";
994 break;
995 default:
996 printRelocationTargetName(Obj, RE, fmt);
997 break;
998 }
999 // X86 and ARM share some relocation types in common.
1000 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
1001 Arch == Triple::ppc) {
1002 // Generic relocation types...
1003 switch (Type) {
1004 case MachO::GENERIC_RELOC_PAIR: // prints no info
Rui Ueyama7d099192015-06-09 15:20:42 +00001005 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +00001006 case MachO::GENERIC_RELOC_SECTDIFF: {
1007 DataRefImpl RelNext = Rel;
1008 Obj->moveRelocationNext(RelNext);
1009 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
1010
1011 // X86 sect diff's must be followed by a relocation of type
1012 // GENERIC_RELOC_PAIR.
1013 unsigned RType = Obj->getAnyRelocationType(RENext);
1014
1015 if (RType != MachO::GENERIC_RELOC_PAIR)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001016 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
1017 "GENERIC_RELOC_SECTDIFF.");
Rafael Espindola37070a52015-06-03 04:48:06 +00001018
1019 printRelocationTargetName(Obj, RE, fmt);
1020 fmt << "-";
1021 printRelocationTargetName(Obj, RENext, fmt);
1022 break;
1023 }
1024 }
1025
1026 if (Arch == Triple::x86 || Arch == Triple::ppc) {
1027 switch (Type) {
1028 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
1029 DataRefImpl RelNext = Rel;
1030 Obj->moveRelocationNext(RelNext);
1031 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
1032
1033 // X86 sect diff's must be followed by a relocation of type
1034 // GENERIC_RELOC_PAIR.
1035 unsigned RType = Obj->getAnyRelocationType(RENext);
1036 if (RType != MachO::GENERIC_RELOC_PAIR)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001037 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
1038 "GENERIC_RELOC_LOCAL_SECTDIFF.");
Rafael Espindola37070a52015-06-03 04:48:06 +00001039
1040 printRelocationTargetName(Obj, RE, fmt);
1041 fmt << "-";
1042 printRelocationTargetName(Obj, RENext, fmt);
1043 break;
1044 }
1045 case MachO::GENERIC_RELOC_TLV: {
1046 printRelocationTargetName(Obj, RE, fmt);
1047 fmt << "@TLV";
1048 if (IsPCRel)
1049 fmt << "P";
1050 break;
1051 }
1052 default:
1053 printRelocationTargetName(Obj, RE, fmt);
1054 }
1055 } else { // ARM-specific relocations
1056 switch (Type) {
1057 case MachO::ARM_RELOC_HALF:
1058 case MachO::ARM_RELOC_HALF_SECTDIFF: {
1059 // Half relocations steal a bit from the length field to encode
1060 // whether this is an upper16 or a lower16 relocation.
Martin Storsjofa5183b2017-07-13 05:54:08 +00001061 bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
Rafael Espindola37070a52015-06-03 04:48:06 +00001062
1063 if (isUpper)
1064 fmt << ":upper16:(";
1065 else
1066 fmt << ":lower16:(";
1067 printRelocationTargetName(Obj, RE, fmt);
1068
1069 DataRefImpl RelNext = Rel;
1070 Obj->moveRelocationNext(RelNext);
1071 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
1072
1073 // ARM half relocs must be followed by a relocation of type
1074 // ARM_RELOC_PAIR.
1075 unsigned RType = Obj->getAnyRelocationType(RENext);
1076 if (RType != MachO::ARM_RELOC_PAIR)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001077 report_error(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
1078 "ARM_RELOC_HALF");
Rafael Espindola37070a52015-06-03 04:48:06 +00001079
1080 // NOTE: The half of the target virtual address is stashed in the
1081 // address field of the secondary relocation, but we can't reverse
1082 // engineer the constant offset from it without decoding the movw/movt
1083 // instruction to find the other half in its immediate field.
1084
1085 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
1086 // symbol/section pointer of the follow-on relocation.
1087 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1088 fmt << "-";
1089 printRelocationTargetName(Obj, RENext, fmt);
1090 }
1091
1092 fmt << ")";
1093 break;
1094 }
1095 default: { printRelocationTargetName(Obj, RE, fmt); }
1096 }
1097 }
1098 } else
1099 printRelocationTargetName(Obj, RE, fmt);
1100
1101 fmt.flush();
1102 Result.append(fmtbuf.begin(), fmtbuf.end());
Rui Ueyama7d099192015-06-09 15:20:42 +00001103 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +00001104}
1105
1106static std::error_code getRelocationValueString(const RelocationRef &Rel,
1107 SmallVectorImpl<char> &Result) {
Rafael Espindola854038e2015-06-26 14:51:16 +00001108 const ObjectFile *Obj = Rel.getObject();
Rafael Espindola37070a52015-06-03 04:48:06 +00001109 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
1110 return getRelocationValueString(ELF, Rel, Result);
1111 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
1112 return getRelocationValueString(COFF, Rel, Result);
Sam Clegg4df5d762017-06-27 20:40:53 +00001113 if (auto *Wasm = dyn_cast<WasmObjectFile>(Obj))
1114 return getRelocationValueString(Wasm, Rel, Result);
1115 if (auto *MachO = dyn_cast<MachOObjectFile>(Obj))
1116 return getRelocationValueString(MachO, Rel, Result);
1117 llvm_unreachable("unknown object file format");
Rafael Espindola37070a52015-06-03 04:48:06 +00001118}
1119
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001120/// @brief Indicates whether this relocation should hidden when listing
1121/// relocations, usually because it is the trailing part of a multipart
1122/// relocation that will be printed as part of the leading relocation.
1123static bool getHidden(RelocationRef RelRef) {
1124 const ObjectFile *Obj = RelRef.getObject();
1125 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
1126 if (!MachO)
1127 return false;
1128
1129 unsigned Arch = MachO->getArch();
1130 DataRefImpl Rel = RelRef.getRawDataRefImpl();
1131 uint64_t Type = MachO->getRelocationType(Rel);
1132
1133 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
1134 // is always hidden.
1135 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
1136 if (Type == MachO::GENERIC_RELOC_PAIR)
1137 return true;
1138 } else if (Arch == Triple::x86_64) {
1139 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
1140 // an X86_64_RELOC_SUBTRACTOR.
1141 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
1142 DataRefImpl RelPrev = Rel;
1143 RelPrev.d.a--;
1144 uint64_t PrevType = MachO->getRelocationType(RelPrev);
1145 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
1146 return true;
1147 }
1148 }
1149
1150 return false;
1151}
1152
Sam Koltonc05d7782016-08-17 10:17:57 +00001153static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) {
1154 assert(Obj->isELF());
1155 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1156 return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1157 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1158 return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1159 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1160 return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1161 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1162 return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1163 llvm_unreachable("Unsupported binary format");
1164}
1165
Sam Parker5fba45a2017-02-08 09:44:18 +00001166template <class ELFT> static void
1167addDynamicElfSymbols(const ELFObjectFile<ELFT> *Obj,
1168 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1169 for (auto Symbol : Obj->getDynamicSymbolIterators()) {
1170 uint8_t SymbolType = Symbol.getELFType();
1171 if (SymbolType != ELF::STT_FUNC || Symbol.getSize() == 0)
1172 continue;
1173
1174 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
1175 if (!AddressOrErr)
1176 report_error(Obj->getFileName(), AddressOrErr.takeError());
1177 uint64_t Address = *AddressOrErr;
1178
1179 Expected<StringRef> Name = Symbol.getName();
1180 if (!Name)
1181 report_error(Obj->getFileName(), Name.takeError());
1182 if (Name->empty())
1183 continue;
1184
1185 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1186 if (!SectionOrErr)
1187 report_error(Obj->getFileName(), SectionOrErr.takeError());
1188 section_iterator SecI = *SectionOrErr;
1189 if (SecI == Obj->section_end())
1190 continue;
1191
1192 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1193 }
1194}
1195
1196static void
1197addDynamicElfSymbols(const ObjectFile *Obj,
1198 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1199 assert(Obj->isELF());
1200 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1201 addDynamicElfSymbols(Elf32LEObj, AllSymbols);
1202 else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1203 addDynamicElfSymbols(Elf64LEObj, AllSymbols);
1204 else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1205 addDynamicElfSymbols(Elf32BEObj, AllSymbols);
1206 else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1207 addDynamicElfSymbols(Elf64BEObj, AllSymbols);
1208 else
1209 llvm_unreachable("Unsupported binary format");
1210}
1211
Michael J. Spencer51862b32011-10-13 22:17:18 +00001212static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001213 if (StartAddress > StopAddress)
1214 error("Start address should be less than stop address");
1215
Jim Grosbachaf9aec02012-08-07 17:53:14 +00001216 const Target *TheTarget = getTarget(Obj);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001217
Jack Carter551efd72012-08-28 19:24:49 +00001218 // Package up features to be passed to target/subtarget
Daniel Sanders1d148642016-06-16 09:17:03 +00001219 SubtargetFeatures Features = Obj->getFeatures();
Jack Carter551efd72012-08-28 19:24:49 +00001220 if (MAttrs.size()) {
Jack Carter551efd72012-08-28 19:24:49 +00001221 for (unsigned i = 0; i != MAttrs.size(); ++i)
1222 Features.AddFeature(MAttrs[i]);
Jack Carter551efd72012-08-28 19:24:49 +00001223 }
1224
Ahmed Charles56440fd2014-03-06 05:51:42 +00001225 std::unique_ptr<const MCRegisterInfo> MRI(
1226 TheTarget->createMCRegInfo(TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +00001227 if (!MRI)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001228 report_error(Obj->getFileName(), "no register info for target " +
1229 TripleName);
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001230
1231 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00001232 std::unique_ptr<const MCAsmInfo> AsmInfo(
1233 TheTarget->createMCAsmInfo(*MRI, TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +00001234 if (!AsmInfo)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001235 report_error(Obj->getFileName(), "no assembly info for target " +
1236 TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +00001237 std::unique_ptr<const MCSubtargetInfo> STI(
Daniel Sanders1d148642016-06-16 09:17:03 +00001238 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
Davide Italiano711e4952015-12-17 01:59:50 +00001239 if (!STI)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001240 report_error(Obj->getFileName(), "no subtarget info for target " +
1241 TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +00001242 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
Davide Italiano711e4952015-12-17 01:59:50 +00001243 if (!MII)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001244 report_error(Obj->getFileName(), "no instruction info for target " +
1245 TripleName);
Sam Kolton3381d7a2016-10-06 13:46:08 +00001246 MCObjectFileInfo MOFI;
1247 MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI);
1248 // FIXME: for now initialize MCObjectFileInfo with default values
Rafael Espindola9f929952017-08-02 20:32:26 +00001249 MOFI.InitMCObjectFileInfo(Triple(TripleName), false, Ctx);
Lang Hamesa1bc0f52014-04-15 04:40:56 +00001250
1251 std::unique_ptr<MCDisassembler> DisAsm(
1252 TheTarget->createMCDisassembler(*STI, Ctx));
Davide Italiano711e4952015-12-17 01:59:50 +00001253 if (!DisAsm)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001254 report_error(Obj->getFileName(), "no disassembler for target " +
1255 TripleName);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001256
Ahmed Charles56440fd2014-03-06 05:51:42 +00001257 std::unique_ptr<const MCInstrAnalysis> MIA(
1258 TheTarget->createMCInstrAnalysis(MII.get()));
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001259
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001260 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Daniel Sanders50f17232015-09-15 16:17:27 +00001261 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1262 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
Davide Italiano711e4952015-12-17 01:59:50 +00001263 if (!IP)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001264 report_error(Obj->getFileName(), "no instruction printer for target " +
1265 TripleName);
Colin LeMahieu14ec76e2015-06-07 21:07:17 +00001266 IP->setPrintImmHex(PrintImmHex);
Colin LeMahieu35436a22015-05-29 14:48:25 +00001267 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001268
Greg Fitzgerald18432272014-03-20 22:55:15 +00001269 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
1270 "\t\t\t%08" PRIx64 ": ";
1271
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001272 SourcePrinter SP(Obj, TheTarget->getName());
1273
Mark Seaborn0929d3d2014-01-25 17:38:19 +00001274 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
1275 // in RelocSecs contain the relocations for section S.
Rafael Espindola4453e42942014-06-13 03:07:50 +00001276 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +00001277 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001278 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001279 section_iterator Sec2 = Section.getRelocatedSection();
Rafael Espindolab5155a52014-02-10 20:24:04 +00001280 if (Sec2 != Obj->section_end())
Alexey Samsonov48803e52014-03-13 14:37:36 +00001281 SectionRelocMap[*Sec2].push_back(Section);
Mark Seaborn0929d3d2014-01-25 17:38:19 +00001282 }
1283
David Majnemer81afca62015-07-07 22:06:59 +00001284 // Create a mapping from virtual address to symbol name. This is used to
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001285 // pretty print the symbols while disassembling.
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001286 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
1287 for (const SymbolRef &Symbol : Obj->symbols()) {
Kevin Enderby931cb652016-06-24 18:24:42 +00001288 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001289 if (!AddressOrErr)
1290 report_error(Obj->getFileName(), AddressOrErr.takeError());
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001291 uint64_t Address = *AddressOrErr;
David Majnemer2603a8fa2015-07-09 18:11:40 +00001292
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001293 Expected<StringRef> Name = Symbol.getName();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001294 if (!Name)
1295 report_error(Obj->getFileName(), Name.takeError());
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001296 if (Name->empty())
1297 continue;
David Majnemer81afca62015-07-07 22:06:59 +00001298
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001299 Expected<section_iterator> SectionOrErr = Symbol.getSection();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001300 if (!SectionOrErr)
1301 report_error(Obj->getFileName(), SectionOrErr.takeError());
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001302 section_iterator SecI = *SectionOrErr;
1303 if (SecI == Obj->section_end())
1304 continue;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001305
Sam Koltonc05d7782016-08-17 10:17:57 +00001306 uint8_t SymbolType = ELF::STT_NOTYPE;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001307 if (Obj->isELF())
Sam Koltonc05d7782016-08-17 10:17:57 +00001308 SymbolType = getElfSymbolType(Obj, Symbol);
David Majnemer81afca62015-07-07 22:06:59 +00001309
Sam Koltonc05d7782016-08-17 10:17:57 +00001310 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1311
David Majnemer81afca62015-07-07 22:06:59 +00001312 }
Sam Parker5fba45a2017-02-08 09:44:18 +00001313 if (AllSymbols.empty() && Obj->isELF())
1314 addDynamicElfSymbols(Obj, AllSymbols);
David Majnemer81afca62015-07-07 22:06:59 +00001315
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001316 // Create a mapping from virtual address to section.
1317 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1318 for (SectionRef Sec : Obj->sections())
1319 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1320 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
1321
1322 // Linked executables (.exe and .dll files) typically don't include a real
1323 // symbol table but they might contain an export table.
1324 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
1325 for (const auto &ExportEntry : COFFObj->export_directories()) {
1326 StringRef Name;
1327 error(ExportEntry.getSymbolName(Name));
1328 if (Name.empty())
1329 continue;
1330 uint32_t RVA;
1331 error(ExportEntry.getExportRVA(RVA));
1332
1333 uint64_t VA = COFFObj->getImageBase() + RVA;
1334 auto Sec = std::upper_bound(
1335 SectionAddresses.begin(), SectionAddresses.end(), VA,
1336 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
1337 return LHS < RHS.first;
1338 });
1339 if (Sec != SectionAddresses.begin())
1340 --Sec;
1341 else
1342 Sec = SectionAddresses.end();
1343
1344 if (Sec != SectionAddresses.end())
Sam Koltonc05d7782016-08-17 10:17:57 +00001345 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001346 }
1347 }
1348
1349 // Sort all the symbols, this allows us to use a simple binary search to find
1350 // a symbol near an address.
1351 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1352 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
1353
Colin LeMahieu77804be2015-07-29 15:45:39 +00001354 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Colin LeMahieuf34933e2015-07-23 20:58:49 +00001355 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
Mark Seaborneb03ac52014-01-25 00:32:01 +00001356 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +00001357
Rafael Espindola80291272014-10-08 15:28:58 +00001358 uint64_t SectionAddr = Section.getAddress();
1359 uint64_t SectSize = Section.getSize();
David Majnemer185b5b12014-11-11 09:58:25 +00001360 if (!SectSize)
1361 continue;
Simon Atanasyan2b614e12014-02-24 22:12:11 +00001362
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001363 // Get the list of all the symbols in this section.
1364 SectionSymbolsTy &Symbols = AllSymbols[Section];
Davide Italianof0706882015-10-01 21:57:09 +00001365 std::vector<uint64_t> DataMappingSymsAddr;
1366 std::vector<uint64_t> TextMappingSymsAddr;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001367 if (isArmElf(Obj)) {
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001368 for (const auto &Symb : Symbols) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001369 uint64_t Address = std::get<0>(Symb);
1370 StringRef Name = std::get<1>(Symb);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001371 if (Name.startswith("$d"))
David Majnemer153722d2015-11-18 04:35:32 +00001372 DataMappingSymsAddr.push_back(Address - SectionAddr);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001373 if (Name.startswith("$x"))
David Majnemer153722d2015-11-18 04:35:32 +00001374 TextMappingSymsAddr.push_back(Address - SectionAddr);
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001375 if (Name.startswith("$a"))
1376 TextMappingSymsAddr.push_back(Address - SectionAddr);
1377 if (Name.startswith("$t"))
1378 TextMappingSymsAddr.push_back(Address - SectionAddr);
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001379 }
1380 }
1381
Mandeep Singh Grang8db564e2018-04-01 21:24:53 +00001382 llvm::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end());
1383 llvm::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end());
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001384
Sam Kolton3381d7a2016-10-06 13:46:08 +00001385 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1386 // AMDGPU disassembler uses symbolizer for printing labels
1387 std::unique_ptr<MCRelocationInfo> RelInfo(
1388 TheTarget->createMCRelocationInfo(TripleName, Ctx));
1389 if (RelInfo) {
1390 std::unique_ptr<MCSymbolizer> Symbolizer(
1391 TheTarget->createMCSymbolizer(
1392 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1393 DisAsm->setSymbolizer(std::move(Symbolizer));
1394 }
1395 }
1396
Michael J. Spencer51862b32011-10-13 22:17:18 +00001397 // Make a list of all the relocations for this section.
1398 std::vector<RelocationRef> Rels;
1399 if (InlineRelocs) {
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001400 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
1401 for (const RelocationRef &Reloc : RelocSec.relocations()) {
1402 Rels.push_back(Reloc);
1403 }
Michael J. Spencer51862b32011-10-13 22:17:18 +00001404 }
1405 }
1406
1407 // Sort relocations by address.
Mandeep Singh Grang8db564e2018-04-01 21:24:53 +00001408 llvm::sort(Rels.begin(), Rels.end(), RelocAddressLess);
Michael J. Spencer51862b32011-10-13 22:17:18 +00001409
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001410 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +00001411 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001412 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +00001413 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001414 }
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001415 StringRef SectionName;
1416 error(Section.getName(SectionName));
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001417
Rafael Espindola7884c952015-06-04 15:01:05 +00001418 // If the section has no symbol at the start, just insert a dummy one.
Sam Koltonc05d7782016-08-17 10:17:57 +00001419 if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) {
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001420 Symbols.insert(
1421 Symbols.begin(),
1422 std::make_tuple(SectionAddr, SectionName,
1423 Section.isText() ? ELF::STT_FUNC : ELF::STT_OBJECT));
Sam Koltonc05d7782016-08-17 10:17:57 +00001424 }
Alp Tokere69170a2014-06-26 22:52:05 +00001425
1426 SmallString<40> Comments;
1427 raw_svector_ostream CommentStream(Comments);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001428
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001429 StringRef BytesStr;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001430 error(Section.getContents(BytesStr));
Aaron Ballman106fd7b2014-11-12 14:01:17 +00001431 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1432 BytesStr.size());
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001433
Michael J. Spencer2670c252011-01-20 06:39:06 +00001434 uint64_t Size;
1435 uint64_t Index;
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001436 bool PrintedSection = false;
Michael J. Spencer2670c252011-01-20 06:39:06 +00001437
Michael J. Spencer51862b32011-10-13 22:17:18 +00001438 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
1439 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001440 // Disassemble symbol by symbol.
1441 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001442 uint64_t Start = std::get<0>(Symbols[si]) - SectionAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001443 // The end is either the section end or the beginning of the next
1444 // symbol.
1445 uint64_t End =
Sam Koltonc05d7782016-08-17 10:17:57 +00001446 (si == se - 1) ? SectSize : std::get<0>(Symbols[si + 1]) - SectionAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001447 // Don't try to disassemble beyond the end of section contents.
1448 if (End > SectSize)
1449 End = SectSize;
Rafael Espindolae45c7402014-08-17 16:31:39 +00001450 // If this symbol has the same address as the next symbol, then skip it.
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001451 if (Start >= End)
Michael J. Spenceree84f642011-10-13 20:37:08 +00001452 continue;
1453
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001454 // Check if we need to skip symbol
1455 // Skip if the symbol's data is not between StartAddress and StopAddress
1456 if (End + SectionAddr < StartAddress ||
1457 Start + SectionAddr > StopAddress) {
1458 continue;
1459 }
1460
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001461 /// Skip if user requested specific symbols and this is not in the list
1462 if (!DisasmFuncsSet.empty() &&
1463 !DisasmFuncsSet.count(std::get<1>(Symbols[si])))
1464 continue;
1465
1466 if (!PrintedSection) {
1467 PrintedSection = true;
1468 outs() << "Disassembly of section ";
1469 if (!SegmentName.empty())
1470 outs() << SegmentName << ",";
1471 outs() << SectionName << ':';
1472 }
1473
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001474 // Stop disassembly at the stop address specified
1475 if (End + SectionAddr > StopAddress)
1476 End = StopAddress - SectionAddr;
1477
Valery Pykhtinde048052016-04-07 07:24:01 +00001478 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001479 if (std::get<2>(Symbols[si]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1480 // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)
1481 Start += 256;
1482 }
1483 if (si == se - 1 ||
1484 std::get<2>(Symbols[si + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1485 // cut trailing zeroes at the end of kernel
1486 // cut up to 256 bytes
1487 const uint64_t EndAlign = 256;
1488 const auto Limit = End - (std::min)(EndAlign, End - Start);
1489 while (End > Limit &&
1490 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1491 End -= 4;
1492 }
Valery Pykhtinde048052016-04-07 07:24:01 +00001493 }
1494
Sam Koltonc05d7782016-08-17 10:17:57 +00001495 outs() << '\n' << std::get<1>(Symbols[si]) << ":\n";
Michael J. Spencer2670c252011-01-20 06:39:06 +00001496
Francis Visoiu Mistrih18346822018-04-19 17:02:57 +00001497 // Don't print raw contents of a virtual section. A virtual section
1498 // doesn't have any contents in the file.
1499 if (Section.isVirtual()) {
1500 outs() << "...\n";
1501 continue;
1502 }
1503
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001504#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +00001505 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001506#else
Mark Seaborneb03ac52014-01-25 00:32:01 +00001507 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001508#endif
1509
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001510 for (Index = Start; Index < End; Index += Size) {
1511 MCInst Inst;
Owen Andersona0c3b972011-09-15 23:38:46 +00001512
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001513 if (Index + SectionAddr < StartAddress ||
1514 Index + SectionAddr > StopAddress) {
1515 // skip byte by byte till StartAddress is reached
1516 Size = 1;
1517 continue;
1518 }
Davide Italianof0706882015-10-01 21:57:09 +00001519 // AArch64 ELF binaries can interleave data and text in the
1520 // same section. We rely on the markers introduced to
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001521 // understand what we need to dump. If the data marker is within a
1522 // function, it is denoted as a word/short etc
1523 if (isArmElf(Obj) && std::get<2>(Symbols[si]) != ELF::STT_OBJECT &&
1524 !DisassembleAll) {
Davide Italianof0706882015-10-01 21:57:09 +00001525 uint64_t Stride = 0;
1526
1527 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1528 DataMappingSymsAddr.end(), Index);
1529 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1530 // Switch to data.
1531 while (Index < End) {
1532 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1533 outs() << "\t";
1534 if (Index + 4 <= End) {
1535 Stride = 4;
1536 dumpBytes(Bytes.slice(Index, 4), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001537 outs() << "\t.word\t";
1538 uint32_t Data = 0;
1539 if (Obj->isLittleEndian()) {
1540 const auto Word =
1541 reinterpret_cast<const support::ulittle32_t *>(
1542 Bytes.data() + Index);
1543 Data = *Word;
1544 } else {
1545 const auto Word = reinterpret_cast<const support::ubig32_t *>(
1546 Bytes.data() + Index);
1547 Data = *Word;
1548 }
1549 outs() << "0x" << format("%08" PRIx32, Data);
Davide Italianof0706882015-10-01 21:57:09 +00001550 } else if (Index + 2 <= End) {
1551 Stride = 2;
1552 dumpBytes(Bytes.slice(Index, 2), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001553 outs() << "\t\t.short\t";
1554 uint16_t Data = 0;
1555 if (Obj->isLittleEndian()) {
1556 const auto Short =
1557 reinterpret_cast<const support::ulittle16_t *>(
1558 Bytes.data() + Index);
1559 Data = *Short;
1560 } else {
1561 const auto Short =
1562 reinterpret_cast<const support::ubig16_t *>(Bytes.data() +
1563 Index);
1564 Data = *Short;
1565 }
1566 outs() << "0x" << format("%04" PRIx16, Data);
Davide Italianof0706882015-10-01 21:57:09 +00001567 } else {
1568 Stride = 1;
1569 dumpBytes(Bytes.slice(Index, 1), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001570 outs() << "\t\t.byte\t";
1571 outs() << "0x" << format("%02" PRIx8, Bytes.slice(Index, 1)[0]);
Davide Italianof0706882015-10-01 21:57:09 +00001572 }
1573 Index += Stride;
1574 outs() << "\n";
1575 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1576 TextMappingSymsAddr.end(), Index);
1577 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1578 break;
1579 }
1580 }
1581 }
1582
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001583 // If there is a data symbol inside an ELF text section and we are only
1584 // disassembling text (applicable all architectures),
1585 // we are in a situation where we must print the data and not
1586 // disassemble it.
1587 if (Obj->isELF() && std::get<2>(Symbols[si]) == ELF::STT_OBJECT &&
1588 !DisassembleAll && Section.isText()) {
1589 // print out data up to 8 bytes at a time in hex and ascii
1590 uint8_t AsciiData[9] = {'\0'};
1591 uint8_t Byte;
1592 int NumBytes = 0;
1593
1594 for (Index = Start; Index < End; Index += 1) {
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001595 if (((SectionAddr + Index) < StartAddress) ||
1596 ((SectionAddr + Index) > StopAddress))
1597 continue;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001598 if (NumBytes == 0) {
1599 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1600 outs() << "\t";
1601 }
1602 Byte = Bytes.slice(Index)[0];
1603 outs() << format(" %02x", Byte);
1604 AsciiData[NumBytes] = isprint(Byte) ? Byte : '.';
1605
1606 uint8_t IndentOffset = 0;
1607 NumBytes++;
1608 if (Index == End - 1 || NumBytes > 8) {
1609 // Indent the space for less than 8 bytes data.
1610 // 2 spaces for byte and one for space between bytes
1611 IndentOffset = 3 * (8 - NumBytes);
1612 for (int Excess = 8 - NumBytes; Excess < 8; Excess++)
1613 AsciiData[Excess] = '\0';
1614 NumBytes = 8;
1615 }
1616 if (NumBytes == 8) {
1617 AsciiData[8] = '\0';
1618 outs() << std::string(IndentOffset, ' ') << " ";
1619 outs() << reinterpret_cast<char *>(AsciiData);
1620 outs() << '\n';
1621 NumBytes = 0;
1622 }
1623 }
1624 }
Davide Italianof0706882015-10-01 21:57:09 +00001625 if (Index >= End)
1626 break;
1627
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001628 // Disassemble a real instruction or a data when disassemble all is
1629 // provided
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001630 bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1631 SectionAddr + Index, DebugOut,
1632 CommentStream);
1633 if (Size == 0)
1634 Size = 1;
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001635
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001636 PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001637 Bytes.slice(Index, Size), SectionAddr + Index, outs(), "",
1638 *STI, &SP);
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001639 outs() << CommentStream.str();
1640 Comments.clear();
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001641
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001642 // Try to resolve the target of a call, tail call, etc. to a specific
1643 // symbol.
1644 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1645 MIA->isConditionalBranch(Inst))) {
1646 uint64_t Target;
1647 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1648 // In a relocatable object, the target's section must reside in
1649 // the same section as the call instruction or it is accessed
1650 // through a relocation.
1651 //
1652 // In a non-relocatable object, the target may be in any section.
1653 //
1654 // N.B. We don't walk the relocations in the relocatable case yet.
1655 auto *TargetSectionSymbols = &Symbols;
1656 if (!Obj->isRelocatableObject()) {
1657 auto SectionAddress = std::upper_bound(
1658 SectionAddresses.begin(), SectionAddresses.end(), Target,
1659 [](uint64_t LHS,
1660 const std::pair<uint64_t, SectionRef> &RHS) {
1661 return LHS < RHS.first;
1662 });
1663 if (SectionAddress != SectionAddresses.begin()) {
1664 --SectionAddress;
1665 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1666 } else {
1667 TargetSectionSymbols = nullptr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001668 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001669 }
David Majnemer2603a8fa2015-07-09 18:11:40 +00001670
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001671 // Find the first symbol in the section whose offset is less than
1672 // or equal to the target.
1673 if (TargetSectionSymbols) {
1674 auto TargetSym = std::upper_bound(
1675 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1676 Target, [](uint64_t LHS,
Sam Koltonc05d7782016-08-17 10:17:57 +00001677 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1678 return LHS < std::get<0>(RHS);
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001679 });
1680 if (TargetSym != TargetSectionSymbols->begin()) {
1681 --TargetSym;
1682 uint64_t TargetAddress = std::get<0>(*TargetSym);
1683 StringRef TargetName = std::get<1>(*TargetSym);
1684 outs() << " <" << TargetName;
1685 uint64_t Disp = Target - TargetAddress;
1686 if (Disp)
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00001687 outs() << "+0x" << Twine::utohexstr(Disp);
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001688 outs() << '>';
David Majnemer81afca62015-07-07 22:06:59 +00001689 }
1690 }
1691 }
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001692 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001693 outs() << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001694
1695 // Print relocation for instruction.
1696 while (rel_cur != rel_end) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001697 bool hidden = getHidden(*rel_cur);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001698 uint64_t addr = rel_cur->getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +00001699 SmallString<16> name;
1700 SmallString<32> val;
Owen Andersonfa3e5202011-10-25 20:35:53 +00001701
1702 // If this relocation is hidden, skip it.
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001703 if (hidden || ((SectionAddr + addr) < StartAddress)) {
1704 ++rel_cur;
1705 continue;
1706 }
Owen Andersonfa3e5202011-10-25 20:35:53 +00001707
Michael J. Spencer51862b32011-10-13 22:17:18 +00001708 // Stop when rel_cur's address is past the current instruction.
Owen Andersonf20e3e52011-10-25 20:15:39 +00001709 if (addr >= Index + Size) break;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001710 rel_cur->getTypeName(name);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001711 error(getRelocationValueString(*rel_cur, val));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001712 outs() << format(Fmt.data(), SectionAddr + addr) << name
Benjamin Kramer82803112012-03-10 02:04:38 +00001713 << "\t" << val << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001714 ++rel_cur;
1715 }
Benjamin Kramer87ee76c2011-07-20 19:37:35 +00001716 }
Michael J. Spencer2670c252011-01-20 06:39:06 +00001717 }
1718 }
1719}
1720
Kevin Enderby98da6132015-01-20 21:47:46 +00001721void llvm::PrintRelocations(const ObjectFile *Obj) {
Greg Fitzgerald18432272014-03-20 22:55:15 +00001722 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1723 "%08" PRIx64;
Rafael Espindola9219fe72016-03-21 20:59:15 +00001724 // Regular objdump doesn't print relocations in non-relocatable object
1725 // files.
1726 if (!Obj->isRelocatableObject())
1727 return;
Rafael Espindolac66d7612014-08-17 19:09:37 +00001728
Colin LeMahieu77804be2015-07-29 15:45:39 +00001729 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001730 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001731 continue;
1732 StringRef secname;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001733 error(Section.getName(secname));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001734 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001735 for (const RelocationRef &Reloc : Section.relocations()) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001736 bool hidden = getHidden(Reloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001737 uint64_t address = Reloc.getOffset();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001738 SmallString<32> relocname;
1739 SmallString<32> valuestr;
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001740 if (address < StartAddress || address > StopAddress || hidden)
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001741 continue;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001742 Reloc.getTypeName(relocname);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001743 error(getRelocationValueString(Reloc, valuestr));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001744 outs() << format(Fmt.data(), address) << " " << relocname << " "
1745 << valuestr << "\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001746 }
1747 outs() << "\n";
1748 }
1749}
1750
Kevin Enderby98da6132015-01-20 21:47:46 +00001751void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001752 outs() << "Sections:\n"
1753 "Idx Name Size Address Type\n";
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001754 unsigned i = 0;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001755 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001756 StringRef Name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001757 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001758 uint64_t Address = Section.getAddress();
1759 uint64_t Size = Section.getSize();
1760 bool Text = Section.isText();
1761 bool Data = Section.isData();
1762 bool BSS = Section.isBSS();
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001763 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +00001764 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
Alexey Samsonov48803e52014-03-13 14:37:36 +00001765 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1766 Name.str().c_str(), Size, Address, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001767 ++i;
1768 }
1769}
1770
Kevin Enderby98da6132015-01-20 21:47:46 +00001771void llvm::PrintSectionContents(const ObjectFile *Obj) {
Rafael Espindola4453e42942014-06-13 03:07:50 +00001772 std::error_code EC;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001773 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001774 StringRef Name;
1775 StringRef Contents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001776 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001777 uint64_t BaseAddr = Section.getAddress();
David Majnemer185b5b12014-11-11 09:58:25 +00001778 uint64_t Size = Section.getSize();
1779 if (!Size)
1780 continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001781
1782 outs() << "Contents of section " << Name << ":\n";
David Majnemer185b5b12014-11-11 09:58:25 +00001783 if (Section.isBSS()) {
Alexey Samsonov209095c2013-04-16 10:53:11 +00001784 outs() << format("<skipping contents of bss section at [%04" PRIx64
David Majnemer8f6b04c2014-07-14 16:20:14 +00001785 ", %04" PRIx64 ")>\n",
1786 BaseAddr, BaseAddr + Size);
Alexey Samsonov209095c2013-04-16 10:53:11 +00001787 continue;
1788 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001789
Davide Italianoccd53fe2015-08-05 07:18:31 +00001790 error(Section.getContents(Contents));
David Majnemer8f6b04c2014-07-14 16:20:14 +00001791
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001792 // Dump out the content as hex and printable ascii characters.
1793 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer82803112012-03-10 02:04:38 +00001794 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001795 // Dump line of hex.
1796 for (std::size_t i = 0; i < 16; ++i) {
1797 if (i != 0 && i % 4 == 0)
1798 outs() << ' ';
1799 if (addr + i < end)
1800 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1801 << hexdigit(Contents[addr + i] & 0xF, true);
1802 else
1803 outs() << " ";
1804 }
1805 // Print ascii.
1806 outs() << " ";
1807 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
Guy Benyei83c74e92013-02-12 21:21:59 +00001808 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001809 outs() << Contents[addr + i];
1810 else
1811 outs() << ".";
1812 }
1813 outs() << "\n";
1814 }
1815 }
1816}
1817
Kevin Enderby9acb1092016-05-31 20:35:34 +00001818void llvm::PrintSymbolTable(const ObjectFile *o, StringRef ArchiveName,
1819 StringRef ArchitectureName) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001820 outs() << "SYMBOL TABLE:\n";
1821
Rui Ueyama4e39f712014-03-18 18:58:51 +00001822 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
Davide Italianoe85abf72015-12-20 09:54:34 +00001823 printCOFFSymbolTable(coff);
Rui Ueyama4e39f712014-03-18 18:58:51 +00001824 return;
1825 }
1826 for (const SymbolRef &Symbol : o->symbols()) {
Kevin Enderby931cb652016-06-24 18:24:42 +00001827 Expected<uint64_t> AddressOrError = Symbol.getAddress();
1828 if (!AddressOrError)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001829 report_error(ArchiveName, o->getFileName(), AddressOrError.takeError(),
1830 ArchitectureName);
Rafael Espindolaed067c42015-07-03 18:19:00 +00001831 uint64_t Address = *AddressOrError;
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001832 if ((Address < StartAddress) || (Address > StopAddress))
1833 continue;
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001834 Expected<SymbolRef::Type> TypeOrError = Symbol.getType();
1835 if (!TypeOrError)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001836 report_error(ArchiveName, o->getFileName(), TypeOrError.takeError(),
1837 ArchitectureName);
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00001838 SymbolRef::Type Type = *TypeOrError;
Rui Ueyama4e39f712014-03-18 18:58:51 +00001839 uint32_t Flags = Symbol.getFlags();
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001840 Expected<section_iterator> SectionOrErr = Symbol.getSection();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001841 if (!SectionOrErr)
1842 report_error(ArchiveName, o->getFileName(), SectionOrErr.takeError(),
1843 ArchitectureName);
Rafael Espindola8bab8892015-08-07 23:27:14 +00001844 section_iterator Section = *SectionOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001845 StringRef Name;
1846 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1847 Section->getName(Name);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001848 } else {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001849 Expected<StringRef> NameOrErr = Symbol.getName();
1850 if (!NameOrErr)
Kevin Enderby9acb1092016-05-31 20:35:34 +00001851 report_error(ArchiveName, o->getFileName(), NameOrErr.takeError(),
1852 ArchitectureName);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001853 Name = *NameOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001854 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001855
Rui Ueyama4e39f712014-03-18 18:58:51 +00001856 bool Global = Flags & SymbolRef::SF_Global;
1857 bool Weak = Flags & SymbolRef::SF_Weak;
1858 bool Absolute = Flags & SymbolRef::SF_Absolute;
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001859 bool Common = Flags & SymbolRef::SF_Common;
Davide Italianocd2514d2015-04-30 23:08:53 +00001860 bool Hidden = Flags & SymbolRef::SF_Hidden;
David Meyer1df4b842012-02-28 23:47:53 +00001861
Rui Ueyama4e39f712014-03-18 18:58:51 +00001862 char GlobLoc = ' ';
1863 if (Type != SymbolRef::ST_Unknown)
1864 GlobLoc = Global ? 'g' : 'l';
1865 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1866 ? 'd' : ' ';
1867 char FileFunc = ' ';
1868 if (Type == SymbolRef::ST_File)
1869 FileFunc = 'f';
1870 else if (Type == SymbolRef::ST_Function)
1871 FileFunc = 'F';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001872
Rui Ueyama4e39f712014-03-18 18:58:51 +00001873 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1874 "%08" PRIx64;
Michael J. Spencerd857c1c2013-01-10 22:40:50 +00001875
Rui Ueyama4e39f712014-03-18 18:58:51 +00001876 outs() << format(Fmt, Address) << " "
1877 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1878 << (Weak ? 'w' : ' ') // Weak?
1879 << ' ' // Constructor. Not supported yet.
1880 << ' ' // Warning. Not supported yet.
1881 << ' ' // Indirect reference to another symbol.
1882 << Debug // Debugging (d) or dynamic (D) symbol.
1883 << FileFunc // Name of function (F), file (f) or object (O).
1884 << ' ';
1885 if (Absolute) {
1886 outs() << "*ABS*";
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001887 } else if (Common) {
1888 outs() << "*COM*";
Rui Ueyama4e39f712014-03-18 18:58:51 +00001889 } else if (Section == o->section_end()) {
1890 outs() << "*UND*";
1891 } else {
1892 if (const MachOObjectFile *MachO =
1893 dyn_cast<const MachOObjectFile>(o)) {
1894 DataRefImpl DR = Section->getRawDataRefImpl();
1895 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1896 outs() << SegmentName << ",";
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001897 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00001898 StringRef SectionName;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001899 error(Section->getName(SectionName));
Rui Ueyama4e39f712014-03-18 18:58:51 +00001900 outs() << SectionName;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001901 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001902
1903 outs() << '\t';
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001904 if (Common || isa<ELFObjectFileBase>(o)) {
Rafael Espindoladbb6bd32015-06-25 22:10:04 +00001905 uint64_t Val =
1906 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001907 outs() << format("\t %08" PRIx64 " ", Val);
1908 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001909
Davide Italianocd2514d2015-04-30 23:08:53 +00001910 if (Hidden) {
1911 outs() << ".hidden ";
1912 }
1913 outs() << Name
Rui Ueyama4e39f712014-03-18 18:58:51 +00001914 << '\n';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001915 }
1916}
1917
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001918static void PrintUnwindInfo(const ObjectFile *o) {
1919 outs() << "Unwind info:\n\n";
1920
1921 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1922 printCOFFUnwindInfo(coff);
Tim Northover4bd286a2014-08-01 13:07:19 +00001923 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1924 printMachOUnwindInfo(MachO);
1925 else {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001926 // TODO: Extract DWARF dump tool to objdump.
1927 errs() << "This operation is only currently supported "
Tim Northover4bd286a2014-08-01 13:07:19 +00001928 "for COFF and MachO object files.\n";
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001929 return;
1930 }
1931}
1932
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001933void llvm::printExportsTrie(const ObjectFile *o) {
Nick Kledzikd04bc352014-08-30 00:20:14 +00001934 outs() << "Exports trie:\n";
1935 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1936 printMachOExportsTrie(MachO);
1937 else {
1938 errs() << "This operation is only currently supported "
1939 "for Mach-O executable files.\n";
1940 return;
1941 }
1942}
1943
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001944void llvm::printRebaseTable(ObjectFile *o) {
Nick Kledzikac431442014-09-12 21:34:15 +00001945 outs() << "Rebase table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001946 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzikac431442014-09-12 21:34:15 +00001947 printMachORebaseTable(MachO);
1948 else {
1949 errs() << "This operation is only currently supported "
1950 "for Mach-O executable files.\n";
1951 return;
1952 }
1953}
1954
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001955void llvm::printBindTable(ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001956 outs() << "Bind table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001957 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzik56ebef42014-09-16 01:41:51 +00001958 printMachOBindTable(MachO);
1959 else {
1960 errs() << "This operation is only currently supported "
1961 "for Mach-O executable files.\n";
1962 return;
1963 }
1964}
1965
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001966void llvm::printLazyBindTable(ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001967 outs() << "Lazy bind table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001968 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzik56ebef42014-09-16 01:41:51 +00001969 printMachOLazyBindTable(MachO);
1970 else {
1971 errs() << "This operation is only currently supported "
1972 "for Mach-O executable files.\n";
1973 return;
1974 }
1975}
1976
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001977void llvm::printWeakBindTable(ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001978 outs() << "Weak bind table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001979 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzik56ebef42014-09-16 01:41:51 +00001980 printMachOWeakBindTable(MachO);
1981 else {
1982 errs() << "This operation is only currently supported "
1983 "for Mach-O executable files.\n";
1984 return;
1985 }
1986}
Nick Kledzikac431442014-09-12 21:34:15 +00001987
Adrian Prantl437105a2015-07-08 02:04:15 +00001988/// Dump the raw contents of the __clangast section so the output can be piped
1989/// into llvm-bcanalyzer.
1990void llvm::printRawClangAST(const ObjectFile *Obj) {
1991 if (outs().is_displayed()) {
1992 errs() << "The -raw-clang-ast option will dump the raw binary contents of "
1993 "the clang ast section.\n"
1994 "Please redirect the output to a file or another program such as "
1995 "llvm-bcanalyzer.\n";
1996 return;
1997 }
1998
1999 StringRef ClangASTSectionName("__clangast");
2000 if (isa<COFFObjectFile>(Obj)) {
2001 ClangASTSectionName = "clangast";
2002 }
2003
2004 Optional<object::SectionRef> ClangASTSection;
Colin LeMahieu77804be2015-07-29 15:45:39 +00002005 for (auto Sec : ToolSectionFilter(*Obj)) {
Adrian Prantl437105a2015-07-08 02:04:15 +00002006 StringRef Name;
2007 Sec.getName(Name);
2008 if (Name == ClangASTSectionName) {
2009 ClangASTSection = Sec;
2010 break;
2011 }
2012 }
2013 if (!ClangASTSection)
2014 return;
2015
2016 StringRef ClangASTContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00002017 error(ClangASTSection.getValue().getContents(ClangASTContents));
Adrian Prantl437105a2015-07-08 02:04:15 +00002018 outs().write(ClangASTContents.data(), ClangASTContents.size());
2019}
2020
Sanjoy Das6f567a42015-06-22 18:03:02 +00002021static void printFaultMaps(const ObjectFile *Obj) {
2022 const char *FaultMapSectionName = nullptr;
2023
2024 if (isa<ELFObjectFileBase>(Obj)) {
2025 FaultMapSectionName = ".llvm_faultmaps";
2026 } else if (isa<MachOObjectFile>(Obj)) {
2027 FaultMapSectionName = "__llvm_faultmaps";
2028 } else {
2029 errs() << "This operation is only currently supported "
2030 "for ELF and Mach-O executable files.\n";
2031 return;
2032 }
2033
2034 Optional<object::SectionRef> FaultMapSection;
2035
Colin LeMahieu77804be2015-07-29 15:45:39 +00002036 for (auto Sec : ToolSectionFilter(*Obj)) {
Sanjoy Das6f567a42015-06-22 18:03:02 +00002037 StringRef Name;
2038 Sec.getName(Name);
2039 if (Name == FaultMapSectionName) {
2040 FaultMapSection = Sec;
2041 break;
2042 }
2043 }
2044
2045 outs() << "FaultMap table:\n";
2046
2047 if (!FaultMapSection.hasValue()) {
2048 outs() << "<not found>\n";
2049 return;
2050 }
2051
2052 StringRef FaultMapContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00002053 error(FaultMapSection.getValue().getContents(FaultMapContents));
Sanjoy Das6f567a42015-06-22 18:03:02 +00002054
2055 FaultMapParser FMP(FaultMapContents.bytes_begin(),
2056 FaultMapContents.bytes_end());
2057
2058 outs() << FMP;
2059}
2060
Davide Italiano1bdaa202016-09-18 04:39:15 +00002061static void printPrivateFileHeaders(const ObjectFile *o, bool onlyFirst) {
Kevin Enderby0ae163f2016-01-13 00:25:36 +00002062 if (o->isELF())
Davide Italiano1bdaa202016-09-18 04:39:15 +00002063 return printELFFileHeader(o);
2064 if (o->isCOFF())
2065 return printCOFFFileHeader(o);
Derek Schuff2c6f75d2016-11-30 16:49:11 +00002066 if (o->isWasm())
2067 return printWasmFileHeader(o);
Davide Italiano1bdaa202016-09-18 04:39:15 +00002068 if (o->isMachO()) {
Kevin Enderby0ae163f2016-01-13 00:25:36 +00002069 printMachOFileHeader(o);
Davide Italiano1bdaa202016-09-18 04:39:15 +00002070 if (!onlyFirst)
2071 printMachOLoadCommands(o);
2072 return;
2073 }
Kevin Enderby7fa40c92016-11-16 22:17:38 +00002074 report_error(o->getFileName(), "Invalid/Unsupported object file format");
Rui Ueyamac2bed422013-09-27 21:04:00 +00002075}
2076
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002077static void DumpObject(ObjectFile *o, const Archive *a = nullptr) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002078 StringRef ArchiveName = a != nullptr ? a->getFileName() : "";
Adrian Prantl437105a2015-07-08 02:04:15 +00002079 // Avoid other output when using a raw option.
2080 if (!RawClangAST) {
2081 outs() << '\n';
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002082 if (a)
2083 outs() << a->getFileName() << "(" << o->getFileName() << ")";
2084 else
2085 outs() << o->getFileName();
2086 outs() << ":\tfile format " << o->getFileFormatName() << "\n\n";
Adrian Prantl437105a2015-07-08 02:04:15 +00002087 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00002088
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002089 if (Disassemble)
Michael J. Spencer51862b32011-10-13 22:17:18 +00002090 DisassembleObject(o, Relocations);
2091 if (Relocations && !Disassemble)
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002092 PrintRelocations(o);
Nick Lewyckyfcf84622011-10-10 21:21:34 +00002093 if (SectionHeaders)
2094 PrintSectionHeaders(o);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00002095 if (SectionContents)
2096 PrintSectionContents(o);
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002097 if (SymbolTable)
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002098 PrintSymbolTable(o, ArchiveName);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00002099 if (UnwindInfo)
2100 PrintUnwindInfo(o);
Davide Italiano1bdaa202016-09-18 04:39:15 +00002101 if (PrivateHeaders || FirstPrivateHeader)
2102 printPrivateFileHeaders(o, FirstPrivateHeader);
Nick Kledzikd04bc352014-08-30 00:20:14 +00002103 if (ExportsTrie)
2104 printExportsTrie(o);
Nick Kledzikac431442014-09-12 21:34:15 +00002105 if (Rebase)
2106 printRebaseTable(o);
Nick Kledzik56ebef42014-09-16 01:41:51 +00002107 if (Bind)
2108 printBindTable(o);
2109 if (LazyBind)
2110 printLazyBindTable(o);
2111 if (WeakBind)
2112 printWeakBindTable(o);
Adrian Prantl437105a2015-07-08 02:04:15 +00002113 if (RawClangAST)
2114 printRawClangAST(o);
Sanjoy Das6f567a42015-06-22 18:03:02 +00002115 if (PrintFaultMaps)
2116 printFaultMaps(o);
Igor Laevsky03a670c2016-01-26 15:09:42 +00002117 if (DwarfDumpType != DIDT_Null) {
Rafael Espindolac398e672017-07-19 22:27:28 +00002118 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*o);
Igor Laevsky03a670c2016-01-26 15:09:42 +00002119 // Dump the complete DWARF structure.
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00002120 DIDumpOptions DumpOpts;
2121 DumpOpts.DumpType = DwarfDumpType;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00002122 DICtx->dump(outs(), DumpOpts);
Igor Laevsky03a670c2016-01-26 15:09:42 +00002123 }
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002124}
2125
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00002126static void DumpObject(const COFFImportFile *I, const Archive *A) {
2127 StringRef ArchiveName = A ? A->getFileName() : "";
2128
2129 // Avoid other output when using a raw option.
2130 if (!RawClangAST)
2131 outs() << '\n'
2132 << ArchiveName << "(" << I->getFileName() << ")"
2133 << ":\tfile format COFF-import-file"
2134 << "\n\n";
2135
2136 if (SymbolTable)
2137 printCOFFSymbolTable(I);
2138}
2139
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002140/// @brief Dump each object file in \a a;
2141static void DumpArchive(const Archive *a) {
Mehdi Amini41af4302016-11-11 04:28:40 +00002142 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00002143 for (auto &C : a->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002144 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2145 if (!ChildOrErr) {
2146 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2147 report_error(a->getFileName(), C, std::move(E));
2148 continue;
2149 }
Rafael Espindolaae460022014-06-16 16:08:36 +00002150 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002151 DumpObject(o, a);
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00002152 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
2153 DumpObject(I, a);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002154 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00002155 report_error(a->getFileName(), object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002156 }
Lang Hamesfc209622016-07-14 02:24:01 +00002157 if (Err)
2158 report_error(a->getFileName(), std::move(Err));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002159}
2160
2161/// @brief Open file and figure out how to dump it.
2162static void DumpInput(StringRef file) {
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002163
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002164 // If we are using the Mach-O specific object file parser, then let it parse
2165 // the file and process the command line options. So the -arch flags can
2166 // be used to select specific slices, etc.
2167 if (MachOOpt) {
2168 ParseInputMachO(file);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002169 return;
2170 }
2171
2172 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00002173 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
2174 if (!BinaryOrErr)
Kevin Enderbyb34e3a12016-05-05 17:43:35 +00002175 report_error(file, BinaryOrErr.takeError());
Rafael Espindola48af1c22014-08-19 18:44:46 +00002176 Binary &Binary = *BinaryOrErr.get().getBinary();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002177
Rafael Espindola3f6481d2014-08-01 14:31:55 +00002178 if (Archive *a = dyn_cast<Archive>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002179 DumpArchive(a);
Rafael Espindola3f6481d2014-08-01 14:31:55 +00002180 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002181 DumpObject(o);
Jim Grosbachaf9aec02012-08-07 17:53:14 +00002182 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00002183 report_error(file, object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002184}
2185
Michael J. Spencer2670c252011-01-20 06:39:06 +00002186int main(int argc, char **argv) {
Rui Ueyama197194b2018-04-13 18:26:06 +00002187 InitLLVM X(argc, argv);
Michael J. Spencer2670c252011-01-20 06:39:06 +00002188
2189 // Initialize targets and assembly printers/parsers.
2190 llvm::InitializeAllTargetInfos();
Evan Cheng8c886a42011-07-22 21:58:54 +00002191 llvm::InitializeAllTargetMCs();
Michael J. Spencer2670c252011-01-20 06:39:06 +00002192 llvm::InitializeAllDisassemblers();
2193
Pete Cooper28fb4fc2012-05-03 23:20:10 +00002194 // Register the target printer for --version.
2195 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
2196
Michael J. Spencer2670c252011-01-20 06:39:06 +00002197 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
2198 TripleName = Triple::normalize(TripleName);
2199
2200 ToolName = argv[0];
2201
2202 // Defaults to a.out if no filenames specified.
2203 if (InputFilenames.size() == 0)
2204 InputFilenames.push_back("a.out");
2205
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00002206 if (DisassembleAll || PrintSource || PrintLines)
Colin LeMahieuf34933e2015-07-23 20:58:49 +00002207 Disassemble = true;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002208 if (!Disassemble
2209 && !Relocations
2210 && !SectionHeaders
2211 && !SectionContents
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00002212 && !SymbolTable
Michael J. Spencer209565db2013-01-06 03:56:49 +00002213 && !UnwindInfo
Nick Kledzikd04bc352014-08-30 00:20:14 +00002214 && !PrivateHeaders
Kevin Enderby0ae163f2016-01-13 00:25:36 +00002215 && !FirstPrivateHeader
Nick Kledzikac431442014-09-12 21:34:15 +00002216 && !ExportsTrie
Nick Kledzik56ebef42014-09-16 01:41:51 +00002217 && !Rebase
2218 && !Bind
2219 && !LazyBind
Kevin Enderby131d1772015-01-09 19:22:37 +00002220 && !WeakBind
Adrian Prantl437105a2015-07-08 02:04:15 +00002221 && !RawClangAST
Kevin Enderby13023a12015-01-15 23:19:11 +00002222 && !(UniversalHeaders && MachOOpt)
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00002223 && !(ArchiveHeaders && MachOOpt)
Kevin Enderby69fe98d2015-01-23 18:52:17 +00002224 && !(IndirectSymbols && MachOOpt)
Kevin Enderby9a509442015-01-27 21:28:24 +00002225 && !(DataInCode && MachOOpt)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002226 && !(LinkOptHints && MachOOpt)
Kevin Enderbycd66be52015-03-11 22:06:32 +00002227 && !(InfoPlist && MachOOpt)
Kevin Enderbybc847fa2015-03-16 20:08:09 +00002228 && !(DylibsUsed && MachOOpt)
2229 && !(DylibId && MachOOpt)
Kevin Enderby0fc11822015-04-01 20:57:01 +00002230 && !(ObjcMetaData && MachOOpt)
Colin LeMahieufcc32762015-07-29 19:08:10 +00002231 && !(FilterSections.size() != 0 && MachOOpt)
Igor Laevsky03a670c2016-01-26 15:09:42 +00002232 && !PrintFaultMaps
2233 && DwarfDumpType == DIDT_Null) {
Michael J. Spencer2670c252011-01-20 06:39:06 +00002234 cl::PrintHelpMessage();
Dimitry Andrice4f5d012017-12-18 19:46:56 +00002235 return 2;
2236 }
2237
Rafael Aulerb0e4b912018-03-09 19:13:44 +00002238 DisasmFuncsSet.insert(DisassembleFunctions.begin(),
2239 DisassembleFunctions.end());
2240
Dimitry Andrice4f5d012017-12-18 19:46:56 +00002241 llvm::for_each(InputFilenames, DumpInput);
2242
2243 return EXIT_SUCCESS;
2244}