blob: ba8d3c5b8d5c0d69f8a383a81730969368b15d78 [file] [log] [blame]
Michael J. Spencer92e1deb2011-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. Spencerdd3aa9e2013-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. Spencer92e1deb2011-01-20 06:39:06 +000017//===----------------------------------------------------------------------===//
18
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000019#include "llvm-objdump.h"
Sanjoy Dase0ef46e2015-06-22 18:03:02 +000020#include "llvm/ADT/Optional.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000021#include "llvm/ADT/STLExtras.h"
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +000022#include "llvm/ADT/StringExtras.h"
Rafael Auler67fe7952018-03-09 19:13:44 +000023#include "llvm/ADT/StringSet.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000024#include "llvm/ADT/Triple.h"
Sanjoy Dasef42e112015-06-23 20:09:03 +000025#include "llvm/CodeGen/FaultMaps.h"
Igor Laevsky25574802016-01-26 15:09:42 +000026#include "llvm/DebugInfo/DWARF/DWARFContext.h"
Hemant Kulkarni502957c2016-08-15 19:49:24 +000027#include "llvm/DebugInfo/Symbolize/Symbolize.h"
Paul Semelbaea3f02018-07-18 16:39:21 +000028#include "llvm/Demangle/Demangle.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000029#include "llvm/MC/MCAsmInfo.h"
Ahmed Bougacha2c94d0f2013-05-24 00:39:57 +000030#include "llvm/MC/MCContext.h"
Benjamin Kramerb6242a82016-01-26 16:44:37 +000031#include "llvm/MC/MCDisassembler/MCDisassembler.h"
32#include "llvm/MC/MCDisassembler/MCRelocationInfo.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000033#include "llvm/MC/MCInst.h"
34#include "llvm/MC/MCInstPrinter.h"
Ahmed Bougachaef993562013-05-24 01:07:04 +000035#include "llvm/MC/MCInstrAnalysis.h"
Craig Topper17463b32012-04-02 06:09:36 +000036#include "llvm/MC/MCInstrInfo.h"
Ahmed Bougacha2c94d0f2013-05-24 00:39:57 +000037#include "llvm/MC/MCObjectFileInfo.h"
Jim Grosbachc6449b62012-03-05 19:33:20 +000038#include "llvm/MC/MCRegisterInfo.h"
Ahmed Bougachaef993562013-05-24 01:07:04 +000039#include "llvm/MC/MCSubtargetInfo.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000040#include "llvm/Object/Archive.h"
41#include "llvm/Object/COFF.h"
Saleem Abdulrasool8a836022016-08-18 16:39:19 +000042#include "llvm/Object/COFFImportFile.h"
Benjamin Kramerb6242a82016-01-26 16:44:37 +000043#include "llvm/Object/ELFObjectFile.h"
Rafael Espindolacef81b32012-12-21 03:47:03 +000044#include "llvm/Object/MachO.h"
Dave Lee58b1de42018-08-03 00:06:38 +000045#include "llvm/Object/MachOUniversal.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000046#include "llvm/Object/ObjectFile.h"
Sam Clegg08da5c52017-06-27 20:40:53 +000047#include "llvm/Object/Wasm.h"
Michael J. Spencer27781b72011-10-08 00:18:30 +000048#include "llvm/Support/Casting.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000049#include "llvm/Support/CommandLine.h"
50#include "llvm/Support/Debug.h"
Alexey Samsonov1b77d222015-06-04 18:34:11 +000051#include "llvm/Support/Errc.h"
Michael J. Spencer27781b72011-10-08 00:18:30 +000052#include "llvm/Support/FileSystem.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000053#include "llvm/Support/Format.h"
Benjamin Kramer853b0fd2011-07-25 23:04:36 +000054#include "llvm/Support/GraphWriter.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000055#include "llvm/Support/Host.h"
Rui Ueyama0b9d56a2018-04-13 18:26:06 +000056#include "llvm/Support/InitLLVM.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000057#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000058#include "llvm/Support/SourceMgr.h"
Joel Galensone47abe72018-08-24 15:21:57 +000059#include "llvm/Support/StringSaver.h"
Evan Cheng3e74d6f2011-08-24 18:08:43 +000060#include "llvm/Support/TargetRegistry.h"
61#include "llvm/Support/TargetSelect.h"
Jonas Devlieghere8e8485e2018-11-11 22:12:04 +000062#include "llvm/Support/WithColor.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000063#include "llvm/Support/raw_ostream.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000064#include <algorithm>
Benjamin Kramer81bbdfd2012-03-23 11:49:32 +000065#include <cctype>
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000066#include <cstring>
Rafael Espindolad5132f92014-06-12 17:38:55 +000067#include <system_error>
Hemant Kulkarni502957c2016-08-15 19:49:24 +000068#include <unordered_map>
Rafael Espindolaee809ac2017-07-19 22:27:28 +000069#include <utility>
Ahmed Bougacha171ac8c2013-08-21 07:29:02 +000070
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000071using namespace llvm;
72using namespace object;
73
Fangrui Song84e5dbf2018-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 Kramer0b8b7712011-09-19 17:56:04 +000080static cl::list<std::string>
81InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000082
Kevin Enderby60e9ca42015-01-07 21:02:18 +000083cl::opt<bool>
84llvm::Disassemble("disassemble",
Benjamin Kramer0b8b7712011-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 LeMahieuedbf9d72015-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 LeMahieuea805022015-07-23 20:58:49 +000095 cl::aliasopt(DisassembleAll));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000096
Zachary Turnerc04ae042018-08-20 22:18:21 +000097cl::opt<bool> llvm::Demangle("demangle", cl::desc("Demangle symbols names"),
98 cl::init(false));
Paul Semelbaea3f02018-07-18 16:39:21 +000099
100static cl::alias DemangleShort("C", cl::desc("Alias for --demangle"),
Zachary Turnerc04ae042018-08-20 22:18:21 +0000101 cl::aliasopt(llvm::Demangle));
Paul Semelbaea3f02018-07-18 16:39:21 +0000102
Rafael Auler67fe7952018-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 Enderbyc97fb732015-01-20 21:47:46 +0000109cl::opt<bool>
Kristina Brooksbb1b8952018-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. Spencer27781b72011-10-08 00:18:30 +0000115
Kevin Enderbyc97fb732015-01-20 21:47:46 +0000116cl::opt<bool>
Paul Semel3fc706582018-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 Henderson198a3ab2018-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. Spencer1e8ba3f2011-10-17 17:13:22 +0000129
Kristina Brooks6ee01632018-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 Brooksa3cc6ce2018-10-31 09:35:25 +0000132 cl::NotHidden,
Kristina Brooks6ee01632018-10-31 05:45:01 +0000133 cl::aliasopt(llvm::SymbolTable));
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000134
Kevin Enderby60e9ca42015-01-07 21:02:18 +0000135cl::opt<bool>
136llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +0000137
Kevin Enderby60e9ca42015-01-07 21:02:18 +0000138cl::opt<bool>
139llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
Nick Kledzika240fc52014-09-12 21:34:15 +0000140
Kevin Enderby60e9ca42015-01-07 21:02:18 +0000141cl::opt<bool>
142llvm::Bind("bind", cl::desc("Display mach-o binding info"));
Nick Kledzik367cf702014-09-16 01:41:51 +0000143
Kevin Enderby60e9ca42015-01-07 21:02:18 +0000144cl::opt<bool>
145llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
Nick Kledzik367cf702014-09-16 01:41:51 +0000146
Kevin Enderby60e9ca42015-01-07 21:02:18 +0000147cl::opt<bool>
148llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
Nick Kledzik367cf702014-09-16 01:41:51 +0000149
Adrian Prantl54a27682015-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 Kledzik367cf702014-09-16 01:41:51 +0000154static cl::opt<bool>
Rafael Espindolacef81b32012-12-21 03:47:03 +0000155MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000156static cl::alias
Rafael Espindolacef81b32012-12-21 03:47:03 +0000157MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
Benjamin Kramer685a2502011-07-20 19:37:35 +0000158
Benjamin Kramer0b8b7712011-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 Enderby75d423f2014-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 Enderby543abe42014-12-04 23:56:27 +0000170llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000171 "see -version for available targets"));
172
Kevin Enderbyc97fb732015-01-20 21:47:46 +0000173cl::opt<bool>
174llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
175 "headers for each section."));
Nick Lewycky023bb152011-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 LeMahieu154b3f02015-07-29 19:08:10 +0000182
Colin LeMahieuedbf9d72015-07-29 15:45:39 +0000183cl::list<std::string>
Colin LeMahieu154b3f02015-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 Lewycky023bb152011-10-10 21:21:34 +0000189
Kevin Enderby75d423f2014-08-06 23:24:41 +0000190cl::list<std::string>
191llvm::MAttrs("mattr",
Jack Carterfd6d1652012-08-28 19:24:49 +0000192 cl::CommaSeparated,
193 cl::desc("Target specific attributes"),
194 cl::value_desc("a1,+a2,-a3,..."));
195
Kevin Enderbye7938622014-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 Abdulrasool5bbd1892017-02-08 18:11:31 +0000200cl::opt<bool>
201llvm::NoLeadingAddr("no-leading-addr", cl::desc("Print no leading address"));
Eli Bendersky8b9da532012-11-20 22:57:02 +0000202
Kevin Enderbyc97fb732015-01-20 21:47:46 +0000203cl::opt<bool>
204llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
Michael J. Spencereef7b622012-12-05 20:12:35 +0000205
206static cl::alias
207UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
208 cl::aliasopt(UnwindInfo));
209
Kevin Enderby60e9ca42015-01-07 21:02:18 +0000210cl::opt<bool>
211llvm::PrivateHeaders("private-headers",
212 cl::desc("Display format specific file headers"));
Michael J. Spencerb2c064c2013-01-06 03:56:49 +0000213
Kevin Enderbyf3e60262016-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. Spencerb2c064c2013-01-06 03:56:49 +0000219static cl::alias
220PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
221 cl::aliasopt(PrivateHeaders));
222
Paul Semeld069a212018-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 LeMahieu8cc8dbc2015-06-07 21:07:17 +0000230cl::opt<bool>
Paul Semelfd466782018-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 LeMahieu8cc8dbc2015-06-07 21:07:17 +0000239 llvm::PrintImmHex("print-imm-hex",
Colin LeMahieudf06a072016-04-08 18:15:37 +0000240 cl::desc("Use hex format for immediate values"));
Colin LeMahieu8cc8dbc2015-06-07 21:07:17 +0000241
Sanjoy Dase0ef46e2015-06-22 18:03:02 +0000242cl::opt<bool> PrintFaultMaps("fault-map-section",
243 cl::desc("Display contents of faultmap section"));
244
Igor Laevsky25574802016-01-26 15:09:42 +0000245cl::opt<DIDumpType> llvm::DwarfDumpType(
246 "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"),
Jonas Devlieghere6ad43562017-09-18 14:15:57 +0000247 cl::values(clEnumValN(DIDT_DebugFrame, "frames", ".debug_frame")));
Igor Laevsky25574802016-01-26 15:09:42 +0000248
Hemant Kulkarni502957c2016-08-15 19:49:24 +0000249cl::opt<bool> PrintSource(
250 "source",
251 cl::desc(
Alex Denisov25b29aa2018-02-02 19:20:37 +0000252 "Display source inlined with disassembly. Implies disassemble object"));
Hemant Kulkarni502957c2016-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 Kulkarni11981cd2016-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>
George Rimar54820302019-01-10 14:55:26 +0000268 StopAddress("stop-address",
George Rimardaf83322019-01-15 14:03:50 +0000269 cl::desc("Stop disassembly at address"),
Hemant Kulkarni11981cd2016-09-12 17:08:22 +0000270 cl::value_desc("address"), cl::init(UINT64_MAX));
George Rimar54820302019-01-10 14:55:26 +0000271
George Rimardaf83322019-01-15 14:03:50 +0000272cl::opt<bool> DisassembleZeroes(
273 "disassemble-zeroes",
274 cl::desc("Do not skip blocks of zeroes when disassembling"));
George Rimar54820302019-01-10 14:55:26 +0000275cl::alias DisassembleZeroesShort("z",
276 cl::desc("Alias for --disassemble-zeroes"),
277 cl::aliasopt(DisassembleZeroes));
278
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000279static StringRef ToolName;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000280
Sam Parker3bfb1e82017-02-08 09:44:18 +0000281typedef std::vector<std::tuple<uint64_t, StringRef, uint8_t>> SectionSymbolsTy;
282
Colin LeMahieuedbf9d72015-07-29 15:45:39 +0000283namespace {
Colin LeMahieu154b3f02015-07-29 19:08:10 +0000284typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate;
Colin LeMahieuedbf9d72015-07-29 15:45:39 +0000285
286class SectionFilterIterator {
287public:
288 SectionFilterIterator(FilterPredicate P,
289 llvm::object::section_iterator const &I,
290 llvm::object::section_iterator const &E)
Benjamin Kramer14aae012016-05-27 14:27:24 +0000291 : Predicate(std::move(P)), Iterator(I), End(E) {
Colin LeMahieuedbf9d72015-07-29 15:45:39 +0000292 ScanPredicate();
293 }
Benjamin Kramercdac3312015-09-24 14:52:52 +0000294 const llvm::object::SectionRef &operator*() const { return *Iterator; }
Colin LeMahieuedbf9d72015-07-29 15:45:39 +0000295 SectionFilterIterator &operator++() {
296 ++Iterator;
297 ScanPredicate();
298 return *this;
299 }
300 bool operator!=(SectionFilterIterator const &Other) const {
301 return Iterator != Other.Iterator;
302 }
303
304private:
305 void ScanPredicate() {
Colin LeMahieu55e9a412015-07-29 19:21:13 +0000306 while (Iterator != End && !Predicate(*Iterator)) {
Colin LeMahieuedbf9d72015-07-29 15:45:39 +0000307 ++Iterator;
308 }
309 }
310 FilterPredicate Predicate;
311 llvm::object::section_iterator Iterator;
312 llvm::object::section_iterator End;
313};
314
315class SectionFilter {
316public:
317 SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O)
Benjamin Kramer14aae012016-05-27 14:27:24 +0000318 : Predicate(std::move(P)), Object(O) {}
Colin LeMahieuedbf9d72015-07-29 15:45:39 +0000319 SectionFilterIterator begin() {
320 return SectionFilterIterator(Predicate, Object.section_begin(),
321 Object.section_end());
322 }
323 SectionFilterIterator end() {
324 return SectionFilterIterator(Predicate, Object.section_end(),
325 Object.section_end());
326 }
327
328private:
329 FilterPredicate Predicate;
330 llvm::object::ObjectFile const &Object;
331};
332SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) {
David Majnemer2d62ce62016-08-12 03:55:06 +0000333 return SectionFilter(
334 [](llvm::object::SectionRef const &S) {
335 if (FilterSections.empty())
336 return true;
337 llvm::StringRef String;
338 std::error_code error = S.getName(String);
339 if (error)
340 return false;
341 return is_contained(FilterSections, String);
342 },
343 O);
Colin LeMahieuedbf9d72015-07-29 15:45:39 +0000344}
345}
346
Davide Italiano281c1b02015-08-05 07:18:31 +0000347void llvm::error(std::error_code EC) {
Mark Seaborn2760cc22014-01-25 00:32:01 +0000348 if (!EC)
Davide Italiano281c1b02015-08-05 07:18:31 +0000349 return;
Jonas Devlieghere8e8485e2018-11-11 22:12:04 +0000350 WithColor::error(errs(), ToolName)
351 << "reading file: " << EC.message() << ".\n";
Davide Italiano8e798f82015-12-25 18:16:45 +0000352 errs().flush();
Davide Italiano0de20882015-08-06 00:18:52 +0000353 exit(1);
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000354}
355
Kevin Enderbyc827f2c2016-06-28 23:16:13 +0000356LLVM_ATTRIBUTE_NORETURN void llvm::error(Twine Message) {
Jonas Devlieghere8e8485e2018-11-11 22:12:04 +0000357 WithColor::error(errs(), ToolName) << Message << ".\n";
Kevin Enderbyc827f2c2016-06-28 23:16:13 +0000358 errs().flush();
359 exit(1);
360}
361
Paul Semelbaea3f02018-07-18 16:39:21 +0000362void llvm::warn(StringRef Message) {
Jonas Devlieghere8e8485e2018-11-11 22:12:04 +0000363 WithColor::warning(errs(), ToolName) << Message << ".\n";
Paul Semelbaea3f02018-07-18 16:39:21 +0000364 errs().flush();
365}
366
Davide Italianoec0fb282015-12-29 13:41:02 +0000367LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
Kevin Enderbyfbd189d2016-11-16 22:17:38 +0000368 Twine Message) {
Jonas Devlieghere8e8485e2018-11-11 22:12:04 +0000369 WithColor::error(errs(), ToolName)
370 << "'" << File << "': " << Message << ".\n";
Kevin Enderbyfbd189d2016-11-16 22:17:38 +0000371 exit(1);
372}
373
374LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
Davide Italianoec0fb282015-12-29 13:41:02 +0000375 std::error_code EC) {
Alexey Samsonov1b77d222015-06-04 18:34:11 +0000376 assert(EC);
Jonas Devlieghere8e8485e2018-11-11 22:12:04 +0000377 WithColor::error(errs(), ToolName)
378 << "'" << File << "': " << EC.message() << ".\n";
Davide Italiano281c1b02015-08-05 07:18:31 +0000379 exit(1);
Alexey Samsonov1b77d222015-06-04 18:34:11 +0000380}
381
Kevin Enderbyc6bf9be2016-04-06 22:14:09 +0000382LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
383 llvm::Error E) {
384 assert(E);
385 std::string Buf;
386 raw_string_ostream OS(Buf);
Jonas Devlieghere686dfe32018-11-11 01:46:03 +0000387 logAllUnhandledErrors(std::move(E), OS);
Kevin Enderbyc6bf9be2016-04-06 22:14:09 +0000388 OS.flush();
Jonas Devlieghere8e8485e2018-11-11 22:12:04 +0000389 WithColor::error(errs(), ToolName) << "'" << File << "': " << Buf;
Kevin Enderbyc6bf9be2016-04-06 22:14:09 +0000390 exit(1);
391}
392
Kevin Enderby77be0942016-05-17 17:10:12 +0000393LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
394 StringRef FileName,
Kevin Enderbye9ddf3a2016-05-31 20:35:34 +0000395 llvm::Error E,
396 StringRef ArchitectureName) {
Kevin Enderby77be0942016-05-17 17:10:12 +0000397 assert(E);
Jonas Devlieghere8e8485e2018-11-11 22:12:04 +0000398 WithColor::error(errs(), ToolName);
Kevin Enderby77be0942016-05-17 17:10:12 +0000399 if (ArchiveName != "")
400 errs() << ArchiveName << "(" << FileName << ")";
401 else
Justin Bogner403d9062016-10-26 22:37:52 +0000402 errs() << "'" << FileName << "'";
Kevin Enderbye9ddf3a2016-05-31 20:35:34 +0000403 if (!ArchitectureName.empty())
404 errs() << " (for architecture " << ArchitectureName << ")";
Kevin Enderby77be0942016-05-17 17:10:12 +0000405 std::string Buf;
406 raw_string_ostream OS(Buf);
Jonas Devlieghere686dfe32018-11-11 01:46:03 +0000407 logAllUnhandledErrors(std::move(E), OS);
Kevin Enderby77be0942016-05-17 17:10:12 +0000408 OS.flush();
Justin Bogner403d9062016-10-26 22:37:52 +0000409 errs() << ": " << Buf;
Kevin Enderby77be0942016-05-17 17:10:12 +0000410 exit(1);
411}
412
413LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
414 const object::Archive::Child &C,
Kevin Enderbye9ddf3a2016-05-31 20:35:34 +0000415 llvm::Error E,
416 StringRef ArchitectureName) {
Kevin Enderby2a715172016-07-29 17:44:13 +0000417 Expected<StringRef> NameOrErr = C.getName();
Kevin Enderby77be0942016-05-17 17:10:12 +0000418 // TODO: if we have a error getting the name then it would be nice to print
419 // the index of which archive member this is and or its offset in the
420 // archive instead of "???" as the name.
Kevin Enderby2a715172016-07-29 17:44:13 +0000421 if (!NameOrErr) {
422 consumeError(NameOrErr.takeError());
Kevin Enderbye9ddf3a2016-05-31 20:35:34 +0000423 llvm::report_error(ArchiveName, "???", std::move(E), ArchitectureName);
Kevin Enderby2a715172016-07-29 17:44:13 +0000424 } else
Kevin Enderbye9ddf3a2016-05-31 20:35:34 +0000425 llvm::report_error(ArchiveName, NameOrErr.get(), std::move(E),
426 ArchitectureName);
Kevin Enderby77be0942016-05-17 17:10:12 +0000427}
428
Craig Topper573faec2014-04-25 04:24:47 +0000429static const Target *getTarget(const ObjectFile *Obj = nullptr) {
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000430 // Figure out the target triple.
Kevin Enderby9ed9e5d2012-05-08 23:38:45 +0000431 llvm::Triple TheTriple("unknown-unknown-unknown");
Michael J. Spencerd11699d2011-01-20 07:22:04 +0000432 if (TripleName.empty()) {
George Rimar45d116d2019-01-15 09:19:18 +0000433 if (Obj)
Vlad Tsyrklevichb261c462017-09-19 02:22:48 +0000434 TheTriple = Obj->makeTriple();
Sam Parkeraa967632017-01-18 13:52:12 +0000435 } else {
Kevin Enderby9ed9e5d2012-05-08 23:38:45 +0000436 TheTriple.setTriple(Triple::normalize(TripleName));
Vlad Tsyrklevichb261c462017-09-19 02:22:48 +0000437
Sam Parkeraa967632017-01-18 13:52:12 +0000438 // Use the triple, but also try to combine with ARM build attributes.
439 if (Obj) {
440 auto Arch = Obj->getArch();
George Rimar45d116d2019-01-15 09:19:18 +0000441 if (Arch == Triple::arm || Arch == Triple::armeb)
Sam Parkeraa967632017-01-18 13:52:12 +0000442 Obj->setARMSubArch(TheTriple);
Sam Parkeraa967632017-01-18 13:52:12 +0000443 }
444 }
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000445
446 // Get the target specific parser.
447 std::string Error;
Kevin Enderby9ed9e5d2012-05-08 23:38:45 +0000448 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
449 Error);
Kevin Enderbyfbd189d2016-11-16 22:17:38 +0000450 if (!TheTarget) {
451 if (Obj)
452 report_error(Obj->getFileName(), "can't find target: " + Error);
453 else
454 error("can't find target: " + Error);
455 }
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000456
Kevin Enderby9ed9e5d2012-05-08 23:38:45 +0000457 // Update the triple name and return the found target.
458 TripleName = TheTriple.getTriple();
459 return TheTarget;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000460}
461
George Rimar45d116d2019-01-15 09:19:18 +0000462bool llvm::isRelocAddressLess(RelocationRef A, RelocationRef B) {
463 return A.getOffset() < B.getOffset();
Michael J. Spencer942eb002011-10-13 22:17:18 +0000464}
465
George Rimar927407d2018-12-19 10:29:35 +0000466static std::string demangle(StringRef Name) {
467 char *Demangled = nullptr;
468 if (Name.startswith("_Z"))
469 Demangled = itaniumDemangle(Name.data(), Demangled, nullptr, nullptr);
470 else if (Name.startswith("?"))
471 Demangled = microsoftDemangle(Name.data(), Demangled, nullptr, nullptr);
472
473 if (!Demangled)
474 return Name;
475
476 std::string Ret = Demangled;
477 free(Demangled);
478 return Ret;
479}
480
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000481template <class ELFT>
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000482static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
Rafael Espindolae03b9f52015-08-10 20:50:40 +0000483 const RelocationRef &RelRef,
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000484 SmallVectorImpl<char> &Result) {
485 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
486 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
Rafael Espindolaab6b4cf2015-07-02 14:21:38 +0000487 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
488
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000489 const ELFFile<ELFT> &EF = *Obj->getELFFile();
George Rimar45d116d2019-01-15 09:19:18 +0000490 DataRefImpl Rel = RelRef.getRawDataRefImpl();
Davide Italiano63830bc2016-11-16 05:10:28 +0000491 auto SecOrErr = EF.getSection(Rel.d.a);
492 if (!SecOrErr)
493 return errorToErrorCode(SecOrErr.takeError());
Rafael Espindoladf3edb62015-07-01 12:56:27 +0000494 const Elf_Shdr *Sec = *SecOrErr;
Davide Italiano63830bc2016-11-16 05:10:28 +0000495 auto SymTabOrErr = EF.getSection(Sec->sh_link);
496 if (!SymTabOrErr)
497 return errorToErrorCode(SymTabOrErr.takeError());
Rafael Espindoladf3edb62015-07-01 12:56:27 +0000498 const Elf_Shdr *SymTab = *SymTabOrErr;
Rafael Espindolae8f07a72015-06-29 12:38:31 +0000499 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
500 SymTab->sh_type == ELF::SHT_DYNSYM);
Davide Italiano63830bc2016-11-16 05:10:28 +0000501 auto StrTabSec = EF.getSection(SymTab->sh_link);
502 if (!StrTabSec)
503 return errorToErrorCode(StrTabSec.takeError());
504 auto StrTabOrErr = EF.getStringTable(*StrTabSec);
505 if (!StrTabOrErr)
506 return errorToErrorCode(StrTabOrErr.takeError());
Rafael Espindola9a6c9022015-06-29 14:39:25 +0000507 StringRef StrTab = *StrTabOrErr;
George Rimar45d116d2019-01-15 09:19:18 +0000508 int64_t Addend = 0;
Paul Semel3fc706582018-06-07 13:30:55 +0000509 // If there is no Symbol associated with the relocation, we set the undef
510 // boolean value to 'true'. This will prevent us from calling functions that
511 // requires the relocation to be associated with a symbol.
George Rimar45d116d2019-01-15 09:19:18 +0000512 bool Undef = false;
Rafael Espindoladf3edb62015-07-01 12:56:27 +0000513 switch (Sec->sh_type) {
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000514 default:
515 return object_error::parse_failed;
516 case ELF::SHT_REL: {
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000517 // TODO: Read implicit addend from section data.
518 break;
519 }
520 case ELF::SHT_RELA: {
Rafael Espindolaab6b4cf2015-07-02 14:21:38 +0000521 const Elf_Rela *ERela = Obj->getRela(Rel);
George Rimar45d116d2019-01-15 09:19:18 +0000522 Addend = ERela->r_addend;
523 Undef = ERela->getSymbol(false) == 0;
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000524 break;
525 }
526 }
George Rimar92b052b2018-12-19 10:21:45 +0000527 std::string Target;
George Rimar45d116d2019-01-15 09:19:18 +0000528 if (!Undef) {
Paul Semel3fc706582018-06-07 13:30:55 +0000529 symbol_iterator SI = RelRef.getSymbol();
530 const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
531 if (symb->getType() == ELF::STT_SECTION) {
532 Expected<section_iterator> SymSI = SI->getSection();
533 if (!SymSI)
534 return errorToErrorCode(SymSI.takeError());
535 const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
536 auto SecName = EF.getSectionName(SymSec);
537 if (!SecName)
538 return errorToErrorCode(SecName.takeError());
539 Target = *SecName;
540 } else {
541 Expected<StringRef> SymName = symb->getName(StrTab);
542 if (!SymName)
543 return errorToErrorCode(SymName.takeError());
George Rimar96c60ea2018-12-19 10:44:49 +0000544 if (Demangle)
545 Target = demangle(*SymName);
546 else
547 Target = *SymName;
Paul Semel3fc706582018-06-07 13:30:55 +0000548 }
549 } else
550 Target = "*ABS*";
Daniel Cederman86986e72018-06-01 05:31:58 +0000551
552 // Default scheme is to print Target, as well as "+ <addend>" for nonzero
553 // addend. Should be acceptable for all normal purposes.
George Rimar45d116d2019-01-15 09:19:18 +0000554 std::string FmtBuf;
555 raw_string_ostream Fmt(FmtBuf);
556 Fmt << Target;
557 if (Addend != 0)
558 Fmt << (Addend < 0 ? "" : "+") << Addend;
559 Fmt.flush();
560 Result.append(FmtBuf.begin(), FmtBuf.end());
Rui Ueyamaeae46732015-06-09 15:20:42 +0000561 return std::error_code();
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000562}
563
564static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
Rafael Espindolae03b9f52015-08-10 20:50:40 +0000565 const RelocationRef &Rel,
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000566 SmallVectorImpl<char> &Result) {
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000567 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
568 return getRelocationValueString(ELF32LE, Rel, Result);
569 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
570 return getRelocationValueString(ELF64LE, Rel, Result);
571 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
572 return getRelocationValueString(ELF32BE, Rel, Result);
573 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
574 return getRelocationValueString(ELF64BE, Rel, Result);
575}
576
577static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
578 const RelocationRef &Rel,
579 SmallVectorImpl<char> &Result) {
580 symbol_iterator SymI = Rel.getSymbol();
Kevin Enderby813e0cf2016-04-20 21:24:34 +0000581 Expected<StringRef> SymNameOrErr = SymI->getName();
582 if (!SymNameOrErr)
583 return errorToErrorCode(SymNameOrErr.takeError());
Rafael Espindola8a806412015-07-02 20:55:21 +0000584 StringRef SymName = *SymNameOrErr;
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000585 Result.append(SymName.begin(), SymName.end());
Rui Ueyamaeae46732015-06-09 15:20:42 +0000586 return std::error_code();
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000587}
588
589static void printRelocationTargetName(const MachOObjectFile *O,
590 const MachO::any_relocation_info &RE,
George Rimar45d116d2019-01-15 09:19:18 +0000591 raw_string_ostream &Fmt) {
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000592 // Target of a scattered relocation is an address. In the interest of
593 // generating pretty output, scan through the symbol table looking for a
594 // symbol that aligns with that address. If we find one, print it.
595 // Otherwise, we just print the hex address of the target.
George Rimar45d116d2019-01-15 09:19:18 +0000596 if (O->isRelocationScattered(RE)) {
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000597 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
598
599 for (const SymbolRef &Symbol : O->symbols()) {
Kevin Enderby317de7c2016-06-24 18:24:42 +0000600 Expected<uint64_t> Addr = Symbol.getAddress();
Kevin Enderbyfbd189d2016-11-16 22:17:38 +0000601 if (!Addr)
602 report_error(O->getFileName(), Addr.takeError());
Rafael Espindola5954faa2015-07-03 18:19:00 +0000603 if (*Addr != Val)
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000604 continue;
Kevin Enderby813e0cf2016-04-20 21:24:34 +0000605 Expected<StringRef> Name = Symbol.getName();
Kevin Enderbyfbd189d2016-11-16 22:17:38 +0000606 if (!Name)
607 report_error(O->getFileName(), Name.takeError());
George Rimar45d116d2019-01-15 09:19:18 +0000608 Fmt << *Name;
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000609 return;
610 }
611
612 // If we couldn't find a symbol that this relocation refers to, try
613 // to find a section beginning instead.
Colin LeMahieuedbf9d72015-07-29 15:45:39 +0000614 for (const SectionRef &Section : ToolSectionFilter(*O)) {
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000615 std::error_code ec;
616
617 StringRef Name;
618 uint64_t Addr = Section.getAddress();
619 if (Addr != Val)
620 continue;
621 if ((ec = Section.getName(Name)))
Kevin Enderbyfbd189d2016-11-16 22:17:38 +0000622 report_error(O->getFileName(), ec);
George Rimar45d116d2019-01-15 09:19:18 +0000623 Fmt << Name;
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000624 return;
625 }
626
George Rimar45d116d2019-01-15 09:19:18 +0000627 Fmt << format("0x%x", Val);
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000628 return;
629 }
630
631 StringRef S;
632 bool isExtern = O->getPlainRelocationExternal(RE);
633 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
634
Martin Storsjo5dbda1e2017-07-13 17:03:02 +0000635 if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND) {
George Rimar45d116d2019-01-15 09:19:18 +0000636 Fmt << format("0x%0" PRIx64, Val);
Martin Storsjo5dbda1e2017-07-13 17:03:02 +0000637 return;
George Rimar45d116d2019-01-15 09:19:18 +0000638 }
639
640 if (isExtern) {
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000641 symbol_iterator SI = O->symbol_begin();
642 advance(SI, Val);
Kevin Enderby813e0cf2016-04-20 21:24:34 +0000643 Expected<StringRef> SOrErr = SI->getName();
Kevin Enderbyfbd189d2016-11-16 22:17:38 +0000644 if (!SOrErr)
645 report_error(O->getFileName(), SOrErr.takeError());
Davide Italiano281c1b02015-08-05 07:18:31 +0000646 S = *SOrErr;
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000647 } else {
648 section_iterator SI = O->section_begin();
649 // Adjust for the fact that sections are 1-indexed.
Kevin Enderbyce8f24e2017-11-03 21:32:44 +0000650 if (Val == 0) {
George Rimar45d116d2019-01-15 09:19:18 +0000651 Fmt << "0 (?,?)";
Kevin Enderbyce8f24e2017-11-03 21:32:44 +0000652 return;
653 }
George Rimar45d116d2019-01-15 09:19:18 +0000654 uint32_t I = Val - 1;
655 while (I != 0 && SI != O->section_end()) {
656 --I;
Kevin Enderbyce8f24e2017-11-03 21:32:44 +0000657 advance(SI, 1);
658 }
659 if (SI == O->section_end())
George Rimar45d116d2019-01-15 09:19:18 +0000660 Fmt << Val << " (?,?)";
Kevin Enderbyce8f24e2017-11-03 21:32:44 +0000661 else
662 SI->getName(S);
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000663 }
664
George Rimar45d116d2019-01-15 09:19:18 +0000665 Fmt << S;
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000666}
667
Sam Clegg08da5c52017-06-27 20:40:53 +0000668static std::error_code getRelocationValueString(const WasmObjectFile *Obj,
669 const RelocationRef &RelRef,
670 SmallVectorImpl<char> &Result) {
671 const wasm::WasmRelocation& Rel = Obj->getWasmRelocation(RelRef);
Sam Clegg588fa1c2018-04-26 16:41:51 +0000672 symbol_iterator SI = RelRef.getSymbol();
George Rimar45d116d2019-01-15 09:19:18 +0000673 std::string FmtBuf;
674 raw_string_ostream Fmt(FmtBuf);
Sam Cleggcc3b83d2018-04-26 17:05:04 +0000675 if (SI == Obj->symbol_end()) {
676 // Not all wasm relocations have symbols associated with them.
677 // In particular R_WEBASSEMBLY_TYPE_INDEX_LEB.
George Rimar45d116d2019-01-15 09:19:18 +0000678 Fmt << Rel.Index;
Sam Clegg588fa1c2018-04-26 16:41:51 +0000679 } else {
Sam Cleggcc3b83d2018-04-26 17:05:04 +0000680 Expected<StringRef> SymNameOrErr = SI->getName();
681 if (!SymNameOrErr)
682 return errorToErrorCode(SymNameOrErr.takeError());
Sam Clegg588fa1c2018-04-26 16:41:51 +0000683 StringRef SymName = *SymNameOrErr;
684 Result.append(SymName.begin(), SymName.end());
685 }
George Rimar45d116d2019-01-15 09:19:18 +0000686 Fmt << (Rel.Addend < 0 ? "" : "+") << Rel.Addend;
687 Fmt.flush();
688 Result.append(FmtBuf.begin(), FmtBuf.end());
Sam Clegg08da5c52017-06-27 20:40:53 +0000689 return std::error_code();
690}
691
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000692static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
693 const RelocationRef &RelRef,
694 SmallVectorImpl<char> &Result) {
695 DataRefImpl Rel = RelRef.getRawDataRefImpl();
696 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
697
698 unsigned Arch = Obj->getArch();
699
George Rimar45d116d2019-01-15 09:19:18 +0000700 std::string FmtBuf;
701 raw_string_ostream Fmt(FmtBuf);
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000702 unsigned Type = Obj->getAnyRelocationType(RE);
703 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
704
705 // Determine any addends that should be displayed with the relocation.
706 // These require decoding the relocation type, which is triple-specific.
707
708 // X86_64 has entirely custom relocation types.
709 if (Arch == Triple::x86_64) {
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000710 switch (Type) {
711 case MachO::X86_64_RELOC_GOT_LOAD:
712 case MachO::X86_64_RELOC_GOT: {
George Rimar45d116d2019-01-15 09:19:18 +0000713 printRelocationTargetName(Obj, RE, Fmt);
714 Fmt << "@GOT";
715 if (IsPCRel)
716 Fmt << "PCREL";
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000717 break;
718 }
719 case MachO::X86_64_RELOC_SUBTRACTOR: {
720 DataRefImpl RelNext = Rel;
721 Obj->moveRelocationNext(RelNext);
722 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
723
724 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
725 // X86_64_RELOC_UNSIGNED.
726 // NOTE: Scattered relocations don't exist on x86_64.
727 unsigned RType = Obj->getAnyRelocationType(RENext);
728 if (RType != MachO::X86_64_RELOC_UNSIGNED)
Kevin Enderbyfbd189d2016-11-16 22:17:38 +0000729 report_error(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
730 "X86_64_RELOC_SUBTRACTOR.");
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000731
732 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
733 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
George Rimar45d116d2019-01-15 09:19:18 +0000734 printRelocationTargetName(Obj, RENext, Fmt);
735 Fmt << "-";
736 printRelocationTargetName(Obj, RE, Fmt);
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000737 break;
738 }
739 case MachO::X86_64_RELOC_TLV:
George Rimar45d116d2019-01-15 09:19:18 +0000740 printRelocationTargetName(Obj, RE, Fmt);
741 Fmt << "@TLV";
742 if (IsPCRel)
743 Fmt << "P";
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000744 break;
745 case MachO::X86_64_RELOC_SIGNED_1:
George Rimar45d116d2019-01-15 09:19:18 +0000746 printRelocationTargetName(Obj, RE, Fmt);
747 Fmt << "-1";
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000748 break;
749 case MachO::X86_64_RELOC_SIGNED_2:
George Rimar45d116d2019-01-15 09:19:18 +0000750 printRelocationTargetName(Obj, RE, Fmt);
751 Fmt << "-2";
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000752 break;
753 case MachO::X86_64_RELOC_SIGNED_4:
George Rimar45d116d2019-01-15 09:19:18 +0000754 printRelocationTargetName(Obj, RE, Fmt);
755 Fmt << "-4";
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000756 break;
757 default:
George Rimar45d116d2019-01-15 09:19:18 +0000758 printRelocationTargetName(Obj, RE, Fmt);
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000759 break;
760 }
761 // X86 and ARM share some relocation types in common.
762 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
763 Arch == Triple::ppc) {
764 // Generic relocation types...
765 switch (Type) {
766 case MachO::GENERIC_RELOC_PAIR: // prints no info
Rui Ueyamaeae46732015-06-09 15:20:42 +0000767 return std::error_code();
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000768 case MachO::GENERIC_RELOC_SECTDIFF: {
769 DataRefImpl RelNext = Rel;
770 Obj->moveRelocationNext(RelNext);
771 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
772
773 // X86 sect diff's must be followed by a relocation of type
774 // GENERIC_RELOC_PAIR.
775 unsigned RType = Obj->getAnyRelocationType(RENext);
776
777 if (RType != MachO::GENERIC_RELOC_PAIR)
Kevin Enderbyfbd189d2016-11-16 22:17:38 +0000778 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
779 "GENERIC_RELOC_SECTDIFF.");
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000780
George Rimar45d116d2019-01-15 09:19:18 +0000781 printRelocationTargetName(Obj, RE, Fmt);
782 Fmt << "-";
783 printRelocationTargetName(Obj, RENext, Fmt);
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000784 break;
785 }
786 }
787
788 if (Arch == Triple::x86 || Arch == Triple::ppc) {
789 switch (Type) {
790 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
791 DataRefImpl RelNext = Rel;
792 Obj->moveRelocationNext(RelNext);
793 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
794
795 // X86 sect diff's must be followed by a relocation of type
796 // GENERIC_RELOC_PAIR.
797 unsigned RType = Obj->getAnyRelocationType(RENext);
798 if (RType != MachO::GENERIC_RELOC_PAIR)
Kevin Enderbyfbd189d2016-11-16 22:17:38 +0000799 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
800 "GENERIC_RELOC_LOCAL_SECTDIFF.");
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000801
George Rimar45d116d2019-01-15 09:19:18 +0000802 printRelocationTargetName(Obj, RE, Fmt);
803 Fmt << "-";
804 printRelocationTargetName(Obj, RENext, Fmt);
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000805 break;
806 }
807 case MachO::GENERIC_RELOC_TLV: {
George Rimar45d116d2019-01-15 09:19:18 +0000808 printRelocationTargetName(Obj, RE, Fmt);
809 Fmt << "@TLV";
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000810 if (IsPCRel)
George Rimar45d116d2019-01-15 09:19:18 +0000811 Fmt << "P";
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000812 break;
813 }
814 default:
George Rimar45d116d2019-01-15 09:19:18 +0000815 printRelocationTargetName(Obj, RE, Fmt);
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000816 }
817 } else { // ARM-specific relocations
818 switch (Type) {
819 case MachO::ARM_RELOC_HALF:
820 case MachO::ARM_RELOC_HALF_SECTDIFF: {
821 // Half relocations steal a bit from the length field to encode
822 // whether this is an upper16 or a lower16 relocation.
Martin Storsjo8ca723a2017-07-13 05:54:08 +0000823 bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000824
825 if (isUpper)
George Rimar45d116d2019-01-15 09:19:18 +0000826 Fmt << ":upper16:(";
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000827 else
George Rimar45d116d2019-01-15 09:19:18 +0000828 Fmt << ":lower16:(";
829 printRelocationTargetName(Obj, RE, Fmt);
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000830
831 DataRefImpl RelNext = Rel;
832 Obj->moveRelocationNext(RelNext);
833 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
834
835 // ARM half relocs must be followed by a relocation of type
836 // ARM_RELOC_PAIR.
837 unsigned RType = Obj->getAnyRelocationType(RENext);
838 if (RType != MachO::ARM_RELOC_PAIR)
Kevin Enderbyfbd189d2016-11-16 22:17:38 +0000839 report_error(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
840 "ARM_RELOC_HALF");
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000841
842 // NOTE: The half of the target virtual address is stashed in the
843 // address field of the secondary relocation, but we can't reverse
844 // engineer the constant offset from it without decoding the movw/movt
845 // instruction to find the other half in its immediate field.
846
847 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
848 // symbol/section pointer of the follow-on relocation.
849 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
George Rimar45d116d2019-01-15 09:19:18 +0000850 Fmt << "-";
851 printRelocationTargetName(Obj, RENext, Fmt);
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000852 }
853
George Rimar45d116d2019-01-15 09:19:18 +0000854 Fmt << ")";
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000855 break;
856 }
George Rimar45d116d2019-01-15 09:19:18 +0000857 default: { printRelocationTargetName(Obj, RE, Fmt); }
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000858 }
859 }
860 } else
George Rimar45d116d2019-01-15 09:19:18 +0000861 printRelocationTargetName(Obj, RE, Fmt);
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000862
George Rimar45d116d2019-01-15 09:19:18 +0000863 Fmt.flush();
864 Result.append(FmtBuf.begin(), FmtBuf.end());
Rui Ueyamaeae46732015-06-09 15:20:42 +0000865 return std::error_code();
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000866}
867
868static std::error_code getRelocationValueString(const RelocationRef &Rel,
869 SmallVectorImpl<char> &Result) {
Rafael Espindolaea767132015-06-26 14:51:16 +0000870 const ObjectFile *Obj = Rel.getObject();
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000871 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
872 return getRelocationValueString(ELF, Rel, Result);
873 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
874 return getRelocationValueString(COFF, Rel, Result);
Sam Clegg08da5c52017-06-27 20:40:53 +0000875 if (auto *Wasm = dyn_cast<WasmObjectFile>(Obj))
876 return getRelocationValueString(Wasm, Rel, Result);
877 if (auto *MachO = dyn_cast<MachOObjectFile>(Obj))
878 return getRelocationValueString(MachO, Rel, Result);
879 llvm_unreachable("unknown object file format");
Rafael Espindola8c7a0fd2015-06-03 04:48:06 +0000880}
881
Adrian Prantl0b24b742018-05-01 16:10:38 +0000882/// Indicates whether this relocation should hidden when listing
Rafael Espindola09912eb92015-06-30 03:41:26 +0000883/// relocations, usually because it is the trailing part of a multipart
884/// relocation that will be printed as part of the leading relocation.
885static bool getHidden(RelocationRef RelRef) {
George Rimar45d116d2019-01-15 09:19:18 +0000886 auto *MachO = dyn_cast<MachOObjectFile>(RelRef.getObject());
Rafael Espindola09912eb92015-06-30 03:41:26 +0000887 if (!MachO)
888 return false;
889
890 unsigned Arch = MachO->getArch();
891 DataRefImpl Rel = RelRef.getRawDataRefImpl();
892 uint64_t Type = MachO->getRelocationType(Rel);
893
894 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
895 // is always hidden.
George Rimar45d116d2019-01-15 09:19:18 +0000896 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc)
897 return Type == MachO::GENERIC_RELOC_PAIR;
898
899 if (Arch == Triple::x86_64) {
Rafael Espindola09912eb92015-06-30 03:41:26 +0000900 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
901 // an X86_64_RELOC_SUBTRACTOR.
902 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
903 DataRefImpl RelPrev = Rel;
904 RelPrev.d.a--;
905 uint64_t PrevType = MachO->getRelocationType(RelPrev);
906 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
907 return true;
908 }
909 }
910
911 return false;
912}
913
Sid Manning86cf2322018-05-14 19:46:08 +0000914namespace {
915class SourcePrinter {
916protected:
917 DILineInfo OldLineInfo;
918 const ObjectFile *Obj = nullptr;
919 std::unique_ptr<symbolize::LLVMSymbolizer> Symbolizer;
920 // File name to file contents of source
921 std::unordered_map<std::string, std::unique_ptr<MemoryBuffer>> SourceCache;
922 // Mark the line endings of the cached source
923 std::unordered_map<std::string, std::vector<StringRef>> LineCache;
924
925private:
926 bool cacheSource(const DILineInfo& LineInfoFile);
927
928public:
929 SourcePrinter() = default;
930 SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch) : Obj(Obj) {
931 symbolize::LLVMSymbolizer::Options SymbolizerOpts(
932 DILineInfoSpecifier::FunctionNameKind::None, true, false, false,
933 DefaultArch);
934 Symbolizer.reset(new symbolize::LLVMSymbolizer(SymbolizerOpts));
935 }
936 virtual ~SourcePrinter() = default;
937 virtual void printSourceLine(raw_ostream &OS, uint64_t Address,
938 StringRef Delimiter = "; ");
939};
940
941bool SourcePrinter::cacheSource(const DILineInfo &LineInfo) {
942 std::unique_ptr<MemoryBuffer> Buffer;
943 if (LineInfo.Source) {
944 Buffer = MemoryBuffer::getMemBuffer(*LineInfo.Source);
945 } else {
946 auto BufferOrError = MemoryBuffer::getFile(LineInfo.FileName);
947 if (!BufferOrError)
948 return false;
949 Buffer = std::move(*BufferOrError);
950 }
951 // Chomp the file to get lines
952 size_t BufferSize = Buffer->getBufferSize();
953 const char *BufferStart = Buffer->getBufferStart();
954 for (const char *Start = BufferStart, *End = BufferStart;
955 End < BufferStart + BufferSize; End++)
956 if (*End == '\n' || End == BufferStart + BufferSize - 1 ||
957 (*End == '\r' && *(End + 1) == '\n')) {
958 LineCache[LineInfo.FileName].push_back(StringRef(Start, End - Start));
959 if (*End == '\r')
960 End++;
961 Start = End + 1;
962 }
963 SourceCache[LineInfo.FileName] = std::move(Buffer);
964 return true;
965}
966
967void SourcePrinter::printSourceLine(raw_ostream &OS, uint64_t Address,
968 StringRef Delimiter) {
969 if (!Symbolizer)
970 return;
971 DILineInfo LineInfo = DILineInfo();
972 auto ExpectecLineInfo =
973 Symbolizer->symbolizeCode(Obj->getFileName(), Address);
974 if (!ExpectecLineInfo)
975 consumeError(ExpectecLineInfo.takeError());
976 else
977 LineInfo = *ExpectecLineInfo;
978
979 if ((LineInfo.FileName == "<invalid>") || OldLineInfo.Line == LineInfo.Line ||
980 LineInfo.Line == 0)
981 return;
982
983 if (PrintLines)
984 OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line << "\n";
985 if (PrintSource) {
986 if (SourceCache.find(LineInfo.FileName) == SourceCache.end())
987 if (!cacheSource(LineInfo))
988 return;
989 auto FileBuffer = SourceCache.find(LineInfo.FileName);
990 if (FileBuffer != SourceCache.end()) {
991 auto LineBuffer = LineCache.find(LineInfo.FileName);
992 if (LineBuffer != LineCache.end()) {
993 if (LineInfo.Line > LineBuffer->second.size())
994 return;
995 // Vector begins at 0, line numbers are non-zero
996 OS << Delimiter << LineBuffer->second[LineInfo.Line - 1].ltrim()
997 << "\n";
998 }
999 }
1000 }
1001 OldLineInfo = LineInfo;
1002}
1003
1004static bool isArmElf(const ObjectFile *Obj) {
1005 return (Obj->isELF() &&
1006 (Obj->getArch() == Triple::aarch64 ||
1007 Obj->getArch() == Triple::aarch64_be ||
1008 Obj->getArch() == Triple::arm || Obj->getArch() == Triple::armeb ||
1009 Obj->getArch() == Triple::thumb ||
1010 Obj->getArch() == Triple::thumbeb));
1011}
1012
1013class PrettyPrinter {
1014public:
1015 virtual ~PrettyPrinter() = default;
1016 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
1017 ArrayRef<uint8_t> Bytes, uint64_t Address,
1018 raw_ostream &OS, StringRef Annot,
1019 MCSubtargetInfo const &STI, SourcePrinter *SP,
1020 std::vector<RelocationRef> *Rels = nullptr) {
1021 if (SP && (PrintSource || PrintLines))
1022 SP->printSourceLine(OS, Address);
1023 if (!NoLeadingAddr)
1024 OS << format("%8" PRIx64 ":", Address);
1025 if (!NoShowRawInsn) {
1026 OS << "\t";
1027 dumpBytes(Bytes, OS);
1028 }
1029 if (MI)
1030 IP.printInst(MI, OS, "", STI);
1031 else
1032 OS << " <unknown>";
1033 }
1034};
1035PrettyPrinter PrettyPrinterInst;
1036class HexagonPrettyPrinter : public PrettyPrinter {
1037public:
1038 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
1039 raw_ostream &OS) {
1040 uint32_t opcode =
1041 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
1042 if (!NoLeadingAddr)
1043 OS << format("%8" PRIx64 ":", Address);
1044 if (!NoShowRawInsn) {
1045 OS << "\t";
1046 dumpBytes(Bytes.slice(0, 4), OS);
1047 OS << format("%08" PRIx32, opcode);
1048 }
1049 }
1050 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1051 uint64_t Address, raw_ostream &OS, StringRef Annot,
1052 MCSubtargetInfo const &STI, SourcePrinter *SP,
1053 std::vector<RelocationRef> *Rels) override {
1054 if (SP && (PrintSource || PrintLines))
1055 SP->printSourceLine(OS, Address, "");
1056 if (!MI) {
1057 printLead(Bytes, Address, OS);
1058 OS << " <unknown>";
1059 return;
1060 }
1061 std::string Buffer;
1062 {
1063 raw_string_ostream TempStream(Buffer);
1064 IP.printInst(MI, TempStream, "", STI);
1065 }
1066 StringRef Contents(Buffer);
1067 // Split off bundle attributes
1068 auto PacketBundle = Contents.rsplit('\n');
1069 // Split off first instruction from the rest
1070 auto HeadTail = PacketBundle.first.split('\n');
1071 auto Preamble = " { ";
1072 auto Separator = "";
1073 StringRef Fmt = "\t\t\t%08" PRIx64 ": ";
George Rimar45d116d2019-01-15 09:19:18 +00001074 std::vector<RelocationRef>::const_iterator RelCur = Rels->begin();
1075 std::vector<RelocationRef>::const_iterator RelEnd = Rels->end();
Sid Manning86cf2322018-05-14 19:46:08 +00001076
1077 // Hexagon's packets require relocations to be inline rather than
1078 // clustered at the end of the packet.
1079 auto PrintReloc = [&]() -> void {
George Rimar45d116d2019-01-15 09:19:18 +00001080 while ((RelCur != RelEnd) && (RelCur->getOffset() <= Address)) {
1081 if (RelCur->getOffset() == Address) {
1082 SmallString<16> Name;
1083 SmallString<32> Val;
1084 RelCur->getTypeName(Name);
1085 error(getRelocationValueString(*RelCur, Val));
1086 OS << Separator << format(Fmt.data(), Address) << Name << "\t" << Val
Sid Manning86cf2322018-05-14 19:46:08 +00001087 << "\n";
1088 return;
1089 }
George Rimar45d116d2019-01-15 09:19:18 +00001090 ++RelCur;
Sid Manning86cf2322018-05-14 19:46:08 +00001091 }
1092 };
1093
George Rimar45d116d2019-01-15 09:19:18 +00001094 while (!HeadTail.first.empty()) {
Sid Manning86cf2322018-05-14 19:46:08 +00001095 OS << Separator;
1096 Separator = "\n";
1097 if (SP && (PrintSource || PrintLines))
1098 SP->printSourceLine(OS, Address, "");
1099 printLead(Bytes, Address, OS);
1100 OS << Preamble;
1101 Preamble = " ";
1102 StringRef Inst;
1103 auto Duplex = HeadTail.first.split('\v');
George Rimar45d116d2019-01-15 09:19:18 +00001104 if (!Duplex.second.empty()) {
Sid Manning86cf2322018-05-14 19:46:08 +00001105 OS << Duplex.first;
1106 OS << "; ";
1107 Inst = Duplex.second;
1108 }
1109 else
1110 Inst = HeadTail.first;
1111 OS << Inst;
1112 HeadTail = HeadTail.second.split('\n');
1113 if (HeadTail.first.empty())
1114 OS << " } " << PacketBundle.second;
1115 PrintReloc();
1116 Bytes = Bytes.slice(4);
1117 Address += 4;
1118 }
1119 }
1120};
1121HexagonPrettyPrinter HexagonPrettyPrinterInst;
1122
1123class AMDGCNPrettyPrinter : public PrettyPrinter {
1124public:
1125 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1126 uint64_t Address, raw_ostream &OS, StringRef Annot,
1127 MCSubtargetInfo const &STI, SourcePrinter *SP,
1128 std::vector<RelocationRef> *Rels) override {
1129 if (SP && (PrintSource || PrintLines))
1130 SP->printSourceLine(OS, Address);
1131
1132 typedef support::ulittle32_t U32;
1133
1134 if (MI) {
1135 SmallString<40> InstStr;
1136 raw_svector_ostream IS(InstStr);
1137
1138 IP.printInst(MI, IS, "", STI);
1139
1140 OS << left_justify(IS.str(), 60);
1141 } else {
1142 // an unrecognized encoding - this is probably data so represent it
1143 // using the .long directive, or .byte directive if fewer than 4 bytes
1144 // remaining
1145 if (Bytes.size() >= 4) {
1146 OS << format("\t.long 0x%08" PRIx32 " ",
1147 static_cast<uint32_t>(*reinterpret_cast<const U32*>(Bytes.data())));
1148 OS.indent(42);
1149 } else {
1150 OS << format("\t.byte 0x%02" PRIx8, Bytes[0]);
1151 for (unsigned int i = 1; i < Bytes.size(); i++)
1152 OS << format(", 0x%02" PRIx8, Bytes[i]);
1153 OS.indent(55 - (6 * Bytes.size()));
1154 }
1155 }
1156
1157 OS << format("// %012" PRIX64 ": ", Address);
1158 if (Bytes.size() >=4) {
1159 for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
1160 Bytes.size() / sizeof(U32)))
1161 // D should be explicitly casted to uint32_t here as it is passed
1162 // by format to snprintf as vararg.
1163 OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D));
1164 } else {
1165 for (unsigned int i = 0; i < Bytes.size(); i++)
1166 OS << format("%02" PRIX8 " ", Bytes[i]);
1167 }
1168
1169 if (!Annot.empty())
1170 OS << "// " << Annot;
1171 }
1172};
1173AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
1174
1175class BPFPrettyPrinter : public PrettyPrinter {
1176public:
1177 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1178 uint64_t Address, raw_ostream &OS, StringRef Annot,
1179 MCSubtargetInfo const &STI, SourcePrinter *SP,
1180 std::vector<RelocationRef> *Rels) override {
1181 if (SP && (PrintSource || PrintLines))
1182 SP->printSourceLine(OS, Address);
1183 if (!NoLeadingAddr)
1184 OS << format("%8" PRId64 ":", Address / 8);
1185 if (!NoShowRawInsn) {
1186 OS << "\t";
1187 dumpBytes(Bytes, OS);
1188 }
1189 if (MI)
1190 IP.printInst(MI, OS, "", STI);
1191 else
1192 OS << " <unknown>";
1193 }
1194};
1195BPFPrettyPrinter BPFPrettyPrinterInst;
1196
1197PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
1198 switch(Triple.getArch()) {
1199 default:
1200 return PrettyPrinterInst;
1201 case Triple::hexagon:
1202 return HexagonPrettyPrinterInst;
1203 case Triple::amdgcn:
1204 return AMDGCNPrettyPrinterInst;
1205 case Triple::bpfel:
1206 case Triple::bpfeb:
1207 return BPFPrettyPrinterInst;
1208 }
1209}
1210}
1211
Sam Koltonae331602016-08-17 10:17:57 +00001212static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) {
1213 assert(Obj->isELF());
1214 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1215 return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1216 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1217 return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1218 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1219 return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1220 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1221 return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1222 llvm_unreachable("Unsupported binary format");
1223}
1224
Sam Parker3bfb1e82017-02-08 09:44:18 +00001225template <class ELFT> static void
1226addDynamicElfSymbols(const ELFObjectFile<ELFT> *Obj,
1227 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1228 for (auto Symbol : Obj->getDynamicSymbolIterators()) {
1229 uint8_t SymbolType = Symbol.getELFType();
1230 if (SymbolType != ELF::STT_FUNC || Symbol.getSize() == 0)
1231 continue;
1232
1233 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
1234 if (!AddressOrErr)
1235 report_error(Obj->getFileName(), AddressOrErr.takeError());
Sam Parker3bfb1e82017-02-08 09:44:18 +00001236
1237 Expected<StringRef> Name = Symbol.getName();
1238 if (!Name)
1239 report_error(Obj->getFileName(), Name.takeError());
1240 if (Name->empty())
1241 continue;
1242
1243 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1244 if (!SectionOrErr)
1245 report_error(Obj->getFileName(), SectionOrErr.takeError());
1246 section_iterator SecI = *SectionOrErr;
1247 if (SecI == Obj->section_end())
1248 continue;
1249
George Rimar45d116d2019-01-15 09:19:18 +00001250 AllSymbols[*SecI].emplace_back(*AddressOrErr, *Name, SymbolType);
Sam Parker3bfb1e82017-02-08 09:44:18 +00001251 }
1252}
1253
1254static void
1255addDynamicElfSymbols(const ObjectFile *Obj,
1256 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1257 assert(Obj->isELF());
1258 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1259 addDynamicElfSymbols(Elf32LEObj, AllSymbols);
1260 else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1261 addDynamicElfSymbols(Elf64LEObj, AllSymbols);
1262 else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1263 addDynamicElfSymbols(Elf32BEObj, AllSymbols);
1264 else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1265 addDynamicElfSymbols(Elf64BEObj, AllSymbols);
1266 else
1267 llvm_unreachable("Unsupported binary format");
1268}
1269
Joel Galensone47abe72018-08-24 15:21:57 +00001270static void addPltEntries(const ObjectFile *Obj,
1271 std::map<SectionRef, SectionSymbolsTy> &AllSymbols,
1272 StringSaver &Saver) {
1273 Optional<SectionRef> Plt = None;
1274 for (const SectionRef &Section : Obj->sections()) {
1275 StringRef Name;
1276 if (Section.getName(Name))
1277 continue;
1278 if (Name == ".plt")
1279 Plt = Section;
1280 }
1281 if (!Plt)
1282 return;
1283 if (auto *ElfObj = dyn_cast<ELFObjectFileBase>(Obj)) {
1284 for (auto PltEntry : ElfObj->getPltAddresses()) {
1285 SymbolRef Symbol(PltEntry.first, ElfObj);
Joel Galensone47abe72018-08-24 15:21:57 +00001286 uint8_t SymbolType = getElfSymbolType(Obj, Symbol);
1287
1288 Expected<StringRef> NameOrErr = Symbol.getName();
1289 if (!NameOrErr)
1290 report_error(Obj->getFileName(), NameOrErr.takeError());
1291 if (NameOrErr->empty())
1292 continue;
1293 StringRef Name = Saver.save((*NameOrErr + "@plt").str());
1294
1295 AllSymbols[*Plt].emplace_back(PltEntry.second, Name, SymbolType);
1296 }
1297 }
1298}
1299
George Rimar54820302019-01-10 14:55:26 +00001300// Normally the disassembly output will skip blocks of zeroes. This function
1301// returns the number of zero bytes that can be skipped when dumping the
1302// disassembly of the instructions in Buf.
1303static size_t countSkippableZeroBytes(ArrayRef<uint8_t> Buf) {
1304 // When -z or --disassemble-zeroes are given we always dissasemble them.
1305 if (DisassembleZeroes)
1306 return 0;
1307
1308 // Find the number of leading zeroes.
1309 size_t N = 0;
1310 while (N < Buf.size() && !Buf[N])
1311 ++N;
1312
1313 // We may want to skip blocks of zero bytes, but unless we see
1314 // at least 8 of them in a row.
1315 if (N < 8)
1316 return 0;
1317
1318 // We skip zeroes in multiples of 4 because do not want to truncate an
1319 // instruction if it starts with a zero byte.
1320 return N & ~0x3;
1321}
1322
George Rimar45d116d2019-01-15 09:19:18 +00001323static void disassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Hemant Kulkarni11981cd2016-09-12 17:08:22 +00001324 if (StartAddress > StopAddress)
1325 error("Start address should be less than stop address");
1326
Jim Grosbach3f5d1a22012-08-07 17:53:14 +00001327 const Target *TheTarget = getTarget(Obj);
Michael J. Spencer92e1deb2011-01-20 06:39:06 +00001328
Jack Carterfd6d1652012-08-28 19:24:49 +00001329 // Package up features to be passed to target/subtarget
Daniel Sanders0b8fc772016-06-16 09:17:03 +00001330 SubtargetFeatures Features = Obj->getFeatures();
George Rimar45d116d2019-01-15 09:19:18 +00001331 if (!MAttrs.empty())
1332 for (unsigned I = 0; I != MAttrs.size(); ++I)
1333 Features.AddFeature(MAttrs[I]);
Jack Carterfd6d1652012-08-28 19:24:49 +00001334
Ahmed Charlesf4ccd112014-03-06 05:51:42 +00001335 std::unique_ptr<const MCRegisterInfo> MRI(
1336 TheTarget->createMCRegInfo(TripleName));
Davide Italiano4151f0d2015-12-17 01:59:50 +00001337 if (!MRI)
Kevin Enderbyfbd189d2016-11-16 22:17:38 +00001338 report_error(Obj->getFileName(), "no register info for target " +
1339 TripleName);
Ahmed Bougacha27a33ad2013-05-16 21:28:23 +00001340
1341 // Set up disassembler.
Ahmed Charlesf4ccd112014-03-06 05:51:42 +00001342 std::unique_ptr<const MCAsmInfo> AsmInfo(
1343 TheTarget->createMCAsmInfo(*MRI, TripleName));
Davide Italiano4151f0d2015-12-17 01:59:50 +00001344 if (!AsmInfo)
Kevin Enderbyfbd189d2016-11-16 22:17:38 +00001345 report_error(Obj->getFileName(), "no assembly info for target " +
1346 TripleName);
Ahmed Charlesf4ccd112014-03-06 05:51:42 +00001347 std::unique_ptr<const MCSubtargetInfo> STI(
Daniel Sanders0b8fc772016-06-16 09:17:03 +00001348 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
Davide Italiano4151f0d2015-12-17 01:59:50 +00001349 if (!STI)
Kevin Enderbyfbd189d2016-11-16 22:17:38 +00001350 report_error(Obj->getFileName(), "no subtarget info for target " +
1351 TripleName);
Ahmed Charlesf4ccd112014-03-06 05:51:42 +00001352 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
Davide Italiano4151f0d2015-12-17 01:59:50 +00001353 if (!MII)
Kevin Enderbyfbd189d2016-11-16 22:17:38 +00001354 report_error(Obj->getFileName(), "no instruction info for target " +
1355 TripleName);
Sam Kolton665e9762016-10-06 13:46:08 +00001356 MCObjectFileInfo MOFI;
1357 MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI);
1358 // FIXME: for now initialize MCObjectFileInfo with default values
Rafael Espindola2600a672017-08-02 20:32:26 +00001359 MOFI.InitMCObjectFileInfo(Triple(TripleName), false, Ctx);
Lang Hames508bd632014-04-15 04:40:56 +00001360
1361 std::unique_ptr<MCDisassembler> DisAsm(
1362 TheTarget->createMCDisassembler(*STI, Ctx));
Davide Italiano4151f0d2015-12-17 01:59:50 +00001363 if (!DisAsm)
Kevin Enderbyfbd189d2016-11-16 22:17:38 +00001364 report_error(Obj->getFileName(), "no disassembler for target " +
1365 TripleName);
Ahmed Bougacha2c94d0f2013-05-24 00:39:57 +00001366
Ahmed Charlesf4ccd112014-03-06 05:51:42 +00001367 std::unique_ptr<const MCInstrAnalysis> MIA(
1368 TheTarget->createMCInstrAnalysis(MII.get()));
Ahmed Bougachaef993562013-05-24 01:07:04 +00001369
Ahmed Bougacha27a33ad2013-05-16 21:28:23 +00001370 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Daniel Sanders47b167d2015-09-15 16:17:27 +00001371 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1372 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
Davide Italiano4151f0d2015-12-17 01:59:50 +00001373 if (!IP)
Kevin Enderbyfbd189d2016-11-16 22:17:38 +00001374 report_error(Obj->getFileName(), "no instruction printer for target " +
1375 TripleName);
Colin LeMahieu8cc8dbc2015-06-07 21:07:17 +00001376 IP->setPrintImmHex(PrintImmHex);
Colin LeMahieu00703e92015-05-29 14:48:25 +00001377 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
Ahmed Bougacha27a33ad2013-05-16 21:28:23 +00001378
Greg Fitzgeraldaff0ab42014-03-20 22:55:15 +00001379 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
1380 "\t\t\t%08" PRIx64 ": ";
1381
Hemant Kulkarni502957c2016-08-15 19:49:24 +00001382 SourcePrinter SP(Obj, TheTarget->getName());
1383
Mark Seaborn2effd6c2014-01-25 17:38:19 +00001384 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
1385 // in RelocSecs contain the relocations for section S.
Rafael Espindola1ad45022014-06-13 03:07:50 +00001386 std::error_code EC;
Alexey Samsonov7a2da952014-03-13 14:37:36 +00001387 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
Colin LeMahieuedbf9d72015-07-29 15:45:39 +00001388 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov7a2da952014-03-13 14:37:36 +00001389 section_iterator Sec2 = Section.getRelocatedSection();
Rafael Espindolaa40b3522014-02-10 20:24:04 +00001390 if (Sec2 != Obj->section_end())
Alexey Samsonov7a2da952014-03-13 14:37:36 +00001391 SectionRelocMap[*Sec2].push_back(Section);
Mark Seaborn2effd6c2014-01-25 17:38:19 +00001392 }
1393
David Majnemerb99ee322015-07-07 22:06:59 +00001394 // Create a mapping from virtual address to symbol name. This is used to
David Majnemer6ac90f12015-11-18 02:49:19 +00001395 // pretty print the symbols while disassembling.
David Majnemer6ac90f12015-11-18 02:49:19 +00001396 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
Sterling Augustine3605e122018-06-28 18:57:13 +00001397 SectionSymbolsTy AbsoluteSymbols;
David Majnemer6ac90f12015-11-18 02:49:19 +00001398 for (const SymbolRef &Symbol : Obj->symbols()) {
Kevin Enderby317de7c2016-06-24 18:24:42 +00001399 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
Kevin Enderbyfbd189d2016-11-16 22:17:38 +00001400 if (!AddressOrErr)
1401 report_error(Obj->getFileName(), AddressOrErr.takeError());
David Majnemer6ac90f12015-11-18 02:49:19 +00001402 uint64_t Address = *AddressOrErr;
David Majnemerf2c71ff2015-07-09 18:11:40 +00001403
Kevin Enderby813e0cf2016-04-20 21:24:34 +00001404 Expected<StringRef> Name = Symbol.getName();
Kevin Enderbyfbd189d2016-11-16 22:17:38 +00001405 if (!Name)
1406 report_error(Obj->getFileName(), Name.takeError());
David Majnemer6ac90f12015-11-18 02:49:19 +00001407 if (Name->empty())
1408 continue;
David Majnemerb99ee322015-07-07 22:06:59 +00001409
Kevin Enderbya486dca2016-05-02 20:28:12 +00001410 Expected<section_iterator> SectionOrErr = Symbol.getSection();
Kevin Enderbyfbd189d2016-11-16 22:17:38 +00001411 if (!SectionOrErr)
1412 report_error(Obj->getFileName(), SectionOrErr.takeError());
Hemant Kulkarnic76060f2016-08-25 19:41:08 +00001413
Sam Koltonae331602016-08-17 10:17:57 +00001414 uint8_t SymbolType = ELF::STT_NOTYPE;
Hemant Kulkarnic76060f2016-08-25 19:41:08 +00001415 if (Obj->isELF())
Sam Koltonae331602016-08-17 10:17:57 +00001416 SymbolType = getElfSymbolType(Obj, Symbol);
David Majnemerb99ee322015-07-07 22:06:59 +00001417
Sterling Augustine3605e122018-06-28 18:57:13 +00001418 section_iterator SecI = *SectionOrErr;
1419 if (SecI != Obj->section_end())
1420 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1421 else
1422 AbsoluteSymbols.emplace_back(Address, *Name, SymbolType);
1423
Sam Koltonae331602016-08-17 10:17:57 +00001424
David Majnemerb99ee322015-07-07 22:06:59 +00001425 }
Sam Parker3bfb1e82017-02-08 09:44:18 +00001426 if (AllSymbols.empty() && Obj->isELF())
1427 addDynamicElfSymbols(Obj, AllSymbols);
David Majnemerb99ee322015-07-07 22:06:59 +00001428
Joel Galensone47abe72018-08-24 15:21:57 +00001429 BumpPtrAllocator A;
1430 StringSaver Saver(A);
1431 addPltEntries(Obj, AllSymbols, Saver);
1432
David Majnemer6ac90f12015-11-18 02:49:19 +00001433 // Create a mapping from virtual address to section.
1434 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1435 for (SectionRef Sec : Obj->sections())
1436 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1437 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
1438
1439 // Linked executables (.exe and .dll files) typically don't include a real
1440 // symbol table but they might contain an export table.
1441 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
1442 for (const auto &ExportEntry : COFFObj->export_directories()) {
1443 StringRef Name;
1444 error(ExportEntry.getSymbolName(Name));
1445 if (Name.empty())
1446 continue;
1447 uint32_t RVA;
1448 error(ExportEntry.getExportRVA(RVA));
1449
1450 uint64_t VA = COFFObj->getImageBase() + RVA;
1451 auto Sec = std::upper_bound(
1452 SectionAddresses.begin(), SectionAddresses.end(), VA,
1453 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
1454 return LHS < RHS.first;
1455 });
1456 if (Sec != SectionAddresses.begin())
1457 --Sec;
1458 else
1459 Sec = SectionAddresses.end();
1460
1461 if (Sec != SectionAddresses.end())
Sam Koltonae331602016-08-17 10:17:57 +00001462 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
Sterling Augustine3605e122018-06-28 18:57:13 +00001463 else
1464 AbsoluteSymbols.emplace_back(VA, Name, ELF::STT_NOTYPE);
David Majnemer6ac90f12015-11-18 02:49:19 +00001465 }
1466 }
1467
1468 // Sort all the symbols, this allows us to use a simple binary search to find
1469 // a symbol near an address.
1470 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1471 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
Sterling Augustine3605e122018-06-28 18:57:13 +00001472 array_pod_sort(AbsoluteSymbols.begin(), AbsoluteSymbols.end());
David Majnemer6ac90f12015-11-18 02:49:19 +00001473
Colin LeMahieuedbf9d72015-07-29 15:45:39 +00001474 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Colin LeMahieuea805022015-07-23 20:58:49 +00001475 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
Mark Seaborn2760cc22014-01-25 00:32:01 +00001476 continue;
Michael J. Spencer25b15772011-06-25 17:55:23 +00001477
Rafael Espindola8175be52014-10-08 15:28:58 +00001478 uint64_t SectionAddr = Section.getAddress();
1479 uint64_t SectSize = Section.getSize();
David Majnemer1dd631f2014-11-11 09:58:25 +00001480 if (!SectSize)
1481 continue;
Simon Atanasyan341d0f42014-02-24 22:12:11 +00001482
David Majnemer6ac90f12015-11-18 02:49:19 +00001483 // Get the list of all the symbols in this section.
1484 SectionSymbolsTy &Symbols = AllSymbols[Section];
Davide Italiano52c04442015-10-01 21:57:09 +00001485 std::vector<uint64_t> DataMappingSymsAddr;
1486 std::vector<uint64_t> TextMappingSymsAddr;
Hemant Kulkarnic76060f2016-08-25 19:41:08 +00001487 if (isArmElf(Obj)) {
David Majnemer6ac90f12015-11-18 02:49:19 +00001488 for (const auto &Symb : Symbols) {
Sam Koltonae331602016-08-17 10:17:57 +00001489 uint64_t Address = std::get<0>(Symb);
1490 StringRef Name = std::get<1>(Symb);
David Majnemer6ac90f12015-11-18 02:49:19 +00001491 if (Name.startswith("$d"))
David Majnemer35da61a2015-11-18 04:35:32 +00001492 DataMappingSymsAddr.push_back(Address - SectionAddr);
David Majnemer6ac90f12015-11-18 02:49:19 +00001493 if (Name.startswith("$x"))
David Majnemer35da61a2015-11-18 04:35:32 +00001494 TextMappingSymsAddr.push_back(Address - SectionAddr);
Hemant Kulkarnic76060f2016-08-25 19:41:08 +00001495 if (Name.startswith("$a"))
1496 TextMappingSymsAddr.push_back(Address - SectionAddr);
1497 if (Name.startswith("$t"))
1498 TextMappingSymsAddr.push_back(Address - SectionAddr);
Benjamin Kramer739b65b2011-07-15 18:39:24 +00001499 }
1500 }
1501
Fangrui Song3b35e172018-09-27 02:13:45 +00001502 llvm::sort(DataMappingSymsAddr);
1503 llvm::sort(TextMappingSymsAddr);
Benjamin Kramer739b65b2011-07-15 18:39:24 +00001504
Sam Kolton665e9762016-10-06 13:46:08 +00001505 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1506 // AMDGPU disassembler uses symbolizer for printing labels
1507 std::unique_ptr<MCRelocationInfo> RelInfo(
1508 TheTarget->createMCRelocationInfo(TripleName, Ctx));
1509 if (RelInfo) {
1510 std::unique_ptr<MCSymbolizer> Symbolizer(
1511 TheTarget->createMCSymbolizer(
1512 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1513 DisAsm->setSymbolizer(std::move(Symbolizer));
1514 }
1515 }
1516
Michael J. Spencer942eb002011-10-13 22:17:18 +00001517 // Make a list of all the relocations for this section.
1518 std::vector<RelocationRef> Rels;
1519 if (InlineRelocs) {
Alexey Samsonov6f07b352014-03-14 14:22:49 +00001520 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
1521 for (const RelocationRef &Reloc : RelocSec.relocations()) {
1522 Rels.push_back(Reloc);
1523 }
Michael J. Spencer942eb002011-10-13 22:17:18 +00001524 }
1525 }
1526
1527 // Sort relocations by address.
George Rimar45d116d2019-01-15 09:19:18 +00001528 llvm::sort(Rels, isRelocAddressLess);
Michael J. Spencer942eb002011-10-13 22:17:18 +00001529
Rafael Espindolacef81b32012-12-21 03:47:03 +00001530 StringRef SegmentName = "";
Mark Seaborn2760cc22014-01-25 00:32:01 +00001531 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov7a2da952014-03-13 14:37:36 +00001532 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindolafd7aa382013-04-18 18:08:55 +00001533 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolacef81b32012-12-21 03:47:03 +00001534 }
Rafael Auler67fe7952018-03-09 19:13:44 +00001535 StringRef SectionName;
1536 error(Section.getName(SectionName));
Benjamin Kramer739b65b2011-07-15 18:39:24 +00001537
Rafael Espindola45edf272015-06-04 15:01:05 +00001538 // If the section has no symbol at the start, just insert a dummy one.
Sam Koltonae331602016-08-17 10:17:57 +00001539 if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) {
Rafael Auler67fe7952018-03-09 19:13:44 +00001540 Symbols.insert(
1541 Symbols.begin(),
1542 std::make_tuple(SectionAddr, SectionName,
1543 Section.isText() ? ELF::STT_FUNC : ELF::STT_OBJECT));
Sam Koltonae331602016-08-17 10:17:57 +00001544 }
Alp Toker8dd8d5c2014-06-26 22:52:05 +00001545
1546 SmallString<40> Comments;
1547 raw_svector_ostream CommentStream(Comments);
Ahmed Bougacha2c94d0f2013-05-24 00:39:57 +00001548
Rafael Espindola6a222ec2014-11-12 02:04:27 +00001549 StringRef BytesStr;
Davide Italiano281c1b02015-08-05 07:18:31 +00001550 error(Section.getContents(BytesStr));
Aaron Ballman1caf5202014-11-12 14:01:17 +00001551 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1552 BytesStr.size());
Rafael Espindola6a222ec2014-11-12 02:04:27 +00001553
Michael J. Spencer92e1deb2011-01-20 06:39:06 +00001554 uint64_t Size;
1555 uint64_t Index;
Rafael Auler67fe7952018-03-09 19:13:44 +00001556 bool PrintedSection = false;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +00001557
George Rimar45d116d2019-01-15 09:19:18 +00001558 std::vector<RelocationRef>::const_iterator RelCur = Rels.begin();
1559 std::vector<RelocationRef>::const_iterator RelEnd = Rels.end();
Benjamin Kramer739b65b2011-07-15 18:39:24 +00001560 // Disassemble symbol by symbol.
George Rimar45d116d2019-01-15 09:19:18 +00001561 for (unsigned SI = 0, SE = Symbols.size(); SI != SE; ++SI) {
1562 uint64_t Start = std::get<0>(Symbols[SI]) - SectionAddr;
David Majnemer6ac90f12015-11-18 02:49:19 +00001563 // The end is either the section end or the beginning of the next
1564 // symbol.
George Rimar45d116d2019-01-15 09:19:18 +00001565 uint64_t End = (SI == SE - 1)
1566 ? SectSize
1567 : std::get<0>(Symbols[SI + 1]) - SectionAddr;
David Majnemer6ac90f12015-11-18 02:49:19 +00001568 // Don't try to disassemble beyond the end of section contents.
1569 if (End > SectSize)
1570 End = SectSize;
Rafael Espindola4c511cd2014-08-17 16:31:39 +00001571 // If this symbol has the same address as the next symbol, then skip it.
David Majnemer6ac90f12015-11-18 02:49:19 +00001572 if (Start >= End)
Michael J. Spencer178dbd42011-10-13 20:37:08 +00001573 continue;
1574
Hemant Kulkarni11981cd2016-09-12 17:08:22 +00001575 // Check if we need to skip symbol
1576 // Skip if the symbol's data is not between StartAddress and StopAddress
1577 if (End + SectionAddr < StartAddress ||
1578 Start + SectionAddr > StopAddress) {
1579 continue;
1580 }
1581
Rafael Auler67fe7952018-03-09 19:13:44 +00001582 /// Skip if user requested specific symbols and this is not in the list
1583 if (!DisasmFuncsSet.empty() &&
George Rimar45d116d2019-01-15 09:19:18 +00001584 !DisasmFuncsSet.count(std::get<1>(Symbols[SI])))
Rafael Auler67fe7952018-03-09 19:13:44 +00001585 continue;
1586
1587 if (!PrintedSection) {
1588 PrintedSection = true;
1589 outs() << "Disassembly of section ";
1590 if (!SegmentName.empty())
1591 outs() << SegmentName << ",";
1592 outs() << SectionName << ':';
1593 }
1594
Hemant Kulkarni11981cd2016-09-12 17:08:22 +00001595 // Stop disassembly at the stop address specified
1596 if (End + SectionAddr > StopAddress)
1597 End = StopAddress - SectionAddr;
1598
Valery Pykhtin514b0032016-04-07 07:24:01 +00001599 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
George Rimar45d116d2019-01-15 09:19:18 +00001600 if (std::get<2>(Symbols[SI]) == ELF::STT_AMDGPU_HSA_KERNEL) {
Sam Koltonae331602016-08-17 10:17:57 +00001601 // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)
1602 Start += 256;
1603 }
George Rimar45d116d2019-01-15 09:19:18 +00001604 if (SI == SE - 1 ||
1605 std::get<2>(Symbols[SI + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) {
Sam Koltonae331602016-08-17 10:17:57 +00001606 // cut trailing zeroes at the end of kernel
1607 // cut up to 256 bytes
1608 const uint64_t EndAlign = 256;
1609 const auto Limit = End - (std::min)(EndAlign, End - Start);
1610 while (End > Limit &&
1611 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1612 End -= 4;
1613 }
Valery Pykhtin514b0032016-04-07 07:24:01 +00001614 }
1615
George Rimar92b052b2018-12-19 10:21:45 +00001616 outs() << '\n';
George Rimar56b18a62019-01-09 14:43:33 +00001617 if (!NoLeadingAddr)
1618 outs() << format("%016" PRIx64 " ", SectionAddr + Start);
1619
George Rimar45d116d2019-01-15 09:19:18 +00001620 StringRef SymbolName = std::get<1>(Symbols[SI]);
George Rimar92b052b2018-12-19 10:21:45 +00001621 if (Demangle)
1622 outs() << demangle(SymbolName) << ":\n";
1623 else
1624 outs() << SymbolName << ":\n";
Michael J. Spencer92e1deb2011-01-20 06:39:06 +00001625
Francis Visoiu Mistrih7effcbd2018-04-19 17:02:57 +00001626 // Don't print raw contents of a virtual section. A virtual section
1627 // doesn't have any contents in the file.
1628 if (Section.isVirtual()) {
1629 outs() << "...\n";
1630 continue;
1631 }
1632
Benjamin Kramer739b65b2011-07-15 18:39:24 +00001633#ifndef NDEBUG
Mark Seaborn2760cc22014-01-25 00:32:01 +00001634 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramer739b65b2011-07-15 18:39:24 +00001635#else
Mark Seaborn2760cc22014-01-25 00:32:01 +00001636 raw_ostream &DebugOut = nulls();
Benjamin Kramer739b65b2011-07-15 18:39:24 +00001637#endif
1638
Benjamin Kramer0b8b7712011-09-19 17:56:04 +00001639 for (Index = Start; Index < End; Index += Size) {
1640 MCInst Inst;
Owen Anderson98c5dda2011-09-15 23:38:46 +00001641
Hemant Kulkarni11981cd2016-09-12 17:08:22 +00001642 if (Index + SectionAddr < StartAddress ||
1643 Index + SectionAddr > StopAddress) {
1644 // skip byte by byte till StartAddress is reached
1645 Size = 1;
1646 continue;
1647 }
Davide Italiano52c04442015-10-01 21:57:09 +00001648 // AArch64 ELF binaries can interleave data and text in the
1649 // same section. We rely on the markers introduced to
Hemant Kulkarnic76060f2016-08-25 19:41:08 +00001650 // understand what we need to dump. If the data marker is within a
1651 // function, it is denoted as a word/short etc
George Rimar45d116d2019-01-15 09:19:18 +00001652 if (isArmElf(Obj) && std::get<2>(Symbols[SI]) != ELF::STT_OBJECT &&
Hemant Kulkarnic76060f2016-08-25 19:41:08 +00001653 !DisassembleAll) {
Davide Italiano52c04442015-10-01 21:57:09 +00001654 uint64_t Stride = 0;
1655
1656 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1657 DataMappingSymsAddr.end(), Index);
1658 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1659 // Switch to data.
1660 while (Index < End) {
1661 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1662 outs() << "\t";
1663 if (Index + 4 <= End) {
1664 Stride = 4;
1665 dumpBytes(Bytes.slice(Index, 4), outs());
Hemant Kulkarnic76060f2016-08-25 19:41:08 +00001666 outs() << "\t.word\t";
1667 uint32_t Data = 0;
1668 if (Obj->isLittleEndian()) {
1669 const auto Word =
1670 reinterpret_cast<const support::ulittle32_t *>(
1671 Bytes.data() + Index);
1672 Data = *Word;
1673 } else {
1674 const auto Word = reinterpret_cast<const support::ubig32_t *>(
1675 Bytes.data() + Index);
1676 Data = *Word;
1677 }
1678 outs() << "0x" << format("%08" PRIx32, Data);
Davide Italiano52c04442015-10-01 21:57:09 +00001679 } else if (Index + 2 <= End) {
1680 Stride = 2;
1681 dumpBytes(Bytes.slice(Index, 2), outs());
Hemant Kulkarnic76060f2016-08-25 19:41:08 +00001682 outs() << "\t\t.short\t";
1683 uint16_t Data = 0;
1684 if (Obj->isLittleEndian()) {
1685 const auto Short =
1686 reinterpret_cast<const support::ulittle16_t *>(
1687 Bytes.data() + Index);
1688 Data = *Short;
1689 } else {
1690 const auto Short =
1691 reinterpret_cast<const support::ubig16_t *>(Bytes.data() +
1692 Index);
1693 Data = *Short;
1694 }
1695 outs() << "0x" << format("%04" PRIx16, Data);
Davide Italiano52c04442015-10-01 21:57:09 +00001696 } else {
1697 Stride = 1;
1698 dumpBytes(Bytes.slice(Index, 1), outs());
Hemant Kulkarnic76060f2016-08-25 19:41:08 +00001699 outs() << "\t\t.byte\t";
1700 outs() << "0x" << format("%02" PRIx8, Bytes.slice(Index, 1)[0]);
Davide Italiano52c04442015-10-01 21:57:09 +00001701 }
1702 Index += Stride;
1703 outs() << "\n";
1704 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1705 TextMappingSymsAddr.end(), Index);
1706 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1707 break;
1708 }
1709 }
1710 }
1711
Hemant Kulkarnic76060f2016-08-25 19:41:08 +00001712 // If there is a data symbol inside an ELF text section and we are only
1713 // disassembling text (applicable all architectures),
1714 // we are in a situation where we must print the data and not
1715 // disassemble it.
George Rimar45d116d2019-01-15 09:19:18 +00001716 if (Obj->isELF() && std::get<2>(Symbols[SI]) == ELF::STT_OBJECT &&
Hemant Kulkarnic76060f2016-08-25 19:41:08 +00001717 !DisassembleAll && Section.isText()) {
1718 // print out data up to 8 bytes at a time in hex and ascii
1719 uint8_t AsciiData[9] = {'\0'};
1720 uint8_t Byte;
1721 int NumBytes = 0;
1722
1723 for (Index = Start; Index < End; Index += 1) {
Hemant Kulkarni11981cd2016-09-12 17:08:22 +00001724 if (((SectionAddr + Index) < StartAddress) ||
1725 ((SectionAddr + Index) > StopAddress))
1726 continue;
Hemant Kulkarnic76060f2016-08-25 19:41:08 +00001727 if (NumBytes == 0) {
1728 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1729 outs() << "\t";
1730 }
1731 Byte = Bytes.slice(Index)[0];
1732 outs() << format(" %02x", Byte);
Michael Kruse6069e662018-07-26 15:31:41 +00001733 AsciiData[NumBytes] = isPrint(Byte) ? Byte : '.';
Hemant Kulkarnic76060f2016-08-25 19:41:08 +00001734
1735 uint8_t IndentOffset = 0;
1736 NumBytes++;
1737 if (Index == End - 1 || NumBytes > 8) {
1738 // Indent the space for less than 8 bytes data.
1739 // 2 spaces for byte and one for space between bytes
1740 IndentOffset = 3 * (8 - NumBytes);
1741 for (int Excess = 8 - NumBytes; Excess < 8; Excess++)
1742 AsciiData[Excess] = '\0';
1743 NumBytes = 8;
1744 }
1745 if (NumBytes == 8) {
1746 AsciiData[8] = '\0';
1747 outs() << std::string(IndentOffset, ' ') << " ";
1748 outs() << reinterpret_cast<char *>(AsciiData);
1749 outs() << '\n';
1750 NumBytes = 0;
1751 }
1752 }
1753 }
Davide Italiano52c04442015-10-01 21:57:09 +00001754 if (Index >= End)
1755 break;
1756
George Rimar54820302019-01-10 14:55:26 +00001757 if (size_t N =
1758 countSkippableZeroBytes(Bytes.slice(Index, End - Index))) {
1759 outs() << "\t\t..." << '\n';
1760 Index += N;
1761 if (Index >= End)
1762 break;
1763 }
1764
Hemant Kulkarnic76060f2016-08-25 19:41:08 +00001765 // Disassemble a real instruction or a data when disassemble all is
1766 // provided
Colin LeMahieu16616832016-03-18 16:26:48 +00001767 bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1768 SectionAddr + Index, DebugOut,
1769 CommentStream);
1770 if (Size == 0)
1771 Size = 1;
Hemant Kulkarni502957c2016-08-15 19:49:24 +00001772
Colin LeMahieu16616832016-03-18 16:26:48 +00001773 PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
Hemant Kulkarni502957c2016-08-15 19:49:24 +00001774 Bytes.slice(Index, Size), SectionAddr + Index, outs(), "",
Sid Manning86cf2322018-05-14 19:46:08 +00001775 *STI, &SP, &Rels);
Colin LeMahieu16616832016-03-18 16:26:48 +00001776 outs() << CommentStream.str();
1777 Comments.clear();
David Majnemer6ac90f12015-11-18 02:49:19 +00001778
Colin LeMahieu16616832016-03-18 16:26:48 +00001779 // Try to resolve the target of a call, tail call, etc. to a specific
1780 // symbol.
1781 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1782 MIA->isConditionalBranch(Inst))) {
1783 uint64_t Target;
1784 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1785 // In a relocatable object, the target's section must reside in
1786 // the same section as the call instruction or it is accessed
1787 // through a relocation.
1788 //
1789 // In a non-relocatable object, the target may be in any section.
1790 //
1791 // N.B. We don't walk the relocations in the relocatable case yet.
1792 auto *TargetSectionSymbols = &Symbols;
1793 if (!Obj->isRelocatableObject()) {
1794 auto SectionAddress = std::upper_bound(
1795 SectionAddresses.begin(), SectionAddresses.end(), Target,
1796 [](uint64_t LHS,
1797 const std::pair<uint64_t, SectionRef> &RHS) {
1798 return LHS < RHS.first;
1799 });
1800 if (SectionAddress != SectionAddresses.begin()) {
1801 --SectionAddress;
1802 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1803 } else {
Sterling Augustine3605e122018-06-28 18:57:13 +00001804 TargetSectionSymbols = &AbsoluteSymbols;
David Majnemer6ac90f12015-11-18 02:49:19 +00001805 }
Colin LeMahieu16616832016-03-18 16:26:48 +00001806 }
David Majnemerf2c71ff2015-07-09 18:11:40 +00001807
Colin LeMahieu16616832016-03-18 16:26:48 +00001808 // Find the first symbol in the section whose offset is less than
Sterling Augustine3605e122018-06-28 18:57:13 +00001809 // or equal to the target. If there isn't a section that contains
1810 // the target, find the nearest preceding absolute symbol.
1811 auto TargetSym = std::upper_bound(
1812 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1813 Target, [](uint64_t LHS,
1814 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1815 return LHS < std::get<0>(RHS);
1816 });
1817 if (TargetSym == TargetSectionSymbols->begin()) {
1818 TargetSectionSymbols = &AbsoluteSymbols;
1819 TargetSym = std::upper_bound(
1820 AbsoluteSymbols.begin(), AbsoluteSymbols.end(),
Colin LeMahieu16616832016-03-18 16:26:48 +00001821 Target, [](uint64_t LHS,
Sam Koltonae331602016-08-17 10:17:57 +00001822 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
Sterling Augustine3605e122018-06-28 18:57:13 +00001823 return LHS < std::get<0>(RHS);
1824 });
1825 }
1826 if (TargetSym != TargetSectionSymbols->begin()) {
1827 --TargetSym;
1828 uint64_t TargetAddress = std::get<0>(*TargetSym);
1829 StringRef TargetName = std::get<1>(*TargetSym);
1830 outs() << " <" << TargetName;
1831 uint64_t Disp = Target - TargetAddress;
1832 if (Disp)
1833 outs() << "+0x" << Twine::utohexstr(Disp);
1834 outs() << '>';
David Majnemerb99ee322015-07-07 22:06:59 +00001835 }
1836 }
Benjamin Kramer739b65b2011-07-15 18:39:24 +00001837 }
Colin LeMahieu16616832016-03-18 16:26:48 +00001838 outs() << "\n";
Michael J. Spencer942eb002011-10-13 22:17:18 +00001839
Sid Manning86cf2322018-05-14 19:46:08 +00001840 // Hexagon does this in pretty printer
1841 if (Obj->getArch() != Triple::hexagon)
1842 // Print relocation for instruction.
George Rimar45d116d2019-01-15 09:19:18 +00001843 while (RelCur != RelEnd) {
1844 uint64_t Addr = RelCur->getOffset();
1845 SmallString<16> Name;
1846 SmallString<32> Val;
Owen Anderson0685e942011-10-25 20:35:53 +00001847
Sid Manning86cf2322018-05-14 19:46:08 +00001848 // If this relocation is hidden, skip it.
George Rimar45d116d2019-01-15 09:19:18 +00001849 if (getHidden(*RelCur) || ((SectionAddr + Addr) < StartAddress)) {
1850 ++RelCur;
Sid Manning86cf2322018-05-14 19:46:08 +00001851 continue;
1852 }
1853
1854 // Stop when rel_cur's address is past the current instruction.
George Rimar45d116d2019-01-15 09:19:18 +00001855 if (Addr >= Index + Size)
1856 break;
1857 RelCur->getTypeName(Name);
1858 error(getRelocationValueString(*RelCur, Val));
1859 outs() << format(Fmt.data(), SectionAddr + Addr) << Name << "\t"
1860 << Val << "\n";
1861 ++RelCur;
Hemant Kulkarni11981cd2016-09-12 17:08:22 +00001862 }
Benjamin Kramer685a2502011-07-20 19:37:35 +00001863 }
Michael J. Spencer92e1deb2011-01-20 06:39:06 +00001864 }
1865 }
1866}
1867
George Rimar45d116d2019-01-15 09:19:18 +00001868void llvm::printRelocations(const ObjectFile *Obj) {
Greg Fitzgeraldaff0ab42014-03-20 22:55:15 +00001869 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1870 "%08" PRIx64;
Rafael Espindola05601d52016-03-21 20:59:15 +00001871 // Regular objdump doesn't print relocations in non-relocatable object
1872 // files.
1873 if (!Obj->isRelocatableObject())
1874 return;
Rafael Espindola78e8d522014-08-17 19:09:37 +00001875
Colin LeMahieuedbf9d72015-07-29 15:45:39 +00001876 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov7a2da952014-03-13 14:37:36 +00001877 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencer27781b72011-10-08 00:18:30 +00001878 continue;
George Rimar45d116d2019-01-15 09:19:18 +00001879 StringRef SecName;
1880 error(Section.getName(SecName));
1881 outs() << "RELOCATION RECORDS FOR [" << SecName << "]:\n";
Alexey Samsonov6f07b352014-03-14 14:22:49 +00001882 for (const RelocationRef &Reloc : Section.relocations()) {
George Rimar45d116d2019-01-15 09:19:18 +00001883 uint64_t Address = Reloc.getOffset();
1884 SmallString<32> RelocName;
1885 SmallString<32> ValueStr;
1886 if (Address < StartAddress || Address > StopAddress || getHidden(Reloc))
Alexey Samsonov6f07b352014-03-14 14:22:49 +00001887 continue;
George Rimar45d116d2019-01-15 09:19:18 +00001888 Reloc.getTypeName(RelocName);
1889 error(getRelocationValueString(Reloc, ValueStr));
1890 outs() << format(Fmt.data(), Address) << " " << RelocName << " "
1891 << ValueStr << "\n";
Michael J. Spencer27781b72011-10-08 00:18:30 +00001892 }
1893 outs() << "\n";
1894 }
1895}
1896
George Rimar45d116d2019-01-15 09:19:18 +00001897void llvm::printDynamicRelocations(const ObjectFile *Obj) {
Paul Semel3fc706582018-06-07 13:30:55 +00001898 // For the moment, this option is for ELF only
1899 if (!Obj->isELF())
1900 return;
1901
1902 const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj);
Paul Semel3fc706582018-06-07 13:30:55 +00001903 if (!Elf || Elf->getEType() != ELF::ET_DYN) {
1904 error("not a dynamic object");
1905 return;
1906 }
1907
Paul Semel3fc706582018-06-07 13:30:55 +00001908 std::vector<SectionRef> DynRelSec = Obj->dynamic_relocation_sections();
1909 if (DynRelSec.empty())
1910 return;
1911
1912 outs() << "DYNAMIC RELOCATION RECORDS\n";
George Rimar45d116d2019-01-15 09:19:18 +00001913 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
Paul Semel3fc706582018-06-07 13:30:55 +00001914 for (const SectionRef &Section : DynRelSec) {
1915 if (Section.relocation_begin() == Section.relocation_end())
1916 continue;
1917 for (const RelocationRef &Reloc : Section.relocations()) {
George Rimar45d116d2019-01-15 09:19:18 +00001918 uint64_t Address = Reloc.getOffset();
1919 SmallString<32> RelocName;
1920 SmallString<32> ValueStr;
1921 Reloc.getTypeName(RelocName);
1922 error(getRelocationValueString(Reloc, ValueStr));
1923 outs() << format(Fmt.data(), Address) << " " << RelocName << " "
1924 << ValueStr << "\n";
Paul Semel3fc706582018-06-07 13:30:55 +00001925 }
1926 }
1927}
1928
George Rimar45d116d2019-01-15 09:19:18 +00001929void llvm::printSectionHeaders(const ObjectFile *Obj) {
Nick Lewycky023bb152011-10-10 21:21:34 +00001930 outs() << "Sections:\n"
1931 "Idx Name Size Address Type\n";
Colin LeMahieuedbf9d72015-07-29 15:45:39 +00001932 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Nick Lewycky023bb152011-10-10 21:21:34 +00001933 StringRef Name;
Davide Italiano281c1b02015-08-05 07:18:31 +00001934 error(Section.getName(Name));
Rafael Espindola8175be52014-10-08 15:28:58 +00001935 uint64_t Address = Section.getAddress();
1936 uint64_t Size = Section.getSize();
1937 bool Text = Section.isText();
1938 bool Data = Section.isData();
1939 bool BSS = Section.isBSS();
Nick Lewycky023bb152011-10-10 21:21:34 +00001940 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer14a5f462011-10-13 20:37:20 +00001941 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
George Rimar10c3b3d2018-07-18 08:34:35 +00001942 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n",
George Rimar9c475e32018-07-18 09:25:36 +00001943 (unsigned)Section.getIndex(), Name.str().c_str(), Size,
1944 Address, Type.c_str());
Nick Lewycky023bb152011-10-10 21:21:34 +00001945 }
Xing GUO4376a272018-11-17 08:12:48 +00001946 outs() << "\n";
Nick Lewycky023bb152011-10-10 21:21:34 +00001947}
1948
George Rimar45d116d2019-01-15 09:19:18 +00001949void llvm::printSectionContents(const ObjectFile *Obj) {
Rafael Espindola1ad45022014-06-13 03:07:50 +00001950 std::error_code EC;
Colin LeMahieuedbf9d72015-07-29 15:45:39 +00001951 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +00001952 StringRef Name;
1953 StringRef Contents;
Davide Italiano281c1b02015-08-05 07:18:31 +00001954 error(Section.getName(Name));
Rafael Espindola8175be52014-10-08 15:28:58 +00001955 uint64_t BaseAddr = Section.getAddress();
David Majnemer1dd631f2014-11-11 09:58:25 +00001956 uint64_t Size = Section.getSize();
1957 if (!Size)
1958 continue;
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +00001959
1960 outs() << "Contents of section " << Name << ":\n";
David Majnemer1dd631f2014-11-11 09:58:25 +00001961 if (Section.isBSS()) {
Alexey Samsonov0eaa6f62013-04-16 10:53:11 +00001962 outs() << format("<skipping contents of bss section at [%04" PRIx64
David Majnemere3aafcc2014-07-14 16:20:14 +00001963 ", %04" PRIx64 ")>\n",
1964 BaseAddr, BaseAddr + Size);
Alexey Samsonov0eaa6f62013-04-16 10:53:11 +00001965 continue;
1966 }
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +00001967
Davide Italiano281c1b02015-08-05 07:18:31 +00001968 error(Section.getContents(Contents));
David Majnemere3aafcc2014-07-14 16:20:14 +00001969
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +00001970 // Dump out the content as hex and printable ascii characters.
George Rimar45d116d2019-01-15 09:19:18 +00001971 for (std::size_t Addr = 0, End = Contents.size(); Addr < End; Addr += 16) {
1972 outs() << format(" %04" PRIx64 " ", BaseAddr + Addr);
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +00001973 // Dump line of hex.
George Rimar45d116d2019-01-15 09:19:18 +00001974 for (std::size_t I = 0; I < 16; ++I) {
1975 if (I != 0 && I % 4 == 0)
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +00001976 outs() << ' ';
George Rimar45d116d2019-01-15 09:19:18 +00001977 if (Addr + I < End)
1978 outs() << hexdigit((Contents[Addr + I] >> 4) & 0xF, true)
1979 << hexdigit(Contents[Addr + I] & 0xF, true);
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +00001980 else
1981 outs() << " ";
1982 }
1983 // Print ascii.
1984 outs() << " ";
George Rimar45d116d2019-01-15 09:19:18 +00001985 for (std::size_t I = 0; I < 16 && Addr + I < End; ++I) {
1986 if (isPrint(static_cast<unsigned char>(Contents[Addr + I]) & 0xFF))
1987 outs() << Contents[Addr + I];
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +00001988 else
1989 outs() << ".";
1990 }
1991 outs() << "\n";
1992 }
1993 }
1994}
1995
George Rimar45d116d2019-01-15 09:19:18 +00001996void llvm::printSymbolTable(const ObjectFile *O, StringRef ArchiveName,
Kevin Enderbye9ddf3a2016-05-31 20:35:34 +00001997 StringRef ArchitectureName) {
Michael J. Spencer22ff0f32011-10-18 19:32:17 +00001998 outs() << "SYMBOL TABLE:\n";
1999
George Rimar45d116d2019-01-15 09:19:18 +00002000 if (const COFFObjectFile *Coff = dyn_cast<const COFFObjectFile>(O)) {
2001 printCOFFSymbolTable(Coff);
Rui Ueyama172c3182014-03-18 18:58:51 +00002002 return;
2003 }
George Rimar03e297e2019-01-10 16:24:10 +00002004
George Rimar45d116d2019-01-15 09:19:18 +00002005 for (auto I = O->symbol_begin(), E = O->symbol_end(); I != E; ++I) {
George Rimar03e297e2019-01-10 16:24:10 +00002006 // Skip printing the special zero symbol when dumping an ELF file.
2007 // This makes the output consistent with the GNU objdump.
George Rimar45d116d2019-01-15 09:19:18 +00002008 if (I == O->symbol_begin() && isa<ELFObjectFileBase>(O))
George Rimar03e297e2019-01-10 16:24:10 +00002009 continue;
2010
2011 const SymbolRef &Symbol = *I;
Kevin Enderby317de7c2016-06-24 18:24:42 +00002012 Expected<uint64_t> AddressOrError = Symbol.getAddress();
2013 if (!AddressOrError)
George Rimar45d116d2019-01-15 09:19:18 +00002014 report_error(ArchiveName, O->getFileName(), AddressOrError.takeError(),
Kevin Enderbyfbd189d2016-11-16 22:17:38 +00002015 ArchitectureName);
Rafael Espindola5954faa2015-07-03 18:19:00 +00002016 uint64_t Address = *AddressOrError;
Hemant Kulkarni11981cd2016-09-12 17:08:22 +00002017 if ((Address < StartAddress) || (Address > StopAddress))
2018 continue;
Kevin Enderbya486dca2016-05-02 20:28:12 +00002019 Expected<SymbolRef::Type> TypeOrError = Symbol.getType();
2020 if (!TypeOrError)
George Rimar45d116d2019-01-15 09:19:18 +00002021 report_error(ArchiveName, O->getFileName(), TypeOrError.takeError(),
Kevin Enderbyfbd189d2016-11-16 22:17:38 +00002022 ArchitectureName);
Kevin Enderby46e35ed2016-03-23 20:27:00 +00002023 SymbolRef::Type Type = *TypeOrError;
Rui Ueyama172c3182014-03-18 18:58:51 +00002024 uint32_t Flags = Symbol.getFlags();
Kevin Enderbya486dca2016-05-02 20:28:12 +00002025 Expected<section_iterator> SectionOrErr = Symbol.getSection();
Kevin Enderbyfbd189d2016-11-16 22:17:38 +00002026 if (!SectionOrErr)
George Rimar45d116d2019-01-15 09:19:18 +00002027 report_error(ArchiveName, O->getFileName(), SectionOrErr.takeError(),
Kevin Enderbyfbd189d2016-11-16 22:17:38 +00002028 ArchitectureName);
Rafael Espindolae84d8c12015-08-07 23:27:14 +00002029 section_iterator Section = *SectionOrErr;
Rafael Espindola201a5512015-06-03 05:14:22 +00002030 StringRef Name;
George Rimar45d116d2019-01-15 09:19:18 +00002031 if (Type == SymbolRef::ST_Debug && Section != O->section_end()) {
Rafael Espindola201a5512015-06-03 05:14:22 +00002032 Section->getName(Name);
Rafael Espindola8a806412015-07-02 20:55:21 +00002033 } else {
Kevin Enderby813e0cf2016-04-20 21:24:34 +00002034 Expected<StringRef> NameOrErr = Symbol.getName();
2035 if (!NameOrErr)
George Rimar45d116d2019-01-15 09:19:18 +00002036 report_error(ArchiveName, O->getFileName(), NameOrErr.takeError(),
Kevin Enderbye9ddf3a2016-05-31 20:35:34 +00002037 ArchitectureName);
Rafael Espindola8a806412015-07-02 20:55:21 +00002038 Name = *NameOrErr;
Rafael Espindola201a5512015-06-03 05:14:22 +00002039 }
Michael J. Spencer22ff0f32011-10-18 19:32:17 +00002040
Rui Ueyama172c3182014-03-18 18:58:51 +00002041 bool Global = Flags & SymbolRef::SF_Global;
2042 bool Weak = Flags & SymbolRef::SF_Weak;
2043 bool Absolute = Flags & SymbolRef::SF_Absolute;
Colin LeMahieu88fa6642015-01-23 20:06:24 +00002044 bool Common = Flags & SymbolRef::SF_Common;
Davide Italiano0c54b7a2015-04-30 23:08:53 +00002045 bool Hidden = Flags & SymbolRef::SF_Hidden;
David Meyerc46255a2012-02-28 23:47:53 +00002046
Rui Ueyama172c3182014-03-18 18:58:51 +00002047 char GlobLoc = ' ';
2048 if (Type != SymbolRef::ST_Unknown)
2049 GlobLoc = Global ? 'g' : 'l';
2050 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
2051 ? 'd' : ' ';
2052 char FileFunc = ' ';
2053 if (Type == SymbolRef::ST_File)
2054 FileFunc = 'f';
2055 else if (Type == SymbolRef::ST_Function)
2056 FileFunc = 'F';
Kristina Brooks11c08882018-11-11 17:47:13 +00002057 else if (Type == SymbolRef::ST_Data)
2058 FileFunc = 'O';
Michael J. Spencer22ff0f32011-10-18 19:32:17 +00002059
George Rimar45d116d2019-01-15 09:19:18 +00002060 const char *Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 :
Rui Ueyama172c3182014-03-18 18:58:51 +00002061 "%08" PRIx64;
Michael J. Spencer27b2b1b2013-01-10 22:40:50 +00002062
Rui Ueyama172c3182014-03-18 18:58:51 +00002063 outs() << format(Fmt, Address) << " "
2064 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
2065 << (Weak ? 'w' : ' ') // Weak?
2066 << ' ' // Constructor. Not supported yet.
2067 << ' ' // Warning. Not supported yet.
2068 << ' ' // Indirect reference to another symbol.
2069 << Debug // Debugging (d) or dynamic (D) symbol.
2070 << FileFunc // Name of function (F), file (f) or object (O).
2071 << ' ';
2072 if (Absolute) {
2073 outs() << "*ABS*";
Colin LeMahieu88fa6642015-01-23 20:06:24 +00002074 } else if (Common) {
2075 outs() << "*COM*";
George Rimar45d116d2019-01-15 09:19:18 +00002076 } else if (Section == O->section_end()) {
Rui Ueyama172c3182014-03-18 18:58:51 +00002077 outs() << "*UND*";
2078 } else {
2079 if (const MachOObjectFile *MachO =
George Rimar45d116d2019-01-15 09:19:18 +00002080 dyn_cast<const MachOObjectFile>(O)) {
Rui Ueyama172c3182014-03-18 18:58:51 +00002081 DataRefImpl DR = Section->getRawDataRefImpl();
2082 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
2083 outs() << SegmentName << ",";
Michael J. Spencer22ff0f32011-10-18 19:32:17 +00002084 }
Rui Ueyama172c3182014-03-18 18:58:51 +00002085 StringRef SectionName;
Davide Italiano281c1b02015-08-05 07:18:31 +00002086 error(Section->getName(SectionName));
Rui Ueyama172c3182014-03-18 18:58:51 +00002087 outs() << SectionName;
Michael J. Spencer22ff0f32011-10-18 19:32:17 +00002088 }
Rafael Espindolabd1e6052015-06-23 15:45:38 +00002089
2090 outs() << '\t';
George Rimar45d116d2019-01-15 09:19:18 +00002091 if (Common || isa<ELFObjectFileBase>(O)) {
Rafael Espindolab24bbb72015-06-25 22:10:04 +00002092 uint64_t Val =
2093 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
Rafael Espindola8bb10c62015-06-23 18:34:25 +00002094 outs() << format("\t %08" PRIx64 " ", Val);
2095 }
Rafael Espindolabd1e6052015-06-23 15:45:38 +00002096
George Rimar45d116d2019-01-15 09:19:18 +00002097 if (Hidden)
Davide Italiano0c54b7a2015-04-30 23:08:53 +00002098 outs() << ".hidden ";
George Rimar92b052b2018-12-19 10:21:45 +00002099
2100 if (Demangle)
2101 outs() << demangle(Name) << '\n';
2102 else
2103 outs() << Name << '\n';
Michael J. Spencer22ff0f32011-10-18 19:32:17 +00002104 }
2105}
2106
George Rimar45d116d2019-01-15 09:19:18 +00002107static void printUnwindInfo(const ObjectFile *O) {
Michael J. Spencereef7b622012-12-05 20:12:35 +00002108 outs() << "Unwind info:\n\n";
2109
George Rimar45d116d2019-01-15 09:19:18 +00002110 if (const COFFObjectFile *Coff = dyn_cast<COFFObjectFile>(O))
2111 printCOFFUnwindInfo(Coff);
2112 else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O))
Tim Northoverf28a36e2014-08-01 13:07:19 +00002113 printMachOUnwindInfo(MachO);
George Rimar45d116d2019-01-15 09:19:18 +00002114 else
Michael J. Spencereef7b622012-12-05 20:12:35 +00002115 // TODO: Extract DWARF dump tool to objdump.
Jonas Devlieghere8e8485e2018-11-11 22:12:04 +00002116 WithColor::error(errs(), ToolName)
2117 << "This operation is only currently supported "
2118 "for COFF and MachO object files.\n";
Michael J. Spencereef7b622012-12-05 20:12:35 +00002119}
2120
Kevin Enderby60e9ca42015-01-07 21:02:18 +00002121void llvm::printExportsTrie(const ObjectFile *o) {
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00002122 outs() << "Exports trie:\n";
2123 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
2124 printMachOExportsTrie(MachO);
George Rimar45d116d2019-01-15 09:19:18 +00002125 else
Jonas Devlieghere8e8485e2018-11-11 22:12:04 +00002126 WithColor::error(errs(), ToolName)
2127 << "This operation is only currently supported "
2128 "for Mach-O executable files.\n";
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00002129}
2130
Kevin Enderby1ae32f12017-03-20 19:46:55 +00002131void llvm::printRebaseTable(ObjectFile *o) {
Nick Kledzika240fc52014-09-12 21:34:15 +00002132 outs() << "Rebase table:\n";
Kevin Enderby1ae32f12017-03-20 19:46:55 +00002133 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzika240fc52014-09-12 21:34:15 +00002134 printMachORebaseTable(MachO);
George Rimar45d116d2019-01-15 09:19:18 +00002135 else
Jonas Devlieghere8e8485e2018-11-11 22:12:04 +00002136 WithColor::error(errs(), ToolName)
2137 << "This operation is only currently supported "
2138 "for Mach-O executable files.\n";
Nick Kledzika240fc52014-09-12 21:34:15 +00002139}
2140
Kevin Enderby1ae32f12017-03-20 19:46:55 +00002141void llvm::printBindTable(ObjectFile *o) {
Nick Kledzik367cf702014-09-16 01:41:51 +00002142 outs() << "Bind table:\n";
Kevin Enderby1ae32f12017-03-20 19:46:55 +00002143 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzik367cf702014-09-16 01:41:51 +00002144 printMachOBindTable(MachO);
George Rimar45d116d2019-01-15 09:19:18 +00002145 else
Jonas Devlieghere8e8485e2018-11-11 22:12:04 +00002146 WithColor::error(errs(), ToolName)
2147 << "This operation is only currently supported "
2148 "for Mach-O executable files.\n";
Nick Kledzik367cf702014-09-16 01:41:51 +00002149}
2150
Kevin Enderby1ae32f12017-03-20 19:46:55 +00002151void llvm::printLazyBindTable(ObjectFile *o) {
Nick Kledzik367cf702014-09-16 01:41:51 +00002152 outs() << "Lazy bind table:\n";
Kevin Enderby1ae32f12017-03-20 19:46:55 +00002153 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzik367cf702014-09-16 01:41:51 +00002154 printMachOLazyBindTable(MachO);
George Rimar45d116d2019-01-15 09:19:18 +00002155 else
Jonas Devlieghere8e8485e2018-11-11 22:12:04 +00002156 WithColor::error(errs(), ToolName)
2157 << "This operation is only currently supported "
2158 "for Mach-O executable files.\n";
Nick Kledzik367cf702014-09-16 01:41:51 +00002159}
2160
Kevin Enderby1ae32f12017-03-20 19:46:55 +00002161void llvm::printWeakBindTable(ObjectFile *o) {
Nick Kledzik367cf702014-09-16 01:41:51 +00002162 outs() << "Weak bind table:\n";
Kevin Enderby1ae32f12017-03-20 19:46:55 +00002163 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzik367cf702014-09-16 01:41:51 +00002164 printMachOWeakBindTable(MachO);
George Rimar45d116d2019-01-15 09:19:18 +00002165 else
Jonas Devlieghere8e8485e2018-11-11 22:12:04 +00002166 WithColor::error(errs(), ToolName)
2167 << "This operation is only currently supported "
2168 "for Mach-O executable files.\n";
Nick Kledzik367cf702014-09-16 01:41:51 +00002169}
Nick Kledzika240fc52014-09-12 21:34:15 +00002170
Adrian Prantl54a27682015-07-08 02:04:15 +00002171/// Dump the raw contents of the __clangast section so the output can be piped
2172/// into llvm-bcanalyzer.
2173void llvm::printRawClangAST(const ObjectFile *Obj) {
2174 if (outs().is_displayed()) {
Jonas Devlieghere8e8485e2018-11-11 22:12:04 +00002175 WithColor::error(errs(), ToolName)
2176 << "The -raw-clang-ast option will dump the raw binary contents of "
2177 "the clang ast section.\n"
2178 "Please redirect the output to a file or another program such as "
2179 "llvm-bcanalyzer.\n";
Adrian Prantl54a27682015-07-08 02:04:15 +00002180 return;
2181 }
2182
2183 StringRef ClangASTSectionName("__clangast");
2184 if (isa<COFFObjectFile>(Obj)) {
2185 ClangASTSectionName = "clangast";
2186 }
2187
2188 Optional<object::SectionRef> ClangASTSection;
Colin LeMahieuedbf9d72015-07-29 15:45:39 +00002189 for (auto Sec : ToolSectionFilter(*Obj)) {
Adrian Prantl54a27682015-07-08 02:04:15 +00002190 StringRef Name;
2191 Sec.getName(Name);
2192 if (Name == ClangASTSectionName) {
2193 ClangASTSection = Sec;
2194 break;
2195 }
2196 }
2197 if (!ClangASTSection)
2198 return;
2199
2200 StringRef ClangASTContents;
Davide Italiano281c1b02015-08-05 07:18:31 +00002201 error(ClangASTSection.getValue().getContents(ClangASTContents));
Adrian Prantl54a27682015-07-08 02:04:15 +00002202 outs().write(ClangASTContents.data(), ClangASTContents.size());
2203}
2204
Sanjoy Dase0ef46e2015-06-22 18:03:02 +00002205static void printFaultMaps(const ObjectFile *Obj) {
George Rimar45d116d2019-01-15 09:19:18 +00002206 StringRef FaultMapSectionName;
Sanjoy Dase0ef46e2015-06-22 18:03:02 +00002207
2208 if (isa<ELFObjectFileBase>(Obj)) {
2209 FaultMapSectionName = ".llvm_faultmaps";
2210 } else if (isa<MachOObjectFile>(Obj)) {
2211 FaultMapSectionName = "__llvm_faultmaps";
2212 } else {
Jonas Devlieghere8e8485e2018-11-11 22:12:04 +00002213 WithColor::error(errs(), ToolName)
2214 << "This operation is only currently supported "
2215 "for ELF and Mach-O executable files.\n";
Sanjoy Dase0ef46e2015-06-22 18:03:02 +00002216 return;
2217 }
2218
2219 Optional<object::SectionRef> FaultMapSection;
2220
Colin LeMahieuedbf9d72015-07-29 15:45:39 +00002221 for (auto Sec : ToolSectionFilter(*Obj)) {
Sanjoy Dase0ef46e2015-06-22 18:03:02 +00002222 StringRef Name;
2223 Sec.getName(Name);
2224 if (Name == FaultMapSectionName) {
2225 FaultMapSection = Sec;
2226 break;
2227 }
2228 }
2229
2230 outs() << "FaultMap table:\n";
2231
2232 if (!FaultMapSection.hasValue()) {
2233 outs() << "<not found>\n";
2234 return;
2235 }
2236
2237 StringRef FaultMapContents;
Davide Italiano281c1b02015-08-05 07:18:31 +00002238 error(FaultMapSection.getValue().getContents(FaultMapContents));
Sanjoy Dase0ef46e2015-06-22 18:03:02 +00002239
2240 FaultMapParser FMP(FaultMapContents.bytes_begin(),
2241 FaultMapContents.bytes_end());
2242
2243 outs() << FMP;
2244}
2245
George Rimar45d116d2019-01-15 09:19:18 +00002246static void printPrivateFileHeaders(const ObjectFile *O, bool OnlyFirst) {
2247 if (O->isELF()) {
2248 printELFFileHeader(O);
2249 return printELFDynamicSection(O);
Paul Semel05d358b2018-07-25 11:09:20 +00002250 }
George Rimar45d116d2019-01-15 09:19:18 +00002251 if (O->isCOFF())
2252 return printCOFFFileHeader(O);
2253 if (O->isWasm())
2254 return printWasmFileHeader(O);
2255 if (O->isMachO()) {
2256 printMachOFileHeader(O);
2257 if (!OnlyFirst)
2258 printMachOLoadCommands(O);
Davide Italiano4b868ad2016-09-18 04:39:15 +00002259 return;
2260 }
George Rimar45d116d2019-01-15 09:19:18 +00002261 report_error(O->getFileName(), "Invalid/Unsupported object file format");
Rui Ueyamaa6610ee2013-09-27 21:04:00 +00002262}
2263
George Rimar45d116d2019-01-15 09:19:18 +00002264static void printFileHeaders(const ObjectFile *O) {
2265 if (!O->isELF() && !O->isCOFF())
2266 report_error(O->getFileName(), "Invalid/Unsupported object file format");
Paul Semeld069a212018-07-04 15:25:03 +00002267
George Rimar45d116d2019-01-15 09:19:18 +00002268 Triple::ArchType AT = O->getArch();
Paul Semeld069a212018-07-04 15:25:03 +00002269 outs() << "architecture: " << Triple::getArchTypeName(AT) << "\n";
George Rimar45d116d2019-01-15 09:19:18 +00002270 Expected<uint64_t> StartAddrOrErr = O->getStartAddress();
Paul Semeld069a212018-07-04 15:25:03 +00002271 if (!StartAddrOrErr)
George Rimar45d116d2019-01-15 09:19:18 +00002272 report_error(O->getFileName(), StartAddrOrErr.takeError());
Petar Jovanovic95eb9152018-10-19 22:16:49 +00002273
George Rimar45d116d2019-01-15 09:19:18 +00002274 StringRef Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
Petar Jovanovic95eb9152018-10-19 22:16:49 +00002275 uint64_t Address = StartAddrOrErr.get();
Paul Semeld069a212018-07-04 15:25:03 +00002276 outs() << "start address: "
George Rimar04fde6b2019-01-12 12:17:24 +00002277 << "0x" << format(Fmt.data(), Address) << "\n\n";
Paul Semeld069a212018-07-04 15:25:03 +00002278}
2279
Paul Semelfd466782018-07-05 14:43:29 +00002280static void printArchiveChild(StringRef Filename, const Archive::Child &C) {
2281 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
2282 if (!ModeOrErr) {
Jonas Devlieghere8e8485e2018-11-11 22:12:04 +00002283 WithColor::error(errs(), ToolName) << "ill-formed archive entry.\n";
Paul Semelfd466782018-07-05 14:43:29 +00002284 consumeError(ModeOrErr.takeError());
2285 return;
2286 }
2287 sys::fs::perms Mode = ModeOrErr.get();
2288 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
2289 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
2290 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
2291 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
2292 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
2293 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
2294 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
2295 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
2296 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
2297
2298 outs() << " ";
2299
2300 Expected<unsigned> UIDOrErr = C.getUID();
2301 if (!UIDOrErr)
2302 report_error(Filename, UIDOrErr.takeError());
2303 unsigned UID = UIDOrErr.get();
2304 outs() << format("%d/", UID);
2305
2306 Expected<unsigned> GIDOrErr = C.getGID();
2307 if (!GIDOrErr)
2308 report_error(Filename, GIDOrErr.takeError());
2309 unsigned GID = GIDOrErr.get();
2310 outs() << format("%-d ", GID);
2311
2312 Expected<uint64_t> Size = C.getRawSize();
2313 if (!Size)
2314 report_error(Filename, Size.takeError());
2315 outs() << format("%6" PRId64, Size.get()) << " ";
2316
2317 StringRef RawLastModified = C.getRawLastModified();
2318 unsigned Seconds;
2319 if (RawLastModified.getAsInteger(10, Seconds))
2320 outs() << "(date: \"" << RawLastModified
2321 << "\" contains non-decimal chars) ";
2322 else {
2323 // Since ctime(3) returns a 26 character string of the form:
2324 // "Sun Sep 16 01:03:52 1973\n\0"
2325 // just print 24 characters.
2326 time_t t = Seconds;
2327 outs() << format("%.24s ", ctime(&t));
2328 }
2329
2330 StringRef Name = "";
2331 Expected<StringRef> NameOrErr = C.getName();
2332 if (!NameOrErr) {
2333 consumeError(NameOrErr.takeError());
2334 Expected<StringRef> RawNameOrErr = C.getRawName();
2335 if (!RawNameOrErr)
2336 report_error(Filename, NameOrErr.takeError());
2337 Name = RawNameOrErr.get();
2338 } else {
2339 Name = NameOrErr.get();
2340 }
2341 outs() << Name << "\n";
2342}
2343
George Rimar45d116d2019-01-15 09:19:18 +00002344static void dumpObject(ObjectFile *O, const Archive *A = nullptr,
2345 const Archive::Child *C = nullptr) {
Adrian Prantl54a27682015-07-08 02:04:15 +00002346 // Avoid other output when using a raw option.
2347 if (!RawClangAST) {
2348 outs() << '\n';
George Rimar45d116d2019-01-15 09:19:18 +00002349 if (A)
2350 outs() << A->getFileName() << "(" << O->getFileName() << ")";
Kevin Enderby77be0942016-05-17 17:10:12 +00002351 else
George Rimar45d116d2019-01-15 09:19:18 +00002352 outs() << O->getFileName();
2353 outs() << ":\tfile format " << O->getFileFormatName() << "\n\n";
Adrian Prantl54a27682015-07-08 02:04:15 +00002354 }
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +00002355
George Rimar45d116d2019-01-15 09:19:18 +00002356 StringRef ArchiveName = A ? A->getFileName() : "";
George Rimar04fde6b2019-01-12 12:17:24 +00002357 if (FileHeaders)
George Rimar45d116d2019-01-15 09:19:18 +00002358 printFileHeaders(O);
2359 if (ArchiveHeaders && !MachOOpt && C)
2360 printArchiveChild(ArchiveName, *C);
Michael J. Spencer27781b72011-10-08 00:18:30 +00002361 if (Disassemble)
George Rimar45d116d2019-01-15 09:19:18 +00002362 disassembleObject(O, Relocations);
Michael J. Spencer942eb002011-10-13 22:17:18 +00002363 if (Relocations && !Disassemble)
George Rimar45d116d2019-01-15 09:19:18 +00002364 printRelocations(O);
Paul Semel3fc706582018-06-07 13:30:55 +00002365 if (DynamicRelocations)
George Rimar45d116d2019-01-15 09:19:18 +00002366 printDynamicRelocations(O);
Nick Lewycky023bb152011-10-10 21:21:34 +00002367 if (SectionHeaders)
George Rimar45d116d2019-01-15 09:19:18 +00002368 printSectionHeaders(O);
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +00002369 if (SectionContents)
George Rimar45d116d2019-01-15 09:19:18 +00002370 printSectionContents(O);
Michael J. Spencer22ff0f32011-10-18 19:32:17 +00002371 if (SymbolTable)
George Rimar45d116d2019-01-15 09:19:18 +00002372 printSymbolTable(O, ArchiveName);
Michael J. Spencereef7b622012-12-05 20:12:35 +00002373 if (UnwindInfo)
George Rimar45d116d2019-01-15 09:19:18 +00002374 printUnwindInfo(O);
Davide Italiano4b868ad2016-09-18 04:39:15 +00002375 if (PrivateHeaders || FirstPrivateHeader)
George Rimar45d116d2019-01-15 09:19:18 +00002376 printPrivateFileHeaders(O, FirstPrivateHeader);
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00002377 if (ExportsTrie)
George Rimar45d116d2019-01-15 09:19:18 +00002378 printExportsTrie(O);
Nick Kledzika240fc52014-09-12 21:34:15 +00002379 if (Rebase)
George Rimar45d116d2019-01-15 09:19:18 +00002380 printRebaseTable(O);
Nick Kledzik367cf702014-09-16 01:41:51 +00002381 if (Bind)
George Rimar45d116d2019-01-15 09:19:18 +00002382 printBindTable(O);
Nick Kledzik367cf702014-09-16 01:41:51 +00002383 if (LazyBind)
George Rimar45d116d2019-01-15 09:19:18 +00002384 printLazyBindTable(O);
Nick Kledzik367cf702014-09-16 01:41:51 +00002385 if (WeakBind)
George Rimar45d116d2019-01-15 09:19:18 +00002386 printWeakBindTable(O);
Adrian Prantl54a27682015-07-08 02:04:15 +00002387 if (RawClangAST)
George Rimar45d116d2019-01-15 09:19:18 +00002388 printRawClangAST(O);
Sanjoy Dase0ef46e2015-06-22 18:03:02 +00002389 if (PrintFaultMaps)
George Rimar45d116d2019-01-15 09:19:18 +00002390 printFaultMaps(O);
Igor Laevsky25574802016-01-26 15:09:42 +00002391 if (DwarfDumpType != DIDT_Null) {
George Rimar45d116d2019-01-15 09:19:18 +00002392 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*O);
Igor Laevsky25574802016-01-26 15:09:42 +00002393 // Dump the complete DWARF structure.
Adrian Prantlad988ad2017-06-01 18:18:23 +00002394 DIDumpOptions DumpOpts;
2395 DumpOpts.DumpType = DwarfDumpType;
Adrian Prantlad988ad2017-06-01 18:18:23 +00002396 DICtx->dump(outs(), DumpOpts);
Igor Laevsky25574802016-01-26 15:09:42 +00002397 }
Michael J. Spencer27781b72011-10-08 00:18:30 +00002398}
2399
George Rimar45d116d2019-01-15 09:19:18 +00002400static void dumpObject(const COFFImportFile *I, const Archive *A,
Paul Semelfd466782018-07-05 14:43:29 +00002401 const Archive::Child *C = nullptr) {
Saleem Abdulrasool8a836022016-08-18 16:39:19 +00002402 StringRef ArchiveName = A ? A->getFileName() : "";
2403
2404 // Avoid other output when using a raw option.
2405 if (!RawClangAST)
2406 outs() << '\n'
2407 << ArchiveName << "(" << I->getFileName() << ")"
2408 << ":\tfile format COFF-import-file"
2409 << "\n\n";
2410
James Hendersond32696a2018-10-29 14:17:08 +00002411 if (ArchiveHeaders && !MachOOpt && C)
2412 printArchiveChild(ArchiveName, *C);
Saleem Abdulrasool8a836022016-08-18 16:39:19 +00002413 if (SymbolTable)
2414 printCOFFSymbolTable(I);
2415}
2416
Adrian Prantl0b24b742018-05-01 16:10:38 +00002417/// Dump each object file in \a a;
George Rimar45d116d2019-01-15 09:19:18 +00002418static void dumpArchive(const Archive *A) {
Mehdi Aminidf0b8bc2016-11-11 04:28:40 +00002419 Error Err = Error::success();
George Rimar45d116d2019-01-15 09:19:18 +00002420 for (auto &C : A->children(Err)) {
Kevin Enderby77be0942016-05-17 17:10:12 +00002421 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2422 if (!ChildOrErr) {
2423 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
George Rimar45d116d2019-01-15 09:19:18 +00002424 report_error(A->getFileName(), C, std::move(E));
Kevin Enderby77be0942016-05-17 17:10:12 +00002425 continue;
2426 }
George Rimar45d116d2019-01-15 09:19:18 +00002427 if (ObjectFile *O = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
2428 dumpObject(O, A, &C);
Saleem Abdulrasool8a836022016-08-18 16:39:19 +00002429 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
George Rimar45d116d2019-01-15 09:19:18 +00002430 dumpObject(I, A, &C);
Michael J. Spencer27781b72011-10-08 00:18:30 +00002431 else
George Rimar45d116d2019-01-15 09:19:18 +00002432 report_error(A->getFileName(), object_error::invalid_file_type);
Michael J. Spencer27781b72011-10-08 00:18:30 +00002433 }
Lang Hamesaacf2fb2016-07-14 02:24:01 +00002434 if (Err)
George Rimar45d116d2019-01-15 09:19:18 +00002435 report_error(A->getFileName(), std::move(Err));
Michael J. Spencer27781b72011-10-08 00:18:30 +00002436}
2437
Adrian Prantl0b24b742018-05-01 16:10:38 +00002438/// Open file and figure out how to dump it.
George Rimar45d116d2019-01-15 09:19:18 +00002439static void dumpInput(StringRef file) {
Kevin Enderby60e9ca42015-01-07 21:02:18 +00002440 // If we are using the Mach-O specific object file parser, then let it parse
2441 // the file and process the command line options. So the -arch flags can
2442 // be used to select specific slices, etc.
2443 if (MachOOpt) {
George Rimar45d116d2019-01-15 09:19:18 +00002444 parseInputMachO(file);
Michael J. Spencer27781b72011-10-08 00:18:30 +00002445 return;
2446 }
2447
2448 // Attempt to open the binary.
Kevin Enderbyc6bf9be2016-04-06 22:14:09 +00002449 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
2450 if (!BinaryOrErr)
Kevin Enderby00e8fc52016-05-05 17:43:35 +00002451 report_error(file, BinaryOrErr.takeError());
Rafael Espindola548f2b62014-08-19 18:44:46 +00002452 Binary &Binary = *BinaryOrErr.get().getBinary();
Michael J. Spencer27781b72011-10-08 00:18:30 +00002453
George Rimar45d116d2019-01-15 09:19:18 +00002454 if (Archive *A = dyn_cast<Archive>(&Binary))
2455 dumpArchive(A);
2456 else if (ObjectFile *O = dyn_cast<ObjectFile>(&Binary))
2457 dumpObject(O);
Dave Lee58b1de42018-08-03 00:06:38 +00002458 else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Binary))
George Rimar45d116d2019-01-15 09:19:18 +00002459 parseInputMachO(UB);
Jim Grosbach3f5d1a22012-08-07 17:53:14 +00002460 else
Alexey Samsonov1b77d222015-06-04 18:34:11 +00002461 report_error(file, object_error::invalid_file_type);
Michael J. Spencer27781b72011-10-08 00:18:30 +00002462}
2463
Michael J. Spencer92e1deb2011-01-20 06:39:06 +00002464int main(int argc, char **argv) {
Rui Ueyama0b9d56a2018-04-13 18:26:06 +00002465 InitLLVM X(argc, argv);
Michael J. Spencer92e1deb2011-01-20 06:39:06 +00002466
2467 // Initialize targets and assembly printers/parsers.
2468 llvm::InitializeAllTargetInfos();
Evan Chenge78085a2011-07-22 21:58:54 +00002469 llvm::InitializeAllTargetMCs();
Michael J. Spencer92e1deb2011-01-20 06:39:06 +00002470 llvm::InitializeAllDisassemblers();
2471
Pete Cooperff204962012-05-03 23:20:10 +00002472 // Register the target printer for --version.
2473 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
2474
Michael J. Spencer92e1deb2011-01-20 06:39:06 +00002475 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
Michael J. Spencer92e1deb2011-01-20 06:39:06 +00002476
2477 ToolName = argv[0];
2478
2479 // Defaults to a.out if no filenames specified.
Jordan Rupprechtf6ea1292018-12-20 00:57:06 +00002480 if (InputFilenames.empty())
Michael J. Spencer92e1deb2011-01-20 06:39:06 +00002481 InputFilenames.push_back("a.out");
2482
Fangrui Song84e5dbf2018-06-27 20:45:11 +00002483 if (AllHeaders)
George Rimar04fde6b2019-01-12 12:17:24 +00002484 FileHeaders = PrivateHeaders = Relocations = SectionHeaders = SymbolTable =
2485 true;
Fangrui Song84e5dbf2018-06-27 20:45:11 +00002486
Hemant Kulkarni502957c2016-08-15 19:49:24 +00002487 if (DisassembleAll || PrintSource || PrintLines)
Colin LeMahieuea805022015-07-23 20:58:49 +00002488 Disassemble = true;
Paul Semelbaea3f02018-07-18 16:39:21 +00002489
Michael J. Spencer22ff0f32011-10-18 19:32:17 +00002490 if (!Disassemble
2491 && !Relocations
Paul Semel3fc706582018-06-07 13:30:55 +00002492 && !DynamicRelocations
Michael J. Spencer22ff0f32011-10-18 19:32:17 +00002493 && !SectionHeaders
2494 && !SectionContents
Michael J. Spencereef7b622012-12-05 20:12:35 +00002495 && !SymbolTable
Michael J. Spencerb2c064c2013-01-06 03:56:49 +00002496 && !UnwindInfo
Nick Kledzikaa4d2ac2014-08-30 00:20:14 +00002497 && !PrivateHeaders
Paul Semeld069a212018-07-04 15:25:03 +00002498 && !FileHeaders
Kevin Enderbyf3e60262016-01-13 00:25:36 +00002499 && !FirstPrivateHeader
Nick Kledzika240fc52014-09-12 21:34:15 +00002500 && !ExportsTrie
Nick Kledzik367cf702014-09-16 01:41:51 +00002501 && !Rebase
2502 && !Bind
2503 && !LazyBind
Kevin Enderby6248d1b2015-01-09 19:22:37 +00002504 && !WeakBind
Adrian Prantl54a27682015-07-08 02:04:15 +00002505 && !RawClangAST
Kevin Enderbycdfe54f2015-01-15 23:19:11 +00002506 && !(UniversalHeaders && MachOOpt)
Paul Semelfd466782018-07-05 14:43:29 +00002507 && !ArchiveHeaders
Kevin Enderby66e2ddc2015-01-23 18:52:17 +00002508 && !(IndirectSymbols && MachOOpt)
Kevin Enderbya167fe12015-01-27 21:28:24 +00002509 && !(DataInCode && MachOOpt)
Kevin Enderby06024442015-01-31 00:37:11 +00002510 && !(LinkOptHints && MachOOpt)
Kevin Enderby8284f0f2015-03-11 22:06:32 +00002511 && !(InfoPlist && MachOOpt)
Kevin Enderby62507242015-03-16 20:08:09 +00002512 && !(DylibsUsed && MachOOpt)
2513 && !(DylibId && MachOOpt)
Kevin Enderby95d81552015-04-01 20:57:01 +00002514 && !(ObjcMetaData && MachOOpt)
Jordan Rupprechtf6ea1292018-12-20 00:57:06 +00002515 && !(!FilterSections.empty() && MachOOpt)
Igor Laevsky25574802016-01-26 15:09:42 +00002516 && !PrintFaultMaps
2517 && DwarfDumpType == DIDT_Null) {
Michael J. Spencer92e1deb2011-01-20 06:39:06 +00002518 cl::PrintHelpMessage();
Dimitry Andricd1fe0c42017-12-18 19:46:56 +00002519 return 2;
2520 }
2521
Rafael Auler67fe7952018-03-09 19:13:44 +00002522 DisasmFuncsSet.insert(DisassembleFunctions.begin(),
2523 DisassembleFunctions.end());
2524
George Rimar45d116d2019-01-15 09:19:18 +00002525 llvm::for_each(InputFilenames, dumpInput);
Dimitry Andricd1fe0c42017-12-18 19:46:56 +00002526
2527 return EXIT_SUCCESS;
2528}