blob: 920ad4a7dd60ca6a0c4134eb3e640263873afe84 [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,
296 std::error_code EC) {
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000297 assert(EC);
298 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
Davide Italianoccd53fe2015-08-05 07:18:31 +0000299 exit(1);
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000300}
301
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000302LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
303 llvm::Error E) {
304 assert(E);
305 std::string Buf;
306 raw_string_ostream OS(Buf);
307 logAllUnhandledErrors(std::move(E), OS, "");
308 OS.flush();
Kevin Enderbyb34e3a12016-05-05 17:43:35 +0000309 errs() << ToolName << ": '" << File << "': " << Buf;
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000310 exit(1);
311}
312
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000313LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
314 StringRef FileName,
Kevin Enderby9acb1092016-05-31 20:35:34 +0000315 llvm::Error E,
316 StringRef ArchitectureName) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000317 assert(E);
318 errs() << ToolName << ": ";
319 if (ArchiveName != "")
320 errs() << ArchiveName << "(" << FileName << ")";
321 else
Justin Bogner31d8b7d2016-10-26 22:37:52 +0000322 errs() << "'" << FileName << "'";
Kevin Enderby9acb1092016-05-31 20:35:34 +0000323 if (!ArchitectureName.empty())
324 errs() << " (for architecture " << ArchitectureName << ")";
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000325 std::string Buf;
326 raw_string_ostream OS(Buf);
327 logAllUnhandledErrors(std::move(E), OS, "");
328 OS.flush();
Justin Bogner31d8b7d2016-10-26 22:37:52 +0000329 errs() << ": " << Buf;
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000330 exit(1);
331}
332
333LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
334 const object::Archive::Child &C,
Kevin Enderby9acb1092016-05-31 20:35:34 +0000335 llvm::Error E,
336 StringRef ArchitectureName) {
Kevin Enderbyf4586032016-07-29 17:44:13 +0000337 Expected<StringRef> NameOrErr = C.getName();
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000338 // TODO: if we have a error getting the name then it would be nice to print
339 // the index of which archive member this is and or its offset in the
340 // archive instead of "???" as the name.
Kevin Enderbyf4586032016-07-29 17:44:13 +0000341 if (!NameOrErr) {
342 consumeError(NameOrErr.takeError());
Kevin Enderby9acb1092016-05-31 20:35:34 +0000343 llvm::report_error(ArchiveName, "???", std::move(E), ArchitectureName);
Kevin Enderbyf4586032016-07-29 17:44:13 +0000344 } else
Kevin Enderby9acb1092016-05-31 20:35:34 +0000345 llvm::report_error(ArchiveName, NameOrErr.get(), std::move(E),
346 ArchitectureName);
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000347}
348
Craig Toppere6cb63e2014-04-25 04:24:47 +0000349static const Target *getTarget(const ObjectFile *Obj = nullptr) {
Michael J. Spencer2670c252011-01-20 06:39:06 +0000350 // Figure out the target triple.
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000351 llvm::Triple TheTriple("unknown-unknown-unknown");
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000352 if (TripleName.empty()) {
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000353 if (Obj) {
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000354 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000355 // TheTriple defaults to ELF, and COFF doesn't have an environment:
356 // the best we can do here is indicate that it is mach-o.
357 if (Obj->isMachO())
Saleem Abdulrasool35476332014-03-06 20:47:11 +0000358 TheTriple.setObjectFormat(Triple::MachO);
Saleem Abdulrasool98938f12014-04-17 06:17:23 +0000359
360 if (Obj->isCOFF()) {
361 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
362 if (COFFObj->getArch() == Triple::thumb)
363 TheTriple.setTriple("thumbv7-windows");
364 }
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000365 }
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000366 } else
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000367 TheTriple.setTriple(Triple::normalize(TripleName));
Michael J. Spencer2670c252011-01-20 06:39:06 +0000368
369 // Get the target specific parser.
370 std::string Error;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000371 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
372 Error);
Davide Italianobb599e32015-12-03 22:13:40 +0000373 if (!TheTarget)
374 report_fatal_error("can't find target: " + Error);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000375
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000376 // Update the triple name and return the found target.
377 TripleName = TheTriple.getTriple();
378 return TheTarget;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000379}
380
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000381bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
Rafael Espindola704cd842015-07-06 15:47:43 +0000382 return a.getOffset() < b.getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +0000383}
384
Colin LeMahieufb76b002015-05-28 19:07:14 +0000385namespace {
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000386class SourcePrinter {
387protected:
388 DILineInfo OldLineInfo;
389 const ObjectFile *Obj;
390 std::unique_ptr<symbolize::LLVMSymbolizer> Symbolizer;
391 // File name to file contents of source
392 std::unordered_map<std::string, std::unique_ptr<MemoryBuffer>> SourceCache;
393 // Mark the line endings of the cached source
394 std::unordered_map<std::string, std::vector<StringRef>> LineCache;
395
396private:
397 bool cacheSource(std::string File);
398
399public:
400 virtual ~SourcePrinter() {}
401 SourcePrinter() : Obj(nullptr), Symbolizer(nullptr) {}
402 SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch) : Obj(Obj) {
403 symbolize::LLVMSymbolizer::Options SymbolizerOpts(
404 DILineInfoSpecifier::FunctionNameKind::None, true, false, false,
405 DefaultArch);
406 Symbolizer.reset(new symbolize::LLVMSymbolizer(SymbolizerOpts));
407 }
408 virtual void printSourceLine(raw_ostream &OS, uint64_t Address,
409 StringRef Delimiter = "; ");
410};
411
412bool SourcePrinter::cacheSource(std::string File) {
413 auto BufferOrError = MemoryBuffer::getFile(File);
414 if (!BufferOrError)
415 return false;
416 // Chomp the file to get lines
417 size_t BufferSize = (*BufferOrError)->getBufferSize();
418 const char *BufferStart = (*BufferOrError)->getBufferStart();
419 for (const char *Start = BufferStart, *End = BufferStart;
420 End < BufferStart + BufferSize; End++)
421 if (*End == '\n' || End == BufferStart + BufferSize - 1 ||
422 (*End == '\r' && *(End + 1) == '\n')) {
423 LineCache[File].push_back(StringRef(Start, End - Start));
424 if (*End == '\r')
425 End++;
426 Start = End + 1;
427 }
428 SourceCache[File] = std::move(*BufferOrError);
429 return true;
430}
431
432void SourcePrinter::printSourceLine(raw_ostream &OS, uint64_t Address,
433 StringRef Delimiter) {
434 if (!Symbolizer)
435 return;
436 DILineInfo LineInfo = DILineInfo();
437 auto ExpectecLineInfo =
438 Symbolizer->symbolizeCode(Obj->getFileName(), Address);
439 if (!ExpectecLineInfo)
440 consumeError(ExpectecLineInfo.takeError());
441 else
442 LineInfo = *ExpectecLineInfo;
443
444 if ((LineInfo.FileName == "<invalid>") || OldLineInfo.Line == LineInfo.Line ||
445 LineInfo.Line == 0)
446 return;
447
448 if (PrintLines)
449 OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line << "\n";
450 if (PrintSource) {
451 if (SourceCache.find(LineInfo.FileName) == SourceCache.end())
452 if (!cacheSource(LineInfo.FileName))
453 return;
454 auto FileBuffer = SourceCache.find(LineInfo.FileName);
455 if (FileBuffer != SourceCache.end()) {
456 auto LineBuffer = LineCache.find(LineInfo.FileName);
457 if (LineBuffer != LineCache.end())
458 // Vector begins at 0, line numbers are non-zero
459 OS << Delimiter << LineBuffer->second[LineInfo.Line - 1].ltrim()
460 << "\n";
461 }
462 }
463 OldLineInfo = LineInfo;
464}
465
Hemant Kulkarni5b60f632016-08-25 19:41:08 +0000466static bool isArmElf(const ObjectFile *Obj) {
467 return (Obj->isELF() &&
468 (Obj->getArch() == Triple::aarch64 ||
469 Obj->getArch() == Triple::aarch64_be ||
470 Obj->getArch() == Triple::arm || Obj->getArch() == Triple::armeb ||
471 Obj->getArch() == Triple::thumb ||
472 Obj->getArch() == Triple::thumbeb));
473}
474
Colin LeMahieufb76b002015-05-28 19:07:14 +0000475class PrettyPrinter {
476public:
Colin LeMahieu0b5890d2015-05-28 20:59:08 +0000477 virtual ~PrettyPrinter(){}
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000478 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
Colin LeMahieufb76b002015-05-28 19:07:14 +0000479 ArrayRef<uint8_t> Bytes, uint64_t Address,
480 raw_ostream &OS, StringRef Annot,
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000481 MCSubtargetInfo const &STI, SourcePrinter *SP) {
482 if (SP && (PrintSource || PrintLines))
483 SP->printSourceLine(OS, Address);
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000484 OS << format("%8" PRIx64 ":", Address);
Colin LeMahieufb76b002015-05-28 19:07:14 +0000485 if (!NoShowRawInsn) {
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000486 OS << "\t";
487 dumpBytes(Bytes, OS);
Colin LeMahieufb76b002015-05-28 19:07:14 +0000488 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000489 if (MI)
490 IP.printInst(MI, OS, "", STI);
491 else
492 OS << " <unknown>";
Colin LeMahieufb76b002015-05-28 19:07:14 +0000493 }
494};
495PrettyPrinter PrettyPrinterInst;
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000496class HexagonPrettyPrinter : public PrettyPrinter {
497public:
498 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
499 raw_ostream &OS) {
500 uint32_t opcode =
501 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
502 OS << format("%8" PRIx64 ":", Address);
503 if (!NoShowRawInsn) {
504 OS << "\t";
505 dumpBytes(Bytes.slice(0, 4), OS);
506 OS << format("%08" PRIx32, opcode);
507 }
508 }
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000509 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
510 uint64_t Address, raw_ostream &OS, StringRef Annot,
511 MCSubtargetInfo const &STI, SourcePrinter *SP) override {
Hemant Kulkarnie77a0a92016-08-18 21:50:13 +0000512 if (SP && (PrintSource || PrintLines))
513 SP->printSourceLine(OS, Address, "");
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000514 if (!MI) {
515 printLead(Bytes, Address, OS);
516 OS << " <unknown>";
517 return;
518 }
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000519 std::string Buffer;
520 {
521 raw_string_ostream TempStream(Buffer);
522 IP.printInst(MI, TempStream, "", STI);
523 }
524 StringRef Contents(Buffer);
525 // Split off bundle attributes
526 auto PacketBundle = Contents.rsplit('\n');
527 // Split off first instruction from the rest
528 auto HeadTail = PacketBundle.first.split('\n');
529 auto Preamble = " { ";
530 auto Separator = "";
531 while(!HeadTail.first.empty()) {
532 OS << Separator;
533 Separator = "\n";
Hemant Kulkarnie77a0a92016-08-18 21:50:13 +0000534 if (SP && (PrintSource || PrintLines))
535 SP->printSourceLine(OS, Address, "");
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000536 printLead(Bytes, Address, OS);
537 OS << Preamble;
538 Preamble = " ";
539 StringRef Inst;
540 auto Duplex = HeadTail.first.split('\v');
541 if(!Duplex.second.empty()){
542 OS << Duplex.first;
543 OS << "; ";
544 Inst = Duplex.second;
545 }
546 else
547 Inst = HeadTail.first;
548 OS << Inst;
549 Bytes = Bytes.slice(4);
550 Address += 4;
551 HeadTail = HeadTail.second.split('\n');
552 }
553 OS << " } " << PacketBundle.second;
554 }
555};
556HexagonPrettyPrinter HexagonPrettyPrinterInst;
Valery Pykhtinde048052016-04-07 07:24:01 +0000557
558class AMDGCNPrettyPrinter : public PrettyPrinter {
559public:
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000560 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
561 uint64_t Address, raw_ostream &OS, StringRef Annot,
562 MCSubtargetInfo const &STI, SourcePrinter *SP) override {
Matt Arsenault87d80db2016-04-22 21:23:41 +0000563 if (!MI) {
564 OS << " <unknown>";
565 return;
566 }
567
Valery Pykhtinde048052016-04-07 07:24:01 +0000568 SmallString<40> InstStr;
569 raw_svector_ostream IS(InstStr);
570
571 IP.printInst(MI, IS, "", STI);
572
Valery Pykhtin8e79f5b2016-04-07 08:38:20 +0000573 OS << left_justify(IS.str(), 60) << format("// %012" PRIX64 ": ", Address);
Valery Pykhtinde048052016-04-07 07:24:01 +0000574 typedef support::ulittle32_t U32;
575 for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
576 Bytes.size() / sizeof(U32)))
577 // D should be explicitly casted to uint32_t here as it is passed
578 // by format to snprintf as vararg.
Valery Pykhtin8e79f5b2016-04-07 08:38:20 +0000579 OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D));
Valery Pykhtinde048052016-04-07 07:24:01 +0000580
581 if (!Annot.empty())
582 OS << "// " << Annot;
583 }
584};
585AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
586
Colin LeMahieu35436a22015-05-29 14:48:25 +0000587PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000588 switch(Triple.getArch()) {
589 default:
590 return PrettyPrinterInst;
591 case Triple::hexagon:
592 return HexagonPrettyPrinterInst;
Valery Pykhtinde048052016-04-07 07:24:01 +0000593 case Triple::amdgcn:
594 return AMDGCNPrettyPrinterInst;
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000595 }
Colin LeMahieufb76b002015-05-28 19:07:14 +0000596}
597}
598
Rafael Espindola37070a52015-06-03 04:48:06 +0000599template <class ELFT>
Rafael Espindola37070a52015-06-03 04:48:06 +0000600static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000601 const RelocationRef &RelRef,
Rafael Espindola37070a52015-06-03 04:48:06 +0000602 SmallVectorImpl<char> &Result) {
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000603 DataRefImpl Rel = RelRef.getRawDataRefImpl();
604
Rafael Espindola37070a52015-06-03 04:48:06 +0000605 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
606 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000607 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
608
Rafael Espindola37070a52015-06-03 04:48:06 +0000609 const ELFFile<ELFT> &EF = *Obj->getELFFile();
610
Rafael Espindola6def3042015-07-01 12:56:27 +0000611 ErrorOr<const Elf_Shdr *> SecOrErr = EF.getSection(Rel.d.a);
612 if (std::error_code EC = SecOrErr.getError())
613 return EC;
614 const Elf_Shdr *Sec = *SecOrErr;
615 ErrorOr<const Elf_Shdr *> SymTabOrErr = EF.getSection(Sec->sh_link);
616 if (std::error_code EC = SymTabOrErr.getError())
617 return EC;
618 const Elf_Shdr *SymTab = *SymTabOrErr;
Rafael Espindola719dc7c2015-06-29 12:38:31 +0000619 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
620 SymTab->sh_type == ELF::SHT_DYNSYM);
Rafael Espindola6def3042015-07-01 12:56:27 +0000621 ErrorOr<const Elf_Shdr *> StrTabSec = EF.getSection(SymTab->sh_link);
622 if (std::error_code EC = StrTabSec.getError())
623 return EC;
624 ErrorOr<StringRef> StrTabOrErr = EF.getStringTable(*StrTabSec);
Rafael Espindola6a1bfb22015-06-29 14:39:25 +0000625 if (std::error_code EC = StrTabOrErr.getError())
626 return EC;
627 StringRef StrTab = *StrTabOrErr;
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000628 uint8_t type = RelRef.getType();
Rafael Espindola37070a52015-06-03 04:48:06 +0000629 StringRef res;
630 int64_t addend = 0;
Rafael Espindola6def3042015-07-01 12:56:27 +0000631 switch (Sec->sh_type) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000632 default:
633 return object_error::parse_failed;
634 case ELF::SHT_REL: {
Rafael Espindola37070a52015-06-03 04:48:06 +0000635 // TODO: Read implicit addend from section data.
636 break;
637 }
638 case ELF::SHT_RELA: {
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000639 const Elf_Rela *ERela = Obj->getRela(Rel);
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000640 addend = ERela->r_addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000641 break;
642 }
643 }
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000644 symbol_iterator SI = RelRef.getSymbol();
645 const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
Rafael Espindola75d5b542015-06-03 05:14:22 +0000646 StringRef Target;
Rafael Espindola75d5b542015-06-03 05:14:22 +0000647 if (symb->getType() == ELF::STT_SECTION) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000648 Expected<section_iterator> SymSI = SI->getSection();
649 if (!SymSI)
650 return errorToErrorCode(SymSI.takeError());
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000651 const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
652 ErrorOr<StringRef> SecName = EF.getSectionName(SymSec);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000653 if (std::error_code EC = SecName.getError())
654 return EC;
655 Target = *SecName;
656 } else {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000657 Expected<StringRef> SymName = symb->getName(StrTab);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000658 if (!SymName)
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000659 return errorToErrorCode(SymName.takeError());
Rafael Espindola75d5b542015-06-03 05:14:22 +0000660 Target = *SymName;
661 }
Rafael Espindola37070a52015-06-03 04:48:06 +0000662 switch (EF.getHeader()->e_machine) {
663 case ELF::EM_X86_64:
664 switch (type) {
665 case ELF::R_X86_64_PC8:
666 case ELF::R_X86_64_PC16:
667 case ELF::R_X86_64_PC32: {
668 std::string fmtbuf;
669 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000670 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
Rafael Espindola37070a52015-06-03 04:48:06 +0000671 fmt.flush();
672 Result.append(fmtbuf.begin(), fmtbuf.end());
673 } break;
674 case ELF::R_X86_64_8:
675 case ELF::R_X86_64_16:
676 case ELF::R_X86_64_32:
677 case ELF::R_X86_64_32S:
678 case ELF::R_X86_64_64: {
679 std::string fmtbuf;
680 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000681 fmt << Target << (addend < 0 ? "" : "+") << addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000682 fmt.flush();
683 Result.append(fmtbuf.begin(), fmtbuf.end());
684 } break;
685 default:
686 res = "Unknown";
687 }
688 break;
Jacques Pienaarea9f25a2016-03-01 21:21:42 +0000689 case ELF::EM_LANAI:
Dylan McKay11661122016-09-28 13:15:17 +0000690 case ELF::EM_AVR:
Rafael Espindola37070a52015-06-03 04:48:06 +0000691 case ELF::EM_AARCH64: {
692 std::string fmtbuf;
693 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000694 fmt << Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000695 if (addend != 0)
696 fmt << (addend < 0 ? "" : "+") << addend;
697 fmt.flush();
698 Result.append(fmtbuf.begin(), fmtbuf.end());
699 break;
700 }
701 case ELF::EM_386:
Michael Kupersteina3b79dd2015-11-04 11:21:50 +0000702 case ELF::EM_IAMCU:
Rafael Espindola37070a52015-06-03 04:48:06 +0000703 case ELF::EM_ARM:
704 case ELF::EM_HEXAGON:
705 case ELF::EM_MIPS:
Alexei Starovoitovcfb51f52016-07-15 22:27:55 +0000706 case ELF::EM_BPF:
Alex Bradbury1524f622016-11-01 16:59:37 +0000707 case ELF::EM_RISCV:
Rafael Espindola75d5b542015-06-03 05:14:22 +0000708 res = Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000709 break;
Dan Gohman46350172016-01-12 20:56:01 +0000710 case ELF::EM_WEBASSEMBLY:
711 switch (type) {
712 case ELF::R_WEBASSEMBLY_DATA: {
713 std::string fmtbuf;
714 raw_string_ostream fmt(fmtbuf);
715 fmt << Target << (addend < 0 ? "" : "+") << addend;
716 fmt.flush();
717 Result.append(fmtbuf.begin(), fmtbuf.end());
718 break;
719 }
720 case ELF::R_WEBASSEMBLY_FUNCTION:
721 res = Target;
722 break;
723 default:
724 res = "Unknown";
725 }
726 break;
Rafael Espindola37070a52015-06-03 04:48:06 +0000727 default:
728 res = "Unknown";
729 }
730 if (Result.empty())
731 Result.append(res.begin(), res.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000732 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000733}
734
735static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000736 const RelocationRef &Rel,
Rafael Espindola37070a52015-06-03 04:48:06 +0000737 SmallVectorImpl<char> &Result) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000738 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
739 return getRelocationValueString(ELF32LE, Rel, Result);
740 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
741 return getRelocationValueString(ELF64LE, Rel, Result);
742 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
743 return getRelocationValueString(ELF32BE, Rel, Result);
744 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
745 return getRelocationValueString(ELF64BE, Rel, Result);
746}
747
748static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
749 const RelocationRef &Rel,
750 SmallVectorImpl<char> &Result) {
751 symbol_iterator SymI = Rel.getSymbol();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000752 Expected<StringRef> SymNameOrErr = SymI->getName();
753 if (!SymNameOrErr)
754 return errorToErrorCode(SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000755 StringRef SymName = *SymNameOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000756 Result.append(SymName.begin(), SymName.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000757 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000758}
759
760static void printRelocationTargetName(const MachOObjectFile *O,
761 const MachO::any_relocation_info &RE,
762 raw_string_ostream &fmt) {
763 bool IsScattered = O->isRelocationScattered(RE);
764
765 // Target of a scattered relocation is an address. In the interest of
766 // generating pretty output, scan through the symbol table looking for a
767 // symbol that aligns with that address. If we find one, print it.
768 // Otherwise, we just print the hex address of the target.
769 if (IsScattered) {
770 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
771
772 for (const SymbolRef &Symbol : O->symbols()) {
773 std::error_code ec;
Kevin Enderby931cb652016-06-24 18:24:42 +0000774 Expected<uint64_t> Addr = Symbol.getAddress();
775 if (!Addr) {
776 std::string Buf;
777 raw_string_ostream OS(Buf);
778 logAllUnhandledErrors(Addr.takeError(), OS, "");
779 OS.flush();
780 report_fatal_error(Buf);
781 }
Rafael Espindolaed067c42015-07-03 18:19:00 +0000782 if (*Addr != Val)
Rafael Espindola37070a52015-06-03 04:48:06 +0000783 continue;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000784 Expected<StringRef> Name = Symbol.getName();
785 if (!Name) {
786 std::string Buf;
787 raw_string_ostream OS(Buf);
788 logAllUnhandledErrors(Name.takeError(), OS, "");
789 OS.flush();
790 report_fatal_error(Buf);
791 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000792 fmt << *Name;
Rafael Espindola37070a52015-06-03 04:48:06 +0000793 return;
794 }
795
796 // If we couldn't find a symbol that this relocation refers to, try
797 // to find a section beginning instead.
Colin LeMahieu77804be2015-07-29 15:45:39 +0000798 for (const SectionRef &Section : ToolSectionFilter(*O)) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000799 std::error_code ec;
800
801 StringRef Name;
802 uint64_t Addr = Section.getAddress();
803 if (Addr != Val)
804 continue;
805 if ((ec = Section.getName(Name)))
806 report_fatal_error(ec.message());
807 fmt << Name;
808 return;
809 }
810
811 fmt << format("0x%x", Val);
812 return;
813 }
814
815 StringRef S;
816 bool isExtern = O->getPlainRelocationExternal(RE);
817 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
818
819 if (isExtern) {
820 symbol_iterator SI = O->symbol_begin();
821 advance(SI, Val);
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000822 Expected<StringRef> SOrErr = SI->getName();
823 error(errorToErrorCode(SOrErr.takeError()));
Davide Italianoccd53fe2015-08-05 07:18:31 +0000824 S = *SOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000825 } else {
826 section_iterator SI = O->section_begin();
827 // Adjust for the fact that sections are 1-indexed.
828 advance(SI, Val - 1);
829 SI->getName(S);
830 }
831
832 fmt << S;
833}
834
835static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
836 const RelocationRef &RelRef,
837 SmallVectorImpl<char> &Result) {
838 DataRefImpl Rel = RelRef.getRawDataRefImpl();
839 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
840
841 unsigned Arch = Obj->getArch();
842
843 std::string fmtbuf;
844 raw_string_ostream fmt(fmtbuf);
845 unsigned Type = Obj->getAnyRelocationType(RE);
846 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
847
848 // Determine any addends that should be displayed with the relocation.
849 // These require decoding the relocation type, which is triple-specific.
850
851 // X86_64 has entirely custom relocation types.
852 if (Arch == Triple::x86_64) {
853 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
854
855 switch (Type) {
856 case MachO::X86_64_RELOC_GOT_LOAD:
857 case MachO::X86_64_RELOC_GOT: {
858 printRelocationTargetName(Obj, RE, fmt);
859 fmt << "@GOT";
860 if (isPCRel)
861 fmt << "PCREL";
862 break;
863 }
864 case MachO::X86_64_RELOC_SUBTRACTOR: {
865 DataRefImpl RelNext = Rel;
866 Obj->moveRelocationNext(RelNext);
867 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
868
869 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
870 // X86_64_RELOC_UNSIGNED.
871 // NOTE: Scattered relocations don't exist on x86_64.
872 unsigned RType = Obj->getAnyRelocationType(RENext);
873 if (RType != MachO::X86_64_RELOC_UNSIGNED)
874 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
875 "X86_64_RELOC_SUBTRACTOR.");
876
877 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
878 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
879 printRelocationTargetName(Obj, RENext, fmt);
880 fmt << "-";
881 printRelocationTargetName(Obj, RE, fmt);
882 break;
883 }
884 case MachO::X86_64_RELOC_TLV:
885 printRelocationTargetName(Obj, RE, fmt);
886 fmt << "@TLV";
887 if (isPCRel)
888 fmt << "P";
889 break;
890 case MachO::X86_64_RELOC_SIGNED_1:
891 printRelocationTargetName(Obj, RE, fmt);
892 fmt << "-1";
893 break;
894 case MachO::X86_64_RELOC_SIGNED_2:
895 printRelocationTargetName(Obj, RE, fmt);
896 fmt << "-2";
897 break;
898 case MachO::X86_64_RELOC_SIGNED_4:
899 printRelocationTargetName(Obj, RE, fmt);
900 fmt << "-4";
901 break;
902 default:
903 printRelocationTargetName(Obj, RE, fmt);
904 break;
905 }
906 // X86 and ARM share some relocation types in common.
907 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
908 Arch == Triple::ppc) {
909 // Generic relocation types...
910 switch (Type) {
911 case MachO::GENERIC_RELOC_PAIR: // prints no info
Rui Ueyama7d099192015-06-09 15:20:42 +0000912 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000913 case MachO::GENERIC_RELOC_SECTDIFF: {
914 DataRefImpl RelNext = Rel;
915 Obj->moveRelocationNext(RelNext);
916 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
917
918 // X86 sect diff's must be followed by a relocation of type
919 // GENERIC_RELOC_PAIR.
920 unsigned RType = Obj->getAnyRelocationType(RENext);
921
922 if (RType != MachO::GENERIC_RELOC_PAIR)
923 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
924 "GENERIC_RELOC_SECTDIFF.");
925
926 printRelocationTargetName(Obj, RE, fmt);
927 fmt << "-";
928 printRelocationTargetName(Obj, RENext, fmt);
929 break;
930 }
931 }
932
933 if (Arch == Triple::x86 || Arch == Triple::ppc) {
934 switch (Type) {
935 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
936 DataRefImpl RelNext = Rel;
937 Obj->moveRelocationNext(RelNext);
938 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
939
940 // X86 sect diff's must be followed by a relocation of type
941 // GENERIC_RELOC_PAIR.
942 unsigned RType = Obj->getAnyRelocationType(RENext);
943 if (RType != MachO::GENERIC_RELOC_PAIR)
944 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
945 "GENERIC_RELOC_LOCAL_SECTDIFF.");
946
947 printRelocationTargetName(Obj, RE, fmt);
948 fmt << "-";
949 printRelocationTargetName(Obj, RENext, fmt);
950 break;
951 }
952 case MachO::GENERIC_RELOC_TLV: {
953 printRelocationTargetName(Obj, RE, fmt);
954 fmt << "@TLV";
955 if (IsPCRel)
956 fmt << "P";
957 break;
958 }
959 default:
960 printRelocationTargetName(Obj, RE, fmt);
961 }
962 } else { // ARM-specific relocations
963 switch (Type) {
964 case MachO::ARM_RELOC_HALF:
965 case MachO::ARM_RELOC_HALF_SECTDIFF: {
966 // Half relocations steal a bit from the length field to encode
967 // whether this is an upper16 or a lower16 relocation.
968 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
969
970 if (isUpper)
971 fmt << ":upper16:(";
972 else
973 fmt << ":lower16:(";
974 printRelocationTargetName(Obj, RE, fmt);
975
976 DataRefImpl RelNext = Rel;
977 Obj->moveRelocationNext(RelNext);
978 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
979
980 // ARM half relocs must be followed by a relocation of type
981 // ARM_RELOC_PAIR.
982 unsigned RType = Obj->getAnyRelocationType(RENext);
983 if (RType != MachO::ARM_RELOC_PAIR)
984 report_fatal_error("Expected ARM_RELOC_PAIR after "
985 "ARM_RELOC_HALF");
986
987 // NOTE: The half of the target virtual address is stashed in the
988 // address field of the secondary relocation, but we can't reverse
989 // engineer the constant offset from it without decoding the movw/movt
990 // instruction to find the other half in its immediate field.
991
992 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
993 // symbol/section pointer of the follow-on relocation.
994 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
995 fmt << "-";
996 printRelocationTargetName(Obj, RENext, fmt);
997 }
998
999 fmt << ")";
1000 break;
1001 }
1002 default: { printRelocationTargetName(Obj, RE, fmt); }
1003 }
1004 }
1005 } else
1006 printRelocationTargetName(Obj, RE, fmt);
1007
1008 fmt.flush();
1009 Result.append(fmtbuf.begin(), fmtbuf.end());
Rui Ueyama7d099192015-06-09 15:20:42 +00001010 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +00001011}
1012
1013static std::error_code getRelocationValueString(const RelocationRef &Rel,
1014 SmallVectorImpl<char> &Result) {
Rafael Espindola854038e2015-06-26 14:51:16 +00001015 const ObjectFile *Obj = Rel.getObject();
Rafael Espindola37070a52015-06-03 04:48:06 +00001016 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
1017 return getRelocationValueString(ELF, Rel, Result);
1018 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
1019 return getRelocationValueString(COFF, Rel, Result);
1020 auto *MachO = cast<MachOObjectFile>(Obj);
1021 return getRelocationValueString(MachO, Rel, Result);
1022}
1023
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001024/// @brief Indicates whether this relocation should hidden when listing
1025/// relocations, usually because it is the trailing part of a multipart
1026/// relocation that will be printed as part of the leading relocation.
1027static bool getHidden(RelocationRef RelRef) {
1028 const ObjectFile *Obj = RelRef.getObject();
1029 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
1030 if (!MachO)
1031 return false;
1032
1033 unsigned Arch = MachO->getArch();
1034 DataRefImpl Rel = RelRef.getRawDataRefImpl();
1035 uint64_t Type = MachO->getRelocationType(Rel);
1036
1037 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
1038 // is always hidden.
1039 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
1040 if (Type == MachO::GENERIC_RELOC_PAIR)
1041 return true;
1042 } else if (Arch == Triple::x86_64) {
1043 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
1044 // an X86_64_RELOC_SUBTRACTOR.
1045 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
1046 DataRefImpl RelPrev = Rel;
1047 RelPrev.d.a--;
1048 uint64_t PrevType = MachO->getRelocationType(RelPrev);
1049 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
1050 return true;
1051 }
1052 }
1053
1054 return false;
1055}
1056
Sam Koltonc05d7782016-08-17 10:17:57 +00001057static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) {
1058 assert(Obj->isELF());
1059 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1060 return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1061 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1062 return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1063 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1064 return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1065 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1066 return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1067 llvm_unreachable("Unsupported binary format");
1068}
1069
Michael J. Spencer51862b32011-10-13 22:17:18 +00001070static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001071 if (StartAddress > StopAddress)
1072 error("Start address should be less than stop address");
1073
Jim Grosbachaf9aec02012-08-07 17:53:14 +00001074 const Target *TheTarget = getTarget(Obj);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001075
Jack Carter551efd72012-08-28 19:24:49 +00001076 // Package up features to be passed to target/subtarget
Daniel Sanders1d148642016-06-16 09:17:03 +00001077 SubtargetFeatures Features = Obj->getFeatures();
Jack Carter551efd72012-08-28 19:24:49 +00001078 if (MAttrs.size()) {
Jack Carter551efd72012-08-28 19:24:49 +00001079 for (unsigned i = 0; i != MAttrs.size(); ++i)
1080 Features.AddFeature(MAttrs[i]);
Jack Carter551efd72012-08-28 19:24:49 +00001081 }
1082
Ahmed Charles56440fd2014-03-06 05:51:42 +00001083 std::unique_ptr<const MCRegisterInfo> MRI(
1084 TheTarget->createMCRegInfo(TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +00001085 if (!MRI)
1086 report_fatal_error("error: no register info for target " + TripleName);
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001087
1088 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00001089 std::unique_ptr<const MCAsmInfo> AsmInfo(
1090 TheTarget->createMCAsmInfo(*MRI, TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +00001091 if (!AsmInfo)
1092 report_fatal_error("error: no assembly info for target " + TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +00001093 std::unique_ptr<const MCSubtargetInfo> STI(
Daniel Sanders1d148642016-06-16 09:17:03 +00001094 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
Davide Italiano711e4952015-12-17 01:59:50 +00001095 if (!STI)
1096 report_fatal_error("error: no subtarget info for target " + TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +00001097 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
Davide Italiano711e4952015-12-17 01:59:50 +00001098 if (!MII)
1099 report_fatal_error("error: no instruction info for target " + TripleName);
Sam Kolton3381d7a2016-10-06 13:46:08 +00001100 MCObjectFileInfo MOFI;
1101 MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI);
1102 // FIXME: for now initialize MCObjectFileInfo with default values
1103 MOFI.InitMCObjectFileInfo(Triple(TripleName), false, CodeModel::Default, Ctx);
Lang Hamesa1bc0f52014-04-15 04:40:56 +00001104
1105 std::unique_ptr<MCDisassembler> DisAsm(
1106 TheTarget->createMCDisassembler(*STI, Ctx));
Davide Italiano711e4952015-12-17 01:59:50 +00001107 if (!DisAsm)
1108 report_fatal_error("error: no disassembler for target " + TripleName);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001109
Ahmed Charles56440fd2014-03-06 05:51:42 +00001110 std::unique_ptr<const MCInstrAnalysis> MIA(
1111 TheTarget->createMCInstrAnalysis(MII.get()));
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001112
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001113 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Daniel Sanders50f17232015-09-15 16:17:27 +00001114 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1115 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
Davide Italiano711e4952015-12-17 01:59:50 +00001116 if (!IP)
1117 report_fatal_error("error: no instruction printer for target " +
1118 TripleName);
Colin LeMahieu14ec76e2015-06-07 21:07:17 +00001119 IP->setPrintImmHex(PrintImmHex);
Colin LeMahieu35436a22015-05-29 14:48:25 +00001120 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001121
Greg Fitzgerald18432272014-03-20 22:55:15 +00001122 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
1123 "\t\t\t%08" PRIx64 ": ";
1124
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001125 SourcePrinter SP(Obj, TheTarget->getName());
1126
Mark Seaborn0929d3d2014-01-25 17:38:19 +00001127 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
1128 // in RelocSecs contain the relocations for section S.
Rafael Espindola4453e42942014-06-13 03:07:50 +00001129 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +00001130 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001131 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001132 section_iterator Sec2 = Section.getRelocatedSection();
Rafael Espindolab5155a52014-02-10 20:24:04 +00001133 if (Sec2 != Obj->section_end())
Alexey Samsonov48803e52014-03-13 14:37:36 +00001134 SectionRelocMap[*Sec2].push_back(Section);
Mark Seaborn0929d3d2014-01-25 17:38:19 +00001135 }
1136
David Majnemer81afca62015-07-07 22:06:59 +00001137 // Create a mapping from virtual address to symbol name. This is used to
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001138 // pretty print the symbols while disassembling.
Sam Koltonc05d7782016-08-17 10:17:57 +00001139 typedef std::vector<std::tuple<uint64_t, StringRef, uint8_t>> SectionSymbolsTy;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001140 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
1141 for (const SymbolRef &Symbol : Obj->symbols()) {
Kevin Enderby931cb652016-06-24 18:24:42 +00001142 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
1143 error(errorToErrorCode(AddressOrErr.takeError()));
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001144 uint64_t Address = *AddressOrErr;
David Majnemer2603a8fa2015-07-09 18:11:40 +00001145
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001146 Expected<StringRef> Name = Symbol.getName();
1147 error(errorToErrorCode(Name.takeError()));
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001148 if (Name->empty())
1149 continue;
David Majnemer81afca62015-07-07 22:06:59 +00001150
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001151 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1152 error(errorToErrorCode(SectionOrErr.takeError()));
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001153 section_iterator SecI = *SectionOrErr;
1154 if (SecI == Obj->section_end())
1155 continue;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001156
Sam Koltonc05d7782016-08-17 10:17:57 +00001157 uint8_t SymbolType = ELF::STT_NOTYPE;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001158 if (Obj->isELF())
Sam Koltonc05d7782016-08-17 10:17:57 +00001159 SymbolType = getElfSymbolType(Obj, Symbol);
David Majnemer81afca62015-07-07 22:06:59 +00001160
Sam Koltonc05d7782016-08-17 10:17:57 +00001161 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1162
David Majnemer81afca62015-07-07 22:06:59 +00001163 }
1164
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001165 // Create a mapping from virtual address to section.
1166 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1167 for (SectionRef Sec : Obj->sections())
1168 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1169 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
1170
1171 // Linked executables (.exe and .dll files) typically don't include a real
1172 // symbol table but they might contain an export table.
1173 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
1174 for (const auto &ExportEntry : COFFObj->export_directories()) {
1175 StringRef Name;
1176 error(ExportEntry.getSymbolName(Name));
1177 if (Name.empty())
1178 continue;
1179 uint32_t RVA;
1180 error(ExportEntry.getExportRVA(RVA));
1181
1182 uint64_t VA = COFFObj->getImageBase() + RVA;
1183 auto Sec = std::upper_bound(
1184 SectionAddresses.begin(), SectionAddresses.end(), VA,
1185 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
1186 return LHS < RHS.first;
1187 });
1188 if (Sec != SectionAddresses.begin())
1189 --Sec;
1190 else
1191 Sec = SectionAddresses.end();
1192
1193 if (Sec != SectionAddresses.end())
Sam Koltonc05d7782016-08-17 10:17:57 +00001194 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001195 }
1196 }
1197
1198 // Sort all the symbols, this allows us to use a simple binary search to find
1199 // a symbol near an address.
1200 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1201 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
1202
Colin LeMahieu77804be2015-07-29 15:45:39 +00001203 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Colin LeMahieuf34933e2015-07-23 20:58:49 +00001204 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
Mark Seaborneb03ac52014-01-25 00:32:01 +00001205 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +00001206
Rafael Espindola80291272014-10-08 15:28:58 +00001207 uint64_t SectionAddr = Section.getAddress();
1208 uint64_t SectSize = Section.getSize();
David Majnemer185b5b12014-11-11 09:58:25 +00001209 if (!SectSize)
1210 continue;
Simon Atanasyan2b614e12014-02-24 22:12:11 +00001211
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001212 // Get the list of all the symbols in this section.
1213 SectionSymbolsTy &Symbols = AllSymbols[Section];
Davide Italianof0706882015-10-01 21:57:09 +00001214 std::vector<uint64_t> DataMappingSymsAddr;
1215 std::vector<uint64_t> TextMappingSymsAddr;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001216 if (isArmElf(Obj)) {
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001217 for (const auto &Symb : Symbols) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001218 uint64_t Address = std::get<0>(Symb);
1219 StringRef Name = std::get<1>(Symb);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001220 if (Name.startswith("$d"))
David Majnemer153722d2015-11-18 04:35:32 +00001221 DataMappingSymsAddr.push_back(Address - SectionAddr);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001222 if (Name.startswith("$x"))
David Majnemer153722d2015-11-18 04:35:32 +00001223 TextMappingSymsAddr.push_back(Address - SectionAddr);
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001224 if (Name.startswith("$a"))
1225 TextMappingSymsAddr.push_back(Address - SectionAddr);
1226 if (Name.startswith("$t"))
1227 TextMappingSymsAddr.push_back(Address - SectionAddr);
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001228 }
1229 }
1230
Davide Italianof0706882015-10-01 21:57:09 +00001231 std::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end());
1232 std::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end());
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001233
Sam Kolton3381d7a2016-10-06 13:46:08 +00001234 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1235 // AMDGPU disassembler uses symbolizer for printing labels
1236 std::unique_ptr<MCRelocationInfo> RelInfo(
1237 TheTarget->createMCRelocationInfo(TripleName, Ctx));
1238 if (RelInfo) {
1239 std::unique_ptr<MCSymbolizer> Symbolizer(
1240 TheTarget->createMCSymbolizer(
1241 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1242 DisAsm->setSymbolizer(std::move(Symbolizer));
1243 }
1244 }
1245
Michael J. Spencer51862b32011-10-13 22:17:18 +00001246 // Make a list of all the relocations for this section.
1247 std::vector<RelocationRef> Rels;
1248 if (InlineRelocs) {
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001249 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
1250 for (const RelocationRef &Reloc : RelocSec.relocations()) {
1251 Rels.push_back(Reloc);
1252 }
Michael J. Spencer51862b32011-10-13 22:17:18 +00001253 }
1254 }
1255
1256 // Sort relocations by address.
1257 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
1258
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001259 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +00001260 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001261 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +00001262 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001263 }
Michael J. Spencer1d6167f2011-06-25 17:55:23 +00001264 StringRef name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001265 error(Section.getName(name));
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001266
1267 if ((SectionAddr <= StopAddress) &&
1268 (SectionAddr + SectSize) >= StartAddress) {
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001269 outs() << "Disassembly of section ";
1270 if (!SegmentName.empty())
1271 outs() << SegmentName << ",";
1272 outs() << name << ':';
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001273 }
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001274
Rafael Espindola7884c952015-06-04 15:01:05 +00001275 // If the section has no symbol at the start, just insert a dummy one.
Sam Koltonc05d7782016-08-17 10:17:57 +00001276 if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) {
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001277 Symbols.insert(Symbols.begin(),
1278 std::make_tuple(SectionAddr, name, Section.isText()
1279 ? ELF::STT_FUNC
1280 : ELF::STT_OBJECT));
Sam Koltonc05d7782016-08-17 10:17:57 +00001281 }
Alp Tokere69170a2014-06-26 22:52:05 +00001282
1283 SmallString<40> Comments;
1284 raw_svector_ostream CommentStream(Comments);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001285
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001286 StringRef BytesStr;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001287 error(Section.getContents(BytesStr));
Aaron Ballman106fd7b2014-11-12 14:01:17 +00001288 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1289 BytesStr.size());
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001290
Michael J. Spencer2670c252011-01-20 06:39:06 +00001291 uint64_t Size;
1292 uint64_t Index;
1293
Michael J. Spencer51862b32011-10-13 22:17:18 +00001294 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
1295 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001296 // Disassemble symbol by symbol.
1297 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001298 uint64_t Start = std::get<0>(Symbols[si]) - SectionAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001299 // The end is either the section end or the beginning of the next
1300 // symbol.
1301 uint64_t End =
Sam Koltonc05d7782016-08-17 10:17:57 +00001302 (si == se - 1) ? SectSize : std::get<0>(Symbols[si + 1]) - SectionAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001303 // Don't try to disassemble beyond the end of section contents.
1304 if (End > SectSize)
1305 End = SectSize;
Rafael Espindolae45c7402014-08-17 16:31:39 +00001306 // If this symbol has the same address as the next symbol, then skip it.
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001307 if (Start >= End)
Michael J. Spenceree84f642011-10-13 20:37:08 +00001308 continue;
1309
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001310 // Check if we need to skip symbol
1311 // Skip if the symbol's data is not between StartAddress and StopAddress
1312 if (End + SectionAddr < StartAddress ||
1313 Start + SectionAddr > StopAddress) {
1314 continue;
1315 }
1316
1317 // Stop disassembly at the stop address specified
1318 if (End + SectionAddr > StopAddress)
1319 End = StopAddress - SectionAddr;
1320
Valery Pykhtinde048052016-04-07 07:24:01 +00001321 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1322 // make size 4 bytes folded
1323 End = Start + ((End - Start) & ~0x3ull);
Sam Koltonc05d7782016-08-17 10:17:57 +00001324 if (std::get<2>(Symbols[si]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1325 // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)
1326 Start += 256;
1327 }
1328 if (si == se - 1 ||
1329 std::get<2>(Symbols[si + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1330 // cut trailing zeroes at the end of kernel
1331 // cut up to 256 bytes
1332 const uint64_t EndAlign = 256;
1333 const auto Limit = End - (std::min)(EndAlign, End - Start);
1334 while (End > Limit &&
1335 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1336 End -= 4;
1337 }
Valery Pykhtinde048052016-04-07 07:24:01 +00001338 }
1339
Sam Koltonc05d7782016-08-17 10:17:57 +00001340 outs() << '\n' << std::get<1>(Symbols[si]) << ":\n";
Michael J. Spencer2670c252011-01-20 06:39:06 +00001341
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001342#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +00001343 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001344#else
Mark Seaborneb03ac52014-01-25 00:32:01 +00001345 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001346#endif
1347
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001348 for (Index = Start; Index < End; Index += Size) {
1349 MCInst Inst;
Owen Andersona0c3b972011-09-15 23:38:46 +00001350
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001351 if (Index + SectionAddr < StartAddress ||
1352 Index + SectionAddr > StopAddress) {
1353 // skip byte by byte till StartAddress is reached
1354 Size = 1;
1355 continue;
1356 }
Davide Italianof0706882015-10-01 21:57:09 +00001357 // AArch64 ELF binaries can interleave data and text in the
1358 // same section. We rely on the markers introduced to
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001359 // understand what we need to dump. If the data marker is within a
1360 // function, it is denoted as a word/short etc
1361 if (isArmElf(Obj) && std::get<2>(Symbols[si]) != ELF::STT_OBJECT &&
1362 !DisassembleAll) {
Davide Italianof0706882015-10-01 21:57:09 +00001363 uint64_t Stride = 0;
1364
1365 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1366 DataMappingSymsAddr.end(), Index);
1367 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1368 // Switch to data.
1369 while (Index < End) {
1370 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1371 outs() << "\t";
1372 if (Index + 4 <= End) {
1373 Stride = 4;
1374 dumpBytes(Bytes.slice(Index, 4), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001375 outs() << "\t.word\t";
1376 uint32_t Data = 0;
1377 if (Obj->isLittleEndian()) {
1378 const auto Word =
1379 reinterpret_cast<const support::ulittle32_t *>(
1380 Bytes.data() + Index);
1381 Data = *Word;
1382 } else {
1383 const auto Word = reinterpret_cast<const support::ubig32_t *>(
1384 Bytes.data() + Index);
1385 Data = *Word;
1386 }
1387 outs() << "0x" << format("%08" PRIx32, Data);
Davide Italianof0706882015-10-01 21:57:09 +00001388 } else if (Index + 2 <= End) {
1389 Stride = 2;
1390 dumpBytes(Bytes.slice(Index, 2), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001391 outs() << "\t\t.short\t";
1392 uint16_t Data = 0;
1393 if (Obj->isLittleEndian()) {
1394 const auto Short =
1395 reinterpret_cast<const support::ulittle16_t *>(
1396 Bytes.data() + Index);
1397 Data = *Short;
1398 } else {
1399 const auto Short =
1400 reinterpret_cast<const support::ubig16_t *>(Bytes.data() +
1401 Index);
1402 Data = *Short;
1403 }
1404 outs() << "0x" << format("%04" PRIx16, Data);
Davide Italianof0706882015-10-01 21:57:09 +00001405 } else {
1406 Stride = 1;
1407 dumpBytes(Bytes.slice(Index, 1), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001408 outs() << "\t\t.byte\t";
1409 outs() << "0x" << format("%02" PRIx8, Bytes.slice(Index, 1)[0]);
Davide Italianof0706882015-10-01 21:57:09 +00001410 }
1411 Index += Stride;
1412 outs() << "\n";
1413 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1414 TextMappingSymsAddr.end(), Index);
1415 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1416 break;
1417 }
1418 }
1419 }
1420
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001421 // If there is a data symbol inside an ELF text section and we are only
1422 // disassembling text (applicable all architectures),
1423 // we are in a situation where we must print the data and not
1424 // disassemble it.
1425 if (Obj->isELF() && std::get<2>(Symbols[si]) == ELF::STT_OBJECT &&
1426 !DisassembleAll && Section.isText()) {
1427 // print out data up to 8 bytes at a time in hex and ascii
1428 uint8_t AsciiData[9] = {'\0'};
1429 uint8_t Byte;
1430 int NumBytes = 0;
1431
1432 for (Index = Start; Index < End; Index += 1) {
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001433 if (((SectionAddr + Index) < StartAddress) ||
1434 ((SectionAddr + Index) > StopAddress))
1435 continue;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001436 if (NumBytes == 0) {
1437 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1438 outs() << "\t";
1439 }
1440 Byte = Bytes.slice(Index)[0];
1441 outs() << format(" %02x", Byte);
1442 AsciiData[NumBytes] = isprint(Byte) ? Byte : '.';
1443
1444 uint8_t IndentOffset = 0;
1445 NumBytes++;
1446 if (Index == End - 1 || NumBytes > 8) {
1447 // Indent the space for less than 8 bytes data.
1448 // 2 spaces for byte and one for space between bytes
1449 IndentOffset = 3 * (8 - NumBytes);
1450 for (int Excess = 8 - NumBytes; Excess < 8; Excess++)
1451 AsciiData[Excess] = '\0';
1452 NumBytes = 8;
1453 }
1454 if (NumBytes == 8) {
1455 AsciiData[8] = '\0';
1456 outs() << std::string(IndentOffset, ' ') << " ";
1457 outs() << reinterpret_cast<char *>(AsciiData);
1458 outs() << '\n';
1459 NumBytes = 0;
1460 }
1461 }
1462 }
Davide Italianof0706882015-10-01 21:57:09 +00001463 if (Index >= End)
1464 break;
1465
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001466 // Disassemble a real instruction or a data when disassemble all is
1467 // provided
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001468 bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1469 SectionAddr + Index, DebugOut,
1470 CommentStream);
1471 if (Size == 0)
1472 Size = 1;
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001473
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001474 PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001475 Bytes.slice(Index, Size), SectionAddr + Index, outs(), "",
1476 *STI, &SP);
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001477 outs() << CommentStream.str();
1478 Comments.clear();
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001479
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001480 // Try to resolve the target of a call, tail call, etc. to a specific
1481 // symbol.
1482 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1483 MIA->isConditionalBranch(Inst))) {
1484 uint64_t Target;
1485 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1486 // In a relocatable object, the target's section must reside in
1487 // the same section as the call instruction or it is accessed
1488 // through a relocation.
1489 //
1490 // In a non-relocatable object, the target may be in any section.
1491 //
1492 // N.B. We don't walk the relocations in the relocatable case yet.
1493 auto *TargetSectionSymbols = &Symbols;
1494 if (!Obj->isRelocatableObject()) {
1495 auto SectionAddress = std::upper_bound(
1496 SectionAddresses.begin(), SectionAddresses.end(), Target,
1497 [](uint64_t LHS,
1498 const std::pair<uint64_t, SectionRef> &RHS) {
1499 return LHS < RHS.first;
1500 });
1501 if (SectionAddress != SectionAddresses.begin()) {
1502 --SectionAddress;
1503 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1504 } else {
1505 TargetSectionSymbols = nullptr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001506 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001507 }
David Majnemer2603a8fa2015-07-09 18:11:40 +00001508
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001509 // Find the first symbol in the section whose offset is less than
1510 // or equal to the target.
1511 if (TargetSectionSymbols) {
1512 auto TargetSym = std::upper_bound(
1513 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1514 Target, [](uint64_t LHS,
Sam Koltonc05d7782016-08-17 10:17:57 +00001515 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1516 return LHS < std::get<0>(RHS);
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001517 });
1518 if (TargetSym != TargetSectionSymbols->begin()) {
1519 --TargetSym;
1520 uint64_t TargetAddress = std::get<0>(*TargetSym);
1521 StringRef TargetName = std::get<1>(*TargetSym);
1522 outs() << " <" << TargetName;
1523 uint64_t Disp = Target - TargetAddress;
1524 if (Disp)
1525 outs() << "+0x" << utohexstr(Disp);
1526 outs() << '>';
David Majnemer81afca62015-07-07 22:06:59 +00001527 }
1528 }
1529 }
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001530 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001531 outs() << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001532
1533 // Print relocation for instruction.
1534 while (rel_cur != rel_end) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001535 bool hidden = getHidden(*rel_cur);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001536 uint64_t addr = rel_cur->getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +00001537 SmallString<16> name;
1538 SmallString<32> val;
Owen Andersonfa3e5202011-10-25 20:35:53 +00001539
1540 // If this relocation is hidden, skip it.
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001541 if (hidden || ((SectionAddr + addr) < StartAddress)) {
1542 ++rel_cur;
1543 continue;
1544 }
Owen Andersonfa3e5202011-10-25 20:35:53 +00001545
Michael J. Spencer51862b32011-10-13 22:17:18 +00001546 // Stop when rel_cur's address is past the current instruction.
Owen Andersonf20e3e52011-10-25 20:15:39 +00001547 if (addr >= Index + Size) break;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001548 rel_cur->getTypeName(name);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001549 error(getRelocationValueString(*rel_cur, val));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001550 outs() << format(Fmt.data(), SectionAddr + addr) << name
Benjamin Kramer82803112012-03-10 02:04:38 +00001551 << "\t" << val << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001552 ++rel_cur;
1553 }
Benjamin Kramer87ee76c2011-07-20 19:37:35 +00001554 }
Michael J. Spencer2670c252011-01-20 06:39:06 +00001555 }
1556 }
1557}
1558
Kevin Enderby98da6132015-01-20 21:47:46 +00001559void llvm::PrintRelocations(const ObjectFile *Obj) {
Greg Fitzgerald18432272014-03-20 22:55:15 +00001560 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1561 "%08" PRIx64;
Rafael Espindola9219fe72016-03-21 20:59:15 +00001562 // Regular objdump doesn't print relocations in non-relocatable object
1563 // files.
1564 if (!Obj->isRelocatableObject())
1565 return;
Rafael Espindolac66d7612014-08-17 19:09:37 +00001566
Colin LeMahieu77804be2015-07-29 15:45:39 +00001567 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001568 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001569 continue;
1570 StringRef secname;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001571 error(Section.getName(secname));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001572 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001573 for (const RelocationRef &Reloc : Section.relocations()) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001574 bool hidden = getHidden(Reloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001575 uint64_t address = Reloc.getOffset();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001576 SmallString<32> relocname;
1577 SmallString<32> valuestr;
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001578 if (address < StartAddress || address > StopAddress || hidden)
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001579 continue;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001580 Reloc.getTypeName(relocname);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001581 error(getRelocationValueString(Reloc, valuestr));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001582 outs() << format(Fmt.data(), address) << " " << relocname << " "
1583 << valuestr << "\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001584 }
1585 outs() << "\n";
1586 }
1587}
1588
Kevin Enderby98da6132015-01-20 21:47:46 +00001589void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001590 outs() << "Sections:\n"
1591 "Idx Name Size Address Type\n";
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001592 unsigned i = 0;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001593 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001594 StringRef Name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001595 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001596 uint64_t Address = Section.getAddress();
1597 uint64_t Size = Section.getSize();
1598 bool Text = Section.isText();
1599 bool Data = Section.isData();
1600 bool BSS = Section.isBSS();
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001601 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +00001602 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
Alexey Samsonov48803e52014-03-13 14:37:36 +00001603 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1604 Name.str().c_str(), Size, Address, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001605 ++i;
1606 }
1607}
1608
Kevin Enderby98da6132015-01-20 21:47:46 +00001609void llvm::PrintSectionContents(const ObjectFile *Obj) {
Rafael Espindola4453e42942014-06-13 03:07:50 +00001610 std::error_code EC;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001611 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001612 StringRef Name;
1613 StringRef Contents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001614 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001615 uint64_t BaseAddr = Section.getAddress();
David Majnemer185b5b12014-11-11 09:58:25 +00001616 uint64_t Size = Section.getSize();
1617 if (!Size)
1618 continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001619
1620 outs() << "Contents of section " << Name << ":\n";
David Majnemer185b5b12014-11-11 09:58:25 +00001621 if (Section.isBSS()) {
Alexey Samsonov209095c2013-04-16 10:53:11 +00001622 outs() << format("<skipping contents of bss section at [%04" PRIx64
David Majnemer8f6b04c2014-07-14 16:20:14 +00001623 ", %04" PRIx64 ")>\n",
1624 BaseAddr, BaseAddr + Size);
Alexey Samsonov209095c2013-04-16 10:53:11 +00001625 continue;
1626 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001627
Davide Italianoccd53fe2015-08-05 07:18:31 +00001628 error(Section.getContents(Contents));
David Majnemer8f6b04c2014-07-14 16:20:14 +00001629
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001630 // Dump out the content as hex and printable ascii characters.
1631 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer82803112012-03-10 02:04:38 +00001632 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001633 // Dump line of hex.
1634 for (std::size_t i = 0; i < 16; ++i) {
1635 if (i != 0 && i % 4 == 0)
1636 outs() << ' ';
1637 if (addr + i < end)
1638 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1639 << hexdigit(Contents[addr + i] & 0xF, true);
1640 else
1641 outs() << " ";
1642 }
1643 // Print ascii.
1644 outs() << " ";
1645 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
Guy Benyei83c74e92013-02-12 21:21:59 +00001646 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001647 outs() << Contents[addr + i];
1648 else
1649 outs() << ".";
1650 }
1651 outs() << "\n";
1652 }
1653 }
1654}
1655
Kevin Enderby9acb1092016-05-31 20:35:34 +00001656void llvm::PrintSymbolTable(const ObjectFile *o, StringRef ArchiveName,
1657 StringRef ArchitectureName) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001658 outs() << "SYMBOL TABLE:\n";
1659
Rui Ueyama4e39f712014-03-18 18:58:51 +00001660 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
Davide Italianoe85abf72015-12-20 09:54:34 +00001661 printCOFFSymbolTable(coff);
Rui Ueyama4e39f712014-03-18 18:58:51 +00001662 return;
1663 }
1664 for (const SymbolRef &Symbol : o->symbols()) {
Kevin Enderby931cb652016-06-24 18:24:42 +00001665 Expected<uint64_t> AddressOrError = Symbol.getAddress();
1666 if (!AddressOrError)
1667 report_error(ArchiveName, o->getFileName(), AddressOrError.takeError());
Rafael Espindolaed067c42015-07-03 18:19:00 +00001668 uint64_t Address = *AddressOrError;
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001669 if ((Address < StartAddress) || (Address > StopAddress))
1670 continue;
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001671 Expected<SymbolRef::Type> TypeOrError = Symbol.getType();
1672 if (!TypeOrError)
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001673 report_error(ArchiveName, o->getFileName(), TypeOrError.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00001674 SymbolRef::Type Type = *TypeOrError;
Rui Ueyama4e39f712014-03-18 18:58:51 +00001675 uint32_t Flags = Symbol.getFlags();
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001676 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1677 error(errorToErrorCode(SectionOrErr.takeError()));
Rafael Espindola8bab8892015-08-07 23:27:14 +00001678 section_iterator Section = *SectionOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001679 StringRef Name;
1680 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1681 Section->getName(Name);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001682 } else {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001683 Expected<StringRef> NameOrErr = Symbol.getName();
1684 if (!NameOrErr)
Kevin Enderby9acb1092016-05-31 20:35:34 +00001685 report_error(ArchiveName, o->getFileName(), NameOrErr.takeError(),
1686 ArchitectureName);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001687 Name = *NameOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001688 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001689
Rui Ueyama4e39f712014-03-18 18:58:51 +00001690 bool Global = Flags & SymbolRef::SF_Global;
1691 bool Weak = Flags & SymbolRef::SF_Weak;
1692 bool Absolute = Flags & SymbolRef::SF_Absolute;
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001693 bool Common = Flags & SymbolRef::SF_Common;
Davide Italianocd2514d2015-04-30 23:08:53 +00001694 bool Hidden = Flags & SymbolRef::SF_Hidden;
David Meyer1df4b842012-02-28 23:47:53 +00001695
Rui Ueyama4e39f712014-03-18 18:58:51 +00001696 char GlobLoc = ' ';
1697 if (Type != SymbolRef::ST_Unknown)
1698 GlobLoc = Global ? 'g' : 'l';
1699 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1700 ? 'd' : ' ';
1701 char FileFunc = ' ';
1702 if (Type == SymbolRef::ST_File)
1703 FileFunc = 'f';
1704 else if (Type == SymbolRef::ST_Function)
1705 FileFunc = 'F';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001706
Rui Ueyama4e39f712014-03-18 18:58:51 +00001707 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1708 "%08" PRIx64;
Michael J. Spencerd857c1c2013-01-10 22:40:50 +00001709
Rui Ueyama4e39f712014-03-18 18:58:51 +00001710 outs() << format(Fmt, Address) << " "
1711 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1712 << (Weak ? 'w' : ' ') // Weak?
1713 << ' ' // Constructor. Not supported yet.
1714 << ' ' // Warning. Not supported yet.
1715 << ' ' // Indirect reference to another symbol.
1716 << Debug // Debugging (d) or dynamic (D) symbol.
1717 << FileFunc // Name of function (F), file (f) or object (O).
1718 << ' ';
1719 if (Absolute) {
1720 outs() << "*ABS*";
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001721 } else if (Common) {
1722 outs() << "*COM*";
Rui Ueyama4e39f712014-03-18 18:58:51 +00001723 } else if (Section == o->section_end()) {
1724 outs() << "*UND*";
1725 } else {
1726 if (const MachOObjectFile *MachO =
1727 dyn_cast<const MachOObjectFile>(o)) {
1728 DataRefImpl DR = Section->getRawDataRefImpl();
1729 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1730 outs() << SegmentName << ",";
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001731 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00001732 StringRef SectionName;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001733 error(Section->getName(SectionName));
Rui Ueyama4e39f712014-03-18 18:58:51 +00001734 outs() << SectionName;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001735 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001736
1737 outs() << '\t';
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001738 if (Common || isa<ELFObjectFileBase>(o)) {
Rafael Espindoladbb6bd32015-06-25 22:10:04 +00001739 uint64_t Val =
1740 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001741 outs() << format("\t %08" PRIx64 " ", Val);
1742 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001743
Davide Italianocd2514d2015-04-30 23:08:53 +00001744 if (Hidden) {
1745 outs() << ".hidden ";
1746 }
1747 outs() << Name
Rui Ueyama4e39f712014-03-18 18:58:51 +00001748 << '\n';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001749 }
1750}
1751
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001752static void PrintUnwindInfo(const ObjectFile *o) {
1753 outs() << "Unwind info:\n\n";
1754
1755 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1756 printCOFFUnwindInfo(coff);
Tim Northover4bd286a2014-08-01 13:07:19 +00001757 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1758 printMachOUnwindInfo(MachO);
1759 else {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001760 // TODO: Extract DWARF dump tool to objdump.
1761 errs() << "This operation is only currently supported "
Tim Northover4bd286a2014-08-01 13:07:19 +00001762 "for COFF and MachO object files.\n";
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001763 return;
1764 }
1765}
1766
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001767void llvm::printExportsTrie(const ObjectFile *o) {
Nick Kledzikd04bc352014-08-30 00:20:14 +00001768 outs() << "Exports trie:\n";
1769 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1770 printMachOExportsTrie(MachO);
1771 else {
1772 errs() << "This operation is only currently supported "
1773 "for Mach-O executable files.\n";
1774 return;
1775 }
1776}
1777
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001778void llvm::printRebaseTable(const ObjectFile *o) {
Nick Kledzikac431442014-09-12 21:34:15 +00001779 outs() << "Rebase table:\n";
1780 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1781 printMachORebaseTable(MachO);
1782 else {
1783 errs() << "This operation is only currently supported "
1784 "for Mach-O executable files.\n";
1785 return;
1786 }
1787}
1788
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001789void llvm::printBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001790 outs() << "Bind table:\n";
1791 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1792 printMachOBindTable(MachO);
1793 else {
1794 errs() << "This operation is only currently supported "
1795 "for Mach-O executable files.\n";
1796 return;
1797 }
1798}
1799
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001800void llvm::printLazyBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001801 outs() << "Lazy bind table:\n";
1802 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1803 printMachOLazyBindTable(MachO);
1804 else {
1805 errs() << "This operation is only currently supported "
1806 "for Mach-O executable files.\n";
1807 return;
1808 }
1809}
1810
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001811void llvm::printWeakBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001812 outs() << "Weak bind table:\n";
1813 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1814 printMachOWeakBindTable(MachO);
1815 else {
1816 errs() << "This operation is only currently supported "
1817 "for Mach-O executable files.\n";
1818 return;
1819 }
1820}
Nick Kledzikac431442014-09-12 21:34:15 +00001821
Adrian Prantl437105a2015-07-08 02:04:15 +00001822/// Dump the raw contents of the __clangast section so the output can be piped
1823/// into llvm-bcanalyzer.
1824void llvm::printRawClangAST(const ObjectFile *Obj) {
1825 if (outs().is_displayed()) {
1826 errs() << "The -raw-clang-ast option will dump the raw binary contents of "
1827 "the clang ast section.\n"
1828 "Please redirect the output to a file or another program such as "
1829 "llvm-bcanalyzer.\n";
1830 return;
1831 }
1832
1833 StringRef ClangASTSectionName("__clangast");
1834 if (isa<COFFObjectFile>(Obj)) {
1835 ClangASTSectionName = "clangast";
1836 }
1837
1838 Optional<object::SectionRef> ClangASTSection;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001839 for (auto Sec : ToolSectionFilter(*Obj)) {
Adrian Prantl437105a2015-07-08 02:04:15 +00001840 StringRef Name;
1841 Sec.getName(Name);
1842 if (Name == ClangASTSectionName) {
1843 ClangASTSection = Sec;
1844 break;
1845 }
1846 }
1847 if (!ClangASTSection)
1848 return;
1849
1850 StringRef ClangASTContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001851 error(ClangASTSection.getValue().getContents(ClangASTContents));
Adrian Prantl437105a2015-07-08 02:04:15 +00001852 outs().write(ClangASTContents.data(), ClangASTContents.size());
1853}
1854
Sanjoy Das6f567a42015-06-22 18:03:02 +00001855static void printFaultMaps(const ObjectFile *Obj) {
1856 const char *FaultMapSectionName = nullptr;
1857
1858 if (isa<ELFObjectFileBase>(Obj)) {
1859 FaultMapSectionName = ".llvm_faultmaps";
1860 } else if (isa<MachOObjectFile>(Obj)) {
1861 FaultMapSectionName = "__llvm_faultmaps";
1862 } else {
1863 errs() << "This operation is only currently supported "
1864 "for ELF and Mach-O executable files.\n";
1865 return;
1866 }
1867
1868 Optional<object::SectionRef> FaultMapSection;
1869
Colin LeMahieu77804be2015-07-29 15:45:39 +00001870 for (auto Sec : ToolSectionFilter(*Obj)) {
Sanjoy Das6f567a42015-06-22 18:03:02 +00001871 StringRef Name;
1872 Sec.getName(Name);
1873 if (Name == FaultMapSectionName) {
1874 FaultMapSection = Sec;
1875 break;
1876 }
1877 }
1878
1879 outs() << "FaultMap table:\n";
1880
1881 if (!FaultMapSection.hasValue()) {
1882 outs() << "<not found>\n";
1883 return;
1884 }
1885
1886 StringRef FaultMapContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001887 error(FaultMapSection.getValue().getContents(FaultMapContents));
Sanjoy Das6f567a42015-06-22 18:03:02 +00001888
1889 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1890 FaultMapContents.bytes_end());
1891
1892 outs() << FMP;
1893}
1894
Davide Italiano1bdaa202016-09-18 04:39:15 +00001895static void printPrivateFileHeaders(const ObjectFile *o, bool onlyFirst) {
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001896 if (o->isELF())
Davide Italiano1bdaa202016-09-18 04:39:15 +00001897 return printELFFileHeader(o);
1898 if (o->isCOFF())
1899 return printCOFFFileHeader(o);
1900 if (o->isMachO()) {
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001901 printMachOFileHeader(o);
Davide Italiano1bdaa202016-09-18 04:39:15 +00001902 if (!onlyFirst)
1903 printMachOLoadCommands(o);
1904 return;
1905 }
1906 report_fatal_error("Invalid/Unsupported object file format");
Rui Ueyamac2bed422013-09-27 21:04:00 +00001907}
1908
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001909static void DumpObject(const ObjectFile *o, const Archive *a = nullptr) {
1910 StringRef ArchiveName = a != nullptr ? a->getFileName() : "";
Adrian Prantl437105a2015-07-08 02:04:15 +00001911 // Avoid other output when using a raw option.
1912 if (!RawClangAST) {
1913 outs() << '\n';
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001914 if (a)
1915 outs() << a->getFileName() << "(" << o->getFileName() << ")";
1916 else
1917 outs() << o->getFileName();
1918 outs() << ":\tfile format " << o->getFileFormatName() << "\n\n";
Adrian Prantl437105a2015-07-08 02:04:15 +00001919 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001920
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001921 if (Disassemble)
Michael J. Spencer51862b32011-10-13 22:17:18 +00001922 DisassembleObject(o, Relocations);
1923 if (Relocations && !Disassemble)
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001924 PrintRelocations(o);
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001925 if (SectionHeaders)
1926 PrintSectionHeaders(o);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001927 if (SectionContents)
1928 PrintSectionContents(o);
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001929 if (SymbolTable)
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001930 PrintSymbolTable(o, ArchiveName);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001931 if (UnwindInfo)
1932 PrintUnwindInfo(o);
Davide Italiano1bdaa202016-09-18 04:39:15 +00001933 if (PrivateHeaders || FirstPrivateHeader)
1934 printPrivateFileHeaders(o, FirstPrivateHeader);
Nick Kledzikd04bc352014-08-30 00:20:14 +00001935 if (ExportsTrie)
1936 printExportsTrie(o);
Nick Kledzikac431442014-09-12 21:34:15 +00001937 if (Rebase)
1938 printRebaseTable(o);
Nick Kledzik56ebef42014-09-16 01:41:51 +00001939 if (Bind)
1940 printBindTable(o);
1941 if (LazyBind)
1942 printLazyBindTable(o);
1943 if (WeakBind)
1944 printWeakBindTable(o);
Adrian Prantl437105a2015-07-08 02:04:15 +00001945 if (RawClangAST)
1946 printRawClangAST(o);
Sanjoy Das6f567a42015-06-22 18:03:02 +00001947 if (PrintFaultMaps)
1948 printFaultMaps(o);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001949 if (DwarfDumpType != DIDT_Null) {
1950 std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*o));
1951 // Dump the complete DWARF structure.
1952 DICtx->dump(outs(), DwarfDumpType, true /* DumpEH */);
1953 }
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001954}
1955
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00001956static void DumpObject(const COFFImportFile *I, const Archive *A) {
1957 StringRef ArchiveName = A ? A->getFileName() : "";
1958
1959 // Avoid other output when using a raw option.
1960 if (!RawClangAST)
1961 outs() << '\n'
1962 << ArchiveName << "(" << I->getFileName() << ")"
1963 << ":\tfile format COFF-import-file"
1964 << "\n\n";
1965
1966 if (SymbolTable)
1967 printCOFFSymbolTable(I);
1968}
1969
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001970/// @brief Dump each object file in \a a;
1971static void DumpArchive(const Archive *a) {
Mehdi Amini41af4302016-11-11 04:28:40 +00001972 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00001973 for (auto &C : a->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001974 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1975 if (!ChildOrErr) {
1976 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1977 report_error(a->getFileName(), C, std::move(E));
1978 continue;
1979 }
Rafael Espindolaae460022014-06-16 16:08:36 +00001980 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001981 DumpObject(o, a);
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00001982 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
1983 DumpObject(I, a);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001984 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001985 report_error(a->getFileName(), object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001986 }
Lang Hamesfc209622016-07-14 02:24:01 +00001987 if (Err)
1988 report_error(a->getFileName(), std::move(Err));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001989}
1990
1991/// @brief Open file and figure out how to dump it.
1992static void DumpInput(StringRef file) {
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001993
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001994 // If we are using the Mach-O specific object file parser, then let it parse
1995 // the file and process the command line options. So the -arch flags can
1996 // be used to select specific slices, etc.
1997 if (MachOOpt) {
1998 ParseInputMachO(file);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001999 return;
2000 }
2001
2002 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00002003 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
2004 if (!BinaryOrErr)
Kevin Enderbyb34e3a12016-05-05 17:43:35 +00002005 report_error(file, BinaryOrErr.takeError());
Rafael Espindola48af1c22014-08-19 18:44:46 +00002006 Binary &Binary = *BinaryOrErr.get().getBinary();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002007
Rafael Espindola3f6481d2014-08-01 14:31:55 +00002008 if (Archive *a = dyn_cast<Archive>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002009 DumpArchive(a);
Rafael Espindola3f6481d2014-08-01 14:31:55 +00002010 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002011 DumpObject(o);
Jim Grosbachaf9aec02012-08-07 17:53:14 +00002012 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00002013 report_error(file, object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002014}
2015
Michael J. Spencer2670c252011-01-20 06:39:06 +00002016int main(int argc, char **argv) {
2017 // Print a stack trace if we signal out.
Richard Smith2ad6d482016-06-09 00:53:21 +00002018 sys::PrintStackTraceOnErrorSignal(argv[0]);
Michael J. Spencer2670c252011-01-20 06:39:06 +00002019 PrettyStackTraceProgram X(argc, argv);
2020 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
2021
2022 // Initialize targets and assembly printers/parsers.
2023 llvm::InitializeAllTargetInfos();
Evan Cheng8c886a42011-07-22 21:58:54 +00002024 llvm::InitializeAllTargetMCs();
Michael J. Spencer2670c252011-01-20 06:39:06 +00002025 llvm::InitializeAllDisassemblers();
2026
Pete Cooper28fb4fc2012-05-03 23:20:10 +00002027 // Register the target printer for --version.
2028 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
2029
Michael J. Spencer2670c252011-01-20 06:39:06 +00002030 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
2031 TripleName = Triple::normalize(TripleName);
2032
2033 ToolName = argv[0];
2034
2035 // Defaults to a.out if no filenames specified.
2036 if (InputFilenames.size() == 0)
2037 InputFilenames.push_back("a.out");
2038
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00002039 if (DisassembleAll || PrintSource || PrintLines)
Colin LeMahieuf34933e2015-07-23 20:58:49 +00002040 Disassemble = true;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002041 if (!Disassemble
2042 && !Relocations
2043 && !SectionHeaders
2044 && !SectionContents
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00002045 && !SymbolTable
Michael J. Spencer209565db2013-01-06 03:56:49 +00002046 && !UnwindInfo
Nick Kledzikd04bc352014-08-30 00:20:14 +00002047 && !PrivateHeaders
Kevin Enderby0ae163f2016-01-13 00:25:36 +00002048 && !FirstPrivateHeader
Nick Kledzikac431442014-09-12 21:34:15 +00002049 && !ExportsTrie
Nick Kledzik56ebef42014-09-16 01:41:51 +00002050 && !Rebase
2051 && !Bind
2052 && !LazyBind
Kevin Enderby131d1772015-01-09 19:22:37 +00002053 && !WeakBind
Adrian Prantl437105a2015-07-08 02:04:15 +00002054 && !RawClangAST
Kevin Enderby13023a12015-01-15 23:19:11 +00002055 && !(UniversalHeaders && MachOOpt)
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00002056 && !(ArchiveHeaders && MachOOpt)
Kevin Enderby69fe98d2015-01-23 18:52:17 +00002057 && !(IndirectSymbols && MachOOpt)
Kevin Enderby9a509442015-01-27 21:28:24 +00002058 && !(DataInCode && MachOOpt)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002059 && !(LinkOptHints && MachOOpt)
Kevin Enderbycd66be52015-03-11 22:06:32 +00002060 && !(InfoPlist && MachOOpt)
Kevin Enderbybc847fa2015-03-16 20:08:09 +00002061 && !(DylibsUsed && MachOOpt)
2062 && !(DylibId && MachOOpt)
Kevin Enderby0fc11822015-04-01 20:57:01 +00002063 && !(ObjcMetaData && MachOOpt)
Colin LeMahieufcc32762015-07-29 19:08:10 +00002064 && !(FilterSections.size() != 0 && MachOOpt)
Igor Laevsky03a670c2016-01-26 15:09:42 +00002065 && !PrintFaultMaps
2066 && DwarfDumpType == DIDT_Null) {
Michael J. Spencer2670c252011-01-20 06:39:06 +00002067 cl::PrintHelpMessage();
2068 return 2;
2069 }
2070
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002071 std::for_each(InputFilenames.begin(), InputFilenames.end(),
2072 DumpInput);
Michael J. Spencer2670c252011-01-20 06:39:06 +00002073
Davide Italianoccd53fe2015-08-05 07:18:31 +00002074 return EXIT_SUCCESS;
Michael J. Spencer2670c252011-01-20 06:39:06 +00002075}