blob: d54b45515f05f31a2198752954c1900ad854656a [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"
Sam Clegg4df5d762017-06-27 20:40:53 +000044#include "llvm/Object/Wasm.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000045#include "llvm/Support/Casting.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000046#include "llvm/Support/CommandLine.h"
47#include "llvm/Support/Debug.h"
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +000048#include "llvm/Support/Errc.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000049#include "llvm/Support/FileSystem.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000050#include "llvm/Support/Format.h"
Benjamin Kramerbf115312011-07-25 23:04:36 +000051#include "llvm/Support/GraphWriter.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000052#include "llvm/Support/Host.h"
53#include "llvm/Support/ManagedStatic.h"
54#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000055#include "llvm/Support/PrettyStackTrace.h"
56#include "llvm/Support/Signals.h"
57#include "llvm/Support/SourceMgr.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000058#include "llvm/Support/TargetRegistry.h"
59#include "llvm/Support/TargetSelect.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000060#include "llvm/Support/raw_ostream.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000061#include <algorithm>
Benjamin Kramera5177e62012-03-23 11:49:32 +000062#include <cctype>
Michael J. Spencer2670c252011-01-20 06:39:06 +000063#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000064#include <system_error>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000065#include <utility>
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +000066#include <unordered_map>
Ahmed Bougacha17926472013-08-21 07:29:02 +000067
Michael J. Spencer2670c252011-01-20 06:39:06 +000068using namespace llvm;
69using namespace object;
70
Benjamin Kramer43a772e2011-09-19 17:56:04 +000071static cl::list<std::string>
72InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
Michael J. Spencer2670c252011-01-20 06:39:06 +000073
Kevin Enderbye2297dd2015-01-07 21:02:18 +000074cl::opt<bool>
75llvm::Disassemble("disassemble",
Benjamin Kramer43a772e2011-09-19 17:56:04 +000076 cl::desc("Display assembler mnemonics for the machine instructions"));
77static cl::alias
78Disassembled("d", cl::desc("Alias for --disassemble"),
Colin LeMahieu77804be2015-07-29 15:45:39 +000079 cl::aliasopt(Disassemble));
80
81cl::opt<bool>
82llvm::DisassembleAll("disassemble-all",
83 cl::desc("Display assembler mnemonics for the machine instructions"));
84static cl::alias
85DisassembleAlld("D", cl::desc("Alias for --disassemble-all"),
Colin LeMahieuf34933e2015-07-23 20:58:49 +000086 cl::aliasopt(DisassembleAll));
Michael J. Spencer2670c252011-01-20 06:39:06 +000087
Kevin Enderby98da6132015-01-20 21:47:46 +000088cl::opt<bool>
89llvm::Relocations("r", cl::desc("Display the relocation entries in the file"));
Michael J. Spencerba4a3622011-10-08 00:18:30 +000090
Kevin Enderby98da6132015-01-20 21:47:46 +000091cl::opt<bool>
92llvm::SectionContents("s", cl::desc("Display the content of each section"));
Michael J. Spencer4e25c022011-10-17 17:13:22 +000093
Kevin Enderby98da6132015-01-20 21:47:46 +000094cl::opt<bool>
95llvm::SymbolTable("t", cl::desc("Display the symbol table"));
Michael J. Spencerbfa06782011-10-18 19:32:17 +000096
Kevin Enderbye2297dd2015-01-07 21:02:18 +000097cl::opt<bool>
98llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
Nick Kledzikd04bc352014-08-30 00:20:14 +000099
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000100cl::opt<bool>
101llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
Nick Kledzikac431442014-09-12 21:34:15 +0000102
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000103cl::opt<bool>
104llvm::Bind("bind", cl::desc("Display mach-o binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000105
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000106cl::opt<bool>
107llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000108
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000109cl::opt<bool>
110llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000111
Adrian Prantl437105a2015-07-08 02:04:15 +0000112cl::opt<bool>
113llvm::RawClangAST("raw-clang-ast",
114 cl::desc("Dump the raw binary contents of the clang AST section"));
115
Nick Kledzik56ebef42014-09-16 01:41:51 +0000116static cl::opt<bool>
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000117MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000118static cl::alias
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000119MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
Benjamin Kramer87ee76c2011-07-20 19:37:35 +0000120
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000121cl::opt<std::string>
122llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
123 "see -version for available targets"));
124
125cl::opt<std::string>
Kevin Enderbyc9595622014-08-06 23:24:41 +0000126llvm::MCPU("mcpu",
127 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
128 cl::value_desc("cpu-name"),
129 cl::init(""));
130
131cl::opt<std::string>
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000132llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
Michael J. Spencer2670c252011-01-20 06:39:06 +0000133 "see -version for available targets"));
134
Kevin Enderby98da6132015-01-20 21:47:46 +0000135cl::opt<bool>
136llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
137 "headers for each section."));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000138static cl::alias
139SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
140 cl::aliasopt(SectionHeaders));
141static cl::alias
142SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
143 cl::aliasopt(SectionHeaders));
Colin LeMahieufcc32762015-07-29 19:08:10 +0000144
Colin LeMahieu77804be2015-07-29 15:45:39 +0000145cl::list<std::string>
Colin LeMahieufcc32762015-07-29 19:08:10 +0000146llvm::FilterSections("section", cl::desc("Operate on the specified sections only. "
147 "With -macho dump segment,section"));
148cl::alias
149static FilterSectionsj("j", cl::desc("Alias for --section"),
150 cl::aliasopt(llvm::FilterSections));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000151
Kevin Enderbyc9595622014-08-06 23:24:41 +0000152cl::list<std::string>
153llvm::MAttrs("mattr",
Jack Carter551efd72012-08-28 19:24:49 +0000154 cl::CommaSeparated,
155 cl::desc("Target specific attributes"),
156 cl::value_desc("a1,+a2,-a3,..."));
157
Kevin Enderbybf246f52014-09-24 23:08:22 +0000158cl::opt<bool>
159llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
160 "instructions, do not print "
161 "the instruction bytes."));
Saleem Abdulrasooldea14b22017-02-08 18:11:31 +0000162cl::opt<bool>
163llvm::NoLeadingAddr("no-leading-addr", cl::desc("Print no leading address"));
Eli Bendersky3a6808c2012-11-20 22:57:02 +0000164
Kevin Enderby98da6132015-01-20 21:47:46 +0000165cl::opt<bool>
166llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000167
168static cl::alias
169UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
170 cl::aliasopt(UnwindInfo));
171
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000172cl::opt<bool>
173llvm::PrivateHeaders("private-headers",
174 cl::desc("Display format specific file headers"));
Michael J. Spencer209565db2013-01-06 03:56:49 +0000175
Kevin Enderby0ae163f2016-01-13 00:25:36 +0000176cl::opt<bool>
177llvm::FirstPrivateHeader("private-header",
178 cl::desc("Display only the first format specific file "
179 "header"));
180
Michael J. Spencer209565db2013-01-06 03:56:49 +0000181static cl::alias
182PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
183 cl::aliasopt(PrivateHeaders));
184
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000185cl::opt<bool>
186 llvm::PrintImmHex("print-imm-hex",
Colin LeMahieuefe37322016-04-08 18:15:37 +0000187 cl::desc("Use hex format for immediate values"));
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000188
Sanjoy Das6f567a42015-06-22 18:03:02 +0000189cl::opt<bool> PrintFaultMaps("fault-map-section",
190 cl::desc("Display contents of faultmap section"));
191
Igor Laevsky03a670c2016-01-26 15:09:42 +0000192cl::opt<DIDumpType> llvm::DwarfDumpType(
193 "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"),
Mehdi Amini732afdd2016-10-08 19:41:06 +0000194 cl::values(clEnumValN(DIDT_Frames, "frames", ".debug_frame")));
Igor Laevsky03a670c2016-01-26 15:09:42 +0000195
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000196cl::opt<bool> PrintSource(
197 "source",
198 cl::desc(
199 "Display source inlined with disassembly. Implies disassmble object"));
200
201cl::alias PrintSourceShort("S", cl::desc("Alias for -source"),
202 cl::aliasopt(PrintSource));
203
204cl::opt<bool> PrintLines("line-numbers",
205 cl::desc("Display source line numbers with "
206 "disassembly. Implies disassemble object"));
207
208cl::alias PrintLinesShort("l", cl::desc("Alias for -line-numbers"),
209 cl::aliasopt(PrintLines));
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +0000210
211cl::opt<unsigned long long>
212 StartAddress("start-address", cl::desc("Disassemble beginning at address"),
213 cl::value_desc("address"), cl::init(0));
214cl::opt<unsigned long long>
215 StopAddress("stop-address", cl::desc("Stop disassembly at address"),
216 cl::value_desc("address"), cl::init(UINT64_MAX));
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000217static StringRef ToolName;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000218
Sam Parker5fba45a2017-02-08 09:44:18 +0000219typedef std::vector<std::tuple<uint64_t, StringRef, uint8_t>> SectionSymbolsTy;
220
Colin LeMahieu77804be2015-07-29 15:45:39 +0000221namespace {
Colin LeMahieufcc32762015-07-29 19:08:10 +0000222typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate;
Colin LeMahieu77804be2015-07-29 15:45:39 +0000223
224class SectionFilterIterator {
225public:
226 SectionFilterIterator(FilterPredicate P,
227 llvm::object::section_iterator const &I,
228 llvm::object::section_iterator const &E)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000229 : Predicate(std::move(P)), Iterator(I), End(E) {
Colin LeMahieu77804be2015-07-29 15:45:39 +0000230 ScanPredicate();
231 }
Benjamin Kramerac9257b2015-09-24 14:52:52 +0000232 const llvm::object::SectionRef &operator*() const { return *Iterator; }
Colin LeMahieu77804be2015-07-29 15:45:39 +0000233 SectionFilterIterator &operator++() {
234 ++Iterator;
235 ScanPredicate();
236 return *this;
237 }
238 bool operator!=(SectionFilterIterator const &Other) const {
239 return Iterator != Other.Iterator;
240 }
241
242private:
243 void ScanPredicate() {
Colin LeMahieuda1723f2015-07-29 19:21:13 +0000244 while (Iterator != End && !Predicate(*Iterator)) {
Colin LeMahieu77804be2015-07-29 15:45:39 +0000245 ++Iterator;
246 }
247 }
248 FilterPredicate Predicate;
249 llvm::object::section_iterator Iterator;
250 llvm::object::section_iterator End;
251};
252
253class SectionFilter {
254public:
255 SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000256 : Predicate(std::move(P)), Object(O) {}
Colin LeMahieu77804be2015-07-29 15:45:39 +0000257 SectionFilterIterator begin() {
258 return SectionFilterIterator(Predicate, Object.section_begin(),
259 Object.section_end());
260 }
261 SectionFilterIterator end() {
262 return SectionFilterIterator(Predicate, Object.section_end(),
263 Object.section_end());
264 }
265
266private:
267 FilterPredicate Predicate;
268 llvm::object::ObjectFile const &Object;
269};
270SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) {
David Majnemer42531262016-08-12 03:55:06 +0000271 return SectionFilter(
272 [](llvm::object::SectionRef const &S) {
273 if (FilterSections.empty())
274 return true;
275 llvm::StringRef String;
276 std::error_code error = S.getName(String);
277 if (error)
278 return false;
279 return is_contained(FilterSections, String);
280 },
281 O);
Colin LeMahieu77804be2015-07-29 15:45:39 +0000282}
283}
284
Davide Italianoccd53fe2015-08-05 07:18:31 +0000285void llvm::error(std::error_code EC) {
Mark Seaborneb03ac52014-01-25 00:32:01 +0000286 if (!EC)
Davide Italianoccd53fe2015-08-05 07:18:31 +0000287 return;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000288
Davide Italiano140af642015-12-25 18:16:45 +0000289 errs() << ToolName << ": error reading file: " << EC.message() << ".\n";
290 errs().flush();
Davide Italiano7f6c3012015-08-06 00:18:52 +0000291 exit(1);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000292}
293
Kevin Enderby42398052016-06-28 23:16:13 +0000294LLVM_ATTRIBUTE_NORETURN void llvm::error(Twine Message) {
295 errs() << ToolName << ": " << Message << ".\n";
296 errs().flush();
297 exit(1);
298}
299
Davide Italianoed9d95b2015-12-29 13:41:02 +0000300LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000301 Twine Message) {
302 errs() << ToolName << ": '" << File << "': " << Message << ".\n";
303 exit(1);
304}
305
306LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
Davide Italianoed9d95b2015-12-29 13:41:02 +0000307 std::error_code EC) {
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000308 assert(EC);
309 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
Davide Italianoccd53fe2015-08-05 07:18:31 +0000310 exit(1);
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000311}
312
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000313LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
314 llvm::Error E) {
315 assert(E);
316 std::string Buf;
317 raw_string_ostream OS(Buf);
318 logAllUnhandledErrors(std::move(E), OS, "");
319 OS.flush();
Kevin Enderbyb34e3a12016-05-05 17:43:35 +0000320 errs() << ToolName << ": '" << File << "': " << Buf;
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000321 exit(1);
322}
323
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000324LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
325 StringRef FileName,
Kevin Enderby9acb1092016-05-31 20:35:34 +0000326 llvm::Error E,
327 StringRef ArchitectureName) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000328 assert(E);
329 errs() << ToolName << ": ";
330 if (ArchiveName != "")
331 errs() << ArchiveName << "(" << FileName << ")";
332 else
Justin Bogner31d8b7d2016-10-26 22:37:52 +0000333 errs() << "'" << FileName << "'";
Kevin Enderby9acb1092016-05-31 20:35:34 +0000334 if (!ArchitectureName.empty())
335 errs() << " (for architecture " << ArchitectureName << ")";
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000336 std::string Buf;
337 raw_string_ostream OS(Buf);
338 logAllUnhandledErrors(std::move(E), OS, "");
339 OS.flush();
Justin Bogner31d8b7d2016-10-26 22:37:52 +0000340 errs() << ": " << Buf;
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000341 exit(1);
342}
343
344LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
345 const object::Archive::Child &C,
Kevin Enderby9acb1092016-05-31 20:35:34 +0000346 llvm::Error E,
347 StringRef ArchitectureName) {
Kevin Enderbyf4586032016-07-29 17:44:13 +0000348 Expected<StringRef> NameOrErr = C.getName();
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000349 // TODO: if we have a error getting the name then it would be nice to print
350 // the index of which archive member this is and or its offset in the
351 // archive instead of "???" as the name.
Kevin Enderbyf4586032016-07-29 17:44:13 +0000352 if (!NameOrErr) {
353 consumeError(NameOrErr.takeError());
Kevin Enderby9acb1092016-05-31 20:35:34 +0000354 llvm::report_error(ArchiveName, "???", std::move(E), ArchitectureName);
Kevin Enderbyf4586032016-07-29 17:44:13 +0000355 } else
Kevin Enderby9acb1092016-05-31 20:35:34 +0000356 llvm::report_error(ArchiveName, NameOrErr.get(), std::move(E),
357 ArchitectureName);
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000358}
359
Craig Toppere6cb63e2014-04-25 04:24:47 +0000360static const Target *getTarget(const ObjectFile *Obj = nullptr) {
Michael J. Spencer2670c252011-01-20 06:39:06 +0000361 // Figure out the target triple.
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000362 llvm::Triple TheTriple("unknown-unknown-unknown");
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000363 if (TripleName.empty()) {
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000364 if (Obj) {
Sam Parkerdf7c6ef2017-01-18 13:52:12 +0000365 auto Arch = Obj->getArch();
366 TheTriple.setArch(Triple::ArchType(Arch));
367
368 // For ARM targets, try to use the build attributes to build determine
369 // the build target. Target features are also added, but later during
370 // disassembly.
371 if (Arch == Triple::arm || Arch == Triple::armeb) {
372 Obj->setARMSubArch(TheTriple);
373 }
374
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000375 // TheTriple defaults to ELF, and COFF doesn't have an environment:
376 // the best we can do here is indicate that it is mach-o.
377 if (Obj->isMachO())
Saleem Abdulrasool35476332014-03-06 20:47:11 +0000378 TheTriple.setObjectFormat(Triple::MachO);
Saleem Abdulrasool98938f12014-04-17 06:17:23 +0000379
380 if (Obj->isCOFF()) {
381 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
382 if (COFFObj->getArch() == Triple::thumb)
383 TheTriple.setTriple("thumbv7-windows");
384 }
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000385 }
Sam Parkerdf7c6ef2017-01-18 13:52:12 +0000386 } else {
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000387 TheTriple.setTriple(Triple::normalize(TripleName));
Sam Parkerdf7c6ef2017-01-18 13:52:12 +0000388 // Use the triple, but also try to combine with ARM build attributes.
389 if (Obj) {
390 auto Arch = Obj->getArch();
391 if (Arch == Triple::arm || Arch == Triple::armeb) {
392 Obj->setARMSubArch(TheTriple);
393 }
394 }
395 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000396
397 // Get the target specific parser.
398 std::string Error;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000399 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
400 Error);
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000401 if (!TheTarget) {
402 if (Obj)
403 report_error(Obj->getFileName(), "can't find target: " + Error);
404 else
405 error("can't find target: " + Error);
406 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000407
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000408 // Update the triple name and return the found target.
409 TripleName = TheTriple.getTriple();
410 return TheTarget;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000411}
412
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000413bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
Rafael Espindola704cd842015-07-06 15:47:43 +0000414 return a.getOffset() < b.getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +0000415}
416
Colin LeMahieufb76b002015-05-28 19:07:14 +0000417namespace {
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000418class SourcePrinter {
419protected:
420 DILineInfo OldLineInfo;
421 const ObjectFile *Obj;
422 std::unique_ptr<symbolize::LLVMSymbolizer> Symbolizer;
423 // File name to file contents of source
424 std::unordered_map<std::string, std::unique_ptr<MemoryBuffer>> SourceCache;
425 // Mark the line endings of the cached source
426 std::unordered_map<std::string, std::vector<StringRef>> LineCache;
427
428private:
429 bool cacheSource(std::string File);
430
431public:
432 virtual ~SourcePrinter() {}
433 SourcePrinter() : Obj(nullptr), Symbolizer(nullptr) {}
434 SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch) : Obj(Obj) {
435 symbolize::LLVMSymbolizer::Options SymbolizerOpts(
436 DILineInfoSpecifier::FunctionNameKind::None, true, false, false,
437 DefaultArch);
438 Symbolizer.reset(new symbolize::LLVMSymbolizer(SymbolizerOpts));
439 }
440 virtual void printSourceLine(raw_ostream &OS, uint64_t Address,
441 StringRef Delimiter = "; ");
442};
443
444bool SourcePrinter::cacheSource(std::string File) {
445 auto BufferOrError = MemoryBuffer::getFile(File);
446 if (!BufferOrError)
447 return false;
448 // Chomp the file to get lines
449 size_t BufferSize = (*BufferOrError)->getBufferSize();
450 const char *BufferStart = (*BufferOrError)->getBufferStart();
451 for (const char *Start = BufferStart, *End = BufferStart;
452 End < BufferStart + BufferSize; End++)
453 if (*End == '\n' || End == BufferStart + BufferSize - 1 ||
454 (*End == '\r' && *(End + 1) == '\n')) {
455 LineCache[File].push_back(StringRef(Start, End - Start));
456 if (*End == '\r')
457 End++;
458 Start = End + 1;
459 }
460 SourceCache[File] = std::move(*BufferOrError);
461 return true;
462}
463
464void SourcePrinter::printSourceLine(raw_ostream &OS, uint64_t Address,
465 StringRef Delimiter) {
466 if (!Symbolizer)
467 return;
468 DILineInfo LineInfo = DILineInfo();
469 auto ExpectecLineInfo =
470 Symbolizer->symbolizeCode(Obj->getFileName(), Address);
471 if (!ExpectecLineInfo)
472 consumeError(ExpectecLineInfo.takeError());
473 else
474 LineInfo = *ExpectecLineInfo;
475
476 if ((LineInfo.FileName == "<invalid>") || OldLineInfo.Line == LineInfo.Line ||
477 LineInfo.Line == 0)
478 return;
479
480 if (PrintLines)
481 OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line << "\n";
482 if (PrintSource) {
483 if (SourceCache.find(LineInfo.FileName) == SourceCache.end())
484 if (!cacheSource(LineInfo.FileName))
485 return;
486 auto FileBuffer = SourceCache.find(LineInfo.FileName);
487 if (FileBuffer != SourceCache.end()) {
488 auto LineBuffer = LineCache.find(LineInfo.FileName);
Petr Hosek86611a02017-04-25 18:56:33 +0000489 if (LineBuffer != LineCache.end()) {
490 if (LineInfo.Line > LineBuffer->second.size())
491 return;
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000492 // Vector begins at 0, line numbers are non-zero
493 OS << Delimiter << LineBuffer->second[LineInfo.Line - 1].ltrim()
494 << "\n";
Petr Hosek86611a02017-04-25 18:56:33 +0000495 }
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000496 }
497 }
498 OldLineInfo = LineInfo;
499}
500
Hemant Kulkarni5b60f632016-08-25 19:41:08 +0000501static bool isArmElf(const ObjectFile *Obj) {
502 return (Obj->isELF() &&
503 (Obj->getArch() == Triple::aarch64 ||
504 Obj->getArch() == Triple::aarch64_be ||
505 Obj->getArch() == Triple::arm || Obj->getArch() == Triple::armeb ||
506 Obj->getArch() == Triple::thumb ||
507 Obj->getArch() == Triple::thumbeb));
508}
509
Colin LeMahieufb76b002015-05-28 19:07:14 +0000510class PrettyPrinter {
511public:
Colin LeMahieu0b5890d2015-05-28 20:59:08 +0000512 virtual ~PrettyPrinter(){}
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000513 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
Colin LeMahieufb76b002015-05-28 19:07:14 +0000514 ArrayRef<uint8_t> Bytes, uint64_t Address,
515 raw_ostream &OS, StringRef Annot,
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000516 MCSubtargetInfo const &STI, SourcePrinter *SP) {
517 if (SP && (PrintSource || PrintLines))
518 SP->printSourceLine(OS, Address);
Saleem Abdulrasooldea14b22017-02-08 18:11:31 +0000519 if (!NoLeadingAddr)
520 OS << format("%8" PRIx64 ":", Address);
Colin LeMahieufb76b002015-05-28 19:07:14 +0000521 if (!NoShowRawInsn) {
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000522 OS << "\t";
523 dumpBytes(Bytes, OS);
Colin LeMahieufb76b002015-05-28 19:07:14 +0000524 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000525 if (MI)
526 IP.printInst(MI, OS, "", STI);
527 else
528 OS << " <unknown>";
Colin LeMahieufb76b002015-05-28 19:07:14 +0000529 }
530};
531PrettyPrinter PrettyPrinterInst;
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000532class HexagonPrettyPrinter : public PrettyPrinter {
533public:
534 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
535 raw_ostream &OS) {
536 uint32_t opcode =
537 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
Saleem Abdulrasooldea14b22017-02-08 18:11:31 +0000538 if (!NoLeadingAddr)
539 OS << format("%8" PRIx64 ":", Address);
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000540 if (!NoShowRawInsn) {
541 OS << "\t";
542 dumpBytes(Bytes.slice(0, 4), OS);
543 OS << format("%08" PRIx32, opcode);
544 }
545 }
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000546 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
547 uint64_t Address, raw_ostream &OS, StringRef Annot,
548 MCSubtargetInfo const &STI, SourcePrinter *SP) override {
Hemant Kulkarnie77a0a92016-08-18 21:50:13 +0000549 if (SP && (PrintSource || PrintLines))
550 SP->printSourceLine(OS, Address, "");
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000551 if (!MI) {
552 printLead(Bytes, Address, OS);
553 OS << " <unknown>";
554 return;
555 }
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000556 std::string Buffer;
557 {
558 raw_string_ostream TempStream(Buffer);
559 IP.printInst(MI, TempStream, "", STI);
560 }
561 StringRef Contents(Buffer);
562 // Split off bundle attributes
563 auto PacketBundle = Contents.rsplit('\n');
564 // Split off first instruction from the rest
565 auto HeadTail = PacketBundle.first.split('\n');
566 auto Preamble = " { ";
567 auto Separator = "";
568 while(!HeadTail.first.empty()) {
569 OS << Separator;
570 Separator = "\n";
Hemant Kulkarnie77a0a92016-08-18 21:50:13 +0000571 if (SP && (PrintSource || PrintLines))
572 SP->printSourceLine(OS, Address, "");
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000573 printLead(Bytes, Address, OS);
574 OS << Preamble;
575 Preamble = " ";
576 StringRef Inst;
577 auto Duplex = HeadTail.first.split('\v');
578 if(!Duplex.second.empty()){
579 OS << Duplex.first;
580 OS << "; ";
581 Inst = Duplex.second;
582 }
583 else
584 Inst = HeadTail.first;
585 OS << Inst;
586 Bytes = Bytes.slice(4);
587 Address += 4;
588 HeadTail = HeadTail.second.split('\n');
589 }
590 OS << " } " << PacketBundle.second;
591 }
592};
593HexagonPrettyPrinter HexagonPrettyPrinterInst;
Valery Pykhtinde048052016-04-07 07:24:01 +0000594
595class AMDGCNPrettyPrinter : public PrettyPrinter {
596public:
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000597 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
598 uint64_t Address, raw_ostream &OS, StringRef Annot,
599 MCSubtargetInfo const &STI, SourcePrinter *SP) override {
Konstantin Zhuravlyovf895b202017-03-07 20:17:11 +0000600 if (SP && (PrintSource || PrintLines))
601 SP->printSourceLine(OS, Address);
602
Matt Arsenault87d80db2016-04-22 21:23:41 +0000603 if (!MI) {
604 OS << " <unknown>";
605 return;
606 }
607
Valery Pykhtinde048052016-04-07 07:24:01 +0000608 SmallString<40> InstStr;
609 raw_svector_ostream IS(InstStr);
610
611 IP.printInst(MI, IS, "", STI);
612
Valery Pykhtin8e79f5b2016-04-07 08:38:20 +0000613 OS << left_justify(IS.str(), 60) << format("// %012" PRIX64 ": ", Address);
Valery Pykhtinde048052016-04-07 07:24:01 +0000614 typedef support::ulittle32_t U32;
615 for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
616 Bytes.size() / sizeof(U32)))
617 // D should be explicitly casted to uint32_t here as it is passed
618 // by format to snprintf as vararg.
Valery Pykhtin8e79f5b2016-04-07 08:38:20 +0000619 OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D));
Valery Pykhtinde048052016-04-07 07:24:01 +0000620
621 if (!Annot.empty())
622 OS << "// " << Annot;
623 }
624};
625AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
626
Alexei Starovoitov3b9efca2016-12-13 19:07:08 +0000627class BPFPrettyPrinter : public PrettyPrinter {
628public:
629 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
630 uint64_t Address, raw_ostream &OS, StringRef Annot,
631 MCSubtargetInfo const &STI, SourcePrinter *SP) override {
632 if (SP && (PrintSource || PrintLines))
633 SP->printSourceLine(OS, Address);
Saleem Abdulrasooldea14b22017-02-08 18:11:31 +0000634 if (!NoLeadingAddr)
635 OS << format("%8" PRId64 ":", Address / 8);
Alexei Starovoitov3b9efca2016-12-13 19:07:08 +0000636 if (!NoShowRawInsn) {
637 OS << "\t";
638 dumpBytes(Bytes, OS);
639 }
640 if (MI)
641 IP.printInst(MI, OS, "", STI);
642 else
643 OS << " <unknown>";
644 }
645};
646BPFPrettyPrinter BPFPrettyPrinterInst;
647
Colin LeMahieu35436a22015-05-29 14:48:25 +0000648PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000649 switch(Triple.getArch()) {
650 default:
651 return PrettyPrinterInst;
652 case Triple::hexagon:
653 return HexagonPrettyPrinterInst;
Valery Pykhtinde048052016-04-07 07:24:01 +0000654 case Triple::amdgcn:
655 return AMDGCNPrettyPrinterInst;
Alexei Starovoitov3b9efca2016-12-13 19:07:08 +0000656 case Triple::bpfel:
657 case Triple::bpfeb:
658 return BPFPrettyPrinterInst;
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000659 }
Colin LeMahieufb76b002015-05-28 19:07:14 +0000660}
661}
662
Rafael Espindola37070a52015-06-03 04:48:06 +0000663template <class ELFT>
Rafael Espindola37070a52015-06-03 04:48:06 +0000664static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000665 const RelocationRef &RelRef,
Rafael Espindola37070a52015-06-03 04:48:06 +0000666 SmallVectorImpl<char> &Result) {
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000667 DataRefImpl Rel = RelRef.getRawDataRefImpl();
668
Rafael Espindola37070a52015-06-03 04:48:06 +0000669 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
670 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000671 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
672
Rafael Espindola37070a52015-06-03 04:48:06 +0000673 const ELFFile<ELFT> &EF = *Obj->getELFFile();
674
Davide Italiano6cf09262016-11-16 05:10:28 +0000675 auto SecOrErr = EF.getSection(Rel.d.a);
676 if (!SecOrErr)
677 return errorToErrorCode(SecOrErr.takeError());
Rafael Espindola6def3042015-07-01 12:56:27 +0000678 const Elf_Shdr *Sec = *SecOrErr;
Davide Italiano6cf09262016-11-16 05:10:28 +0000679 auto SymTabOrErr = EF.getSection(Sec->sh_link);
680 if (!SymTabOrErr)
681 return errorToErrorCode(SymTabOrErr.takeError());
Rafael Espindola6def3042015-07-01 12:56:27 +0000682 const Elf_Shdr *SymTab = *SymTabOrErr;
Rafael Espindola719dc7c2015-06-29 12:38:31 +0000683 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
684 SymTab->sh_type == ELF::SHT_DYNSYM);
Davide Italiano6cf09262016-11-16 05:10:28 +0000685 auto StrTabSec = EF.getSection(SymTab->sh_link);
686 if (!StrTabSec)
687 return errorToErrorCode(StrTabSec.takeError());
688 auto StrTabOrErr = EF.getStringTable(*StrTabSec);
689 if (!StrTabOrErr)
690 return errorToErrorCode(StrTabOrErr.takeError());
Rafael Espindola6a1bfb22015-06-29 14:39:25 +0000691 StringRef StrTab = *StrTabOrErr;
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000692 uint8_t type = RelRef.getType();
Rafael Espindola37070a52015-06-03 04:48:06 +0000693 StringRef res;
694 int64_t addend = 0;
Rafael Espindola6def3042015-07-01 12:56:27 +0000695 switch (Sec->sh_type) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000696 default:
697 return object_error::parse_failed;
698 case ELF::SHT_REL: {
Rafael Espindola37070a52015-06-03 04:48:06 +0000699 // TODO: Read implicit addend from section data.
700 break;
701 }
702 case ELF::SHT_RELA: {
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000703 const Elf_Rela *ERela = Obj->getRela(Rel);
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000704 addend = ERela->r_addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000705 break;
706 }
707 }
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000708 symbol_iterator SI = RelRef.getSymbol();
709 const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
Rafael Espindola75d5b542015-06-03 05:14:22 +0000710 StringRef Target;
Rafael Espindola75d5b542015-06-03 05:14:22 +0000711 if (symb->getType() == ELF::STT_SECTION) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000712 Expected<section_iterator> SymSI = SI->getSection();
713 if (!SymSI)
714 return errorToErrorCode(SymSI.takeError());
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000715 const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
Davide Italiano6cf09262016-11-16 05:10:28 +0000716 auto SecName = EF.getSectionName(SymSec);
717 if (!SecName)
718 return errorToErrorCode(SecName.takeError());
Rafael Espindola75d5b542015-06-03 05:14:22 +0000719 Target = *SecName;
720 } else {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000721 Expected<StringRef> SymName = symb->getName(StrTab);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000722 if (!SymName)
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000723 return errorToErrorCode(SymName.takeError());
Rafael Espindola75d5b542015-06-03 05:14:22 +0000724 Target = *SymName;
725 }
Rafael Espindola37070a52015-06-03 04:48:06 +0000726 switch (EF.getHeader()->e_machine) {
727 case ELF::EM_X86_64:
728 switch (type) {
729 case ELF::R_X86_64_PC8:
730 case ELF::R_X86_64_PC16:
731 case ELF::R_X86_64_PC32: {
732 std::string fmtbuf;
733 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000734 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
Rafael Espindola37070a52015-06-03 04:48:06 +0000735 fmt.flush();
736 Result.append(fmtbuf.begin(), fmtbuf.end());
737 } break;
738 case ELF::R_X86_64_8:
739 case ELF::R_X86_64_16:
740 case ELF::R_X86_64_32:
741 case ELF::R_X86_64_32S:
742 case ELF::R_X86_64_64: {
743 std::string fmtbuf;
744 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000745 fmt << Target << (addend < 0 ? "" : "+") << addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000746 fmt.flush();
747 Result.append(fmtbuf.begin(), fmtbuf.end());
748 } break;
749 default:
750 res = "Unknown";
751 }
752 break;
Jacques Pienaarea9f25a2016-03-01 21:21:42 +0000753 case ELF::EM_LANAI:
Dylan McKay11661122016-09-28 13:15:17 +0000754 case ELF::EM_AVR:
Rafael Espindola37070a52015-06-03 04:48:06 +0000755 case ELF::EM_AARCH64: {
756 std::string fmtbuf;
757 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000758 fmt << Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000759 if (addend != 0)
760 fmt << (addend < 0 ? "" : "+") << addend;
761 fmt.flush();
762 Result.append(fmtbuf.begin(), fmtbuf.end());
763 break;
764 }
765 case ELF::EM_386:
Michael Kupersteina3b79dd2015-11-04 11:21:50 +0000766 case ELF::EM_IAMCU:
Rafael Espindola37070a52015-06-03 04:48:06 +0000767 case ELF::EM_ARM:
768 case ELF::EM_HEXAGON:
769 case ELF::EM_MIPS:
Alexei Starovoitovcfb51f52016-07-15 22:27:55 +0000770 case ELF::EM_BPF:
Alex Bradbury1524f622016-11-01 16:59:37 +0000771 case ELF::EM_RISCV:
Rafael Espindola75d5b542015-06-03 05:14:22 +0000772 res = Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000773 break;
Dan Gohman46350172016-01-12 20:56:01 +0000774 case ELF::EM_WEBASSEMBLY:
775 switch (type) {
776 case ELF::R_WEBASSEMBLY_DATA: {
777 std::string fmtbuf;
778 raw_string_ostream fmt(fmtbuf);
779 fmt << Target << (addend < 0 ? "" : "+") << addend;
780 fmt.flush();
781 Result.append(fmtbuf.begin(), fmtbuf.end());
782 break;
783 }
784 case ELF::R_WEBASSEMBLY_FUNCTION:
785 res = Target;
786 break;
787 default:
788 res = "Unknown";
789 }
790 break;
Rafael Espindola37070a52015-06-03 04:48:06 +0000791 default:
792 res = "Unknown";
793 }
794 if (Result.empty())
795 Result.append(res.begin(), res.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000796 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000797}
798
799static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000800 const RelocationRef &Rel,
Rafael Espindola37070a52015-06-03 04:48:06 +0000801 SmallVectorImpl<char> &Result) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000802 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
803 return getRelocationValueString(ELF32LE, Rel, Result);
804 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
805 return getRelocationValueString(ELF64LE, Rel, Result);
806 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
807 return getRelocationValueString(ELF32BE, Rel, Result);
808 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
809 return getRelocationValueString(ELF64BE, Rel, Result);
810}
811
812static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
813 const RelocationRef &Rel,
814 SmallVectorImpl<char> &Result) {
815 symbol_iterator SymI = Rel.getSymbol();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000816 Expected<StringRef> SymNameOrErr = SymI->getName();
817 if (!SymNameOrErr)
818 return errorToErrorCode(SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000819 StringRef SymName = *SymNameOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000820 Result.append(SymName.begin(), SymName.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000821 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000822}
823
824static void printRelocationTargetName(const MachOObjectFile *O,
825 const MachO::any_relocation_info &RE,
826 raw_string_ostream &fmt) {
827 bool IsScattered = O->isRelocationScattered(RE);
828
829 // Target of a scattered relocation is an address. In the interest of
830 // generating pretty output, scan through the symbol table looking for a
831 // symbol that aligns with that address. If we find one, print it.
832 // Otherwise, we just print the hex address of the target.
833 if (IsScattered) {
834 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
835
836 for (const SymbolRef &Symbol : O->symbols()) {
837 std::error_code ec;
Kevin Enderby931cb652016-06-24 18:24:42 +0000838 Expected<uint64_t> Addr = Symbol.getAddress();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000839 if (!Addr)
840 report_error(O->getFileName(), Addr.takeError());
Rafael Espindolaed067c42015-07-03 18:19:00 +0000841 if (*Addr != Val)
Rafael Espindola37070a52015-06-03 04:48:06 +0000842 continue;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000843 Expected<StringRef> Name = Symbol.getName();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000844 if (!Name)
845 report_error(O->getFileName(), Name.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000846 fmt << *Name;
Rafael Espindola37070a52015-06-03 04:48:06 +0000847 return;
848 }
849
850 // If we couldn't find a symbol that this relocation refers to, try
851 // to find a section beginning instead.
Colin LeMahieu77804be2015-07-29 15:45:39 +0000852 for (const SectionRef &Section : ToolSectionFilter(*O)) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000853 std::error_code ec;
854
855 StringRef Name;
856 uint64_t Addr = Section.getAddress();
857 if (Addr != Val)
858 continue;
859 if ((ec = Section.getName(Name)))
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000860 report_error(O->getFileName(), ec);
Rafael Espindola37070a52015-06-03 04:48:06 +0000861 fmt << Name;
862 return;
863 }
864
865 fmt << format("0x%x", Val);
866 return;
867 }
868
869 StringRef S;
870 bool isExtern = O->getPlainRelocationExternal(RE);
871 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
872
Martin Storsjo8c0317d2017-07-13 17:03:02 +0000873 if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND) {
874 fmt << format("0x%x", Val);
875 return;
876 } else if (isExtern) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000877 symbol_iterator SI = O->symbol_begin();
878 advance(SI, Val);
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000879 Expected<StringRef> SOrErr = SI->getName();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000880 if (!SOrErr)
881 report_error(O->getFileName(), SOrErr.takeError());
Davide Italianoccd53fe2015-08-05 07:18:31 +0000882 S = *SOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000883 } else {
884 section_iterator SI = O->section_begin();
885 // Adjust for the fact that sections are 1-indexed.
886 advance(SI, Val - 1);
887 SI->getName(S);
888 }
889
890 fmt << S;
891}
892
Sam Clegg4df5d762017-06-27 20:40:53 +0000893static std::error_code getRelocationValueString(const WasmObjectFile *Obj,
894 const RelocationRef &RelRef,
895 SmallVectorImpl<char> &Result) {
896 const wasm::WasmRelocation& Rel = Obj->getWasmRelocation(RelRef);
897 std::string fmtbuf;
898 raw_string_ostream fmt(fmtbuf);
899 fmt << Rel.Index << (Rel.Addend < 0 ? "" : "+") << Rel.Addend;
900 fmt.flush();
901 Result.append(fmtbuf.begin(), fmtbuf.end());
902 return std::error_code();
903}
904
Rafael Espindola37070a52015-06-03 04:48:06 +0000905static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
906 const RelocationRef &RelRef,
907 SmallVectorImpl<char> &Result) {
908 DataRefImpl Rel = RelRef.getRawDataRefImpl();
909 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
910
911 unsigned Arch = Obj->getArch();
912
913 std::string fmtbuf;
914 raw_string_ostream fmt(fmtbuf);
915 unsigned Type = Obj->getAnyRelocationType(RE);
916 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
917
918 // Determine any addends that should be displayed with the relocation.
919 // These require decoding the relocation type, which is triple-specific.
920
921 // X86_64 has entirely custom relocation types.
922 if (Arch == Triple::x86_64) {
923 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
924
925 switch (Type) {
926 case MachO::X86_64_RELOC_GOT_LOAD:
927 case MachO::X86_64_RELOC_GOT: {
928 printRelocationTargetName(Obj, RE, fmt);
929 fmt << "@GOT";
930 if (isPCRel)
931 fmt << "PCREL";
932 break;
933 }
934 case MachO::X86_64_RELOC_SUBTRACTOR: {
935 DataRefImpl RelNext = Rel;
936 Obj->moveRelocationNext(RelNext);
937 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
938
939 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
940 // X86_64_RELOC_UNSIGNED.
941 // NOTE: Scattered relocations don't exist on x86_64.
942 unsigned RType = Obj->getAnyRelocationType(RENext);
943 if (RType != MachO::X86_64_RELOC_UNSIGNED)
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000944 report_error(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
945 "X86_64_RELOC_SUBTRACTOR.");
Rafael Espindola37070a52015-06-03 04:48:06 +0000946
947 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
948 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
949 printRelocationTargetName(Obj, RENext, fmt);
950 fmt << "-";
951 printRelocationTargetName(Obj, RE, fmt);
952 break;
953 }
954 case MachO::X86_64_RELOC_TLV:
955 printRelocationTargetName(Obj, RE, fmt);
956 fmt << "@TLV";
957 if (isPCRel)
958 fmt << "P";
959 break;
960 case MachO::X86_64_RELOC_SIGNED_1:
961 printRelocationTargetName(Obj, RE, fmt);
962 fmt << "-1";
963 break;
964 case MachO::X86_64_RELOC_SIGNED_2:
965 printRelocationTargetName(Obj, RE, fmt);
966 fmt << "-2";
967 break;
968 case MachO::X86_64_RELOC_SIGNED_4:
969 printRelocationTargetName(Obj, RE, fmt);
970 fmt << "-4";
971 break;
972 default:
973 printRelocationTargetName(Obj, RE, fmt);
974 break;
975 }
976 // X86 and ARM share some relocation types in common.
977 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
978 Arch == Triple::ppc) {
979 // Generic relocation types...
980 switch (Type) {
981 case MachO::GENERIC_RELOC_PAIR: // prints no info
Rui Ueyama7d099192015-06-09 15:20:42 +0000982 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000983 case MachO::GENERIC_RELOC_SECTDIFF: {
984 DataRefImpl RelNext = Rel;
985 Obj->moveRelocationNext(RelNext);
986 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
987
988 // X86 sect diff's must be followed by a relocation of type
989 // GENERIC_RELOC_PAIR.
990 unsigned RType = Obj->getAnyRelocationType(RENext);
991
992 if (RType != MachO::GENERIC_RELOC_PAIR)
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000993 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
994 "GENERIC_RELOC_SECTDIFF.");
Rafael Espindola37070a52015-06-03 04:48:06 +0000995
996 printRelocationTargetName(Obj, RE, fmt);
997 fmt << "-";
998 printRelocationTargetName(Obj, RENext, fmt);
999 break;
1000 }
1001 }
1002
1003 if (Arch == Triple::x86 || Arch == Triple::ppc) {
1004 switch (Type) {
1005 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
1006 DataRefImpl RelNext = Rel;
1007 Obj->moveRelocationNext(RelNext);
1008 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
1009
1010 // X86 sect diff's must be followed by a relocation of type
1011 // GENERIC_RELOC_PAIR.
1012 unsigned RType = Obj->getAnyRelocationType(RENext);
1013 if (RType != MachO::GENERIC_RELOC_PAIR)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001014 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
1015 "GENERIC_RELOC_LOCAL_SECTDIFF.");
Rafael Espindola37070a52015-06-03 04:48:06 +00001016
1017 printRelocationTargetName(Obj, RE, fmt);
1018 fmt << "-";
1019 printRelocationTargetName(Obj, RENext, fmt);
1020 break;
1021 }
1022 case MachO::GENERIC_RELOC_TLV: {
1023 printRelocationTargetName(Obj, RE, fmt);
1024 fmt << "@TLV";
1025 if (IsPCRel)
1026 fmt << "P";
1027 break;
1028 }
1029 default:
1030 printRelocationTargetName(Obj, RE, fmt);
1031 }
1032 } else { // ARM-specific relocations
1033 switch (Type) {
1034 case MachO::ARM_RELOC_HALF:
1035 case MachO::ARM_RELOC_HALF_SECTDIFF: {
1036 // Half relocations steal a bit from the length field to encode
1037 // whether this is an upper16 or a lower16 relocation.
Martin Storsjofa5183b2017-07-13 05:54:08 +00001038 bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
Rafael Espindola37070a52015-06-03 04:48:06 +00001039
1040 if (isUpper)
1041 fmt << ":upper16:(";
1042 else
1043 fmt << ":lower16:(";
1044 printRelocationTargetName(Obj, RE, fmt);
1045
1046 DataRefImpl RelNext = Rel;
1047 Obj->moveRelocationNext(RelNext);
1048 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
1049
1050 // ARM half relocs must be followed by a relocation of type
1051 // ARM_RELOC_PAIR.
1052 unsigned RType = Obj->getAnyRelocationType(RENext);
1053 if (RType != MachO::ARM_RELOC_PAIR)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001054 report_error(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
1055 "ARM_RELOC_HALF");
Rafael Espindola37070a52015-06-03 04:48:06 +00001056
1057 // NOTE: The half of the target virtual address is stashed in the
1058 // address field of the secondary relocation, but we can't reverse
1059 // engineer the constant offset from it without decoding the movw/movt
1060 // instruction to find the other half in its immediate field.
1061
1062 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
1063 // symbol/section pointer of the follow-on relocation.
1064 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1065 fmt << "-";
1066 printRelocationTargetName(Obj, RENext, fmt);
1067 }
1068
1069 fmt << ")";
1070 break;
1071 }
1072 default: { printRelocationTargetName(Obj, RE, fmt); }
1073 }
1074 }
1075 } else
1076 printRelocationTargetName(Obj, RE, fmt);
1077
1078 fmt.flush();
1079 Result.append(fmtbuf.begin(), fmtbuf.end());
Rui Ueyama7d099192015-06-09 15:20:42 +00001080 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +00001081}
1082
1083static std::error_code getRelocationValueString(const RelocationRef &Rel,
1084 SmallVectorImpl<char> &Result) {
Rafael Espindola854038e2015-06-26 14:51:16 +00001085 const ObjectFile *Obj = Rel.getObject();
Rafael Espindola37070a52015-06-03 04:48:06 +00001086 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
1087 return getRelocationValueString(ELF, Rel, Result);
1088 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
1089 return getRelocationValueString(COFF, Rel, Result);
Sam Clegg4df5d762017-06-27 20:40:53 +00001090 if (auto *Wasm = dyn_cast<WasmObjectFile>(Obj))
1091 return getRelocationValueString(Wasm, Rel, Result);
1092 if (auto *MachO = dyn_cast<MachOObjectFile>(Obj))
1093 return getRelocationValueString(MachO, Rel, Result);
1094 llvm_unreachable("unknown object file format");
Rafael Espindola37070a52015-06-03 04:48:06 +00001095}
1096
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001097/// @brief Indicates whether this relocation should hidden when listing
1098/// relocations, usually because it is the trailing part of a multipart
1099/// relocation that will be printed as part of the leading relocation.
1100static bool getHidden(RelocationRef RelRef) {
1101 const ObjectFile *Obj = RelRef.getObject();
1102 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
1103 if (!MachO)
1104 return false;
1105
1106 unsigned Arch = MachO->getArch();
1107 DataRefImpl Rel = RelRef.getRawDataRefImpl();
1108 uint64_t Type = MachO->getRelocationType(Rel);
1109
1110 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
1111 // is always hidden.
1112 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
1113 if (Type == MachO::GENERIC_RELOC_PAIR)
1114 return true;
1115 } else if (Arch == Triple::x86_64) {
1116 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
1117 // an X86_64_RELOC_SUBTRACTOR.
1118 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
1119 DataRefImpl RelPrev = Rel;
1120 RelPrev.d.a--;
1121 uint64_t PrevType = MachO->getRelocationType(RelPrev);
1122 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
1123 return true;
1124 }
1125 }
1126
1127 return false;
1128}
1129
Sam Koltonc05d7782016-08-17 10:17:57 +00001130static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) {
1131 assert(Obj->isELF());
1132 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1133 return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1134 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1135 return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1136 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1137 return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1138 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1139 return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1140 llvm_unreachable("Unsupported binary format");
1141}
1142
Sam Parker5fba45a2017-02-08 09:44:18 +00001143template <class ELFT> static void
1144addDynamicElfSymbols(const ELFObjectFile<ELFT> *Obj,
1145 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1146 for (auto Symbol : Obj->getDynamicSymbolIterators()) {
1147 uint8_t SymbolType = Symbol.getELFType();
1148 if (SymbolType != ELF::STT_FUNC || Symbol.getSize() == 0)
1149 continue;
1150
1151 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
1152 if (!AddressOrErr)
1153 report_error(Obj->getFileName(), AddressOrErr.takeError());
1154 uint64_t Address = *AddressOrErr;
1155
1156 Expected<StringRef> Name = Symbol.getName();
1157 if (!Name)
1158 report_error(Obj->getFileName(), Name.takeError());
1159 if (Name->empty())
1160 continue;
1161
1162 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1163 if (!SectionOrErr)
1164 report_error(Obj->getFileName(), SectionOrErr.takeError());
1165 section_iterator SecI = *SectionOrErr;
1166 if (SecI == Obj->section_end())
1167 continue;
1168
1169 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1170 }
1171}
1172
1173static void
1174addDynamicElfSymbols(const ObjectFile *Obj,
1175 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1176 assert(Obj->isELF());
1177 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1178 addDynamicElfSymbols(Elf32LEObj, AllSymbols);
1179 else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1180 addDynamicElfSymbols(Elf64LEObj, AllSymbols);
1181 else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1182 addDynamicElfSymbols(Elf32BEObj, AllSymbols);
1183 else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1184 addDynamicElfSymbols(Elf64BEObj, AllSymbols);
1185 else
1186 llvm_unreachable("Unsupported binary format");
1187}
1188
Michael J. Spencer51862b32011-10-13 22:17:18 +00001189static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001190 if (StartAddress > StopAddress)
1191 error("Start address should be less than stop address");
1192
Jim Grosbachaf9aec02012-08-07 17:53:14 +00001193 const Target *TheTarget = getTarget(Obj);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001194
Jack Carter551efd72012-08-28 19:24:49 +00001195 // Package up features to be passed to target/subtarget
Daniel Sanders1d148642016-06-16 09:17:03 +00001196 SubtargetFeatures Features = Obj->getFeatures();
Jack Carter551efd72012-08-28 19:24:49 +00001197 if (MAttrs.size()) {
Jack Carter551efd72012-08-28 19:24:49 +00001198 for (unsigned i = 0; i != MAttrs.size(); ++i)
1199 Features.AddFeature(MAttrs[i]);
Jack Carter551efd72012-08-28 19:24:49 +00001200 }
1201
Ahmed Charles56440fd2014-03-06 05:51:42 +00001202 std::unique_ptr<const MCRegisterInfo> MRI(
1203 TheTarget->createMCRegInfo(TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +00001204 if (!MRI)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001205 report_error(Obj->getFileName(), "no register info for target " +
1206 TripleName);
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001207
1208 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00001209 std::unique_ptr<const MCAsmInfo> AsmInfo(
1210 TheTarget->createMCAsmInfo(*MRI, TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +00001211 if (!AsmInfo)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001212 report_error(Obj->getFileName(), "no assembly info for target " +
1213 TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +00001214 std::unique_ptr<const MCSubtargetInfo> STI(
Daniel Sanders1d148642016-06-16 09:17:03 +00001215 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
Davide Italiano711e4952015-12-17 01:59:50 +00001216 if (!STI)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001217 report_error(Obj->getFileName(), "no subtarget info for target " +
1218 TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +00001219 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
Davide Italiano711e4952015-12-17 01:59:50 +00001220 if (!MII)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001221 report_error(Obj->getFileName(), "no instruction info for target " +
1222 TripleName);
Sam Kolton3381d7a2016-10-06 13:46:08 +00001223 MCObjectFileInfo MOFI;
1224 MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI);
1225 // FIXME: for now initialize MCObjectFileInfo with default values
1226 MOFI.InitMCObjectFileInfo(Triple(TripleName), false, CodeModel::Default, Ctx);
Lang Hamesa1bc0f52014-04-15 04:40:56 +00001227
1228 std::unique_ptr<MCDisassembler> DisAsm(
1229 TheTarget->createMCDisassembler(*STI, Ctx));
Davide Italiano711e4952015-12-17 01:59:50 +00001230 if (!DisAsm)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001231 report_error(Obj->getFileName(), "no disassembler for target " +
1232 TripleName);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001233
Ahmed Charles56440fd2014-03-06 05:51:42 +00001234 std::unique_ptr<const MCInstrAnalysis> MIA(
1235 TheTarget->createMCInstrAnalysis(MII.get()));
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001236
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001237 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Daniel Sanders50f17232015-09-15 16:17:27 +00001238 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1239 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
Davide Italiano711e4952015-12-17 01:59:50 +00001240 if (!IP)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001241 report_error(Obj->getFileName(), "no instruction printer for target " +
1242 TripleName);
Colin LeMahieu14ec76e2015-06-07 21:07:17 +00001243 IP->setPrintImmHex(PrintImmHex);
Colin LeMahieu35436a22015-05-29 14:48:25 +00001244 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001245
Greg Fitzgerald18432272014-03-20 22:55:15 +00001246 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
1247 "\t\t\t%08" PRIx64 ": ";
1248
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001249 SourcePrinter SP(Obj, TheTarget->getName());
1250
Mark Seaborn0929d3d2014-01-25 17:38:19 +00001251 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
1252 // in RelocSecs contain the relocations for section S.
Rafael Espindola4453e42942014-06-13 03:07:50 +00001253 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +00001254 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001255 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001256 section_iterator Sec2 = Section.getRelocatedSection();
Rafael Espindolab5155a52014-02-10 20:24:04 +00001257 if (Sec2 != Obj->section_end())
Alexey Samsonov48803e52014-03-13 14:37:36 +00001258 SectionRelocMap[*Sec2].push_back(Section);
Mark Seaborn0929d3d2014-01-25 17:38:19 +00001259 }
1260
David Majnemer81afca62015-07-07 22:06:59 +00001261 // Create a mapping from virtual address to symbol name. This is used to
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001262 // pretty print the symbols while disassembling.
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001263 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
1264 for (const SymbolRef &Symbol : Obj->symbols()) {
Kevin Enderby931cb652016-06-24 18:24:42 +00001265 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001266 if (!AddressOrErr)
1267 report_error(Obj->getFileName(), AddressOrErr.takeError());
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001268 uint64_t Address = *AddressOrErr;
David Majnemer2603a8fa2015-07-09 18:11:40 +00001269
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001270 Expected<StringRef> Name = Symbol.getName();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001271 if (!Name)
1272 report_error(Obj->getFileName(), Name.takeError());
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001273 if (Name->empty())
1274 continue;
David Majnemer81afca62015-07-07 22:06:59 +00001275
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001276 Expected<section_iterator> SectionOrErr = Symbol.getSection();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001277 if (!SectionOrErr)
1278 report_error(Obj->getFileName(), SectionOrErr.takeError());
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001279 section_iterator SecI = *SectionOrErr;
1280 if (SecI == Obj->section_end())
1281 continue;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001282
Sam Koltonc05d7782016-08-17 10:17:57 +00001283 uint8_t SymbolType = ELF::STT_NOTYPE;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001284 if (Obj->isELF())
Sam Koltonc05d7782016-08-17 10:17:57 +00001285 SymbolType = getElfSymbolType(Obj, Symbol);
David Majnemer81afca62015-07-07 22:06:59 +00001286
Sam Koltonc05d7782016-08-17 10:17:57 +00001287 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1288
David Majnemer81afca62015-07-07 22:06:59 +00001289 }
Sam Parker5fba45a2017-02-08 09:44:18 +00001290 if (AllSymbols.empty() && Obj->isELF())
1291 addDynamicElfSymbols(Obj, AllSymbols);
David Majnemer81afca62015-07-07 22:06:59 +00001292
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001293 // Create a mapping from virtual address to section.
1294 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1295 for (SectionRef Sec : Obj->sections())
1296 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1297 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
1298
1299 // Linked executables (.exe and .dll files) typically don't include a real
1300 // symbol table but they might contain an export table.
1301 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
1302 for (const auto &ExportEntry : COFFObj->export_directories()) {
1303 StringRef Name;
1304 error(ExportEntry.getSymbolName(Name));
1305 if (Name.empty())
1306 continue;
1307 uint32_t RVA;
1308 error(ExportEntry.getExportRVA(RVA));
1309
1310 uint64_t VA = COFFObj->getImageBase() + RVA;
1311 auto Sec = std::upper_bound(
1312 SectionAddresses.begin(), SectionAddresses.end(), VA,
1313 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
1314 return LHS < RHS.first;
1315 });
1316 if (Sec != SectionAddresses.begin())
1317 --Sec;
1318 else
1319 Sec = SectionAddresses.end();
1320
1321 if (Sec != SectionAddresses.end())
Sam Koltonc05d7782016-08-17 10:17:57 +00001322 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001323 }
1324 }
1325
1326 // Sort all the symbols, this allows us to use a simple binary search to find
1327 // a symbol near an address.
1328 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1329 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
1330
Colin LeMahieu77804be2015-07-29 15:45:39 +00001331 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Colin LeMahieuf34933e2015-07-23 20:58:49 +00001332 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
Mark Seaborneb03ac52014-01-25 00:32:01 +00001333 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +00001334
Rafael Espindola80291272014-10-08 15:28:58 +00001335 uint64_t SectionAddr = Section.getAddress();
1336 uint64_t SectSize = Section.getSize();
David Majnemer185b5b12014-11-11 09:58:25 +00001337 if (!SectSize)
1338 continue;
Simon Atanasyan2b614e12014-02-24 22:12:11 +00001339
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001340 // Get the list of all the symbols in this section.
1341 SectionSymbolsTy &Symbols = AllSymbols[Section];
Davide Italianof0706882015-10-01 21:57:09 +00001342 std::vector<uint64_t> DataMappingSymsAddr;
1343 std::vector<uint64_t> TextMappingSymsAddr;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001344 if (isArmElf(Obj)) {
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001345 for (const auto &Symb : Symbols) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001346 uint64_t Address = std::get<0>(Symb);
1347 StringRef Name = std::get<1>(Symb);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001348 if (Name.startswith("$d"))
David Majnemer153722d2015-11-18 04:35:32 +00001349 DataMappingSymsAddr.push_back(Address - SectionAddr);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001350 if (Name.startswith("$x"))
David Majnemer153722d2015-11-18 04:35:32 +00001351 TextMappingSymsAddr.push_back(Address - SectionAddr);
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001352 if (Name.startswith("$a"))
1353 TextMappingSymsAddr.push_back(Address - SectionAddr);
1354 if (Name.startswith("$t"))
1355 TextMappingSymsAddr.push_back(Address - SectionAddr);
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001356 }
1357 }
1358
Davide Italianof0706882015-10-01 21:57:09 +00001359 std::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end());
1360 std::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end());
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001361
Sam Kolton3381d7a2016-10-06 13:46:08 +00001362 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1363 // AMDGPU disassembler uses symbolizer for printing labels
1364 std::unique_ptr<MCRelocationInfo> RelInfo(
1365 TheTarget->createMCRelocationInfo(TripleName, Ctx));
1366 if (RelInfo) {
1367 std::unique_ptr<MCSymbolizer> Symbolizer(
1368 TheTarget->createMCSymbolizer(
1369 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1370 DisAsm->setSymbolizer(std::move(Symbolizer));
1371 }
1372 }
1373
Michael J. Spencer51862b32011-10-13 22:17:18 +00001374 // Make a list of all the relocations for this section.
1375 std::vector<RelocationRef> Rels;
1376 if (InlineRelocs) {
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001377 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
1378 for (const RelocationRef &Reloc : RelocSec.relocations()) {
1379 Rels.push_back(Reloc);
1380 }
Michael J. Spencer51862b32011-10-13 22:17:18 +00001381 }
1382 }
1383
1384 // Sort relocations by address.
1385 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
1386
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001387 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +00001388 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001389 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +00001390 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001391 }
Michael J. Spencer1d6167f2011-06-25 17:55:23 +00001392 StringRef name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001393 error(Section.getName(name));
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001394
1395 if ((SectionAddr <= StopAddress) &&
1396 (SectionAddr + SectSize) >= StartAddress) {
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001397 outs() << "Disassembly of section ";
1398 if (!SegmentName.empty())
1399 outs() << SegmentName << ",";
1400 outs() << name << ':';
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001401 }
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001402
Rafael Espindola7884c952015-06-04 15:01:05 +00001403 // If the section has no symbol at the start, just insert a dummy one.
Sam Koltonc05d7782016-08-17 10:17:57 +00001404 if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) {
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001405 Symbols.insert(Symbols.begin(),
1406 std::make_tuple(SectionAddr, name, Section.isText()
1407 ? ELF::STT_FUNC
1408 : ELF::STT_OBJECT));
Sam Koltonc05d7782016-08-17 10:17:57 +00001409 }
Alp Tokere69170a2014-06-26 22:52:05 +00001410
1411 SmallString<40> Comments;
1412 raw_svector_ostream CommentStream(Comments);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001413
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001414 StringRef BytesStr;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001415 error(Section.getContents(BytesStr));
Aaron Ballman106fd7b2014-11-12 14:01:17 +00001416 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1417 BytesStr.size());
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001418
Michael J. Spencer2670c252011-01-20 06:39:06 +00001419 uint64_t Size;
1420 uint64_t Index;
1421
Michael J. Spencer51862b32011-10-13 22:17:18 +00001422 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
1423 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001424 // Disassemble symbol by symbol.
1425 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001426 uint64_t Start = std::get<0>(Symbols[si]) - SectionAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001427 // The end is either the section end or the beginning of the next
1428 // symbol.
1429 uint64_t End =
Sam Koltonc05d7782016-08-17 10:17:57 +00001430 (si == se - 1) ? SectSize : std::get<0>(Symbols[si + 1]) - SectionAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001431 // Don't try to disassemble beyond the end of section contents.
1432 if (End > SectSize)
1433 End = SectSize;
Rafael Espindolae45c7402014-08-17 16:31:39 +00001434 // If this symbol has the same address as the next symbol, then skip it.
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001435 if (Start >= End)
Michael J. Spenceree84f642011-10-13 20:37:08 +00001436 continue;
1437
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001438 // Check if we need to skip symbol
1439 // Skip if the symbol's data is not between StartAddress and StopAddress
1440 if (End + SectionAddr < StartAddress ||
1441 Start + SectionAddr > StopAddress) {
1442 continue;
1443 }
1444
1445 // Stop disassembly at the stop address specified
1446 if (End + SectionAddr > StopAddress)
1447 End = StopAddress - SectionAddr;
1448
Valery Pykhtinde048052016-04-07 07:24:01 +00001449 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1450 // make size 4 bytes folded
1451 End = Start + ((End - Start) & ~0x3ull);
Sam Koltonc05d7782016-08-17 10:17:57 +00001452 if (std::get<2>(Symbols[si]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1453 // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)
1454 Start += 256;
1455 }
1456 if (si == se - 1 ||
1457 std::get<2>(Symbols[si + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1458 // cut trailing zeroes at the end of kernel
1459 // cut up to 256 bytes
1460 const uint64_t EndAlign = 256;
1461 const auto Limit = End - (std::min)(EndAlign, End - Start);
1462 while (End > Limit &&
1463 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1464 End -= 4;
1465 }
Valery Pykhtinde048052016-04-07 07:24:01 +00001466 }
1467
Sam Koltonc05d7782016-08-17 10:17:57 +00001468 outs() << '\n' << std::get<1>(Symbols[si]) << ":\n";
Michael J. Spencer2670c252011-01-20 06:39:06 +00001469
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001470#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +00001471 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001472#else
Mark Seaborneb03ac52014-01-25 00:32:01 +00001473 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001474#endif
1475
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001476 for (Index = Start; Index < End; Index += Size) {
1477 MCInst Inst;
Owen Andersona0c3b972011-09-15 23:38:46 +00001478
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001479 if (Index + SectionAddr < StartAddress ||
1480 Index + SectionAddr > StopAddress) {
1481 // skip byte by byte till StartAddress is reached
1482 Size = 1;
1483 continue;
1484 }
Davide Italianof0706882015-10-01 21:57:09 +00001485 // AArch64 ELF binaries can interleave data and text in the
1486 // same section. We rely on the markers introduced to
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001487 // understand what we need to dump. If the data marker is within a
1488 // function, it is denoted as a word/short etc
1489 if (isArmElf(Obj) && std::get<2>(Symbols[si]) != ELF::STT_OBJECT &&
1490 !DisassembleAll) {
Davide Italianof0706882015-10-01 21:57:09 +00001491 uint64_t Stride = 0;
1492
1493 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1494 DataMappingSymsAddr.end(), Index);
1495 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1496 // Switch to data.
1497 while (Index < End) {
1498 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1499 outs() << "\t";
1500 if (Index + 4 <= End) {
1501 Stride = 4;
1502 dumpBytes(Bytes.slice(Index, 4), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001503 outs() << "\t.word\t";
1504 uint32_t Data = 0;
1505 if (Obj->isLittleEndian()) {
1506 const auto Word =
1507 reinterpret_cast<const support::ulittle32_t *>(
1508 Bytes.data() + Index);
1509 Data = *Word;
1510 } else {
1511 const auto Word = reinterpret_cast<const support::ubig32_t *>(
1512 Bytes.data() + Index);
1513 Data = *Word;
1514 }
1515 outs() << "0x" << format("%08" PRIx32, Data);
Davide Italianof0706882015-10-01 21:57:09 +00001516 } else if (Index + 2 <= End) {
1517 Stride = 2;
1518 dumpBytes(Bytes.slice(Index, 2), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001519 outs() << "\t\t.short\t";
1520 uint16_t Data = 0;
1521 if (Obj->isLittleEndian()) {
1522 const auto Short =
1523 reinterpret_cast<const support::ulittle16_t *>(
1524 Bytes.data() + Index);
1525 Data = *Short;
1526 } else {
1527 const auto Short =
1528 reinterpret_cast<const support::ubig16_t *>(Bytes.data() +
1529 Index);
1530 Data = *Short;
1531 }
1532 outs() << "0x" << format("%04" PRIx16, Data);
Davide Italianof0706882015-10-01 21:57:09 +00001533 } else {
1534 Stride = 1;
1535 dumpBytes(Bytes.slice(Index, 1), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001536 outs() << "\t\t.byte\t";
1537 outs() << "0x" << format("%02" PRIx8, Bytes.slice(Index, 1)[0]);
Davide Italianof0706882015-10-01 21:57:09 +00001538 }
1539 Index += Stride;
1540 outs() << "\n";
1541 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1542 TextMappingSymsAddr.end(), Index);
1543 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1544 break;
1545 }
1546 }
1547 }
1548
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001549 // If there is a data symbol inside an ELF text section and we are only
1550 // disassembling text (applicable all architectures),
1551 // we are in a situation where we must print the data and not
1552 // disassemble it.
1553 if (Obj->isELF() && std::get<2>(Symbols[si]) == ELF::STT_OBJECT &&
1554 !DisassembleAll && Section.isText()) {
1555 // print out data up to 8 bytes at a time in hex and ascii
1556 uint8_t AsciiData[9] = {'\0'};
1557 uint8_t Byte;
1558 int NumBytes = 0;
1559
1560 for (Index = Start; Index < End; Index += 1) {
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001561 if (((SectionAddr + Index) < StartAddress) ||
1562 ((SectionAddr + Index) > StopAddress))
1563 continue;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001564 if (NumBytes == 0) {
1565 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1566 outs() << "\t";
1567 }
1568 Byte = Bytes.slice(Index)[0];
1569 outs() << format(" %02x", Byte);
1570 AsciiData[NumBytes] = isprint(Byte) ? Byte : '.';
1571
1572 uint8_t IndentOffset = 0;
1573 NumBytes++;
1574 if (Index == End - 1 || NumBytes > 8) {
1575 // Indent the space for less than 8 bytes data.
1576 // 2 spaces for byte and one for space between bytes
1577 IndentOffset = 3 * (8 - NumBytes);
1578 for (int Excess = 8 - NumBytes; Excess < 8; Excess++)
1579 AsciiData[Excess] = '\0';
1580 NumBytes = 8;
1581 }
1582 if (NumBytes == 8) {
1583 AsciiData[8] = '\0';
1584 outs() << std::string(IndentOffset, ' ') << " ";
1585 outs() << reinterpret_cast<char *>(AsciiData);
1586 outs() << '\n';
1587 NumBytes = 0;
1588 }
1589 }
1590 }
Davide Italianof0706882015-10-01 21:57:09 +00001591 if (Index >= End)
1592 break;
1593
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001594 // Disassemble a real instruction or a data when disassemble all is
1595 // provided
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001596 bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1597 SectionAddr + Index, DebugOut,
1598 CommentStream);
1599 if (Size == 0)
1600 Size = 1;
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001601
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001602 PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001603 Bytes.slice(Index, Size), SectionAddr + Index, outs(), "",
1604 *STI, &SP);
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001605 outs() << CommentStream.str();
1606 Comments.clear();
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001607
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001608 // Try to resolve the target of a call, tail call, etc. to a specific
1609 // symbol.
1610 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1611 MIA->isConditionalBranch(Inst))) {
1612 uint64_t Target;
1613 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1614 // In a relocatable object, the target's section must reside in
1615 // the same section as the call instruction or it is accessed
1616 // through a relocation.
1617 //
1618 // In a non-relocatable object, the target may be in any section.
1619 //
1620 // N.B. We don't walk the relocations in the relocatable case yet.
1621 auto *TargetSectionSymbols = &Symbols;
1622 if (!Obj->isRelocatableObject()) {
1623 auto SectionAddress = std::upper_bound(
1624 SectionAddresses.begin(), SectionAddresses.end(), Target,
1625 [](uint64_t LHS,
1626 const std::pair<uint64_t, SectionRef> &RHS) {
1627 return LHS < RHS.first;
1628 });
1629 if (SectionAddress != SectionAddresses.begin()) {
1630 --SectionAddress;
1631 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1632 } else {
1633 TargetSectionSymbols = nullptr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001634 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001635 }
David Majnemer2603a8fa2015-07-09 18:11:40 +00001636
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001637 // Find the first symbol in the section whose offset is less than
1638 // or equal to the target.
1639 if (TargetSectionSymbols) {
1640 auto TargetSym = std::upper_bound(
1641 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1642 Target, [](uint64_t LHS,
Sam Koltonc05d7782016-08-17 10:17:57 +00001643 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1644 return LHS < std::get<0>(RHS);
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001645 });
1646 if (TargetSym != TargetSectionSymbols->begin()) {
1647 --TargetSym;
1648 uint64_t TargetAddress = std::get<0>(*TargetSym);
1649 StringRef TargetName = std::get<1>(*TargetSym);
1650 outs() << " <" << TargetName;
1651 uint64_t Disp = Target - TargetAddress;
1652 if (Disp)
1653 outs() << "+0x" << utohexstr(Disp);
1654 outs() << '>';
David Majnemer81afca62015-07-07 22:06:59 +00001655 }
1656 }
1657 }
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001658 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001659 outs() << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001660
1661 // Print relocation for instruction.
1662 while (rel_cur != rel_end) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001663 bool hidden = getHidden(*rel_cur);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001664 uint64_t addr = rel_cur->getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +00001665 SmallString<16> name;
1666 SmallString<32> val;
Owen Andersonfa3e5202011-10-25 20:35:53 +00001667
1668 // If this relocation is hidden, skip it.
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001669 if (hidden || ((SectionAddr + addr) < StartAddress)) {
1670 ++rel_cur;
1671 continue;
1672 }
Owen Andersonfa3e5202011-10-25 20:35:53 +00001673
Michael J. Spencer51862b32011-10-13 22:17:18 +00001674 // Stop when rel_cur's address is past the current instruction.
Owen Andersonf20e3e52011-10-25 20:15:39 +00001675 if (addr >= Index + Size) break;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001676 rel_cur->getTypeName(name);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001677 error(getRelocationValueString(*rel_cur, val));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001678 outs() << format(Fmt.data(), SectionAddr + addr) << name
Benjamin Kramer82803112012-03-10 02:04:38 +00001679 << "\t" << val << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001680 ++rel_cur;
1681 }
Benjamin Kramer87ee76c2011-07-20 19:37:35 +00001682 }
Michael J. Spencer2670c252011-01-20 06:39:06 +00001683 }
1684 }
1685}
1686
Kevin Enderby98da6132015-01-20 21:47:46 +00001687void llvm::PrintRelocations(const ObjectFile *Obj) {
Greg Fitzgerald18432272014-03-20 22:55:15 +00001688 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1689 "%08" PRIx64;
Rafael Espindola9219fe72016-03-21 20:59:15 +00001690 // Regular objdump doesn't print relocations in non-relocatable object
1691 // files.
1692 if (!Obj->isRelocatableObject())
1693 return;
Rafael Espindolac66d7612014-08-17 19:09:37 +00001694
Colin LeMahieu77804be2015-07-29 15:45:39 +00001695 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001696 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001697 continue;
1698 StringRef secname;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001699 error(Section.getName(secname));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001700 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001701 for (const RelocationRef &Reloc : Section.relocations()) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001702 bool hidden = getHidden(Reloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001703 uint64_t address = Reloc.getOffset();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001704 SmallString<32> relocname;
1705 SmallString<32> valuestr;
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001706 if (address < StartAddress || address > StopAddress || hidden)
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001707 continue;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001708 Reloc.getTypeName(relocname);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001709 error(getRelocationValueString(Reloc, valuestr));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001710 outs() << format(Fmt.data(), address) << " " << relocname << " "
1711 << valuestr << "\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001712 }
1713 outs() << "\n";
1714 }
1715}
1716
Kevin Enderby98da6132015-01-20 21:47:46 +00001717void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001718 outs() << "Sections:\n"
1719 "Idx Name Size Address Type\n";
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001720 unsigned i = 0;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001721 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001722 StringRef Name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001723 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001724 uint64_t Address = Section.getAddress();
1725 uint64_t Size = Section.getSize();
1726 bool Text = Section.isText();
1727 bool Data = Section.isData();
1728 bool BSS = Section.isBSS();
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001729 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +00001730 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
Alexey Samsonov48803e52014-03-13 14:37:36 +00001731 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1732 Name.str().c_str(), Size, Address, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001733 ++i;
1734 }
1735}
1736
Kevin Enderby98da6132015-01-20 21:47:46 +00001737void llvm::PrintSectionContents(const ObjectFile *Obj) {
Rafael Espindola4453e42942014-06-13 03:07:50 +00001738 std::error_code EC;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001739 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001740 StringRef Name;
1741 StringRef Contents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001742 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001743 uint64_t BaseAddr = Section.getAddress();
David Majnemer185b5b12014-11-11 09:58:25 +00001744 uint64_t Size = Section.getSize();
1745 if (!Size)
1746 continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001747
1748 outs() << "Contents of section " << Name << ":\n";
David Majnemer185b5b12014-11-11 09:58:25 +00001749 if (Section.isBSS()) {
Alexey Samsonov209095c2013-04-16 10:53:11 +00001750 outs() << format("<skipping contents of bss section at [%04" PRIx64
David Majnemer8f6b04c2014-07-14 16:20:14 +00001751 ", %04" PRIx64 ")>\n",
1752 BaseAddr, BaseAddr + Size);
Alexey Samsonov209095c2013-04-16 10:53:11 +00001753 continue;
1754 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001755
Davide Italianoccd53fe2015-08-05 07:18:31 +00001756 error(Section.getContents(Contents));
David Majnemer8f6b04c2014-07-14 16:20:14 +00001757
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001758 // Dump out the content as hex and printable ascii characters.
1759 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer82803112012-03-10 02:04:38 +00001760 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001761 // Dump line of hex.
1762 for (std::size_t i = 0; i < 16; ++i) {
1763 if (i != 0 && i % 4 == 0)
1764 outs() << ' ';
1765 if (addr + i < end)
1766 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1767 << hexdigit(Contents[addr + i] & 0xF, true);
1768 else
1769 outs() << " ";
1770 }
1771 // Print ascii.
1772 outs() << " ";
1773 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
Guy Benyei83c74e92013-02-12 21:21:59 +00001774 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001775 outs() << Contents[addr + i];
1776 else
1777 outs() << ".";
1778 }
1779 outs() << "\n";
1780 }
1781 }
1782}
1783
Kevin Enderby9acb1092016-05-31 20:35:34 +00001784void llvm::PrintSymbolTable(const ObjectFile *o, StringRef ArchiveName,
1785 StringRef ArchitectureName) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001786 outs() << "SYMBOL TABLE:\n";
1787
Rui Ueyama4e39f712014-03-18 18:58:51 +00001788 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
Davide Italianoe85abf72015-12-20 09:54:34 +00001789 printCOFFSymbolTable(coff);
Rui Ueyama4e39f712014-03-18 18:58:51 +00001790 return;
1791 }
1792 for (const SymbolRef &Symbol : o->symbols()) {
Kevin Enderby931cb652016-06-24 18:24:42 +00001793 Expected<uint64_t> AddressOrError = Symbol.getAddress();
1794 if (!AddressOrError)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001795 report_error(ArchiveName, o->getFileName(), AddressOrError.takeError(),
1796 ArchitectureName);
Rafael Espindolaed067c42015-07-03 18:19:00 +00001797 uint64_t Address = *AddressOrError;
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001798 if ((Address < StartAddress) || (Address > StopAddress))
1799 continue;
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001800 Expected<SymbolRef::Type> TypeOrError = Symbol.getType();
1801 if (!TypeOrError)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001802 report_error(ArchiveName, o->getFileName(), TypeOrError.takeError(),
1803 ArchitectureName);
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00001804 SymbolRef::Type Type = *TypeOrError;
Rui Ueyama4e39f712014-03-18 18:58:51 +00001805 uint32_t Flags = Symbol.getFlags();
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001806 Expected<section_iterator> SectionOrErr = Symbol.getSection();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001807 if (!SectionOrErr)
1808 report_error(ArchiveName, o->getFileName(), SectionOrErr.takeError(),
1809 ArchitectureName);
Rafael Espindola8bab8892015-08-07 23:27:14 +00001810 section_iterator Section = *SectionOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001811 StringRef Name;
1812 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1813 Section->getName(Name);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001814 } else {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001815 Expected<StringRef> NameOrErr = Symbol.getName();
1816 if (!NameOrErr)
Kevin Enderby9acb1092016-05-31 20:35:34 +00001817 report_error(ArchiveName, o->getFileName(), NameOrErr.takeError(),
1818 ArchitectureName);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001819 Name = *NameOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001820 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001821
Rui Ueyama4e39f712014-03-18 18:58:51 +00001822 bool Global = Flags & SymbolRef::SF_Global;
1823 bool Weak = Flags & SymbolRef::SF_Weak;
1824 bool Absolute = Flags & SymbolRef::SF_Absolute;
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001825 bool Common = Flags & SymbolRef::SF_Common;
Davide Italianocd2514d2015-04-30 23:08:53 +00001826 bool Hidden = Flags & SymbolRef::SF_Hidden;
David Meyer1df4b842012-02-28 23:47:53 +00001827
Rui Ueyama4e39f712014-03-18 18:58:51 +00001828 char GlobLoc = ' ';
1829 if (Type != SymbolRef::ST_Unknown)
1830 GlobLoc = Global ? 'g' : 'l';
1831 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1832 ? 'd' : ' ';
1833 char FileFunc = ' ';
1834 if (Type == SymbolRef::ST_File)
1835 FileFunc = 'f';
1836 else if (Type == SymbolRef::ST_Function)
1837 FileFunc = 'F';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001838
Rui Ueyama4e39f712014-03-18 18:58:51 +00001839 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1840 "%08" PRIx64;
Michael J. Spencerd857c1c2013-01-10 22:40:50 +00001841
Rui Ueyama4e39f712014-03-18 18:58:51 +00001842 outs() << format(Fmt, Address) << " "
1843 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1844 << (Weak ? 'w' : ' ') // Weak?
1845 << ' ' // Constructor. Not supported yet.
1846 << ' ' // Warning. Not supported yet.
1847 << ' ' // Indirect reference to another symbol.
1848 << Debug // Debugging (d) or dynamic (D) symbol.
1849 << FileFunc // Name of function (F), file (f) or object (O).
1850 << ' ';
1851 if (Absolute) {
1852 outs() << "*ABS*";
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001853 } else if (Common) {
1854 outs() << "*COM*";
Rui Ueyama4e39f712014-03-18 18:58:51 +00001855 } else if (Section == o->section_end()) {
1856 outs() << "*UND*";
1857 } else {
1858 if (const MachOObjectFile *MachO =
1859 dyn_cast<const MachOObjectFile>(o)) {
1860 DataRefImpl DR = Section->getRawDataRefImpl();
1861 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1862 outs() << SegmentName << ",";
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001863 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00001864 StringRef SectionName;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001865 error(Section->getName(SectionName));
Rui Ueyama4e39f712014-03-18 18:58:51 +00001866 outs() << SectionName;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001867 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001868
1869 outs() << '\t';
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001870 if (Common || isa<ELFObjectFileBase>(o)) {
Rafael Espindoladbb6bd32015-06-25 22:10:04 +00001871 uint64_t Val =
1872 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001873 outs() << format("\t %08" PRIx64 " ", Val);
1874 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001875
Davide Italianocd2514d2015-04-30 23:08:53 +00001876 if (Hidden) {
1877 outs() << ".hidden ";
1878 }
1879 outs() << Name
Rui Ueyama4e39f712014-03-18 18:58:51 +00001880 << '\n';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001881 }
1882}
1883
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001884static void PrintUnwindInfo(const ObjectFile *o) {
1885 outs() << "Unwind info:\n\n";
1886
1887 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1888 printCOFFUnwindInfo(coff);
Tim Northover4bd286a2014-08-01 13:07:19 +00001889 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1890 printMachOUnwindInfo(MachO);
1891 else {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001892 // TODO: Extract DWARF dump tool to objdump.
1893 errs() << "This operation is only currently supported "
Tim Northover4bd286a2014-08-01 13:07:19 +00001894 "for COFF and MachO object files.\n";
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001895 return;
1896 }
1897}
1898
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001899void llvm::printExportsTrie(const ObjectFile *o) {
Nick Kledzikd04bc352014-08-30 00:20:14 +00001900 outs() << "Exports trie:\n";
1901 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1902 printMachOExportsTrie(MachO);
1903 else {
1904 errs() << "This operation is only currently supported "
1905 "for Mach-O executable files.\n";
1906 return;
1907 }
1908}
1909
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001910void llvm::printRebaseTable(ObjectFile *o) {
Nick Kledzikac431442014-09-12 21:34:15 +00001911 outs() << "Rebase table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001912 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzikac431442014-09-12 21:34:15 +00001913 printMachORebaseTable(MachO);
1914 else {
1915 errs() << "This operation is only currently supported "
1916 "for Mach-O executable files.\n";
1917 return;
1918 }
1919}
1920
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001921void llvm::printBindTable(ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001922 outs() << "Bind table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001923 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzik56ebef42014-09-16 01:41:51 +00001924 printMachOBindTable(MachO);
1925 else {
1926 errs() << "This operation is only currently supported "
1927 "for Mach-O executable files.\n";
1928 return;
1929 }
1930}
1931
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001932void llvm::printLazyBindTable(ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001933 outs() << "Lazy bind table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001934 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzik56ebef42014-09-16 01:41:51 +00001935 printMachOLazyBindTable(MachO);
1936 else {
1937 errs() << "This operation is only currently supported "
1938 "for Mach-O executable files.\n";
1939 return;
1940 }
1941}
1942
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001943void llvm::printWeakBindTable(ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001944 outs() << "Weak bind table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001945 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzik56ebef42014-09-16 01:41:51 +00001946 printMachOWeakBindTable(MachO);
1947 else {
1948 errs() << "This operation is only currently supported "
1949 "for Mach-O executable files.\n";
1950 return;
1951 }
1952}
Nick Kledzikac431442014-09-12 21:34:15 +00001953
Adrian Prantl437105a2015-07-08 02:04:15 +00001954/// Dump the raw contents of the __clangast section so the output can be piped
1955/// into llvm-bcanalyzer.
1956void llvm::printRawClangAST(const ObjectFile *Obj) {
1957 if (outs().is_displayed()) {
1958 errs() << "The -raw-clang-ast option will dump the raw binary contents of "
1959 "the clang ast section.\n"
1960 "Please redirect the output to a file or another program such as "
1961 "llvm-bcanalyzer.\n";
1962 return;
1963 }
1964
1965 StringRef ClangASTSectionName("__clangast");
1966 if (isa<COFFObjectFile>(Obj)) {
1967 ClangASTSectionName = "clangast";
1968 }
1969
1970 Optional<object::SectionRef> ClangASTSection;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001971 for (auto Sec : ToolSectionFilter(*Obj)) {
Adrian Prantl437105a2015-07-08 02:04:15 +00001972 StringRef Name;
1973 Sec.getName(Name);
1974 if (Name == ClangASTSectionName) {
1975 ClangASTSection = Sec;
1976 break;
1977 }
1978 }
1979 if (!ClangASTSection)
1980 return;
1981
1982 StringRef ClangASTContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001983 error(ClangASTSection.getValue().getContents(ClangASTContents));
Adrian Prantl437105a2015-07-08 02:04:15 +00001984 outs().write(ClangASTContents.data(), ClangASTContents.size());
1985}
1986
Sanjoy Das6f567a42015-06-22 18:03:02 +00001987static void printFaultMaps(const ObjectFile *Obj) {
1988 const char *FaultMapSectionName = nullptr;
1989
1990 if (isa<ELFObjectFileBase>(Obj)) {
1991 FaultMapSectionName = ".llvm_faultmaps";
1992 } else if (isa<MachOObjectFile>(Obj)) {
1993 FaultMapSectionName = "__llvm_faultmaps";
1994 } else {
1995 errs() << "This operation is only currently supported "
1996 "for ELF and Mach-O executable files.\n";
1997 return;
1998 }
1999
2000 Optional<object::SectionRef> FaultMapSection;
2001
Colin LeMahieu77804be2015-07-29 15:45:39 +00002002 for (auto Sec : ToolSectionFilter(*Obj)) {
Sanjoy Das6f567a42015-06-22 18:03:02 +00002003 StringRef Name;
2004 Sec.getName(Name);
2005 if (Name == FaultMapSectionName) {
2006 FaultMapSection = Sec;
2007 break;
2008 }
2009 }
2010
2011 outs() << "FaultMap table:\n";
2012
2013 if (!FaultMapSection.hasValue()) {
2014 outs() << "<not found>\n";
2015 return;
2016 }
2017
2018 StringRef FaultMapContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00002019 error(FaultMapSection.getValue().getContents(FaultMapContents));
Sanjoy Das6f567a42015-06-22 18:03:02 +00002020
2021 FaultMapParser FMP(FaultMapContents.bytes_begin(),
2022 FaultMapContents.bytes_end());
2023
2024 outs() << FMP;
2025}
2026
Davide Italiano1bdaa202016-09-18 04:39:15 +00002027static void printPrivateFileHeaders(const ObjectFile *o, bool onlyFirst) {
Kevin Enderby0ae163f2016-01-13 00:25:36 +00002028 if (o->isELF())
Davide Italiano1bdaa202016-09-18 04:39:15 +00002029 return printELFFileHeader(o);
2030 if (o->isCOFF())
2031 return printCOFFFileHeader(o);
Derek Schuff2c6f75d2016-11-30 16:49:11 +00002032 if (o->isWasm())
2033 return printWasmFileHeader(o);
Davide Italiano1bdaa202016-09-18 04:39:15 +00002034 if (o->isMachO()) {
Kevin Enderby0ae163f2016-01-13 00:25:36 +00002035 printMachOFileHeader(o);
Davide Italiano1bdaa202016-09-18 04:39:15 +00002036 if (!onlyFirst)
2037 printMachOLoadCommands(o);
2038 return;
2039 }
Kevin Enderby7fa40c92016-11-16 22:17:38 +00002040 report_error(o->getFileName(), "Invalid/Unsupported object file format");
Rui Ueyamac2bed422013-09-27 21:04:00 +00002041}
2042
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002043static void DumpObject(ObjectFile *o, const Archive *a = nullptr) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002044 StringRef ArchiveName = a != nullptr ? a->getFileName() : "";
Adrian Prantl437105a2015-07-08 02:04:15 +00002045 // Avoid other output when using a raw option.
2046 if (!RawClangAST) {
2047 outs() << '\n';
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002048 if (a)
2049 outs() << a->getFileName() << "(" << o->getFileName() << ")";
2050 else
2051 outs() << o->getFileName();
2052 outs() << ":\tfile format " << o->getFileFormatName() << "\n\n";
Adrian Prantl437105a2015-07-08 02:04:15 +00002053 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00002054
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002055 if (Disassemble)
Michael J. Spencer51862b32011-10-13 22:17:18 +00002056 DisassembleObject(o, Relocations);
2057 if (Relocations && !Disassemble)
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002058 PrintRelocations(o);
Nick Lewyckyfcf84622011-10-10 21:21:34 +00002059 if (SectionHeaders)
2060 PrintSectionHeaders(o);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00002061 if (SectionContents)
2062 PrintSectionContents(o);
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002063 if (SymbolTable)
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002064 PrintSymbolTable(o, ArchiveName);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00002065 if (UnwindInfo)
2066 PrintUnwindInfo(o);
Davide Italiano1bdaa202016-09-18 04:39:15 +00002067 if (PrivateHeaders || FirstPrivateHeader)
2068 printPrivateFileHeaders(o, FirstPrivateHeader);
Nick Kledzikd04bc352014-08-30 00:20:14 +00002069 if (ExportsTrie)
2070 printExportsTrie(o);
Nick Kledzikac431442014-09-12 21:34:15 +00002071 if (Rebase)
2072 printRebaseTable(o);
Nick Kledzik56ebef42014-09-16 01:41:51 +00002073 if (Bind)
2074 printBindTable(o);
2075 if (LazyBind)
2076 printLazyBindTable(o);
2077 if (WeakBind)
2078 printWeakBindTable(o);
Adrian Prantl437105a2015-07-08 02:04:15 +00002079 if (RawClangAST)
2080 printRawClangAST(o);
Sanjoy Das6f567a42015-06-22 18:03:02 +00002081 if (PrintFaultMaps)
2082 printFaultMaps(o);
Igor Laevsky03a670c2016-01-26 15:09:42 +00002083 if (DwarfDumpType != DIDT_Null) {
2084 std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*o));
2085 // Dump the complete DWARF structure.
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00002086 DIDumpOptions DumpOpts;
2087 DumpOpts.DumpType = DwarfDumpType;
2088 DumpOpts.DumpEH = true;
2089 DICtx->dump(outs(), DumpOpts);
Igor Laevsky03a670c2016-01-26 15:09:42 +00002090 }
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002091}
2092
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00002093static void DumpObject(const COFFImportFile *I, const Archive *A) {
2094 StringRef ArchiveName = A ? A->getFileName() : "";
2095
2096 // Avoid other output when using a raw option.
2097 if (!RawClangAST)
2098 outs() << '\n'
2099 << ArchiveName << "(" << I->getFileName() << ")"
2100 << ":\tfile format COFF-import-file"
2101 << "\n\n";
2102
2103 if (SymbolTable)
2104 printCOFFSymbolTable(I);
2105}
2106
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002107/// @brief Dump each object file in \a a;
2108static void DumpArchive(const Archive *a) {
Mehdi Amini41af4302016-11-11 04:28:40 +00002109 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00002110 for (auto &C : a->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002111 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2112 if (!ChildOrErr) {
2113 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2114 report_error(a->getFileName(), C, std::move(E));
2115 continue;
2116 }
Rafael Espindolaae460022014-06-16 16:08:36 +00002117 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002118 DumpObject(o, a);
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00002119 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
2120 DumpObject(I, a);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002121 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00002122 report_error(a->getFileName(), object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002123 }
Lang Hamesfc209622016-07-14 02:24:01 +00002124 if (Err)
2125 report_error(a->getFileName(), std::move(Err));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002126}
2127
2128/// @brief Open file and figure out how to dump it.
2129static void DumpInput(StringRef file) {
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002130
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002131 // If we are using the Mach-O specific object file parser, then let it parse
2132 // the file and process the command line options. So the -arch flags can
2133 // be used to select specific slices, etc.
2134 if (MachOOpt) {
2135 ParseInputMachO(file);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002136 return;
2137 }
2138
2139 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00002140 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
2141 if (!BinaryOrErr)
Kevin Enderbyb34e3a12016-05-05 17:43:35 +00002142 report_error(file, BinaryOrErr.takeError());
Rafael Espindola48af1c22014-08-19 18:44:46 +00002143 Binary &Binary = *BinaryOrErr.get().getBinary();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002144
Rafael Espindola3f6481d2014-08-01 14:31:55 +00002145 if (Archive *a = dyn_cast<Archive>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002146 DumpArchive(a);
Rafael Espindola3f6481d2014-08-01 14:31:55 +00002147 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002148 DumpObject(o);
Jim Grosbachaf9aec02012-08-07 17:53:14 +00002149 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00002150 report_error(file, object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002151}
2152
Michael J. Spencer2670c252011-01-20 06:39:06 +00002153int main(int argc, char **argv) {
2154 // Print a stack trace if we signal out.
Richard Smith2ad6d482016-06-09 00:53:21 +00002155 sys::PrintStackTraceOnErrorSignal(argv[0]);
Michael J. Spencer2670c252011-01-20 06:39:06 +00002156 PrettyStackTraceProgram X(argc, argv);
2157 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
2158
2159 // Initialize targets and assembly printers/parsers.
2160 llvm::InitializeAllTargetInfos();
Evan Cheng8c886a42011-07-22 21:58:54 +00002161 llvm::InitializeAllTargetMCs();
Michael J. Spencer2670c252011-01-20 06:39:06 +00002162 llvm::InitializeAllDisassemblers();
2163
Pete Cooper28fb4fc2012-05-03 23:20:10 +00002164 // Register the target printer for --version.
2165 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
2166
Michael J. Spencer2670c252011-01-20 06:39:06 +00002167 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
2168 TripleName = Triple::normalize(TripleName);
2169
2170 ToolName = argv[0];
2171
2172 // Defaults to a.out if no filenames specified.
2173 if (InputFilenames.size() == 0)
2174 InputFilenames.push_back("a.out");
2175
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00002176 if (DisassembleAll || PrintSource || PrintLines)
Colin LeMahieuf34933e2015-07-23 20:58:49 +00002177 Disassemble = true;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002178 if (!Disassemble
2179 && !Relocations
2180 && !SectionHeaders
2181 && !SectionContents
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00002182 && !SymbolTable
Michael J. Spencer209565db2013-01-06 03:56:49 +00002183 && !UnwindInfo
Nick Kledzikd04bc352014-08-30 00:20:14 +00002184 && !PrivateHeaders
Kevin Enderby0ae163f2016-01-13 00:25:36 +00002185 && !FirstPrivateHeader
Nick Kledzikac431442014-09-12 21:34:15 +00002186 && !ExportsTrie
Nick Kledzik56ebef42014-09-16 01:41:51 +00002187 && !Rebase
2188 && !Bind
2189 && !LazyBind
Kevin Enderby131d1772015-01-09 19:22:37 +00002190 && !WeakBind
Adrian Prantl437105a2015-07-08 02:04:15 +00002191 && !RawClangAST
Kevin Enderby13023a12015-01-15 23:19:11 +00002192 && !(UniversalHeaders && MachOOpt)
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00002193 && !(ArchiveHeaders && MachOOpt)
Kevin Enderby69fe98d2015-01-23 18:52:17 +00002194 && !(IndirectSymbols && MachOOpt)
Kevin Enderby9a509442015-01-27 21:28:24 +00002195 && !(DataInCode && MachOOpt)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002196 && !(LinkOptHints && MachOOpt)
Kevin Enderbycd66be52015-03-11 22:06:32 +00002197 && !(InfoPlist && MachOOpt)
Kevin Enderbybc847fa2015-03-16 20:08:09 +00002198 && !(DylibsUsed && MachOOpt)
2199 && !(DylibId && MachOOpt)
Kevin Enderby0fc11822015-04-01 20:57:01 +00002200 && !(ObjcMetaData && MachOOpt)
Colin LeMahieufcc32762015-07-29 19:08:10 +00002201 && !(FilterSections.size() != 0 && MachOOpt)
Igor Laevsky03a670c2016-01-26 15:09:42 +00002202 && !PrintFaultMaps
2203 && DwarfDumpType == DIDT_Null) {
Michael J. Spencer2670c252011-01-20 06:39:06 +00002204 cl::PrintHelpMessage();
2205 return 2;
2206 }
2207
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002208 std::for_each(InputFilenames.begin(), InputFilenames.end(),
2209 DumpInput);
Michael J. Spencer2670c252011-01-20 06:39:06 +00002210
Davide Italianoccd53fe2015-08-05 07:18:31 +00002211 return EXIT_SUCCESS;
Michael J. Spencer2670c252011-01-20 06:39:06 +00002212}