blob: d38ffc1a3ce60c563ab1bbdf662ed6f43b32891f [file] [log] [blame]
Michael J. Spencer2670c252011-01-20 06:39:06 +00001//===-- llvm-objdump.cpp - Object file dumping utility for llvm -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This program is a utility that works like binutils "objdump", that is, it
11// dumps out a plethora of information about an object file depending on the
12// flags.
13//
Michael J. Spencerd7e70032013-02-05 20:27:22 +000014// The flags and output of this program should be near identical to those of
15// binutils objdump.
16//
Michael J. Spencer2670c252011-01-20 06:39:06 +000017//===----------------------------------------------------------------------===//
18
Benjamin Kramer43a772e2011-09-19 17:56:04 +000019#include "llvm-objdump.h"
Sanjoy Das6f567a42015-06-22 18:03:02 +000020#include "llvm/ADT/Optional.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000021#include "llvm/ADT/STLExtras.h"
Michael J. Spencer4e25c022011-10-17 17:13:22 +000022#include "llvm/ADT/StringExtras.h"
Rafael Aulerb0e4b912018-03-09 19:13:44 +000023#include "llvm/ADT/StringSet.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000024#include "llvm/ADT/Triple.h"
Sanjoy Das3f1bc3b2015-06-23 20:09:03 +000025#include "llvm/CodeGen/FaultMaps.h"
Igor Laevsky03a670c2016-01-26 15:09:42 +000026#include "llvm/DebugInfo/DWARF/DWARFContext.h"
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +000027#include "llvm/DebugInfo/Symbolize/Symbolize.h"
Paul Semel007dedb2018-07-18 16:39:21 +000028#include "llvm/Demangle/Demangle.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000029#include "llvm/MC/MCAsmInfo.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000030#include "llvm/MC/MCContext.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000031#include "llvm/MC/MCDisassembler/MCDisassembler.h"
32#include "llvm/MC/MCDisassembler/MCRelocationInfo.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000033#include "llvm/MC/MCInst.h"
34#include "llvm/MC/MCInstPrinter.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000035#include "llvm/MC/MCInstrAnalysis.h"
Craig Topper54bfde72012-04-02 06:09:36 +000036#include "llvm/MC/MCInstrInfo.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000037#include "llvm/MC/MCObjectFileInfo.h"
Jim Grosbachfd93a592012-03-05 19:33:20 +000038#include "llvm/MC/MCRegisterInfo.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000039#include "llvm/MC/MCSubtargetInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000040#include "llvm/Object/Archive.h"
41#include "llvm/Object/COFF.h"
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +000042#include "llvm/Object/COFFImportFile.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000043#include "llvm/Object/ELFObjectFile.h"
Rafael Espindolaa9f810b2012-12-21 03:47:03 +000044#include "llvm/Object/MachO.h"
Dave Lee3fb120f2018-08-03 00:06:38 +000045#include "llvm/Object/MachOUniversal.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000046#include "llvm/Object/ObjectFile.h"
Sam Clegg4df5d762017-06-27 20:40:53 +000047#include "llvm/Object/Wasm.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000048#include "llvm/Support/Casting.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000049#include "llvm/Support/CommandLine.h"
50#include "llvm/Support/Debug.h"
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +000051#include "llvm/Support/Errc.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000052#include "llvm/Support/FileSystem.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000053#include "llvm/Support/Format.h"
Benjamin Kramerbf115312011-07-25 23:04:36 +000054#include "llvm/Support/GraphWriter.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000055#include "llvm/Support/Host.h"
Rui Ueyama197194b2018-04-13 18:26:06 +000056#include "llvm/Support/InitLLVM.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000057#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000058#include "llvm/Support/SourceMgr.h"
Joel Galenson134cf472018-08-24 15:21:57 +000059#include "llvm/Support/StringSaver.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000060#include "llvm/Support/TargetRegistry.h"
61#include "llvm/Support/TargetSelect.h"
Jonas Devliegheree787efd2018-11-11 22:12:04 +000062#include "llvm/Support/WithColor.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000063#include "llvm/Support/raw_ostream.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000064#include <algorithm>
Benjamin Kramera5177e62012-03-23 11:49:32 +000065#include <cctype>
Michael J. Spencer2670c252011-01-20 06:39:06 +000066#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000067#include <system_error>
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +000068#include <unordered_map>
Rafael Espindolac398e672017-07-19 22:27:28 +000069#include <utility>
Ahmed Bougacha17926472013-08-21 07:29:02 +000070
Michael J. Spencer2670c252011-01-20 06:39:06 +000071using namespace llvm;
72using namespace object;
73
Fangrui Song8513cd42018-06-27 20:45:11 +000074cl::opt<bool>
75 llvm::AllHeaders("all-headers",
76 cl::desc("Display all available header information"));
77static cl::alias AllHeadersShort("x", cl::desc("Alias for --all-headers"),
78 cl::aliasopt(AllHeaders));
79
Benjamin Kramer43a772e2011-09-19 17:56:04 +000080static cl::list<std::string>
81InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
Michael J. Spencer2670c252011-01-20 06:39:06 +000082
Kevin Enderbye2297dd2015-01-07 21:02:18 +000083cl::opt<bool>
84llvm::Disassemble("disassemble",
Benjamin Kramer43a772e2011-09-19 17:56:04 +000085 cl::desc("Display assembler mnemonics for the machine instructions"));
86static cl::alias
87Disassembled("d", cl::desc("Alias for --disassemble"),
Colin LeMahieu77804be2015-07-29 15:45:39 +000088 cl::aliasopt(Disassemble));
89
90cl::opt<bool>
91llvm::DisassembleAll("disassemble-all",
92 cl::desc("Display assembler mnemonics for the machine instructions"));
93static cl::alias
94DisassembleAlld("D", cl::desc("Alias for --disassemble-all"),
Colin LeMahieuf34933e2015-07-23 20:58:49 +000095 cl::aliasopt(DisassembleAll));
Michael J. Spencer2670c252011-01-20 06:39:06 +000096
Zachary Turner030ad372018-08-20 22:18:21 +000097cl::opt<bool> llvm::Demangle("demangle", cl::desc("Demangle symbols names"),
98 cl::init(false));
Paul Semel007dedb2018-07-18 16:39:21 +000099
100static cl::alias DemangleShort("C", cl::desc("Alias for --demangle"),
Zachary Turner030ad372018-08-20 22:18:21 +0000101 cl::aliasopt(llvm::Demangle));
Paul Semel007dedb2018-07-18 16:39:21 +0000102
Rafael Aulerb0e4b912018-03-09 19:13:44 +0000103static cl::list<std::string>
104DisassembleFunctions("df",
105 cl::CommaSeparated,
106 cl::desc("List of functions to disassemble"));
107static StringSet<> DisasmFuncsSet;
108
Kevin Enderby98da6132015-01-20 21:47:46 +0000109cl::opt<bool>
Kristina Brooks31579e92018-10-31 09:34:08 +0000110llvm::Relocations("reloc",
111 cl::desc("Display the relocation entries in the file"));
112static cl::alias RelocationsShort("r", cl::desc("Alias for --reloc"),
113 cl::NotHidden,
114 cl::aliasopt(llvm::Relocations));
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000115
Kevin Enderby98da6132015-01-20 21:47:46 +0000116cl::opt<bool>
Paul Semelcb0f0432018-06-07 13:30:55 +0000117llvm::DynamicRelocations("dynamic-reloc",
118 cl::desc("Display the dynamic relocation entries in the file"));
119static cl::alias
120DynamicRelocationsd("R", cl::desc("Alias for --dynamic-reloc"),
121 cl::aliasopt(DynamicRelocations));
122
123cl::opt<bool>
James Hendersonb55b6582018-10-29 10:05:39 +0000124 llvm::SectionContents("full-contents",
125 cl::desc("Display the content of each section"));
126static cl::alias SectionContentsShort("s",
127 cl::desc("Alias for --full-contents"),
128 cl::aliasopt(SectionContents));
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000129
Kristina Brooks3baa5f72018-10-31 05:45:01 +0000130cl::opt<bool> llvm::SymbolTable("syms", cl::desc("Display the symbol table"));
131static cl::alias SymbolTableShort("t", cl::desc("Alias for --syms"),
Kristina Brooks889356e2018-10-31 09:35:25 +0000132 cl::NotHidden,
Kristina Brooks3baa5f72018-10-31 05:45:01 +0000133 cl::aliasopt(llvm::SymbolTable));
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000134
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000135cl::opt<bool>
136llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
Nick Kledzikd04bc352014-08-30 00:20:14 +0000137
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000138cl::opt<bool>
139llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
Nick Kledzikac431442014-09-12 21:34:15 +0000140
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000141cl::opt<bool>
142llvm::Bind("bind", cl::desc("Display mach-o binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000143
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000144cl::opt<bool>
145llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000146
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000147cl::opt<bool>
148llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000149
Adrian Prantl437105a2015-07-08 02:04:15 +0000150cl::opt<bool>
151llvm::RawClangAST("raw-clang-ast",
152 cl::desc("Dump the raw binary contents of the clang AST section"));
153
Nick Kledzik56ebef42014-09-16 01:41:51 +0000154static cl::opt<bool>
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000155MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000156static cl::alias
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000157MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
Benjamin Kramer87ee76c2011-07-20 19:37:35 +0000158
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000159cl::opt<std::string>
160llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
161 "see -version for available targets"));
162
163cl::opt<std::string>
Kevin Enderbyc9595622014-08-06 23:24:41 +0000164llvm::MCPU("mcpu",
165 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
166 cl::value_desc("cpu-name"),
167 cl::init(""));
168
169cl::opt<std::string>
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000170llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
Michael J. Spencer2670c252011-01-20 06:39:06 +0000171 "see -version for available targets"));
172
Kevin Enderby98da6132015-01-20 21:47:46 +0000173cl::opt<bool>
174llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
175 "headers for each section."));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000176static cl::alias
177SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
178 cl::aliasopt(SectionHeaders));
179static cl::alias
180SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
181 cl::aliasopt(SectionHeaders));
Colin LeMahieufcc32762015-07-29 19:08:10 +0000182
Colin LeMahieu77804be2015-07-29 15:45:39 +0000183cl::list<std::string>
Colin LeMahieufcc32762015-07-29 19:08:10 +0000184llvm::FilterSections("section", cl::desc("Operate on the specified sections only. "
185 "With -macho dump segment,section"));
186cl::alias
187static FilterSectionsj("j", cl::desc("Alias for --section"),
188 cl::aliasopt(llvm::FilterSections));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000189
Kevin Enderbyc9595622014-08-06 23:24:41 +0000190cl::list<std::string>
191llvm::MAttrs("mattr",
Jack Carter551efd72012-08-28 19:24:49 +0000192 cl::CommaSeparated,
193 cl::desc("Target specific attributes"),
194 cl::value_desc("a1,+a2,-a3,..."));
195
Kevin Enderbybf246f52014-09-24 23:08:22 +0000196cl::opt<bool>
197llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
198 "instructions, do not print "
199 "the instruction bytes."));
Saleem Abdulrasooldea14b22017-02-08 18:11:31 +0000200cl::opt<bool>
201llvm::NoLeadingAddr("no-leading-addr", cl::desc("Print no leading address"));
Eli Bendersky3a6808c2012-11-20 22:57:02 +0000202
Kevin Enderby98da6132015-01-20 21:47:46 +0000203cl::opt<bool>
204llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000205
206static cl::alias
207UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
208 cl::aliasopt(UnwindInfo));
209
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000210cl::opt<bool>
211llvm::PrivateHeaders("private-headers",
212 cl::desc("Display format specific file headers"));
Michael J. Spencer209565db2013-01-06 03:56:49 +0000213
Kevin Enderby0ae163f2016-01-13 00:25:36 +0000214cl::opt<bool>
215llvm::FirstPrivateHeader("private-header",
216 cl::desc("Display only the first format specific file "
217 "header"));
218
Michael J. Spencer209565db2013-01-06 03:56:49 +0000219static cl::alias
220PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
221 cl::aliasopt(PrivateHeaders));
222
Paul Semeld2af4d62018-07-04 15:25:03 +0000223cl::opt<bool> llvm::FileHeaders(
224 "file-headers",
225 cl::desc("Display the contents of the overall file header"));
226
227static cl::alias FileHeadersShort("f", cl::desc("Alias for --file-headers"),
228 cl::aliasopt(FileHeaders));
229
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000230cl::opt<bool>
Paul Semel0dc92f62018-07-05 14:43:29 +0000231 llvm::ArchiveHeaders("archive-headers",
232 cl::desc("Display archive header information"));
233
234cl::alias
235ArchiveHeadersShort("a", cl::desc("Alias for --archive-headers"),
236 cl::aliasopt(ArchiveHeaders));
237
238cl::opt<bool>
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000239 llvm::PrintImmHex("print-imm-hex",
Colin LeMahieuefe37322016-04-08 18:15:37 +0000240 cl::desc("Use hex format for immediate values"));
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000241
Sanjoy Das6f567a42015-06-22 18:03:02 +0000242cl::opt<bool> PrintFaultMaps("fault-map-section",
243 cl::desc("Display contents of faultmap section"));
244
Igor Laevsky03a670c2016-01-26 15:09:42 +0000245cl::opt<DIDumpType> llvm::DwarfDumpType(
246 "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"),
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000247 cl::values(clEnumValN(DIDT_DebugFrame, "frames", ".debug_frame")));
Igor Laevsky03a670c2016-01-26 15:09:42 +0000248
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000249cl::opt<bool> PrintSource(
250 "source",
251 cl::desc(
Alex Denisova07169e2018-02-02 19:20:37 +0000252 "Display source inlined with disassembly. Implies disassemble object"));
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000253
254cl::alias PrintSourceShort("S", cl::desc("Alias for -source"),
255 cl::aliasopt(PrintSource));
256
257cl::opt<bool> PrintLines("line-numbers",
258 cl::desc("Display source line numbers with "
259 "disassembly. Implies disassemble object"));
260
261cl::alias PrintLinesShort("l", cl::desc("Alias for -line-numbers"),
262 cl::aliasopt(PrintLines));
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +0000263
264cl::opt<unsigned long long>
265 StartAddress("start-address", cl::desc("Disassemble beginning at address"),
266 cl::value_desc("address"), cl::init(0));
267cl::opt<unsigned long long>
268 StopAddress("stop-address", cl::desc("Stop disassembly at address"),
269 cl::value_desc("address"), cl::init(UINT64_MAX));
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000270static StringRef ToolName;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000271
Sam Parker5fba45a2017-02-08 09:44:18 +0000272typedef std::vector<std::tuple<uint64_t, StringRef, uint8_t>> SectionSymbolsTy;
273
Colin LeMahieu77804be2015-07-29 15:45:39 +0000274namespace {
Colin LeMahieufcc32762015-07-29 19:08:10 +0000275typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate;
Colin LeMahieu77804be2015-07-29 15:45:39 +0000276
277class SectionFilterIterator {
278public:
279 SectionFilterIterator(FilterPredicate P,
280 llvm::object::section_iterator const &I,
281 llvm::object::section_iterator const &E)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000282 : Predicate(std::move(P)), Iterator(I), End(E) {
Colin LeMahieu77804be2015-07-29 15:45:39 +0000283 ScanPredicate();
284 }
Benjamin Kramerac9257b2015-09-24 14:52:52 +0000285 const llvm::object::SectionRef &operator*() const { return *Iterator; }
Colin LeMahieu77804be2015-07-29 15:45:39 +0000286 SectionFilterIterator &operator++() {
287 ++Iterator;
288 ScanPredicate();
289 return *this;
290 }
291 bool operator!=(SectionFilterIterator const &Other) const {
292 return Iterator != Other.Iterator;
293 }
294
295private:
296 void ScanPredicate() {
Colin LeMahieuda1723f2015-07-29 19:21:13 +0000297 while (Iterator != End && !Predicate(*Iterator)) {
Colin LeMahieu77804be2015-07-29 15:45:39 +0000298 ++Iterator;
299 }
300 }
301 FilterPredicate Predicate;
302 llvm::object::section_iterator Iterator;
303 llvm::object::section_iterator End;
304};
305
306class SectionFilter {
307public:
308 SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000309 : Predicate(std::move(P)), Object(O) {}
Colin LeMahieu77804be2015-07-29 15:45:39 +0000310 SectionFilterIterator begin() {
311 return SectionFilterIterator(Predicate, Object.section_begin(),
312 Object.section_end());
313 }
314 SectionFilterIterator end() {
315 return SectionFilterIterator(Predicate, Object.section_end(),
316 Object.section_end());
317 }
318
319private:
320 FilterPredicate Predicate;
321 llvm::object::ObjectFile const &Object;
322};
323SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) {
David Majnemer42531262016-08-12 03:55:06 +0000324 return SectionFilter(
325 [](llvm::object::SectionRef const &S) {
326 if (FilterSections.empty())
327 return true;
328 llvm::StringRef String;
329 std::error_code error = S.getName(String);
330 if (error)
331 return false;
332 return is_contained(FilterSections, String);
333 },
334 O);
Colin LeMahieu77804be2015-07-29 15:45:39 +0000335}
336}
337
Davide Italianoccd53fe2015-08-05 07:18:31 +0000338void llvm::error(std::error_code EC) {
Mark Seaborneb03ac52014-01-25 00:32:01 +0000339 if (!EC)
Davide Italianoccd53fe2015-08-05 07:18:31 +0000340 return;
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000341 WithColor::error(errs(), ToolName)
342 << "reading file: " << EC.message() << ".\n";
Davide Italiano140af642015-12-25 18:16:45 +0000343 errs().flush();
Davide Italiano7f6c3012015-08-06 00:18:52 +0000344 exit(1);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000345}
346
Kevin Enderby42398052016-06-28 23:16:13 +0000347LLVM_ATTRIBUTE_NORETURN void llvm::error(Twine Message) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000348 WithColor::error(errs(), ToolName) << Message << ".\n";
Kevin Enderby42398052016-06-28 23:16:13 +0000349 errs().flush();
350 exit(1);
351}
352
Paul Semel007dedb2018-07-18 16:39:21 +0000353void llvm::warn(StringRef Message) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000354 WithColor::warning(errs(), ToolName) << Message << ".\n";
Paul Semel007dedb2018-07-18 16:39:21 +0000355 errs().flush();
356}
357
Davide Italianoed9d95b2015-12-29 13:41:02 +0000358LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000359 Twine Message) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000360 WithColor::error(errs(), ToolName)
361 << "'" << File << "': " << Message << ".\n";
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000362 exit(1);
363}
364
365LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
Davide Italianoed9d95b2015-12-29 13:41:02 +0000366 std::error_code EC) {
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000367 assert(EC);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000368 WithColor::error(errs(), ToolName)
369 << "'" << File << "': " << EC.message() << ".\n";
Davide Italianoccd53fe2015-08-05 07:18:31 +0000370 exit(1);
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000371}
372
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000373LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
374 llvm::Error E) {
375 assert(E);
376 std::string Buf;
377 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +0000378 logAllUnhandledErrors(std::move(E), OS);
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000379 OS.flush();
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000380 WithColor::error(errs(), ToolName) << "'" << File << "': " << Buf;
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000381 exit(1);
382}
383
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000384LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
385 StringRef FileName,
Kevin Enderby9acb1092016-05-31 20:35:34 +0000386 llvm::Error E,
387 StringRef ArchitectureName) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000388 assert(E);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000389 WithColor::error(errs(), ToolName);
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000390 if (ArchiveName != "")
391 errs() << ArchiveName << "(" << FileName << ")";
392 else
Justin Bogner31d8b7d2016-10-26 22:37:52 +0000393 errs() << "'" << FileName << "'";
Kevin Enderby9acb1092016-05-31 20:35:34 +0000394 if (!ArchitectureName.empty())
395 errs() << " (for architecture " << ArchitectureName << ")";
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000396 std::string Buf;
397 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +0000398 logAllUnhandledErrors(std::move(E), OS);
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000399 OS.flush();
Justin Bogner31d8b7d2016-10-26 22:37:52 +0000400 errs() << ": " << Buf;
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000401 exit(1);
402}
403
404LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
405 const object::Archive::Child &C,
Kevin Enderby9acb1092016-05-31 20:35:34 +0000406 llvm::Error E,
407 StringRef ArchitectureName) {
Kevin Enderbyf4586032016-07-29 17:44:13 +0000408 Expected<StringRef> NameOrErr = C.getName();
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000409 // TODO: if we have a error getting the name then it would be nice to print
410 // the index of which archive member this is and or its offset in the
411 // archive instead of "???" as the name.
Kevin Enderbyf4586032016-07-29 17:44:13 +0000412 if (!NameOrErr) {
413 consumeError(NameOrErr.takeError());
Kevin Enderby9acb1092016-05-31 20:35:34 +0000414 llvm::report_error(ArchiveName, "???", std::move(E), ArchitectureName);
Kevin Enderbyf4586032016-07-29 17:44:13 +0000415 } else
Kevin Enderby9acb1092016-05-31 20:35:34 +0000416 llvm::report_error(ArchiveName, NameOrErr.get(), std::move(E),
417 ArchitectureName);
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000418}
419
Craig Toppere6cb63e2014-04-25 04:24:47 +0000420static const Target *getTarget(const ObjectFile *Obj = nullptr) {
Michael J. Spencer2670c252011-01-20 06:39:06 +0000421 // Figure out the target triple.
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000422 llvm::Triple TheTriple("unknown-unknown-unknown");
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000423 if (TripleName.empty()) {
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000424 if (Obj) {
Vlad Tsyrklevichde620462017-09-19 02:22:48 +0000425 TheTriple = Obj->makeTriple();
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000426 }
Sam Parkerdf7c6ef2017-01-18 13:52:12 +0000427 } else {
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000428 TheTriple.setTriple(Triple::normalize(TripleName));
Vlad Tsyrklevichde620462017-09-19 02:22:48 +0000429
Sam Parkerdf7c6ef2017-01-18 13:52:12 +0000430 // Use the triple, but also try to combine with ARM build attributes.
431 if (Obj) {
432 auto Arch = Obj->getArch();
433 if (Arch == Triple::arm || Arch == Triple::armeb) {
434 Obj->setARMSubArch(TheTriple);
435 }
436 }
437 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000438
439 // Get the target specific parser.
440 std::string Error;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000441 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
442 Error);
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000443 if (!TheTarget) {
444 if (Obj)
445 report_error(Obj->getFileName(), "can't find target: " + Error);
446 else
447 error("can't find target: " + Error);
448 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000449
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000450 // Update the triple name and return the found target.
451 TripleName = TheTriple.getTriple();
452 return TheTarget;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000453}
454
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000455bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
Rafael Espindola704cd842015-07-06 15:47:43 +0000456 return a.getOffset() < b.getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +0000457}
458
Rafael Espindola37070a52015-06-03 04:48:06 +0000459template <class ELFT>
Rafael Espindola37070a52015-06-03 04:48:06 +0000460static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000461 const RelocationRef &RelRef,
Rafael Espindola37070a52015-06-03 04:48:06 +0000462 SmallVectorImpl<char> &Result) {
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000463 DataRefImpl Rel = RelRef.getRawDataRefImpl();
464
Rafael Espindola37070a52015-06-03 04:48:06 +0000465 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
466 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000467 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
468
Rafael Espindola37070a52015-06-03 04:48:06 +0000469 const ELFFile<ELFT> &EF = *Obj->getELFFile();
470
Davide Italiano6cf09262016-11-16 05:10:28 +0000471 auto SecOrErr = EF.getSection(Rel.d.a);
472 if (!SecOrErr)
473 return errorToErrorCode(SecOrErr.takeError());
Rafael Espindola6def3042015-07-01 12:56:27 +0000474 const Elf_Shdr *Sec = *SecOrErr;
Davide Italiano6cf09262016-11-16 05:10:28 +0000475 auto SymTabOrErr = EF.getSection(Sec->sh_link);
476 if (!SymTabOrErr)
477 return errorToErrorCode(SymTabOrErr.takeError());
Rafael Espindola6def3042015-07-01 12:56:27 +0000478 const Elf_Shdr *SymTab = *SymTabOrErr;
Rafael Espindola719dc7c2015-06-29 12:38:31 +0000479 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
480 SymTab->sh_type == ELF::SHT_DYNSYM);
Davide Italiano6cf09262016-11-16 05:10:28 +0000481 auto StrTabSec = EF.getSection(SymTab->sh_link);
482 if (!StrTabSec)
483 return errorToErrorCode(StrTabSec.takeError());
484 auto StrTabOrErr = EF.getStringTable(*StrTabSec);
485 if (!StrTabOrErr)
486 return errorToErrorCode(StrTabOrErr.takeError());
Rafael Espindola6a1bfb22015-06-29 14:39:25 +0000487 StringRef StrTab = *StrTabOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000488 int64_t addend = 0;
Paul Semelcb0f0432018-06-07 13:30:55 +0000489 // If there is no Symbol associated with the relocation, we set the undef
490 // boolean value to 'true'. This will prevent us from calling functions that
491 // requires the relocation to be associated with a symbol.
492 bool undef = false;
Rafael Espindola6def3042015-07-01 12:56:27 +0000493 switch (Sec->sh_type) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000494 default:
495 return object_error::parse_failed;
496 case ELF::SHT_REL: {
Rafael Espindola37070a52015-06-03 04:48:06 +0000497 // TODO: Read implicit addend from section data.
498 break;
499 }
500 case ELF::SHT_RELA: {
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000501 const Elf_Rela *ERela = Obj->getRela(Rel);
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000502 addend = ERela->r_addend;
Paul Semelcb0f0432018-06-07 13:30:55 +0000503 undef = ERela->getSymbol(false) == 0;
Rafael Espindola37070a52015-06-03 04:48:06 +0000504 break;
505 }
506 }
Rafael Espindola75d5b542015-06-03 05:14:22 +0000507 StringRef Target;
Paul Semelcb0f0432018-06-07 13:30:55 +0000508 if (!undef) {
509 symbol_iterator SI = RelRef.getSymbol();
510 const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
511 if (symb->getType() == ELF::STT_SECTION) {
512 Expected<section_iterator> SymSI = SI->getSection();
513 if (!SymSI)
514 return errorToErrorCode(SymSI.takeError());
515 const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
516 auto SecName = EF.getSectionName(SymSec);
517 if (!SecName)
518 return errorToErrorCode(SecName.takeError());
519 Target = *SecName;
520 } else {
521 Expected<StringRef> SymName = symb->getName(StrTab);
522 if (!SymName)
523 return errorToErrorCode(SymName.takeError());
524 Target = *SymName;
525 }
526 } else
527 Target = "*ABS*";
Daniel Cedermand72b9fd2018-06-01 05:31:58 +0000528
529 // Default scheme is to print Target, as well as "+ <addend>" for nonzero
530 // addend. Should be acceptable for all normal purposes.
531 std::string fmtbuf;
532 raw_string_ostream fmt(fmtbuf);
533 fmt << Target;
534 if (addend != 0)
535 fmt << (addend < 0 ? "" : "+") << addend;
536 fmt.flush();
537 Result.append(fmtbuf.begin(), fmtbuf.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000538 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000539}
540
541static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000542 const RelocationRef &Rel,
Rafael Espindola37070a52015-06-03 04:48:06 +0000543 SmallVectorImpl<char> &Result) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000544 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
545 return getRelocationValueString(ELF32LE, Rel, Result);
546 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
547 return getRelocationValueString(ELF64LE, Rel, Result);
548 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
549 return getRelocationValueString(ELF32BE, Rel, Result);
550 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
551 return getRelocationValueString(ELF64BE, Rel, Result);
552}
553
554static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
555 const RelocationRef &Rel,
556 SmallVectorImpl<char> &Result) {
557 symbol_iterator SymI = Rel.getSymbol();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000558 Expected<StringRef> SymNameOrErr = SymI->getName();
559 if (!SymNameOrErr)
560 return errorToErrorCode(SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000561 StringRef SymName = *SymNameOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000562 Result.append(SymName.begin(), SymName.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000563 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000564}
565
566static void printRelocationTargetName(const MachOObjectFile *O,
567 const MachO::any_relocation_info &RE,
568 raw_string_ostream &fmt) {
569 bool IsScattered = O->isRelocationScattered(RE);
570
571 // Target of a scattered relocation is an address. In the interest of
572 // generating pretty output, scan through the symbol table looking for a
573 // symbol that aligns with that address. If we find one, print it.
574 // Otherwise, we just print the hex address of the target.
575 if (IsScattered) {
576 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
577
578 for (const SymbolRef &Symbol : O->symbols()) {
579 std::error_code ec;
Kevin Enderby931cb652016-06-24 18:24:42 +0000580 Expected<uint64_t> Addr = Symbol.getAddress();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000581 if (!Addr)
582 report_error(O->getFileName(), Addr.takeError());
Rafael Espindolaed067c42015-07-03 18:19:00 +0000583 if (*Addr != Val)
Rafael Espindola37070a52015-06-03 04:48:06 +0000584 continue;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000585 Expected<StringRef> Name = Symbol.getName();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000586 if (!Name)
587 report_error(O->getFileName(), Name.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000588 fmt << *Name;
Rafael Espindola37070a52015-06-03 04:48:06 +0000589 return;
590 }
591
592 // If we couldn't find a symbol that this relocation refers to, try
593 // to find a section beginning instead.
Colin LeMahieu77804be2015-07-29 15:45:39 +0000594 for (const SectionRef &Section : ToolSectionFilter(*O)) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000595 std::error_code ec;
596
597 StringRef Name;
598 uint64_t Addr = Section.getAddress();
599 if (Addr != Val)
600 continue;
601 if ((ec = Section.getName(Name)))
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000602 report_error(O->getFileName(), ec);
Rafael Espindola37070a52015-06-03 04:48:06 +0000603 fmt << Name;
604 return;
605 }
606
607 fmt << format("0x%x", Val);
608 return;
609 }
610
611 StringRef S;
612 bool isExtern = O->getPlainRelocationExternal(RE);
613 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
614
Martin Storsjo8c0317d2017-07-13 17:03:02 +0000615 if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND) {
Simon Dardis38867052017-08-07 12:29:38 +0000616 fmt << format("0x%0" PRIx64, Val);
Martin Storsjo8c0317d2017-07-13 17:03:02 +0000617 return;
618 } else if (isExtern) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000619 symbol_iterator SI = O->symbol_begin();
620 advance(SI, Val);
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000621 Expected<StringRef> SOrErr = SI->getName();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000622 if (!SOrErr)
623 report_error(O->getFileName(), SOrErr.takeError());
Davide Italianoccd53fe2015-08-05 07:18:31 +0000624 S = *SOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000625 } else {
626 section_iterator SI = O->section_begin();
627 // Adjust for the fact that sections are 1-indexed.
Kevin Enderby3fc91882017-11-03 21:32:44 +0000628 if (Val == 0) {
629 fmt << "0 (?,?)";
630 return;
631 }
632 uint32_t i = Val - 1;
633 while (i != 0 && SI != O->section_end()) {
634 i--;
635 advance(SI, 1);
636 }
637 if (SI == O->section_end())
638 fmt << Val << " (?,?)";
639 else
640 SI->getName(S);
Rafael Espindola37070a52015-06-03 04:48:06 +0000641 }
642
643 fmt << S;
644}
645
Sam Clegg4df5d762017-06-27 20:40:53 +0000646static std::error_code getRelocationValueString(const WasmObjectFile *Obj,
647 const RelocationRef &RelRef,
648 SmallVectorImpl<char> &Result) {
649 const wasm::WasmRelocation& Rel = Obj->getWasmRelocation(RelRef);
Sam Cleggf676cdd2018-04-26 16:41:51 +0000650 symbol_iterator SI = RelRef.getSymbol();
Sam Clegg4df5d762017-06-27 20:40:53 +0000651 std::string fmtbuf;
652 raw_string_ostream fmt(fmtbuf);
Sam Clegg8c4b0ce2018-04-26 17:05:04 +0000653 if (SI == Obj->symbol_end()) {
654 // Not all wasm relocations have symbols associated with them.
655 // In particular R_WEBASSEMBLY_TYPE_INDEX_LEB.
Sam Cleggf676cdd2018-04-26 16:41:51 +0000656 fmt << Rel.Index;
657 } else {
Sam Clegg8c4b0ce2018-04-26 17:05:04 +0000658 Expected<StringRef> SymNameOrErr = SI->getName();
659 if (!SymNameOrErr)
660 return errorToErrorCode(SymNameOrErr.takeError());
Sam Cleggf676cdd2018-04-26 16:41:51 +0000661 StringRef SymName = *SymNameOrErr;
662 Result.append(SymName.begin(), SymName.end());
663 }
664 fmt << (Rel.Addend < 0 ? "" : "+") << Rel.Addend;
Sam Clegg4df5d762017-06-27 20:40:53 +0000665 fmt.flush();
666 Result.append(fmtbuf.begin(), fmtbuf.end());
667 return std::error_code();
668}
669
Rafael Espindola37070a52015-06-03 04:48:06 +0000670static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
671 const RelocationRef &RelRef,
672 SmallVectorImpl<char> &Result) {
673 DataRefImpl Rel = RelRef.getRawDataRefImpl();
674 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
675
676 unsigned Arch = Obj->getArch();
677
678 std::string fmtbuf;
679 raw_string_ostream fmt(fmtbuf);
680 unsigned Type = Obj->getAnyRelocationType(RE);
681 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
682
683 // Determine any addends that should be displayed with the relocation.
684 // These require decoding the relocation type, which is triple-specific.
685
686 // X86_64 has entirely custom relocation types.
687 if (Arch == Triple::x86_64) {
688 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
689
690 switch (Type) {
691 case MachO::X86_64_RELOC_GOT_LOAD:
692 case MachO::X86_64_RELOC_GOT: {
693 printRelocationTargetName(Obj, RE, fmt);
694 fmt << "@GOT";
695 if (isPCRel)
696 fmt << "PCREL";
697 break;
698 }
699 case MachO::X86_64_RELOC_SUBTRACTOR: {
700 DataRefImpl RelNext = Rel;
701 Obj->moveRelocationNext(RelNext);
702 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
703
704 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
705 // X86_64_RELOC_UNSIGNED.
706 // NOTE: Scattered relocations don't exist on x86_64.
707 unsigned RType = Obj->getAnyRelocationType(RENext);
708 if (RType != MachO::X86_64_RELOC_UNSIGNED)
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000709 report_error(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
710 "X86_64_RELOC_SUBTRACTOR.");
Rafael Espindola37070a52015-06-03 04:48:06 +0000711
712 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
713 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
714 printRelocationTargetName(Obj, RENext, fmt);
715 fmt << "-";
716 printRelocationTargetName(Obj, RE, fmt);
717 break;
718 }
719 case MachO::X86_64_RELOC_TLV:
720 printRelocationTargetName(Obj, RE, fmt);
721 fmt << "@TLV";
722 if (isPCRel)
723 fmt << "P";
724 break;
725 case MachO::X86_64_RELOC_SIGNED_1:
726 printRelocationTargetName(Obj, RE, fmt);
727 fmt << "-1";
728 break;
729 case MachO::X86_64_RELOC_SIGNED_2:
730 printRelocationTargetName(Obj, RE, fmt);
731 fmt << "-2";
732 break;
733 case MachO::X86_64_RELOC_SIGNED_4:
734 printRelocationTargetName(Obj, RE, fmt);
735 fmt << "-4";
736 break;
737 default:
738 printRelocationTargetName(Obj, RE, fmt);
739 break;
740 }
741 // X86 and ARM share some relocation types in common.
742 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
743 Arch == Triple::ppc) {
744 // Generic relocation types...
745 switch (Type) {
746 case MachO::GENERIC_RELOC_PAIR: // prints no info
Rui Ueyama7d099192015-06-09 15:20:42 +0000747 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000748 case MachO::GENERIC_RELOC_SECTDIFF: {
749 DataRefImpl RelNext = Rel;
750 Obj->moveRelocationNext(RelNext);
751 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
752
753 // X86 sect diff's must be followed by a relocation of type
754 // GENERIC_RELOC_PAIR.
755 unsigned RType = Obj->getAnyRelocationType(RENext);
756
757 if (RType != MachO::GENERIC_RELOC_PAIR)
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000758 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
759 "GENERIC_RELOC_SECTDIFF.");
Rafael Espindola37070a52015-06-03 04:48:06 +0000760
761 printRelocationTargetName(Obj, RE, fmt);
762 fmt << "-";
763 printRelocationTargetName(Obj, RENext, fmt);
764 break;
765 }
766 }
767
768 if (Arch == Triple::x86 || Arch == Triple::ppc) {
769 switch (Type) {
770 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
771 DataRefImpl RelNext = Rel;
772 Obj->moveRelocationNext(RelNext);
773 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
774
775 // X86 sect diff's must be followed by a relocation of type
776 // GENERIC_RELOC_PAIR.
777 unsigned RType = Obj->getAnyRelocationType(RENext);
778 if (RType != MachO::GENERIC_RELOC_PAIR)
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000779 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
780 "GENERIC_RELOC_LOCAL_SECTDIFF.");
Rafael Espindola37070a52015-06-03 04:48:06 +0000781
782 printRelocationTargetName(Obj, RE, fmt);
783 fmt << "-";
784 printRelocationTargetName(Obj, RENext, fmt);
785 break;
786 }
787 case MachO::GENERIC_RELOC_TLV: {
788 printRelocationTargetName(Obj, RE, fmt);
789 fmt << "@TLV";
790 if (IsPCRel)
791 fmt << "P";
792 break;
793 }
794 default:
795 printRelocationTargetName(Obj, RE, fmt);
796 }
797 } else { // ARM-specific relocations
798 switch (Type) {
799 case MachO::ARM_RELOC_HALF:
800 case MachO::ARM_RELOC_HALF_SECTDIFF: {
801 // Half relocations steal a bit from the length field to encode
802 // whether this is an upper16 or a lower16 relocation.
Martin Storsjofa5183b2017-07-13 05:54:08 +0000803 bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
Rafael Espindola37070a52015-06-03 04:48:06 +0000804
805 if (isUpper)
806 fmt << ":upper16:(";
807 else
808 fmt << ":lower16:(";
809 printRelocationTargetName(Obj, RE, fmt);
810
811 DataRefImpl RelNext = Rel;
812 Obj->moveRelocationNext(RelNext);
813 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
814
815 // ARM half relocs must be followed by a relocation of type
816 // ARM_RELOC_PAIR.
817 unsigned RType = Obj->getAnyRelocationType(RENext);
818 if (RType != MachO::ARM_RELOC_PAIR)
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000819 report_error(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
820 "ARM_RELOC_HALF");
Rafael Espindola37070a52015-06-03 04:48:06 +0000821
822 // NOTE: The half of the target virtual address is stashed in the
823 // address field of the secondary relocation, but we can't reverse
824 // engineer the constant offset from it without decoding the movw/movt
825 // instruction to find the other half in its immediate field.
826
827 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
828 // symbol/section pointer of the follow-on relocation.
829 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
830 fmt << "-";
831 printRelocationTargetName(Obj, RENext, fmt);
832 }
833
834 fmt << ")";
835 break;
836 }
837 default: { printRelocationTargetName(Obj, RE, fmt); }
838 }
839 }
840 } else
841 printRelocationTargetName(Obj, RE, fmt);
842
843 fmt.flush();
844 Result.append(fmtbuf.begin(), fmtbuf.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000845 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000846}
847
848static std::error_code getRelocationValueString(const RelocationRef &Rel,
849 SmallVectorImpl<char> &Result) {
Rafael Espindola854038e2015-06-26 14:51:16 +0000850 const ObjectFile *Obj = Rel.getObject();
Rafael Espindola37070a52015-06-03 04:48:06 +0000851 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
852 return getRelocationValueString(ELF, Rel, Result);
853 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
854 return getRelocationValueString(COFF, Rel, Result);
Sam Clegg4df5d762017-06-27 20:40:53 +0000855 if (auto *Wasm = dyn_cast<WasmObjectFile>(Obj))
856 return getRelocationValueString(Wasm, Rel, Result);
857 if (auto *MachO = dyn_cast<MachOObjectFile>(Obj))
858 return getRelocationValueString(MachO, Rel, Result);
859 llvm_unreachable("unknown object file format");
Rafael Espindola37070a52015-06-03 04:48:06 +0000860}
861
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000862/// Indicates whether this relocation should hidden when listing
Rafael Espindola0ad71d92015-06-30 03:41:26 +0000863/// relocations, usually because it is the trailing part of a multipart
864/// relocation that will be printed as part of the leading relocation.
865static bool getHidden(RelocationRef RelRef) {
866 const ObjectFile *Obj = RelRef.getObject();
867 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
868 if (!MachO)
869 return false;
870
871 unsigned Arch = MachO->getArch();
872 DataRefImpl Rel = RelRef.getRawDataRefImpl();
873 uint64_t Type = MachO->getRelocationType(Rel);
874
875 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
876 // is always hidden.
877 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
878 if (Type == MachO::GENERIC_RELOC_PAIR)
879 return true;
880 } else if (Arch == Triple::x86_64) {
881 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
882 // an X86_64_RELOC_SUBTRACTOR.
883 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
884 DataRefImpl RelPrev = Rel;
885 RelPrev.d.a--;
886 uint64_t PrevType = MachO->getRelocationType(RelPrev);
887 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
888 return true;
889 }
890 }
891
892 return false;
893}
894
Sid Manningd9f28732018-05-14 19:46:08 +0000895namespace {
896class SourcePrinter {
897protected:
898 DILineInfo OldLineInfo;
899 const ObjectFile *Obj = nullptr;
900 std::unique_ptr<symbolize::LLVMSymbolizer> Symbolizer;
901 // File name to file contents of source
902 std::unordered_map<std::string, std::unique_ptr<MemoryBuffer>> SourceCache;
903 // Mark the line endings of the cached source
904 std::unordered_map<std::string, std::vector<StringRef>> LineCache;
905
906private:
907 bool cacheSource(const DILineInfo& LineInfoFile);
908
909public:
910 SourcePrinter() = default;
911 SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch) : Obj(Obj) {
912 symbolize::LLVMSymbolizer::Options SymbolizerOpts(
913 DILineInfoSpecifier::FunctionNameKind::None, true, false, false,
914 DefaultArch);
915 Symbolizer.reset(new symbolize::LLVMSymbolizer(SymbolizerOpts));
916 }
917 virtual ~SourcePrinter() = default;
918 virtual void printSourceLine(raw_ostream &OS, uint64_t Address,
919 StringRef Delimiter = "; ");
920};
921
922bool SourcePrinter::cacheSource(const DILineInfo &LineInfo) {
923 std::unique_ptr<MemoryBuffer> Buffer;
924 if (LineInfo.Source) {
925 Buffer = MemoryBuffer::getMemBuffer(*LineInfo.Source);
926 } else {
927 auto BufferOrError = MemoryBuffer::getFile(LineInfo.FileName);
928 if (!BufferOrError)
929 return false;
930 Buffer = std::move(*BufferOrError);
931 }
932 // Chomp the file to get lines
933 size_t BufferSize = Buffer->getBufferSize();
934 const char *BufferStart = Buffer->getBufferStart();
935 for (const char *Start = BufferStart, *End = BufferStart;
936 End < BufferStart + BufferSize; End++)
937 if (*End == '\n' || End == BufferStart + BufferSize - 1 ||
938 (*End == '\r' && *(End + 1) == '\n')) {
939 LineCache[LineInfo.FileName].push_back(StringRef(Start, End - Start));
940 if (*End == '\r')
941 End++;
942 Start = End + 1;
943 }
944 SourceCache[LineInfo.FileName] = std::move(Buffer);
945 return true;
946}
947
948void SourcePrinter::printSourceLine(raw_ostream &OS, uint64_t Address,
949 StringRef Delimiter) {
950 if (!Symbolizer)
951 return;
952 DILineInfo LineInfo = DILineInfo();
953 auto ExpectecLineInfo =
954 Symbolizer->symbolizeCode(Obj->getFileName(), Address);
955 if (!ExpectecLineInfo)
956 consumeError(ExpectecLineInfo.takeError());
957 else
958 LineInfo = *ExpectecLineInfo;
959
960 if ((LineInfo.FileName == "<invalid>") || OldLineInfo.Line == LineInfo.Line ||
961 LineInfo.Line == 0)
962 return;
963
964 if (PrintLines)
965 OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line << "\n";
966 if (PrintSource) {
967 if (SourceCache.find(LineInfo.FileName) == SourceCache.end())
968 if (!cacheSource(LineInfo))
969 return;
970 auto FileBuffer = SourceCache.find(LineInfo.FileName);
971 if (FileBuffer != SourceCache.end()) {
972 auto LineBuffer = LineCache.find(LineInfo.FileName);
973 if (LineBuffer != LineCache.end()) {
974 if (LineInfo.Line > LineBuffer->second.size())
975 return;
976 // Vector begins at 0, line numbers are non-zero
977 OS << Delimiter << LineBuffer->second[LineInfo.Line - 1].ltrim()
978 << "\n";
979 }
980 }
981 }
982 OldLineInfo = LineInfo;
983}
984
985static bool isArmElf(const ObjectFile *Obj) {
986 return (Obj->isELF() &&
987 (Obj->getArch() == Triple::aarch64 ||
988 Obj->getArch() == Triple::aarch64_be ||
989 Obj->getArch() == Triple::arm || Obj->getArch() == Triple::armeb ||
990 Obj->getArch() == Triple::thumb ||
991 Obj->getArch() == Triple::thumbeb));
992}
993
994class PrettyPrinter {
995public:
996 virtual ~PrettyPrinter() = default;
997 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
998 ArrayRef<uint8_t> Bytes, uint64_t Address,
999 raw_ostream &OS, StringRef Annot,
1000 MCSubtargetInfo const &STI, SourcePrinter *SP,
1001 std::vector<RelocationRef> *Rels = nullptr) {
1002 if (SP && (PrintSource || PrintLines))
1003 SP->printSourceLine(OS, Address);
1004 if (!NoLeadingAddr)
1005 OS << format("%8" PRIx64 ":", Address);
1006 if (!NoShowRawInsn) {
1007 OS << "\t";
1008 dumpBytes(Bytes, OS);
1009 }
1010 if (MI)
1011 IP.printInst(MI, OS, "", STI);
1012 else
1013 OS << " <unknown>";
1014 }
1015};
1016PrettyPrinter PrettyPrinterInst;
1017class HexagonPrettyPrinter : public PrettyPrinter {
1018public:
1019 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
1020 raw_ostream &OS) {
1021 uint32_t opcode =
1022 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
1023 if (!NoLeadingAddr)
1024 OS << format("%8" PRIx64 ":", Address);
1025 if (!NoShowRawInsn) {
1026 OS << "\t";
1027 dumpBytes(Bytes.slice(0, 4), OS);
1028 OS << format("%08" PRIx32, opcode);
1029 }
1030 }
1031 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1032 uint64_t Address, raw_ostream &OS, StringRef Annot,
1033 MCSubtargetInfo const &STI, SourcePrinter *SP,
1034 std::vector<RelocationRef> *Rels) override {
1035 if (SP && (PrintSource || PrintLines))
1036 SP->printSourceLine(OS, Address, "");
1037 if (!MI) {
1038 printLead(Bytes, Address, OS);
1039 OS << " <unknown>";
1040 return;
1041 }
1042 std::string Buffer;
1043 {
1044 raw_string_ostream TempStream(Buffer);
1045 IP.printInst(MI, TempStream, "", STI);
1046 }
1047 StringRef Contents(Buffer);
1048 // Split off bundle attributes
1049 auto PacketBundle = Contents.rsplit('\n');
1050 // Split off first instruction from the rest
1051 auto HeadTail = PacketBundle.first.split('\n');
1052 auto Preamble = " { ";
1053 auto Separator = "";
1054 StringRef Fmt = "\t\t\t%08" PRIx64 ": ";
1055 std::vector<RelocationRef>::const_iterator rel_cur = Rels->begin();
1056 std::vector<RelocationRef>::const_iterator rel_end = Rels->end();
1057
1058 // Hexagon's packets require relocations to be inline rather than
1059 // clustered at the end of the packet.
1060 auto PrintReloc = [&]() -> void {
1061 while ((rel_cur != rel_end) && (rel_cur->getOffset() <= Address)) {
1062 if (rel_cur->getOffset() == Address) {
1063 SmallString<16> name;
1064 SmallString<32> val;
1065 rel_cur->getTypeName(name);
1066 error(getRelocationValueString(*rel_cur, val));
1067 OS << Separator << format(Fmt.data(), Address) << name << "\t" << val
1068 << "\n";
1069 return;
1070 }
1071 rel_cur++;
1072 }
1073 };
1074
1075 while(!HeadTail.first.empty()) {
1076 OS << Separator;
1077 Separator = "\n";
1078 if (SP && (PrintSource || PrintLines))
1079 SP->printSourceLine(OS, Address, "");
1080 printLead(Bytes, Address, OS);
1081 OS << Preamble;
1082 Preamble = " ";
1083 StringRef Inst;
1084 auto Duplex = HeadTail.first.split('\v');
1085 if(!Duplex.second.empty()){
1086 OS << Duplex.first;
1087 OS << "; ";
1088 Inst = Duplex.second;
1089 }
1090 else
1091 Inst = HeadTail.first;
1092 OS << Inst;
1093 HeadTail = HeadTail.second.split('\n');
1094 if (HeadTail.first.empty())
1095 OS << " } " << PacketBundle.second;
1096 PrintReloc();
1097 Bytes = Bytes.slice(4);
1098 Address += 4;
1099 }
1100 }
1101};
1102HexagonPrettyPrinter HexagonPrettyPrinterInst;
1103
1104class AMDGCNPrettyPrinter : public PrettyPrinter {
1105public:
1106 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1107 uint64_t Address, raw_ostream &OS, StringRef Annot,
1108 MCSubtargetInfo const &STI, SourcePrinter *SP,
1109 std::vector<RelocationRef> *Rels) override {
1110 if (SP && (PrintSource || PrintLines))
1111 SP->printSourceLine(OS, Address);
1112
1113 typedef support::ulittle32_t U32;
1114
1115 if (MI) {
1116 SmallString<40> InstStr;
1117 raw_svector_ostream IS(InstStr);
1118
1119 IP.printInst(MI, IS, "", STI);
1120
1121 OS << left_justify(IS.str(), 60);
1122 } else {
1123 // an unrecognized encoding - this is probably data so represent it
1124 // using the .long directive, or .byte directive if fewer than 4 bytes
1125 // remaining
1126 if (Bytes.size() >= 4) {
1127 OS << format("\t.long 0x%08" PRIx32 " ",
1128 static_cast<uint32_t>(*reinterpret_cast<const U32*>(Bytes.data())));
1129 OS.indent(42);
1130 } else {
1131 OS << format("\t.byte 0x%02" PRIx8, Bytes[0]);
1132 for (unsigned int i = 1; i < Bytes.size(); i++)
1133 OS << format(", 0x%02" PRIx8, Bytes[i]);
1134 OS.indent(55 - (6 * Bytes.size()));
1135 }
1136 }
1137
1138 OS << format("// %012" PRIX64 ": ", Address);
1139 if (Bytes.size() >=4) {
1140 for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
1141 Bytes.size() / sizeof(U32)))
1142 // D should be explicitly casted to uint32_t here as it is passed
1143 // by format to snprintf as vararg.
1144 OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D));
1145 } else {
1146 for (unsigned int i = 0; i < Bytes.size(); i++)
1147 OS << format("%02" PRIX8 " ", Bytes[i]);
1148 }
1149
1150 if (!Annot.empty())
1151 OS << "// " << Annot;
1152 }
1153};
1154AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
1155
1156class BPFPrettyPrinter : public PrettyPrinter {
1157public:
1158 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1159 uint64_t Address, raw_ostream &OS, StringRef Annot,
1160 MCSubtargetInfo const &STI, SourcePrinter *SP,
1161 std::vector<RelocationRef> *Rels) override {
1162 if (SP && (PrintSource || PrintLines))
1163 SP->printSourceLine(OS, Address);
1164 if (!NoLeadingAddr)
1165 OS << format("%8" PRId64 ":", Address / 8);
1166 if (!NoShowRawInsn) {
1167 OS << "\t";
1168 dumpBytes(Bytes, OS);
1169 }
1170 if (MI)
1171 IP.printInst(MI, OS, "", STI);
1172 else
1173 OS << " <unknown>";
1174 }
1175};
1176BPFPrettyPrinter BPFPrettyPrinterInst;
1177
1178PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
1179 switch(Triple.getArch()) {
1180 default:
1181 return PrettyPrinterInst;
1182 case Triple::hexagon:
1183 return HexagonPrettyPrinterInst;
1184 case Triple::amdgcn:
1185 return AMDGCNPrettyPrinterInst;
1186 case Triple::bpfel:
1187 case Triple::bpfeb:
1188 return BPFPrettyPrinterInst;
1189 }
1190}
1191}
1192
Sam Koltonc05d7782016-08-17 10:17:57 +00001193static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) {
1194 assert(Obj->isELF());
1195 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1196 return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1197 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1198 return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1199 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1200 return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1201 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1202 return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1203 llvm_unreachable("Unsupported binary format");
1204}
1205
Sam Parker5fba45a2017-02-08 09:44:18 +00001206template <class ELFT> static void
1207addDynamicElfSymbols(const ELFObjectFile<ELFT> *Obj,
1208 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1209 for (auto Symbol : Obj->getDynamicSymbolIterators()) {
1210 uint8_t SymbolType = Symbol.getELFType();
1211 if (SymbolType != ELF::STT_FUNC || Symbol.getSize() == 0)
1212 continue;
1213
1214 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
1215 if (!AddressOrErr)
1216 report_error(Obj->getFileName(), AddressOrErr.takeError());
1217 uint64_t Address = *AddressOrErr;
1218
1219 Expected<StringRef> Name = Symbol.getName();
1220 if (!Name)
1221 report_error(Obj->getFileName(), Name.takeError());
1222 if (Name->empty())
1223 continue;
1224
1225 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1226 if (!SectionOrErr)
1227 report_error(Obj->getFileName(), SectionOrErr.takeError());
1228 section_iterator SecI = *SectionOrErr;
1229 if (SecI == Obj->section_end())
1230 continue;
1231
1232 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1233 }
1234}
1235
1236static void
1237addDynamicElfSymbols(const ObjectFile *Obj,
1238 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1239 assert(Obj->isELF());
1240 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1241 addDynamicElfSymbols(Elf32LEObj, AllSymbols);
1242 else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1243 addDynamicElfSymbols(Elf64LEObj, AllSymbols);
1244 else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1245 addDynamicElfSymbols(Elf32BEObj, AllSymbols);
1246 else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1247 addDynamicElfSymbols(Elf64BEObj, AllSymbols);
1248 else
1249 llvm_unreachable("Unsupported binary format");
1250}
1251
Joel Galenson134cf472018-08-24 15:21:57 +00001252static void addPltEntries(const ObjectFile *Obj,
1253 std::map<SectionRef, SectionSymbolsTy> &AllSymbols,
1254 StringSaver &Saver) {
1255 Optional<SectionRef> Plt = None;
1256 for (const SectionRef &Section : Obj->sections()) {
1257 StringRef Name;
1258 if (Section.getName(Name))
1259 continue;
1260 if (Name == ".plt")
1261 Plt = Section;
1262 }
1263 if (!Plt)
1264 return;
1265 if (auto *ElfObj = dyn_cast<ELFObjectFileBase>(Obj)) {
1266 for (auto PltEntry : ElfObj->getPltAddresses()) {
1267 SymbolRef Symbol(PltEntry.first, ElfObj);
1268
1269 uint8_t SymbolType = getElfSymbolType(Obj, Symbol);
1270
1271 Expected<StringRef> NameOrErr = Symbol.getName();
1272 if (!NameOrErr)
1273 report_error(Obj->getFileName(), NameOrErr.takeError());
1274 if (NameOrErr->empty())
1275 continue;
1276 StringRef Name = Saver.save((*NameOrErr + "@plt").str());
1277
1278 AllSymbols[*Plt].emplace_back(PltEntry.second, Name, SymbolType);
1279 }
1280 }
1281}
1282
Michael J. Spencer51862b32011-10-13 22:17:18 +00001283static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001284 if (StartAddress > StopAddress)
1285 error("Start address should be less than stop address");
1286
Jim Grosbachaf9aec02012-08-07 17:53:14 +00001287 const Target *TheTarget = getTarget(Obj);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001288
Jack Carter551efd72012-08-28 19:24:49 +00001289 // Package up features to be passed to target/subtarget
Daniel Sanders1d148642016-06-16 09:17:03 +00001290 SubtargetFeatures Features = Obj->getFeatures();
Jack Carter551efd72012-08-28 19:24:49 +00001291 if (MAttrs.size()) {
Jack Carter551efd72012-08-28 19:24:49 +00001292 for (unsigned i = 0; i != MAttrs.size(); ++i)
1293 Features.AddFeature(MAttrs[i]);
Jack Carter551efd72012-08-28 19:24:49 +00001294 }
1295
Ahmed Charles56440fd2014-03-06 05:51:42 +00001296 std::unique_ptr<const MCRegisterInfo> MRI(
1297 TheTarget->createMCRegInfo(TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +00001298 if (!MRI)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001299 report_error(Obj->getFileName(), "no register info for target " +
1300 TripleName);
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001301
1302 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00001303 std::unique_ptr<const MCAsmInfo> AsmInfo(
1304 TheTarget->createMCAsmInfo(*MRI, TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +00001305 if (!AsmInfo)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001306 report_error(Obj->getFileName(), "no assembly info for target " +
1307 TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +00001308 std::unique_ptr<const MCSubtargetInfo> STI(
Daniel Sanders1d148642016-06-16 09:17:03 +00001309 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
Davide Italiano711e4952015-12-17 01:59:50 +00001310 if (!STI)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001311 report_error(Obj->getFileName(), "no subtarget info for target " +
1312 TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +00001313 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
Davide Italiano711e4952015-12-17 01:59:50 +00001314 if (!MII)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001315 report_error(Obj->getFileName(), "no instruction info for target " +
1316 TripleName);
Sam Kolton3381d7a2016-10-06 13:46:08 +00001317 MCObjectFileInfo MOFI;
1318 MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI);
1319 // FIXME: for now initialize MCObjectFileInfo with default values
Rafael Espindola9f929952017-08-02 20:32:26 +00001320 MOFI.InitMCObjectFileInfo(Triple(TripleName), false, Ctx);
Lang Hamesa1bc0f52014-04-15 04:40:56 +00001321
1322 std::unique_ptr<MCDisassembler> DisAsm(
1323 TheTarget->createMCDisassembler(*STI, Ctx));
Davide Italiano711e4952015-12-17 01:59:50 +00001324 if (!DisAsm)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001325 report_error(Obj->getFileName(), "no disassembler for target " +
1326 TripleName);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001327
Ahmed Charles56440fd2014-03-06 05:51:42 +00001328 std::unique_ptr<const MCInstrAnalysis> MIA(
1329 TheTarget->createMCInstrAnalysis(MII.get()));
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001330
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001331 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Daniel Sanders50f17232015-09-15 16:17:27 +00001332 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1333 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
Davide Italiano711e4952015-12-17 01:59:50 +00001334 if (!IP)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001335 report_error(Obj->getFileName(), "no instruction printer for target " +
1336 TripleName);
Colin LeMahieu14ec76e2015-06-07 21:07:17 +00001337 IP->setPrintImmHex(PrintImmHex);
Colin LeMahieu35436a22015-05-29 14:48:25 +00001338 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001339
Greg Fitzgerald18432272014-03-20 22:55:15 +00001340 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
1341 "\t\t\t%08" PRIx64 ": ";
1342
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001343 SourcePrinter SP(Obj, TheTarget->getName());
1344
Mark Seaborn0929d3d2014-01-25 17:38:19 +00001345 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
1346 // in RelocSecs contain the relocations for section S.
Rafael Espindola4453e42942014-06-13 03:07:50 +00001347 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +00001348 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001349 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001350 section_iterator Sec2 = Section.getRelocatedSection();
Rafael Espindolab5155a52014-02-10 20:24:04 +00001351 if (Sec2 != Obj->section_end())
Alexey Samsonov48803e52014-03-13 14:37:36 +00001352 SectionRelocMap[*Sec2].push_back(Section);
Mark Seaborn0929d3d2014-01-25 17:38:19 +00001353 }
1354
David Majnemer81afca62015-07-07 22:06:59 +00001355 // Create a mapping from virtual address to symbol name. This is used to
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001356 // pretty print the symbols while disassembling.
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001357 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
Sterling Augustinebc78b622018-06-28 18:57:13 +00001358 SectionSymbolsTy AbsoluteSymbols;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001359 for (const SymbolRef &Symbol : Obj->symbols()) {
Kevin Enderby931cb652016-06-24 18:24:42 +00001360 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001361 if (!AddressOrErr)
1362 report_error(Obj->getFileName(), AddressOrErr.takeError());
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001363 uint64_t Address = *AddressOrErr;
David Majnemer2603a8fa2015-07-09 18:11:40 +00001364
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001365 Expected<StringRef> Name = Symbol.getName();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001366 if (!Name)
1367 report_error(Obj->getFileName(), Name.takeError());
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001368 if (Name->empty())
1369 continue;
David Majnemer81afca62015-07-07 22:06:59 +00001370
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001371 Expected<section_iterator> SectionOrErr = Symbol.getSection();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001372 if (!SectionOrErr)
1373 report_error(Obj->getFileName(), SectionOrErr.takeError());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001374
Sam Koltonc05d7782016-08-17 10:17:57 +00001375 uint8_t SymbolType = ELF::STT_NOTYPE;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001376 if (Obj->isELF())
Sam Koltonc05d7782016-08-17 10:17:57 +00001377 SymbolType = getElfSymbolType(Obj, Symbol);
David Majnemer81afca62015-07-07 22:06:59 +00001378
Sterling Augustinebc78b622018-06-28 18:57:13 +00001379 section_iterator SecI = *SectionOrErr;
1380 if (SecI != Obj->section_end())
1381 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1382 else
1383 AbsoluteSymbols.emplace_back(Address, *Name, SymbolType);
1384
Sam Koltonc05d7782016-08-17 10:17:57 +00001385
David Majnemer81afca62015-07-07 22:06:59 +00001386 }
Sam Parker5fba45a2017-02-08 09:44:18 +00001387 if (AllSymbols.empty() && Obj->isELF())
1388 addDynamicElfSymbols(Obj, AllSymbols);
David Majnemer81afca62015-07-07 22:06:59 +00001389
Joel Galenson134cf472018-08-24 15:21:57 +00001390 BumpPtrAllocator A;
1391 StringSaver Saver(A);
1392 addPltEntries(Obj, AllSymbols, Saver);
1393
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001394 // Create a mapping from virtual address to section.
1395 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1396 for (SectionRef Sec : Obj->sections())
1397 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1398 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
1399
1400 // Linked executables (.exe and .dll files) typically don't include a real
1401 // symbol table but they might contain an export table.
1402 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
1403 for (const auto &ExportEntry : COFFObj->export_directories()) {
1404 StringRef Name;
1405 error(ExportEntry.getSymbolName(Name));
1406 if (Name.empty())
1407 continue;
1408 uint32_t RVA;
1409 error(ExportEntry.getExportRVA(RVA));
1410
1411 uint64_t VA = COFFObj->getImageBase() + RVA;
1412 auto Sec = std::upper_bound(
1413 SectionAddresses.begin(), SectionAddresses.end(), VA,
1414 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
1415 return LHS < RHS.first;
1416 });
1417 if (Sec != SectionAddresses.begin())
1418 --Sec;
1419 else
1420 Sec = SectionAddresses.end();
1421
1422 if (Sec != SectionAddresses.end())
Sam Koltonc05d7782016-08-17 10:17:57 +00001423 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
Sterling Augustinebc78b622018-06-28 18:57:13 +00001424 else
1425 AbsoluteSymbols.emplace_back(VA, Name, ELF::STT_NOTYPE);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001426 }
1427 }
1428
1429 // Sort all the symbols, this allows us to use a simple binary search to find
1430 // a symbol near an address.
1431 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1432 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
Sterling Augustinebc78b622018-06-28 18:57:13 +00001433 array_pod_sort(AbsoluteSymbols.begin(), AbsoluteSymbols.end());
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001434
Colin LeMahieu77804be2015-07-29 15:45:39 +00001435 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Colin LeMahieuf34933e2015-07-23 20:58:49 +00001436 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
Mark Seaborneb03ac52014-01-25 00:32:01 +00001437 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +00001438
Rafael Espindola80291272014-10-08 15:28:58 +00001439 uint64_t SectionAddr = Section.getAddress();
1440 uint64_t SectSize = Section.getSize();
David Majnemer185b5b12014-11-11 09:58:25 +00001441 if (!SectSize)
1442 continue;
Simon Atanasyan2b614e12014-02-24 22:12:11 +00001443
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001444 // Get the list of all the symbols in this section.
1445 SectionSymbolsTy &Symbols = AllSymbols[Section];
Davide Italianof0706882015-10-01 21:57:09 +00001446 std::vector<uint64_t> DataMappingSymsAddr;
1447 std::vector<uint64_t> TextMappingSymsAddr;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001448 if (isArmElf(Obj)) {
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001449 for (const auto &Symb : Symbols) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001450 uint64_t Address = std::get<0>(Symb);
1451 StringRef Name = std::get<1>(Symb);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001452 if (Name.startswith("$d"))
David Majnemer153722d2015-11-18 04:35:32 +00001453 DataMappingSymsAddr.push_back(Address - SectionAddr);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001454 if (Name.startswith("$x"))
David Majnemer153722d2015-11-18 04:35:32 +00001455 TextMappingSymsAddr.push_back(Address - SectionAddr);
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001456 if (Name.startswith("$a"))
1457 TextMappingSymsAddr.push_back(Address - SectionAddr);
1458 if (Name.startswith("$t"))
1459 TextMappingSymsAddr.push_back(Address - SectionAddr);
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001460 }
1461 }
1462
Fangrui Song0cac7262018-09-27 02:13:45 +00001463 llvm::sort(DataMappingSymsAddr);
1464 llvm::sort(TextMappingSymsAddr);
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001465
Sam Kolton3381d7a2016-10-06 13:46:08 +00001466 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1467 // AMDGPU disassembler uses symbolizer for printing labels
1468 std::unique_ptr<MCRelocationInfo> RelInfo(
1469 TheTarget->createMCRelocationInfo(TripleName, Ctx));
1470 if (RelInfo) {
1471 std::unique_ptr<MCSymbolizer> Symbolizer(
1472 TheTarget->createMCSymbolizer(
1473 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1474 DisAsm->setSymbolizer(std::move(Symbolizer));
1475 }
1476 }
1477
Michael J. Spencer51862b32011-10-13 22:17:18 +00001478 // Make a list of all the relocations for this section.
1479 std::vector<RelocationRef> Rels;
1480 if (InlineRelocs) {
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001481 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
1482 for (const RelocationRef &Reloc : RelocSec.relocations()) {
1483 Rels.push_back(Reloc);
1484 }
Michael J. Spencer51862b32011-10-13 22:17:18 +00001485 }
1486 }
1487
1488 // Sort relocations by address.
Fangrui Song0cac7262018-09-27 02:13:45 +00001489 llvm::sort(Rels, RelocAddressLess);
Michael J. Spencer51862b32011-10-13 22:17:18 +00001490
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001491 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +00001492 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001493 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +00001494 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001495 }
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001496 StringRef SectionName;
1497 error(Section.getName(SectionName));
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001498
Rafael Espindola7884c952015-06-04 15:01:05 +00001499 // If the section has no symbol at the start, just insert a dummy one.
Sam Koltonc05d7782016-08-17 10:17:57 +00001500 if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) {
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001501 Symbols.insert(
1502 Symbols.begin(),
1503 std::make_tuple(SectionAddr, SectionName,
1504 Section.isText() ? ELF::STT_FUNC : ELF::STT_OBJECT));
Sam Koltonc05d7782016-08-17 10:17:57 +00001505 }
Alp Tokere69170a2014-06-26 22:52:05 +00001506
1507 SmallString<40> Comments;
1508 raw_svector_ostream CommentStream(Comments);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001509
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001510 StringRef BytesStr;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001511 error(Section.getContents(BytesStr));
Aaron Ballman106fd7b2014-11-12 14:01:17 +00001512 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1513 BytesStr.size());
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001514
Michael J. Spencer2670c252011-01-20 06:39:06 +00001515 uint64_t Size;
1516 uint64_t Index;
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001517 bool PrintedSection = false;
Michael J. Spencer2670c252011-01-20 06:39:06 +00001518
Michael J. Spencer51862b32011-10-13 22:17:18 +00001519 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
1520 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001521 // Disassemble symbol by symbol.
1522 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001523 uint64_t Start = std::get<0>(Symbols[si]) - SectionAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001524 // The end is either the section end or the beginning of the next
1525 // symbol.
1526 uint64_t End =
Sam Koltonc05d7782016-08-17 10:17:57 +00001527 (si == se - 1) ? SectSize : std::get<0>(Symbols[si + 1]) - SectionAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001528 // Don't try to disassemble beyond the end of section contents.
1529 if (End > SectSize)
1530 End = SectSize;
Rafael Espindolae45c7402014-08-17 16:31:39 +00001531 // If this symbol has the same address as the next symbol, then skip it.
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001532 if (Start >= End)
Michael J. Spenceree84f642011-10-13 20:37:08 +00001533 continue;
1534
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001535 // Check if we need to skip symbol
1536 // Skip if the symbol's data is not between StartAddress and StopAddress
1537 if (End + SectionAddr < StartAddress ||
1538 Start + SectionAddr > StopAddress) {
1539 continue;
1540 }
1541
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001542 /// Skip if user requested specific symbols and this is not in the list
1543 if (!DisasmFuncsSet.empty() &&
1544 !DisasmFuncsSet.count(std::get<1>(Symbols[si])))
1545 continue;
1546
1547 if (!PrintedSection) {
1548 PrintedSection = true;
1549 outs() << "Disassembly of section ";
1550 if (!SegmentName.empty())
1551 outs() << SegmentName << ",";
1552 outs() << SectionName << ':';
1553 }
1554
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001555 // Stop disassembly at the stop address specified
1556 if (End + SectionAddr > StopAddress)
1557 End = StopAddress - SectionAddr;
1558
Valery Pykhtinde048052016-04-07 07:24:01 +00001559 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001560 if (std::get<2>(Symbols[si]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1561 // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)
1562 Start += 256;
1563 }
1564 if (si == se - 1 ||
1565 std::get<2>(Symbols[si + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1566 // cut trailing zeroes at the end of kernel
1567 // cut up to 256 bytes
1568 const uint64_t EndAlign = 256;
1569 const auto Limit = End - (std::min)(EndAlign, End - Start);
1570 while (End > Limit &&
1571 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1572 End -= 4;
1573 }
Valery Pykhtinde048052016-04-07 07:24:01 +00001574 }
1575
Paul Semel007dedb2018-07-18 16:39:21 +00001576 auto PrintSymbol = [](StringRef Name) {
1577 outs() << '\n' << Name << ":\n";
1578 };
1579 StringRef SymbolName = std::get<1>(Symbols[si]);
Zachary Turner030ad372018-08-20 22:18:21 +00001580 if (Demangle) {
Paul Semel007dedb2018-07-18 16:39:21 +00001581 char *DemangledSymbol = nullptr;
1582 size_t Size = 0;
Zachary Turner030ad372018-08-20 22:18:21 +00001583 int Status = -1;
1584 if (SymbolName.startswith("_Z"))
1585 DemangledSymbol = itaniumDemangle(SymbolName.data(), DemangledSymbol,
1586 &Size, &Status);
1587 else if (SymbolName.startswith("?"))
1588 DemangledSymbol = microsoftDemangle(SymbolName.data(),
1589 DemangledSymbol, &Size, &Status);
1590
1591 if (Status == 0 && DemangledSymbol)
Paul Semel007dedb2018-07-18 16:39:21 +00001592 PrintSymbol(StringRef(DemangledSymbol));
1593 else
1594 PrintSymbol(SymbolName);
1595
Zachary Turner030ad372018-08-20 22:18:21 +00001596 if (DemangledSymbol)
Paul Semel007dedb2018-07-18 16:39:21 +00001597 free(DemangledSymbol);
1598 } else
1599 PrintSymbol(SymbolName);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001600
Francis Visoiu Mistrih18346822018-04-19 17:02:57 +00001601 // Don't print raw contents of a virtual section. A virtual section
1602 // doesn't have any contents in the file.
1603 if (Section.isVirtual()) {
1604 outs() << "...\n";
1605 continue;
1606 }
1607
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001608#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +00001609 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001610#else
Mark Seaborneb03ac52014-01-25 00:32:01 +00001611 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001612#endif
1613
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001614 for (Index = Start; Index < End; Index += Size) {
1615 MCInst Inst;
Owen Andersona0c3b972011-09-15 23:38:46 +00001616
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001617 if (Index + SectionAddr < StartAddress ||
1618 Index + SectionAddr > StopAddress) {
1619 // skip byte by byte till StartAddress is reached
1620 Size = 1;
1621 continue;
1622 }
Davide Italianof0706882015-10-01 21:57:09 +00001623 // AArch64 ELF binaries can interleave data and text in the
1624 // same section. We rely on the markers introduced to
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001625 // understand what we need to dump. If the data marker is within a
1626 // function, it is denoted as a word/short etc
1627 if (isArmElf(Obj) && std::get<2>(Symbols[si]) != ELF::STT_OBJECT &&
1628 !DisassembleAll) {
Davide Italianof0706882015-10-01 21:57:09 +00001629 uint64_t Stride = 0;
1630
1631 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1632 DataMappingSymsAddr.end(), Index);
1633 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1634 // Switch to data.
1635 while (Index < End) {
1636 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1637 outs() << "\t";
1638 if (Index + 4 <= End) {
1639 Stride = 4;
1640 dumpBytes(Bytes.slice(Index, 4), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001641 outs() << "\t.word\t";
1642 uint32_t Data = 0;
1643 if (Obj->isLittleEndian()) {
1644 const auto Word =
1645 reinterpret_cast<const support::ulittle32_t *>(
1646 Bytes.data() + Index);
1647 Data = *Word;
1648 } else {
1649 const auto Word = reinterpret_cast<const support::ubig32_t *>(
1650 Bytes.data() + Index);
1651 Data = *Word;
1652 }
1653 outs() << "0x" << format("%08" PRIx32, Data);
Davide Italianof0706882015-10-01 21:57:09 +00001654 } else if (Index + 2 <= End) {
1655 Stride = 2;
1656 dumpBytes(Bytes.slice(Index, 2), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001657 outs() << "\t\t.short\t";
1658 uint16_t Data = 0;
1659 if (Obj->isLittleEndian()) {
1660 const auto Short =
1661 reinterpret_cast<const support::ulittle16_t *>(
1662 Bytes.data() + Index);
1663 Data = *Short;
1664 } else {
1665 const auto Short =
1666 reinterpret_cast<const support::ubig16_t *>(Bytes.data() +
1667 Index);
1668 Data = *Short;
1669 }
1670 outs() << "0x" << format("%04" PRIx16, Data);
Davide Italianof0706882015-10-01 21:57:09 +00001671 } else {
1672 Stride = 1;
1673 dumpBytes(Bytes.slice(Index, 1), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001674 outs() << "\t\t.byte\t";
1675 outs() << "0x" << format("%02" PRIx8, Bytes.slice(Index, 1)[0]);
Davide Italianof0706882015-10-01 21:57:09 +00001676 }
1677 Index += Stride;
1678 outs() << "\n";
1679 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1680 TextMappingSymsAddr.end(), Index);
1681 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1682 break;
1683 }
1684 }
1685 }
1686
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001687 // If there is a data symbol inside an ELF text section and we are only
1688 // disassembling text (applicable all architectures),
1689 // we are in a situation where we must print the data and not
1690 // disassemble it.
1691 if (Obj->isELF() && std::get<2>(Symbols[si]) == ELF::STT_OBJECT &&
1692 !DisassembleAll && Section.isText()) {
1693 // print out data up to 8 bytes at a time in hex and ascii
1694 uint8_t AsciiData[9] = {'\0'};
1695 uint8_t Byte;
1696 int NumBytes = 0;
1697
1698 for (Index = Start; Index < End; Index += 1) {
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001699 if (((SectionAddr + Index) < StartAddress) ||
1700 ((SectionAddr + Index) > StopAddress))
1701 continue;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001702 if (NumBytes == 0) {
1703 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1704 outs() << "\t";
1705 }
1706 Byte = Bytes.slice(Index)[0];
1707 outs() << format(" %02x", Byte);
Michael Kruse6f1da6e2018-07-26 15:31:41 +00001708 AsciiData[NumBytes] = isPrint(Byte) ? Byte : '.';
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001709
1710 uint8_t IndentOffset = 0;
1711 NumBytes++;
1712 if (Index == End - 1 || NumBytes > 8) {
1713 // Indent the space for less than 8 bytes data.
1714 // 2 spaces for byte and one for space between bytes
1715 IndentOffset = 3 * (8 - NumBytes);
1716 for (int Excess = 8 - NumBytes; Excess < 8; Excess++)
1717 AsciiData[Excess] = '\0';
1718 NumBytes = 8;
1719 }
1720 if (NumBytes == 8) {
1721 AsciiData[8] = '\0';
1722 outs() << std::string(IndentOffset, ' ') << " ";
1723 outs() << reinterpret_cast<char *>(AsciiData);
1724 outs() << '\n';
1725 NumBytes = 0;
1726 }
1727 }
1728 }
Davide Italianof0706882015-10-01 21:57:09 +00001729 if (Index >= End)
1730 break;
1731
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001732 // Disassemble a real instruction or a data when disassemble all is
1733 // provided
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001734 bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1735 SectionAddr + Index, DebugOut,
1736 CommentStream);
1737 if (Size == 0)
1738 Size = 1;
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001739
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001740 PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001741 Bytes.slice(Index, Size), SectionAddr + Index, outs(), "",
Sid Manningd9f28732018-05-14 19:46:08 +00001742 *STI, &SP, &Rels);
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001743 outs() << CommentStream.str();
1744 Comments.clear();
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001745
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001746 // Try to resolve the target of a call, tail call, etc. to a specific
1747 // symbol.
1748 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1749 MIA->isConditionalBranch(Inst))) {
1750 uint64_t Target;
1751 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1752 // In a relocatable object, the target's section must reside in
1753 // the same section as the call instruction or it is accessed
1754 // through a relocation.
1755 //
1756 // In a non-relocatable object, the target may be in any section.
1757 //
1758 // N.B. We don't walk the relocations in the relocatable case yet.
1759 auto *TargetSectionSymbols = &Symbols;
1760 if (!Obj->isRelocatableObject()) {
1761 auto SectionAddress = std::upper_bound(
1762 SectionAddresses.begin(), SectionAddresses.end(), Target,
1763 [](uint64_t LHS,
1764 const std::pair<uint64_t, SectionRef> &RHS) {
1765 return LHS < RHS.first;
1766 });
1767 if (SectionAddress != SectionAddresses.begin()) {
1768 --SectionAddress;
1769 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1770 } else {
Sterling Augustinebc78b622018-06-28 18:57:13 +00001771 TargetSectionSymbols = &AbsoluteSymbols;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001772 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001773 }
David Majnemer2603a8fa2015-07-09 18:11:40 +00001774
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001775 // Find the first symbol in the section whose offset is less than
Sterling Augustinebc78b622018-06-28 18:57:13 +00001776 // or equal to the target. If there isn't a section that contains
1777 // the target, find the nearest preceding absolute symbol.
1778 auto TargetSym = std::upper_bound(
1779 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1780 Target, [](uint64_t LHS,
1781 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1782 return LHS < std::get<0>(RHS);
1783 });
1784 if (TargetSym == TargetSectionSymbols->begin()) {
1785 TargetSectionSymbols = &AbsoluteSymbols;
1786 TargetSym = std::upper_bound(
1787 AbsoluteSymbols.begin(), AbsoluteSymbols.end(),
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001788 Target, [](uint64_t LHS,
Sam Koltonc05d7782016-08-17 10:17:57 +00001789 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
Sterling Augustinebc78b622018-06-28 18:57:13 +00001790 return LHS < std::get<0>(RHS);
1791 });
1792 }
1793 if (TargetSym != TargetSectionSymbols->begin()) {
1794 --TargetSym;
1795 uint64_t TargetAddress = std::get<0>(*TargetSym);
1796 StringRef TargetName = std::get<1>(*TargetSym);
1797 outs() << " <" << TargetName;
1798 uint64_t Disp = Target - TargetAddress;
1799 if (Disp)
1800 outs() << "+0x" << Twine::utohexstr(Disp);
1801 outs() << '>';
David Majnemer81afca62015-07-07 22:06:59 +00001802 }
1803 }
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001804 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001805 outs() << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001806
Sid Manningd9f28732018-05-14 19:46:08 +00001807 // Hexagon does this in pretty printer
1808 if (Obj->getArch() != Triple::hexagon)
1809 // Print relocation for instruction.
1810 while (rel_cur != rel_end) {
1811 bool hidden = getHidden(*rel_cur);
1812 uint64_t addr = rel_cur->getOffset();
1813 SmallString<16> name;
1814 SmallString<32> val;
Owen Andersonfa3e5202011-10-25 20:35:53 +00001815
Sid Manningd9f28732018-05-14 19:46:08 +00001816 // If this relocation is hidden, skip it.
1817 if (hidden || ((SectionAddr + addr) < StartAddress)) {
1818 ++rel_cur;
1819 continue;
1820 }
1821
1822 // Stop when rel_cur's address is past the current instruction.
1823 if (addr >= Index + Size) break;
1824 rel_cur->getTypeName(name);
1825 error(getRelocationValueString(*rel_cur, val));
1826 outs() << format(Fmt.data(), SectionAddr + addr) << name
1827 << "\t" << val << "\n";
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001828 ++rel_cur;
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001829 }
Benjamin Kramer87ee76c2011-07-20 19:37:35 +00001830 }
Michael J. Spencer2670c252011-01-20 06:39:06 +00001831 }
1832 }
1833}
1834
Kevin Enderby98da6132015-01-20 21:47:46 +00001835void llvm::PrintRelocations(const ObjectFile *Obj) {
Greg Fitzgerald18432272014-03-20 22:55:15 +00001836 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1837 "%08" PRIx64;
Rafael Espindola9219fe72016-03-21 20:59:15 +00001838 // Regular objdump doesn't print relocations in non-relocatable object
1839 // files.
1840 if (!Obj->isRelocatableObject())
1841 return;
Rafael Espindolac66d7612014-08-17 19:09:37 +00001842
Colin LeMahieu77804be2015-07-29 15:45:39 +00001843 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001844 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001845 continue;
1846 StringRef secname;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001847 error(Section.getName(secname));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001848 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001849 for (const RelocationRef &Reloc : Section.relocations()) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001850 bool hidden = getHidden(Reloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001851 uint64_t address = Reloc.getOffset();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001852 SmallString<32> relocname;
1853 SmallString<32> valuestr;
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001854 if (address < StartAddress || address > StopAddress || hidden)
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001855 continue;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001856 Reloc.getTypeName(relocname);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001857 error(getRelocationValueString(Reloc, valuestr));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001858 outs() << format(Fmt.data(), address) << " " << relocname << " "
1859 << valuestr << "\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001860 }
1861 outs() << "\n";
1862 }
1863}
1864
Paul Semelcb0f0432018-06-07 13:30:55 +00001865void llvm::PrintDynamicRelocations(const ObjectFile *Obj) {
1866
1867 // For the moment, this option is for ELF only
1868 if (!Obj->isELF())
1869 return;
1870
1871 const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj);
1872
1873 if (!Elf || Elf->getEType() != ELF::ET_DYN) {
1874 error("not a dynamic object");
1875 return;
1876 }
1877
1878 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
1879
1880 std::vector<SectionRef> DynRelSec = Obj->dynamic_relocation_sections();
1881 if (DynRelSec.empty())
1882 return;
1883
1884 outs() << "DYNAMIC RELOCATION RECORDS\n";
1885 for (const SectionRef &Section : DynRelSec) {
1886 if (Section.relocation_begin() == Section.relocation_end())
1887 continue;
1888 for (const RelocationRef &Reloc : Section.relocations()) {
1889 uint64_t address = Reloc.getOffset();
1890 SmallString<32> relocname;
1891 SmallString<32> valuestr;
1892 Reloc.getTypeName(relocname);
1893 error(getRelocationValueString(Reloc, valuestr));
1894 outs() << format(Fmt.data(), address) << " " << relocname << " "
1895 << valuestr << "\n";
1896 }
1897 }
1898}
1899
Kevin Enderby98da6132015-01-20 21:47:46 +00001900void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001901 outs() << "Sections:\n"
1902 "Idx Name Size Address Type\n";
Colin LeMahieu77804be2015-07-29 15:45:39 +00001903 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001904 StringRef Name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001905 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001906 uint64_t Address = Section.getAddress();
1907 uint64_t Size = Section.getSize();
1908 bool Text = Section.isText();
1909 bool Data = Section.isData();
1910 bool BSS = Section.isBSS();
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001911 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +00001912 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
George Rimare35e6442018-07-18 08:34:35 +00001913 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n",
George Rimarc1090da2018-07-18 09:25:36 +00001914 (unsigned)Section.getIndex(), Name.str().c_str(), Size,
1915 Address, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001916 }
1917}
1918
Kevin Enderby98da6132015-01-20 21:47:46 +00001919void llvm::PrintSectionContents(const ObjectFile *Obj) {
Rafael Espindola4453e42942014-06-13 03:07:50 +00001920 std::error_code EC;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001921 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001922 StringRef Name;
1923 StringRef Contents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001924 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001925 uint64_t BaseAddr = Section.getAddress();
David Majnemer185b5b12014-11-11 09:58:25 +00001926 uint64_t Size = Section.getSize();
1927 if (!Size)
1928 continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001929
1930 outs() << "Contents of section " << Name << ":\n";
David Majnemer185b5b12014-11-11 09:58:25 +00001931 if (Section.isBSS()) {
Alexey Samsonov209095c2013-04-16 10:53:11 +00001932 outs() << format("<skipping contents of bss section at [%04" PRIx64
David Majnemer8f6b04c2014-07-14 16:20:14 +00001933 ", %04" PRIx64 ")>\n",
1934 BaseAddr, BaseAddr + Size);
Alexey Samsonov209095c2013-04-16 10:53:11 +00001935 continue;
1936 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001937
Davide Italianoccd53fe2015-08-05 07:18:31 +00001938 error(Section.getContents(Contents));
David Majnemer8f6b04c2014-07-14 16:20:14 +00001939
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001940 // Dump out the content as hex and printable ascii characters.
1941 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer82803112012-03-10 02:04:38 +00001942 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001943 // Dump line of hex.
1944 for (std::size_t i = 0; i < 16; ++i) {
1945 if (i != 0 && i % 4 == 0)
1946 outs() << ' ';
1947 if (addr + i < end)
1948 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1949 << hexdigit(Contents[addr + i] & 0xF, true);
1950 else
1951 outs() << " ";
1952 }
1953 // Print ascii.
1954 outs() << " ";
1955 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
Michael Kruse6f1da6e2018-07-26 15:31:41 +00001956 if (isPrint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001957 outs() << Contents[addr + i];
1958 else
1959 outs() << ".";
1960 }
1961 outs() << "\n";
1962 }
1963 }
1964}
1965
Kevin Enderby9acb1092016-05-31 20:35:34 +00001966void llvm::PrintSymbolTable(const ObjectFile *o, StringRef ArchiveName,
1967 StringRef ArchitectureName) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001968 outs() << "SYMBOL TABLE:\n";
1969
Rui Ueyama4e39f712014-03-18 18:58:51 +00001970 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
Davide Italianoe85abf72015-12-20 09:54:34 +00001971 printCOFFSymbolTable(coff);
Rui Ueyama4e39f712014-03-18 18:58:51 +00001972 return;
1973 }
1974 for (const SymbolRef &Symbol : o->symbols()) {
Kevin Enderby931cb652016-06-24 18:24:42 +00001975 Expected<uint64_t> AddressOrError = Symbol.getAddress();
1976 if (!AddressOrError)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001977 report_error(ArchiveName, o->getFileName(), AddressOrError.takeError(),
1978 ArchitectureName);
Rafael Espindolaed067c42015-07-03 18:19:00 +00001979 uint64_t Address = *AddressOrError;
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001980 if ((Address < StartAddress) || (Address > StopAddress))
1981 continue;
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001982 Expected<SymbolRef::Type> TypeOrError = Symbol.getType();
1983 if (!TypeOrError)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001984 report_error(ArchiveName, o->getFileName(), TypeOrError.takeError(),
1985 ArchitectureName);
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00001986 SymbolRef::Type Type = *TypeOrError;
Rui Ueyama4e39f712014-03-18 18:58:51 +00001987 uint32_t Flags = Symbol.getFlags();
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001988 Expected<section_iterator> SectionOrErr = Symbol.getSection();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001989 if (!SectionOrErr)
1990 report_error(ArchiveName, o->getFileName(), SectionOrErr.takeError(),
1991 ArchitectureName);
Rafael Espindola8bab8892015-08-07 23:27:14 +00001992 section_iterator Section = *SectionOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001993 StringRef Name;
1994 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1995 Section->getName(Name);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001996 } else {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001997 Expected<StringRef> NameOrErr = Symbol.getName();
1998 if (!NameOrErr)
Kevin Enderby9acb1092016-05-31 20:35:34 +00001999 report_error(ArchiveName, o->getFileName(), NameOrErr.takeError(),
2000 ArchitectureName);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002001 Name = *NameOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00002002 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002003
Rui Ueyama4e39f712014-03-18 18:58:51 +00002004 bool Global = Flags & SymbolRef::SF_Global;
2005 bool Weak = Flags & SymbolRef::SF_Weak;
2006 bool Absolute = Flags & SymbolRef::SF_Absolute;
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00002007 bool Common = Flags & SymbolRef::SF_Common;
Davide Italianocd2514d2015-04-30 23:08:53 +00002008 bool Hidden = Flags & SymbolRef::SF_Hidden;
David Meyer1df4b842012-02-28 23:47:53 +00002009
Rui Ueyama4e39f712014-03-18 18:58:51 +00002010 char GlobLoc = ' ';
2011 if (Type != SymbolRef::ST_Unknown)
2012 GlobLoc = Global ? 'g' : 'l';
2013 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
2014 ? 'd' : ' ';
2015 char FileFunc = ' ';
2016 if (Type == SymbolRef::ST_File)
2017 FileFunc = 'f';
2018 else if (Type == SymbolRef::ST_Function)
2019 FileFunc = 'F';
Kristina Brooks0674f9d2018-11-11 17:47:13 +00002020 else if (Type == SymbolRef::ST_Data)
2021 FileFunc = 'O';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002022
Rui Ueyama4e39f712014-03-18 18:58:51 +00002023 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
2024 "%08" PRIx64;
Michael J. Spencerd857c1c2013-01-10 22:40:50 +00002025
Rui Ueyama4e39f712014-03-18 18:58:51 +00002026 outs() << format(Fmt, Address) << " "
2027 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
2028 << (Weak ? 'w' : ' ') // Weak?
2029 << ' ' // Constructor. Not supported yet.
2030 << ' ' // Warning. Not supported yet.
2031 << ' ' // Indirect reference to another symbol.
2032 << Debug // Debugging (d) or dynamic (D) symbol.
2033 << FileFunc // Name of function (F), file (f) or object (O).
2034 << ' ';
2035 if (Absolute) {
2036 outs() << "*ABS*";
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00002037 } else if (Common) {
2038 outs() << "*COM*";
Rui Ueyama4e39f712014-03-18 18:58:51 +00002039 } else if (Section == o->section_end()) {
2040 outs() << "*UND*";
2041 } else {
2042 if (const MachOObjectFile *MachO =
2043 dyn_cast<const MachOObjectFile>(o)) {
2044 DataRefImpl DR = Section->getRawDataRefImpl();
2045 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
2046 outs() << SegmentName << ",";
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002047 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00002048 StringRef SectionName;
Davide Italianoccd53fe2015-08-05 07:18:31 +00002049 error(Section->getName(SectionName));
Rui Ueyama4e39f712014-03-18 18:58:51 +00002050 outs() << SectionName;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002051 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00002052
2053 outs() << '\t';
Rafael Espindolaae3ac082015-06-23 18:34:25 +00002054 if (Common || isa<ELFObjectFileBase>(o)) {
Rafael Espindoladbb6bd32015-06-25 22:10:04 +00002055 uint64_t Val =
2056 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
Rafael Espindolaae3ac082015-06-23 18:34:25 +00002057 outs() << format("\t %08" PRIx64 " ", Val);
2058 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00002059
Davide Italianocd2514d2015-04-30 23:08:53 +00002060 if (Hidden) {
2061 outs() << ".hidden ";
2062 }
2063 outs() << Name
Rui Ueyama4e39f712014-03-18 18:58:51 +00002064 << '\n';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002065 }
2066}
2067
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00002068static void PrintUnwindInfo(const ObjectFile *o) {
2069 outs() << "Unwind info:\n\n";
2070
2071 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
2072 printCOFFUnwindInfo(coff);
Tim Northover4bd286a2014-08-01 13:07:19 +00002073 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
2074 printMachOUnwindInfo(MachO);
2075 else {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00002076 // TODO: Extract DWARF dump tool to objdump.
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002077 WithColor::error(errs(), ToolName)
2078 << "This operation is only currently supported "
2079 "for COFF and MachO object files.\n";
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00002080 return;
2081 }
2082}
2083
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002084void llvm::printExportsTrie(const ObjectFile *o) {
Nick Kledzikd04bc352014-08-30 00:20:14 +00002085 outs() << "Exports trie:\n";
2086 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
2087 printMachOExportsTrie(MachO);
2088 else {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002089 WithColor::error(errs(), ToolName)
2090 << "This operation is only currently supported "
2091 "for Mach-O executable files.\n";
Nick Kledzikd04bc352014-08-30 00:20:14 +00002092 return;
2093 }
2094}
2095
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002096void llvm::printRebaseTable(ObjectFile *o) {
Nick Kledzikac431442014-09-12 21:34:15 +00002097 outs() << "Rebase table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002098 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzikac431442014-09-12 21:34:15 +00002099 printMachORebaseTable(MachO);
2100 else {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002101 WithColor::error(errs(), ToolName)
2102 << "This operation is only currently supported "
2103 "for Mach-O executable files.\n";
Nick Kledzikac431442014-09-12 21:34:15 +00002104 return;
2105 }
2106}
2107
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002108void llvm::printBindTable(ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00002109 outs() << "Bind table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002110 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzik56ebef42014-09-16 01:41:51 +00002111 printMachOBindTable(MachO);
2112 else {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002113 WithColor::error(errs(), ToolName)
2114 << "This operation is only currently supported "
2115 "for Mach-O executable files.\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00002116 return;
2117 }
2118}
2119
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002120void llvm::printLazyBindTable(ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00002121 outs() << "Lazy bind table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002122 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzik56ebef42014-09-16 01:41:51 +00002123 printMachOLazyBindTable(MachO);
2124 else {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002125 WithColor::error(errs(), ToolName)
2126 << "This operation is only currently supported "
2127 "for Mach-O executable files.\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00002128 return;
2129 }
2130}
2131
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002132void llvm::printWeakBindTable(ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00002133 outs() << "Weak bind table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002134 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzik56ebef42014-09-16 01:41:51 +00002135 printMachOWeakBindTable(MachO);
2136 else {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002137 WithColor::error(errs(), ToolName)
2138 << "This operation is only currently supported "
2139 "for Mach-O executable files.\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00002140 return;
2141 }
2142}
Nick Kledzikac431442014-09-12 21:34:15 +00002143
Adrian Prantl437105a2015-07-08 02:04:15 +00002144/// Dump the raw contents of the __clangast section so the output can be piped
2145/// into llvm-bcanalyzer.
2146void llvm::printRawClangAST(const ObjectFile *Obj) {
2147 if (outs().is_displayed()) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002148 WithColor::error(errs(), ToolName)
2149 << "The -raw-clang-ast option will dump the raw binary contents of "
2150 "the clang ast section.\n"
2151 "Please redirect the output to a file or another program such as "
2152 "llvm-bcanalyzer.\n";
Adrian Prantl437105a2015-07-08 02:04:15 +00002153 return;
2154 }
2155
2156 StringRef ClangASTSectionName("__clangast");
2157 if (isa<COFFObjectFile>(Obj)) {
2158 ClangASTSectionName = "clangast";
2159 }
2160
2161 Optional<object::SectionRef> ClangASTSection;
Colin LeMahieu77804be2015-07-29 15:45:39 +00002162 for (auto Sec : ToolSectionFilter(*Obj)) {
Adrian Prantl437105a2015-07-08 02:04:15 +00002163 StringRef Name;
2164 Sec.getName(Name);
2165 if (Name == ClangASTSectionName) {
2166 ClangASTSection = Sec;
2167 break;
2168 }
2169 }
2170 if (!ClangASTSection)
2171 return;
2172
2173 StringRef ClangASTContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00002174 error(ClangASTSection.getValue().getContents(ClangASTContents));
Adrian Prantl437105a2015-07-08 02:04:15 +00002175 outs().write(ClangASTContents.data(), ClangASTContents.size());
2176}
2177
Sanjoy Das6f567a42015-06-22 18:03:02 +00002178static void printFaultMaps(const ObjectFile *Obj) {
2179 const char *FaultMapSectionName = nullptr;
2180
2181 if (isa<ELFObjectFileBase>(Obj)) {
2182 FaultMapSectionName = ".llvm_faultmaps";
2183 } else if (isa<MachOObjectFile>(Obj)) {
2184 FaultMapSectionName = "__llvm_faultmaps";
2185 } else {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002186 WithColor::error(errs(), ToolName)
2187 << "This operation is only currently supported "
2188 "for ELF and Mach-O executable files.\n";
Sanjoy Das6f567a42015-06-22 18:03:02 +00002189 return;
2190 }
2191
2192 Optional<object::SectionRef> FaultMapSection;
2193
Colin LeMahieu77804be2015-07-29 15:45:39 +00002194 for (auto Sec : ToolSectionFilter(*Obj)) {
Sanjoy Das6f567a42015-06-22 18:03:02 +00002195 StringRef Name;
2196 Sec.getName(Name);
2197 if (Name == FaultMapSectionName) {
2198 FaultMapSection = Sec;
2199 break;
2200 }
2201 }
2202
2203 outs() << "FaultMap table:\n";
2204
2205 if (!FaultMapSection.hasValue()) {
2206 outs() << "<not found>\n";
2207 return;
2208 }
2209
2210 StringRef FaultMapContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00002211 error(FaultMapSection.getValue().getContents(FaultMapContents));
Sanjoy Das6f567a42015-06-22 18:03:02 +00002212
2213 FaultMapParser FMP(FaultMapContents.bytes_begin(),
2214 FaultMapContents.bytes_end());
2215
2216 outs() << FMP;
2217}
2218
Davide Italiano1bdaa202016-09-18 04:39:15 +00002219static void printPrivateFileHeaders(const ObjectFile *o, bool onlyFirst) {
Paul Semel0913dcd2018-07-25 11:09:20 +00002220 if (o->isELF()) {
2221 printELFFileHeader(o);
2222 return printELFDynamicSection(o);
2223 }
Davide Italiano1bdaa202016-09-18 04:39:15 +00002224 if (o->isCOFF())
2225 return printCOFFFileHeader(o);
Derek Schuff2c6f75d2016-11-30 16:49:11 +00002226 if (o->isWasm())
2227 return printWasmFileHeader(o);
Davide Italiano1bdaa202016-09-18 04:39:15 +00002228 if (o->isMachO()) {
Kevin Enderby0ae163f2016-01-13 00:25:36 +00002229 printMachOFileHeader(o);
Davide Italiano1bdaa202016-09-18 04:39:15 +00002230 if (!onlyFirst)
2231 printMachOLoadCommands(o);
2232 return;
2233 }
Kevin Enderby7fa40c92016-11-16 22:17:38 +00002234 report_error(o->getFileName(), "Invalid/Unsupported object file format");
Rui Ueyamac2bed422013-09-27 21:04:00 +00002235}
2236
Paul Semeld2af4d62018-07-04 15:25:03 +00002237static void printFileHeaders(const ObjectFile *o) {
2238 if (!o->isELF() && !o->isCOFF())
2239 report_error(o->getFileName(), "Invalid/Unsupported object file format");
2240
2241 Triple::ArchType AT = o->getArch();
2242 outs() << "architecture: " << Triple::getArchTypeName(AT) << "\n";
2243 Expected<uint64_t> StartAddrOrErr = o->getStartAddress();
2244 if (!StartAddrOrErr)
2245 report_error(o->getFileName(), StartAddrOrErr.takeError());
Petar Jovanovic8d947ba2018-10-19 22:16:49 +00002246
2247 StringRef Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
2248 uint64_t Address = StartAddrOrErr.get();
Paul Semeld2af4d62018-07-04 15:25:03 +00002249 outs() << "start address: "
Petar Jovanovic8d947ba2018-10-19 22:16:49 +00002250 << "0x" << format(Fmt.data(), Address)
Paul Semeld2af4d62018-07-04 15:25:03 +00002251 << "\n";
2252}
2253
Paul Semel0dc92f62018-07-05 14:43:29 +00002254static void printArchiveChild(StringRef Filename, const Archive::Child &C) {
2255 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
2256 if (!ModeOrErr) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002257 WithColor::error(errs(), ToolName) << "ill-formed archive entry.\n";
Paul Semel0dc92f62018-07-05 14:43:29 +00002258 consumeError(ModeOrErr.takeError());
2259 return;
2260 }
2261 sys::fs::perms Mode = ModeOrErr.get();
2262 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
2263 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
2264 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
2265 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
2266 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
2267 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
2268 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
2269 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
2270 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
2271
2272 outs() << " ";
2273
2274 Expected<unsigned> UIDOrErr = C.getUID();
2275 if (!UIDOrErr)
2276 report_error(Filename, UIDOrErr.takeError());
2277 unsigned UID = UIDOrErr.get();
2278 outs() << format("%d/", UID);
2279
2280 Expected<unsigned> GIDOrErr = C.getGID();
2281 if (!GIDOrErr)
2282 report_error(Filename, GIDOrErr.takeError());
2283 unsigned GID = GIDOrErr.get();
2284 outs() << format("%-d ", GID);
2285
2286 Expected<uint64_t> Size = C.getRawSize();
2287 if (!Size)
2288 report_error(Filename, Size.takeError());
2289 outs() << format("%6" PRId64, Size.get()) << " ";
2290
2291 StringRef RawLastModified = C.getRawLastModified();
2292 unsigned Seconds;
2293 if (RawLastModified.getAsInteger(10, Seconds))
2294 outs() << "(date: \"" << RawLastModified
2295 << "\" contains non-decimal chars) ";
2296 else {
2297 // Since ctime(3) returns a 26 character string of the form:
2298 // "Sun Sep 16 01:03:52 1973\n\0"
2299 // just print 24 characters.
2300 time_t t = Seconds;
2301 outs() << format("%.24s ", ctime(&t));
2302 }
2303
2304 StringRef Name = "";
2305 Expected<StringRef> NameOrErr = C.getName();
2306 if (!NameOrErr) {
2307 consumeError(NameOrErr.takeError());
2308 Expected<StringRef> RawNameOrErr = C.getRawName();
2309 if (!RawNameOrErr)
2310 report_error(Filename, NameOrErr.takeError());
2311 Name = RawNameOrErr.get();
2312 } else {
2313 Name = NameOrErr.get();
2314 }
2315 outs() << Name << "\n";
2316}
2317
2318static void DumpObject(ObjectFile *o, const Archive *a = nullptr,
2319 const Archive::Child *c = nullptr) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002320 StringRef ArchiveName = a != nullptr ? a->getFileName() : "";
Adrian Prantl437105a2015-07-08 02:04:15 +00002321 // Avoid other output when using a raw option.
2322 if (!RawClangAST) {
2323 outs() << '\n';
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002324 if (a)
2325 outs() << a->getFileName() << "(" << o->getFileName() << ")";
2326 else
2327 outs() << o->getFileName();
2328 outs() << ":\tfile format " << o->getFileFormatName() << "\n\n";
Adrian Prantl437105a2015-07-08 02:04:15 +00002329 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00002330
James Hendersonc1608c92018-10-29 14:17:08 +00002331 if (ArchiveHeaders && !MachOOpt && c)
2332 printArchiveChild(ArchiveName, *c);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002333 if (Disassemble)
Michael J. Spencer51862b32011-10-13 22:17:18 +00002334 DisassembleObject(o, Relocations);
2335 if (Relocations && !Disassemble)
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002336 PrintRelocations(o);
Paul Semelcb0f0432018-06-07 13:30:55 +00002337 if (DynamicRelocations)
2338 PrintDynamicRelocations(o);
Nick Lewyckyfcf84622011-10-10 21:21:34 +00002339 if (SectionHeaders)
2340 PrintSectionHeaders(o);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00002341 if (SectionContents)
2342 PrintSectionContents(o);
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002343 if (SymbolTable)
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002344 PrintSymbolTable(o, ArchiveName);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00002345 if (UnwindInfo)
2346 PrintUnwindInfo(o);
Davide Italiano1bdaa202016-09-18 04:39:15 +00002347 if (PrivateHeaders || FirstPrivateHeader)
2348 printPrivateFileHeaders(o, FirstPrivateHeader);
Paul Semeld2af4d62018-07-04 15:25:03 +00002349 if (FileHeaders)
2350 printFileHeaders(o);
Nick Kledzikd04bc352014-08-30 00:20:14 +00002351 if (ExportsTrie)
2352 printExportsTrie(o);
Nick Kledzikac431442014-09-12 21:34:15 +00002353 if (Rebase)
2354 printRebaseTable(o);
Nick Kledzik56ebef42014-09-16 01:41:51 +00002355 if (Bind)
2356 printBindTable(o);
2357 if (LazyBind)
2358 printLazyBindTable(o);
2359 if (WeakBind)
2360 printWeakBindTable(o);
Adrian Prantl437105a2015-07-08 02:04:15 +00002361 if (RawClangAST)
2362 printRawClangAST(o);
Sanjoy Das6f567a42015-06-22 18:03:02 +00002363 if (PrintFaultMaps)
2364 printFaultMaps(o);
Igor Laevsky03a670c2016-01-26 15:09:42 +00002365 if (DwarfDumpType != DIDT_Null) {
Rafael Espindolac398e672017-07-19 22:27:28 +00002366 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*o);
Igor Laevsky03a670c2016-01-26 15:09:42 +00002367 // Dump the complete DWARF structure.
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00002368 DIDumpOptions DumpOpts;
2369 DumpOpts.DumpType = DwarfDumpType;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00002370 DICtx->dump(outs(), DumpOpts);
Igor Laevsky03a670c2016-01-26 15:09:42 +00002371 }
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002372}
2373
Paul Semel0dc92f62018-07-05 14:43:29 +00002374static void DumpObject(const COFFImportFile *I, const Archive *A,
2375 const Archive::Child *C = nullptr) {
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00002376 StringRef ArchiveName = A ? A->getFileName() : "";
2377
2378 // Avoid other output when using a raw option.
2379 if (!RawClangAST)
2380 outs() << '\n'
2381 << ArchiveName << "(" << I->getFileName() << ")"
2382 << ":\tfile format COFF-import-file"
2383 << "\n\n";
2384
James Hendersonc1608c92018-10-29 14:17:08 +00002385 if (ArchiveHeaders && !MachOOpt && C)
2386 printArchiveChild(ArchiveName, *C);
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00002387 if (SymbolTable)
2388 printCOFFSymbolTable(I);
2389}
2390
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +00002391/// Dump each object file in \a a;
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002392static void DumpArchive(const Archive *a) {
Mehdi Amini41af4302016-11-11 04:28:40 +00002393 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00002394 for (auto &C : a->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002395 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2396 if (!ChildOrErr) {
2397 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2398 report_error(a->getFileName(), C, std::move(E));
2399 continue;
2400 }
Rafael Espindolaae460022014-06-16 16:08:36 +00002401 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
Paul Semel0dc92f62018-07-05 14:43:29 +00002402 DumpObject(o, a, &C);
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00002403 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
Paul Semel0dc92f62018-07-05 14:43:29 +00002404 DumpObject(I, a, &C);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002405 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00002406 report_error(a->getFileName(), object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002407 }
Lang Hamesfc209622016-07-14 02:24:01 +00002408 if (Err)
2409 report_error(a->getFileName(), std::move(Err));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002410}
2411
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +00002412/// Open file and figure out how to dump it.
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002413static void DumpInput(StringRef file) {
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002414
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002415 // If we are using the Mach-O specific object file parser, then let it parse
2416 // the file and process the command line options. So the -arch flags can
2417 // be used to select specific slices, etc.
2418 if (MachOOpt) {
2419 ParseInputMachO(file);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002420 return;
2421 }
2422
2423 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00002424 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
2425 if (!BinaryOrErr)
Kevin Enderbyb34e3a12016-05-05 17:43:35 +00002426 report_error(file, BinaryOrErr.takeError());
Rafael Espindola48af1c22014-08-19 18:44:46 +00002427 Binary &Binary = *BinaryOrErr.get().getBinary();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002428
Rafael Espindola3f6481d2014-08-01 14:31:55 +00002429 if (Archive *a = dyn_cast<Archive>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002430 DumpArchive(a);
Rafael Espindola3f6481d2014-08-01 14:31:55 +00002431 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002432 DumpObject(o);
Dave Lee3fb120f2018-08-03 00:06:38 +00002433 else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Binary))
2434 ParseInputMachO(UB);
Jim Grosbachaf9aec02012-08-07 17:53:14 +00002435 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00002436 report_error(file, object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002437}
2438
Michael J. Spencer2670c252011-01-20 06:39:06 +00002439int main(int argc, char **argv) {
Rui Ueyama197194b2018-04-13 18:26:06 +00002440 InitLLVM X(argc, argv);
Michael J. Spencer2670c252011-01-20 06:39:06 +00002441
2442 // Initialize targets and assembly printers/parsers.
2443 llvm::InitializeAllTargetInfos();
Evan Cheng8c886a42011-07-22 21:58:54 +00002444 llvm::InitializeAllTargetMCs();
Michael J. Spencer2670c252011-01-20 06:39:06 +00002445 llvm::InitializeAllDisassemblers();
2446
Pete Cooper28fb4fc2012-05-03 23:20:10 +00002447 // Register the target printer for --version.
2448 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
2449
Michael J. Spencer2670c252011-01-20 06:39:06 +00002450 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
Michael J. Spencer2670c252011-01-20 06:39:06 +00002451
2452 ToolName = argv[0];
2453
2454 // Defaults to a.out if no filenames specified.
2455 if (InputFilenames.size() == 0)
2456 InputFilenames.push_back("a.out");
2457
Fangrui Song8513cd42018-06-27 20:45:11 +00002458 if (AllHeaders)
2459 PrivateHeaders = Relocations = SectionHeaders = SymbolTable = true;
2460
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00002461 if (DisassembleAll || PrintSource || PrintLines)
Colin LeMahieuf34933e2015-07-23 20:58:49 +00002462 Disassemble = true;
Paul Semel007dedb2018-07-18 16:39:21 +00002463
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002464 if (!Disassemble
2465 && !Relocations
Paul Semelcb0f0432018-06-07 13:30:55 +00002466 && !DynamicRelocations
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002467 && !SectionHeaders
2468 && !SectionContents
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00002469 && !SymbolTable
Michael J. Spencer209565db2013-01-06 03:56:49 +00002470 && !UnwindInfo
Nick Kledzikd04bc352014-08-30 00:20:14 +00002471 && !PrivateHeaders
Paul Semeld2af4d62018-07-04 15:25:03 +00002472 && !FileHeaders
Kevin Enderby0ae163f2016-01-13 00:25:36 +00002473 && !FirstPrivateHeader
Nick Kledzikac431442014-09-12 21:34:15 +00002474 && !ExportsTrie
Nick Kledzik56ebef42014-09-16 01:41:51 +00002475 && !Rebase
2476 && !Bind
2477 && !LazyBind
Kevin Enderby131d1772015-01-09 19:22:37 +00002478 && !WeakBind
Adrian Prantl437105a2015-07-08 02:04:15 +00002479 && !RawClangAST
Kevin Enderby13023a12015-01-15 23:19:11 +00002480 && !(UniversalHeaders && MachOOpt)
Paul Semel0dc92f62018-07-05 14:43:29 +00002481 && !ArchiveHeaders
Kevin Enderby69fe98d2015-01-23 18:52:17 +00002482 && !(IndirectSymbols && MachOOpt)
Kevin Enderby9a509442015-01-27 21:28:24 +00002483 && !(DataInCode && MachOOpt)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002484 && !(LinkOptHints && MachOOpt)
Kevin Enderbycd66be52015-03-11 22:06:32 +00002485 && !(InfoPlist && MachOOpt)
Kevin Enderbybc847fa2015-03-16 20:08:09 +00002486 && !(DylibsUsed && MachOOpt)
2487 && !(DylibId && MachOOpt)
Kevin Enderby0fc11822015-04-01 20:57:01 +00002488 && !(ObjcMetaData && MachOOpt)
Colin LeMahieufcc32762015-07-29 19:08:10 +00002489 && !(FilterSections.size() != 0 && MachOOpt)
Igor Laevsky03a670c2016-01-26 15:09:42 +00002490 && !PrintFaultMaps
2491 && DwarfDumpType == DIDT_Null) {
Michael J. Spencer2670c252011-01-20 06:39:06 +00002492 cl::PrintHelpMessage();
Dimitry Andrice4f5d012017-12-18 19:46:56 +00002493 return 2;
2494 }
2495
Rafael Aulerb0e4b912018-03-09 19:13:44 +00002496 DisasmFuncsSet.insert(DisassembleFunctions.begin(),
2497 DisassembleFunctions.end());
2498
Dimitry Andrice4f5d012017-12-18 19:46:56 +00002499 llvm::for_each(InputFilenames, DumpInput);
2500
2501 return EXIT_SUCCESS;
2502}