blob: 974f55a72089b2b7f936d3dfc31eeed820bb573c [file] [log] [blame]
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001//===-- MachODump.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
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the MachO-specific dumper for llvm-objdump.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm-objdump.h"
Kevin Enderby98c9acc2014-09-16 18:00:57 +000014#include "llvm-c/Disassembler.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000015#include "llvm/ADT/STLExtras.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000016#include "llvm/ADT/StringExtras.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000017#include "llvm/ADT/Triple.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000018#include "llvm/BinaryFormat/MachO.h"
Kevin Enderby04bf6932014-10-28 23:39:46 +000019#include "llvm/Config/config.h"
Zachary Turner6489d7b2015-04-23 17:37:47 +000020#include "llvm/DebugInfo/DIContext.h"
21#include "llvm/DebugInfo/DWARF/DWARFContext.h"
Rafael Espindolab940b662016-09-06 19:16:48 +000022#include "llvm/Demangle/Demangle.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000023#include "llvm/MC/MCAsmInfo.h"
Lang Hamesa1bc0f52014-04-15 04:40:56 +000024#include "llvm/MC/MCContext.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000025#include "llvm/MC/MCDisassembler/MCDisassembler.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000026#include "llvm/MC/MCInst.h"
27#include "llvm/MC/MCInstPrinter.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000028#include "llvm/MC/MCInstrDesc.h"
29#include "llvm/MC/MCInstrInfo.h"
Jim Grosbachfd93a592012-03-05 19:33:20 +000030#include "llvm/MC/MCRegisterInfo.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000031#include "llvm/MC/MCSubtargetInfo.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000032#include "llvm/Object/MachO.h"
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +000033#include "llvm/Object/MachOUniversal.h"
Rafael Espindola9b709252013-04-13 01:45:40 +000034#include "llvm/Support/Casting.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000035#include "llvm/Support/CommandLine.h"
36#include "llvm/Support/Debug.h"
Tim Northover4bd286a2014-08-01 13:07:19 +000037#include "llvm/Support/Endian.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000038#include "llvm/Support/Format.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000039#include "llvm/Support/FormattedStream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000040#include "llvm/Support/GraphWriter.h"
Kevin Enderby9a509442015-01-27 21:28:24 +000041#include "llvm/Support/LEB128.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000042#include "llvm/Support/MemoryBuffer.h"
43#include "llvm/Support/TargetRegistry.h"
44#include "llvm/Support/TargetSelect.h"
Kevin Enderby9873e2c2016-05-23 21:34:12 +000045#include "llvm/Support/ToolOutputFile.h"
Jonas Devliegheree787efd2018-11-11 22:12:04 +000046#include "llvm/Support/WithColor.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000047#include "llvm/Support/raw_ostream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000048#include <algorithm>
49#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000050#include <system_error>
Kevin Enderby04bf6932014-10-28 23:39:46 +000051
Kevin Enderby9873e2c2016-05-23 21:34:12 +000052#ifdef HAVE_LIBXAR
53extern "C" {
54#include <xar/xar.h>
55}
56#endif
57
Benjamin Kramer43a772e2011-09-19 17:56:04 +000058using namespace llvm;
59using namespace object;
60
61static cl::opt<bool>
Matthew Voss0f436772019-02-19 19:46:08 +000062 UseDbg("g", cl::Grouping,
Kevin Enderbyb28ed012014-10-29 21:28:24 +000063 cl::desc("Print line information from debug info if available"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000064
Kevin Enderbyb28ed012014-10-29 21:28:24 +000065static cl::opt<std::string> DSYMFile("dsym",
66 cl::desc("Use .dSYM file for debug info"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000067
Kevin Enderbyb28ed012014-10-29 21:28:24 +000068static cl::opt<bool> FullLeadingAddr("full-leading-addr",
69 cl::desc("Print full leading address"));
Kevin Enderbybf246f52014-09-24 23:08:22 +000070
Kevin Enderbyf9d60f02016-11-29 21:43:40 +000071static cl::opt<bool> NoLeadingHeaders("no-leading-headers",
72 cl::desc("Print no leading headers"));
73
Kevin Enderby13023a12015-01-15 23:19:11 +000074cl::opt<bool> llvm::UniversalHeaders("universal-headers",
75 cl::desc("Print Mach-O universal headers "
76 "(requires -macho)"));
77
Kevin Enderby131d1772015-01-09 19:22:37 +000078cl::opt<bool>
Kevin Enderby8972e482015-04-30 20:30:42 +000079 ArchiveMemberOffsets("archive-member-offsets",
80 cl::desc("Print the offset to each archive member for "
81 "Mach-O archives (requires -macho and "
82 "-archive-headers)"));
83
84cl::opt<bool>
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +000085 llvm::IndirectSymbols("indirect-symbols",
86 cl::desc("Print indirect symbol table for Mach-O "
87 "objects (requires -macho)"));
88
Kevin Enderby69fe98d2015-01-23 18:52:17 +000089cl::opt<bool>
90 llvm::DataInCode("data-in-code",
91 cl::desc("Print the data in code table for Mach-O objects "
92 "(requires -macho)"));
93
Kevin Enderby9a509442015-01-27 21:28:24 +000094cl::opt<bool>
95 llvm::LinkOptHints("link-opt-hints",
96 cl::desc("Print the linker optimization hints for "
97 "Mach-O objects (requires -macho)"));
98
Kevin Enderbycd66be52015-03-11 22:06:32 +000099cl::opt<bool>
100 llvm::InfoPlist("info-plist",
101 cl::desc("Print the info plist section as strings for "
102 "Mach-O objects (requires -macho)"));
103
Kevin Enderbyf0640752015-03-13 17:56:32 +0000104cl::opt<bool>
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000105 llvm::DylibsUsed("dylibs-used",
106 cl::desc("Print the shared libraries used for linked "
107 "Mach-O files (requires -macho)"));
108
109cl::opt<bool>
110 llvm::DylibId("dylib-id",
111 cl::desc("Print the shared library's id for the dylib Mach-O "
112 "file (requires -macho)"));
113
114cl::opt<bool>
Kevin Enderbyf0640752015-03-13 17:56:32 +0000115 llvm::NonVerbose("non-verbose",
116 cl::desc("Print the info for Mach-O objects in "
117 "non-verbose or numeric form (requires -macho)"));
118
Kevin Enderby0fc11822015-04-01 20:57:01 +0000119cl::opt<bool>
120 llvm::ObjcMetaData("objc-meta-data",
121 cl::desc("Print the Objective-C runtime meta data for "
122 "Mach-O files (requires -macho)"));
123
Kevin Enderby6a221752015-03-17 17:10:57 +0000124cl::opt<std::string> llvm::DisSymName(
125 "dis-symname",
Saleem Abdulrasoolec6a7742016-09-08 23:17:34 +0000126 cl::desc("disassemble just this symbol's instructions (requires -macho)"));
Kevin Enderby6a221752015-03-17 17:10:57 +0000127
Kevin Enderby8e29ec92015-03-17 22:26:11 +0000128static cl::opt<bool> NoSymbolicOperands(
129 "no-symbolic-operands",
130 cl::desc("do not symbolic operands when disassembling (requires -macho)"));
131
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000132static cl::list<std::string>
133 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
134 cl::ZeroOrMore);
Hans Wennborgcc9deb42015-09-29 18:02:48 +0000135
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000136bool ArchAll = false;
137
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000138static std::string ThumbTripleName;
139
140static const Target *GetTarget(const MachOObjectFile *MachOObj,
141 const char **McpuDefault,
142 const Target **ThumbTarget) {
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000143 // Figure out the target triple.
Tim Northover9e8eb412016-04-22 23:21:13 +0000144 llvm::Triple TT(TripleName);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000145 if (TripleName.empty()) {
Tim Northover9e8eb412016-04-22 23:21:13 +0000146 TT = MachOObj->getArchTriple(McpuDefault);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000147 TripleName = TT.str();
Tim Northover9e8eb412016-04-22 23:21:13 +0000148 }
149
150 if (TT.getArch() == Triple::arm) {
151 // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
152 // that support ARM are also capable of Thumb mode.
153 llvm::Triple ThumbTriple = TT;
154 std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str();
155 ThumbTriple.setArchName(ThumbName);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000156 ThumbTripleName = ThumbTriple.str();
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000157 }
158
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000159 // Get the target specific parser.
160 std::string Error;
161 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000162 if (TheTarget && ThumbTripleName.empty())
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000163 return TheTarget;
164
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000165 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
166 if (*ThumbTarget)
167 return TheTarget;
168
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000169 WithColor::error(errs(), "llvm-objdump") << "unable to get target for '";
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000170 if (!TheTarget)
171 errs() << TripleName;
172 else
173 errs() << ThumbTripleName;
174 errs() << "', see --version and --triple.\n";
Craig Toppere6cb63e2014-04-25 04:24:47 +0000175 return nullptr;
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000176}
177
Owen Andersond9243c42011-10-17 21:37:35 +0000178struct SymbolSorter {
179 bool operator()(const SymbolRef &A, const SymbolRef &B) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000180 Expected<SymbolRef::Type> ATypeOrErr = A.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000181 if (!ATypeOrErr)
Fangrui Songe7834bd2019-04-07 08:19:55 +0000182 report_error(ATypeOrErr.takeError(), A.getObject()->getFileName());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000183 SymbolRef::Type AType = *ATypeOrErr;
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000184 Expected<SymbolRef::Type> BTypeOrErr = B.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000185 if (!BTypeOrErr)
Fangrui Songe7834bd2019-04-07 08:19:55 +0000186 report_error(BTypeOrErr.takeError(), B.getObject()->getFileName());
Kevin Enderby74f58d42016-03-23 21:45:21 +0000187 SymbolRef::Type BType = *BTypeOrErr;
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000188 uint64_t AAddr = (AType != SymbolRef::ST_Function) ? 0 : A.getValue();
189 uint64_t BAddr = (BType != SymbolRef::ST_Function) ? 0 : B.getValue();
Owen Andersond9243c42011-10-17 21:37:35 +0000190 return AAddr < BAddr;
191 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000192};
193
Kevin Enderby273ae012013-06-06 17:20:50 +0000194// Types for the storted data in code table that is built before disassembly
195// and the predicate function to sort them.
196typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
197typedef std::vector<DiceTableEntry> DiceTable;
198typedef DiceTable::iterator dice_table_iterator;
199
Francis Ricci195a66f2017-10-06 15:54:20 +0000200#ifdef HAVE_LIBXAR
Francis Ricci6f942972017-10-06 15:33:28 +0000201namespace {
202struct ScopedXarFile {
203 xar_t xar;
Francis Ricci57d84522017-10-09 20:27:14 +0000204 ScopedXarFile(const char *filename, int32_t flags)
205 : xar(xar_open(filename, flags)) {}
Francis Ricci6f942972017-10-06 15:33:28 +0000206 ~ScopedXarFile() {
207 if (xar)
208 xar_close(xar);
209 }
210 ScopedXarFile(const ScopedXarFile &) = delete;
211 ScopedXarFile &operator=(const ScopedXarFile &) = delete;
212 operator xar_t() { return xar; }
213};
214
215struct ScopedXarIter {
216 xar_iter_t iter;
Francis Ricci57d84522017-10-09 20:27:14 +0000217 ScopedXarIter() : iter(xar_iter_new()) {}
Francis Ricci6f942972017-10-06 15:33:28 +0000218 ~ScopedXarIter() {
219 if (iter)
220 xar_iter_free(iter);
221 }
222 ScopedXarIter(const ScopedXarIter &) = delete;
223 ScopedXarIter &operator=(const ScopedXarIter &) = delete;
224 operator xar_iter_t() { return iter; }
225};
226} // namespace
Francis Ricci195a66f2017-10-06 15:54:20 +0000227#endif // defined(HAVE_LIBXAR)
Francis Ricci6f942972017-10-06 15:33:28 +0000228
Kevin Enderby930fdc72014-11-06 19:00:13 +0000229// This is used to search for a data in code table entry for the PC being
230// disassembled. The j parameter has the PC in j.first. A single data in code
231// table entry can cover many bytes for each of its Kind's. So if the offset,
232// aka the i.first value, of the data in code table entry plus its Length
233// covers the PC being searched for this will return true. If not it will
234// return false.
David Majnemerea9b8ee2014-11-04 08:41:48 +0000235static bool compareDiceTableEntries(const DiceTableEntry &i,
236 const DiceTableEntry &j) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000237 uint16_t Length;
238 i.second.getLength(Length);
239
240 return j.first >= i.first && j.first < i.first + Length;
Kevin Enderby273ae012013-06-06 17:20:50 +0000241}
242
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000243static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
Kevin Enderby930fdc72014-11-06 19:00:13 +0000244 unsigned short Kind) {
245 uint32_t Value, Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000246
247 switch (Kind) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000248 default:
Charles Davis8bdfafd2013-09-01 04:28:48 +0000249 case MachO::DICE_KIND_DATA:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000250 if (Length >= 4) {
251 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000252 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000253 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000254 outs() << "\t.long " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000255 Size = 4;
256 } else if (Length >= 2) {
257 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000258 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000259 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000260 outs() << "\t.short " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000261 Size = 2;
262 } else {
263 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000264 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000265 Value = bytes[0];
266 outs() << "\t.byte " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000267 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000268 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000269 if (Kind == MachO::DICE_KIND_DATA)
270 outs() << "\t@ KIND_DATA\n";
271 else
272 outs() << "\t@ data in code kind = " << Kind << "\n";
Kevin Enderby273ae012013-06-06 17:20:50 +0000273 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000274 case MachO::DICE_KIND_JUMP_TABLE8:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000275 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000276 dumpBytes(makeArrayRef(bytes, 1), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000277 Value = bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000278 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
279 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000280 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000281 case MachO::DICE_KIND_JUMP_TABLE16:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000282 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000283 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000284 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000285 outs() << "\t.short " << format("%5u", Value & 0xffff)
286 << "\t@ KIND_JUMP_TABLE16\n";
287 Size = 2;
Kevin Enderby273ae012013-06-06 17:20:50 +0000288 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000289 case MachO::DICE_KIND_JUMP_TABLE32:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000290 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
291 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000292 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000293 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000294 outs() << "\t.long " << Value;
295 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
296 outs() << "\t@ KIND_JUMP_TABLE32\n";
297 else
298 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
299 Size = 4;
Kevin Enderby273ae012013-06-06 17:20:50 +0000300 break;
301 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000302 return Size;
Kevin Enderby273ae012013-06-06 17:20:50 +0000303}
304
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000305static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000306 std::vector<SectionRef> &Sections,
307 std::vector<SymbolRef> &Symbols,
308 SmallVectorImpl<uint64_t> &FoundFns,
309 uint64_t &BaseSegmentAddress) {
Fangrui Songe7834bd2019-04-07 08:19:55 +0000310 const StringRef FileName = MachOObj->getFileName();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000311 for (const SymbolRef &Symbol : MachOObj->symbols()) {
Fangrui Songe7834bd2019-04-07 08:19:55 +0000312 StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
313 if (!SymName.startswith("ltmp"))
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000314 Symbols.push_back(Symbol);
315 }
Owen Andersond9243c42011-10-17 21:37:35 +0000316
Alexey Samsonov48803e52014-03-13 14:37:36 +0000317 for (const SectionRef &Section : MachOObj->sections()) {
Owen Andersond9243c42011-10-17 21:37:35 +0000318 StringRef SectName;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000319 Section.getName(SectName);
320 Sections.push_back(Section);
Owen Andersond9243c42011-10-17 21:37:35 +0000321 }
322
Kevin Enderby273ae012013-06-06 17:20:50 +0000323 bool BaseSegmentAddressSet = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000324 for (const auto &Command : MachOObj->load_commands()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000325 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
Benjamin Kramer699128e2011-09-21 01:13:19 +0000326 // We found a function starts segment, parse the addresses for later
327 // consumption.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000328 MachO::linkedit_data_command LLC =
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000329 MachOObj->getLinkeditDataLoadCommand(Command);
Benjamin Kramer699128e2011-09-21 01:13:19 +0000330
Charles Davis8bdfafd2013-09-01 04:28:48 +0000331 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000332 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
333 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000334 StringRef SegName = SLC.segname;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000335 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
Kevin Enderby273ae012013-06-06 17:20:50 +0000336 BaseSegmentAddressSet = true;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000337 BaseSegmentAddress = SLC.vmaddr;
Kevin Enderby273ae012013-06-06 17:20:50 +0000338 }
339 }
Benjamin Kramer8a529dc2011-09-21 22:16:43 +0000340 }
Benjamin Kramer699128e2011-09-21 01:13:19 +0000341}
342
George Rimarc1964882019-01-18 11:33:26 +0000343static void printRelocationTargetName(const MachOObjectFile *O,
344 const MachO::any_relocation_info &RE,
345 raw_string_ostream &Fmt) {
346 // Target of a scattered relocation is an address. In the interest of
347 // generating pretty output, scan through the symbol table looking for a
348 // symbol that aligns with that address. If we find one, print it.
349 // Otherwise, we just print the hex address of the target.
Fangrui Songe7834bd2019-04-07 08:19:55 +0000350 const StringRef FileName = O->getFileName();
George Rimarc1964882019-01-18 11:33:26 +0000351 if (O->isRelocationScattered(RE)) {
352 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
353
354 for (const SymbolRef &Symbol : O->symbols()) {
Fangrui Songe7834bd2019-04-07 08:19:55 +0000355 uint64_t Addr = unwrapOrError(Symbol.getAddress(), FileName);
356 if (Addr != Val)
George Rimarc1964882019-01-18 11:33:26 +0000357 continue;
Fangrui Songe7834bd2019-04-07 08:19:55 +0000358 Fmt << unwrapOrError(Symbol.getName(), FileName);
George Rimarc1964882019-01-18 11:33:26 +0000359 return;
360 }
361
362 // If we couldn't find a symbol that this relocation refers to, try
363 // to find a section beginning instead.
364 for (const SectionRef &Section : ToolSectionFilter(*O)) {
365 std::error_code ec;
366
367 StringRef Name;
368 uint64_t Addr = Section.getAddress();
369 if (Addr != Val)
370 continue;
371 if ((ec = Section.getName(Name)))
372 report_error(O->getFileName(), ec);
373 Fmt << Name;
374 return;
375 }
376
377 Fmt << format("0x%x", Val);
378 return;
379 }
380
381 StringRef S;
382 bool isExtern = O->getPlainRelocationExternal(RE);
383 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
384
385 if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND) {
386 Fmt << format("0x%0" PRIx64, Val);
387 return;
388 }
389
390 if (isExtern) {
391 symbol_iterator SI = O->symbol_begin();
392 advance(SI, Val);
Fangrui Songe7834bd2019-04-07 08:19:55 +0000393 S = unwrapOrError(SI->getName(), FileName);
George Rimarc1964882019-01-18 11:33:26 +0000394 } else {
395 section_iterator SI = O->section_begin();
396 // Adjust for the fact that sections are 1-indexed.
397 if (Val == 0) {
398 Fmt << "0 (?,?)";
399 return;
400 }
401 uint32_t I = Val - 1;
402 while (I != 0 && SI != O->section_end()) {
403 --I;
404 advance(SI, 1);
405 }
406 if (SI == O->section_end())
407 Fmt << Val << " (?,?)";
408 else
409 SI->getName(S);
410 }
411
412 Fmt << S;
413}
414
415std::error_code
416llvm::getMachORelocationValueString(const MachOObjectFile *Obj,
417 const RelocationRef &RelRef,
418 SmallVectorImpl<char> &Result) {
419 DataRefImpl Rel = RelRef.getRawDataRefImpl();
420 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
421
422 unsigned Arch = Obj->getArch();
423
424 std::string FmtBuf;
425 raw_string_ostream Fmt(FmtBuf);
426 unsigned Type = Obj->getAnyRelocationType(RE);
427 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
428
429 // Determine any addends that should be displayed with the relocation.
430 // These require decoding the relocation type, which is triple-specific.
431
432 // X86_64 has entirely custom relocation types.
433 if (Arch == Triple::x86_64) {
434 switch (Type) {
435 case MachO::X86_64_RELOC_GOT_LOAD:
436 case MachO::X86_64_RELOC_GOT: {
437 printRelocationTargetName(Obj, RE, Fmt);
438 Fmt << "@GOT";
439 if (IsPCRel)
440 Fmt << "PCREL";
441 break;
442 }
443 case MachO::X86_64_RELOC_SUBTRACTOR: {
444 DataRefImpl RelNext = Rel;
445 Obj->moveRelocationNext(RelNext);
446 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
447
448 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
449 // X86_64_RELOC_UNSIGNED.
450 // NOTE: Scattered relocations don't exist on x86_64.
451 unsigned RType = Obj->getAnyRelocationType(RENext);
452 if (RType != MachO::X86_64_RELOC_UNSIGNED)
453 report_error(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
454 "X86_64_RELOC_SUBTRACTOR.");
455
456 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
457 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
458 printRelocationTargetName(Obj, RENext, Fmt);
459 Fmt << "-";
460 printRelocationTargetName(Obj, RE, Fmt);
461 break;
462 }
463 case MachO::X86_64_RELOC_TLV:
464 printRelocationTargetName(Obj, RE, Fmt);
465 Fmt << "@TLV";
466 if (IsPCRel)
467 Fmt << "P";
468 break;
469 case MachO::X86_64_RELOC_SIGNED_1:
470 printRelocationTargetName(Obj, RE, Fmt);
471 Fmt << "-1";
472 break;
473 case MachO::X86_64_RELOC_SIGNED_2:
474 printRelocationTargetName(Obj, RE, Fmt);
475 Fmt << "-2";
476 break;
477 case MachO::X86_64_RELOC_SIGNED_4:
478 printRelocationTargetName(Obj, RE, Fmt);
479 Fmt << "-4";
480 break;
481 default:
482 printRelocationTargetName(Obj, RE, Fmt);
483 break;
484 }
485 // X86 and ARM share some relocation types in common.
486 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
487 Arch == Triple::ppc) {
488 // Generic relocation types...
489 switch (Type) {
490 case MachO::GENERIC_RELOC_PAIR: // prints no info
491 return std::error_code();
492 case MachO::GENERIC_RELOC_SECTDIFF: {
493 DataRefImpl RelNext = Rel;
494 Obj->moveRelocationNext(RelNext);
495 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
496
497 // X86 sect diff's must be followed by a relocation of type
498 // GENERIC_RELOC_PAIR.
499 unsigned RType = Obj->getAnyRelocationType(RENext);
500
501 if (RType != MachO::GENERIC_RELOC_PAIR)
502 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
503 "GENERIC_RELOC_SECTDIFF.");
504
505 printRelocationTargetName(Obj, RE, Fmt);
506 Fmt << "-";
507 printRelocationTargetName(Obj, RENext, Fmt);
508 break;
509 }
510 }
511
512 if (Arch == Triple::x86 || Arch == Triple::ppc) {
513 switch (Type) {
514 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
515 DataRefImpl RelNext = Rel;
516 Obj->moveRelocationNext(RelNext);
517 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
518
519 // X86 sect diff's must be followed by a relocation of type
520 // GENERIC_RELOC_PAIR.
521 unsigned RType = Obj->getAnyRelocationType(RENext);
522 if (RType != MachO::GENERIC_RELOC_PAIR)
523 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
524 "GENERIC_RELOC_LOCAL_SECTDIFF.");
525
526 printRelocationTargetName(Obj, RE, Fmt);
527 Fmt << "-";
528 printRelocationTargetName(Obj, RENext, Fmt);
529 break;
530 }
531 case MachO::GENERIC_RELOC_TLV: {
532 printRelocationTargetName(Obj, RE, Fmt);
533 Fmt << "@TLV";
534 if (IsPCRel)
535 Fmt << "P";
536 break;
537 }
538 default:
539 printRelocationTargetName(Obj, RE, Fmt);
540 }
541 } else { // ARM-specific relocations
542 switch (Type) {
543 case MachO::ARM_RELOC_HALF:
544 case MachO::ARM_RELOC_HALF_SECTDIFF: {
545 // Half relocations steal a bit from the length field to encode
546 // whether this is an upper16 or a lower16 relocation.
547 bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
548
549 if (isUpper)
550 Fmt << ":upper16:(";
551 else
552 Fmt << ":lower16:(";
553 printRelocationTargetName(Obj, RE, Fmt);
554
555 DataRefImpl RelNext = Rel;
556 Obj->moveRelocationNext(RelNext);
557 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
558
559 // ARM half relocs must be followed by a relocation of type
560 // ARM_RELOC_PAIR.
561 unsigned RType = Obj->getAnyRelocationType(RENext);
562 if (RType != MachO::ARM_RELOC_PAIR)
563 report_error(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
564 "ARM_RELOC_HALF");
565
566 // NOTE: The half of the target virtual address is stashed in the
567 // address field of the secondary relocation, but we can't reverse
568 // engineer the constant offset from it without decoding the movw/movt
569 // instruction to find the other half in its immediate field.
570
571 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
572 // symbol/section pointer of the follow-on relocation.
573 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
574 Fmt << "-";
575 printRelocationTargetName(Obj, RENext, Fmt);
576 }
577
578 Fmt << ")";
579 break;
580 }
581 default: {
582 printRelocationTargetName(Obj, RE, Fmt);
583 }
584 }
585 }
586 } else
587 printRelocationTargetName(Obj, RE, Fmt);
588
589 Fmt.flush();
590 Result.append(FmtBuf.begin(), FmtBuf.end());
591 return std::error_code();
592}
593
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000594static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
595 uint32_t n, uint32_t count,
596 uint32_t stride, uint64_t addr) {
597 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
598 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
599 if (n > nindirectsyms)
600 outs() << " (entries start past the end of the indirect symbol "
601 "table) (reserved1 field greater than the table size)";
602 else if (n + count > nindirectsyms)
603 outs() << " (entries extends past the end of the indirect symbol "
604 "table)";
605 outs() << "\n";
606 uint32_t cputype = O->getHeader().cputype;
607 if (cputype & MachO::CPU_ARCH_ABI64)
608 outs() << "address index";
609 else
610 outs() << "address index";
611 if (verbose)
612 outs() << " name\n";
613 else
614 outs() << "\n";
615 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
616 if (cputype & MachO::CPU_ARCH_ABI64)
617 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
618 else
Tim Northover43978372016-04-26 18:29:16 +0000619 outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " ";
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000620 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
621 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
622 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
623 outs() << "LOCAL\n";
624 continue;
625 }
626 if (indirect_symbol ==
627 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
628 outs() << "LOCAL ABSOLUTE\n";
629 continue;
630 }
631 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
632 outs() << "ABSOLUTE\n";
633 continue;
634 }
635 outs() << format("%5u ", indirect_symbol);
Kevin Enderbyf0640752015-03-13 17:56:32 +0000636 if (verbose) {
637 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
638 if (indirect_symbol < Symtab.nsyms) {
639 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
640 SymbolRef Symbol = *Sym;
Fangrui Songe7834bd2019-04-07 08:19:55 +0000641 outs() << unwrapOrError(Symbol.getName(), O->getFileName());
Kevin Enderbyf0640752015-03-13 17:56:32 +0000642 } else {
643 outs() << "?";
644 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000645 }
646 outs() << "\n";
647 }
648}
649
650static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000651 for (const auto &Load : O->load_commands()) {
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000652 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
653 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
654 for (unsigned J = 0; J < Seg.nsects; ++J) {
655 MachO::section_64 Sec = O->getSection64(Load, J);
656 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
657 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
658 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
659 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
660 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
661 section_type == MachO::S_SYMBOL_STUBS) {
662 uint32_t stride;
663 if (section_type == MachO::S_SYMBOL_STUBS)
664 stride = Sec.reserved2;
665 else
666 stride = 8;
667 if (stride == 0) {
668 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
669 << Sec.sectname << ") "
670 << "(size of stubs in reserved2 field is zero)\n";
671 continue;
672 }
673 uint32_t count = Sec.size / stride;
674 outs() << "Indirect symbols for (" << Sec.segname << ","
675 << Sec.sectname << ") " << count << " entries";
676 uint32_t n = Sec.reserved1;
677 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
678 }
679 }
680 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
681 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
682 for (unsigned J = 0; J < Seg.nsects; ++J) {
683 MachO::section Sec = O->getSection(Load, J);
684 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
685 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
686 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
687 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
688 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
689 section_type == MachO::S_SYMBOL_STUBS) {
690 uint32_t stride;
691 if (section_type == MachO::S_SYMBOL_STUBS)
692 stride = Sec.reserved2;
693 else
694 stride = 4;
695 if (stride == 0) {
696 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
697 << Sec.sectname << ") "
698 << "(size of stubs in reserved2 field is zero)\n";
699 continue;
700 }
701 uint32_t count = Sec.size / stride;
702 outs() << "Indirect symbols for (" << Sec.segname << ","
703 << Sec.sectname << ") " << count << " entries";
704 uint32_t n = Sec.reserved1;
705 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
706 }
707 }
708 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000709 }
710}
711
Michael Trenta1703b12017-12-15 17:57:40 +0000712static void PrintRType(const uint64_t cputype, const unsigned r_type) {
713 static char const *generic_r_types[] = {
714 "VANILLA ", "PAIR ", "SECTDIF ", "PBLAPTR ", "LOCSDIF ", "TLV ",
715 " 6 (?) ", " 7 (?) ", " 8 (?) ", " 9 (?) ", " 10 (?) ", " 11 (?) ",
716 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
717 };
718 static char const *x86_64_r_types[] = {
719 "UNSIGND ", "SIGNED ", "BRANCH ", "GOT_LD ", "GOT ", "SUB ",
720 "SIGNED1 ", "SIGNED2 ", "SIGNED4 ", "TLV ", " 10 (?) ", " 11 (?) ",
721 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
722 };
723 static char const *arm_r_types[] = {
724 "VANILLA ", "PAIR ", "SECTDIFF", "LOCSDIF ", "PBLAPTR ",
725 "BR24 ", "T_BR22 ", "T_BR32 ", "HALF ", "HALFDIF ",
726 " 10 (?) ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
727 };
728 static char const *arm64_r_types[] = {
729 "UNSIGND ", "SUB ", "BR26 ", "PAGE21 ", "PAGOF12 ",
730 "GOTLDP ", "GOTLDPOF", "PTRTGOT ", "TLVLDP ", "TLVLDPOF",
731 "ADDEND ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
732 };
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000733
Michael Trenta1703b12017-12-15 17:57:40 +0000734 if (r_type > 0xf){
735 outs() << format("%-7u", r_type) << " ";
736 return;
737 }
738 switch (cputype) {
739 case MachO::CPU_TYPE_I386:
740 outs() << generic_r_types[r_type];
741 break;
742 case MachO::CPU_TYPE_X86_64:
743 outs() << x86_64_r_types[r_type];
744 break;
745 case MachO::CPU_TYPE_ARM:
746 outs() << arm_r_types[r_type];
747 break;
748 case MachO::CPU_TYPE_ARM64:
749 outs() << arm64_r_types[r_type];
750 break;
751 default:
752 outs() << format("%-7u ", r_type);
753 }
754}
755
756static void PrintRLength(const uint64_t cputype, const unsigned r_type,
757 const unsigned r_length, const bool previous_arm_half){
758 if (cputype == MachO::CPU_TYPE_ARM &&
759 (r_type == llvm::MachO::ARM_RELOC_HALF ||
760 r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF ||
761 previous_arm_half == true)) {
762 if ((r_length & 0x1) == 0)
763 outs() << "lo/";
764 else
765 outs() << "hi/";
766 if ((r_length & 0x1) == 0)
767 outs() << "arm ";
768 else
769 outs() << "thm ";
770 } else {
771 switch (r_length) {
772 case 0:
773 outs() << "byte ";
774 break;
775 case 1:
776 outs() << "word ";
777 break;
778 case 2:
779 outs() << "long ";
780 break;
781 case 3:
782 if (cputype == MachO::CPU_TYPE_X86_64)
783 outs() << "quad ";
784 else
785 outs() << format("?(%2d) ", r_length);
786 break;
787 default:
788 outs() << format("?(%2d) ", r_length);
789 }
790 }
791}
792
793static void PrintRelocationEntries(const MachOObjectFile *O,
794 const relocation_iterator Begin,
795 const relocation_iterator End,
796 const uint64_t cputype,
797 const bool verbose) {
798 const MachO::symtab_command Symtab = O->getSymtabLoadCommand();
799 bool previous_arm_half = false;
800 bool previous_sectdiff = false;
801 uint32_t sectdiff_r_type = 0;
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000802
Michael Trenta1703b12017-12-15 17:57:40 +0000803 for (relocation_iterator Reloc = Begin; Reloc != End; ++Reloc) {
804 const DataRefImpl Rel = Reloc->getRawDataRefImpl();
805 const MachO::any_relocation_info RE = O->getRelocation(Rel);
806 const unsigned r_type = O->getAnyRelocationType(RE);
807 const bool r_scattered = O->isRelocationScattered(RE);
808 const unsigned r_pcrel = O->getAnyRelocationPCRel(RE);
809 const unsigned r_length = O->getAnyRelocationLength(RE);
810 const unsigned r_address = O->getAnyRelocationAddress(RE);
811 const bool r_extern = (r_scattered ? false :
812 O->getPlainRelocationExternal(RE));
813 const uint32_t r_value = (r_scattered ?
814 O->getScatteredRelocationValue(RE) : 0);
815 const unsigned r_symbolnum = (r_scattered ? 0 :
816 O->getPlainRelocationSymbolNum(RE));
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000817
Michael Trenta1703b12017-12-15 17:57:40 +0000818 if (r_scattered && cputype != MachO::CPU_TYPE_X86_64) {
819 if (verbose) {
820 // scattered: address
821 if ((cputype == MachO::CPU_TYPE_I386 &&
822 r_type == llvm::MachO::GENERIC_RELOC_PAIR) ||
823 (cputype == MachO::CPU_TYPE_ARM &&
824 r_type == llvm::MachO::ARM_RELOC_PAIR))
825 outs() << " ";
826 else
827 outs() << format("%08x ", (unsigned int)r_address);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000828
Michael Trenta1703b12017-12-15 17:57:40 +0000829 // scattered: pcrel
830 if (r_pcrel)
831 outs() << "True ";
832 else
833 outs() << "False ";
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000834
Michael Trenta1703b12017-12-15 17:57:40 +0000835 // scattered: length
836 PrintRLength(cputype, r_type, r_length, previous_arm_half);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000837
Michael Trenta1703b12017-12-15 17:57:40 +0000838 // scattered: extern & type
839 outs() << "n/a ";
840 PrintRType(cputype, r_type);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000841
Michael Trenta1703b12017-12-15 17:57:40 +0000842 // scattered: scattered & value
843 outs() << format("True 0x%08x", (unsigned int)r_value);
844 if (previous_sectdiff == false) {
845 if ((cputype == MachO::CPU_TYPE_ARM &&
846 r_type == llvm::MachO::ARM_RELOC_PAIR))
847 outs() << format(" half = 0x%04x ", (unsigned int)r_address);
848 }
849 else if (cputype == MachO::CPU_TYPE_ARM &&
850 sectdiff_r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF)
851 outs() << format(" other_half = 0x%04x ", (unsigned int)r_address);
852 if ((cputype == MachO::CPU_TYPE_I386 &&
853 (r_type == llvm::MachO::GENERIC_RELOC_SECTDIFF ||
854 r_type == llvm::MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) ||
855 (cputype == MachO::CPU_TYPE_ARM &&
856 (sectdiff_r_type == llvm::MachO::ARM_RELOC_SECTDIFF ||
857 sectdiff_r_type == llvm::MachO::ARM_RELOC_LOCAL_SECTDIFF ||
858 sectdiff_r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF))) {
859 previous_sectdiff = true;
860 sectdiff_r_type = r_type;
861 }
862 else {
863 previous_sectdiff = false;
864 sectdiff_r_type = 0;
865 }
866 if (cputype == MachO::CPU_TYPE_ARM &&
867 (r_type == llvm::MachO::ARM_RELOC_HALF ||
868 r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF))
869 previous_arm_half = true;
870 else
871 previous_arm_half = false;
872 outs() << "\n";
873 }
874 else {
875 // scattered: address pcrel length extern type scattered value
876 outs() << format("%08x %1d %-2d n/a %-7d 1 0x%08x\n",
877 (unsigned int)r_address, r_pcrel, r_length, r_type,
878 (unsigned int)r_value);
879 }
880 }
881 else {
882 if (verbose) {
883 // plain: address
884 if (cputype == MachO::CPU_TYPE_ARM &&
885 r_type == llvm::MachO::ARM_RELOC_PAIR)
886 outs() << " ";
887 else
888 outs() << format("%08x ", (unsigned int)r_address);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000889
Michael Trenta1703b12017-12-15 17:57:40 +0000890 // plain: pcrel
891 if (r_pcrel)
892 outs() << "True ";
893 else
894 outs() << "False ";
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000895
Michael Trenta1703b12017-12-15 17:57:40 +0000896 // plain: length
897 PrintRLength(cputype, r_type, r_length, previous_arm_half);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000898
Michael Trenta1703b12017-12-15 17:57:40 +0000899 if (r_extern) {
900 // plain: extern & type & scattered
901 outs() << "True ";
902 PrintRType(cputype, r_type);
903 outs() << "False ";
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000904
Michael Trenta1703b12017-12-15 17:57:40 +0000905 // plain: symbolnum/value
906 if (r_symbolnum > Symtab.nsyms)
907 outs() << format("?(%d)\n", r_symbolnum);
908 else {
909 SymbolRef Symbol = *O->getSymbolByIndex(r_symbolnum);
910 Expected<StringRef> SymNameNext = Symbol.getName();
911 const char *name = NULL;
912 if (SymNameNext)
913 name = SymNameNext->data();
914 if (name == NULL)
915 outs() << format("?(%d)\n", r_symbolnum);
916 else
917 outs() << name << "\n";
918 }
919 }
920 else {
921 // plain: extern & type & scattered
922 outs() << "False ";
923 PrintRType(cputype, r_type);
924 outs() << "False ";
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000925
Michael Trenta1703b12017-12-15 17:57:40 +0000926 // plain: symbolnum/value
927 if (cputype == MachO::CPU_TYPE_ARM &&
928 r_type == llvm::MachO::ARM_RELOC_PAIR)
929 outs() << format("other_half = 0x%04x\n", (unsigned int)r_address);
930 else if (cputype == MachO::CPU_TYPE_ARM64 &&
931 r_type == llvm::MachO::ARM64_RELOC_ADDEND)
932 outs() << format("addend = 0x%06x\n", (unsigned int)r_symbolnum);
933 else {
934 outs() << format("%d ", r_symbolnum);
935 if (r_symbolnum == llvm::MachO::R_ABS)
936 outs() << "R_ABS\n";
937 else {
938 // in this case, r_symbolnum is actually a 1-based section number
939 uint32_t nsects = O->section_end()->getRawDataRefImpl().d.a;
940 if (r_symbolnum > 0 && r_symbolnum <= nsects) {
941 llvm::object::DataRefImpl DRI;
942 DRI.d.a = r_symbolnum-1;
943 StringRef SegName = O->getSectionFinalSegmentName(DRI);
944 StringRef SectName;
945 if (O->getSectionName(DRI, SectName))
946 outs() << "(?,?)\n";
947 else
948 outs() << "(" << SegName << "," << SectName << ")\n";
949 }
950 else {
951 outs() << "(?,?)\n";
952 }
953 }
954 }
955 }
956 if (cputype == MachO::CPU_TYPE_ARM &&
957 (r_type == llvm::MachO::ARM_RELOC_HALF ||
958 r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF))
959 previous_arm_half = true;
960 else
961 previous_arm_half = false;
962 }
963 else {
964 // plain: address pcrel length extern type scattered symbolnum/section
965 outs() << format("%08x %1d %-2d %1d %-7d 0 %d\n",
966 (unsigned int)r_address, r_pcrel, r_length, r_extern,
967 r_type, r_symbolnum);
968 }
969 }
970 }
971}
972
973static void PrintRelocations(const MachOObjectFile *O, const bool verbose) {
974 const uint64_t cputype = O->getHeader().cputype;
975 const MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
976 if (Dysymtab.nextrel != 0) {
977 outs() << "External relocation information " << Dysymtab.nextrel
978 << " entries";
979 outs() << "\naddress pcrel length extern type scattered "
980 "symbolnum/value\n";
981 PrintRelocationEntries(O, O->extrel_begin(), O->extrel_end(), cputype,
982 verbose);
983 }
984 if (Dysymtab.nlocrel != 0) {
985 outs() << format("Local relocation information %u entries",
986 Dysymtab.nlocrel);
987 outs() << "\naddress pcrel length extern type scattered "
988 "symbolnum/value\n";
989 PrintRelocationEntries(O, O->locrel_begin(), O->locrel_end(), cputype,
990 verbose);
991 }
992 for (const auto &Load : O->load_commands()) {
993 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
994 const MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
995 for (unsigned J = 0; J < Seg.nsects; ++J) {
996 const MachO::section_64 Sec = O->getSection64(Load, J);
997 if (Sec.nreloc != 0) {
998 DataRefImpl DRI;
999 DRI.d.a = J;
1000 const StringRef SegName = O->getSectionFinalSegmentName(DRI);
1001 StringRef SectName;
1002 if (O->getSectionName(DRI, SectName))
1003 outs() << "Relocation information (" << SegName << ",?) "
1004 << format("%u entries", Sec.nreloc);
1005 else
1006 outs() << "Relocation information (" << SegName << ","
1007 << SectName << format(") %u entries", Sec.nreloc);
1008 outs() << "\naddress pcrel length extern type scattered "
1009 "symbolnum/value\n";
1010 PrintRelocationEntries(O, O->section_rel_begin(DRI),
1011 O->section_rel_end(DRI), cputype, verbose);
1012 }
1013 }
1014 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1015 const MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
1016 for (unsigned J = 0; J < Seg.nsects; ++J) {
1017 const MachO::section Sec = O->getSection(Load, J);
1018 if (Sec.nreloc != 0) {
1019 DataRefImpl DRI;
1020 DRI.d.a = J;
1021 const StringRef SegName = O->getSectionFinalSegmentName(DRI);
1022 StringRef SectName;
1023 if (O->getSectionName(DRI, SectName))
1024 outs() << "Relocation information (" << SegName << ",?) "
1025 << format("%u entries", Sec.nreloc);
1026 else
1027 outs() << "Relocation information (" << SegName << ","
1028 << SectName << format(") %u entries", Sec.nreloc);
1029 outs() << "\naddress pcrel length extern type scattered "
1030 "symbolnum/value\n";
1031 PrintRelocationEntries(O, O->section_rel_begin(DRI),
1032 O->section_rel_end(DRI), cputype, verbose);
1033 }
1034 }
1035 }
1036 }
1037}
1038
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001039static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
1040 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
1041 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
1042 outs() << "Data in code table (" << nentries << " entries)\n";
1043 outs() << "offset length kind\n";
1044 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
1045 ++DI) {
1046 uint32_t Offset;
1047 DI->getOffset(Offset);
1048 outs() << format("0x%08" PRIx32, Offset) << " ";
1049 uint16_t Length;
1050 DI->getLength(Length);
1051 outs() << format("%6u", Length) << " ";
1052 uint16_t Kind;
1053 DI->getKind(Kind);
1054 if (verbose) {
1055 switch (Kind) {
1056 case MachO::DICE_KIND_DATA:
1057 outs() << "DATA";
1058 break;
1059 case MachO::DICE_KIND_JUMP_TABLE8:
1060 outs() << "JUMP_TABLE8";
1061 break;
1062 case MachO::DICE_KIND_JUMP_TABLE16:
1063 outs() << "JUMP_TABLE16";
1064 break;
1065 case MachO::DICE_KIND_JUMP_TABLE32:
1066 outs() << "JUMP_TABLE32";
1067 break;
1068 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
1069 outs() << "ABS_JUMP_TABLE32";
1070 break;
1071 default:
1072 outs() << format("0x%04" PRIx32, Kind);
1073 break;
1074 }
1075 } else
1076 outs() << format("0x%04" PRIx32, Kind);
1077 outs() << "\n";
1078 }
1079}
1080
Kevin Enderby9a509442015-01-27 21:28:24 +00001081static void PrintLinkOptHints(MachOObjectFile *O) {
1082 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
1083 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
1084 uint32_t nloh = LohLC.datasize;
1085 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
1086 for (uint32_t i = 0; i < nloh;) {
1087 unsigned n;
1088 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
1089 i += n;
1090 outs() << " identifier " << identifier << " ";
1091 if (i >= nloh)
1092 return;
1093 switch (identifier) {
1094 case 1:
1095 outs() << "AdrpAdrp\n";
1096 break;
1097 case 2:
1098 outs() << "AdrpLdr\n";
1099 break;
1100 case 3:
1101 outs() << "AdrpAddLdr\n";
1102 break;
1103 case 4:
1104 outs() << "AdrpLdrGotLdr\n";
1105 break;
1106 case 5:
1107 outs() << "AdrpAddStr\n";
1108 break;
1109 case 6:
1110 outs() << "AdrpLdrGotStr\n";
1111 break;
1112 case 7:
1113 outs() << "AdrpAdd\n";
1114 break;
1115 case 8:
1116 outs() << "AdrpLdrGot\n";
1117 break;
1118 default:
1119 outs() << "Unknown identifier value\n";
1120 break;
1121 }
1122 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
1123 i += n;
1124 outs() << " narguments " << narguments << "\n";
1125 if (i >= nloh)
1126 return;
1127
1128 for (uint32_t j = 0; j < narguments; j++) {
1129 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
1130 i += n;
1131 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
1132 if (i >= nloh)
1133 return;
1134 }
1135 }
1136}
1137
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001138static void PrintDylibs(MachOObjectFile *O, bool JustId) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00001139 unsigned Index = 0;
1140 for (const auto &Load : O->load_commands()) {
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001141 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
1142 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
1143 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
1144 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
1145 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
1146 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
1147 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
1148 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
1149 if (dl.dylib.name < dl.cmdsize) {
1150 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
1151 if (JustId)
1152 outs() << p << "\n";
1153 else {
1154 outs() << "\t" << p;
1155 outs() << " (compatibility version "
1156 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
1157 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
1158 << (dl.dylib.compatibility_version & 0xff) << ",";
1159 outs() << " current version "
1160 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
1161 << ((dl.dylib.current_version >> 8) & 0xff) << "."
1162 << (dl.dylib.current_version & 0xff) << ")\n";
1163 }
1164 } else {
1165 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
1166 if (Load.C.cmd == MachO::LC_ID_DYLIB)
1167 outs() << "LC_ID_DYLIB ";
1168 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
1169 outs() << "LC_LOAD_DYLIB ";
1170 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1171 outs() << "LC_LOAD_WEAK_DYLIB ";
1172 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1173 outs() << "LC_LAZY_LOAD_DYLIB ";
1174 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1175 outs() << "LC_REEXPORT_DYLIB ";
1176 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1177 outs() << "LC_LOAD_UPWARD_DYLIB ";
1178 else
1179 outs() << "LC_??? ";
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00001180 outs() << "command " << Index++ << "\n";
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001181 }
1182 }
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001183 }
1184}
1185
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001186typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
1187
1188static void CreateSymbolAddressMap(MachOObjectFile *O,
1189 SymbolAddressMap *AddrMap) {
1190 // Create a map of symbol addresses to symbol names.
Fangrui Songe7834bd2019-04-07 08:19:55 +00001191 const StringRef FileName = O->getFileName();
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001192 for (const SymbolRef &Symbol : O->symbols()) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00001193 SymbolRef::Type ST = unwrapOrError(Symbol.getType(), FileName);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001194 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
1195 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00001196 uint64_t Address = Symbol.getValue();
Fangrui Songe7834bd2019-04-07 08:19:55 +00001197 StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
Kevin Enderby846c0002015-04-16 17:19:59 +00001198 if (!SymName.startswith(".objc"))
1199 (*AddrMap)[Address] = SymName;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001200 }
1201 }
1202}
1203
1204// GuessSymbolName is passed the address of what might be a symbol and a
1205// pointer to the SymbolAddressMap. It returns the name of a symbol
1206// with that address or nullptr if no symbol is found with that address.
1207static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
1208 const char *SymbolName = nullptr;
1209 // A DenseMap can't lookup up some values.
1210 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
1211 StringRef name = AddrMap->lookup(value);
1212 if (!name.empty())
1213 SymbolName = name.data();
1214 }
1215 return SymbolName;
1216}
1217
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001218static void DumpCstringChar(const char c) {
1219 char p[2];
1220 p[0] = c;
1221 p[1] = '\0';
1222 outs().write_escaped(p);
1223}
1224
Kevin Enderby10ba0412015-02-04 21:38:42 +00001225static void DumpCstringSection(MachOObjectFile *O, const char *sect,
1226 uint32_t sect_size, uint64_t sect_addr,
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001227 bool print_addresses) {
Kevin Enderby10ba0412015-02-04 21:38:42 +00001228 for (uint32_t i = 0; i < sect_size; i++) {
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001229 if (print_addresses) {
1230 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001231 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001232 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001233 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001234 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001235 for (; i < sect_size && sect[i] != '\0'; i++)
1236 DumpCstringChar(sect[i]);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001237 if (i < sect_size && sect[i] == '\0')
1238 outs() << "\n";
1239 }
1240}
1241
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001242static void DumpLiteral4(uint32_t l, float f) {
1243 outs() << format("0x%08" PRIx32, l);
1244 if ((l & 0x7f800000) != 0x7f800000)
1245 outs() << format(" (%.16e)\n", f);
1246 else {
1247 if (l == 0x7f800000)
1248 outs() << " (+Infinity)\n";
1249 else if (l == 0xff800000)
1250 outs() << " (-Infinity)\n";
1251 else if ((l & 0x00400000) == 0x00400000)
1252 outs() << " (non-signaling Not-a-Number)\n";
1253 else
1254 outs() << " (signaling Not-a-Number)\n";
1255 }
1256}
1257
1258static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
1259 uint32_t sect_size, uint64_t sect_addr,
1260 bool print_addresses) {
1261 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
1262 if (print_addresses) {
1263 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001264 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001265 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001266 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001267 }
1268 float f;
1269 memcpy(&f, sect + i, sizeof(float));
1270 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1271 sys::swapByteOrder(f);
1272 uint32_t l;
1273 memcpy(&l, sect + i, sizeof(uint32_t));
1274 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1275 sys::swapByteOrder(l);
1276 DumpLiteral4(l, f);
1277 }
1278}
1279
1280static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
1281 double d) {
1282 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
1283 uint32_t Hi, Lo;
Davide Italianob627d9f2015-12-12 21:50:11 +00001284 Hi = (O->isLittleEndian()) ? l1 : l0;
1285 Lo = (O->isLittleEndian()) ? l0 : l1;
1286
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001287 // Hi is the high word, so this is equivalent to if(isfinite(d))
1288 if ((Hi & 0x7ff00000) != 0x7ff00000)
1289 outs() << format(" (%.16e)\n", d);
1290 else {
1291 if (Hi == 0x7ff00000 && Lo == 0)
1292 outs() << " (+Infinity)\n";
1293 else if (Hi == 0xfff00000 && Lo == 0)
1294 outs() << " (-Infinity)\n";
1295 else if ((Hi & 0x00080000) == 0x00080000)
1296 outs() << " (non-signaling Not-a-Number)\n";
1297 else
1298 outs() << " (signaling Not-a-Number)\n";
1299 }
1300}
1301
1302static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
1303 uint32_t sect_size, uint64_t sect_addr,
1304 bool print_addresses) {
1305 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
1306 if (print_addresses) {
1307 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001308 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001309 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001310 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001311 }
1312 double d;
1313 memcpy(&d, sect + i, sizeof(double));
1314 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1315 sys::swapByteOrder(d);
1316 uint32_t l0, l1;
1317 memcpy(&l0, sect + i, sizeof(uint32_t));
1318 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1319 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1320 sys::swapByteOrder(l0);
1321 sys::swapByteOrder(l1);
1322 }
1323 DumpLiteral8(O, l0, l1, d);
1324 }
1325}
1326
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001327static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
1328 outs() << format("0x%08" PRIx32, l0) << " ";
1329 outs() << format("0x%08" PRIx32, l1) << " ";
1330 outs() << format("0x%08" PRIx32, l2) << " ";
1331 outs() << format("0x%08" PRIx32, l3) << "\n";
1332}
1333
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001334static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
1335 uint32_t sect_size, uint64_t sect_addr,
1336 bool print_addresses) {
1337 for (uint32_t i = 0; i < sect_size; i += 16) {
1338 if (print_addresses) {
1339 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001340 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001341 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001342 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001343 }
1344 uint32_t l0, l1, l2, l3;
1345 memcpy(&l0, sect + i, sizeof(uint32_t));
1346 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1347 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
1348 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
1349 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1350 sys::swapByteOrder(l0);
1351 sys::swapByteOrder(l1);
1352 sys::swapByteOrder(l2);
1353 sys::swapByteOrder(l3);
1354 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001355 DumpLiteral16(l0, l1, l2, l3);
1356 }
1357}
1358
1359static void DumpLiteralPointerSection(MachOObjectFile *O,
1360 const SectionRef &Section,
1361 const char *sect, uint32_t sect_size,
1362 uint64_t sect_addr,
1363 bool print_addresses) {
1364 // Collect the literal sections in this Mach-O file.
1365 std::vector<SectionRef> LiteralSections;
1366 for (const SectionRef &Section : O->sections()) {
1367 DataRefImpl Ref = Section.getRawDataRefImpl();
1368 uint32_t section_type;
1369 if (O->is64Bit()) {
1370 const MachO::section_64 Sec = O->getSection64(Ref);
1371 section_type = Sec.flags & MachO::SECTION_TYPE;
1372 } else {
1373 const MachO::section Sec = O->getSection(Ref);
1374 section_type = Sec.flags & MachO::SECTION_TYPE;
1375 }
1376 if (section_type == MachO::S_CSTRING_LITERALS ||
1377 section_type == MachO::S_4BYTE_LITERALS ||
1378 section_type == MachO::S_8BYTE_LITERALS ||
1379 section_type == MachO::S_16BYTE_LITERALS)
1380 LiteralSections.push_back(Section);
1381 }
1382
1383 // Set the size of the literal pointer.
1384 uint32_t lp_size = O->is64Bit() ? 8 : 4;
1385
Eric Christopher572e03a2015-06-19 01:53:21 +00001386 // Collect the external relocation symbols for the literal pointers.
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001387 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1388 for (const RelocationRef &Reloc : Section.relocations()) {
1389 DataRefImpl Rel;
1390 MachO::any_relocation_info RE;
1391 bool isExtern = false;
1392 Rel = Reloc.getRawDataRefImpl();
1393 RE = O->getRelocation(Rel);
1394 isExtern = O->getPlainRelocationExternal(RE);
1395 if (isExtern) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001396 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001397 symbol_iterator RelocSym = Reloc.getSymbol();
1398 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1399 }
1400 }
1401 array_pod_sort(Relocs.begin(), Relocs.end());
1402
1403 // Dump each literal pointer.
1404 for (uint32_t i = 0; i < sect_size; i += lp_size) {
1405 if (print_addresses) {
1406 if (O->is64Bit())
1407 outs() << format("%016" PRIx64, sect_addr + i) << " ";
1408 else
1409 outs() << format("%08" PRIx64, sect_addr + i) << " ";
1410 }
1411 uint64_t lp;
1412 if (O->is64Bit()) {
1413 memcpy(&lp, sect + i, sizeof(uint64_t));
1414 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1415 sys::swapByteOrder(lp);
1416 } else {
1417 uint32_t li;
1418 memcpy(&li, sect + i, sizeof(uint32_t));
1419 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1420 sys::swapByteOrder(li);
1421 lp = li;
1422 }
1423
1424 // First look for an external relocation entry for this literal pointer.
David Majnemer42531262016-08-12 03:55:06 +00001425 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1426 return P.first == i;
1427 });
David Blaikie33dd45d02015-03-23 18:39:02 +00001428 if (Reloc != Relocs.end()) {
1429 symbol_iterator RelocSym = Reloc->second;
Fangrui Songe7834bd2019-04-07 08:19:55 +00001430 StringRef SymName = unwrapOrError(RelocSym->getName(), O->getFileName());
1431 outs() << "external relocation entry for symbol:" << SymName << "\n";
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001432 continue;
David Blaikie33dd45d02015-03-23 18:39:02 +00001433 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001434
1435 // For local references see what the section the literal pointer points to.
David Majnemer562e8292016-08-12 00:18:03 +00001436 auto Sect = find_if(LiteralSections, [&](const SectionRef &R) {
1437 return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
1438 });
David Blaikie33dd45d02015-03-23 18:39:02 +00001439 if (Sect == LiteralSections.end()) {
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001440 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
David Blaikie33dd45d02015-03-23 18:39:02 +00001441 continue;
1442 }
1443
1444 uint64_t SectAddress = Sect->getAddress();
1445 uint64_t SectSize = Sect->getSize();
1446
1447 StringRef SectName;
1448 Sect->getName(SectName);
1449 DataRefImpl Ref = Sect->getRawDataRefImpl();
1450 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
1451 outs() << SegmentName << ":" << SectName << ":";
1452
1453 uint32_t section_type;
1454 if (O->is64Bit()) {
1455 const MachO::section_64 Sec = O->getSection64(Ref);
1456 section_type = Sec.flags & MachO::SECTION_TYPE;
1457 } else {
1458 const MachO::section Sec = O->getSection(Ref);
1459 section_type = Sec.flags & MachO::SECTION_TYPE;
1460 }
1461
1462 StringRef BytesStr;
1463 Sect->getContents(BytesStr);
1464 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
1465
1466 switch (section_type) {
1467 case MachO::S_CSTRING_LITERALS:
1468 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
1469 i++) {
1470 DumpCstringChar(Contents[i]);
1471 }
1472 outs() << "\n";
1473 break;
1474 case MachO::S_4BYTE_LITERALS:
1475 float f;
1476 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
1477 uint32_t l;
1478 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
1479 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1480 sys::swapByteOrder(f);
1481 sys::swapByteOrder(l);
1482 }
1483 DumpLiteral4(l, f);
1484 break;
1485 case MachO::S_8BYTE_LITERALS: {
1486 double d;
1487 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
1488 uint32_t l0, l1;
1489 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1490 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1491 sizeof(uint32_t));
1492 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1493 sys::swapByteOrder(f);
1494 sys::swapByteOrder(l0);
1495 sys::swapByteOrder(l1);
1496 }
1497 DumpLiteral8(O, l0, l1, d);
1498 break;
1499 }
1500 case MachO::S_16BYTE_LITERALS: {
1501 uint32_t l0, l1, l2, l3;
1502 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1503 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1504 sizeof(uint32_t));
1505 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
1506 sizeof(uint32_t));
1507 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
1508 sizeof(uint32_t));
1509 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1510 sys::swapByteOrder(l0);
1511 sys::swapByteOrder(l1);
1512 sys::swapByteOrder(l2);
1513 sys::swapByteOrder(l3);
1514 }
1515 DumpLiteral16(l0, l1, l2, l3);
1516 break;
1517 }
1518 }
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001519 }
1520}
1521
Kevin Enderby85b7a662018-03-20 20:29:52 +00001522static void DumpInitTermPointerSection(MachOObjectFile *O,
1523 const SectionRef &Section,
1524 const char *sect,
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001525 uint32_t sect_size, uint64_t sect_addr,
1526 SymbolAddressMap *AddrMap,
1527 bool verbose) {
1528 uint32_t stride;
Davide Italiano3eb47e22015-12-15 23:14:21 +00001529 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
Kevin Enderby85b7a662018-03-20 20:29:52 +00001530
1531 // Collect the external relocation symbols for the pointers.
1532 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1533 for (const RelocationRef &Reloc : Section.relocations()) {
1534 DataRefImpl Rel;
1535 MachO::any_relocation_info RE;
1536 bool isExtern = false;
1537 Rel = Reloc.getRawDataRefImpl();
1538 RE = O->getRelocation(Rel);
1539 isExtern = O->getPlainRelocationExternal(RE);
1540 if (isExtern) {
1541 uint64_t RelocOffset = Reloc.getOffset();
1542 symbol_iterator RelocSym = Reloc.getSymbol();
1543 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1544 }
1545 }
1546 array_pod_sort(Relocs.begin(), Relocs.end());
1547
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001548 for (uint32_t i = 0; i < sect_size; i += stride) {
1549 const char *SymbolName = nullptr;
Kevin Enderby85b7a662018-03-20 20:29:52 +00001550 uint64_t p;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001551 if (O->is64Bit()) {
1552 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
1553 uint64_t pointer_value;
1554 memcpy(&pointer_value, sect + i, stride);
1555 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1556 sys::swapByteOrder(pointer_value);
1557 outs() << format("0x%016" PRIx64, pointer_value);
Kevin Enderby85b7a662018-03-20 20:29:52 +00001558 p = pointer_value;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001559 } else {
1560 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
1561 uint32_t pointer_value;
1562 memcpy(&pointer_value, sect + i, stride);
1563 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1564 sys::swapByteOrder(pointer_value);
1565 outs() << format("0x%08" PRIx32, pointer_value);
Kevin Enderby85b7a662018-03-20 20:29:52 +00001566 p = pointer_value;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001567 }
Kevin Enderby85b7a662018-03-20 20:29:52 +00001568 if (verbose) {
1569 // First look for an external relocation entry for this pointer.
1570 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1571 return P.first == i;
1572 });
1573 if (Reloc != Relocs.end()) {
1574 symbol_iterator RelocSym = Reloc->second;
Fangrui Songe7834bd2019-04-07 08:19:55 +00001575 outs() << " " << unwrapOrError(RelocSym->getName(), O->getFileName());
Kevin Enderby85b7a662018-03-20 20:29:52 +00001576 } else {
1577 SymbolName = GuessSymbolName(p, AddrMap);
1578 if (SymbolName)
1579 outs() << " " << SymbolName;
1580 }
1581 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001582 outs() << "\n";
1583 }
1584}
1585
1586static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
1587 uint32_t size, uint64_t addr) {
1588 uint32_t cputype = O->getHeader().cputype;
1589 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
1590 uint32_t j;
1591 for (uint32_t i = 0; i < size; i += j, addr += j) {
1592 if (O->is64Bit())
1593 outs() << format("%016" PRIx64, addr) << "\t";
1594 else
Kevin Enderbyf0640752015-03-13 17:56:32 +00001595 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001596 for (j = 0; j < 16 && i + j < size; j++) {
1597 uint8_t byte_word = *(sect + i + j);
1598 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1599 }
1600 outs() << "\n";
1601 }
1602 } else {
1603 uint32_t j;
1604 for (uint32_t i = 0; i < size; i += j, addr += j) {
1605 if (O->is64Bit())
1606 outs() << format("%016" PRIx64, addr) << "\t";
1607 else
Kevin Enderbyc4930852016-04-27 22:36:18 +00001608 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001609 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1610 j += sizeof(int32_t)) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001611 if (i + j + sizeof(int32_t) <= size) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001612 uint32_t long_word;
1613 memcpy(&long_word, sect + i + j, sizeof(int32_t));
1614 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1615 sys::swapByteOrder(long_word);
1616 outs() << format("%08" PRIx32, long_word) << " ";
1617 } else {
1618 for (uint32_t k = 0; i + j + k < size; k++) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001619 uint8_t byte_word = *(sect + i + j + k);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001620 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1621 }
1622 }
1623 }
1624 outs() << "\n";
1625 }
1626 }
1627}
1628
Kevin Enderby95df54c2015-02-04 01:01:38 +00001629static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1630 StringRef DisSegName, StringRef DisSectName);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001631static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1632 uint32_t size, uint32_t addr);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001633#ifdef HAVE_LIBXAR
1634static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
1635 uint32_t size, bool verbose,
1636 bool PrintXarHeader, bool PrintXarFileHeaders,
1637 std::string XarMemberName);
1638#endif // defined(HAVE_LIBXAR)
Kevin Enderby95df54c2015-02-04 01:01:38 +00001639
1640static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1641 bool verbose) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001642 SymbolAddressMap AddrMap;
1643 if (verbose)
1644 CreateSymbolAddressMap(O, &AddrMap);
1645
Colin LeMahieufcc32762015-07-29 19:08:10 +00001646 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1647 StringRef DumpSection = FilterSections[i];
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001648 std::pair<StringRef, StringRef> DumpSegSectName;
1649 DumpSegSectName = DumpSection.split(',');
1650 StringRef DumpSegName, DumpSectName;
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00001651 if (!DumpSegSectName.second.empty()) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001652 DumpSegName = DumpSegSectName.first;
1653 DumpSectName = DumpSegSectName.second;
1654 } else {
1655 DumpSegName = "";
1656 DumpSectName = DumpSegSectName.first;
1657 }
1658 for (const SectionRef &Section : O->sections()) {
1659 StringRef SectName;
1660 Section.getName(SectName);
1661 DataRefImpl Ref = Section.getRawDataRefImpl();
1662 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1663 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1664 (SectName == DumpSectName)) {
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001665
Kevin Enderby95df54c2015-02-04 01:01:38 +00001666 uint32_t section_flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001667 if (O->is64Bit()) {
1668 const MachO::section_64 Sec = O->getSection64(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001669 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001670
1671 } else {
1672 const MachO::section Sec = O->getSection(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001673 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001674 }
Kevin Enderby95df54c2015-02-04 01:01:38 +00001675 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001676
1677 StringRef BytesStr;
1678 Section.getContents(BytesStr);
1679 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1680 uint32_t sect_size = BytesStr.size();
1681 uint64_t sect_addr = Section.getAddress();
1682
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001683 outs() << "Contents of (" << SegName << "," << SectName
1684 << ") section\n";
1685
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001686 if (verbose) {
Kevin Enderby95df54c2015-02-04 01:01:38 +00001687 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1688 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1689 DisassembleMachO(Filename, O, SegName, SectName);
1690 continue;
1691 }
Kevin Enderbycd66be52015-03-11 22:06:32 +00001692 if (SegName == "__TEXT" && SectName == "__info_plist") {
1693 outs() << sect;
1694 continue;
1695 }
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001696 if (SegName == "__OBJC" && SectName == "__protocol") {
1697 DumpProtocolSection(O, sect, sect_size, sect_addr);
1698 continue;
1699 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001700#ifdef HAVE_LIBXAR
1701 if (SegName == "__LLVM" && SectName == "__bundle") {
1702 DumpBitcodeSection(O, sect, sect_size, verbose, !NoSymbolicOperands,
1703 ArchiveHeaders, "");
1704 continue;
1705 }
1706#endif // defined(HAVE_LIBXAR)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001707 switch (section_type) {
1708 case MachO::S_REGULAR:
1709 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1710 break;
1711 case MachO::S_ZEROFILL:
1712 outs() << "zerofill section and has no contents in the file\n";
1713 break;
Kevin Enderby10ba0412015-02-04 21:38:42 +00001714 case MachO::S_CSTRING_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001715 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001716 break;
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001717 case MachO::S_4BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001718 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001719 break;
1720 case MachO::S_8BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001721 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001722 break;
1723 case MachO::S_16BYTE_LITERALS:
Kevin Enderby0fc11822015-04-01 20:57:01 +00001724 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1725 break;
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001726 case MachO::S_LITERAL_POINTERS:
1727 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001728 !NoLeadingAddr);
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001729 break;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001730 case MachO::S_MOD_INIT_FUNC_POINTERS:
1731 case MachO::S_MOD_TERM_FUNC_POINTERS:
Kevin Enderby85b7a662018-03-20 20:29:52 +00001732 DumpInitTermPointerSection(O, Section, sect, sect_size, sect_addr,
1733 &AddrMap, verbose);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001734 break;
1735 default:
1736 outs() << "Unknown section type ("
1737 << format("0x%08" PRIx32, section_type) << ")\n";
1738 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1739 break;
1740 }
1741 } else {
1742 if (section_type == MachO::S_ZEROFILL)
1743 outs() << "zerofill section and has no contents in the file\n";
1744 else
1745 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1746 }
1747 }
1748 }
1749 }
1750}
1751
Kevin Enderbycd66be52015-03-11 22:06:32 +00001752static void DumpInfoPlistSectionContents(StringRef Filename,
1753 MachOObjectFile *O) {
1754 for (const SectionRef &Section : O->sections()) {
1755 StringRef SectName;
1756 Section.getName(SectName);
1757 DataRefImpl Ref = Section.getRawDataRefImpl();
1758 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1759 if (SegName == "__TEXT" && SectName == "__info_plist") {
Kevin Enderby30cf2e82017-06-20 21:00:25 +00001760 if (!NoLeadingHeaders)
1761 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
Kevin Enderbycd66be52015-03-11 22:06:32 +00001762 StringRef BytesStr;
1763 Section.getContents(BytesStr);
1764 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
Kevin Enderby418659f2017-02-06 21:01:08 +00001765 outs() << format("%.*s", BytesStr.size(), sect) << "\n";
Kevin Enderbycd66be52015-03-11 22:06:32 +00001766 return;
1767 }
1768 }
1769}
1770
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001771// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1772// and if it is and there is a list of architecture flags is specified then
1773// check to make sure this Mach-O file is one of those architectures or all
1774// architectures were specified. If not then an error is generated and this
1775// routine returns false. Else it returns true.
1776static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
David Majnemer91160d82016-10-31 17:11:31 +00001777 auto *MachO = dyn_cast<MachOObjectFile>(O);
1778
1779 if (!MachO || ArchAll || ArchFlags.empty())
1780 return true;
1781
1782 MachO::mach_header H;
1783 MachO::mach_header_64 H_64;
1784 Triple T;
Kevin Enderby59343a92016-12-16 22:54:02 +00001785 const char *McpuDefault, *ArchFlag;
David Majnemer91160d82016-10-31 17:11:31 +00001786 if (MachO->is64Bit()) {
1787 H_64 = MachO->MachOObjectFile::getHeader64();
Kevin Enderby59343a92016-12-16 22:54:02 +00001788 T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype,
1789 &McpuDefault, &ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001790 } else {
1791 H = MachO->MachOObjectFile::getHeader();
Kevin Enderby59343a92016-12-16 22:54:02 +00001792 T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype,
1793 &McpuDefault, &ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001794 }
Kevin Enderby59343a92016-12-16 22:54:02 +00001795 const std::string ArchFlagName(ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001796 if (none_of(ArchFlags, [&](const std::string &Name) {
Kevin Enderby59343a92016-12-16 22:54:02 +00001797 return Name == ArchFlagName;
David Majnemer91160d82016-10-31 17:11:31 +00001798 })) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00001799 WithColor::error(errs(), "llvm-objdump")
1800 << Filename << ": no architecture specified.\n";
David Majnemer91160d82016-10-31 17:11:31 +00001801 return false;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001802 }
1803 return true;
1804}
1805
Kevin Enderby0fc11822015-04-01 20:57:01 +00001806static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1807
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001808// ProcessMachO() is passed a single opened Mach-O file, which may be an
1809// archive member and or in a slice of a universal file. It prints the
1810// the file name and header info and then processes it according to the
1811// command line options.
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001812static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001813 StringRef ArchiveMemberName = StringRef(),
1814 StringRef ArchitectureName = StringRef()) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001815 // If we are doing some processing here on the Mach-O file print the header
1816 // info. And don't print it otherwise like in the case of printing the
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001817 // UniversalHeaders or ArchiveHeaders.
Michael Trenta1703b12017-12-15 17:57:40 +00001818 if (Disassemble || Relocations || PrivateHeaders || ExportsTrie || Rebase ||
1819 Bind || SymbolTable || LazyBind || WeakBind || IndirectSymbols ||
1820 DataInCode || LinkOptHints || DylibsUsed || DylibId || ObjcMetaData ||
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00001821 (!FilterSections.empty())) {
Kevin Enderbyf9d60f02016-11-29 21:43:40 +00001822 if (!NoLeadingHeaders) {
1823 outs() << Name;
1824 if (!ArchiveMemberName.empty())
1825 outs() << '(' << ArchiveMemberName << ')';
1826 if (!ArchitectureName.empty())
1827 outs() << " (architecture " << ArchitectureName << ")";
1828 outs() << ":\n";
1829 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001830 }
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001831 // To use the report_error() form with an ArchiveName and FileName set
1832 // these up based on what is passed for Name and ArchiveMemberName.
1833 StringRef ArchiveName;
1834 StringRef FileName;
1835 if (!ArchiveMemberName.empty()) {
1836 ArchiveName = Name;
1837 FileName = ArchiveMemberName;
1838 } else {
1839 ArchiveName = StringRef();
1840 FileName = Name;
1841 }
1842
1843 // If we need the symbol table to do the operation then check it here to
1844 // produce a good error message as to where the Mach-O file comes from in
1845 // the error message.
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00001846 if (Disassemble || IndirectSymbols || !FilterSections.empty() || UnwindInfo)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001847 if (Error Err = MachOOF->checkSymbolTable())
Fangrui Songe7834bd2019-04-07 08:19:55 +00001848 report_error(std::move(Err), ArchiveName, FileName, ArchitectureName);
1849
Michael Trent7e660212019-01-15 20:41:30 +00001850 if (DisassembleAll) {
1851 for (const SectionRef &Section : MachOOF->sections()) {
1852 StringRef SectName;
1853 Section.getName(SectName);
1854 if (SectName.equals("__text")) {
1855 DataRefImpl Ref = Section.getRawDataRefImpl();
1856 StringRef SegName = MachOOF->getSectionFinalSegmentName(Ref);
1857 DisassembleMachO(FileName, MachOOF, SegName, SectName);
1858 }
1859 }
1860 }
1861 else if (Disassemble) {
Kevin Enderbyaf2999a2017-06-22 19:50:56 +00001862 if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE &&
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00001863 MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64)
Kevin Enderbyaf2999a2017-06-22 19:50:56 +00001864 DisassembleMachO(FileName, MachOOF, "__TEXT_EXEC", "__text");
1865 else
1866 DisassembleMachO(FileName, MachOOF, "__TEXT", "__text");
1867 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001868 if (IndirectSymbols)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001869 PrintIndirectSymbols(MachOOF, !NonVerbose);
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001870 if (DataInCode)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001871 PrintDataInCodeTable(MachOOF, !NonVerbose);
Kevin Enderby9a509442015-01-27 21:28:24 +00001872 if (LinkOptHints)
1873 PrintLinkOptHints(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001874 if (Relocations)
Michael Trenta1703b12017-12-15 17:57:40 +00001875 PrintRelocations(MachOOF, !NonVerbose);
Kevin Enderby98da6132015-01-20 21:47:46 +00001876 if (SectionHeaders)
George Rimar73a27232019-01-15 09:19:18 +00001877 printSectionHeaders(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001878 if (SectionContents)
George Rimar73a27232019-01-15 09:19:18 +00001879 printSectionContents(MachOOF);
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00001880 if (!FilterSections.empty())
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001881 DumpSectionContents(FileName, MachOOF, !NonVerbose);
Kevin Enderbycd66be52015-03-11 22:06:32 +00001882 if (InfoPlist)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001883 DumpInfoPlistSectionContents(FileName, MachOOF);
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001884 if (DylibsUsed)
1885 PrintDylibs(MachOOF, false);
1886 if (DylibId)
1887 PrintDylibs(MachOOF, true);
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001888 if (SymbolTable)
George Rimar73a27232019-01-15 09:19:18 +00001889 printSymbolTable(MachOOF, ArchiveName, ArchitectureName);
Kevin Enderby98da6132015-01-20 21:47:46 +00001890 if (UnwindInfo)
1891 printMachOUnwindInfo(MachOOF);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001892 if (PrivateHeaders) {
1893 printMachOFileHeader(MachOOF);
1894 printMachOLoadCommands(MachOOF);
1895 }
1896 if (FirstPrivateHeader)
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001897 printMachOFileHeader(MachOOF);
Kevin Enderby0fc11822015-04-01 20:57:01 +00001898 if (ObjcMetaData)
1899 printObjcMetaData(MachOOF, !NonVerbose);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001900 if (ExportsTrie)
1901 printExportsTrie(MachOOF);
1902 if (Rebase)
1903 printRebaseTable(MachOOF);
1904 if (Bind)
1905 printBindTable(MachOOF);
1906 if (LazyBind)
1907 printLazyBindTable(MachOOF);
1908 if (WeakBind)
1909 printWeakBindTable(MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001910
1911 if (DwarfDumpType != DIDT_Null) {
Rafael Espindolac398e672017-07-19 22:27:28 +00001912 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001913 // Dump the complete DWARF structure.
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00001914 DIDumpOptions DumpOpts;
1915 DumpOpts.DumpType = DwarfDumpType;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00001916 DICtx->dump(outs(), DumpOpts);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001917 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001918}
1919
Kevin Enderby131d1772015-01-09 19:22:37 +00001920// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1921static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1922 outs() << " cputype (" << cputype << ")\n";
1923 outs() << " cpusubtype (" << cpusubtype << ")\n";
1924}
1925
1926// printCPUType() helps print_fat_headers by printing the cputype and
1927// pusubtype (symbolically for the one's it knows about).
1928static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1929 switch (cputype) {
1930 case MachO::CPU_TYPE_I386:
1931 switch (cpusubtype) {
1932 case MachO::CPU_SUBTYPE_I386_ALL:
1933 outs() << " cputype CPU_TYPE_I386\n";
1934 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1935 break;
1936 default:
1937 printUnknownCPUType(cputype, cpusubtype);
1938 break;
1939 }
1940 break;
1941 case MachO::CPU_TYPE_X86_64:
1942 switch (cpusubtype) {
1943 case MachO::CPU_SUBTYPE_X86_64_ALL:
1944 outs() << " cputype CPU_TYPE_X86_64\n";
1945 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1946 break;
1947 case MachO::CPU_SUBTYPE_X86_64_H:
1948 outs() << " cputype CPU_TYPE_X86_64\n";
1949 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1950 break;
1951 default:
1952 printUnknownCPUType(cputype, cpusubtype);
1953 break;
1954 }
1955 break;
1956 case MachO::CPU_TYPE_ARM:
1957 switch (cpusubtype) {
1958 case MachO::CPU_SUBTYPE_ARM_ALL:
1959 outs() << " cputype CPU_TYPE_ARM\n";
1960 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1961 break;
1962 case MachO::CPU_SUBTYPE_ARM_V4T:
1963 outs() << " cputype CPU_TYPE_ARM\n";
1964 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1965 break;
1966 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1967 outs() << " cputype CPU_TYPE_ARM\n";
1968 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1969 break;
1970 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1971 outs() << " cputype CPU_TYPE_ARM\n";
1972 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1973 break;
1974 case MachO::CPU_SUBTYPE_ARM_V6:
1975 outs() << " cputype CPU_TYPE_ARM\n";
1976 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1977 break;
1978 case MachO::CPU_SUBTYPE_ARM_V6M:
1979 outs() << " cputype CPU_TYPE_ARM\n";
1980 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1981 break;
1982 case MachO::CPU_SUBTYPE_ARM_V7:
1983 outs() << " cputype CPU_TYPE_ARM\n";
1984 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1985 break;
1986 case MachO::CPU_SUBTYPE_ARM_V7EM:
1987 outs() << " cputype CPU_TYPE_ARM\n";
1988 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1989 break;
1990 case MachO::CPU_SUBTYPE_ARM_V7K:
1991 outs() << " cputype CPU_TYPE_ARM\n";
1992 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1993 break;
1994 case MachO::CPU_SUBTYPE_ARM_V7M:
1995 outs() << " cputype CPU_TYPE_ARM\n";
1996 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1997 break;
1998 case MachO::CPU_SUBTYPE_ARM_V7S:
1999 outs() << " cputype CPU_TYPE_ARM\n";
2000 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
2001 break;
2002 default:
2003 printUnknownCPUType(cputype, cpusubtype);
2004 break;
2005 }
2006 break;
2007 case MachO::CPU_TYPE_ARM64:
2008 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2009 case MachO::CPU_SUBTYPE_ARM64_ALL:
2010 outs() << " cputype CPU_TYPE_ARM64\n";
2011 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
2012 break;
2013 default:
2014 printUnknownCPUType(cputype, cpusubtype);
2015 break;
2016 }
2017 break;
2018 default:
2019 printUnknownCPUType(cputype, cpusubtype);
2020 break;
2021 }
2022}
2023
2024static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
2025 bool verbose) {
2026 outs() << "Fat headers\n";
Kevin Enderby606a3382016-06-21 21:55:01 +00002027 if (verbose) {
2028 if (UB->getMagic() == MachO::FAT_MAGIC)
2029 outs() << "fat_magic FAT_MAGIC\n";
2030 else // UB->getMagic() == MachO::FAT_MAGIC_64
2031 outs() << "fat_magic FAT_MAGIC_64\n";
2032 } else
Kevin Enderby131d1772015-01-09 19:22:37 +00002033 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
2034
2035 uint32_t nfat_arch = UB->getNumberOfObjects();
2036 StringRef Buf = UB->getData();
2037 uint64_t size = Buf.size();
2038 uint64_t big_size = sizeof(struct MachO::fat_header) +
2039 nfat_arch * sizeof(struct MachO::fat_arch);
2040 outs() << "nfat_arch " << UB->getNumberOfObjects();
2041 if (nfat_arch == 0)
2042 outs() << " (malformed, contains zero architecture types)\n";
2043 else if (big_size > size)
2044 outs() << " (malformed, architectures past end of file)\n";
2045 else
2046 outs() << "\n";
2047
2048 for (uint32_t i = 0; i < nfat_arch; ++i) {
2049 MachOUniversalBinary::ObjectForArch OFA(UB, i);
2050 uint32_t cputype = OFA.getCPUType();
2051 uint32_t cpusubtype = OFA.getCPUSubType();
2052 outs() << "architecture ";
2053 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
2054 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
2055 uint32_t other_cputype = other_OFA.getCPUType();
2056 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
Kevin Enderby0512bd72015-01-09 21:55:03 +00002057 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
Kevin Enderby131d1772015-01-09 19:22:37 +00002058 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
Kevin Enderby0512bd72015-01-09 21:55:03 +00002059 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00002060 outs() << "(illegal duplicate architecture) ";
2061 break;
Kevin Enderby0512bd72015-01-09 21:55:03 +00002062 }
Kevin Enderby131d1772015-01-09 19:22:37 +00002063 }
2064 if (verbose) {
Kevin Enderby59343a92016-12-16 22:54:02 +00002065 outs() << OFA.getArchFlagName() << "\n";
Kevin Enderby131d1772015-01-09 19:22:37 +00002066 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2067 } else {
2068 outs() << i << "\n";
2069 outs() << " cputype " << cputype << "\n";
2070 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
2071 << "\n";
2072 }
2073 if (verbose &&
2074 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
2075 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
2076 else
2077 outs() << " capabilities "
2078 << format("0x%" PRIx32,
2079 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
2080 outs() << " offset " << OFA.getOffset();
2081 if (OFA.getOffset() > size)
2082 outs() << " (past end of file)";
2083 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
2084 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
2085 outs() << "\n";
2086 outs() << " size " << OFA.getSize();
2087 big_size = OFA.getOffset() + OFA.getSize();
2088 if (big_size > size)
2089 outs() << " (past end of file)";
2090 outs() << "\n";
2091 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
2092 << ")\n";
2093 }
2094}
2095
Kevin Enderby6524bd82016-07-19 20:47:07 +00002096static void printArchiveChild(StringRef Filename, const Archive::Child &C,
2097 bool verbose, bool print_offset,
2098 StringRef ArchitectureName = StringRef()) {
Kevin Enderby13023a12015-01-15 23:19:11 +00002099 if (print_offset)
2100 outs() << C.getChildOffset() << "\t";
Fangrui Songe7834bd2019-04-07 08:19:55 +00002101 sys::fs::perms Mode =
2102 unwrapOrError(C.getAccessMode(), Filename, C, ArchitectureName);
Kevin Enderby13023a12015-01-15 23:19:11 +00002103 if (verbose) {
2104 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
2105 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
2106 outs() << "-";
Davide Italianobb9a6cc2015-09-07 20:47:03 +00002107 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
2108 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
2109 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
2110 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
2111 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
2112 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
2113 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
2114 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
2115 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
Kevin Enderby13023a12015-01-15 23:19:11 +00002116 } else {
2117 outs() << format("0%o ", Mode);
2118 }
2119
Fangrui Songe7834bd2019-04-07 08:19:55 +00002120 outs() << format(
2121 "%3d/%-3d %5" PRId64 " ",
2122 unwrapOrError(C.getUID(), Filename, C, ArchitectureName),
2123 unwrapOrError(C.getGID(), Filename, C, ArchitectureName),
2124 unwrapOrError(C.getRawSize(), Filename, C, ArchitectureName));
Kevin Enderby13023a12015-01-15 23:19:11 +00002125
2126 StringRef RawLastModified = C.getRawLastModified();
2127 if (verbose) {
2128 unsigned Seconds;
2129 if (RawLastModified.getAsInteger(10, Seconds))
Vedant Kumar4031d9f2016-08-03 19:02:50 +00002130 outs() << "(date: \"" << RawLastModified
2131 << "\" contains non-decimal chars) ";
Kevin Enderby13023a12015-01-15 23:19:11 +00002132 else {
2133 // Since cime(3) returns a 26 character string of the form:
2134 // "Sun Sep 16 01:03:52 1973\n\0"
2135 // just print 24 characters.
2136 time_t t = Seconds;
2137 outs() << format("%.24s ", ctime(&t));
2138 }
2139 } else {
2140 outs() << RawLastModified << " ";
2141 }
2142
2143 if (verbose) {
Kevin Enderbyf4586032016-07-29 17:44:13 +00002144 Expected<StringRef> NameOrErr = C.getName();
2145 if (!NameOrErr) {
2146 consumeError(NameOrErr.takeError());
Fangrui Songe7834bd2019-04-07 08:19:55 +00002147 outs() << unwrapOrError(C.getRawName(), Filename, C, ArchitectureName)
2148 << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00002149 } else {
2150 StringRef Name = NameOrErr.get();
2151 outs() << Name << "\n";
2152 }
2153 } else {
Fangrui Songe7834bd2019-04-07 08:19:55 +00002154 outs() << unwrapOrError(C.getRawName(), Filename, C, ArchitectureName)
2155 << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00002156 }
2157}
2158
Kevin Enderby6524bd82016-07-19 20:47:07 +00002159static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
2160 bool print_offset,
2161 StringRef ArchitectureName = StringRef()) {
Mehdi Amini41af4302016-11-11 04:28:40 +00002162 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00002163 for (const auto &C : A->children(Err, false))
Kevin Enderby6524bd82016-07-19 20:47:07 +00002164 printArchiveChild(Filename, C, verbose, print_offset, ArchitectureName);
2165
Lang Hamesfc209622016-07-14 02:24:01 +00002166 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +00002167 report_error(std::move(Err), StringRef(), Filename, ArchitectureName);
Kevin Enderby13023a12015-01-15 23:19:11 +00002168}
2169
Dave Lee3fb120f2018-08-03 00:06:38 +00002170static bool ValidateArchFlags() {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002171 // Check for -arch all and verifiy the -arch flags are valid.
2172 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2173 if (ArchFlags[i] == "all") {
2174 ArchAll = true;
2175 } else {
2176 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002177 WithColor::error(errs(), "llvm-objdump")
2178 << "unknown architecture named '" + ArchFlags[i] +
2179 "'for the -arch option\n";
Dave Lee3fb120f2018-08-03 00:06:38 +00002180 return false;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002181 }
2182 }
2183 }
Dave Lee3fb120f2018-08-03 00:06:38 +00002184 return true;
2185}
2186
2187// ParseInputMachO() parses the named Mach-O file in Filename and handles the
2188// -arch flags selecting just those slices as specified by them and also parses
2189// archive files. Then for each individual Mach-O file ProcessMachO() is
2190// called to process the file based on the command line options.
George Rimar73a27232019-01-15 09:19:18 +00002191void llvm::parseInputMachO(StringRef Filename) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002192 if (!ValidateArchFlags())
2193 return;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002194
2195 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00002196 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
Kevin Enderby98898f22017-01-30 20:53:17 +00002197 if (!BinaryOrErr) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00002198 if (Error E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError()))
2199 report_error(std::move(E), Filename);
Kevin Enderby98898f22017-01-30 20:53:17 +00002200 else
2201 outs() << Filename << ": is not an object file\n";
2202 return;
2203 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002204 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00002205
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002206 if (Archive *A = dyn_cast<Archive>(&Bin)) {
2207 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00002208 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00002209 printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets);
2210
Mehdi Amini41af4302016-11-11 04:28:40 +00002211 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00002212 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002213 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2214 if (!ChildOrErr) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00002215 if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2216 report_error(std::move(E), Filename, C);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002217 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002218 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002219 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2220 if (!checkMachOAndArchFlags(O, Filename))
2221 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002222 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002223 }
2224 }
Lang Hamesfc209622016-07-14 02:24:01 +00002225 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +00002226 report_error(std::move(Err), Filename);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002227 return;
2228 }
2229 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
George Rimar73a27232019-01-15 09:19:18 +00002230 parseInputMachO(UB);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002231 return;
2232 }
2233 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
2234 if (!checkMachOAndArchFlags(O, Filename))
2235 return;
Dave Lee3fb120f2018-08-03 00:06:38 +00002236 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002237 ProcessMachO(Filename, MachOOF);
Dave Lee3fb120f2018-08-03 00:06:38 +00002238 else
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002239 WithColor::error(errs(), "llvm-objdump")
2240 << Filename << "': "
2241 << "object is not a Mach-O file type.\n";
Davide Italiano25d84582016-01-13 04:11:36 +00002242 return;
2243 }
2244 llvm_unreachable("Input object can't be invalid at this point");
Rafael Espindola9b709252013-04-13 01:45:40 +00002245}
2246
George Rimar73a27232019-01-15 09:19:18 +00002247void llvm::parseInputMachO(MachOUniversalBinary *UB) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002248 if (!ValidateArchFlags())
2249 return;
2250
2251 auto Filename = UB->getFileName();
2252
2253 if (UniversalHeaders)
2254 printMachOUniversalHeaders(UB, !NonVerbose);
2255
2256 // If we have a list of architecture flags specified dump only those.
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00002257 if (!ArchAll && !ArchFlags.empty()) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002258 // Look for a slice in the universal binary that matches each ArchFlag.
2259 bool ArchFound;
2260 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2261 ArchFound = false;
2262 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2263 E = UB->end_objects();
2264 I != E; ++I) {
2265 if (ArchFlags[i] == I->getArchFlagName()) {
2266 ArchFound = true;
2267 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
2268 I->getAsObjectFile();
2269 std::string ArchitectureName = "";
2270 if (ArchFlags.size() > 1)
2271 ArchitectureName = I->getArchFlagName();
2272 if (ObjOrErr) {
2273 ObjectFile &O = *ObjOrErr.get();
2274 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2275 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Fangrui Songe7834bd2019-04-07 08:19:55 +00002276 } else if (Error E = isNotObjectErrorInvalidFileType(
2277 ObjOrErr.takeError())) {
2278 report_error(std::move(E), Filename, StringRef(), ArchitectureName);
Dave Lee3fb120f2018-08-03 00:06:38 +00002279 continue;
2280 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Fangrui Songe7834bd2019-04-07 08:19:55 +00002281 I->getAsArchive()) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002282 std::unique_ptr<Archive> &A = *AOrErr;
2283 outs() << "Archive : " << Filename;
2284 if (!ArchitectureName.empty())
2285 outs() << " (architecture " << ArchitectureName << ")";
2286 outs() << "\n";
2287 if (ArchiveHeaders)
2288 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2289 ArchiveMemberOffsets, ArchitectureName);
2290 Error Err = Error::success();
2291 for (auto &C : A->children(Err)) {
2292 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2293 if (!ChildOrErr) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00002294 if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2295 report_error(std::move(E), Filename, C, ArchitectureName);
Dave Lee3fb120f2018-08-03 00:06:38 +00002296 continue;
2297 }
2298 if (MachOObjectFile *O =
2299 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2300 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
2301 }
2302 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +00002303 report_error(std::move(Err), Filename);
Dave Lee3fb120f2018-08-03 00:06:38 +00002304 } else {
2305 consumeError(AOrErr.takeError());
2306 error("Mach-O universal file: " + Filename + " for " +
2307 "architecture " + StringRef(I->getArchFlagName()) +
2308 " is not a Mach-O file or an archive file");
2309 }
2310 }
2311 }
2312 if (!ArchFound) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002313 WithColor::error(errs(), "llvm-objdump")
2314 << "file: " + Filename + " does not contain "
2315 << "architecture: " + ArchFlags[i] + "\n";
Dave Lee3fb120f2018-08-03 00:06:38 +00002316 return;
2317 }
2318 }
2319 return;
2320 }
2321 // No architecture flags were specified so if this contains a slice that
2322 // matches the host architecture dump only that.
2323 if (!ArchAll) {
2324 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2325 E = UB->end_objects();
2326 I != E; ++I) {
2327 if (MachOObjectFile::getHostArch().getArchName() ==
2328 I->getArchFlagName()) {
2329 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2330 std::string ArchiveName;
2331 ArchiveName.clear();
2332 if (ObjOrErr) {
2333 ObjectFile &O = *ObjOrErr.get();
2334 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2335 ProcessMachO(Filename, MachOOF);
Fangrui Songe7834bd2019-04-07 08:19:55 +00002336 } else if (Error E =
2337 isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
2338 report_error(std::move(E), Filename);
Dave Lee3fb120f2018-08-03 00:06:38 +00002339 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Fangrui Songe7834bd2019-04-07 08:19:55 +00002340 I->getAsArchive()) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002341 std::unique_ptr<Archive> &A = *AOrErr;
2342 outs() << "Archive : " << Filename << "\n";
2343 if (ArchiveHeaders)
2344 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2345 ArchiveMemberOffsets);
2346 Error Err = Error::success();
2347 for (auto &C : A->children(Err)) {
2348 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2349 if (!ChildOrErr) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00002350 if (Error E =
2351 isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2352 report_error(std::move(E), Filename, C);
Dave Lee3fb120f2018-08-03 00:06:38 +00002353 continue;
2354 }
2355 if (MachOObjectFile *O =
2356 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2357 ProcessMachO(Filename, O, O->getFileName());
2358 }
2359 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +00002360 report_error(std::move(Err), Filename);
Dave Lee3fb120f2018-08-03 00:06:38 +00002361 } else {
2362 consumeError(AOrErr.takeError());
2363 error("Mach-O universal file: " + Filename + " for architecture " +
2364 StringRef(I->getArchFlagName()) +
2365 " is not a Mach-O file or an archive file");
2366 }
2367 return;
2368 }
2369 }
2370 }
2371 // Either all architectures have been specified or none have been specified
2372 // and this does not contain the host architecture so dump all the slices.
2373 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
2374 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2375 E = UB->end_objects();
2376 I != E; ++I) {
2377 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2378 std::string ArchitectureName = "";
2379 if (moreThanOneArch)
2380 ArchitectureName = I->getArchFlagName();
2381 if (ObjOrErr) {
2382 ObjectFile &Obj = *ObjOrErr.get();
2383 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
2384 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Fangrui Songe7834bd2019-04-07 08:19:55 +00002385 } else if (Error E =
2386 isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
2387 report_error(std::move(E), StringRef(), Filename, ArchitectureName);
2388 } else if (Expected<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002389 std::unique_ptr<Archive> &A = *AOrErr;
2390 outs() << "Archive : " << Filename;
2391 if (!ArchitectureName.empty())
2392 outs() << " (architecture " << ArchitectureName << ")";
2393 outs() << "\n";
2394 if (ArchiveHeaders)
2395 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2396 ArchiveMemberOffsets, ArchitectureName);
2397 Error Err = Error::success();
2398 for (auto &C : A->children(Err)) {
2399 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2400 if (!ChildOrErr) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00002401 if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2402 report_error(std::move(E), Filename, C, ArchitectureName);
Dave Lee3fb120f2018-08-03 00:06:38 +00002403 continue;
2404 }
2405 if (MachOObjectFile *O =
2406 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2407 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
2408 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
2409 ArchitectureName);
2410 }
2411 }
2412 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +00002413 report_error(std::move(Err), Filename);
Dave Lee3fb120f2018-08-03 00:06:38 +00002414 } else {
2415 consumeError(AOrErr.takeError());
2416 error("Mach-O universal file: " + Filename + " for architecture " +
2417 StringRef(I->getArchFlagName()) +
2418 " is not a Mach-O file or an archive file");
2419 }
2420 }
2421}
2422
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002423// The block of info used by the Symbolizer call backs.
2424struct DisassembleInfo {
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002425 DisassembleInfo(MachOObjectFile *O, SymbolAddressMap *AddrMap,
2426 std::vector<SectionRef> *Sections, bool verbose)
2427 : verbose(verbose), O(O), AddrMap(AddrMap), Sections(Sections) {}
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002428 bool verbose;
2429 MachOObjectFile *O;
2430 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00002431 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002432 std::vector<SectionRef> *Sections;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002433 const char *class_name = nullptr;
2434 const char *selector_name = nullptr;
David Blaikie0e550682018-02-20 18:48:51 +00002435 std::unique_ptr<char[]> method = nullptr;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002436 char *demangled_name = nullptr;
2437 uint64_t adrp_addr = 0;
2438 uint32_t adrp_inst = 0;
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00002439 std::unique_ptr<SymbolAddressMap> bindtable;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002440 uint32_t depth = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002441};
2442
2443// SymbolizerGetOpInfo() is the operand information call back function.
2444// This is called to get the symbolic information for operand(s) of an
2445// instruction when it is being done. This routine does this from
2446// the relocation information, symbol table, etc. That block of information
2447// is a pointer to the struct DisassembleInfo that was passed when the
2448// disassembler context was created and passed to back to here when
2449// called back by the disassembler for instruction operands that could have
2450// relocation information. The address of the instruction containing operand is
2451// at the Pc parameter. The immediate value the operand has is passed in
2452// op_info->Value and is at Offset past the start of the instruction and has a
2453// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
2454// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
2455// names and addends of the symbolic expression to add for the operand. The
2456// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
2457// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002458static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
2459 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002460 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2461 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002462 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002463
2464 // Make sure all fields returned are zero if we don't set them.
2465 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
2466 op_info->Value = value;
2467
2468 // If the TagType is not the value 1 which it code knows about or if no
2469 // verbose symbolic information is wanted then just return 0, indicating no
2470 // information is being returned.
David Blaikie33dd45d02015-03-23 18:39:02 +00002471 if (TagType != 1 || !info->verbose)
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002472 return 0;
2473
2474 unsigned int Arch = info->O->getArch();
2475 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002476 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2477 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002478 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2479 // TODO:
2480 // Search the external relocation entries of a fully linked image
2481 // (if any) for an entry that matches this segment offset.
2482 // uint32_t seg_offset = (Pc + Offset);
2483 return 0;
2484 }
2485 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2486 // for an entry for this section offset.
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002487 uint32_t sect_addr = info->S.getAddress();
2488 uint32_t sect_offset = (Pc + Offset) - sect_addr;
2489 bool reloc_found = false;
2490 DataRefImpl Rel;
2491 MachO::any_relocation_info RE;
2492 bool isExtern = false;
2493 SymbolRef Symbol;
2494 bool r_scattered = false;
2495 uint32_t r_value, pair_r_value, r_type;
2496 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002497 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002498 if (RelocOffset == sect_offset) {
2499 Rel = Reloc.getRawDataRefImpl();
2500 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00002501 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002502 r_scattered = info->O->isRelocationScattered(RE);
2503 if (r_scattered) {
2504 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002505 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2506 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
2507 DataRefImpl RelNext = Rel;
2508 info->O->moveRelocationNext(RelNext);
2509 MachO::any_relocation_info RENext;
2510 RENext = info->O->getRelocation(RelNext);
2511 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002512 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002513 else
2514 return 0;
2515 }
2516 } else {
2517 isExtern = info->O->getPlainRelocationExternal(RE);
2518 if (isExtern) {
2519 symbol_iterator RelocSym = Reloc.getSymbol();
2520 Symbol = *RelocSym;
2521 }
2522 }
2523 reloc_found = true;
2524 break;
2525 }
2526 }
2527 if (reloc_found && isExtern) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002528 op_info->AddSymbol.Present = 1;
Fangrui Songe7834bd2019-04-07 08:19:55 +00002529 op_info->AddSymbol.Name =
2530 unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002531 // For i386 extern relocation entries the value in the instruction is
2532 // the offset from the symbol, and value is already set in op_info->Value.
2533 return 1;
2534 }
2535 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2536 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002537 const char *add = GuessSymbolName(r_value, info->AddrMap);
2538 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002539 uint32_t offset = value - (r_value - pair_r_value);
2540 op_info->AddSymbol.Present = 1;
2541 if (add != nullptr)
2542 op_info->AddSymbol.Name = add;
2543 else
2544 op_info->AddSymbol.Value = r_value;
2545 op_info->SubtractSymbol.Present = 1;
2546 if (sub != nullptr)
2547 op_info->SubtractSymbol.Name = sub;
2548 else
2549 op_info->SubtractSymbol.Value = pair_r_value;
2550 op_info->Value = offset;
2551 return 1;
2552 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002553 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002554 }
2555 if (Arch == Triple::x86_64) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002556 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2557 return 0;
Kevin Enderbyabf10f22017-06-22 17:41:22 +00002558 // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external
2559 // relocation entries of a linked image (if any) for an entry that matches
2560 // this segment offset.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002561 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
Kevin Enderbyabf10f22017-06-22 17:41:22 +00002562 uint64_t seg_offset = Pc + Offset;
2563 bool reloc_found = false;
2564 DataRefImpl Rel;
2565 MachO::any_relocation_info RE;
2566 bool isExtern = false;
2567 SymbolRef Symbol;
2568 for (const RelocationRef &Reloc : info->O->external_relocations()) {
2569 uint64_t RelocOffset = Reloc.getOffset();
2570 if (RelocOffset == seg_offset) {
2571 Rel = Reloc.getRawDataRefImpl();
2572 RE = info->O->getRelocation(Rel);
2573 // external relocation entries should always be external.
2574 isExtern = info->O->getPlainRelocationExternal(RE);
2575 if (isExtern) {
2576 symbol_iterator RelocSym = Reloc.getSymbol();
2577 Symbol = *RelocSym;
2578 }
2579 reloc_found = true;
2580 break;
2581 }
2582 }
2583 if (reloc_found && isExtern) {
2584 // The Value passed in will be adjusted by the Pc if the instruction
2585 // adds the Pc. But for x86_64 external relocation entries the Value
2586 // is the offset from the external symbol.
2587 if (info->O->getAnyRelocationPCRel(RE))
2588 op_info->Value -= Pc + Offset + Size;
Fangrui Songe7834bd2019-04-07 08:19:55 +00002589 const char *name =
2590 unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
Kevin Enderbyabf10f22017-06-22 17:41:22 +00002591 op_info->AddSymbol.Present = 1;
2592 op_info->AddSymbol.Name = name;
2593 return 1;
2594 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002595 return 0;
2596 }
2597 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2598 // for an entry for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00002599 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002600 uint64_t sect_offset = (Pc + Offset) - sect_addr;
2601 bool reloc_found = false;
2602 DataRefImpl Rel;
2603 MachO::any_relocation_info RE;
2604 bool isExtern = false;
2605 SymbolRef Symbol;
2606 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002607 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002608 if (RelocOffset == sect_offset) {
2609 Rel = Reloc.getRawDataRefImpl();
2610 RE = info->O->getRelocation(Rel);
2611 // NOTE: Scattered relocations don't exist on x86_64.
2612 isExtern = info->O->getPlainRelocationExternal(RE);
2613 if (isExtern) {
2614 symbol_iterator RelocSym = Reloc.getSymbol();
2615 Symbol = *RelocSym;
2616 }
2617 reloc_found = true;
2618 break;
2619 }
2620 }
2621 if (reloc_found && isExtern) {
2622 // The Value passed in will be adjusted by the Pc if the instruction
2623 // adds the Pc. But for x86_64 external relocation entries the Value
2624 // is the offset from the external symbol.
2625 if (info->O->getAnyRelocationPCRel(RE))
2626 op_info->Value -= Pc + Offset + Size;
Fangrui Songe7834bd2019-04-07 08:19:55 +00002627 const char *name =
2628 unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002629 unsigned Type = info->O->getAnyRelocationType(RE);
2630 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
2631 DataRefImpl RelNext = Rel;
2632 info->O->moveRelocationNext(RelNext);
2633 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2634 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
2635 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
2636 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
2637 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
2638 op_info->SubtractSymbol.Present = 1;
2639 op_info->SubtractSymbol.Name = name;
2640 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
2641 Symbol = *RelocSymNext;
Fangrui Songe7834bd2019-04-07 08:19:55 +00002642 name = unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002643 }
2644 }
2645 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
2646 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
2647 op_info->AddSymbol.Present = 1;
2648 op_info->AddSymbol.Name = name;
2649 return 1;
2650 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002651 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002652 }
2653 if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002654 if (Offset != 0 || (Size != 4 && Size != 2))
2655 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002656 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2657 // TODO:
2658 // Search the external relocation entries of a fully linked image
2659 // (if any) for an entry that matches this segment offset.
2660 // uint32_t seg_offset = (Pc + Offset);
2661 return 0;
2662 }
2663 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2664 // for an entry for this section offset.
Kevin Enderby930fdc72014-11-06 19:00:13 +00002665 uint32_t sect_addr = info->S.getAddress();
2666 uint32_t sect_offset = (Pc + Offset) - sect_addr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002667 DataRefImpl Rel;
2668 MachO::any_relocation_info RE;
2669 bool isExtern = false;
2670 SymbolRef Symbol;
2671 bool r_scattered = false;
2672 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
David Blaikie33dd45d02015-03-23 18:39:02 +00002673 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002674 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2675 uint64_t RelocOffset = Reloc.getOffset();
2676 return RelocOffset == sect_offset;
2677 });
David Blaikie33dd45d02015-03-23 18:39:02 +00002678
2679 if (Reloc == info->S.relocations().end())
2680 return 0;
2681
2682 Rel = Reloc->getRawDataRefImpl();
2683 RE = info->O->getRelocation(Rel);
2684 r_length = info->O->getAnyRelocationLength(RE);
2685 r_scattered = info->O->isRelocationScattered(RE);
2686 if (r_scattered) {
2687 r_value = info->O->getScatteredRelocationValue(RE);
2688 r_type = info->O->getScatteredRelocationType(RE);
2689 } else {
2690 r_type = info->O->getAnyRelocationType(RE);
2691 isExtern = info->O->getPlainRelocationExternal(RE);
2692 if (isExtern) {
2693 symbol_iterator RelocSym = Reloc->getSymbol();
2694 Symbol = *RelocSym;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002695 }
2696 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002697 if (r_type == MachO::ARM_RELOC_HALF ||
2698 r_type == MachO::ARM_RELOC_SECTDIFF ||
2699 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
2700 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2701 DataRefImpl RelNext = Rel;
2702 info->O->moveRelocationNext(RelNext);
2703 MachO::any_relocation_info RENext;
2704 RENext = info->O->getRelocation(RelNext);
2705 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2706 if (info->O->isRelocationScattered(RENext))
2707 pair_r_value = info->O->getScatteredRelocationValue(RENext);
2708 }
2709
2710 if (isExtern) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00002711 const char *name =
2712 unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
Kevin Enderby930fdc72014-11-06 19:00:13 +00002713 op_info->AddSymbol.Present = 1;
2714 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002715 switch (r_type) {
2716 case MachO::ARM_RELOC_HALF:
2717 if ((r_length & 0x1) == 1) {
2718 op_info->Value = value << 16 | other_half;
2719 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2720 } else {
2721 op_info->Value = other_half << 16 | value;
2722 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00002723 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002724 break;
2725 default:
2726 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002727 }
2728 return 1;
2729 }
2730 // If we have a branch that is not an external relocation entry then
2731 // return 0 so the code in tryAddingSymbolicOperand() can use the
2732 // SymbolLookUp call back with the branch target address to look up the
Simon Pilgrimdae11f72016-11-20 13:31:13 +00002733 // symbol and possibility add an annotation for a symbol stub.
David Blaikie33dd45d02015-03-23 18:39:02 +00002734 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2735 r_type == MachO::ARM_THUMB_RELOC_BR22))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002736 return 0;
2737
2738 uint32_t offset = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002739 if (r_type == MachO::ARM_RELOC_HALF ||
2740 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2741 if ((r_length & 0x1) == 1)
2742 value = value << 16 | other_half;
2743 else
2744 value = other_half << 16 | value;
2745 }
2746 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2747 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2748 offset = value - r_value;
2749 value = r_value;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002750 }
2751
David Blaikie33dd45d02015-03-23 18:39:02 +00002752 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002753 if ((r_length & 0x1) == 1)
2754 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2755 else
2756 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002757 const char *add = GuessSymbolName(r_value, info->AddrMap);
2758 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002759 int32_t offset = value - (r_value - pair_r_value);
2760 op_info->AddSymbol.Present = 1;
2761 if (add != nullptr)
2762 op_info->AddSymbol.Name = add;
2763 else
2764 op_info->AddSymbol.Value = r_value;
2765 op_info->SubtractSymbol.Present = 1;
2766 if (sub != nullptr)
2767 op_info->SubtractSymbol.Name = sub;
2768 else
2769 op_info->SubtractSymbol.Value = pair_r_value;
2770 op_info->Value = offset;
2771 return 1;
2772 }
2773
Kevin Enderby930fdc72014-11-06 19:00:13 +00002774 op_info->AddSymbol.Present = 1;
2775 op_info->Value = offset;
David Blaikie33dd45d02015-03-23 18:39:02 +00002776 if (r_type == MachO::ARM_RELOC_HALF) {
2777 if ((r_length & 0x1) == 1)
2778 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2779 else
2780 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002781 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002782 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002783 if (add != nullptr) {
2784 op_info->AddSymbol.Name = add;
2785 return 1;
2786 }
2787 op_info->AddSymbol.Value = value;
2788 return 1;
David Blaikie33dd45d02015-03-23 18:39:02 +00002789 }
2790 if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002791 if (Offset != 0 || Size != 4)
2792 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002793 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2794 // TODO:
2795 // Search the external relocation entries of a fully linked image
2796 // (if any) for an entry that matches this segment offset.
2797 // uint64_t seg_offset = (Pc + Offset);
2798 return 0;
2799 }
2800 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2801 // for an entry for this section offset.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002802 uint64_t sect_addr = info->S.getAddress();
2803 uint64_t sect_offset = (Pc + Offset) - sect_addr;
David Blaikie33dd45d02015-03-23 18:39:02 +00002804 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002805 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2806 uint64_t RelocOffset = Reloc.getOffset();
2807 return RelocOffset == sect_offset;
2808 });
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002809
David Blaikie33dd45d02015-03-23 18:39:02 +00002810 if (Reloc == info->S.relocations().end())
2811 return 0;
2812
2813 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2814 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2815 uint32_t r_type = info->O->getAnyRelocationType(RE);
2816 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2817 DataRefImpl RelNext = Rel;
2818 info->O->moveRelocationNext(RelNext);
2819 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2820 if (value == 0) {
2821 value = info->O->getPlainRelocationSymbolNum(RENext);
2822 op_info->Value = value;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002823 }
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002824 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002825 // NOTE: Scattered relocations don't exist on arm64.
2826 if (!info->O->getPlainRelocationExternal(RE))
2827 return 0;
Fangrui Songe7834bd2019-04-07 08:19:55 +00002828 const char *name =
2829 unwrapOrError(Reloc->getSymbol()->getName(), info->O->getFileName())
2830 .data();
David Blaikie33dd45d02015-03-23 18:39:02 +00002831 op_info->AddSymbol.Present = 1;
2832 op_info->AddSymbol.Name = name;
2833
2834 switch (r_type) {
2835 case MachO::ARM64_RELOC_PAGE21:
2836 /* @page */
2837 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2838 break;
2839 case MachO::ARM64_RELOC_PAGEOFF12:
2840 /* @pageoff */
2841 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2842 break;
2843 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2844 /* @gotpage */
2845 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2846 break;
2847 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2848 /* @gotpageoff */
2849 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2850 break;
2851 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2852 /* @tvlppage is not implemented in llvm-mc */
2853 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2854 break;
2855 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2856 /* @tvlppageoff is not implemented in llvm-mc */
2857 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2858 break;
2859 default:
2860 case MachO::ARM64_RELOC_BRANCH26:
2861 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2862 break;
2863 }
2864 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002865 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002866 return 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002867}
2868
Kevin Enderbybf246f52014-09-24 23:08:22 +00002869// GuessCstringPointer is passed the address of what might be a pointer to a
2870// literal string in a cstring section. If that address is in a cstring section
2871// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002872static const char *GuessCstringPointer(uint64_t ReferenceValue,
2873 struct DisassembleInfo *info) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002874 for (const auto &Load : info->O->load_commands()) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002875 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2876 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2877 for (unsigned J = 0; J < Seg.nsects; ++J) {
2878 MachO::section_64 Sec = info->O->getSection64(Load, J);
2879 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2880 if (section_type == MachO::S_CSTRING_LITERALS &&
2881 ReferenceValue >= Sec.addr &&
2882 ReferenceValue < Sec.addr + Sec.size) {
2883 uint64_t sect_offset = ReferenceValue - Sec.addr;
2884 uint64_t object_offset = Sec.offset + sect_offset;
2885 StringRef MachOContents = info->O->getData();
2886 uint64_t object_size = MachOContents.size();
2887 const char *object_addr = (const char *)MachOContents.data();
2888 if (object_offset < object_size) {
2889 const char *name = object_addr + object_offset;
2890 return name;
2891 } else {
2892 return nullptr;
2893 }
2894 }
2895 }
2896 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2897 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2898 for (unsigned J = 0; J < Seg.nsects; ++J) {
2899 MachO::section Sec = info->O->getSection(Load, J);
2900 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2901 if (section_type == MachO::S_CSTRING_LITERALS &&
2902 ReferenceValue >= Sec.addr &&
2903 ReferenceValue < Sec.addr + Sec.size) {
2904 uint64_t sect_offset = ReferenceValue - Sec.addr;
2905 uint64_t object_offset = Sec.offset + sect_offset;
2906 StringRef MachOContents = info->O->getData();
2907 uint64_t object_size = MachOContents.size();
2908 const char *object_addr = (const char *)MachOContents.data();
2909 if (object_offset < object_size) {
2910 const char *name = object_addr + object_offset;
2911 return name;
2912 } else {
2913 return nullptr;
2914 }
2915 }
2916 }
2917 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002918 }
2919 return nullptr;
2920}
2921
Kevin Enderby85974882014-09-26 22:20:44 +00002922// GuessIndirectSymbol returns the name of the indirect symbol for the
2923// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2924// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2925// symbol name being referenced by the stub or pointer.
2926static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2927 struct DisassembleInfo *info) {
Kevin Enderby85974882014-09-26 22:20:44 +00002928 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2929 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002930 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby85974882014-09-26 22:20:44 +00002931 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2932 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2933 for (unsigned J = 0; J < Seg.nsects; ++J) {
2934 MachO::section_64 Sec = info->O->getSection64(Load, J);
2935 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2936 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2937 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2938 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2939 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2940 section_type == MachO::S_SYMBOL_STUBS) &&
2941 ReferenceValue >= Sec.addr &&
2942 ReferenceValue < Sec.addr + Sec.size) {
2943 uint32_t stride;
2944 if (section_type == MachO::S_SYMBOL_STUBS)
2945 stride = Sec.reserved2;
2946 else
2947 stride = 8;
2948 if (stride == 0)
2949 return nullptr;
2950 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2951 if (index < Dysymtab.nindirectsyms) {
2952 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002953 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002954 if (indirect_symbol < Symtab.nsyms) {
2955 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
Fangrui Songe7834bd2019-04-07 08:19:55 +00002956 return unwrapOrError(Sym->getName(), info->O->getFileName())
2957 .data();
Kevin Enderby85974882014-09-26 22:20:44 +00002958 }
2959 }
2960 }
2961 }
2962 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2963 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2964 for (unsigned J = 0; J < Seg.nsects; ++J) {
2965 MachO::section Sec = info->O->getSection(Load, J);
2966 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2967 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2968 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2969 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2970 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2971 section_type == MachO::S_SYMBOL_STUBS) &&
2972 ReferenceValue >= Sec.addr &&
2973 ReferenceValue < Sec.addr + Sec.size) {
2974 uint32_t stride;
2975 if (section_type == MachO::S_SYMBOL_STUBS)
2976 stride = Sec.reserved2;
2977 else
2978 stride = 4;
2979 if (stride == 0)
2980 return nullptr;
2981 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2982 if (index < Dysymtab.nindirectsyms) {
2983 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002984 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002985 if (indirect_symbol < Symtab.nsyms) {
2986 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
Fangrui Songe7834bd2019-04-07 08:19:55 +00002987 return unwrapOrError(Sym->getName(), info->O->getFileName())
2988 .data();
Kevin Enderby85974882014-09-26 22:20:44 +00002989 }
2990 }
2991 }
2992 }
2993 }
Kevin Enderby85974882014-09-26 22:20:44 +00002994 }
2995 return nullptr;
2996}
2997
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002998// method_reference() is called passing it the ReferenceName that might be
2999// a reference it to an Objective-C method call. If so then it allocates and
3000// assembles a method call string with the values last seen and saved in
3001// the DisassembleInfo's class_name and selector_name fields. This is saved
3002// into the method field of the info and any previous string is free'ed.
3003// Then the class_name field in the info is set to nullptr. The method call
3004// string is set into ReferenceName and ReferenceType is set to
3005// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
3006// then both ReferenceType and ReferenceName are left unchanged.
3007static void method_reference(struct DisassembleInfo *info,
3008 uint64_t *ReferenceType,
3009 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003010 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003011 if (*ReferenceName != nullptr) {
3012 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003013 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003014 if (info->class_name != nullptr) {
David Blaikie0e550682018-02-20 18:48:51 +00003015 info->method = llvm::make_unique<char[]>(
3016 5 + strlen(info->class_name) + strlen(info->selector_name));
3017 char *method = info->method.get();
3018 if (method != nullptr) {
3019 strcpy(method, "+[");
3020 strcat(method, info->class_name);
3021 strcat(method, " ");
3022 strcat(method, info->selector_name);
3023 strcat(method, "]");
3024 *ReferenceName = method;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003025 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3026 }
3027 } else {
David Blaikie0e550682018-02-20 18:48:51 +00003028 info->method =
3029 llvm::make_unique<char[]>(9 + strlen(info->selector_name));
3030 char *method = info->method.get();
3031 if (method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003032 if (Arch == Triple::x86_64)
David Blaikie0e550682018-02-20 18:48:51 +00003033 strcpy(method, "-[%rdi ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003034 else if (Arch == Triple::aarch64)
David Blaikie0e550682018-02-20 18:48:51 +00003035 strcpy(method, "-[x0 ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003036 else
David Blaikie0e550682018-02-20 18:48:51 +00003037 strcpy(method, "-[r? ");
3038 strcat(method, info->selector_name);
3039 strcat(method, "]");
3040 *ReferenceName = method;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003041 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3042 }
3043 }
3044 info->class_name = nullptr;
3045 }
3046 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003047 if (info->selector_name != nullptr) {
David Blaikie0e550682018-02-20 18:48:51 +00003048 info->method =
3049 llvm::make_unique<char[]>(17 + strlen(info->selector_name));
3050 char *method = info->method.get();
3051 if (method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003052 if (Arch == Triple::x86_64)
David Blaikie0e550682018-02-20 18:48:51 +00003053 strcpy(method, "-[[%rdi super] ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003054 else if (Arch == Triple::aarch64)
David Blaikie0e550682018-02-20 18:48:51 +00003055 strcpy(method, "-[[x0 super] ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003056 else
David Blaikie0e550682018-02-20 18:48:51 +00003057 strcpy(method, "-[[r? super] ");
3058 strcat(method, info->selector_name);
3059 strcat(method, "]");
3060 *ReferenceName = method;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003061 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3062 }
3063 info->class_name = nullptr;
3064 }
3065 }
3066 }
3067}
3068
3069// GuessPointerPointer() is passed the address of what might be a pointer to
3070// a reference to an Objective-C class, selector, message ref or cfstring.
3071// If so the value of the pointer is returned and one of the booleans are set
3072// to true. If not zero is returned and all the booleans are set to false.
3073static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
3074 struct DisassembleInfo *info,
3075 bool &classref, bool &selref, bool &msgref,
3076 bool &cfstring) {
3077 classref = false;
3078 selref = false;
3079 msgref = false;
3080 cfstring = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00003081 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003082 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3083 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3084 for (unsigned J = 0; J < Seg.nsects; ++J) {
3085 MachO::section_64 Sec = info->O->getSection64(Load, J);
3086 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
3087 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
3088 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
3089 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
3090 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
3091 ReferenceValue >= Sec.addr &&
3092 ReferenceValue < Sec.addr + Sec.size) {
3093 uint64_t sect_offset = ReferenceValue - Sec.addr;
3094 uint64_t object_offset = Sec.offset + sect_offset;
3095 StringRef MachOContents = info->O->getData();
3096 uint64_t object_size = MachOContents.size();
3097 const char *object_addr = (const char *)MachOContents.data();
3098 if (object_offset < object_size) {
3099 uint64_t pointer_value;
3100 memcpy(&pointer_value, object_addr + object_offset,
3101 sizeof(uint64_t));
3102 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3103 sys::swapByteOrder(pointer_value);
3104 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
3105 selref = true;
3106 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
3107 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
3108 classref = true;
3109 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
3110 ReferenceValue + 8 < Sec.addr + Sec.size) {
3111 msgref = true;
3112 memcpy(&pointer_value, object_addr + object_offset + 8,
3113 sizeof(uint64_t));
3114 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3115 sys::swapByteOrder(pointer_value);
3116 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
3117 cfstring = true;
3118 return pointer_value;
3119 } else {
3120 return 0;
3121 }
3122 }
3123 }
3124 }
3125 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003126 }
3127 return 0;
3128}
3129
3130// get_pointer_64 returns a pointer to the bytes in the object file at the
3131// Address from a section in the Mach-O file. And indirectly returns the
3132// offset into the section, number of bytes left in the section past the offset
3133// and which section is was being referenced. If the Address is not in a
3134// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003135static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
3136 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00003137 DisassembleInfo *info,
3138 bool objc_only = false) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003139 offset = 0;
3140 left = 0;
3141 S = SectionRef();
3142 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
3143 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
3144 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
Kevin Enderby46e642f2015-10-08 22:50:55 +00003145 if (SectSize == 0)
3146 continue;
Kevin Enderby846c0002015-04-16 17:19:59 +00003147 if (objc_only) {
3148 StringRef SectName;
3149 ((*(info->Sections))[SectIdx]).getName(SectName);
3150 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
3151 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
3152 if (SegName != "__OBJC" && SectName != "__cstring")
3153 continue;
3154 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003155 if (Address >= SectAddress && Address < SectAddress + SectSize) {
3156 S = (*(info->Sections))[SectIdx];
3157 offset = Address - SectAddress;
3158 left = SectSize - offset;
3159 StringRef SectContents;
3160 ((*(info->Sections))[SectIdx]).getContents(SectContents);
3161 return SectContents.data() + offset;
3162 }
3163 }
3164 return nullptr;
3165}
3166
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003167static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
3168 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00003169 DisassembleInfo *info,
3170 bool objc_only = false) {
3171 return get_pointer_64(Address, offset, left, S, info, objc_only);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003172}
3173
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003174// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
3175// the symbol indirectly through n_value. Based on the relocation information
3176// for the specified section offset in the specified section reference.
Kevin Enderby0fc11822015-04-01 20:57:01 +00003177// If no relocation information is found and a non-zero ReferenceValue for the
3178// symbol is passed, look up that address in the info's AddrMap.
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00003179static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
3180 DisassembleInfo *info, uint64_t &n_value,
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00003181 uint64_t ReferenceValue = 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003182 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00003183 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003184 return nullptr;
3185
3186 // See if there is an external relocation entry at the sect_offset.
3187 bool reloc_found = false;
3188 DataRefImpl Rel;
3189 MachO::any_relocation_info RE;
3190 bool isExtern = false;
3191 SymbolRef Symbol;
3192 for (const RelocationRef &Reloc : S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00003193 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003194 if (RelocOffset == sect_offset) {
3195 Rel = Reloc.getRawDataRefImpl();
3196 RE = info->O->getRelocation(Rel);
3197 if (info->O->isRelocationScattered(RE))
3198 continue;
3199 isExtern = info->O->getPlainRelocationExternal(RE);
3200 if (isExtern) {
3201 symbol_iterator RelocSym = Reloc.getSymbol();
3202 Symbol = *RelocSym;
3203 }
3204 reloc_found = true;
3205 break;
3206 }
3207 }
3208 // If there is an external relocation entry for a symbol in this section
3209 // at this section_offset then use that symbol's value for the n_value
3210 // and return its name.
3211 const char *SymbolName = nullptr;
3212 if (reloc_found && isExtern) {
Rafael Espindoladea00162015-07-03 17:44:18 +00003213 n_value = Symbol.getValue();
Fangrui Songe7834bd2019-04-07 08:19:55 +00003214 StringRef Name = unwrapOrError(Symbol.getName(), info->O->getFileName());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00003215 if (!Name.empty()) {
3216 SymbolName = Name.data();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003217 return SymbolName;
3218 }
3219 }
3220
3221 // TODO: For fully linked images, look through the external relocation
3222 // entries off the dynamic symtab command. For these the r_offset is from the
3223 // start of the first writeable segment in the Mach-O file. So the offset
3224 // to this section from that segment is passed to this routine by the caller,
3225 // as the database_offset. Which is the difference of the section's starting
3226 // address and the first writable segment.
3227 //
3228 // NOTE: need add passing the database_offset to this routine.
3229
Kevin Enderby0fc11822015-04-01 20:57:01 +00003230 // We did not find an external relocation entry so look up the ReferenceValue
3231 // as an address of a symbol and if found return that symbol's name.
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00003232 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003233
3234 return SymbolName;
3235}
3236
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003237static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
3238 DisassembleInfo *info,
3239 uint32_t ReferenceValue) {
3240 uint64_t n_value64;
3241 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
3242}
3243
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003244// These are structs in the Objective-C meta data and read to produce the
3245// comments for disassembly. While these are part of the ABI they are no
Zachary Turner264b5d92017-06-07 03:48:56 +00003246// public defintions. So the are here not in include/llvm/BinaryFormat/MachO.h
3247// .
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003248
3249// The cfstring object in a 64-bit Mach-O file.
3250struct cfstring64_t {
3251 uint64_t isa; // class64_t * (64-bit pointer)
3252 uint64_t flags; // flag bits
3253 uint64_t characters; // char * (64-bit pointer)
3254 uint64_t length; // number of non-NULL characters in above
3255};
3256
3257// The class object in a 64-bit Mach-O file.
3258struct class64_t {
3259 uint64_t isa; // class64_t * (64-bit pointer)
3260 uint64_t superclass; // class64_t * (64-bit pointer)
3261 uint64_t cache; // Cache (64-bit pointer)
3262 uint64_t vtable; // IMP * (64-bit pointer)
3263 uint64_t data; // class_ro64_t * (64-bit pointer)
3264};
3265
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003266struct class32_t {
3267 uint32_t isa; /* class32_t * (32-bit pointer) */
3268 uint32_t superclass; /* class32_t * (32-bit pointer) */
3269 uint32_t cache; /* Cache (32-bit pointer) */
3270 uint32_t vtable; /* IMP * (32-bit pointer) */
3271 uint32_t data; /* class_ro32_t * (32-bit pointer) */
3272};
3273
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003274struct class_ro64_t {
3275 uint32_t flags;
3276 uint32_t instanceStart;
3277 uint32_t instanceSize;
3278 uint32_t reserved;
3279 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
3280 uint64_t name; // const char * (64-bit pointer)
3281 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
3282 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
3283 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
3284 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
3285 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
3286};
3287
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003288struct class_ro32_t {
3289 uint32_t flags;
3290 uint32_t instanceStart;
3291 uint32_t instanceSize;
3292 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
3293 uint32_t name; /* const char * (32-bit pointer) */
3294 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
3295 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
3296 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
3297 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
3298 uint32_t baseProperties; /* const struct objc_property_list *
3299 (32-bit pointer) */
3300};
3301
3302/* Values for class_ro{64,32}_t->flags */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003303#define RO_META (1 << 0)
3304#define RO_ROOT (1 << 1)
3305#define RO_HAS_CXX_STRUCTORS (1 << 2)
3306
3307struct method_list64_t {
3308 uint32_t entsize;
3309 uint32_t count;
3310 /* struct method64_t first; These structures follow inline */
3311};
3312
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003313struct method_list32_t {
3314 uint32_t entsize;
3315 uint32_t count;
3316 /* struct method32_t first; These structures follow inline */
3317};
3318
Kevin Enderby0fc11822015-04-01 20:57:01 +00003319struct method64_t {
3320 uint64_t name; /* SEL (64-bit pointer) */
3321 uint64_t types; /* const char * (64-bit pointer) */
3322 uint64_t imp; /* IMP (64-bit pointer) */
3323};
3324
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003325struct method32_t {
3326 uint32_t name; /* SEL (32-bit pointer) */
3327 uint32_t types; /* const char * (32-bit pointer) */
3328 uint32_t imp; /* IMP (32-bit pointer) */
3329};
3330
Kevin Enderby0fc11822015-04-01 20:57:01 +00003331struct protocol_list64_t {
3332 uint64_t count; /* uintptr_t (a 64-bit value) */
3333 /* struct protocol64_t * list[0]; These pointers follow inline */
3334};
3335
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003336struct protocol_list32_t {
3337 uint32_t count; /* uintptr_t (a 32-bit value) */
3338 /* struct protocol32_t * list[0]; These pointers follow inline */
3339};
3340
Kevin Enderby0fc11822015-04-01 20:57:01 +00003341struct protocol64_t {
3342 uint64_t isa; /* id * (64-bit pointer) */
3343 uint64_t name; /* const char * (64-bit pointer) */
3344 uint64_t protocols; /* struct protocol_list64_t *
3345 (64-bit pointer) */
3346 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
3347 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
3348 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
3349 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
3350 uint64_t instanceProperties; /* struct objc_property_list *
3351 (64-bit pointer) */
3352};
3353
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003354struct protocol32_t {
3355 uint32_t isa; /* id * (32-bit pointer) */
3356 uint32_t name; /* const char * (32-bit pointer) */
3357 uint32_t protocols; /* struct protocol_list_t *
3358 (32-bit pointer) */
3359 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
3360 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
3361 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
3362 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
3363 uint32_t instanceProperties; /* struct objc_property_list *
3364 (32-bit pointer) */
3365};
3366
Kevin Enderby0fc11822015-04-01 20:57:01 +00003367struct ivar_list64_t {
3368 uint32_t entsize;
3369 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003370 /* struct ivar64_t first; These structures follow inline */
3371};
3372
3373struct ivar_list32_t {
3374 uint32_t entsize;
3375 uint32_t count;
3376 /* struct ivar32_t first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003377};
3378
3379struct ivar64_t {
3380 uint64_t offset; /* uintptr_t * (64-bit pointer) */
3381 uint64_t name; /* const char * (64-bit pointer) */
3382 uint64_t type; /* const char * (64-bit pointer) */
3383 uint32_t alignment;
3384 uint32_t size;
3385};
3386
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003387struct ivar32_t {
3388 uint32_t offset; /* uintptr_t * (32-bit pointer) */
3389 uint32_t name; /* const char * (32-bit pointer) */
3390 uint32_t type; /* const char * (32-bit pointer) */
3391 uint32_t alignment;
3392 uint32_t size;
3393};
3394
Kevin Enderby0fc11822015-04-01 20:57:01 +00003395struct objc_property_list64 {
3396 uint32_t entsize;
3397 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003398 /* struct objc_property64 first; These structures follow inline */
3399};
3400
3401struct objc_property_list32 {
3402 uint32_t entsize;
3403 uint32_t count;
3404 /* struct objc_property32 first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003405};
3406
3407struct objc_property64 {
3408 uint64_t name; /* const char * (64-bit pointer) */
3409 uint64_t attributes; /* const char * (64-bit pointer) */
3410};
3411
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003412struct objc_property32 {
3413 uint32_t name; /* const char * (32-bit pointer) */
3414 uint32_t attributes; /* const char * (32-bit pointer) */
3415};
3416
Kevin Enderby0fc11822015-04-01 20:57:01 +00003417struct category64_t {
3418 uint64_t name; /* const char * (64-bit pointer) */
3419 uint64_t cls; /* struct class_t * (64-bit pointer) */
3420 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
3421 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
3422 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
3423 uint64_t instanceProperties; /* struct objc_property_list *
3424 (64-bit pointer) */
3425};
3426
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003427struct category32_t {
3428 uint32_t name; /* const char * (32-bit pointer) */
3429 uint32_t cls; /* struct class_t * (32-bit pointer) */
3430 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
3431 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
3432 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
3433 uint32_t instanceProperties; /* struct objc_property_list *
3434 (32-bit pointer) */
3435};
3436
Kevin Enderby0fc11822015-04-01 20:57:01 +00003437struct objc_image_info64 {
3438 uint32_t version;
3439 uint32_t flags;
3440};
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003441struct objc_image_info32 {
3442 uint32_t version;
3443 uint32_t flags;
3444};
Kevin Enderby846c0002015-04-16 17:19:59 +00003445struct imageInfo_t {
3446 uint32_t version;
3447 uint32_t flags;
3448};
Kevin Enderby0fc11822015-04-01 20:57:01 +00003449/* masks for objc_image_info.flags */
3450#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
3451#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
Dave Lee390abe42018-07-06 05:11:35 +00003452#define OBJC_IMAGE_IS_SIMULATED (1 << 5)
3453#define OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES (1 << 6)
Kevin Enderby0fc11822015-04-01 20:57:01 +00003454
3455struct message_ref64 {
3456 uint64_t imp; /* IMP (64-bit pointer) */
3457 uint64_t sel; /* SEL (64-bit pointer) */
3458};
3459
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003460struct message_ref32 {
3461 uint32_t imp; /* IMP (32-bit pointer) */
3462 uint32_t sel; /* SEL (32-bit pointer) */
3463};
3464
Kevin Enderby846c0002015-04-16 17:19:59 +00003465// Objective-C 1 (32-bit only) meta data structs.
3466
3467struct objc_module_t {
3468 uint32_t version;
3469 uint32_t size;
3470 uint32_t name; /* char * (32-bit pointer) */
3471 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
3472};
3473
3474struct objc_symtab_t {
3475 uint32_t sel_ref_cnt;
3476 uint32_t refs; /* SEL * (32-bit pointer) */
3477 uint16_t cls_def_cnt;
3478 uint16_t cat_def_cnt;
3479 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
3480};
3481
3482struct objc_class_t {
3483 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3484 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
3485 uint32_t name; /* const char * (32-bit pointer) */
3486 int32_t version;
3487 int32_t info;
3488 int32_t instance_size;
3489 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
3490 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
3491 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
3492 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
3493};
3494
3495#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
3496// class is not a metaclass
3497#define CLS_CLASS 0x1
3498// class is a metaclass
3499#define CLS_META 0x2
3500
3501struct objc_category_t {
3502 uint32_t category_name; /* char * (32-bit pointer) */
3503 uint32_t class_name; /* char * (32-bit pointer) */
3504 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
3505 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
3506 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
3507};
3508
3509struct objc_ivar_t {
3510 uint32_t ivar_name; /* char * (32-bit pointer) */
3511 uint32_t ivar_type; /* char * (32-bit pointer) */
3512 int32_t ivar_offset;
3513};
3514
3515struct objc_ivar_list_t {
3516 int32_t ivar_count;
3517 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
3518};
3519
3520struct objc_method_list_t {
3521 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
3522 int32_t method_count;
3523 // struct objc_method_t method_list[1]; /* variable length structure */
3524};
3525
3526struct objc_method_t {
3527 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3528 uint32_t method_types; /* char * (32-bit pointer) */
3529 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
3530 (32-bit pointer) */
3531};
3532
3533struct objc_protocol_list_t {
3534 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
3535 int32_t count;
3536 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
3537 // (32-bit pointer) */
3538};
3539
3540struct objc_protocol_t {
3541 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3542 uint32_t protocol_name; /* char * (32-bit pointer) */
3543 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
3544 uint32_t instance_methods; /* struct objc_method_description_list *
3545 (32-bit pointer) */
3546 uint32_t class_methods; /* struct objc_method_description_list *
3547 (32-bit pointer) */
3548};
3549
3550struct objc_method_description_list_t {
3551 int32_t count;
3552 // struct objc_method_description_t list[1];
3553};
3554
3555struct objc_method_description_t {
3556 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3557 uint32_t types; /* char * (32-bit pointer) */
3558};
3559
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003560inline void swapStruct(struct cfstring64_t &cfs) {
3561 sys::swapByteOrder(cfs.isa);
3562 sys::swapByteOrder(cfs.flags);
3563 sys::swapByteOrder(cfs.characters);
3564 sys::swapByteOrder(cfs.length);
3565}
3566
3567inline void swapStruct(struct class64_t &c) {
3568 sys::swapByteOrder(c.isa);
3569 sys::swapByteOrder(c.superclass);
3570 sys::swapByteOrder(c.cache);
3571 sys::swapByteOrder(c.vtable);
3572 sys::swapByteOrder(c.data);
3573}
3574
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003575inline void swapStruct(struct class32_t &c) {
3576 sys::swapByteOrder(c.isa);
3577 sys::swapByteOrder(c.superclass);
3578 sys::swapByteOrder(c.cache);
3579 sys::swapByteOrder(c.vtable);
3580 sys::swapByteOrder(c.data);
3581}
3582
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003583inline void swapStruct(struct class_ro64_t &cro) {
3584 sys::swapByteOrder(cro.flags);
3585 sys::swapByteOrder(cro.instanceStart);
3586 sys::swapByteOrder(cro.instanceSize);
3587 sys::swapByteOrder(cro.reserved);
3588 sys::swapByteOrder(cro.ivarLayout);
3589 sys::swapByteOrder(cro.name);
3590 sys::swapByteOrder(cro.baseMethods);
3591 sys::swapByteOrder(cro.baseProtocols);
3592 sys::swapByteOrder(cro.ivars);
3593 sys::swapByteOrder(cro.weakIvarLayout);
3594 sys::swapByteOrder(cro.baseProperties);
3595}
3596
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003597inline void swapStruct(struct class_ro32_t &cro) {
3598 sys::swapByteOrder(cro.flags);
3599 sys::swapByteOrder(cro.instanceStart);
3600 sys::swapByteOrder(cro.instanceSize);
3601 sys::swapByteOrder(cro.ivarLayout);
3602 sys::swapByteOrder(cro.name);
3603 sys::swapByteOrder(cro.baseMethods);
3604 sys::swapByteOrder(cro.baseProtocols);
3605 sys::swapByteOrder(cro.ivars);
3606 sys::swapByteOrder(cro.weakIvarLayout);
3607 sys::swapByteOrder(cro.baseProperties);
3608}
3609
Kevin Enderby0fc11822015-04-01 20:57:01 +00003610inline void swapStruct(struct method_list64_t &ml) {
3611 sys::swapByteOrder(ml.entsize);
3612 sys::swapByteOrder(ml.count);
3613}
3614
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003615inline void swapStruct(struct method_list32_t &ml) {
3616 sys::swapByteOrder(ml.entsize);
3617 sys::swapByteOrder(ml.count);
3618}
3619
Kevin Enderby0fc11822015-04-01 20:57:01 +00003620inline void swapStruct(struct method64_t &m) {
3621 sys::swapByteOrder(m.name);
3622 sys::swapByteOrder(m.types);
3623 sys::swapByteOrder(m.imp);
3624}
3625
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003626inline void swapStruct(struct method32_t &m) {
3627 sys::swapByteOrder(m.name);
3628 sys::swapByteOrder(m.types);
3629 sys::swapByteOrder(m.imp);
3630}
3631
Kevin Enderby0fc11822015-04-01 20:57:01 +00003632inline void swapStruct(struct protocol_list64_t &pl) {
3633 sys::swapByteOrder(pl.count);
3634}
3635
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003636inline void swapStruct(struct protocol_list32_t &pl) {
3637 sys::swapByteOrder(pl.count);
3638}
3639
Kevin Enderby0fc11822015-04-01 20:57:01 +00003640inline void swapStruct(struct protocol64_t &p) {
3641 sys::swapByteOrder(p.isa);
3642 sys::swapByteOrder(p.name);
3643 sys::swapByteOrder(p.protocols);
3644 sys::swapByteOrder(p.instanceMethods);
3645 sys::swapByteOrder(p.classMethods);
3646 sys::swapByteOrder(p.optionalInstanceMethods);
3647 sys::swapByteOrder(p.optionalClassMethods);
3648 sys::swapByteOrder(p.instanceProperties);
3649}
3650
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003651inline void swapStruct(struct protocol32_t &p) {
3652 sys::swapByteOrder(p.isa);
3653 sys::swapByteOrder(p.name);
3654 sys::swapByteOrder(p.protocols);
3655 sys::swapByteOrder(p.instanceMethods);
3656 sys::swapByteOrder(p.classMethods);
3657 sys::swapByteOrder(p.optionalInstanceMethods);
3658 sys::swapByteOrder(p.optionalClassMethods);
3659 sys::swapByteOrder(p.instanceProperties);
3660}
3661
Kevin Enderby0fc11822015-04-01 20:57:01 +00003662inline void swapStruct(struct ivar_list64_t &il) {
3663 sys::swapByteOrder(il.entsize);
3664 sys::swapByteOrder(il.count);
3665}
3666
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003667inline void swapStruct(struct ivar_list32_t &il) {
3668 sys::swapByteOrder(il.entsize);
3669 sys::swapByteOrder(il.count);
3670}
3671
Kevin Enderby0fc11822015-04-01 20:57:01 +00003672inline void swapStruct(struct ivar64_t &i) {
3673 sys::swapByteOrder(i.offset);
3674 sys::swapByteOrder(i.name);
3675 sys::swapByteOrder(i.type);
3676 sys::swapByteOrder(i.alignment);
3677 sys::swapByteOrder(i.size);
3678}
3679
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003680inline void swapStruct(struct ivar32_t &i) {
3681 sys::swapByteOrder(i.offset);
3682 sys::swapByteOrder(i.name);
3683 sys::swapByteOrder(i.type);
3684 sys::swapByteOrder(i.alignment);
3685 sys::swapByteOrder(i.size);
3686}
3687
Kevin Enderby0fc11822015-04-01 20:57:01 +00003688inline void swapStruct(struct objc_property_list64 &pl) {
3689 sys::swapByteOrder(pl.entsize);
3690 sys::swapByteOrder(pl.count);
3691}
3692
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003693inline void swapStruct(struct objc_property_list32 &pl) {
3694 sys::swapByteOrder(pl.entsize);
3695 sys::swapByteOrder(pl.count);
3696}
3697
Kevin Enderby0fc11822015-04-01 20:57:01 +00003698inline void swapStruct(struct objc_property64 &op) {
3699 sys::swapByteOrder(op.name);
3700 sys::swapByteOrder(op.attributes);
3701}
3702
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003703inline void swapStruct(struct objc_property32 &op) {
3704 sys::swapByteOrder(op.name);
3705 sys::swapByteOrder(op.attributes);
3706}
3707
Kevin Enderby0fc11822015-04-01 20:57:01 +00003708inline void swapStruct(struct category64_t &c) {
3709 sys::swapByteOrder(c.name);
3710 sys::swapByteOrder(c.cls);
3711 sys::swapByteOrder(c.instanceMethods);
3712 sys::swapByteOrder(c.classMethods);
3713 sys::swapByteOrder(c.protocols);
3714 sys::swapByteOrder(c.instanceProperties);
3715}
3716
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003717inline void swapStruct(struct category32_t &c) {
3718 sys::swapByteOrder(c.name);
3719 sys::swapByteOrder(c.cls);
3720 sys::swapByteOrder(c.instanceMethods);
3721 sys::swapByteOrder(c.classMethods);
3722 sys::swapByteOrder(c.protocols);
3723 sys::swapByteOrder(c.instanceProperties);
3724}
3725
Kevin Enderby0fc11822015-04-01 20:57:01 +00003726inline void swapStruct(struct objc_image_info64 &o) {
3727 sys::swapByteOrder(o.version);
3728 sys::swapByteOrder(o.flags);
3729}
3730
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003731inline void swapStruct(struct objc_image_info32 &o) {
3732 sys::swapByteOrder(o.version);
3733 sys::swapByteOrder(o.flags);
3734}
3735
Kevin Enderby846c0002015-04-16 17:19:59 +00003736inline void swapStruct(struct imageInfo_t &o) {
3737 sys::swapByteOrder(o.version);
3738 sys::swapByteOrder(o.flags);
3739}
3740
Kevin Enderby0fc11822015-04-01 20:57:01 +00003741inline void swapStruct(struct message_ref64 &mr) {
3742 sys::swapByteOrder(mr.imp);
3743 sys::swapByteOrder(mr.sel);
3744}
3745
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003746inline void swapStruct(struct message_ref32 &mr) {
3747 sys::swapByteOrder(mr.imp);
3748 sys::swapByteOrder(mr.sel);
3749}
3750
Kevin Enderby846c0002015-04-16 17:19:59 +00003751inline void swapStruct(struct objc_module_t &module) {
3752 sys::swapByteOrder(module.version);
3753 sys::swapByteOrder(module.size);
3754 sys::swapByteOrder(module.name);
3755 sys::swapByteOrder(module.symtab);
Jingyue Wufedecc42015-04-16 18:43:44 +00003756}
Kevin Enderby846c0002015-04-16 17:19:59 +00003757
3758inline void swapStruct(struct objc_symtab_t &symtab) {
3759 sys::swapByteOrder(symtab.sel_ref_cnt);
3760 sys::swapByteOrder(symtab.refs);
3761 sys::swapByteOrder(symtab.cls_def_cnt);
3762 sys::swapByteOrder(symtab.cat_def_cnt);
Jingyue Wufedecc42015-04-16 18:43:44 +00003763}
Kevin Enderby846c0002015-04-16 17:19:59 +00003764
3765inline void swapStruct(struct objc_class_t &objc_class) {
3766 sys::swapByteOrder(objc_class.isa);
3767 sys::swapByteOrder(objc_class.super_class);
3768 sys::swapByteOrder(objc_class.name);
3769 sys::swapByteOrder(objc_class.version);
3770 sys::swapByteOrder(objc_class.info);
3771 sys::swapByteOrder(objc_class.instance_size);
3772 sys::swapByteOrder(objc_class.ivars);
3773 sys::swapByteOrder(objc_class.methodLists);
3774 sys::swapByteOrder(objc_class.cache);
3775 sys::swapByteOrder(objc_class.protocols);
Jingyue Wufedecc42015-04-16 18:43:44 +00003776}
Kevin Enderby846c0002015-04-16 17:19:59 +00003777
3778inline void swapStruct(struct objc_category_t &objc_category) {
3779 sys::swapByteOrder(objc_category.category_name);
3780 sys::swapByteOrder(objc_category.class_name);
3781 sys::swapByteOrder(objc_category.instance_methods);
3782 sys::swapByteOrder(objc_category.class_methods);
3783 sys::swapByteOrder(objc_category.protocols);
3784}
3785
3786inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3787 sys::swapByteOrder(objc_ivar_list.ivar_count);
3788}
3789
3790inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3791 sys::swapByteOrder(objc_ivar.ivar_name);
3792 sys::swapByteOrder(objc_ivar.ivar_type);
3793 sys::swapByteOrder(objc_ivar.ivar_offset);
Jingyue Wufedecc42015-04-16 18:43:44 +00003794}
Kevin Enderby846c0002015-04-16 17:19:59 +00003795
3796inline void swapStruct(struct objc_method_list_t &method_list) {
3797 sys::swapByteOrder(method_list.obsolete);
3798 sys::swapByteOrder(method_list.method_count);
3799}
3800
3801inline void swapStruct(struct objc_method_t &method) {
3802 sys::swapByteOrder(method.method_name);
3803 sys::swapByteOrder(method.method_types);
3804 sys::swapByteOrder(method.method_imp);
3805}
3806
3807inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3808 sys::swapByteOrder(protocol_list.next);
3809 sys::swapByteOrder(protocol_list.count);
3810}
3811
3812inline void swapStruct(struct objc_protocol_t &protocol) {
3813 sys::swapByteOrder(protocol.isa);
3814 sys::swapByteOrder(protocol.protocol_name);
3815 sys::swapByteOrder(protocol.protocol_list);
3816 sys::swapByteOrder(protocol.instance_methods);
3817 sys::swapByteOrder(protocol.class_methods);
3818}
3819
3820inline void swapStruct(struct objc_method_description_list_t &mdl) {
3821 sys::swapByteOrder(mdl.count);
3822}
3823
3824inline void swapStruct(struct objc_method_description_t &md) {
3825 sys::swapByteOrder(md.name);
3826 sys::swapByteOrder(md.types);
3827}
3828
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003829static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3830 struct DisassembleInfo *info);
3831
3832// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3833// to an Objective-C class and returns the class name. It is also passed the
3834// address of the pointer, so when the pointer is zero as it can be in an .o
3835// file, that is used to look for an external relocation entry with a symbol
3836// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003837static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3838 uint64_t ReferenceValue,
3839 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003840 const char *r;
3841 uint32_t offset, left;
3842 SectionRef S;
3843
3844 // The pointer_value can be 0 in an object file and have a relocation
3845 // entry for the class symbol at the ReferenceValue (the address of the
3846 // pointer).
3847 if (pointer_value == 0) {
3848 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3849 if (r == nullptr || left < sizeof(uint64_t))
3850 return nullptr;
3851 uint64_t n_value;
3852 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3853 if (symbol_name == nullptr)
3854 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00003855 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003856 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3857 return class_name + 2;
3858 else
3859 return nullptr;
3860 }
3861
3862 // The case were the pointer_value is non-zero and points to a class defined
3863 // in this Mach-O file.
3864 r = get_pointer_64(pointer_value, offset, left, S, info);
3865 if (r == nullptr || left < sizeof(struct class64_t))
3866 return nullptr;
3867 struct class64_t c;
3868 memcpy(&c, r, sizeof(struct class64_t));
3869 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3870 swapStruct(c);
3871 if (c.data == 0)
3872 return nullptr;
3873 r = get_pointer_64(c.data, offset, left, S, info);
3874 if (r == nullptr || left < sizeof(struct class_ro64_t))
3875 return nullptr;
3876 struct class_ro64_t cro;
3877 memcpy(&cro, r, sizeof(struct class_ro64_t));
3878 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3879 swapStruct(cro);
3880 if (cro.name == 0)
3881 return nullptr;
3882 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3883 return name;
3884}
3885
3886// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3887// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003888static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3889 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003890 const char *r, *name;
3891 uint32_t offset, left;
3892 SectionRef S;
3893 struct cfstring64_t cfs;
3894 uint64_t cfs_characters;
3895
3896 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3897 if (r == nullptr || left < sizeof(struct cfstring64_t))
3898 return nullptr;
3899 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3900 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3901 swapStruct(cfs);
3902 if (cfs.characters == 0) {
3903 uint64_t n_value;
3904 const char *symbol_name = get_symbol_64(
3905 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3906 if (symbol_name == nullptr)
3907 return nullptr;
3908 cfs_characters = n_value;
3909 } else
3910 cfs_characters = cfs.characters;
3911 name = get_pointer_64(cfs_characters, offset, left, S, info);
3912
3913 return name;
3914}
3915
3916// get_objc2_64bit_selref() is used for disassembly and is passed a the address
3917// of a pointer to an Objective-C selector reference when the pointer value is
3918// zero as in a .o file and is likely to have a external relocation entry with
3919// who's symbol's n_value is the real pointer to the selector name. If that is
3920// the case the real pointer to the selector name is returned else 0 is
3921// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003922static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3923 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003924 uint32_t offset, left;
3925 SectionRef S;
3926
3927 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3928 if (r == nullptr || left < sizeof(uint64_t))
3929 return 0;
3930 uint64_t n_value;
3931 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3932 if (symbol_name == nullptr)
3933 return 0;
3934 return n_value;
3935}
3936
Kevin Enderby0fc11822015-04-01 20:57:01 +00003937static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3938 const char *sectname) {
3939 for (const SectionRef &Section : O->sections()) {
3940 StringRef SectName;
3941 Section.getName(SectName);
3942 DataRefImpl Ref = Section.getRawDataRefImpl();
3943 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3944 if (SegName == segname && SectName == sectname)
3945 return Section;
3946 }
3947 return SectionRef();
3948}
3949
3950static void
3951walk_pointer_list_64(const char *listname, const SectionRef S,
3952 MachOObjectFile *O, struct DisassembleInfo *info,
3953 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3954 if (S == SectionRef())
3955 return;
3956
3957 StringRef SectName;
3958 S.getName(SectName);
3959 DataRefImpl Ref = S.getRawDataRefImpl();
3960 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3961 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3962
3963 StringRef BytesStr;
3964 S.getContents(BytesStr);
3965 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3966
3967 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3968 uint32_t left = S.getSize() - i;
3969 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3970 uint64_t p = 0;
3971 memcpy(&p, Contents + i, size);
3972 if (i + sizeof(uint64_t) > S.getSize())
3973 outs() << listname << " list pointer extends past end of (" << SegName
3974 << "," << SectName << ") section\n";
3975 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3976
3977 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3978 sys::swapByteOrder(p);
3979
3980 uint64_t n_value = 0;
3981 const char *name = get_symbol_64(i, S, info, n_value, p);
3982 if (name == nullptr)
3983 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3984
3985 if (n_value != 0) {
3986 outs() << format("0x%" PRIx64, n_value);
3987 if (p != 0)
3988 outs() << " + " << format("0x%" PRIx64, p);
3989 } else
3990 outs() << format("0x%" PRIx64, p);
3991 if (name != nullptr)
3992 outs() << " " << name;
3993 outs() << "\n";
3994
3995 p += n_value;
3996 if (func)
3997 func(p, info);
3998 }
3999}
4000
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004001static void
4002walk_pointer_list_32(const char *listname, const SectionRef S,
4003 MachOObjectFile *O, struct DisassembleInfo *info,
4004 void (*func)(uint32_t, struct DisassembleInfo *info)) {
4005 if (S == SectionRef())
4006 return;
4007
4008 StringRef SectName;
4009 S.getName(SectName);
4010 DataRefImpl Ref = S.getRawDataRefImpl();
4011 StringRef SegName = O->getSectionFinalSegmentName(Ref);
4012 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4013
4014 StringRef BytesStr;
4015 S.getContents(BytesStr);
4016 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
4017
4018 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
4019 uint32_t left = S.getSize() - i;
4020 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
4021 uint32_t p = 0;
4022 memcpy(&p, Contents + i, size);
4023 if (i + sizeof(uint32_t) > S.getSize())
4024 outs() << listname << " list pointer extends past end of (" << SegName
4025 << "," << SectName << ") section\n";
Kevin Enderbycf261312015-04-06 22:33:43 +00004026 uint32_t Address = S.getAddress() + i;
4027 outs() << format("%08" PRIx32, Address) << " ";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004028
4029 if (O->isLittleEndian() != sys::IsLittleEndianHost)
4030 sys::swapByteOrder(p);
4031 outs() << format("0x%" PRIx32, p);
4032
4033 const char *name = get_symbol_32(i, S, info, p);
4034 if (name != nullptr)
4035 outs() << " " << name;
4036 outs() << "\n";
4037
4038 if (func)
4039 func(p, info);
4040 }
4041}
4042
4043static void print_layout_map(const char *layout_map, uint32_t left) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00004044 if (layout_map == nullptr)
4045 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004046 outs() << " layout map: ";
4047 do {
4048 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
4049 left--;
4050 layout_map++;
4051 } while (*layout_map != '\0' && left != 0);
4052 outs() << "\n";
4053}
4054
Kevin Enderby0fc11822015-04-01 20:57:01 +00004055static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
4056 uint32_t offset, left;
4057 SectionRef S;
4058 const char *layout_map;
4059
4060 if (p == 0)
4061 return;
4062 layout_map = get_pointer_64(p, offset, left, S, info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004063 print_layout_map(layout_map, left);
4064}
4065
4066static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
4067 uint32_t offset, left;
4068 SectionRef S;
4069 const char *layout_map;
4070
4071 if (p == 0)
4072 return;
4073 layout_map = get_pointer_32(p, offset, left, S, info);
4074 print_layout_map(layout_map, left);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004075}
4076
4077static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
4078 const char *indent) {
4079 struct method_list64_t ml;
4080 struct method64_t m;
4081 const char *r;
4082 uint32_t offset, xoffset, left, i;
4083 SectionRef S, xS;
4084 const char *name, *sym_name;
4085 uint64_t n_value;
4086
4087 r = get_pointer_64(p, offset, left, S, info);
4088 if (r == nullptr)
4089 return;
4090 memset(&ml, '\0', sizeof(struct method_list64_t));
4091 if (left < sizeof(struct method_list64_t)) {
4092 memcpy(&ml, r, left);
4093 outs() << " (method_list_t entends past the end of the section)\n";
4094 } else
4095 memcpy(&ml, r, sizeof(struct method_list64_t));
4096 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4097 swapStruct(ml);
4098 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
4099 outs() << indent << "\t\t count " << ml.count << "\n";
4100
4101 p += sizeof(struct method_list64_t);
4102 offset += sizeof(struct method_list64_t);
4103 for (i = 0; i < ml.count; i++) {
4104 r = get_pointer_64(p, offset, left, S, info);
4105 if (r == nullptr)
4106 return;
4107 memset(&m, '\0', sizeof(struct method64_t));
4108 if (left < sizeof(struct method64_t)) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00004109 memcpy(&m, r, left);
4110 outs() << indent << " (method_t extends past the end of the section)\n";
Kevin Enderby0fc11822015-04-01 20:57:01 +00004111 } else
4112 memcpy(&m, r, sizeof(struct method64_t));
4113 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4114 swapStruct(m);
4115
4116 outs() << indent << "\t\t name ";
4117 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
4118 info, n_value, m.name);
4119 if (n_value != 0) {
4120 if (info->verbose && sym_name != nullptr)
4121 outs() << sym_name;
4122 else
4123 outs() << format("0x%" PRIx64, n_value);
4124 if (m.name != 0)
4125 outs() << " + " << format("0x%" PRIx64, m.name);
4126 } else
4127 outs() << format("0x%" PRIx64, m.name);
4128 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
4129 if (name != nullptr)
4130 outs() << format(" %.*s", left, name);
4131 outs() << "\n";
4132
4133 outs() << indent << "\t\t types ";
4134 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
4135 info, n_value, m.types);
4136 if (n_value != 0) {
4137 if (info->verbose && sym_name != nullptr)
4138 outs() << sym_name;
4139 else
4140 outs() << format("0x%" PRIx64, n_value);
4141 if (m.types != 0)
4142 outs() << " + " << format("0x%" PRIx64, m.types);
4143 } else
4144 outs() << format("0x%" PRIx64, m.types);
4145 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
4146 if (name != nullptr)
4147 outs() << format(" %.*s", left, name);
4148 outs() << "\n";
4149
4150 outs() << indent << "\t\t imp ";
4151 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
4152 n_value, m.imp);
4153 if (info->verbose && name == nullptr) {
4154 if (n_value != 0) {
4155 outs() << format("0x%" PRIx64, n_value) << " ";
4156 if (m.imp != 0)
4157 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
4158 } else
4159 outs() << format("0x%" PRIx64, m.imp) << " ";
4160 }
4161 if (name != nullptr)
4162 outs() << name;
4163 outs() << "\n";
4164
4165 p += sizeof(struct method64_t);
4166 offset += sizeof(struct method64_t);
4167 }
4168}
4169
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004170static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
4171 const char *indent) {
4172 struct method_list32_t ml;
4173 struct method32_t m;
Kevin Enderby846c0002015-04-16 17:19:59 +00004174 const char *r, *name;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004175 uint32_t offset, xoffset, left, i;
4176 SectionRef S, xS;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004177
4178 r = get_pointer_32(p, offset, left, S, info);
4179 if (r == nullptr)
4180 return;
4181 memset(&ml, '\0', sizeof(struct method_list32_t));
4182 if (left < sizeof(struct method_list32_t)) {
4183 memcpy(&ml, r, left);
4184 outs() << " (method_list_t entends past the end of the section)\n";
4185 } else
4186 memcpy(&ml, r, sizeof(struct method_list32_t));
4187 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4188 swapStruct(ml);
4189 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
4190 outs() << indent << "\t\t count " << ml.count << "\n";
4191
4192 p += sizeof(struct method_list32_t);
4193 offset += sizeof(struct method_list32_t);
4194 for (i = 0; i < ml.count; i++) {
4195 r = get_pointer_32(p, offset, left, S, info);
4196 if (r == nullptr)
4197 return;
4198 memset(&m, '\0', sizeof(struct method32_t));
4199 if (left < sizeof(struct method32_t)) {
4200 memcpy(&ml, r, left);
4201 outs() << indent << " (method_t entends past the end of the section)\n";
4202 } else
4203 memcpy(&m, r, sizeof(struct method32_t));
4204 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4205 swapStruct(m);
4206
4207 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
4208 name = get_pointer_32(m.name, xoffset, left, xS, info);
4209 if (name != nullptr)
4210 outs() << format(" %.*s", left, name);
4211 outs() << "\n";
4212
4213 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
4214 name = get_pointer_32(m.types, xoffset, left, xS, info);
4215 if (name != nullptr)
4216 outs() << format(" %.*s", left, name);
4217 outs() << "\n";
4218
4219 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
4220 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
4221 m.imp);
4222 if (name != nullptr)
4223 outs() << " " << name;
4224 outs() << "\n";
4225
4226 p += sizeof(struct method32_t);
4227 offset += sizeof(struct method32_t);
4228 }
4229}
4230
Kevin Enderby846c0002015-04-16 17:19:59 +00004231static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
4232 uint32_t offset, left, xleft;
4233 SectionRef S;
4234 struct objc_method_list_t method_list;
4235 struct objc_method_t method;
4236 const char *r, *methods, *name, *SymbolName;
4237 int32_t i;
4238
4239 r = get_pointer_32(p, offset, left, S, info, true);
4240 if (r == nullptr)
4241 return true;
4242
4243 outs() << "\n";
4244 if (left > sizeof(struct objc_method_list_t)) {
4245 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
4246 } else {
4247 outs() << "\t\t objc_method_list extends past end of the section\n";
4248 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
4249 memcpy(&method_list, r, left);
4250 }
4251 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4252 swapStruct(method_list);
4253
4254 outs() << "\t\t obsolete "
4255 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
4256 outs() << "\t\t method_count " << method_list.method_count << "\n";
4257
4258 methods = r + sizeof(struct objc_method_list_t);
4259 for (i = 0; i < method_list.method_count; i++) {
4260 if ((i + 1) * sizeof(struct objc_method_t) > left) {
4261 outs() << "\t\t remaining method's extend past the of the section\n";
4262 break;
4263 }
4264 memcpy(&method, methods + i * sizeof(struct objc_method_t),
4265 sizeof(struct objc_method_t));
4266 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4267 swapStruct(method);
4268
4269 outs() << "\t\t method_name "
4270 << format("0x%08" PRIx32, method.method_name);
4271 if (info->verbose) {
4272 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
4273 if (name != nullptr)
4274 outs() << format(" %.*s", xleft, name);
4275 else
4276 outs() << " (not in an __OBJC section)";
4277 }
4278 outs() << "\n";
4279
4280 outs() << "\t\t method_types "
4281 << format("0x%08" PRIx32, method.method_types);
4282 if (info->verbose) {
4283 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
4284 if (name != nullptr)
4285 outs() << format(" %.*s", xleft, name);
4286 else
4287 outs() << " (not in an __OBJC section)";
4288 }
4289 outs() << "\n";
4290
4291 outs() << "\t\t method_imp "
4292 << format("0x%08" PRIx32, method.method_imp) << " ";
4293 if (info->verbose) {
4294 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
4295 if (SymbolName != nullptr)
4296 outs() << SymbolName;
4297 }
4298 outs() << "\n";
4299 }
4300 return false;
4301}
4302
Kevin Enderby0fc11822015-04-01 20:57:01 +00004303static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
4304 struct protocol_list64_t pl;
4305 uint64_t q, n_value;
4306 struct protocol64_t pc;
4307 const char *r;
4308 uint32_t offset, xoffset, left, i;
4309 SectionRef S, xS;
4310 const char *name, *sym_name;
4311
4312 r = get_pointer_64(p, offset, left, S, info);
4313 if (r == nullptr)
4314 return;
4315 memset(&pl, '\0', sizeof(struct protocol_list64_t));
4316 if (left < sizeof(struct protocol_list64_t)) {
4317 memcpy(&pl, r, left);
4318 outs() << " (protocol_list_t entends past the end of the section)\n";
4319 } else
4320 memcpy(&pl, r, sizeof(struct protocol_list64_t));
4321 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4322 swapStruct(pl);
4323 outs() << " count " << pl.count << "\n";
4324
4325 p += sizeof(struct protocol_list64_t);
4326 offset += sizeof(struct protocol_list64_t);
4327 for (i = 0; i < pl.count; i++) {
4328 r = get_pointer_64(p, offset, left, S, info);
4329 if (r == nullptr)
4330 return;
4331 q = 0;
4332 if (left < sizeof(uint64_t)) {
4333 memcpy(&q, r, left);
4334 outs() << " (protocol_t * entends past the end of the section)\n";
4335 } else
4336 memcpy(&q, r, sizeof(uint64_t));
4337 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4338 sys::swapByteOrder(q);
4339
4340 outs() << "\t\t list[" << i << "] ";
4341 sym_name = get_symbol_64(offset, S, info, n_value, q);
4342 if (n_value != 0) {
4343 if (info->verbose && sym_name != nullptr)
4344 outs() << sym_name;
4345 else
4346 outs() << format("0x%" PRIx64, n_value);
4347 if (q != 0)
4348 outs() << " + " << format("0x%" PRIx64, q);
4349 } else
4350 outs() << format("0x%" PRIx64, q);
4351 outs() << " (struct protocol_t *)\n";
4352
4353 r = get_pointer_64(q + n_value, offset, left, S, info);
4354 if (r == nullptr)
4355 return;
4356 memset(&pc, '\0', sizeof(struct protocol64_t));
4357 if (left < sizeof(struct protocol64_t)) {
4358 memcpy(&pc, r, left);
4359 outs() << " (protocol_t entends past the end of the section)\n";
4360 } else
4361 memcpy(&pc, r, sizeof(struct protocol64_t));
4362 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4363 swapStruct(pc);
4364
4365 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
4366
4367 outs() << "\t\t\t name ";
4368 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
4369 info, n_value, pc.name);
4370 if (n_value != 0) {
4371 if (info->verbose && sym_name != nullptr)
4372 outs() << sym_name;
4373 else
4374 outs() << format("0x%" PRIx64, n_value);
4375 if (pc.name != 0)
4376 outs() << " + " << format("0x%" PRIx64, pc.name);
4377 } else
4378 outs() << format("0x%" PRIx64, pc.name);
4379 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
4380 if (name != nullptr)
4381 outs() << format(" %.*s", left, name);
4382 outs() << "\n";
4383
4384 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
4385
4386 outs() << "\t\t instanceMethods ";
4387 sym_name =
4388 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
4389 S, info, n_value, pc.instanceMethods);
4390 if (n_value != 0) {
4391 if (info->verbose && sym_name != nullptr)
4392 outs() << sym_name;
4393 else
4394 outs() << format("0x%" PRIx64, n_value);
4395 if (pc.instanceMethods != 0)
4396 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
4397 } else
4398 outs() << format("0x%" PRIx64, pc.instanceMethods);
4399 outs() << " (struct method_list_t *)\n";
4400 if (pc.instanceMethods + n_value != 0)
4401 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
4402
4403 outs() << "\t\t classMethods ";
4404 sym_name =
4405 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
4406 info, n_value, pc.classMethods);
4407 if (n_value != 0) {
4408 if (info->verbose && sym_name != nullptr)
4409 outs() << sym_name;
4410 else
4411 outs() << format("0x%" PRIx64, n_value);
4412 if (pc.classMethods != 0)
4413 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
4414 } else
4415 outs() << format("0x%" PRIx64, pc.classMethods);
4416 outs() << " (struct method_list_t *)\n";
4417 if (pc.classMethods + n_value != 0)
4418 print_method_list64_t(pc.classMethods + n_value, info, "\t");
4419
4420 outs() << "\t optionalInstanceMethods "
4421 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
4422 outs() << "\t optionalClassMethods "
4423 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
4424 outs() << "\t instanceProperties "
4425 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
4426
4427 p += sizeof(uint64_t);
4428 offset += sizeof(uint64_t);
4429 }
4430}
4431
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004432static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
4433 struct protocol_list32_t pl;
4434 uint32_t q;
4435 struct protocol32_t pc;
4436 const char *r;
4437 uint32_t offset, xoffset, left, i;
4438 SectionRef S, xS;
4439 const char *name;
4440
4441 r = get_pointer_32(p, offset, left, S, info);
4442 if (r == nullptr)
4443 return;
4444 memset(&pl, '\0', sizeof(struct protocol_list32_t));
4445 if (left < sizeof(struct protocol_list32_t)) {
4446 memcpy(&pl, r, left);
4447 outs() << " (protocol_list_t entends past the end of the section)\n";
4448 } else
4449 memcpy(&pl, r, sizeof(struct protocol_list32_t));
4450 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4451 swapStruct(pl);
4452 outs() << " count " << pl.count << "\n";
4453
4454 p += sizeof(struct protocol_list32_t);
4455 offset += sizeof(struct protocol_list32_t);
4456 for (i = 0; i < pl.count; i++) {
4457 r = get_pointer_32(p, offset, left, S, info);
4458 if (r == nullptr)
4459 return;
4460 q = 0;
4461 if (left < sizeof(uint32_t)) {
4462 memcpy(&q, r, left);
4463 outs() << " (protocol_t * entends past the end of the section)\n";
4464 } else
4465 memcpy(&q, r, sizeof(uint32_t));
4466 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4467 sys::swapByteOrder(q);
4468 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
4469 << " (struct protocol_t *)\n";
4470 r = get_pointer_32(q, offset, left, S, info);
4471 if (r == nullptr)
4472 return;
4473 memset(&pc, '\0', sizeof(struct protocol32_t));
4474 if (left < sizeof(struct protocol32_t)) {
4475 memcpy(&pc, r, left);
4476 outs() << " (protocol_t entends past the end of the section)\n";
4477 } else
4478 memcpy(&pc, r, sizeof(struct protocol32_t));
4479 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4480 swapStruct(pc);
4481 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
4482 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
4483 name = get_pointer_32(pc.name, xoffset, left, xS, info);
4484 if (name != nullptr)
4485 outs() << format(" %.*s", left, name);
4486 outs() << "\n";
4487 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
4488 outs() << "\t\t instanceMethods "
4489 << format("0x%" PRIx32, pc.instanceMethods)
4490 << " (struct method_list_t *)\n";
4491 if (pc.instanceMethods != 0)
4492 print_method_list32_t(pc.instanceMethods, info, "\t");
4493 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
4494 << " (struct method_list_t *)\n";
4495 if (pc.classMethods != 0)
4496 print_method_list32_t(pc.classMethods, info, "\t");
4497 outs() << "\t optionalInstanceMethods "
4498 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
4499 outs() << "\t optionalClassMethods "
4500 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
4501 outs() << "\t instanceProperties "
4502 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
4503 p += sizeof(uint32_t);
4504 offset += sizeof(uint32_t);
4505 }
4506}
4507
Kevin Enderby846c0002015-04-16 17:19:59 +00004508static void print_indent(uint32_t indent) {
4509 for (uint32_t i = 0; i < indent;) {
4510 if (indent - i >= 8) {
4511 outs() << "\t";
4512 i += 8;
4513 } else {
4514 for (uint32_t j = i; j < indent; j++)
4515 outs() << " ";
4516 return;
4517 }
4518 }
4519}
4520
4521static bool print_method_description_list(uint32_t p, uint32_t indent,
4522 struct DisassembleInfo *info) {
4523 uint32_t offset, left, xleft;
4524 SectionRef S;
4525 struct objc_method_description_list_t mdl;
4526 struct objc_method_description_t md;
4527 const char *r, *list, *name;
4528 int32_t i;
4529
4530 r = get_pointer_32(p, offset, left, S, info, true);
4531 if (r == nullptr)
4532 return true;
4533
4534 outs() << "\n";
4535 if (left > sizeof(struct objc_method_description_list_t)) {
4536 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
4537 } else {
4538 print_indent(indent);
4539 outs() << " objc_method_description_list extends past end of the section\n";
4540 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
4541 memcpy(&mdl, r, left);
4542 }
4543 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4544 swapStruct(mdl);
4545
4546 print_indent(indent);
4547 outs() << " count " << mdl.count << "\n";
4548
4549 list = r + sizeof(struct objc_method_description_list_t);
4550 for (i = 0; i < mdl.count; i++) {
4551 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
4552 print_indent(indent);
4553 outs() << " remaining list entries extend past the of the section\n";
4554 break;
4555 }
4556 print_indent(indent);
4557 outs() << " list[" << i << "]\n";
4558 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
4559 sizeof(struct objc_method_description_t));
4560 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4561 swapStruct(md);
4562
4563 print_indent(indent);
4564 outs() << " name " << format("0x%08" PRIx32, md.name);
4565 if (info->verbose) {
4566 name = get_pointer_32(md.name, offset, xleft, S, info, true);
4567 if (name != nullptr)
4568 outs() << format(" %.*s", xleft, name);
4569 else
4570 outs() << " (not in an __OBJC section)";
4571 }
4572 outs() << "\n";
4573
4574 print_indent(indent);
4575 outs() << " types " << format("0x%08" PRIx32, md.types);
4576 if (info->verbose) {
4577 name = get_pointer_32(md.types, offset, xleft, S, info, true);
4578 if (name != nullptr)
4579 outs() << format(" %.*s", xleft, name);
4580 else
4581 outs() << " (not in an __OBJC section)";
4582 }
4583 outs() << "\n";
4584 }
4585 return false;
4586}
4587
4588static bool print_protocol_list(uint32_t p, uint32_t indent,
4589 struct DisassembleInfo *info);
4590
4591static bool print_protocol(uint32_t p, uint32_t indent,
4592 struct DisassembleInfo *info) {
4593 uint32_t offset, left;
4594 SectionRef S;
4595 struct objc_protocol_t protocol;
4596 const char *r, *name;
4597
4598 r = get_pointer_32(p, offset, left, S, info, true);
4599 if (r == nullptr)
4600 return true;
4601
4602 outs() << "\n";
4603 if (left >= sizeof(struct objc_protocol_t)) {
4604 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
4605 } else {
4606 print_indent(indent);
4607 outs() << " Protocol extends past end of the section\n";
4608 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
4609 memcpy(&protocol, r, left);
4610 }
4611 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4612 swapStruct(protocol);
4613
4614 print_indent(indent);
4615 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
4616 << "\n";
4617
4618 print_indent(indent);
4619 outs() << " protocol_name "
4620 << format("0x%08" PRIx32, protocol.protocol_name);
4621 if (info->verbose) {
4622 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
4623 if (name != nullptr)
4624 outs() << format(" %.*s", left, name);
4625 else
4626 outs() << " (not in an __OBJC section)";
4627 }
4628 outs() << "\n";
4629
4630 print_indent(indent);
4631 outs() << " protocol_list "
4632 << format("0x%08" PRIx32, protocol.protocol_list);
4633 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
4634 outs() << " (not in an __OBJC section)\n";
4635
4636 print_indent(indent);
4637 outs() << " instance_methods "
4638 << format("0x%08" PRIx32, protocol.instance_methods);
4639 if (print_method_description_list(protocol.instance_methods, indent, info))
4640 outs() << " (not in an __OBJC section)\n";
4641
4642 print_indent(indent);
4643 outs() << " class_methods "
4644 << format("0x%08" PRIx32, protocol.class_methods);
4645 if (print_method_description_list(protocol.class_methods, indent, info))
4646 outs() << " (not in an __OBJC section)\n";
4647
4648 return false;
4649}
4650
4651static bool print_protocol_list(uint32_t p, uint32_t indent,
4652 struct DisassembleInfo *info) {
4653 uint32_t offset, left, l;
4654 SectionRef S;
4655 struct objc_protocol_list_t protocol_list;
4656 const char *r, *list;
4657 int32_t i;
4658
4659 r = get_pointer_32(p, offset, left, S, info, true);
4660 if (r == nullptr)
4661 return true;
4662
4663 outs() << "\n";
4664 if (left > sizeof(struct objc_protocol_list_t)) {
4665 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4666 } else {
4667 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4668 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4669 memcpy(&protocol_list, r, left);
4670 }
4671 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4672 swapStruct(protocol_list);
4673
4674 print_indent(indent);
4675 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
4676 << "\n";
4677 print_indent(indent);
4678 outs() << " count " << protocol_list.count << "\n";
4679
4680 list = r + sizeof(struct objc_protocol_list_t);
4681 for (i = 0; i < protocol_list.count; i++) {
4682 if ((i + 1) * sizeof(uint32_t) > left) {
4683 outs() << "\t\t remaining list entries extend past the of the section\n";
4684 break;
4685 }
4686 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4687 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4688 sys::swapByteOrder(l);
4689
4690 print_indent(indent);
4691 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
4692 if (print_protocol(l, indent, info))
4693 outs() << "(not in an __OBJC section)\n";
4694 }
4695 return false;
4696}
4697
Kevin Enderby0fc11822015-04-01 20:57:01 +00004698static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4699 struct ivar_list64_t il;
4700 struct ivar64_t i;
4701 const char *r;
4702 uint32_t offset, xoffset, left, j;
4703 SectionRef S, xS;
4704 const char *name, *sym_name, *ivar_offset_p;
4705 uint64_t ivar_offset, n_value;
4706
4707 r = get_pointer_64(p, offset, left, S, info);
4708 if (r == nullptr)
4709 return;
4710 memset(&il, '\0', sizeof(struct ivar_list64_t));
4711 if (left < sizeof(struct ivar_list64_t)) {
4712 memcpy(&il, r, left);
4713 outs() << " (ivar_list_t entends past the end of the section)\n";
4714 } else
4715 memcpy(&il, r, sizeof(struct ivar_list64_t));
4716 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4717 swapStruct(il);
4718 outs() << " entsize " << il.entsize << "\n";
4719 outs() << " count " << il.count << "\n";
4720
4721 p += sizeof(struct ivar_list64_t);
4722 offset += sizeof(struct ivar_list64_t);
4723 for (j = 0; j < il.count; j++) {
4724 r = get_pointer_64(p, offset, left, S, info);
4725 if (r == nullptr)
4726 return;
4727 memset(&i, '\0', sizeof(struct ivar64_t));
4728 if (left < sizeof(struct ivar64_t)) {
4729 memcpy(&i, r, left);
4730 outs() << " (ivar_t entends past the end of the section)\n";
4731 } else
4732 memcpy(&i, r, sizeof(struct ivar64_t));
4733 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4734 swapStruct(i);
4735
4736 outs() << "\t\t\t offset ";
4737 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4738 info, n_value, i.offset);
4739 if (n_value != 0) {
4740 if (info->verbose && sym_name != nullptr)
4741 outs() << sym_name;
4742 else
4743 outs() << format("0x%" PRIx64, n_value);
4744 if (i.offset != 0)
4745 outs() << " + " << format("0x%" PRIx64, i.offset);
4746 } else
4747 outs() << format("0x%" PRIx64, i.offset);
4748 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4749 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4750 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4751 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4752 sys::swapByteOrder(ivar_offset);
4753 outs() << " " << ivar_offset << "\n";
4754 } else
4755 outs() << "\n";
4756
4757 outs() << "\t\t\t name ";
4758 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4759 n_value, i.name);
4760 if (n_value != 0) {
4761 if (info->verbose && sym_name != nullptr)
4762 outs() << sym_name;
4763 else
4764 outs() << format("0x%" PRIx64, n_value);
4765 if (i.name != 0)
4766 outs() << " + " << format("0x%" PRIx64, i.name);
4767 } else
4768 outs() << format("0x%" PRIx64, i.name);
4769 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4770 if (name != nullptr)
4771 outs() << format(" %.*s", left, name);
4772 outs() << "\n";
4773
4774 outs() << "\t\t\t type ";
4775 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4776 n_value, i.name);
4777 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4778 if (n_value != 0) {
4779 if (info->verbose && sym_name != nullptr)
4780 outs() << sym_name;
4781 else
4782 outs() << format("0x%" PRIx64, n_value);
4783 if (i.type != 0)
4784 outs() << " + " << format("0x%" PRIx64, i.type);
4785 } else
4786 outs() << format("0x%" PRIx64, i.type);
4787 if (name != nullptr)
4788 outs() << format(" %.*s", left, name);
4789 outs() << "\n";
4790
4791 outs() << "\t\t\talignment " << i.alignment << "\n";
4792 outs() << "\t\t\t size " << i.size << "\n";
4793
4794 p += sizeof(struct ivar64_t);
4795 offset += sizeof(struct ivar64_t);
4796 }
4797}
4798
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004799static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4800 struct ivar_list32_t il;
4801 struct ivar32_t i;
4802 const char *r;
4803 uint32_t offset, xoffset, left, j;
4804 SectionRef S, xS;
4805 const char *name, *ivar_offset_p;
4806 uint32_t ivar_offset;
4807
4808 r = get_pointer_32(p, offset, left, S, info);
4809 if (r == nullptr)
4810 return;
4811 memset(&il, '\0', sizeof(struct ivar_list32_t));
4812 if (left < sizeof(struct ivar_list32_t)) {
4813 memcpy(&il, r, left);
4814 outs() << " (ivar_list_t entends past the end of the section)\n";
4815 } else
4816 memcpy(&il, r, sizeof(struct ivar_list32_t));
4817 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4818 swapStruct(il);
4819 outs() << " entsize " << il.entsize << "\n";
4820 outs() << " count " << il.count << "\n";
4821
4822 p += sizeof(struct ivar_list32_t);
4823 offset += sizeof(struct ivar_list32_t);
4824 for (j = 0; j < il.count; j++) {
4825 r = get_pointer_32(p, offset, left, S, info);
4826 if (r == nullptr)
4827 return;
4828 memset(&i, '\0', sizeof(struct ivar32_t));
4829 if (left < sizeof(struct ivar32_t)) {
4830 memcpy(&i, r, left);
4831 outs() << " (ivar_t entends past the end of the section)\n";
4832 } else
4833 memcpy(&i, r, sizeof(struct ivar32_t));
4834 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4835 swapStruct(i);
4836
4837 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4838 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4839 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4840 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4841 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4842 sys::swapByteOrder(ivar_offset);
4843 outs() << " " << ivar_offset << "\n";
4844 } else
4845 outs() << "\n";
4846
4847 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4848 name = get_pointer_32(i.name, xoffset, left, xS, info);
4849 if (name != nullptr)
4850 outs() << format(" %.*s", left, name);
4851 outs() << "\n";
4852
4853 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4854 name = get_pointer_32(i.type, xoffset, left, xS, info);
4855 if (name != nullptr)
4856 outs() << format(" %.*s", left, name);
4857 outs() << "\n";
4858
4859 outs() << "\t\t\talignment " << i.alignment << "\n";
4860 outs() << "\t\t\t size " << i.size << "\n";
4861
4862 p += sizeof(struct ivar32_t);
4863 offset += sizeof(struct ivar32_t);
4864 }
4865}
4866
Kevin Enderby0fc11822015-04-01 20:57:01 +00004867static void print_objc_property_list64(uint64_t p,
4868 struct DisassembleInfo *info) {
4869 struct objc_property_list64 opl;
4870 struct objc_property64 op;
4871 const char *r;
4872 uint32_t offset, xoffset, left, j;
4873 SectionRef S, xS;
4874 const char *name, *sym_name;
4875 uint64_t n_value;
4876
4877 r = get_pointer_64(p, offset, left, S, info);
4878 if (r == nullptr)
4879 return;
4880 memset(&opl, '\0', sizeof(struct objc_property_list64));
4881 if (left < sizeof(struct objc_property_list64)) {
4882 memcpy(&opl, r, left);
4883 outs() << " (objc_property_list entends past the end of the section)\n";
4884 } else
4885 memcpy(&opl, r, sizeof(struct objc_property_list64));
4886 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4887 swapStruct(opl);
4888 outs() << " entsize " << opl.entsize << "\n";
4889 outs() << " count " << opl.count << "\n";
4890
4891 p += sizeof(struct objc_property_list64);
4892 offset += sizeof(struct objc_property_list64);
4893 for (j = 0; j < opl.count; j++) {
4894 r = get_pointer_64(p, offset, left, S, info);
4895 if (r == nullptr)
4896 return;
4897 memset(&op, '\0', sizeof(struct objc_property64));
4898 if (left < sizeof(struct objc_property64)) {
4899 memcpy(&op, r, left);
4900 outs() << " (objc_property entends past the end of the section)\n";
4901 } else
4902 memcpy(&op, r, sizeof(struct objc_property64));
4903 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4904 swapStruct(op);
4905
4906 outs() << "\t\t\t name ";
4907 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4908 info, n_value, op.name);
4909 if (n_value != 0) {
4910 if (info->verbose && sym_name != nullptr)
4911 outs() << sym_name;
4912 else
4913 outs() << format("0x%" PRIx64, n_value);
4914 if (op.name != 0)
4915 outs() << " + " << format("0x%" PRIx64, op.name);
4916 } else
4917 outs() << format("0x%" PRIx64, op.name);
4918 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4919 if (name != nullptr)
4920 outs() << format(" %.*s", left, name);
4921 outs() << "\n";
4922
4923 outs() << "\t\t\tattributes ";
4924 sym_name =
4925 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4926 info, n_value, op.attributes);
4927 if (n_value != 0) {
4928 if (info->verbose && sym_name != nullptr)
4929 outs() << sym_name;
4930 else
4931 outs() << format("0x%" PRIx64, n_value);
4932 if (op.attributes != 0)
4933 outs() << " + " << format("0x%" PRIx64, op.attributes);
4934 } else
4935 outs() << format("0x%" PRIx64, op.attributes);
4936 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4937 if (name != nullptr)
4938 outs() << format(" %.*s", left, name);
4939 outs() << "\n";
4940
4941 p += sizeof(struct objc_property64);
4942 offset += sizeof(struct objc_property64);
4943 }
4944}
4945
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004946static void print_objc_property_list32(uint32_t p,
4947 struct DisassembleInfo *info) {
4948 struct objc_property_list32 opl;
4949 struct objc_property32 op;
4950 const char *r;
4951 uint32_t offset, xoffset, left, j;
4952 SectionRef S, xS;
4953 const char *name;
4954
4955 r = get_pointer_32(p, offset, left, S, info);
4956 if (r == nullptr)
4957 return;
4958 memset(&opl, '\0', sizeof(struct objc_property_list32));
4959 if (left < sizeof(struct objc_property_list32)) {
4960 memcpy(&opl, r, left);
4961 outs() << " (objc_property_list entends past the end of the section)\n";
4962 } else
4963 memcpy(&opl, r, sizeof(struct objc_property_list32));
4964 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4965 swapStruct(opl);
4966 outs() << " entsize " << opl.entsize << "\n";
4967 outs() << " count " << opl.count << "\n";
4968
4969 p += sizeof(struct objc_property_list32);
4970 offset += sizeof(struct objc_property_list32);
4971 for (j = 0; j < opl.count; j++) {
4972 r = get_pointer_32(p, offset, left, S, info);
4973 if (r == nullptr)
4974 return;
4975 memset(&op, '\0', sizeof(struct objc_property32));
4976 if (left < sizeof(struct objc_property32)) {
4977 memcpy(&op, r, left);
4978 outs() << " (objc_property entends past the end of the section)\n";
4979 } else
4980 memcpy(&op, r, sizeof(struct objc_property32));
4981 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4982 swapStruct(op);
4983
4984 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4985 name = get_pointer_32(op.name, xoffset, left, xS, info);
4986 if (name != nullptr)
4987 outs() << format(" %.*s", left, name);
4988 outs() << "\n";
4989
4990 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4991 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4992 if (name != nullptr)
4993 outs() << format(" %.*s", left, name);
4994 outs() << "\n";
4995
4996 p += sizeof(struct objc_property32);
4997 offset += sizeof(struct objc_property32);
4998 }
4999}
5000
Richard Smith81ff44d2015-10-09 22:09:56 +00005001static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
Kevin Enderby0fc11822015-04-01 20:57:01 +00005002 bool &is_meta_class) {
5003 struct class_ro64_t cro;
5004 const char *r;
5005 uint32_t offset, xoffset, left;
5006 SectionRef S, xS;
5007 const char *name, *sym_name;
5008 uint64_t n_value;
5009
5010 r = get_pointer_64(p, offset, left, S, info);
5011 if (r == nullptr || left < sizeof(struct class_ro64_t))
Richard Smith81ff44d2015-10-09 22:09:56 +00005012 return false;
Chandler Carruth33e58902016-11-04 07:10:24 +00005013 memcpy(&cro, r, sizeof(struct class_ro64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00005014 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5015 swapStruct(cro);
5016 outs() << " flags " << format("0x%" PRIx32, cro.flags);
5017 if (cro.flags & RO_META)
5018 outs() << " RO_META";
5019 if (cro.flags & RO_ROOT)
5020 outs() << " RO_ROOT";
5021 if (cro.flags & RO_HAS_CXX_STRUCTORS)
5022 outs() << " RO_HAS_CXX_STRUCTORS";
5023 outs() << "\n";
5024 outs() << " instanceStart " << cro.instanceStart << "\n";
5025 outs() << " instanceSize " << cro.instanceSize << "\n";
5026 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
5027 << "\n";
5028 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
5029 << "\n";
5030 print_layout_map64(cro.ivarLayout, info);
5031
5032 outs() << " name ";
5033 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
5034 info, n_value, cro.name);
5035 if (n_value != 0) {
5036 if (info->verbose && sym_name != nullptr)
5037 outs() << sym_name;
5038 else
5039 outs() << format("0x%" PRIx64, n_value);
5040 if (cro.name != 0)
5041 outs() << " + " << format("0x%" PRIx64, cro.name);
5042 } else
5043 outs() << format("0x%" PRIx64, cro.name);
5044 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
5045 if (name != nullptr)
5046 outs() << format(" %.*s", left, name);
5047 outs() << "\n";
5048
5049 outs() << " baseMethods ";
5050 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
5051 S, info, n_value, cro.baseMethods);
5052 if (n_value != 0) {
5053 if (info->verbose && sym_name != nullptr)
5054 outs() << sym_name;
5055 else
5056 outs() << format("0x%" PRIx64, n_value);
5057 if (cro.baseMethods != 0)
5058 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
5059 } else
5060 outs() << format("0x%" PRIx64, cro.baseMethods);
5061 outs() << " (struct method_list_t *)\n";
5062 if (cro.baseMethods + n_value != 0)
5063 print_method_list64_t(cro.baseMethods + n_value, info, "");
5064
5065 outs() << " baseProtocols ";
5066 sym_name =
5067 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
5068 info, n_value, cro.baseProtocols);
5069 if (n_value != 0) {
5070 if (info->verbose && sym_name != nullptr)
5071 outs() << sym_name;
5072 else
5073 outs() << format("0x%" PRIx64, n_value);
5074 if (cro.baseProtocols != 0)
5075 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
5076 } else
5077 outs() << format("0x%" PRIx64, cro.baseProtocols);
5078 outs() << "\n";
5079 if (cro.baseProtocols + n_value != 0)
5080 print_protocol_list64_t(cro.baseProtocols + n_value, info);
5081
5082 outs() << " ivars ";
5083 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005084 info, n_value, cro.ivars);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005085 if (n_value != 0) {
5086 if (info->verbose && sym_name != nullptr)
5087 outs() << sym_name;
5088 else
5089 outs() << format("0x%" PRIx64, n_value);
5090 if (cro.ivars != 0)
5091 outs() << " + " << format("0x%" PRIx64, cro.ivars);
5092 } else
5093 outs() << format("0x%" PRIx64, cro.ivars);
5094 outs() << "\n";
5095 if (cro.ivars + n_value != 0)
5096 print_ivar_list64_t(cro.ivars + n_value, info);
5097
5098 outs() << " weakIvarLayout ";
5099 sym_name =
5100 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
5101 info, n_value, cro.weakIvarLayout);
5102 if (n_value != 0) {
5103 if (info->verbose && sym_name != nullptr)
5104 outs() << sym_name;
5105 else
5106 outs() << format("0x%" PRIx64, n_value);
5107 if (cro.weakIvarLayout != 0)
5108 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
5109 } else
5110 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
5111 outs() << "\n";
5112 print_layout_map64(cro.weakIvarLayout + n_value, info);
5113
5114 outs() << " baseProperties ";
5115 sym_name =
5116 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
5117 info, n_value, cro.baseProperties);
5118 if (n_value != 0) {
5119 if (info->verbose && sym_name != nullptr)
5120 outs() << sym_name;
5121 else
5122 outs() << format("0x%" PRIx64, n_value);
5123 if (cro.baseProperties != 0)
5124 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
5125 } else
5126 outs() << format("0x%" PRIx64, cro.baseProperties);
5127 outs() << "\n";
5128 if (cro.baseProperties + n_value != 0)
5129 print_objc_property_list64(cro.baseProperties + n_value, info);
5130
Rafael Espindolab9091322015-10-24 23:19:10 +00005131 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00005132 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005133}
5134
Richard Smith81ff44d2015-10-09 22:09:56 +00005135static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005136 bool &is_meta_class) {
5137 struct class_ro32_t cro;
5138 const char *r;
5139 uint32_t offset, xoffset, left;
5140 SectionRef S, xS;
5141 const char *name;
5142
5143 r = get_pointer_32(p, offset, left, S, info);
5144 if (r == nullptr)
Richard Smith81ff44d2015-10-09 22:09:56 +00005145 return false;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005146 memset(&cro, '\0', sizeof(struct class_ro32_t));
5147 if (left < sizeof(struct class_ro32_t)) {
5148 memcpy(&cro, r, left);
5149 outs() << " (class_ro_t entends past the end of the section)\n";
5150 } else
5151 memcpy(&cro, r, sizeof(struct class_ro32_t));
5152 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5153 swapStruct(cro);
5154 outs() << " flags " << format("0x%" PRIx32, cro.flags);
5155 if (cro.flags & RO_META)
5156 outs() << " RO_META";
5157 if (cro.flags & RO_ROOT)
5158 outs() << " RO_ROOT";
5159 if (cro.flags & RO_HAS_CXX_STRUCTORS)
5160 outs() << " RO_HAS_CXX_STRUCTORS";
5161 outs() << "\n";
5162 outs() << " instanceStart " << cro.instanceStart << "\n";
5163 outs() << " instanceSize " << cro.instanceSize << "\n";
5164 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
5165 << "\n";
5166 print_layout_map32(cro.ivarLayout, info);
5167
5168 outs() << " name " << format("0x%" PRIx32, cro.name);
5169 name = get_pointer_32(cro.name, xoffset, left, xS, info);
5170 if (name != nullptr)
5171 outs() << format(" %.*s", left, name);
5172 outs() << "\n";
5173
5174 outs() << " baseMethods "
5175 << format("0x%" PRIx32, cro.baseMethods)
5176 << " (struct method_list_t *)\n";
5177 if (cro.baseMethods != 0)
5178 print_method_list32_t(cro.baseMethods, info, "");
5179
5180 outs() << " baseProtocols "
5181 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
5182 if (cro.baseProtocols != 0)
5183 print_protocol_list32_t(cro.baseProtocols, info);
5184 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
5185 << "\n";
5186 if (cro.ivars != 0)
5187 print_ivar_list32_t(cro.ivars, info);
5188 outs() << " weakIvarLayout "
5189 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
5190 print_layout_map32(cro.weakIvarLayout, info);
5191 outs() << " baseProperties "
5192 << format("0x%" PRIx32, cro.baseProperties) << "\n";
5193 if (cro.baseProperties != 0)
5194 print_objc_property_list32(cro.baseProperties, info);
Rafael Espindolab9091322015-10-24 23:19:10 +00005195 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00005196 return true;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005197}
5198
Kevin Enderby0fc11822015-04-01 20:57:01 +00005199static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
5200 struct class64_t c;
5201 const char *r;
5202 uint32_t offset, left;
5203 SectionRef S;
5204 const char *name;
5205 uint64_t isa_n_value, n_value;
5206
5207 r = get_pointer_64(p, offset, left, S, info);
5208 if (r == nullptr || left < sizeof(struct class64_t))
5209 return;
Chandler Carruth33e58902016-11-04 07:10:24 +00005210 memcpy(&c, r, sizeof(struct class64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00005211 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5212 swapStruct(c);
5213
5214 outs() << " isa " << format("0x%" PRIx64, c.isa);
5215 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
5216 isa_n_value, c.isa);
5217 if (name != nullptr)
5218 outs() << " " << name;
5219 outs() << "\n";
5220
5221 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
5222 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
5223 n_value, c.superclass);
5224 if (name != nullptr)
5225 outs() << " " << name;
Kevin Enderby1ce38582017-06-20 22:55:11 +00005226 else {
5227 name = get_dyld_bind_info_symbolname(S.getAddress() +
5228 offset + offsetof(struct class64_t, superclass), info);
5229 if (name != nullptr)
5230 outs() << " " << name;
5231 }
Kevin Enderby0fc11822015-04-01 20:57:01 +00005232 outs() << "\n";
5233
5234 outs() << " cache " << format("0x%" PRIx64, c.cache);
5235 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
5236 n_value, c.cache);
5237 if (name != nullptr)
5238 outs() << " " << name;
5239 outs() << "\n";
5240
5241 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
5242 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
5243 n_value, c.vtable);
5244 if (name != nullptr)
5245 outs() << " " << name;
5246 outs() << "\n";
5247
5248 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
5249 n_value, c.data);
5250 outs() << " data ";
5251 if (n_value != 0) {
5252 if (info->verbose && name != nullptr)
5253 outs() << name;
5254 else
5255 outs() << format("0x%" PRIx64, n_value);
5256 if (c.data != 0)
5257 outs() << " + " << format("0x%" PRIx64, c.data);
5258 } else
5259 outs() << format("0x%" PRIx64, c.data);
5260 outs() << " (struct class_ro_t *)";
5261
5262 // This is a Swift class if some of the low bits of the pointer are set.
5263 if ((c.data + n_value) & 0x7)
5264 outs() << " Swift class";
5265 outs() << "\n";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005266 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00005267 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
5268 return;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005269
Kevin Enderbyaac75382015-10-08 16:56:35 +00005270 if (!is_meta_class &&
5271 c.isa + isa_n_value != p &&
5272 c.isa + isa_n_value != 0 &&
5273 info->depth < 100) {
5274 info->depth++;
5275 outs() << "Meta Class\n";
5276 print_class64_t(c.isa + isa_n_value, info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005277 }
5278}
5279
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005280static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
5281 struct class32_t c;
5282 const char *r;
5283 uint32_t offset, left;
5284 SectionRef S;
5285 const char *name;
5286
5287 r = get_pointer_32(p, offset, left, S, info);
5288 if (r == nullptr)
5289 return;
5290 memset(&c, '\0', sizeof(struct class32_t));
5291 if (left < sizeof(struct class32_t)) {
5292 memcpy(&c, r, left);
5293 outs() << " (class_t entends past the end of the section)\n";
5294 } else
5295 memcpy(&c, r, sizeof(struct class32_t));
5296 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5297 swapStruct(c);
5298
5299 outs() << " isa " << format("0x%" PRIx32, c.isa);
5300 name =
5301 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
5302 if (name != nullptr)
5303 outs() << " " << name;
5304 outs() << "\n";
5305
5306 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
5307 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
5308 c.superclass);
5309 if (name != nullptr)
5310 outs() << " " << name;
5311 outs() << "\n";
5312
5313 outs() << " cache " << format("0x%" PRIx32, c.cache);
5314 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
5315 c.cache);
5316 if (name != nullptr)
5317 outs() << " " << name;
5318 outs() << "\n";
5319
5320 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
5321 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
5322 c.vtable);
5323 if (name != nullptr)
5324 outs() << " " << name;
5325 outs() << "\n";
5326
5327 name =
5328 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
5329 outs() << " data " << format("0x%" PRIx32, c.data)
5330 << " (struct class_ro_t *)";
5331
5332 // This is a Swift class if some of the low bits of the pointer are set.
5333 if (c.data & 0x3)
5334 outs() << " Swift class";
5335 outs() << "\n";
5336 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00005337 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
5338 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005339
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005340 if (!is_meta_class) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005341 outs() << "Meta Class\n";
5342 print_class32_t(c.isa, info);
5343 }
5344}
5345
Kevin Enderby846c0002015-04-16 17:19:59 +00005346static void print_objc_class_t(struct objc_class_t *objc_class,
5347 struct DisassembleInfo *info) {
5348 uint32_t offset, left, xleft;
5349 const char *name, *p, *ivar_list;
5350 SectionRef S;
5351 int32_t i;
5352 struct objc_ivar_list_t objc_ivar_list;
5353 struct objc_ivar_t ivar;
5354
5355 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
5356 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
5357 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
5358 if (name != nullptr)
5359 outs() << format(" %.*s", left, name);
5360 else
5361 outs() << " (not in an __OBJC section)";
5362 }
5363 outs() << "\n";
5364
5365 outs() << "\t super_class "
5366 << format("0x%08" PRIx32, objc_class->super_class);
5367 if (info->verbose) {
5368 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
5369 if (name != nullptr)
5370 outs() << format(" %.*s", left, name);
5371 else
5372 outs() << " (not in an __OBJC section)";
5373 }
5374 outs() << "\n";
5375
5376 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
5377 if (info->verbose) {
5378 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
5379 if (name != nullptr)
5380 outs() << format(" %.*s", left, name);
5381 else
5382 outs() << " (not in an __OBJC section)";
5383 }
5384 outs() << "\n";
5385
5386 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
5387 << "\n";
5388
5389 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
5390 if (info->verbose) {
5391 if (CLS_GETINFO(objc_class, CLS_CLASS))
5392 outs() << " CLS_CLASS";
5393 else if (CLS_GETINFO(objc_class, CLS_META))
5394 outs() << " CLS_META";
5395 }
5396 outs() << "\n";
5397
5398 outs() << "\t instance_size "
5399 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
5400
5401 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
5402 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
5403 if (p != nullptr) {
5404 if (left > sizeof(struct objc_ivar_list_t)) {
5405 outs() << "\n";
5406 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
5407 } else {
5408 outs() << " (entends past the end of the section)\n";
5409 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
5410 memcpy(&objc_ivar_list, p, left);
5411 }
5412 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5413 swapStruct(objc_ivar_list);
5414 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
5415 ivar_list = p + sizeof(struct objc_ivar_list_t);
5416 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
5417 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
5418 outs() << "\t\t remaining ivar's extend past the of the section\n";
5419 break;
5420 }
5421 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
5422 sizeof(struct objc_ivar_t));
5423 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5424 swapStruct(ivar);
5425
5426 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
5427 if (info->verbose) {
5428 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
5429 if (name != nullptr)
5430 outs() << format(" %.*s", xleft, name);
5431 else
5432 outs() << " (not in an __OBJC section)";
5433 }
5434 outs() << "\n";
5435
5436 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
5437 if (info->verbose) {
5438 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
5439 if (name != nullptr)
5440 outs() << format(" %.*s", xleft, name);
5441 else
5442 outs() << " (not in an __OBJC section)";
5443 }
5444 outs() << "\n";
5445
5446 outs() << "\t\t ivar_offset "
5447 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
5448 }
5449 } else {
5450 outs() << " (not in an __OBJC section)\n";
5451 }
5452
5453 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
5454 if (print_method_list(objc_class->methodLists, info))
5455 outs() << " (not in an __OBJC section)\n";
5456
5457 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
5458 << "\n";
5459
5460 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
5461 if (print_protocol_list(objc_class->protocols, 16, info))
5462 outs() << " (not in an __OBJC section)\n";
5463}
5464
5465static void print_objc_objc_category_t(struct objc_category_t *objc_category,
5466 struct DisassembleInfo *info) {
5467 uint32_t offset, left;
5468 const char *name;
5469 SectionRef S;
5470
5471 outs() << "\t category name "
5472 << format("0x%08" PRIx32, objc_category->category_name);
5473 if (info->verbose) {
5474 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
5475 true);
5476 if (name != nullptr)
5477 outs() << format(" %.*s", left, name);
5478 else
5479 outs() << " (not in an __OBJC section)";
5480 }
5481 outs() << "\n";
5482
5483 outs() << "\t\t class name "
5484 << format("0x%08" PRIx32, objc_category->class_name);
5485 if (info->verbose) {
5486 name =
5487 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
5488 if (name != nullptr)
5489 outs() << format(" %.*s", left, name);
5490 else
5491 outs() << " (not in an __OBJC section)";
5492 }
5493 outs() << "\n";
5494
5495 outs() << "\t instance methods "
5496 << format("0x%08" PRIx32, objc_category->instance_methods);
5497 if (print_method_list(objc_category->instance_methods, info))
5498 outs() << " (not in an __OBJC section)\n";
5499
5500 outs() << "\t class methods "
5501 << format("0x%08" PRIx32, objc_category->class_methods);
5502 if (print_method_list(objc_category->class_methods, info))
5503 outs() << " (not in an __OBJC section)\n";
5504}
5505
Kevin Enderby0fc11822015-04-01 20:57:01 +00005506static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
5507 struct category64_t c;
5508 const char *r;
5509 uint32_t offset, xoffset, left;
5510 SectionRef S, xS;
5511 const char *name, *sym_name;
5512 uint64_t n_value;
5513
5514 r = get_pointer_64(p, offset, left, S, info);
5515 if (r == nullptr)
5516 return;
5517 memset(&c, '\0', sizeof(struct category64_t));
5518 if (left < sizeof(struct category64_t)) {
5519 memcpy(&c, r, left);
5520 outs() << " (category_t entends past the end of the section)\n";
5521 } else
5522 memcpy(&c, r, sizeof(struct category64_t));
5523 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5524 swapStruct(c);
5525
5526 outs() << " name ";
5527 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
5528 info, n_value, c.name);
5529 if (n_value != 0) {
5530 if (info->verbose && sym_name != nullptr)
5531 outs() << sym_name;
5532 else
5533 outs() << format("0x%" PRIx64, n_value);
5534 if (c.name != 0)
5535 outs() << " + " << format("0x%" PRIx64, c.name);
5536 } else
5537 outs() << format("0x%" PRIx64, c.name);
5538 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
5539 if (name != nullptr)
5540 outs() << format(" %.*s", left, name);
5541 outs() << "\n";
5542
5543 outs() << " cls ";
5544 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
5545 n_value, c.cls);
5546 if (n_value != 0) {
5547 if (info->verbose && sym_name != nullptr)
5548 outs() << sym_name;
5549 else
5550 outs() << format("0x%" PRIx64, n_value);
5551 if (c.cls != 0)
5552 outs() << " + " << format("0x%" PRIx64, c.cls);
5553 } else
5554 outs() << format("0x%" PRIx64, c.cls);
5555 outs() << "\n";
5556 if (c.cls + n_value != 0)
5557 print_class64_t(c.cls + n_value, info);
5558
5559 outs() << " instanceMethods ";
5560 sym_name =
5561 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
5562 info, n_value, c.instanceMethods);
5563 if (n_value != 0) {
5564 if (info->verbose && sym_name != nullptr)
5565 outs() << sym_name;
5566 else
5567 outs() << format("0x%" PRIx64, n_value);
5568 if (c.instanceMethods != 0)
5569 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
5570 } else
5571 outs() << format("0x%" PRIx64, c.instanceMethods);
5572 outs() << "\n";
5573 if (c.instanceMethods + n_value != 0)
5574 print_method_list64_t(c.instanceMethods + n_value, info, "");
5575
5576 outs() << " classMethods ";
5577 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
5578 S, info, n_value, c.classMethods);
5579 if (n_value != 0) {
5580 if (info->verbose && sym_name != nullptr)
5581 outs() << sym_name;
5582 else
5583 outs() << format("0x%" PRIx64, n_value);
5584 if (c.classMethods != 0)
5585 outs() << " + " << format("0x%" PRIx64, c.classMethods);
5586 } else
5587 outs() << format("0x%" PRIx64, c.classMethods);
5588 outs() << "\n";
5589 if (c.classMethods + n_value != 0)
5590 print_method_list64_t(c.classMethods + n_value, info, "");
5591
5592 outs() << " protocols ";
5593 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
5594 info, n_value, c.protocols);
5595 if (n_value != 0) {
5596 if (info->verbose && sym_name != nullptr)
5597 outs() << sym_name;
5598 else
5599 outs() << format("0x%" PRIx64, n_value);
5600 if (c.protocols != 0)
5601 outs() << " + " << format("0x%" PRIx64, c.protocols);
5602 } else
5603 outs() << format("0x%" PRIx64, c.protocols);
5604 outs() << "\n";
5605 if (c.protocols + n_value != 0)
5606 print_protocol_list64_t(c.protocols + n_value, info);
5607
5608 outs() << "instanceProperties ";
5609 sym_name =
5610 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
5611 S, info, n_value, c.instanceProperties);
5612 if (n_value != 0) {
5613 if (info->verbose && sym_name != nullptr)
5614 outs() << sym_name;
5615 else
5616 outs() << format("0x%" PRIx64, n_value);
5617 if (c.instanceProperties != 0)
5618 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
5619 } else
5620 outs() << format("0x%" PRIx64, c.instanceProperties);
5621 outs() << "\n";
5622 if (c.instanceProperties + n_value != 0)
5623 print_objc_property_list64(c.instanceProperties + n_value, info);
5624}
5625
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005626static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
5627 struct category32_t c;
5628 const char *r;
5629 uint32_t offset, left;
5630 SectionRef S, xS;
5631 const char *name;
5632
5633 r = get_pointer_32(p, offset, left, S, info);
5634 if (r == nullptr)
5635 return;
5636 memset(&c, '\0', sizeof(struct category32_t));
5637 if (left < sizeof(struct category32_t)) {
5638 memcpy(&c, r, left);
5639 outs() << " (category_t entends past the end of the section)\n";
5640 } else
5641 memcpy(&c, r, sizeof(struct category32_t));
5642 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5643 swapStruct(c);
5644
5645 outs() << " name " << format("0x%" PRIx32, c.name);
5646 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
5647 c.name);
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005648 if (name)
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005649 outs() << " " << name;
5650 outs() << "\n";
5651
5652 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
5653 if (c.cls != 0)
5654 print_class32_t(c.cls, info);
5655 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
5656 << "\n";
5657 if (c.instanceMethods != 0)
5658 print_method_list32_t(c.instanceMethods, info, "");
5659 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
5660 << "\n";
5661 if (c.classMethods != 0)
5662 print_method_list32_t(c.classMethods, info, "");
5663 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
5664 if (c.protocols != 0)
5665 print_protocol_list32_t(c.protocols, info);
5666 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
5667 << "\n";
5668 if (c.instanceProperties != 0)
5669 print_objc_property_list32(c.instanceProperties, info);
5670}
5671
Kevin Enderby0fc11822015-04-01 20:57:01 +00005672static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5673 uint32_t i, left, offset, xoffset;
5674 uint64_t p, n_value;
5675 struct message_ref64 mr;
5676 const char *name, *sym_name;
5677 const char *r;
5678 SectionRef xS;
5679
5680 if (S == SectionRef())
5681 return;
5682
5683 StringRef SectName;
5684 S.getName(SectName);
5685 DataRefImpl Ref = S.getRawDataRefImpl();
5686 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5687 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5688 offset = 0;
5689 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5690 p = S.getAddress() + i;
5691 r = get_pointer_64(p, offset, left, S, info);
5692 if (r == nullptr)
5693 return;
5694 memset(&mr, '\0', sizeof(struct message_ref64));
5695 if (left < sizeof(struct message_ref64)) {
5696 memcpy(&mr, r, left);
5697 outs() << " (message_ref entends past the end of the section)\n";
5698 } else
5699 memcpy(&mr, r, sizeof(struct message_ref64));
5700 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5701 swapStruct(mr);
5702
5703 outs() << " imp ";
5704 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5705 n_value, mr.imp);
5706 if (n_value != 0) {
5707 outs() << format("0x%" PRIx64, n_value) << " ";
5708 if (mr.imp != 0)
5709 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5710 } else
5711 outs() << format("0x%" PRIx64, mr.imp) << " ";
5712 if (name != nullptr)
5713 outs() << " " << name;
5714 outs() << "\n";
5715
5716 outs() << " sel ";
5717 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5718 info, n_value, mr.sel);
5719 if (n_value != 0) {
5720 if (info->verbose && sym_name != nullptr)
5721 outs() << sym_name;
5722 else
5723 outs() << format("0x%" PRIx64, n_value);
5724 if (mr.sel != 0)
5725 outs() << " + " << format("0x%" PRIx64, mr.sel);
5726 } else
5727 outs() << format("0x%" PRIx64, mr.sel);
5728 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5729 if (name != nullptr)
5730 outs() << format(" %.*s", left, name);
5731 outs() << "\n";
5732
5733 offset += sizeof(struct message_ref64);
5734 }
5735}
5736
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005737static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5738 uint32_t i, left, offset, xoffset, p;
5739 struct message_ref32 mr;
5740 const char *name, *r;
5741 SectionRef xS;
5742
5743 if (S == SectionRef())
5744 return;
5745
5746 StringRef SectName;
5747 S.getName(SectName);
5748 DataRefImpl Ref = S.getRawDataRefImpl();
5749 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5750 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5751 offset = 0;
5752 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5753 p = S.getAddress() + i;
5754 r = get_pointer_32(p, offset, left, S, info);
5755 if (r == nullptr)
5756 return;
5757 memset(&mr, '\0', sizeof(struct message_ref32));
5758 if (left < sizeof(struct message_ref32)) {
5759 memcpy(&mr, r, left);
5760 outs() << " (message_ref entends past the end of the section)\n";
5761 } else
5762 memcpy(&mr, r, sizeof(struct message_ref32));
5763 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5764 swapStruct(mr);
5765
5766 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5767 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5768 mr.imp);
5769 if (name != nullptr)
5770 outs() << " " << name;
5771 outs() << "\n";
5772
5773 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5774 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5775 if (name != nullptr)
5776 outs() << " " << name;
5777 outs() << "\n";
5778
5779 offset += sizeof(struct message_ref32);
5780 }
5781}
5782
Kevin Enderby0fc11822015-04-01 20:57:01 +00005783static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5784 uint32_t left, offset, swift_version;
5785 uint64_t p;
5786 struct objc_image_info64 o;
5787 const char *r;
5788
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00005789 if (S == SectionRef())
5790 return;
5791
Kevin Enderby0fc11822015-04-01 20:57:01 +00005792 StringRef SectName;
5793 S.getName(SectName);
5794 DataRefImpl Ref = S.getRawDataRefImpl();
5795 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5796 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5797 p = S.getAddress();
5798 r = get_pointer_64(p, offset, left, S, info);
5799 if (r == nullptr)
5800 return;
5801 memset(&o, '\0', sizeof(struct objc_image_info64));
5802 if (left < sizeof(struct objc_image_info64)) {
5803 memcpy(&o, r, left);
5804 outs() << " (objc_image_info entends past the end of the section)\n";
5805 } else
5806 memcpy(&o, r, sizeof(struct objc_image_info64));
5807 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5808 swapStruct(o);
5809 outs() << " version " << o.version << "\n";
5810 outs() << " flags " << format("0x%" PRIx32, o.flags);
5811 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5812 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5813 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5814 outs() << " OBJC_IMAGE_SUPPORTS_GC";
Dave Lee390abe42018-07-06 05:11:35 +00005815 if (o.flags & OBJC_IMAGE_IS_SIMULATED)
5816 outs() << " OBJC_IMAGE_IS_SIMULATED";
5817 if (o.flags & OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES)
5818 outs() << " OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES";
Kevin Enderby0fc11822015-04-01 20:57:01 +00005819 swift_version = (o.flags >> 8) & 0xff;
5820 if (swift_version != 0) {
5821 if (swift_version == 1)
5822 outs() << " Swift 1.0";
5823 else if (swift_version == 2)
5824 outs() << " Swift 1.1";
Kevin Enderbycda2ced2018-02-09 19:31:27 +00005825 else if(swift_version == 3)
5826 outs() << " Swift 2.0";
5827 else if(swift_version == 4)
5828 outs() << " Swift 3.0";
5829 else if(swift_version == 5)
5830 outs() << " Swift 4.0";
5831 else if(swift_version == 6)
Michael Trentf7254a62018-12-07 19:55:03 +00005832 outs() << " Swift 4.1/Swift 4.2";
5833 else if(swift_version == 7)
5834 outs() << " Swift 5 or later";
Kevin Enderby0fc11822015-04-01 20:57:01 +00005835 else
5836 outs() << " unknown future Swift version (" << swift_version << ")";
5837 }
5838 outs() << "\n";
5839}
5840
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005841static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5842 uint32_t left, offset, swift_version, p;
5843 struct objc_image_info32 o;
5844 const char *r;
5845
Kevin Enderby19be2512016-04-21 19:49:29 +00005846 if (S == SectionRef())
5847 return;
5848
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005849 StringRef SectName;
5850 S.getName(SectName);
5851 DataRefImpl Ref = S.getRawDataRefImpl();
5852 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5853 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5854 p = S.getAddress();
5855 r = get_pointer_32(p, offset, left, S, info);
5856 if (r == nullptr)
5857 return;
5858 memset(&o, '\0', sizeof(struct objc_image_info32));
5859 if (left < sizeof(struct objc_image_info32)) {
5860 memcpy(&o, r, left);
5861 outs() << " (objc_image_info entends past the end of the section)\n";
5862 } else
5863 memcpy(&o, r, sizeof(struct objc_image_info32));
5864 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5865 swapStruct(o);
5866 outs() << " version " << o.version << "\n";
5867 outs() << " flags " << format("0x%" PRIx32, o.flags);
5868 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5869 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5870 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5871 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5872 swift_version = (o.flags >> 8) & 0xff;
5873 if (swift_version != 0) {
5874 if (swift_version == 1)
5875 outs() << " Swift 1.0";
5876 else if (swift_version == 2)
5877 outs() << " Swift 1.1";
Kevin Enderbycda2ced2018-02-09 19:31:27 +00005878 else if(swift_version == 3)
5879 outs() << " Swift 2.0";
5880 else if(swift_version == 4)
5881 outs() << " Swift 3.0";
5882 else if(swift_version == 5)
5883 outs() << " Swift 4.0";
5884 else if(swift_version == 6)
Michael Trentf7254a62018-12-07 19:55:03 +00005885 outs() << " Swift 4.1/Swift 4.2";
5886 else if(swift_version == 7)
5887 outs() << " Swift 5 or later";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005888 else
5889 outs() << " unknown future Swift version (" << swift_version << ")";
5890 }
5891 outs() << "\n";
5892}
5893
Kevin Enderby846c0002015-04-16 17:19:59 +00005894static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5895 uint32_t left, offset, p;
5896 struct imageInfo_t o;
5897 const char *r;
5898
5899 StringRef SectName;
5900 S.getName(SectName);
5901 DataRefImpl Ref = S.getRawDataRefImpl();
5902 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5903 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5904 p = S.getAddress();
5905 r = get_pointer_32(p, offset, left, S, info);
5906 if (r == nullptr)
5907 return;
5908 memset(&o, '\0', sizeof(struct imageInfo_t));
5909 if (left < sizeof(struct imageInfo_t)) {
5910 memcpy(&o, r, left);
5911 outs() << " (imageInfo entends past the end of the section)\n";
5912 } else
5913 memcpy(&o, r, sizeof(struct imageInfo_t));
5914 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5915 swapStruct(o);
5916 outs() << " version " << o.version << "\n";
5917 outs() << " flags " << format("0x%" PRIx32, o.flags);
5918 if (o.flags & 0x1)
5919 outs() << " F&C";
5920 if (o.flags & 0x2)
5921 outs() << " GC";
5922 if (o.flags & 0x4)
5923 outs() << " GC-only";
5924 else
5925 outs() << " RR";
5926 outs() << "\n";
5927}
5928
Kevin Enderby0fc11822015-04-01 20:57:01 +00005929static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5930 SymbolAddressMap AddrMap;
5931 if (verbose)
5932 CreateSymbolAddressMap(O, &AddrMap);
5933
5934 std::vector<SectionRef> Sections;
5935 for (const SectionRef &Section : O->sections()) {
5936 StringRef SectName;
5937 Section.getName(SectName);
5938 Sections.push_back(Section);
5939 }
5940
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00005941 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005942
Davide Italiano62507042015-12-11 22:27:59 +00005943 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5944 if (CL == SectionRef())
5945 CL = get_section(O, "__DATA", "__objc_classlist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005946 if (CL == SectionRef())
5947 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
5948 if (CL == SectionRef())
5949 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
Davide Italiano62507042015-12-11 22:27:59 +00005950 info.S = CL;
5951 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005952
Davide Italiano62507042015-12-11 22:27:59 +00005953 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5954 if (CR == SectionRef())
5955 CR = get_section(O, "__DATA", "__objc_classrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005956 if (CR == SectionRef())
5957 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
5958 if (CR == SectionRef())
5959 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005960 info.S = CR;
5961 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005962
Davide Italiano62507042015-12-11 22:27:59 +00005963 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5964 if (SR == SectionRef())
5965 SR = get_section(O, "__DATA", "__objc_superrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005966 if (SR == SectionRef())
5967 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
5968 if (SR == SectionRef())
5969 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005970 info.S = SR;
5971 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005972
Davide Italiano62507042015-12-11 22:27:59 +00005973 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5974 if (CA == SectionRef())
5975 CA = get_section(O, "__DATA", "__objc_catlist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005976 if (CA == SectionRef())
5977 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
5978 if (CA == SectionRef())
5979 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
Davide Italiano62507042015-12-11 22:27:59 +00005980 info.S = CA;
5981 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005982
Davide Italiano62507042015-12-11 22:27:59 +00005983 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5984 if (PL == SectionRef())
5985 PL = get_section(O, "__DATA", "__objc_protolist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005986 if (PL == SectionRef())
5987 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
5988 if (PL == SectionRef())
5989 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
Davide Italiano62507042015-12-11 22:27:59 +00005990 info.S = PL;
5991 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005992
Davide Italiano62507042015-12-11 22:27:59 +00005993 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5994 if (MR == SectionRef())
5995 MR = get_section(O, "__DATA", "__objc_msgrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005996 if (MR == SectionRef())
5997 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
5998 if (MR == SectionRef())
5999 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
Davide Italiano62507042015-12-11 22:27:59 +00006000 info.S = MR;
6001 print_message_refs64(MR, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006002
Davide Italiano62507042015-12-11 22:27:59 +00006003 SectionRef II = get_section(O, "__OBJC2", "__image_info");
6004 if (II == SectionRef())
6005 II = get_section(O, "__DATA", "__objc_imageinfo");
Kevin Enderby5879a482017-02-09 17:56:26 +00006006 if (II == SectionRef())
6007 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
6008 if (II == SectionRef())
6009 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
Davide Italiano62507042015-12-11 22:27:59 +00006010 info.S = II;
6011 print_image_info64(II, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006012}
6013
6014static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006015 SymbolAddressMap AddrMap;
6016 if (verbose)
6017 CreateSymbolAddressMap(O, &AddrMap);
6018
6019 std::vector<SectionRef> Sections;
6020 for (const SectionRef &Section : O->sections()) {
6021 StringRef SectName;
6022 Section.getName(SectName);
6023 Sections.push_back(Section);
6024 }
6025
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006026 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006027
Kevin Enderby5879a482017-02-09 17:56:26 +00006028 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
6029 if (CL == SectionRef())
6030 CL = get_section(O, "__DATA", "__objc_classlist");
6031 if (CL == SectionRef())
6032 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
6033 if (CL == SectionRef())
6034 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
6035 info.S = CL;
6036 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006037
Kevin Enderby5879a482017-02-09 17:56:26 +00006038 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
6039 if (CR == SectionRef())
6040 CR = get_section(O, "__DATA", "__objc_classrefs");
6041 if (CR == SectionRef())
6042 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
6043 if (CR == SectionRef())
6044 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
6045 info.S = CR;
6046 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006047
Kevin Enderby5879a482017-02-09 17:56:26 +00006048 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
6049 if (SR == SectionRef())
6050 SR = get_section(O, "__DATA", "__objc_superrefs");
6051 if (SR == SectionRef())
6052 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
6053 if (SR == SectionRef())
6054 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
6055 info.S = SR;
6056 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006057
Kevin Enderby5879a482017-02-09 17:56:26 +00006058 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
6059 if (CA == SectionRef())
6060 CA = get_section(O, "__DATA", "__objc_catlist");
6061 if (CA == SectionRef())
6062 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
6063 if (CA == SectionRef())
6064 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
6065 info.S = CA;
6066 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006067
Kevin Enderby5879a482017-02-09 17:56:26 +00006068 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
6069 if (PL == SectionRef())
6070 PL = get_section(O, "__DATA", "__objc_protolist");
6071 if (PL == SectionRef())
6072 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
6073 if (PL == SectionRef())
6074 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
6075 info.S = PL;
6076 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006077
Kevin Enderby5879a482017-02-09 17:56:26 +00006078 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
6079 if (MR == SectionRef())
6080 MR = get_section(O, "__DATA", "__objc_msgrefs");
6081 if (MR == SectionRef())
6082 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
6083 if (MR == SectionRef())
6084 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
6085 info.S = MR;
6086 print_message_refs32(MR, &info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006087
Kevin Enderby5879a482017-02-09 17:56:26 +00006088 SectionRef II = get_section(O, "__OBJC2", "__image_info");
6089 if (II == SectionRef())
6090 II = get_section(O, "__DATA", "__objc_imageinfo");
6091 if (II == SectionRef())
6092 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
6093 if (II == SectionRef())
6094 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
6095 info.S = II;
6096 print_image_info32(II, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006097}
6098
6099static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby846c0002015-04-16 17:19:59 +00006100 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
6101 const char *r, *name, *defs;
6102 struct objc_module_t module;
6103 SectionRef S, xS;
6104 struct objc_symtab_t symtab;
6105 struct objc_class_t objc_class;
6106 struct objc_category_t objc_category;
6107
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006108 outs() << "Objective-C segment\n";
Kevin Enderby846c0002015-04-16 17:19:59 +00006109 S = get_section(O, "__OBJC", "__module_info");
6110 if (S == SectionRef())
6111 return false;
6112
6113 SymbolAddressMap AddrMap;
6114 if (verbose)
6115 CreateSymbolAddressMap(O, &AddrMap);
6116
6117 std::vector<SectionRef> Sections;
6118 for (const SectionRef &Section : O->sections()) {
6119 StringRef SectName;
6120 Section.getName(SectName);
6121 Sections.push_back(Section);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006122 }
Kevin Enderby846c0002015-04-16 17:19:59 +00006123
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006124 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby846c0002015-04-16 17:19:59 +00006125
6126 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
6127 p = S.getAddress() + i;
6128 r = get_pointer_32(p, offset, left, S, &info, true);
6129 if (r == nullptr)
6130 return true;
6131 memset(&module, '\0', sizeof(struct objc_module_t));
6132 if (left < sizeof(struct objc_module_t)) {
6133 memcpy(&module, r, left);
6134 outs() << " (module extends past end of __module_info section)\n";
6135 } else
6136 memcpy(&module, r, sizeof(struct objc_module_t));
6137 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6138 swapStruct(module);
6139
6140 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
6141 outs() << " version " << module.version << "\n";
6142 outs() << " size " << module.size << "\n";
6143 outs() << " name ";
6144 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
6145 if (name != nullptr)
6146 outs() << format("%.*s", left, name);
6147 else
6148 outs() << format("0x%08" PRIx32, module.name)
6149 << "(not in an __OBJC section)";
6150 outs() << "\n";
6151
6152 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
6153 if (module.symtab == 0 || r == nullptr) {
6154 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
6155 << " (not in an __OBJC section)\n";
6156 continue;
6157 }
6158 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
6159 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
6160 defs_left = 0;
6161 defs = nullptr;
6162 if (left < sizeof(struct objc_symtab_t)) {
6163 memcpy(&symtab, r, left);
6164 outs() << "\tsymtab extends past end of an __OBJC section)\n";
6165 } else {
6166 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
6167 if (left > sizeof(struct objc_symtab_t)) {
6168 defs_left = left - sizeof(struct objc_symtab_t);
6169 defs = r + sizeof(struct objc_symtab_t);
6170 }
6171 }
6172 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6173 swapStruct(symtab);
6174
6175 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
6176 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
6177 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
6178 if (r == nullptr)
6179 outs() << " (not in an __OBJC section)";
6180 outs() << "\n";
6181 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
6182 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
6183 if (symtab.cls_def_cnt > 0)
6184 outs() << "\tClass Definitions\n";
6185 for (j = 0; j < symtab.cls_def_cnt; j++) {
6186 if ((j + 1) * sizeof(uint32_t) > defs_left) {
6187 outs() << "\t(remaining class defs entries entends past the end of the "
6188 << "section)\n";
6189 break;
6190 }
6191 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
6192 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6193 sys::swapByteOrder(def);
6194
6195 r = get_pointer_32(def, xoffset, left, xS, &info, true);
6196 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
6197 if (r != nullptr) {
6198 if (left > sizeof(struct objc_class_t)) {
6199 outs() << "\n";
6200 memcpy(&objc_class, r, sizeof(struct objc_class_t));
6201 } else {
6202 outs() << " (entends past the end of the section)\n";
6203 memset(&objc_class, '\0', sizeof(struct objc_class_t));
6204 memcpy(&objc_class, r, left);
6205 }
6206 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6207 swapStruct(objc_class);
6208 print_objc_class_t(&objc_class, &info);
6209 } else {
6210 outs() << "(not in an __OBJC section)\n";
6211 }
6212
6213 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
6214 outs() << "\tMeta Class";
6215 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
6216 if (r != nullptr) {
6217 if (left > sizeof(struct objc_class_t)) {
6218 outs() << "\n";
6219 memcpy(&objc_class, r, sizeof(struct objc_class_t));
6220 } else {
6221 outs() << " (entends past the end of the section)\n";
6222 memset(&objc_class, '\0', sizeof(struct objc_class_t));
6223 memcpy(&objc_class, r, left);
6224 }
6225 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6226 swapStruct(objc_class);
6227 print_objc_class_t(&objc_class, &info);
6228 } else {
6229 outs() << "(not in an __OBJC section)\n";
6230 }
6231 }
6232 }
6233 if (symtab.cat_def_cnt > 0)
6234 outs() << "\tCategory Definitions\n";
6235 for (j = 0; j < symtab.cat_def_cnt; j++) {
6236 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
6237 outs() << "\t(remaining category defs entries entends past the end of "
6238 << "the section)\n";
6239 break;
6240 }
6241 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
6242 sizeof(uint32_t));
6243 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6244 sys::swapByteOrder(def);
6245
6246 r = get_pointer_32(def, xoffset, left, xS, &info, true);
6247 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
6248 << format("0x%08" PRIx32, def);
6249 if (r != nullptr) {
6250 if (left > sizeof(struct objc_category_t)) {
6251 outs() << "\n";
6252 memcpy(&objc_category, r, sizeof(struct objc_category_t));
6253 } else {
6254 outs() << " (entends past the end of the section)\n";
6255 memset(&objc_category, '\0', sizeof(struct objc_category_t));
6256 memcpy(&objc_category, r, left);
6257 }
6258 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6259 swapStruct(objc_category);
6260 print_objc_objc_category_t(&objc_category, &info);
6261 } else {
6262 outs() << "(not in an __OBJC section)\n";
6263 }
6264 }
6265 }
6266 const SectionRef II = get_section(O, "__OBJC", "__image_info");
6267 if (II != SectionRef())
6268 print_image_info(II, &info);
6269
6270 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00006271}
6272
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00006273static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
6274 uint32_t size, uint32_t addr) {
6275 SymbolAddressMap AddrMap;
6276 CreateSymbolAddressMap(O, &AddrMap);
6277
6278 std::vector<SectionRef> Sections;
6279 for (const SectionRef &Section : O->sections()) {
6280 StringRef SectName;
6281 Section.getName(SectName);
6282 Sections.push_back(Section);
6283 }
6284
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006285 struct DisassembleInfo info(O, &AddrMap, &Sections, true);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00006286
6287 const char *p;
6288 struct objc_protocol_t protocol;
6289 uint32_t left, paddr;
6290 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
6291 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
6292 left = size - (p - sect);
6293 if (left < sizeof(struct objc_protocol_t)) {
6294 outs() << "Protocol extends past end of __protocol section\n";
6295 memcpy(&protocol, p, left);
6296 } else
6297 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
6298 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6299 swapStruct(protocol);
6300 paddr = addr + (p - sect);
6301 outs() << "Protocol " << format("0x%" PRIx32, paddr);
6302 if (print_protocol(paddr, 0, &info))
6303 outs() << "(not in an __OBJC section)\n";
6304 }
6305}
6306
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006307#ifdef HAVE_LIBXAR
6308inline void swapStruct(struct xar_header &xar) {
6309 sys::swapByteOrder(xar.magic);
6310 sys::swapByteOrder(xar.size);
6311 sys::swapByteOrder(xar.version);
6312 sys::swapByteOrder(xar.toc_length_compressed);
6313 sys::swapByteOrder(xar.toc_length_uncompressed);
6314 sys::swapByteOrder(xar.cksum_alg);
6315}
6316
6317static void PrintModeVerbose(uint32_t mode) {
6318 switch(mode & S_IFMT){
6319 case S_IFDIR:
6320 outs() << "d";
6321 break;
6322 case S_IFCHR:
6323 outs() << "c";
6324 break;
6325 case S_IFBLK:
6326 outs() << "b";
6327 break;
6328 case S_IFREG:
6329 outs() << "-";
6330 break;
6331 case S_IFLNK:
6332 outs() << "l";
6333 break;
6334 case S_IFSOCK:
6335 outs() << "s";
6336 break;
6337 default:
6338 outs() << "?";
6339 break;
6340 }
6341
6342 /* owner permissions */
6343 if(mode & S_IREAD)
6344 outs() << "r";
6345 else
6346 outs() << "-";
6347 if(mode & S_IWRITE)
6348 outs() << "w";
6349 else
6350 outs() << "-";
6351 if(mode & S_ISUID)
6352 outs() << "s";
6353 else if(mode & S_IEXEC)
6354 outs() << "x";
6355 else
6356 outs() << "-";
6357
6358 /* group permissions */
6359 if(mode & (S_IREAD >> 3))
6360 outs() << "r";
6361 else
6362 outs() << "-";
6363 if(mode & (S_IWRITE >> 3))
6364 outs() << "w";
6365 else
6366 outs() << "-";
6367 if(mode & S_ISGID)
6368 outs() << "s";
6369 else if(mode & (S_IEXEC >> 3))
6370 outs() << "x";
6371 else
6372 outs() << "-";
6373
6374 /* other permissions */
6375 if(mode & (S_IREAD >> 6))
6376 outs() << "r";
6377 else
6378 outs() << "-";
6379 if(mode & (S_IWRITE >> 6))
6380 outs() << "w";
6381 else
6382 outs() << "-";
6383 if(mode & S_ISVTX)
6384 outs() << "t";
6385 else if(mode & (S_IEXEC >> 6))
6386 outs() << "x";
6387 else
6388 outs() << "-";
6389}
6390
6391static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006392 xar_file_t xf;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006393 const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
6394 char *endp;
6395 uint32_t mode_value;
6396
Francis Ricci6f942972017-10-06 15:33:28 +00006397 ScopedXarIter xi;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006398 if (!xi) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006399 WithColor::error(errs(), "llvm-objdump")
6400 << "can't obtain an xar iterator for xar archive " << XarFilename
6401 << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006402 return;
6403 }
6404
6405 // Go through the xar's files.
6406 for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
Francis Ricci6f942972017-10-06 15:33:28 +00006407 ScopedXarIter xp;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006408 if(!xp){
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006409 WithColor::error(errs(), "llvm-objdump")
6410 << "can't obtain an xar iterator for xar archive " << XarFilename
6411 << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006412 return;
6413 }
6414 type = nullptr;
6415 mode = nullptr;
6416 user = nullptr;
6417 group = nullptr;
6418 size = nullptr;
6419 mtime = nullptr;
6420 name = nullptr;
6421 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
Jonas Devliegherec0a758d2017-09-18 14:15:57 +00006422 const char *val = nullptr;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006423 xar_prop_get(xf, key, &val);
6424#if 0 // Useful for debugging.
6425 outs() << "key: " << key << " value: " << val << "\n";
6426#endif
6427 if(strcmp(key, "type") == 0)
6428 type = val;
6429 if(strcmp(key, "mode") == 0)
6430 mode = val;
6431 if(strcmp(key, "user") == 0)
6432 user = val;
6433 if(strcmp(key, "group") == 0)
6434 group = val;
6435 if(strcmp(key, "data/size") == 0)
6436 size = val;
6437 if(strcmp(key, "mtime") == 0)
6438 mtime = val;
6439 if(strcmp(key, "name") == 0)
6440 name = val;
6441 }
6442 if(mode != nullptr){
6443 mode_value = strtoul(mode, &endp, 8);
6444 if(*endp != '\0')
6445 outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
6446 if(strcmp(type, "file") == 0)
6447 mode_value |= S_IFREG;
6448 PrintModeVerbose(mode_value);
6449 outs() << " ";
6450 }
6451 if(user != nullptr)
6452 outs() << format("%10s/", user);
6453 if(group != nullptr)
6454 outs() << format("%-10s ", group);
6455 if(size != nullptr)
6456 outs() << format("%7s ", size);
6457 if(mtime != nullptr){
6458 for(m = mtime; *m != 'T' && *m != '\0'; m++)
6459 outs() << *m;
6460 if(*m == 'T')
6461 m++;
6462 outs() << " ";
6463 for( ; *m != 'Z' && *m != '\0'; m++)
6464 outs() << *m;
6465 outs() << " ";
6466 }
6467 if(name != nullptr)
6468 outs() << name;
6469 outs() << "\n";
6470 }
6471}
6472
6473static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
6474 uint32_t size, bool verbose,
6475 bool PrintXarHeader, bool PrintXarFileHeaders,
6476 std::string XarMemberName) {
6477 if(size < sizeof(struct xar_header)) {
6478 outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
6479 "of struct xar_header)\n";
6480 return;
6481 }
6482 struct xar_header XarHeader;
6483 memcpy(&XarHeader, sect, sizeof(struct xar_header));
6484 if (sys::IsLittleEndianHost)
6485 swapStruct(XarHeader);
6486 if (PrintXarHeader) {
6487 if (!XarMemberName.empty())
6488 outs() << "In xar member " << XarMemberName << ": ";
6489 else
6490 outs() << "For (__LLVM,__bundle) section: ";
6491 outs() << "xar header\n";
6492 if (XarHeader.magic == XAR_HEADER_MAGIC)
6493 outs() << " magic XAR_HEADER_MAGIC\n";
6494 else
6495 outs() << " magic "
6496 << format_hex(XarHeader.magic, 10, true)
6497 << " (not XAR_HEADER_MAGIC)\n";
6498 outs() << " size " << XarHeader.size << "\n";
6499 outs() << " version " << XarHeader.version << "\n";
6500 outs() << " toc_length_compressed " << XarHeader.toc_length_compressed
6501 << "\n";
6502 outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
6503 << "\n";
6504 outs() << " cksum_alg ";
6505 switch (XarHeader.cksum_alg) {
6506 case XAR_CKSUM_NONE:
6507 outs() << "XAR_CKSUM_NONE\n";
6508 break;
6509 case XAR_CKSUM_SHA1:
6510 outs() << "XAR_CKSUM_SHA1\n";
6511 break;
6512 case XAR_CKSUM_MD5:
6513 outs() << "XAR_CKSUM_MD5\n";
6514 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006515#ifdef XAR_CKSUM_SHA256
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006516 case XAR_CKSUM_SHA256:
6517 outs() << "XAR_CKSUM_SHA256\n";
6518 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006519#endif
6520#ifdef XAR_CKSUM_SHA512
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006521 case XAR_CKSUM_SHA512:
6522 outs() << "XAR_CKSUM_SHA512\n";
6523 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006524#endif
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006525 default:
6526 outs() << XarHeader.cksum_alg << "\n";
6527 }
6528 }
6529
6530 SmallString<128> XarFilename;
6531 int FD;
6532 std::error_code XarEC =
6533 sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
6534 if (XarEC) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006535 WithColor::error(errs(), "llvm-objdump") << XarEC.message() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006536 return;
6537 }
Reid Kleckner3fc649c2017-09-23 01:03:17 +00006538 ToolOutputFile XarFile(XarFilename, FD);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006539 raw_fd_ostream &XarOut = XarFile.os();
6540 StringRef XarContents(sect, size);
6541 XarOut << XarContents;
6542 XarOut.close();
6543 if (XarOut.has_error())
6544 return;
6545
Francis Ricci6f942972017-10-06 15:33:28 +00006546 ScopedXarFile xar(XarFilename.c_str(), READ);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006547 if (!xar) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006548 WithColor::error(errs(), "llvm-objdump")
6549 << "can't create temporary xar archive " << XarFilename << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006550 return;
6551 }
6552
6553 SmallString<128> TocFilename;
6554 std::error_code TocEC =
6555 sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
6556 if (TocEC) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006557 WithColor::error(errs(), "llvm-objdump") << TocEC.message() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006558 return;
6559 }
6560 xar_serialize(xar, TocFilename.c_str());
6561
6562 if (PrintXarFileHeaders) {
6563 if (!XarMemberName.empty())
6564 outs() << "In xar member " << XarMemberName << ": ";
6565 else
6566 outs() << "For (__LLVM,__bundle) section: ";
6567 outs() << "xar archive files:\n";
6568 PrintXarFilesSummary(XarFilename.c_str(), xar);
6569 }
6570
6571 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
6572 MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
6573 if (std::error_code EC = FileOrErr.getError()) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006574 WithColor::error(errs(), "llvm-objdump") << EC.message() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006575 return;
6576 }
6577 std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
6578
6579 if (!XarMemberName.empty())
6580 outs() << "In xar member " << XarMemberName << ": ";
6581 else
6582 outs() << "For (__LLVM,__bundle) section: ";
6583 outs() << "xar table of contents:\n";
6584 outs() << Buffer->getBuffer() << "\n";
6585
6586 // TODO: Go through the xar's files.
Francis Ricci6f942972017-10-06 15:33:28 +00006587 ScopedXarIter xi;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006588 if(!xi){
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006589 WithColor::error(errs(), "llvm-objdump")
6590 << "can't obtain an xar iterator for xar archive "
6591 << XarFilename.c_str() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006592 return;
6593 }
6594 for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
6595 const char *key;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006596 const char *member_name, *member_type, *member_size_string;
6597 size_t member_size;
6598
Francis Ricci6f942972017-10-06 15:33:28 +00006599 ScopedXarIter xp;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006600 if(!xp){
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006601 WithColor::error(errs(), "llvm-objdump")
6602 << "can't obtain an xar iterator for xar archive "
6603 << XarFilename.c_str() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006604 return;
6605 }
6606 member_name = NULL;
6607 member_type = NULL;
6608 member_size_string = NULL;
6609 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
Jonas Devliegherec0a758d2017-09-18 14:15:57 +00006610 const char *val = nullptr;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006611 xar_prop_get(xf, key, &val);
6612#if 0 // Useful for debugging.
6613 outs() << "key: " << key << " value: " << val << "\n";
6614#endif
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006615 if (strcmp(key, "name") == 0)
6616 member_name = val;
6617 if (strcmp(key, "type") == 0)
6618 member_type = val;
6619 if (strcmp(key, "data/size") == 0)
6620 member_size_string = val;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006621 }
6622 /*
6623 * If we find a file with a name, date/size and type properties
6624 * and with the type being "file" see if that is a xar file.
6625 */
6626 if (member_name != NULL && member_type != NULL &&
6627 strcmp(member_type, "file") == 0 &&
6628 member_size_string != NULL){
6629 // Extract the file into a buffer.
6630 char *endptr;
6631 member_size = strtoul(member_size_string, &endptr, 10);
6632 if (*endptr == '\0' && member_size != 0) {
Francis Ricci1bae0ac2017-09-13 13:57:45 +00006633 char *buffer;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006634 if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006635#if 0 // Useful for debugging.
NAKAMURA Takumi6f43bd42017-10-18 13:31:28 +00006636 outs() << "xar member: " << member_name << " extracted\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006637#endif
6638 // Set the XarMemberName we want to see printed in the header.
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006639 std::string OldXarMemberName;
6640 // If XarMemberName is already set this is nested. So
6641 // save the old name and create the nested name.
6642 if (!XarMemberName.empty()) {
6643 OldXarMemberName = XarMemberName;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006644 XarMemberName =
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006645 (Twine("[") + XarMemberName + "]" + member_name).str();
6646 } else {
6647 OldXarMemberName = "";
6648 XarMemberName = member_name;
6649 }
6650 // See if this is could be a xar file (nested).
6651 if (member_size >= sizeof(struct xar_header)) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006652#if 0 // Useful for debugging.
NAKAMURA Takumi6f43bd42017-10-18 13:31:28 +00006653 outs() << "could be a xar file: " << member_name << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006654#endif
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006655 memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006656 if (sys::IsLittleEndianHost)
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006657 swapStruct(XarHeader);
6658 if (XarHeader.magic == XAR_HEADER_MAGIC)
6659 DumpBitcodeSection(O, buffer, member_size, verbose,
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006660 PrintXarHeader, PrintXarFileHeaders,
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006661 XarMemberName);
6662 }
6663 XarMemberName = OldXarMemberName;
Francis Ricci1bae0ac2017-09-13 13:57:45 +00006664 delete buffer;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006665 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006666 }
6667 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006668 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006669}
6670#endif // defined(HAVE_LIBXAR)
6671
Kevin Enderby0fc11822015-04-01 20:57:01 +00006672static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6673 if (O->is64Bit())
6674 printObjc2_64bit_MetaData(O, verbose);
6675 else {
6676 MachO::mach_header H;
6677 H = O->getHeader();
6678 if (H.cputype == MachO::CPU_TYPE_ARM)
6679 printObjc2_32bit_MetaData(O, verbose);
6680 else {
6681 // This is the 32-bit non-arm cputype case. Which is normally
6682 // the first Objective-C ABI. But it may be the case of a
6683 // binary for the iOS simulator which is the second Objective-C
6684 // ABI. In that case printObjc1_32bit_MetaData() will determine that
6685 // and return false.
Hans Wennborgcc9deb42015-09-29 18:02:48 +00006686 if (!printObjc1_32bit_MetaData(O, verbose))
Kevin Enderby0fc11822015-04-01 20:57:01 +00006687 printObjc2_32bit_MetaData(O, verbose);
6688 }
6689 }
6690}
6691
Kevin Enderbybf246f52014-09-24 23:08:22 +00006692// GuessLiteralPointer returns a string which for the item in the Mach-O file
6693// for the address passed in as ReferenceValue for printing as a comment with
6694// the instruction and also returns the corresponding type of that item
6695// indirectly through ReferenceType.
6696//
6697// If ReferenceValue is an address of literal cstring then a pointer to the
6698// cstring is returned and ReferenceType is set to
6699// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6700//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006701// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6702// Class ref that name is returned and the ReferenceType is set accordingly.
6703//
6704// Lastly, literals which are Symbol address in a literal pool are looked for
6705// and if found the symbol name is returned and ReferenceType is set to
6706// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6707//
6708// If there is no item in the Mach-O file for the address passed in as
6709// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006710static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6711 uint64_t ReferencePC,
6712 uint64_t *ReferenceType,
6713 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006714 // First see if there is an external relocation entry at the ReferencePC.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006715 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6716 uint64_t sect_addr = info->S.getAddress();
6717 uint64_t sect_offset = ReferencePC - sect_addr;
6718 bool reloc_found = false;
6719 DataRefImpl Rel;
6720 MachO::any_relocation_info RE;
6721 bool isExtern = false;
6722 SymbolRef Symbol;
6723 for (const RelocationRef &Reloc : info->S.relocations()) {
6724 uint64_t RelocOffset = Reloc.getOffset();
6725 if (RelocOffset == sect_offset) {
6726 Rel = Reloc.getRawDataRefImpl();
6727 RE = info->O->getRelocation(Rel);
6728 if (info->O->isRelocationScattered(RE))
6729 continue;
6730 isExtern = info->O->getPlainRelocationExternal(RE);
6731 if (isExtern) {
6732 symbol_iterator RelocSym = Reloc.getSymbol();
6733 Symbol = *RelocSym;
6734 }
6735 reloc_found = true;
6736 break;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006737 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006738 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006739 // If there is an external relocation entry for a symbol in a section
6740 // then used that symbol's value for the value of the reference.
6741 if (reloc_found && isExtern) {
6742 if (info->O->getAnyRelocationPCRel(RE)) {
6743 unsigned Type = info->O->getAnyRelocationType(RE);
6744 if (Type == MachO::X86_64_RELOC_SIGNED) {
6745 ReferenceValue = Symbol.getValue();
6746 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006747 }
6748 }
6749 }
6750
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006751 // Look for literals such as Objective-C CFStrings refs, Selector refs,
6752 // Message refs and Class refs.
6753 bool classref, selref, msgref, cfstring;
6754 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6755 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00006756 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006757 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6758 // And the pointer_value in that section is typically zero as it will be
6759 // set by dyld as part of the "bind information".
6760 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6761 if (name != nullptr) {
6762 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00006763 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006764 if (class_name != nullptr && class_name[1] == '_' &&
6765 class_name[2] != '\0') {
6766 info->class_name = class_name + 2;
6767 return name;
6768 }
6769 }
6770 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006771
David Blaikie33dd45d02015-03-23 18:39:02 +00006772 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006773 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6774 const char *name =
6775 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6776 if (name != nullptr)
6777 info->class_name = name;
6778 else
6779 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00006780 return name;
6781 }
6782
David Blaikie33dd45d02015-03-23 18:39:02 +00006783 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006784 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6785 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6786 return name;
6787 }
6788
David Blaikie33dd45d02015-03-23 18:39:02 +00006789 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006790 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6791
6792 if (pointer_value != 0)
6793 ReferenceValue = pointer_value;
6794
6795 const char *name = GuessCstringPointer(ReferenceValue, info);
6796 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00006797 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006798 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6799 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00006800 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006801 info->class_name = nullptr;
6802 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6803 info->selector_name = name;
6804 } else
6805 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6806 return name;
6807 }
6808
6809 // Lastly look for an indirect symbol with this ReferenceValue which is in
6810 // a literal pool. If found return that symbol name.
6811 name = GuessIndirectSymbol(ReferenceValue, info);
6812 if (name) {
6813 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6814 return name;
6815 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006816
6817 return nullptr;
6818}
6819
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006820// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00006821// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006822// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6823// is created and returns the symbol name that matches the ReferenceValue or
6824// nullptr if none. The ReferenceType is passed in for the IN type of
6825// reference the instruction is making from the values in defined in the header
6826// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
6827// Out type and the ReferenceName will also be set which is added as a comment
6828// to the disassembled instruction.
6829//
Kevin Enderby04bf6932014-10-28 23:39:46 +00006830// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006831// returned through ReferenceName and ReferenceType is set to
6832// LLVMDisassembler_ReferenceType_DeMangled_Name .
6833//
6834// When this is called to get a symbol name for a branch target then the
6835// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
6836// SymbolValue will be looked for in the indirect symbol table to determine if
6837// it is an address for a symbol stub. If so then the symbol name for that
6838// stub is returned indirectly through ReferenceName and then ReferenceType is
6839// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
6840//
Kevin Enderbybf246f52014-09-24 23:08:22 +00006841// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006842// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
6843// SymbolValue is checked to be an address of literal pointer, symbol pointer,
6844// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006845// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006846static const char *SymbolizerSymbolLookUp(void *DisInfo,
6847 uint64_t ReferenceValue,
6848 uint64_t *ReferenceType,
6849 uint64_t ReferencePC,
6850 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006851 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006852 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00006853 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006854 *ReferenceName = nullptr;
6855 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006856 return nullptr;
6857 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006858
Kevin Enderbyf6d25852015-01-31 00:37:11 +00006859 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006860
Kevin Enderby85974882014-09-26 22:20:44 +00006861 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
6862 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006863 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006864 method_reference(info, ReferenceType, ReferenceName);
6865 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
6866 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
Rafael Espindolab940b662016-09-06 19:16:48 +00006867 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006868 if (info->demangled_name != nullptr)
6869 free(info->demangled_name);
6870 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006871 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00006872 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006873 if (info->demangled_name != nullptr) {
6874 *ReferenceName = info->demangled_name;
6875 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6876 } else
6877 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6878 } else
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006879 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6880 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
6881 *ReferenceName =
6882 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00006883 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006884 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00006885 else
6886 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006887 // If this is arm64 and the reference is an adrp instruction save the
6888 // instruction, passed in ReferenceValue and the address of the instruction
6889 // for use later if we see and add immediate instruction.
6890 } else if (info->O->getArch() == Triple::aarch64 &&
6891 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
6892 info->adrp_inst = ReferenceValue;
6893 info->adrp_addr = ReferencePC;
6894 SymbolName = nullptr;
6895 *ReferenceName = nullptr;
6896 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6897 // If this is arm64 and reference is an add immediate instruction and we
6898 // have
6899 // seen an adrp instruction just before it and the adrp's Xd register
6900 // matches
6901 // this add's Xn register reconstruct the value being referenced and look to
6902 // see if it is a literal pointer. Note the add immediate instruction is
6903 // passed in ReferenceValue.
6904 } else if (info->O->getArch() == Triple::aarch64 &&
6905 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
6906 ReferencePC - 4 == info->adrp_addr &&
6907 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6908 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6909 uint32_t addxri_inst;
6910 uint64_t adrp_imm, addxri_imm;
6911
6912 adrp_imm =
6913 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6914 if (info->adrp_inst & 0x0200000)
6915 adrp_imm |= 0xfffffffffc000000LL;
6916
6917 addxri_inst = ReferenceValue;
6918 addxri_imm = (addxri_inst >> 10) & 0xfff;
6919 if (((addxri_inst >> 22) & 0x3) == 1)
6920 addxri_imm <<= 12;
6921
6922 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6923 (adrp_imm << 12) + addxri_imm;
6924
6925 *ReferenceName =
6926 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6927 if (*ReferenceName == nullptr)
6928 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6929 // If this is arm64 and the reference is a load register instruction and we
6930 // have seen an adrp instruction just before it and the adrp's Xd register
6931 // matches this add's Xn register reconstruct the value being referenced and
6932 // look to see if it is a literal pointer. Note the load register
6933 // instruction is passed in ReferenceValue.
6934 } else if (info->O->getArch() == Triple::aarch64 &&
6935 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
6936 ReferencePC - 4 == info->adrp_addr &&
6937 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6938 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6939 uint32_t ldrxui_inst;
6940 uint64_t adrp_imm, ldrxui_imm;
6941
6942 adrp_imm =
6943 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6944 if (info->adrp_inst & 0x0200000)
6945 adrp_imm |= 0xfffffffffc000000LL;
6946
6947 ldrxui_inst = ReferenceValue;
6948 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
6949
6950 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6951 (adrp_imm << 12) + (ldrxui_imm << 3);
6952
6953 *ReferenceName =
6954 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6955 if (*ReferenceName == nullptr)
6956 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6957 }
6958 // If this arm64 and is an load register (PC-relative) instruction the
6959 // ReferenceValue is the PC plus the immediate value.
6960 else if (info->O->getArch() == Triple::aarch64 &&
6961 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
6962 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
6963 *ReferenceName =
6964 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6965 if (*ReferenceName == nullptr)
6966 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Rafael Espindolab940b662016-09-06 19:16:48 +00006967 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006968 if (info->demangled_name != nullptr)
6969 free(info->demangled_name);
6970 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006971 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00006972 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006973 if (info->demangled_name != nullptr) {
6974 *ReferenceName = info->demangled_name;
6975 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6976 }
6977 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006978 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006979 *ReferenceName = nullptr;
6980 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6981 }
6982
6983 return SymbolName;
6984}
6985
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006986/// Emits the comments that are stored in the CommentStream.
Kevin Enderbybf246f52014-09-24 23:08:22 +00006987/// Each comment in the CommentStream must end with a newline.
6988static void emitComments(raw_svector_ostream &CommentStream,
6989 SmallString<128> &CommentsToEmit,
6990 formatted_raw_ostream &FormattedOS,
6991 const MCAsmInfo &MAI) {
6992 // Flush the stream before taking its content.
Kevin Enderbybf246f52014-09-24 23:08:22 +00006993 StringRef Comments = CommentsToEmit.str();
6994 // Get the default information for printing a comment.
Mehdi Amini36d33fc2016-10-01 06:46:33 +00006995 StringRef CommentBegin = MAI.getCommentString();
Kevin Enderbybf246f52014-09-24 23:08:22 +00006996 unsigned CommentColumn = MAI.getCommentColumn();
6997 bool IsFirst = true;
6998 while (!Comments.empty()) {
6999 if (!IsFirst)
7000 FormattedOS << '\n';
7001 // Emit a line of comments.
7002 FormattedOS.PadToColumn(CommentColumn);
7003 size_t Position = Comments.find('\n');
7004 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
7005 // Move after the newline character.
7006 Comments = Comments.substr(Position + 1);
7007 IsFirst = false;
7008 }
7009 FormattedOS.flush();
7010
7011 // Tell the comment stream that the vector changed underneath it.
7012 CommentsToEmit.clear();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007013}
7014
Kevin Enderby95df54c2015-02-04 01:01:38 +00007015static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
7016 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007017 const char *McpuDefault = nullptr;
7018 const Target *ThumbTarget = nullptr;
7019 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007020 if (!TheTarget) {
7021 // GetTarget prints out stuff.
7022 return;
7023 }
Kevin Enderbyf310e622017-09-21 21:45:02 +00007024 std::string MachOMCPU;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007025 if (MCPU.empty() && McpuDefault)
Kevin Enderbyf310e622017-09-21 21:45:02 +00007026 MachOMCPU = McpuDefault;
7027 else
7028 MachOMCPU = MCPU;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007029
Ahmed Charles56440fd2014-03-06 05:51:42 +00007030 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007031 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007032 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007033 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007034
Kevin Enderbyc9595622014-08-06 23:24:41 +00007035 // Package up features to be passed to target/subtarget
7036 std::string FeaturesStr;
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00007037 if (!MAttrs.empty()) {
Kevin Enderbyc9595622014-08-06 23:24:41 +00007038 SubtargetFeatures Features;
7039 for (unsigned i = 0; i != MAttrs.size(); ++i)
7040 Features.AddFeature(MAttrs[i]);
7041 FeaturesStr = Features.getString();
7042 }
7043
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007044 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00007045 std::unique_ptr<const MCRegisterInfo> MRI(
7046 TheTarget->createMCRegInfo(TripleName));
7047 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00007048 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00007049 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyf310e622017-09-21 21:45:02 +00007050 TheTarget->createMCSubtargetInfo(TripleName, MachOMCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00007051 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007052 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007053 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007054 std::unique_ptr<MCSymbolizer> Symbolizer;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00007055 struct DisassembleInfo SymbolizerInfo(nullptr, nullptr, nullptr, false);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007056 std::unique_ptr<MCRelocationInfo> RelInfo(
7057 TheTarget->createMCRelocationInfo(TripleName, Ctx));
7058 if (RelInfo) {
7059 Symbolizer.reset(TheTarget->createMCSymbolizer(
7060 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00007061 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007062 DisAsm->setSymbolizer(std::move(Symbolizer));
7063 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007064 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00007065 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00007066 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00007067 // Set the display preference for hex vs. decimal immediates.
7068 IP->setPrintImmHex(PrintImmHex);
7069 // Comment stream and backing vector.
7070 SmallString<128> CommentsToEmit;
7071 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00007072 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
7073 // if it is done then arm64 comments for string literals don't get printed
7074 // and some constant get printed instead and not setting it causes intel
7075 // (32-bit and 64-bit) comments printed with different spacing before the
7076 // comment causing different diffs with the 'C' disassembler library API.
7077 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007078
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007079 if (!AsmInfo || !STI || !DisAsm || !IP) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00007080 WithColor::error(errs(), "llvm-objdump")
7081 << "couldn't initialize disassembler for target " << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007082 return;
7083 }
7084
Tim Northover09ca33e2016-04-22 23:23:31 +00007085 // Set up separate thumb disassembler if needed.
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007086 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
7087 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
7088 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007089 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007090 std::unique_ptr<MCInstPrinter> ThumbIP;
7091 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007092 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00007093 struct DisassembleInfo ThumbSymbolizerInfo(nullptr, nullptr, nullptr, false);
Kevin Enderby930fdc72014-11-06 19:00:13 +00007094 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007095 if (ThumbTarget) {
7096 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
7097 ThumbAsmInfo.reset(
7098 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
7099 ThumbSTI.reset(
Kevin Enderbyf310e622017-09-21 21:45:02 +00007100 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MachOMCPU,
7101 FeaturesStr));
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007102 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
7103 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00007104 MCContext *PtrThumbCtx = ThumbCtx.get();
7105 ThumbRelInfo.reset(
7106 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
7107 if (ThumbRelInfo) {
7108 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
7109 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00007110 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00007111 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
7112 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007113 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
7114 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00007115 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
7116 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00007117 // Set the display preference for hex vs. decimal immediates.
7118 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007119 }
7120
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007121 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00007122 WithColor::error(errs(), "llvm-objdump")
7123 << "couldn't initialize disassembler for target " << ThumbTripleName
7124 << '\n';
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007125 return;
7126 }
7127
Charles Davis8bdfafd2013-09-01 04:28:48 +00007128 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007129
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007130 // FIXME: Using the -cfg command line option, this code used to be able to
7131 // annotate relocations with the referenced symbol's name, and if this was
7132 // inside a __[cf]string section, the data it points to. This is now replaced
7133 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00007134 std::vector<SectionRef> Sections;
7135 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007136 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00007137 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007138
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00007139 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
Kevin Enderby273ae012013-06-06 17:20:50 +00007140 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007141
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007142 // Sort the symbols by address, just in case they didn't come in that way.
Fangrui Song0cac7262018-09-27 02:13:45 +00007143 llvm::sort(Symbols, SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007144
Kevin Enderby273ae012013-06-06 17:20:50 +00007145 // Build a data in code table that is sorted on by the address of each entry.
7146 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00007147 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00007148 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00007149 else
7150 BaseAddress = BaseSegmentAddress;
7151 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00007152 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00007153 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00007154 uint32_t Offset;
7155 DI->getOffset(Offset);
7156 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
7157 }
7158 array_pod_sort(Dices.begin(), Dices.end());
7159
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007160#ifndef NDEBUG
7161 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
7162#else
7163 raw_ostream &DebugOut = nulls();
7164#endif
7165
Ahmed Charles56440fd2014-03-06 05:51:42 +00007166 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00007167 ObjectFile *DbgObj = MachOOF;
Francis Visoiu Mistrih8e864be2018-08-31 13:10:54 +00007168 std::unique_ptr<MemoryBuffer> DSYMBuf;
Benjamin Kramer699128e2011-09-21 01:13:19 +00007169 // Try to find debug info and set up the DIContext for it.
7170 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00007171 // A separate DSym file path was specified, parse it as a macho file,
7172 // get the sections and supply it to the section name parsing machinery.
7173 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00007174 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00007175 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00007176 if (std::error_code EC = BufOrErr.getError()) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00007177 report_error(errorCodeToError(EC), DSYMFile);
Benjamin Kramer699128e2011-09-21 01:13:19 +00007178 return;
7179 }
Francis Visoiu Mistrihb8819dc2019-01-10 17:36:54 +00007180
Fangrui Songe7834bd2019-04-07 08:19:55 +00007181 std::unique_ptr<MachOObjectFile> DbgObjCheck = unwrapOrError(
7182 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef()),
7183 DSYMFile.getValue());
7184 DbgObj = DbgObjCheck.release();
Francis Visoiu Mistrih8e864be2018-08-31 13:10:54 +00007185 // We need to keep the file alive, because we're replacing DbgObj with it.
7186 DSYMBuf = std::move(BufOrErr.get());
Benjamin Kramer699128e2011-09-21 01:13:19 +00007187 }
7188
Eric Christopher7370b552012-11-12 21:40:38 +00007189 // Setup the DIContext
Rafael Espindolac398e672017-07-19 22:27:28 +00007190 diContext = DWARFContext::create(*DbgObj);
Benjamin Kramer699128e2011-09-21 01:13:19 +00007191 }
7192
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00007193 if (FilterSections.empty())
Kevin Enderby95df54c2015-02-04 01:01:38 +00007194 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00007195
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007196 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00007197 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00007198 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
7199 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007200
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00007201 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007202
Rafael Espindolab0f76a42013-04-05 15:15:22 +00007203 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00007204 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00007205 continue;
7206
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007207 StringRef BytesStr;
7208 Sections[SectIdx].getContents(BytesStr);
Fangrui Song6a0746a2019-04-07 03:58:42 +00007209 ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(BytesStr);
Rafael Espindola80291272014-10-08 15:28:58 +00007210 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00007211
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007212 bool symbolTableWorked = false;
7213
Kevin Enderbybf246f52014-09-24 23:08:22 +00007214 // Create a map of symbol addresses to symbol names for use by
7215 // the SymbolizerSymbolLookUp() routine.
7216 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00007217 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007218 for (const SymbolRef &Symbol : MachOOF->symbols()) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00007219 SymbolRef::Type ST =
7220 unwrapOrError(Symbol.getType(), MachOOF->getFileName());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007221 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
7222 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00007223 uint64_t Address = Symbol.getValue();
Fangrui Songe7834bd2019-04-07 08:19:55 +00007224 StringRef SymName =
7225 unwrapOrError(Symbol.getName(), MachOOF->getFileName());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007226 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00007227 if (!DisSymName.empty() && DisSymName == SymName)
7228 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007229 }
7230 }
David Blaikie33dd45d02015-03-23 18:39:02 +00007231 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00007232 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
7233 return;
7234 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007235 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00007236 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007237 SymbolizerInfo.O = MachOOF;
7238 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00007239 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007240 SymbolizerInfo.Sections = &Sections;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007241 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00007242 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007243 ThumbSymbolizerInfo.O = MachOOF;
7244 ThumbSymbolizerInfo.S = Sections[SectIdx];
7245 ThumbSymbolizerInfo.AddrMap = &AddrMap;
7246 ThumbSymbolizerInfo.Sections = &Sections;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007247
Kevin Enderby4b627be2016-04-28 20:14:13 +00007248 unsigned int Arch = MachOOF->getArch();
7249
Tim Northoverf203ab52016-07-14 22:13:32 +00007250 // Skip all symbols if this is a stubs file.
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00007251 if (Bytes.empty())
Tim Northoverf203ab52016-07-14 22:13:32 +00007252 return;
7253
Kevin Enderbyc138da32017-02-06 18:43:18 +00007254 // If the section has symbols but no symbol at the start of the section
7255 // these are used to make sure the bytes before the first symbol are
7256 // disassembled.
7257 bool FirstSymbol = true;
7258 bool FirstSymbolAtSectionStart = true;
7259
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007260 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007261 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00007262 StringRef SymName =
7263 unwrapOrError(Symbols[SymIdx].getName(), MachOOF->getFileName());
7264 SymbolRef::Type ST =
7265 unwrapOrError(Symbols[SymIdx].getType(), MachOOF->getFileName());
Kuba Breckade833222015-11-12 09:40:29 +00007266 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
Owen Andersond9243c42011-10-17 21:37:35 +00007267 continue;
7268
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007269 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00007270 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00007271 if (!containsSym) {
7272 if (!DisSymName.empty() && DisSymName == SymName) {
7273 outs() << "-dis-symname: " << DisSymName << " not in the section\n";
7274 return;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00007275 }
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00007276 continue;
7277 }
7278 // The __mh_execute_header is special and we need to deal with that fact
7279 // this symbol is before the start of the (__TEXT,__text) section and at the
7280 // address of the start of the __TEXT segment. This is because this symbol
7281 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
7282 // start of the section in a standard MH_EXECUTE filetype.
7283 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
7284 outs() << "-dis-symname: __mh_execute_header not in any section\n";
7285 return;
7286 }
Tim Northoverfbefee32016-07-14 23:13:03 +00007287 // When this code is trying to disassemble a symbol at a time and in the
7288 // case there is only the __mh_execute_header symbol left as in a stripped
7289 // executable, we need to deal with this by ignoring this symbol so the
7290 // whole section is disassembled and this symbol is then not displayed.
7291 if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
7292 SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
7293 SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007294 continue;
7295
Kevin Enderby6a221752015-03-17 17:10:57 +00007296 // If we are only disassembling one symbol see if this is that symbol.
7297 if (!DisSymName.empty() && DisSymName != SymName)
7298 continue;
7299
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007300 // Start at the address of the symbol relative to the section's address.
Tim Northoverf203ab52016-07-14 22:13:32 +00007301 uint64_t SectSize = Sections[SectIdx].getSize();
Rafael Espindoladea00162015-07-03 17:44:18 +00007302 uint64_t Start = Symbols[SymIdx].getValue();
Rafael Espindola80291272014-10-08 15:28:58 +00007303 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Cameron Zwarich54478a52012-02-03 05:42:17 +00007304 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00007305
Tim Northoverf203ab52016-07-14 22:13:32 +00007306 if (Start > SectSize) {
7307 outs() << "section data ends, " << SymName
7308 << " lies outside valid range\n";
7309 return;
7310 }
7311
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007312 // Stop disassembling either at the beginning of the next symbol or at
7313 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00007314 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00007315 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007316 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00007317 while (Symbols.size() > NextSymIdx) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00007318 SymbolRef::Type NextSymType = unwrapOrError(
7319 Symbols[NextSymIdx].getType(), MachOOF->getFileName());
Owen Andersond9243c42011-10-17 21:37:35 +00007320 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00007321 containsNextSym =
7322 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Rafael Espindoladea00162015-07-03 17:44:18 +00007323 NextSym = Symbols[NextSymIdx].getValue();
Cameron Zwarich54478a52012-02-03 05:42:17 +00007324 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00007325 break;
7326 }
7327 ++NextSymIdx;
7328 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007329
Tim Northoverf203ab52016-07-14 22:13:32 +00007330 uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00007331 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007332
7333 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00007334
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007335 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
Tim Northover09ca33e2016-04-22 23:23:31 +00007336 bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
7337
7338 // We only need the dedicated Thumb target if there's a real choice
7339 // (i.e. we're not targeting M-class) and the function is Thumb.
7340 bool UseThumbTarget = IsThumb && ThumbTarget;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007341
Kevin Enderbyc138da32017-02-06 18:43:18 +00007342 // If we are not specifying a symbol to start disassembly with and this
7343 // is the first symbol in the section but not at the start of the section
7344 // then move the disassembly index to the start of the section and
7345 // don't print the symbol name just yet. This is so the bytes before the
7346 // first symbol are disassembled.
7347 uint64_t SymbolStart = Start;
7348 if (DisSymName.empty() && FirstSymbol && Start != 0) {
7349 FirstSymbolAtSectionStart = false;
7350 Start = 0;
7351 }
7352 else
7353 outs() << SymName << ":\n";
7354
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007355 DILineInfo lastLine;
7356 for (uint64_t Index = Start; Index < End; Index += Size) {
7357 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00007358
Kevin Enderbyc138da32017-02-06 18:43:18 +00007359 // If this is the first symbol in the section and it was not at the
7360 // start of the section, see if we are at its Index now and if so print
7361 // the symbol name.
7362 if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
7363 outs() << SymName << ":\n";
7364
Kevin Enderbybf246f52014-09-24 23:08:22 +00007365 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00007366 if (!NoLeadingAddr) {
7367 if (FullLeadingAddr) {
7368 if (MachOOF->is64Bit())
7369 outs() << format("%016" PRIx64, PC);
7370 else
7371 outs() << format("%08" PRIx64, PC);
7372 } else {
7373 outs() << format("%8" PRIx64 ":", PC);
7374 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00007375 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00007376 if (!NoShowRawInsn || Arch == Triple::arm)
Kevin Enderbybf246f52014-09-24 23:08:22 +00007377 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00007378
7379 // Check the data in code table here to see if this is data not an
7380 // instruction to be disassembled.
7381 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007382 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007383 dice_table_iterator DTI =
7384 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
7385 compareDiceTableEntries);
7386 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00007387 uint16_t Length;
7388 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00007389 uint16_t Kind;
7390 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00007391 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00007392 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
7393 (PC == (DTI->first + Length - 1)) && (Length & 1))
7394 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00007395 continue;
7396 }
7397
Kevin Enderbybf246f52014-09-24 23:08:22 +00007398 SmallVector<char, 64> AnnotationsBytes;
7399 raw_svector_ostream Annotations(AnnotationsBytes);
7400
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007401 bool gotInst;
Tim Northover09ca33e2016-04-22 23:23:31 +00007402 if (UseThumbTarget)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007403 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007404 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007405 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007406 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00007407 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007408 if (gotInst) {
Kevin Enderby4b627be2016-04-28 20:14:13 +00007409 if (!NoShowRawInsn || Arch == Triple::arm) {
Craig Topper0013be12015-09-21 05:32:41 +00007410 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007411 }
7412 formatted_raw_ostream FormattedOS(outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007413 StringRef AnnotationsStr = Annotations.str();
Tim Northover09ca33e2016-04-22 23:23:31 +00007414 if (UseThumbTarget)
Akira Hatanakab46d0232015-03-27 20:36:02 +00007415 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007416 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00007417 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00007418 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00007419
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007420 // Print debug info.
7421 if (diContext) {
Alexey Lapshin77fc1f62019-02-27 13:17:36 +00007422 DILineInfo dli = diContext->getLineInfoForAddress({PC, SectIdx});
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007423 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00007424 if (dli != lastLine && dli.Line != 0)
7425 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
7426 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007427 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007428 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007429 outs() << "\n";
7430 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007431 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007432 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007433 outs() << format("\t.byte 0x%02x #bad opcode\n",
7434 *(Bytes.data() + Index) & 0xff);
7435 Size = 1; // skip exactly one illegible byte and move on.
Tim Northover09ca33e2016-04-22 23:23:31 +00007436 } else if (Arch == Triple::aarch64 ||
7437 (Arch == Triple::arm && !IsThumb)) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007438 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7439 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
7440 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
7441 (*(Bytes.data() + Index + 3) & 0xff) << 24;
7442 outs() << format("\t.long\t0x%08x\n", opcode);
7443 Size = 4;
Tim Northover09ca33e2016-04-22 23:23:31 +00007444 } else if (Arch == Triple::arm) {
7445 assert(IsThumb && "ARM mode should have been dealt with above");
7446 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7447 (*(Bytes.data() + Index + 1) & 0xff) << 8;
7448 outs() << format("\t.short\t0x%04x\n", opcode);
7449 Size = 2;
7450 } else{
Jonas Devliegheree787efd2018-11-11 22:12:04 +00007451 WithColor::warning(errs(), "llvm-objdump")
7452 << "invalid instruction encoding\n";
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007453 if (Size == 0)
7454 Size = 1; // skip illegible bytes
7455 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007456 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007457 }
Kevin Enderbyc138da32017-02-06 18:43:18 +00007458 // Now that we are done disassembled the first symbol set the bool that
7459 // were doing this to false.
7460 FirstSymbol = false;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007461 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007462 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00007463 // Reading the symbol table didn't work, disassemble the whole section.
7464 uint64_t SectAddress = Sections[SectIdx].getAddress();
7465 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00007466 uint64_t InstSize;
7467 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00007468 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00007469
Kevin Enderbybf246f52014-09-24 23:08:22 +00007470 uint64_t PC = SectAddress + Index;
Kevin Enderby02d3a372017-01-31 18:09:10 +00007471 SmallVector<char, 64> AnnotationsBytes;
7472 raw_svector_ostream Annotations(AnnotationsBytes);
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007473 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
Kevin Enderby02d3a372017-01-31 18:09:10 +00007474 DebugOut, Annotations)) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00007475 if (!NoLeadingAddr) {
7476 if (FullLeadingAddr) {
7477 if (MachOOF->is64Bit())
7478 outs() << format("%016" PRIx64, PC);
7479 else
7480 outs() << format("%08" PRIx64, PC);
7481 } else {
7482 outs() << format("%8" PRIx64 ":", PC);
7483 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00007484 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00007485 if (!NoShowRawInsn || Arch == Triple::arm) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00007486 outs() << "\t";
Craig Topper0013be12015-09-21 05:32:41 +00007487 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007488 }
Kevin Enderby02d3a372017-01-31 18:09:10 +00007489 StringRef AnnotationsStr = Annotations.str();
7490 IP->printInst(&Inst, outs(), AnnotationsStr, *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00007491 outs() << "\n";
7492 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007493 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007494 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007495 outs() << format("\t.byte 0x%02x #bad opcode\n",
7496 *(Bytes.data() + Index) & 0xff);
7497 InstSize = 1; // skip exactly one illegible byte and move on.
7498 } else {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00007499 WithColor::warning(errs(), "llvm-objdump")
7500 << "invalid instruction encoding\n";
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007501 if (InstSize == 0)
7502 InstSize = 1; // skip illegible bytes
7503 }
Bill Wendling4e68e062012-07-19 00:17:40 +00007504 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00007505 }
7506 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00007507 // The TripleName's need to be reset if we are called again for a different
7508 // archtecture.
7509 TripleName = "";
7510 ThumbTripleName = "";
7511
Kevin Enderby04bf6932014-10-28 23:39:46 +00007512 if (SymbolizerInfo.demangled_name != nullptr)
7513 free(SymbolizerInfo.demangled_name);
Kevin Enderby930fdc72014-11-06 19:00:13 +00007514 if (ThumbSymbolizerInfo.demangled_name != nullptr)
7515 free(ThumbSymbolizerInfo.demangled_name);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007516 }
7517}
Tim Northover4bd286a2014-08-01 13:07:19 +00007518
Tim Northover39c70bb2014-08-12 11:52:59 +00007519//===----------------------------------------------------------------------===//
7520// __compact_unwind section dumping
7521//===----------------------------------------------------------------------===//
7522
Tim Northover4bd286a2014-08-01 13:07:19 +00007523namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00007524
Tim Northover3a4e1c72018-01-23 13:51:57 +00007525template <typename T>
7526static uint64_t read(StringRef Contents, ptrdiff_t Offset) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007527 using llvm::support::little;
7528 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00007529
Tim Northover3a4e1c72018-01-23 13:51:57 +00007530 if (Offset + sizeof(T) > Contents.size()) {
7531 outs() << "warning: attempt to read past end of buffer\n";
7532 return T();
7533 }
7534
7535 uint64_t Val =
7536 support::endian::read<T, little, unaligned>(Contents.data() + Offset);
7537 return Val;
7538}
7539
7540template <typename T>
7541static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) {
7542 T Val = read<T>(Contents, Offset);
7543 Offset += sizeof(T);
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007544 return Val;
7545}
Tim Northover39c70bb2014-08-12 11:52:59 +00007546
Tim Northover4bd286a2014-08-01 13:07:19 +00007547struct CompactUnwindEntry {
7548 uint32_t OffsetInSection;
7549
7550 uint64_t FunctionAddr;
7551 uint32_t Length;
7552 uint32_t CompactEncoding;
7553 uint64_t PersonalityAddr;
7554 uint64_t LSDAAddr;
7555
7556 RelocationRef FunctionReloc;
7557 RelocationRef PersonalityReloc;
7558 RelocationRef LSDAReloc;
7559
7560 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007561 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007562 if (Is64)
Tim Northover3a4e1c72018-01-23 13:51:57 +00007563 read<uint64_t>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007564 else
Tim Northover3a4e1c72018-01-23 13:51:57 +00007565 read<uint32_t>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007566 }
7567
7568private:
Tim Northover3a4e1c72018-01-23 13:51:57 +00007569 template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) {
7570 FunctionAddr = readNext<UIntPtr>(Contents, Offset);
7571 Length = readNext<uint32_t>(Contents, Offset);
7572 CompactEncoding = readNext<uint32_t>(Contents, Offset);
7573 PersonalityAddr = readNext<UIntPtr>(Contents, Offset);
7574 LSDAAddr = readNext<UIntPtr>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007575 }
7576};
7577}
7578
7579/// Given a relocation from __compact_unwind, consisting of the RelocationRef
7580/// and data being relocated, determine the best base Name and Addend to use for
7581/// display purposes.
7582///
7583/// 1. An Extern relocation will directly reference a symbol (and the data is
7584/// then already an addend), so use that.
7585/// 2. Otherwise the data is an offset in the object file's layout; try to find
7586// a symbol before it in the same section, and use the offset from there.
7587/// 3. Finally, if all that fails, fall back to an offset from the start of the
7588/// referenced section.
7589static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
7590 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007591 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00007592 StringRef &Name, uint64_t &Addend) {
7593 if (Reloc.getSymbol() != Obj->symbol_end()) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00007594 Name = unwrapOrError(Reloc.getSymbol()->getName(), Obj->getFileName());
Tim Northover4bd286a2014-08-01 13:07:19 +00007595 Addend = Addr;
7596 return;
7597 }
7598
7599 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
Keno Fischerc780e8e2015-05-21 21:24:32 +00007600 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
Tim Northover4bd286a2014-08-01 13:07:19 +00007601
Rafael Espindola80291272014-10-08 15:28:58 +00007602 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00007603
7604 auto Sym = Symbols.upper_bound(Addr);
7605 if (Sym == Symbols.begin()) {
7606 // The first symbol in the object is after this reference, the best we can
7607 // do is section-relative notation.
7608 RelocSection.getName(Name);
7609 Addend = Addr - SectionAddr;
7610 return;
7611 }
7612
7613 // Go back one so that SymbolAddress <= Addr.
7614 --Sym;
7615
Fangrui Songe7834bd2019-04-07 08:19:55 +00007616 section_iterator SymSection =
7617 unwrapOrError(Sym->second.getSection(), Obj->getFileName());
Tim Northover4bd286a2014-08-01 13:07:19 +00007618 if (RelocSection == *SymSection) {
7619 // There's a valid symbol in the same section before this reference.
Fangrui Songe7834bd2019-04-07 08:19:55 +00007620 Name = unwrapOrError(Sym->second.getName(), Obj->getFileName());
Tim Northover4bd286a2014-08-01 13:07:19 +00007621 Addend = Addr - Sym->first;
7622 return;
7623 }
7624
7625 // There is a symbol before this reference, but it's in a different
7626 // section. Probably not helpful to mention it, so use the section name.
7627 RelocSection.getName(Name);
7628 Addend = Addr - SectionAddr;
7629}
7630
7631static void printUnwindRelocDest(const MachOObjectFile *Obj,
7632 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007633 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007634 StringRef Name;
7635 uint64_t Addend;
7636
Rafael Espindola854038e2015-06-26 14:51:16 +00007637 if (!Reloc.getObject())
Tim Northover0b0add52014-09-09 10:45:06 +00007638 return;
7639
Tim Northover4bd286a2014-08-01 13:07:19 +00007640 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
7641
7642 outs() << Name;
7643 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00007644 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00007645}
7646
7647static void
7648printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7649 std::map<uint64_t, SymbolRef> &Symbols,
7650 const SectionRef &CompactUnwind) {
7651
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007652 if (!Obj->isLittleEndian()) {
7653 outs() << "Skipping big-endian __compact_unwind section\n";
7654 return;
7655 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007656
7657 bool Is64 = Obj->is64Bit();
7658 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7659 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7660
7661 StringRef Contents;
7662 CompactUnwind.getContents(Contents);
7663
7664 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7665
7666 // First populate the initial raw offsets, encodings and so on from the entry.
7667 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007668 CompactUnwindEntry Entry(Contents, Offset, Is64);
Tim Northover4bd286a2014-08-01 13:07:19 +00007669 CompactUnwinds.push_back(Entry);
7670 }
7671
7672 // Next we need to look at the relocations to find out what objects are
7673 // actually being referred to.
7674 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00007675 uint64_t RelocAddress = Reloc.getOffset();
Tim Northover4bd286a2014-08-01 13:07:19 +00007676
7677 uint32_t EntryIdx = RelocAddress / EntrySize;
7678 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7679 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7680
7681 if (OffsetInEntry == 0)
7682 Entry.FunctionReloc = Reloc;
7683 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7684 Entry.PersonalityReloc = Reloc;
7685 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7686 Entry.LSDAReloc = Reloc;
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007687 else {
7688 outs() << "Invalid relocation in __compact_unwind section\n";
7689 return;
7690 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007691 }
7692
7693 // Finally, we're ready to print the data we've gathered.
7694 outs() << "Contents of __compact_unwind section:\n";
7695 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00007696 outs() << " Entry at offset "
7697 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00007698
7699 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007700 outs() << " start: " << format("0x%" PRIx64,
7701 Entry.FunctionAddr) << ' ';
7702 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00007703 outs() << '\n';
7704
7705 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007706 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
7707 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007708 // 3. The 32-bit compact encoding.
7709 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007710 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007711
7712 // 4. The personality function, if present.
Rafael Espindola854038e2015-06-26 14:51:16 +00007713 if (Entry.PersonalityReloc.getObject()) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007714 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007715 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007716 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7717 Entry.PersonalityAddr);
7718 outs() << '\n';
7719 }
7720
7721 // 5. This entry's language-specific data area.
Rafael Espindola854038e2015-06-26 14:51:16 +00007722 if (Entry.LSDAReloc.getObject()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007723 outs() << " LSDA: " << format("0x%" PRIx64,
7724 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007725 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7726 outs() << '\n';
7727 }
7728 }
7729}
7730
Tim Northover39c70bb2014-08-12 11:52:59 +00007731//===----------------------------------------------------------------------===//
7732// __unwind_info section dumping
7733//===----------------------------------------------------------------------===//
7734
Tim Northover3a4e1c72018-01-23 13:51:57 +00007735static void printRegularSecondLevelUnwindPage(StringRef PageData) {
7736 ptrdiff_t Pos = 0;
7737 uint32_t Kind = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007738 (void)Kind;
7739 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7740
Tim Northover3a4e1c72018-01-23 13:51:57 +00007741 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7742 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007743
Tim Northover3a4e1c72018-01-23 13:51:57 +00007744 Pos = EntriesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007745 for (unsigned i = 0; i < NumEntries; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007746 uint32_t FunctionOffset = readNext<uint32_t>(PageData, Pos);
7747 uint32_t Encoding = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007748
7749 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007750 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7751 << ", "
7752 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007753 }
7754}
7755
7756static void printCompressedSecondLevelUnwindPage(
Tim Northover3a4e1c72018-01-23 13:51:57 +00007757 StringRef PageData, uint32_t FunctionBase,
Tim Northover39c70bb2014-08-12 11:52:59 +00007758 const SmallVectorImpl<uint32_t> &CommonEncodings) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007759 ptrdiff_t Pos = 0;
7760 uint32_t Kind = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007761 (void)Kind;
7762 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
7763
Tim Northover3a4e1c72018-01-23 13:51:57 +00007764 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7765 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007766
Tim Northover3a4e1c72018-01-23 13:51:57 +00007767 uint16_t EncodingsStart = readNext<uint16_t>(PageData, Pos);
7768 readNext<uint16_t>(PageData, Pos);
7769 StringRef PageEncodings = PageData.substr(EncodingsStart, StringRef::npos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007770
Tim Northover3a4e1c72018-01-23 13:51:57 +00007771 Pos = EntriesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007772 for (unsigned i = 0; i < NumEntries; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007773 uint32_t Entry = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007774 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
7775 uint32_t EncodingIdx = Entry >> 24;
7776
7777 uint32_t Encoding;
7778 if (EncodingIdx < CommonEncodings.size())
7779 Encoding = CommonEncodings[EncodingIdx];
7780 else
Tim Northover3a4e1c72018-01-23 13:51:57 +00007781 Encoding = read<uint32_t>(PageEncodings,
7782 sizeof(uint32_t) *
7783 (EncodingIdx - CommonEncodings.size()));
Tim Northover39c70bb2014-08-12 11:52:59 +00007784
7785 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007786 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7787 << ", "
7788 << "encoding[" << EncodingIdx
7789 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007790 }
7791}
7792
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007793static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
7794 std::map<uint64_t, SymbolRef> &Symbols,
7795 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00007796
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007797 if (!Obj->isLittleEndian()) {
7798 outs() << "Skipping big-endian __unwind_info section\n";
7799 return;
7800 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007801
7802 outs() << "Contents of __unwind_info section:\n";
7803
7804 StringRef Contents;
7805 UnwindInfo.getContents(Contents);
Tim Northover3a4e1c72018-01-23 13:51:57 +00007806 ptrdiff_t Pos = 0;
Tim Northover39c70bb2014-08-12 11:52:59 +00007807
7808 //===----------------------------------
7809 // Section header
7810 //===----------------------------------
7811
Tim Northover3a4e1c72018-01-23 13:51:57 +00007812 uint32_t Version = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007813 outs() << " Version: "
7814 << format("0x%" PRIx32, Version) << '\n';
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007815 if (Version != 1) {
7816 outs() << " Skipping section with unknown version\n";
7817 return;
7818 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007819
Tim Northover3a4e1c72018-01-23 13:51:57 +00007820 uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007821 outs() << " Common encodings array section offset: "
7822 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007823 uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007824 outs() << " Number of common encodings in array: "
7825 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
7826
Tim Northover3a4e1c72018-01-23 13:51:57 +00007827 uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007828 outs() << " Personality function array section offset: "
7829 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007830 uint32_t NumPersonalities = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007831 outs() << " Number of personality functions in array: "
7832 << format("0x%" PRIx32, NumPersonalities) << '\n';
7833
Tim Northover3a4e1c72018-01-23 13:51:57 +00007834 uint32_t IndicesStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007835 outs() << " Index array section offset: "
7836 << format("0x%" PRIx32, IndicesStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007837 uint32_t NumIndices = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007838 outs() << " Number of indices in array: "
7839 << format("0x%" PRIx32, NumIndices) << '\n';
7840
7841 //===----------------------------------
7842 // A shared list of common encodings
7843 //===----------------------------------
7844
7845 // These occupy indices in the range [0, N] whenever an encoding is referenced
7846 // from a compressed 2nd level index table. In practice the linker only
7847 // creates ~128 of these, so that indices are available to embed encodings in
7848 // the 2nd level index.
7849
7850 SmallVector<uint32_t, 64> CommonEncodings;
7851 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007852 Pos = CommonEncodingsStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007853 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007854 uint32_t Encoding = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007855 CommonEncodings.push_back(Encoding);
7856
7857 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
7858 << '\n';
7859 }
7860
Tim Northover39c70bb2014-08-12 11:52:59 +00007861 //===----------------------------------
7862 // Personality functions used in this executable
7863 //===----------------------------------
7864
7865 // There should be only a handful of these (one per source language,
7866 // roughly). Particularly since they only get 2 bits in the compact encoding.
7867
7868 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007869 Pos = PersonalitiesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007870 for (unsigned i = 0; i < NumPersonalities; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007871 uint32_t PersonalityFn = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007872 outs() << " personality[" << i + 1
7873 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
7874 }
7875
7876 //===----------------------------------
7877 // The level 1 index entries
7878 //===----------------------------------
7879
7880 // These specify an approximate place to start searching for the more detailed
7881 // information, sorted by PC.
7882
7883 struct IndexEntry {
7884 uint32_t FunctionOffset;
7885 uint32_t SecondLevelPageStart;
7886 uint32_t LSDAStart;
7887 };
7888
7889 SmallVector<IndexEntry, 4> IndexEntries;
7890
7891 outs() << " Top level indices: (count = " << NumIndices << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007892 Pos = IndicesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007893 for (unsigned i = 0; i < NumIndices; ++i) {
7894 IndexEntry Entry;
7895
Tim Northover3a4e1c72018-01-23 13:51:57 +00007896 Entry.FunctionOffset = readNext<uint32_t>(Contents, Pos);
7897 Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Pos);
7898 Entry.LSDAStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007899 IndexEntries.push_back(Entry);
7900
7901 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007902 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
7903 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00007904 << "2nd level page offset="
7905 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007906 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007907 }
7908
Tim Northover39c70bb2014-08-12 11:52:59 +00007909 //===----------------------------------
7910 // Next come the LSDA tables
7911 //===----------------------------------
7912
7913 // The LSDA layout is rather implicit: it's a contiguous array of entries from
7914 // the first top-level index's LSDAOffset to the last (sentinel).
7915
7916 outs() << " LSDA descriptors:\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007917 Pos = IndexEntries[0].LSDAStart;
7918 const uint32_t LSDASize = 2 * sizeof(uint32_t);
7919 int NumLSDAs =
7920 (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize;
7921
Tim Northover39c70bb2014-08-12 11:52:59 +00007922 for (int i = 0; i < NumLSDAs; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007923 uint32_t FunctionOffset = readNext<uint32_t>(Contents, Pos);
7924 uint32_t LSDAOffset = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007925 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007926 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7927 << ", "
7928 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007929 }
7930
7931 //===----------------------------------
7932 // Finally, the 2nd level indices
7933 //===----------------------------------
7934
7935 // Generally these are 4K in size, and have 2 possible forms:
7936 // + Regular stores up to 511 entries with disparate encodings
7937 // + Compressed stores up to 1021 entries if few enough compact encoding
7938 // values are used.
7939 outs() << " Second level indices:\n";
7940 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
7941 // The final sentinel top-level index has no associated 2nd level page
7942 if (IndexEntries[i].SecondLevelPageStart == 0)
7943 break;
7944
7945 outs() << " Second level index[" << i << "]: "
7946 << "offset in section="
7947 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
7948 << ", "
7949 << "base function offset="
7950 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
7951
Tim Northover3a4e1c72018-01-23 13:51:57 +00007952 Pos = IndexEntries[i].SecondLevelPageStart;
7953 if (Pos + sizeof(uint32_t) > Contents.size()) {
7954 outs() << "warning: invalid offset for second level page: " << Pos << '\n';
7955 continue;
7956 }
7957
7958 uint32_t Kind =
7959 *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007960 if (Kind == 2)
Tim Northover3a4e1c72018-01-23 13:51:57 +00007961 printRegularSecondLevelUnwindPage(Contents.substr(Pos, 4096));
Tim Northover39c70bb2014-08-12 11:52:59 +00007962 else if (Kind == 3)
Tim Northover3a4e1c72018-01-23 13:51:57 +00007963 printCompressedSecondLevelUnwindPage(Contents.substr(Pos, 4096),
7964 IndexEntries[i].FunctionOffset,
Tim Northover39c70bb2014-08-12 11:52:59 +00007965 CommonEncodings);
7966 else
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007967 outs() << " Skipping 2nd level page with unknown kind " << Kind
7968 << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007969 }
7970}
7971
Tim Northover4bd286a2014-08-01 13:07:19 +00007972void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
7973 std::map<uint64_t, SymbolRef> Symbols;
7974 for (const SymbolRef &SymRef : Obj->symbols()) {
7975 // Discard any undefined or absolute symbols. They're not going to take part
7976 // in the convenience lookup for unwind info and just take up resources.
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007977 auto SectOrErr = SymRef.getSection();
7978 if (!SectOrErr) {
7979 // TODO: Actually report errors helpfully.
7980 consumeError(SectOrErr.takeError());
7981 continue;
7982 }
7983 section_iterator Section = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007984 if (Section == Obj->section_end())
7985 continue;
7986
Rafael Espindoladea00162015-07-03 17:44:18 +00007987 uint64_t Addr = SymRef.getValue();
Tim Northover4bd286a2014-08-01 13:07:19 +00007988 Symbols.insert(std::make_pair(Addr, SymRef));
7989 }
7990
7991 for (const SectionRef &Section : Obj->sections()) {
7992 StringRef SectName;
7993 Section.getName(SectName);
7994 if (SectName == "__compact_unwind")
7995 printMachOCompactUnwindSection(Obj, Symbols, Section);
7996 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00007997 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00007998 }
7999}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008000
8001static void PrintMachHeader(uint32_t magic, uint32_t cputype,
8002 uint32_t cpusubtype, uint32_t filetype,
8003 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
8004 bool verbose) {
8005 outs() << "Mach header\n";
8006 outs() << " magic cputype cpusubtype caps filetype ncmds "
8007 "sizeofcmds flags\n";
8008 if (verbose) {
8009 if (magic == MachO::MH_MAGIC)
8010 outs() << " MH_MAGIC";
8011 else if (magic == MachO::MH_MAGIC_64)
8012 outs() << "MH_MAGIC_64";
8013 else
8014 outs() << format(" 0x%08" PRIx32, magic);
8015 switch (cputype) {
8016 case MachO::CPU_TYPE_I386:
8017 outs() << " I386";
8018 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8019 case MachO::CPU_SUBTYPE_I386_ALL:
8020 outs() << " ALL";
8021 break;
8022 default:
8023 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8024 break;
8025 }
8026 break;
8027 case MachO::CPU_TYPE_X86_64:
8028 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00008029 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8030 case MachO::CPU_SUBTYPE_X86_64_ALL:
8031 outs() << " ALL";
8032 break;
8033 case MachO::CPU_SUBTYPE_X86_64_H:
8034 outs() << " Haswell";
8035 break;
8036 default:
8037 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8038 break;
8039 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008040 break;
8041 case MachO::CPU_TYPE_ARM:
8042 outs() << " ARM";
8043 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8044 case MachO::CPU_SUBTYPE_ARM_ALL:
8045 outs() << " ALL";
8046 break;
8047 case MachO::CPU_SUBTYPE_ARM_V4T:
8048 outs() << " V4T";
8049 break;
8050 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
8051 outs() << " V5TEJ";
8052 break;
8053 case MachO::CPU_SUBTYPE_ARM_XSCALE:
8054 outs() << " XSCALE";
8055 break;
8056 case MachO::CPU_SUBTYPE_ARM_V6:
8057 outs() << " V6";
8058 break;
8059 case MachO::CPU_SUBTYPE_ARM_V6M:
8060 outs() << " V6M";
8061 break;
8062 case MachO::CPU_SUBTYPE_ARM_V7:
8063 outs() << " V7";
8064 break;
8065 case MachO::CPU_SUBTYPE_ARM_V7EM:
8066 outs() << " V7EM";
8067 break;
8068 case MachO::CPU_SUBTYPE_ARM_V7K:
8069 outs() << " V7K";
8070 break;
8071 case MachO::CPU_SUBTYPE_ARM_V7M:
8072 outs() << " V7M";
8073 break;
8074 case MachO::CPU_SUBTYPE_ARM_V7S:
8075 outs() << " V7S";
8076 break;
8077 default:
8078 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8079 break;
8080 }
8081 break;
8082 case MachO::CPU_TYPE_ARM64:
8083 outs() << " ARM64";
8084 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8085 case MachO::CPU_SUBTYPE_ARM64_ALL:
8086 outs() << " ALL";
8087 break;
8088 default:
8089 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8090 break;
8091 }
8092 break;
8093 case MachO::CPU_TYPE_POWERPC:
8094 outs() << " PPC";
8095 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8096 case MachO::CPU_SUBTYPE_POWERPC_ALL:
8097 outs() << " ALL";
8098 break;
8099 default:
8100 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8101 break;
8102 }
8103 break;
8104 case MachO::CPU_TYPE_POWERPC64:
8105 outs() << " PPC64";
8106 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8107 case MachO::CPU_SUBTYPE_POWERPC_ALL:
8108 outs() << " ALL";
8109 break;
8110 default:
8111 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8112 break;
8113 }
8114 break;
Kevin Enderby40fdbf82016-01-26 18:20:49 +00008115 default:
8116 outs() << format(" %7d", cputype);
8117 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8118 break;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008119 }
8120 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008121 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008122 } else {
8123 outs() << format(" 0x%02" PRIx32,
8124 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8125 }
8126 switch (filetype) {
8127 case MachO::MH_OBJECT:
8128 outs() << " OBJECT";
8129 break;
8130 case MachO::MH_EXECUTE:
8131 outs() << " EXECUTE";
8132 break;
8133 case MachO::MH_FVMLIB:
8134 outs() << " FVMLIB";
8135 break;
8136 case MachO::MH_CORE:
8137 outs() << " CORE";
8138 break;
8139 case MachO::MH_PRELOAD:
8140 outs() << " PRELOAD";
8141 break;
8142 case MachO::MH_DYLIB:
8143 outs() << " DYLIB";
8144 break;
8145 case MachO::MH_DYLIB_STUB:
8146 outs() << " DYLIB_STUB";
8147 break;
8148 case MachO::MH_DYLINKER:
8149 outs() << " DYLINKER";
8150 break;
8151 case MachO::MH_BUNDLE:
8152 outs() << " BUNDLE";
8153 break;
8154 case MachO::MH_DSYM:
8155 outs() << " DSYM";
8156 break;
8157 case MachO::MH_KEXT_BUNDLE:
8158 outs() << " KEXTBUNDLE";
8159 break;
8160 default:
8161 outs() << format(" %10u", filetype);
8162 break;
8163 }
8164 outs() << format(" %5u", ncmds);
8165 outs() << format(" %10u", sizeofcmds);
8166 uint32_t f = flags;
8167 if (f & MachO::MH_NOUNDEFS) {
8168 outs() << " NOUNDEFS";
8169 f &= ~MachO::MH_NOUNDEFS;
8170 }
8171 if (f & MachO::MH_INCRLINK) {
8172 outs() << " INCRLINK";
8173 f &= ~MachO::MH_INCRLINK;
8174 }
8175 if (f & MachO::MH_DYLDLINK) {
8176 outs() << " DYLDLINK";
8177 f &= ~MachO::MH_DYLDLINK;
8178 }
8179 if (f & MachO::MH_BINDATLOAD) {
8180 outs() << " BINDATLOAD";
8181 f &= ~MachO::MH_BINDATLOAD;
8182 }
8183 if (f & MachO::MH_PREBOUND) {
8184 outs() << " PREBOUND";
8185 f &= ~MachO::MH_PREBOUND;
8186 }
8187 if (f & MachO::MH_SPLIT_SEGS) {
8188 outs() << " SPLIT_SEGS";
8189 f &= ~MachO::MH_SPLIT_SEGS;
8190 }
8191 if (f & MachO::MH_LAZY_INIT) {
8192 outs() << " LAZY_INIT";
8193 f &= ~MachO::MH_LAZY_INIT;
8194 }
8195 if (f & MachO::MH_TWOLEVEL) {
8196 outs() << " TWOLEVEL";
8197 f &= ~MachO::MH_TWOLEVEL;
8198 }
8199 if (f & MachO::MH_FORCE_FLAT) {
8200 outs() << " FORCE_FLAT";
8201 f &= ~MachO::MH_FORCE_FLAT;
8202 }
8203 if (f & MachO::MH_NOMULTIDEFS) {
8204 outs() << " NOMULTIDEFS";
8205 f &= ~MachO::MH_NOMULTIDEFS;
8206 }
8207 if (f & MachO::MH_NOFIXPREBINDING) {
8208 outs() << " NOFIXPREBINDING";
8209 f &= ~MachO::MH_NOFIXPREBINDING;
8210 }
8211 if (f & MachO::MH_PREBINDABLE) {
8212 outs() << " PREBINDABLE";
8213 f &= ~MachO::MH_PREBINDABLE;
8214 }
8215 if (f & MachO::MH_ALLMODSBOUND) {
8216 outs() << " ALLMODSBOUND";
8217 f &= ~MachO::MH_ALLMODSBOUND;
8218 }
8219 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
8220 outs() << " SUBSECTIONS_VIA_SYMBOLS";
8221 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
8222 }
8223 if (f & MachO::MH_CANONICAL) {
8224 outs() << " CANONICAL";
8225 f &= ~MachO::MH_CANONICAL;
8226 }
8227 if (f & MachO::MH_WEAK_DEFINES) {
8228 outs() << " WEAK_DEFINES";
8229 f &= ~MachO::MH_WEAK_DEFINES;
8230 }
8231 if (f & MachO::MH_BINDS_TO_WEAK) {
8232 outs() << " BINDS_TO_WEAK";
8233 f &= ~MachO::MH_BINDS_TO_WEAK;
8234 }
8235 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
8236 outs() << " ALLOW_STACK_EXECUTION";
8237 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
8238 }
8239 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
8240 outs() << " DEAD_STRIPPABLE_DYLIB";
8241 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
8242 }
8243 if (f & MachO::MH_PIE) {
8244 outs() << " PIE";
8245 f &= ~MachO::MH_PIE;
8246 }
8247 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
8248 outs() << " NO_REEXPORTED_DYLIBS";
8249 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
8250 }
8251 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
8252 outs() << " MH_HAS_TLV_DESCRIPTORS";
8253 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
8254 }
8255 if (f & MachO::MH_NO_HEAP_EXECUTION) {
8256 outs() << " MH_NO_HEAP_EXECUTION";
8257 f &= ~MachO::MH_NO_HEAP_EXECUTION;
8258 }
8259 if (f & MachO::MH_APP_EXTENSION_SAFE) {
8260 outs() << " APP_EXTENSION_SAFE";
8261 f &= ~MachO::MH_APP_EXTENSION_SAFE;
8262 }
Kevin Enderbydf0d6da2017-06-19 19:38:22 +00008263 if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
8264 outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO";
8265 f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO;
8266 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008267 if (f != 0 || flags == 0)
8268 outs() << format(" 0x%08" PRIx32, f);
8269 } else {
8270 outs() << format(" 0x%08" PRIx32, magic);
8271 outs() << format(" %7d", cputype);
8272 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8273 outs() << format(" 0x%02" PRIx32,
8274 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8275 outs() << format(" %10u", filetype);
8276 outs() << format(" %5u", ncmds);
8277 outs() << format(" %10u", sizeofcmds);
8278 outs() << format(" 0x%08" PRIx32, flags);
8279 }
8280 outs() << "\n";
8281}
8282
Kevin Enderby956366c2014-08-29 22:30:52 +00008283static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
8284 StringRef SegName, uint64_t vmaddr,
8285 uint64_t vmsize, uint64_t fileoff,
8286 uint64_t filesize, uint32_t maxprot,
8287 uint32_t initprot, uint32_t nsects,
8288 uint32_t flags, uint32_t object_size,
8289 bool verbose) {
8290 uint64_t expected_cmdsize;
8291 if (cmd == MachO::LC_SEGMENT) {
8292 outs() << " cmd LC_SEGMENT\n";
8293 expected_cmdsize = nsects;
8294 expected_cmdsize *= sizeof(struct MachO::section);
8295 expected_cmdsize += sizeof(struct MachO::segment_command);
8296 } else {
8297 outs() << " cmd LC_SEGMENT_64\n";
8298 expected_cmdsize = nsects;
8299 expected_cmdsize *= sizeof(struct MachO::section_64);
8300 expected_cmdsize += sizeof(struct MachO::segment_command_64);
8301 }
8302 outs() << " cmdsize " << cmdsize;
8303 if (cmdsize != expected_cmdsize)
8304 outs() << " Inconsistent size\n";
8305 else
8306 outs() << "\n";
8307 outs() << " segname " << SegName << "\n";
8308 if (cmd == MachO::LC_SEGMENT_64) {
8309 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
8310 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
8311 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00008312 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
8313 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008314 }
8315 outs() << " fileoff " << fileoff;
8316 if (fileoff > object_size)
8317 outs() << " (past end of file)\n";
8318 else
8319 outs() << "\n";
8320 outs() << " filesize " << filesize;
8321 if (fileoff + filesize > object_size)
8322 outs() << " (past end of file)\n";
8323 else
8324 outs() << "\n";
8325 if (verbose) {
8326 if ((maxprot &
8327 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8328 MachO::VM_PROT_EXECUTE)) != 0)
8329 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
8330 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00008331 outs() << " maxprot ";
8332 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
8333 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8334 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00008335 }
8336 if ((initprot &
8337 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8338 MachO::VM_PROT_EXECUTE)) != 0)
Kevin Enderby41c9c002016-10-21 18:22:35 +00008339 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008340 else {
Kevin Enderby41c9c002016-10-21 18:22:35 +00008341 outs() << " initprot ";
Davide Italiano37ff06a2015-09-02 16:53:25 +00008342 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
8343 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8344 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00008345 }
8346 } else {
8347 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
8348 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
8349 }
8350 outs() << " nsects " << nsects << "\n";
8351 if (verbose) {
8352 outs() << " flags";
8353 if (flags == 0)
8354 outs() << " (none)\n";
8355 else {
8356 if (flags & MachO::SG_HIGHVM) {
8357 outs() << " HIGHVM";
8358 flags &= ~MachO::SG_HIGHVM;
8359 }
8360 if (flags & MachO::SG_FVMLIB) {
8361 outs() << " FVMLIB";
8362 flags &= ~MachO::SG_FVMLIB;
8363 }
8364 if (flags & MachO::SG_NORELOC) {
8365 outs() << " NORELOC";
8366 flags &= ~MachO::SG_NORELOC;
8367 }
8368 if (flags & MachO::SG_PROTECTED_VERSION_1) {
8369 outs() << " PROTECTED_VERSION_1";
8370 flags &= ~MachO::SG_PROTECTED_VERSION_1;
8371 }
8372 if (flags)
8373 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
8374 else
8375 outs() << "\n";
8376 }
8377 } else {
8378 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
8379 }
8380}
8381
8382static void PrintSection(const char *sectname, const char *segname,
8383 uint64_t addr, uint64_t size, uint32_t offset,
8384 uint32_t align, uint32_t reloff, uint32_t nreloc,
8385 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
8386 uint32_t cmd, const char *sg_segname,
8387 uint32_t filetype, uint32_t object_size,
8388 bool verbose) {
8389 outs() << "Section\n";
8390 outs() << " sectname " << format("%.16s\n", sectname);
8391 outs() << " segname " << format("%.16s", segname);
8392 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
8393 outs() << " (does not match segment)\n";
8394 else
8395 outs() << "\n";
8396 if (cmd == MachO::LC_SEGMENT_64) {
8397 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
8398 outs() << " size " << format("0x%016" PRIx64, size);
8399 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00008400 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
8401 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00008402 }
8403 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
8404 outs() << " (past end of file)\n";
8405 else
8406 outs() << "\n";
8407 outs() << " offset " << offset;
8408 if (offset > object_size)
8409 outs() << " (past end of file)\n";
8410 else
8411 outs() << "\n";
8412 uint32_t align_shifted = 1 << align;
8413 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
8414 outs() << " reloff " << reloff;
8415 if (reloff > object_size)
8416 outs() << " (past end of file)\n";
8417 else
8418 outs() << "\n";
8419 outs() << " nreloc " << nreloc;
8420 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
8421 outs() << " (past end of file)\n";
8422 else
8423 outs() << "\n";
8424 uint32_t section_type = flags & MachO::SECTION_TYPE;
8425 if (verbose) {
8426 outs() << " type";
8427 if (section_type == MachO::S_REGULAR)
8428 outs() << " S_REGULAR\n";
8429 else if (section_type == MachO::S_ZEROFILL)
8430 outs() << " S_ZEROFILL\n";
8431 else if (section_type == MachO::S_CSTRING_LITERALS)
8432 outs() << " S_CSTRING_LITERALS\n";
8433 else if (section_type == MachO::S_4BYTE_LITERALS)
8434 outs() << " S_4BYTE_LITERALS\n";
8435 else if (section_type == MachO::S_8BYTE_LITERALS)
8436 outs() << " S_8BYTE_LITERALS\n";
8437 else if (section_type == MachO::S_16BYTE_LITERALS)
8438 outs() << " S_16BYTE_LITERALS\n";
8439 else if (section_type == MachO::S_LITERAL_POINTERS)
8440 outs() << " S_LITERAL_POINTERS\n";
8441 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
8442 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
8443 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
8444 outs() << " S_LAZY_SYMBOL_POINTERS\n";
8445 else if (section_type == MachO::S_SYMBOL_STUBS)
8446 outs() << " S_SYMBOL_STUBS\n";
8447 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
8448 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
8449 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
8450 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
8451 else if (section_type == MachO::S_COALESCED)
8452 outs() << " S_COALESCED\n";
8453 else if (section_type == MachO::S_INTERPOSING)
8454 outs() << " S_INTERPOSING\n";
8455 else if (section_type == MachO::S_DTRACE_DOF)
8456 outs() << " S_DTRACE_DOF\n";
8457 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
8458 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
8459 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
8460 outs() << " S_THREAD_LOCAL_REGULAR\n";
8461 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
8462 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
8463 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
8464 outs() << " S_THREAD_LOCAL_VARIABLES\n";
8465 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8466 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
8467 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
8468 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
8469 else
8470 outs() << format("0x%08" PRIx32, section_type) << "\n";
8471 outs() << "attributes";
8472 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
8473 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
8474 outs() << " PURE_INSTRUCTIONS";
8475 if (section_attributes & MachO::S_ATTR_NO_TOC)
8476 outs() << " NO_TOC";
8477 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
8478 outs() << " STRIP_STATIC_SYMS";
8479 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
8480 outs() << " NO_DEAD_STRIP";
8481 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
8482 outs() << " LIVE_SUPPORT";
8483 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
8484 outs() << " SELF_MODIFYING_CODE";
8485 if (section_attributes & MachO::S_ATTR_DEBUG)
8486 outs() << " DEBUG";
8487 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
8488 outs() << " SOME_INSTRUCTIONS";
8489 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
8490 outs() << " EXT_RELOC";
8491 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
8492 outs() << " LOC_RELOC";
8493 if (section_attributes == 0)
8494 outs() << " (none)";
8495 outs() << "\n";
8496 } else
8497 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
8498 outs() << " reserved1 " << reserved1;
8499 if (section_type == MachO::S_SYMBOL_STUBS ||
8500 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
8501 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
8502 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
8503 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8504 outs() << " (index into indirect symbol table)\n";
8505 else
8506 outs() << "\n";
8507 outs() << " reserved2 " << reserved2;
8508 if (section_type == MachO::S_SYMBOL_STUBS)
8509 outs() << " (size of stubs)\n";
8510 else
8511 outs() << "\n";
8512}
8513
David Majnemer73cc6ff2014-11-13 19:48:56 +00008514static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00008515 uint32_t object_size) {
8516 outs() << " cmd LC_SYMTAB\n";
8517 outs() << " cmdsize " << st.cmdsize;
8518 if (st.cmdsize != sizeof(struct MachO::symtab_command))
8519 outs() << " Incorrect size\n";
8520 else
8521 outs() << "\n";
8522 outs() << " symoff " << st.symoff;
8523 if (st.symoff > object_size)
8524 outs() << " (past end of file)\n";
8525 else
8526 outs() << "\n";
8527 outs() << " nsyms " << st.nsyms;
8528 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00008529 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008530 big_size = st.nsyms;
8531 big_size *= sizeof(struct MachO::nlist_64);
8532 big_size += st.symoff;
8533 if (big_size > object_size)
8534 outs() << " (past end of file)\n";
8535 else
8536 outs() << "\n";
8537 } else {
8538 big_size = st.nsyms;
8539 big_size *= sizeof(struct MachO::nlist);
8540 big_size += st.symoff;
8541 if (big_size > object_size)
8542 outs() << " (past end of file)\n";
8543 else
8544 outs() << "\n";
8545 }
8546 outs() << " stroff " << st.stroff;
8547 if (st.stroff > object_size)
8548 outs() << " (past end of file)\n";
8549 else
8550 outs() << "\n";
8551 outs() << " strsize " << st.strsize;
8552 big_size = st.stroff;
8553 big_size += st.strsize;
8554 if (big_size > object_size)
8555 outs() << " (past end of file)\n";
8556 else
8557 outs() << "\n";
8558}
8559
8560static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
8561 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00008562 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008563 outs() << " cmd LC_DYSYMTAB\n";
8564 outs() << " cmdsize " << dyst.cmdsize;
8565 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
8566 outs() << " Incorrect size\n";
8567 else
8568 outs() << "\n";
8569 outs() << " ilocalsym " << dyst.ilocalsym;
8570 if (dyst.ilocalsym > nsyms)
8571 outs() << " (greater than the number of symbols)\n";
8572 else
8573 outs() << "\n";
8574 outs() << " nlocalsym " << dyst.nlocalsym;
8575 uint64_t big_size;
8576 big_size = dyst.ilocalsym;
8577 big_size += dyst.nlocalsym;
8578 if (big_size > nsyms)
8579 outs() << " (past the end of the symbol table)\n";
8580 else
8581 outs() << "\n";
8582 outs() << " iextdefsym " << dyst.iextdefsym;
8583 if (dyst.iextdefsym > nsyms)
8584 outs() << " (greater than the number of symbols)\n";
8585 else
8586 outs() << "\n";
8587 outs() << " nextdefsym " << dyst.nextdefsym;
8588 big_size = dyst.iextdefsym;
8589 big_size += dyst.nextdefsym;
8590 if (big_size > nsyms)
8591 outs() << " (past the end of the symbol table)\n";
8592 else
8593 outs() << "\n";
8594 outs() << " iundefsym " << dyst.iundefsym;
8595 if (dyst.iundefsym > nsyms)
8596 outs() << " (greater than the number of symbols)\n";
8597 else
8598 outs() << "\n";
8599 outs() << " nundefsym " << dyst.nundefsym;
8600 big_size = dyst.iundefsym;
8601 big_size += dyst.nundefsym;
8602 if (big_size > nsyms)
8603 outs() << " (past the end of the symbol table)\n";
8604 else
8605 outs() << "\n";
8606 outs() << " tocoff " << dyst.tocoff;
8607 if (dyst.tocoff > object_size)
8608 outs() << " (past end of file)\n";
8609 else
8610 outs() << "\n";
8611 outs() << " ntoc " << dyst.ntoc;
8612 big_size = dyst.ntoc;
8613 big_size *= sizeof(struct MachO::dylib_table_of_contents);
8614 big_size += dyst.tocoff;
8615 if (big_size > object_size)
8616 outs() << " (past end of file)\n";
8617 else
8618 outs() << "\n";
8619 outs() << " modtaboff " << dyst.modtaboff;
8620 if (dyst.modtaboff > object_size)
8621 outs() << " (past end of file)\n";
8622 else
8623 outs() << "\n";
8624 outs() << " nmodtab " << dyst.nmodtab;
8625 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00008626 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008627 modtabend = dyst.nmodtab;
8628 modtabend *= sizeof(struct MachO::dylib_module_64);
8629 modtabend += dyst.modtaboff;
8630 } else {
8631 modtabend = dyst.nmodtab;
8632 modtabend *= sizeof(struct MachO::dylib_module);
8633 modtabend += dyst.modtaboff;
8634 }
8635 if (modtabend > object_size)
8636 outs() << " (past end of file)\n";
8637 else
8638 outs() << "\n";
8639 outs() << " extrefsymoff " << dyst.extrefsymoff;
8640 if (dyst.extrefsymoff > object_size)
8641 outs() << " (past end of file)\n";
8642 else
8643 outs() << "\n";
8644 outs() << " nextrefsyms " << dyst.nextrefsyms;
8645 big_size = dyst.nextrefsyms;
8646 big_size *= sizeof(struct MachO::dylib_reference);
8647 big_size += dyst.extrefsymoff;
8648 if (big_size > object_size)
8649 outs() << " (past end of file)\n";
8650 else
8651 outs() << "\n";
8652 outs() << " indirectsymoff " << dyst.indirectsymoff;
8653 if (dyst.indirectsymoff > object_size)
8654 outs() << " (past end of file)\n";
8655 else
8656 outs() << "\n";
8657 outs() << " nindirectsyms " << dyst.nindirectsyms;
8658 big_size = dyst.nindirectsyms;
8659 big_size *= sizeof(uint32_t);
8660 big_size += dyst.indirectsymoff;
8661 if (big_size > object_size)
8662 outs() << " (past end of file)\n";
8663 else
8664 outs() << "\n";
8665 outs() << " extreloff " << dyst.extreloff;
8666 if (dyst.extreloff > object_size)
8667 outs() << " (past end of file)\n";
8668 else
8669 outs() << "\n";
8670 outs() << " nextrel " << dyst.nextrel;
8671 big_size = dyst.nextrel;
8672 big_size *= sizeof(struct MachO::relocation_info);
8673 big_size += dyst.extreloff;
8674 if (big_size > object_size)
8675 outs() << " (past end of file)\n";
8676 else
8677 outs() << "\n";
8678 outs() << " locreloff " << dyst.locreloff;
8679 if (dyst.locreloff > object_size)
8680 outs() << " (past end of file)\n";
8681 else
8682 outs() << "\n";
8683 outs() << " nlocrel " << dyst.nlocrel;
8684 big_size = dyst.nlocrel;
8685 big_size *= sizeof(struct MachO::relocation_info);
8686 big_size += dyst.locreloff;
8687 if (big_size > object_size)
8688 outs() << " (past end of file)\n";
8689 else
8690 outs() << "\n";
8691}
8692
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008693static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8694 uint32_t object_size) {
8695 if (dc.cmd == MachO::LC_DYLD_INFO)
8696 outs() << " cmd LC_DYLD_INFO\n";
8697 else
8698 outs() << " cmd LC_DYLD_INFO_ONLY\n";
8699 outs() << " cmdsize " << dc.cmdsize;
8700 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8701 outs() << " Incorrect size\n";
8702 else
8703 outs() << "\n";
8704 outs() << " rebase_off " << dc.rebase_off;
8705 if (dc.rebase_off > object_size)
8706 outs() << " (past end of file)\n";
8707 else
8708 outs() << "\n";
8709 outs() << " rebase_size " << dc.rebase_size;
8710 uint64_t big_size;
8711 big_size = dc.rebase_off;
8712 big_size += dc.rebase_size;
8713 if (big_size > object_size)
8714 outs() << " (past end of file)\n";
8715 else
8716 outs() << "\n";
8717 outs() << " bind_off " << dc.bind_off;
8718 if (dc.bind_off > object_size)
8719 outs() << " (past end of file)\n";
8720 else
8721 outs() << "\n";
8722 outs() << " bind_size " << dc.bind_size;
8723 big_size = dc.bind_off;
8724 big_size += dc.bind_size;
8725 if (big_size > object_size)
8726 outs() << " (past end of file)\n";
8727 else
8728 outs() << "\n";
8729 outs() << " weak_bind_off " << dc.weak_bind_off;
8730 if (dc.weak_bind_off > object_size)
8731 outs() << " (past end of file)\n";
8732 else
8733 outs() << "\n";
8734 outs() << " weak_bind_size " << dc.weak_bind_size;
8735 big_size = dc.weak_bind_off;
8736 big_size += dc.weak_bind_size;
8737 if (big_size > object_size)
8738 outs() << " (past end of file)\n";
8739 else
8740 outs() << "\n";
8741 outs() << " lazy_bind_off " << dc.lazy_bind_off;
8742 if (dc.lazy_bind_off > object_size)
8743 outs() << " (past end of file)\n";
8744 else
8745 outs() << "\n";
8746 outs() << " lazy_bind_size " << dc.lazy_bind_size;
8747 big_size = dc.lazy_bind_off;
8748 big_size += dc.lazy_bind_size;
8749 if (big_size > object_size)
8750 outs() << " (past end of file)\n";
8751 else
8752 outs() << "\n";
8753 outs() << " export_off " << dc.export_off;
8754 if (dc.export_off > object_size)
8755 outs() << " (past end of file)\n";
8756 else
8757 outs() << "\n";
8758 outs() << " export_size " << dc.export_size;
8759 big_size = dc.export_off;
8760 big_size += dc.export_size;
8761 if (big_size > object_size)
8762 outs() << " (past end of file)\n";
8763 else
8764 outs() << "\n";
8765}
8766
8767static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
8768 const char *Ptr) {
8769 if (dyld.cmd == MachO::LC_ID_DYLINKER)
8770 outs() << " cmd LC_ID_DYLINKER\n";
8771 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
8772 outs() << " cmd LC_LOAD_DYLINKER\n";
8773 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
8774 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
8775 else
8776 outs() << " cmd ?(" << dyld.cmd << ")\n";
8777 outs() << " cmdsize " << dyld.cmdsize;
8778 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
8779 outs() << " Incorrect size\n";
8780 else
8781 outs() << "\n";
8782 if (dyld.name >= dyld.cmdsize)
8783 outs() << " name ?(bad offset " << dyld.name << ")\n";
8784 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008785 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008786 outs() << " name " << P << " (offset " << dyld.name << ")\n";
8787 }
8788}
8789
8790static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
8791 outs() << " cmd LC_UUID\n";
8792 outs() << " cmdsize " << uuid.cmdsize;
8793 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
8794 outs() << " Incorrect size\n";
8795 else
8796 outs() << "\n";
8797 outs() << " uuid ";
Davide Italianoc74277a2015-12-07 00:03:28 +00008798 for (int i = 0; i < 16; ++i) {
8799 outs() << format("%02" PRIX32, uuid.uuid[i]);
8800 if (i == 3 || i == 5 || i == 7 || i == 9)
8801 outs() << "-";
8802 }
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008803 outs() << "\n";
8804}
8805
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008806static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008807 outs() << " cmd LC_RPATH\n";
8808 outs() << " cmdsize " << rpath.cmdsize;
8809 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
8810 outs() << " Incorrect size\n";
8811 else
8812 outs() << "\n";
8813 if (rpath.path >= rpath.cmdsize)
8814 outs() << " path ?(bad offset " << rpath.path << ")\n";
8815 else {
8816 const char *P = (const char *)(Ptr) + rpath.path;
8817 outs() << " path " << P << " (offset " << rpath.path << ")\n";
8818 }
8819}
8820
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008821static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
Tim Northoverbfbfb122015-11-02 21:26:58 +00008822 StringRef LoadCmdName;
8823 switch (vd.cmd) {
8824 case MachO::LC_VERSION_MIN_MACOSX:
8825 LoadCmdName = "LC_VERSION_MIN_MACOSX";
8826 break;
8827 case MachO::LC_VERSION_MIN_IPHONEOS:
8828 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
8829 break;
8830 case MachO::LC_VERSION_MIN_TVOS:
8831 LoadCmdName = "LC_VERSION_MIN_TVOS";
8832 break;
8833 case MachO::LC_VERSION_MIN_WATCHOS:
8834 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
8835 break;
8836 default:
8837 llvm_unreachable("Unknown version min load command");
8838 }
8839
8840 outs() << " cmd " << LoadCmdName << '\n';
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008841 outs() << " cmdsize " << vd.cmdsize;
8842 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
8843 outs() << " Incorrect size\n";
8844 else
8845 outs() << "\n";
Davide Italiano56baef32015-08-26 12:26:11 +00008846 outs() << " version "
8847 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
8848 << MachOObjectFile::getVersionMinMinor(vd, false);
8849 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
8850 if (Update != 0)
8851 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008852 outs() << "\n";
8853 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00008854 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008855 else {
Davide Italiano56baef32015-08-26 12:26:11 +00008856 outs() << " sdk "
8857 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
8858 << MachOObjectFile::getVersionMinMinor(vd, true);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008859 }
Davide Italiano56baef32015-08-26 12:26:11 +00008860 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
8861 if (Update != 0)
8862 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008863 outs() << "\n";
8864}
8865
Kevin Enderbya4579c42017-01-19 17:36:31 +00008866static void PrintNoteLoadCommand(MachO::note_command Nt) {
8867 outs() << " cmd LC_NOTE\n";
8868 outs() << " cmdsize " << Nt.cmdsize;
8869 if (Nt.cmdsize != sizeof(struct MachO::note_command))
8870 outs() << " Incorrect size\n";
8871 else
8872 outs() << "\n";
8873 const char *d = Nt.data_owner;
8874 outs() << "data_owner " << format("%.16s\n", d);
8875 outs() << " offset " << Nt.offset << "\n";
8876 outs() << " size " << Nt.size << "\n";
8877}
8878
Steven Wu5b54a422017-01-23 20:07:55 +00008879static void PrintBuildToolVersion(MachO::build_tool_version bv) {
8880 outs() << " tool " << MachOObjectFile::getBuildTool(bv.tool) << "\n";
8881 outs() << " version " << MachOObjectFile::getVersionString(bv.version)
8882 << "\n";
8883}
8884
8885static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
8886 MachO::build_version_command bd) {
8887 outs() << " cmd LC_BUILD_VERSION\n";
8888 outs() << " cmdsize " << bd.cmdsize;
8889 if (bd.cmdsize !=
8890 sizeof(struct MachO::build_version_command) +
8891 bd.ntools * sizeof(struct MachO::build_tool_version))
8892 outs() << " Incorrect size\n";
8893 else
8894 outs() << "\n";
8895 outs() << " platform " << MachOObjectFile::getBuildPlatform(bd.platform)
8896 << "\n";
8897 if (bd.sdk)
8898 outs() << " sdk " << MachOObjectFile::getVersionString(bd.sdk)
8899 << "\n";
8900 else
8901 outs() << " sdk n/a\n";
8902 outs() << " minos " << MachOObjectFile::getVersionString(bd.minos)
8903 << "\n";
8904 outs() << " ntools " << bd.ntools << "\n";
8905 for (unsigned i = 0; i < bd.ntools; ++i) {
8906 MachO::build_tool_version bv = obj->getBuildToolVersion(i);
8907 PrintBuildToolVersion(bv);
8908 }
8909}
8910
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008911static void PrintSourceVersionCommand(MachO::source_version_command sd) {
8912 outs() << " cmd LC_SOURCE_VERSION\n";
8913 outs() << " cmdsize " << sd.cmdsize;
8914 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
8915 outs() << " Incorrect size\n";
8916 else
8917 outs() << "\n";
8918 uint64_t a = (sd.version >> 40) & 0xffffff;
8919 uint64_t b = (sd.version >> 30) & 0x3ff;
8920 uint64_t c = (sd.version >> 20) & 0x3ff;
8921 uint64_t d = (sd.version >> 10) & 0x3ff;
8922 uint64_t e = sd.version & 0x3ff;
8923 outs() << " version " << a << "." << b;
8924 if (e != 0)
8925 outs() << "." << c << "." << d << "." << e;
8926 else if (d != 0)
8927 outs() << "." << c << "." << d;
8928 else if (c != 0)
8929 outs() << "." << c;
8930 outs() << "\n";
8931}
8932
8933static void PrintEntryPointCommand(MachO::entry_point_command ep) {
8934 outs() << " cmd LC_MAIN\n";
8935 outs() << " cmdsize " << ep.cmdsize;
8936 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
8937 outs() << " Incorrect size\n";
8938 else
8939 outs() << "\n";
8940 outs() << " entryoff " << ep.entryoff << "\n";
8941 outs() << " stacksize " << ep.stacksize << "\n";
8942}
8943
Kevin Enderby0804f4672014-12-16 23:25:52 +00008944static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
8945 uint32_t object_size) {
8946 outs() << " cmd LC_ENCRYPTION_INFO\n";
8947 outs() << " cmdsize " << ec.cmdsize;
8948 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
8949 outs() << " Incorrect size\n";
8950 else
8951 outs() << "\n";
8952 outs() << " cryptoff " << ec.cryptoff;
8953 if (ec.cryptoff > object_size)
8954 outs() << " (past end of file)\n";
8955 else
8956 outs() << "\n";
8957 outs() << " cryptsize " << ec.cryptsize;
8958 if (ec.cryptsize > object_size)
8959 outs() << " (past end of file)\n";
8960 else
8961 outs() << "\n";
8962 outs() << " cryptid " << ec.cryptid << "\n";
8963}
8964
Kevin Enderby57538292014-12-17 01:01:30 +00008965static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008966 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00008967 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
8968 outs() << " cmdsize " << ec.cmdsize;
8969 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
8970 outs() << " Incorrect size\n";
8971 else
8972 outs() << "\n";
8973 outs() << " cryptoff " << ec.cryptoff;
8974 if (ec.cryptoff > object_size)
8975 outs() << " (past end of file)\n";
8976 else
8977 outs() << "\n";
8978 outs() << " cryptsize " << ec.cryptsize;
8979 if (ec.cryptsize > object_size)
8980 outs() << " (past end of file)\n";
8981 else
8982 outs() << "\n";
8983 outs() << " cryptid " << ec.cryptid << "\n";
8984 outs() << " pad " << ec.pad << "\n";
8985}
8986
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008987static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
8988 const char *Ptr) {
8989 outs() << " cmd LC_LINKER_OPTION\n";
8990 outs() << " cmdsize " << lo.cmdsize;
8991 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
8992 outs() << " Incorrect size\n";
8993 else
8994 outs() << "\n";
8995 outs() << " count " << lo.count << "\n";
8996 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
8997 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
8998 uint32_t i = 0;
8999 while (left > 0) {
9000 while (*string == '\0' && left > 0) {
9001 string++;
9002 left--;
9003 }
9004 if (left > 0) {
9005 i++;
9006 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00009007 uint32_t NullPos = StringRef(string, left).find('\0');
9008 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009009 string += len;
9010 left -= len;
9011 }
9012 }
9013 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009014 outs() << " count " << lo.count << " does not match number of strings "
9015 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009016}
9017
Kevin Enderbyb4b79312014-12-18 19:24:35 +00009018static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
9019 const char *Ptr) {
9020 outs() << " cmd LC_SUB_FRAMEWORK\n";
9021 outs() << " cmdsize " << sub.cmdsize;
9022 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
9023 outs() << " Incorrect size\n";
9024 else
9025 outs() << "\n";
9026 if (sub.umbrella < sub.cmdsize) {
9027 const char *P = Ptr + sub.umbrella;
9028 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
9029 } else {
9030 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
9031 }
9032}
9033
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00009034static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
9035 const char *Ptr) {
9036 outs() << " cmd LC_SUB_UMBRELLA\n";
9037 outs() << " cmdsize " << sub.cmdsize;
9038 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
9039 outs() << " Incorrect size\n";
9040 else
9041 outs() << "\n";
9042 if (sub.sub_umbrella < sub.cmdsize) {
9043 const char *P = Ptr + sub.sub_umbrella;
9044 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
9045 } else {
9046 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
9047 }
9048}
9049
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009050static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009051 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009052 outs() << " cmd LC_SUB_LIBRARY\n";
9053 outs() << " cmdsize " << sub.cmdsize;
9054 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
9055 outs() << " Incorrect size\n";
9056 else
9057 outs() << "\n";
9058 if (sub.sub_library < sub.cmdsize) {
9059 const char *P = Ptr + sub.sub_library;
9060 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
9061 } else {
9062 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
9063 }
9064}
9065
Kevin Enderby186eac32014-12-19 21:06:24 +00009066static void PrintSubClientCommand(MachO::sub_client_command sub,
9067 const char *Ptr) {
9068 outs() << " cmd LC_SUB_CLIENT\n";
9069 outs() << " cmdsize " << sub.cmdsize;
9070 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
9071 outs() << " Incorrect size\n";
9072 else
9073 outs() << "\n";
9074 if (sub.client < sub.cmdsize) {
9075 const char *P = Ptr + sub.client;
9076 outs() << " client " << P << " (offset " << sub.client << ")\n";
9077 } else {
9078 outs() << " client ?(bad offset " << sub.client << ")\n";
9079 }
9080}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009081
Kevin Enderby52e4ce42014-12-19 22:25:22 +00009082static void PrintRoutinesCommand(MachO::routines_command r) {
9083 outs() << " cmd LC_ROUTINES\n";
9084 outs() << " cmdsize " << r.cmdsize;
9085 if (r.cmdsize != sizeof(struct MachO::routines_command))
9086 outs() << " Incorrect size\n";
9087 else
9088 outs() << "\n";
9089 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
9090 outs() << " init_module " << r.init_module << "\n";
9091 outs() << " reserved1 " << r.reserved1 << "\n";
9092 outs() << " reserved2 " << r.reserved2 << "\n";
9093 outs() << " reserved3 " << r.reserved3 << "\n";
9094 outs() << " reserved4 " << r.reserved4 << "\n";
9095 outs() << " reserved5 " << r.reserved5 << "\n";
9096 outs() << " reserved6 " << r.reserved6 << "\n";
9097}
9098
9099static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
9100 outs() << " cmd LC_ROUTINES_64\n";
9101 outs() << " cmdsize " << r.cmdsize;
9102 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
9103 outs() << " Incorrect size\n";
9104 else
9105 outs() << "\n";
9106 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
9107 outs() << " init_module " << r.init_module << "\n";
9108 outs() << " reserved1 " << r.reserved1 << "\n";
9109 outs() << " reserved2 " << r.reserved2 << "\n";
9110 outs() << " reserved3 " << r.reserved3 << "\n";
9111 outs() << " reserved4 " << r.reserved4 << "\n";
9112 outs() << " reserved5 " << r.reserved5 << "\n";
9113 outs() << " reserved6 " << r.reserved6 << "\n";
9114}
9115
Kevin Enderbyc3a035d2017-01-23 21:13:29 +00009116static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
9117 outs() << "\t eax " << format("0x%08" PRIx32, cpu32.eax);
9118 outs() << " ebx " << format("0x%08" PRIx32, cpu32.ebx);
9119 outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx);
9120 outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n";
9121 outs() << "\t edi " << format("0x%08" PRIx32, cpu32.edi);
9122 outs() << " esi " << format("0x%08" PRIx32, cpu32.esi);
9123 outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp);
9124 outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n";
9125 outs() << "\t ss " << format("0x%08" PRIx32, cpu32.ss);
9126 outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags);
9127 outs() << " eip " << format("0x%08" PRIx32, cpu32.eip);
9128 outs() << " cs " << format("0x%08" PRIx32, cpu32.cs) << "\n";
9129 outs() << "\t ds " << format("0x%08" PRIx32, cpu32.ds);
9130 outs() << " es " << format("0x%08" PRIx32, cpu32.es);
9131 outs() << " fs " << format("0x%08" PRIx32, cpu32.fs);
9132 outs() << " gs " << format("0x%08" PRIx32, cpu32.gs) << "\n";
9133}
9134
Kevin Enderby48ef5342014-12-23 22:56:39 +00009135static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
9136 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
9137 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
9138 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
9139 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
9140 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
9141 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
9142 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
9143 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
9144 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
9145 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
9146 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
9147 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
9148 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
9149 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
9150 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
9151 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
9152 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
9153 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
9154 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
9155 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
9156 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
9157}
9158
Kevin Enderby227df342014-12-23 23:43:59 +00009159static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009160 uint32_t f;
9161 outs() << "\t mmst_reg ";
9162 for (f = 0; f < 10; f++)
9163 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
9164 outs() << "\n";
9165 outs() << "\t mmst_rsrv ";
9166 for (f = 0; f < 6; f++)
9167 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
9168 outs() << "\n";
9169}
9170
Kevin Enderbyaefb0032014-12-24 00:16:51 +00009171static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009172 uint32_t f;
9173 outs() << "\t xmm_reg ";
9174 for (f = 0; f < 16; f++)
9175 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
9176 outs() << "\n";
9177}
9178
9179static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
9180 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
9181 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
9182 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
9183 outs() << " denorm " << fpu.fpu_fcw.denorm;
9184 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
9185 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
9186 outs() << " undfl " << fpu.fpu_fcw.undfl;
9187 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
9188 outs() << "\t\t pc ";
9189 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
9190 outs() << "FP_PREC_24B ";
9191 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
9192 outs() << "FP_PREC_53B ";
9193 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
9194 outs() << "FP_PREC_64B ";
9195 else
9196 outs() << fpu.fpu_fcw.pc << " ";
9197 outs() << "rc ";
9198 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
9199 outs() << "FP_RND_NEAR ";
9200 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
9201 outs() << "FP_RND_DOWN ";
9202 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
9203 outs() << "FP_RND_UP ";
9204 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009205 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009206 outs() << "\n";
9207 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
9208 outs() << " denorm " << fpu.fpu_fsw.denorm;
9209 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
9210 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
9211 outs() << " undfl " << fpu.fpu_fsw.undfl;
9212 outs() << " precis " << fpu.fpu_fsw.precis;
9213 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
9214 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
9215 outs() << " c0 " << fpu.fpu_fsw.c0;
9216 outs() << " c1 " << fpu.fpu_fsw.c1;
9217 outs() << " c2 " << fpu.fpu_fsw.c2;
9218 outs() << " tos " << fpu.fpu_fsw.tos;
9219 outs() << " c3 " << fpu.fpu_fsw.c3;
9220 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
9221 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
9222 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
9223 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
9224 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
9225 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
9226 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
9227 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
9228 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
9229 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
9230 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
9231 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
9232 outs() << "\n";
9233 outs() << "\t fpu_stmm0:\n";
9234 Print_mmst_reg(fpu.fpu_stmm0);
9235 outs() << "\t fpu_stmm1:\n";
9236 Print_mmst_reg(fpu.fpu_stmm1);
9237 outs() << "\t fpu_stmm2:\n";
9238 Print_mmst_reg(fpu.fpu_stmm2);
9239 outs() << "\t fpu_stmm3:\n";
9240 Print_mmst_reg(fpu.fpu_stmm3);
9241 outs() << "\t fpu_stmm4:\n";
9242 Print_mmst_reg(fpu.fpu_stmm4);
9243 outs() << "\t fpu_stmm5:\n";
9244 Print_mmst_reg(fpu.fpu_stmm5);
9245 outs() << "\t fpu_stmm6:\n";
9246 Print_mmst_reg(fpu.fpu_stmm6);
9247 outs() << "\t fpu_stmm7:\n";
9248 Print_mmst_reg(fpu.fpu_stmm7);
9249 outs() << "\t fpu_xmm0:\n";
9250 Print_xmm_reg(fpu.fpu_xmm0);
9251 outs() << "\t fpu_xmm1:\n";
9252 Print_xmm_reg(fpu.fpu_xmm1);
9253 outs() << "\t fpu_xmm2:\n";
9254 Print_xmm_reg(fpu.fpu_xmm2);
9255 outs() << "\t fpu_xmm3:\n";
9256 Print_xmm_reg(fpu.fpu_xmm3);
9257 outs() << "\t fpu_xmm4:\n";
9258 Print_xmm_reg(fpu.fpu_xmm4);
9259 outs() << "\t fpu_xmm5:\n";
9260 Print_xmm_reg(fpu.fpu_xmm5);
9261 outs() << "\t fpu_xmm6:\n";
9262 Print_xmm_reg(fpu.fpu_xmm6);
9263 outs() << "\t fpu_xmm7:\n";
9264 Print_xmm_reg(fpu.fpu_xmm7);
9265 outs() << "\t fpu_xmm8:\n";
9266 Print_xmm_reg(fpu.fpu_xmm8);
9267 outs() << "\t fpu_xmm9:\n";
9268 Print_xmm_reg(fpu.fpu_xmm9);
9269 outs() << "\t fpu_xmm10:\n";
9270 Print_xmm_reg(fpu.fpu_xmm10);
9271 outs() << "\t fpu_xmm11:\n";
9272 Print_xmm_reg(fpu.fpu_xmm11);
9273 outs() << "\t fpu_xmm12:\n";
9274 Print_xmm_reg(fpu.fpu_xmm12);
9275 outs() << "\t fpu_xmm13:\n";
9276 Print_xmm_reg(fpu.fpu_xmm13);
9277 outs() << "\t fpu_xmm14:\n";
9278 Print_xmm_reg(fpu.fpu_xmm14);
9279 outs() << "\t fpu_xmm15:\n";
9280 Print_xmm_reg(fpu.fpu_xmm15);
9281 outs() << "\t fpu_rsrv4:\n";
9282 for (uint32_t f = 0; f < 6; f++) {
9283 outs() << "\t ";
9284 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009285 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009286 outs() << "\n";
9287 }
9288 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
9289 outs() << "\n";
9290}
9291
9292static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
9293 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
9294 outs() << " err " << format("0x%08" PRIx32, exc64.err);
9295 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
9296}
9297
Kevin Enderby41c9c002016-10-21 18:22:35 +00009298static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
9299 outs() << "\t r0 " << format("0x%08" PRIx32, cpu32.r[0]);
9300 outs() << " r1 " << format("0x%08" PRIx32, cpu32.r[1]);
9301 outs() << " r2 " << format("0x%08" PRIx32, cpu32.r[2]);
9302 outs() << " r3 " << format("0x%08" PRIx32, cpu32.r[3]) << "\n";
9303 outs() << "\t r4 " << format("0x%08" PRIx32, cpu32.r[4]);
9304 outs() << " r5 " << format("0x%08" PRIx32, cpu32.r[5]);
9305 outs() << " r6 " << format("0x%08" PRIx32, cpu32.r[6]);
9306 outs() << " r7 " << format("0x%08" PRIx32, cpu32.r[7]) << "\n";
9307 outs() << "\t r8 " << format("0x%08" PRIx32, cpu32.r[8]);
9308 outs() << " r9 " << format("0x%08" PRIx32, cpu32.r[9]);
9309 outs() << " r10 " << format("0x%08" PRIx32, cpu32.r[10]);
9310 outs() << " r11 " << format("0x%08" PRIx32, cpu32.r[11]) << "\n";
9311 outs() << "\t r12 " << format("0x%08" PRIx32, cpu32.r[12]);
9312 outs() << " sp " << format("0x%08" PRIx32, cpu32.sp);
9313 outs() << " lr " << format("0x%08" PRIx32, cpu32.lr);
9314 outs() << " pc " << format("0x%08" PRIx32, cpu32.pc) << "\n";
9315 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n";
9316}
9317
Kevin Enderby7747cb52016-11-03 20:51:28 +00009318static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
9319 outs() << "\t x0 " << format("0x%016" PRIx64, cpu64.x[0]);
9320 outs() << " x1 " << format("0x%016" PRIx64, cpu64.x[1]);
9321 outs() << " x2 " << format("0x%016" PRIx64, cpu64.x[2]) << "\n";
9322 outs() << "\t x3 " << format("0x%016" PRIx64, cpu64.x[3]);
9323 outs() << " x4 " << format("0x%016" PRIx64, cpu64.x[4]);
9324 outs() << " x5 " << format("0x%016" PRIx64, cpu64.x[5]) << "\n";
9325 outs() << "\t x6 " << format("0x%016" PRIx64, cpu64.x[6]);
9326 outs() << " x7 " << format("0x%016" PRIx64, cpu64.x[7]);
9327 outs() << " x8 " << format("0x%016" PRIx64, cpu64.x[8]) << "\n";
9328 outs() << "\t x9 " << format("0x%016" PRIx64, cpu64.x[9]);
9329 outs() << " x10 " << format("0x%016" PRIx64, cpu64.x[10]);
9330 outs() << " x11 " << format("0x%016" PRIx64, cpu64.x[11]) << "\n";
9331 outs() << "\t x12 " << format("0x%016" PRIx64, cpu64.x[12]);
9332 outs() << " x13 " << format("0x%016" PRIx64, cpu64.x[13]);
9333 outs() << " x14 " << format("0x%016" PRIx64, cpu64.x[14]) << "\n";
9334 outs() << "\t x15 " << format("0x%016" PRIx64, cpu64.x[15]);
9335 outs() << " x16 " << format("0x%016" PRIx64, cpu64.x[16]);
9336 outs() << " x17 " << format("0x%016" PRIx64, cpu64.x[17]) << "\n";
9337 outs() << "\t x18 " << format("0x%016" PRIx64, cpu64.x[18]);
9338 outs() << " x19 " << format("0x%016" PRIx64, cpu64.x[19]);
9339 outs() << " x20 " << format("0x%016" PRIx64, cpu64.x[20]) << "\n";
9340 outs() << "\t x21 " << format("0x%016" PRIx64, cpu64.x[21]);
9341 outs() << " x22 " << format("0x%016" PRIx64, cpu64.x[22]);
9342 outs() << " x23 " << format("0x%016" PRIx64, cpu64.x[23]) << "\n";
9343 outs() << "\t x24 " << format("0x%016" PRIx64, cpu64.x[24]);
9344 outs() << " x25 " << format("0x%016" PRIx64, cpu64.x[25]);
9345 outs() << " x26 " << format("0x%016" PRIx64, cpu64.x[26]) << "\n";
9346 outs() << "\t x27 " << format("0x%016" PRIx64, cpu64.x[27]);
9347 outs() << " x28 " << format("0x%016" PRIx64, cpu64.x[28]);
9348 outs() << " fp " << format("0x%016" PRIx64, cpu64.fp) << "\n";
9349 outs() << "\t lr " << format("0x%016" PRIx64, cpu64.lr);
9350 outs() << " sp " << format("0x%016" PRIx64, cpu64.sp);
9351 outs() << " pc " << format("0x%016" PRIx64, cpu64.pc) << "\n";
9352 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu64.cpsr) << "\n";
9353}
9354
Kevin Enderby48ef5342014-12-23 22:56:39 +00009355static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
9356 bool isLittleEndian, uint32_t cputype) {
9357 if (t.cmd == MachO::LC_THREAD)
9358 outs() << " cmd LC_THREAD\n";
9359 else if (t.cmd == MachO::LC_UNIXTHREAD)
9360 outs() << " cmd LC_UNIXTHREAD\n";
9361 else
9362 outs() << " cmd " << t.cmd << " (unknown)\n";
9363 outs() << " cmdsize " << t.cmdsize;
9364 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
9365 outs() << " Incorrect size\n";
9366 else
9367 outs() << "\n";
9368
9369 const char *begin = Ptr + sizeof(struct MachO::thread_command);
9370 const char *end = Ptr + t.cmdsize;
9371 uint32_t flavor, count, left;
Kevin Enderbyc3a035d2017-01-23 21:13:29 +00009372 if (cputype == MachO::CPU_TYPE_I386) {
9373 while (begin < end) {
9374 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9375 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9376 begin += sizeof(uint32_t);
9377 } else {
9378 flavor = 0;
9379 begin = end;
9380 }
9381 if (isLittleEndian != sys::IsLittleEndianHost)
9382 sys::swapByteOrder(flavor);
9383 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9384 memcpy((char *)&count, begin, sizeof(uint32_t));
9385 begin += sizeof(uint32_t);
9386 } else {
9387 count = 0;
9388 begin = end;
9389 }
9390 if (isLittleEndian != sys::IsLittleEndianHost)
9391 sys::swapByteOrder(count);
9392 if (flavor == MachO::x86_THREAD_STATE32) {
9393 outs() << " flavor i386_THREAD_STATE\n";
9394 if (count == MachO::x86_THREAD_STATE32_COUNT)
9395 outs() << " count i386_THREAD_STATE_COUNT\n";
9396 else
9397 outs() << " count " << count
9398 << " (not x86_THREAD_STATE32_COUNT)\n";
9399 MachO::x86_thread_state32_t cpu32;
9400 left = end - begin;
9401 if (left >= sizeof(MachO::x86_thread_state32_t)) {
9402 memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t));
9403 begin += sizeof(MachO::x86_thread_state32_t);
9404 } else {
9405 memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t));
9406 memcpy(&cpu32, begin, left);
9407 begin += left;
9408 }
9409 if (isLittleEndian != sys::IsLittleEndianHost)
9410 swapStruct(cpu32);
9411 Print_x86_thread_state32_t(cpu32);
9412 } else if (flavor == MachO::x86_THREAD_STATE) {
9413 outs() << " flavor x86_THREAD_STATE\n";
9414 if (count == MachO::x86_THREAD_STATE_COUNT)
9415 outs() << " count x86_THREAD_STATE_COUNT\n";
9416 else
9417 outs() << " count " << count
9418 << " (not x86_THREAD_STATE_COUNT)\n";
9419 struct MachO::x86_thread_state_t ts;
9420 left = end - begin;
9421 if (left >= sizeof(MachO::x86_thread_state_t)) {
9422 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9423 begin += sizeof(MachO::x86_thread_state_t);
9424 } else {
9425 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9426 memcpy(&ts, begin, left);
9427 begin += left;
9428 }
9429 if (isLittleEndian != sys::IsLittleEndianHost)
9430 swapStruct(ts);
9431 if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
9432 outs() << "\t tsh.flavor x86_THREAD_STATE32 ";
9433 if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
9434 outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
9435 else
9436 outs() << "tsh.count " << ts.tsh.count
9437 << " (not x86_THREAD_STATE32_COUNT\n";
9438 Print_x86_thread_state32_t(ts.uts.ts32);
9439 } else {
9440 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9441 << ts.tsh.count << "\n";
9442 }
9443 } else {
9444 outs() << " flavor " << flavor << " (unknown)\n";
9445 outs() << " count " << count << "\n";
9446 outs() << " state (unknown)\n";
9447 begin += count * sizeof(uint32_t);
9448 }
9449 }
9450 } else if (cputype == MachO::CPU_TYPE_X86_64) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009451 while (begin < end) {
9452 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9453 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9454 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009455 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009456 flavor = 0;
9457 begin = end;
9458 }
9459 if (isLittleEndian != sys::IsLittleEndianHost)
9460 sys::swapByteOrder(flavor);
9461 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9462 memcpy((char *)&count, begin, sizeof(uint32_t));
9463 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009464 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009465 count = 0;
9466 begin = end;
9467 }
9468 if (isLittleEndian != sys::IsLittleEndianHost)
9469 sys::swapByteOrder(count);
9470 if (flavor == MachO::x86_THREAD_STATE64) {
9471 outs() << " flavor x86_THREAD_STATE64\n";
9472 if (count == MachO::x86_THREAD_STATE64_COUNT)
9473 outs() << " count x86_THREAD_STATE64_COUNT\n";
9474 else
9475 outs() << " count " << count
9476 << " (not x86_THREAD_STATE64_COUNT)\n";
9477 MachO::x86_thread_state64_t cpu64;
9478 left = end - begin;
9479 if (left >= sizeof(MachO::x86_thread_state64_t)) {
9480 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
9481 begin += sizeof(MachO::x86_thread_state64_t);
9482 } else {
9483 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
9484 memcpy(&cpu64, begin, left);
9485 begin += left;
9486 }
9487 if (isLittleEndian != sys::IsLittleEndianHost)
9488 swapStruct(cpu64);
9489 Print_x86_thread_state64_t(cpu64);
9490 } else if (flavor == MachO::x86_THREAD_STATE) {
9491 outs() << " flavor x86_THREAD_STATE\n";
9492 if (count == MachO::x86_THREAD_STATE_COUNT)
9493 outs() << " count x86_THREAD_STATE_COUNT\n";
9494 else
9495 outs() << " count " << count
9496 << " (not x86_THREAD_STATE_COUNT)\n";
9497 struct MachO::x86_thread_state_t ts;
9498 left = end - begin;
9499 if (left >= sizeof(MachO::x86_thread_state_t)) {
9500 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9501 begin += sizeof(MachO::x86_thread_state_t);
9502 } else {
9503 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9504 memcpy(&ts, begin, left);
9505 begin += left;
9506 }
9507 if (isLittleEndian != sys::IsLittleEndianHost)
9508 swapStruct(ts);
9509 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
9510 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
9511 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
9512 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
9513 else
9514 outs() << "tsh.count " << ts.tsh.count
9515 << " (not x86_THREAD_STATE64_COUNT\n";
9516 Print_x86_thread_state64_t(ts.uts.ts64);
9517 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009518 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9519 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009520 }
9521 } else if (flavor == MachO::x86_FLOAT_STATE) {
9522 outs() << " flavor x86_FLOAT_STATE\n";
9523 if (count == MachO::x86_FLOAT_STATE_COUNT)
9524 outs() << " count x86_FLOAT_STATE_COUNT\n";
9525 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009526 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009527 struct MachO::x86_float_state_t fs;
9528 left = end - begin;
9529 if (left >= sizeof(MachO::x86_float_state_t)) {
9530 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
9531 begin += sizeof(MachO::x86_float_state_t);
9532 } else {
9533 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
9534 memcpy(&fs, begin, left);
9535 begin += left;
9536 }
9537 if (isLittleEndian != sys::IsLittleEndianHost)
9538 swapStruct(fs);
9539 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
9540 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009541 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00009542 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
9543 else
9544 outs() << "fsh.count " << fs.fsh.count
9545 << " (not x86_FLOAT_STATE64_COUNT\n";
9546 Print_x86_float_state_t(fs.ufs.fs64);
9547 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009548 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
9549 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009550 }
9551 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
9552 outs() << " flavor x86_EXCEPTION_STATE\n";
9553 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
9554 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
9555 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009556 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00009557 << " (not x86_EXCEPTION_STATE_COUNT)\n";
9558 struct MachO::x86_exception_state_t es;
9559 left = end - begin;
9560 if (left >= sizeof(MachO::x86_exception_state_t)) {
9561 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
9562 begin += sizeof(MachO::x86_exception_state_t);
9563 } else {
9564 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
9565 memcpy(&es, begin, left);
9566 begin += left;
9567 }
9568 if (isLittleEndian != sys::IsLittleEndianHost)
9569 swapStruct(es);
9570 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
9571 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009572 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00009573 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
9574 else
9575 outs() << "\t esh.count " << es.esh.count
9576 << " (not x86_EXCEPTION_STATE64_COUNT\n";
9577 Print_x86_exception_state_t(es.ues.es64);
9578 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009579 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
9580 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009581 }
Kevin Enderby299cd892018-03-08 23:10:38 +00009582 } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
9583 outs() << " flavor x86_EXCEPTION_STATE64\n";
9584 if (count == MachO::x86_EXCEPTION_STATE64_COUNT)
9585 outs() << " count x86_EXCEPTION_STATE64_COUNT\n";
9586 else
9587 outs() << " count " << count
9588 << " (not x86_EXCEPTION_STATE64_COUNT)\n";
9589 struct MachO::x86_exception_state64_t es64;
9590 left = end - begin;
9591 if (left >= sizeof(MachO::x86_exception_state64_t)) {
9592 memcpy(&es64, begin, sizeof(MachO::x86_exception_state64_t));
9593 begin += sizeof(MachO::x86_exception_state64_t);
9594 } else {
9595 memset(&es64, '\0', sizeof(MachO::x86_exception_state64_t));
9596 memcpy(&es64, begin, left);
9597 begin += left;
9598 }
9599 if (isLittleEndian != sys::IsLittleEndianHost)
9600 swapStruct(es64);
9601 Print_x86_exception_state_t(es64);
Kevin Enderby48ef5342014-12-23 22:56:39 +00009602 } else {
9603 outs() << " flavor " << flavor << " (unknown)\n";
9604 outs() << " count " << count << "\n";
9605 outs() << " state (unknown)\n";
9606 begin += count * sizeof(uint32_t);
9607 }
9608 }
Kevin Enderby41c9c002016-10-21 18:22:35 +00009609 } else if (cputype == MachO::CPU_TYPE_ARM) {
9610 while (begin < end) {
9611 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9612 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9613 begin += sizeof(uint32_t);
9614 } else {
9615 flavor = 0;
9616 begin = end;
9617 }
9618 if (isLittleEndian != sys::IsLittleEndianHost)
9619 sys::swapByteOrder(flavor);
9620 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9621 memcpy((char *)&count, begin, sizeof(uint32_t));
9622 begin += sizeof(uint32_t);
9623 } else {
9624 count = 0;
9625 begin = end;
9626 }
9627 if (isLittleEndian != sys::IsLittleEndianHost)
9628 sys::swapByteOrder(count);
9629 if (flavor == MachO::ARM_THREAD_STATE) {
9630 outs() << " flavor ARM_THREAD_STATE\n";
9631 if (count == MachO::ARM_THREAD_STATE_COUNT)
9632 outs() << " count ARM_THREAD_STATE_COUNT\n";
9633 else
9634 outs() << " count " << count
9635 << " (not ARM_THREAD_STATE_COUNT)\n";
9636 MachO::arm_thread_state32_t cpu32;
9637 left = end - begin;
9638 if (left >= sizeof(MachO::arm_thread_state32_t)) {
9639 memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
9640 begin += sizeof(MachO::arm_thread_state32_t);
9641 } else {
9642 memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
9643 memcpy(&cpu32, begin, left);
9644 begin += left;
9645 }
9646 if (isLittleEndian != sys::IsLittleEndianHost)
9647 swapStruct(cpu32);
9648 Print_arm_thread_state32_t(cpu32);
9649 } else {
9650 outs() << " flavor " << flavor << " (unknown)\n";
9651 outs() << " count " << count << "\n";
9652 outs() << " state (unknown)\n";
9653 begin += count * sizeof(uint32_t);
9654 }
9655 }
Kevin Enderby7747cb52016-11-03 20:51:28 +00009656 } else if (cputype == MachO::CPU_TYPE_ARM64) {
9657 while (begin < end) {
9658 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9659 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9660 begin += sizeof(uint32_t);
9661 } else {
9662 flavor = 0;
9663 begin = end;
9664 }
9665 if (isLittleEndian != sys::IsLittleEndianHost)
9666 sys::swapByteOrder(flavor);
9667 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9668 memcpy((char *)&count, begin, sizeof(uint32_t));
9669 begin += sizeof(uint32_t);
9670 } else {
9671 count = 0;
9672 begin = end;
9673 }
9674 if (isLittleEndian != sys::IsLittleEndianHost)
9675 sys::swapByteOrder(count);
9676 if (flavor == MachO::ARM_THREAD_STATE64) {
9677 outs() << " flavor ARM_THREAD_STATE64\n";
9678 if (count == MachO::ARM_THREAD_STATE64_COUNT)
9679 outs() << " count ARM_THREAD_STATE64_COUNT\n";
9680 else
9681 outs() << " count " << count
9682 << " (not ARM_THREAD_STATE64_COUNT)\n";
9683 MachO::arm_thread_state64_t cpu64;
9684 left = end - begin;
9685 if (left >= sizeof(MachO::arm_thread_state64_t)) {
9686 memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
9687 begin += sizeof(MachO::arm_thread_state64_t);
9688 } else {
9689 memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
9690 memcpy(&cpu64, begin, left);
9691 begin += left;
9692 }
9693 if (isLittleEndian != sys::IsLittleEndianHost)
9694 swapStruct(cpu64);
9695 Print_arm_thread_state64_t(cpu64);
9696 } else {
9697 outs() << " flavor " << flavor << " (unknown)\n";
9698 outs() << " count " << count << "\n";
9699 outs() << " state (unknown)\n";
9700 begin += count * sizeof(uint32_t);
9701 }
9702 }
Kevin Enderby48ef5342014-12-23 22:56:39 +00009703 } else {
9704 while (begin < end) {
9705 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9706 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9707 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009708 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009709 flavor = 0;
9710 begin = end;
9711 }
9712 if (isLittleEndian != sys::IsLittleEndianHost)
9713 sys::swapByteOrder(flavor);
9714 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9715 memcpy((char *)&count, begin, sizeof(uint32_t));
9716 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009717 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009718 count = 0;
9719 begin = end;
9720 }
9721 if (isLittleEndian != sys::IsLittleEndianHost)
9722 sys::swapByteOrder(count);
9723 outs() << " flavor " << flavor << "\n";
9724 outs() << " count " << count << "\n";
9725 outs() << " state (Unknown cputype/cpusubtype)\n";
9726 begin += count * sizeof(uint32_t);
9727 }
9728 }
9729}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009730
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009731static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
9732 if (dl.cmd == MachO::LC_ID_DYLIB)
9733 outs() << " cmd LC_ID_DYLIB\n";
9734 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
9735 outs() << " cmd LC_LOAD_DYLIB\n";
9736 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
9737 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
9738 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
9739 outs() << " cmd LC_REEXPORT_DYLIB\n";
9740 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
9741 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
9742 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
9743 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
9744 else
9745 outs() << " cmd " << dl.cmd << " (unknown)\n";
9746 outs() << " cmdsize " << dl.cmdsize;
9747 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
9748 outs() << " Incorrect size\n";
9749 else
9750 outs() << "\n";
9751 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009752 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009753 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
9754 } else {
9755 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
9756 }
9757 outs() << " time stamp " << dl.dylib.timestamp << " ";
9758 time_t t = dl.dylib.timestamp;
9759 outs() << ctime(&t);
9760 outs() << " current version ";
9761 if (dl.dylib.current_version == 0xffffffff)
9762 outs() << "n/a\n";
9763 else
9764 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
9765 << ((dl.dylib.current_version >> 8) & 0xff) << "."
9766 << (dl.dylib.current_version & 0xff) << "\n";
9767 outs() << "compatibility version ";
9768 if (dl.dylib.compatibility_version == 0xffffffff)
9769 outs() << "n/a\n";
9770 else
9771 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
9772 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
9773 << (dl.dylib.compatibility_version & 0xff) << "\n";
9774}
9775
9776static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
9777 uint32_t object_size) {
9778 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
Kevin Enderby1be37a32016-04-28 21:07:20 +00009779 outs() << " cmd LC_CODE_SIGNATURE\n";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009780 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
9781 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
9782 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
9783 outs() << " cmd LC_FUNCTION_STARTS\n";
9784 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
9785 outs() << " cmd LC_DATA_IN_CODE\n";
9786 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
9787 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
9788 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
9789 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
9790 else
9791 outs() << " cmd " << ld.cmd << " (?)\n";
9792 outs() << " cmdsize " << ld.cmdsize;
9793 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
9794 outs() << " Incorrect size\n";
9795 else
9796 outs() << "\n";
9797 outs() << " dataoff " << ld.dataoff;
9798 if (ld.dataoff > object_size)
9799 outs() << " (past end of file)\n";
9800 else
9801 outs() << "\n";
9802 outs() << " datasize " << ld.datasize;
9803 uint64_t big_size = ld.dataoff;
9804 big_size += ld.datasize;
9805 if (big_size > object_size)
9806 outs() << " (past end of file)\n";
9807 else
9808 outs() << "\n";
9809}
9810
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009811static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
9812 uint32_t cputype, bool verbose) {
Kevin Enderby956366c2014-08-29 22:30:52 +00009813 StringRef Buf = Obj->getData();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009814 unsigned Index = 0;
9815 for (const auto &Command : Obj->load_commands()) {
9816 outs() << "Load command " << Index++ << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00009817 if (Command.C.cmd == MachO::LC_SEGMENT) {
9818 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
9819 const char *sg_segname = SLC.segname;
9820 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
9821 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
9822 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
9823 verbose);
9824 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00009825 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00009826 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
9827 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
9828 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
9829 }
9830 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
9831 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
9832 const char *sg_segname = SLC_64.segname;
9833 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
9834 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
9835 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
9836 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
9837 for (unsigned j = 0; j < SLC_64.nsects; j++) {
9838 MachO::section_64 S_64 = Obj->getSection64(Command, j);
9839 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
9840 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
9841 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
9842 sg_segname, filetype, Buf.size(), verbose);
9843 }
9844 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
9845 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00009846 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009847 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
9848 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
9849 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00009850 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
9851 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009852 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
9853 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
9854 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
9855 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
9856 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
9857 Command.C.cmd == MachO::LC_ID_DYLINKER ||
9858 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
9859 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
9860 PrintDyldLoadCommand(Dyld, Command.Ptr);
9861 } else if (Command.C.cmd == MachO::LC_UUID) {
9862 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
9863 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00009864 } else if (Command.C.cmd == MachO::LC_RPATH) {
9865 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
9866 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00009867 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
Tim Northoverbfbfb122015-11-02 21:26:58 +00009868 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
9869 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
9870 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009871 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
9872 PrintVersionMinLoadCommand(Vd);
Kevin Enderbya4579c42017-01-19 17:36:31 +00009873 } else if (Command.C.cmd == MachO::LC_NOTE) {
9874 MachO::note_command Nt = Obj->getNoteLoadCommand(Command);
9875 PrintNoteLoadCommand(Nt);
Steven Wu5b54a422017-01-23 20:07:55 +00009876 } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
9877 MachO::build_version_command Bv =
9878 Obj->getBuildVersionLoadCommand(Command);
9879 PrintBuildVersionLoadCommand(Obj, Bv);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009880 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
9881 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
9882 PrintSourceVersionCommand(Sd);
9883 } else if (Command.C.cmd == MachO::LC_MAIN) {
9884 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
9885 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009886 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009887 MachO::encryption_info_command Ei =
9888 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009889 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00009890 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009891 MachO::encryption_info_command_64 Ei =
9892 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00009893 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009894 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009895 MachO::linker_option_command Lo =
9896 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009897 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00009898 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
9899 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
9900 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00009901 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
9902 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
9903 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009904 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
9905 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
9906 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00009907 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
9908 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
9909 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00009910 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
9911 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
9912 PrintRoutinesCommand(Rc);
9913 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
9914 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
9915 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00009916 } else if (Command.C.cmd == MachO::LC_THREAD ||
9917 Command.C.cmd == MachO::LC_UNIXTHREAD) {
9918 MachO::thread_command Tc = Obj->getThreadCommand(Command);
9919 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00009920 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
9921 Command.C.cmd == MachO::LC_ID_DYLIB ||
9922 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
9923 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
9924 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
9925 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009926 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
9927 PrintDylibCommand(Dl, Command.Ptr);
9928 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
9929 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
9930 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
9931 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
9932 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
9933 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
9934 MachO::linkedit_data_command Ld =
9935 Obj->getLinkeditDataLoadCommand(Command);
9936 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009937 } else {
9938 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
9939 << ")\n";
9940 outs() << " cmdsize " << Command.C.cmdsize << "\n";
9941 // TODO: get and print the raw bytes of the load command.
9942 }
9943 // TODO: print all the other kinds of load commands.
Kevin Enderby956366c2014-08-29 22:30:52 +00009944 }
9945}
9946
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009947static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009948 if (Obj->is64Bit()) {
9949 MachO::mach_header_64 H_64;
9950 H_64 = Obj->getHeader64();
9951 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
9952 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
9953 } else {
9954 MachO::mach_header H;
9955 H = Obj->getHeader();
9956 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
9957 H.sizeofcmds, H.flags, verbose);
9958 }
9959}
9960
9961void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
9962 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009963 PrintMachHeader(file, !NonVerbose);
9964}
9965
9966void llvm::printMachOLoadCommands(const object::ObjectFile *Obj) {
9967 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00009968 uint32_t filetype = 0;
9969 uint32_t cputype = 0;
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009970 if (file->is64Bit()) {
9971 MachO::mach_header_64 H_64;
9972 H_64 = file->getHeader64();
9973 filetype = H_64.filetype;
9974 cputype = H_64.cputype;
9975 } else {
9976 MachO::mach_header H;
9977 H = file->getHeader();
9978 filetype = H.filetype;
9979 cputype = H.cputype;
9980 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009981 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009982}
Nick Kledzikd04bc352014-08-30 00:20:14 +00009983
9984//===----------------------------------------------------------------------===//
9985// export trie dumping
9986//===----------------------------------------------------------------------===//
9987
9988void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Kevin Enderby0d5ec112017-06-19 21:23:07 +00009989 uint64_t BaseSegmentAddress = 0;
9990 for (const auto &Command : Obj->load_commands()) {
9991 if (Command.C.cmd == MachO::LC_SEGMENT) {
9992 MachO::segment_command Seg = Obj->getSegmentLoadCommand(Command);
9993 if (Seg.fileoff == 0 && Seg.filesize != 0) {
9994 BaseSegmentAddress = Seg.vmaddr;
9995 break;
9996 }
9997 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
9998 MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(Command);
9999 if (Seg.fileoff == 0 && Seg.filesize != 0) {
10000 BaseSegmentAddress = Seg.vmaddr;
10001 break;
10002 }
10003 }
10004 }
Kevin Enderby3e95bd22017-07-20 23:08:41 +000010005 Error Err = Error::success();
Alexander Shaposhnikove5740342017-07-29 00:30:45 +000010006 for (const llvm::object::ExportEntry &Entry : Obj->exports(Err)) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010007 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +000010008 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
10009 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
10010 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10011 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
10012 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10013 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
10014 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
10015 if (ReExport)
10016 outs() << "[re-export] ";
10017 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010018 outs() << format("0x%08llX ",
Kevin Enderby0d5ec112017-06-19 21:23:07 +000010019 Entry.address() + BaseSegmentAddress);
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010020 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +000010021 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010022 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +000010023 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +000010024 if (WeakDef) {
10025 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010026 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +000010027 }
10028 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010029 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +000010030 outs() << ", ";
10031 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010032 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +000010033 }
10034 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010035 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +000010036 outs() << ", ";
10037 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010038 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +000010039 }
10040 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010041 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +000010042 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010043 outs() << format("resolver=0x%08llX", Entry.other());
10044 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +000010045 }
10046 outs() << "]";
10047 }
10048 if (ReExport) {
10049 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010050 int Ordinal = Entry.other() - 1;
10051 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
10052 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +000010053 outs() << " (from " << DylibName << ")";
10054 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010055 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +000010056 }
10057 outs() << "\n";
10058 }
Kevin Enderby3e95bd22017-07-20 23:08:41 +000010059 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +000010060 report_error(std::move(Err), Obj->getFileName());
Nick Kledzikd04bc352014-08-30 00:20:14 +000010061}
Nick Kledzikac431442014-09-12 21:34:15 +000010062
Nick Kledzikac431442014-09-12 21:34:15 +000010063//===----------------------------------------------------------------------===//
10064// rebase table dumping
10065//===----------------------------------------------------------------------===//
10066
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010067void llvm::printMachORebaseTable(object::MachOObjectFile *Obj) {
Nick Kledzikac431442014-09-12 21:34:15 +000010068 outs() << "segment section address type\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010069 Error Err = Error::success();
10070 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
10071 StringRef SegmentName = Entry.segmentName();
10072 StringRef SectionName = Entry.sectionName();
10073 uint64_t Address = Entry.address();
Nick Kledzikac431442014-09-12 21:34:15 +000010074
10075 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010076 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
10077 SegmentName.str().c_str(), SectionName.str().c_str(),
10078 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +000010079 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010080 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +000010081 report_error(std::move(Err), Obj->getFileName());
Nick Kledzikac431442014-09-12 21:34:15 +000010082}
Nick Kledzik56ebef42014-09-16 01:41:51 +000010083
10084static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
10085 StringRef DylibName;
10086 switch (Ordinal) {
10087 case MachO::BIND_SPECIAL_DYLIB_SELF:
10088 return "this-image";
10089 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
10090 return "main-executable";
10091 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
10092 return "flat-namespace";
10093 default:
Nick Kledzikabd29872014-09-16 22:03:13 +000010094 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010095 std::error_code EC =
10096 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +000010097 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +000010098 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +000010099 return DylibName;
10100 }
Nick Kledzik56ebef42014-09-16 01:41:51 +000010101 }
Nick Kledzikabd29872014-09-16 22:03:13 +000010102 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +000010103}
10104
10105//===----------------------------------------------------------------------===//
10106// bind table dumping
10107//===----------------------------------------------------------------------===//
10108
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010109void llvm::printMachOBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik56ebef42014-09-16 01:41:51 +000010110 // Build table of sections so names can used in final output.
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010111 outs() << "segment section address type "
10112 "addend dylib symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010113 Error Err = Error::success();
10114 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010115 StringRef SegmentName = Entry.segmentName();
10116 StringRef SectionName = Entry.sectionName();
10117 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +000010118
10119 // Table lines look like:
10120 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010121 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +000010122 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010123 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010124 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010125 << left_justify(SectionName, 18) << " "
10126 << format_hex(Address, 10, true) << " "
10127 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010128 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010129 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010130 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +000010131 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010132 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +000010133 report_error(std::move(Err), Obj->getFileName());
Nick Kledzik56ebef42014-09-16 01:41:51 +000010134}
10135
10136//===----------------------------------------------------------------------===//
10137// lazy bind table dumping
10138//===----------------------------------------------------------------------===//
10139
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010140void llvm::printMachOLazyBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010141 outs() << "segment section address "
10142 "dylib symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010143 Error Err = Error::success();
10144 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010145 StringRef SegmentName = Entry.segmentName();
10146 StringRef SectionName = Entry.sectionName();
10147 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +000010148
10149 // Table lines look like:
10150 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010151 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010152 << left_justify(SectionName, 18) << " "
10153 << format_hex(Address, 10, true) << " "
10154 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +000010155 << Entry.symbolName() << "\n";
10156 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010157 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +000010158 report_error(std::move(Err), Obj->getFileName());
Nick Kledzik56ebef42014-09-16 01:41:51 +000010159}
10160
Nick Kledzik56ebef42014-09-16 01:41:51 +000010161//===----------------------------------------------------------------------===//
10162// weak bind table dumping
10163//===----------------------------------------------------------------------===//
10164
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010165void llvm::printMachOWeakBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010166 outs() << "segment section address "
10167 "type addend symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010168 Error Err = Error::success();
10169 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
Nick Kledzik56ebef42014-09-16 01:41:51 +000010170 // Strong symbols don't have a location to update.
10171 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010172 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +000010173 << Entry.symbolName() << "\n";
10174 continue;
10175 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010176 StringRef SegmentName = Entry.segmentName();
10177 StringRef SectionName = Entry.sectionName();
10178 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +000010179
10180 // Table lines look like:
10181 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010182 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010183 << left_justify(SectionName, 18) << " "
10184 << format_hex(Address, 10, true) << " "
10185 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010186 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
10187 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +000010188 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010189 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +000010190 report_error(std::move(Err), Obj->getFileName());
Nick Kledzik56ebef42014-09-16 01:41:51 +000010191}
10192
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010193// get_dyld_bind_info_symbolname() is used for disassembly and passed an
10194// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
10195// information for that address. If the address is found its binding symbol
10196// name is returned. If not nullptr is returned.
10197static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
10198 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +000010199 if (info->bindtable == nullptr) {
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +000010200 info->bindtable = llvm::make_unique<SymbolAddressMap>();
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010201 Error Err = Error::success();
10202 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010203 uint64_t Address = Entry.address();
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010204 StringRef name = Entry.symbolName();
10205 if (!name.empty())
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +000010206 (*info->bindtable)[Address] = name;
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010207 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010208 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +000010209 report_error(std::move(Err), info->O->getFileName());
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010210 }
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +000010211 auto name = info->bindtable->lookup(ReferenceValue);
10212 return !name.empty() ? name.data() : nullptr;
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010213}
Michael Trent1854ecc2017-12-05 07:50:00 +000010214