blob: 914789f18f828692456555da31615e2d124f4429 [file] [log] [blame]
Michael J. Spencer2670c252011-01-20 06:39:06 +00001//===-- llvm-objdump.cpp - Object file dumping utility for llvm -----------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Michael J. Spencer2670c252011-01-20 06:39:06 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This program is a utility that works like binutils "objdump", that is, it
10// dumps out a plethora of information about an object file depending on the
11// flags.
12//
Michael J. Spencerd7e70032013-02-05 20:27:22 +000013// The flags and output of this program should be near identical to those of
14// binutils objdump.
15//
Michael J. Spencer2670c252011-01-20 06:39:06 +000016//===----------------------------------------------------------------------===//
17
Benjamin Kramer43a772e2011-09-19 17:56:04 +000018#include "llvm-objdump.h"
Sanjoy Das6f567a42015-06-22 18:03:02 +000019#include "llvm/ADT/Optional.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000020#include "llvm/ADT/STLExtras.h"
Michael J. Spencer4e25c022011-10-17 17:13:22 +000021#include "llvm/ADT/StringExtras.h"
Rafael Aulerb0e4b912018-03-09 19:13:44 +000022#include "llvm/ADT/StringSet.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000023#include "llvm/ADT/Triple.h"
Sanjoy Das3f1bc3b2015-06-23 20:09:03 +000024#include "llvm/CodeGen/FaultMaps.h"
Igor Laevsky03a670c2016-01-26 15:09:42 +000025#include "llvm/DebugInfo/DWARF/DWARFContext.h"
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +000026#include "llvm/DebugInfo/Symbolize/Symbolize.h"
Paul Semel007dedb2018-07-18 16:39:21 +000027#include "llvm/Demangle/Demangle.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000028#include "llvm/MC/MCAsmInfo.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000029#include "llvm/MC/MCContext.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000030#include "llvm/MC/MCDisassembler/MCDisassembler.h"
31#include "llvm/MC/MCDisassembler/MCRelocationInfo.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000032#include "llvm/MC/MCInst.h"
33#include "llvm/MC/MCInstPrinter.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000034#include "llvm/MC/MCInstrAnalysis.h"
Craig Topper54bfde72012-04-02 06:09:36 +000035#include "llvm/MC/MCInstrInfo.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000036#include "llvm/MC/MCObjectFileInfo.h"
Jim Grosbachfd93a592012-03-05 19:33:20 +000037#include "llvm/MC/MCRegisterInfo.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000038#include "llvm/MC/MCSubtargetInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000039#include "llvm/Object/Archive.h"
40#include "llvm/Object/COFF.h"
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +000041#include "llvm/Object/COFFImportFile.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000042#include "llvm/Object/ELFObjectFile.h"
Rafael Espindolaa9f810b2012-12-21 03:47:03 +000043#include "llvm/Object/MachO.h"
Dave Lee3fb120f2018-08-03 00:06:38 +000044#include "llvm/Object/MachOUniversal.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000045#include "llvm/Object/ObjectFile.h"
Sam Clegg4df5d762017-06-27 20:40:53 +000046#include "llvm/Object/Wasm.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000047#include "llvm/Support/Casting.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000048#include "llvm/Support/CommandLine.h"
49#include "llvm/Support/Debug.h"
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +000050#include "llvm/Support/Errc.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000051#include "llvm/Support/FileSystem.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000052#include "llvm/Support/Format.h"
Benjamin Kramerbf115312011-07-25 23:04:36 +000053#include "llvm/Support/GraphWriter.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000054#include "llvm/Support/Host.h"
Rui Ueyama197194b2018-04-13 18:26:06 +000055#include "llvm/Support/InitLLVM.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000056#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000057#include "llvm/Support/SourceMgr.h"
Joel Galenson134cf472018-08-24 15:21:57 +000058#include "llvm/Support/StringSaver.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000059#include "llvm/Support/TargetRegistry.h"
60#include "llvm/Support/TargetSelect.h"
Jonas Devliegheree787efd2018-11-11 22:12:04 +000061#include "llvm/Support/WithColor.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000062#include "llvm/Support/raw_ostream.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000063#include <algorithm>
Benjamin Kramera5177e62012-03-23 11:49:32 +000064#include <cctype>
Michael J. Spencer2670c252011-01-20 06:39:06 +000065#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000066#include <system_error>
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +000067#include <unordered_map>
Rafael Espindolac398e672017-07-19 22:27:28 +000068#include <utility>
Ahmed Bougacha17926472013-08-21 07:29:02 +000069
Michael J. Spencer2670c252011-01-20 06:39:06 +000070using namespace llvm;
71using namespace object;
72
George Rimar4c3b2972019-01-28 10:44:01 +000073cl::opt<unsigned long long> AdjustVMA(
74 "adjust-vma",
75 cl::desc("Increase the displayed address by the specified offset"),
76 cl::value_desc("offset"), cl::init(0));
77
Fangrui Song8513cd42018-06-27 20:45:11 +000078cl::opt<bool>
79 llvm::AllHeaders("all-headers",
80 cl::desc("Display all available header information"));
81static cl::alias AllHeadersShort("x", cl::desc("Alias for --all-headers"),
Matthew Voss0f436772019-02-19 19:46:08 +000082 cl::NotHidden, cl::Grouping,
83 cl::aliasopt(AllHeaders));
Fangrui Song8513cd42018-06-27 20:45:11 +000084
Benjamin Kramer43a772e2011-09-19 17:56:04 +000085static cl::list<std::string>
86InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
Michael J. Spencer2670c252011-01-20 06:39:06 +000087
Kevin Enderbye2297dd2015-01-07 21:02:18 +000088cl::opt<bool>
89llvm::Disassemble("disassemble",
Benjamin Kramer43a772e2011-09-19 17:56:04 +000090 cl::desc("Display assembler mnemonics for the machine instructions"));
George Rimar845d3292019-01-18 10:41:26 +000091static cl::alias Disassembled("d", cl::desc("Alias for --disassemble"),
Matthew Voss0f436772019-02-19 19:46:08 +000092 cl::NotHidden, cl::Grouping,
93 cl::aliasopt(Disassemble));
Colin LeMahieu77804be2015-07-29 15:45:39 +000094
95cl::opt<bool>
96llvm::DisassembleAll("disassemble-all",
97 cl::desc("Display assembler mnemonics for the machine instructions"));
George Rimar845d3292019-01-18 10:41:26 +000098static cl::alias DisassembleAlld("D", cl::desc("Alias for --disassemble-all"),
Matthew Voss0f436772019-02-19 19:46:08 +000099 cl::NotHidden, cl::Grouping,
100 cl::aliasopt(DisassembleAll));
Michael J. Spencer2670c252011-01-20 06:39:06 +0000101
Zachary Turner030ad372018-08-20 22:18:21 +0000102cl::opt<bool> llvm::Demangle("demangle", cl::desc("Demangle symbols names"),
103 cl::init(false));
Paul Semel007dedb2018-07-18 16:39:21 +0000104
105static cl::alias DemangleShort("C", cl::desc("Alias for --demangle"),
Matthew Voss0f436772019-02-19 19:46:08 +0000106 cl::NotHidden, cl::Grouping,
107 cl::aliasopt(llvm::Demangle));
Paul Semel007dedb2018-07-18 16:39:21 +0000108
Rafael Aulerb0e4b912018-03-09 19:13:44 +0000109static cl::list<std::string>
Matthew Voss0f436772019-02-19 19:46:08 +0000110DisassembleFunctions("disassemble-functions",
Rafael Aulerb0e4b912018-03-09 19:13:44 +0000111 cl::CommaSeparated,
112 cl::desc("List of functions to disassemble"));
113static StringSet<> DisasmFuncsSet;
114
Kevin Enderby98da6132015-01-20 21:47:46 +0000115cl::opt<bool>
Kristina Brooks31579e92018-10-31 09:34:08 +0000116llvm::Relocations("reloc",
117 cl::desc("Display the relocation entries in the file"));
118static cl::alias RelocationsShort("r", cl::desc("Alias for --reloc"),
Matthew Voss0f436772019-02-19 19:46:08 +0000119 cl::NotHidden, cl::Grouping,
Kristina Brooks31579e92018-10-31 09:34:08 +0000120 cl::aliasopt(llvm::Relocations));
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000121
Kevin Enderby98da6132015-01-20 21:47:46 +0000122cl::opt<bool>
Paul Semelcb0f0432018-06-07 13:30:55 +0000123llvm::DynamicRelocations("dynamic-reloc",
124 cl::desc("Display the dynamic relocation entries in the file"));
George Rimar845d3292019-01-18 10:41:26 +0000125static cl::alias DynamicRelocationsd("R", cl::desc("Alias for --dynamic-reloc"),
Matthew Voss0f436772019-02-19 19:46:08 +0000126 cl::NotHidden, cl::Grouping,
George Rimar845d3292019-01-18 10:41:26 +0000127 cl::aliasopt(DynamicRelocations));
Paul Semelcb0f0432018-06-07 13:30:55 +0000128
129cl::opt<bool>
James Hendersonb55b6582018-10-29 10:05:39 +0000130 llvm::SectionContents("full-contents",
131 cl::desc("Display the content of each section"));
132static cl::alias SectionContentsShort("s",
133 cl::desc("Alias for --full-contents"),
Matthew Voss0f436772019-02-19 19:46:08 +0000134 cl::NotHidden, cl::Grouping,
James Hendersonb55b6582018-10-29 10:05:39 +0000135 cl::aliasopt(SectionContents));
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000136
Kristina Brooks3baa5f72018-10-31 05:45:01 +0000137cl::opt<bool> llvm::SymbolTable("syms", cl::desc("Display the symbol table"));
138static cl::alias SymbolTableShort("t", cl::desc("Alias for --syms"),
Matthew Voss0f436772019-02-19 19:46:08 +0000139 cl::NotHidden, cl::Grouping,
Kristina Brooks3baa5f72018-10-31 05:45:01 +0000140 cl::aliasopt(llvm::SymbolTable));
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000141
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000142cl::opt<bool>
143llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
Nick Kledzikd04bc352014-08-30 00:20:14 +0000144
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000145cl::opt<bool>
146llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
Nick Kledzikac431442014-09-12 21:34:15 +0000147
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000148cl::opt<bool>
149llvm::Bind("bind", cl::desc("Display mach-o binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000150
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000151cl::opt<bool>
152llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000153
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000154cl::opt<bool>
155llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000156
Adrian Prantl437105a2015-07-08 02:04:15 +0000157cl::opt<bool>
158llvm::RawClangAST("raw-clang-ast",
159 cl::desc("Dump the raw binary contents of the clang AST section"));
160
Nick Kledzik56ebef42014-09-16 01:41:51 +0000161static cl::opt<bool>
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000162MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
George Rimar845d3292019-01-18 10:41:26 +0000163static cl::alias MachOm("m", cl::desc("Alias for --macho"), cl::NotHidden,
Matthew Voss0f436772019-02-19 19:46:08 +0000164 cl::Grouping, cl::aliasopt(MachOOpt));
Benjamin Kramer87ee76c2011-07-20 19:37:35 +0000165
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000166cl::opt<std::string>
167llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
168 "see -version for available targets"));
169
170cl::opt<std::string>
Kevin Enderbyc9595622014-08-06 23:24:41 +0000171llvm::MCPU("mcpu",
172 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
173 cl::value_desc("cpu-name"),
174 cl::init(""));
175
176cl::opt<std::string>
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000177llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
Michael J. Spencer2670c252011-01-20 06:39:06 +0000178 "see -version for available targets"));
179
Kevin Enderby98da6132015-01-20 21:47:46 +0000180cl::opt<bool>
181llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
182 "headers for each section."));
George Rimar845d3292019-01-18 10:41:26 +0000183static cl::alias SectionHeadersShort("headers",
184 cl::desc("Alias for --section-headers"),
185 cl::NotHidden,
186 cl::aliasopt(SectionHeaders));
187static cl::alias SectionHeadersShorter("h",
188 cl::desc("Alias for --section-headers"),
Matthew Voss0f436772019-02-19 19:46:08 +0000189 cl::NotHidden, cl::Grouping,
George Rimar845d3292019-01-18 10:41:26 +0000190 cl::aliasopt(SectionHeaders));
Colin LeMahieufcc32762015-07-29 19:08:10 +0000191
George Rimar87fa2e62019-01-28 14:11:35 +0000192static cl::opt<bool>
193 ShowLMA("show-lma",
194 cl::desc("Display LMA column when dumping ELF section headers"));
195
Colin LeMahieu77804be2015-07-29 15:45:39 +0000196cl::list<std::string>
Colin LeMahieufcc32762015-07-29 19:08:10 +0000197llvm::FilterSections("section", cl::desc("Operate on the specified sections only. "
198 "With -macho dump segment,section"));
George Rimar845d3292019-01-18 10:41:26 +0000199cl::alias static FilterSectionsj("j", cl::desc("Alias for --section"),
200 cl::NotHidden,
201 cl::aliasopt(llvm::FilterSections));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000202
Kevin Enderbyc9595622014-08-06 23:24:41 +0000203cl::list<std::string>
204llvm::MAttrs("mattr",
Jack Carter551efd72012-08-28 19:24:49 +0000205 cl::CommaSeparated,
206 cl::desc("Target specific attributes"),
207 cl::value_desc("a1,+a2,-a3,..."));
208
Kevin Enderbybf246f52014-09-24 23:08:22 +0000209cl::opt<bool>
210llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
211 "instructions, do not print "
212 "the instruction bytes."));
Saleem Abdulrasooldea14b22017-02-08 18:11:31 +0000213cl::opt<bool>
214llvm::NoLeadingAddr("no-leading-addr", cl::desc("Print no leading address"));
Eli Bendersky3a6808c2012-11-20 22:57:02 +0000215
Kevin Enderby98da6132015-01-20 21:47:46 +0000216cl::opt<bool>
217llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000218
George Rimar845d3292019-01-18 10:41:26 +0000219static cl::alias UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
Matthew Voss0f436772019-02-19 19:46:08 +0000220 cl::NotHidden, cl::Grouping,
221 cl::aliasopt(UnwindInfo));
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000222
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000223cl::opt<bool>
224llvm::PrivateHeaders("private-headers",
225 cl::desc("Display format specific file headers"));
Michael J. Spencer209565db2013-01-06 03:56:49 +0000226
Kevin Enderby0ae163f2016-01-13 00:25:36 +0000227cl::opt<bool>
228llvm::FirstPrivateHeader("private-header",
229 cl::desc("Display only the first format specific file "
230 "header"));
231
George Rimar845d3292019-01-18 10:41:26 +0000232static cl::alias PrivateHeadersShort("p",
233 cl::desc("Alias for --private-headers"),
Matthew Voss0f436772019-02-19 19:46:08 +0000234 cl::NotHidden, cl::Grouping,
George Rimar845d3292019-01-18 10:41:26 +0000235 cl::aliasopt(PrivateHeaders));
Michael J. Spencer209565db2013-01-06 03:56:49 +0000236
Paul Semeld2af4d62018-07-04 15:25:03 +0000237cl::opt<bool> llvm::FileHeaders(
238 "file-headers",
239 cl::desc("Display the contents of the overall file header"));
240
241static cl::alias FileHeadersShort("f", cl::desc("Alias for --file-headers"),
Matthew Voss0f436772019-02-19 19:46:08 +0000242 cl::NotHidden, cl::Grouping,
243 cl::aliasopt(FileHeaders));
Paul Semeld2af4d62018-07-04 15:25:03 +0000244
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000245cl::opt<bool>
Paul Semel0dc92f62018-07-05 14:43:29 +0000246 llvm::ArchiveHeaders("archive-headers",
247 cl::desc("Display archive header information"));
248
George Rimar845d3292019-01-18 10:41:26 +0000249cl::alias ArchiveHeadersShort("a", cl::desc("Alias for --archive-headers"),
Matthew Voss0f436772019-02-19 19:46:08 +0000250 cl::NotHidden, cl::Grouping,
251 cl::aliasopt(ArchiveHeaders));
Paul Semel0dc92f62018-07-05 14:43:29 +0000252
253cl::opt<bool>
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000254 llvm::PrintImmHex("print-imm-hex",
Colin LeMahieuefe37322016-04-08 18:15:37 +0000255 cl::desc("Use hex format for immediate values"));
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000256
Sanjoy Das6f567a42015-06-22 18:03:02 +0000257cl::opt<bool> PrintFaultMaps("fault-map-section",
258 cl::desc("Display contents of faultmap section"));
259
Igor Laevsky03a670c2016-01-26 15:09:42 +0000260cl::opt<DIDumpType> llvm::DwarfDumpType(
261 "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"),
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000262 cl::values(clEnumValN(DIDT_DebugFrame, "frames", ".debug_frame")));
Igor Laevsky03a670c2016-01-26 15:09:42 +0000263
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000264cl::opt<bool> PrintSource(
265 "source",
266 cl::desc(
Alex Denisova07169e2018-02-02 19:20:37 +0000267 "Display source inlined with disassembly. Implies disassemble object"));
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000268
George Rimar845d3292019-01-18 10:41:26 +0000269cl::alias PrintSourceShort("S", cl::desc("Alias for -source"), cl::NotHidden,
Matthew Voss0f436772019-02-19 19:46:08 +0000270 cl::Grouping, cl::aliasopt(PrintSource));
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000271
272cl::opt<bool> PrintLines("line-numbers",
273 cl::desc("Display source line numbers with "
274 "disassembly. Implies disassemble object"));
275
276cl::alias PrintLinesShort("l", cl::desc("Alias for -line-numbers"),
Matthew Voss0f436772019-02-19 19:46:08 +0000277 cl::NotHidden, cl::Grouping,
278 cl::aliasopt(PrintLines));
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +0000279
280cl::opt<unsigned long long>
281 StartAddress("start-address", cl::desc("Disassemble beginning at address"),
282 cl::value_desc("address"), cl::init(0));
283cl::opt<unsigned long long>
George Rimar70d197d2019-01-10 14:55:26 +0000284 StopAddress("stop-address",
George Rimar3687c3e92019-01-15 14:03:50 +0000285 cl::desc("Stop disassembly at address"),
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +0000286 cl::value_desc("address"), cl::init(UINT64_MAX));
George Rimar70d197d2019-01-10 14:55:26 +0000287
George Rimar3687c3e92019-01-15 14:03:50 +0000288cl::opt<bool> DisassembleZeroes(
289 "disassemble-zeroes",
290 cl::desc("Do not skip blocks of zeroes when disassembling"));
George Rimar70d197d2019-01-10 14:55:26 +0000291cl::alias DisassembleZeroesShort("z",
292 cl::desc("Alias for --disassemble-zeroes"),
Matthew Voss0f436772019-02-19 19:46:08 +0000293 cl::NotHidden, cl::Grouping,
George Rimar70d197d2019-01-10 14:55:26 +0000294 cl::aliasopt(DisassembleZeroes));
295
Igor Kudrin2d3faad2019-02-26 12:15:14 +0000296static cl::list<std::string>
297 DisassemblerOptions("disassembler-options",
298 cl::desc("Pass target specific disassembler options"),
299 cl::value_desc("options"), cl::CommaSeparated);
300static cl::alias
301 DisassemblerOptionsShort("M", cl::desc("Alias for --disassembler-options"),
302 cl::NotHidden, cl::Prefix, cl::CommaSeparated,
303 cl::aliasopt(DisassemblerOptions));
304
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000305static StringRef ToolName;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000306
Clement Courbetd1a3bd42019-01-18 15:26:14 +0000307typedef std::vector<std::tuple<uint64_t, StringRef, uint8_t>> SectionSymbolsTy;
Clement Courbet2d7d4a32019-01-18 09:40:19 +0000308
George Rimarc1964882019-01-18 11:33:26 +0000309SectionFilter llvm::ToolSectionFilter(llvm::object::ObjectFile const &O) {
David Majnemer42531262016-08-12 03:55:06 +0000310 return SectionFilter(
311 [](llvm::object::SectionRef const &S) {
312 if (FilterSections.empty())
313 return true;
314 llvm::StringRef String;
315 std::error_code error = S.getName(String);
316 if (error)
317 return false;
318 return is_contained(FilterSections, String);
319 },
320 O);
Colin LeMahieu77804be2015-07-29 15:45:39 +0000321}
Colin LeMahieu77804be2015-07-29 15:45:39 +0000322
Davide Italianoccd53fe2015-08-05 07:18:31 +0000323void llvm::error(std::error_code EC) {
Mark Seaborneb03ac52014-01-25 00:32:01 +0000324 if (!EC)
Davide Italianoccd53fe2015-08-05 07:18:31 +0000325 return;
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000326 WithColor::error(errs(), ToolName)
327 << "reading file: " << EC.message() << ".\n";
Davide Italiano140af642015-12-25 18:16:45 +0000328 errs().flush();
Davide Italiano7f6c3012015-08-06 00:18:52 +0000329 exit(1);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000330}
331
Kevin Enderby42398052016-06-28 23:16:13 +0000332LLVM_ATTRIBUTE_NORETURN void llvm::error(Twine Message) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000333 WithColor::error(errs(), ToolName) << Message << ".\n";
Kevin Enderby42398052016-06-28 23:16:13 +0000334 errs().flush();
335 exit(1);
336}
337
Paul Semel007dedb2018-07-18 16:39:21 +0000338void llvm::warn(StringRef Message) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000339 WithColor::warning(errs(), ToolName) << Message << ".\n";
Paul Semel007dedb2018-07-18 16:39:21 +0000340 errs().flush();
341}
342
Davide Italianoed9d95b2015-12-29 13:41:02 +0000343LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000344 Twine Message) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000345 WithColor::error(errs(), ToolName)
346 << "'" << File << "': " << Message << ".\n";
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000347 exit(1);
348}
349
350LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
Davide Italianoed9d95b2015-12-29 13:41:02 +0000351 std::error_code EC) {
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000352 assert(EC);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000353 WithColor::error(errs(), ToolName)
354 << "'" << File << "': " << EC.message() << ".\n";
Davide Italianoccd53fe2015-08-05 07:18:31 +0000355 exit(1);
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000356}
357
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000358LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
359 llvm::Error E) {
360 assert(E);
361 std::string Buf;
362 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +0000363 logAllUnhandledErrors(std::move(E), OS);
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000364 OS.flush();
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000365 WithColor::error(errs(), ToolName) << "'" << File << "': " << Buf;
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000366 exit(1);
367}
368
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000369LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
370 StringRef FileName,
Kevin Enderby9acb1092016-05-31 20:35:34 +0000371 llvm::Error E,
372 StringRef ArchitectureName) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000373 assert(E);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000374 WithColor::error(errs(), ToolName);
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000375 if (ArchiveName != "")
376 errs() << ArchiveName << "(" << FileName << ")";
377 else
Justin Bogner31d8b7d2016-10-26 22:37:52 +0000378 errs() << "'" << FileName << "'";
Kevin Enderby9acb1092016-05-31 20:35:34 +0000379 if (!ArchitectureName.empty())
380 errs() << " (for architecture " << ArchitectureName << ")";
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000381 std::string Buf;
382 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +0000383 logAllUnhandledErrors(std::move(E), OS);
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000384 OS.flush();
Justin Bogner31d8b7d2016-10-26 22:37:52 +0000385 errs() << ": " << Buf;
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000386 exit(1);
387}
388
389LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
390 const object::Archive::Child &C,
Kevin Enderby9acb1092016-05-31 20:35:34 +0000391 llvm::Error E,
392 StringRef ArchitectureName) {
Kevin Enderbyf4586032016-07-29 17:44:13 +0000393 Expected<StringRef> NameOrErr = C.getName();
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000394 // TODO: if we have a error getting the name then it would be nice to print
395 // the index of which archive member this is and or its offset in the
396 // archive instead of "???" as the name.
Kevin Enderbyf4586032016-07-29 17:44:13 +0000397 if (!NameOrErr) {
398 consumeError(NameOrErr.takeError());
Kevin Enderby9acb1092016-05-31 20:35:34 +0000399 llvm::report_error(ArchiveName, "???", std::move(E), ArchitectureName);
Kevin Enderbyf4586032016-07-29 17:44:13 +0000400 } else
Kevin Enderby9acb1092016-05-31 20:35:34 +0000401 llvm::report_error(ArchiveName, NameOrErr.get(), std::move(E),
402 ArchitectureName);
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000403}
404
Craig Toppere6cb63e2014-04-25 04:24:47 +0000405static const Target *getTarget(const ObjectFile *Obj = nullptr) {
Michael J. Spencer2670c252011-01-20 06:39:06 +0000406 // Figure out the target triple.
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000407 llvm::Triple TheTriple("unknown-unknown-unknown");
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000408 if (TripleName.empty()) {
George Rimar73a27232019-01-15 09:19:18 +0000409 if (Obj)
Vlad Tsyrklevichde620462017-09-19 02:22:48 +0000410 TheTriple = Obj->makeTriple();
Sam Parkerdf7c6ef2017-01-18 13:52:12 +0000411 } else {
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000412 TheTriple.setTriple(Triple::normalize(TripleName));
Vlad Tsyrklevichde620462017-09-19 02:22:48 +0000413
Sam Parkerdf7c6ef2017-01-18 13:52:12 +0000414 // Use the triple, but also try to combine with ARM build attributes.
415 if (Obj) {
416 auto Arch = Obj->getArch();
George Rimar73a27232019-01-15 09:19:18 +0000417 if (Arch == Triple::arm || Arch == Triple::armeb)
Sam Parkerdf7c6ef2017-01-18 13:52:12 +0000418 Obj->setARMSubArch(TheTriple);
Sam Parkerdf7c6ef2017-01-18 13:52:12 +0000419 }
420 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000421
422 // Get the target specific parser.
423 std::string Error;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000424 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
425 Error);
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000426 if (!TheTarget) {
427 if (Obj)
428 report_error(Obj->getFileName(), "can't find target: " + Error);
429 else
430 error("can't find target: " + Error);
431 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000432
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000433 // Update the triple name and return the found target.
434 TripleName = TheTriple.getTriple();
435 return TheTarget;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000436}
437
George Rimar73a27232019-01-15 09:19:18 +0000438bool llvm::isRelocAddressLess(RelocationRef A, RelocationRef B) {
439 return A.getOffset() < B.getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +0000440}
441
Rafael Espindola37070a52015-06-03 04:48:06 +0000442static std::error_code getRelocationValueString(const RelocationRef &Rel,
443 SmallVectorImpl<char> &Result) {
Rafael Espindola854038e2015-06-26 14:51:16 +0000444 const ObjectFile *Obj = Rel.getObject();
Rafael Espindola37070a52015-06-03 04:48:06 +0000445 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
George Rimarc1964882019-01-18 11:33:26 +0000446 return getELFRelocationValueString(ELF, Rel, Result);
Rafael Espindola37070a52015-06-03 04:48:06 +0000447 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
George Rimarc1964882019-01-18 11:33:26 +0000448 return getCOFFRelocationValueString(COFF, Rel, Result);
Sam Clegg4df5d762017-06-27 20:40:53 +0000449 if (auto *Wasm = dyn_cast<WasmObjectFile>(Obj))
George Rimarc1964882019-01-18 11:33:26 +0000450 return getWasmRelocationValueString(Wasm, Rel, Result);
Sam Clegg4df5d762017-06-27 20:40:53 +0000451 if (auto *MachO = dyn_cast<MachOObjectFile>(Obj))
George Rimarc1964882019-01-18 11:33:26 +0000452 return getMachORelocationValueString(MachO, Rel, Result);
Sam Clegg4df5d762017-06-27 20:40:53 +0000453 llvm_unreachable("unknown object file format");
Rafael Espindola37070a52015-06-03 04:48:06 +0000454}
455
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000456/// Indicates whether this relocation should hidden when listing
Rafael Espindola0ad71d92015-06-30 03:41:26 +0000457/// relocations, usually because it is the trailing part of a multipart
458/// relocation that will be printed as part of the leading relocation.
459static bool getHidden(RelocationRef RelRef) {
George Rimar73a27232019-01-15 09:19:18 +0000460 auto *MachO = dyn_cast<MachOObjectFile>(RelRef.getObject());
Rafael Espindola0ad71d92015-06-30 03:41:26 +0000461 if (!MachO)
462 return false;
463
464 unsigned Arch = MachO->getArch();
465 DataRefImpl Rel = RelRef.getRawDataRefImpl();
466 uint64_t Type = MachO->getRelocationType(Rel);
467
468 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
469 // is always hidden.
George Rimar73a27232019-01-15 09:19:18 +0000470 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc)
471 return Type == MachO::GENERIC_RELOC_PAIR;
472
473 if (Arch == Triple::x86_64) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +0000474 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
475 // an X86_64_RELOC_SUBTRACTOR.
476 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
477 DataRefImpl RelPrev = Rel;
478 RelPrev.d.a--;
479 uint64_t PrevType = MachO->getRelocationType(RelPrev);
480 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
481 return true;
482 }
483 }
484
485 return false;
486}
487
Sid Manningd9f28732018-05-14 19:46:08 +0000488namespace {
489class SourcePrinter {
490protected:
491 DILineInfo OldLineInfo;
492 const ObjectFile *Obj = nullptr;
493 std::unique_ptr<symbolize::LLVMSymbolizer> Symbolizer;
494 // File name to file contents of source
495 std::unordered_map<std::string, std::unique_ptr<MemoryBuffer>> SourceCache;
496 // Mark the line endings of the cached source
497 std::unordered_map<std::string, std::vector<StringRef>> LineCache;
498
499private:
500 bool cacheSource(const DILineInfo& LineInfoFile);
501
502public:
503 SourcePrinter() = default;
504 SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch) : Obj(Obj) {
505 symbolize::LLVMSymbolizer::Options SymbolizerOpts(
506 DILineInfoSpecifier::FunctionNameKind::None, true, false, false,
507 DefaultArch);
508 Symbolizer.reset(new symbolize::LLVMSymbolizer(SymbolizerOpts));
509 }
510 virtual ~SourcePrinter() = default;
511 virtual void printSourceLine(raw_ostream &OS, uint64_t Address,
512 StringRef Delimiter = "; ");
513};
514
515bool SourcePrinter::cacheSource(const DILineInfo &LineInfo) {
516 std::unique_ptr<MemoryBuffer> Buffer;
517 if (LineInfo.Source) {
518 Buffer = MemoryBuffer::getMemBuffer(*LineInfo.Source);
519 } else {
520 auto BufferOrError = MemoryBuffer::getFile(LineInfo.FileName);
521 if (!BufferOrError)
522 return false;
523 Buffer = std::move(*BufferOrError);
524 }
525 // Chomp the file to get lines
526 size_t BufferSize = Buffer->getBufferSize();
527 const char *BufferStart = Buffer->getBufferStart();
528 for (const char *Start = BufferStart, *End = BufferStart;
529 End < BufferStart + BufferSize; End++)
530 if (*End == '\n' || End == BufferStart + BufferSize - 1 ||
531 (*End == '\r' && *(End + 1) == '\n')) {
532 LineCache[LineInfo.FileName].push_back(StringRef(Start, End - Start));
533 if (*End == '\r')
534 End++;
535 Start = End + 1;
536 }
537 SourceCache[LineInfo.FileName] = std::move(Buffer);
538 return true;
539}
540
541void SourcePrinter::printSourceLine(raw_ostream &OS, uint64_t Address,
542 StringRef Delimiter) {
543 if (!Symbolizer)
544 return;
545 DILineInfo LineInfo = DILineInfo();
546 auto ExpectecLineInfo =
547 Symbolizer->symbolizeCode(Obj->getFileName(), Address);
548 if (!ExpectecLineInfo)
549 consumeError(ExpectecLineInfo.takeError());
550 else
551 LineInfo = *ExpectecLineInfo;
552
553 if ((LineInfo.FileName == "<invalid>") || OldLineInfo.Line == LineInfo.Line ||
554 LineInfo.Line == 0)
555 return;
556
557 if (PrintLines)
558 OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line << "\n";
559 if (PrintSource) {
560 if (SourceCache.find(LineInfo.FileName) == SourceCache.end())
561 if (!cacheSource(LineInfo))
562 return;
563 auto FileBuffer = SourceCache.find(LineInfo.FileName);
564 if (FileBuffer != SourceCache.end()) {
565 auto LineBuffer = LineCache.find(LineInfo.FileName);
566 if (LineBuffer != LineCache.end()) {
567 if (LineInfo.Line > LineBuffer->second.size())
568 return;
569 // Vector begins at 0, line numbers are non-zero
570 OS << Delimiter << LineBuffer->second[LineInfo.Line - 1].ltrim()
571 << "\n";
572 }
573 }
574 }
575 OldLineInfo = LineInfo;
576}
577
578static bool isArmElf(const ObjectFile *Obj) {
579 return (Obj->isELF() &&
580 (Obj->getArch() == Triple::aarch64 ||
581 Obj->getArch() == Triple::aarch64_be ||
582 Obj->getArch() == Triple::arm || Obj->getArch() == Triple::armeb ||
583 Obj->getArch() == Triple::thumb ||
584 Obj->getArch() == Triple::thumbeb));
585}
586
George Rimar617adef2019-01-23 13:39:12 +0000587static void printRelocation(const RelocationRef &Rel, uint64_t Address,
588 uint8_t AddrSize) {
589 StringRef Fmt =
590 AddrSize > 4 ? "\t\t%016" PRIx64 ": " : "\t\t\t%08" PRIx64 ": ";
591 SmallString<16> Name;
592 SmallString<32> Val;
593 Rel.getTypeName(Name);
594 error(getRelocationValueString(Rel, Val));
595 outs() << format(Fmt.data(), Address) << Name << "\t" << Val << "\n";
596}
597
Sid Manningd9f28732018-05-14 19:46:08 +0000598class PrettyPrinter {
599public:
600 virtual ~PrettyPrinter() = default;
601 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
602 ArrayRef<uint8_t> Bytes, uint64_t Address,
603 raw_ostream &OS, StringRef Annot,
604 MCSubtargetInfo const &STI, SourcePrinter *SP,
605 std::vector<RelocationRef> *Rels = nullptr) {
606 if (SP && (PrintSource || PrintLines))
607 SP->printSourceLine(OS, Address);
608 if (!NoLeadingAddr)
609 OS << format("%8" PRIx64 ":", Address);
610 if (!NoShowRawInsn) {
611 OS << "\t";
612 dumpBytes(Bytes, OS);
613 }
614 if (MI)
615 IP.printInst(MI, OS, "", STI);
616 else
617 OS << " <unknown>";
618 }
619};
620PrettyPrinter PrettyPrinterInst;
621class HexagonPrettyPrinter : public PrettyPrinter {
622public:
623 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
624 raw_ostream &OS) {
625 uint32_t opcode =
626 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
627 if (!NoLeadingAddr)
628 OS << format("%8" PRIx64 ":", Address);
629 if (!NoShowRawInsn) {
630 OS << "\t";
631 dumpBytes(Bytes.slice(0, 4), OS);
632 OS << format("%08" PRIx32, opcode);
633 }
634 }
635 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
636 uint64_t Address, raw_ostream &OS, StringRef Annot,
637 MCSubtargetInfo const &STI, SourcePrinter *SP,
638 std::vector<RelocationRef> *Rels) override {
639 if (SP && (PrintSource || PrintLines))
640 SP->printSourceLine(OS, Address, "");
641 if (!MI) {
642 printLead(Bytes, Address, OS);
643 OS << " <unknown>";
644 return;
645 }
646 std::string Buffer;
647 {
648 raw_string_ostream TempStream(Buffer);
649 IP.printInst(MI, TempStream, "", STI);
650 }
651 StringRef Contents(Buffer);
652 // Split off bundle attributes
653 auto PacketBundle = Contents.rsplit('\n');
654 // Split off first instruction from the rest
655 auto HeadTail = PacketBundle.first.split('\n');
656 auto Preamble = " { ";
657 auto Separator = "";
Sid Manningd9f28732018-05-14 19:46:08 +0000658
659 // Hexagon's packets require relocations to be inline rather than
660 // clustered at the end of the packet.
George Rimar617adef2019-01-23 13:39:12 +0000661 std::vector<RelocationRef>::const_iterator RelCur = Rels->begin();
662 std::vector<RelocationRef>::const_iterator RelEnd = Rels->end();
Sid Manningd9f28732018-05-14 19:46:08 +0000663 auto PrintReloc = [&]() -> void {
George Rimar73a27232019-01-15 09:19:18 +0000664 while ((RelCur != RelEnd) && (RelCur->getOffset() <= Address)) {
665 if (RelCur->getOffset() == Address) {
George Rimar617adef2019-01-23 13:39:12 +0000666 printRelocation(*RelCur, Address, 4);
Sid Manningd9f28732018-05-14 19:46:08 +0000667 return;
668 }
George Rimar73a27232019-01-15 09:19:18 +0000669 ++RelCur;
Sid Manningd9f28732018-05-14 19:46:08 +0000670 }
671 };
672
George Rimar73a27232019-01-15 09:19:18 +0000673 while (!HeadTail.first.empty()) {
Sid Manningd9f28732018-05-14 19:46:08 +0000674 OS << Separator;
675 Separator = "\n";
676 if (SP && (PrintSource || PrintLines))
677 SP->printSourceLine(OS, Address, "");
678 printLead(Bytes, Address, OS);
679 OS << Preamble;
680 Preamble = " ";
681 StringRef Inst;
682 auto Duplex = HeadTail.first.split('\v');
George Rimar73a27232019-01-15 09:19:18 +0000683 if (!Duplex.second.empty()) {
Sid Manningd9f28732018-05-14 19:46:08 +0000684 OS << Duplex.first;
685 OS << "; ";
686 Inst = Duplex.second;
687 }
688 else
689 Inst = HeadTail.first;
690 OS << Inst;
691 HeadTail = HeadTail.second.split('\n');
692 if (HeadTail.first.empty())
693 OS << " } " << PacketBundle.second;
694 PrintReloc();
695 Bytes = Bytes.slice(4);
696 Address += 4;
697 }
698 }
699};
700HexagonPrettyPrinter HexagonPrettyPrinterInst;
701
702class AMDGCNPrettyPrinter : public PrettyPrinter {
703public:
704 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
705 uint64_t Address, raw_ostream &OS, StringRef Annot,
706 MCSubtargetInfo const &STI, SourcePrinter *SP,
707 std::vector<RelocationRef> *Rels) override {
708 if (SP && (PrintSource || PrintLines))
709 SP->printSourceLine(OS, Address);
710
711 typedef support::ulittle32_t U32;
712
713 if (MI) {
714 SmallString<40> InstStr;
715 raw_svector_ostream IS(InstStr);
716
717 IP.printInst(MI, IS, "", STI);
718
719 OS << left_justify(IS.str(), 60);
720 } else {
721 // an unrecognized encoding - this is probably data so represent it
722 // using the .long directive, or .byte directive if fewer than 4 bytes
723 // remaining
724 if (Bytes.size() >= 4) {
725 OS << format("\t.long 0x%08" PRIx32 " ",
726 static_cast<uint32_t>(*reinterpret_cast<const U32*>(Bytes.data())));
727 OS.indent(42);
728 } else {
729 OS << format("\t.byte 0x%02" PRIx8, Bytes[0]);
730 for (unsigned int i = 1; i < Bytes.size(); i++)
731 OS << format(", 0x%02" PRIx8, Bytes[i]);
732 OS.indent(55 - (6 * Bytes.size()));
733 }
734 }
735
736 OS << format("// %012" PRIX64 ": ", Address);
737 if (Bytes.size() >=4) {
738 for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
739 Bytes.size() / sizeof(U32)))
740 // D should be explicitly casted to uint32_t here as it is passed
741 // by format to snprintf as vararg.
742 OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D));
743 } else {
744 for (unsigned int i = 0; i < Bytes.size(); i++)
745 OS << format("%02" PRIX8 " ", Bytes[i]);
746 }
747
748 if (!Annot.empty())
749 OS << "// " << Annot;
750 }
751};
752AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
753
754class BPFPrettyPrinter : public PrettyPrinter {
755public:
756 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
757 uint64_t Address, raw_ostream &OS, StringRef Annot,
758 MCSubtargetInfo const &STI, SourcePrinter *SP,
759 std::vector<RelocationRef> *Rels) override {
760 if (SP && (PrintSource || PrintLines))
761 SP->printSourceLine(OS, Address);
762 if (!NoLeadingAddr)
763 OS << format("%8" PRId64 ":", Address / 8);
764 if (!NoShowRawInsn) {
765 OS << "\t";
766 dumpBytes(Bytes, OS);
767 }
768 if (MI)
769 IP.printInst(MI, OS, "", STI);
770 else
771 OS << " <unknown>";
772 }
773};
774BPFPrettyPrinter BPFPrettyPrinterInst;
775
776PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
777 switch(Triple.getArch()) {
778 default:
779 return PrettyPrinterInst;
780 case Triple::hexagon:
781 return HexagonPrettyPrinterInst;
782 case Triple::amdgcn:
783 return AMDGCNPrettyPrinterInst;
784 case Triple::bpfel:
785 case Triple::bpfeb:
786 return BPFPrettyPrinterInst;
787 }
788}
789}
790
Sam Koltonc05d7782016-08-17 10:17:57 +0000791static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) {
792 assert(Obj->isELF());
793 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
794 return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
795 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
796 return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
797 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
798 return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
799 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
800 return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
801 llvm_unreachable("Unsupported binary format");
802}
803
Sam Parker5fba45a2017-02-08 09:44:18 +0000804template <class ELFT> static void
805addDynamicElfSymbols(const ELFObjectFile<ELFT> *Obj,
806 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
807 for (auto Symbol : Obj->getDynamicSymbolIterators()) {
808 uint8_t SymbolType = Symbol.getELFType();
809 if (SymbolType != ELF::STT_FUNC || Symbol.getSize() == 0)
810 continue;
811
812 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
813 if (!AddressOrErr)
814 report_error(Obj->getFileName(), AddressOrErr.takeError());
Sam Parker5fba45a2017-02-08 09:44:18 +0000815
816 Expected<StringRef> Name = Symbol.getName();
817 if (!Name)
818 report_error(Obj->getFileName(), Name.takeError());
819 if (Name->empty())
820 continue;
821
822 Expected<section_iterator> SectionOrErr = Symbol.getSection();
823 if (!SectionOrErr)
824 report_error(Obj->getFileName(), SectionOrErr.takeError());
825 section_iterator SecI = *SectionOrErr;
826 if (SecI == Obj->section_end())
827 continue;
828
George Rimar73a27232019-01-15 09:19:18 +0000829 AllSymbols[*SecI].emplace_back(*AddressOrErr, *Name, SymbolType);
Sam Parker5fba45a2017-02-08 09:44:18 +0000830 }
831}
832
833static void
834addDynamicElfSymbols(const ObjectFile *Obj,
835 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
836 assert(Obj->isELF());
837 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
838 addDynamicElfSymbols(Elf32LEObj, AllSymbols);
839 else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
840 addDynamicElfSymbols(Elf64LEObj, AllSymbols);
841 else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
842 addDynamicElfSymbols(Elf32BEObj, AllSymbols);
843 else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
844 addDynamicElfSymbols(Elf64BEObj, AllSymbols);
845 else
846 llvm_unreachable("Unsupported binary format");
847}
848
Joel Galenson134cf472018-08-24 15:21:57 +0000849static void addPltEntries(const ObjectFile *Obj,
850 std::map<SectionRef, SectionSymbolsTy> &AllSymbols,
851 StringSaver &Saver) {
852 Optional<SectionRef> Plt = None;
853 for (const SectionRef &Section : Obj->sections()) {
854 StringRef Name;
855 if (Section.getName(Name))
856 continue;
857 if (Name == ".plt")
858 Plt = Section;
859 }
860 if (!Plt)
861 return;
862 if (auto *ElfObj = dyn_cast<ELFObjectFileBase>(Obj)) {
863 for (auto PltEntry : ElfObj->getPltAddresses()) {
864 SymbolRef Symbol(PltEntry.first, ElfObj);
Joel Galenson134cf472018-08-24 15:21:57 +0000865 uint8_t SymbolType = getElfSymbolType(Obj, Symbol);
866
867 Expected<StringRef> NameOrErr = Symbol.getName();
868 if (!NameOrErr)
869 report_error(Obj->getFileName(), NameOrErr.takeError());
870 if (NameOrErr->empty())
871 continue;
872 StringRef Name = Saver.save((*NameOrErr + "@plt").str());
873
874 AllSymbols[*Plt].emplace_back(PltEntry.second, Name, SymbolType);
875 }
876 }
877}
878
George Rimar70d197d2019-01-10 14:55:26 +0000879// Normally the disassembly output will skip blocks of zeroes. This function
880// returns the number of zero bytes that can be skipped when dumping the
881// disassembly of the instructions in Buf.
882static size_t countSkippableZeroBytes(ArrayRef<uint8_t> Buf) {
George Rimar70d197d2019-01-10 14:55:26 +0000883 // Find the number of leading zeroes.
884 size_t N = 0;
885 while (N < Buf.size() && !Buf[N])
886 ++N;
887
888 // We may want to skip blocks of zero bytes, but unless we see
889 // at least 8 of them in a row.
890 if (N < 8)
891 return 0;
892
893 // We skip zeroes in multiples of 4 because do not want to truncate an
894 // instruction if it starts with a zero byte.
895 return N & ~0x3;
896}
897
George Rimar121fcd72019-01-22 14:09:37 +0000898// Returns a map from sections to their relocations.
899static std::map<SectionRef, std::vector<RelocationRef>>
900getRelocsMap(llvm::object::ObjectFile const &Obj) {
901 std::map<SectionRef, std::vector<RelocationRef>> Ret;
902 for (const SectionRef &Section : ToolSectionFilter(Obj)) {
903 section_iterator RelSec = Section.getRelocatedSection();
904 if (RelSec == Obj.section_end())
905 continue;
906 std::vector<RelocationRef> &V = Ret[*RelSec];
907 for (const RelocationRef &R : Section.relocations())
908 V.push_back(R);
909 // Sort relocations by address.
910 llvm::sort(V, isRelocAddressLess);
911 }
912 return Ret;
913}
914
George Rimar4c3b2972019-01-28 10:44:01 +0000915// Used for --adjust-vma to check if address should be adjusted by the
916// specified value for a given section.
917// For ELF we do not adjust non-allocatable sections like debug ones,
918// because they are not loadable.
919// TODO: implement for other file formats.
920static bool shouldAdjustVA(const SectionRef &Section) {
921 const ObjectFile *Obj = Section.getObject();
922 if (isa<object::ELFObjectFileBase>(Obj))
923 return ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC;
924 return false;
925}
926
George Rimarbcbe98b2019-01-23 10:33:26 +0000927static void disassembleObject(const Target *TheTarget, const ObjectFile *Obj,
928 MCContext &Ctx, MCDisassembler *DisAsm,
929 const MCInstrAnalysis *MIA, MCInstPrinter *IP,
930 const MCSubtargetInfo *STI, PrettyPrinter &PIP,
931 SourcePrinter &SP, bool InlineRelocs) {
George Rimar121fcd72019-01-22 14:09:37 +0000932 std::map<SectionRef, std::vector<RelocationRef>> RelocMap;
933 if (InlineRelocs)
934 RelocMap = getRelocsMap(*Obj);
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000935
David Majnemer81afca62015-07-07 22:06:59 +0000936 // Create a mapping from virtual address to symbol name. This is used to
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000937 // pretty print the symbols while disassembling.
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000938 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
Sterling Augustinebc78b622018-06-28 18:57:13 +0000939 SectionSymbolsTy AbsoluteSymbols;
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000940 for (const SymbolRef &Symbol : Obj->symbols()) {
Kevin Enderby931cb652016-06-24 18:24:42 +0000941 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000942 if (!AddressOrErr)
943 report_error(Obj->getFileName(), AddressOrErr.takeError());
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000944 uint64_t Address = *AddressOrErr;
David Majnemer2603a8fa2015-07-09 18:11:40 +0000945
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000946 Expected<StringRef> Name = Symbol.getName();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000947 if (!Name)
948 report_error(Obj->getFileName(), Name.takeError());
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000949 if (Name->empty())
950 continue;
David Majnemer81afca62015-07-07 22:06:59 +0000951
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000952 Expected<section_iterator> SectionOrErr = Symbol.getSection();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000953 if (!SectionOrErr)
954 report_error(Obj->getFileName(), SectionOrErr.takeError());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +0000955
Sam Koltonc05d7782016-08-17 10:17:57 +0000956 uint8_t SymbolType = ELF::STT_NOTYPE;
Matt Davis82937e42019-01-31 19:42:21 +0000957 if (Obj->isELF()) {
Sam Koltonc05d7782016-08-17 10:17:57 +0000958 SymbolType = getElfSymbolType(Obj, Symbol);
Matt Davis82937e42019-01-31 19:42:21 +0000959 if (SymbolType == ELF::STT_SECTION)
960 continue;
961 }
David Majnemer81afca62015-07-07 22:06:59 +0000962
Sterling Augustinebc78b622018-06-28 18:57:13 +0000963 section_iterator SecI = *SectionOrErr;
964 if (SecI != Obj->section_end())
965 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
966 else
967 AbsoluteSymbols.emplace_back(Address, *Name, SymbolType);
968
Sam Koltonc05d7782016-08-17 10:17:57 +0000969
David Majnemer81afca62015-07-07 22:06:59 +0000970 }
Sam Parker5fba45a2017-02-08 09:44:18 +0000971 if (AllSymbols.empty() && Obj->isELF())
972 addDynamicElfSymbols(Obj, AllSymbols);
David Majnemer81afca62015-07-07 22:06:59 +0000973
Joel Galenson134cf472018-08-24 15:21:57 +0000974 BumpPtrAllocator A;
975 StringSaver Saver(A);
976 addPltEntries(Obj, AllSymbols, Saver);
977
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000978 // Create a mapping from virtual address to section.
979 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
980 for (SectionRef Sec : Obj->sections())
981 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
982 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
983
984 // Linked executables (.exe and .dll files) typically don't include a real
985 // symbol table but they might contain an export table.
986 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
987 for (const auto &ExportEntry : COFFObj->export_directories()) {
988 StringRef Name;
989 error(ExportEntry.getSymbolName(Name));
990 if (Name.empty())
991 continue;
992 uint32_t RVA;
993 error(ExportEntry.getExportRVA(RVA));
994
995 uint64_t VA = COFFObj->getImageBase() + RVA;
996 auto Sec = std::upper_bound(
997 SectionAddresses.begin(), SectionAddresses.end(), VA,
998 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
999 return LHS < RHS.first;
1000 });
1001 if (Sec != SectionAddresses.begin())
1002 --Sec;
1003 else
1004 Sec = SectionAddresses.end();
1005
1006 if (Sec != SectionAddresses.end())
Sam Koltonc05d7782016-08-17 10:17:57 +00001007 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
Sterling Augustinebc78b622018-06-28 18:57:13 +00001008 else
1009 AbsoluteSymbols.emplace_back(VA, Name, ELF::STT_NOTYPE);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001010 }
1011 }
1012
1013 // Sort all the symbols, this allows us to use a simple binary search to find
1014 // a symbol near an address.
1015 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1016 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
Sterling Augustinebc78b622018-06-28 18:57:13 +00001017 array_pod_sort(AbsoluteSymbols.begin(), AbsoluteSymbols.end());
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001018
Colin LeMahieu77804be2015-07-29 15:45:39 +00001019 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Colin LeMahieuf34933e2015-07-23 20:58:49 +00001020 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
Mark Seaborneb03ac52014-01-25 00:32:01 +00001021 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +00001022
Rafael Espindola80291272014-10-08 15:28:58 +00001023 uint64_t SectionAddr = Section.getAddress();
1024 uint64_t SectSize = Section.getSize();
David Majnemer185b5b12014-11-11 09:58:25 +00001025 if (!SectSize)
1026 continue;
Simon Atanasyan2b614e12014-02-24 22:12:11 +00001027
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001028 // Get the list of all the symbols in this section.
1029 SectionSymbolsTy &Symbols = AllSymbols[Section];
Davide Italianof0706882015-10-01 21:57:09 +00001030 std::vector<uint64_t> DataMappingSymsAddr;
1031 std::vector<uint64_t> TextMappingSymsAddr;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001032 if (isArmElf(Obj)) {
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001033 for (const auto &Symb : Symbols) {
Clement Courbetd1a3bd42019-01-18 15:26:14 +00001034 uint64_t Address = std::get<0>(Symb);
1035 StringRef Name = std::get<1>(Symb);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001036 if (Name.startswith("$d"))
David Majnemer153722d2015-11-18 04:35:32 +00001037 DataMappingSymsAddr.push_back(Address - SectionAddr);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001038 if (Name.startswith("$x"))
David Majnemer153722d2015-11-18 04:35:32 +00001039 TextMappingSymsAddr.push_back(Address - SectionAddr);
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001040 if (Name.startswith("$a"))
1041 TextMappingSymsAddr.push_back(Address - SectionAddr);
1042 if (Name.startswith("$t"))
1043 TextMappingSymsAddr.push_back(Address - SectionAddr);
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001044 }
1045 }
1046
Fangrui Song0cac7262018-09-27 02:13:45 +00001047 llvm::sort(DataMappingSymsAddr);
1048 llvm::sort(TextMappingSymsAddr);
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001049
Sam Kolton3381d7a2016-10-06 13:46:08 +00001050 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1051 // AMDGPU disassembler uses symbolizer for printing labels
1052 std::unique_ptr<MCRelocationInfo> RelInfo(
1053 TheTarget->createMCRelocationInfo(TripleName, Ctx));
1054 if (RelInfo) {
1055 std::unique_ptr<MCSymbolizer> Symbolizer(
1056 TheTarget->createMCSymbolizer(
1057 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1058 DisAsm->setSymbolizer(std::move(Symbolizer));
1059 }
1060 }
1061
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001062 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +00001063 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001064 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +00001065 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001066 }
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001067 StringRef SectionName;
1068 error(Section.getName(SectionName));
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001069
Rafael Espindola7884c952015-06-04 15:01:05 +00001070 // If the section has no symbol at the start, just insert a dummy one.
Clement Courbetd1a3bd42019-01-18 15:26:14 +00001071 if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) {
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001072 Symbols.insert(
1073 Symbols.begin(),
Clement Courbetd1a3bd42019-01-18 15:26:14 +00001074 std::make_tuple(SectionAddr, SectionName,
1075 Section.isText() ? ELF::STT_FUNC : ELF::STT_OBJECT));
Sam Koltonc05d7782016-08-17 10:17:57 +00001076 }
Alp Tokere69170a2014-06-26 22:52:05 +00001077
1078 SmallString<40> Comments;
1079 raw_svector_ostream CommentStream(Comments);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001080
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001081 StringRef BytesStr;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001082 error(Section.getContents(BytesStr));
Aaron Ballman106fd7b2014-11-12 14:01:17 +00001083 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1084 BytesStr.size());
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001085
George Rimar4c3b2972019-01-28 10:44:01 +00001086 uint64_t VMAAdjustment = 0;
1087 if (shouldAdjustVA(Section))
1088 VMAAdjustment = AdjustVMA;
1089
Michael J. Spencer2670c252011-01-20 06:39:06 +00001090 uint64_t Size;
1091 uint64_t Index;
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001092 bool PrintedSection = false;
George Rimar121fcd72019-01-22 14:09:37 +00001093 std::vector<RelocationRef> Rels = RelocMap[Section];
George Rimar73a27232019-01-15 09:19:18 +00001094 std::vector<RelocationRef>::const_iterator RelCur = Rels.begin();
1095 std::vector<RelocationRef>::const_iterator RelEnd = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001096 // Disassemble symbol by symbol.
George Rimar73a27232019-01-15 09:19:18 +00001097 for (unsigned SI = 0, SE = Symbols.size(); SI != SE; ++SI) {
Clement Courbetd1a3bd42019-01-18 15:26:14 +00001098 uint64_t Start = std::get<0>(Symbols[SI]) - SectionAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001099 // The end is either the section end or the beginning of the next
1100 // symbol.
Clement Courbetd1a3bd42019-01-18 15:26:14 +00001101 uint64_t End = (SI == SE - 1)
1102 ? SectSize
1103 : std::get<0>(Symbols[SI + 1]) - SectionAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001104 // Don't try to disassemble beyond the end of section contents.
1105 if (End > SectSize)
1106 End = SectSize;
Rafael Espindolae45c7402014-08-17 16:31:39 +00001107 // If this symbol has the same address as the next symbol, then skip it.
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001108 if (Start >= End)
Michael J. Spenceree84f642011-10-13 20:37:08 +00001109 continue;
1110
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001111 // Check if we need to skip symbol
1112 // Skip if the symbol's data is not between StartAddress and StopAddress
1113 if (End + SectionAddr < StartAddress ||
1114 Start + SectionAddr > StopAddress) {
1115 continue;
1116 }
1117
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001118 /// Skip if user requested specific symbols and this is not in the list
Clement Courbetd1a3bd42019-01-18 15:26:14 +00001119 if (!DisasmFuncsSet.empty() &&
1120 !DisasmFuncsSet.count(std::get<1>(Symbols[SI])))
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001121 continue;
1122
1123 if (!PrintedSection) {
1124 PrintedSection = true;
1125 outs() << "Disassembly of section ";
1126 if (!SegmentName.empty())
1127 outs() << SegmentName << ",";
1128 outs() << SectionName << ':';
1129 }
1130
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001131 // Stop disassembly at the stop address specified
1132 if (End + SectionAddr > StopAddress)
1133 End = StopAddress - SectionAddr;
1134
Valery Pykhtinde048052016-04-07 07:24:01 +00001135 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
Clement Courbetd1a3bd42019-01-18 15:26:14 +00001136 if (std::get<2>(Symbols[SI]) == ELF::STT_AMDGPU_HSA_KERNEL) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001137 // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)
1138 Start += 256;
1139 }
George Rimar73a27232019-01-15 09:19:18 +00001140 if (SI == SE - 1 ||
Clement Courbetd1a3bd42019-01-18 15:26:14 +00001141 std::get<2>(Symbols[SI + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001142 // cut trailing zeroes at the end of kernel
1143 // cut up to 256 bytes
1144 const uint64_t EndAlign = 256;
1145 const auto Limit = End - (std::min)(EndAlign, End - Start);
1146 while (End > Limit &&
1147 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1148 End -= 4;
1149 }
Valery Pykhtinde048052016-04-07 07:24:01 +00001150 }
1151
George Rimar6622d412018-12-19 10:21:45 +00001152 outs() << '\n';
George Rimar3ba0f3c02019-01-09 14:43:33 +00001153 if (!NoLeadingAddr)
George Rimar4c3b2972019-01-28 10:44:01 +00001154 outs() << format("%016" PRIx64 " ",
1155 SectionAddr + Start + VMAAdjustment);
George Rimar3ba0f3c02019-01-09 14:43:33 +00001156
Clement Courbetd1a3bd42019-01-18 15:26:14 +00001157 StringRef SymbolName = std::get<1>(Symbols[SI]);
George Rimar6622d412018-12-19 10:21:45 +00001158 if (Demangle)
1159 outs() << demangle(SymbolName) << ":\n";
1160 else
1161 outs() << SymbolName << ":\n";
Michael J. Spencer2670c252011-01-20 06:39:06 +00001162
Francis Visoiu Mistrih18346822018-04-19 17:02:57 +00001163 // Don't print raw contents of a virtual section. A virtual section
1164 // doesn't have any contents in the file.
1165 if (Section.isVirtual()) {
1166 outs() << "...\n";
1167 continue;
1168 }
1169
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001170#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +00001171 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001172#else
Mark Seaborneb03ac52014-01-25 00:32:01 +00001173 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001174#endif
1175
Wouter van Oortmerssenf3b762a2019-01-17 18:14:09 +00001176 // Some targets (like WebAssembly) have a special prelude at the start
1177 // of each symbol.
1178 DisAsm->onSymbolStart(SymbolName, Size, Bytes.slice(Start, End - Start),
1179 SectionAddr + Start, DebugOut, CommentStream);
1180 Start += Size;
1181
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001182 for (Index = Start; Index < End; Index += Size) {
1183 MCInst Inst;
Owen Andersona0c3b972011-09-15 23:38:46 +00001184
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001185 if (Index + SectionAddr < StartAddress ||
1186 Index + SectionAddr > StopAddress) {
1187 // skip byte by byte till StartAddress is reached
1188 Size = 1;
1189 continue;
1190 }
Davide Italianof0706882015-10-01 21:57:09 +00001191 // AArch64 ELF binaries can interleave data and text in the
1192 // same section. We rely on the markers introduced to
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001193 // understand what we need to dump. If the data marker is within a
1194 // function, it is denoted as a word/short etc
Clement Courbetd1a3bd42019-01-18 15:26:14 +00001195 if (isArmElf(Obj) && std::get<2>(Symbols[SI]) != ELF::STT_OBJECT &&
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001196 !DisassembleAll) {
Davide Italianof0706882015-10-01 21:57:09 +00001197 uint64_t Stride = 0;
1198
1199 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1200 DataMappingSymsAddr.end(), Index);
1201 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1202 // Switch to data.
1203 while (Index < End) {
1204 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1205 outs() << "\t";
1206 if (Index + 4 <= End) {
1207 Stride = 4;
1208 dumpBytes(Bytes.slice(Index, 4), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001209 outs() << "\t.word\t";
1210 uint32_t Data = 0;
1211 if (Obj->isLittleEndian()) {
1212 const auto Word =
1213 reinterpret_cast<const support::ulittle32_t *>(
1214 Bytes.data() + Index);
1215 Data = *Word;
1216 } else {
1217 const auto Word = reinterpret_cast<const support::ubig32_t *>(
1218 Bytes.data() + Index);
1219 Data = *Word;
1220 }
1221 outs() << "0x" << format("%08" PRIx32, Data);
Davide Italianof0706882015-10-01 21:57:09 +00001222 } else if (Index + 2 <= End) {
1223 Stride = 2;
1224 dumpBytes(Bytes.slice(Index, 2), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001225 outs() << "\t\t.short\t";
1226 uint16_t Data = 0;
1227 if (Obj->isLittleEndian()) {
1228 const auto Short =
1229 reinterpret_cast<const support::ulittle16_t *>(
1230 Bytes.data() + Index);
1231 Data = *Short;
1232 } else {
1233 const auto Short =
1234 reinterpret_cast<const support::ubig16_t *>(Bytes.data() +
1235 Index);
1236 Data = *Short;
1237 }
1238 outs() << "0x" << format("%04" PRIx16, Data);
Davide Italianof0706882015-10-01 21:57:09 +00001239 } else {
1240 Stride = 1;
1241 dumpBytes(Bytes.slice(Index, 1), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001242 outs() << "\t\t.byte\t";
1243 outs() << "0x" << format("%02" PRIx8, Bytes.slice(Index, 1)[0]);
Davide Italianof0706882015-10-01 21:57:09 +00001244 }
1245 Index += Stride;
1246 outs() << "\n";
1247 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1248 TextMappingSymsAddr.end(), Index);
1249 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1250 break;
1251 }
1252 }
1253 }
1254
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001255 // If there is a data symbol inside an ELF text section and we are only
1256 // disassembling text (applicable all architectures),
1257 // we are in a situation where we must print the data and not
1258 // disassemble it.
Clement Courbetd1a3bd42019-01-18 15:26:14 +00001259 if (Obj->isELF() && std::get<2>(Symbols[SI]) == ELF::STT_OBJECT &&
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001260 !DisassembleAll && Section.isText()) {
1261 // print out data up to 8 bytes at a time in hex and ascii
1262 uint8_t AsciiData[9] = {'\0'};
1263 uint8_t Byte;
1264 int NumBytes = 0;
1265
1266 for (Index = Start; Index < End; Index += 1) {
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001267 if (((SectionAddr + Index) < StartAddress) ||
1268 ((SectionAddr + Index) > StopAddress))
1269 continue;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001270 if (NumBytes == 0) {
1271 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1272 outs() << "\t";
1273 }
1274 Byte = Bytes.slice(Index)[0];
1275 outs() << format(" %02x", Byte);
Michael Kruse6f1da6e2018-07-26 15:31:41 +00001276 AsciiData[NumBytes] = isPrint(Byte) ? Byte : '.';
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001277
1278 uint8_t IndentOffset = 0;
1279 NumBytes++;
1280 if (Index == End - 1 || NumBytes > 8) {
1281 // Indent the space for less than 8 bytes data.
1282 // 2 spaces for byte and one for space between bytes
1283 IndentOffset = 3 * (8 - NumBytes);
Sid Manning5d9c8ad2019-02-01 19:11:47 +00001284 for (int Excess = NumBytes; Excess < 8; Excess++)
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001285 AsciiData[Excess] = '\0';
1286 NumBytes = 8;
1287 }
1288 if (NumBytes == 8) {
1289 AsciiData[8] = '\0';
1290 outs() << std::string(IndentOffset, ' ') << " ";
1291 outs() << reinterpret_cast<char *>(AsciiData);
1292 outs() << '\n';
1293 NumBytes = 0;
1294 }
1295 }
1296 }
Davide Italianof0706882015-10-01 21:57:09 +00001297 if (Index >= End)
1298 break;
1299
George Rimarc5f29202019-02-19 12:38:36 +00001300 // When -z or --disassemble-zeroes are given we always dissasemble them.
1301 // Otherwise we might want to skip zero bytes we see.
1302 if (!DisassembleZeroes) {
1303 uint64_t MaxOffset = End - Index;
1304 // For -reloc: print zero blocks patched by relocations, so that
1305 // relocations can be shown in the dump.
1306 if (RelCur != RelEnd)
1307 MaxOffset = RelCur->getOffset() - Index;
1308
1309 if (size_t N =
1310 countSkippableZeroBytes(Bytes.slice(Index, MaxOffset))) {
1311 outs() << "\t\t..." << '\n';
1312 Index += N;
1313 if (Index >= End)
1314 break;
1315 }
George Rimar70d197d2019-01-10 14:55:26 +00001316 }
1317
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001318 // Disassemble a real instruction or a data when disassemble all is
1319 // provided
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001320 bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1321 SectionAddr + Index, DebugOut,
1322 CommentStream);
1323 if (Size == 0)
1324 Size = 1;
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001325
George Rimar4c3b2972019-01-28 10:44:01 +00001326 PIP.printInst(
1327 *IP, Disassembled ? &Inst : nullptr, Bytes.slice(Index, Size),
1328 SectionAddr + Index + VMAAdjustment, outs(), "", *STI, &SP, &Rels);
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001329 outs() << CommentStream.str();
1330 Comments.clear();
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001331
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001332 // Try to resolve the target of a call, tail call, etc. to a specific
1333 // symbol.
1334 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1335 MIA->isConditionalBranch(Inst))) {
1336 uint64_t Target;
1337 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1338 // In a relocatable object, the target's section must reside in
1339 // the same section as the call instruction or it is accessed
1340 // through a relocation.
1341 //
1342 // In a non-relocatable object, the target may be in any section.
1343 //
1344 // N.B. We don't walk the relocations in the relocatable case yet.
1345 auto *TargetSectionSymbols = &Symbols;
1346 if (!Obj->isRelocatableObject()) {
1347 auto SectionAddress = std::upper_bound(
1348 SectionAddresses.begin(), SectionAddresses.end(), Target,
1349 [](uint64_t LHS,
1350 const std::pair<uint64_t, SectionRef> &RHS) {
1351 return LHS < RHS.first;
1352 });
1353 if (SectionAddress != SectionAddresses.begin()) {
1354 --SectionAddress;
1355 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1356 } else {
Sterling Augustinebc78b622018-06-28 18:57:13 +00001357 TargetSectionSymbols = &AbsoluteSymbols;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001358 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001359 }
David Majnemer2603a8fa2015-07-09 18:11:40 +00001360
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001361 // Find the first symbol in the section whose offset is less than
Sterling Augustinebc78b622018-06-28 18:57:13 +00001362 // or equal to the target. If there isn't a section that contains
1363 // the target, find the nearest preceding absolute symbol.
1364 auto TargetSym = std::upper_bound(
1365 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
Clement Courbetd1a3bd42019-01-18 15:26:14 +00001366 Target, [](uint64_t LHS,
1367 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1368 return LHS < std::get<0>(RHS);
Sterling Augustinebc78b622018-06-28 18:57:13 +00001369 });
1370 if (TargetSym == TargetSectionSymbols->begin()) {
1371 TargetSectionSymbols = &AbsoluteSymbols;
1372 TargetSym = std::upper_bound(
Clement Courbetd1a3bd42019-01-18 15:26:14 +00001373 AbsoluteSymbols.begin(), AbsoluteSymbols.end(),
1374 Target, [](uint64_t LHS,
1375 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1376 return LHS < std::get<0>(RHS);
1377 });
Sterling Augustinebc78b622018-06-28 18:57:13 +00001378 }
1379 if (TargetSym != TargetSectionSymbols->begin()) {
1380 --TargetSym;
Clement Courbetd1a3bd42019-01-18 15:26:14 +00001381 uint64_t TargetAddress = std::get<0>(*TargetSym);
1382 StringRef TargetName = std::get<1>(*TargetSym);
1383 outs() << " <" << TargetName;
1384 uint64_t Disp = Target - TargetAddress;
Sterling Augustinebc78b622018-06-28 18:57:13 +00001385 if (Disp)
1386 outs() << "+0x" << Twine::utohexstr(Disp);
1387 outs() << '>';
David Majnemer81afca62015-07-07 22:06:59 +00001388 }
1389 }
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001390 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001391 outs() << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001392
Sid Manningd9f28732018-05-14 19:46:08 +00001393 // Hexagon does this in pretty printer
George Rimarfd383e72019-01-23 10:52:38 +00001394 if (Obj->getArch() != Triple::hexagon) {
Sid Manningd9f28732018-05-14 19:46:08 +00001395 // Print relocation for instruction.
George Rimar73a27232019-01-15 09:19:18 +00001396 while (RelCur != RelEnd) {
George Rimar617adef2019-01-23 13:39:12 +00001397 uint64_t Offset = RelCur->getOffset();
Sid Manningd9f28732018-05-14 19:46:08 +00001398 // If this relocation is hidden, skip it.
George Rimar617adef2019-01-23 13:39:12 +00001399 if (getHidden(*RelCur) || ((SectionAddr + Offset) < StartAddress)) {
George Rimar73a27232019-01-15 09:19:18 +00001400 ++RelCur;
Sid Manningd9f28732018-05-14 19:46:08 +00001401 continue;
1402 }
1403
George Rimar740974d2019-01-28 10:48:54 +00001404 // Stop when RelCur's offset is past the current instruction.
George Rimar617adef2019-01-23 13:39:12 +00001405 if (Offset >= Index + Size)
George Rimar73a27232019-01-15 09:19:18 +00001406 break;
George Rimar617adef2019-01-23 13:39:12 +00001407
George Rimar4c3b2972019-01-28 10:44:01 +00001408 // When --adjust-vma is used, update the address printed.
1409 if (RelCur->getSymbol() != Obj->symbol_end()) {
1410 Expected<section_iterator> SymSI =
1411 RelCur->getSymbol()->getSection();
1412 if (SymSI && *SymSI != Obj->section_end() &&
1413 (shouldAdjustVA(**SymSI)))
1414 Offset += AdjustVMA;
1415 }
1416
George Rimar617adef2019-01-23 13:39:12 +00001417 printRelocation(*RelCur, SectionAddr + Offset,
1418 Obj->getBytesInAddress());
George Rimar73a27232019-01-15 09:19:18 +00001419 ++RelCur;
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001420 }
George Rimarfd383e72019-01-23 10:52:38 +00001421 }
Benjamin Kramer87ee76c2011-07-20 19:37:35 +00001422 }
Michael J. Spencer2670c252011-01-20 06:39:06 +00001423 }
1424 }
1425}
1426
George Rimarbcbe98b2019-01-23 10:33:26 +00001427static void disassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
1428 if (StartAddress > StopAddress)
1429 error("Start address should be less than stop address");
1430
1431 const Target *TheTarget = getTarget(Obj);
1432
1433 // Package up features to be passed to target/subtarget
1434 SubtargetFeatures Features = Obj->getFeatures();
1435 if (!MAttrs.empty())
1436 for (unsigned I = 0; I != MAttrs.size(); ++I)
1437 Features.AddFeature(MAttrs[I]);
1438
1439 std::unique_ptr<const MCRegisterInfo> MRI(
1440 TheTarget->createMCRegInfo(TripleName));
1441 if (!MRI)
1442 report_error(Obj->getFileName(),
1443 "no register info for target " + TripleName);
1444
1445 // Set up disassembler.
1446 std::unique_ptr<const MCAsmInfo> AsmInfo(
1447 TheTarget->createMCAsmInfo(*MRI, TripleName));
1448 if (!AsmInfo)
1449 report_error(Obj->getFileName(),
1450 "no assembly info for target " + TripleName);
1451 std::unique_ptr<const MCSubtargetInfo> STI(
1452 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
1453 if (!STI)
1454 report_error(Obj->getFileName(),
1455 "no subtarget info for target " + TripleName);
1456 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
1457 if (!MII)
1458 report_error(Obj->getFileName(),
1459 "no instruction info for target " + TripleName);
1460 MCObjectFileInfo MOFI;
1461 MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI);
1462 // FIXME: for now initialize MCObjectFileInfo with default values
1463 MOFI.InitMCObjectFileInfo(Triple(TripleName), false, Ctx);
1464
1465 std::unique_ptr<MCDisassembler> DisAsm(
1466 TheTarget->createMCDisassembler(*STI, Ctx));
1467 if (!DisAsm)
1468 report_error(Obj->getFileName(),
1469 "no disassembler for target " + TripleName);
1470
1471 std::unique_ptr<const MCInstrAnalysis> MIA(
1472 TheTarget->createMCInstrAnalysis(MII.get()));
1473
1474 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
1475 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1476 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
1477 if (!IP)
1478 report_error(Obj->getFileName(),
1479 "no instruction printer for target " + TripleName);
1480 IP->setPrintImmHex(PrintImmHex);
1481
1482 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
1483 SourcePrinter SP(Obj, TheTarget->getName());
1484
Igor Kudrin2d3faad2019-02-26 12:15:14 +00001485 for (StringRef Opt : DisassemblerOptions)
1486 if (!IP->applyTargetSpecificCLOption(Opt))
1487 error("Unrecognized disassembler option: " + Opt);
1488
George Rimarbcbe98b2019-01-23 10:33:26 +00001489 disassembleObject(TheTarget, Obj, Ctx, DisAsm.get(), MIA.get(), IP.get(),
1490 STI.get(), PIP, SP, InlineRelocs);
1491}
1492
George Rimar73a27232019-01-15 09:19:18 +00001493void llvm::printRelocations(const ObjectFile *Obj) {
Greg Fitzgerald18432272014-03-20 22:55:15 +00001494 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1495 "%08" PRIx64;
Rafael Espindola9219fe72016-03-21 20:59:15 +00001496 // Regular objdump doesn't print relocations in non-relocatable object
1497 // files.
1498 if (!Obj->isRelocatableObject())
1499 return;
Rafael Espindolac66d7612014-08-17 19:09:37 +00001500
Colin LeMahieu77804be2015-07-29 15:45:39 +00001501 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001502 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001503 continue;
George Rimar73a27232019-01-15 09:19:18 +00001504 StringRef SecName;
1505 error(Section.getName(SecName));
1506 outs() << "RELOCATION RECORDS FOR [" << SecName << "]:\n";
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001507 for (const RelocationRef &Reloc : Section.relocations()) {
George Rimar73a27232019-01-15 09:19:18 +00001508 uint64_t Address = Reloc.getOffset();
1509 SmallString<32> RelocName;
1510 SmallString<32> ValueStr;
1511 if (Address < StartAddress || Address > StopAddress || getHidden(Reloc))
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001512 continue;
George Rimar73a27232019-01-15 09:19:18 +00001513 Reloc.getTypeName(RelocName);
1514 error(getRelocationValueString(Reloc, ValueStr));
1515 outs() << format(Fmt.data(), Address) << " " << RelocName << " "
1516 << ValueStr << "\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001517 }
1518 outs() << "\n";
1519 }
1520}
1521
George Rimar73a27232019-01-15 09:19:18 +00001522void llvm::printDynamicRelocations(const ObjectFile *Obj) {
Paul Semelcb0f0432018-06-07 13:30:55 +00001523 // For the moment, this option is for ELF only
1524 if (!Obj->isELF())
1525 return;
1526
1527 const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj);
Paul Semelcb0f0432018-06-07 13:30:55 +00001528 if (!Elf || Elf->getEType() != ELF::ET_DYN) {
1529 error("not a dynamic object");
1530 return;
1531 }
1532
Paul Semelcb0f0432018-06-07 13:30:55 +00001533 std::vector<SectionRef> DynRelSec = Obj->dynamic_relocation_sections();
1534 if (DynRelSec.empty())
1535 return;
1536
1537 outs() << "DYNAMIC RELOCATION RECORDS\n";
George Rimar73a27232019-01-15 09:19:18 +00001538 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
Paul Semelcb0f0432018-06-07 13:30:55 +00001539 for (const SectionRef &Section : DynRelSec) {
1540 if (Section.relocation_begin() == Section.relocation_end())
1541 continue;
1542 for (const RelocationRef &Reloc : Section.relocations()) {
George Rimar73a27232019-01-15 09:19:18 +00001543 uint64_t Address = Reloc.getOffset();
1544 SmallString<32> RelocName;
1545 SmallString<32> ValueStr;
1546 Reloc.getTypeName(RelocName);
1547 error(getRelocationValueString(Reloc, ValueStr));
1548 outs() << format(Fmt.data(), Address) << " " << RelocName << " "
1549 << ValueStr << "\n";
Paul Semelcb0f0432018-06-07 13:30:55 +00001550 }
1551 }
1552}
1553
George Rimar87fa2e62019-01-28 14:11:35 +00001554// Returns true if we need to show LMA column when dumping section headers. We
1555// show it only when the platform is ELF and either we have at least one section
1556// whose VMA and LMA are different and/or when --show-lma flag is used.
1557static bool shouldDisplayLMA(const ObjectFile *Obj) {
1558 if (!Obj->isELF())
1559 return false;
1560 for (const SectionRef &S : ToolSectionFilter(*Obj))
1561 if (S.getAddress() != getELFSectionLMA(S))
1562 return true;
1563 return ShowLMA;
1564}
1565
George Rimar73a27232019-01-15 09:19:18 +00001566void llvm::printSectionHeaders(const ObjectFile *Obj) {
George Rimar87fa2e62019-01-28 14:11:35 +00001567 bool HasLMAColumn = shouldDisplayLMA(Obj);
1568 if (HasLMAColumn)
1569 outs() << "Sections:\n"
1570 "Idx Name Size VMA LMA "
1571 "Type\n";
1572 else
1573 outs() << "Sections:\n"
1574 "Idx Name Size VMA Type\n";
1575
Colin LeMahieu77804be2015-07-29 15:45:39 +00001576 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001577 StringRef Name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001578 error(Section.getName(Name));
George Rimar87fa2e62019-01-28 14:11:35 +00001579 uint64_t VMA = Section.getAddress();
George Rimar4463ebe2019-01-28 16:36:12 +00001580 if (shouldAdjustVA(Section))
1581 VMA += AdjustVMA;
1582
Rafael Espindola80291272014-10-08 15:28:58 +00001583 uint64_t Size = Section.getSize();
1584 bool Text = Section.isText();
1585 bool Data = Section.isData();
1586 bool BSS = Section.isBSS();
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001587 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +00001588 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
George Rimar87fa2e62019-01-28 14:11:35 +00001589
1590 if (HasLMAColumn)
1591 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %016" PRIx64
1592 " %s\n",
1593 (unsigned)Section.getIndex(), Name.str().c_str(), Size,
1594 VMA, getELFSectionLMA(Section), Type.c_str());
1595 else
1596 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n",
1597 (unsigned)Section.getIndex(), Name.str().c_str(), Size,
1598 VMA, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001599 }
Xing GUO785edea2018-11-17 08:12:48 +00001600 outs() << "\n";
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001601}
1602
George Rimar73a27232019-01-15 09:19:18 +00001603void llvm::printSectionContents(const ObjectFile *Obj) {
Rafael Espindola4453e42942014-06-13 03:07:50 +00001604 std::error_code EC;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001605 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001606 StringRef Name;
1607 StringRef Contents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001608 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001609 uint64_t BaseAddr = Section.getAddress();
David Majnemer185b5b12014-11-11 09:58:25 +00001610 uint64_t Size = Section.getSize();
1611 if (!Size)
1612 continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001613
1614 outs() << "Contents of section " << Name << ":\n";
David Majnemer185b5b12014-11-11 09:58:25 +00001615 if (Section.isBSS()) {
Alexey Samsonov209095c2013-04-16 10:53:11 +00001616 outs() << format("<skipping contents of bss section at [%04" PRIx64
David Majnemer8f6b04c2014-07-14 16:20:14 +00001617 ", %04" PRIx64 ")>\n",
1618 BaseAddr, BaseAddr + Size);
Alexey Samsonov209095c2013-04-16 10:53:11 +00001619 continue;
1620 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001621
Davide Italianoccd53fe2015-08-05 07:18:31 +00001622 error(Section.getContents(Contents));
David Majnemer8f6b04c2014-07-14 16:20:14 +00001623
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001624 // Dump out the content as hex and printable ascii characters.
George Rimar73a27232019-01-15 09:19:18 +00001625 for (std::size_t Addr = 0, End = Contents.size(); Addr < End; Addr += 16) {
1626 outs() << format(" %04" PRIx64 " ", BaseAddr + Addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001627 // Dump line of hex.
George Rimar73a27232019-01-15 09:19:18 +00001628 for (std::size_t I = 0; I < 16; ++I) {
1629 if (I != 0 && I % 4 == 0)
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001630 outs() << ' ';
George Rimar73a27232019-01-15 09:19:18 +00001631 if (Addr + I < End)
1632 outs() << hexdigit((Contents[Addr + I] >> 4) & 0xF, true)
1633 << hexdigit(Contents[Addr + I] & 0xF, true);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001634 else
1635 outs() << " ";
1636 }
1637 // Print ascii.
1638 outs() << " ";
George Rimar73a27232019-01-15 09:19:18 +00001639 for (std::size_t I = 0; I < 16 && Addr + I < End; ++I) {
1640 if (isPrint(static_cast<unsigned char>(Contents[Addr + I]) & 0xFF))
1641 outs() << Contents[Addr + I];
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001642 else
1643 outs() << ".";
1644 }
1645 outs() << "\n";
1646 }
1647 }
1648}
1649
George Rimar73a27232019-01-15 09:19:18 +00001650void llvm::printSymbolTable(const ObjectFile *O, StringRef ArchiveName,
Kevin Enderby9acb1092016-05-31 20:35:34 +00001651 StringRef ArchitectureName) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001652 outs() << "SYMBOL TABLE:\n";
1653
George Rimar73a27232019-01-15 09:19:18 +00001654 if (const COFFObjectFile *Coff = dyn_cast<const COFFObjectFile>(O)) {
1655 printCOFFSymbolTable(Coff);
Rui Ueyama4e39f712014-03-18 18:58:51 +00001656 return;
1657 }
George Rimar8e0a70b2019-01-10 16:24:10 +00001658
George Rimar73a27232019-01-15 09:19:18 +00001659 for (auto I = O->symbol_begin(), E = O->symbol_end(); I != E; ++I) {
George Rimar8e0a70b2019-01-10 16:24:10 +00001660 // Skip printing the special zero symbol when dumping an ELF file.
1661 // This makes the output consistent with the GNU objdump.
George Rimar73a27232019-01-15 09:19:18 +00001662 if (I == O->symbol_begin() && isa<ELFObjectFileBase>(O))
George Rimar8e0a70b2019-01-10 16:24:10 +00001663 continue;
1664
1665 const SymbolRef &Symbol = *I;
Kevin Enderby931cb652016-06-24 18:24:42 +00001666 Expected<uint64_t> AddressOrError = Symbol.getAddress();
1667 if (!AddressOrError)
George Rimar73a27232019-01-15 09:19:18 +00001668 report_error(ArchiveName, O->getFileName(), AddressOrError.takeError(),
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001669 ArchitectureName);
Rafael Espindolaed067c42015-07-03 18:19:00 +00001670 uint64_t Address = *AddressOrError;
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001671 if ((Address < StartAddress) || (Address > StopAddress))
1672 continue;
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001673 Expected<SymbolRef::Type> TypeOrError = Symbol.getType();
1674 if (!TypeOrError)
George Rimar73a27232019-01-15 09:19:18 +00001675 report_error(ArchiveName, O->getFileName(), TypeOrError.takeError(),
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001676 ArchitectureName);
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00001677 SymbolRef::Type Type = *TypeOrError;
Rui Ueyama4e39f712014-03-18 18:58:51 +00001678 uint32_t Flags = Symbol.getFlags();
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001679 Expected<section_iterator> SectionOrErr = Symbol.getSection();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001680 if (!SectionOrErr)
George Rimar73a27232019-01-15 09:19:18 +00001681 report_error(ArchiveName, O->getFileName(), SectionOrErr.takeError(),
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001682 ArchitectureName);
Rafael Espindola8bab8892015-08-07 23:27:14 +00001683 section_iterator Section = *SectionOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001684 StringRef Name;
George Rimar73a27232019-01-15 09:19:18 +00001685 if (Type == SymbolRef::ST_Debug && Section != O->section_end()) {
Rafael Espindola75d5b542015-06-03 05:14:22 +00001686 Section->getName(Name);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001687 } else {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001688 Expected<StringRef> NameOrErr = Symbol.getName();
1689 if (!NameOrErr)
George Rimar73a27232019-01-15 09:19:18 +00001690 report_error(ArchiveName, O->getFileName(), NameOrErr.takeError(),
Kevin Enderby9acb1092016-05-31 20:35:34 +00001691 ArchitectureName);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001692 Name = *NameOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001693 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001694
Rui Ueyama4e39f712014-03-18 18:58:51 +00001695 bool Global = Flags & SymbolRef::SF_Global;
1696 bool Weak = Flags & SymbolRef::SF_Weak;
1697 bool Absolute = Flags & SymbolRef::SF_Absolute;
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001698 bool Common = Flags & SymbolRef::SF_Common;
Davide Italianocd2514d2015-04-30 23:08:53 +00001699 bool Hidden = Flags & SymbolRef::SF_Hidden;
David Meyer1df4b842012-02-28 23:47:53 +00001700
Rui Ueyama4e39f712014-03-18 18:58:51 +00001701 char GlobLoc = ' ';
1702 if (Type != SymbolRef::ST_Unknown)
1703 GlobLoc = Global ? 'g' : 'l';
1704 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1705 ? 'd' : ' ';
1706 char FileFunc = ' ';
1707 if (Type == SymbolRef::ST_File)
1708 FileFunc = 'f';
1709 else if (Type == SymbolRef::ST_Function)
1710 FileFunc = 'F';
Kristina Brooks0674f9d2018-11-11 17:47:13 +00001711 else if (Type == SymbolRef::ST_Data)
1712 FileFunc = 'O';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001713
George Rimar73a27232019-01-15 09:19:18 +00001714 const char *Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 :
Rui Ueyama4e39f712014-03-18 18:58:51 +00001715 "%08" PRIx64;
Michael J. Spencerd857c1c2013-01-10 22:40:50 +00001716
Rui Ueyama4e39f712014-03-18 18:58:51 +00001717 outs() << format(Fmt, Address) << " "
1718 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1719 << (Weak ? 'w' : ' ') // Weak?
1720 << ' ' // Constructor. Not supported yet.
1721 << ' ' // Warning. Not supported yet.
1722 << ' ' // Indirect reference to another symbol.
1723 << Debug // Debugging (d) or dynamic (D) symbol.
1724 << FileFunc // Name of function (F), file (f) or object (O).
1725 << ' ';
1726 if (Absolute) {
1727 outs() << "*ABS*";
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001728 } else if (Common) {
1729 outs() << "*COM*";
George Rimar73a27232019-01-15 09:19:18 +00001730 } else if (Section == O->section_end()) {
Rui Ueyama4e39f712014-03-18 18:58:51 +00001731 outs() << "*UND*";
1732 } else {
1733 if (const MachOObjectFile *MachO =
George Rimar73a27232019-01-15 09:19:18 +00001734 dyn_cast<const MachOObjectFile>(O)) {
Rui Ueyama4e39f712014-03-18 18:58:51 +00001735 DataRefImpl DR = Section->getRawDataRefImpl();
1736 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1737 outs() << SegmentName << ",";
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001738 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00001739 StringRef SectionName;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001740 error(Section->getName(SectionName));
Rui Ueyama4e39f712014-03-18 18:58:51 +00001741 outs() << SectionName;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001742 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001743
1744 outs() << '\t';
George Rimar73a27232019-01-15 09:19:18 +00001745 if (Common || isa<ELFObjectFileBase>(O)) {
Rafael Espindoladbb6bd32015-06-25 22:10:04 +00001746 uint64_t Val =
1747 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001748 outs() << format("\t %08" PRIx64 " ", Val);
1749 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001750
George Rimar73a27232019-01-15 09:19:18 +00001751 if (Hidden)
Davide Italianocd2514d2015-04-30 23:08:53 +00001752 outs() << ".hidden ";
George Rimar6622d412018-12-19 10:21:45 +00001753
1754 if (Demangle)
1755 outs() << demangle(Name) << '\n';
1756 else
1757 outs() << Name << '\n';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001758 }
1759}
1760
George Rimar73a27232019-01-15 09:19:18 +00001761static void printUnwindInfo(const ObjectFile *O) {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001762 outs() << "Unwind info:\n\n";
1763
George Rimar73a27232019-01-15 09:19:18 +00001764 if (const COFFObjectFile *Coff = dyn_cast<COFFObjectFile>(O))
1765 printCOFFUnwindInfo(Coff);
1766 else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O))
Tim Northover4bd286a2014-08-01 13:07:19 +00001767 printMachOUnwindInfo(MachO);
George Rimar73a27232019-01-15 09:19:18 +00001768 else
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001769 // TODO: Extract DWARF dump tool to objdump.
Jonas Devliegheree787efd2018-11-11 22:12:04 +00001770 WithColor::error(errs(), ToolName)
1771 << "This operation is only currently supported "
1772 "for COFF and MachO object files.\n";
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001773}
1774
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001775void llvm::printExportsTrie(const ObjectFile *o) {
Nick Kledzikd04bc352014-08-30 00:20:14 +00001776 outs() << "Exports trie:\n";
1777 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1778 printMachOExportsTrie(MachO);
George Rimar73a27232019-01-15 09:19:18 +00001779 else
Jonas Devliegheree787efd2018-11-11 22:12:04 +00001780 WithColor::error(errs(), ToolName)
1781 << "This operation is only currently supported "
1782 "for Mach-O executable files.\n";
Nick Kledzikd04bc352014-08-30 00:20:14 +00001783}
1784
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001785void llvm::printRebaseTable(ObjectFile *o) {
Nick Kledzikac431442014-09-12 21:34:15 +00001786 outs() << "Rebase table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001787 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzikac431442014-09-12 21:34:15 +00001788 printMachORebaseTable(MachO);
George Rimar73a27232019-01-15 09:19:18 +00001789 else
Jonas Devliegheree787efd2018-11-11 22:12:04 +00001790 WithColor::error(errs(), ToolName)
1791 << "This operation is only currently supported "
1792 "for Mach-O executable files.\n";
Nick Kledzikac431442014-09-12 21:34:15 +00001793}
1794
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001795void llvm::printBindTable(ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001796 outs() << "Bind table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001797 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzik56ebef42014-09-16 01:41:51 +00001798 printMachOBindTable(MachO);
George Rimar73a27232019-01-15 09:19:18 +00001799 else
Jonas Devliegheree787efd2018-11-11 22:12:04 +00001800 WithColor::error(errs(), ToolName)
1801 << "This operation is only currently supported "
1802 "for Mach-O executable files.\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00001803}
1804
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001805void llvm::printLazyBindTable(ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001806 outs() << "Lazy bind table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001807 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzik56ebef42014-09-16 01:41:51 +00001808 printMachOLazyBindTable(MachO);
George Rimar73a27232019-01-15 09:19:18 +00001809 else
Jonas Devliegheree787efd2018-11-11 22:12:04 +00001810 WithColor::error(errs(), ToolName)
1811 << "This operation is only currently supported "
1812 "for Mach-O executable files.\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00001813}
1814
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001815void llvm::printWeakBindTable(ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001816 outs() << "Weak bind table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001817 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzik56ebef42014-09-16 01:41:51 +00001818 printMachOWeakBindTable(MachO);
George Rimar73a27232019-01-15 09:19:18 +00001819 else
Jonas Devliegheree787efd2018-11-11 22:12:04 +00001820 WithColor::error(errs(), ToolName)
1821 << "This operation is only currently supported "
1822 "for Mach-O executable files.\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00001823}
Nick Kledzikac431442014-09-12 21:34:15 +00001824
Adrian Prantl437105a2015-07-08 02:04:15 +00001825/// Dump the raw contents of the __clangast section so the output can be piped
1826/// into llvm-bcanalyzer.
1827void llvm::printRawClangAST(const ObjectFile *Obj) {
1828 if (outs().is_displayed()) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00001829 WithColor::error(errs(), ToolName)
1830 << "The -raw-clang-ast option will dump the raw binary contents of "
1831 "the clang ast section.\n"
1832 "Please redirect the output to a file or another program such as "
1833 "llvm-bcanalyzer.\n";
Adrian Prantl437105a2015-07-08 02:04:15 +00001834 return;
1835 }
1836
1837 StringRef ClangASTSectionName("__clangast");
1838 if (isa<COFFObjectFile>(Obj)) {
1839 ClangASTSectionName = "clangast";
1840 }
1841
1842 Optional<object::SectionRef> ClangASTSection;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001843 for (auto Sec : ToolSectionFilter(*Obj)) {
Adrian Prantl437105a2015-07-08 02:04:15 +00001844 StringRef Name;
1845 Sec.getName(Name);
1846 if (Name == ClangASTSectionName) {
1847 ClangASTSection = Sec;
1848 break;
1849 }
1850 }
1851 if (!ClangASTSection)
1852 return;
1853
1854 StringRef ClangASTContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001855 error(ClangASTSection.getValue().getContents(ClangASTContents));
Adrian Prantl437105a2015-07-08 02:04:15 +00001856 outs().write(ClangASTContents.data(), ClangASTContents.size());
1857}
1858
Sanjoy Das6f567a42015-06-22 18:03:02 +00001859static void printFaultMaps(const ObjectFile *Obj) {
George Rimar73a27232019-01-15 09:19:18 +00001860 StringRef FaultMapSectionName;
Sanjoy Das6f567a42015-06-22 18:03:02 +00001861
1862 if (isa<ELFObjectFileBase>(Obj)) {
1863 FaultMapSectionName = ".llvm_faultmaps";
1864 } else if (isa<MachOObjectFile>(Obj)) {
1865 FaultMapSectionName = "__llvm_faultmaps";
1866 } else {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00001867 WithColor::error(errs(), ToolName)
1868 << "This operation is only currently supported "
1869 "for ELF and Mach-O executable files.\n";
Sanjoy Das6f567a42015-06-22 18:03:02 +00001870 return;
1871 }
1872
1873 Optional<object::SectionRef> FaultMapSection;
1874
Colin LeMahieu77804be2015-07-29 15:45:39 +00001875 for (auto Sec : ToolSectionFilter(*Obj)) {
Sanjoy Das6f567a42015-06-22 18:03:02 +00001876 StringRef Name;
1877 Sec.getName(Name);
1878 if (Name == FaultMapSectionName) {
1879 FaultMapSection = Sec;
1880 break;
1881 }
1882 }
1883
1884 outs() << "FaultMap table:\n";
1885
1886 if (!FaultMapSection.hasValue()) {
1887 outs() << "<not found>\n";
1888 return;
1889 }
1890
1891 StringRef FaultMapContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001892 error(FaultMapSection.getValue().getContents(FaultMapContents));
Sanjoy Das6f567a42015-06-22 18:03:02 +00001893
1894 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1895 FaultMapContents.bytes_end());
1896
1897 outs() << FMP;
1898}
1899
George Rimar73a27232019-01-15 09:19:18 +00001900static void printPrivateFileHeaders(const ObjectFile *O, bool OnlyFirst) {
1901 if (O->isELF()) {
1902 printELFFileHeader(O);
Xing GUO56d651d2019-02-25 13:13:19 +00001903 printELFDynamicSection(O);
1904 printELFSymbolVersionInfo(O);
1905 return;
Paul Semel0913dcd2018-07-25 11:09:20 +00001906 }
George Rimar73a27232019-01-15 09:19:18 +00001907 if (O->isCOFF())
1908 return printCOFFFileHeader(O);
1909 if (O->isWasm())
1910 return printWasmFileHeader(O);
1911 if (O->isMachO()) {
1912 printMachOFileHeader(O);
1913 if (!OnlyFirst)
1914 printMachOLoadCommands(O);
Davide Italiano1bdaa202016-09-18 04:39:15 +00001915 return;
1916 }
George Rimar73a27232019-01-15 09:19:18 +00001917 report_error(O->getFileName(), "Invalid/Unsupported object file format");
Rui Ueyamac2bed422013-09-27 21:04:00 +00001918}
1919
George Rimar73a27232019-01-15 09:19:18 +00001920static void printFileHeaders(const ObjectFile *O) {
1921 if (!O->isELF() && !O->isCOFF())
1922 report_error(O->getFileName(), "Invalid/Unsupported object file format");
Paul Semeld2af4d62018-07-04 15:25:03 +00001923
George Rimar73a27232019-01-15 09:19:18 +00001924 Triple::ArchType AT = O->getArch();
Paul Semeld2af4d62018-07-04 15:25:03 +00001925 outs() << "architecture: " << Triple::getArchTypeName(AT) << "\n";
George Rimar73a27232019-01-15 09:19:18 +00001926 Expected<uint64_t> StartAddrOrErr = O->getStartAddress();
Paul Semeld2af4d62018-07-04 15:25:03 +00001927 if (!StartAddrOrErr)
George Rimar73a27232019-01-15 09:19:18 +00001928 report_error(O->getFileName(), StartAddrOrErr.takeError());
Petar Jovanovic8d947ba2018-10-19 22:16:49 +00001929
George Rimar73a27232019-01-15 09:19:18 +00001930 StringRef Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
Petar Jovanovic8d947ba2018-10-19 22:16:49 +00001931 uint64_t Address = StartAddrOrErr.get();
Paul Semeld2af4d62018-07-04 15:25:03 +00001932 outs() << "start address: "
George Rimar9b6fe7e2019-01-12 12:17:24 +00001933 << "0x" << format(Fmt.data(), Address) << "\n\n";
Paul Semeld2af4d62018-07-04 15:25:03 +00001934}
1935
Paul Semel0dc92f62018-07-05 14:43:29 +00001936static void printArchiveChild(StringRef Filename, const Archive::Child &C) {
1937 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
1938 if (!ModeOrErr) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00001939 WithColor::error(errs(), ToolName) << "ill-formed archive entry.\n";
Paul Semel0dc92f62018-07-05 14:43:29 +00001940 consumeError(ModeOrErr.takeError());
1941 return;
1942 }
1943 sys::fs::perms Mode = ModeOrErr.get();
1944 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1945 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1946 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1947 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1948 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1949 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1950 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1951 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1952 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
1953
1954 outs() << " ";
1955
1956 Expected<unsigned> UIDOrErr = C.getUID();
1957 if (!UIDOrErr)
1958 report_error(Filename, UIDOrErr.takeError());
1959 unsigned UID = UIDOrErr.get();
1960 outs() << format("%d/", UID);
1961
1962 Expected<unsigned> GIDOrErr = C.getGID();
1963 if (!GIDOrErr)
1964 report_error(Filename, GIDOrErr.takeError());
1965 unsigned GID = GIDOrErr.get();
1966 outs() << format("%-d ", GID);
1967
1968 Expected<uint64_t> Size = C.getRawSize();
1969 if (!Size)
1970 report_error(Filename, Size.takeError());
1971 outs() << format("%6" PRId64, Size.get()) << " ";
1972
1973 StringRef RawLastModified = C.getRawLastModified();
1974 unsigned Seconds;
1975 if (RawLastModified.getAsInteger(10, Seconds))
1976 outs() << "(date: \"" << RawLastModified
1977 << "\" contains non-decimal chars) ";
1978 else {
1979 // Since ctime(3) returns a 26 character string of the form:
1980 // "Sun Sep 16 01:03:52 1973\n\0"
1981 // just print 24 characters.
1982 time_t t = Seconds;
1983 outs() << format("%.24s ", ctime(&t));
1984 }
1985
1986 StringRef Name = "";
1987 Expected<StringRef> NameOrErr = C.getName();
1988 if (!NameOrErr) {
1989 consumeError(NameOrErr.takeError());
1990 Expected<StringRef> RawNameOrErr = C.getRawName();
1991 if (!RawNameOrErr)
1992 report_error(Filename, NameOrErr.takeError());
1993 Name = RawNameOrErr.get();
1994 } else {
1995 Name = NameOrErr.get();
1996 }
1997 outs() << Name << "\n";
1998}
1999
George Rimar73a27232019-01-15 09:19:18 +00002000static void dumpObject(ObjectFile *O, const Archive *A = nullptr,
2001 const Archive::Child *C = nullptr) {
Adrian Prantl437105a2015-07-08 02:04:15 +00002002 // Avoid other output when using a raw option.
2003 if (!RawClangAST) {
2004 outs() << '\n';
George Rimar73a27232019-01-15 09:19:18 +00002005 if (A)
2006 outs() << A->getFileName() << "(" << O->getFileName() << ")";
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002007 else
George Rimar73a27232019-01-15 09:19:18 +00002008 outs() << O->getFileName();
2009 outs() << ":\tfile format " << O->getFileFormatName() << "\n\n";
Adrian Prantl437105a2015-07-08 02:04:15 +00002010 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00002011
George Rimar73a27232019-01-15 09:19:18 +00002012 StringRef ArchiveName = A ? A->getFileName() : "";
George Rimar9b6fe7e2019-01-12 12:17:24 +00002013 if (FileHeaders)
George Rimar73a27232019-01-15 09:19:18 +00002014 printFileHeaders(O);
2015 if (ArchiveHeaders && !MachOOpt && C)
2016 printArchiveChild(ArchiveName, *C);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002017 if (Disassemble)
George Rimar73a27232019-01-15 09:19:18 +00002018 disassembleObject(O, Relocations);
Michael J. Spencer51862b32011-10-13 22:17:18 +00002019 if (Relocations && !Disassemble)
George Rimar73a27232019-01-15 09:19:18 +00002020 printRelocations(O);
Paul Semelcb0f0432018-06-07 13:30:55 +00002021 if (DynamicRelocations)
George Rimar73a27232019-01-15 09:19:18 +00002022 printDynamicRelocations(O);
Nick Lewyckyfcf84622011-10-10 21:21:34 +00002023 if (SectionHeaders)
George Rimar73a27232019-01-15 09:19:18 +00002024 printSectionHeaders(O);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00002025 if (SectionContents)
George Rimar73a27232019-01-15 09:19:18 +00002026 printSectionContents(O);
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002027 if (SymbolTable)
George Rimar73a27232019-01-15 09:19:18 +00002028 printSymbolTable(O, ArchiveName);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00002029 if (UnwindInfo)
George Rimar73a27232019-01-15 09:19:18 +00002030 printUnwindInfo(O);
Davide Italiano1bdaa202016-09-18 04:39:15 +00002031 if (PrivateHeaders || FirstPrivateHeader)
George Rimar73a27232019-01-15 09:19:18 +00002032 printPrivateFileHeaders(O, FirstPrivateHeader);
Nick Kledzikd04bc352014-08-30 00:20:14 +00002033 if (ExportsTrie)
George Rimar73a27232019-01-15 09:19:18 +00002034 printExportsTrie(O);
Nick Kledzikac431442014-09-12 21:34:15 +00002035 if (Rebase)
George Rimar73a27232019-01-15 09:19:18 +00002036 printRebaseTable(O);
Nick Kledzik56ebef42014-09-16 01:41:51 +00002037 if (Bind)
George Rimar73a27232019-01-15 09:19:18 +00002038 printBindTable(O);
Nick Kledzik56ebef42014-09-16 01:41:51 +00002039 if (LazyBind)
George Rimar73a27232019-01-15 09:19:18 +00002040 printLazyBindTable(O);
Nick Kledzik56ebef42014-09-16 01:41:51 +00002041 if (WeakBind)
George Rimar73a27232019-01-15 09:19:18 +00002042 printWeakBindTable(O);
Adrian Prantl437105a2015-07-08 02:04:15 +00002043 if (RawClangAST)
George Rimar73a27232019-01-15 09:19:18 +00002044 printRawClangAST(O);
Sanjoy Das6f567a42015-06-22 18:03:02 +00002045 if (PrintFaultMaps)
George Rimar73a27232019-01-15 09:19:18 +00002046 printFaultMaps(O);
Igor Laevsky03a670c2016-01-26 15:09:42 +00002047 if (DwarfDumpType != DIDT_Null) {
George Rimar73a27232019-01-15 09:19:18 +00002048 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*O);
Igor Laevsky03a670c2016-01-26 15:09:42 +00002049 // Dump the complete DWARF structure.
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00002050 DIDumpOptions DumpOpts;
2051 DumpOpts.DumpType = DwarfDumpType;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00002052 DICtx->dump(outs(), DumpOpts);
Igor Laevsky03a670c2016-01-26 15:09:42 +00002053 }
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002054}
2055
George Rimar73a27232019-01-15 09:19:18 +00002056static void dumpObject(const COFFImportFile *I, const Archive *A,
Paul Semel0dc92f62018-07-05 14:43:29 +00002057 const Archive::Child *C = nullptr) {
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00002058 StringRef ArchiveName = A ? A->getFileName() : "";
2059
2060 // Avoid other output when using a raw option.
2061 if (!RawClangAST)
2062 outs() << '\n'
2063 << ArchiveName << "(" << I->getFileName() << ")"
2064 << ":\tfile format COFF-import-file"
2065 << "\n\n";
2066
James Hendersonc1608c92018-10-29 14:17:08 +00002067 if (ArchiveHeaders && !MachOOpt && C)
2068 printArchiveChild(ArchiveName, *C);
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00002069 if (SymbolTable)
2070 printCOFFSymbolTable(I);
2071}
2072
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +00002073/// Dump each object file in \a a;
George Rimar73a27232019-01-15 09:19:18 +00002074static void dumpArchive(const Archive *A) {
Mehdi Amini41af4302016-11-11 04:28:40 +00002075 Error Err = Error::success();
George Rimar73a27232019-01-15 09:19:18 +00002076 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002077 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2078 if (!ChildOrErr) {
2079 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
George Rimar73a27232019-01-15 09:19:18 +00002080 report_error(A->getFileName(), C, std::move(E));
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002081 continue;
2082 }
George Rimar73a27232019-01-15 09:19:18 +00002083 if (ObjectFile *O = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
2084 dumpObject(O, A, &C);
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00002085 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
George Rimar73a27232019-01-15 09:19:18 +00002086 dumpObject(I, A, &C);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002087 else
George Rimar73a27232019-01-15 09:19:18 +00002088 report_error(A->getFileName(), object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002089 }
Lang Hamesfc209622016-07-14 02:24:01 +00002090 if (Err)
George Rimar73a27232019-01-15 09:19:18 +00002091 report_error(A->getFileName(), std::move(Err));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002092}
2093
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +00002094/// Open file and figure out how to dump it.
George Rimar73a27232019-01-15 09:19:18 +00002095static void dumpInput(StringRef file) {
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002096 // If we are using the Mach-O specific object file parser, then let it parse
2097 // the file and process the command line options. So the -arch flags can
2098 // be used to select specific slices, etc.
2099 if (MachOOpt) {
George Rimar73a27232019-01-15 09:19:18 +00002100 parseInputMachO(file);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002101 return;
2102 }
2103
2104 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00002105 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
2106 if (!BinaryOrErr)
Kevin Enderbyb34e3a12016-05-05 17:43:35 +00002107 report_error(file, BinaryOrErr.takeError());
Rafael Espindola48af1c22014-08-19 18:44:46 +00002108 Binary &Binary = *BinaryOrErr.get().getBinary();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002109
George Rimar73a27232019-01-15 09:19:18 +00002110 if (Archive *A = dyn_cast<Archive>(&Binary))
2111 dumpArchive(A);
2112 else if (ObjectFile *O = dyn_cast<ObjectFile>(&Binary))
2113 dumpObject(O);
Dave Lee3fb120f2018-08-03 00:06:38 +00002114 else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Binary))
George Rimar73a27232019-01-15 09:19:18 +00002115 parseInputMachO(UB);
Jim Grosbachaf9aec02012-08-07 17:53:14 +00002116 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00002117 report_error(file, object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002118}
2119
Michael J. Spencer2670c252011-01-20 06:39:06 +00002120int main(int argc, char **argv) {
Rui Ueyama197194b2018-04-13 18:26:06 +00002121 InitLLVM X(argc, argv);
Michael J. Spencer2670c252011-01-20 06:39:06 +00002122
2123 // Initialize targets and assembly printers/parsers.
2124 llvm::InitializeAllTargetInfos();
Evan Cheng8c886a42011-07-22 21:58:54 +00002125 llvm::InitializeAllTargetMCs();
Michael J. Spencer2670c252011-01-20 06:39:06 +00002126 llvm::InitializeAllDisassemblers();
2127
Pete Cooper28fb4fc2012-05-03 23:20:10 +00002128 // Register the target printer for --version.
2129 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
2130
Michael J. Spencer2670c252011-01-20 06:39:06 +00002131 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
Michael J. Spencer2670c252011-01-20 06:39:06 +00002132
2133 ToolName = argv[0];
2134
2135 // Defaults to a.out if no filenames specified.
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00002136 if (InputFilenames.empty())
Michael J. Spencer2670c252011-01-20 06:39:06 +00002137 InputFilenames.push_back("a.out");
2138
Fangrui Song8513cd42018-06-27 20:45:11 +00002139 if (AllHeaders)
George Rimar5e364332019-01-18 12:01:59 +00002140 ArchiveHeaders = FileHeaders = PrivateHeaders = Relocations =
2141 SectionHeaders = SymbolTable = true;
Fangrui Song8513cd42018-06-27 20:45:11 +00002142
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00002143 if (DisassembleAll || PrintSource || PrintLines)
Colin LeMahieuf34933e2015-07-23 20:58:49 +00002144 Disassemble = true;
Paul Semel007dedb2018-07-18 16:39:21 +00002145
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002146 if (!Disassemble
2147 && !Relocations
Paul Semelcb0f0432018-06-07 13:30:55 +00002148 && !DynamicRelocations
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002149 && !SectionHeaders
2150 && !SectionContents
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00002151 && !SymbolTable
Michael J. Spencer209565db2013-01-06 03:56:49 +00002152 && !UnwindInfo
Nick Kledzikd04bc352014-08-30 00:20:14 +00002153 && !PrivateHeaders
Paul Semeld2af4d62018-07-04 15:25:03 +00002154 && !FileHeaders
Kevin Enderby0ae163f2016-01-13 00:25:36 +00002155 && !FirstPrivateHeader
Nick Kledzikac431442014-09-12 21:34:15 +00002156 && !ExportsTrie
Nick Kledzik56ebef42014-09-16 01:41:51 +00002157 && !Rebase
2158 && !Bind
2159 && !LazyBind
Kevin Enderby131d1772015-01-09 19:22:37 +00002160 && !WeakBind
Adrian Prantl437105a2015-07-08 02:04:15 +00002161 && !RawClangAST
Kevin Enderby13023a12015-01-15 23:19:11 +00002162 && !(UniversalHeaders && MachOOpt)
Paul Semel0dc92f62018-07-05 14:43:29 +00002163 && !ArchiveHeaders
Kevin Enderby69fe98d2015-01-23 18:52:17 +00002164 && !(IndirectSymbols && MachOOpt)
Kevin Enderby9a509442015-01-27 21:28:24 +00002165 && !(DataInCode && MachOOpt)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002166 && !(LinkOptHints && MachOOpt)
Kevin Enderbycd66be52015-03-11 22:06:32 +00002167 && !(InfoPlist && MachOOpt)
Kevin Enderbybc847fa2015-03-16 20:08:09 +00002168 && !(DylibsUsed && MachOOpt)
2169 && !(DylibId && MachOOpt)
Kevin Enderby0fc11822015-04-01 20:57:01 +00002170 && !(ObjcMetaData && MachOOpt)
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00002171 && !(!FilterSections.empty() && MachOOpt)
Igor Laevsky03a670c2016-01-26 15:09:42 +00002172 && !PrintFaultMaps
2173 && DwarfDumpType == DIDT_Null) {
Michael J. Spencer2670c252011-01-20 06:39:06 +00002174 cl::PrintHelpMessage();
Dimitry Andrice4f5d012017-12-18 19:46:56 +00002175 return 2;
2176 }
2177
Rafael Aulerb0e4b912018-03-09 19:13:44 +00002178 DisasmFuncsSet.insert(DisassembleFunctions.begin(),
2179 DisassembleFunctions.end());
2180
George Rimar73a27232019-01-15 09:19:18 +00002181 llvm::for_each(InputFilenames, dumpInput);
Dimitry Andrice4f5d012017-12-18 19:46:56 +00002182
2183 return EXIT_SUCCESS;
2184}