blob: 3beb01ad6eb4a541ab6fd034e1d299c48dbeac60 [file] [log] [blame]
Michael J. Spencer2670c252011-01-20 06:39:06 +00001//===-- llvm-objdump.cpp - Object file dumping utility for llvm -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This program is a utility that works like binutils "objdump", that is, it
11// dumps out a plethora of information about an object file depending on the
12// flags.
13//
Michael J. Spencerd7e70032013-02-05 20:27:22 +000014// The flags and output of this program should be near identical to those of
15// binutils objdump.
16//
Michael J. Spencer2670c252011-01-20 06:39:06 +000017//===----------------------------------------------------------------------===//
18
Benjamin Kramer43a772e2011-09-19 17:56:04 +000019#include "llvm-objdump.h"
Sanjoy Das6f567a42015-06-22 18:03:02 +000020#include "llvm/ADT/Optional.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000021#include "llvm/ADT/STLExtras.h"
Michael J. Spencer4e25c022011-10-17 17:13:22 +000022#include "llvm/ADT/StringExtras.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000023#include "llvm/ADT/Triple.h"
Sanjoy Das3f1bc3b2015-06-23 20:09:03 +000024#include "llvm/CodeGen/FaultMaps.h"
Igor Laevsky03a670c2016-01-26 15:09:42 +000025#include "llvm/DebugInfo/DWARF/DWARFContext.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000026#include "llvm/MC/MCAsmInfo.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000027#include "llvm/MC/MCContext.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000028#include "llvm/MC/MCDisassembler/MCDisassembler.h"
29#include "llvm/MC/MCDisassembler/MCRelocationInfo.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000030#include "llvm/MC/MCInst.h"
31#include "llvm/MC/MCInstPrinter.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000032#include "llvm/MC/MCInstrAnalysis.h"
Craig Topper54bfde72012-04-02 06:09:36 +000033#include "llvm/MC/MCInstrInfo.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000034#include "llvm/MC/MCObjectFileInfo.h"
Jim Grosbachfd93a592012-03-05 19:33:20 +000035#include "llvm/MC/MCRegisterInfo.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000036#include "llvm/MC/MCSubtargetInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000037#include "llvm/Object/Archive.h"
38#include "llvm/Object/COFF.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000039#include "llvm/Object/ELFObjectFile.h"
Rafael Espindolaa9f810b2012-12-21 03:47:03 +000040#include "llvm/Object/MachO.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000041#include "llvm/Object/ObjectFile.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000042#include "llvm/Support/Casting.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000043#include "llvm/Support/CommandLine.h"
44#include "llvm/Support/Debug.h"
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +000045#include "llvm/Support/Errc.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000046#include "llvm/Support/FileSystem.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000047#include "llvm/Support/Format.h"
Benjamin Kramerbf115312011-07-25 23:04:36 +000048#include "llvm/Support/GraphWriter.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000049#include "llvm/Support/Host.h"
50#include "llvm/Support/ManagedStatic.h"
51#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000052#include "llvm/Support/PrettyStackTrace.h"
53#include "llvm/Support/Signals.h"
54#include "llvm/Support/SourceMgr.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000055#include "llvm/Support/TargetRegistry.h"
56#include "llvm/Support/TargetSelect.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000057#include "llvm/Support/raw_ostream.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000058#include <algorithm>
Benjamin Kramera5177e62012-03-23 11:49:32 +000059#include <cctype>
Michael J. Spencer2670c252011-01-20 06:39:06 +000060#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000061#include <system_error>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000062#include <utility>
Ahmed Bougacha17926472013-08-21 07:29:02 +000063
Michael J. Spencer2670c252011-01-20 06:39:06 +000064using namespace llvm;
65using namespace object;
66
Benjamin Kramer43a772e2011-09-19 17:56:04 +000067static cl::list<std::string>
68InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
Michael J. Spencer2670c252011-01-20 06:39:06 +000069
Kevin Enderbye2297dd2015-01-07 21:02:18 +000070cl::opt<bool>
71llvm::Disassemble("disassemble",
Benjamin Kramer43a772e2011-09-19 17:56:04 +000072 cl::desc("Display assembler mnemonics for the machine instructions"));
73static cl::alias
74Disassembled("d", cl::desc("Alias for --disassemble"),
Colin LeMahieu77804be2015-07-29 15:45:39 +000075 cl::aliasopt(Disassemble));
76
77cl::opt<bool>
78llvm::DisassembleAll("disassemble-all",
79 cl::desc("Display assembler mnemonics for the machine instructions"));
80static cl::alias
81DisassembleAlld("D", cl::desc("Alias for --disassemble-all"),
Colin LeMahieuf34933e2015-07-23 20:58:49 +000082 cl::aliasopt(DisassembleAll));
Michael J. Spencer2670c252011-01-20 06:39:06 +000083
Kevin Enderby98da6132015-01-20 21:47:46 +000084cl::opt<bool>
85llvm::Relocations("r", cl::desc("Display the relocation entries in the file"));
Michael J. Spencerba4a3622011-10-08 00:18:30 +000086
Kevin Enderby98da6132015-01-20 21:47:46 +000087cl::opt<bool>
88llvm::SectionContents("s", cl::desc("Display the content of each section"));
Michael J. Spencer4e25c022011-10-17 17:13:22 +000089
Kevin Enderby98da6132015-01-20 21:47:46 +000090cl::opt<bool>
91llvm::SymbolTable("t", cl::desc("Display the symbol table"));
Michael J. Spencerbfa06782011-10-18 19:32:17 +000092
Kevin Enderbye2297dd2015-01-07 21:02:18 +000093cl::opt<bool>
94llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
Nick Kledzikd04bc352014-08-30 00:20:14 +000095
Kevin Enderbye2297dd2015-01-07 21:02:18 +000096cl::opt<bool>
97llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
Nick Kledzikac431442014-09-12 21:34:15 +000098
Kevin Enderbye2297dd2015-01-07 21:02:18 +000099cl::opt<bool>
100llvm::Bind("bind", cl::desc("Display mach-o binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000101
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000102cl::opt<bool>
103llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000104
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000105cl::opt<bool>
106llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000107
Adrian Prantl437105a2015-07-08 02:04:15 +0000108cl::opt<bool>
109llvm::RawClangAST("raw-clang-ast",
110 cl::desc("Dump the raw binary contents of the clang AST section"));
111
Nick Kledzik56ebef42014-09-16 01:41:51 +0000112static cl::opt<bool>
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000113MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000114static cl::alias
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000115MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
Benjamin Kramer87ee76c2011-07-20 19:37:35 +0000116
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000117cl::opt<std::string>
118llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
119 "see -version for available targets"));
120
121cl::opt<std::string>
Kevin Enderbyc9595622014-08-06 23:24:41 +0000122llvm::MCPU("mcpu",
123 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
124 cl::value_desc("cpu-name"),
125 cl::init(""));
126
127cl::opt<std::string>
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000128llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
Michael J. Spencer2670c252011-01-20 06:39:06 +0000129 "see -version for available targets"));
130
Kevin Enderby98da6132015-01-20 21:47:46 +0000131cl::opt<bool>
132llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
133 "headers for each section."));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000134static cl::alias
135SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
136 cl::aliasopt(SectionHeaders));
137static cl::alias
138SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
139 cl::aliasopt(SectionHeaders));
Colin LeMahieufcc32762015-07-29 19:08:10 +0000140
Colin LeMahieu77804be2015-07-29 15:45:39 +0000141cl::list<std::string>
Colin LeMahieufcc32762015-07-29 19:08:10 +0000142llvm::FilterSections("section", cl::desc("Operate on the specified sections only. "
143 "With -macho dump segment,section"));
144cl::alias
145static FilterSectionsj("j", cl::desc("Alias for --section"),
146 cl::aliasopt(llvm::FilterSections));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000147
Kevin Enderbyc9595622014-08-06 23:24:41 +0000148cl::list<std::string>
149llvm::MAttrs("mattr",
Jack Carter551efd72012-08-28 19:24:49 +0000150 cl::CommaSeparated,
151 cl::desc("Target specific attributes"),
152 cl::value_desc("a1,+a2,-a3,..."));
153
Kevin Enderbybf246f52014-09-24 23:08:22 +0000154cl::opt<bool>
155llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
156 "instructions, do not print "
157 "the instruction bytes."));
Eli Bendersky3a6808c2012-11-20 22:57:02 +0000158
Kevin Enderby98da6132015-01-20 21:47:46 +0000159cl::opt<bool>
160llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000161
162static cl::alias
163UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
164 cl::aliasopt(UnwindInfo));
165
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000166cl::opt<bool>
167llvm::PrivateHeaders("private-headers",
168 cl::desc("Display format specific file headers"));
Michael J. Spencer209565db2013-01-06 03:56:49 +0000169
Kevin Enderby0ae163f2016-01-13 00:25:36 +0000170cl::opt<bool>
171llvm::FirstPrivateHeader("private-header",
172 cl::desc("Display only the first format specific file "
173 "header"));
174
Michael J. Spencer209565db2013-01-06 03:56:49 +0000175static cl::alias
176PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
177 cl::aliasopt(PrivateHeaders));
178
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000179cl::opt<bool>
180 llvm::PrintImmHex("print-imm-hex",
Colin LeMahieuefe37322016-04-08 18:15:37 +0000181 cl::desc("Use hex format for immediate values"));
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000182
Sanjoy Das6f567a42015-06-22 18:03:02 +0000183cl::opt<bool> PrintFaultMaps("fault-map-section",
184 cl::desc("Display contents of faultmap section"));
185
Igor Laevsky03a670c2016-01-26 15:09:42 +0000186cl::opt<DIDumpType> llvm::DwarfDumpType(
187 "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"),
188 cl::values(clEnumValN(DIDT_Frames, "frames", ".debug_frame"),
189 clEnumValEnd));
190
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000191static StringRef ToolName;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000192
Colin LeMahieu77804be2015-07-29 15:45:39 +0000193namespace {
Colin LeMahieufcc32762015-07-29 19:08:10 +0000194typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate;
Colin LeMahieu77804be2015-07-29 15:45:39 +0000195
196class SectionFilterIterator {
197public:
198 SectionFilterIterator(FilterPredicate P,
199 llvm::object::section_iterator const &I,
200 llvm::object::section_iterator const &E)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000201 : Predicate(std::move(P)), Iterator(I), End(E) {
Colin LeMahieu77804be2015-07-29 15:45:39 +0000202 ScanPredicate();
203 }
Benjamin Kramerac9257b2015-09-24 14:52:52 +0000204 const llvm::object::SectionRef &operator*() const { return *Iterator; }
Colin LeMahieu77804be2015-07-29 15:45:39 +0000205 SectionFilterIterator &operator++() {
206 ++Iterator;
207 ScanPredicate();
208 return *this;
209 }
210 bool operator!=(SectionFilterIterator const &Other) const {
211 return Iterator != Other.Iterator;
212 }
213
214private:
215 void ScanPredicate() {
Colin LeMahieuda1723f2015-07-29 19:21:13 +0000216 while (Iterator != End && !Predicate(*Iterator)) {
Colin LeMahieu77804be2015-07-29 15:45:39 +0000217 ++Iterator;
218 }
219 }
220 FilterPredicate Predicate;
221 llvm::object::section_iterator Iterator;
222 llvm::object::section_iterator End;
223};
224
225class SectionFilter {
226public:
227 SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000228 : Predicate(std::move(P)), Object(O) {}
Colin LeMahieu77804be2015-07-29 15:45:39 +0000229 SectionFilterIterator begin() {
230 return SectionFilterIterator(Predicate, Object.section_begin(),
231 Object.section_end());
232 }
233 SectionFilterIterator end() {
234 return SectionFilterIterator(Predicate, Object.section_end(),
235 Object.section_end());
236 }
237
238private:
239 FilterPredicate Predicate;
240 llvm::object::ObjectFile const &Object;
241};
242SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) {
Colin LeMahieu77804be2015-07-29 15:45:39 +0000243 return SectionFilter([](llvm::object::SectionRef const &S) {
Colin LeMahieufcc32762015-07-29 19:08:10 +0000244 if(FilterSections.empty())
Colin LeMahieuda1723f2015-07-29 19:21:13 +0000245 return true;
Colin LeMahieu77804be2015-07-29 15:45:39 +0000246 llvm::StringRef String;
247 std::error_code error = S.getName(String);
Colin LeMahieufcc32762015-07-29 19:08:10 +0000248 if (error)
Colin LeMahieuda1723f2015-07-29 19:21:13 +0000249 return false;
Colin LeMahieufcc32762015-07-29 19:08:10 +0000250 return std::find(FilterSections.begin(),
251 FilterSections.end(),
Colin LeMahieuda1723f2015-07-29 19:21:13 +0000252 String) != FilterSections.end();
Colin LeMahieu77804be2015-07-29 15:45:39 +0000253 },
254 O);
255}
256}
257
Davide Italianoccd53fe2015-08-05 07:18:31 +0000258void llvm::error(std::error_code EC) {
Mark Seaborneb03ac52014-01-25 00:32:01 +0000259 if (!EC)
Davide Italianoccd53fe2015-08-05 07:18:31 +0000260 return;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000261
Davide Italiano140af642015-12-25 18:16:45 +0000262 errs() << ToolName << ": error reading file: " << EC.message() << ".\n";
263 errs().flush();
Davide Italiano7f6c3012015-08-06 00:18:52 +0000264 exit(1);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000265}
266
Davide Italianoed9d95b2015-12-29 13:41:02 +0000267LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
268 std::error_code EC) {
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000269 assert(EC);
270 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
Davide Italianoccd53fe2015-08-05 07:18:31 +0000271 exit(1);
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000272}
273
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000274LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
275 llvm::Error E) {
276 assert(E);
277 std::string Buf;
278 raw_string_ostream OS(Buf);
279 logAllUnhandledErrors(std::move(E), OS, "");
280 OS.flush();
Kevin Enderbyb34e3a12016-05-05 17:43:35 +0000281 errs() << ToolName << ": '" << File << "': " << Buf;
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000282 exit(1);
283}
284
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000285LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
286 StringRef FileName,
Kevin Enderby9acb1092016-05-31 20:35:34 +0000287 llvm::Error E,
288 StringRef ArchitectureName) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000289 assert(E);
290 errs() << ToolName << ": ";
291 if (ArchiveName != "")
292 errs() << ArchiveName << "(" << FileName << ")";
293 else
294 errs() << FileName;
Kevin Enderby9acb1092016-05-31 20:35:34 +0000295 if (!ArchitectureName.empty())
296 errs() << " (for architecture " << ArchitectureName << ")";
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000297 std::string Buf;
298 raw_string_ostream OS(Buf);
299 logAllUnhandledErrors(std::move(E), OS, "");
300 OS.flush();
301 errs() << " " << Buf;
302 exit(1);
303}
304
305LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
306 const object::Archive::Child &C,
Kevin Enderby9acb1092016-05-31 20:35:34 +0000307 llvm::Error E,
308 StringRef ArchitectureName) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000309 ErrorOr<StringRef> NameOrErr = C.getName();
310 // TODO: if we have a error getting the name then it would be nice to print
311 // the index of which archive member this is and or its offset in the
312 // archive instead of "???" as the name.
313 if (NameOrErr.getError())
Kevin Enderby9acb1092016-05-31 20:35:34 +0000314 llvm::report_error(ArchiveName, "???", std::move(E), ArchitectureName);
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000315 else
Kevin Enderby9acb1092016-05-31 20:35:34 +0000316 llvm::report_error(ArchiveName, NameOrErr.get(), std::move(E),
317 ArchitectureName);
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000318}
319
Craig Toppere6cb63e2014-04-25 04:24:47 +0000320static const Target *getTarget(const ObjectFile *Obj = nullptr) {
Michael J. Spencer2670c252011-01-20 06:39:06 +0000321 // Figure out the target triple.
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000322 llvm::Triple TheTriple("unknown-unknown-unknown");
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000323 if (TripleName.empty()) {
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000324 if (Obj) {
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000325 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000326 // TheTriple defaults to ELF, and COFF doesn't have an environment:
327 // the best we can do here is indicate that it is mach-o.
328 if (Obj->isMachO())
Saleem Abdulrasool35476332014-03-06 20:47:11 +0000329 TheTriple.setObjectFormat(Triple::MachO);
Saleem Abdulrasool98938f12014-04-17 06:17:23 +0000330
331 if (Obj->isCOFF()) {
332 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
333 if (COFFObj->getArch() == Triple::thumb)
334 TheTriple.setTriple("thumbv7-windows");
335 }
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000336 }
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000337 } else
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000338 TheTriple.setTriple(Triple::normalize(TripleName));
Michael J. Spencer2670c252011-01-20 06:39:06 +0000339
340 // Get the target specific parser.
341 std::string Error;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000342 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
343 Error);
Davide Italianobb599e32015-12-03 22:13:40 +0000344 if (!TheTarget)
345 report_fatal_error("can't find target: " + Error);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000346
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000347 // Update the triple name and return the found target.
348 TripleName = TheTriple.getTriple();
349 return TheTarget;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000350}
351
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000352bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
Rafael Espindola704cd842015-07-06 15:47:43 +0000353 return a.getOffset() < b.getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +0000354}
355
Colin LeMahieufb76b002015-05-28 19:07:14 +0000356namespace {
357class PrettyPrinter {
358public:
Colin LeMahieu0b5890d2015-05-28 20:59:08 +0000359 virtual ~PrettyPrinter(){}
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000360 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
Colin LeMahieufb76b002015-05-28 19:07:14 +0000361 ArrayRef<uint8_t> Bytes, uint64_t Address,
362 raw_ostream &OS, StringRef Annot,
363 MCSubtargetInfo const &STI) {
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000364 OS << format("%8" PRIx64 ":", Address);
Colin LeMahieufb76b002015-05-28 19:07:14 +0000365 if (!NoShowRawInsn) {
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000366 OS << "\t";
367 dumpBytes(Bytes, OS);
Colin LeMahieufb76b002015-05-28 19:07:14 +0000368 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000369 if (MI)
370 IP.printInst(MI, OS, "", STI);
371 else
372 OS << " <unknown>";
Colin LeMahieufb76b002015-05-28 19:07:14 +0000373 }
374};
375PrettyPrinter PrettyPrinterInst;
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000376class HexagonPrettyPrinter : public PrettyPrinter {
377public:
378 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
379 raw_ostream &OS) {
380 uint32_t opcode =
381 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
382 OS << format("%8" PRIx64 ":", Address);
383 if (!NoShowRawInsn) {
384 OS << "\t";
385 dumpBytes(Bytes.slice(0, 4), OS);
386 OS << format("%08" PRIx32, opcode);
387 }
388 }
389 void printInst(MCInstPrinter &IP, const MCInst *MI,
390 ArrayRef<uint8_t> Bytes, uint64_t Address,
391 raw_ostream &OS, StringRef Annot,
392 MCSubtargetInfo const &STI) override {
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000393 if (!MI) {
394 printLead(Bytes, Address, OS);
395 OS << " <unknown>";
396 return;
397 }
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000398 std::string Buffer;
399 {
400 raw_string_ostream TempStream(Buffer);
401 IP.printInst(MI, TempStream, "", STI);
402 }
403 StringRef Contents(Buffer);
404 // Split off bundle attributes
405 auto PacketBundle = Contents.rsplit('\n');
406 // Split off first instruction from the rest
407 auto HeadTail = PacketBundle.first.split('\n');
408 auto Preamble = " { ";
409 auto Separator = "";
410 while(!HeadTail.first.empty()) {
411 OS << Separator;
412 Separator = "\n";
413 printLead(Bytes, Address, OS);
414 OS << Preamble;
415 Preamble = " ";
416 StringRef Inst;
417 auto Duplex = HeadTail.first.split('\v');
418 if(!Duplex.second.empty()){
419 OS << Duplex.first;
420 OS << "; ";
421 Inst = Duplex.second;
422 }
423 else
424 Inst = HeadTail.first;
425 OS << Inst;
426 Bytes = Bytes.slice(4);
427 Address += 4;
428 HeadTail = HeadTail.second.split('\n');
429 }
430 OS << " } " << PacketBundle.second;
431 }
432};
433HexagonPrettyPrinter HexagonPrettyPrinterInst;
Valery Pykhtinde048052016-04-07 07:24:01 +0000434
435class AMDGCNPrettyPrinter : public PrettyPrinter {
436public:
437 void printInst(MCInstPrinter &IP,
438 const MCInst *MI,
439 ArrayRef<uint8_t> Bytes,
440 uint64_t Address,
441 raw_ostream &OS,
442 StringRef Annot,
443 MCSubtargetInfo const &STI) override {
Matt Arsenault87d80db2016-04-22 21:23:41 +0000444 if (!MI) {
445 OS << " <unknown>";
446 return;
447 }
448
Valery Pykhtinde048052016-04-07 07:24:01 +0000449 SmallString<40> InstStr;
450 raw_svector_ostream IS(InstStr);
451
452 IP.printInst(MI, IS, "", STI);
453
Valery Pykhtin8e79f5b2016-04-07 08:38:20 +0000454 OS << left_justify(IS.str(), 60) << format("// %012" PRIX64 ": ", Address);
Valery Pykhtinde048052016-04-07 07:24:01 +0000455 typedef support::ulittle32_t U32;
456 for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
457 Bytes.size() / sizeof(U32)))
458 // D should be explicitly casted to uint32_t here as it is passed
459 // by format to snprintf as vararg.
Valery Pykhtin8e79f5b2016-04-07 08:38:20 +0000460 OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D));
Valery Pykhtinde048052016-04-07 07:24:01 +0000461
462 if (!Annot.empty())
463 OS << "// " << Annot;
464 }
465};
466AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
467
Colin LeMahieu35436a22015-05-29 14:48:25 +0000468PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000469 switch(Triple.getArch()) {
470 default:
471 return PrettyPrinterInst;
472 case Triple::hexagon:
473 return HexagonPrettyPrinterInst;
Valery Pykhtinde048052016-04-07 07:24:01 +0000474 case Triple::amdgcn:
475 return AMDGCNPrettyPrinterInst;
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000476 }
Colin LeMahieufb76b002015-05-28 19:07:14 +0000477}
478}
479
Rafael Espindola37070a52015-06-03 04:48:06 +0000480template <class ELFT>
Rafael Espindola37070a52015-06-03 04:48:06 +0000481static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000482 const RelocationRef &RelRef,
Rafael Espindola37070a52015-06-03 04:48:06 +0000483 SmallVectorImpl<char> &Result) {
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000484 DataRefImpl Rel = RelRef.getRawDataRefImpl();
485
Rafael Espindola37070a52015-06-03 04:48:06 +0000486 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
487 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000488 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
489
Rafael Espindola37070a52015-06-03 04:48:06 +0000490 const ELFFile<ELFT> &EF = *Obj->getELFFile();
491
Rafael Espindola6def3042015-07-01 12:56:27 +0000492 ErrorOr<const Elf_Shdr *> SecOrErr = EF.getSection(Rel.d.a);
493 if (std::error_code EC = SecOrErr.getError())
494 return EC;
495 const Elf_Shdr *Sec = *SecOrErr;
496 ErrorOr<const Elf_Shdr *> SymTabOrErr = EF.getSection(Sec->sh_link);
497 if (std::error_code EC = SymTabOrErr.getError())
498 return EC;
499 const Elf_Shdr *SymTab = *SymTabOrErr;
Rafael Espindola719dc7c2015-06-29 12:38:31 +0000500 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
501 SymTab->sh_type == ELF::SHT_DYNSYM);
Rafael Espindola6def3042015-07-01 12:56:27 +0000502 ErrorOr<const Elf_Shdr *> StrTabSec = EF.getSection(SymTab->sh_link);
503 if (std::error_code EC = StrTabSec.getError())
504 return EC;
505 ErrorOr<StringRef> StrTabOrErr = EF.getStringTable(*StrTabSec);
Rafael Espindola6a1bfb22015-06-29 14:39:25 +0000506 if (std::error_code EC = StrTabOrErr.getError())
507 return EC;
508 StringRef StrTab = *StrTabOrErr;
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000509 uint8_t type = RelRef.getType();
Rafael Espindola37070a52015-06-03 04:48:06 +0000510 StringRef res;
511 int64_t addend = 0;
Rafael Espindola6def3042015-07-01 12:56:27 +0000512 switch (Sec->sh_type) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000513 default:
514 return object_error::parse_failed;
515 case ELF::SHT_REL: {
Rafael Espindola37070a52015-06-03 04:48:06 +0000516 // TODO: Read implicit addend from section data.
517 break;
518 }
519 case ELF::SHT_RELA: {
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000520 const Elf_Rela *ERela = Obj->getRela(Rel);
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000521 addend = ERela->r_addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000522 break;
523 }
524 }
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000525 symbol_iterator SI = RelRef.getSymbol();
526 const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
Rafael Espindola75d5b542015-06-03 05:14:22 +0000527 StringRef Target;
Rafael Espindola75d5b542015-06-03 05:14:22 +0000528 if (symb->getType() == ELF::STT_SECTION) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000529 Expected<section_iterator> SymSI = SI->getSection();
530 if (!SymSI)
531 return errorToErrorCode(SymSI.takeError());
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000532 const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
533 ErrorOr<StringRef> SecName = EF.getSectionName(SymSec);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000534 if (std::error_code EC = SecName.getError())
535 return EC;
536 Target = *SecName;
537 } else {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000538 Expected<StringRef> SymName = symb->getName(StrTab);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000539 if (!SymName)
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000540 return errorToErrorCode(SymName.takeError());
Rafael Espindola75d5b542015-06-03 05:14:22 +0000541 Target = *SymName;
542 }
Rafael Espindola37070a52015-06-03 04:48:06 +0000543 switch (EF.getHeader()->e_machine) {
544 case ELF::EM_X86_64:
545 switch (type) {
546 case ELF::R_X86_64_PC8:
547 case ELF::R_X86_64_PC16:
548 case ELF::R_X86_64_PC32: {
549 std::string fmtbuf;
550 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000551 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
Rafael Espindola37070a52015-06-03 04:48:06 +0000552 fmt.flush();
553 Result.append(fmtbuf.begin(), fmtbuf.end());
554 } break;
555 case ELF::R_X86_64_8:
556 case ELF::R_X86_64_16:
557 case ELF::R_X86_64_32:
558 case ELF::R_X86_64_32S:
559 case ELF::R_X86_64_64: {
560 std::string fmtbuf;
561 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000562 fmt << Target << (addend < 0 ? "" : "+") << addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000563 fmt.flush();
564 Result.append(fmtbuf.begin(), fmtbuf.end());
565 } break;
566 default:
567 res = "Unknown";
568 }
569 break;
Jacques Pienaarea9f25a2016-03-01 21:21:42 +0000570 case ELF::EM_LANAI:
Rafael Espindola37070a52015-06-03 04:48:06 +0000571 case ELF::EM_AARCH64: {
572 std::string fmtbuf;
573 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000574 fmt << Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000575 if (addend != 0)
576 fmt << (addend < 0 ? "" : "+") << addend;
577 fmt.flush();
578 Result.append(fmtbuf.begin(), fmtbuf.end());
579 break;
580 }
581 case ELF::EM_386:
Michael Kupersteina3b79dd2015-11-04 11:21:50 +0000582 case ELF::EM_IAMCU:
Rafael Espindola37070a52015-06-03 04:48:06 +0000583 case ELF::EM_ARM:
584 case ELF::EM_HEXAGON:
585 case ELF::EM_MIPS:
Rafael Espindola75d5b542015-06-03 05:14:22 +0000586 res = Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000587 break;
Dan Gohman46350172016-01-12 20:56:01 +0000588 case ELF::EM_WEBASSEMBLY:
589 switch (type) {
590 case ELF::R_WEBASSEMBLY_DATA: {
591 std::string fmtbuf;
592 raw_string_ostream fmt(fmtbuf);
593 fmt << Target << (addend < 0 ? "" : "+") << addend;
594 fmt.flush();
595 Result.append(fmtbuf.begin(), fmtbuf.end());
596 break;
597 }
598 case ELF::R_WEBASSEMBLY_FUNCTION:
599 res = Target;
600 break;
601 default:
602 res = "Unknown";
603 }
604 break;
Rafael Espindola37070a52015-06-03 04:48:06 +0000605 default:
606 res = "Unknown";
607 }
608 if (Result.empty())
609 Result.append(res.begin(), res.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000610 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000611}
612
613static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000614 const RelocationRef &Rel,
Rafael Espindola37070a52015-06-03 04:48:06 +0000615 SmallVectorImpl<char> &Result) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000616 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
617 return getRelocationValueString(ELF32LE, Rel, Result);
618 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
619 return getRelocationValueString(ELF64LE, Rel, Result);
620 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
621 return getRelocationValueString(ELF32BE, Rel, Result);
622 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
623 return getRelocationValueString(ELF64BE, Rel, Result);
624}
625
626static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
627 const RelocationRef &Rel,
628 SmallVectorImpl<char> &Result) {
629 symbol_iterator SymI = Rel.getSymbol();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000630 Expected<StringRef> SymNameOrErr = SymI->getName();
631 if (!SymNameOrErr)
632 return errorToErrorCode(SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000633 StringRef SymName = *SymNameOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000634 Result.append(SymName.begin(), SymName.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000635 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000636}
637
638static void printRelocationTargetName(const MachOObjectFile *O,
639 const MachO::any_relocation_info &RE,
640 raw_string_ostream &fmt) {
641 bool IsScattered = O->isRelocationScattered(RE);
642
643 // Target of a scattered relocation is an address. In the interest of
644 // generating pretty output, scan through the symbol table looking for a
645 // symbol that aligns with that address. If we find one, print it.
646 // Otherwise, we just print the hex address of the target.
647 if (IsScattered) {
648 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
649
650 for (const SymbolRef &Symbol : O->symbols()) {
651 std::error_code ec;
Rafael Espindolaed067c42015-07-03 18:19:00 +0000652 ErrorOr<uint64_t> Addr = Symbol.getAddress();
653 if ((ec = Addr.getError()))
Rafael Espindola37070a52015-06-03 04:48:06 +0000654 report_fatal_error(ec.message());
Rafael Espindolaed067c42015-07-03 18:19:00 +0000655 if (*Addr != Val)
Rafael Espindola37070a52015-06-03 04:48:06 +0000656 continue;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000657 Expected<StringRef> Name = Symbol.getName();
658 if (!Name) {
659 std::string Buf;
660 raw_string_ostream OS(Buf);
661 logAllUnhandledErrors(Name.takeError(), OS, "");
662 OS.flush();
663 report_fatal_error(Buf);
664 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000665 fmt << *Name;
Rafael Espindola37070a52015-06-03 04:48:06 +0000666 return;
667 }
668
669 // If we couldn't find a symbol that this relocation refers to, try
670 // to find a section beginning instead.
Colin LeMahieu77804be2015-07-29 15:45:39 +0000671 for (const SectionRef &Section : ToolSectionFilter(*O)) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000672 std::error_code ec;
673
674 StringRef Name;
675 uint64_t Addr = Section.getAddress();
676 if (Addr != Val)
677 continue;
678 if ((ec = Section.getName(Name)))
679 report_fatal_error(ec.message());
680 fmt << Name;
681 return;
682 }
683
684 fmt << format("0x%x", Val);
685 return;
686 }
687
688 StringRef S;
689 bool isExtern = O->getPlainRelocationExternal(RE);
690 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
691
692 if (isExtern) {
693 symbol_iterator SI = O->symbol_begin();
694 advance(SI, Val);
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000695 Expected<StringRef> SOrErr = SI->getName();
696 error(errorToErrorCode(SOrErr.takeError()));
Davide Italianoccd53fe2015-08-05 07:18:31 +0000697 S = *SOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000698 } else {
699 section_iterator SI = O->section_begin();
700 // Adjust for the fact that sections are 1-indexed.
701 advance(SI, Val - 1);
702 SI->getName(S);
703 }
704
705 fmt << S;
706}
707
708static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
709 const RelocationRef &RelRef,
710 SmallVectorImpl<char> &Result) {
711 DataRefImpl Rel = RelRef.getRawDataRefImpl();
712 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
713
714 unsigned Arch = Obj->getArch();
715
716 std::string fmtbuf;
717 raw_string_ostream fmt(fmtbuf);
718 unsigned Type = Obj->getAnyRelocationType(RE);
719 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
720
721 // Determine any addends that should be displayed with the relocation.
722 // These require decoding the relocation type, which is triple-specific.
723
724 // X86_64 has entirely custom relocation types.
725 if (Arch == Triple::x86_64) {
726 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
727
728 switch (Type) {
729 case MachO::X86_64_RELOC_GOT_LOAD:
730 case MachO::X86_64_RELOC_GOT: {
731 printRelocationTargetName(Obj, RE, fmt);
732 fmt << "@GOT";
733 if (isPCRel)
734 fmt << "PCREL";
735 break;
736 }
737 case MachO::X86_64_RELOC_SUBTRACTOR: {
738 DataRefImpl RelNext = Rel;
739 Obj->moveRelocationNext(RelNext);
740 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
741
742 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
743 // X86_64_RELOC_UNSIGNED.
744 // NOTE: Scattered relocations don't exist on x86_64.
745 unsigned RType = Obj->getAnyRelocationType(RENext);
746 if (RType != MachO::X86_64_RELOC_UNSIGNED)
747 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
748 "X86_64_RELOC_SUBTRACTOR.");
749
750 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
751 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
752 printRelocationTargetName(Obj, RENext, fmt);
753 fmt << "-";
754 printRelocationTargetName(Obj, RE, fmt);
755 break;
756 }
757 case MachO::X86_64_RELOC_TLV:
758 printRelocationTargetName(Obj, RE, fmt);
759 fmt << "@TLV";
760 if (isPCRel)
761 fmt << "P";
762 break;
763 case MachO::X86_64_RELOC_SIGNED_1:
764 printRelocationTargetName(Obj, RE, fmt);
765 fmt << "-1";
766 break;
767 case MachO::X86_64_RELOC_SIGNED_2:
768 printRelocationTargetName(Obj, RE, fmt);
769 fmt << "-2";
770 break;
771 case MachO::X86_64_RELOC_SIGNED_4:
772 printRelocationTargetName(Obj, RE, fmt);
773 fmt << "-4";
774 break;
775 default:
776 printRelocationTargetName(Obj, RE, fmt);
777 break;
778 }
779 // X86 and ARM share some relocation types in common.
780 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
781 Arch == Triple::ppc) {
782 // Generic relocation types...
783 switch (Type) {
784 case MachO::GENERIC_RELOC_PAIR: // prints no info
Rui Ueyama7d099192015-06-09 15:20:42 +0000785 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000786 case MachO::GENERIC_RELOC_SECTDIFF: {
787 DataRefImpl RelNext = Rel;
788 Obj->moveRelocationNext(RelNext);
789 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
790
791 // X86 sect diff's must be followed by a relocation of type
792 // GENERIC_RELOC_PAIR.
793 unsigned RType = Obj->getAnyRelocationType(RENext);
794
795 if (RType != MachO::GENERIC_RELOC_PAIR)
796 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
797 "GENERIC_RELOC_SECTDIFF.");
798
799 printRelocationTargetName(Obj, RE, fmt);
800 fmt << "-";
801 printRelocationTargetName(Obj, RENext, fmt);
802 break;
803 }
804 }
805
806 if (Arch == Triple::x86 || Arch == Triple::ppc) {
807 switch (Type) {
808 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
809 DataRefImpl RelNext = Rel;
810 Obj->moveRelocationNext(RelNext);
811 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
812
813 // X86 sect diff's must be followed by a relocation of type
814 // GENERIC_RELOC_PAIR.
815 unsigned RType = Obj->getAnyRelocationType(RENext);
816 if (RType != MachO::GENERIC_RELOC_PAIR)
817 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
818 "GENERIC_RELOC_LOCAL_SECTDIFF.");
819
820 printRelocationTargetName(Obj, RE, fmt);
821 fmt << "-";
822 printRelocationTargetName(Obj, RENext, fmt);
823 break;
824 }
825 case MachO::GENERIC_RELOC_TLV: {
826 printRelocationTargetName(Obj, RE, fmt);
827 fmt << "@TLV";
828 if (IsPCRel)
829 fmt << "P";
830 break;
831 }
832 default:
833 printRelocationTargetName(Obj, RE, fmt);
834 }
835 } else { // ARM-specific relocations
836 switch (Type) {
837 case MachO::ARM_RELOC_HALF:
838 case MachO::ARM_RELOC_HALF_SECTDIFF: {
839 // Half relocations steal a bit from the length field to encode
840 // whether this is an upper16 or a lower16 relocation.
841 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
842
843 if (isUpper)
844 fmt << ":upper16:(";
845 else
846 fmt << ":lower16:(";
847 printRelocationTargetName(Obj, RE, fmt);
848
849 DataRefImpl RelNext = Rel;
850 Obj->moveRelocationNext(RelNext);
851 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
852
853 // ARM half relocs must be followed by a relocation of type
854 // ARM_RELOC_PAIR.
855 unsigned RType = Obj->getAnyRelocationType(RENext);
856 if (RType != MachO::ARM_RELOC_PAIR)
857 report_fatal_error("Expected ARM_RELOC_PAIR after "
858 "ARM_RELOC_HALF");
859
860 // NOTE: The half of the target virtual address is stashed in the
861 // address field of the secondary relocation, but we can't reverse
862 // engineer the constant offset from it without decoding the movw/movt
863 // instruction to find the other half in its immediate field.
864
865 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
866 // symbol/section pointer of the follow-on relocation.
867 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
868 fmt << "-";
869 printRelocationTargetName(Obj, RENext, fmt);
870 }
871
872 fmt << ")";
873 break;
874 }
875 default: { printRelocationTargetName(Obj, RE, fmt); }
876 }
877 }
878 } else
879 printRelocationTargetName(Obj, RE, fmt);
880
881 fmt.flush();
882 Result.append(fmtbuf.begin(), fmtbuf.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000883 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000884}
885
886static std::error_code getRelocationValueString(const RelocationRef &Rel,
887 SmallVectorImpl<char> &Result) {
Rafael Espindola854038e2015-06-26 14:51:16 +0000888 const ObjectFile *Obj = Rel.getObject();
Rafael Espindola37070a52015-06-03 04:48:06 +0000889 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
890 return getRelocationValueString(ELF, Rel, Result);
891 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
892 return getRelocationValueString(COFF, Rel, Result);
893 auto *MachO = cast<MachOObjectFile>(Obj);
894 return getRelocationValueString(MachO, Rel, Result);
895}
896
Rafael Espindola0ad71d92015-06-30 03:41:26 +0000897/// @brief Indicates whether this relocation should hidden when listing
898/// relocations, usually because it is the trailing part of a multipart
899/// relocation that will be printed as part of the leading relocation.
900static bool getHidden(RelocationRef RelRef) {
901 const ObjectFile *Obj = RelRef.getObject();
902 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
903 if (!MachO)
904 return false;
905
906 unsigned Arch = MachO->getArch();
907 DataRefImpl Rel = RelRef.getRawDataRefImpl();
908 uint64_t Type = MachO->getRelocationType(Rel);
909
910 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
911 // is always hidden.
912 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
913 if (Type == MachO::GENERIC_RELOC_PAIR)
914 return true;
915 } else if (Arch == Triple::x86_64) {
916 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
917 // an X86_64_RELOC_SUBTRACTOR.
918 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
919 DataRefImpl RelPrev = Rel;
920 RelPrev.d.a--;
921 uint64_t PrevType = MachO->getRelocationType(RelPrev);
922 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
923 return true;
924 }
925 }
926
927 return false;
928}
929
Michael J. Spencer51862b32011-10-13 22:17:18 +0000930static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Jim Grosbachaf9aec02012-08-07 17:53:14 +0000931 const Target *TheTarget = getTarget(Obj);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000932
Jack Carter551efd72012-08-28 19:24:49 +0000933 // Package up features to be passed to target/subtarget
Daniel Sanders1d148642016-06-16 09:17:03 +0000934 SubtargetFeatures Features = Obj->getFeatures();
Jack Carter551efd72012-08-28 19:24:49 +0000935 if (MAttrs.size()) {
Jack Carter551efd72012-08-28 19:24:49 +0000936 for (unsigned i = 0; i != MAttrs.size(); ++i)
937 Features.AddFeature(MAttrs[i]);
Jack Carter551efd72012-08-28 19:24:49 +0000938 }
939
Ahmed Charles56440fd2014-03-06 05:51:42 +0000940 std::unique_ptr<const MCRegisterInfo> MRI(
941 TheTarget->createMCRegInfo(TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +0000942 if (!MRI)
943 report_fatal_error("error: no register info for target " + TripleName);
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000944
945 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000946 std::unique_ptr<const MCAsmInfo> AsmInfo(
947 TheTarget->createMCAsmInfo(*MRI, TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +0000948 if (!AsmInfo)
949 report_fatal_error("error: no assembly info for target " + TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +0000950 std::unique_ptr<const MCSubtargetInfo> STI(
Daniel Sanders1d148642016-06-16 09:17:03 +0000951 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
Davide Italiano711e4952015-12-17 01:59:50 +0000952 if (!STI)
953 report_fatal_error("error: no subtarget info for target " + TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +0000954 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
Davide Italiano711e4952015-12-17 01:59:50 +0000955 if (!MII)
956 report_fatal_error("error: no instruction info for target " + TripleName);
Lang Hamesa1bc0f52014-04-15 04:40:56 +0000957 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
958 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
959
960 std::unique_ptr<MCDisassembler> DisAsm(
961 TheTarget->createMCDisassembler(*STI, Ctx));
Davide Italiano711e4952015-12-17 01:59:50 +0000962 if (!DisAsm)
963 report_fatal_error("error: no disassembler for target " + TripleName);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000964
Ahmed Charles56440fd2014-03-06 05:51:42 +0000965 std::unique_ptr<const MCInstrAnalysis> MIA(
966 TheTarget->createMCInstrAnalysis(MII.get()));
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000967
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000968 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Daniel Sanders50f17232015-09-15 16:17:27 +0000969 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
970 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
Davide Italiano711e4952015-12-17 01:59:50 +0000971 if (!IP)
972 report_fatal_error("error: no instruction printer for target " +
973 TripleName);
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000974 IP->setPrintImmHex(PrintImmHex);
Colin LeMahieu35436a22015-05-29 14:48:25 +0000975 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000976
Greg Fitzgerald18432272014-03-20 22:55:15 +0000977 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
978 "\t\t\t%08" PRIx64 ": ";
979
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000980 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
981 // in RelocSecs contain the relocations for section S.
Rafael Espindola4453e42942014-06-13 03:07:50 +0000982 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000983 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
Colin LeMahieu77804be2015-07-29 15:45:39 +0000984 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +0000985 section_iterator Sec2 = Section.getRelocatedSection();
Rafael Espindolab5155a52014-02-10 20:24:04 +0000986 if (Sec2 != Obj->section_end())
Alexey Samsonov48803e52014-03-13 14:37:36 +0000987 SectionRelocMap[*Sec2].push_back(Section);
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000988 }
989
David Majnemer81afca62015-07-07 22:06:59 +0000990 // Create a mapping from virtual address to symbol name. This is used to
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000991 // pretty print the symbols while disassembling.
992 typedef std::vector<std::pair<uint64_t, StringRef>> SectionSymbolsTy;
993 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
994 for (const SymbolRef &Symbol : Obj->symbols()) {
995 ErrorOr<uint64_t> AddressOrErr = Symbol.getAddress();
996 error(AddressOrErr.getError());
997 uint64_t Address = *AddressOrErr;
David Majnemer2603a8fa2015-07-09 18:11:40 +0000998
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000999 Expected<StringRef> Name = Symbol.getName();
1000 error(errorToErrorCode(Name.takeError()));
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001001 if (Name->empty())
1002 continue;
David Majnemer81afca62015-07-07 22:06:59 +00001003
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001004 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1005 error(errorToErrorCode(SectionOrErr.takeError()));
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001006 section_iterator SecI = *SectionOrErr;
1007 if (SecI == Obj->section_end())
1008 continue;
David Majnemer81afca62015-07-07 22:06:59 +00001009
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001010 AllSymbols[*SecI].emplace_back(Address, *Name);
David Majnemer81afca62015-07-07 22:06:59 +00001011 }
1012
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001013 // Create a mapping from virtual address to section.
1014 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1015 for (SectionRef Sec : Obj->sections())
1016 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1017 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
1018
1019 // Linked executables (.exe and .dll files) typically don't include a real
1020 // symbol table but they might contain an export table.
1021 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
1022 for (const auto &ExportEntry : COFFObj->export_directories()) {
1023 StringRef Name;
1024 error(ExportEntry.getSymbolName(Name));
1025 if (Name.empty())
1026 continue;
1027 uint32_t RVA;
1028 error(ExportEntry.getExportRVA(RVA));
1029
1030 uint64_t VA = COFFObj->getImageBase() + RVA;
1031 auto Sec = std::upper_bound(
1032 SectionAddresses.begin(), SectionAddresses.end(), VA,
1033 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
1034 return LHS < RHS.first;
1035 });
1036 if (Sec != SectionAddresses.begin())
1037 --Sec;
1038 else
1039 Sec = SectionAddresses.end();
1040
1041 if (Sec != SectionAddresses.end())
1042 AllSymbols[Sec->second].emplace_back(VA, Name);
1043 }
1044 }
1045
1046 // Sort all the symbols, this allows us to use a simple binary search to find
1047 // a symbol near an address.
1048 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1049 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
1050
Colin LeMahieu77804be2015-07-29 15:45:39 +00001051 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Colin LeMahieuf34933e2015-07-23 20:58:49 +00001052 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
Mark Seaborneb03ac52014-01-25 00:32:01 +00001053 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +00001054
Rafael Espindola80291272014-10-08 15:28:58 +00001055 uint64_t SectionAddr = Section.getAddress();
1056 uint64_t SectSize = Section.getSize();
David Majnemer185b5b12014-11-11 09:58:25 +00001057 if (!SectSize)
1058 continue;
Simon Atanasyan2b614e12014-02-24 22:12:11 +00001059
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001060 // Get the list of all the symbols in this section.
1061 SectionSymbolsTy &Symbols = AllSymbols[Section];
Davide Italianof0706882015-10-01 21:57:09 +00001062 std::vector<uint64_t> DataMappingSymsAddr;
1063 std::vector<uint64_t> TextMappingSymsAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001064 if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
1065 for (const auto &Symb : Symbols) {
1066 uint64_t Address = Symb.first;
1067 StringRef Name = Symb.second;
1068 if (Name.startswith("$d"))
David Majnemer153722d2015-11-18 04:35:32 +00001069 DataMappingSymsAddr.push_back(Address - SectionAddr);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001070 if (Name.startswith("$x"))
David Majnemer153722d2015-11-18 04:35:32 +00001071 TextMappingSymsAddr.push_back(Address - SectionAddr);
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001072 }
1073 }
1074
Davide Italianof0706882015-10-01 21:57:09 +00001075 std::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end());
1076 std::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end());
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001077
Michael J. Spencer51862b32011-10-13 22:17:18 +00001078 // Make a list of all the relocations for this section.
1079 std::vector<RelocationRef> Rels;
1080 if (InlineRelocs) {
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001081 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
1082 for (const RelocationRef &Reloc : RelocSec.relocations()) {
1083 Rels.push_back(Reloc);
1084 }
Michael J. Spencer51862b32011-10-13 22:17:18 +00001085 }
1086 }
1087
1088 // Sort relocations by address.
1089 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
1090
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001091 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +00001092 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001093 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +00001094 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001095 }
Michael J. Spencer1d6167f2011-06-25 17:55:23 +00001096 StringRef name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001097 error(Section.getName(name));
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001098 outs() << "Disassembly of section ";
1099 if (!SegmentName.empty())
1100 outs() << SegmentName << ",";
1101 outs() << name << ':';
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001102
Rafael Espindola7884c952015-06-04 15:01:05 +00001103 // If the section has no symbol at the start, just insert a dummy one.
1104 if (Symbols.empty() || Symbols[0].first != 0)
David Majnemer153722d2015-11-18 04:35:32 +00001105 Symbols.insert(Symbols.begin(), std::make_pair(SectionAddr, name));
Alp Tokere69170a2014-06-26 22:52:05 +00001106
1107 SmallString<40> Comments;
1108 raw_svector_ostream CommentStream(Comments);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001109
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001110 StringRef BytesStr;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001111 error(Section.getContents(BytesStr));
Aaron Ballman106fd7b2014-11-12 14:01:17 +00001112 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1113 BytesStr.size());
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001114
Michael J. Spencer2670c252011-01-20 06:39:06 +00001115 uint64_t Size;
1116 uint64_t Index;
1117
Michael J. Spencer51862b32011-10-13 22:17:18 +00001118 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
1119 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001120 // Disassemble symbol by symbol.
1121 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
Rafael Espindolae45c7402014-08-17 16:31:39 +00001122
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001123 uint64_t Start = Symbols[si].first - SectionAddr;
1124 // The end is either the section end or the beginning of the next
1125 // symbol.
1126 uint64_t End =
1127 (si == se - 1) ? SectSize : Symbols[si + 1].first - SectionAddr;
1128 // Don't try to disassemble beyond the end of section contents.
1129 if (End > SectSize)
1130 End = SectSize;
Rafael Espindolae45c7402014-08-17 16:31:39 +00001131 // If this symbol has the same address as the next symbol, then skip it.
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001132 if (Start >= End)
Michael J. Spenceree84f642011-10-13 20:37:08 +00001133 continue;
1134
Valery Pykhtinde048052016-04-07 07:24:01 +00001135 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1136 // make size 4 bytes folded
1137 End = Start + ((End - Start) & ~0x3ull);
1138 Start += 256; // add sizeof(amd_kernel_code_t)
1139 // cut trailing zeroes - up to 256 bytes (align)
1140 const uint64_t EndAlign = 256;
1141 const auto Limit = End - (std::min)(EndAlign, End - Start);
1142 while (End > Limit &&
1143 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1144 End -= 4;
1145 }
1146
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001147 outs() << '\n' << Symbols[si].second << ":\n";
Michael J. Spencer2670c252011-01-20 06:39:06 +00001148
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001149#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +00001150 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001151#else
Mark Seaborneb03ac52014-01-25 00:32:01 +00001152 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001153#endif
1154
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001155 for (Index = Start; Index < End; Index += Size) {
1156 MCInst Inst;
Owen Andersona0c3b972011-09-15 23:38:46 +00001157
Davide Italianof0706882015-10-01 21:57:09 +00001158 // AArch64 ELF binaries can interleave data and text in the
1159 // same section. We rely on the markers introduced to
1160 // understand what we need to dump.
1161 if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
1162 uint64_t Stride = 0;
1163
1164 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1165 DataMappingSymsAddr.end(), Index);
1166 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1167 // Switch to data.
1168 while (Index < End) {
1169 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1170 outs() << "\t";
1171 if (Index + 4 <= End) {
1172 Stride = 4;
1173 dumpBytes(Bytes.slice(Index, 4), outs());
1174 outs() << "\t.word";
1175 } else if (Index + 2 <= End) {
1176 Stride = 2;
1177 dumpBytes(Bytes.slice(Index, 2), outs());
1178 outs() << "\t.short";
1179 } else {
1180 Stride = 1;
1181 dumpBytes(Bytes.slice(Index, 1), outs());
1182 outs() << "\t.byte";
1183 }
1184 Index += Stride;
1185 outs() << "\n";
1186 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1187 TextMappingSymsAddr.end(), Index);
1188 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1189 break;
1190 }
1191 }
1192 }
1193
1194 if (Index >= End)
1195 break;
1196
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001197 bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1198 SectionAddr + Index, DebugOut,
1199 CommentStream);
1200 if (Size == 0)
1201 Size = 1;
1202 PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
1203 Bytes.slice(Index, Size),
1204 SectionAddr + Index, outs(), "", *STI);
1205 outs() << CommentStream.str();
1206 Comments.clear();
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001207
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001208 // Try to resolve the target of a call, tail call, etc. to a specific
1209 // symbol.
1210 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1211 MIA->isConditionalBranch(Inst))) {
1212 uint64_t Target;
1213 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1214 // In a relocatable object, the target's section must reside in
1215 // the same section as the call instruction or it is accessed
1216 // through a relocation.
1217 //
1218 // In a non-relocatable object, the target may be in any section.
1219 //
1220 // N.B. We don't walk the relocations in the relocatable case yet.
1221 auto *TargetSectionSymbols = &Symbols;
1222 if (!Obj->isRelocatableObject()) {
1223 auto SectionAddress = std::upper_bound(
1224 SectionAddresses.begin(), SectionAddresses.end(), Target,
1225 [](uint64_t LHS,
1226 const std::pair<uint64_t, SectionRef> &RHS) {
1227 return LHS < RHS.first;
1228 });
1229 if (SectionAddress != SectionAddresses.begin()) {
1230 --SectionAddress;
1231 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1232 } else {
1233 TargetSectionSymbols = nullptr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001234 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001235 }
David Majnemer2603a8fa2015-07-09 18:11:40 +00001236
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001237 // Find the first symbol in the section whose offset is less than
1238 // or equal to the target.
1239 if (TargetSectionSymbols) {
1240 auto TargetSym = std::upper_bound(
1241 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1242 Target, [](uint64_t LHS,
1243 const std::pair<uint64_t, StringRef> &RHS) {
1244 return LHS < RHS.first;
1245 });
1246 if (TargetSym != TargetSectionSymbols->begin()) {
1247 --TargetSym;
1248 uint64_t TargetAddress = std::get<0>(*TargetSym);
1249 StringRef TargetName = std::get<1>(*TargetSym);
1250 outs() << " <" << TargetName;
1251 uint64_t Disp = Target - TargetAddress;
1252 if (Disp)
1253 outs() << "+0x" << utohexstr(Disp);
1254 outs() << '>';
David Majnemer81afca62015-07-07 22:06:59 +00001255 }
1256 }
1257 }
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001258 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001259 outs() << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001260
1261 // Print relocation for instruction.
1262 while (rel_cur != rel_end) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001263 bool hidden = getHidden(*rel_cur);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001264 uint64_t addr = rel_cur->getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +00001265 SmallString<16> name;
1266 SmallString<32> val;
Owen Andersonfa3e5202011-10-25 20:35:53 +00001267
1268 // If this relocation is hidden, skip it.
Owen Andersonfa3e5202011-10-25 20:35:53 +00001269 if (hidden) goto skip_print_rel;
1270
Michael J. Spencer51862b32011-10-13 22:17:18 +00001271 // Stop when rel_cur's address is past the current instruction.
Owen Andersonf20e3e52011-10-25 20:15:39 +00001272 if (addr >= Index + Size) break;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001273 rel_cur->getTypeName(name);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001274 error(getRelocationValueString(*rel_cur, val));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001275 outs() << format(Fmt.data(), SectionAddr + addr) << name
Benjamin Kramer82803112012-03-10 02:04:38 +00001276 << "\t" << val << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001277
1278 skip_print_rel:
1279 ++rel_cur;
1280 }
Benjamin Kramer87ee76c2011-07-20 19:37:35 +00001281 }
Michael J. Spencer2670c252011-01-20 06:39:06 +00001282 }
1283 }
1284}
1285
Kevin Enderby98da6132015-01-20 21:47:46 +00001286void llvm::PrintRelocations(const ObjectFile *Obj) {
Greg Fitzgerald18432272014-03-20 22:55:15 +00001287 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1288 "%08" PRIx64;
Rafael Espindola9219fe72016-03-21 20:59:15 +00001289 // Regular objdump doesn't print relocations in non-relocatable object
1290 // files.
1291 if (!Obj->isRelocatableObject())
1292 return;
Rafael Espindolac66d7612014-08-17 19:09:37 +00001293
Colin LeMahieu77804be2015-07-29 15:45:39 +00001294 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001295 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001296 continue;
1297 StringRef secname;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001298 error(Section.getName(secname));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001299 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001300 for (const RelocationRef &Reloc : Section.relocations()) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001301 bool hidden = getHidden(Reloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001302 uint64_t address = Reloc.getOffset();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001303 SmallString<32> relocname;
1304 SmallString<32> valuestr;
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001305 if (hidden)
1306 continue;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001307 Reloc.getTypeName(relocname);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001308 error(getRelocationValueString(Reloc, valuestr));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001309 outs() << format(Fmt.data(), address) << " " << relocname << " "
1310 << valuestr << "\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001311 }
1312 outs() << "\n";
1313 }
1314}
1315
Kevin Enderby98da6132015-01-20 21:47:46 +00001316void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001317 outs() << "Sections:\n"
1318 "Idx Name Size Address Type\n";
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001319 unsigned i = 0;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001320 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001321 StringRef Name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001322 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001323 uint64_t Address = Section.getAddress();
1324 uint64_t Size = Section.getSize();
1325 bool Text = Section.isText();
1326 bool Data = Section.isData();
1327 bool BSS = Section.isBSS();
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001328 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +00001329 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
Alexey Samsonov48803e52014-03-13 14:37:36 +00001330 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1331 Name.str().c_str(), Size, Address, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001332 ++i;
1333 }
1334}
1335
Kevin Enderby98da6132015-01-20 21:47:46 +00001336void llvm::PrintSectionContents(const ObjectFile *Obj) {
Rafael Espindola4453e42942014-06-13 03:07:50 +00001337 std::error_code EC;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001338 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001339 StringRef Name;
1340 StringRef Contents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001341 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001342 uint64_t BaseAddr = Section.getAddress();
David Majnemer185b5b12014-11-11 09:58:25 +00001343 uint64_t Size = Section.getSize();
1344 if (!Size)
1345 continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001346
1347 outs() << "Contents of section " << Name << ":\n";
David Majnemer185b5b12014-11-11 09:58:25 +00001348 if (Section.isBSS()) {
Alexey Samsonov209095c2013-04-16 10:53:11 +00001349 outs() << format("<skipping contents of bss section at [%04" PRIx64
David Majnemer8f6b04c2014-07-14 16:20:14 +00001350 ", %04" PRIx64 ")>\n",
1351 BaseAddr, BaseAddr + Size);
Alexey Samsonov209095c2013-04-16 10:53:11 +00001352 continue;
1353 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001354
Davide Italianoccd53fe2015-08-05 07:18:31 +00001355 error(Section.getContents(Contents));
David Majnemer8f6b04c2014-07-14 16:20:14 +00001356
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001357 // Dump out the content as hex and printable ascii characters.
1358 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer82803112012-03-10 02:04:38 +00001359 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001360 // Dump line of hex.
1361 for (std::size_t i = 0; i < 16; ++i) {
1362 if (i != 0 && i % 4 == 0)
1363 outs() << ' ';
1364 if (addr + i < end)
1365 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1366 << hexdigit(Contents[addr + i] & 0xF, true);
1367 else
1368 outs() << " ";
1369 }
1370 // Print ascii.
1371 outs() << " ";
1372 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
Guy Benyei83c74e92013-02-12 21:21:59 +00001373 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001374 outs() << Contents[addr + i];
1375 else
1376 outs() << ".";
1377 }
1378 outs() << "\n";
1379 }
1380 }
1381}
1382
Kevin Enderby9acb1092016-05-31 20:35:34 +00001383void llvm::PrintSymbolTable(const ObjectFile *o, StringRef ArchiveName,
1384 StringRef ArchitectureName) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001385 outs() << "SYMBOL TABLE:\n";
1386
Rui Ueyama4e39f712014-03-18 18:58:51 +00001387 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
Davide Italianoe85abf72015-12-20 09:54:34 +00001388 printCOFFSymbolTable(coff);
Rui Ueyama4e39f712014-03-18 18:58:51 +00001389 return;
1390 }
1391 for (const SymbolRef &Symbol : o->symbols()) {
Rafael Espindolaed067c42015-07-03 18:19:00 +00001392 ErrorOr<uint64_t> AddressOrError = Symbol.getAddress();
Davide Italianoccd53fe2015-08-05 07:18:31 +00001393 error(AddressOrError.getError());
Rafael Espindolaed067c42015-07-03 18:19:00 +00001394 uint64_t Address = *AddressOrError;
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001395 Expected<SymbolRef::Type> TypeOrError = Symbol.getType();
1396 if (!TypeOrError)
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001397 report_error(ArchiveName, o->getFileName(), TypeOrError.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00001398 SymbolRef::Type Type = *TypeOrError;
Rui Ueyama4e39f712014-03-18 18:58:51 +00001399 uint32_t Flags = Symbol.getFlags();
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001400 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1401 error(errorToErrorCode(SectionOrErr.takeError()));
Rafael Espindola8bab8892015-08-07 23:27:14 +00001402 section_iterator Section = *SectionOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001403 StringRef Name;
1404 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1405 Section->getName(Name);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001406 } else {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001407 Expected<StringRef> NameOrErr = Symbol.getName();
1408 if (!NameOrErr)
Kevin Enderby9acb1092016-05-31 20:35:34 +00001409 report_error(ArchiveName, o->getFileName(), NameOrErr.takeError(),
1410 ArchitectureName);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001411 Name = *NameOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001412 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001413
Rui Ueyama4e39f712014-03-18 18:58:51 +00001414 bool Global = Flags & SymbolRef::SF_Global;
1415 bool Weak = Flags & SymbolRef::SF_Weak;
1416 bool Absolute = Flags & SymbolRef::SF_Absolute;
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001417 bool Common = Flags & SymbolRef::SF_Common;
Davide Italianocd2514d2015-04-30 23:08:53 +00001418 bool Hidden = Flags & SymbolRef::SF_Hidden;
David Meyer1df4b842012-02-28 23:47:53 +00001419
Rui Ueyama4e39f712014-03-18 18:58:51 +00001420 char GlobLoc = ' ';
1421 if (Type != SymbolRef::ST_Unknown)
1422 GlobLoc = Global ? 'g' : 'l';
1423 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1424 ? 'd' : ' ';
1425 char FileFunc = ' ';
1426 if (Type == SymbolRef::ST_File)
1427 FileFunc = 'f';
1428 else if (Type == SymbolRef::ST_Function)
1429 FileFunc = 'F';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001430
Rui Ueyama4e39f712014-03-18 18:58:51 +00001431 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1432 "%08" PRIx64;
Michael J. Spencerd857c1c2013-01-10 22:40:50 +00001433
Rui Ueyama4e39f712014-03-18 18:58:51 +00001434 outs() << format(Fmt, Address) << " "
1435 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1436 << (Weak ? 'w' : ' ') // Weak?
1437 << ' ' // Constructor. Not supported yet.
1438 << ' ' // Warning. Not supported yet.
1439 << ' ' // Indirect reference to another symbol.
1440 << Debug // Debugging (d) or dynamic (D) symbol.
1441 << FileFunc // Name of function (F), file (f) or object (O).
1442 << ' ';
1443 if (Absolute) {
1444 outs() << "*ABS*";
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001445 } else if (Common) {
1446 outs() << "*COM*";
Rui Ueyama4e39f712014-03-18 18:58:51 +00001447 } else if (Section == o->section_end()) {
1448 outs() << "*UND*";
1449 } else {
1450 if (const MachOObjectFile *MachO =
1451 dyn_cast<const MachOObjectFile>(o)) {
1452 DataRefImpl DR = Section->getRawDataRefImpl();
1453 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1454 outs() << SegmentName << ",";
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001455 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00001456 StringRef SectionName;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001457 error(Section->getName(SectionName));
Rui Ueyama4e39f712014-03-18 18:58:51 +00001458 outs() << SectionName;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001459 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001460
1461 outs() << '\t';
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001462 if (Common || isa<ELFObjectFileBase>(o)) {
Rafael Espindoladbb6bd32015-06-25 22:10:04 +00001463 uint64_t Val =
1464 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001465 outs() << format("\t %08" PRIx64 " ", Val);
1466 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001467
Davide Italianocd2514d2015-04-30 23:08:53 +00001468 if (Hidden) {
1469 outs() << ".hidden ";
1470 }
1471 outs() << Name
Rui Ueyama4e39f712014-03-18 18:58:51 +00001472 << '\n';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001473 }
1474}
1475
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001476static void PrintUnwindInfo(const ObjectFile *o) {
1477 outs() << "Unwind info:\n\n";
1478
1479 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1480 printCOFFUnwindInfo(coff);
Tim Northover4bd286a2014-08-01 13:07:19 +00001481 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1482 printMachOUnwindInfo(MachO);
1483 else {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001484 // TODO: Extract DWARF dump tool to objdump.
1485 errs() << "This operation is only currently supported "
Tim Northover4bd286a2014-08-01 13:07:19 +00001486 "for COFF and MachO object files.\n";
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001487 return;
1488 }
1489}
1490
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001491void llvm::printExportsTrie(const ObjectFile *o) {
Nick Kledzikd04bc352014-08-30 00:20:14 +00001492 outs() << "Exports trie:\n";
1493 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1494 printMachOExportsTrie(MachO);
1495 else {
1496 errs() << "This operation is only currently supported "
1497 "for Mach-O executable files.\n";
1498 return;
1499 }
1500}
1501
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001502void llvm::printRebaseTable(const ObjectFile *o) {
Nick Kledzikac431442014-09-12 21:34:15 +00001503 outs() << "Rebase table:\n";
1504 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1505 printMachORebaseTable(MachO);
1506 else {
1507 errs() << "This operation is only currently supported "
1508 "for Mach-O executable files.\n";
1509 return;
1510 }
1511}
1512
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001513void llvm::printBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001514 outs() << "Bind table:\n";
1515 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1516 printMachOBindTable(MachO);
1517 else {
1518 errs() << "This operation is only currently supported "
1519 "for Mach-O executable files.\n";
1520 return;
1521 }
1522}
1523
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001524void llvm::printLazyBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001525 outs() << "Lazy bind table:\n";
1526 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1527 printMachOLazyBindTable(MachO);
1528 else {
1529 errs() << "This operation is only currently supported "
1530 "for Mach-O executable files.\n";
1531 return;
1532 }
1533}
1534
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001535void llvm::printWeakBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001536 outs() << "Weak bind table:\n";
1537 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1538 printMachOWeakBindTable(MachO);
1539 else {
1540 errs() << "This operation is only currently supported "
1541 "for Mach-O executable files.\n";
1542 return;
1543 }
1544}
Nick Kledzikac431442014-09-12 21:34:15 +00001545
Adrian Prantl437105a2015-07-08 02:04:15 +00001546/// Dump the raw contents of the __clangast section so the output can be piped
1547/// into llvm-bcanalyzer.
1548void llvm::printRawClangAST(const ObjectFile *Obj) {
1549 if (outs().is_displayed()) {
1550 errs() << "The -raw-clang-ast option will dump the raw binary contents of "
1551 "the clang ast section.\n"
1552 "Please redirect the output to a file or another program such as "
1553 "llvm-bcanalyzer.\n";
1554 return;
1555 }
1556
1557 StringRef ClangASTSectionName("__clangast");
1558 if (isa<COFFObjectFile>(Obj)) {
1559 ClangASTSectionName = "clangast";
1560 }
1561
1562 Optional<object::SectionRef> ClangASTSection;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001563 for (auto Sec : ToolSectionFilter(*Obj)) {
Adrian Prantl437105a2015-07-08 02:04:15 +00001564 StringRef Name;
1565 Sec.getName(Name);
1566 if (Name == ClangASTSectionName) {
1567 ClangASTSection = Sec;
1568 break;
1569 }
1570 }
1571 if (!ClangASTSection)
1572 return;
1573
1574 StringRef ClangASTContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001575 error(ClangASTSection.getValue().getContents(ClangASTContents));
Adrian Prantl437105a2015-07-08 02:04:15 +00001576 outs().write(ClangASTContents.data(), ClangASTContents.size());
1577}
1578
Sanjoy Das6f567a42015-06-22 18:03:02 +00001579static void printFaultMaps(const ObjectFile *Obj) {
1580 const char *FaultMapSectionName = nullptr;
1581
1582 if (isa<ELFObjectFileBase>(Obj)) {
1583 FaultMapSectionName = ".llvm_faultmaps";
1584 } else if (isa<MachOObjectFile>(Obj)) {
1585 FaultMapSectionName = "__llvm_faultmaps";
1586 } else {
1587 errs() << "This operation is only currently supported "
1588 "for ELF and Mach-O executable files.\n";
1589 return;
1590 }
1591
1592 Optional<object::SectionRef> FaultMapSection;
1593
Colin LeMahieu77804be2015-07-29 15:45:39 +00001594 for (auto Sec : ToolSectionFilter(*Obj)) {
Sanjoy Das6f567a42015-06-22 18:03:02 +00001595 StringRef Name;
1596 Sec.getName(Name);
1597 if (Name == FaultMapSectionName) {
1598 FaultMapSection = Sec;
1599 break;
1600 }
1601 }
1602
1603 outs() << "FaultMap table:\n";
1604
1605 if (!FaultMapSection.hasValue()) {
1606 outs() << "<not found>\n";
1607 return;
1608 }
1609
1610 StringRef FaultMapContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001611 error(FaultMapSection.getValue().getContents(FaultMapContents));
Sanjoy Das6f567a42015-06-22 18:03:02 +00001612
1613 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1614 FaultMapContents.bytes_end());
1615
1616 outs() << FMP;
1617}
1618
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001619static void printPrivateFileHeaders(const ObjectFile *o) {
1620 if (o->isELF())
1621 printELFFileHeader(o);
1622 else if (o->isCOFF())
1623 printCOFFFileHeader(o);
1624 else if (o->isMachO()) {
1625 printMachOFileHeader(o);
1626 printMachOLoadCommands(o);
1627 } else
1628 report_fatal_error("Invalid/Unsupported object file format");
1629}
1630
1631static void printFirstPrivateFileHeader(const ObjectFile *o) {
Davide Italiano540e9212015-12-19 22:09:40 +00001632 if (o->isELF())
Rui Ueyamac2bed422013-09-27 21:04:00 +00001633 printELFFileHeader(o);
Davide Italiano540e9212015-12-19 22:09:40 +00001634 else if (o->isCOFF())
Rui Ueyamac2bed422013-09-27 21:04:00 +00001635 printCOFFFileHeader(o);
Davide Italiano540e9212015-12-19 22:09:40 +00001636 else if (o->isMachO())
Kevin Enderbyb76d3862014-08-22 20:35:18 +00001637 printMachOFileHeader(o);
Davide Italiano540e9212015-12-19 22:09:40 +00001638 else
1639 report_fatal_error("Invalid/Unsupported object file format");
Rui Ueyamac2bed422013-09-27 21:04:00 +00001640}
1641
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001642static void DumpObject(const ObjectFile *o, const Archive *a = nullptr) {
1643 StringRef ArchiveName = a != nullptr ? a->getFileName() : "";
Adrian Prantl437105a2015-07-08 02:04:15 +00001644 // Avoid other output when using a raw option.
1645 if (!RawClangAST) {
1646 outs() << '\n';
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001647 if (a)
1648 outs() << a->getFileName() << "(" << o->getFileName() << ")";
1649 else
1650 outs() << o->getFileName();
1651 outs() << ":\tfile format " << o->getFileFormatName() << "\n\n";
Adrian Prantl437105a2015-07-08 02:04:15 +00001652 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001653
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001654 if (Disassemble)
Michael J. Spencer51862b32011-10-13 22:17:18 +00001655 DisassembleObject(o, Relocations);
1656 if (Relocations && !Disassemble)
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001657 PrintRelocations(o);
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001658 if (SectionHeaders)
1659 PrintSectionHeaders(o);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001660 if (SectionContents)
1661 PrintSectionContents(o);
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001662 if (SymbolTable)
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001663 PrintSymbolTable(o, ArchiveName);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001664 if (UnwindInfo)
1665 PrintUnwindInfo(o);
Rui Ueyamac2bed422013-09-27 21:04:00 +00001666 if (PrivateHeaders)
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001667 printPrivateFileHeaders(o);
1668 if (FirstPrivateHeader)
1669 printFirstPrivateFileHeader(o);
Nick Kledzikd04bc352014-08-30 00:20:14 +00001670 if (ExportsTrie)
1671 printExportsTrie(o);
Nick Kledzikac431442014-09-12 21:34:15 +00001672 if (Rebase)
1673 printRebaseTable(o);
Nick Kledzik56ebef42014-09-16 01:41:51 +00001674 if (Bind)
1675 printBindTable(o);
1676 if (LazyBind)
1677 printLazyBindTable(o);
1678 if (WeakBind)
1679 printWeakBindTable(o);
Adrian Prantl437105a2015-07-08 02:04:15 +00001680 if (RawClangAST)
1681 printRawClangAST(o);
Sanjoy Das6f567a42015-06-22 18:03:02 +00001682 if (PrintFaultMaps)
1683 printFaultMaps(o);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001684 if (DwarfDumpType != DIDT_Null) {
1685 std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*o));
1686 // Dump the complete DWARF structure.
1687 DICtx->dump(outs(), DwarfDumpType, true /* DumpEH */);
1688 }
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001689}
1690
1691/// @brief Dump each object file in \a a;
1692static void DumpArchive(const Archive *a) {
Kevin Enderby7a969422015-11-05 19:24:56 +00001693 for (auto &ErrorOrChild : a->children()) {
1694 if (std::error_code EC = ErrorOrChild.getError())
1695 report_error(a->getFileName(), EC);
1696 const Archive::Child &C = *ErrorOrChild;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001697 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1698 if (!ChildOrErr) {
1699 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1700 report_error(a->getFileName(), C, std::move(E));
1701 continue;
1702 }
Rafael Espindolaae460022014-06-16 16:08:36 +00001703 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001704 DumpObject(o, a);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001705 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001706 report_error(a->getFileName(), object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001707 }
1708}
1709
1710/// @brief Open file and figure out how to dump it.
1711static void DumpInput(StringRef file) {
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001712
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001713 // If we are using the Mach-O specific object file parser, then let it parse
1714 // the file and process the command line options. So the -arch flags can
1715 // be used to select specific slices, etc.
1716 if (MachOOpt) {
1717 ParseInputMachO(file);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001718 return;
1719 }
1720
1721 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00001722 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
1723 if (!BinaryOrErr)
Kevin Enderbyb34e3a12016-05-05 17:43:35 +00001724 report_error(file, BinaryOrErr.takeError());
Rafael Espindola48af1c22014-08-19 18:44:46 +00001725 Binary &Binary = *BinaryOrErr.get().getBinary();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001726
Rafael Espindola3f6481d2014-08-01 14:31:55 +00001727 if (Archive *a = dyn_cast<Archive>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001728 DumpArchive(a);
Rafael Espindola3f6481d2014-08-01 14:31:55 +00001729 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001730 DumpObject(o);
Jim Grosbachaf9aec02012-08-07 17:53:14 +00001731 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001732 report_error(file, object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001733}
1734
Michael J. Spencer2670c252011-01-20 06:39:06 +00001735int main(int argc, char **argv) {
1736 // Print a stack trace if we signal out.
Richard Smith2ad6d482016-06-09 00:53:21 +00001737 sys::PrintStackTraceOnErrorSignal(argv[0]);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001738 PrettyStackTraceProgram X(argc, argv);
1739 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1740
1741 // Initialize targets and assembly printers/parsers.
1742 llvm::InitializeAllTargetInfos();
Evan Cheng8c886a42011-07-22 21:58:54 +00001743 llvm::InitializeAllTargetMCs();
Michael J. Spencer2670c252011-01-20 06:39:06 +00001744 llvm::InitializeAllDisassemblers();
1745
Pete Cooper28fb4fc2012-05-03 23:20:10 +00001746 // Register the target printer for --version.
1747 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
1748
Michael J. Spencer2670c252011-01-20 06:39:06 +00001749 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
1750 TripleName = Triple::normalize(TripleName);
1751
1752 ToolName = argv[0];
1753
1754 // Defaults to a.out if no filenames specified.
1755 if (InputFilenames.size() == 0)
1756 InputFilenames.push_back("a.out");
1757
Colin LeMahieuf34933e2015-07-23 20:58:49 +00001758 if (DisassembleAll)
1759 Disassemble = true;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001760 if (!Disassemble
1761 && !Relocations
1762 && !SectionHeaders
1763 && !SectionContents
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001764 && !SymbolTable
Michael J. Spencer209565db2013-01-06 03:56:49 +00001765 && !UnwindInfo
Nick Kledzikd04bc352014-08-30 00:20:14 +00001766 && !PrivateHeaders
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001767 && !FirstPrivateHeader
Nick Kledzikac431442014-09-12 21:34:15 +00001768 && !ExportsTrie
Nick Kledzik56ebef42014-09-16 01:41:51 +00001769 && !Rebase
1770 && !Bind
1771 && !LazyBind
Kevin Enderby131d1772015-01-09 19:22:37 +00001772 && !WeakBind
Adrian Prantl437105a2015-07-08 02:04:15 +00001773 && !RawClangAST
Kevin Enderby13023a12015-01-15 23:19:11 +00001774 && !(UniversalHeaders && MachOOpt)
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001775 && !(ArchiveHeaders && MachOOpt)
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001776 && !(IndirectSymbols && MachOOpt)
Kevin Enderby9a509442015-01-27 21:28:24 +00001777 && !(DataInCode && MachOOpt)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001778 && !(LinkOptHints && MachOOpt)
Kevin Enderbycd66be52015-03-11 22:06:32 +00001779 && !(InfoPlist && MachOOpt)
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001780 && !(DylibsUsed && MachOOpt)
1781 && !(DylibId && MachOOpt)
Kevin Enderby0fc11822015-04-01 20:57:01 +00001782 && !(ObjcMetaData && MachOOpt)
Colin LeMahieufcc32762015-07-29 19:08:10 +00001783 && !(FilterSections.size() != 0 && MachOOpt)
Igor Laevsky03a670c2016-01-26 15:09:42 +00001784 && !PrintFaultMaps
1785 && DwarfDumpType == DIDT_Null) {
Michael J. Spencer2670c252011-01-20 06:39:06 +00001786 cl::PrintHelpMessage();
1787 return 2;
1788 }
1789
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001790 std::for_each(InputFilenames.begin(), InputFilenames.end(),
1791 DumpInput);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001792
Davide Italianoccd53fe2015-08-05 07:18:31 +00001793 return EXIT_SUCCESS;
Michael J. Spencer2670c252011-01-20 06:39:06 +00001794}