blob: 6b8a43ea1bdd35d03b673e9a152d6775bb65c33d [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"
Michael J. Spencer2670c252011-01-20 06:39:06 +000023#include "llvm/ADT/Triple.h"
Sanjoy Das3f1bc3b2015-06-23 20:09:03 +000024#include "llvm/CodeGen/FaultMaps.h"
Igor Laevsky03a670c2016-01-26 15:09:42 +000025#include "llvm/DebugInfo/DWARF/DWARFContext.h"
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +000026#include "llvm/DebugInfo/Symbolize/Symbolize.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000027#include "llvm/MC/MCAsmInfo.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000028#include "llvm/MC/MCContext.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000029#include "llvm/MC/MCDisassembler/MCDisassembler.h"
30#include "llvm/MC/MCDisassembler/MCRelocationInfo.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000031#include "llvm/MC/MCInst.h"
32#include "llvm/MC/MCInstPrinter.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000033#include "llvm/MC/MCInstrAnalysis.h"
Craig Topper54bfde72012-04-02 06:09:36 +000034#include "llvm/MC/MCInstrInfo.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000035#include "llvm/MC/MCObjectFileInfo.h"
Jim Grosbachfd93a592012-03-05 19:33:20 +000036#include "llvm/MC/MCRegisterInfo.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000037#include "llvm/MC/MCSubtargetInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000038#include "llvm/Object/Archive.h"
39#include "llvm/Object/COFF.h"
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +000040#include "llvm/Object/COFFImportFile.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000041#include "llvm/Object/ELFObjectFile.h"
Rafael Espindolaa9f810b2012-12-21 03:47:03 +000042#include "llvm/Object/MachO.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000043#include "llvm/Object/ObjectFile.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000044#include "llvm/Support/Casting.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000045#include "llvm/Support/CommandLine.h"
46#include "llvm/Support/Debug.h"
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +000047#include "llvm/Support/Errc.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000048#include "llvm/Support/FileSystem.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000049#include "llvm/Support/Format.h"
Benjamin Kramerbf115312011-07-25 23:04:36 +000050#include "llvm/Support/GraphWriter.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000051#include "llvm/Support/Host.h"
52#include "llvm/Support/ManagedStatic.h"
53#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000054#include "llvm/Support/PrettyStackTrace.h"
55#include "llvm/Support/Signals.h"
56#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>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000064#include <utility>
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +000065#include <unordered_map>
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
Kevin Enderby98da6132015-01-20 21:47:46 +000087cl::opt<bool>
88llvm::Relocations("r", cl::desc("Display the relocation entries in the file"));
Michael J. Spencerba4a3622011-10-08 00:18:30 +000089
Kevin Enderby98da6132015-01-20 21:47:46 +000090cl::opt<bool>
91llvm::SectionContents("s", cl::desc("Display the content of each section"));
Michael J. Spencer4e25c022011-10-17 17:13:22 +000092
Kevin Enderby98da6132015-01-20 21:47:46 +000093cl::opt<bool>
94llvm::SymbolTable("t", cl::desc("Display the symbol table"));
Michael J. Spencerbfa06782011-10-18 19:32:17 +000095
Kevin Enderbye2297dd2015-01-07 21:02:18 +000096cl::opt<bool>
97llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
Nick Kledzikd04bc352014-08-30 00:20:14 +000098
Kevin Enderbye2297dd2015-01-07 21:02:18 +000099cl::opt<bool>
100llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
Nick Kledzikac431442014-09-12 21:34:15 +0000101
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000102cl::opt<bool>
103llvm::Bind("bind", cl::desc("Display mach-o binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000104
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000105cl::opt<bool>
106llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000107
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000108cl::opt<bool>
109llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000110
Adrian Prantl437105a2015-07-08 02:04:15 +0000111cl::opt<bool>
112llvm::RawClangAST("raw-clang-ast",
113 cl::desc("Dump the raw binary contents of the clang AST section"));
114
Nick Kledzik56ebef42014-09-16 01:41:51 +0000115static cl::opt<bool>
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000116MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000117static cl::alias
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000118MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
Benjamin Kramer87ee76c2011-07-20 19:37:35 +0000119
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000120cl::opt<std::string>
121llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
122 "see -version for available targets"));
123
124cl::opt<std::string>
Kevin Enderbyc9595622014-08-06 23:24:41 +0000125llvm::MCPU("mcpu",
126 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
127 cl::value_desc("cpu-name"),
128 cl::init(""));
129
130cl::opt<std::string>
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000131llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
Michael J. Spencer2670c252011-01-20 06:39:06 +0000132 "see -version for available targets"));
133
Kevin Enderby98da6132015-01-20 21:47:46 +0000134cl::opt<bool>
135llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
136 "headers for each section."));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000137static cl::alias
138SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
139 cl::aliasopt(SectionHeaders));
140static cl::alias
141SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
142 cl::aliasopt(SectionHeaders));
Colin LeMahieufcc32762015-07-29 19:08:10 +0000143
Colin LeMahieu77804be2015-07-29 15:45:39 +0000144cl::list<std::string>
Colin LeMahieufcc32762015-07-29 19:08:10 +0000145llvm::FilterSections("section", cl::desc("Operate on the specified sections only. "
146 "With -macho dump segment,section"));
147cl::alias
148static FilterSectionsj("j", cl::desc("Alias for --section"),
149 cl::aliasopt(llvm::FilterSections));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000150
Kevin Enderbyc9595622014-08-06 23:24:41 +0000151cl::list<std::string>
152llvm::MAttrs("mattr",
Jack Carter551efd72012-08-28 19:24:49 +0000153 cl::CommaSeparated,
154 cl::desc("Target specific attributes"),
155 cl::value_desc("a1,+a2,-a3,..."));
156
Kevin Enderbybf246f52014-09-24 23:08:22 +0000157cl::opt<bool>
158llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
159 "instructions, do not print "
160 "the instruction bytes."));
Eli Bendersky3a6808c2012-11-20 22:57:02 +0000161
Kevin Enderby98da6132015-01-20 21:47:46 +0000162cl::opt<bool>
163llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000164
165static cl::alias
166UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
167 cl::aliasopt(UnwindInfo));
168
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000169cl::opt<bool>
170llvm::PrivateHeaders("private-headers",
171 cl::desc("Display format specific file headers"));
Michael J. Spencer209565db2013-01-06 03:56:49 +0000172
Kevin Enderby0ae163f2016-01-13 00:25:36 +0000173cl::opt<bool>
174llvm::FirstPrivateHeader("private-header",
175 cl::desc("Display only the first format specific file "
176 "header"));
177
Michael J. Spencer209565db2013-01-06 03:56:49 +0000178static cl::alias
179PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
180 cl::aliasopt(PrivateHeaders));
181
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000182cl::opt<bool>
183 llvm::PrintImmHex("print-imm-hex",
Colin LeMahieuefe37322016-04-08 18:15:37 +0000184 cl::desc("Use hex format for immediate values"));
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000185
Sanjoy Das6f567a42015-06-22 18:03:02 +0000186cl::opt<bool> PrintFaultMaps("fault-map-section",
187 cl::desc("Display contents of faultmap section"));
188
Igor Laevsky03a670c2016-01-26 15:09:42 +0000189cl::opt<DIDumpType> llvm::DwarfDumpType(
190 "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"),
Mehdi Amini732afdd2016-10-08 19:41:06 +0000191 cl::values(clEnumValN(DIDT_Frames, "frames", ".debug_frame")));
Igor Laevsky03a670c2016-01-26 15:09:42 +0000192
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000193cl::opt<bool> PrintSource(
194 "source",
195 cl::desc(
196 "Display source inlined with disassembly. Implies disassmble object"));
197
198cl::alias PrintSourceShort("S", cl::desc("Alias for -source"),
199 cl::aliasopt(PrintSource));
200
201cl::opt<bool> PrintLines("line-numbers",
202 cl::desc("Display source line numbers with "
203 "disassembly. Implies disassemble object"));
204
205cl::alias PrintLinesShort("l", cl::desc("Alias for -line-numbers"),
206 cl::aliasopt(PrintLines));
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +0000207
208cl::opt<unsigned long long>
209 StartAddress("start-address", cl::desc("Disassemble beginning at address"),
210 cl::value_desc("address"), cl::init(0));
211cl::opt<unsigned long long>
212 StopAddress("stop-address", cl::desc("Stop disassembly at address"),
213 cl::value_desc("address"), cl::init(UINT64_MAX));
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000214static StringRef ToolName;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000215
Colin LeMahieu77804be2015-07-29 15:45:39 +0000216namespace {
Colin LeMahieufcc32762015-07-29 19:08:10 +0000217typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate;
Colin LeMahieu77804be2015-07-29 15:45:39 +0000218
219class SectionFilterIterator {
220public:
221 SectionFilterIterator(FilterPredicate P,
222 llvm::object::section_iterator const &I,
223 llvm::object::section_iterator const &E)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000224 : Predicate(std::move(P)), Iterator(I), End(E) {
Colin LeMahieu77804be2015-07-29 15:45:39 +0000225 ScanPredicate();
226 }
Benjamin Kramerac9257b2015-09-24 14:52:52 +0000227 const llvm::object::SectionRef &operator*() const { return *Iterator; }
Colin LeMahieu77804be2015-07-29 15:45:39 +0000228 SectionFilterIterator &operator++() {
229 ++Iterator;
230 ScanPredicate();
231 return *this;
232 }
233 bool operator!=(SectionFilterIterator const &Other) const {
234 return Iterator != Other.Iterator;
235 }
236
237private:
238 void ScanPredicate() {
Colin LeMahieuda1723f2015-07-29 19:21:13 +0000239 while (Iterator != End && !Predicate(*Iterator)) {
Colin LeMahieu77804be2015-07-29 15:45:39 +0000240 ++Iterator;
241 }
242 }
243 FilterPredicate Predicate;
244 llvm::object::section_iterator Iterator;
245 llvm::object::section_iterator End;
246};
247
248class SectionFilter {
249public:
250 SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000251 : Predicate(std::move(P)), Object(O) {}
Colin LeMahieu77804be2015-07-29 15:45:39 +0000252 SectionFilterIterator begin() {
253 return SectionFilterIterator(Predicate, Object.section_begin(),
254 Object.section_end());
255 }
256 SectionFilterIterator end() {
257 return SectionFilterIterator(Predicate, Object.section_end(),
258 Object.section_end());
259 }
260
261private:
262 FilterPredicate Predicate;
263 llvm::object::ObjectFile const &Object;
264};
265SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) {
David Majnemer42531262016-08-12 03:55:06 +0000266 return SectionFilter(
267 [](llvm::object::SectionRef const &S) {
268 if (FilterSections.empty())
269 return true;
270 llvm::StringRef String;
271 std::error_code error = S.getName(String);
272 if (error)
273 return false;
274 return is_contained(FilterSections, String);
275 },
276 O);
Colin LeMahieu77804be2015-07-29 15:45:39 +0000277}
278}
279
Davide Italianoccd53fe2015-08-05 07:18:31 +0000280void llvm::error(std::error_code EC) {
Mark Seaborneb03ac52014-01-25 00:32:01 +0000281 if (!EC)
Davide Italianoccd53fe2015-08-05 07:18:31 +0000282 return;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000283
Davide Italiano140af642015-12-25 18:16:45 +0000284 errs() << ToolName << ": error reading file: " << EC.message() << ".\n";
285 errs().flush();
Davide Italiano7f6c3012015-08-06 00:18:52 +0000286 exit(1);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000287}
288
Kevin Enderby42398052016-06-28 23:16:13 +0000289LLVM_ATTRIBUTE_NORETURN void llvm::error(Twine Message) {
290 errs() << ToolName << ": " << Message << ".\n";
291 errs().flush();
292 exit(1);
293}
294
Davide Italianoed9d95b2015-12-29 13:41:02 +0000295LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000296 Twine Message) {
297 errs() << ToolName << ": '" << File << "': " << Message << ".\n";
298 exit(1);
299}
300
301LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
Davide Italianoed9d95b2015-12-29 13:41:02 +0000302 std::error_code EC) {
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000303 assert(EC);
304 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
Davide Italianoccd53fe2015-08-05 07:18:31 +0000305 exit(1);
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000306}
307
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000308LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
309 llvm::Error E) {
310 assert(E);
311 std::string Buf;
312 raw_string_ostream OS(Buf);
313 logAllUnhandledErrors(std::move(E), OS, "");
314 OS.flush();
Kevin Enderbyb34e3a12016-05-05 17:43:35 +0000315 errs() << ToolName << ": '" << File << "': " << Buf;
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000316 exit(1);
317}
318
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000319LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
320 StringRef FileName,
Kevin Enderby9acb1092016-05-31 20:35:34 +0000321 llvm::Error E,
322 StringRef ArchitectureName) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000323 assert(E);
324 errs() << ToolName << ": ";
325 if (ArchiveName != "")
326 errs() << ArchiveName << "(" << FileName << ")";
327 else
Justin Bogner31d8b7d2016-10-26 22:37:52 +0000328 errs() << "'" << FileName << "'";
Kevin Enderby9acb1092016-05-31 20:35:34 +0000329 if (!ArchitectureName.empty())
330 errs() << " (for architecture " << ArchitectureName << ")";
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000331 std::string Buf;
332 raw_string_ostream OS(Buf);
333 logAllUnhandledErrors(std::move(E), OS, "");
334 OS.flush();
Justin Bogner31d8b7d2016-10-26 22:37:52 +0000335 errs() << ": " << Buf;
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000336 exit(1);
337}
338
339LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
340 const object::Archive::Child &C,
Kevin Enderby9acb1092016-05-31 20:35:34 +0000341 llvm::Error E,
342 StringRef ArchitectureName) {
Kevin Enderbyf4586032016-07-29 17:44:13 +0000343 Expected<StringRef> NameOrErr = C.getName();
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000344 // TODO: if we have a error getting the name then it would be nice to print
345 // the index of which archive member this is and or its offset in the
346 // archive instead of "???" as the name.
Kevin Enderbyf4586032016-07-29 17:44:13 +0000347 if (!NameOrErr) {
348 consumeError(NameOrErr.takeError());
Kevin Enderby9acb1092016-05-31 20:35:34 +0000349 llvm::report_error(ArchiveName, "???", std::move(E), ArchitectureName);
Kevin Enderbyf4586032016-07-29 17:44:13 +0000350 } else
Kevin Enderby9acb1092016-05-31 20:35:34 +0000351 llvm::report_error(ArchiveName, NameOrErr.get(), std::move(E),
352 ArchitectureName);
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000353}
354
Craig Toppere6cb63e2014-04-25 04:24:47 +0000355static const Target *getTarget(const ObjectFile *Obj = nullptr) {
Michael J. Spencer2670c252011-01-20 06:39:06 +0000356 // Figure out the target triple.
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000357 llvm::Triple TheTriple("unknown-unknown-unknown");
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000358 if (TripleName.empty()) {
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000359 if (Obj) {
Sam Parkerdf7c6ef2017-01-18 13:52:12 +0000360 auto Arch = Obj->getArch();
361 TheTriple.setArch(Triple::ArchType(Arch));
362
363 // For ARM targets, try to use the build attributes to build determine
364 // the build target. Target features are also added, but later during
365 // disassembly.
366 if (Arch == Triple::arm || Arch == Triple::armeb) {
367 Obj->setARMSubArch(TheTriple);
368 }
369
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000370 // TheTriple defaults to ELF, and COFF doesn't have an environment:
371 // the best we can do here is indicate that it is mach-o.
372 if (Obj->isMachO())
Saleem Abdulrasool35476332014-03-06 20:47:11 +0000373 TheTriple.setObjectFormat(Triple::MachO);
Saleem Abdulrasool98938f12014-04-17 06:17:23 +0000374
375 if (Obj->isCOFF()) {
376 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
377 if (COFFObj->getArch() == Triple::thumb)
378 TheTriple.setTriple("thumbv7-windows");
379 }
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000380 }
Sam Parkerdf7c6ef2017-01-18 13:52:12 +0000381 } else {
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000382 TheTriple.setTriple(Triple::normalize(TripleName));
Sam Parkerdf7c6ef2017-01-18 13:52:12 +0000383 // Use the triple, but also try to combine with ARM build attributes.
384 if (Obj) {
385 auto Arch = Obj->getArch();
386 if (Arch == Triple::arm || Arch == Triple::armeb) {
387 Obj->setARMSubArch(TheTriple);
388 }
389 }
390 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000391
392 // Get the target specific parser.
393 std::string Error;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000394 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
395 Error);
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000396 if (!TheTarget) {
397 if (Obj)
398 report_error(Obj->getFileName(), "can't find target: " + Error);
399 else
400 error("can't find target: " + Error);
401 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000402
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000403 // Update the triple name and return the found target.
404 TripleName = TheTriple.getTriple();
405 return TheTarget;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000406}
407
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000408bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
Rafael Espindola704cd842015-07-06 15:47:43 +0000409 return a.getOffset() < b.getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +0000410}
411
Colin LeMahieufb76b002015-05-28 19:07:14 +0000412namespace {
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000413class SourcePrinter {
414protected:
415 DILineInfo OldLineInfo;
416 const ObjectFile *Obj;
417 std::unique_ptr<symbolize::LLVMSymbolizer> Symbolizer;
418 // File name to file contents of source
419 std::unordered_map<std::string, std::unique_ptr<MemoryBuffer>> SourceCache;
420 // Mark the line endings of the cached source
421 std::unordered_map<std::string, std::vector<StringRef>> LineCache;
422
423private:
424 bool cacheSource(std::string File);
425
426public:
427 virtual ~SourcePrinter() {}
428 SourcePrinter() : Obj(nullptr), Symbolizer(nullptr) {}
429 SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch) : Obj(Obj) {
430 symbolize::LLVMSymbolizer::Options SymbolizerOpts(
431 DILineInfoSpecifier::FunctionNameKind::None, true, false, false,
432 DefaultArch);
433 Symbolizer.reset(new symbolize::LLVMSymbolizer(SymbolizerOpts));
434 }
435 virtual void printSourceLine(raw_ostream &OS, uint64_t Address,
436 StringRef Delimiter = "; ");
437};
438
439bool SourcePrinter::cacheSource(std::string File) {
440 auto BufferOrError = MemoryBuffer::getFile(File);
441 if (!BufferOrError)
442 return false;
443 // Chomp the file to get lines
444 size_t BufferSize = (*BufferOrError)->getBufferSize();
445 const char *BufferStart = (*BufferOrError)->getBufferStart();
446 for (const char *Start = BufferStart, *End = BufferStart;
447 End < BufferStart + BufferSize; End++)
448 if (*End == '\n' || End == BufferStart + BufferSize - 1 ||
449 (*End == '\r' && *(End + 1) == '\n')) {
450 LineCache[File].push_back(StringRef(Start, End - Start));
451 if (*End == '\r')
452 End++;
453 Start = End + 1;
454 }
455 SourceCache[File] = std::move(*BufferOrError);
456 return true;
457}
458
459void SourcePrinter::printSourceLine(raw_ostream &OS, uint64_t Address,
460 StringRef Delimiter) {
461 if (!Symbolizer)
462 return;
463 DILineInfo LineInfo = DILineInfo();
464 auto ExpectecLineInfo =
465 Symbolizer->symbolizeCode(Obj->getFileName(), Address);
466 if (!ExpectecLineInfo)
467 consumeError(ExpectecLineInfo.takeError());
468 else
469 LineInfo = *ExpectecLineInfo;
470
471 if ((LineInfo.FileName == "<invalid>") || OldLineInfo.Line == LineInfo.Line ||
472 LineInfo.Line == 0)
473 return;
474
475 if (PrintLines)
476 OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line << "\n";
477 if (PrintSource) {
478 if (SourceCache.find(LineInfo.FileName) == SourceCache.end())
479 if (!cacheSource(LineInfo.FileName))
480 return;
481 auto FileBuffer = SourceCache.find(LineInfo.FileName);
482 if (FileBuffer != SourceCache.end()) {
483 auto LineBuffer = LineCache.find(LineInfo.FileName);
484 if (LineBuffer != LineCache.end())
485 // Vector begins at 0, line numbers are non-zero
486 OS << Delimiter << LineBuffer->second[LineInfo.Line - 1].ltrim()
487 << "\n";
488 }
489 }
490 OldLineInfo = LineInfo;
491}
492
Hemant Kulkarni5b60f632016-08-25 19:41:08 +0000493static bool isArmElf(const ObjectFile *Obj) {
494 return (Obj->isELF() &&
495 (Obj->getArch() == Triple::aarch64 ||
496 Obj->getArch() == Triple::aarch64_be ||
497 Obj->getArch() == Triple::arm || Obj->getArch() == Triple::armeb ||
498 Obj->getArch() == Triple::thumb ||
499 Obj->getArch() == Triple::thumbeb));
500}
501
Colin LeMahieufb76b002015-05-28 19:07:14 +0000502class PrettyPrinter {
503public:
Colin LeMahieu0b5890d2015-05-28 20:59:08 +0000504 virtual ~PrettyPrinter(){}
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000505 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
Colin LeMahieufb76b002015-05-28 19:07:14 +0000506 ArrayRef<uint8_t> Bytes, uint64_t Address,
507 raw_ostream &OS, StringRef Annot,
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000508 MCSubtargetInfo const &STI, SourcePrinter *SP) {
509 if (SP && (PrintSource || PrintLines))
510 SP->printSourceLine(OS, Address);
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000511 OS << format("%8" PRIx64 ":", Address);
Colin LeMahieufb76b002015-05-28 19:07:14 +0000512 if (!NoShowRawInsn) {
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000513 OS << "\t";
514 dumpBytes(Bytes, OS);
Colin LeMahieufb76b002015-05-28 19:07:14 +0000515 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000516 if (MI)
517 IP.printInst(MI, OS, "", STI);
518 else
519 OS << " <unknown>";
Colin LeMahieufb76b002015-05-28 19:07:14 +0000520 }
521};
522PrettyPrinter PrettyPrinterInst;
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000523class HexagonPrettyPrinter : public PrettyPrinter {
524public:
525 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
526 raw_ostream &OS) {
527 uint32_t opcode =
528 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
529 OS << format("%8" PRIx64 ":", Address);
530 if (!NoShowRawInsn) {
531 OS << "\t";
532 dumpBytes(Bytes.slice(0, 4), OS);
533 OS << format("%08" PRIx32, opcode);
534 }
535 }
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000536 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
537 uint64_t Address, raw_ostream &OS, StringRef Annot,
538 MCSubtargetInfo const &STI, SourcePrinter *SP) override {
Hemant Kulkarnie77a0a92016-08-18 21:50:13 +0000539 if (SP && (PrintSource || PrintLines))
540 SP->printSourceLine(OS, Address, "");
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000541 if (!MI) {
542 printLead(Bytes, Address, OS);
543 OS << " <unknown>";
544 return;
545 }
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000546 std::string Buffer;
547 {
548 raw_string_ostream TempStream(Buffer);
549 IP.printInst(MI, TempStream, "", STI);
550 }
551 StringRef Contents(Buffer);
552 // Split off bundle attributes
553 auto PacketBundle = Contents.rsplit('\n');
554 // Split off first instruction from the rest
555 auto HeadTail = PacketBundle.first.split('\n');
556 auto Preamble = " { ";
557 auto Separator = "";
558 while(!HeadTail.first.empty()) {
559 OS << Separator;
560 Separator = "\n";
Hemant Kulkarnie77a0a92016-08-18 21:50:13 +0000561 if (SP && (PrintSource || PrintLines))
562 SP->printSourceLine(OS, Address, "");
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000563 printLead(Bytes, Address, OS);
564 OS << Preamble;
565 Preamble = " ";
566 StringRef Inst;
567 auto Duplex = HeadTail.first.split('\v');
568 if(!Duplex.second.empty()){
569 OS << Duplex.first;
570 OS << "; ";
571 Inst = Duplex.second;
572 }
573 else
574 Inst = HeadTail.first;
575 OS << Inst;
576 Bytes = Bytes.slice(4);
577 Address += 4;
578 HeadTail = HeadTail.second.split('\n');
579 }
580 OS << " } " << PacketBundle.second;
581 }
582};
583HexagonPrettyPrinter HexagonPrettyPrinterInst;
Valery Pykhtinde048052016-04-07 07:24:01 +0000584
585class AMDGCNPrettyPrinter : public PrettyPrinter {
586public:
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000587 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
588 uint64_t Address, raw_ostream &OS, StringRef Annot,
589 MCSubtargetInfo const &STI, SourcePrinter *SP) override {
Matt Arsenault87d80db2016-04-22 21:23:41 +0000590 if (!MI) {
591 OS << " <unknown>";
592 return;
593 }
594
Valery Pykhtinde048052016-04-07 07:24:01 +0000595 SmallString<40> InstStr;
596 raw_svector_ostream IS(InstStr);
597
598 IP.printInst(MI, IS, "", STI);
599
Valery Pykhtin8e79f5b2016-04-07 08:38:20 +0000600 OS << left_justify(IS.str(), 60) << format("// %012" PRIX64 ": ", Address);
Valery Pykhtinde048052016-04-07 07:24:01 +0000601 typedef support::ulittle32_t U32;
602 for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
603 Bytes.size() / sizeof(U32)))
604 // D should be explicitly casted to uint32_t here as it is passed
605 // by format to snprintf as vararg.
Valery Pykhtin8e79f5b2016-04-07 08:38:20 +0000606 OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D));
Valery Pykhtinde048052016-04-07 07:24:01 +0000607
608 if (!Annot.empty())
609 OS << "// " << Annot;
610 }
611};
612AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
613
Alexei Starovoitov3b9efca2016-12-13 19:07:08 +0000614class BPFPrettyPrinter : public PrettyPrinter {
615public:
616 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
617 uint64_t Address, raw_ostream &OS, StringRef Annot,
618 MCSubtargetInfo const &STI, SourcePrinter *SP) override {
619 if (SP && (PrintSource || PrintLines))
620 SP->printSourceLine(OS, Address);
621 OS << format("%8" PRId64 ":", Address / 8);
622 if (!NoShowRawInsn) {
623 OS << "\t";
624 dumpBytes(Bytes, OS);
625 }
626 if (MI)
627 IP.printInst(MI, OS, "", STI);
628 else
629 OS << " <unknown>";
630 }
631};
632BPFPrettyPrinter BPFPrettyPrinterInst;
633
Colin LeMahieu35436a22015-05-29 14:48:25 +0000634PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000635 switch(Triple.getArch()) {
636 default:
637 return PrettyPrinterInst;
638 case Triple::hexagon:
639 return HexagonPrettyPrinterInst;
Valery Pykhtinde048052016-04-07 07:24:01 +0000640 case Triple::amdgcn:
641 return AMDGCNPrettyPrinterInst;
Alexei Starovoitov3b9efca2016-12-13 19:07:08 +0000642 case Triple::bpfel:
643 case Triple::bpfeb:
644 return BPFPrettyPrinterInst;
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000645 }
Colin LeMahieufb76b002015-05-28 19:07:14 +0000646}
647}
648
Rafael Espindola37070a52015-06-03 04:48:06 +0000649template <class ELFT>
Rafael Espindola37070a52015-06-03 04:48:06 +0000650static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000651 const RelocationRef &RelRef,
Rafael Espindola37070a52015-06-03 04:48:06 +0000652 SmallVectorImpl<char> &Result) {
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000653 DataRefImpl Rel = RelRef.getRawDataRefImpl();
654
Rafael Espindola37070a52015-06-03 04:48:06 +0000655 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
656 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000657 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
658
Rafael Espindola37070a52015-06-03 04:48:06 +0000659 const ELFFile<ELFT> &EF = *Obj->getELFFile();
660
Davide Italiano6cf09262016-11-16 05:10:28 +0000661 auto SecOrErr = EF.getSection(Rel.d.a);
662 if (!SecOrErr)
663 return errorToErrorCode(SecOrErr.takeError());
Rafael Espindola6def3042015-07-01 12:56:27 +0000664 const Elf_Shdr *Sec = *SecOrErr;
Davide Italiano6cf09262016-11-16 05:10:28 +0000665 auto SymTabOrErr = EF.getSection(Sec->sh_link);
666 if (!SymTabOrErr)
667 return errorToErrorCode(SymTabOrErr.takeError());
Rafael Espindola6def3042015-07-01 12:56:27 +0000668 const Elf_Shdr *SymTab = *SymTabOrErr;
Rafael Espindola719dc7c2015-06-29 12:38:31 +0000669 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
670 SymTab->sh_type == ELF::SHT_DYNSYM);
Davide Italiano6cf09262016-11-16 05:10:28 +0000671 auto StrTabSec = EF.getSection(SymTab->sh_link);
672 if (!StrTabSec)
673 return errorToErrorCode(StrTabSec.takeError());
674 auto StrTabOrErr = EF.getStringTable(*StrTabSec);
675 if (!StrTabOrErr)
676 return errorToErrorCode(StrTabOrErr.takeError());
Rafael Espindola6a1bfb22015-06-29 14:39:25 +0000677 StringRef StrTab = *StrTabOrErr;
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000678 uint8_t type = RelRef.getType();
Rafael Espindola37070a52015-06-03 04:48:06 +0000679 StringRef res;
680 int64_t addend = 0;
Rafael Espindola6def3042015-07-01 12:56:27 +0000681 switch (Sec->sh_type) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000682 default:
683 return object_error::parse_failed;
684 case ELF::SHT_REL: {
Rafael Espindola37070a52015-06-03 04:48:06 +0000685 // TODO: Read implicit addend from section data.
686 break;
687 }
688 case ELF::SHT_RELA: {
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000689 const Elf_Rela *ERela = Obj->getRela(Rel);
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000690 addend = ERela->r_addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000691 break;
692 }
693 }
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000694 symbol_iterator SI = RelRef.getSymbol();
695 const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
Rafael Espindola75d5b542015-06-03 05:14:22 +0000696 StringRef Target;
Rafael Espindola75d5b542015-06-03 05:14:22 +0000697 if (symb->getType() == ELF::STT_SECTION) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000698 Expected<section_iterator> SymSI = SI->getSection();
699 if (!SymSI)
700 return errorToErrorCode(SymSI.takeError());
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000701 const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
Davide Italiano6cf09262016-11-16 05:10:28 +0000702 auto SecName = EF.getSectionName(SymSec);
703 if (!SecName)
704 return errorToErrorCode(SecName.takeError());
Rafael Espindola75d5b542015-06-03 05:14:22 +0000705 Target = *SecName;
706 } else {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000707 Expected<StringRef> SymName = symb->getName(StrTab);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000708 if (!SymName)
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000709 return errorToErrorCode(SymName.takeError());
Rafael Espindola75d5b542015-06-03 05:14:22 +0000710 Target = *SymName;
711 }
Rafael Espindola37070a52015-06-03 04:48:06 +0000712 switch (EF.getHeader()->e_machine) {
713 case ELF::EM_X86_64:
714 switch (type) {
715 case ELF::R_X86_64_PC8:
716 case ELF::R_X86_64_PC16:
717 case ELF::R_X86_64_PC32: {
718 std::string fmtbuf;
719 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000720 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
Rafael Espindola37070a52015-06-03 04:48:06 +0000721 fmt.flush();
722 Result.append(fmtbuf.begin(), fmtbuf.end());
723 } break;
724 case ELF::R_X86_64_8:
725 case ELF::R_X86_64_16:
726 case ELF::R_X86_64_32:
727 case ELF::R_X86_64_32S:
728 case ELF::R_X86_64_64: {
729 std::string fmtbuf;
730 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000731 fmt << Target << (addend < 0 ? "" : "+") << addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000732 fmt.flush();
733 Result.append(fmtbuf.begin(), fmtbuf.end());
734 } break;
735 default:
736 res = "Unknown";
737 }
738 break;
Jacques Pienaarea9f25a2016-03-01 21:21:42 +0000739 case ELF::EM_LANAI:
Dylan McKay11661122016-09-28 13:15:17 +0000740 case ELF::EM_AVR:
Rafael Espindola37070a52015-06-03 04:48:06 +0000741 case ELF::EM_AARCH64: {
742 std::string fmtbuf;
743 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000744 fmt << Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000745 if (addend != 0)
746 fmt << (addend < 0 ? "" : "+") << addend;
747 fmt.flush();
748 Result.append(fmtbuf.begin(), fmtbuf.end());
749 break;
750 }
751 case ELF::EM_386:
Michael Kupersteina3b79dd2015-11-04 11:21:50 +0000752 case ELF::EM_IAMCU:
Rafael Espindola37070a52015-06-03 04:48:06 +0000753 case ELF::EM_ARM:
754 case ELF::EM_HEXAGON:
755 case ELF::EM_MIPS:
Alexei Starovoitovcfb51f52016-07-15 22:27:55 +0000756 case ELF::EM_BPF:
Alex Bradbury1524f622016-11-01 16:59:37 +0000757 case ELF::EM_RISCV:
Rafael Espindola75d5b542015-06-03 05:14:22 +0000758 res = Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000759 break;
Dan Gohman46350172016-01-12 20:56:01 +0000760 case ELF::EM_WEBASSEMBLY:
761 switch (type) {
762 case ELF::R_WEBASSEMBLY_DATA: {
763 std::string fmtbuf;
764 raw_string_ostream fmt(fmtbuf);
765 fmt << Target << (addend < 0 ? "" : "+") << addend;
766 fmt.flush();
767 Result.append(fmtbuf.begin(), fmtbuf.end());
768 break;
769 }
770 case ELF::R_WEBASSEMBLY_FUNCTION:
771 res = Target;
772 break;
773 default:
774 res = "Unknown";
775 }
776 break;
Rafael Espindola37070a52015-06-03 04:48:06 +0000777 default:
778 res = "Unknown";
779 }
780 if (Result.empty())
781 Result.append(res.begin(), res.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000782 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000783}
784
785static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000786 const RelocationRef &Rel,
Rafael Espindola37070a52015-06-03 04:48:06 +0000787 SmallVectorImpl<char> &Result) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000788 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
789 return getRelocationValueString(ELF32LE, Rel, Result);
790 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
791 return getRelocationValueString(ELF64LE, Rel, Result);
792 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
793 return getRelocationValueString(ELF32BE, Rel, Result);
794 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
795 return getRelocationValueString(ELF64BE, Rel, Result);
796}
797
798static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
799 const RelocationRef &Rel,
800 SmallVectorImpl<char> &Result) {
801 symbol_iterator SymI = Rel.getSymbol();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000802 Expected<StringRef> SymNameOrErr = SymI->getName();
803 if (!SymNameOrErr)
804 return errorToErrorCode(SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000805 StringRef SymName = *SymNameOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000806 Result.append(SymName.begin(), SymName.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000807 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000808}
809
810static void printRelocationTargetName(const MachOObjectFile *O,
811 const MachO::any_relocation_info &RE,
812 raw_string_ostream &fmt) {
813 bool IsScattered = O->isRelocationScattered(RE);
814
815 // Target of a scattered relocation is an address. In the interest of
816 // generating pretty output, scan through the symbol table looking for a
817 // symbol that aligns with that address. If we find one, print it.
818 // Otherwise, we just print the hex address of the target.
819 if (IsScattered) {
820 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
821
822 for (const SymbolRef &Symbol : O->symbols()) {
823 std::error_code ec;
Kevin Enderby931cb652016-06-24 18:24:42 +0000824 Expected<uint64_t> Addr = Symbol.getAddress();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000825 if (!Addr)
826 report_error(O->getFileName(), Addr.takeError());
Rafael Espindolaed067c42015-07-03 18:19:00 +0000827 if (*Addr != Val)
Rafael Espindola37070a52015-06-03 04:48:06 +0000828 continue;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000829 Expected<StringRef> Name = Symbol.getName();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000830 if (!Name)
831 report_error(O->getFileName(), Name.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000832 fmt << *Name;
Rafael Espindola37070a52015-06-03 04:48:06 +0000833 return;
834 }
835
836 // If we couldn't find a symbol that this relocation refers to, try
837 // to find a section beginning instead.
Colin LeMahieu77804be2015-07-29 15:45:39 +0000838 for (const SectionRef &Section : ToolSectionFilter(*O)) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000839 std::error_code ec;
840
841 StringRef Name;
842 uint64_t Addr = Section.getAddress();
843 if (Addr != Val)
844 continue;
845 if ((ec = Section.getName(Name)))
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000846 report_error(O->getFileName(), ec);
Rafael Espindola37070a52015-06-03 04:48:06 +0000847 fmt << Name;
848 return;
849 }
850
851 fmt << format("0x%x", Val);
852 return;
853 }
854
855 StringRef S;
856 bool isExtern = O->getPlainRelocationExternal(RE);
857 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
858
859 if (isExtern) {
860 symbol_iterator SI = O->symbol_begin();
861 advance(SI, Val);
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000862 Expected<StringRef> SOrErr = SI->getName();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000863 if (!SOrErr)
864 report_error(O->getFileName(), SOrErr.takeError());
Davide Italianoccd53fe2015-08-05 07:18:31 +0000865 S = *SOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000866 } else {
867 section_iterator SI = O->section_begin();
868 // Adjust for the fact that sections are 1-indexed.
869 advance(SI, Val - 1);
870 SI->getName(S);
871 }
872
873 fmt << S;
874}
875
876static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
877 const RelocationRef &RelRef,
878 SmallVectorImpl<char> &Result) {
879 DataRefImpl Rel = RelRef.getRawDataRefImpl();
880 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
881
882 unsigned Arch = Obj->getArch();
883
884 std::string fmtbuf;
885 raw_string_ostream fmt(fmtbuf);
886 unsigned Type = Obj->getAnyRelocationType(RE);
887 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
888
889 // Determine any addends that should be displayed with the relocation.
890 // These require decoding the relocation type, which is triple-specific.
891
892 // X86_64 has entirely custom relocation types.
893 if (Arch == Triple::x86_64) {
894 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
895
896 switch (Type) {
897 case MachO::X86_64_RELOC_GOT_LOAD:
898 case MachO::X86_64_RELOC_GOT: {
899 printRelocationTargetName(Obj, RE, fmt);
900 fmt << "@GOT";
901 if (isPCRel)
902 fmt << "PCREL";
903 break;
904 }
905 case MachO::X86_64_RELOC_SUBTRACTOR: {
906 DataRefImpl RelNext = Rel;
907 Obj->moveRelocationNext(RelNext);
908 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
909
910 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
911 // X86_64_RELOC_UNSIGNED.
912 // NOTE: Scattered relocations don't exist on x86_64.
913 unsigned RType = Obj->getAnyRelocationType(RENext);
914 if (RType != MachO::X86_64_RELOC_UNSIGNED)
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000915 report_error(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
916 "X86_64_RELOC_SUBTRACTOR.");
Rafael Espindola37070a52015-06-03 04:48:06 +0000917
918 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
919 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
920 printRelocationTargetName(Obj, RENext, fmt);
921 fmt << "-";
922 printRelocationTargetName(Obj, RE, fmt);
923 break;
924 }
925 case MachO::X86_64_RELOC_TLV:
926 printRelocationTargetName(Obj, RE, fmt);
927 fmt << "@TLV";
928 if (isPCRel)
929 fmt << "P";
930 break;
931 case MachO::X86_64_RELOC_SIGNED_1:
932 printRelocationTargetName(Obj, RE, fmt);
933 fmt << "-1";
934 break;
935 case MachO::X86_64_RELOC_SIGNED_2:
936 printRelocationTargetName(Obj, RE, fmt);
937 fmt << "-2";
938 break;
939 case MachO::X86_64_RELOC_SIGNED_4:
940 printRelocationTargetName(Obj, RE, fmt);
941 fmt << "-4";
942 break;
943 default:
944 printRelocationTargetName(Obj, RE, fmt);
945 break;
946 }
947 // X86 and ARM share some relocation types in common.
948 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
949 Arch == Triple::ppc) {
950 // Generic relocation types...
951 switch (Type) {
952 case MachO::GENERIC_RELOC_PAIR: // prints no info
Rui Ueyama7d099192015-06-09 15:20:42 +0000953 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000954 case MachO::GENERIC_RELOC_SECTDIFF: {
955 DataRefImpl RelNext = Rel;
956 Obj->moveRelocationNext(RelNext);
957 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
958
959 // X86 sect diff's must be followed by a relocation of type
960 // GENERIC_RELOC_PAIR.
961 unsigned RType = Obj->getAnyRelocationType(RENext);
962
963 if (RType != MachO::GENERIC_RELOC_PAIR)
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000964 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
965 "GENERIC_RELOC_SECTDIFF.");
Rafael Espindola37070a52015-06-03 04:48:06 +0000966
967 printRelocationTargetName(Obj, RE, fmt);
968 fmt << "-";
969 printRelocationTargetName(Obj, RENext, fmt);
970 break;
971 }
972 }
973
974 if (Arch == Triple::x86 || Arch == Triple::ppc) {
975 switch (Type) {
976 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
977 DataRefImpl RelNext = Rel;
978 Obj->moveRelocationNext(RelNext);
979 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
980
981 // X86 sect diff's must be followed by a relocation of type
982 // GENERIC_RELOC_PAIR.
983 unsigned RType = Obj->getAnyRelocationType(RENext);
984 if (RType != MachO::GENERIC_RELOC_PAIR)
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000985 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
986 "GENERIC_RELOC_LOCAL_SECTDIFF.");
Rafael Espindola37070a52015-06-03 04:48:06 +0000987
988 printRelocationTargetName(Obj, RE, fmt);
989 fmt << "-";
990 printRelocationTargetName(Obj, RENext, fmt);
991 break;
992 }
993 case MachO::GENERIC_RELOC_TLV: {
994 printRelocationTargetName(Obj, RE, fmt);
995 fmt << "@TLV";
996 if (IsPCRel)
997 fmt << "P";
998 break;
999 }
1000 default:
1001 printRelocationTargetName(Obj, RE, fmt);
1002 }
1003 } else { // ARM-specific relocations
1004 switch (Type) {
1005 case MachO::ARM_RELOC_HALF:
1006 case MachO::ARM_RELOC_HALF_SECTDIFF: {
1007 // Half relocations steal a bit from the length field to encode
1008 // whether this is an upper16 or a lower16 relocation.
1009 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
1010
1011 if (isUpper)
1012 fmt << ":upper16:(";
1013 else
1014 fmt << ":lower16:(";
1015 printRelocationTargetName(Obj, RE, fmt);
1016
1017 DataRefImpl RelNext = Rel;
1018 Obj->moveRelocationNext(RelNext);
1019 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
1020
1021 // ARM half relocs must be followed by a relocation of type
1022 // ARM_RELOC_PAIR.
1023 unsigned RType = Obj->getAnyRelocationType(RENext);
1024 if (RType != MachO::ARM_RELOC_PAIR)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001025 report_error(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
1026 "ARM_RELOC_HALF");
Rafael Espindola37070a52015-06-03 04:48:06 +00001027
1028 // NOTE: The half of the target virtual address is stashed in the
1029 // address field of the secondary relocation, but we can't reverse
1030 // engineer the constant offset from it without decoding the movw/movt
1031 // instruction to find the other half in its immediate field.
1032
1033 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
1034 // symbol/section pointer of the follow-on relocation.
1035 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1036 fmt << "-";
1037 printRelocationTargetName(Obj, RENext, fmt);
1038 }
1039
1040 fmt << ")";
1041 break;
1042 }
1043 default: { printRelocationTargetName(Obj, RE, fmt); }
1044 }
1045 }
1046 } else
1047 printRelocationTargetName(Obj, RE, fmt);
1048
1049 fmt.flush();
1050 Result.append(fmtbuf.begin(), fmtbuf.end());
Rui Ueyama7d099192015-06-09 15:20:42 +00001051 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +00001052}
1053
1054static std::error_code getRelocationValueString(const RelocationRef &Rel,
1055 SmallVectorImpl<char> &Result) {
Rafael Espindola854038e2015-06-26 14:51:16 +00001056 const ObjectFile *Obj = Rel.getObject();
Rafael Espindola37070a52015-06-03 04:48:06 +00001057 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
1058 return getRelocationValueString(ELF, Rel, Result);
1059 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
1060 return getRelocationValueString(COFF, Rel, Result);
1061 auto *MachO = cast<MachOObjectFile>(Obj);
1062 return getRelocationValueString(MachO, Rel, Result);
1063}
1064
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001065/// @brief Indicates whether this relocation should hidden when listing
1066/// relocations, usually because it is the trailing part of a multipart
1067/// relocation that will be printed as part of the leading relocation.
1068static bool getHidden(RelocationRef RelRef) {
1069 const ObjectFile *Obj = RelRef.getObject();
1070 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
1071 if (!MachO)
1072 return false;
1073
1074 unsigned Arch = MachO->getArch();
1075 DataRefImpl Rel = RelRef.getRawDataRefImpl();
1076 uint64_t Type = MachO->getRelocationType(Rel);
1077
1078 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
1079 // is always hidden.
1080 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
1081 if (Type == MachO::GENERIC_RELOC_PAIR)
1082 return true;
1083 } else if (Arch == Triple::x86_64) {
1084 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
1085 // an X86_64_RELOC_SUBTRACTOR.
1086 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
1087 DataRefImpl RelPrev = Rel;
1088 RelPrev.d.a--;
1089 uint64_t PrevType = MachO->getRelocationType(RelPrev);
1090 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
1091 return true;
1092 }
1093 }
1094
1095 return false;
1096}
1097
Sam Koltonc05d7782016-08-17 10:17:57 +00001098static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) {
1099 assert(Obj->isELF());
1100 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1101 return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1102 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1103 return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1104 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1105 return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1106 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1107 return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1108 llvm_unreachable("Unsupported binary format");
1109}
1110
Michael J. Spencer51862b32011-10-13 22:17:18 +00001111static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001112 if (StartAddress > StopAddress)
1113 error("Start address should be less than stop address");
1114
Jim Grosbachaf9aec02012-08-07 17:53:14 +00001115 const Target *TheTarget = getTarget(Obj);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001116
Jack Carter551efd72012-08-28 19:24:49 +00001117 // Package up features to be passed to target/subtarget
Daniel Sanders1d148642016-06-16 09:17:03 +00001118 SubtargetFeatures Features = Obj->getFeatures();
Jack Carter551efd72012-08-28 19:24:49 +00001119 if (MAttrs.size()) {
Jack Carter551efd72012-08-28 19:24:49 +00001120 for (unsigned i = 0; i != MAttrs.size(); ++i)
1121 Features.AddFeature(MAttrs[i]);
Jack Carter551efd72012-08-28 19:24:49 +00001122 }
1123
Ahmed Charles56440fd2014-03-06 05:51:42 +00001124 std::unique_ptr<const MCRegisterInfo> MRI(
1125 TheTarget->createMCRegInfo(TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +00001126 if (!MRI)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001127 report_error(Obj->getFileName(), "no register info for target " +
1128 TripleName);
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001129
1130 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00001131 std::unique_ptr<const MCAsmInfo> AsmInfo(
1132 TheTarget->createMCAsmInfo(*MRI, TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +00001133 if (!AsmInfo)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001134 report_error(Obj->getFileName(), "no assembly info for target " +
1135 TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +00001136 std::unique_ptr<const MCSubtargetInfo> STI(
Daniel Sanders1d148642016-06-16 09:17:03 +00001137 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
Davide Italiano711e4952015-12-17 01:59:50 +00001138 if (!STI)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001139 report_error(Obj->getFileName(), "no subtarget info for target " +
1140 TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +00001141 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
Davide Italiano711e4952015-12-17 01:59:50 +00001142 if (!MII)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001143 report_error(Obj->getFileName(), "no instruction info for target " +
1144 TripleName);
Sam Kolton3381d7a2016-10-06 13:46:08 +00001145 MCObjectFileInfo MOFI;
1146 MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI);
1147 // FIXME: for now initialize MCObjectFileInfo with default values
1148 MOFI.InitMCObjectFileInfo(Triple(TripleName), false, CodeModel::Default, Ctx);
Lang Hamesa1bc0f52014-04-15 04:40:56 +00001149
1150 std::unique_ptr<MCDisassembler> DisAsm(
1151 TheTarget->createMCDisassembler(*STI, Ctx));
Davide Italiano711e4952015-12-17 01:59:50 +00001152 if (!DisAsm)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001153 report_error(Obj->getFileName(), "no disassembler for target " +
1154 TripleName);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001155
Ahmed Charles56440fd2014-03-06 05:51:42 +00001156 std::unique_ptr<const MCInstrAnalysis> MIA(
1157 TheTarget->createMCInstrAnalysis(MII.get()));
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001158
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001159 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Daniel Sanders50f17232015-09-15 16:17:27 +00001160 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1161 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
Davide Italiano711e4952015-12-17 01:59:50 +00001162 if (!IP)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001163 report_error(Obj->getFileName(), "no instruction printer for target " +
1164 TripleName);
Colin LeMahieu14ec76e2015-06-07 21:07:17 +00001165 IP->setPrintImmHex(PrintImmHex);
Colin LeMahieu35436a22015-05-29 14:48:25 +00001166 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001167
Greg Fitzgerald18432272014-03-20 22:55:15 +00001168 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
1169 "\t\t\t%08" PRIx64 ": ";
1170
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001171 SourcePrinter SP(Obj, TheTarget->getName());
1172
Mark Seaborn0929d3d2014-01-25 17:38:19 +00001173 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
1174 // in RelocSecs contain the relocations for section S.
Rafael Espindola4453e42942014-06-13 03:07:50 +00001175 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +00001176 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001177 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001178 section_iterator Sec2 = Section.getRelocatedSection();
Rafael Espindolab5155a52014-02-10 20:24:04 +00001179 if (Sec2 != Obj->section_end())
Alexey Samsonov48803e52014-03-13 14:37:36 +00001180 SectionRelocMap[*Sec2].push_back(Section);
Mark Seaborn0929d3d2014-01-25 17:38:19 +00001181 }
1182
David Majnemer81afca62015-07-07 22:06:59 +00001183 // Create a mapping from virtual address to symbol name. This is used to
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001184 // pretty print the symbols while disassembling.
Sam Koltonc05d7782016-08-17 10:17:57 +00001185 typedef std::vector<std::tuple<uint64_t, StringRef, uint8_t>> SectionSymbolsTy;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001186 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
1187 for (const SymbolRef &Symbol : Obj->symbols()) {
Kevin Enderby931cb652016-06-24 18:24:42 +00001188 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001189 if (!AddressOrErr)
1190 report_error(Obj->getFileName(), AddressOrErr.takeError());
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001191 uint64_t Address = *AddressOrErr;
David Majnemer2603a8fa2015-07-09 18:11:40 +00001192
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001193 Expected<StringRef> Name = Symbol.getName();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001194 if (!Name)
1195 report_error(Obj->getFileName(), Name.takeError());
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001196 if (Name->empty())
1197 continue;
David Majnemer81afca62015-07-07 22:06:59 +00001198
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001199 Expected<section_iterator> SectionOrErr = Symbol.getSection();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001200 if (!SectionOrErr)
1201 report_error(Obj->getFileName(), SectionOrErr.takeError());
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001202 section_iterator SecI = *SectionOrErr;
1203 if (SecI == Obj->section_end())
1204 continue;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001205
Sam Koltonc05d7782016-08-17 10:17:57 +00001206 uint8_t SymbolType = ELF::STT_NOTYPE;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001207 if (Obj->isELF())
Sam Koltonc05d7782016-08-17 10:17:57 +00001208 SymbolType = getElfSymbolType(Obj, Symbol);
David Majnemer81afca62015-07-07 22:06:59 +00001209
Sam Koltonc05d7782016-08-17 10:17:57 +00001210 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1211
David Majnemer81afca62015-07-07 22:06:59 +00001212 }
1213
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001214 // Create a mapping from virtual address to section.
1215 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1216 for (SectionRef Sec : Obj->sections())
1217 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1218 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
1219
1220 // Linked executables (.exe and .dll files) typically don't include a real
1221 // symbol table but they might contain an export table.
1222 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
1223 for (const auto &ExportEntry : COFFObj->export_directories()) {
1224 StringRef Name;
1225 error(ExportEntry.getSymbolName(Name));
1226 if (Name.empty())
1227 continue;
1228 uint32_t RVA;
1229 error(ExportEntry.getExportRVA(RVA));
1230
1231 uint64_t VA = COFFObj->getImageBase() + RVA;
1232 auto Sec = std::upper_bound(
1233 SectionAddresses.begin(), SectionAddresses.end(), VA,
1234 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
1235 return LHS < RHS.first;
1236 });
1237 if (Sec != SectionAddresses.begin())
1238 --Sec;
1239 else
1240 Sec = SectionAddresses.end();
1241
1242 if (Sec != SectionAddresses.end())
Sam Koltonc05d7782016-08-17 10:17:57 +00001243 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001244 }
1245 }
1246
1247 // Sort all the symbols, this allows us to use a simple binary search to find
1248 // a symbol near an address.
1249 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1250 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
1251
Colin LeMahieu77804be2015-07-29 15:45:39 +00001252 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Colin LeMahieuf34933e2015-07-23 20:58:49 +00001253 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
Mark Seaborneb03ac52014-01-25 00:32:01 +00001254 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +00001255
Rafael Espindola80291272014-10-08 15:28:58 +00001256 uint64_t SectionAddr = Section.getAddress();
1257 uint64_t SectSize = Section.getSize();
David Majnemer185b5b12014-11-11 09:58:25 +00001258 if (!SectSize)
1259 continue;
Simon Atanasyan2b614e12014-02-24 22:12:11 +00001260
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001261 // Get the list of all the symbols in this section.
1262 SectionSymbolsTy &Symbols = AllSymbols[Section];
Davide Italianof0706882015-10-01 21:57:09 +00001263 std::vector<uint64_t> DataMappingSymsAddr;
1264 std::vector<uint64_t> TextMappingSymsAddr;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001265 if (isArmElf(Obj)) {
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001266 for (const auto &Symb : Symbols) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001267 uint64_t Address = std::get<0>(Symb);
1268 StringRef Name = std::get<1>(Symb);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001269 if (Name.startswith("$d"))
David Majnemer153722d2015-11-18 04:35:32 +00001270 DataMappingSymsAddr.push_back(Address - SectionAddr);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001271 if (Name.startswith("$x"))
David Majnemer153722d2015-11-18 04:35:32 +00001272 TextMappingSymsAddr.push_back(Address - SectionAddr);
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001273 if (Name.startswith("$a"))
1274 TextMappingSymsAddr.push_back(Address - SectionAddr);
1275 if (Name.startswith("$t"))
1276 TextMappingSymsAddr.push_back(Address - SectionAddr);
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001277 }
1278 }
1279
Davide Italianof0706882015-10-01 21:57:09 +00001280 std::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end());
1281 std::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end());
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001282
Sam Kolton3381d7a2016-10-06 13:46:08 +00001283 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1284 // AMDGPU disassembler uses symbolizer for printing labels
1285 std::unique_ptr<MCRelocationInfo> RelInfo(
1286 TheTarget->createMCRelocationInfo(TripleName, Ctx));
1287 if (RelInfo) {
1288 std::unique_ptr<MCSymbolizer> Symbolizer(
1289 TheTarget->createMCSymbolizer(
1290 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1291 DisAsm->setSymbolizer(std::move(Symbolizer));
1292 }
1293 }
1294
Michael J. Spencer51862b32011-10-13 22:17:18 +00001295 // Make a list of all the relocations for this section.
1296 std::vector<RelocationRef> Rels;
1297 if (InlineRelocs) {
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001298 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
1299 for (const RelocationRef &Reloc : RelocSec.relocations()) {
1300 Rels.push_back(Reloc);
1301 }
Michael J. Spencer51862b32011-10-13 22:17:18 +00001302 }
1303 }
1304
1305 // Sort relocations by address.
1306 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
1307
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001308 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +00001309 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001310 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +00001311 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001312 }
Michael J. Spencer1d6167f2011-06-25 17:55:23 +00001313 StringRef name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001314 error(Section.getName(name));
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001315
1316 if ((SectionAddr <= StopAddress) &&
1317 (SectionAddr + SectSize) >= StartAddress) {
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001318 outs() << "Disassembly of section ";
1319 if (!SegmentName.empty())
1320 outs() << SegmentName << ",";
1321 outs() << name << ':';
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001322 }
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001323
Rafael Espindola7884c952015-06-04 15:01:05 +00001324 // If the section has no symbol at the start, just insert a dummy one.
Sam Koltonc05d7782016-08-17 10:17:57 +00001325 if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) {
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001326 Symbols.insert(Symbols.begin(),
1327 std::make_tuple(SectionAddr, name, Section.isText()
1328 ? ELF::STT_FUNC
1329 : ELF::STT_OBJECT));
Sam Koltonc05d7782016-08-17 10:17:57 +00001330 }
Alp Tokere69170a2014-06-26 22:52:05 +00001331
1332 SmallString<40> Comments;
1333 raw_svector_ostream CommentStream(Comments);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001334
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001335 StringRef BytesStr;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001336 error(Section.getContents(BytesStr));
Aaron Ballman106fd7b2014-11-12 14:01:17 +00001337 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1338 BytesStr.size());
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001339
Michael J. Spencer2670c252011-01-20 06:39:06 +00001340 uint64_t Size;
1341 uint64_t Index;
1342
Michael J. Spencer51862b32011-10-13 22:17:18 +00001343 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
1344 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001345 // Disassemble symbol by symbol.
1346 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001347 uint64_t Start = std::get<0>(Symbols[si]) - SectionAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001348 // The end is either the section end or the beginning of the next
1349 // symbol.
1350 uint64_t End =
Sam Koltonc05d7782016-08-17 10:17:57 +00001351 (si == se - 1) ? SectSize : std::get<0>(Symbols[si + 1]) - SectionAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001352 // Don't try to disassemble beyond the end of section contents.
1353 if (End > SectSize)
1354 End = SectSize;
Rafael Espindolae45c7402014-08-17 16:31:39 +00001355 // If this symbol has the same address as the next symbol, then skip it.
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001356 if (Start >= End)
Michael J. Spenceree84f642011-10-13 20:37:08 +00001357 continue;
1358
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001359 // Check if we need to skip symbol
1360 // Skip if the symbol's data is not between StartAddress and StopAddress
1361 if (End + SectionAddr < StartAddress ||
1362 Start + SectionAddr > StopAddress) {
1363 continue;
1364 }
1365
1366 // Stop disassembly at the stop address specified
1367 if (End + SectionAddr > StopAddress)
1368 End = StopAddress - SectionAddr;
1369
Valery Pykhtinde048052016-04-07 07:24:01 +00001370 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1371 // make size 4 bytes folded
1372 End = Start + ((End - Start) & ~0x3ull);
Sam Koltonc05d7782016-08-17 10:17:57 +00001373 if (std::get<2>(Symbols[si]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1374 // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)
1375 Start += 256;
1376 }
1377 if (si == se - 1 ||
1378 std::get<2>(Symbols[si + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1379 // cut trailing zeroes at the end of kernel
1380 // cut up to 256 bytes
1381 const uint64_t EndAlign = 256;
1382 const auto Limit = End - (std::min)(EndAlign, End - Start);
1383 while (End > Limit &&
1384 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1385 End -= 4;
1386 }
Valery Pykhtinde048052016-04-07 07:24:01 +00001387 }
1388
Sam Koltonc05d7782016-08-17 10:17:57 +00001389 outs() << '\n' << std::get<1>(Symbols[si]) << ":\n";
Michael J. Spencer2670c252011-01-20 06:39:06 +00001390
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001391#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +00001392 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001393#else
Mark Seaborneb03ac52014-01-25 00:32:01 +00001394 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001395#endif
1396
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001397 for (Index = Start; Index < End; Index += Size) {
1398 MCInst Inst;
Owen Andersona0c3b972011-09-15 23:38:46 +00001399
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001400 if (Index + SectionAddr < StartAddress ||
1401 Index + SectionAddr > StopAddress) {
1402 // skip byte by byte till StartAddress is reached
1403 Size = 1;
1404 continue;
1405 }
Davide Italianof0706882015-10-01 21:57:09 +00001406 // AArch64 ELF binaries can interleave data and text in the
1407 // same section. We rely on the markers introduced to
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001408 // understand what we need to dump. If the data marker is within a
1409 // function, it is denoted as a word/short etc
1410 if (isArmElf(Obj) && std::get<2>(Symbols[si]) != ELF::STT_OBJECT &&
1411 !DisassembleAll) {
Davide Italianof0706882015-10-01 21:57:09 +00001412 uint64_t Stride = 0;
1413
1414 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1415 DataMappingSymsAddr.end(), Index);
1416 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1417 // Switch to data.
1418 while (Index < End) {
1419 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1420 outs() << "\t";
1421 if (Index + 4 <= End) {
1422 Stride = 4;
1423 dumpBytes(Bytes.slice(Index, 4), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001424 outs() << "\t.word\t";
1425 uint32_t Data = 0;
1426 if (Obj->isLittleEndian()) {
1427 const auto Word =
1428 reinterpret_cast<const support::ulittle32_t *>(
1429 Bytes.data() + Index);
1430 Data = *Word;
1431 } else {
1432 const auto Word = reinterpret_cast<const support::ubig32_t *>(
1433 Bytes.data() + Index);
1434 Data = *Word;
1435 }
1436 outs() << "0x" << format("%08" PRIx32, Data);
Davide Italianof0706882015-10-01 21:57:09 +00001437 } else if (Index + 2 <= End) {
1438 Stride = 2;
1439 dumpBytes(Bytes.slice(Index, 2), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001440 outs() << "\t\t.short\t";
1441 uint16_t Data = 0;
1442 if (Obj->isLittleEndian()) {
1443 const auto Short =
1444 reinterpret_cast<const support::ulittle16_t *>(
1445 Bytes.data() + Index);
1446 Data = *Short;
1447 } else {
1448 const auto Short =
1449 reinterpret_cast<const support::ubig16_t *>(Bytes.data() +
1450 Index);
1451 Data = *Short;
1452 }
1453 outs() << "0x" << format("%04" PRIx16, Data);
Davide Italianof0706882015-10-01 21:57:09 +00001454 } else {
1455 Stride = 1;
1456 dumpBytes(Bytes.slice(Index, 1), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001457 outs() << "\t\t.byte\t";
1458 outs() << "0x" << format("%02" PRIx8, Bytes.slice(Index, 1)[0]);
Davide Italianof0706882015-10-01 21:57:09 +00001459 }
1460 Index += Stride;
1461 outs() << "\n";
1462 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1463 TextMappingSymsAddr.end(), Index);
1464 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1465 break;
1466 }
1467 }
1468 }
1469
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001470 // If there is a data symbol inside an ELF text section and we are only
1471 // disassembling text (applicable all architectures),
1472 // we are in a situation where we must print the data and not
1473 // disassemble it.
1474 if (Obj->isELF() && std::get<2>(Symbols[si]) == ELF::STT_OBJECT &&
1475 !DisassembleAll && Section.isText()) {
1476 // print out data up to 8 bytes at a time in hex and ascii
1477 uint8_t AsciiData[9] = {'\0'};
1478 uint8_t Byte;
1479 int NumBytes = 0;
1480
1481 for (Index = Start; Index < End; Index += 1) {
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001482 if (((SectionAddr + Index) < StartAddress) ||
1483 ((SectionAddr + Index) > StopAddress))
1484 continue;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001485 if (NumBytes == 0) {
1486 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1487 outs() << "\t";
1488 }
1489 Byte = Bytes.slice(Index)[0];
1490 outs() << format(" %02x", Byte);
1491 AsciiData[NumBytes] = isprint(Byte) ? Byte : '.';
1492
1493 uint8_t IndentOffset = 0;
1494 NumBytes++;
1495 if (Index == End - 1 || NumBytes > 8) {
1496 // Indent the space for less than 8 bytes data.
1497 // 2 spaces for byte and one for space between bytes
1498 IndentOffset = 3 * (8 - NumBytes);
1499 for (int Excess = 8 - NumBytes; Excess < 8; Excess++)
1500 AsciiData[Excess] = '\0';
1501 NumBytes = 8;
1502 }
1503 if (NumBytes == 8) {
1504 AsciiData[8] = '\0';
1505 outs() << std::string(IndentOffset, ' ') << " ";
1506 outs() << reinterpret_cast<char *>(AsciiData);
1507 outs() << '\n';
1508 NumBytes = 0;
1509 }
1510 }
1511 }
Davide Italianof0706882015-10-01 21:57:09 +00001512 if (Index >= End)
1513 break;
1514
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001515 // Disassemble a real instruction or a data when disassemble all is
1516 // provided
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001517 bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1518 SectionAddr + Index, DebugOut,
1519 CommentStream);
1520 if (Size == 0)
1521 Size = 1;
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001522
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001523 PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001524 Bytes.slice(Index, Size), SectionAddr + Index, outs(), "",
1525 *STI, &SP);
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001526 outs() << CommentStream.str();
1527 Comments.clear();
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001528
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001529 // Try to resolve the target of a call, tail call, etc. to a specific
1530 // symbol.
1531 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1532 MIA->isConditionalBranch(Inst))) {
1533 uint64_t Target;
1534 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1535 // In a relocatable object, the target's section must reside in
1536 // the same section as the call instruction or it is accessed
1537 // through a relocation.
1538 //
1539 // In a non-relocatable object, the target may be in any section.
1540 //
1541 // N.B. We don't walk the relocations in the relocatable case yet.
1542 auto *TargetSectionSymbols = &Symbols;
1543 if (!Obj->isRelocatableObject()) {
1544 auto SectionAddress = std::upper_bound(
1545 SectionAddresses.begin(), SectionAddresses.end(), Target,
1546 [](uint64_t LHS,
1547 const std::pair<uint64_t, SectionRef> &RHS) {
1548 return LHS < RHS.first;
1549 });
1550 if (SectionAddress != SectionAddresses.begin()) {
1551 --SectionAddress;
1552 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1553 } else {
1554 TargetSectionSymbols = nullptr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001555 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001556 }
David Majnemer2603a8fa2015-07-09 18:11:40 +00001557
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001558 // Find the first symbol in the section whose offset is less than
1559 // or equal to the target.
1560 if (TargetSectionSymbols) {
1561 auto TargetSym = std::upper_bound(
1562 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1563 Target, [](uint64_t LHS,
Sam Koltonc05d7782016-08-17 10:17:57 +00001564 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1565 return LHS < std::get<0>(RHS);
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001566 });
1567 if (TargetSym != TargetSectionSymbols->begin()) {
1568 --TargetSym;
1569 uint64_t TargetAddress = std::get<0>(*TargetSym);
1570 StringRef TargetName = std::get<1>(*TargetSym);
1571 outs() << " <" << TargetName;
1572 uint64_t Disp = Target - TargetAddress;
1573 if (Disp)
1574 outs() << "+0x" << utohexstr(Disp);
1575 outs() << '>';
David Majnemer81afca62015-07-07 22:06:59 +00001576 }
1577 }
1578 }
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001579 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001580 outs() << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001581
1582 // Print relocation for instruction.
1583 while (rel_cur != rel_end) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001584 bool hidden = getHidden(*rel_cur);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001585 uint64_t addr = rel_cur->getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +00001586 SmallString<16> name;
1587 SmallString<32> val;
Owen Andersonfa3e5202011-10-25 20:35:53 +00001588
1589 // If this relocation is hidden, skip it.
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001590 if (hidden || ((SectionAddr + addr) < StartAddress)) {
1591 ++rel_cur;
1592 continue;
1593 }
Owen Andersonfa3e5202011-10-25 20:35:53 +00001594
Michael J. Spencer51862b32011-10-13 22:17:18 +00001595 // Stop when rel_cur's address is past the current instruction.
Owen Andersonf20e3e52011-10-25 20:15:39 +00001596 if (addr >= Index + Size) break;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001597 rel_cur->getTypeName(name);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001598 error(getRelocationValueString(*rel_cur, val));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001599 outs() << format(Fmt.data(), SectionAddr + addr) << name
Benjamin Kramer82803112012-03-10 02:04:38 +00001600 << "\t" << val << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001601 ++rel_cur;
1602 }
Benjamin Kramer87ee76c2011-07-20 19:37:35 +00001603 }
Michael J. Spencer2670c252011-01-20 06:39:06 +00001604 }
1605 }
1606}
1607
Kevin Enderby98da6132015-01-20 21:47:46 +00001608void llvm::PrintRelocations(const ObjectFile *Obj) {
Greg Fitzgerald18432272014-03-20 22:55:15 +00001609 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1610 "%08" PRIx64;
Rafael Espindola9219fe72016-03-21 20:59:15 +00001611 // Regular objdump doesn't print relocations in non-relocatable object
1612 // files.
1613 if (!Obj->isRelocatableObject())
1614 return;
Rafael Espindolac66d7612014-08-17 19:09:37 +00001615
Colin LeMahieu77804be2015-07-29 15:45:39 +00001616 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001617 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001618 continue;
1619 StringRef secname;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001620 error(Section.getName(secname));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001621 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001622 for (const RelocationRef &Reloc : Section.relocations()) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001623 bool hidden = getHidden(Reloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001624 uint64_t address = Reloc.getOffset();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001625 SmallString<32> relocname;
1626 SmallString<32> valuestr;
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001627 if (address < StartAddress || address > StopAddress || hidden)
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001628 continue;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001629 Reloc.getTypeName(relocname);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001630 error(getRelocationValueString(Reloc, valuestr));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001631 outs() << format(Fmt.data(), address) << " " << relocname << " "
1632 << valuestr << "\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001633 }
1634 outs() << "\n";
1635 }
1636}
1637
Kevin Enderby98da6132015-01-20 21:47:46 +00001638void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001639 outs() << "Sections:\n"
1640 "Idx Name Size Address Type\n";
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001641 unsigned i = 0;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001642 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001643 StringRef Name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001644 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001645 uint64_t Address = Section.getAddress();
1646 uint64_t Size = Section.getSize();
1647 bool Text = Section.isText();
1648 bool Data = Section.isData();
1649 bool BSS = Section.isBSS();
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001650 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +00001651 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
Alexey Samsonov48803e52014-03-13 14:37:36 +00001652 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1653 Name.str().c_str(), Size, Address, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001654 ++i;
1655 }
1656}
1657
Kevin Enderby98da6132015-01-20 21:47:46 +00001658void llvm::PrintSectionContents(const ObjectFile *Obj) {
Rafael Espindola4453e42942014-06-13 03:07:50 +00001659 std::error_code EC;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001660 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001661 StringRef Name;
1662 StringRef Contents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001663 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001664 uint64_t BaseAddr = Section.getAddress();
David Majnemer185b5b12014-11-11 09:58:25 +00001665 uint64_t Size = Section.getSize();
1666 if (!Size)
1667 continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001668
1669 outs() << "Contents of section " << Name << ":\n";
David Majnemer185b5b12014-11-11 09:58:25 +00001670 if (Section.isBSS()) {
Alexey Samsonov209095c2013-04-16 10:53:11 +00001671 outs() << format("<skipping contents of bss section at [%04" PRIx64
David Majnemer8f6b04c2014-07-14 16:20:14 +00001672 ", %04" PRIx64 ")>\n",
1673 BaseAddr, BaseAddr + Size);
Alexey Samsonov209095c2013-04-16 10:53:11 +00001674 continue;
1675 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001676
Davide Italianoccd53fe2015-08-05 07:18:31 +00001677 error(Section.getContents(Contents));
David Majnemer8f6b04c2014-07-14 16:20:14 +00001678
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001679 // Dump out the content as hex and printable ascii characters.
1680 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer82803112012-03-10 02:04:38 +00001681 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001682 // Dump line of hex.
1683 for (std::size_t i = 0; i < 16; ++i) {
1684 if (i != 0 && i % 4 == 0)
1685 outs() << ' ';
1686 if (addr + i < end)
1687 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1688 << hexdigit(Contents[addr + i] & 0xF, true);
1689 else
1690 outs() << " ";
1691 }
1692 // Print ascii.
1693 outs() << " ";
1694 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
Guy Benyei83c74e92013-02-12 21:21:59 +00001695 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001696 outs() << Contents[addr + i];
1697 else
1698 outs() << ".";
1699 }
1700 outs() << "\n";
1701 }
1702 }
1703}
1704
Kevin Enderby9acb1092016-05-31 20:35:34 +00001705void llvm::PrintSymbolTable(const ObjectFile *o, StringRef ArchiveName,
1706 StringRef ArchitectureName) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001707 outs() << "SYMBOL TABLE:\n";
1708
Rui Ueyama4e39f712014-03-18 18:58:51 +00001709 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
Davide Italianoe85abf72015-12-20 09:54:34 +00001710 printCOFFSymbolTable(coff);
Rui Ueyama4e39f712014-03-18 18:58:51 +00001711 return;
1712 }
1713 for (const SymbolRef &Symbol : o->symbols()) {
Kevin Enderby931cb652016-06-24 18:24:42 +00001714 Expected<uint64_t> AddressOrError = Symbol.getAddress();
1715 if (!AddressOrError)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001716 report_error(ArchiveName, o->getFileName(), AddressOrError.takeError(),
1717 ArchitectureName);
Rafael Espindolaed067c42015-07-03 18:19:00 +00001718 uint64_t Address = *AddressOrError;
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001719 if ((Address < StartAddress) || (Address > StopAddress))
1720 continue;
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001721 Expected<SymbolRef::Type> TypeOrError = Symbol.getType();
1722 if (!TypeOrError)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001723 report_error(ArchiveName, o->getFileName(), TypeOrError.takeError(),
1724 ArchitectureName);
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00001725 SymbolRef::Type Type = *TypeOrError;
Rui Ueyama4e39f712014-03-18 18:58:51 +00001726 uint32_t Flags = Symbol.getFlags();
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001727 Expected<section_iterator> SectionOrErr = Symbol.getSection();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001728 if (!SectionOrErr)
1729 report_error(ArchiveName, o->getFileName(), SectionOrErr.takeError(),
1730 ArchitectureName);
Rafael Espindola8bab8892015-08-07 23:27:14 +00001731 section_iterator Section = *SectionOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001732 StringRef Name;
1733 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1734 Section->getName(Name);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001735 } else {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001736 Expected<StringRef> NameOrErr = Symbol.getName();
1737 if (!NameOrErr)
Kevin Enderby9acb1092016-05-31 20:35:34 +00001738 report_error(ArchiveName, o->getFileName(), NameOrErr.takeError(),
1739 ArchitectureName);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001740 Name = *NameOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001741 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001742
Rui Ueyama4e39f712014-03-18 18:58:51 +00001743 bool Global = Flags & SymbolRef::SF_Global;
1744 bool Weak = Flags & SymbolRef::SF_Weak;
1745 bool Absolute = Flags & SymbolRef::SF_Absolute;
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001746 bool Common = Flags & SymbolRef::SF_Common;
Davide Italianocd2514d2015-04-30 23:08:53 +00001747 bool Hidden = Flags & SymbolRef::SF_Hidden;
David Meyer1df4b842012-02-28 23:47:53 +00001748
Rui Ueyama4e39f712014-03-18 18:58:51 +00001749 char GlobLoc = ' ';
1750 if (Type != SymbolRef::ST_Unknown)
1751 GlobLoc = Global ? 'g' : 'l';
1752 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1753 ? 'd' : ' ';
1754 char FileFunc = ' ';
1755 if (Type == SymbolRef::ST_File)
1756 FileFunc = 'f';
1757 else if (Type == SymbolRef::ST_Function)
1758 FileFunc = 'F';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001759
Rui Ueyama4e39f712014-03-18 18:58:51 +00001760 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1761 "%08" PRIx64;
Michael J. Spencerd857c1c2013-01-10 22:40:50 +00001762
Rui Ueyama4e39f712014-03-18 18:58:51 +00001763 outs() << format(Fmt, Address) << " "
1764 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1765 << (Weak ? 'w' : ' ') // Weak?
1766 << ' ' // Constructor. Not supported yet.
1767 << ' ' // Warning. Not supported yet.
1768 << ' ' // Indirect reference to another symbol.
1769 << Debug // Debugging (d) or dynamic (D) symbol.
1770 << FileFunc // Name of function (F), file (f) or object (O).
1771 << ' ';
1772 if (Absolute) {
1773 outs() << "*ABS*";
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001774 } else if (Common) {
1775 outs() << "*COM*";
Rui Ueyama4e39f712014-03-18 18:58:51 +00001776 } else if (Section == o->section_end()) {
1777 outs() << "*UND*";
1778 } else {
1779 if (const MachOObjectFile *MachO =
1780 dyn_cast<const MachOObjectFile>(o)) {
1781 DataRefImpl DR = Section->getRawDataRefImpl();
1782 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1783 outs() << SegmentName << ",";
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001784 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00001785 StringRef SectionName;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001786 error(Section->getName(SectionName));
Rui Ueyama4e39f712014-03-18 18:58:51 +00001787 outs() << SectionName;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001788 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001789
1790 outs() << '\t';
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001791 if (Common || isa<ELFObjectFileBase>(o)) {
Rafael Espindoladbb6bd32015-06-25 22:10:04 +00001792 uint64_t Val =
1793 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001794 outs() << format("\t %08" PRIx64 " ", Val);
1795 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001796
Davide Italianocd2514d2015-04-30 23:08:53 +00001797 if (Hidden) {
1798 outs() << ".hidden ";
1799 }
1800 outs() << Name
Rui Ueyama4e39f712014-03-18 18:58:51 +00001801 << '\n';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001802 }
1803}
1804
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001805static void PrintUnwindInfo(const ObjectFile *o) {
1806 outs() << "Unwind info:\n\n";
1807
1808 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1809 printCOFFUnwindInfo(coff);
Tim Northover4bd286a2014-08-01 13:07:19 +00001810 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1811 printMachOUnwindInfo(MachO);
1812 else {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001813 // TODO: Extract DWARF dump tool to objdump.
1814 errs() << "This operation is only currently supported "
Tim Northover4bd286a2014-08-01 13:07:19 +00001815 "for COFF and MachO object files.\n";
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001816 return;
1817 }
1818}
1819
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001820void llvm::printExportsTrie(const ObjectFile *o) {
Nick Kledzikd04bc352014-08-30 00:20:14 +00001821 outs() << "Exports trie:\n";
1822 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1823 printMachOExportsTrie(MachO);
1824 else {
1825 errs() << "This operation is only currently supported "
1826 "for Mach-O executable files.\n";
1827 return;
1828 }
1829}
1830
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001831void llvm::printRebaseTable(const ObjectFile *o) {
Nick Kledzikac431442014-09-12 21:34:15 +00001832 outs() << "Rebase table:\n";
1833 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1834 printMachORebaseTable(MachO);
1835 else {
1836 errs() << "This operation is only currently supported "
1837 "for Mach-O executable files.\n";
1838 return;
1839 }
1840}
1841
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001842void llvm::printBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001843 outs() << "Bind table:\n";
1844 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1845 printMachOBindTable(MachO);
1846 else {
1847 errs() << "This operation is only currently supported "
1848 "for Mach-O executable files.\n";
1849 return;
1850 }
1851}
1852
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001853void llvm::printLazyBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001854 outs() << "Lazy bind table:\n";
1855 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1856 printMachOLazyBindTable(MachO);
1857 else {
1858 errs() << "This operation is only currently supported "
1859 "for Mach-O executable files.\n";
1860 return;
1861 }
1862}
1863
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001864void llvm::printWeakBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001865 outs() << "Weak bind table:\n";
1866 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1867 printMachOWeakBindTable(MachO);
1868 else {
1869 errs() << "This operation is only currently supported "
1870 "for Mach-O executable files.\n";
1871 return;
1872 }
1873}
Nick Kledzikac431442014-09-12 21:34:15 +00001874
Adrian Prantl437105a2015-07-08 02:04:15 +00001875/// Dump the raw contents of the __clangast section so the output can be piped
1876/// into llvm-bcanalyzer.
1877void llvm::printRawClangAST(const ObjectFile *Obj) {
1878 if (outs().is_displayed()) {
1879 errs() << "The -raw-clang-ast option will dump the raw binary contents of "
1880 "the clang ast section.\n"
1881 "Please redirect the output to a file or another program such as "
1882 "llvm-bcanalyzer.\n";
1883 return;
1884 }
1885
1886 StringRef ClangASTSectionName("__clangast");
1887 if (isa<COFFObjectFile>(Obj)) {
1888 ClangASTSectionName = "clangast";
1889 }
1890
1891 Optional<object::SectionRef> ClangASTSection;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001892 for (auto Sec : ToolSectionFilter(*Obj)) {
Adrian Prantl437105a2015-07-08 02:04:15 +00001893 StringRef Name;
1894 Sec.getName(Name);
1895 if (Name == ClangASTSectionName) {
1896 ClangASTSection = Sec;
1897 break;
1898 }
1899 }
1900 if (!ClangASTSection)
1901 return;
1902
1903 StringRef ClangASTContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001904 error(ClangASTSection.getValue().getContents(ClangASTContents));
Adrian Prantl437105a2015-07-08 02:04:15 +00001905 outs().write(ClangASTContents.data(), ClangASTContents.size());
1906}
1907
Sanjoy Das6f567a42015-06-22 18:03:02 +00001908static void printFaultMaps(const ObjectFile *Obj) {
1909 const char *FaultMapSectionName = nullptr;
1910
1911 if (isa<ELFObjectFileBase>(Obj)) {
1912 FaultMapSectionName = ".llvm_faultmaps";
1913 } else if (isa<MachOObjectFile>(Obj)) {
1914 FaultMapSectionName = "__llvm_faultmaps";
1915 } else {
1916 errs() << "This operation is only currently supported "
1917 "for ELF and Mach-O executable files.\n";
1918 return;
1919 }
1920
1921 Optional<object::SectionRef> FaultMapSection;
1922
Colin LeMahieu77804be2015-07-29 15:45:39 +00001923 for (auto Sec : ToolSectionFilter(*Obj)) {
Sanjoy Das6f567a42015-06-22 18:03:02 +00001924 StringRef Name;
1925 Sec.getName(Name);
1926 if (Name == FaultMapSectionName) {
1927 FaultMapSection = Sec;
1928 break;
1929 }
1930 }
1931
1932 outs() << "FaultMap table:\n";
1933
1934 if (!FaultMapSection.hasValue()) {
1935 outs() << "<not found>\n";
1936 return;
1937 }
1938
1939 StringRef FaultMapContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001940 error(FaultMapSection.getValue().getContents(FaultMapContents));
Sanjoy Das6f567a42015-06-22 18:03:02 +00001941
1942 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1943 FaultMapContents.bytes_end());
1944
1945 outs() << FMP;
1946}
1947
Davide Italiano1bdaa202016-09-18 04:39:15 +00001948static void printPrivateFileHeaders(const ObjectFile *o, bool onlyFirst) {
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001949 if (o->isELF())
Davide Italiano1bdaa202016-09-18 04:39:15 +00001950 return printELFFileHeader(o);
1951 if (o->isCOFF())
1952 return printCOFFFileHeader(o);
Derek Schuff2c6f75d2016-11-30 16:49:11 +00001953 if (o->isWasm())
1954 return printWasmFileHeader(o);
Davide Italiano1bdaa202016-09-18 04:39:15 +00001955 if (o->isMachO()) {
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001956 printMachOFileHeader(o);
Davide Italiano1bdaa202016-09-18 04:39:15 +00001957 if (!onlyFirst)
1958 printMachOLoadCommands(o);
1959 return;
1960 }
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001961 report_error(o->getFileName(), "Invalid/Unsupported object file format");
Rui Ueyamac2bed422013-09-27 21:04:00 +00001962}
1963
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001964static void DumpObject(const ObjectFile *o, const Archive *a = nullptr) {
1965 StringRef ArchiveName = a != nullptr ? a->getFileName() : "";
Adrian Prantl437105a2015-07-08 02:04:15 +00001966 // Avoid other output when using a raw option.
1967 if (!RawClangAST) {
1968 outs() << '\n';
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001969 if (a)
1970 outs() << a->getFileName() << "(" << o->getFileName() << ")";
1971 else
1972 outs() << o->getFileName();
1973 outs() << ":\tfile format " << o->getFileFormatName() << "\n\n";
Adrian Prantl437105a2015-07-08 02:04:15 +00001974 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001975
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001976 if (Disassemble)
Michael J. Spencer51862b32011-10-13 22:17:18 +00001977 DisassembleObject(o, Relocations);
1978 if (Relocations && !Disassemble)
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001979 PrintRelocations(o);
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001980 if (SectionHeaders)
1981 PrintSectionHeaders(o);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001982 if (SectionContents)
1983 PrintSectionContents(o);
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001984 if (SymbolTable)
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001985 PrintSymbolTable(o, ArchiveName);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001986 if (UnwindInfo)
1987 PrintUnwindInfo(o);
Davide Italiano1bdaa202016-09-18 04:39:15 +00001988 if (PrivateHeaders || FirstPrivateHeader)
1989 printPrivateFileHeaders(o, FirstPrivateHeader);
Nick Kledzikd04bc352014-08-30 00:20:14 +00001990 if (ExportsTrie)
1991 printExportsTrie(o);
Nick Kledzikac431442014-09-12 21:34:15 +00001992 if (Rebase)
1993 printRebaseTable(o);
Nick Kledzik56ebef42014-09-16 01:41:51 +00001994 if (Bind)
1995 printBindTable(o);
1996 if (LazyBind)
1997 printLazyBindTable(o);
1998 if (WeakBind)
1999 printWeakBindTable(o);
Adrian Prantl437105a2015-07-08 02:04:15 +00002000 if (RawClangAST)
2001 printRawClangAST(o);
Sanjoy Das6f567a42015-06-22 18:03:02 +00002002 if (PrintFaultMaps)
2003 printFaultMaps(o);
Igor Laevsky03a670c2016-01-26 15:09:42 +00002004 if (DwarfDumpType != DIDT_Null) {
2005 std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*o));
2006 // Dump the complete DWARF structure.
2007 DICtx->dump(outs(), DwarfDumpType, true /* DumpEH */);
2008 }
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002009}
2010
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00002011static void DumpObject(const COFFImportFile *I, const Archive *A) {
2012 StringRef ArchiveName = A ? A->getFileName() : "";
2013
2014 // Avoid other output when using a raw option.
2015 if (!RawClangAST)
2016 outs() << '\n'
2017 << ArchiveName << "(" << I->getFileName() << ")"
2018 << ":\tfile format COFF-import-file"
2019 << "\n\n";
2020
2021 if (SymbolTable)
2022 printCOFFSymbolTable(I);
2023}
2024
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002025/// @brief Dump each object file in \a a;
2026static void DumpArchive(const Archive *a) {
Mehdi Amini41af4302016-11-11 04:28:40 +00002027 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00002028 for (auto &C : a->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002029 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2030 if (!ChildOrErr) {
2031 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2032 report_error(a->getFileName(), C, std::move(E));
2033 continue;
2034 }
Rafael Espindolaae460022014-06-16 16:08:36 +00002035 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002036 DumpObject(o, a);
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00002037 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
2038 DumpObject(I, a);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002039 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00002040 report_error(a->getFileName(), object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002041 }
Lang Hamesfc209622016-07-14 02:24:01 +00002042 if (Err)
2043 report_error(a->getFileName(), std::move(Err));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002044}
2045
2046/// @brief Open file and figure out how to dump it.
2047static void DumpInput(StringRef file) {
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002048
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002049 // If we are using the Mach-O specific object file parser, then let it parse
2050 // the file and process the command line options. So the -arch flags can
2051 // be used to select specific slices, etc.
2052 if (MachOOpt) {
2053 ParseInputMachO(file);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002054 return;
2055 }
2056
2057 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00002058 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
2059 if (!BinaryOrErr)
Kevin Enderbyb34e3a12016-05-05 17:43:35 +00002060 report_error(file, BinaryOrErr.takeError());
Rafael Espindola48af1c22014-08-19 18:44:46 +00002061 Binary &Binary = *BinaryOrErr.get().getBinary();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002062
Rafael Espindola3f6481d2014-08-01 14:31:55 +00002063 if (Archive *a = dyn_cast<Archive>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002064 DumpArchive(a);
Rafael Espindola3f6481d2014-08-01 14:31:55 +00002065 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002066 DumpObject(o);
Jim Grosbachaf9aec02012-08-07 17:53:14 +00002067 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00002068 report_error(file, object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002069}
2070
Michael J. Spencer2670c252011-01-20 06:39:06 +00002071int main(int argc, char **argv) {
2072 // Print a stack trace if we signal out.
Richard Smith2ad6d482016-06-09 00:53:21 +00002073 sys::PrintStackTraceOnErrorSignal(argv[0]);
Michael J. Spencer2670c252011-01-20 06:39:06 +00002074 PrettyStackTraceProgram X(argc, argv);
2075 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
2076
2077 // Initialize targets and assembly printers/parsers.
2078 llvm::InitializeAllTargetInfos();
Evan Cheng8c886a42011-07-22 21:58:54 +00002079 llvm::InitializeAllTargetMCs();
Michael J. Spencer2670c252011-01-20 06:39:06 +00002080 llvm::InitializeAllDisassemblers();
2081
Pete Cooper28fb4fc2012-05-03 23:20:10 +00002082 // Register the target printer for --version.
2083 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
2084
Michael J. Spencer2670c252011-01-20 06:39:06 +00002085 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
2086 TripleName = Triple::normalize(TripleName);
2087
2088 ToolName = argv[0];
2089
2090 // Defaults to a.out if no filenames specified.
2091 if (InputFilenames.size() == 0)
2092 InputFilenames.push_back("a.out");
2093
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00002094 if (DisassembleAll || PrintSource || PrintLines)
Colin LeMahieuf34933e2015-07-23 20:58:49 +00002095 Disassemble = true;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002096 if (!Disassemble
2097 && !Relocations
2098 && !SectionHeaders
2099 && !SectionContents
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00002100 && !SymbolTable
Michael J. Spencer209565db2013-01-06 03:56:49 +00002101 && !UnwindInfo
Nick Kledzikd04bc352014-08-30 00:20:14 +00002102 && !PrivateHeaders
Kevin Enderby0ae163f2016-01-13 00:25:36 +00002103 && !FirstPrivateHeader
Nick Kledzikac431442014-09-12 21:34:15 +00002104 && !ExportsTrie
Nick Kledzik56ebef42014-09-16 01:41:51 +00002105 && !Rebase
2106 && !Bind
2107 && !LazyBind
Kevin Enderby131d1772015-01-09 19:22:37 +00002108 && !WeakBind
Adrian Prantl437105a2015-07-08 02:04:15 +00002109 && !RawClangAST
Kevin Enderby13023a12015-01-15 23:19:11 +00002110 && !(UniversalHeaders && MachOOpt)
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00002111 && !(ArchiveHeaders && MachOOpt)
Kevin Enderby69fe98d2015-01-23 18:52:17 +00002112 && !(IndirectSymbols && MachOOpt)
Kevin Enderby9a509442015-01-27 21:28:24 +00002113 && !(DataInCode && MachOOpt)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002114 && !(LinkOptHints && MachOOpt)
Kevin Enderbycd66be52015-03-11 22:06:32 +00002115 && !(InfoPlist && MachOOpt)
Kevin Enderbybc847fa2015-03-16 20:08:09 +00002116 && !(DylibsUsed && MachOOpt)
2117 && !(DylibId && MachOOpt)
Kevin Enderby0fc11822015-04-01 20:57:01 +00002118 && !(ObjcMetaData && MachOOpt)
Colin LeMahieufcc32762015-07-29 19:08:10 +00002119 && !(FilterSections.size() != 0 && MachOOpt)
Igor Laevsky03a670c2016-01-26 15:09:42 +00002120 && !PrintFaultMaps
2121 && DwarfDumpType == DIDT_Null) {
Michael J. Spencer2670c252011-01-20 06:39:06 +00002122 cl::PrintHelpMessage();
2123 return 2;
2124 }
2125
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002126 std::for_each(InputFilenames.begin(), InputFilenames.end(),
2127 DumpInput);
Michael J. Spencer2670c252011-01-20 06:39:06 +00002128
Davide Italianoccd53fe2015-08-05 07:18:31 +00002129 return EXIT_SUCCESS;
Michael J. Spencer2670c252011-01-20 06:39:06 +00002130}