blob: 8373f0ce3f1ef5ceeda3afd425c84a404d761c86 [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) {
Ivan Krasin1ed78962017-01-13 16:45:15 +0000360 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000361 // TheTriple defaults to ELF, and COFF doesn't have an environment:
362 // the best we can do here is indicate that it is mach-o.
363 if (Obj->isMachO())
Saleem Abdulrasool35476332014-03-06 20:47:11 +0000364 TheTriple.setObjectFormat(Triple::MachO);
Saleem Abdulrasool98938f12014-04-17 06:17:23 +0000365
366 if (Obj->isCOFF()) {
367 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
368 if (COFFObj->getArch() == Triple::thumb)
369 TheTriple.setTriple("thumbv7-windows");
370 }
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000371 }
Ivan Krasin1ed78962017-01-13 16:45:15 +0000372 } else
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000373 TheTriple.setTriple(Triple::normalize(TripleName));
Michael J. Spencer2670c252011-01-20 06:39:06 +0000374
375 // Get the target specific parser.
376 std::string Error;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000377 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
378 Error);
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000379 if (!TheTarget) {
380 if (Obj)
381 report_error(Obj->getFileName(), "can't find target: " + Error);
382 else
383 error("can't find target: " + Error);
384 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000385
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000386 // Update the triple name and return the found target.
387 TripleName = TheTriple.getTriple();
388 return TheTarget;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000389}
390
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000391bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
Rafael Espindola704cd842015-07-06 15:47:43 +0000392 return a.getOffset() < b.getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +0000393}
394
Colin LeMahieufb76b002015-05-28 19:07:14 +0000395namespace {
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000396class SourcePrinter {
397protected:
398 DILineInfo OldLineInfo;
399 const ObjectFile *Obj;
400 std::unique_ptr<symbolize::LLVMSymbolizer> Symbolizer;
401 // File name to file contents of source
402 std::unordered_map<std::string, std::unique_ptr<MemoryBuffer>> SourceCache;
403 // Mark the line endings of the cached source
404 std::unordered_map<std::string, std::vector<StringRef>> LineCache;
405
406private:
407 bool cacheSource(std::string File);
408
409public:
410 virtual ~SourcePrinter() {}
411 SourcePrinter() : Obj(nullptr), Symbolizer(nullptr) {}
412 SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch) : Obj(Obj) {
413 symbolize::LLVMSymbolizer::Options SymbolizerOpts(
414 DILineInfoSpecifier::FunctionNameKind::None, true, false, false,
415 DefaultArch);
416 Symbolizer.reset(new symbolize::LLVMSymbolizer(SymbolizerOpts));
417 }
418 virtual void printSourceLine(raw_ostream &OS, uint64_t Address,
419 StringRef Delimiter = "; ");
420};
421
422bool SourcePrinter::cacheSource(std::string File) {
423 auto BufferOrError = MemoryBuffer::getFile(File);
424 if (!BufferOrError)
425 return false;
426 // Chomp the file to get lines
427 size_t BufferSize = (*BufferOrError)->getBufferSize();
428 const char *BufferStart = (*BufferOrError)->getBufferStart();
429 for (const char *Start = BufferStart, *End = BufferStart;
430 End < BufferStart + BufferSize; End++)
431 if (*End == '\n' || End == BufferStart + BufferSize - 1 ||
432 (*End == '\r' && *(End + 1) == '\n')) {
433 LineCache[File].push_back(StringRef(Start, End - Start));
434 if (*End == '\r')
435 End++;
436 Start = End + 1;
437 }
438 SourceCache[File] = std::move(*BufferOrError);
439 return true;
440}
441
442void SourcePrinter::printSourceLine(raw_ostream &OS, uint64_t Address,
443 StringRef Delimiter) {
444 if (!Symbolizer)
445 return;
446 DILineInfo LineInfo = DILineInfo();
447 auto ExpectecLineInfo =
448 Symbolizer->symbolizeCode(Obj->getFileName(), Address);
449 if (!ExpectecLineInfo)
450 consumeError(ExpectecLineInfo.takeError());
451 else
452 LineInfo = *ExpectecLineInfo;
453
454 if ((LineInfo.FileName == "<invalid>") || OldLineInfo.Line == LineInfo.Line ||
455 LineInfo.Line == 0)
456 return;
457
458 if (PrintLines)
459 OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line << "\n";
460 if (PrintSource) {
461 if (SourceCache.find(LineInfo.FileName) == SourceCache.end())
462 if (!cacheSource(LineInfo.FileName))
463 return;
464 auto FileBuffer = SourceCache.find(LineInfo.FileName);
465 if (FileBuffer != SourceCache.end()) {
466 auto LineBuffer = LineCache.find(LineInfo.FileName);
467 if (LineBuffer != LineCache.end())
468 // Vector begins at 0, line numbers are non-zero
469 OS << Delimiter << LineBuffer->second[LineInfo.Line - 1].ltrim()
470 << "\n";
471 }
472 }
473 OldLineInfo = LineInfo;
474}
475
Hemant Kulkarni5b60f632016-08-25 19:41:08 +0000476static bool isArmElf(const ObjectFile *Obj) {
477 return (Obj->isELF() &&
478 (Obj->getArch() == Triple::aarch64 ||
479 Obj->getArch() == Triple::aarch64_be ||
480 Obj->getArch() == Triple::arm || Obj->getArch() == Triple::armeb ||
481 Obj->getArch() == Triple::thumb ||
482 Obj->getArch() == Triple::thumbeb));
483}
484
Colin LeMahieufb76b002015-05-28 19:07:14 +0000485class PrettyPrinter {
486public:
Colin LeMahieu0b5890d2015-05-28 20:59:08 +0000487 virtual ~PrettyPrinter(){}
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000488 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
Colin LeMahieufb76b002015-05-28 19:07:14 +0000489 ArrayRef<uint8_t> Bytes, uint64_t Address,
490 raw_ostream &OS, StringRef Annot,
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000491 MCSubtargetInfo const &STI, SourcePrinter *SP) {
492 if (SP && (PrintSource || PrintLines))
493 SP->printSourceLine(OS, Address);
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000494 OS << format("%8" PRIx64 ":", Address);
Colin LeMahieufb76b002015-05-28 19:07:14 +0000495 if (!NoShowRawInsn) {
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000496 OS << "\t";
497 dumpBytes(Bytes, OS);
Colin LeMahieufb76b002015-05-28 19:07:14 +0000498 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000499 if (MI)
500 IP.printInst(MI, OS, "", STI);
501 else
502 OS << " <unknown>";
Colin LeMahieufb76b002015-05-28 19:07:14 +0000503 }
504};
505PrettyPrinter PrettyPrinterInst;
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000506class HexagonPrettyPrinter : public PrettyPrinter {
507public:
508 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
509 raw_ostream &OS) {
510 uint32_t opcode =
511 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
512 OS << format("%8" PRIx64 ":", Address);
513 if (!NoShowRawInsn) {
514 OS << "\t";
515 dumpBytes(Bytes.slice(0, 4), OS);
516 OS << format("%08" PRIx32, opcode);
517 }
518 }
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000519 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
520 uint64_t Address, raw_ostream &OS, StringRef Annot,
521 MCSubtargetInfo const &STI, SourcePrinter *SP) override {
Hemant Kulkarnie77a0a92016-08-18 21:50:13 +0000522 if (SP && (PrintSource || PrintLines))
523 SP->printSourceLine(OS, Address, "");
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000524 if (!MI) {
525 printLead(Bytes, Address, OS);
526 OS << " <unknown>";
527 return;
528 }
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000529 std::string Buffer;
530 {
531 raw_string_ostream TempStream(Buffer);
532 IP.printInst(MI, TempStream, "", STI);
533 }
534 StringRef Contents(Buffer);
535 // Split off bundle attributes
536 auto PacketBundle = Contents.rsplit('\n');
537 // Split off first instruction from the rest
538 auto HeadTail = PacketBundle.first.split('\n');
539 auto Preamble = " { ";
540 auto Separator = "";
541 while(!HeadTail.first.empty()) {
542 OS << Separator;
543 Separator = "\n";
Hemant Kulkarnie77a0a92016-08-18 21:50:13 +0000544 if (SP && (PrintSource || PrintLines))
545 SP->printSourceLine(OS, Address, "");
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000546 printLead(Bytes, Address, OS);
547 OS << Preamble;
548 Preamble = " ";
549 StringRef Inst;
550 auto Duplex = HeadTail.first.split('\v');
551 if(!Duplex.second.empty()){
552 OS << Duplex.first;
553 OS << "; ";
554 Inst = Duplex.second;
555 }
556 else
557 Inst = HeadTail.first;
558 OS << Inst;
559 Bytes = Bytes.slice(4);
560 Address += 4;
561 HeadTail = HeadTail.second.split('\n');
562 }
563 OS << " } " << PacketBundle.second;
564 }
565};
566HexagonPrettyPrinter HexagonPrettyPrinterInst;
Valery Pykhtinde048052016-04-07 07:24:01 +0000567
568class AMDGCNPrettyPrinter : public PrettyPrinter {
569public:
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000570 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
571 uint64_t Address, raw_ostream &OS, StringRef Annot,
572 MCSubtargetInfo const &STI, SourcePrinter *SP) override {
Matt Arsenault87d80db2016-04-22 21:23:41 +0000573 if (!MI) {
574 OS << " <unknown>";
575 return;
576 }
577
Valery Pykhtinde048052016-04-07 07:24:01 +0000578 SmallString<40> InstStr;
579 raw_svector_ostream IS(InstStr);
580
581 IP.printInst(MI, IS, "", STI);
582
Valery Pykhtin8e79f5b2016-04-07 08:38:20 +0000583 OS << left_justify(IS.str(), 60) << format("// %012" PRIX64 ": ", Address);
Valery Pykhtinde048052016-04-07 07:24:01 +0000584 typedef support::ulittle32_t U32;
585 for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
586 Bytes.size() / sizeof(U32)))
587 // D should be explicitly casted to uint32_t here as it is passed
588 // by format to snprintf as vararg.
Valery Pykhtin8e79f5b2016-04-07 08:38:20 +0000589 OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D));
Valery Pykhtinde048052016-04-07 07:24:01 +0000590
591 if (!Annot.empty())
592 OS << "// " << Annot;
593 }
594};
595AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
596
Alexei Starovoitov3b9efca2016-12-13 19:07:08 +0000597class BPFPrettyPrinter : public PrettyPrinter {
598public:
599 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
600 uint64_t Address, raw_ostream &OS, StringRef Annot,
601 MCSubtargetInfo const &STI, SourcePrinter *SP) override {
602 if (SP && (PrintSource || PrintLines))
603 SP->printSourceLine(OS, Address);
604 OS << format("%8" PRId64 ":", Address / 8);
605 if (!NoShowRawInsn) {
606 OS << "\t";
607 dumpBytes(Bytes, OS);
608 }
609 if (MI)
610 IP.printInst(MI, OS, "", STI);
611 else
612 OS << " <unknown>";
613 }
614};
615BPFPrettyPrinter BPFPrettyPrinterInst;
616
Colin LeMahieu35436a22015-05-29 14:48:25 +0000617PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000618 switch(Triple.getArch()) {
619 default:
620 return PrettyPrinterInst;
621 case Triple::hexagon:
622 return HexagonPrettyPrinterInst;
Valery Pykhtinde048052016-04-07 07:24:01 +0000623 case Triple::amdgcn:
624 return AMDGCNPrettyPrinterInst;
Alexei Starovoitov3b9efca2016-12-13 19:07:08 +0000625 case Triple::bpfel:
626 case Triple::bpfeb:
627 return BPFPrettyPrinterInst;
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000628 }
Colin LeMahieufb76b002015-05-28 19:07:14 +0000629}
630}
631
Rafael Espindola37070a52015-06-03 04:48:06 +0000632template <class ELFT>
Rafael Espindola37070a52015-06-03 04:48:06 +0000633static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000634 const RelocationRef &RelRef,
Rafael Espindola37070a52015-06-03 04:48:06 +0000635 SmallVectorImpl<char> &Result) {
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000636 DataRefImpl Rel = RelRef.getRawDataRefImpl();
637
Rafael Espindola37070a52015-06-03 04:48:06 +0000638 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
639 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000640 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
641
Rafael Espindola37070a52015-06-03 04:48:06 +0000642 const ELFFile<ELFT> &EF = *Obj->getELFFile();
643
Davide Italiano6cf09262016-11-16 05:10:28 +0000644 auto SecOrErr = EF.getSection(Rel.d.a);
645 if (!SecOrErr)
646 return errorToErrorCode(SecOrErr.takeError());
Rafael Espindola6def3042015-07-01 12:56:27 +0000647 const Elf_Shdr *Sec = *SecOrErr;
Davide Italiano6cf09262016-11-16 05:10:28 +0000648 auto SymTabOrErr = EF.getSection(Sec->sh_link);
649 if (!SymTabOrErr)
650 return errorToErrorCode(SymTabOrErr.takeError());
Rafael Espindola6def3042015-07-01 12:56:27 +0000651 const Elf_Shdr *SymTab = *SymTabOrErr;
Rafael Espindola719dc7c2015-06-29 12:38:31 +0000652 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
653 SymTab->sh_type == ELF::SHT_DYNSYM);
Davide Italiano6cf09262016-11-16 05:10:28 +0000654 auto StrTabSec = EF.getSection(SymTab->sh_link);
655 if (!StrTabSec)
656 return errorToErrorCode(StrTabSec.takeError());
657 auto StrTabOrErr = EF.getStringTable(*StrTabSec);
658 if (!StrTabOrErr)
659 return errorToErrorCode(StrTabOrErr.takeError());
Rafael Espindola6a1bfb22015-06-29 14:39:25 +0000660 StringRef StrTab = *StrTabOrErr;
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000661 uint8_t type = RelRef.getType();
Rafael Espindola37070a52015-06-03 04:48:06 +0000662 StringRef res;
663 int64_t addend = 0;
Rafael Espindola6def3042015-07-01 12:56:27 +0000664 switch (Sec->sh_type) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000665 default:
666 return object_error::parse_failed;
667 case ELF::SHT_REL: {
Rafael Espindola37070a52015-06-03 04:48:06 +0000668 // TODO: Read implicit addend from section data.
669 break;
670 }
671 case ELF::SHT_RELA: {
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000672 const Elf_Rela *ERela = Obj->getRela(Rel);
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000673 addend = ERela->r_addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000674 break;
675 }
676 }
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000677 symbol_iterator SI = RelRef.getSymbol();
678 const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
Rafael Espindola75d5b542015-06-03 05:14:22 +0000679 StringRef Target;
Rafael Espindola75d5b542015-06-03 05:14:22 +0000680 if (symb->getType() == ELF::STT_SECTION) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000681 Expected<section_iterator> SymSI = SI->getSection();
682 if (!SymSI)
683 return errorToErrorCode(SymSI.takeError());
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000684 const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
Davide Italiano6cf09262016-11-16 05:10:28 +0000685 auto SecName = EF.getSectionName(SymSec);
686 if (!SecName)
687 return errorToErrorCode(SecName.takeError());
Rafael Espindola75d5b542015-06-03 05:14:22 +0000688 Target = *SecName;
689 } else {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000690 Expected<StringRef> SymName = symb->getName(StrTab);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000691 if (!SymName)
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000692 return errorToErrorCode(SymName.takeError());
Rafael Espindola75d5b542015-06-03 05:14:22 +0000693 Target = *SymName;
694 }
Rafael Espindola37070a52015-06-03 04:48:06 +0000695 switch (EF.getHeader()->e_machine) {
696 case ELF::EM_X86_64:
697 switch (type) {
698 case ELF::R_X86_64_PC8:
699 case ELF::R_X86_64_PC16:
700 case ELF::R_X86_64_PC32: {
701 std::string fmtbuf;
702 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000703 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
Rafael Espindola37070a52015-06-03 04:48:06 +0000704 fmt.flush();
705 Result.append(fmtbuf.begin(), fmtbuf.end());
706 } break;
707 case ELF::R_X86_64_8:
708 case ELF::R_X86_64_16:
709 case ELF::R_X86_64_32:
710 case ELF::R_X86_64_32S:
711 case ELF::R_X86_64_64: {
712 std::string fmtbuf;
713 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000714 fmt << Target << (addend < 0 ? "" : "+") << addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000715 fmt.flush();
716 Result.append(fmtbuf.begin(), fmtbuf.end());
717 } break;
718 default:
719 res = "Unknown";
720 }
721 break;
Jacques Pienaarea9f25a2016-03-01 21:21:42 +0000722 case ELF::EM_LANAI:
Dylan McKay11661122016-09-28 13:15:17 +0000723 case ELF::EM_AVR:
Rafael Espindola37070a52015-06-03 04:48:06 +0000724 case ELF::EM_AARCH64: {
725 std::string fmtbuf;
726 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000727 fmt << Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000728 if (addend != 0)
729 fmt << (addend < 0 ? "" : "+") << addend;
730 fmt.flush();
731 Result.append(fmtbuf.begin(), fmtbuf.end());
732 break;
733 }
734 case ELF::EM_386:
Michael Kupersteina3b79dd2015-11-04 11:21:50 +0000735 case ELF::EM_IAMCU:
Rafael Espindola37070a52015-06-03 04:48:06 +0000736 case ELF::EM_ARM:
737 case ELF::EM_HEXAGON:
738 case ELF::EM_MIPS:
Alexei Starovoitovcfb51f52016-07-15 22:27:55 +0000739 case ELF::EM_BPF:
Alex Bradbury1524f622016-11-01 16:59:37 +0000740 case ELF::EM_RISCV:
Rafael Espindola75d5b542015-06-03 05:14:22 +0000741 res = Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000742 break;
Dan Gohman46350172016-01-12 20:56:01 +0000743 case ELF::EM_WEBASSEMBLY:
744 switch (type) {
745 case ELF::R_WEBASSEMBLY_DATA: {
746 std::string fmtbuf;
747 raw_string_ostream fmt(fmtbuf);
748 fmt << Target << (addend < 0 ? "" : "+") << addend;
749 fmt.flush();
750 Result.append(fmtbuf.begin(), fmtbuf.end());
751 break;
752 }
753 case ELF::R_WEBASSEMBLY_FUNCTION:
754 res = Target;
755 break;
756 default:
757 res = "Unknown";
758 }
759 break;
Rafael Espindola37070a52015-06-03 04:48:06 +0000760 default:
761 res = "Unknown";
762 }
763 if (Result.empty())
764 Result.append(res.begin(), res.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000765 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000766}
767
768static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000769 const RelocationRef &Rel,
Rafael Espindola37070a52015-06-03 04:48:06 +0000770 SmallVectorImpl<char> &Result) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000771 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
772 return getRelocationValueString(ELF32LE, Rel, Result);
773 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
774 return getRelocationValueString(ELF64LE, Rel, Result);
775 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
776 return getRelocationValueString(ELF32BE, Rel, Result);
777 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
778 return getRelocationValueString(ELF64BE, Rel, Result);
779}
780
781static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
782 const RelocationRef &Rel,
783 SmallVectorImpl<char> &Result) {
784 symbol_iterator SymI = Rel.getSymbol();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000785 Expected<StringRef> SymNameOrErr = SymI->getName();
786 if (!SymNameOrErr)
787 return errorToErrorCode(SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000788 StringRef SymName = *SymNameOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000789 Result.append(SymName.begin(), SymName.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000790 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000791}
792
793static void printRelocationTargetName(const MachOObjectFile *O,
794 const MachO::any_relocation_info &RE,
795 raw_string_ostream &fmt) {
796 bool IsScattered = O->isRelocationScattered(RE);
797
798 // Target of a scattered relocation is an address. In the interest of
799 // generating pretty output, scan through the symbol table looking for a
800 // symbol that aligns with that address. If we find one, print it.
801 // Otherwise, we just print the hex address of the target.
802 if (IsScattered) {
803 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
804
805 for (const SymbolRef &Symbol : O->symbols()) {
806 std::error_code ec;
Kevin Enderby931cb652016-06-24 18:24:42 +0000807 Expected<uint64_t> Addr = Symbol.getAddress();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000808 if (!Addr)
809 report_error(O->getFileName(), Addr.takeError());
Rafael Espindolaed067c42015-07-03 18:19:00 +0000810 if (*Addr != Val)
Rafael Espindola37070a52015-06-03 04:48:06 +0000811 continue;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000812 Expected<StringRef> Name = Symbol.getName();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000813 if (!Name)
814 report_error(O->getFileName(), Name.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000815 fmt << *Name;
Rafael Espindola37070a52015-06-03 04:48:06 +0000816 return;
817 }
818
819 // If we couldn't find a symbol that this relocation refers to, try
820 // to find a section beginning instead.
Colin LeMahieu77804be2015-07-29 15:45:39 +0000821 for (const SectionRef &Section : ToolSectionFilter(*O)) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000822 std::error_code ec;
823
824 StringRef Name;
825 uint64_t Addr = Section.getAddress();
826 if (Addr != Val)
827 continue;
828 if ((ec = Section.getName(Name)))
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000829 report_error(O->getFileName(), ec);
Rafael Espindola37070a52015-06-03 04:48:06 +0000830 fmt << Name;
831 return;
832 }
833
834 fmt << format("0x%x", Val);
835 return;
836 }
837
838 StringRef S;
839 bool isExtern = O->getPlainRelocationExternal(RE);
840 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
841
842 if (isExtern) {
843 symbol_iterator SI = O->symbol_begin();
844 advance(SI, Val);
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000845 Expected<StringRef> SOrErr = SI->getName();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000846 if (!SOrErr)
847 report_error(O->getFileName(), SOrErr.takeError());
Davide Italianoccd53fe2015-08-05 07:18:31 +0000848 S = *SOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000849 } else {
850 section_iterator SI = O->section_begin();
851 // Adjust for the fact that sections are 1-indexed.
852 advance(SI, Val - 1);
853 SI->getName(S);
854 }
855
856 fmt << S;
857}
858
859static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
860 const RelocationRef &RelRef,
861 SmallVectorImpl<char> &Result) {
862 DataRefImpl Rel = RelRef.getRawDataRefImpl();
863 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
864
865 unsigned Arch = Obj->getArch();
866
867 std::string fmtbuf;
868 raw_string_ostream fmt(fmtbuf);
869 unsigned Type = Obj->getAnyRelocationType(RE);
870 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
871
872 // Determine any addends that should be displayed with the relocation.
873 // These require decoding the relocation type, which is triple-specific.
874
875 // X86_64 has entirely custom relocation types.
876 if (Arch == Triple::x86_64) {
877 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
878
879 switch (Type) {
880 case MachO::X86_64_RELOC_GOT_LOAD:
881 case MachO::X86_64_RELOC_GOT: {
882 printRelocationTargetName(Obj, RE, fmt);
883 fmt << "@GOT";
884 if (isPCRel)
885 fmt << "PCREL";
886 break;
887 }
888 case MachO::X86_64_RELOC_SUBTRACTOR: {
889 DataRefImpl RelNext = Rel;
890 Obj->moveRelocationNext(RelNext);
891 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
892
893 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
894 // X86_64_RELOC_UNSIGNED.
895 // NOTE: Scattered relocations don't exist on x86_64.
896 unsigned RType = Obj->getAnyRelocationType(RENext);
897 if (RType != MachO::X86_64_RELOC_UNSIGNED)
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000898 report_error(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
899 "X86_64_RELOC_SUBTRACTOR.");
Rafael Espindola37070a52015-06-03 04:48:06 +0000900
901 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
902 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
903 printRelocationTargetName(Obj, RENext, fmt);
904 fmt << "-";
905 printRelocationTargetName(Obj, RE, fmt);
906 break;
907 }
908 case MachO::X86_64_RELOC_TLV:
909 printRelocationTargetName(Obj, RE, fmt);
910 fmt << "@TLV";
911 if (isPCRel)
912 fmt << "P";
913 break;
914 case MachO::X86_64_RELOC_SIGNED_1:
915 printRelocationTargetName(Obj, RE, fmt);
916 fmt << "-1";
917 break;
918 case MachO::X86_64_RELOC_SIGNED_2:
919 printRelocationTargetName(Obj, RE, fmt);
920 fmt << "-2";
921 break;
922 case MachO::X86_64_RELOC_SIGNED_4:
923 printRelocationTargetName(Obj, RE, fmt);
924 fmt << "-4";
925 break;
926 default:
927 printRelocationTargetName(Obj, RE, fmt);
928 break;
929 }
930 // X86 and ARM share some relocation types in common.
931 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
932 Arch == Triple::ppc) {
933 // Generic relocation types...
934 switch (Type) {
935 case MachO::GENERIC_RELOC_PAIR: // prints no info
Rui Ueyama7d099192015-06-09 15:20:42 +0000936 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000937 case MachO::GENERIC_RELOC_SECTDIFF: {
938 DataRefImpl RelNext = Rel;
939 Obj->moveRelocationNext(RelNext);
940 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
941
942 // X86 sect diff's must be followed by a relocation of type
943 // GENERIC_RELOC_PAIR.
944 unsigned RType = Obj->getAnyRelocationType(RENext);
945
946 if (RType != MachO::GENERIC_RELOC_PAIR)
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000947 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
948 "GENERIC_RELOC_SECTDIFF.");
Rafael Espindola37070a52015-06-03 04:48:06 +0000949
950 printRelocationTargetName(Obj, RE, fmt);
951 fmt << "-";
952 printRelocationTargetName(Obj, RENext, fmt);
953 break;
954 }
955 }
956
957 if (Arch == Triple::x86 || Arch == Triple::ppc) {
958 switch (Type) {
959 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
960 DataRefImpl RelNext = Rel;
961 Obj->moveRelocationNext(RelNext);
962 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
963
964 // X86 sect diff's must be followed by a relocation of type
965 // GENERIC_RELOC_PAIR.
966 unsigned RType = Obj->getAnyRelocationType(RENext);
967 if (RType != MachO::GENERIC_RELOC_PAIR)
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000968 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
969 "GENERIC_RELOC_LOCAL_SECTDIFF.");
Rafael Espindola37070a52015-06-03 04:48:06 +0000970
971 printRelocationTargetName(Obj, RE, fmt);
972 fmt << "-";
973 printRelocationTargetName(Obj, RENext, fmt);
974 break;
975 }
976 case MachO::GENERIC_RELOC_TLV: {
977 printRelocationTargetName(Obj, RE, fmt);
978 fmt << "@TLV";
979 if (IsPCRel)
980 fmt << "P";
981 break;
982 }
983 default:
984 printRelocationTargetName(Obj, RE, fmt);
985 }
986 } else { // ARM-specific relocations
987 switch (Type) {
988 case MachO::ARM_RELOC_HALF:
989 case MachO::ARM_RELOC_HALF_SECTDIFF: {
990 // Half relocations steal a bit from the length field to encode
991 // whether this is an upper16 or a lower16 relocation.
992 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
993
994 if (isUpper)
995 fmt << ":upper16:(";
996 else
997 fmt << ":lower16:(";
998 printRelocationTargetName(Obj, RE, fmt);
999
1000 DataRefImpl RelNext = Rel;
1001 Obj->moveRelocationNext(RelNext);
1002 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
1003
1004 // ARM half relocs must be followed by a relocation of type
1005 // ARM_RELOC_PAIR.
1006 unsigned RType = Obj->getAnyRelocationType(RENext);
1007 if (RType != MachO::ARM_RELOC_PAIR)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001008 report_error(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
1009 "ARM_RELOC_HALF");
Rafael Espindola37070a52015-06-03 04:48:06 +00001010
1011 // NOTE: The half of the target virtual address is stashed in the
1012 // address field of the secondary relocation, but we can't reverse
1013 // engineer the constant offset from it without decoding the movw/movt
1014 // instruction to find the other half in its immediate field.
1015
1016 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
1017 // symbol/section pointer of the follow-on relocation.
1018 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1019 fmt << "-";
1020 printRelocationTargetName(Obj, RENext, fmt);
1021 }
1022
1023 fmt << ")";
1024 break;
1025 }
1026 default: { printRelocationTargetName(Obj, RE, fmt); }
1027 }
1028 }
1029 } else
1030 printRelocationTargetName(Obj, RE, fmt);
1031
1032 fmt.flush();
1033 Result.append(fmtbuf.begin(), fmtbuf.end());
Rui Ueyama7d099192015-06-09 15:20:42 +00001034 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +00001035}
1036
1037static std::error_code getRelocationValueString(const RelocationRef &Rel,
1038 SmallVectorImpl<char> &Result) {
Rafael Espindola854038e2015-06-26 14:51:16 +00001039 const ObjectFile *Obj = Rel.getObject();
Rafael Espindola37070a52015-06-03 04:48:06 +00001040 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
1041 return getRelocationValueString(ELF, Rel, Result);
1042 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
1043 return getRelocationValueString(COFF, Rel, Result);
1044 auto *MachO = cast<MachOObjectFile>(Obj);
1045 return getRelocationValueString(MachO, Rel, Result);
1046}
1047
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001048/// @brief Indicates whether this relocation should hidden when listing
1049/// relocations, usually because it is the trailing part of a multipart
1050/// relocation that will be printed as part of the leading relocation.
1051static bool getHidden(RelocationRef RelRef) {
1052 const ObjectFile *Obj = RelRef.getObject();
1053 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
1054 if (!MachO)
1055 return false;
1056
1057 unsigned Arch = MachO->getArch();
1058 DataRefImpl Rel = RelRef.getRawDataRefImpl();
1059 uint64_t Type = MachO->getRelocationType(Rel);
1060
1061 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
1062 // is always hidden.
1063 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
1064 if (Type == MachO::GENERIC_RELOC_PAIR)
1065 return true;
1066 } else if (Arch == Triple::x86_64) {
1067 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
1068 // an X86_64_RELOC_SUBTRACTOR.
1069 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
1070 DataRefImpl RelPrev = Rel;
1071 RelPrev.d.a--;
1072 uint64_t PrevType = MachO->getRelocationType(RelPrev);
1073 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
1074 return true;
1075 }
1076 }
1077
1078 return false;
1079}
1080
Sam Koltonc05d7782016-08-17 10:17:57 +00001081static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) {
1082 assert(Obj->isELF());
1083 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1084 return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1085 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1086 return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1087 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1088 return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1089 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1090 return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1091 llvm_unreachable("Unsupported binary format");
1092}
1093
Michael J. Spencer51862b32011-10-13 22:17:18 +00001094static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001095 if (StartAddress > StopAddress)
1096 error("Start address should be less than stop address");
1097
Jim Grosbachaf9aec02012-08-07 17:53:14 +00001098 const Target *TheTarget = getTarget(Obj);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001099
Jack Carter551efd72012-08-28 19:24:49 +00001100 // Package up features to be passed to target/subtarget
Daniel Sanders1d148642016-06-16 09:17:03 +00001101 SubtargetFeatures Features = Obj->getFeatures();
Jack Carter551efd72012-08-28 19:24:49 +00001102 if (MAttrs.size()) {
Jack Carter551efd72012-08-28 19:24:49 +00001103 for (unsigned i = 0; i != MAttrs.size(); ++i)
1104 Features.AddFeature(MAttrs[i]);
Jack Carter551efd72012-08-28 19:24:49 +00001105 }
1106
Ahmed Charles56440fd2014-03-06 05:51:42 +00001107 std::unique_ptr<const MCRegisterInfo> MRI(
1108 TheTarget->createMCRegInfo(TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +00001109 if (!MRI)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001110 report_error(Obj->getFileName(), "no register info for target " +
1111 TripleName);
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001112
1113 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00001114 std::unique_ptr<const MCAsmInfo> AsmInfo(
1115 TheTarget->createMCAsmInfo(*MRI, TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +00001116 if (!AsmInfo)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001117 report_error(Obj->getFileName(), "no assembly info for target " +
1118 TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +00001119 std::unique_ptr<const MCSubtargetInfo> STI(
Daniel Sanders1d148642016-06-16 09:17:03 +00001120 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
Davide Italiano711e4952015-12-17 01:59:50 +00001121 if (!STI)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001122 report_error(Obj->getFileName(), "no subtarget info for target " +
1123 TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +00001124 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
Davide Italiano711e4952015-12-17 01:59:50 +00001125 if (!MII)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001126 report_error(Obj->getFileName(), "no instruction info for target " +
1127 TripleName);
Sam Kolton3381d7a2016-10-06 13:46:08 +00001128 MCObjectFileInfo MOFI;
1129 MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI);
1130 // FIXME: for now initialize MCObjectFileInfo with default values
1131 MOFI.InitMCObjectFileInfo(Triple(TripleName), false, CodeModel::Default, Ctx);
Lang Hamesa1bc0f52014-04-15 04:40:56 +00001132
1133 std::unique_ptr<MCDisassembler> DisAsm(
1134 TheTarget->createMCDisassembler(*STI, Ctx));
Davide Italiano711e4952015-12-17 01:59:50 +00001135 if (!DisAsm)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001136 report_error(Obj->getFileName(), "no disassembler for target " +
1137 TripleName);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001138
Ahmed Charles56440fd2014-03-06 05:51:42 +00001139 std::unique_ptr<const MCInstrAnalysis> MIA(
1140 TheTarget->createMCInstrAnalysis(MII.get()));
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001141
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001142 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Daniel Sanders50f17232015-09-15 16:17:27 +00001143 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1144 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
Davide Italiano711e4952015-12-17 01:59:50 +00001145 if (!IP)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001146 report_error(Obj->getFileName(), "no instruction printer for target " +
1147 TripleName);
Colin LeMahieu14ec76e2015-06-07 21:07:17 +00001148 IP->setPrintImmHex(PrintImmHex);
Colin LeMahieu35436a22015-05-29 14:48:25 +00001149 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001150
Greg Fitzgerald18432272014-03-20 22:55:15 +00001151 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
1152 "\t\t\t%08" PRIx64 ": ";
1153
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001154 SourcePrinter SP(Obj, TheTarget->getName());
1155
Mark Seaborn0929d3d2014-01-25 17:38:19 +00001156 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
1157 // in RelocSecs contain the relocations for section S.
Rafael Espindola4453e42942014-06-13 03:07:50 +00001158 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +00001159 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001160 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001161 section_iterator Sec2 = Section.getRelocatedSection();
Rafael Espindolab5155a52014-02-10 20:24:04 +00001162 if (Sec2 != Obj->section_end())
Alexey Samsonov48803e52014-03-13 14:37:36 +00001163 SectionRelocMap[*Sec2].push_back(Section);
Mark Seaborn0929d3d2014-01-25 17:38:19 +00001164 }
1165
David Majnemer81afca62015-07-07 22:06:59 +00001166 // Create a mapping from virtual address to symbol name. This is used to
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001167 // pretty print the symbols while disassembling.
Sam Koltonc05d7782016-08-17 10:17:57 +00001168 typedef std::vector<std::tuple<uint64_t, StringRef, uint8_t>> SectionSymbolsTy;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001169 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
1170 for (const SymbolRef &Symbol : Obj->symbols()) {
Kevin Enderby931cb652016-06-24 18:24:42 +00001171 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001172 if (!AddressOrErr)
1173 report_error(Obj->getFileName(), AddressOrErr.takeError());
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001174 uint64_t Address = *AddressOrErr;
David Majnemer2603a8fa2015-07-09 18:11:40 +00001175
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001176 Expected<StringRef> Name = Symbol.getName();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001177 if (!Name)
1178 report_error(Obj->getFileName(), Name.takeError());
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001179 if (Name->empty())
1180 continue;
David Majnemer81afca62015-07-07 22:06:59 +00001181
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001182 Expected<section_iterator> SectionOrErr = Symbol.getSection();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001183 if (!SectionOrErr)
1184 report_error(Obj->getFileName(), SectionOrErr.takeError());
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001185 section_iterator SecI = *SectionOrErr;
1186 if (SecI == Obj->section_end())
1187 continue;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001188
Sam Koltonc05d7782016-08-17 10:17:57 +00001189 uint8_t SymbolType = ELF::STT_NOTYPE;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001190 if (Obj->isELF())
Sam Koltonc05d7782016-08-17 10:17:57 +00001191 SymbolType = getElfSymbolType(Obj, Symbol);
David Majnemer81afca62015-07-07 22:06:59 +00001192
Sam Koltonc05d7782016-08-17 10:17:57 +00001193 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1194
David Majnemer81afca62015-07-07 22:06:59 +00001195 }
1196
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001197 // Create a mapping from virtual address to section.
1198 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1199 for (SectionRef Sec : Obj->sections())
1200 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1201 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
1202
1203 // Linked executables (.exe and .dll files) typically don't include a real
1204 // symbol table but they might contain an export table.
1205 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
1206 for (const auto &ExportEntry : COFFObj->export_directories()) {
1207 StringRef Name;
1208 error(ExportEntry.getSymbolName(Name));
1209 if (Name.empty())
1210 continue;
1211 uint32_t RVA;
1212 error(ExportEntry.getExportRVA(RVA));
1213
1214 uint64_t VA = COFFObj->getImageBase() + RVA;
1215 auto Sec = std::upper_bound(
1216 SectionAddresses.begin(), SectionAddresses.end(), VA,
1217 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
1218 return LHS < RHS.first;
1219 });
1220 if (Sec != SectionAddresses.begin())
1221 --Sec;
1222 else
1223 Sec = SectionAddresses.end();
1224
1225 if (Sec != SectionAddresses.end())
Sam Koltonc05d7782016-08-17 10:17:57 +00001226 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001227 }
1228 }
1229
1230 // Sort all the symbols, this allows us to use a simple binary search to find
1231 // a symbol near an address.
1232 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1233 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
1234
Colin LeMahieu77804be2015-07-29 15:45:39 +00001235 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Colin LeMahieuf34933e2015-07-23 20:58:49 +00001236 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
Mark Seaborneb03ac52014-01-25 00:32:01 +00001237 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +00001238
Rafael Espindola80291272014-10-08 15:28:58 +00001239 uint64_t SectionAddr = Section.getAddress();
1240 uint64_t SectSize = Section.getSize();
David Majnemer185b5b12014-11-11 09:58:25 +00001241 if (!SectSize)
1242 continue;
Simon Atanasyan2b614e12014-02-24 22:12:11 +00001243
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001244 // Get the list of all the symbols in this section.
1245 SectionSymbolsTy &Symbols = AllSymbols[Section];
Davide Italianof0706882015-10-01 21:57:09 +00001246 std::vector<uint64_t> DataMappingSymsAddr;
1247 std::vector<uint64_t> TextMappingSymsAddr;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001248 if (isArmElf(Obj)) {
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001249 for (const auto &Symb : Symbols) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001250 uint64_t Address = std::get<0>(Symb);
1251 StringRef Name = std::get<1>(Symb);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001252 if (Name.startswith("$d"))
David Majnemer153722d2015-11-18 04:35:32 +00001253 DataMappingSymsAddr.push_back(Address - SectionAddr);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001254 if (Name.startswith("$x"))
David Majnemer153722d2015-11-18 04:35:32 +00001255 TextMappingSymsAddr.push_back(Address - SectionAddr);
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001256 if (Name.startswith("$a"))
1257 TextMappingSymsAddr.push_back(Address - SectionAddr);
1258 if (Name.startswith("$t"))
1259 TextMappingSymsAddr.push_back(Address - SectionAddr);
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001260 }
1261 }
1262
Davide Italianof0706882015-10-01 21:57:09 +00001263 std::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end());
1264 std::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end());
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001265
Sam Kolton3381d7a2016-10-06 13:46:08 +00001266 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1267 // AMDGPU disassembler uses symbolizer for printing labels
1268 std::unique_ptr<MCRelocationInfo> RelInfo(
1269 TheTarget->createMCRelocationInfo(TripleName, Ctx));
1270 if (RelInfo) {
1271 std::unique_ptr<MCSymbolizer> Symbolizer(
1272 TheTarget->createMCSymbolizer(
1273 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1274 DisAsm->setSymbolizer(std::move(Symbolizer));
1275 }
1276 }
1277
Michael J. Spencer51862b32011-10-13 22:17:18 +00001278 // Make a list of all the relocations for this section.
1279 std::vector<RelocationRef> Rels;
1280 if (InlineRelocs) {
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001281 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
1282 for (const RelocationRef &Reloc : RelocSec.relocations()) {
1283 Rels.push_back(Reloc);
1284 }
Michael J. Spencer51862b32011-10-13 22:17:18 +00001285 }
1286 }
1287
1288 // Sort relocations by address.
1289 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
1290
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001291 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +00001292 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001293 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +00001294 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001295 }
Michael J. Spencer1d6167f2011-06-25 17:55:23 +00001296 StringRef name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001297 error(Section.getName(name));
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001298
1299 if ((SectionAddr <= StopAddress) &&
1300 (SectionAddr + SectSize) >= StartAddress) {
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001301 outs() << "Disassembly of section ";
1302 if (!SegmentName.empty())
1303 outs() << SegmentName << ",";
1304 outs() << name << ':';
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001305 }
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001306
Rafael Espindola7884c952015-06-04 15:01:05 +00001307 // If the section has no symbol at the start, just insert a dummy one.
Sam Koltonc05d7782016-08-17 10:17:57 +00001308 if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) {
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001309 Symbols.insert(Symbols.begin(),
1310 std::make_tuple(SectionAddr, name, Section.isText()
1311 ? ELF::STT_FUNC
1312 : ELF::STT_OBJECT));
Sam Koltonc05d7782016-08-17 10:17:57 +00001313 }
Alp Tokere69170a2014-06-26 22:52:05 +00001314
1315 SmallString<40> Comments;
1316 raw_svector_ostream CommentStream(Comments);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001317
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001318 StringRef BytesStr;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001319 error(Section.getContents(BytesStr));
Aaron Ballman106fd7b2014-11-12 14:01:17 +00001320 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1321 BytesStr.size());
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001322
Michael J. Spencer2670c252011-01-20 06:39:06 +00001323 uint64_t Size;
1324 uint64_t Index;
1325
Michael J. Spencer51862b32011-10-13 22:17:18 +00001326 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
1327 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001328 // Disassemble symbol by symbol.
1329 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001330 uint64_t Start = std::get<0>(Symbols[si]) - SectionAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001331 // The end is either the section end or the beginning of the next
1332 // symbol.
1333 uint64_t End =
Sam Koltonc05d7782016-08-17 10:17:57 +00001334 (si == se - 1) ? SectSize : std::get<0>(Symbols[si + 1]) - SectionAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001335 // Don't try to disassemble beyond the end of section contents.
1336 if (End > SectSize)
1337 End = SectSize;
Rafael Espindolae45c7402014-08-17 16:31:39 +00001338 // If this symbol has the same address as the next symbol, then skip it.
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001339 if (Start >= End)
Michael J. Spenceree84f642011-10-13 20:37:08 +00001340 continue;
1341
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001342 // Check if we need to skip symbol
1343 // Skip if the symbol's data is not between StartAddress and StopAddress
1344 if (End + SectionAddr < StartAddress ||
1345 Start + SectionAddr > StopAddress) {
1346 continue;
1347 }
1348
1349 // Stop disassembly at the stop address specified
1350 if (End + SectionAddr > StopAddress)
1351 End = StopAddress - SectionAddr;
1352
Valery Pykhtinde048052016-04-07 07:24:01 +00001353 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1354 // make size 4 bytes folded
1355 End = Start + ((End - Start) & ~0x3ull);
Sam Koltonc05d7782016-08-17 10:17:57 +00001356 if (std::get<2>(Symbols[si]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1357 // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)
1358 Start += 256;
1359 }
1360 if (si == se - 1 ||
1361 std::get<2>(Symbols[si + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1362 // cut trailing zeroes at the end of kernel
1363 // cut up to 256 bytes
1364 const uint64_t EndAlign = 256;
1365 const auto Limit = End - (std::min)(EndAlign, End - Start);
1366 while (End > Limit &&
1367 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1368 End -= 4;
1369 }
Valery Pykhtinde048052016-04-07 07:24:01 +00001370 }
1371
Sam Koltonc05d7782016-08-17 10:17:57 +00001372 outs() << '\n' << std::get<1>(Symbols[si]) << ":\n";
Michael J. Spencer2670c252011-01-20 06:39:06 +00001373
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001374#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +00001375 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001376#else
Mark Seaborneb03ac52014-01-25 00:32:01 +00001377 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001378#endif
1379
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001380 for (Index = Start; Index < End; Index += Size) {
1381 MCInst Inst;
Owen Andersona0c3b972011-09-15 23:38:46 +00001382
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001383 if (Index + SectionAddr < StartAddress ||
1384 Index + SectionAddr > StopAddress) {
1385 // skip byte by byte till StartAddress is reached
1386 Size = 1;
1387 continue;
1388 }
Davide Italianof0706882015-10-01 21:57:09 +00001389 // AArch64 ELF binaries can interleave data and text in the
1390 // same section. We rely on the markers introduced to
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001391 // understand what we need to dump. If the data marker is within a
1392 // function, it is denoted as a word/short etc
1393 if (isArmElf(Obj) && std::get<2>(Symbols[si]) != ELF::STT_OBJECT &&
1394 !DisassembleAll) {
Davide Italianof0706882015-10-01 21:57:09 +00001395 uint64_t Stride = 0;
1396
1397 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1398 DataMappingSymsAddr.end(), Index);
1399 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1400 // Switch to data.
1401 while (Index < End) {
1402 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1403 outs() << "\t";
1404 if (Index + 4 <= End) {
1405 Stride = 4;
1406 dumpBytes(Bytes.slice(Index, 4), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001407 outs() << "\t.word\t";
1408 uint32_t Data = 0;
1409 if (Obj->isLittleEndian()) {
1410 const auto Word =
1411 reinterpret_cast<const support::ulittle32_t *>(
1412 Bytes.data() + Index);
1413 Data = *Word;
1414 } else {
1415 const auto Word = reinterpret_cast<const support::ubig32_t *>(
1416 Bytes.data() + Index);
1417 Data = *Word;
1418 }
1419 outs() << "0x" << format("%08" PRIx32, Data);
Davide Italianof0706882015-10-01 21:57:09 +00001420 } else if (Index + 2 <= End) {
1421 Stride = 2;
1422 dumpBytes(Bytes.slice(Index, 2), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001423 outs() << "\t\t.short\t";
1424 uint16_t Data = 0;
1425 if (Obj->isLittleEndian()) {
1426 const auto Short =
1427 reinterpret_cast<const support::ulittle16_t *>(
1428 Bytes.data() + Index);
1429 Data = *Short;
1430 } else {
1431 const auto Short =
1432 reinterpret_cast<const support::ubig16_t *>(Bytes.data() +
1433 Index);
1434 Data = *Short;
1435 }
1436 outs() << "0x" << format("%04" PRIx16, Data);
Davide Italianof0706882015-10-01 21:57:09 +00001437 } else {
1438 Stride = 1;
1439 dumpBytes(Bytes.slice(Index, 1), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001440 outs() << "\t\t.byte\t";
1441 outs() << "0x" << format("%02" PRIx8, Bytes.slice(Index, 1)[0]);
Davide Italianof0706882015-10-01 21:57:09 +00001442 }
1443 Index += Stride;
1444 outs() << "\n";
1445 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1446 TextMappingSymsAddr.end(), Index);
1447 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1448 break;
1449 }
1450 }
1451 }
1452
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001453 // If there is a data symbol inside an ELF text section and we are only
1454 // disassembling text (applicable all architectures),
1455 // we are in a situation where we must print the data and not
1456 // disassemble it.
1457 if (Obj->isELF() && std::get<2>(Symbols[si]) == ELF::STT_OBJECT &&
1458 !DisassembleAll && Section.isText()) {
1459 // print out data up to 8 bytes at a time in hex and ascii
1460 uint8_t AsciiData[9] = {'\0'};
1461 uint8_t Byte;
1462 int NumBytes = 0;
1463
1464 for (Index = Start; Index < End; Index += 1) {
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001465 if (((SectionAddr + Index) < StartAddress) ||
1466 ((SectionAddr + Index) > StopAddress))
1467 continue;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001468 if (NumBytes == 0) {
1469 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1470 outs() << "\t";
1471 }
1472 Byte = Bytes.slice(Index)[0];
1473 outs() << format(" %02x", Byte);
1474 AsciiData[NumBytes] = isprint(Byte) ? Byte : '.';
1475
1476 uint8_t IndentOffset = 0;
1477 NumBytes++;
1478 if (Index == End - 1 || NumBytes > 8) {
1479 // Indent the space for less than 8 bytes data.
1480 // 2 spaces for byte and one for space between bytes
1481 IndentOffset = 3 * (8 - NumBytes);
1482 for (int Excess = 8 - NumBytes; Excess < 8; Excess++)
1483 AsciiData[Excess] = '\0';
1484 NumBytes = 8;
1485 }
1486 if (NumBytes == 8) {
1487 AsciiData[8] = '\0';
1488 outs() << std::string(IndentOffset, ' ') << " ";
1489 outs() << reinterpret_cast<char *>(AsciiData);
1490 outs() << '\n';
1491 NumBytes = 0;
1492 }
1493 }
1494 }
Davide Italianof0706882015-10-01 21:57:09 +00001495 if (Index >= End)
1496 break;
1497
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001498 // Disassemble a real instruction or a data when disassemble all is
1499 // provided
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001500 bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1501 SectionAddr + Index, DebugOut,
1502 CommentStream);
1503 if (Size == 0)
1504 Size = 1;
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001505
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001506 PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001507 Bytes.slice(Index, Size), SectionAddr + Index, outs(), "",
1508 *STI, &SP);
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001509 outs() << CommentStream.str();
1510 Comments.clear();
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001511
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001512 // Try to resolve the target of a call, tail call, etc. to a specific
1513 // symbol.
1514 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1515 MIA->isConditionalBranch(Inst))) {
1516 uint64_t Target;
1517 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1518 // In a relocatable object, the target's section must reside in
1519 // the same section as the call instruction or it is accessed
1520 // through a relocation.
1521 //
1522 // In a non-relocatable object, the target may be in any section.
1523 //
1524 // N.B. We don't walk the relocations in the relocatable case yet.
1525 auto *TargetSectionSymbols = &Symbols;
1526 if (!Obj->isRelocatableObject()) {
1527 auto SectionAddress = std::upper_bound(
1528 SectionAddresses.begin(), SectionAddresses.end(), Target,
1529 [](uint64_t LHS,
1530 const std::pair<uint64_t, SectionRef> &RHS) {
1531 return LHS < RHS.first;
1532 });
1533 if (SectionAddress != SectionAddresses.begin()) {
1534 --SectionAddress;
1535 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1536 } else {
1537 TargetSectionSymbols = nullptr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001538 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001539 }
David Majnemer2603a8fa2015-07-09 18:11:40 +00001540
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001541 // Find the first symbol in the section whose offset is less than
1542 // or equal to the target.
1543 if (TargetSectionSymbols) {
1544 auto TargetSym = std::upper_bound(
1545 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1546 Target, [](uint64_t LHS,
Sam Koltonc05d7782016-08-17 10:17:57 +00001547 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1548 return LHS < std::get<0>(RHS);
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001549 });
1550 if (TargetSym != TargetSectionSymbols->begin()) {
1551 --TargetSym;
1552 uint64_t TargetAddress = std::get<0>(*TargetSym);
1553 StringRef TargetName = std::get<1>(*TargetSym);
1554 outs() << " <" << TargetName;
1555 uint64_t Disp = Target - TargetAddress;
1556 if (Disp)
1557 outs() << "+0x" << utohexstr(Disp);
1558 outs() << '>';
David Majnemer81afca62015-07-07 22:06:59 +00001559 }
1560 }
1561 }
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001562 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001563 outs() << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001564
1565 // Print relocation for instruction.
1566 while (rel_cur != rel_end) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001567 bool hidden = getHidden(*rel_cur);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001568 uint64_t addr = rel_cur->getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +00001569 SmallString<16> name;
1570 SmallString<32> val;
Owen Andersonfa3e5202011-10-25 20:35:53 +00001571
1572 // If this relocation is hidden, skip it.
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001573 if (hidden || ((SectionAddr + addr) < StartAddress)) {
1574 ++rel_cur;
1575 continue;
1576 }
Owen Andersonfa3e5202011-10-25 20:35:53 +00001577
Michael J. Spencer51862b32011-10-13 22:17:18 +00001578 // Stop when rel_cur's address is past the current instruction.
Owen Andersonf20e3e52011-10-25 20:15:39 +00001579 if (addr >= Index + Size) break;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001580 rel_cur->getTypeName(name);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001581 error(getRelocationValueString(*rel_cur, val));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001582 outs() << format(Fmt.data(), SectionAddr + addr) << name
Benjamin Kramer82803112012-03-10 02:04:38 +00001583 << "\t" << val << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001584 ++rel_cur;
1585 }
Benjamin Kramer87ee76c2011-07-20 19:37:35 +00001586 }
Michael J. Spencer2670c252011-01-20 06:39:06 +00001587 }
1588 }
1589}
1590
Kevin Enderby98da6132015-01-20 21:47:46 +00001591void llvm::PrintRelocations(const ObjectFile *Obj) {
Greg Fitzgerald18432272014-03-20 22:55:15 +00001592 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1593 "%08" PRIx64;
Rafael Espindola9219fe72016-03-21 20:59:15 +00001594 // Regular objdump doesn't print relocations in non-relocatable object
1595 // files.
1596 if (!Obj->isRelocatableObject())
1597 return;
Rafael Espindolac66d7612014-08-17 19:09:37 +00001598
Colin LeMahieu77804be2015-07-29 15:45:39 +00001599 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001600 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001601 continue;
1602 StringRef secname;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001603 error(Section.getName(secname));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001604 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001605 for (const RelocationRef &Reloc : Section.relocations()) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001606 bool hidden = getHidden(Reloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001607 uint64_t address = Reloc.getOffset();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001608 SmallString<32> relocname;
1609 SmallString<32> valuestr;
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001610 if (address < StartAddress || address > StopAddress || hidden)
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001611 continue;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001612 Reloc.getTypeName(relocname);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001613 error(getRelocationValueString(Reloc, valuestr));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001614 outs() << format(Fmt.data(), address) << " " << relocname << " "
1615 << valuestr << "\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001616 }
1617 outs() << "\n";
1618 }
1619}
1620
Kevin Enderby98da6132015-01-20 21:47:46 +00001621void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001622 outs() << "Sections:\n"
1623 "Idx Name Size Address Type\n";
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001624 unsigned i = 0;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001625 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001626 StringRef Name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001627 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001628 uint64_t Address = Section.getAddress();
1629 uint64_t Size = Section.getSize();
1630 bool Text = Section.isText();
1631 bool Data = Section.isData();
1632 bool BSS = Section.isBSS();
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001633 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +00001634 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
Alexey Samsonov48803e52014-03-13 14:37:36 +00001635 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1636 Name.str().c_str(), Size, Address, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001637 ++i;
1638 }
1639}
1640
Kevin Enderby98da6132015-01-20 21:47:46 +00001641void llvm::PrintSectionContents(const ObjectFile *Obj) {
Rafael Espindola4453e42942014-06-13 03:07:50 +00001642 std::error_code EC;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001643 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001644 StringRef Name;
1645 StringRef Contents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001646 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001647 uint64_t BaseAddr = Section.getAddress();
David Majnemer185b5b12014-11-11 09:58:25 +00001648 uint64_t Size = Section.getSize();
1649 if (!Size)
1650 continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001651
1652 outs() << "Contents of section " << Name << ":\n";
David Majnemer185b5b12014-11-11 09:58:25 +00001653 if (Section.isBSS()) {
Alexey Samsonov209095c2013-04-16 10:53:11 +00001654 outs() << format("<skipping contents of bss section at [%04" PRIx64
David Majnemer8f6b04c2014-07-14 16:20:14 +00001655 ", %04" PRIx64 ")>\n",
1656 BaseAddr, BaseAddr + Size);
Alexey Samsonov209095c2013-04-16 10:53:11 +00001657 continue;
1658 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001659
Davide Italianoccd53fe2015-08-05 07:18:31 +00001660 error(Section.getContents(Contents));
David Majnemer8f6b04c2014-07-14 16:20:14 +00001661
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001662 // Dump out the content as hex and printable ascii characters.
1663 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer82803112012-03-10 02:04:38 +00001664 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001665 // Dump line of hex.
1666 for (std::size_t i = 0; i < 16; ++i) {
1667 if (i != 0 && i % 4 == 0)
1668 outs() << ' ';
1669 if (addr + i < end)
1670 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1671 << hexdigit(Contents[addr + i] & 0xF, true);
1672 else
1673 outs() << " ";
1674 }
1675 // Print ascii.
1676 outs() << " ";
1677 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
Guy Benyei83c74e92013-02-12 21:21:59 +00001678 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001679 outs() << Contents[addr + i];
1680 else
1681 outs() << ".";
1682 }
1683 outs() << "\n";
1684 }
1685 }
1686}
1687
Kevin Enderby9acb1092016-05-31 20:35:34 +00001688void llvm::PrintSymbolTable(const ObjectFile *o, StringRef ArchiveName,
1689 StringRef ArchitectureName) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001690 outs() << "SYMBOL TABLE:\n";
1691
Rui Ueyama4e39f712014-03-18 18:58:51 +00001692 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
Davide Italianoe85abf72015-12-20 09:54:34 +00001693 printCOFFSymbolTable(coff);
Rui Ueyama4e39f712014-03-18 18:58:51 +00001694 return;
1695 }
1696 for (const SymbolRef &Symbol : o->symbols()) {
Kevin Enderby931cb652016-06-24 18:24:42 +00001697 Expected<uint64_t> AddressOrError = Symbol.getAddress();
1698 if (!AddressOrError)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001699 report_error(ArchiveName, o->getFileName(), AddressOrError.takeError(),
1700 ArchitectureName);
Rafael Espindolaed067c42015-07-03 18:19:00 +00001701 uint64_t Address = *AddressOrError;
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001702 if ((Address < StartAddress) || (Address > StopAddress))
1703 continue;
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001704 Expected<SymbolRef::Type> TypeOrError = Symbol.getType();
1705 if (!TypeOrError)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001706 report_error(ArchiveName, o->getFileName(), TypeOrError.takeError(),
1707 ArchitectureName);
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00001708 SymbolRef::Type Type = *TypeOrError;
Rui Ueyama4e39f712014-03-18 18:58:51 +00001709 uint32_t Flags = Symbol.getFlags();
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001710 Expected<section_iterator> SectionOrErr = Symbol.getSection();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001711 if (!SectionOrErr)
1712 report_error(ArchiveName, o->getFileName(), SectionOrErr.takeError(),
1713 ArchitectureName);
Rafael Espindola8bab8892015-08-07 23:27:14 +00001714 section_iterator Section = *SectionOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001715 StringRef Name;
1716 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1717 Section->getName(Name);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001718 } else {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001719 Expected<StringRef> NameOrErr = Symbol.getName();
1720 if (!NameOrErr)
Kevin Enderby9acb1092016-05-31 20:35:34 +00001721 report_error(ArchiveName, o->getFileName(), NameOrErr.takeError(),
1722 ArchitectureName);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001723 Name = *NameOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001724 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001725
Rui Ueyama4e39f712014-03-18 18:58:51 +00001726 bool Global = Flags & SymbolRef::SF_Global;
1727 bool Weak = Flags & SymbolRef::SF_Weak;
1728 bool Absolute = Flags & SymbolRef::SF_Absolute;
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001729 bool Common = Flags & SymbolRef::SF_Common;
Davide Italianocd2514d2015-04-30 23:08:53 +00001730 bool Hidden = Flags & SymbolRef::SF_Hidden;
David Meyer1df4b842012-02-28 23:47:53 +00001731
Rui Ueyama4e39f712014-03-18 18:58:51 +00001732 char GlobLoc = ' ';
1733 if (Type != SymbolRef::ST_Unknown)
1734 GlobLoc = Global ? 'g' : 'l';
1735 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1736 ? 'd' : ' ';
1737 char FileFunc = ' ';
1738 if (Type == SymbolRef::ST_File)
1739 FileFunc = 'f';
1740 else if (Type == SymbolRef::ST_Function)
1741 FileFunc = 'F';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001742
Rui Ueyama4e39f712014-03-18 18:58:51 +00001743 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1744 "%08" PRIx64;
Michael J. Spencerd857c1c2013-01-10 22:40:50 +00001745
Rui Ueyama4e39f712014-03-18 18:58:51 +00001746 outs() << format(Fmt, Address) << " "
1747 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1748 << (Weak ? 'w' : ' ') // Weak?
1749 << ' ' // Constructor. Not supported yet.
1750 << ' ' // Warning. Not supported yet.
1751 << ' ' // Indirect reference to another symbol.
1752 << Debug // Debugging (d) or dynamic (D) symbol.
1753 << FileFunc // Name of function (F), file (f) or object (O).
1754 << ' ';
1755 if (Absolute) {
1756 outs() << "*ABS*";
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001757 } else if (Common) {
1758 outs() << "*COM*";
Rui Ueyama4e39f712014-03-18 18:58:51 +00001759 } else if (Section == o->section_end()) {
1760 outs() << "*UND*";
1761 } else {
1762 if (const MachOObjectFile *MachO =
1763 dyn_cast<const MachOObjectFile>(o)) {
1764 DataRefImpl DR = Section->getRawDataRefImpl();
1765 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1766 outs() << SegmentName << ",";
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001767 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00001768 StringRef SectionName;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001769 error(Section->getName(SectionName));
Rui Ueyama4e39f712014-03-18 18:58:51 +00001770 outs() << SectionName;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001771 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001772
1773 outs() << '\t';
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001774 if (Common || isa<ELFObjectFileBase>(o)) {
Rafael Espindoladbb6bd32015-06-25 22:10:04 +00001775 uint64_t Val =
1776 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001777 outs() << format("\t %08" PRIx64 " ", Val);
1778 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001779
Davide Italianocd2514d2015-04-30 23:08:53 +00001780 if (Hidden) {
1781 outs() << ".hidden ";
1782 }
1783 outs() << Name
Rui Ueyama4e39f712014-03-18 18:58:51 +00001784 << '\n';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001785 }
1786}
1787
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001788static void PrintUnwindInfo(const ObjectFile *o) {
1789 outs() << "Unwind info:\n\n";
1790
1791 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1792 printCOFFUnwindInfo(coff);
Tim Northover4bd286a2014-08-01 13:07:19 +00001793 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1794 printMachOUnwindInfo(MachO);
1795 else {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001796 // TODO: Extract DWARF dump tool to objdump.
1797 errs() << "This operation is only currently supported "
Tim Northover4bd286a2014-08-01 13:07:19 +00001798 "for COFF and MachO object files.\n";
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001799 return;
1800 }
1801}
1802
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001803void llvm::printExportsTrie(const ObjectFile *o) {
Nick Kledzikd04bc352014-08-30 00:20:14 +00001804 outs() << "Exports trie:\n";
1805 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1806 printMachOExportsTrie(MachO);
1807 else {
1808 errs() << "This operation is only currently supported "
1809 "for Mach-O executable files.\n";
1810 return;
1811 }
1812}
1813
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001814void llvm::printRebaseTable(const ObjectFile *o) {
Nick Kledzikac431442014-09-12 21:34:15 +00001815 outs() << "Rebase table:\n";
1816 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1817 printMachORebaseTable(MachO);
1818 else {
1819 errs() << "This operation is only currently supported "
1820 "for Mach-O executable files.\n";
1821 return;
1822 }
1823}
1824
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001825void llvm::printBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001826 outs() << "Bind table:\n";
1827 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1828 printMachOBindTable(MachO);
1829 else {
1830 errs() << "This operation is only currently supported "
1831 "for Mach-O executable files.\n";
1832 return;
1833 }
1834}
1835
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001836void llvm::printLazyBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001837 outs() << "Lazy bind table:\n";
1838 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1839 printMachOLazyBindTable(MachO);
1840 else {
1841 errs() << "This operation is only currently supported "
1842 "for Mach-O executable files.\n";
1843 return;
1844 }
1845}
1846
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001847void llvm::printWeakBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001848 outs() << "Weak bind table:\n";
1849 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1850 printMachOWeakBindTable(MachO);
1851 else {
1852 errs() << "This operation is only currently supported "
1853 "for Mach-O executable files.\n";
1854 return;
1855 }
1856}
Nick Kledzikac431442014-09-12 21:34:15 +00001857
Adrian Prantl437105a2015-07-08 02:04:15 +00001858/// Dump the raw contents of the __clangast section so the output can be piped
1859/// into llvm-bcanalyzer.
1860void llvm::printRawClangAST(const ObjectFile *Obj) {
1861 if (outs().is_displayed()) {
1862 errs() << "The -raw-clang-ast option will dump the raw binary contents of "
1863 "the clang ast section.\n"
1864 "Please redirect the output to a file or another program such as "
1865 "llvm-bcanalyzer.\n";
1866 return;
1867 }
1868
1869 StringRef ClangASTSectionName("__clangast");
1870 if (isa<COFFObjectFile>(Obj)) {
1871 ClangASTSectionName = "clangast";
1872 }
1873
1874 Optional<object::SectionRef> ClangASTSection;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001875 for (auto Sec : ToolSectionFilter(*Obj)) {
Adrian Prantl437105a2015-07-08 02:04:15 +00001876 StringRef Name;
1877 Sec.getName(Name);
1878 if (Name == ClangASTSectionName) {
1879 ClangASTSection = Sec;
1880 break;
1881 }
1882 }
1883 if (!ClangASTSection)
1884 return;
1885
1886 StringRef ClangASTContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001887 error(ClangASTSection.getValue().getContents(ClangASTContents));
Adrian Prantl437105a2015-07-08 02:04:15 +00001888 outs().write(ClangASTContents.data(), ClangASTContents.size());
1889}
1890
Sanjoy Das6f567a42015-06-22 18:03:02 +00001891static void printFaultMaps(const ObjectFile *Obj) {
1892 const char *FaultMapSectionName = nullptr;
1893
1894 if (isa<ELFObjectFileBase>(Obj)) {
1895 FaultMapSectionName = ".llvm_faultmaps";
1896 } else if (isa<MachOObjectFile>(Obj)) {
1897 FaultMapSectionName = "__llvm_faultmaps";
1898 } else {
1899 errs() << "This operation is only currently supported "
1900 "for ELF and Mach-O executable files.\n";
1901 return;
1902 }
1903
1904 Optional<object::SectionRef> FaultMapSection;
1905
Colin LeMahieu77804be2015-07-29 15:45:39 +00001906 for (auto Sec : ToolSectionFilter(*Obj)) {
Sanjoy Das6f567a42015-06-22 18:03:02 +00001907 StringRef Name;
1908 Sec.getName(Name);
1909 if (Name == FaultMapSectionName) {
1910 FaultMapSection = Sec;
1911 break;
1912 }
1913 }
1914
1915 outs() << "FaultMap table:\n";
1916
1917 if (!FaultMapSection.hasValue()) {
1918 outs() << "<not found>\n";
1919 return;
1920 }
1921
1922 StringRef FaultMapContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001923 error(FaultMapSection.getValue().getContents(FaultMapContents));
Sanjoy Das6f567a42015-06-22 18:03:02 +00001924
1925 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1926 FaultMapContents.bytes_end());
1927
1928 outs() << FMP;
1929}
1930
Davide Italiano1bdaa202016-09-18 04:39:15 +00001931static void printPrivateFileHeaders(const ObjectFile *o, bool onlyFirst) {
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001932 if (o->isELF())
Davide Italiano1bdaa202016-09-18 04:39:15 +00001933 return printELFFileHeader(o);
1934 if (o->isCOFF())
1935 return printCOFFFileHeader(o);
Derek Schuff2c6f75d2016-11-30 16:49:11 +00001936 if (o->isWasm())
1937 return printWasmFileHeader(o);
Davide Italiano1bdaa202016-09-18 04:39:15 +00001938 if (o->isMachO()) {
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001939 printMachOFileHeader(o);
Davide Italiano1bdaa202016-09-18 04:39:15 +00001940 if (!onlyFirst)
1941 printMachOLoadCommands(o);
1942 return;
1943 }
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001944 report_error(o->getFileName(), "Invalid/Unsupported object file format");
Rui Ueyamac2bed422013-09-27 21:04:00 +00001945}
1946
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001947static void DumpObject(const ObjectFile *o, const Archive *a = nullptr) {
1948 StringRef ArchiveName = a != nullptr ? a->getFileName() : "";
Adrian Prantl437105a2015-07-08 02:04:15 +00001949 // Avoid other output when using a raw option.
1950 if (!RawClangAST) {
1951 outs() << '\n';
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001952 if (a)
1953 outs() << a->getFileName() << "(" << o->getFileName() << ")";
1954 else
1955 outs() << o->getFileName();
1956 outs() << ":\tfile format " << o->getFileFormatName() << "\n\n";
Adrian Prantl437105a2015-07-08 02:04:15 +00001957 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001958
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001959 if (Disassemble)
Michael J. Spencer51862b32011-10-13 22:17:18 +00001960 DisassembleObject(o, Relocations);
1961 if (Relocations && !Disassemble)
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001962 PrintRelocations(o);
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001963 if (SectionHeaders)
1964 PrintSectionHeaders(o);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001965 if (SectionContents)
1966 PrintSectionContents(o);
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001967 if (SymbolTable)
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001968 PrintSymbolTable(o, ArchiveName);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001969 if (UnwindInfo)
1970 PrintUnwindInfo(o);
Davide Italiano1bdaa202016-09-18 04:39:15 +00001971 if (PrivateHeaders || FirstPrivateHeader)
1972 printPrivateFileHeaders(o, FirstPrivateHeader);
Nick Kledzikd04bc352014-08-30 00:20:14 +00001973 if (ExportsTrie)
1974 printExportsTrie(o);
Nick Kledzikac431442014-09-12 21:34:15 +00001975 if (Rebase)
1976 printRebaseTable(o);
Nick Kledzik56ebef42014-09-16 01:41:51 +00001977 if (Bind)
1978 printBindTable(o);
1979 if (LazyBind)
1980 printLazyBindTable(o);
1981 if (WeakBind)
1982 printWeakBindTable(o);
Adrian Prantl437105a2015-07-08 02:04:15 +00001983 if (RawClangAST)
1984 printRawClangAST(o);
Sanjoy Das6f567a42015-06-22 18:03:02 +00001985 if (PrintFaultMaps)
1986 printFaultMaps(o);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001987 if (DwarfDumpType != DIDT_Null) {
1988 std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*o));
1989 // Dump the complete DWARF structure.
1990 DICtx->dump(outs(), DwarfDumpType, true /* DumpEH */);
1991 }
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001992}
1993
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00001994static void DumpObject(const COFFImportFile *I, const Archive *A) {
1995 StringRef ArchiveName = A ? A->getFileName() : "";
1996
1997 // Avoid other output when using a raw option.
1998 if (!RawClangAST)
1999 outs() << '\n'
2000 << ArchiveName << "(" << I->getFileName() << ")"
2001 << ":\tfile format COFF-import-file"
2002 << "\n\n";
2003
2004 if (SymbolTable)
2005 printCOFFSymbolTable(I);
2006}
2007
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002008/// @brief Dump each object file in \a a;
2009static void DumpArchive(const Archive *a) {
Mehdi Amini41af4302016-11-11 04:28:40 +00002010 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00002011 for (auto &C : a->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002012 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2013 if (!ChildOrErr) {
2014 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2015 report_error(a->getFileName(), C, std::move(E));
2016 continue;
2017 }
Rafael Espindolaae460022014-06-16 16:08:36 +00002018 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002019 DumpObject(o, a);
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00002020 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
2021 DumpObject(I, a);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002022 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00002023 report_error(a->getFileName(), object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002024 }
Lang Hamesfc209622016-07-14 02:24:01 +00002025 if (Err)
2026 report_error(a->getFileName(), std::move(Err));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002027}
2028
2029/// @brief Open file and figure out how to dump it.
2030static void DumpInput(StringRef file) {
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002031
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002032 // If we are using the Mach-O specific object file parser, then let it parse
2033 // the file and process the command line options. So the -arch flags can
2034 // be used to select specific slices, etc.
2035 if (MachOOpt) {
2036 ParseInputMachO(file);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002037 return;
2038 }
2039
2040 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00002041 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
2042 if (!BinaryOrErr)
Kevin Enderbyb34e3a12016-05-05 17:43:35 +00002043 report_error(file, BinaryOrErr.takeError());
Rafael Espindola48af1c22014-08-19 18:44:46 +00002044 Binary &Binary = *BinaryOrErr.get().getBinary();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002045
Rafael Espindola3f6481d2014-08-01 14:31:55 +00002046 if (Archive *a = dyn_cast<Archive>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002047 DumpArchive(a);
Rafael Espindola3f6481d2014-08-01 14:31:55 +00002048 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002049 DumpObject(o);
Jim Grosbachaf9aec02012-08-07 17:53:14 +00002050 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00002051 report_error(file, object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002052}
2053
Michael J. Spencer2670c252011-01-20 06:39:06 +00002054int main(int argc, char **argv) {
2055 // Print a stack trace if we signal out.
Richard Smith2ad6d482016-06-09 00:53:21 +00002056 sys::PrintStackTraceOnErrorSignal(argv[0]);
Michael J. Spencer2670c252011-01-20 06:39:06 +00002057 PrettyStackTraceProgram X(argc, argv);
2058 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
2059
2060 // Initialize targets and assembly printers/parsers.
2061 llvm::InitializeAllTargetInfos();
Evan Cheng8c886a42011-07-22 21:58:54 +00002062 llvm::InitializeAllTargetMCs();
Michael J. Spencer2670c252011-01-20 06:39:06 +00002063 llvm::InitializeAllDisassemblers();
2064
Pete Cooper28fb4fc2012-05-03 23:20:10 +00002065 // Register the target printer for --version.
2066 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
2067
Michael J. Spencer2670c252011-01-20 06:39:06 +00002068 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
2069 TripleName = Triple::normalize(TripleName);
2070
2071 ToolName = argv[0];
2072
2073 // Defaults to a.out if no filenames specified.
2074 if (InputFilenames.size() == 0)
2075 InputFilenames.push_back("a.out");
2076
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00002077 if (DisassembleAll || PrintSource || PrintLines)
Colin LeMahieuf34933e2015-07-23 20:58:49 +00002078 Disassemble = true;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002079 if (!Disassemble
2080 && !Relocations
2081 && !SectionHeaders
2082 && !SectionContents
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00002083 && !SymbolTable
Michael J. Spencer209565db2013-01-06 03:56:49 +00002084 && !UnwindInfo
Nick Kledzikd04bc352014-08-30 00:20:14 +00002085 && !PrivateHeaders
Kevin Enderby0ae163f2016-01-13 00:25:36 +00002086 && !FirstPrivateHeader
Nick Kledzikac431442014-09-12 21:34:15 +00002087 && !ExportsTrie
Nick Kledzik56ebef42014-09-16 01:41:51 +00002088 && !Rebase
2089 && !Bind
2090 && !LazyBind
Kevin Enderby131d1772015-01-09 19:22:37 +00002091 && !WeakBind
Adrian Prantl437105a2015-07-08 02:04:15 +00002092 && !RawClangAST
Kevin Enderby13023a12015-01-15 23:19:11 +00002093 && !(UniversalHeaders && MachOOpt)
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00002094 && !(ArchiveHeaders && MachOOpt)
Kevin Enderby69fe98d2015-01-23 18:52:17 +00002095 && !(IndirectSymbols && MachOOpt)
Kevin Enderby9a509442015-01-27 21:28:24 +00002096 && !(DataInCode && MachOOpt)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002097 && !(LinkOptHints && MachOOpt)
Kevin Enderbycd66be52015-03-11 22:06:32 +00002098 && !(InfoPlist && MachOOpt)
Kevin Enderbybc847fa2015-03-16 20:08:09 +00002099 && !(DylibsUsed && MachOOpt)
2100 && !(DylibId && MachOOpt)
Kevin Enderby0fc11822015-04-01 20:57:01 +00002101 && !(ObjcMetaData && MachOOpt)
Colin LeMahieufcc32762015-07-29 19:08:10 +00002102 && !(FilterSections.size() != 0 && MachOOpt)
Igor Laevsky03a670c2016-01-26 15:09:42 +00002103 && !PrintFaultMaps
2104 && DwarfDumpType == DIDT_Null) {
Michael J. Spencer2670c252011-01-20 06:39:06 +00002105 cl::PrintHelpMessage();
2106 return 2;
2107 }
2108
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002109 std::for_each(InputFilenames.begin(), InputFilenames.end(),
2110 DumpInput);
Michael J. Spencer2670c252011-01-20 06:39:06 +00002111
Davide Italianoccd53fe2015-08-05 07:18:31 +00002112 return EXIT_SUCCESS;
Michael J. Spencer2670c252011-01-20 06:39:06 +00002113}