blob: 26f639a79d964302d3069087dd06e62c3fde4d32 [file] [log] [blame]
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001//===-- MachODump.cpp - Object file dumping utility for llvm --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the MachO-specific dumper for llvm-objdump.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm-objdump.h"
Kevin Enderby98c9acc2014-09-16 18:00:57 +000015#include "llvm-c/Disassembler.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000016#include "llvm/ADT/STLExtras.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000017#include "llvm/ADT/StringExtras.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000018#include "llvm/ADT/Triple.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000019#include "llvm/BinaryFormat/MachO.h"
Kevin Enderby04bf6932014-10-28 23:39:46 +000020#include "llvm/Config/config.h"
Zachary Turner6489d7b2015-04-23 17:37:47 +000021#include "llvm/DebugInfo/DIContext.h"
22#include "llvm/DebugInfo/DWARF/DWARFContext.h"
Rafael Espindolab940b662016-09-06 19:16:48 +000023#include "llvm/Demangle/Demangle.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000024#include "llvm/MC/MCAsmInfo.h"
Lang Hamesa1bc0f52014-04-15 04:40:56 +000025#include "llvm/MC/MCContext.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000026#include "llvm/MC/MCDisassembler/MCDisassembler.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000027#include "llvm/MC/MCInst.h"
28#include "llvm/MC/MCInstPrinter.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000029#include "llvm/MC/MCInstrDesc.h"
30#include "llvm/MC/MCInstrInfo.h"
Jim Grosbachfd93a592012-03-05 19:33:20 +000031#include "llvm/MC/MCRegisterInfo.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000032#include "llvm/MC/MCSubtargetInfo.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000033#include "llvm/Object/MachO.h"
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +000034#include "llvm/Object/MachOUniversal.h"
Rafael Espindola9b709252013-04-13 01:45:40 +000035#include "llvm/Support/Casting.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000036#include "llvm/Support/CommandLine.h"
37#include "llvm/Support/Debug.h"
Tim Northover4bd286a2014-08-01 13:07:19 +000038#include "llvm/Support/Endian.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000039#include "llvm/Support/Format.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000040#include "llvm/Support/FormattedStream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000041#include "llvm/Support/GraphWriter.h"
Kevin Enderby9a509442015-01-27 21:28:24 +000042#include "llvm/Support/LEB128.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000043#include "llvm/Support/MemoryBuffer.h"
44#include "llvm/Support/TargetRegistry.h"
45#include "llvm/Support/TargetSelect.h"
Kevin Enderby9873e2c2016-05-23 21:34:12 +000046#include "llvm/Support/ToolOutputFile.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>
Kevin Enderbyb28ed012014-10-29 21:28:24 +000062 UseDbg("g",
63 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 Enderby13023a12015-01-15 23:19:11 +000079 llvm::ArchiveHeaders("archive-headers",
80 cl::desc("Print archive headers for Mach-O archives "
81 "(requires -macho)"));
Kevin Enderby131d1772015-01-09 19:22:37 +000082
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +000083cl::opt<bool>
Kevin Enderby8972e482015-04-30 20:30:42 +000084 ArchiveMemberOffsets("archive-member-offsets",
85 cl::desc("Print the offset to each archive member for "
86 "Mach-O archives (requires -macho and "
87 "-archive-headers)"));
88
89cl::opt<bool>
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +000090 llvm::IndirectSymbols("indirect-symbols",
91 cl::desc("Print indirect symbol table for Mach-O "
92 "objects (requires -macho)"));
93
Kevin Enderby69fe98d2015-01-23 18:52:17 +000094cl::opt<bool>
95 llvm::DataInCode("data-in-code",
96 cl::desc("Print the data in code table for Mach-O objects "
97 "(requires -macho)"));
98
Kevin Enderby9a509442015-01-27 21:28:24 +000099cl::opt<bool>
100 llvm::LinkOptHints("link-opt-hints",
101 cl::desc("Print the linker optimization hints for "
102 "Mach-O objects (requires -macho)"));
103
Kevin Enderbycd66be52015-03-11 22:06:32 +0000104cl::opt<bool>
105 llvm::InfoPlist("info-plist",
106 cl::desc("Print the info plist section as strings for "
107 "Mach-O objects (requires -macho)"));
108
Kevin Enderbyf0640752015-03-13 17:56:32 +0000109cl::opt<bool>
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000110 llvm::DylibsUsed("dylibs-used",
111 cl::desc("Print the shared libraries used for linked "
112 "Mach-O files (requires -macho)"));
113
114cl::opt<bool>
115 llvm::DylibId("dylib-id",
116 cl::desc("Print the shared library's id for the dylib Mach-O "
117 "file (requires -macho)"));
118
119cl::opt<bool>
Kevin Enderbyf0640752015-03-13 17:56:32 +0000120 llvm::NonVerbose("non-verbose",
121 cl::desc("Print the info for Mach-O objects in "
122 "non-verbose or numeric form (requires -macho)"));
123
Kevin Enderby0fc11822015-04-01 20:57:01 +0000124cl::opt<bool>
125 llvm::ObjcMetaData("objc-meta-data",
126 cl::desc("Print the Objective-C runtime meta data for "
127 "Mach-O files (requires -macho)"));
128
Kevin Enderby6a221752015-03-17 17:10:57 +0000129cl::opt<std::string> llvm::DisSymName(
130 "dis-symname",
Saleem Abdulrasoolec6a7742016-09-08 23:17:34 +0000131 cl::desc("disassemble just this symbol's instructions (requires -macho)"));
Kevin Enderby6a221752015-03-17 17:10:57 +0000132
Kevin Enderby8e29ec92015-03-17 22:26:11 +0000133static cl::opt<bool> NoSymbolicOperands(
134 "no-symbolic-operands",
135 cl::desc("do not symbolic operands when disassembling (requires -macho)"));
136
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000137static cl::list<std::string>
138 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
139 cl::ZeroOrMore);
Hans Wennborgcc9deb42015-09-29 18:02:48 +0000140
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000141bool ArchAll = false;
142
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000143static std::string ThumbTripleName;
144
145static const Target *GetTarget(const MachOObjectFile *MachOObj,
146 const char **McpuDefault,
147 const Target **ThumbTarget) {
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000148 // Figure out the target triple.
Tim Northover9e8eb412016-04-22 23:21:13 +0000149 llvm::Triple TT(TripleName);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000150 if (TripleName.empty()) {
Tim Northover9e8eb412016-04-22 23:21:13 +0000151 TT = MachOObj->getArchTriple(McpuDefault);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000152 TripleName = TT.str();
Tim Northover9e8eb412016-04-22 23:21:13 +0000153 }
154
155 if (TT.getArch() == Triple::arm) {
156 // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
157 // that support ARM are also capable of Thumb mode.
158 llvm::Triple ThumbTriple = TT;
159 std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str();
160 ThumbTriple.setArchName(ThumbName);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000161 ThumbTripleName = ThumbTriple.str();
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000162 }
163
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000164 // Get the target specific parser.
165 std::string Error;
166 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000167 if (TheTarget && ThumbTripleName.empty())
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000168 return TheTarget;
169
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000170 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
171 if (*ThumbTarget)
172 return TheTarget;
173
174 errs() << "llvm-objdump: error: unable to get target for '";
175 if (!TheTarget)
176 errs() << TripleName;
177 else
178 errs() << ThumbTripleName;
179 errs() << "', see --version and --triple.\n";
Craig Toppere6cb63e2014-04-25 04:24:47 +0000180 return nullptr;
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000181}
182
Owen Andersond9243c42011-10-17 21:37:35 +0000183struct SymbolSorter {
184 bool operator()(const SymbolRef &A, const SymbolRef &B) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000185 Expected<SymbolRef::Type> ATypeOrErr = A.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000186 if (!ATypeOrErr)
187 report_error(A.getObject()->getFileName(), ATypeOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000188 SymbolRef::Type AType = *ATypeOrErr;
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000189 Expected<SymbolRef::Type> BTypeOrErr = B.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000190 if (!BTypeOrErr)
191 report_error(B.getObject()->getFileName(), BTypeOrErr.takeError());
Kevin Enderby74f58d42016-03-23 21:45:21 +0000192 SymbolRef::Type BType = *BTypeOrErr;
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000193 uint64_t AAddr = (AType != SymbolRef::ST_Function) ? 0 : A.getValue();
194 uint64_t BAddr = (BType != SymbolRef::ST_Function) ? 0 : B.getValue();
Owen Andersond9243c42011-10-17 21:37:35 +0000195 return AAddr < BAddr;
196 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000197};
198
Kevin Enderby273ae012013-06-06 17:20:50 +0000199// Types for the storted data in code table that is built before disassembly
200// and the predicate function to sort them.
201typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
202typedef std::vector<DiceTableEntry> DiceTable;
203typedef DiceTable::iterator dice_table_iterator;
204
Francis Ricci195a66f2017-10-06 15:54:20 +0000205#ifdef HAVE_LIBXAR
Francis Ricci6f942972017-10-06 15:33:28 +0000206namespace {
207struct ScopedXarFile {
208 xar_t xar;
Francis Ricci57d84522017-10-09 20:27:14 +0000209 ScopedXarFile(const char *filename, int32_t flags)
210 : xar(xar_open(filename, flags)) {}
Francis Ricci6f942972017-10-06 15:33:28 +0000211 ~ScopedXarFile() {
212 if (xar)
213 xar_close(xar);
214 }
215 ScopedXarFile(const ScopedXarFile &) = delete;
216 ScopedXarFile &operator=(const ScopedXarFile &) = delete;
217 operator xar_t() { return xar; }
218};
219
220struct ScopedXarIter {
221 xar_iter_t iter;
Francis Ricci57d84522017-10-09 20:27:14 +0000222 ScopedXarIter() : iter(xar_iter_new()) {}
Francis Ricci6f942972017-10-06 15:33:28 +0000223 ~ScopedXarIter() {
224 if (iter)
225 xar_iter_free(iter);
226 }
227 ScopedXarIter(const ScopedXarIter &) = delete;
228 ScopedXarIter &operator=(const ScopedXarIter &) = delete;
229 operator xar_iter_t() { return iter; }
230};
231} // namespace
Francis Ricci195a66f2017-10-06 15:54:20 +0000232#endif // defined(HAVE_LIBXAR)
Francis Ricci6f942972017-10-06 15:33:28 +0000233
Kevin Enderby930fdc72014-11-06 19:00:13 +0000234// This is used to search for a data in code table entry for the PC being
235// disassembled. The j parameter has the PC in j.first. A single data in code
236// table entry can cover many bytes for each of its Kind's. So if the offset,
237// aka the i.first value, of the data in code table entry plus its Length
238// covers the PC being searched for this will return true. If not it will
239// return false.
David Majnemerea9b8ee2014-11-04 08:41:48 +0000240static bool compareDiceTableEntries(const DiceTableEntry &i,
241 const DiceTableEntry &j) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000242 uint16_t Length;
243 i.second.getLength(Length);
244
245 return j.first >= i.first && j.first < i.first + Length;
Kevin Enderby273ae012013-06-06 17:20:50 +0000246}
247
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000248static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
Kevin Enderby930fdc72014-11-06 19:00:13 +0000249 unsigned short Kind) {
250 uint32_t Value, Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000251
252 switch (Kind) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000253 default:
Charles Davis8bdfafd2013-09-01 04:28:48 +0000254 case MachO::DICE_KIND_DATA:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000255 if (Length >= 4) {
256 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000257 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000258 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000259 outs() << "\t.long " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000260 Size = 4;
261 } else if (Length >= 2) {
262 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000263 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000264 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000265 outs() << "\t.short " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000266 Size = 2;
267 } else {
268 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000269 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000270 Value = bytes[0];
271 outs() << "\t.byte " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000272 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000273 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000274 if (Kind == MachO::DICE_KIND_DATA)
275 outs() << "\t@ KIND_DATA\n";
276 else
277 outs() << "\t@ data in code kind = " << Kind << "\n";
Kevin Enderby273ae012013-06-06 17:20:50 +0000278 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000279 case MachO::DICE_KIND_JUMP_TABLE8:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000280 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000281 dumpBytes(makeArrayRef(bytes, 1), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000282 Value = bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000283 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
284 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000285 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000286 case MachO::DICE_KIND_JUMP_TABLE16:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000287 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000288 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000289 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000290 outs() << "\t.short " << format("%5u", Value & 0xffff)
291 << "\t@ KIND_JUMP_TABLE16\n";
292 Size = 2;
Kevin Enderby273ae012013-06-06 17:20:50 +0000293 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000294 case MachO::DICE_KIND_JUMP_TABLE32:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000295 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
296 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000297 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000298 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000299 outs() << "\t.long " << Value;
300 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
301 outs() << "\t@ KIND_JUMP_TABLE32\n";
302 else
303 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
304 Size = 4;
Kevin Enderby273ae012013-06-06 17:20:50 +0000305 break;
306 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000307 return Size;
Kevin Enderby273ae012013-06-06 17:20:50 +0000308}
309
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000310static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000311 std::vector<SectionRef> &Sections,
312 std::vector<SymbolRef> &Symbols,
313 SmallVectorImpl<uint64_t> &FoundFns,
314 uint64_t &BaseSegmentAddress) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000315 for (const SymbolRef &Symbol : MachOObj->symbols()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000316 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000317 if (!SymName)
318 report_error(MachOObj->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000319 if (!SymName->startswith("ltmp"))
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000320 Symbols.push_back(Symbol);
321 }
Owen Andersond9243c42011-10-17 21:37:35 +0000322
Alexey Samsonov48803e52014-03-13 14:37:36 +0000323 for (const SectionRef &Section : MachOObj->sections()) {
Owen Andersond9243c42011-10-17 21:37:35 +0000324 StringRef SectName;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000325 Section.getName(SectName);
326 Sections.push_back(Section);
Owen Andersond9243c42011-10-17 21:37:35 +0000327 }
328
Kevin Enderby273ae012013-06-06 17:20:50 +0000329 bool BaseSegmentAddressSet = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000330 for (const auto &Command : MachOObj->load_commands()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000331 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
Benjamin Kramer699128e2011-09-21 01:13:19 +0000332 // We found a function starts segment, parse the addresses for later
333 // consumption.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000334 MachO::linkedit_data_command LLC =
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000335 MachOObj->getLinkeditDataLoadCommand(Command);
Benjamin Kramer699128e2011-09-21 01:13:19 +0000336
Charles Davis8bdfafd2013-09-01 04:28:48 +0000337 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000338 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
339 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000340 StringRef SegName = SLC.segname;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000341 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
Kevin Enderby273ae012013-06-06 17:20:50 +0000342 BaseSegmentAddressSet = true;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000343 BaseSegmentAddress = SLC.vmaddr;
Kevin Enderby273ae012013-06-06 17:20:50 +0000344 }
345 }
Benjamin Kramer8a529dc2011-09-21 22:16:43 +0000346 }
Benjamin Kramer699128e2011-09-21 01:13:19 +0000347}
348
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000349static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
350 uint32_t n, uint32_t count,
351 uint32_t stride, uint64_t addr) {
352 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
353 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
354 if (n > nindirectsyms)
355 outs() << " (entries start past the end of the indirect symbol "
356 "table) (reserved1 field greater than the table size)";
357 else if (n + count > nindirectsyms)
358 outs() << " (entries extends past the end of the indirect symbol "
359 "table)";
360 outs() << "\n";
361 uint32_t cputype = O->getHeader().cputype;
362 if (cputype & MachO::CPU_ARCH_ABI64)
363 outs() << "address index";
364 else
365 outs() << "address index";
366 if (verbose)
367 outs() << " name\n";
368 else
369 outs() << "\n";
370 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
371 if (cputype & MachO::CPU_ARCH_ABI64)
372 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
373 else
Tim Northover43978372016-04-26 18:29:16 +0000374 outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " ";
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000375 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
376 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
377 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
378 outs() << "LOCAL\n";
379 continue;
380 }
381 if (indirect_symbol ==
382 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
383 outs() << "LOCAL ABSOLUTE\n";
384 continue;
385 }
386 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
387 outs() << "ABSOLUTE\n";
388 continue;
389 }
390 outs() << format("%5u ", indirect_symbol);
Kevin Enderbyf0640752015-03-13 17:56:32 +0000391 if (verbose) {
392 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
393 if (indirect_symbol < Symtab.nsyms) {
394 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
395 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000396 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000397 if (!SymName)
398 report_error(O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000399 outs() << *SymName;
Kevin Enderbyf0640752015-03-13 17:56:32 +0000400 } else {
401 outs() << "?";
402 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000403 }
404 outs() << "\n";
405 }
406}
407
408static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000409 for (const auto &Load : O->load_commands()) {
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000410 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
411 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
412 for (unsigned J = 0; J < Seg.nsects; ++J) {
413 MachO::section_64 Sec = O->getSection64(Load, J);
414 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
415 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
416 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
417 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
418 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
419 section_type == MachO::S_SYMBOL_STUBS) {
420 uint32_t stride;
421 if (section_type == MachO::S_SYMBOL_STUBS)
422 stride = Sec.reserved2;
423 else
424 stride = 8;
425 if (stride == 0) {
426 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
427 << Sec.sectname << ") "
428 << "(size of stubs in reserved2 field is zero)\n";
429 continue;
430 }
431 uint32_t count = Sec.size / stride;
432 outs() << "Indirect symbols for (" << Sec.segname << ","
433 << Sec.sectname << ") " << count << " entries";
434 uint32_t n = Sec.reserved1;
435 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
436 }
437 }
438 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
439 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
440 for (unsigned J = 0; J < Seg.nsects; ++J) {
441 MachO::section Sec = O->getSection(Load, J);
442 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
443 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
444 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
445 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
446 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
447 section_type == MachO::S_SYMBOL_STUBS) {
448 uint32_t stride;
449 if (section_type == MachO::S_SYMBOL_STUBS)
450 stride = Sec.reserved2;
451 else
452 stride = 4;
453 if (stride == 0) {
454 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
455 << Sec.sectname << ") "
456 << "(size of stubs in reserved2 field is zero)\n";
457 continue;
458 }
459 uint32_t count = Sec.size / stride;
460 outs() << "Indirect symbols for (" << Sec.segname << ","
461 << Sec.sectname << ") " << count << " entries";
462 uint32_t n = Sec.reserved1;
463 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
464 }
465 }
466 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000467 }
468}
469
Michael Trenta1703b12017-12-15 17:57:40 +0000470static void PrintRType(const uint64_t cputype, const unsigned r_type) {
471 static char const *generic_r_types[] = {
472 "VANILLA ", "PAIR ", "SECTDIF ", "PBLAPTR ", "LOCSDIF ", "TLV ",
473 " 6 (?) ", " 7 (?) ", " 8 (?) ", " 9 (?) ", " 10 (?) ", " 11 (?) ",
474 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
475 };
476 static char const *x86_64_r_types[] = {
477 "UNSIGND ", "SIGNED ", "BRANCH ", "GOT_LD ", "GOT ", "SUB ",
478 "SIGNED1 ", "SIGNED2 ", "SIGNED4 ", "TLV ", " 10 (?) ", " 11 (?) ",
479 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
480 };
481 static char const *arm_r_types[] = {
482 "VANILLA ", "PAIR ", "SECTDIFF", "LOCSDIF ", "PBLAPTR ",
483 "BR24 ", "T_BR22 ", "T_BR32 ", "HALF ", "HALFDIF ",
484 " 10 (?) ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
485 };
486 static char const *arm64_r_types[] = {
487 "UNSIGND ", "SUB ", "BR26 ", "PAGE21 ", "PAGOF12 ",
488 "GOTLDP ", "GOTLDPOF", "PTRTGOT ", "TLVLDP ", "TLVLDPOF",
489 "ADDEND ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
490 };
491
492 if (r_type > 0xf){
493 outs() << format("%-7u", r_type) << " ";
494 return;
495 }
496 switch (cputype) {
497 case MachO::CPU_TYPE_I386:
498 outs() << generic_r_types[r_type];
499 break;
500 case MachO::CPU_TYPE_X86_64:
501 outs() << x86_64_r_types[r_type];
502 break;
503 case MachO::CPU_TYPE_ARM:
504 outs() << arm_r_types[r_type];
505 break;
506 case MachO::CPU_TYPE_ARM64:
507 outs() << arm64_r_types[r_type];
508 break;
509 default:
510 outs() << format("%-7u ", r_type);
511 }
512}
513
514static void PrintRLength(const uint64_t cputype, const unsigned r_type,
515 const unsigned r_length, const bool previous_arm_half){
516 if (cputype == MachO::CPU_TYPE_ARM &&
517 (r_type == llvm::MachO::ARM_RELOC_HALF ||
518 r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF ||
519 previous_arm_half == true)) {
520 if ((r_length & 0x1) == 0)
521 outs() << "lo/";
522 else
523 outs() << "hi/";
524 if ((r_length & 0x1) == 0)
525 outs() << "arm ";
526 else
527 outs() << "thm ";
528 } else {
529 switch (r_length) {
530 case 0:
531 outs() << "byte ";
532 break;
533 case 1:
534 outs() << "word ";
535 break;
536 case 2:
537 outs() << "long ";
538 break;
539 case 3:
540 if (cputype == MachO::CPU_TYPE_X86_64)
541 outs() << "quad ";
542 else
543 outs() << format("?(%2d) ", r_length);
544 break;
545 default:
546 outs() << format("?(%2d) ", r_length);
547 }
548 }
549}
550
551static void PrintRelocationEntries(const MachOObjectFile *O,
552 const relocation_iterator Begin,
553 const relocation_iterator End,
554 const uint64_t cputype,
555 const bool verbose) {
556 const MachO::symtab_command Symtab = O->getSymtabLoadCommand();
557 bool previous_arm_half = false;
558 bool previous_sectdiff = false;
559 uint32_t sectdiff_r_type = 0;
560
561 for (relocation_iterator Reloc = Begin; Reloc != End; ++Reloc) {
562 const DataRefImpl Rel = Reloc->getRawDataRefImpl();
563 const MachO::any_relocation_info RE = O->getRelocation(Rel);
564 const unsigned r_type = O->getAnyRelocationType(RE);
565 const bool r_scattered = O->isRelocationScattered(RE);
566 const unsigned r_pcrel = O->getAnyRelocationPCRel(RE);
567 const unsigned r_length = O->getAnyRelocationLength(RE);
568 const unsigned r_address = O->getAnyRelocationAddress(RE);
569 const bool r_extern = (r_scattered ? false :
570 O->getPlainRelocationExternal(RE));
571 const uint32_t r_value = (r_scattered ?
572 O->getScatteredRelocationValue(RE) : 0);
573 const unsigned r_symbolnum = (r_scattered ? 0 :
574 O->getPlainRelocationSymbolNum(RE));
575
576 if (r_scattered && cputype != MachO::CPU_TYPE_X86_64) {
577 if (verbose) {
578 // scattered: address
579 if ((cputype == MachO::CPU_TYPE_I386 &&
580 r_type == llvm::MachO::GENERIC_RELOC_PAIR) ||
581 (cputype == MachO::CPU_TYPE_ARM &&
582 r_type == llvm::MachO::ARM_RELOC_PAIR))
583 outs() << " ";
584 else
585 outs() << format("%08x ", (unsigned int)r_address);
586
587 // scattered: pcrel
588 if (r_pcrel)
589 outs() << "True ";
590 else
591 outs() << "False ";
592
593 // scattered: length
594 PrintRLength(cputype, r_type, r_length, previous_arm_half);
595
596 // scattered: extern & type
597 outs() << "n/a ";
598 PrintRType(cputype, r_type);
599
600 // scattered: scattered & value
601 outs() << format("True 0x%08x", (unsigned int)r_value);
602 if (previous_sectdiff == false) {
603 if ((cputype == MachO::CPU_TYPE_ARM &&
604 r_type == llvm::MachO::ARM_RELOC_PAIR))
605 outs() << format(" half = 0x%04x ", (unsigned int)r_address);
606 }
607 else if (cputype == MachO::CPU_TYPE_ARM &&
608 sectdiff_r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF)
609 outs() << format(" other_half = 0x%04x ", (unsigned int)r_address);
610 if ((cputype == MachO::CPU_TYPE_I386 &&
611 (r_type == llvm::MachO::GENERIC_RELOC_SECTDIFF ||
612 r_type == llvm::MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) ||
613 (cputype == MachO::CPU_TYPE_ARM &&
614 (sectdiff_r_type == llvm::MachO::ARM_RELOC_SECTDIFF ||
615 sectdiff_r_type == llvm::MachO::ARM_RELOC_LOCAL_SECTDIFF ||
616 sectdiff_r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF))) {
617 previous_sectdiff = true;
618 sectdiff_r_type = r_type;
619 }
620 else {
621 previous_sectdiff = false;
622 sectdiff_r_type = 0;
623 }
624 if (cputype == MachO::CPU_TYPE_ARM &&
625 (r_type == llvm::MachO::ARM_RELOC_HALF ||
626 r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF))
627 previous_arm_half = true;
628 else
629 previous_arm_half = false;
630 outs() << "\n";
631 }
632 else {
633 // scattered: address pcrel length extern type scattered value
634 outs() << format("%08x %1d %-2d n/a %-7d 1 0x%08x\n",
635 (unsigned int)r_address, r_pcrel, r_length, r_type,
636 (unsigned int)r_value);
637 }
638 }
639 else {
640 if (verbose) {
641 // plain: address
642 if (cputype == MachO::CPU_TYPE_ARM &&
643 r_type == llvm::MachO::ARM_RELOC_PAIR)
644 outs() << " ";
645 else
646 outs() << format("%08x ", (unsigned int)r_address);
647
648 // plain: pcrel
649 if (r_pcrel)
650 outs() << "True ";
651 else
652 outs() << "False ";
653
654 // plain: length
655 PrintRLength(cputype, r_type, r_length, previous_arm_half);
656
657 if (r_extern) {
658 // plain: extern & type & scattered
659 outs() << "True ";
660 PrintRType(cputype, r_type);
661 outs() << "False ";
662
663 // plain: symbolnum/value
664 if (r_symbolnum > Symtab.nsyms)
665 outs() << format("?(%d)\n", r_symbolnum);
666 else {
667 SymbolRef Symbol = *O->getSymbolByIndex(r_symbolnum);
668 Expected<StringRef> SymNameNext = Symbol.getName();
669 const char *name = NULL;
670 if (SymNameNext)
671 name = SymNameNext->data();
672 if (name == NULL)
673 outs() << format("?(%d)\n", r_symbolnum);
674 else
675 outs() << name << "\n";
676 }
677 }
678 else {
679 // plain: extern & type & scattered
680 outs() << "False ";
681 PrintRType(cputype, r_type);
682 outs() << "False ";
683
684 // plain: symbolnum/value
685 if (cputype == MachO::CPU_TYPE_ARM &&
686 r_type == llvm::MachO::ARM_RELOC_PAIR)
687 outs() << format("other_half = 0x%04x\n", (unsigned int)r_address);
688 else if (cputype == MachO::CPU_TYPE_ARM64 &&
689 r_type == llvm::MachO::ARM64_RELOC_ADDEND)
690 outs() << format("addend = 0x%06x\n", (unsigned int)r_symbolnum);
691 else {
692 outs() << format("%d ", r_symbolnum);
693 if (r_symbolnum == llvm::MachO::R_ABS)
694 outs() << "R_ABS\n";
695 else {
696 // in this case, r_symbolnum is actually a 1-based section number
697 uint32_t nsects = O->section_end()->getRawDataRefImpl().d.a;
698 if (r_symbolnum > 0 && r_symbolnum <= nsects) {
699 llvm::object::DataRefImpl DRI;
700 DRI.d.a = r_symbolnum-1;
701 StringRef SegName = O->getSectionFinalSegmentName(DRI);
702 StringRef SectName;
703 if (O->getSectionName(DRI, SectName))
704 outs() << "(?,?)\n";
705 else
706 outs() << "(" << SegName << "," << SectName << ")\n";
707 }
708 else {
709 outs() << "(?,?)\n";
710 }
711 }
712 }
713 }
714 if (cputype == MachO::CPU_TYPE_ARM &&
715 (r_type == llvm::MachO::ARM_RELOC_HALF ||
716 r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF))
717 previous_arm_half = true;
718 else
719 previous_arm_half = false;
720 }
721 else {
722 // plain: address pcrel length extern type scattered symbolnum/section
723 outs() << format("%08x %1d %-2d %1d %-7d 0 %d\n",
724 (unsigned int)r_address, r_pcrel, r_length, r_extern,
725 r_type, r_symbolnum);
726 }
727 }
728 }
729}
730
731static void PrintRelocations(const MachOObjectFile *O, const bool verbose) {
732 const uint64_t cputype = O->getHeader().cputype;
733 const MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
734 if (Dysymtab.nextrel != 0) {
735 outs() << "External relocation information " << Dysymtab.nextrel
736 << " entries";
737 outs() << "\naddress pcrel length extern type scattered "
738 "symbolnum/value\n";
739 PrintRelocationEntries(O, O->extrel_begin(), O->extrel_end(), cputype,
740 verbose);
741 }
742 if (Dysymtab.nlocrel != 0) {
743 outs() << format("Local relocation information %u entries",
744 Dysymtab.nlocrel);
745 outs() << "\naddress pcrel length extern type scattered "
746 "symbolnum/value\n";
747 PrintRelocationEntries(O, O->locrel_begin(), O->locrel_end(), cputype,
748 verbose);
749 }
750 for (const auto &Load : O->load_commands()) {
751 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
752 const MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
753 for (unsigned J = 0; J < Seg.nsects; ++J) {
754 const MachO::section_64 Sec = O->getSection64(Load, J);
755 if (Sec.nreloc != 0) {
756 DataRefImpl DRI;
757 DRI.d.a = J;
758 const StringRef SegName = O->getSectionFinalSegmentName(DRI);
759 StringRef SectName;
760 if (O->getSectionName(DRI, SectName))
761 outs() << "Relocation information (" << SegName << ",?) "
762 << format("%u entries", Sec.nreloc);
763 else
764 outs() << "Relocation information (" << SegName << ","
765 << SectName << format(") %u entries", Sec.nreloc);
766 outs() << "\naddress pcrel length extern type scattered "
767 "symbolnum/value\n";
768 PrintRelocationEntries(O, O->section_rel_begin(DRI),
769 O->section_rel_end(DRI), cputype, verbose);
770 }
771 }
772 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
773 const MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
774 for (unsigned J = 0; J < Seg.nsects; ++J) {
775 const MachO::section Sec = O->getSection(Load, J);
776 if (Sec.nreloc != 0) {
777 DataRefImpl DRI;
778 DRI.d.a = J;
779 const StringRef SegName = O->getSectionFinalSegmentName(DRI);
780 StringRef SectName;
781 if (O->getSectionName(DRI, SectName))
782 outs() << "Relocation information (" << SegName << ",?) "
783 << format("%u entries", Sec.nreloc);
784 else
785 outs() << "Relocation information (" << SegName << ","
786 << SectName << format(") %u entries", Sec.nreloc);
787 outs() << "\naddress pcrel length extern type scattered "
788 "symbolnum/value\n";
789 PrintRelocationEntries(O, O->section_rel_begin(DRI),
790 O->section_rel_end(DRI), cputype, verbose);
791 }
792 }
793 }
794 }
795}
796
Kevin Enderby69fe98d2015-01-23 18:52:17 +0000797static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
798 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
799 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
800 outs() << "Data in code table (" << nentries << " entries)\n";
801 outs() << "offset length kind\n";
802 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
803 ++DI) {
804 uint32_t Offset;
805 DI->getOffset(Offset);
806 outs() << format("0x%08" PRIx32, Offset) << " ";
807 uint16_t Length;
808 DI->getLength(Length);
809 outs() << format("%6u", Length) << " ";
810 uint16_t Kind;
811 DI->getKind(Kind);
812 if (verbose) {
813 switch (Kind) {
814 case MachO::DICE_KIND_DATA:
815 outs() << "DATA";
816 break;
817 case MachO::DICE_KIND_JUMP_TABLE8:
818 outs() << "JUMP_TABLE8";
819 break;
820 case MachO::DICE_KIND_JUMP_TABLE16:
821 outs() << "JUMP_TABLE16";
822 break;
823 case MachO::DICE_KIND_JUMP_TABLE32:
824 outs() << "JUMP_TABLE32";
825 break;
826 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
827 outs() << "ABS_JUMP_TABLE32";
828 break;
829 default:
830 outs() << format("0x%04" PRIx32, Kind);
831 break;
832 }
833 } else
834 outs() << format("0x%04" PRIx32, Kind);
835 outs() << "\n";
836 }
837}
838
Kevin Enderby9a509442015-01-27 21:28:24 +0000839static void PrintLinkOptHints(MachOObjectFile *O) {
840 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
841 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
842 uint32_t nloh = LohLC.datasize;
843 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
844 for (uint32_t i = 0; i < nloh;) {
845 unsigned n;
846 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
847 i += n;
848 outs() << " identifier " << identifier << " ";
849 if (i >= nloh)
850 return;
851 switch (identifier) {
852 case 1:
853 outs() << "AdrpAdrp\n";
854 break;
855 case 2:
856 outs() << "AdrpLdr\n";
857 break;
858 case 3:
859 outs() << "AdrpAddLdr\n";
860 break;
861 case 4:
862 outs() << "AdrpLdrGotLdr\n";
863 break;
864 case 5:
865 outs() << "AdrpAddStr\n";
866 break;
867 case 6:
868 outs() << "AdrpLdrGotStr\n";
869 break;
870 case 7:
871 outs() << "AdrpAdd\n";
872 break;
873 case 8:
874 outs() << "AdrpLdrGot\n";
875 break;
876 default:
877 outs() << "Unknown identifier value\n";
878 break;
879 }
880 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
881 i += n;
882 outs() << " narguments " << narguments << "\n";
883 if (i >= nloh)
884 return;
885
886 for (uint32_t j = 0; j < narguments; j++) {
887 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
888 i += n;
889 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
890 if (i >= nloh)
891 return;
892 }
893 }
894}
895
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000896static void PrintDylibs(MachOObjectFile *O, bool JustId) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000897 unsigned Index = 0;
898 for (const auto &Load : O->load_commands()) {
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000899 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
900 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
901 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
902 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
903 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
904 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
905 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
906 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
907 if (dl.dylib.name < dl.cmdsize) {
908 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
909 if (JustId)
910 outs() << p << "\n";
911 else {
912 outs() << "\t" << p;
913 outs() << " (compatibility version "
914 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
915 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
916 << (dl.dylib.compatibility_version & 0xff) << ",";
917 outs() << " current version "
918 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
919 << ((dl.dylib.current_version >> 8) & 0xff) << "."
920 << (dl.dylib.current_version & 0xff) << ")\n";
921 }
922 } else {
923 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
924 if (Load.C.cmd == MachO::LC_ID_DYLIB)
925 outs() << "LC_ID_DYLIB ";
926 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
927 outs() << "LC_LOAD_DYLIB ";
928 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
929 outs() << "LC_LOAD_WEAK_DYLIB ";
930 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
931 outs() << "LC_LAZY_LOAD_DYLIB ";
932 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
933 outs() << "LC_REEXPORT_DYLIB ";
934 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
935 outs() << "LC_LOAD_UPWARD_DYLIB ";
936 else
937 outs() << "LC_??? ";
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000938 outs() << "command " << Index++ << "\n";
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000939 }
940 }
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000941 }
942}
943
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000944typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
945
946static void CreateSymbolAddressMap(MachOObjectFile *O,
947 SymbolAddressMap *AddrMap) {
948 // Create a map of symbol addresses to symbol names.
949 for (const SymbolRef &Symbol : O->symbols()) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000950 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000951 if (!STOrErr)
952 report_error(O->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000953 SymbolRef::Type ST = *STOrErr;
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000954 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
955 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +0000956 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000957 Expected<StringRef> SymNameOrErr = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000958 if (!SymNameOrErr)
959 report_error(O->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000960 StringRef SymName = *SymNameOrErr;
Kevin Enderby846c0002015-04-16 17:19:59 +0000961 if (!SymName.startswith(".objc"))
962 (*AddrMap)[Address] = SymName;
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000963 }
964 }
965}
966
967// GuessSymbolName is passed the address of what might be a symbol and a
968// pointer to the SymbolAddressMap. It returns the name of a symbol
969// with that address or nullptr if no symbol is found with that address.
970static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
971 const char *SymbolName = nullptr;
972 // A DenseMap can't lookup up some values.
973 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
974 StringRef name = AddrMap->lookup(value);
975 if (!name.empty())
976 SymbolName = name.data();
977 }
978 return SymbolName;
979}
980
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000981static void DumpCstringChar(const char c) {
982 char p[2];
983 p[0] = c;
984 p[1] = '\0';
985 outs().write_escaped(p);
986}
987
Kevin Enderby10ba0412015-02-04 21:38:42 +0000988static void DumpCstringSection(MachOObjectFile *O, const char *sect,
989 uint32_t sect_size, uint64_t sect_addr,
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000990 bool print_addresses) {
Kevin Enderby10ba0412015-02-04 21:38:42 +0000991 for (uint32_t i = 0; i < sect_size; i++) {
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000992 if (print_addresses) {
993 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000994 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000995 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000996 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000997 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000998 for (; i < sect_size && sect[i] != '\0'; i++)
999 DumpCstringChar(sect[i]);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001000 if (i < sect_size && sect[i] == '\0')
1001 outs() << "\n";
1002 }
1003}
1004
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001005static void DumpLiteral4(uint32_t l, float f) {
1006 outs() << format("0x%08" PRIx32, l);
1007 if ((l & 0x7f800000) != 0x7f800000)
1008 outs() << format(" (%.16e)\n", f);
1009 else {
1010 if (l == 0x7f800000)
1011 outs() << " (+Infinity)\n";
1012 else if (l == 0xff800000)
1013 outs() << " (-Infinity)\n";
1014 else if ((l & 0x00400000) == 0x00400000)
1015 outs() << " (non-signaling Not-a-Number)\n";
1016 else
1017 outs() << " (signaling Not-a-Number)\n";
1018 }
1019}
1020
1021static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
1022 uint32_t sect_size, uint64_t sect_addr,
1023 bool print_addresses) {
1024 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
1025 if (print_addresses) {
1026 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001027 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001028 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001029 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001030 }
1031 float f;
1032 memcpy(&f, sect + i, sizeof(float));
1033 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1034 sys::swapByteOrder(f);
1035 uint32_t l;
1036 memcpy(&l, sect + i, sizeof(uint32_t));
1037 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1038 sys::swapByteOrder(l);
1039 DumpLiteral4(l, f);
1040 }
1041}
1042
1043static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
1044 double d) {
1045 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
1046 uint32_t Hi, Lo;
Davide Italianob627d9f2015-12-12 21:50:11 +00001047 Hi = (O->isLittleEndian()) ? l1 : l0;
1048 Lo = (O->isLittleEndian()) ? l0 : l1;
1049
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001050 // Hi is the high word, so this is equivalent to if(isfinite(d))
1051 if ((Hi & 0x7ff00000) != 0x7ff00000)
1052 outs() << format(" (%.16e)\n", d);
1053 else {
1054 if (Hi == 0x7ff00000 && Lo == 0)
1055 outs() << " (+Infinity)\n";
1056 else if (Hi == 0xfff00000 && Lo == 0)
1057 outs() << " (-Infinity)\n";
1058 else if ((Hi & 0x00080000) == 0x00080000)
1059 outs() << " (non-signaling Not-a-Number)\n";
1060 else
1061 outs() << " (signaling Not-a-Number)\n";
1062 }
1063}
1064
1065static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
1066 uint32_t sect_size, uint64_t sect_addr,
1067 bool print_addresses) {
1068 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
1069 if (print_addresses) {
1070 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001071 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001072 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001073 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001074 }
1075 double d;
1076 memcpy(&d, sect + i, sizeof(double));
1077 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1078 sys::swapByteOrder(d);
1079 uint32_t l0, l1;
1080 memcpy(&l0, sect + i, sizeof(uint32_t));
1081 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1082 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1083 sys::swapByteOrder(l0);
1084 sys::swapByteOrder(l1);
1085 }
1086 DumpLiteral8(O, l0, l1, d);
1087 }
1088}
1089
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001090static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
1091 outs() << format("0x%08" PRIx32, l0) << " ";
1092 outs() << format("0x%08" PRIx32, l1) << " ";
1093 outs() << format("0x%08" PRIx32, l2) << " ";
1094 outs() << format("0x%08" PRIx32, l3) << "\n";
1095}
1096
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001097static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
1098 uint32_t sect_size, uint64_t sect_addr,
1099 bool print_addresses) {
1100 for (uint32_t i = 0; i < sect_size; i += 16) {
1101 if (print_addresses) {
1102 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001103 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001104 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001105 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001106 }
1107 uint32_t l0, l1, l2, l3;
1108 memcpy(&l0, sect + i, sizeof(uint32_t));
1109 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1110 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
1111 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
1112 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1113 sys::swapByteOrder(l0);
1114 sys::swapByteOrder(l1);
1115 sys::swapByteOrder(l2);
1116 sys::swapByteOrder(l3);
1117 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001118 DumpLiteral16(l0, l1, l2, l3);
1119 }
1120}
1121
1122static void DumpLiteralPointerSection(MachOObjectFile *O,
1123 const SectionRef &Section,
1124 const char *sect, uint32_t sect_size,
1125 uint64_t sect_addr,
1126 bool print_addresses) {
1127 // Collect the literal sections in this Mach-O file.
1128 std::vector<SectionRef> LiteralSections;
1129 for (const SectionRef &Section : O->sections()) {
1130 DataRefImpl Ref = Section.getRawDataRefImpl();
1131 uint32_t section_type;
1132 if (O->is64Bit()) {
1133 const MachO::section_64 Sec = O->getSection64(Ref);
1134 section_type = Sec.flags & MachO::SECTION_TYPE;
1135 } else {
1136 const MachO::section Sec = O->getSection(Ref);
1137 section_type = Sec.flags & MachO::SECTION_TYPE;
1138 }
1139 if (section_type == MachO::S_CSTRING_LITERALS ||
1140 section_type == MachO::S_4BYTE_LITERALS ||
1141 section_type == MachO::S_8BYTE_LITERALS ||
1142 section_type == MachO::S_16BYTE_LITERALS)
1143 LiteralSections.push_back(Section);
1144 }
1145
1146 // Set the size of the literal pointer.
1147 uint32_t lp_size = O->is64Bit() ? 8 : 4;
1148
Eric Christopher572e03a2015-06-19 01:53:21 +00001149 // Collect the external relocation symbols for the literal pointers.
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001150 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1151 for (const RelocationRef &Reloc : Section.relocations()) {
1152 DataRefImpl Rel;
1153 MachO::any_relocation_info RE;
1154 bool isExtern = false;
1155 Rel = Reloc.getRawDataRefImpl();
1156 RE = O->getRelocation(Rel);
1157 isExtern = O->getPlainRelocationExternal(RE);
1158 if (isExtern) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001159 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001160 symbol_iterator RelocSym = Reloc.getSymbol();
1161 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1162 }
1163 }
1164 array_pod_sort(Relocs.begin(), Relocs.end());
1165
1166 // Dump each literal pointer.
1167 for (uint32_t i = 0; i < sect_size; i += lp_size) {
1168 if (print_addresses) {
1169 if (O->is64Bit())
1170 outs() << format("%016" PRIx64, sect_addr + i) << " ";
1171 else
1172 outs() << format("%08" PRIx64, sect_addr + i) << " ";
1173 }
1174 uint64_t lp;
1175 if (O->is64Bit()) {
1176 memcpy(&lp, sect + i, sizeof(uint64_t));
1177 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1178 sys::swapByteOrder(lp);
1179 } else {
1180 uint32_t li;
1181 memcpy(&li, sect + i, sizeof(uint32_t));
1182 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1183 sys::swapByteOrder(li);
1184 lp = li;
1185 }
1186
1187 // First look for an external relocation entry for this literal pointer.
David Majnemer42531262016-08-12 03:55:06 +00001188 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1189 return P.first == i;
1190 });
David Blaikie33dd45d02015-03-23 18:39:02 +00001191 if (Reloc != Relocs.end()) {
1192 symbol_iterator RelocSym = Reloc->second;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001193 Expected<StringRef> SymName = RelocSym->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001194 if (!SymName)
1195 report_error(O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001196 outs() << "external relocation entry for symbol:" << *SymName << "\n";
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001197 continue;
David Blaikie33dd45d02015-03-23 18:39:02 +00001198 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001199
1200 // For local references see what the section the literal pointer points to.
David Majnemer562e8292016-08-12 00:18:03 +00001201 auto Sect = find_if(LiteralSections, [&](const SectionRef &R) {
1202 return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
1203 });
David Blaikie33dd45d02015-03-23 18:39:02 +00001204 if (Sect == LiteralSections.end()) {
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001205 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
David Blaikie33dd45d02015-03-23 18:39:02 +00001206 continue;
1207 }
1208
1209 uint64_t SectAddress = Sect->getAddress();
1210 uint64_t SectSize = Sect->getSize();
1211
1212 StringRef SectName;
1213 Sect->getName(SectName);
1214 DataRefImpl Ref = Sect->getRawDataRefImpl();
1215 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
1216 outs() << SegmentName << ":" << SectName << ":";
1217
1218 uint32_t section_type;
1219 if (O->is64Bit()) {
1220 const MachO::section_64 Sec = O->getSection64(Ref);
1221 section_type = Sec.flags & MachO::SECTION_TYPE;
1222 } else {
1223 const MachO::section Sec = O->getSection(Ref);
1224 section_type = Sec.flags & MachO::SECTION_TYPE;
1225 }
1226
1227 StringRef BytesStr;
1228 Sect->getContents(BytesStr);
1229 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
1230
1231 switch (section_type) {
1232 case MachO::S_CSTRING_LITERALS:
1233 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
1234 i++) {
1235 DumpCstringChar(Contents[i]);
1236 }
1237 outs() << "\n";
1238 break;
1239 case MachO::S_4BYTE_LITERALS:
1240 float f;
1241 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
1242 uint32_t l;
1243 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
1244 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1245 sys::swapByteOrder(f);
1246 sys::swapByteOrder(l);
1247 }
1248 DumpLiteral4(l, f);
1249 break;
1250 case MachO::S_8BYTE_LITERALS: {
1251 double d;
1252 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
1253 uint32_t l0, l1;
1254 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1255 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1256 sizeof(uint32_t));
1257 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1258 sys::swapByteOrder(f);
1259 sys::swapByteOrder(l0);
1260 sys::swapByteOrder(l1);
1261 }
1262 DumpLiteral8(O, l0, l1, d);
1263 break;
1264 }
1265 case MachO::S_16BYTE_LITERALS: {
1266 uint32_t l0, l1, l2, l3;
1267 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1268 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1269 sizeof(uint32_t));
1270 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
1271 sizeof(uint32_t));
1272 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
1273 sizeof(uint32_t));
1274 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1275 sys::swapByteOrder(l0);
1276 sys::swapByteOrder(l1);
1277 sys::swapByteOrder(l2);
1278 sys::swapByteOrder(l3);
1279 }
1280 DumpLiteral16(l0, l1, l2, l3);
1281 break;
1282 }
1283 }
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001284 }
1285}
1286
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001287static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
1288 uint32_t sect_size, uint64_t sect_addr,
1289 SymbolAddressMap *AddrMap,
1290 bool verbose) {
1291 uint32_t stride;
Davide Italiano3eb47e22015-12-15 23:14:21 +00001292 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001293 for (uint32_t i = 0; i < sect_size; i += stride) {
1294 const char *SymbolName = nullptr;
1295 if (O->is64Bit()) {
1296 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
1297 uint64_t pointer_value;
1298 memcpy(&pointer_value, sect + i, stride);
1299 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1300 sys::swapByteOrder(pointer_value);
1301 outs() << format("0x%016" PRIx64, pointer_value);
1302 if (verbose)
1303 SymbolName = GuessSymbolName(pointer_value, AddrMap);
1304 } else {
1305 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
1306 uint32_t pointer_value;
1307 memcpy(&pointer_value, sect + i, stride);
1308 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1309 sys::swapByteOrder(pointer_value);
1310 outs() << format("0x%08" PRIx32, pointer_value);
1311 if (verbose)
1312 SymbolName = GuessSymbolName(pointer_value, AddrMap);
1313 }
1314 if (SymbolName)
1315 outs() << " " << SymbolName;
1316 outs() << "\n";
1317 }
1318}
1319
1320static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
1321 uint32_t size, uint64_t addr) {
1322 uint32_t cputype = O->getHeader().cputype;
1323 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
1324 uint32_t j;
1325 for (uint32_t i = 0; i < size; i += j, addr += j) {
1326 if (O->is64Bit())
1327 outs() << format("%016" PRIx64, addr) << "\t";
1328 else
Kevin Enderbyf0640752015-03-13 17:56:32 +00001329 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001330 for (j = 0; j < 16 && i + j < size; j++) {
1331 uint8_t byte_word = *(sect + i + j);
1332 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1333 }
1334 outs() << "\n";
1335 }
1336 } else {
1337 uint32_t j;
1338 for (uint32_t i = 0; i < size; i += j, addr += j) {
1339 if (O->is64Bit())
1340 outs() << format("%016" PRIx64, addr) << "\t";
1341 else
Kevin Enderbyc4930852016-04-27 22:36:18 +00001342 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001343 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1344 j += sizeof(int32_t)) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001345 if (i + j + sizeof(int32_t) <= size) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001346 uint32_t long_word;
1347 memcpy(&long_word, sect + i + j, sizeof(int32_t));
1348 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1349 sys::swapByteOrder(long_word);
1350 outs() << format("%08" PRIx32, long_word) << " ";
1351 } else {
1352 for (uint32_t k = 0; i + j + k < size; k++) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001353 uint8_t byte_word = *(sect + i + j + k);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001354 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1355 }
1356 }
1357 }
1358 outs() << "\n";
1359 }
1360 }
1361}
1362
Kevin Enderby95df54c2015-02-04 01:01:38 +00001363static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1364 StringRef DisSegName, StringRef DisSectName);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001365static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1366 uint32_t size, uint32_t addr);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001367#ifdef HAVE_LIBXAR
1368static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
1369 uint32_t size, bool verbose,
1370 bool PrintXarHeader, bool PrintXarFileHeaders,
1371 std::string XarMemberName);
1372#endif // defined(HAVE_LIBXAR)
Kevin Enderby95df54c2015-02-04 01:01:38 +00001373
1374static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1375 bool verbose) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001376 SymbolAddressMap AddrMap;
1377 if (verbose)
1378 CreateSymbolAddressMap(O, &AddrMap);
1379
Colin LeMahieufcc32762015-07-29 19:08:10 +00001380 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1381 StringRef DumpSection = FilterSections[i];
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001382 std::pair<StringRef, StringRef> DumpSegSectName;
1383 DumpSegSectName = DumpSection.split(',');
1384 StringRef DumpSegName, DumpSectName;
1385 if (DumpSegSectName.second.size()) {
1386 DumpSegName = DumpSegSectName.first;
1387 DumpSectName = DumpSegSectName.second;
1388 } else {
1389 DumpSegName = "";
1390 DumpSectName = DumpSegSectName.first;
1391 }
1392 for (const SectionRef &Section : O->sections()) {
1393 StringRef SectName;
1394 Section.getName(SectName);
1395 DataRefImpl Ref = Section.getRawDataRefImpl();
1396 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1397 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1398 (SectName == DumpSectName)) {
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001399
Kevin Enderby95df54c2015-02-04 01:01:38 +00001400 uint32_t section_flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001401 if (O->is64Bit()) {
1402 const MachO::section_64 Sec = O->getSection64(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001403 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001404
1405 } else {
1406 const MachO::section Sec = O->getSection(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001407 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001408 }
Kevin Enderby95df54c2015-02-04 01:01:38 +00001409 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001410
1411 StringRef BytesStr;
1412 Section.getContents(BytesStr);
1413 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1414 uint32_t sect_size = BytesStr.size();
1415 uint64_t sect_addr = Section.getAddress();
1416
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001417 outs() << "Contents of (" << SegName << "," << SectName
1418 << ") section\n";
1419
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001420 if (verbose) {
Kevin Enderby95df54c2015-02-04 01:01:38 +00001421 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1422 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1423 DisassembleMachO(Filename, O, SegName, SectName);
1424 continue;
1425 }
Kevin Enderbycd66be52015-03-11 22:06:32 +00001426 if (SegName == "__TEXT" && SectName == "__info_plist") {
1427 outs() << sect;
1428 continue;
1429 }
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001430 if (SegName == "__OBJC" && SectName == "__protocol") {
1431 DumpProtocolSection(O, sect, sect_size, sect_addr);
1432 continue;
1433 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001434#ifdef HAVE_LIBXAR
1435 if (SegName == "__LLVM" && SectName == "__bundle") {
1436 DumpBitcodeSection(O, sect, sect_size, verbose, !NoSymbolicOperands,
1437 ArchiveHeaders, "");
1438 continue;
1439 }
1440#endif // defined(HAVE_LIBXAR)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001441 switch (section_type) {
1442 case MachO::S_REGULAR:
1443 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1444 break;
1445 case MachO::S_ZEROFILL:
1446 outs() << "zerofill section and has no contents in the file\n";
1447 break;
Kevin Enderby10ba0412015-02-04 21:38:42 +00001448 case MachO::S_CSTRING_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001449 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001450 break;
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001451 case MachO::S_4BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001452 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001453 break;
1454 case MachO::S_8BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001455 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001456 break;
1457 case MachO::S_16BYTE_LITERALS:
Kevin Enderby0fc11822015-04-01 20:57:01 +00001458 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1459 break;
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001460 case MachO::S_LITERAL_POINTERS:
1461 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001462 !NoLeadingAddr);
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001463 break;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001464 case MachO::S_MOD_INIT_FUNC_POINTERS:
1465 case MachO::S_MOD_TERM_FUNC_POINTERS:
1466 DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
1467 verbose);
1468 break;
1469 default:
1470 outs() << "Unknown section type ("
1471 << format("0x%08" PRIx32, section_type) << ")\n";
1472 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1473 break;
1474 }
1475 } else {
1476 if (section_type == MachO::S_ZEROFILL)
1477 outs() << "zerofill section and has no contents in the file\n";
1478 else
1479 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1480 }
1481 }
1482 }
1483 }
1484}
1485
Kevin Enderbycd66be52015-03-11 22:06:32 +00001486static void DumpInfoPlistSectionContents(StringRef Filename,
1487 MachOObjectFile *O) {
1488 for (const SectionRef &Section : O->sections()) {
1489 StringRef SectName;
1490 Section.getName(SectName);
1491 DataRefImpl Ref = Section.getRawDataRefImpl();
1492 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1493 if (SegName == "__TEXT" && SectName == "__info_plist") {
Kevin Enderby30cf2e82017-06-20 21:00:25 +00001494 if (!NoLeadingHeaders)
1495 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
Kevin Enderbycd66be52015-03-11 22:06:32 +00001496 StringRef BytesStr;
1497 Section.getContents(BytesStr);
1498 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
Kevin Enderby418659f2017-02-06 21:01:08 +00001499 outs() << format("%.*s", BytesStr.size(), sect) << "\n";
Kevin Enderbycd66be52015-03-11 22:06:32 +00001500 return;
1501 }
1502 }
1503}
1504
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001505// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1506// and if it is and there is a list of architecture flags is specified then
1507// check to make sure this Mach-O file is one of those architectures or all
1508// architectures were specified. If not then an error is generated and this
1509// routine returns false. Else it returns true.
1510static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
David Majnemer91160d82016-10-31 17:11:31 +00001511 auto *MachO = dyn_cast<MachOObjectFile>(O);
1512
1513 if (!MachO || ArchAll || ArchFlags.empty())
1514 return true;
1515
1516 MachO::mach_header H;
1517 MachO::mach_header_64 H_64;
1518 Triple T;
Kevin Enderby59343a92016-12-16 22:54:02 +00001519 const char *McpuDefault, *ArchFlag;
David Majnemer91160d82016-10-31 17:11:31 +00001520 if (MachO->is64Bit()) {
1521 H_64 = MachO->MachOObjectFile::getHeader64();
Kevin Enderby59343a92016-12-16 22:54:02 +00001522 T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype,
1523 &McpuDefault, &ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001524 } else {
1525 H = MachO->MachOObjectFile::getHeader();
Kevin Enderby59343a92016-12-16 22:54:02 +00001526 T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype,
1527 &McpuDefault, &ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001528 }
Kevin Enderby59343a92016-12-16 22:54:02 +00001529 const std::string ArchFlagName(ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001530 if (none_of(ArchFlags, [&](const std::string &Name) {
Kevin Enderby59343a92016-12-16 22:54:02 +00001531 return Name == ArchFlagName;
David Majnemer91160d82016-10-31 17:11:31 +00001532 })) {
1533 errs() << "llvm-objdump: " + Filename + ": No architecture specified.\n";
1534 return false;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001535 }
1536 return true;
1537}
1538
Kevin Enderby0fc11822015-04-01 20:57:01 +00001539static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1540
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001541// ProcessMachO() is passed a single opened Mach-O file, which may be an
1542// archive member and or in a slice of a universal file. It prints the
1543// the file name and header info and then processes it according to the
1544// command line options.
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001545static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001546 StringRef ArchiveMemberName = StringRef(),
1547 StringRef ArchitectureName = StringRef()) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001548 // If we are doing some processing here on the Mach-O file print the header
1549 // info. And don't print it otherwise like in the case of printing the
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001550 // UniversalHeaders or ArchiveHeaders.
Michael Trenta1703b12017-12-15 17:57:40 +00001551 if (Disassemble || Relocations || PrivateHeaders || ExportsTrie || Rebase ||
1552 Bind || SymbolTable || LazyBind || WeakBind || IndirectSymbols ||
1553 DataInCode || LinkOptHints || DylibsUsed || DylibId || ObjcMetaData ||
1554 (FilterSections.size() != 0)) {
Kevin Enderbyf9d60f02016-11-29 21:43:40 +00001555 if (!NoLeadingHeaders) {
1556 outs() << Name;
1557 if (!ArchiveMemberName.empty())
1558 outs() << '(' << ArchiveMemberName << ')';
1559 if (!ArchitectureName.empty())
1560 outs() << " (architecture " << ArchitectureName << ")";
1561 outs() << ":\n";
1562 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001563 }
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001564 // To use the report_error() form with an ArchiveName and FileName set
1565 // these up based on what is passed for Name and ArchiveMemberName.
1566 StringRef ArchiveName;
1567 StringRef FileName;
1568 if (!ArchiveMemberName.empty()) {
1569 ArchiveName = Name;
1570 FileName = ArchiveMemberName;
1571 } else {
1572 ArchiveName = StringRef();
1573 FileName = Name;
1574 }
1575
1576 // If we need the symbol table to do the operation then check it here to
1577 // produce a good error message as to where the Mach-O file comes from in
1578 // the error message.
1579 if (Disassemble || IndirectSymbols || FilterSections.size() != 0 ||
1580 UnwindInfo)
1581 if (Error Err = MachOOF->checkSymbolTable())
1582 report_error(ArchiveName, FileName, std::move(Err), ArchitectureName);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001583
Kevin Enderbyaf2999a2017-06-22 19:50:56 +00001584 if (Disassemble) {
1585 if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE &&
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00001586 MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64)
Kevin Enderbyaf2999a2017-06-22 19:50:56 +00001587 DisassembleMachO(FileName, MachOOF, "__TEXT_EXEC", "__text");
1588 else
1589 DisassembleMachO(FileName, MachOOF, "__TEXT", "__text");
1590 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001591 if (IndirectSymbols)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001592 PrintIndirectSymbols(MachOOF, !NonVerbose);
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001593 if (DataInCode)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001594 PrintDataInCodeTable(MachOOF, !NonVerbose);
Kevin Enderby9a509442015-01-27 21:28:24 +00001595 if (LinkOptHints)
1596 PrintLinkOptHints(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001597 if (Relocations)
Michael Trenta1703b12017-12-15 17:57:40 +00001598 PrintRelocations(MachOOF, !NonVerbose);
Kevin Enderby98da6132015-01-20 21:47:46 +00001599 if (SectionHeaders)
1600 PrintSectionHeaders(MachOOF);
1601 if (SectionContents)
1602 PrintSectionContents(MachOOF);
Colin LeMahieufcc32762015-07-29 19:08:10 +00001603 if (FilterSections.size() != 0)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001604 DumpSectionContents(FileName, MachOOF, !NonVerbose);
Kevin Enderbycd66be52015-03-11 22:06:32 +00001605 if (InfoPlist)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001606 DumpInfoPlistSectionContents(FileName, MachOOF);
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001607 if (DylibsUsed)
1608 PrintDylibs(MachOOF, false);
1609 if (DylibId)
1610 PrintDylibs(MachOOF, true);
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001611 if (SymbolTable)
Kevin Enderby9acb1092016-05-31 20:35:34 +00001612 PrintSymbolTable(MachOOF, ArchiveName, ArchitectureName);
Kevin Enderby98da6132015-01-20 21:47:46 +00001613 if (UnwindInfo)
1614 printMachOUnwindInfo(MachOOF);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001615 if (PrivateHeaders) {
1616 printMachOFileHeader(MachOOF);
1617 printMachOLoadCommands(MachOOF);
1618 }
1619 if (FirstPrivateHeader)
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001620 printMachOFileHeader(MachOOF);
Kevin Enderby0fc11822015-04-01 20:57:01 +00001621 if (ObjcMetaData)
1622 printObjcMetaData(MachOOF, !NonVerbose);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001623 if (ExportsTrie)
1624 printExportsTrie(MachOOF);
1625 if (Rebase)
1626 printRebaseTable(MachOOF);
1627 if (Bind)
1628 printBindTable(MachOOF);
1629 if (LazyBind)
1630 printLazyBindTable(MachOOF);
1631 if (WeakBind)
1632 printWeakBindTable(MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001633
1634 if (DwarfDumpType != DIDT_Null) {
Rafael Espindolac398e672017-07-19 22:27:28 +00001635 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001636 // Dump the complete DWARF structure.
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00001637 DIDumpOptions DumpOpts;
1638 DumpOpts.DumpType = DwarfDumpType;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00001639 DICtx->dump(outs(), DumpOpts);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001640 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001641}
1642
Kevin Enderby131d1772015-01-09 19:22:37 +00001643// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1644static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1645 outs() << " cputype (" << cputype << ")\n";
1646 outs() << " cpusubtype (" << cpusubtype << ")\n";
1647}
1648
1649// printCPUType() helps print_fat_headers by printing the cputype and
1650// pusubtype (symbolically for the one's it knows about).
1651static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1652 switch (cputype) {
1653 case MachO::CPU_TYPE_I386:
1654 switch (cpusubtype) {
1655 case MachO::CPU_SUBTYPE_I386_ALL:
1656 outs() << " cputype CPU_TYPE_I386\n";
1657 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1658 break;
1659 default:
1660 printUnknownCPUType(cputype, cpusubtype);
1661 break;
1662 }
1663 break;
1664 case MachO::CPU_TYPE_X86_64:
1665 switch (cpusubtype) {
1666 case MachO::CPU_SUBTYPE_X86_64_ALL:
1667 outs() << " cputype CPU_TYPE_X86_64\n";
1668 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1669 break;
1670 case MachO::CPU_SUBTYPE_X86_64_H:
1671 outs() << " cputype CPU_TYPE_X86_64\n";
1672 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1673 break;
1674 default:
1675 printUnknownCPUType(cputype, cpusubtype);
1676 break;
1677 }
1678 break;
1679 case MachO::CPU_TYPE_ARM:
1680 switch (cpusubtype) {
1681 case MachO::CPU_SUBTYPE_ARM_ALL:
1682 outs() << " cputype CPU_TYPE_ARM\n";
1683 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1684 break;
1685 case MachO::CPU_SUBTYPE_ARM_V4T:
1686 outs() << " cputype CPU_TYPE_ARM\n";
1687 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1688 break;
1689 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1690 outs() << " cputype CPU_TYPE_ARM\n";
1691 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1692 break;
1693 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1694 outs() << " cputype CPU_TYPE_ARM\n";
1695 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1696 break;
1697 case MachO::CPU_SUBTYPE_ARM_V6:
1698 outs() << " cputype CPU_TYPE_ARM\n";
1699 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1700 break;
1701 case MachO::CPU_SUBTYPE_ARM_V6M:
1702 outs() << " cputype CPU_TYPE_ARM\n";
1703 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1704 break;
1705 case MachO::CPU_SUBTYPE_ARM_V7:
1706 outs() << " cputype CPU_TYPE_ARM\n";
1707 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1708 break;
1709 case MachO::CPU_SUBTYPE_ARM_V7EM:
1710 outs() << " cputype CPU_TYPE_ARM\n";
1711 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1712 break;
1713 case MachO::CPU_SUBTYPE_ARM_V7K:
1714 outs() << " cputype CPU_TYPE_ARM\n";
1715 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1716 break;
1717 case MachO::CPU_SUBTYPE_ARM_V7M:
1718 outs() << " cputype CPU_TYPE_ARM\n";
1719 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1720 break;
1721 case MachO::CPU_SUBTYPE_ARM_V7S:
1722 outs() << " cputype CPU_TYPE_ARM\n";
1723 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1724 break;
1725 default:
1726 printUnknownCPUType(cputype, cpusubtype);
1727 break;
1728 }
1729 break;
1730 case MachO::CPU_TYPE_ARM64:
1731 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1732 case MachO::CPU_SUBTYPE_ARM64_ALL:
1733 outs() << " cputype CPU_TYPE_ARM64\n";
1734 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1735 break;
1736 default:
1737 printUnknownCPUType(cputype, cpusubtype);
1738 break;
1739 }
1740 break;
1741 default:
1742 printUnknownCPUType(cputype, cpusubtype);
1743 break;
1744 }
1745}
1746
1747static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1748 bool verbose) {
1749 outs() << "Fat headers\n";
Kevin Enderby606a3382016-06-21 21:55:01 +00001750 if (verbose) {
1751 if (UB->getMagic() == MachO::FAT_MAGIC)
1752 outs() << "fat_magic FAT_MAGIC\n";
1753 else // UB->getMagic() == MachO::FAT_MAGIC_64
1754 outs() << "fat_magic FAT_MAGIC_64\n";
1755 } else
Kevin Enderby131d1772015-01-09 19:22:37 +00001756 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1757
1758 uint32_t nfat_arch = UB->getNumberOfObjects();
1759 StringRef Buf = UB->getData();
1760 uint64_t size = Buf.size();
1761 uint64_t big_size = sizeof(struct MachO::fat_header) +
1762 nfat_arch * sizeof(struct MachO::fat_arch);
1763 outs() << "nfat_arch " << UB->getNumberOfObjects();
1764 if (nfat_arch == 0)
1765 outs() << " (malformed, contains zero architecture types)\n";
1766 else if (big_size > size)
1767 outs() << " (malformed, architectures past end of file)\n";
1768 else
1769 outs() << "\n";
1770
1771 for (uint32_t i = 0; i < nfat_arch; ++i) {
1772 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1773 uint32_t cputype = OFA.getCPUType();
1774 uint32_t cpusubtype = OFA.getCPUSubType();
1775 outs() << "architecture ";
1776 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1777 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1778 uint32_t other_cputype = other_OFA.getCPUType();
1779 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
Kevin Enderby0512bd72015-01-09 21:55:03 +00001780 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
Kevin Enderby131d1772015-01-09 19:22:37 +00001781 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
Kevin Enderby0512bd72015-01-09 21:55:03 +00001782 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001783 outs() << "(illegal duplicate architecture) ";
1784 break;
Kevin Enderby0512bd72015-01-09 21:55:03 +00001785 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001786 }
1787 if (verbose) {
Kevin Enderby59343a92016-12-16 22:54:02 +00001788 outs() << OFA.getArchFlagName() << "\n";
Kevin Enderby131d1772015-01-09 19:22:37 +00001789 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1790 } else {
1791 outs() << i << "\n";
1792 outs() << " cputype " << cputype << "\n";
1793 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1794 << "\n";
1795 }
1796 if (verbose &&
1797 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1798 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1799 else
1800 outs() << " capabilities "
1801 << format("0x%" PRIx32,
1802 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1803 outs() << " offset " << OFA.getOffset();
1804 if (OFA.getOffset() > size)
1805 outs() << " (past end of file)";
1806 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1807 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1808 outs() << "\n";
1809 outs() << " size " << OFA.getSize();
1810 big_size = OFA.getOffset() + OFA.getSize();
1811 if (big_size > size)
1812 outs() << " (past end of file)";
1813 outs() << "\n";
1814 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1815 << ")\n";
1816 }
1817}
1818
Kevin Enderby6524bd82016-07-19 20:47:07 +00001819static void printArchiveChild(StringRef Filename, const Archive::Child &C,
1820 bool verbose, bool print_offset,
1821 StringRef ArchitectureName = StringRef()) {
Kevin Enderby13023a12015-01-15 23:19:11 +00001822 if (print_offset)
1823 outs() << C.getChildOffset() << "\t";
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001824 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
1825 if (!ModeOrErr)
1826 report_error(Filename, C, ModeOrErr.takeError(), ArchitectureName);
1827 sys::fs::perms Mode = ModeOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001828 if (verbose) {
1829 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1830 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1831 outs() << "-";
Davide Italianobb9a6cc2015-09-07 20:47:03 +00001832 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1833 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1834 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1835 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1836 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1837 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1838 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1839 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1840 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
Kevin Enderby13023a12015-01-15 23:19:11 +00001841 } else {
1842 outs() << format("0%o ", Mode);
1843 }
1844
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001845 Expected<unsigned> UIDOrErr = C.getUID();
1846 if (!UIDOrErr)
1847 report_error(Filename, C, UIDOrErr.takeError(), ArchitectureName);
1848 unsigned UID = UIDOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001849 outs() << format("%3d/", UID);
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001850 Expected<unsigned> GIDOrErr = C.getGID();
1851 if (!GIDOrErr)
1852 report_error(Filename, C, GIDOrErr.takeError(), ArchitectureName);
1853 unsigned GID = GIDOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001854 outs() << format("%-3d ", GID);
Kevin Enderby6524bd82016-07-19 20:47:07 +00001855 Expected<uint64_t> Size = C.getRawSize();
1856 if (!Size)
1857 report_error(Filename, C, Size.takeError(), ArchitectureName);
Kevin Enderby7a969422015-11-05 19:24:56 +00001858 outs() << format("%5" PRId64, Size.get()) << " ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001859
1860 StringRef RawLastModified = C.getRawLastModified();
1861 if (verbose) {
1862 unsigned Seconds;
1863 if (RawLastModified.getAsInteger(10, Seconds))
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001864 outs() << "(date: \"" << RawLastModified
1865 << "\" contains non-decimal chars) ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001866 else {
1867 // Since cime(3) returns a 26 character string of the form:
1868 // "Sun Sep 16 01:03:52 1973\n\0"
1869 // just print 24 characters.
1870 time_t t = Seconds;
1871 outs() << format("%.24s ", ctime(&t));
1872 }
1873 } else {
1874 outs() << RawLastModified << " ";
1875 }
1876
1877 if (verbose) {
Kevin Enderbyf4586032016-07-29 17:44:13 +00001878 Expected<StringRef> NameOrErr = C.getName();
1879 if (!NameOrErr) {
1880 consumeError(NameOrErr.takeError());
1881 Expected<StringRef> NameOrErr = C.getRawName();
1882 if (!NameOrErr)
1883 report_error(Filename, C, NameOrErr.takeError(), ArchitectureName);
1884 StringRef RawName = NameOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001885 outs() << RawName << "\n";
1886 } else {
1887 StringRef Name = NameOrErr.get();
1888 outs() << Name << "\n";
1889 }
1890 } else {
Kevin Enderbyf4586032016-07-29 17:44:13 +00001891 Expected<StringRef> NameOrErr = C.getRawName();
1892 if (!NameOrErr)
1893 report_error(Filename, C, NameOrErr.takeError(), ArchitectureName);
1894 StringRef RawName = NameOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001895 outs() << RawName << "\n";
1896 }
1897}
1898
Kevin Enderby6524bd82016-07-19 20:47:07 +00001899static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
1900 bool print_offset,
1901 StringRef ArchitectureName = StringRef()) {
Mehdi Amini41af4302016-11-11 04:28:40 +00001902 Error Err = Error::success();
1903 ;
Lang Hamesfc209622016-07-14 02:24:01 +00001904 for (const auto &C : A->children(Err, false))
Kevin Enderby6524bd82016-07-19 20:47:07 +00001905 printArchiveChild(Filename, C, verbose, print_offset, ArchitectureName);
1906
Lang Hamesfc209622016-07-14 02:24:01 +00001907 if (Err)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001908 report_error(StringRef(), Filename, std::move(Err), ArchitectureName);
Kevin Enderby13023a12015-01-15 23:19:11 +00001909}
1910
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001911// ParseInputMachO() parses the named Mach-O file in Filename and handles the
1912// -arch flags selecting just those slices as specified by them and also parses
1913// archive files. Then for each individual Mach-O file ProcessMachO() is
1914// called to process the file based on the command line options.
1915void llvm::ParseInputMachO(StringRef Filename) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001916 // Check for -arch all and verifiy the -arch flags are valid.
1917 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1918 if (ArchFlags[i] == "all") {
1919 ArchAll = true;
1920 } else {
1921 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1922 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1923 "'for the -arch option\n";
1924 return;
1925 }
1926 }
1927 }
1928
1929 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00001930 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
Kevin Enderby98898f22017-01-30 20:53:17 +00001931 if (!BinaryOrErr) {
1932 if (auto E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError()))
1933 report_error(Filename, std::move(E));
1934 else
1935 outs() << Filename << ": is not an object file\n";
1936 return;
1937 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001938 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001939
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001940 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1941 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001942 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001943 printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets);
1944
Mehdi Amini41af4302016-11-11 04:28:40 +00001945 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00001946 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001947 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1948 if (!ChildOrErr) {
1949 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1950 report_error(Filename, C, std::move(E));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001951 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001952 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001953 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1954 if (!checkMachOAndArchFlags(O, Filename))
1955 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001956 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001957 }
1958 }
Lang Hamesfc209622016-07-14 02:24:01 +00001959 if (Err)
1960 report_error(Filename, std::move(Err));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001961 return;
1962 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001963 if (UniversalHeaders) {
1964 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
Kevin Enderbyf0640752015-03-13 17:56:32 +00001965 printMachOUniversalHeaders(UB, !NonVerbose);
Kevin Enderby131d1772015-01-09 19:22:37 +00001966 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001967 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1968 // If we have a list of architecture flags specified dump only those.
1969 if (!ArchAll && ArchFlags.size() != 0) {
1970 // Look for a slice in the universal binary that matches each ArchFlag.
1971 bool ArchFound;
1972 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1973 ArchFound = false;
1974 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1975 E = UB->end_objects();
1976 I != E; ++I) {
Kevin Enderby59343a92016-12-16 22:54:02 +00001977 if (ArchFlags[i] == I->getArchFlagName()) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001978 ArchFound = true;
Kevin Enderby9acb1092016-05-31 20:35:34 +00001979 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001980 I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001981 std::string ArchitectureName = "";
1982 if (ArchFlags.size() > 1)
Kevin Enderby59343a92016-12-16 22:54:02 +00001983 ArchitectureName = I->getArchFlagName();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001984 if (ObjOrErr) {
1985 ObjectFile &O = *ObjOrErr.get();
1986 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001987 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Kevin Enderby9acb1092016-05-31 20:35:34 +00001988 } else if (auto E = isNotObjectErrorInvalidFileType(
1989 ObjOrErr.takeError())) {
1990 report_error(Filename, StringRef(), std::move(E),
1991 ArchitectureName);
1992 continue;
Kevin Enderby42398052016-06-28 23:16:13 +00001993 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001994 I->getAsArchive()) {
1995 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001996 outs() << "Archive : " << Filename;
1997 if (!ArchitectureName.empty())
1998 outs() << " (architecture " << ArchitectureName << ")";
1999 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00002000 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00002001 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2002 ArchiveMemberOffsets, ArchitectureName);
Mehdi Amini41af4302016-11-11 04:28:40 +00002003 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00002004 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002005 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2006 if (!ChildOrErr) {
2007 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
Kevin Enderby9acb1092016-05-31 20:35:34 +00002008 report_error(Filename, C, std::move(E), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002009 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002010 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002011 if (MachOObjectFile *O =
2012 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002013 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002014 }
Lang Hamesfc209622016-07-14 02:24:01 +00002015 if (Err)
2016 report_error(Filename, std::move(Err));
Kevin Enderby42398052016-06-28 23:16:13 +00002017 } else {
2018 consumeError(AOrErr.takeError());
2019 error("Mach-O universal file: " + Filename + " for " +
Kevin Enderby59343a92016-12-16 22:54:02 +00002020 "architecture " + StringRef(I->getArchFlagName()) +
Kevin Enderby42398052016-06-28 23:16:13 +00002021 " is not a Mach-O file or an archive file");
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002022 }
2023 }
2024 }
2025 if (!ArchFound) {
2026 errs() << "llvm-objdump: file: " + Filename + " does not contain "
2027 << "architecture: " + ArchFlags[i] + "\n";
2028 return;
2029 }
2030 }
2031 return;
2032 }
2033 // No architecture flags were specified so if this contains a slice that
2034 // matches the host architecture dump only that.
2035 if (!ArchAll) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002036 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2037 E = UB->end_objects();
2038 I != E; ++I) {
Kevin Enderby0512bd72015-01-09 21:55:03 +00002039 if (MachOObjectFile::getHostArch().getArchName() ==
Kevin Enderby59343a92016-12-16 22:54:02 +00002040 I->getArchFlagName()) {
Kevin Enderby9acb1092016-05-31 20:35:34 +00002041 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002042 std::string ArchiveName;
2043 ArchiveName.clear();
2044 if (ObjOrErr) {
2045 ObjectFile &O = *ObjOrErr.get();
2046 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002047 ProcessMachO(Filename, MachOOF);
Kevin Enderby9acb1092016-05-31 20:35:34 +00002048 } else if (auto E = isNotObjectErrorInvalidFileType(
2049 ObjOrErr.takeError())) {
2050 report_error(Filename, std::move(E));
2051 continue;
Kevin Enderby42398052016-06-28 23:16:13 +00002052 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Rafael Espindola0bfe8282014-12-09 21:05:36 +00002053 I->getAsArchive()) {
2054 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002055 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00002056 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00002057 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2058 ArchiveMemberOffsets);
Mehdi Amini41af4302016-11-11 04:28:40 +00002059 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00002060 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002061 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2062 if (!ChildOrErr) {
2063 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2064 report_error(Filename, C, std::move(E));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002065 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002066 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002067 if (MachOObjectFile *O =
2068 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002069 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002070 }
Lang Hamesfc209622016-07-14 02:24:01 +00002071 if (Err)
2072 report_error(Filename, std::move(Err));
Kevin Enderby42398052016-06-28 23:16:13 +00002073 } else {
2074 consumeError(AOrErr.takeError());
2075 error("Mach-O universal file: " + Filename + " for architecture " +
Kevin Enderby59343a92016-12-16 22:54:02 +00002076 StringRef(I->getArchFlagName()) +
Kevin Enderby42398052016-06-28 23:16:13 +00002077 " is not a Mach-O file or an archive file");
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002078 }
2079 return;
2080 }
2081 }
2082 }
2083 // Either all architectures have been specified or none have been specified
2084 // and this does not contain the host architecture so dump all the slices.
2085 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
2086 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2087 E = UB->end_objects();
2088 I != E; ++I) {
Kevin Enderby9acb1092016-05-31 20:35:34 +00002089 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002090 std::string ArchitectureName = "";
2091 if (moreThanOneArch)
Kevin Enderby59343a92016-12-16 22:54:02 +00002092 ArchitectureName = I->getArchFlagName();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002093 if (ObjOrErr) {
2094 ObjectFile &Obj = *ObjOrErr.get();
2095 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002096 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Kevin Enderby9acb1092016-05-31 20:35:34 +00002097 } else if (auto E = isNotObjectErrorInvalidFileType(
2098 ObjOrErr.takeError())) {
2099 report_error(StringRef(), Filename, std::move(E), ArchitectureName);
2100 continue;
Kevin Enderby42398052016-06-28 23:16:13 +00002101 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2102 I->getAsArchive()) {
Rafael Espindola0bfe8282014-12-09 21:05:36 +00002103 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002104 outs() << "Archive : " << Filename;
2105 if (!ArchitectureName.empty())
2106 outs() << " (architecture " << ArchitectureName << ")";
2107 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00002108 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00002109 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2110 ArchiveMemberOffsets, ArchitectureName);
Mehdi Amini41af4302016-11-11 04:28:40 +00002111 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00002112 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002113 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2114 if (!ChildOrErr) {
2115 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
Kevin Enderby9acb1092016-05-31 20:35:34 +00002116 report_error(Filename, C, std::move(E), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002117 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002118 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002119 if (MachOObjectFile *O =
2120 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2121 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002122 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
2123 ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002124 }
2125 }
Lang Hamesfc209622016-07-14 02:24:01 +00002126 if (Err)
2127 report_error(Filename, std::move(Err));
Kevin Enderby42398052016-06-28 23:16:13 +00002128 } else {
2129 consumeError(AOrErr.takeError());
2130 error("Mach-O universal file: " + Filename + " for architecture " +
Kevin Enderby59343a92016-12-16 22:54:02 +00002131 StringRef(I->getArchFlagName()) +
Kevin Enderby42398052016-06-28 23:16:13 +00002132 " is not a Mach-O file or an archive file");
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002133 }
2134 }
2135 return;
2136 }
2137 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
2138 if (!checkMachOAndArchFlags(O, Filename))
2139 return;
2140 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002141 ProcessMachO(Filename, MachOOF);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002142 } else
2143 errs() << "llvm-objdump: '" << Filename << "': "
2144 << "Object is not a Mach-O file type.\n";
Davide Italiano25d84582016-01-13 04:11:36 +00002145 return;
2146 }
2147 llvm_unreachable("Input object can't be invalid at this point");
Rafael Espindola9b709252013-04-13 01:45:40 +00002148}
2149
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002150// The block of info used by the Symbolizer call backs.
2151struct DisassembleInfo {
2152 bool verbose;
2153 MachOObjectFile *O;
2154 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00002155 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002156 std::vector<SectionRef> *Sections;
2157 const char *class_name;
2158 const char *selector_name;
2159 char *method;
Kevin Enderby04bf6932014-10-28 23:39:46 +00002160 char *demangled_name;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002161 uint64_t adrp_addr;
2162 uint32_t adrp_inst;
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00002163 std::unique_ptr<SymbolAddressMap> bindtable;
Kevin Enderbyaac75382015-10-08 16:56:35 +00002164 uint32_t depth;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002165};
2166
2167// SymbolizerGetOpInfo() is the operand information call back function.
2168// This is called to get the symbolic information for operand(s) of an
2169// instruction when it is being done. This routine does this from
2170// the relocation information, symbol table, etc. That block of information
2171// is a pointer to the struct DisassembleInfo that was passed when the
2172// disassembler context was created and passed to back to here when
2173// called back by the disassembler for instruction operands that could have
2174// relocation information. The address of the instruction containing operand is
2175// at the Pc parameter. The immediate value the operand has is passed in
2176// op_info->Value and is at Offset past the start of the instruction and has a
2177// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
2178// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
2179// names and addends of the symbolic expression to add for the operand. The
2180// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
2181// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002182static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
2183 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002184 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2185 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002186 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002187
2188 // Make sure all fields returned are zero if we don't set them.
2189 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
2190 op_info->Value = value;
2191
2192 // If the TagType is not the value 1 which it code knows about or if no
2193 // verbose symbolic information is wanted then just return 0, indicating no
2194 // information is being returned.
David Blaikie33dd45d02015-03-23 18:39:02 +00002195 if (TagType != 1 || !info->verbose)
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002196 return 0;
2197
2198 unsigned int Arch = info->O->getArch();
2199 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002200 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2201 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002202 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2203 // TODO:
2204 // Search the external relocation entries of a fully linked image
2205 // (if any) for an entry that matches this segment offset.
2206 // uint32_t seg_offset = (Pc + Offset);
2207 return 0;
2208 }
2209 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2210 // for an entry for this section offset.
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002211 uint32_t sect_addr = info->S.getAddress();
2212 uint32_t sect_offset = (Pc + Offset) - sect_addr;
2213 bool reloc_found = false;
2214 DataRefImpl Rel;
2215 MachO::any_relocation_info RE;
2216 bool isExtern = false;
2217 SymbolRef Symbol;
2218 bool r_scattered = false;
2219 uint32_t r_value, pair_r_value, r_type;
2220 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002221 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002222 if (RelocOffset == sect_offset) {
2223 Rel = Reloc.getRawDataRefImpl();
2224 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00002225 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002226 r_scattered = info->O->isRelocationScattered(RE);
2227 if (r_scattered) {
2228 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002229 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2230 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
2231 DataRefImpl RelNext = Rel;
2232 info->O->moveRelocationNext(RelNext);
2233 MachO::any_relocation_info RENext;
2234 RENext = info->O->getRelocation(RelNext);
2235 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002236 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002237 else
2238 return 0;
2239 }
2240 } else {
2241 isExtern = info->O->getPlainRelocationExternal(RE);
2242 if (isExtern) {
2243 symbol_iterator RelocSym = Reloc.getSymbol();
2244 Symbol = *RelocSym;
2245 }
2246 }
2247 reloc_found = true;
2248 break;
2249 }
2250 }
2251 if (reloc_found && isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002252 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002253 if (!SymName)
2254 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002255 const char *name = SymName->data();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002256 op_info->AddSymbol.Present = 1;
2257 op_info->AddSymbol.Name = name;
2258 // For i386 extern relocation entries the value in the instruction is
2259 // the offset from the symbol, and value is already set in op_info->Value.
2260 return 1;
2261 }
2262 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2263 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002264 const char *add = GuessSymbolName(r_value, info->AddrMap);
2265 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002266 uint32_t offset = value - (r_value - pair_r_value);
2267 op_info->AddSymbol.Present = 1;
2268 if (add != nullptr)
2269 op_info->AddSymbol.Name = add;
2270 else
2271 op_info->AddSymbol.Value = r_value;
2272 op_info->SubtractSymbol.Present = 1;
2273 if (sub != nullptr)
2274 op_info->SubtractSymbol.Name = sub;
2275 else
2276 op_info->SubtractSymbol.Value = pair_r_value;
2277 op_info->Value = offset;
2278 return 1;
2279 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002280 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002281 }
2282 if (Arch == Triple::x86_64) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002283 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2284 return 0;
Kevin Enderbyabf10f22017-06-22 17:41:22 +00002285 // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external
2286 // relocation entries of a linked image (if any) for an entry that matches
2287 // this segment offset.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002288 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
Kevin Enderbyabf10f22017-06-22 17:41:22 +00002289 uint64_t seg_offset = Pc + Offset;
2290 bool reloc_found = false;
2291 DataRefImpl Rel;
2292 MachO::any_relocation_info RE;
2293 bool isExtern = false;
2294 SymbolRef Symbol;
2295 for (const RelocationRef &Reloc : info->O->external_relocations()) {
2296 uint64_t RelocOffset = Reloc.getOffset();
2297 if (RelocOffset == seg_offset) {
2298 Rel = Reloc.getRawDataRefImpl();
2299 RE = info->O->getRelocation(Rel);
2300 // external relocation entries should always be external.
2301 isExtern = info->O->getPlainRelocationExternal(RE);
2302 if (isExtern) {
2303 symbol_iterator RelocSym = Reloc.getSymbol();
2304 Symbol = *RelocSym;
2305 }
2306 reloc_found = true;
2307 break;
2308 }
2309 }
2310 if (reloc_found && isExtern) {
2311 // The Value passed in will be adjusted by the Pc if the instruction
2312 // adds the Pc. But for x86_64 external relocation entries the Value
2313 // is the offset from the external symbol.
2314 if (info->O->getAnyRelocationPCRel(RE))
2315 op_info->Value -= Pc + Offset + Size;
2316 Expected<StringRef> SymName = Symbol.getName();
2317 if (!SymName)
2318 report_error(info->O->getFileName(), SymName.takeError());
2319 const char *name = SymName->data();
2320 op_info->AddSymbol.Present = 1;
2321 op_info->AddSymbol.Name = name;
2322 return 1;
2323 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002324 return 0;
2325 }
2326 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2327 // for an entry for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00002328 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002329 uint64_t sect_offset = (Pc + Offset) - sect_addr;
2330 bool reloc_found = false;
2331 DataRefImpl Rel;
2332 MachO::any_relocation_info RE;
2333 bool isExtern = false;
2334 SymbolRef Symbol;
2335 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002336 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002337 if (RelocOffset == sect_offset) {
2338 Rel = Reloc.getRawDataRefImpl();
2339 RE = info->O->getRelocation(Rel);
2340 // NOTE: Scattered relocations don't exist on x86_64.
2341 isExtern = info->O->getPlainRelocationExternal(RE);
2342 if (isExtern) {
2343 symbol_iterator RelocSym = Reloc.getSymbol();
2344 Symbol = *RelocSym;
2345 }
2346 reloc_found = true;
2347 break;
2348 }
2349 }
2350 if (reloc_found && isExtern) {
2351 // The Value passed in will be adjusted by the Pc if the instruction
2352 // adds the Pc. But for x86_64 external relocation entries the Value
2353 // is the offset from the external symbol.
2354 if (info->O->getAnyRelocationPCRel(RE))
2355 op_info->Value -= Pc + Offset + Size;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002356 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002357 if (!SymName)
2358 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002359 const char *name = SymName->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002360 unsigned Type = info->O->getAnyRelocationType(RE);
2361 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
2362 DataRefImpl RelNext = Rel;
2363 info->O->moveRelocationNext(RelNext);
2364 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2365 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
2366 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
2367 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
2368 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
2369 op_info->SubtractSymbol.Present = 1;
2370 op_info->SubtractSymbol.Name = name;
2371 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
2372 Symbol = *RelocSymNext;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002373 Expected<StringRef> SymNameNext = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002374 if (!SymNameNext)
2375 report_error(info->O->getFileName(), SymNameNext.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002376 name = SymNameNext->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002377 }
2378 }
2379 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
2380 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
2381 op_info->AddSymbol.Present = 1;
2382 op_info->AddSymbol.Name = name;
2383 return 1;
2384 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002385 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002386 }
2387 if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002388 if (Offset != 0 || (Size != 4 && Size != 2))
2389 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002390 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2391 // TODO:
2392 // Search the external relocation entries of a fully linked image
2393 // (if any) for an entry that matches this segment offset.
2394 // uint32_t seg_offset = (Pc + Offset);
2395 return 0;
2396 }
2397 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2398 // for an entry for this section offset.
Kevin Enderby930fdc72014-11-06 19:00:13 +00002399 uint32_t sect_addr = info->S.getAddress();
2400 uint32_t sect_offset = (Pc + Offset) - sect_addr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002401 DataRefImpl Rel;
2402 MachO::any_relocation_info RE;
2403 bool isExtern = false;
2404 SymbolRef Symbol;
2405 bool r_scattered = false;
2406 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
David Blaikie33dd45d02015-03-23 18:39:02 +00002407 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002408 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2409 uint64_t RelocOffset = Reloc.getOffset();
2410 return RelocOffset == sect_offset;
2411 });
David Blaikie33dd45d02015-03-23 18:39:02 +00002412
2413 if (Reloc == info->S.relocations().end())
2414 return 0;
2415
2416 Rel = Reloc->getRawDataRefImpl();
2417 RE = info->O->getRelocation(Rel);
2418 r_length = info->O->getAnyRelocationLength(RE);
2419 r_scattered = info->O->isRelocationScattered(RE);
2420 if (r_scattered) {
2421 r_value = info->O->getScatteredRelocationValue(RE);
2422 r_type = info->O->getScatteredRelocationType(RE);
2423 } else {
2424 r_type = info->O->getAnyRelocationType(RE);
2425 isExtern = info->O->getPlainRelocationExternal(RE);
2426 if (isExtern) {
2427 symbol_iterator RelocSym = Reloc->getSymbol();
2428 Symbol = *RelocSym;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002429 }
2430 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002431 if (r_type == MachO::ARM_RELOC_HALF ||
2432 r_type == MachO::ARM_RELOC_SECTDIFF ||
2433 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
2434 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2435 DataRefImpl RelNext = Rel;
2436 info->O->moveRelocationNext(RelNext);
2437 MachO::any_relocation_info RENext;
2438 RENext = info->O->getRelocation(RelNext);
2439 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2440 if (info->O->isRelocationScattered(RENext))
2441 pair_r_value = info->O->getScatteredRelocationValue(RENext);
2442 }
2443
2444 if (isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002445 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002446 if (!SymName)
2447 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002448 const char *name = SymName->data();
Kevin Enderby930fdc72014-11-06 19:00:13 +00002449 op_info->AddSymbol.Present = 1;
2450 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002451 switch (r_type) {
2452 case MachO::ARM_RELOC_HALF:
2453 if ((r_length & 0x1) == 1) {
2454 op_info->Value = value << 16 | other_half;
2455 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2456 } else {
2457 op_info->Value = other_half << 16 | value;
2458 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00002459 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002460 break;
2461 default:
2462 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002463 }
2464 return 1;
2465 }
2466 // If we have a branch that is not an external relocation entry then
2467 // return 0 so the code in tryAddingSymbolicOperand() can use the
2468 // SymbolLookUp call back with the branch target address to look up the
Simon Pilgrimdae11f72016-11-20 13:31:13 +00002469 // symbol and possibility add an annotation for a symbol stub.
David Blaikie33dd45d02015-03-23 18:39:02 +00002470 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2471 r_type == MachO::ARM_THUMB_RELOC_BR22))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002472 return 0;
2473
2474 uint32_t offset = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002475 if (r_type == MachO::ARM_RELOC_HALF ||
2476 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2477 if ((r_length & 0x1) == 1)
2478 value = value << 16 | other_half;
2479 else
2480 value = other_half << 16 | value;
2481 }
2482 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2483 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2484 offset = value - r_value;
2485 value = r_value;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002486 }
2487
David Blaikie33dd45d02015-03-23 18:39:02 +00002488 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002489 if ((r_length & 0x1) == 1)
2490 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2491 else
2492 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002493 const char *add = GuessSymbolName(r_value, info->AddrMap);
2494 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002495 int32_t offset = value - (r_value - pair_r_value);
2496 op_info->AddSymbol.Present = 1;
2497 if (add != nullptr)
2498 op_info->AddSymbol.Name = add;
2499 else
2500 op_info->AddSymbol.Value = r_value;
2501 op_info->SubtractSymbol.Present = 1;
2502 if (sub != nullptr)
2503 op_info->SubtractSymbol.Name = sub;
2504 else
2505 op_info->SubtractSymbol.Value = pair_r_value;
2506 op_info->Value = offset;
2507 return 1;
2508 }
2509
Kevin Enderby930fdc72014-11-06 19:00:13 +00002510 op_info->AddSymbol.Present = 1;
2511 op_info->Value = offset;
David Blaikie33dd45d02015-03-23 18:39:02 +00002512 if (r_type == MachO::ARM_RELOC_HALF) {
2513 if ((r_length & 0x1) == 1)
2514 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2515 else
2516 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002517 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002518 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002519 if (add != nullptr) {
2520 op_info->AddSymbol.Name = add;
2521 return 1;
2522 }
2523 op_info->AddSymbol.Value = value;
2524 return 1;
David Blaikie33dd45d02015-03-23 18:39:02 +00002525 }
2526 if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002527 if (Offset != 0 || Size != 4)
2528 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002529 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2530 // TODO:
2531 // Search the external relocation entries of a fully linked image
2532 // (if any) for an entry that matches this segment offset.
2533 // uint64_t seg_offset = (Pc + Offset);
2534 return 0;
2535 }
2536 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2537 // for an entry for this section offset.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002538 uint64_t sect_addr = info->S.getAddress();
2539 uint64_t sect_offset = (Pc + Offset) - sect_addr;
David Blaikie33dd45d02015-03-23 18:39:02 +00002540 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002541 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2542 uint64_t RelocOffset = Reloc.getOffset();
2543 return RelocOffset == sect_offset;
2544 });
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002545
David Blaikie33dd45d02015-03-23 18:39:02 +00002546 if (Reloc == info->S.relocations().end())
2547 return 0;
2548
2549 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2550 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2551 uint32_t r_type = info->O->getAnyRelocationType(RE);
2552 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2553 DataRefImpl RelNext = Rel;
2554 info->O->moveRelocationNext(RelNext);
2555 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2556 if (value == 0) {
2557 value = info->O->getPlainRelocationSymbolNum(RENext);
2558 op_info->Value = value;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002559 }
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002560 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002561 // NOTE: Scattered relocations don't exist on arm64.
2562 if (!info->O->getPlainRelocationExternal(RE))
2563 return 0;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002564 Expected<StringRef> SymName = Reloc->getSymbol()->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002565 if (!SymName)
2566 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002567 const char *name = SymName->data();
David Blaikie33dd45d02015-03-23 18:39:02 +00002568 op_info->AddSymbol.Present = 1;
2569 op_info->AddSymbol.Name = name;
2570
2571 switch (r_type) {
2572 case MachO::ARM64_RELOC_PAGE21:
2573 /* @page */
2574 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2575 break;
2576 case MachO::ARM64_RELOC_PAGEOFF12:
2577 /* @pageoff */
2578 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2579 break;
2580 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2581 /* @gotpage */
2582 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2583 break;
2584 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2585 /* @gotpageoff */
2586 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2587 break;
2588 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2589 /* @tvlppage is not implemented in llvm-mc */
2590 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2591 break;
2592 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2593 /* @tvlppageoff is not implemented in llvm-mc */
2594 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2595 break;
2596 default:
2597 case MachO::ARM64_RELOC_BRANCH26:
2598 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2599 break;
2600 }
2601 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002602 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002603 return 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002604}
2605
Kevin Enderbybf246f52014-09-24 23:08:22 +00002606// GuessCstringPointer is passed the address of what might be a pointer to a
2607// literal string in a cstring section. If that address is in a cstring section
2608// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002609static const char *GuessCstringPointer(uint64_t ReferenceValue,
2610 struct DisassembleInfo *info) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002611 for (const auto &Load : info->O->load_commands()) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002612 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2613 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2614 for (unsigned J = 0; J < Seg.nsects; ++J) {
2615 MachO::section_64 Sec = info->O->getSection64(Load, J);
2616 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2617 if (section_type == MachO::S_CSTRING_LITERALS &&
2618 ReferenceValue >= Sec.addr &&
2619 ReferenceValue < Sec.addr + Sec.size) {
2620 uint64_t sect_offset = ReferenceValue - Sec.addr;
2621 uint64_t object_offset = Sec.offset + sect_offset;
2622 StringRef MachOContents = info->O->getData();
2623 uint64_t object_size = MachOContents.size();
2624 const char *object_addr = (const char *)MachOContents.data();
2625 if (object_offset < object_size) {
2626 const char *name = object_addr + object_offset;
2627 return name;
2628 } else {
2629 return nullptr;
2630 }
2631 }
2632 }
2633 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2634 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2635 for (unsigned J = 0; J < Seg.nsects; ++J) {
2636 MachO::section Sec = info->O->getSection(Load, J);
2637 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2638 if (section_type == MachO::S_CSTRING_LITERALS &&
2639 ReferenceValue >= Sec.addr &&
2640 ReferenceValue < Sec.addr + Sec.size) {
2641 uint64_t sect_offset = ReferenceValue - Sec.addr;
2642 uint64_t object_offset = Sec.offset + sect_offset;
2643 StringRef MachOContents = info->O->getData();
2644 uint64_t object_size = MachOContents.size();
2645 const char *object_addr = (const char *)MachOContents.data();
2646 if (object_offset < object_size) {
2647 const char *name = object_addr + object_offset;
2648 return name;
2649 } else {
2650 return nullptr;
2651 }
2652 }
2653 }
2654 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002655 }
2656 return nullptr;
2657}
2658
Kevin Enderby85974882014-09-26 22:20:44 +00002659// GuessIndirectSymbol returns the name of the indirect symbol for the
2660// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2661// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2662// symbol name being referenced by the stub or pointer.
2663static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2664 struct DisassembleInfo *info) {
Kevin Enderby85974882014-09-26 22:20:44 +00002665 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2666 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002667 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby85974882014-09-26 22:20:44 +00002668 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2669 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2670 for (unsigned J = 0; J < Seg.nsects; ++J) {
2671 MachO::section_64 Sec = info->O->getSection64(Load, J);
2672 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2673 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2674 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2675 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2676 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2677 section_type == MachO::S_SYMBOL_STUBS) &&
2678 ReferenceValue >= Sec.addr &&
2679 ReferenceValue < Sec.addr + Sec.size) {
2680 uint32_t stride;
2681 if (section_type == MachO::S_SYMBOL_STUBS)
2682 stride = Sec.reserved2;
2683 else
2684 stride = 8;
2685 if (stride == 0)
2686 return nullptr;
2687 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2688 if (index < Dysymtab.nindirectsyms) {
2689 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002690 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002691 if (indirect_symbol < Symtab.nsyms) {
2692 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2693 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002694 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002695 if (!SymName)
2696 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002697 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002698 return name;
2699 }
2700 }
2701 }
2702 }
2703 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2704 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2705 for (unsigned J = 0; J < Seg.nsects; ++J) {
2706 MachO::section Sec = info->O->getSection(Load, J);
2707 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2708 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2709 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2710 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2711 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2712 section_type == MachO::S_SYMBOL_STUBS) &&
2713 ReferenceValue >= Sec.addr &&
2714 ReferenceValue < Sec.addr + Sec.size) {
2715 uint32_t stride;
2716 if (section_type == MachO::S_SYMBOL_STUBS)
2717 stride = Sec.reserved2;
2718 else
2719 stride = 4;
2720 if (stride == 0)
2721 return nullptr;
2722 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2723 if (index < Dysymtab.nindirectsyms) {
2724 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002725 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002726 if (indirect_symbol < Symtab.nsyms) {
2727 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2728 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002729 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002730 if (!SymName)
2731 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002732 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002733 return name;
2734 }
2735 }
2736 }
2737 }
2738 }
Kevin Enderby85974882014-09-26 22:20:44 +00002739 }
2740 return nullptr;
2741}
2742
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002743// method_reference() is called passing it the ReferenceName that might be
2744// a reference it to an Objective-C method call. If so then it allocates and
2745// assembles a method call string with the values last seen and saved in
2746// the DisassembleInfo's class_name and selector_name fields. This is saved
2747// into the method field of the info and any previous string is free'ed.
2748// Then the class_name field in the info is set to nullptr. The method call
2749// string is set into ReferenceName and ReferenceType is set to
2750// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2751// then both ReferenceType and ReferenceName are left unchanged.
2752static void method_reference(struct DisassembleInfo *info,
2753 uint64_t *ReferenceType,
2754 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002755 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002756 if (*ReferenceName != nullptr) {
2757 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002758 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002759 if (info->method != nullptr)
2760 free(info->method);
2761 if (info->class_name != nullptr) {
2762 info->method = (char *)malloc(5 + strlen(info->class_name) +
2763 strlen(info->selector_name));
2764 if (info->method != nullptr) {
2765 strcpy(info->method, "+[");
2766 strcat(info->method, info->class_name);
2767 strcat(info->method, " ");
2768 strcat(info->method, info->selector_name);
2769 strcat(info->method, "]");
2770 *ReferenceName = info->method;
2771 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2772 }
2773 } else {
2774 info->method = (char *)malloc(9 + strlen(info->selector_name));
2775 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002776 if (Arch == Triple::x86_64)
2777 strcpy(info->method, "-[%rdi ");
2778 else if (Arch == Triple::aarch64)
2779 strcpy(info->method, "-[x0 ");
2780 else
2781 strcpy(info->method, "-[r? ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002782 strcat(info->method, info->selector_name);
2783 strcat(info->method, "]");
2784 *ReferenceName = info->method;
2785 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2786 }
2787 }
2788 info->class_name = nullptr;
2789 }
2790 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002791 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002792 if (info->method != nullptr)
2793 free(info->method);
2794 info->method = (char *)malloc(17 + strlen(info->selector_name));
2795 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002796 if (Arch == Triple::x86_64)
2797 strcpy(info->method, "-[[%rdi super] ");
2798 else if (Arch == Triple::aarch64)
2799 strcpy(info->method, "-[[x0 super] ");
2800 else
2801 strcpy(info->method, "-[[r? super] ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002802 strcat(info->method, info->selector_name);
2803 strcat(info->method, "]");
2804 *ReferenceName = info->method;
2805 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2806 }
2807 info->class_name = nullptr;
2808 }
2809 }
2810 }
2811}
2812
2813// GuessPointerPointer() is passed the address of what might be a pointer to
2814// a reference to an Objective-C class, selector, message ref or cfstring.
2815// If so the value of the pointer is returned and one of the booleans are set
2816// to true. If not zero is returned and all the booleans are set to false.
2817static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2818 struct DisassembleInfo *info,
2819 bool &classref, bool &selref, bool &msgref,
2820 bool &cfstring) {
2821 classref = false;
2822 selref = false;
2823 msgref = false;
2824 cfstring = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002825 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002826 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2827 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2828 for (unsigned J = 0; J < Seg.nsects; ++J) {
2829 MachO::section_64 Sec = info->O->getSection64(Load, J);
2830 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2831 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2832 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2833 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2834 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2835 ReferenceValue >= Sec.addr &&
2836 ReferenceValue < Sec.addr + Sec.size) {
2837 uint64_t sect_offset = ReferenceValue - Sec.addr;
2838 uint64_t object_offset = Sec.offset + sect_offset;
2839 StringRef MachOContents = info->O->getData();
2840 uint64_t object_size = MachOContents.size();
2841 const char *object_addr = (const char *)MachOContents.data();
2842 if (object_offset < object_size) {
2843 uint64_t pointer_value;
2844 memcpy(&pointer_value, object_addr + object_offset,
2845 sizeof(uint64_t));
2846 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2847 sys::swapByteOrder(pointer_value);
2848 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2849 selref = true;
2850 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2851 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2852 classref = true;
2853 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2854 ReferenceValue + 8 < Sec.addr + Sec.size) {
2855 msgref = true;
2856 memcpy(&pointer_value, object_addr + object_offset + 8,
2857 sizeof(uint64_t));
2858 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2859 sys::swapByteOrder(pointer_value);
2860 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2861 cfstring = true;
2862 return pointer_value;
2863 } else {
2864 return 0;
2865 }
2866 }
2867 }
2868 }
2869 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002870 }
2871 return 0;
2872}
2873
2874// get_pointer_64 returns a pointer to the bytes in the object file at the
2875// Address from a section in the Mach-O file. And indirectly returns the
2876// offset into the section, number of bytes left in the section past the offset
2877// and which section is was being referenced. If the Address is not in a
2878// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002879static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2880 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002881 DisassembleInfo *info,
2882 bool objc_only = false) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002883 offset = 0;
2884 left = 0;
2885 S = SectionRef();
2886 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2887 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2888 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
Kevin Enderby46e642f2015-10-08 22:50:55 +00002889 if (SectSize == 0)
2890 continue;
Kevin Enderby846c0002015-04-16 17:19:59 +00002891 if (objc_only) {
2892 StringRef SectName;
2893 ((*(info->Sections))[SectIdx]).getName(SectName);
2894 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2895 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2896 if (SegName != "__OBJC" && SectName != "__cstring")
2897 continue;
2898 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002899 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2900 S = (*(info->Sections))[SectIdx];
2901 offset = Address - SectAddress;
2902 left = SectSize - offset;
2903 StringRef SectContents;
2904 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2905 return SectContents.data() + offset;
2906 }
2907 }
2908 return nullptr;
2909}
2910
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002911static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2912 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002913 DisassembleInfo *info,
2914 bool objc_only = false) {
2915 return get_pointer_64(Address, offset, left, S, info, objc_only);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002916}
2917
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002918// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2919// the symbol indirectly through n_value. Based on the relocation information
2920// for the specified section offset in the specified section reference.
Kevin Enderby0fc11822015-04-01 20:57:01 +00002921// If no relocation information is found and a non-zero ReferenceValue for the
2922// symbol is passed, look up that address in the info's AddrMap.
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00002923static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2924 DisassembleInfo *info, uint64_t &n_value,
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002925 uint64_t ReferenceValue = 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002926 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002927 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002928 return nullptr;
2929
2930 // See if there is an external relocation entry at the sect_offset.
2931 bool reloc_found = false;
2932 DataRefImpl Rel;
2933 MachO::any_relocation_info RE;
2934 bool isExtern = false;
2935 SymbolRef Symbol;
2936 for (const RelocationRef &Reloc : S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002937 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002938 if (RelocOffset == sect_offset) {
2939 Rel = Reloc.getRawDataRefImpl();
2940 RE = info->O->getRelocation(Rel);
2941 if (info->O->isRelocationScattered(RE))
2942 continue;
2943 isExtern = info->O->getPlainRelocationExternal(RE);
2944 if (isExtern) {
2945 symbol_iterator RelocSym = Reloc.getSymbol();
2946 Symbol = *RelocSym;
2947 }
2948 reloc_found = true;
2949 break;
2950 }
2951 }
2952 // If there is an external relocation entry for a symbol in this section
2953 // at this section_offset then use that symbol's value for the n_value
2954 // and return its name.
2955 const char *SymbolName = nullptr;
2956 if (reloc_found && isExtern) {
Rafael Espindoladea00162015-07-03 17:44:18 +00002957 n_value = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002958 Expected<StringRef> NameOrError = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002959 if (!NameOrError)
2960 report_error(info->O->getFileName(), NameOrError.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002961 StringRef Name = *NameOrError;
2962 if (!Name.empty()) {
2963 SymbolName = Name.data();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002964 return SymbolName;
2965 }
2966 }
2967
2968 // TODO: For fully linked images, look through the external relocation
2969 // entries off the dynamic symtab command. For these the r_offset is from the
2970 // start of the first writeable segment in the Mach-O file. So the offset
2971 // to this section from that segment is passed to this routine by the caller,
2972 // as the database_offset. Which is the difference of the section's starting
2973 // address and the first writable segment.
2974 //
2975 // NOTE: need add passing the database_offset to this routine.
2976
Kevin Enderby0fc11822015-04-01 20:57:01 +00002977 // We did not find an external relocation entry so look up the ReferenceValue
2978 // as an address of a symbol and if found return that symbol's name.
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002979 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002980
2981 return SymbolName;
2982}
2983
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002984static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
2985 DisassembleInfo *info,
2986 uint32_t ReferenceValue) {
2987 uint64_t n_value64;
2988 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
2989}
2990
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002991// These are structs in the Objective-C meta data and read to produce the
2992// comments for disassembly. While these are part of the ABI they are no
Zachary Turner264b5d92017-06-07 03:48:56 +00002993// public defintions. So the are here not in include/llvm/BinaryFormat/MachO.h
2994// .
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002995
2996// The cfstring object in a 64-bit Mach-O file.
2997struct cfstring64_t {
2998 uint64_t isa; // class64_t * (64-bit pointer)
2999 uint64_t flags; // flag bits
3000 uint64_t characters; // char * (64-bit pointer)
3001 uint64_t length; // number of non-NULL characters in above
3002};
3003
3004// The class object in a 64-bit Mach-O file.
3005struct class64_t {
3006 uint64_t isa; // class64_t * (64-bit pointer)
3007 uint64_t superclass; // class64_t * (64-bit pointer)
3008 uint64_t cache; // Cache (64-bit pointer)
3009 uint64_t vtable; // IMP * (64-bit pointer)
3010 uint64_t data; // class_ro64_t * (64-bit pointer)
3011};
3012
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003013struct class32_t {
3014 uint32_t isa; /* class32_t * (32-bit pointer) */
3015 uint32_t superclass; /* class32_t * (32-bit pointer) */
3016 uint32_t cache; /* Cache (32-bit pointer) */
3017 uint32_t vtable; /* IMP * (32-bit pointer) */
3018 uint32_t data; /* class_ro32_t * (32-bit pointer) */
3019};
3020
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003021struct class_ro64_t {
3022 uint32_t flags;
3023 uint32_t instanceStart;
3024 uint32_t instanceSize;
3025 uint32_t reserved;
3026 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
3027 uint64_t name; // const char * (64-bit pointer)
3028 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
3029 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
3030 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
3031 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
3032 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
3033};
3034
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003035struct class_ro32_t {
3036 uint32_t flags;
3037 uint32_t instanceStart;
3038 uint32_t instanceSize;
3039 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
3040 uint32_t name; /* const char * (32-bit pointer) */
3041 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
3042 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
3043 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
3044 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
3045 uint32_t baseProperties; /* const struct objc_property_list *
3046 (32-bit pointer) */
3047};
3048
3049/* Values for class_ro{64,32}_t->flags */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003050#define RO_META (1 << 0)
3051#define RO_ROOT (1 << 1)
3052#define RO_HAS_CXX_STRUCTORS (1 << 2)
3053
3054struct method_list64_t {
3055 uint32_t entsize;
3056 uint32_t count;
3057 /* struct method64_t first; These structures follow inline */
3058};
3059
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003060struct method_list32_t {
3061 uint32_t entsize;
3062 uint32_t count;
3063 /* struct method32_t first; These structures follow inline */
3064};
3065
Kevin Enderby0fc11822015-04-01 20:57:01 +00003066struct method64_t {
3067 uint64_t name; /* SEL (64-bit pointer) */
3068 uint64_t types; /* const char * (64-bit pointer) */
3069 uint64_t imp; /* IMP (64-bit pointer) */
3070};
3071
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003072struct method32_t {
3073 uint32_t name; /* SEL (32-bit pointer) */
3074 uint32_t types; /* const char * (32-bit pointer) */
3075 uint32_t imp; /* IMP (32-bit pointer) */
3076};
3077
Kevin Enderby0fc11822015-04-01 20:57:01 +00003078struct protocol_list64_t {
3079 uint64_t count; /* uintptr_t (a 64-bit value) */
3080 /* struct protocol64_t * list[0]; These pointers follow inline */
3081};
3082
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003083struct protocol_list32_t {
3084 uint32_t count; /* uintptr_t (a 32-bit value) */
3085 /* struct protocol32_t * list[0]; These pointers follow inline */
3086};
3087
Kevin Enderby0fc11822015-04-01 20:57:01 +00003088struct protocol64_t {
3089 uint64_t isa; /* id * (64-bit pointer) */
3090 uint64_t name; /* const char * (64-bit pointer) */
3091 uint64_t protocols; /* struct protocol_list64_t *
3092 (64-bit pointer) */
3093 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
3094 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
3095 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
3096 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
3097 uint64_t instanceProperties; /* struct objc_property_list *
3098 (64-bit pointer) */
3099};
3100
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003101struct protocol32_t {
3102 uint32_t isa; /* id * (32-bit pointer) */
3103 uint32_t name; /* const char * (32-bit pointer) */
3104 uint32_t protocols; /* struct protocol_list_t *
3105 (32-bit pointer) */
3106 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
3107 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
3108 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
3109 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
3110 uint32_t instanceProperties; /* struct objc_property_list *
3111 (32-bit pointer) */
3112};
3113
Kevin Enderby0fc11822015-04-01 20:57:01 +00003114struct ivar_list64_t {
3115 uint32_t entsize;
3116 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003117 /* struct ivar64_t first; These structures follow inline */
3118};
3119
3120struct ivar_list32_t {
3121 uint32_t entsize;
3122 uint32_t count;
3123 /* struct ivar32_t first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003124};
3125
3126struct ivar64_t {
3127 uint64_t offset; /* uintptr_t * (64-bit pointer) */
3128 uint64_t name; /* const char * (64-bit pointer) */
3129 uint64_t type; /* const char * (64-bit pointer) */
3130 uint32_t alignment;
3131 uint32_t size;
3132};
3133
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003134struct ivar32_t {
3135 uint32_t offset; /* uintptr_t * (32-bit pointer) */
3136 uint32_t name; /* const char * (32-bit pointer) */
3137 uint32_t type; /* const char * (32-bit pointer) */
3138 uint32_t alignment;
3139 uint32_t size;
3140};
3141
Kevin Enderby0fc11822015-04-01 20:57:01 +00003142struct objc_property_list64 {
3143 uint32_t entsize;
3144 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003145 /* struct objc_property64 first; These structures follow inline */
3146};
3147
3148struct objc_property_list32 {
3149 uint32_t entsize;
3150 uint32_t count;
3151 /* struct objc_property32 first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003152};
3153
3154struct objc_property64 {
3155 uint64_t name; /* const char * (64-bit pointer) */
3156 uint64_t attributes; /* const char * (64-bit pointer) */
3157};
3158
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003159struct objc_property32 {
3160 uint32_t name; /* const char * (32-bit pointer) */
3161 uint32_t attributes; /* const char * (32-bit pointer) */
3162};
3163
Kevin Enderby0fc11822015-04-01 20:57:01 +00003164struct category64_t {
3165 uint64_t name; /* const char * (64-bit pointer) */
3166 uint64_t cls; /* struct class_t * (64-bit pointer) */
3167 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
3168 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
3169 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
3170 uint64_t instanceProperties; /* struct objc_property_list *
3171 (64-bit pointer) */
3172};
3173
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003174struct category32_t {
3175 uint32_t name; /* const char * (32-bit pointer) */
3176 uint32_t cls; /* struct class_t * (32-bit pointer) */
3177 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
3178 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
3179 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
3180 uint32_t instanceProperties; /* struct objc_property_list *
3181 (32-bit pointer) */
3182};
3183
Kevin Enderby0fc11822015-04-01 20:57:01 +00003184struct objc_image_info64 {
3185 uint32_t version;
3186 uint32_t flags;
3187};
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003188struct objc_image_info32 {
3189 uint32_t version;
3190 uint32_t flags;
3191};
Kevin Enderby846c0002015-04-16 17:19:59 +00003192struct imageInfo_t {
3193 uint32_t version;
3194 uint32_t flags;
3195};
Kevin Enderby0fc11822015-04-01 20:57:01 +00003196/* masks for objc_image_info.flags */
3197#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
3198#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
3199
3200struct message_ref64 {
3201 uint64_t imp; /* IMP (64-bit pointer) */
3202 uint64_t sel; /* SEL (64-bit pointer) */
3203};
3204
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003205struct message_ref32 {
3206 uint32_t imp; /* IMP (32-bit pointer) */
3207 uint32_t sel; /* SEL (32-bit pointer) */
3208};
3209
Kevin Enderby846c0002015-04-16 17:19:59 +00003210// Objective-C 1 (32-bit only) meta data structs.
3211
3212struct objc_module_t {
3213 uint32_t version;
3214 uint32_t size;
3215 uint32_t name; /* char * (32-bit pointer) */
3216 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
3217};
3218
3219struct objc_symtab_t {
3220 uint32_t sel_ref_cnt;
3221 uint32_t refs; /* SEL * (32-bit pointer) */
3222 uint16_t cls_def_cnt;
3223 uint16_t cat_def_cnt;
3224 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
3225};
3226
3227struct objc_class_t {
3228 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3229 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
3230 uint32_t name; /* const char * (32-bit pointer) */
3231 int32_t version;
3232 int32_t info;
3233 int32_t instance_size;
3234 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
3235 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
3236 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
3237 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
3238};
3239
3240#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
3241// class is not a metaclass
3242#define CLS_CLASS 0x1
3243// class is a metaclass
3244#define CLS_META 0x2
3245
3246struct objc_category_t {
3247 uint32_t category_name; /* char * (32-bit pointer) */
3248 uint32_t class_name; /* char * (32-bit pointer) */
3249 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
3250 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
3251 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
3252};
3253
3254struct objc_ivar_t {
3255 uint32_t ivar_name; /* char * (32-bit pointer) */
3256 uint32_t ivar_type; /* char * (32-bit pointer) */
3257 int32_t ivar_offset;
3258};
3259
3260struct objc_ivar_list_t {
3261 int32_t ivar_count;
3262 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
3263};
3264
3265struct objc_method_list_t {
3266 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
3267 int32_t method_count;
3268 // struct objc_method_t method_list[1]; /* variable length structure */
3269};
3270
3271struct objc_method_t {
3272 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3273 uint32_t method_types; /* char * (32-bit pointer) */
3274 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
3275 (32-bit pointer) */
3276};
3277
3278struct objc_protocol_list_t {
3279 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
3280 int32_t count;
3281 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
3282 // (32-bit pointer) */
3283};
3284
3285struct objc_protocol_t {
3286 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3287 uint32_t protocol_name; /* char * (32-bit pointer) */
3288 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
3289 uint32_t instance_methods; /* struct objc_method_description_list *
3290 (32-bit pointer) */
3291 uint32_t class_methods; /* struct objc_method_description_list *
3292 (32-bit pointer) */
3293};
3294
3295struct objc_method_description_list_t {
3296 int32_t count;
3297 // struct objc_method_description_t list[1];
3298};
3299
3300struct objc_method_description_t {
3301 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3302 uint32_t types; /* char * (32-bit pointer) */
3303};
3304
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003305inline void swapStruct(struct cfstring64_t &cfs) {
3306 sys::swapByteOrder(cfs.isa);
3307 sys::swapByteOrder(cfs.flags);
3308 sys::swapByteOrder(cfs.characters);
3309 sys::swapByteOrder(cfs.length);
3310}
3311
3312inline void swapStruct(struct class64_t &c) {
3313 sys::swapByteOrder(c.isa);
3314 sys::swapByteOrder(c.superclass);
3315 sys::swapByteOrder(c.cache);
3316 sys::swapByteOrder(c.vtable);
3317 sys::swapByteOrder(c.data);
3318}
3319
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003320inline void swapStruct(struct class32_t &c) {
3321 sys::swapByteOrder(c.isa);
3322 sys::swapByteOrder(c.superclass);
3323 sys::swapByteOrder(c.cache);
3324 sys::swapByteOrder(c.vtable);
3325 sys::swapByteOrder(c.data);
3326}
3327
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003328inline void swapStruct(struct class_ro64_t &cro) {
3329 sys::swapByteOrder(cro.flags);
3330 sys::swapByteOrder(cro.instanceStart);
3331 sys::swapByteOrder(cro.instanceSize);
3332 sys::swapByteOrder(cro.reserved);
3333 sys::swapByteOrder(cro.ivarLayout);
3334 sys::swapByteOrder(cro.name);
3335 sys::swapByteOrder(cro.baseMethods);
3336 sys::swapByteOrder(cro.baseProtocols);
3337 sys::swapByteOrder(cro.ivars);
3338 sys::swapByteOrder(cro.weakIvarLayout);
3339 sys::swapByteOrder(cro.baseProperties);
3340}
3341
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003342inline void swapStruct(struct class_ro32_t &cro) {
3343 sys::swapByteOrder(cro.flags);
3344 sys::swapByteOrder(cro.instanceStart);
3345 sys::swapByteOrder(cro.instanceSize);
3346 sys::swapByteOrder(cro.ivarLayout);
3347 sys::swapByteOrder(cro.name);
3348 sys::swapByteOrder(cro.baseMethods);
3349 sys::swapByteOrder(cro.baseProtocols);
3350 sys::swapByteOrder(cro.ivars);
3351 sys::swapByteOrder(cro.weakIvarLayout);
3352 sys::swapByteOrder(cro.baseProperties);
3353}
3354
Kevin Enderby0fc11822015-04-01 20:57:01 +00003355inline void swapStruct(struct method_list64_t &ml) {
3356 sys::swapByteOrder(ml.entsize);
3357 sys::swapByteOrder(ml.count);
3358}
3359
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003360inline void swapStruct(struct method_list32_t &ml) {
3361 sys::swapByteOrder(ml.entsize);
3362 sys::swapByteOrder(ml.count);
3363}
3364
Kevin Enderby0fc11822015-04-01 20:57:01 +00003365inline void swapStruct(struct method64_t &m) {
3366 sys::swapByteOrder(m.name);
3367 sys::swapByteOrder(m.types);
3368 sys::swapByteOrder(m.imp);
3369}
3370
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003371inline void swapStruct(struct method32_t &m) {
3372 sys::swapByteOrder(m.name);
3373 sys::swapByteOrder(m.types);
3374 sys::swapByteOrder(m.imp);
3375}
3376
Kevin Enderby0fc11822015-04-01 20:57:01 +00003377inline void swapStruct(struct protocol_list64_t &pl) {
3378 sys::swapByteOrder(pl.count);
3379}
3380
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003381inline void swapStruct(struct protocol_list32_t &pl) {
3382 sys::swapByteOrder(pl.count);
3383}
3384
Kevin Enderby0fc11822015-04-01 20:57:01 +00003385inline void swapStruct(struct protocol64_t &p) {
3386 sys::swapByteOrder(p.isa);
3387 sys::swapByteOrder(p.name);
3388 sys::swapByteOrder(p.protocols);
3389 sys::swapByteOrder(p.instanceMethods);
3390 sys::swapByteOrder(p.classMethods);
3391 sys::swapByteOrder(p.optionalInstanceMethods);
3392 sys::swapByteOrder(p.optionalClassMethods);
3393 sys::swapByteOrder(p.instanceProperties);
3394}
3395
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003396inline void swapStruct(struct protocol32_t &p) {
3397 sys::swapByteOrder(p.isa);
3398 sys::swapByteOrder(p.name);
3399 sys::swapByteOrder(p.protocols);
3400 sys::swapByteOrder(p.instanceMethods);
3401 sys::swapByteOrder(p.classMethods);
3402 sys::swapByteOrder(p.optionalInstanceMethods);
3403 sys::swapByteOrder(p.optionalClassMethods);
3404 sys::swapByteOrder(p.instanceProperties);
3405}
3406
Kevin Enderby0fc11822015-04-01 20:57:01 +00003407inline void swapStruct(struct ivar_list64_t &il) {
3408 sys::swapByteOrder(il.entsize);
3409 sys::swapByteOrder(il.count);
3410}
3411
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003412inline void swapStruct(struct ivar_list32_t &il) {
3413 sys::swapByteOrder(il.entsize);
3414 sys::swapByteOrder(il.count);
3415}
3416
Kevin Enderby0fc11822015-04-01 20:57:01 +00003417inline void swapStruct(struct ivar64_t &i) {
3418 sys::swapByteOrder(i.offset);
3419 sys::swapByteOrder(i.name);
3420 sys::swapByteOrder(i.type);
3421 sys::swapByteOrder(i.alignment);
3422 sys::swapByteOrder(i.size);
3423}
3424
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003425inline void swapStruct(struct ivar32_t &i) {
3426 sys::swapByteOrder(i.offset);
3427 sys::swapByteOrder(i.name);
3428 sys::swapByteOrder(i.type);
3429 sys::swapByteOrder(i.alignment);
3430 sys::swapByteOrder(i.size);
3431}
3432
Kevin Enderby0fc11822015-04-01 20:57:01 +00003433inline void swapStruct(struct objc_property_list64 &pl) {
3434 sys::swapByteOrder(pl.entsize);
3435 sys::swapByteOrder(pl.count);
3436}
3437
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003438inline void swapStruct(struct objc_property_list32 &pl) {
3439 sys::swapByteOrder(pl.entsize);
3440 sys::swapByteOrder(pl.count);
3441}
3442
Kevin Enderby0fc11822015-04-01 20:57:01 +00003443inline void swapStruct(struct objc_property64 &op) {
3444 sys::swapByteOrder(op.name);
3445 sys::swapByteOrder(op.attributes);
3446}
3447
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003448inline void swapStruct(struct objc_property32 &op) {
3449 sys::swapByteOrder(op.name);
3450 sys::swapByteOrder(op.attributes);
3451}
3452
Kevin Enderby0fc11822015-04-01 20:57:01 +00003453inline void swapStruct(struct category64_t &c) {
3454 sys::swapByteOrder(c.name);
3455 sys::swapByteOrder(c.cls);
3456 sys::swapByteOrder(c.instanceMethods);
3457 sys::swapByteOrder(c.classMethods);
3458 sys::swapByteOrder(c.protocols);
3459 sys::swapByteOrder(c.instanceProperties);
3460}
3461
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003462inline void swapStruct(struct category32_t &c) {
3463 sys::swapByteOrder(c.name);
3464 sys::swapByteOrder(c.cls);
3465 sys::swapByteOrder(c.instanceMethods);
3466 sys::swapByteOrder(c.classMethods);
3467 sys::swapByteOrder(c.protocols);
3468 sys::swapByteOrder(c.instanceProperties);
3469}
3470
Kevin Enderby0fc11822015-04-01 20:57:01 +00003471inline void swapStruct(struct objc_image_info64 &o) {
3472 sys::swapByteOrder(o.version);
3473 sys::swapByteOrder(o.flags);
3474}
3475
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003476inline void swapStruct(struct objc_image_info32 &o) {
3477 sys::swapByteOrder(o.version);
3478 sys::swapByteOrder(o.flags);
3479}
3480
Kevin Enderby846c0002015-04-16 17:19:59 +00003481inline void swapStruct(struct imageInfo_t &o) {
3482 sys::swapByteOrder(o.version);
3483 sys::swapByteOrder(o.flags);
3484}
3485
Kevin Enderby0fc11822015-04-01 20:57:01 +00003486inline void swapStruct(struct message_ref64 &mr) {
3487 sys::swapByteOrder(mr.imp);
3488 sys::swapByteOrder(mr.sel);
3489}
3490
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003491inline void swapStruct(struct message_ref32 &mr) {
3492 sys::swapByteOrder(mr.imp);
3493 sys::swapByteOrder(mr.sel);
3494}
3495
Kevin Enderby846c0002015-04-16 17:19:59 +00003496inline void swapStruct(struct objc_module_t &module) {
3497 sys::swapByteOrder(module.version);
3498 sys::swapByteOrder(module.size);
3499 sys::swapByteOrder(module.name);
3500 sys::swapByteOrder(module.symtab);
Jingyue Wufedecc42015-04-16 18:43:44 +00003501}
Kevin Enderby846c0002015-04-16 17:19:59 +00003502
3503inline void swapStruct(struct objc_symtab_t &symtab) {
3504 sys::swapByteOrder(symtab.sel_ref_cnt);
3505 sys::swapByteOrder(symtab.refs);
3506 sys::swapByteOrder(symtab.cls_def_cnt);
3507 sys::swapByteOrder(symtab.cat_def_cnt);
Jingyue Wufedecc42015-04-16 18:43:44 +00003508}
Kevin Enderby846c0002015-04-16 17:19:59 +00003509
3510inline void swapStruct(struct objc_class_t &objc_class) {
3511 sys::swapByteOrder(objc_class.isa);
3512 sys::swapByteOrder(objc_class.super_class);
3513 sys::swapByteOrder(objc_class.name);
3514 sys::swapByteOrder(objc_class.version);
3515 sys::swapByteOrder(objc_class.info);
3516 sys::swapByteOrder(objc_class.instance_size);
3517 sys::swapByteOrder(objc_class.ivars);
3518 sys::swapByteOrder(objc_class.methodLists);
3519 sys::swapByteOrder(objc_class.cache);
3520 sys::swapByteOrder(objc_class.protocols);
Jingyue Wufedecc42015-04-16 18:43:44 +00003521}
Kevin Enderby846c0002015-04-16 17:19:59 +00003522
3523inline void swapStruct(struct objc_category_t &objc_category) {
3524 sys::swapByteOrder(objc_category.category_name);
3525 sys::swapByteOrder(objc_category.class_name);
3526 sys::swapByteOrder(objc_category.instance_methods);
3527 sys::swapByteOrder(objc_category.class_methods);
3528 sys::swapByteOrder(objc_category.protocols);
3529}
3530
3531inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3532 sys::swapByteOrder(objc_ivar_list.ivar_count);
3533}
3534
3535inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3536 sys::swapByteOrder(objc_ivar.ivar_name);
3537 sys::swapByteOrder(objc_ivar.ivar_type);
3538 sys::swapByteOrder(objc_ivar.ivar_offset);
Jingyue Wufedecc42015-04-16 18:43:44 +00003539}
Kevin Enderby846c0002015-04-16 17:19:59 +00003540
3541inline void swapStruct(struct objc_method_list_t &method_list) {
3542 sys::swapByteOrder(method_list.obsolete);
3543 sys::swapByteOrder(method_list.method_count);
3544}
3545
3546inline void swapStruct(struct objc_method_t &method) {
3547 sys::swapByteOrder(method.method_name);
3548 sys::swapByteOrder(method.method_types);
3549 sys::swapByteOrder(method.method_imp);
3550}
3551
3552inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3553 sys::swapByteOrder(protocol_list.next);
3554 sys::swapByteOrder(protocol_list.count);
3555}
3556
3557inline void swapStruct(struct objc_protocol_t &protocol) {
3558 sys::swapByteOrder(protocol.isa);
3559 sys::swapByteOrder(protocol.protocol_name);
3560 sys::swapByteOrder(protocol.protocol_list);
3561 sys::swapByteOrder(protocol.instance_methods);
3562 sys::swapByteOrder(protocol.class_methods);
3563}
3564
3565inline void swapStruct(struct objc_method_description_list_t &mdl) {
3566 sys::swapByteOrder(mdl.count);
3567}
3568
3569inline void swapStruct(struct objc_method_description_t &md) {
3570 sys::swapByteOrder(md.name);
3571 sys::swapByteOrder(md.types);
3572}
3573
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003574static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3575 struct DisassembleInfo *info);
3576
3577// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3578// to an Objective-C class and returns the class name. It is also passed the
3579// address of the pointer, so when the pointer is zero as it can be in an .o
3580// file, that is used to look for an external relocation entry with a symbol
3581// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003582static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3583 uint64_t ReferenceValue,
3584 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003585 const char *r;
3586 uint32_t offset, left;
3587 SectionRef S;
3588
3589 // The pointer_value can be 0 in an object file and have a relocation
3590 // entry for the class symbol at the ReferenceValue (the address of the
3591 // pointer).
3592 if (pointer_value == 0) {
3593 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3594 if (r == nullptr || left < sizeof(uint64_t))
3595 return nullptr;
3596 uint64_t n_value;
3597 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3598 if (symbol_name == nullptr)
3599 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00003600 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003601 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3602 return class_name + 2;
3603 else
3604 return nullptr;
3605 }
3606
3607 // The case were the pointer_value is non-zero and points to a class defined
3608 // in this Mach-O file.
3609 r = get_pointer_64(pointer_value, offset, left, S, info);
3610 if (r == nullptr || left < sizeof(struct class64_t))
3611 return nullptr;
3612 struct class64_t c;
3613 memcpy(&c, r, sizeof(struct class64_t));
3614 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3615 swapStruct(c);
3616 if (c.data == 0)
3617 return nullptr;
3618 r = get_pointer_64(c.data, offset, left, S, info);
3619 if (r == nullptr || left < sizeof(struct class_ro64_t))
3620 return nullptr;
3621 struct class_ro64_t cro;
3622 memcpy(&cro, r, sizeof(struct class_ro64_t));
3623 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3624 swapStruct(cro);
3625 if (cro.name == 0)
3626 return nullptr;
3627 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3628 return name;
3629}
3630
3631// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3632// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003633static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3634 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003635 const char *r, *name;
3636 uint32_t offset, left;
3637 SectionRef S;
3638 struct cfstring64_t cfs;
3639 uint64_t cfs_characters;
3640
3641 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3642 if (r == nullptr || left < sizeof(struct cfstring64_t))
3643 return nullptr;
3644 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3645 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3646 swapStruct(cfs);
3647 if (cfs.characters == 0) {
3648 uint64_t n_value;
3649 const char *symbol_name = get_symbol_64(
3650 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3651 if (symbol_name == nullptr)
3652 return nullptr;
3653 cfs_characters = n_value;
3654 } else
3655 cfs_characters = cfs.characters;
3656 name = get_pointer_64(cfs_characters, offset, left, S, info);
3657
3658 return name;
3659}
3660
3661// get_objc2_64bit_selref() is used for disassembly and is passed a the address
3662// of a pointer to an Objective-C selector reference when the pointer value is
3663// zero as in a .o file and is likely to have a external relocation entry with
3664// who's symbol's n_value is the real pointer to the selector name. If that is
3665// the case the real pointer to the selector name is returned else 0 is
3666// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003667static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3668 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003669 uint32_t offset, left;
3670 SectionRef S;
3671
3672 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3673 if (r == nullptr || left < sizeof(uint64_t))
3674 return 0;
3675 uint64_t n_value;
3676 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3677 if (symbol_name == nullptr)
3678 return 0;
3679 return n_value;
3680}
3681
Kevin Enderby0fc11822015-04-01 20:57:01 +00003682static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3683 const char *sectname) {
3684 for (const SectionRef &Section : O->sections()) {
3685 StringRef SectName;
3686 Section.getName(SectName);
3687 DataRefImpl Ref = Section.getRawDataRefImpl();
3688 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3689 if (SegName == segname && SectName == sectname)
3690 return Section;
3691 }
3692 return SectionRef();
3693}
3694
3695static void
3696walk_pointer_list_64(const char *listname, const SectionRef S,
3697 MachOObjectFile *O, struct DisassembleInfo *info,
3698 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3699 if (S == SectionRef())
3700 return;
3701
3702 StringRef SectName;
3703 S.getName(SectName);
3704 DataRefImpl Ref = S.getRawDataRefImpl();
3705 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3706 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3707
3708 StringRef BytesStr;
3709 S.getContents(BytesStr);
3710 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3711
3712 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3713 uint32_t left = S.getSize() - i;
3714 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3715 uint64_t p = 0;
3716 memcpy(&p, Contents + i, size);
3717 if (i + sizeof(uint64_t) > S.getSize())
3718 outs() << listname << " list pointer extends past end of (" << SegName
3719 << "," << SectName << ") section\n";
3720 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3721
3722 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3723 sys::swapByteOrder(p);
3724
3725 uint64_t n_value = 0;
3726 const char *name = get_symbol_64(i, S, info, n_value, p);
3727 if (name == nullptr)
3728 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3729
3730 if (n_value != 0) {
3731 outs() << format("0x%" PRIx64, n_value);
3732 if (p != 0)
3733 outs() << " + " << format("0x%" PRIx64, p);
3734 } else
3735 outs() << format("0x%" PRIx64, p);
3736 if (name != nullptr)
3737 outs() << " " << name;
3738 outs() << "\n";
3739
3740 p += n_value;
3741 if (func)
3742 func(p, info);
3743 }
3744}
3745
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003746static void
3747walk_pointer_list_32(const char *listname, const SectionRef S,
3748 MachOObjectFile *O, struct DisassembleInfo *info,
3749 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3750 if (S == SectionRef())
3751 return;
3752
3753 StringRef SectName;
3754 S.getName(SectName);
3755 DataRefImpl Ref = S.getRawDataRefImpl();
3756 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3757 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3758
3759 StringRef BytesStr;
3760 S.getContents(BytesStr);
3761 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3762
3763 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3764 uint32_t left = S.getSize() - i;
3765 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3766 uint32_t p = 0;
3767 memcpy(&p, Contents + i, size);
3768 if (i + sizeof(uint32_t) > S.getSize())
3769 outs() << listname << " list pointer extends past end of (" << SegName
3770 << "," << SectName << ") section\n";
Kevin Enderbycf261312015-04-06 22:33:43 +00003771 uint32_t Address = S.getAddress() + i;
3772 outs() << format("%08" PRIx32, Address) << " ";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003773
3774 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3775 sys::swapByteOrder(p);
3776 outs() << format("0x%" PRIx32, p);
3777
3778 const char *name = get_symbol_32(i, S, info, p);
3779 if (name != nullptr)
3780 outs() << " " << name;
3781 outs() << "\n";
3782
3783 if (func)
3784 func(p, info);
3785 }
3786}
3787
3788static void print_layout_map(const char *layout_map, uint32_t left) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003789 if (layout_map == nullptr)
3790 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003791 outs() << " layout map: ";
3792 do {
3793 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3794 left--;
3795 layout_map++;
3796 } while (*layout_map != '\0' && left != 0);
3797 outs() << "\n";
3798}
3799
Kevin Enderby0fc11822015-04-01 20:57:01 +00003800static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3801 uint32_t offset, left;
3802 SectionRef S;
3803 const char *layout_map;
3804
3805 if (p == 0)
3806 return;
3807 layout_map = get_pointer_64(p, offset, left, S, info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003808 print_layout_map(layout_map, left);
3809}
3810
3811static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3812 uint32_t offset, left;
3813 SectionRef S;
3814 const char *layout_map;
3815
3816 if (p == 0)
3817 return;
3818 layout_map = get_pointer_32(p, offset, left, S, info);
3819 print_layout_map(layout_map, left);
Kevin Enderby0fc11822015-04-01 20:57:01 +00003820}
3821
3822static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3823 const char *indent) {
3824 struct method_list64_t ml;
3825 struct method64_t m;
3826 const char *r;
3827 uint32_t offset, xoffset, left, i;
3828 SectionRef S, xS;
3829 const char *name, *sym_name;
3830 uint64_t n_value;
3831
3832 r = get_pointer_64(p, offset, left, S, info);
3833 if (r == nullptr)
3834 return;
3835 memset(&ml, '\0', sizeof(struct method_list64_t));
3836 if (left < sizeof(struct method_list64_t)) {
3837 memcpy(&ml, r, left);
3838 outs() << " (method_list_t entends past the end of the section)\n";
3839 } else
3840 memcpy(&ml, r, sizeof(struct method_list64_t));
3841 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3842 swapStruct(ml);
3843 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3844 outs() << indent << "\t\t count " << ml.count << "\n";
3845
3846 p += sizeof(struct method_list64_t);
3847 offset += sizeof(struct method_list64_t);
3848 for (i = 0; i < ml.count; i++) {
3849 r = get_pointer_64(p, offset, left, S, info);
3850 if (r == nullptr)
3851 return;
3852 memset(&m, '\0', sizeof(struct method64_t));
3853 if (left < sizeof(struct method64_t)) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003854 memcpy(&m, r, left);
3855 outs() << indent << " (method_t extends past the end of the section)\n";
Kevin Enderby0fc11822015-04-01 20:57:01 +00003856 } else
3857 memcpy(&m, r, sizeof(struct method64_t));
3858 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3859 swapStruct(m);
3860
3861 outs() << indent << "\t\t name ";
3862 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3863 info, n_value, m.name);
3864 if (n_value != 0) {
3865 if (info->verbose && sym_name != nullptr)
3866 outs() << sym_name;
3867 else
3868 outs() << format("0x%" PRIx64, n_value);
3869 if (m.name != 0)
3870 outs() << " + " << format("0x%" PRIx64, m.name);
3871 } else
3872 outs() << format("0x%" PRIx64, m.name);
3873 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3874 if (name != nullptr)
3875 outs() << format(" %.*s", left, name);
3876 outs() << "\n";
3877
3878 outs() << indent << "\t\t types ";
3879 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3880 info, n_value, m.types);
3881 if (n_value != 0) {
3882 if (info->verbose && sym_name != nullptr)
3883 outs() << sym_name;
3884 else
3885 outs() << format("0x%" PRIx64, n_value);
3886 if (m.types != 0)
3887 outs() << " + " << format("0x%" PRIx64, m.types);
3888 } else
3889 outs() << format("0x%" PRIx64, m.types);
3890 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3891 if (name != nullptr)
3892 outs() << format(" %.*s", left, name);
3893 outs() << "\n";
3894
3895 outs() << indent << "\t\t imp ";
3896 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3897 n_value, m.imp);
3898 if (info->verbose && name == nullptr) {
3899 if (n_value != 0) {
3900 outs() << format("0x%" PRIx64, n_value) << " ";
3901 if (m.imp != 0)
3902 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3903 } else
3904 outs() << format("0x%" PRIx64, m.imp) << " ";
3905 }
3906 if (name != nullptr)
3907 outs() << name;
3908 outs() << "\n";
3909
3910 p += sizeof(struct method64_t);
3911 offset += sizeof(struct method64_t);
3912 }
3913}
3914
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003915static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3916 const char *indent) {
3917 struct method_list32_t ml;
3918 struct method32_t m;
Kevin Enderby846c0002015-04-16 17:19:59 +00003919 const char *r, *name;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003920 uint32_t offset, xoffset, left, i;
3921 SectionRef S, xS;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003922
3923 r = get_pointer_32(p, offset, left, S, info);
3924 if (r == nullptr)
3925 return;
3926 memset(&ml, '\0', sizeof(struct method_list32_t));
3927 if (left < sizeof(struct method_list32_t)) {
3928 memcpy(&ml, r, left);
3929 outs() << " (method_list_t entends past the end of the section)\n";
3930 } else
3931 memcpy(&ml, r, sizeof(struct method_list32_t));
3932 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3933 swapStruct(ml);
3934 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3935 outs() << indent << "\t\t count " << ml.count << "\n";
3936
3937 p += sizeof(struct method_list32_t);
3938 offset += sizeof(struct method_list32_t);
3939 for (i = 0; i < ml.count; i++) {
3940 r = get_pointer_32(p, offset, left, S, info);
3941 if (r == nullptr)
3942 return;
3943 memset(&m, '\0', sizeof(struct method32_t));
3944 if (left < sizeof(struct method32_t)) {
3945 memcpy(&ml, r, left);
3946 outs() << indent << " (method_t entends past the end of the section)\n";
3947 } else
3948 memcpy(&m, r, sizeof(struct method32_t));
3949 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3950 swapStruct(m);
3951
3952 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
3953 name = get_pointer_32(m.name, xoffset, left, xS, info);
3954 if (name != nullptr)
3955 outs() << format(" %.*s", left, name);
3956 outs() << "\n";
3957
3958 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
3959 name = get_pointer_32(m.types, xoffset, left, xS, info);
3960 if (name != nullptr)
3961 outs() << format(" %.*s", left, name);
3962 outs() << "\n";
3963
3964 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
3965 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
3966 m.imp);
3967 if (name != nullptr)
3968 outs() << " " << name;
3969 outs() << "\n";
3970
3971 p += sizeof(struct method32_t);
3972 offset += sizeof(struct method32_t);
3973 }
3974}
3975
Kevin Enderby846c0002015-04-16 17:19:59 +00003976static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
3977 uint32_t offset, left, xleft;
3978 SectionRef S;
3979 struct objc_method_list_t method_list;
3980 struct objc_method_t method;
3981 const char *r, *methods, *name, *SymbolName;
3982 int32_t i;
3983
3984 r = get_pointer_32(p, offset, left, S, info, true);
3985 if (r == nullptr)
3986 return true;
3987
3988 outs() << "\n";
3989 if (left > sizeof(struct objc_method_list_t)) {
3990 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
3991 } else {
3992 outs() << "\t\t objc_method_list extends past end of the section\n";
3993 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
3994 memcpy(&method_list, r, left);
3995 }
3996 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3997 swapStruct(method_list);
3998
3999 outs() << "\t\t obsolete "
4000 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
4001 outs() << "\t\t method_count " << method_list.method_count << "\n";
4002
4003 methods = r + sizeof(struct objc_method_list_t);
4004 for (i = 0; i < method_list.method_count; i++) {
4005 if ((i + 1) * sizeof(struct objc_method_t) > left) {
4006 outs() << "\t\t remaining method's extend past the of the section\n";
4007 break;
4008 }
4009 memcpy(&method, methods + i * sizeof(struct objc_method_t),
4010 sizeof(struct objc_method_t));
4011 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4012 swapStruct(method);
4013
4014 outs() << "\t\t method_name "
4015 << format("0x%08" PRIx32, method.method_name);
4016 if (info->verbose) {
4017 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
4018 if (name != nullptr)
4019 outs() << format(" %.*s", xleft, name);
4020 else
4021 outs() << " (not in an __OBJC section)";
4022 }
4023 outs() << "\n";
4024
4025 outs() << "\t\t method_types "
4026 << format("0x%08" PRIx32, method.method_types);
4027 if (info->verbose) {
4028 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
4029 if (name != nullptr)
4030 outs() << format(" %.*s", xleft, name);
4031 else
4032 outs() << " (not in an __OBJC section)";
4033 }
4034 outs() << "\n";
4035
4036 outs() << "\t\t method_imp "
4037 << format("0x%08" PRIx32, method.method_imp) << " ";
4038 if (info->verbose) {
4039 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
4040 if (SymbolName != nullptr)
4041 outs() << SymbolName;
4042 }
4043 outs() << "\n";
4044 }
4045 return false;
4046}
4047
Kevin Enderby0fc11822015-04-01 20:57:01 +00004048static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
4049 struct protocol_list64_t pl;
4050 uint64_t q, n_value;
4051 struct protocol64_t pc;
4052 const char *r;
4053 uint32_t offset, xoffset, left, i;
4054 SectionRef S, xS;
4055 const char *name, *sym_name;
4056
4057 r = get_pointer_64(p, offset, left, S, info);
4058 if (r == nullptr)
4059 return;
4060 memset(&pl, '\0', sizeof(struct protocol_list64_t));
4061 if (left < sizeof(struct protocol_list64_t)) {
4062 memcpy(&pl, r, left);
4063 outs() << " (protocol_list_t entends past the end of the section)\n";
4064 } else
4065 memcpy(&pl, r, sizeof(struct protocol_list64_t));
4066 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4067 swapStruct(pl);
4068 outs() << " count " << pl.count << "\n";
4069
4070 p += sizeof(struct protocol_list64_t);
4071 offset += sizeof(struct protocol_list64_t);
4072 for (i = 0; i < pl.count; i++) {
4073 r = get_pointer_64(p, offset, left, S, info);
4074 if (r == nullptr)
4075 return;
4076 q = 0;
4077 if (left < sizeof(uint64_t)) {
4078 memcpy(&q, r, left);
4079 outs() << " (protocol_t * entends past the end of the section)\n";
4080 } else
4081 memcpy(&q, r, sizeof(uint64_t));
4082 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4083 sys::swapByteOrder(q);
4084
4085 outs() << "\t\t list[" << i << "] ";
4086 sym_name = get_symbol_64(offset, S, info, n_value, q);
4087 if (n_value != 0) {
4088 if (info->verbose && sym_name != nullptr)
4089 outs() << sym_name;
4090 else
4091 outs() << format("0x%" PRIx64, n_value);
4092 if (q != 0)
4093 outs() << " + " << format("0x%" PRIx64, q);
4094 } else
4095 outs() << format("0x%" PRIx64, q);
4096 outs() << " (struct protocol_t *)\n";
4097
4098 r = get_pointer_64(q + n_value, offset, left, S, info);
4099 if (r == nullptr)
4100 return;
4101 memset(&pc, '\0', sizeof(struct protocol64_t));
4102 if (left < sizeof(struct protocol64_t)) {
4103 memcpy(&pc, r, left);
4104 outs() << " (protocol_t entends past the end of the section)\n";
4105 } else
4106 memcpy(&pc, r, sizeof(struct protocol64_t));
4107 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4108 swapStruct(pc);
4109
4110 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
4111
4112 outs() << "\t\t\t name ";
4113 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
4114 info, n_value, pc.name);
4115 if (n_value != 0) {
4116 if (info->verbose && sym_name != nullptr)
4117 outs() << sym_name;
4118 else
4119 outs() << format("0x%" PRIx64, n_value);
4120 if (pc.name != 0)
4121 outs() << " + " << format("0x%" PRIx64, pc.name);
4122 } else
4123 outs() << format("0x%" PRIx64, pc.name);
4124 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
4125 if (name != nullptr)
4126 outs() << format(" %.*s", left, name);
4127 outs() << "\n";
4128
4129 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
4130
4131 outs() << "\t\t instanceMethods ";
4132 sym_name =
4133 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
4134 S, info, n_value, pc.instanceMethods);
4135 if (n_value != 0) {
4136 if (info->verbose && sym_name != nullptr)
4137 outs() << sym_name;
4138 else
4139 outs() << format("0x%" PRIx64, n_value);
4140 if (pc.instanceMethods != 0)
4141 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
4142 } else
4143 outs() << format("0x%" PRIx64, pc.instanceMethods);
4144 outs() << " (struct method_list_t *)\n";
4145 if (pc.instanceMethods + n_value != 0)
4146 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
4147
4148 outs() << "\t\t classMethods ";
4149 sym_name =
4150 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
4151 info, n_value, pc.classMethods);
4152 if (n_value != 0) {
4153 if (info->verbose && sym_name != nullptr)
4154 outs() << sym_name;
4155 else
4156 outs() << format("0x%" PRIx64, n_value);
4157 if (pc.classMethods != 0)
4158 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
4159 } else
4160 outs() << format("0x%" PRIx64, pc.classMethods);
4161 outs() << " (struct method_list_t *)\n";
4162 if (pc.classMethods + n_value != 0)
4163 print_method_list64_t(pc.classMethods + n_value, info, "\t");
4164
4165 outs() << "\t optionalInstanceMethods "
4166 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
4167 outs() << "\t optionalClassMethods "
4168 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
4169 outs() << "\t instanceProperties "
4170 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
4171
4172 p += sizeof(uint64_t);
4173 offset += sizeof(uint64_t);
4174 }
4175}
4176
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004177static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
4178 struct protocol_list32_t pl;
4179 uint32_t q;
4180 struct protocol32_t pc;
4181 const char *r;
4182 uint32_t offset, xoffset, left, i;
4183 SectionRef S, xS;
4184 const char *name;
4185
4186 r = get_pointer_32(p, offset, left, S, info);
4187 if (r == nullptr)
4188 return;
4189 memset(&pl, '\0', sizeof(struct protocol_list32_t));
4190 if (left < sizeof(struct protocol_list32_t)) {
4191 memcpy(&pl, r, left);
4192 outs() << " (protocol_list_t entends past the end of the section)\n";
4193 } else
4194 memcpy(&pl, r, sizeof(struct protocol_list32_t));
4195 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4196 swapStruct(pl);
4197 outs() << " count " << pl.count << "\n";
4198
4199 p += sizeof(struct protocol_list32_t);
4200 offset += sizeof(struct protocol_list32_t);
4201 for (i = 0; i < pl.count; i++) {
4202 r = get_pointer_32(p, offset, left, S, info);
4203 if (r == nullptr)
4204 return;
4205 q = 0;
4206 if (left < sizeof(uint32_t)) {
4207 memcpy(&q, r, left);
4208 outs() << " (protocol_t * entends past the end of the section)\n";
4209 } else
4210 memcpy(&q, r, sizeof(uint32_t));
4211 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4212 sys::swapByteOrder(q);
4213 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
4214 << " (struct protocol_t *)\n";
4215 r = get_pointer_32(q, offset, left, S, info);
4216 if (r == nullptr)
4217 return;
4218 memset(&pc, '\0', sizeof(struct protocol32_t));
4219 if (left < sizeof(struct protocol32_t)) {
4220 memcpy(&pc, r, left);
4221 outs() << " (protocol_t entends past the end of the section)\n";
4222 } else
4223 memcpy(&pc, r, sizeof(struct protocol32_t));
4224 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4225 swapStruct(pc);
4226 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
4227 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
4228 name = get_pointer_32(pc.name, xoffset, left, xS, info);
4229 if (name != nullptr)
4230 outs() << format(" %.*s", left, name);
4231 outs() << "\n";
4232 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
4233 outs() << "\t\t instanceMethods "
4234 << format("0x%" PRIx32, pc.instanceMethods)
4235 << " (struct method_list_t *)\n";
4236 if (pc.instanceMethods != 0)
4237 print_method_list32_t(pc.instanceMethods, info, "\t");
4238 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
4239 << " (struct method_list_t *)\n";
4240 if (pc.classMethods != 0)
4241 print_method_list32_t(pc.classMethods, info, "\t");
4242 outs() << "\t optionalInstanceMethods "
4243 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
4244 outs() << "\t optionalClassMethods "
4245 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
4246 outs() << "\t instanceProperties "
4247 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
4248 p += sizeof(uint32_t);
4249 offset += sizeof(uint32_t);
4250 }
4251}
4252
Kevin Enderby846c0002015-04-16 17:19:59 +00004253static void print_indent(uint32_t indent) {
4254 for (uint32_t i = 0; i < indent;) {
4255 if (indent - i >= 8) {
4256 outs() << "\t";
4257 i += 8;
4258 } else {
4259 for (uint32_t j = i; j < indent; j++)
4260 outs() << " ";
4261 return;
4262 }
4263 }
4264}
4265
4266static bool print_method_description_list(uint32_t p, uint32_t indent,
4267 struct DisassembleInfo *info) {
4268 uint32_t offset, left, xleft;
4269 SectionRef S;
4270 struct objc_method_description_list_t mdl;
4271 struct objc_method_description_t md;
4272 const char *r, *list, *name;
4273 int32_t i;
4274
4275 r = get_pointer_32(p, offset, left, S, info, true);
4276 if (r == nullptr)
4277 return true;
4278
4279 outs() << "\n";
4280 if (left > sizeof(struct objc_method_description_list_t)) {
4281 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
4282 } else {
4283 print_indent(indent);
4284 outs() << " objc_method_description_list extends past end of the section\n";
4285 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
4286 memcpy(&mdl, r, left);
4287 }
4288 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4289 swapStruct(mdl);
4290
4291 print_indent(indent);
4292 outs() << " count " << mdl.count << "\n";
4293
4294 list = r + sizeof(struct objc_method_description_list_t);
4295 for (i = 0; i < mdl.count; i++) {
4296 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
4297 print_indent(indent);
4298 outs() << " remaining list entries extend past the of the section\n";
4299 break;
4300 }
4301 print_indent(indent);
4302 outs() << " list[" << i << "]\n";
4303 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
4304 sizeof(struct objc_method_description_t));
4305 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4306 swapStruct(md);
4307
4308 print_indent(indent);
4309 outs() << " name " << format("0x%08" PRIx32, md.name);
4310 if (info->verbose) {
4311 name = get_pointer_32(md.name, offset, xleft, S, info, true);
4312 if (name != nullptr)
4313 outs() << format(" %.*s", xleft, name);
4314 else
4315 outs() << " (not in an __OBJC section)";
4316 }
4317 outs() << "\n";
4318
4319 print_indent(indent);
4320 outs() << " types " << format("0x%08" PRIx32, md.types);
4321 if (info->verbose) {
4322 name = get_pointer_32(md.types, offset, xleft, S, info, true);
4323 if (name != nullptr)
4324 outs() << format(" %.*s", xleft, name);
4325 else
4326 outs() << " (not in an __OBJC section)";
4327 }
4328 outs() << "\n";
4329 }
4330 return false;
4331}
4332
4333static bool print_protocol_list(uint32_t p, uint32_t indent,
4334 struct DisassembleInfo *info);
4335
4336static bool print_protocol(uint32_t p, uint32_t indent,
4337 struct DisassembleInfo *info) {
4338 uint32_t offset, left;
4339 SectionRef S;
4340 struct objc_protocol_t protocol;
4341 const char *r, *name;
4342
4343 r = get_pointer_32(p, offset, left, S, info, true);
4344 if (r == nullptr)
4345 return true;
4346
4347 outs() << "\n";
4348 if (left >= sizeof(struct objc_protocol_t)) {
4349 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
4350 } else {
4351 print_indent(indent);
4352 outs() << " Protocol extends past end of the section\n";
4353 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
4354 memcpy(&protocol, r, left);
4355 }
4356 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4357 swapStruct(protocol);
4358
4359 print_indent(indent);
4360 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
4361 << "\n";
4362
4363 print_indent(indent);
4364 outs() << " protocol_name "
4365 << format("0x%08" PRIx32, protocol.protocol_name);
4366 if (info->verbose) {
4367 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
4368 if (name != nullptr)
4369 outs() << format(" %.*s", left, name);
4370 else
4371 outs() << " (not in an __OBJC section)";
4372 }
4373 outs() << "\n";
4374
4375 print_indent(indent);
4376 outs() << " protocol_list "
4377 << format("0x%08" PRIx32, protocol.protocol_list);
4378 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
4379 outs() << " (not in an __OBJC section)\n";
4380
4381 print_indent(indent);
4382 outs() << " instance_methods "
4383 << format("0x%08" PRIx32, protocol.instance_methods);
4384 if (print_method_description_list(protocol.instance_methods, indent, info))
4385 outs() << " (not in an __OBJC section)\n";
4386
4387 print_indent(indent);
4388 outs() << " class_methods "
4389 << format("0x%08" PRIx32, protocol.class_methods);
4390 if (print_method_description_list(protocol.class_methods, indent, info))
4391 outs() << " (not in an __OBJC section)\n";
4392
4393 return false;
4394}
4395
4396static bool print_protocol_list(uint32_t p, uint32_t indent,
4397 struct DisassembleInfo *info) {
4398 uint32_t offset, left, l;
4399 SectionRef S;
4400 struct objc_protocol_list_t protocol_list;
4401 const char *r, *list;
4402 int32_t i;
4403
4404 r = get_pointer_32(p, offset, left, S, info, true);
4405 if (r == nullptr)
4406 return true;
4407
4408 outs() << "\n";
4409 if (left > sizeof(struct objc_protocol_list_t)) {
4410 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4411 } else {
4412 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4413 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4414 memcpy(&protocol_list, r, left);
4415 }
4416 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4417 swapStruct(protocol_list);
4418
4419 print_indent(indent);
4420 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
4421 << "\n";
4422 print_indent(indent);
4423 outs() << " count " << protocol_list.count << "\n";
4424
4425 list = r + sizeof(struct objc_protocol_list_t);
4426 for (i = 0; i < protocol_list.count; i++) {
4427 if ((i + 1) * sizeof(uint32_t) > left) {
4428 outs() << "\t\t remaining list entries extend past the of the section\n";
4429 break;
4430 }
4431 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4432 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4433 sys::swapByteOrder(l);
4434
4435 print_indent(indent);
4436 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
4437 if (print_protocol(l, indent, info))
4438 outs() << "(not in an __OBJC section)\n";
4439 }
4440 return false;
4441}
4442
Kevin Enderby0fc11822015-04-01 20:57:01 +00004443static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4444 struct ivar_list64_t il;
4445 struct ivar64_t i;
4446 const char *r;
4447 uint32_t offset, xoffset, left, j;
4448 SectionRef S, xS;
4449 const char *name, *sym_name, *ivar_offset_p;
4450 uint64_t ivar_offset, n_value;
4451
4452 r = get_pointer_64(p, offset, left, S, info);
4453 if (r == nullptr)
4454 return;
4455 memset(&il, '\0', sizeof(struct ivar_list64_t));
4456 if (left < sizeof(struct ivar_list64_t)) {
4457 memcpy(&il, r, left);
4458 outs() << " (ivar_list_t entends past the end of the section)\n";
4459 } else
4460 memcpy(&il, r, sizeof(struct ivar_list64_t));
4461 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4462 swapStruct(il);
4463 outs() << " entsize " << il.entsize << "\n";
4464 outs() << " count " << il.count << "\n";
4465
4466 p += sizeof(struct ivar_list64_t);
4467 offset += sizeof(struct ivar_list64_t);
4468 for (j = 0; j < il.count; j++) {
4469 r = get_pointer_64(p, offset, left, S, info);
4470 if (r == nullptr)
4471 return;
4472 memset(&i, '\0', sizeof(struct ivar64_t));
4473 if (left < sizeof(struct ivar64_t)) {
4474 memcpy(&i, r, left);
4475 outs() << " (ivar_t entends past the end of the section)\n";
4476 } else
4477 memcpy(&i, r, sizeof(struct ivar64_t));
4478 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4479 swapStruct(i);
4480
4481 outs() << "\t\t\t offset ";
4482 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4483 info, n_value, i.offset);
4484 if (n_value != 0) {
4485 if (info->verbose && sym_name != nullptr)
4486 outs() << sym_name;
4487 else
4488 outs() << format("0x%" PRIx64, n_value);
4489 if (i.offset != 0)
4490 outs() << " + " << format("0x%" PRIx64, i.offset);
4491 } else
4492 outs() << format("0x%" PRIx64, i.offset);
4493 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4494 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4495 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4496 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4497 sys::swapByteOrder(ivar_offset);
4498 outs() << " " << ivar_offset << "\n";
4499 } else
4500 outs() << "\n";
4501
4502 outs() << "\t\t\t name ";
4503 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4504 n_value, i.name);
4505 if (n_value != 0) {
4506 if (info->verbose && sym_name != nullptr)
4507 outs() << sym_name;
4508 else
4509 outs() << format("0x%" PRIx64, n_value);
4510 if (i.name != 0)
4511 outs() << " + " << format("0x%" PRIx64, i.name);
4512 } else
4513 outs() << format("0x%" PRIx64, i.name);
4514 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4515 if (name != nullptr)
4516 outs() << format(" %.*s", left, name);
4517 outs() << "\n";
4518
4519 outs() << "\t\t\t type ";
4520 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4521 n_value, i.name);
4522 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4523 if (n_value != 0) {
4524 if (info->verbose && sym_name != nullptr)
4525 outs() << sym_name;
4526 else
4527 outs() << format("0x%" PRIx64, n_value);
4528 if (i.type != 0)
4529 outs() << " + " << format("0x%" PRIx64, i.type);
4530 } else
4531 outs() << format("0x%" PRIx64, i.type);
4532 if (name != nullptr)
4533 outs() << format(" %.*s", left, name);
4534 outs() << "\n";
4535
4536 outs() << "\t\t\talignment " << i.alignment << "\n";
4537 outs() << "\t\t\t size " << i.size << "\n";
4538
4539 p += sizeof(struct ivar64_t);
4540 offset += sizeof(struct ivar64_t);
4541 }
4542}
4543
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004544static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4545 struct ivar_list32_t il;
4546 struct ivar32_t i;
4547 const char *r;
4548 uint32_t offset, xoffset, left, j;
4549 SectionRef S, xS;
4550 const char *name, *ivar_offset_p;
4551 uint32_t ivar_offset;
4552
4553 r = get_pointer_32(p, offset, left, S, info);
4554 if (r == nullptr)
4555 return;
4556 memset(&il, '\0', sizeof(struct ivar_list32_t));
4557 if (left < sizeof(struct ivar_list32_t)) {
4558 memcpy(&il, r, left);
4559 outs() << " (ivar_list_t entends past the end of the section)\n";
4560 } else
4561 memcpy(&il, r, sizeof(struct ivar_list32_t));
4562 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4563 swapStruct(il);
4564 outs() << " entsize " << il.entsize << "\n";
4565 outs() << " count " << il.count << "\n";
4566
4567 p += sizeof(struct ivar_list32_t);
4568 offset += sizeof(struct ivar_list32_t);
4569 for (j = 0; j < il.count; j++) {
4570 r = get_pointer_32(p, offset, left, S, info);
4571 if (r == nullptr)
4572 return;
4573 memset(&i, '\0', sizeof(struct ivar32_t));
4574 if (left < sizeof(struct ivar32_t)) {
4575 memcpy(&i, r, left);
4576 outs() << " (ivar_t entends past the end of the section)\n";
4577 } else
4578 memcpy(&i, r, sizeof(struct ivar32_t));
4579 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4580 swapStruct(i);
4581
4582 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4583 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4584 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4585 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4586 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4587 sys::swapByteOrder(ivar_offset);
4588 outs() << " " << ivar_offset << "\n";
4589 } else
4590 outs() << "\n";
4591
4592 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4593 name = get_pointer_32(i.name, xoffset, left, xS, info);
4594 if (name != nullptr)
4595 outs() << format(" %.*s", left, name);
4596 outs() << "\n";
4597
4598 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4599 name = get_pointer_32(i.type, xoffset, left, xS, info);
4600 if (name != nullptr)
4601 outs() << format(" %.*s", left, name);
4602 outs() << "\n";
4603
4604 outs() << "\t\t\talignment " << i.alignment << "\n";
4605 outs() << "\t\t\t size " << i.size << "\n";
4606
4607 p += sizeof(struct ivar32_t);
4608 offset += sizeof(struct ivar32_t);
4609 }
4610}
4611
Kevin Enderby0fc11822015-04-01 20:57:01 +00004612static void print_objc_property_list64(uint64_t p,
4613 struct DisassembleInfo *info) {
4614 struct objc_property_list64 opl;
4615 struct objc_property64 op;
4616 const char *r;
4617 uint32_t offset, xoffset, left, j;
4618 SectionRef S, xS;
4619 const char *name, *sym_name;
4620 uint64_t n_value;
4621
4622 r = get_pointer_64(p, offset, left, S, info);
4623 if (r == nullptr)
4624 return;
4625 memset(&opl, '\0', sizeof(struct objc_property_list64));
4626 if (left < sizeof(struct objc_property_list64)) {
4627 memcpy(&opl, r, left);
4628 outs() << " (objc_property_list entends past the end of the section)\n";
4629 } else
4630 memcpy(&opl, r, sizeof(struct objc_property_list64));
4631 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4632 swapStruct(opl);
4633 outs() << " entsize " << opl.entsize << "\n";
4634 outs() << " count " << opl.count << "\n";
4635
4636 p += sizeof(struct objc_property_list64);
4637 offset += sizeof(struct objc_property_list64);
4638 for (j = 0; j < opl.count; j++) {
4639 r = get_pointer_64(p, offset, left, S, info);
4640 if (r == nullptr)
4641 return;
4642 memset(&op, '\0', sizeof(struct objc_property64));
4643 if (left < sizeof(struct objc_property64)) {
4644 memcpy(&op, r, left);
4645 outs() << " (objc_property entends past the end of the section)\n";
4646 } else
4647 memcpy(&op, r, sizeof(struct objc_property64));
4648 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4649 swapStruct(op);
4650
4651 outs() << "\t\t\t name ";
4652 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4653 info, n_value, op.name);
4654 if (n_value != 0) {
4655 if (info->verbose && sym_name != nullptr)
4656 outs() << sym_name;
4657 else
4658 outs() << format("0x%" PRIx64, n_value);
4659 if (op.name != 0)
4660 outs() << " + " << format("0x%" PRIx64, op.name);
4661 } else
4662 outs() << format("0x%" PRIx64, op.name);
4663 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4664 if (name != nullptr)
4665 outs() << format(" %.*s", left, name);
4666 outs() << "\n";
4667
4668 outs() << "\t\t\tattributes ";
4669 sym_name =
4670 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4671 info, n_value, op.attributes);
4672 if (n_value != 0) {
4673 if (info->verbose && sym_name != nullptr)
4674 outs() << sym_name;
4675 else
4676 outs() << format("0x%" PRIx64, n_value);
4677 if (op.attributes != 0)
4678 outs() << " + " << format("0x%" PRIx64, op.attributes);
4679 } else
4680 outs() << format("0x%" PRIx64, op.attributes);
4681 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4682 if (name != nullptr)
4683 outs() << format(" %.*s", left, name);
4684 outs() << "\n";
4685
4686 p += sizeof(struct objc_property64);
4687 offset += sizeof(struct objc_property64);
4688 }
4689}
4690
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004691static void print_objc_property_list32(uint32_t p,
4692 struct DisassembleInfo *info) {
4693 struct objc_property_list32 opl;
4694 struct objc_property32 op;
4695 const char *r;
4696 uint32_t offset, xoffset, left, j;
4697 SectionRef S, xS;
4698 const char *name;
4699
4700 r = get_pointer_32(p, offset, left, S, info);
4701 if (r == nullptr)
4702 return;
4703 memset(&opl, '\0', sizeof(struct objc_property_list32));
4704 if (left < sizeof(struct objc_property_list32)) {
4705 memcpy(&opl, r, left);
4706 outs() << " (objc_property_list entends past the end of the section)\n";
4707 } else
4708 memcpy(&opl, r, sizeof(struct objc_property_list32));
4709 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4710 swapStruct(opl);
4711 outs() << " entsize " << opl.entsize << "\n";
4712 outs() << " count " << opl.count << "\n";
4713
4714 p += sizeof(struct objc_property_list32);
4715 offset += sizeof(struct objc_property_list32);
4716 for (j = 0; j < opl.count; j++) {
4717 r = get_pointer_32(p, offset, left, S, info);
4718 if (r == nullptr)
4719 return;
4720 memset(&op, '\0', sizeof(struct objc_property32));
4721 if (left < sizeof(struct objc_property32)) {
4722 memcpy(&op, r, left);
4723 outs() << " (objc_property entends past the end of the section)\n";
4724 } else
4725 memcpy(&op, r, sizeof(struct objc_property32));
4726 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4727 swapStruct(op);
4728
4729 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4730 name = get_pointer_32(op.name, xoffset, left, xS, info);
4731 if (name != nullptr)
4732 outs() << format(" %.*s", left, name);
4733 outs() << "\n";
4734
4735 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4736 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4737 if (name != nullptr)
4738 outs() << format(" %.*s", left, name);
4739 outs() << "\n";
4740
4741 p += sizeof(struct objc_property32);
4742 offset += sizeof(struct objc_property32);
4743 }
4744}
4745
Richard Smith81ff44d2015-10-09 22:09:56 +00004746static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
Kevin Enderby0fc11822015-04-01 20:57:01 +00004747 bool &is_meta_class) {
4748 struct class_ro64_t cro;
4749 const char *r;
4750 uint32_t offset, xoffset, left;
4751 SectionRef S, xS;
4752 const char *name, *sym_name;
4753 uint64_t n_value;
4754
4755 r = get_pointer_64(p, offset, left, S, info);
4756 if (r == nullptr || left < sizeof(struct class_ro64_t))
Richard Smith81ff44d2015-10-09 22:09:56 +00004757 return false;
Chandler Carruth33e58902016-11-04 07:10:24 +00004758 memcpy(&cro, r, sizeof(struct class_ro64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00004759 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4760 swapStruct(cro);
4761 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4762 if (cro.flags & RO_META)
4763 outs() << " RO_META";
4764 if (cro.flags & RO_ROOT)
4765 outs() << " RO_ROOT";
4766 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4767 outs() << " RO_HAS_CXX_STRUCTORS";
4768 outs() << "\n";
4769 outs() << " instanceStart " << cro.instanceStart << "\n";
4770 outs() << " instanceSize " << cro.instanceSize << "\n";
4771 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4772 << "\n";
4773 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4774 << "\n";
4775 print_layout_map64(cro.ivarLayout, info);
4776
4777 outs() << " name ";
4778 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4779 info, n_value, cro.name);
4780 if (n_value != 0) {
4781 if (info->verbose && sym_name != nullptr)
4782 outs() << sym_name;
4783 else
4784 outs() << format("0x%" PRIx64, n_value);
4785 if (cro.name != 0)
4786 outs() << " + " << format("0x%" PRIx64, cro.name);
4787 } else
4788 outs() << format("0x%" PRIx64, cro.name);
4789 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4790 if (name != nullptr)
4791 outs() << format(" %.*s", left, name);
4792 outs() << "\n";
4793
4794 outs() << " baseMethods ";
4795 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4796 S, info, n_value, cro.baseMethods);
4797 if (n_value != 0) {
4798 if (info->verbose && sym_name != nullptr)
4799 outs() << sym_name;
4800 else
4801 outs() << format("0x%" PRIx64, n_value);
4802 if (cro.baseMethods != 0)
4803 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4804 } else
4805 outs() << format("0x%" PRIx64, cro.baseMethods);
4806 outs() << " (struct method_list_t *)\n";
4807 if (cro.baseMethods + n_value != 0)
4808 print_method_list64_t(cro.baseMethods + n_value, info, "");
4809
4810 outs() << " baseProtocols ";
4811 sym_name =
4812 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4813 info, n_value, cro.baseProtocols);
4814 if (n_value != 0) {
4815 if (info->verbose && sym_name != nullptr)
4816 outs() << sym_name;
4817 else
4818 outs() << format("0x%" PRIx64, n_value);
4819 if (cro.baseProtocols != 0)
4820 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4821 } else
4822 outs() << format("0x%" PRIx64, cro.baseProtocols);
4823 outs() << "\n";
4824 if (cro.baseProtocols + n_value != 0)
4825 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4826
4827 outs() << " ivars ";
4828 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004829 info, n_value, cro.ivars);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004830 if (n_value != 0) {
4831 if (info->verbose && sym_name != nullptr)
4832 outs() << sym_name;
4833 else
4834 outs() << format("0x%" PRIx64, n_value);
4835 if (cro.ivars != 0)
4836 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4837 } else
4838 outs() << format("0x%" PRIx64, cro.ivars);
4839 outs() << "\n";
4840 if (cro.ivars + n_value != 0)
4841 print_ivar_list64_t(cro.ivars + n_value, info);
4842
4843 outs() << " weakIvarLayout ";
4844 sym_name =
4845 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4846 info, n_value, cro.weakIvarLayout);
4847 if (n_value != 0) {
4848 if (info->verbose && sym_name != nullptr)
4849 outs() << sym_name;
4850 else
4851 outs() << format("0x%" PRIx64, n_value);
4852 if (cro.weakIvarLayout != 0)
4853 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4854 } else
4855 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4856 outs() << "\n";
4857 print_layout_map64(cro.weakIvarLayout + n_value, info);
4858
4859 outs() << " baseProperties ";
4860 sym_name =
4861 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4862 info, n_value, cro.baseProperties);
4863 if (n_value != 0) {
4864 if (info->verbose && sym_name != nullptr)
4865 outs() << sym_name;
4866 else
4867 outs() << format("0x%" PRIx64, n_value);
4868 if (cro.baseProperties != 0)
4869 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4870 } else
4871 outs() << format("0x%" PRIx64, cro.baseProperties);
4872 outs() << "\n";
4873 if (cro.baseProperties + n_value != 0)
4874 print_objc_property_list64(cro.baseProperties + n_value, info);
4875
Rafael Espindolab9091322015-10-24 23:19:10 +00004876 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004877 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004878}
4879
Richard Smith81ff44d2015-10-09 22:09:56 +00004880static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004881 bool &is_meta_class) {
4882 struct class_ro32_t cro;
4883 const char *r;
4884 uint32_t offset, xoffset, left;
4885 SectionRef S, xS;
4886 const char *name;
4887
4888 r = get_pointer_32(p, offset, left, S, info);
4889 if (r == nullptr)
Richard Smith81ff44d2015-10-09 22:09:56 +00004890 return false;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004891 memset(&cro, '\0', sizeof(struct class_ro32_t));
4892 if (left < sizeof(struct class_ro32_t)) {
4893 memcpy(&cro, r, left);
4894 outs() << " (class_ro_t entends past the end of the section)\n";
4895 } else
4896 memcpy(&cro, r, sizeof(struct class_ro32_t));
4897 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4898 swapStruct(cro);
4899 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4900 if (cro.flags & RO_META)
4901 outs() << " RO_META";
4902 if (cro.flags & RO_ROOT)
4903 outs() << " RO_ROOT";
4904 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4905 outs() << " RO_HAS_CXX_STRUCTORS";
4906 outs() << "\n";
4907 outs() << " instanceStart " << cro.instanceStart << "\n";
4908 outs() << " instanceSize " << cro.instanceSize << "\n";
4909 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4910 << "\n";
4911 print_layout_map32(cro.ivarLayout, info);
4912
4913 outs() << " name " << format("0x%" PRIx32, cro.name);
4914 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4915 if (name != nullptr)
4916 outs() << format(" %.*s", left, name);
4917 outs() << "\n";
4918
4919 outs() << " baseMethods "
4920 << format("0x%" PRIx32, cro.baseMethods)
4921 << " (struct method_list_t *)\n";
4922 if (cro.baseMethods != 0)
4923 print_method_list32_t(cro.baseMethods, info, "");
4924
4925 outs() << " baseProtocols "
4926 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4927 if (cro.baseProtocols != 0)
4928 print_protocol_list32_t(cro.baseProtocols, info);
4929 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4930 << "\n";
4931 if (cro.ivars != 0)
4932 print_ivar_list32_t(cro.ivars, info);
4933 outs() << " weakIvarLayout "
4934 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4935 print_layout_map32(cro.weakIvarLayout, info);
4936 outs() << " baseProperties "
4937 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4938 if (cro.baseProperties != 0)
4939 print_objc_property_list32(cro.baseProperties, info);
Rafael Espindolab9091322015-10-24 23:19:10 +00004940 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004941 return true;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004942}
4943
Kevin Enderby0fc11822015-04-01 20:57:01 +00004944static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4945 struct class64_t c;
4946 const char *r;
4947 uint32_t offset, left;
4948 SectionRef S;
4949 const char *name;
4950 uint64_t isa_n_value, n_value;
4951
4952 r = get_pointer_64(p, offset, left, S, info);
4953 if (r == nullptr || left < sizeof(struct class64_t))
4954 return;
Chandler Carruth33e58902016-11-04 07:10:24 +00004955 memcpy(&c, r, sizeof(struct class64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00004956 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4957 swapStruct(c);
4958
4959 outs() << " isa " << format("0x%" PRIx64, c.isa);
4960 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
4961 isa_n_value, c.isa);
4962 if (name != nullptr)
4963 outs() << " " << name;
4964 outs() << "\n";
4965
4966 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
4967 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
4968 n_value, c.superclass);
4969 if (name != nullptr)
4970 outs() << " " << name;
Kevin Enderby1ce38582017-06-20 22:55:11 +00004971 else {
4972 name = get_dyld_bind_info_symbolname(S.getAddress() +
4973 offset + offsetof(struct class64_t, superclass), info);
4974 if (name != nullptr)
4975 outs() << " " << name;
4976 }
Kevin Enderby0fc11822015-04-01 20:57:01 +00004977 outs() << "\n";
4978
4979 outs() << " cache " << format("0x%" PRIx64, c.cache);
4980 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
4981 n_value, c.cache);
4982 if (name != nullptr)
4983 outs() << " " << name;
4984 outs() << "\n";
4985
4986 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
4987 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
4988 n_value, c.vtable);
4989 if (name != nullptr)
4990 outs() << " " << name;
4991 outs() << "\n";
4992
4993 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
4994 n_value, c.data);
4995 outs() << " data ";
4996 if (n_value != 0) {
4997 if (info->verbose && name != nullptr)
4998 outs() << name;
4999 else
5000 outs() << format("0x%" PRIx64, n_value);
5001 if (c.data != 0)
5002 outs() << " + " << format("0x%" PRIx64, c.data);
5003 } else
5004 outs() << format("0x%" PRIx64, c.data);
5005 outs() << " (struct class_ro_t *)";
5006
5007 // This is a Swift class if some of the low bits of the pointer are set.
5008 if ((c.data + n_value) & 0x7)
5009 outs() << " Swift class";
5010 outs() << "\n";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005011 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00005012 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
5013 return;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005014
Kevin Enderbyaac75382015-10-08 16:56:35 +00005015 if (!is_meta_class &&
5016 c.isa + isa_n_value != p &&
5017 c.isa + isa_n_value != 0 &&
5018 info->depth < 100) {
5019 info->depth++;
5020 outs() << "Meta Class\n";
5021 print_class64_t(c.isa + isa_n_value, info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005022 }
5023}
5024
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005025static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
5026 struct class32_t c;
5027 const char *r;
5028 uint32_t offset, left;
5029 SectionRef S;
5030 const char *name;
5031
5032 r = get_pointer_32(p, offset, left, S, info);
5033 if (r == nullptr)
5034 return;
5035 memset(&c, '\0', sizeof(struct class32_t));
5036 if (left < sizeof(struct class32_t)) {
5037 memcpy(&c, r, left);
5038 outs() << " (class_t entends past the end of the section)\n";
5039 } else
5040 memcpy(&c, r, sizeof(struct class32_t));
5041 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5042 swapStruct(c);
5043
5044 outs() << " isa " << format("0x%" PRIx32, c.isa);
5045 name =
5046 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
5047 if (name != nullptr)
5048 outs() << " " << name;
5049 outs() << "\n";
5050
5051 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
5052 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
5053 c.superclass);
5054 if (name != nullptr)
5055 outs() << " " << name;
5056 outs() << "\n";
5057
5058 outs() << " cache " << format("0x%" PRIx32, c.cache);
5059 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
5060 c.cache);
5061 if (name != nullptr)
5062 outs() << " " << name;
5063 outs() << "\n";
5064
5065 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
5066 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
5067 c.vtable);
5068 if (name != nullptr)
5069 outs() << " " << name;
5070 outs() << "\n";
5071
5072 name =
5073 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
5074 outs() << " data " << format("0x%" PRIx32, c.data)
5075 << " (struct class_ro_t *)";
5076
5077 // This is a Swift class if some of the low bits of the pointer are set.
5078 if (c.data & 0x3)
5079 outs() << " Swift class";
5080 outs() << "\n";
5081 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00005082 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
5083 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005084
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005085 if (!is_meta_class) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005086 outs() << "Meta Class\n";
5087 print_class32_t(c.isa, info);
5088 }
5089}
5090
Kevin Enderby846c0002015-04-16 17:19:59 +00005091static void print_objc_class_t(struct objc_class_t *objc_class,
5092 struct DisassembleInfo *info) {
5093 uint32_t offset, left, xleft;
5094 const char *name, *p, *ivar_list;
5095 SectionRef S;
5096 int32_t i;
5097 struct objc_ivar_list_t objc_ivar_list;
5098 struct objc_ivar_t ivar;
5099
5100 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
5101 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
5102 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
5103 if (name != nullptr)
5104 outs() << format(" %.*s", left, name);
5105 else
5106 outs() << " (not in an __OBJC section)";
5107 }
5108 outs() << "\n";
5109
5110 outs() << "\t super_class "
5111 << format("0x%08" PRIx32, objc_class->super_class);
5112 if (info->verbose) {
5113 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
5114 if (name != nullptr)
5115 outs() << format(" %.*s", left, name);
5116 else
5117 outs() << " (not in an __OBJC section)";
5118 }
5119 outs() << "\n";
5120
5121 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
5122 if (info->verbose) {
5123 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
5124 if (name != nullptr)
5125 outs() << format(" %.*s", left, name);
5126 else
5127 outs() << " (not in an __OBJC section)";
5128 }
5129 outs() << "\n";
5130
5131 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
5132 << "\n";
5133
5134 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
5135 if (info->verbose) {
5136 if (CLS_GETINFO(objc_class, CLS_CLASS))
5137 outs() << " CLS_CLASS";
5138 else if (CLS_GETINFO(objc_class, CLS_META))
5139 outs() << " CLS_META";
5140 }
5141 outs() << "\n";
5142
5143 outs() << "\t instance_size "
5144 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
5145
5146 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
5147 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
5148 if (p != nullptr) {
5149 if (left > sizeof(struct objc_ivar_list_t)) {
5150 outs() << "\n";
5151 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
5152 } else {
5153 outs() << " (entends past the end of the section)\n";
5154 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
5155 memcpy(&objc_ivar_list, p, left);
5156 }
5157 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5158 swapStruct(objc_ivar_list);
5159 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
5160 ivar_list = p + sizeof(struct objc_ivar_list_t);
5161 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
5162 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
5163 outs() << "\t\t remaining ivar's extend past the of the section\n";
5164 break;
5165 }
5166 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
5167 sizeof(struct objc_ivar_t));
5168 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5169 swapStruct(ivar);
5170
5171 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
5172 if (info->verbose) {
5173 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
5174 if (name != nullptr)
5175 outs() << format(" %.*s", xleft, name);
5176 else
5177 outs() << " (not in an __OBJC section)";
5178 }
5179 outs() << "\n";
5180
5181 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
5182 if (info->verbose) {
5183 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
5184 if (name != nullptr)
5185 outs() << format(" %.*s", xleft, name);
5186 else
5187 outs() << " (not in an __OBJC section)";
5188 }
5189 outs() << "\n";
5190
5191 outs() << "\t\t ivar_offset "
5192 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
5193 }
5194 } else {
5195 outs() << " (not in an __OBJC section)\n";
5196 }
5197
5198 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
5199 if (print_method_list(objc_class->methodLists, info))
5200 outs() << " (not in an __OBJC section)\n";
5201
5202 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
5203 << "\n";
5204
5205 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
5206 if (print_protocol_list(objc_class->protocols, 16, info))
5207 outs() << " (not in an __OBJC section)\n";
5208}
5209
5210static void print_objc_objc_category_t(struct objc_category_t *objc_category,
5211 struct DisassembleInfo *info) {
5212 uint32_t offset, left;
5213 const char *name;
5214 SectionRef S;
5215
5216 outs() << "\t category name "
5217 << format("0x%08" PRIx32, objc_category->category_name);
5218 if (info->verbose) {
5219 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
5220 true);
5221 if (name != nullptr)
5222 outs() << format(" %.*s", left, name);
5223 else
5224 outs() << " (not in an __OBJC section)";
5225 }
5226 outs() << "\n";
5227
5228 outs() << "\t\t class name "
5229 << format("0x%08" PRIx32, objc_category->class_name);
5230 if (info->verbose) {
5231 name =
5232 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
5233 if (name != nullptr)
5234 outs() << format(" %.*s", left, name);
5235 else
5236 outs() << " (not in an __OBJC section)";
5237 }
5238 outs() << "\n";
5239
5240 outs() << "\t instance methods "
5241 << format("0x%08" PRIx32, objc_category->instance_methods);
5242 if (print_method_list(objc_category->instance_methods, info))
5243 outs() << " (not in an __OBJC section)\n";
5244
5245 outs() << "\t class methods "
5246 << format("0x%08" PRIx32, objc_category->class_methods);
5247 if (print_method_list(objc_category->class_methods, info))
5248 outs() << " (not in an __OBJC section)\n";
5249}
5250
Kevin Enderby0fc11822015-04-01 20:57:01 +00005251static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
5252 struct category64_t c;
5253 const char *r;
5254 uint32_t offset, xoffset, left;
5255 SectionRef S, xS;
5256 const char *name, *sym_name;
5257 uint64_t n_value;
5258
5259 r = get_pointer_64(p, offset, left, S, info);
5260 if (r == nullptr)
5261 return;
5262 memset(&c, '\0', sizeof(struct category64_t));
5263 if (left < sizeof(struct category64_t)) {
5264 memcpy(&c, r, left);
5265 outs() << " (category_t entends past the end of the section)\n";
5266 } else
5267 memcpy(&c, r, sizeof(struct category64_t));
5268 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5269 swapStruct(c);
5270
5271 outs() << " name ";
5272 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
5273 info, n_value, c.name);
5274 if (n_value != 0) {
5275 if (info->verbose && sym_name != nullptr)
5276 outs() << sym_name;
5277 else
5278 outs() << format("0x%" PRIx64, n_value);
5279 if (c.name != 0)
5280 outs() << " + " << format("0x%" PRIx64, c.name);
5281 } else
5282 outs() << format("0x%" PRIx64, c.name);
5283 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
5284 if (name != nullptr)
5285 outs() << format(" %.*s", left, name);
5286 outs() << "\n";
5287
5288 outs() << " cls ";
5289 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
5290 n_value, c.cls);
5291 if (n_value != 0) {
5292 if (info->verbose && sym_name != nullptr)
5293 outs() << sym_name;
5294 else
5295 outs() << format("0x%" PRIx64, n_value);
5296 if (c.cls != 0)
5297 outs() << " + " << format("0x%" PRIx64, c.cls);
5298 } else
5299 outs() << format("0x%" PRIx64, c.cls);
5300 outs() << "\n";
5301 if (c.cls + n_value != 0)
5302 print_class64_t(c.cls + n_value, info);
5303
5304 outs() << " instanceMethods ";
5305 sym_name =
5306 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
5307 info, n_value, c.instanceMethods);
5308 if (n_value != 0) {
5309 if (info->verbose && sym_name != nullptr)
5310 outs() << sym_name;
5311 else
5312 outs() << format("0x%" PRIx64, n_value);
5313 if (c.instanceMethods != 0)
5314 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
5315 } else
5316 outs() << format("0x%" PRIx64, c.instanceMethods);
5317 outs() << "\n";
5318 if (c.instanceMethods + n_value != 0)
5319 print_method_list64_t(c.instanceMethods + n_value, info, "");
5320
5321 outs() << " classMethods ";
5322 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
5323 S, info, n_value, c.classMethods);
5324 if (n_value != 0) {
5325 if (info->verbose && sym_name != nullptr)
5326 outs() << sym_name;
5327 else
5328 outs() << format("0x%" PRIx64, n_value);
5329 if (c.classMethods != 0)
5330 outs() << " + " << format("0x%" PRIx64, c.classMethods);
5331 } else
5332 outs() << format("0x%" PRIx64, c.classMethods);
5333 outs() << "\n";
5334 if (c.classMethods + n_value != 0)
5335 print_method_list64_t(c.classMethods + n_value, info, "");
5336
5337 outs() << " protocols ";
5338 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
5339 info, n_value, c.protocols);
5340 if (n_value != 0) {
5341 if (info->verbose && sym_name != nullptr)
5342 outs() << sym_name;
5343 else
5344 outs() << format("0x%" PRIx64, n_value);
5345 if (c.protocols != 0)
5346 outs() << " + " << format("0x%" PRIx64, c.protocols);
5347 } else
5348 outs() << format("0x%" PRIx64, c.protocols);
5349 outs() << "\n";
5350 if (c.protocols + n_value != 0)
5351 print_protocol_list64_t(c.protocols + n_value, info);
5352
5353 outs() << "instanceProperties ";
5354 sym_name =
5355 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
5356 S, info, n_value, c.instanceProperties);
5357 if (n_value != 0) {
5358 if (info->verbose && sym_name != nullptr)
5359 outs() << sym_name;
5360 else
5361 outs() << format("0x%" PRIx64, n_value);
5362 if (c.instanceProperties != 0)
5363 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
5364 } else
5365 outs() << format("0x%" PRIx64, c.instanceProperties);
5366 outs() << "\n";
5367 if (c.instanceProperties + n_value != 0)
5368 print_objc_property_list64(c.instanceProperties + n_value, info);
5369}
5370
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005371static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
5372 struct category32_t c;
5373 const char *r;
5374 uint32_t offset, left;
5375 SectionRef S, xS;
5376 const char *name;
5377
5378 r = get_pointer_32(p, offset, left, S, info);
5379 if (r == nullptr)
5380 return;
5381 memset(&c, '\0', sizeof(struct category32_t));
5382 if (left < sizeof(struct category32_t)) {
5383 memcpy(&c, r, left);
5384 outs() << " (category_t entends past the end of the section)\n";
5385 } else
5386 memcpy(&c, r, sizeof(struct category32_t));
5387 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5388 swapStruct(c);
5389
5390 outs() << " name " << format("0x%" PRIx32, c.name);
5391 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
5392 c.name);
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005393 if (name)
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005394 outs() << " " << name;
5395 outs() << "\n";
5396
5397 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
5398 if (c.cls != 0)
5399 print_class32_t(c.cls, info);
5400 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
5401 << "\n";
5402 if (c.instanceMethods != 0)
5403 print_method_list32_t(c.instanceMethods, info, "");
5404 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
5405 << "\n";
5406 if (c.classMethods != 0)
5407 print_method_list32_t(c.classMethods, info, "");
5408 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
5409 if (c.protocols != 0)
5410 print_protocol_list32_t(c.protocols, info);
5411 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
5412 << "\n";
5413 if (c.instanceProperties != 0)
5414 print_objc_property_list32(c.instanceProperties, info);
5415}
5416
Kevin Enderby0fc11822015-04-01 20:57:01 +00005417static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5418 uint32_t i, left, offset, xoffset;
5419 uint64_t p, n_value;
5420 struct message_ref64 mr;
5421 const char *name, *sym_name;
5422 const char *r;
5423 SectionRef xS;
5424
5425 if (S == SectionRef())
5426 return;
5427
5428 StringRef SectName;
5429 S.getName(SectName);
5430 DataRefImpl Ref = S.getRawDataRefImpl();
5431 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5432 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5433 offset = 0;
5434 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5435 p = S.getAddress() + i;
5436 r = get_pointer_64(p, offset, left, S, info);
5437 if (r == nullptr)
5438 return;
5439 memset(&mr, '\0', sizeof(struct message_ref64));
5440 if (left < sizeof(struct message_ref64)) {
5441 memcpy(&mr, r, left);
5442 outs() << " (message_ref entends past the end of the section)\n";
5443 } else
5444 memcpy(&mr, r, sizeof(struct message_ref64));
5445 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5446 swapStruct(mr);
5447
5448 outs() << " imp ";
5449 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5450 n_value, mr.imp);
5451 if (n_value != 0) {
5452 outs() << format("0x%" PRIx64, n_value) << " ";
5453 if (mr.imp != 0)
5454 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5455 } else
5456 outs() << format("0x%" PRIx64, mr.imp) << " ";
5457 if (name != nullptr)
5458 outs() << " " << name;
5459 outs() << "\n";
5460
5461 outs() << " sel ";
5462 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5463 info, n_value, mr.sel);
5464 if (n_value != 0) {
5465 if (info->verbose && sym_name != nullptr)
5466 outs() << sym_name;
5467 else
5468 outs() << format("0x%" PRIx64, n_value);
5469 if (mr.sel != 0)
5470 outs() << " + " << format("0x%" PRIx64, mr.sel);
5471 } else
5472 outs() << format("0x%" PRIx64, mr.sel);
5473 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5474 if (name != nullptr)
5475 outs() << format(" %.*s", left, name);
5476 outs() << "\n";
5477
5478 offset += sizeof(struct message_ref64);
5479 }
5480}
5481
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005482static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5483 uint32_t i, left, offset, xoffset, p;
5484 struct message_ref32 mr;
5485 const char *name, *r;
5486 SectionRef xS;
5487
5488 if (S == SectionRef())
5489 return;
5490
5491 StringRef SectName;
5492 S.getName(SectName);
5493 DataRefImpl Ref = S.getRawDataRefImpl();
5494 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5495 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5496 offset = 0;
5497 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5498 p = S.getAddress() + i;
5499 r = get_pointer_32(p, offset, left, S, info);
5500 if (r == nullptr)
5501 return;
5502 memset(&mr, '\0', sizeof(struct message_ref32));
5503 if (left < sizeof(struct message_ref32)) {
5504 memcpy(&mr, r, left);
5505 outs() << " (message_ref entends past the end of the section)\n";
5506 } else
5507 memcpy(&mr, r, sizeof(struct message_ref32));
5508 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5509 swapStruct(mr);
5510
5511 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5512 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5513 mr.imp);
5514 if (name != nullptr)
5515 outs() << " " << name;
5516 outs() << "\n";
5517
5518 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5519 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5520 if (name != nullptr)
5521 outs() << " " << name;
5522 outs() << "\n";
5523
5524 offset += sizeof(struct message_ref32);
5525 }
5526}
5527
Kevin Enderby0fc11822015-04-01 20:57:01 +00005528static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5529 uint32_t left, offset, swift_version;
5530 uint64_t p;
5531 struct objc_image_info64 o;
5532 const char *r;
5533
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00005534 if (S == SectionRef())
5535 return;
5536
Kevin Enderby0fc11822015-04-01 20:57:01 +00005537 StringRef SectName;
5538 S.getName(SectName);
5539 DataRefImpl Ref = S.getRawDataRefImpl();
5540 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5541 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5542 p = S.getAddress();
5543 r = get_pointer_64(p, offset, left, S, info);
5544 if (r == nullptr)
5545 return;
5546 memset(&o, '\0', sizeof(struct objc_image_info64));
5547 if (left < sizeof(struct objc_image_info64)) {
5548 memcpy(&o, r, left);
5549 outs() << " (objc_image_info entends past the end of the section)\n";
5550 } else
5551 memcpy(&o, r, sizeof(struct objc_image_info64));
5552 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5553 swapStruct(o);
5554 outs() << " version " << o.version << "\n";
5555 outs() << " flags " << format("0x%" PRIx32, o.flags);
5556 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5557 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5558 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5559 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5560 swift_version = (o.flags >> 8) & 0xff;
5561 if (swift_version != 0) {
5562 if (swift_version == 1)
5563 outs() << " Swift 1.0";
5564 else if (swift_version == 2)
5565 outs() << " Swift 1.1";
Kevin Enderbycda2ced2018-02-09 19:31:27 +00005566 else if(swift_version == 3)
5567 outs() << " Swift 2.0";
5568 else if(swift_version == 4)
5569 outs() << " Swift 3.0";
5570 else if(swift_version == 5)
5571 outs() << " Swift 4.0";
5572 else if(swift_version == 6)
5573 outs() << " Swift 4.1";
Kevin Enderby0fc11822015-04-01 20:57:01 +00005574 else
5575 outs() << " unknown future Swift version (" << swift_version << ")";
5576 }
5577 outs() << "\n";
5578}
5579
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005580static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5581 uint32_t left, offset, swift_version, p;
5582 struct objc_image_info32 o;
5583 const char *r;
5584
Kevin Enderby19be2512016-04-21 19:49:29 +00005585 if (S == SectionRef())
5586 return;
5587
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005588 StringRef SectName;
5589 S.getName(SectName);
5590 DataRefImpl Ref = S.getRawDataRefImpl();
5591 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5592 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5593 p = S.getAddress();
5594 r = get_pointer_32(p, offset, left, S, info);
5595 if (r == nullptr)
5596 return;
5597 memset(&o, '\0', sizeof(struct objc_image_info32));
5598 if (left < sizeof(struct objc_image_info32)) {
5599 memcpy(&o, r, left);
5600 outs() << " (objc_image_info entends past the end of the section)\n";
5601 } else
5602 memcpy(&o, r, sizeof(struct objc_image_info32));
5603 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5604 swapStruct(o);
5605 outs() << " version " << o.version << "\n";
5606 outs() << " flags " << format("0x%" PRIx32, o.flags);
5607 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5608 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5609 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5610 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5611 swift_version = (o.flags >> 8) & 0xff;
5612 if (swift_version != 0) {
5613 if (swift_version == 1)
5614 outs() << " Swift 1.0";
5615 else if (swift_version == 2)
5616 outs() << " Swift 1.1";
Kevin Enderbycda2ced2018-02-09 19:31:27 +00005617 else if(swift_version == 3)
5618 outs() << " Swift 2.0";
5619 else if(swift_version == 4)
5620 outs() << " Swift 3.0";
5621 else if(swift_version == 5)
5622 outs() << " Swift 4.0";
5623 else if(swift_version == 6)
5624 outs() << " Swift 4.1";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005625 else
5626 outs() << " unknown future Swift version (" << swift_version << ")";
5627 }
5628 outs() << "\n";
5629}
5630
Kevin Enderby846c0002015-04-16 17:19:59 +00005631static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5632 uint32_t left, offset, p;
5633 struct imageInfo_t o;
5634 const char *r;
5635
5636 StringRef SectName;
5637 S.getName(SectName);
5638 DataRefImpl Ref = S.getRawDataRefImpl();
5639 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5640 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5641 p = S.getAddress();
5642 r = get_pointer_32(p, offset, left, S, info);
5643 if (r == nullptr)
5644 return;
5645 memset(&o, '\0', sizeof(struct imageInfo_t));
5646 if (left < sizeof(struct imageInfo_t)) {
5647 memcpy(&o, r, left);
5648 outs() << " (imageInfo entends past the end of the section)\n";
5649 } else
5650 memcpy(&o, r, sizeof(struct imageInfo_t));
5651 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5652 swapStruct(o);
5653 outs() << " version " << o.version << "\n";
5654 outs() << " flags " << format("0x%" PRIx32, o.flags);
5655 if (o.flags & 0x1)
5656 outs() << " F&C";
5657 if (o.flags & 0x2)
5658 outs() << " GC";
5659 if (o.flags & 0x4)
5660 outs() << " GC-only";
5661 else
5662 outs() << " RR";
5663 outs() << "\n";
5664}
5665
Kevin Enderby0fc11822015-04-01 20:57:01 +00005666static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5667 SymbolAddressMap AddrMap;
5668 if (verbose)
5669 CreateSymbolAddressMap(O, &AddrMap);
5670
5671 std::vector<SectionRef> Sections;
5672 for (const SectionRef &Section : O->sections()) {
5673 StringRef SectName;
5674 Section.getName(SectName);
5675 Sections.push_back(Section);
5676 }
5677
5678 struct DisassembleInfo info;
5679 // Set up the block of info used by the Symbolizer call backs.
5680 info.verbose = verbose;
5681 info.O = O;
5682 info.AddrMap = &AddrMap;
5683 info.Sections = &Sections;
5684 info.class_name = nullptr;
5685 info.selector_name = nullptr;
5686 info.method = nullptr;
5687 info.demangled_name = nullptr;
5688 info.bindtable = nullptr;
5689 info.adrp_addr = 0;
5690 info.adrp_inst = 0;
5691
Kevin Enderbyaac75382015-10-08 16:56:35 +00005692 info.depth = 0;
Davide Italiano62507042015-12-11 22:27:59 +00005693 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5694 if (CL == SectionRef())
5695 CL = get_section(O, "__DATA", "__objc_classlist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005696 if (CL == SectionRef())
5697 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
5698 if (CL == SectionRef())
5699 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
Davide Italiano62507042015-12-11 22:27:59 +00005700 info.S = CL;
5701 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005702
Davide Italiano62507042015-12-11 22:27:59 +00005703 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5704 if (CR == SectionRef())
5705 CR = get_section(O, "__DATA", "__objc_classrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005706 if (CR == SectionRef())
5707 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
5708 if (CR == SectionRef())
5709 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005710 info.S = CR;
5711 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005712
Davide Italiano62507042015-12-11 22:27:59 +00005713 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5714 if (SR == SectionRef())
5715 SR = get_section(O, "__DATA", "__objc_superrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005716 if (SR == SectionRef())
5717 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
5718 if (SR == SectionRef())
5719 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005720 info.S = SR;
5721 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005722
Davide Italiano62507042015-12-11 22:27:59 +00005723 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5724 if (CA == SectionRef())
5725 CA = get_section(O, "__DATA", "__objc_catlist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005726 if (CA == SectionRef())
5727 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
5728 if (CA == SectionRef())
5729 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
Davide Italiano62507042015-12-11 22:27:59 +00005730 info.S = CA;
5731 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005732
Davide Italiano62507042015-12-11 22:27:59 +00005733 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5734 if (PL == SectionRef())
5735 PL = get_section(O, "__DATA", "__objc_protolist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005736 if (PL == SectionRef())
5737 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
5738 if (PL == SectionRef())
5739 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
Davide Italiano62507042015-12-11 22:27:59 +00005740 info.S = PL;
5741 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005742
Davide Italiano62507042015-12-11 22:27:59 +00005743 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5744 if (MR == SectionRef())
5745 MR = get_section(O, "__DATA", "__objc_msgrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005746 if (MR == SectionRef())
5747 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
5748 if (MR == SectionRef())
5749 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005750 info.S = MR;
5751 print_message_refs64(MR, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005752
Davide Italiano62507042015-12-11 22:27:59 +00005753 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5754 if (II == SectionRef())
5755 II = get_section(O, "__DATA", "__objc_imageinfo");
Kevin Enderby5879a482017-02-09 17:56:26 +00005756 if (II == SectionRef())
5757 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
5758 if (II == SectionRef())
5759 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
Davide Italiano62507042015-12-11 22:27:59 +00005760 info.S = II;
5761 print_image_info64(II, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005762}
5763
5764static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005765 SymbolAddressMap AddrMap;
5766 if (verbose)
5767 CreateSymbolAddressMap(O, &AddrMap);
5768
5769 std::vector<SectionRef> Sections;
5770 for (const SectionRef &Section : O->sections()) {
5771 StringRef SectName;
5772 Section.getName(SectName);
5773 Sections.push_back(Section);
5774 }
5775
5776 struct DisassembleInfo info;
5777 // Set up the block of info used by the Symbolizer call backs.
5778 info.verbose = verbose;
5779 info.O = O;
5780 info.AddrMap = &AddrMap;
5781 info.Sections = &Sections;
5782 info.class_name = nullptr;
5783 info.selector_name = nullptr;
5784 info.method = nullptr;
5785 info.demangled_name = nullptr;
5786 info.bindtable = nullptr;
5787 info.adrp_addr = 0;
5788 info.adrp_inst = 0;
5789
Kevin Enderby5879a482017-02-09 17:56:26 +00005790 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5791 if (CL == SectionRef())
5792 CL = get_section(O, "__DATA", "__objc_classlist");
5793 if (CL == SectionRef())
5794 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
5795 if (CL == SectionRef())
5796 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
5797 info.S = CL;
5798 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005799
Kevin Enderby5879a482017-02-09 17:56:26 +00005800 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5801 if (CR == SectionRef())
5802 CR = get_section(O, "__DATA", "__objc_classrefs");
5803 if (CR == SectionRef())
5804 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
5805 if (CR == SectionRef())
5806 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
5807 info.S = CR;
5808 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005809
Kevin Enderby5879a482017-02-09 17:56:26 +00005810 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5811 if (SR == SectionRef())
5812 SR = get_section(O, "__DATA", "__objc_superrefs");
5813 if (SR == SectionRef())
5814 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
5815 if (SR == SectionRef())
5816 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
5817 info.S = SR;
5818 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005819
Kevin Enderby5879a482017-02-09 17:56:26 +00005820 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5821 if (CA == SectionRef())
5822 CA = get_section(O, "__DATA", "__objc_catlist");
5823 if (CA == SectionRef())
5824 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
5825 if (CA == SectionRef())
5826 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
5827 info.S = CA;
5828 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005829
Kevin Enderby5879a482017-02-09 17:56:26 +00005830 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5831 if (PL == SectionRef())
5832 PL = get_section(O, "__DATA", "__objc_protolist");
5833 if (PL == SectionRef())
5834 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
5835 if (PL == SectionRef())
5836 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
5837 info.S = PL;
5838 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005839
Kevin Enderby5879a482017-02-09 17:56:26 +00005840 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5841 if (MR == SectionRef())
5842 MR = get_section(O, "__DATA", "__objc_msgrefs");
5843 if (MR == SectionRef())
5844 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
5845 if (MR == SectionRef())
5846 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
5847 info.S = MR;
5848 print_message_refs32(MR, &info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005849
Kevin Enderby5879a482017-02-09 17:56:26 +00005850 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5851 if (II == SectionRef())
5852 II = get_section(O, "__DATA", "__objc_imageinfo");
5853 if (II == SectionRef())
5854 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
5855 if (II == SectionRef())
5856 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
5857 info.S = II;
5858 print_image_info32(II, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005859}
5860
5861static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby846c0002015-04-16 17:19:59 +00005862 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5863 const char *r, *name, *defs;
5864 struct objc_module_t module;
5865 SectionRef S, xS;
5866 struct objc_symtab_t symtab;
5867 struct objc_class_t objc_class;
5868 struct objc_category_t objc_category;
5869
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005870 outs() << "Objective-C segment\n";
Kevin Enderby846c0002015-04-16 17:19:59 +00005871 S = get_section(O, "__OBJC", "__module_info");
5872 if (S == SectionRef())
5873 return false;
5874
5875 SymbolAddressMap AddrMap;
5876 if (verbose)
5877 CreateSymbolAddressMap(O, &AddrMap);
5878
5879 std::vector<SectionRef> Sections;
5880 for (const SectionRef &Section : O->sections()) {
5881 StringRef SectName;
5882 Section.getName(SectName);
5883 Sections.push_back(Section);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005884 }
Kevin Enderby846c0002015-04-16 17:19:59 +00005885
5886 struct DisassembleInfo info;
5887 // Set up the block of info used by the Symbolizer call backs.
5888 info.verbose = verbose;
5889 info.O = O;
5890 info.AddrMap = &AddrMap;
5891 info.Sections = &Sections;
5892 info.class_name = nullptr;
5893 info.selector_name = nullptr;
5894 info.method = nullptr;
5895 info.demangled_name = nullptr;
5896 info.bindtable = nullptr;
5897 info.adrp_addr = 0;
5898 info.adrp_inst = 0;
5899
5900 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5901 p = S.getAddress() + i;
5902 r = get_pointer_32(p, offset, left, S, &info, true);
5903 if (r == nullptr)
5904 return true;
5905 memset(&module, '\0', sizeof(struct objc_module_t));
5906 if (left < sizeof(struct objc_module_t)) {
5907 memcpy(&module, r, left);
5908 outs() << " (module extends past end of __module_info section)\n";
5909 } else
5910 memcpy(&module, r, sizeof(struct objc_module_t));
5911 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5912 swapStruct(module);
5913
5914 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5915 outs() << " version " << module.version << "\n";
5916 outs() << " size " << module.size << "\n";
5917 outs() << " name ";
5918 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5919 if (name != nullptr)
5920 outs() << format("%.*s", left, name);
5921 else
5922 outs() << format("0x%08" PRIx32, module.name)
5923 << "(not in an __OBJC section)";
5924 outs() << "\n";
5925
5926 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5927 if (module.symtab == 0 || r == nullptr) {
5928 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5929 << " (not in an __OBJC section)\n";
5930 continue;
5931 }
5932 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5933 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5934 defs_left = 0;
5935 defs = nullptr;
5936 if (left < sizeof(struct objc_symtab_t)) {
5937 memcpy(&symtab, r, left);
5938 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5939 } else {
5940 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5941 if (left > sizeof(struct objc_symtab_t)) {
5942 defs_left = left - sizeof(struct objc_symtab_t);
5943 defs = r + sizeof(struct objc_symtab_t);
5944 }
5945 }
5946 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5947 swapStruct(symtab);
5948
5949 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5950 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5951 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5952 if (r == nullptr)
5953 outs() << " (not in an __OBJC section)";
5954 outs() << "\n";
5955 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5956 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5957 if (symtab.cls_def_cnt > 0)
5958 outs() << "\tClass Definitions\n";
5959 for (j = 0; j < symtab.cls_def_cnt; j++) {
5960 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5961 outs() << "\t(remaining class defs entries entends past the end of the "
5962 << "section)\n";
5963 break;
5964 }
5965 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5966 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5967 sys::swapByteOrder(def);
5968
5969 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5970 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5971 if (r != nullptr) {
5972 if (left > sizeof(struct objc_class_t)) {
5973 outs() << "\n";
5974 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5975 } else {
5976 outs() << " (entends past the end of the section)\n";
5977 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5978 memcpy(&objc_class, r, left);
5979 }
5980 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5981 swapStruct(objc_class);
5982 print_objc_class_t(&objc_class, &info);
5983 } else {
5984 outs() << "(not in an __OBJC section)\n";
5985 }
5986
5987 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
5988 outs() << "\tMeta Class";
5989 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
5990 if (r != nullptr) {
5991 if (left > sizeof(struct objc_class_t)) {
5992 outs() << "\n";
5993 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5994 } else {
5995 outs() << " (entends past the end of the section)\n";
5996 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5997 memcpy(&objc_class, r, left);
5998 }
5999 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6000 swapStruct(objc_class);
6001 print_objc_class_t(&objc_class, &info);
6002 } else {
6003 outs() << "(not in an __OBJC section)\n";
6004 }
6005 }
6006 }
6007 if (symtab.cat_def_cnt > 0)
6008 outs() << "\tCategory Definitions\n";
6009 for (j = 0; j < symtab.cat_def_cnt; j++) {
6010 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
6011 outs() << "\t(remaining category defs entries entends past the end of "
6012 << "the section)\n";
6013 break;
6014 }
6015 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
6016 sizeof(uint32_t));
6017 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6018 sys::swapByteOrder(def);
6019
6020 r = get_pointer_32(def, xoffset, left, xS, &info, true);
6021 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
6022 << format("0x%08" PRIx32, def);
6023 if (r != nullptr) {
6024 if (left > sizeof(struct objc_category_t)) {
6025 outs() << "\n";
6026 memcpy(&objc_category, r, sizeof(struct objc_category_t));
6027 } else {
6028 outs() << " (entends past the end of the section)\n";
6029 memset(&objc_category, '\0', sizeof(struct objc_category_t));
6030 memcpy(&objc_category, r, left);
6031 }
6032 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6033 swapStruct(objc_category);
6034 print_objc_objc_category_t(&objc_category, &info);
6035 } else {
6036 outs() << "(not in an __OBJC section)\n";
6037 }
6038 }
6039 }
6040 const SectionRef II = get_section(O, "__OBJC", "__image_info");
6041 if (II != SectionRef())
6042 print_image_info(II, &info);
6043
6044 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00006045}
6046
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00006047static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
6048 uint32_t size, uint32_t addr) {
6049 SymbolAddressMap AddrMap;
6050 CreateSymbolAddressMap(O, &AddrMap);
6051
6052 std::vector<SectionRef> Sections;
6053 for (const SectionRef &Section : O->sections()) {
6054 StringRef SectName;
6055 Section.getName(SectName);
6056 Sections.push_back(Section);
6057 }
6058
6059 struct DisassembleInfo info;
6060 // Set up the block of info used by the Symbolizer call backs.
6061 info.verbose = true;
6062 info.O = O;
6063 info.AddrMap = &AddrMap;
6064 info.Sections = &Sections;
6065 info.class_name = nullptr;
6066 info.selector_name = nullptr;
6067 info.method = nullptr;
6068 info.demangled_name = nullptr;
6069 info.bindtable = nullptr;
6070 info.adrp_addr = 0;
6071 info.adrp_inst = 0;
6072
6073 const char *p;
6074 struct objc_protocol_t protocol;
6075 uint32_t left, paddr;
6076 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
6077 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
6078 left = size - (p - sect);
6079 if (left < sizeof(struct objc_protocol_t)) {
6080 outs() << "Protocol extends past end of __protocol section\n";
6081 memcpy(&protocol, p, left);
6082 } else
6083 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
6084 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6085 swapStruct(protocol);
6086 paddr = addr + (p - sect);
6087 outs() << "Protocol " << format("0x%" PRIx32, paddr);
6088 if (print_protocol(paddr, 0, &info))
6089 outs() << "(not in an __OBJC section)\n";
6090 }
6091}
6092
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006093#ifdef HAVE_LIBXAR
6094inline void swapStruct(struct xar_header &xar) {
6095 sys::swapByteOrder(xar.magic);
6096 sys::swapByteOrder(xar.size);
6097 sys::swapByteOrder(xar.version);
6098 sys::swapByteOrder(xar.toc_length_compressed);
6099 sys::swapByteOrder(xar.toc_length_uncompressed);
6100 sys::swapByteOrder(xar.cksum_alg);
6101}
6102
6103static void PrintModeVerbose(uint32_t mode) {
6104 switch(mode & S_IFMT){
6105 case S_IFDIR:
6106 outs() << "d";
6107 break;
6108 case S_IFCHR:
6109 outs() << "c";
6110 break;
6111 case S_IFBLK:
6112 outs() << "b";
6113 break;
6114 case S_IFREG:
6115 outs() << "-";
6116 break;
6117 case S_IFLNK:
6118 outs() << "l";
6119 break;
6120 case S_IFSOCK:
6121 outs() << "s";
6122 break;
6123 default:
6124 outs() << "?";
6125 break;
6126 }
6127
6128 /* owner permissions */
6129 if(mode & S_IREAD)
6130 outs() << "r";
6131 else
6132 outs() << "-";
6133 if(mode & S_IWRITE)
6134 outs() << "w";
6135 else
6136 outs() << "-";
6137 if(mode & S_ISUID)
6138 outs() << "s";
6139 else if(mode & S_IEXEC)
6140 outs() << "x";
6141 else
6142 outs() << "-";
6143
6144 /* group permissions */
6145 if(mode & (S_IREAD >> 3))
6146 outs() << "r";
6147 else
6148 outs() << "-";
6149 if(mode & (S_IWRITE >> 3))
6150 outs() << "w";
6151 else
6152 outs() << "-";
6153 if(mode & S_ISGID)
6154 outs() << "s";
6155 else if(mode & (S_IEXEC >> 3))
6156 outs() << "x";
6157 else
6158 outs() << "-";
6159
6160 /* other permissions */
6161 if(mode & (S_IREAD >> 6))
6162 outs() << "r";
6163 else
6164 outs() << "-";
6165 if(mode & (S_IWRITE >> 6))
6166 outs() << "w";
6167 else
6168 outs() << "-";
6169 if(mode & S_ISVTX)
6170 outs() << "t";
6171 else if(mode & (S_IEXEC >> 6))
6172 outs() << "x";
6173 else
6174 outs() << "-";
6175}
6176
6177static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006178 xar_file_t xf;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006179 const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
6180 char *endp;
6181 uint32_t mode_value;
6182
Francis Ricci6f942972017-10-06 15:33:28 +00006183 ScopedXarIter xi;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006184 if (!xi) {
6185 errs() << "Can't obtain an xar iterator for xar archive "
6186 << XarFilename << "\n";
6187 return;
6188 }
6189
6190 // Go through the xar's files.
6191 for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
Francis Ricci6f942972017-10-06 15:33:28 +00006192 ScopedXarIter xp;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006193 if(!xp){
6194 errs() << "Can't obtain an xar iterator for xar archive "
6195 << XarFilename << "\n";
6196 return;
6197 }
6198 type = nullptr;
6199 mode = nullptr;
6200 user = nullptr;
6201 group = nullptr;
6202 size = nullptr;
6203 mtime = nullptr;
6204 name = nullptr;
6205 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
Jonas Devliegherec0a758d2017-09-18 14:15:57 +00006206 const char *val = nullptr;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006207 xar_prop_get(xf, key, &val);
6208#if 0 // Useful for debugging.
6209 outs() << "key: " << key << " value: " << val << "\n";
6210#endif
6211 if(strcmp(key, "type") == 0)
6212 type = val;
6213 if(strcmp(key, "mode") == 0)
6214 mode = val;
6215 if(strcmp(key, "user") == 0)
6216 user = val;
6217 if(strcmp(key, "group") == 0)
6218 group = val;
6219 if(strcmp(key, "data/size") == 0)
6220 size = val;
6221 if(strcmp(key, "mtime") == 0)
6222 mtime = val;
6223 if(strcmp(key, "name") == 0)
6224 name = val;
6225 }
6226 if(mode != nullptr){
6227 mode_value = strtoul(mode, &endp, 8);
6228 if(*endp != '\0')
6229 outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
6230 if(strcmp(type, "file") == 0)
6231 mode_value |= S_IFREG;
6232 PrintModeVerbose(mode_value);
6233 outs() << " ";
6234 }
6235 if(user != nullptr)
6236 outs() << format("%10s/", user);
6237 if(group != nullptr)
6238 outs() << format("%-10s ", group);
6239 if(size != nullptr)
6240 outs() << format("%7s ", size);
6241 if(mtime != nullptr){
6242 for(m = mtime; *m != 'T' && *m != '\0'; m++)
6243 outs() << *m;
6244 if(*m == 'T')
6245 m++;
6246 outs() << " ";
6247 for( ; *m != 'Z' && *m != '\0'; m++)
6248 outs() << *m;
6249 outs() << " ";
6250 }
6251 if(name != nullptr)
6252 outs() << name;
6253 outs() << "\n";
6254 }
6255}
6256
6257static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
6258 uint32_t size, bool verbose,
6259 bool PrintXarHeader, bool PrintXarFileHeaders,
6260 std::string XarMemberName) {
6261 if(size < sizeof(struct xar_header)) {
6262 outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
6263 "of struct xar_header)\n";
6264 return;
6265 }
6266 struct xar_header XarHeader;
6267 memcpy(&XarHeader, sect, sizeof(struct xar_header));
6268 if (sys::IsLittleEndianHost)
6269 swapStruct(XarHeader);
6270 if (PrintXarHeader) {
6271 if (!XarMemberName.empty())
6272 outs() << "In xar member " << XarMemberName << ": ";
6273 else
6274 outs() << "For (__LLVM,__bundle) section: ";
6275 outs() << "xar header\n";
6276 if (XarHeader.magic == XAR_HEADER_MAGIC)
6277 outs() << " magic XAR_HEADER_MAGIC\n";
6278 else
6279 outs() << " magic "
6280 << format_hex(XarHeader.magic, 10, true)
6281 << " (not XAR_HEADER_MAGIC)\n";
6282 outs() << " size " << XarHeader.size << "\n";
6283 outs() << " version " << XarHeader.version << "\n";
6284 outs() << " toc_length_compressed " << XarHeader.toc_length_compressed
6285 << "\n";
6286 outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
6287 << "\n";
6288 outs() << " cksum_alg ";
6289 switch (XarHeader.cksum_alg) {
6290 case XAR_CKSUM_NONE:
6291 outs() << "XAR_CKSUM_NONE\n";
6292 break;
6293 case XAR_CKSUM_SHA1:
6294 outs() << "XAR_CKSUM_SHA1\n";
6295 break;
6296 case XAR_CKSUM_MD5:
6297 outs() << "XAR_CKSUM_MD5\n";
6298 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006299#ifdef XAR_CKSUM_SHA256
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006300 case XAR_CKSUM_SHA256:
6301 outs() << "XAR_CKSUM_SHA256\n";
6302 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006303#endif
6304#ifdef XAR_CKSUM_SHA512
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006305 case XAR_CKSUM_SHA512:
6306 outs() << "XAR_CKSUM_SHA512\n";
6307 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006308#endif
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006309 default:
6310 outs() << XarHeader.cksum_alg << "\n";
6311 }
6312 }
6313
6314 SmallString<128> XarFilename;
6315 int FD;
6316 std::error_code XarEC =
6317 sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
6318 if (XarEC) {
6319 errs() << XarEC.message() << "\n";
6320 return;
6321 }
Reid Kleckner3fc649c2017-09-23 01:03:17 +00006322 ToolOutputFile XarFile(XarFilename, FD);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006323 raw_fd_ostream &XarOut = XarFile.os();
6324 StringRef XarContents(sect, size);
6325 XarOut << XarContents;
6326 XarOut.close();
6327 if (XarOut.has_error())
6328 return;
6329
Francis Ricci6f942972017-10-06 15:33:28 +00006330 ScopedXarFile xar(XarFilename.c_str(), READ);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006331 if (!xar) {
6332 errs() << "Can't create temporary xar archive " << XarFilename << "\n";
6333 return;
6334 }
6335
6336 SmallString<128> TocFilename;
6337 std::error_code TocEC =
6338 sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
6339 if (TocEC) {
6340 errs() << TocEC.message() << "\n";
6341 return;
6342 }
6343 xar_serialize(xar, TocFilename.c_str());
6344
6345 if (PrintXarFileHeaders) {
6346 if (!XarMemberName.empty())
6347 outs() << "In xar member " << XarMemberName << ": ";
6348 else
6349 outs() << "For (__LLVM,__bundle) section: ";
6350 outs() << "xar archive files:\n";
6351 PrintXarFilesSummary(XarFilename.c_str(), xar);
6352 }
6353
6354 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
6355 MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
6356 if (std::error_code EC = FileOrErr.getError()) {
6357 errs() << EC.message() << "\n";
6358 return;
6359 }
6360 std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
6361
6362 if (!XarMemberName.empty())
6363 outs() << "In xar member " << XarMemberName << ": ";
6364 else
6365 outs() << "For (__LLVM,__bundle) section: ";
6366 outs() << "xar table of contents:\n";
6367 outs() << Buffer->getBuffer() << "\n";
6368
6369 // TODO: Go through the xar's files.
Francis Ricci6f942972017-10-06 15:33:28 +00006370 ScopedXarIter xi;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006371 if(!xi){
6372 errs() << "Can't obtain an xar iterator for xar archive "
6373 << XarFilename.c_str() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006374 return;
6375 }
6376 for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
6377 const char *key;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006378 const char *member_name, *member_type, *member_size_string;
6379 size_t member_size;
6380
Francis Ricci6f942972017-10-06 15:33:28 +00006381 ScopedXarIter xp;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006382 if(!xp){
6383 errs() << "Can't obtain an xar iterator for xar archive "
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006384 << XarFilename.c_str() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006385 return;
6386 }
6387 member_name = NULL;
6388 member_type = NULL;
6389 member_size_string = NULL;
6390 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
Jonas Devliegherec0a758d2017-09-18 14:15:57 +00006391 const char *val = nullptr;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006392 xar_prop_get(xf, key, &val);
6393#if 0 // Useful for debugging.
6394 outs() << "key: " << key << " value: " << val << "\n";
6395#endif
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006396 if (strcmp(key, "name") == 0)
6397 member_name = val;
6398 if (strcmp(key, "type") == 0)
6399 member_type = val;
6400 if (strcmp(key, "data/size") == 0)
6401 member_size_string = val;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006402 }
6403 /*
6404 * If we find a file with a name, date/size and type properties
6405 * and with the type being "file" see if that is a xar file.
6406 */
6407 if (member_name != NULL && member_type != NULL &&
6408 strcmp(member_type, "file") == 0 &&
6409 member_size_string != NULL){
6410 // Extract the file into a buffer.
6411 char *endptr;
6412 member_size = strtoul(member_size_string, &endptr, 10);
6413 if (*endptr == '\0' && member_size != 0) {
Francis Ricci1bae0ac2017-09-13 13:57:45 +00006414 char *buffer;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006415 if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006416#if 0 // Useful for debugging.
NAKAMURA Takumi6f43bd42017-10-18 13:31:28 +00006417 outs() << "xar member: " << member_name << " extracted\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006418#endif
6419 // Set the XarMemberName we want to see printed in the header.
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006420 std::string OldXarMemberName;
6421 // If XarMemberName is already set this is nested. So
6422 // save the old name and create the nested name.
6423 if (!XarMemberName.empty()) {
6424 OldXarMemberName = XarMemberName;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006425 XarMemberName =
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006426 (Twine("[") + XarMemberName + "]" + member_name).str();
6427 } else {
6428 OldXarMemberName = "";
6429 XarMemberName = member_name;
6430 }
6431 // See if this is could be a xar file (nested).
6432 if (member_size >= sizeof(struct xar_header)) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006433#if 0 // Useful for debugging.
NAKAMURA Takumi6f43bd42017-10-18 13:31:28 +00006434 outs() << "could be a xar file: " << member_name << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006435#endif
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006436 memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006437 if (sys::IsLittleEndianHost)
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006438 swapStruct(XarHeader);
6439 if (XarHeader.magic == XAR_HEADER_MAGIC)
6440 DumpBitcodeSection(O, buffer, member_size, verbose,
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006441 PrintXarHeader, PrintXarFileHeaders,
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006442 XarMemberName);
6443 }
6444 XarMemberName = OldXarMemberName;
Francis Ricci1bae0ac2017-09-13 13:57:45 +00006445 delete buffer;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006446 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006447 }
6448 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006449 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006450}
6451#endif // defined(HAVE_LIBXAR)
6452
Kevin Enderby0fc11822015-04-01 20:57:01 +00006453static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6454 if (O->is64Bit())
6455 printObjc2_64bit_MetaData(O, verbose);
6456 else {
6457 MachO::mach_header H;
6458 H = O->getHeader();
6459 if (H.cputype == MachO::CPU_TYPE_ARM)
6460 printObjc2_32bit_MetaData(O, verbose);
6461 else {
6462 // This is the 32-bit non-arm cputype case. Which is normally
6463 // the first Objective-C ABI. But it may be the case of a
6464 // binary for the iOS simulator which is the second Objective-C
6465 // ABI. In that case printObjc1_32bit_MetaData() will determine that
6466 // and return false.
Hans Wennborgcc9deb42015-09-29 18:02:48 +00006467 if (!printObjc1_32bit_MetaData(O, verbose))
Kevin Enderby0fc11822015-04-01 20:57:01 +00006468 printObjc2_32bit_MetaData(O, verbose);
6469 }
6470 }
6471}
6472
Kevin Enderbybf246f52014-09-24 23:08:22 +00006473// GuessLiteralPointer returns a string which for the item in the Mach-O file
6474// for the address passed in as ReferenceValue for printing as a comment with
6475// the instruction and also returns the corresponding type of that item
6476// indirectly through ReferenceType.
6477//
6478// If ReferenceValue is an address of literal cstring then a pointer to the
6479// cstring is returned and ReferenceType is set to
6480// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6481//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006482// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6483// Class ref that name is returned and the ReferenceType is set accordingly.
6484//
6485// Lastly, literals which are Symbol address in a literal pool are looked for
6486// and if found the symbol name is returned and ReferenceType is set to
6487// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6488//
6489// If there is no item in the Mach-O file for the address passed in as
6490// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006491static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6492 uint64_t ReferencePC,
6493 uint64_t *ReferenceType,
6494 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006495 // First see if there is an external relocation entry at the ReferencePC.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006496 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6497 uint64_t sect_addr = info->S.getAddress();
6498 uint64_t sect_offset = ReferencePC - sect_addr;
6499 bool reloc_found = false;
6500 DataRefImpl Rel;
6501 MachO::any_relocation_info RE;
6502 bool isExtern = false;
6503 SymbolRef Symbol;
6504 for (const RelocationRef &Reloc : info->S.relocations()) {
6505 uint64_t RelocOffset = Reloc.getOffset();
6506 if (RelocOffset == sect_offset) {
6507 Rel = Reloc.getRawDataRefImpl();
6508 RE = info->O->getRelocation(Rel);
6509 if (info->O->isRelocationScattered(RE))
6510 continue;
6511 isExtern = info->O->getPlainRelocationExternal(RE);
6512 if (isExtern) {
6513 symbol_iterator RelocSym = Reloc.getSymbol();
6514 Symbol = *RelocSym;
6515 }
6516 reloc_found = true;
6517 break;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006518 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006519 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006520 // If there is an external relocation entry for a symbol in a section
6521 // then used that symbol's value for the value of the reference.
6522 if (reloc_found && isExtern) {
6523 if (info->O->getAnyRelocationPCRel(RE)) {
6524 unsigned Type = info->O->getAnyRelocationType(RE);
6525 if (Type == MachO::X86_64_RELOC_SIGNED) {
6526 ReferenceValue = Symbol.getValue();
6527 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006528 }
6529 }
6530 }
6531
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006532 // Look for literals such as Objective-C CFStrings refs, Selector refs,
6533 // Message refs and Class refs.
6534 bool classref, selref, msgref, cfstring;
6535 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6536 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00006537 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006538 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6539 // And the pointer_value in that section is typically zero as it will be
6540 // set by dyld as part of the "bind information".
6541 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6542 if (name != nullptr) {
6543 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00006544 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006545 if (class_name != nullptr && class_name[1] == '_' &&
6546 class_name[2] != '\0') {
6547 info->class_name = class_name + 2;
6548 return name;
6549 }
6550 }
6551 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006552
David Blaikie33dd45d02015-03-23 18:39:02 +00006553 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006554 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6555 const char *name =
6556 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6557 if (name != nullptr)
6558 info->class_name = name;
6559 else
6560 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00006561 return name;
6562 }
6563
David Blaikie33dd45d02015-03-23 18:39:02 +00006564 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006565 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6566 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6567 return name;
6568 }
6569
David Blaikie33dd45d02015-03-23 18:39:02 +00006570 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006571 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6572
6573 if (pointer_value != 0)
6574 ReferenceValue = pointer_value;
6575
6576 const char *name = GuessCstringPointer(ReferenceValue, info);
6577 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00006578 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006579 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6580 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00006581 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006582 info->class_name = nullptr;
6583 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6584 info->selector_name = name;
6585 } else
6586 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6587 return name;
6588 }
6589
6590 // Lastly look for an indirect symbol with this ReferenceValue which is in
6591 // a literal pool. If found return that symbol name.
6592 name = GuessIndirectSymbol(ReferenceValue, info);
6593 if (name) {
6594 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6595 return name;
6596 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006597
6598 return nullptr;
6599}
6600
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006601// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00006602// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006603// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6604// is created and returns the symbol name that matches the ReferenceValue or
6605// nullptr if none. The ReferenceType is passed in for the IN type of
6606// reference the instruction is making from the values in defined in the header
6607// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
6608// Out type and the ReferenceName will also be set which is added as a comment
6609// to the disassembled instruction.
6610//
Kevin Enderby04bf6932014-10-28 23:39:46 +00006611// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006612// returned through ReferenceName and ReferenceType is set to
6613// LLVMDisassembler_ReferenceType_DeMangled_Name .
6614//
6615// When this is called to get a symbol name for a branch target then the
6616// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
6617// SymbolValue will be looked for in the indirect symbol table to determine if
6618// it is an address for a symbol stub. If so then the symbol name for that
6619// stub is returned indirectly through ReferenceName and then ReferenceType is
6620// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
6621//
Kevin Enderbybf246f52014-09-24 23:08:22 +00006622// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006623// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
6624// SymbolValue is checked to be an address of literal pointer, symbol pointer,
6625// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006626// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006627static const char *SymbolizerSymbolLookUp(void *DisInfo,
6628 uint64_t ReferenceValue,
6629 uint64_t *ReferenceType,
6630 uint64_t ReferencePC,
6631 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006632 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006633 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00006634 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006635 *ReferenceName = nullptr;
6636 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006637 return nullptr;
6638 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006639
Kevin Enderbyf6d25852015-01-31 00:37:11 +00006640 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006641
Kevin Enderby85974882014-09-26 22:20:44 +00006642 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
6643 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006644 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006645 method_reference(info, ReferenceType, ReferenceName);
6646 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
6647 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
Rafael Espindolab940b662016-09-06 19:16:48 +00006648 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006649 if (info->demangled_name != nullptr)
6650 free(info->demangled_name);
6651 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006652 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00006653 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006654 if (info->demangled_name != nullptr) {
6655 *ReferenceName = info->demangled_name;
6656 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6657 } else
6658 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6659 } else
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006660 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6661 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
6662 *ReferenceName =
6663 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00006664 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006665 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00006666 else
6667 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006668 // If this is arm64 and the reference is an adrp instruction save the
6669 // instruction, passed in ReferenceValue and the address of the instruction
6670 // for use later if we see and add immediate instruction.
6671 } else if (info->O->getArch() == Triple::aarch64 &&
6672 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
6673 info->adrp_inst = ReferenceValue;
6674 info->adrp_addr = ReferencePC;
6675 SymbolName = nullptr;
6676 *ReferenceName = nullptr;
6677 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6678 // If this is arm64 and reference is an add immediate instruction and we
6679 // have
6680 // seen an adrp instruction just before it and the adrp's Xd register
6681 // matches
6682 // this add's Xn register reconstruct the value being referenced and look to
6683 // see if it is a literal pointer. Note the add immediate instruction is
6684 // passed in ReferenceValue.
6685 } else if (info->O->getArch() == Triple::aarch64 &&
6686 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
6687 ReferencePC - 4 == info->adrp_addr &&
6688 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6689 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6690 uint32_t addxri_inst;
6691 uint64_t adrp_imm, addxri_imm;
6692
6693 adrp_imm =
6694 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6695 if (info->adrp_inst & 0x0200000)
6696 adrp_imm |= 0xfffffffffc000000LL;
6697
6698 addxri_inst = ReferenceValue;
6699 addxri_imm = (addxri_inst >> 10) & 0xfff;
6700 if (((addxri_inst >> 22) & 0x3) == 1)
6701 addxri_imm <<= 12;
6702
6703 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6704 (adrp_imm << 12) + addxri_imm;
6705
6706 *ReferenceName =
6707 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6708 if (*ReferenceName == nullptr)
6709 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6710 // If this is arm64 and the reference is a load register instruction and we
6711 // have seen an adrp instruction just before it and the adrp's Xd register
6712 // matches this add's Xn register reconstruct the value being referenced and
6713 // look to see if it is a literal pointer. Note the load register
6714 // instruction is passed in ReferenceValue.
6715 } else if (info->O->getArch() == Triple::aarch64 &&
6716 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
6717 ReferencePC - 4 == info->adrp_addr &&
6718 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6719 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6720 uint32_t ldrxui_inst;
6721 uint64_t adrp_imm, ldrxui_imm;
6722
6723 adrp_imm =
6724 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6725 if (info->adrp_inst & 0x0200000)
6726 adrp_imm |= 0xfffffffffc000000LL;
6727
6728 ldrxui_inst = ReferenceValue;
6729 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
6730
6731 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6732 (adrp_imm << 12) + (ldrxui_imm << 3);
6733
6734 *ReferenceName =
6735 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6736 if (*ReferenceName == nullptr)
6737 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6738 }
6739 // If this arm64 and is an load register (PC-relative) instruction the
6740 // ReferenceValue is the PC plus the immediate value.
6741 else if (info->O->getArch() == Triple::aarch64 &&
6742 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
6743 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
6744 *ReferenceName =
6745 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6746 if (*ReferenceName == nullptr)
6747 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Rafael Espindolab940b662016-09-06 19:16:48 +00006748 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006749 if (info->demangled_name != nullptr)
6750 free(info->demangled_name);
6751 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006752 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00006753 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006754 if (info->demangled_name != nullptr) {
6755 *ReferenceName = info->demangled_name;
6756 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6757 }
6758 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006759 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006760 *ReferenceName = nullptr;
6761 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6762 }
6763
6764 return SymbolName;
6765}
6766
Kevin Enderbybf246f52014-09-24 23:08:22 +00006767/// \brief Emits the comments that are stored in the CommentStream.
6768/// Each comment in the CommentStream must end with a newline.
6769static void emitComments(raw_svector_ostream &CommentStream,
6770 SmallString<128> &CommentsToEmit,
6771 formatted_raw_ostream &FormattedOS,
6772 const MCAsmInfo &MAI) {
6773 // Flush the stream before taking its content.
Kevin Enderbybf246f52014-09-24 23:08:22 +00006774 StringRef Comments = CommentsToEmit.str();
6775 // Get the default information for printing a comment.
Mehdi Amini36d33fc2016-10-01 06:46:33 +00006776 StringRef CommentBegin = MAI.getCommentString();
Kevin Enderbybf246f52014-09-24 23:08:22 +00006777 unsigned CommentColumn = MAI.getCommentColumn();
6778 bool IsFirst = true;
6779 while (!Comments.empty()) {
6780 if (!IsFirst)
6781 FormattedOS << '\n';
6782 // Emit a line of comments.
6783 FormattedOS.PadToColumn(CommentColumn);
6784 size_t Position = Comments.find('\n');
6785 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
6786 // Move after the newline character.
6787 Comments = Comments.substr(Position + 1);
6788 IsFirst = false;
6789 }
6790 FormattedOS.flush();
6791
6792 // Tell the comment stream that the vector changed underneath it.
6793 CommentsToEmit.clear();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006794}
6795
Kevin Enderby95df54c2015-02-04 01:01:38 +00006796static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
6797 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006798 const char *McpuDefault = nullptr;
6799 const Target *ThumbTarget = nullptr;
6800 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006801 if (!TheTarget) {
6802 // GetTarget prints out stuff.
6803 return;
6804 }
Kevin Enderbyf310e622017-09-21 21:45:02 +00006805 std::string MachOMCPU;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006806 if (MCPU.empty() && McpuDefault)
Kevin Enderbyf310e622017-09-21 21:45:02 +00006807 MachOMCPU = McpuDefault;
6808 else
6809 MachOMCPU = MCPU;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006810
Ahmed Charles56440fd2014-03-06 05:51:42 +00006811 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006812 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006813 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006814 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006815
Kevin Enderbyc9595622014-08-06 23:24:41 +00006816 // Package up features to be passed to target/subtarget
6817 std::string FeaturesStr;
6818 if (MAttrs.size()) {
6819 SubtargetFeatures Features;
6820 for (unsigned i = 0; i != MAttrs.size(); ++i)
6821 Features.AddFeature(MAttrs[i]);
6822 FeaturesStr = Features.getString();
6823 }
6824
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006825 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00006826 std::unique_ptr<const MCRegisterInfo> MRI(
6827 TheTarget->createMCRegInfo(TripleName));
6828 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00006829 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00006830 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyf310e622017-09-21 21:45:02 +00006831 TheTarget->createMCSubtargetInfo(TripleName, MachOMCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00006832 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006833 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006834 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006835 std::unique_ptr<MCSymbolizer> Symbolizer;
6836 struct DisassembleInfo SymbolizerInfo;
6837 std::unique_ptr<MCRelocationInfo> RelInfo(
6838 TheTarget->createMCRelocationInfo(TripleName, Ctx));
6839 if (RelInfo) {
6840 Symbolizer.reset(TheTarget->createMCSymbolizer(
6841 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006842 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006843 DisAsm->setSymbolizer(std::move(Symbolizer));
6844 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006845 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00006846 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006847 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006848 // Set the display preference for hex vs. decimal immediates.
6849 IP->setPrintImmHex(PrintImmHex);
6850 // Comment stream and backing vector.
6851 SmallString<128> CommentsToEmit;
6852 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006853 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
6854 // if it is done then arm64 comments for string literals don't get printed
6855 // and some constant get printed instead and not setting it causes intel
6856 // (32-bit and 64-bit) comments printed with different spacing before the
6857 // comment causing different diffs with the 'C' disassembler library API.
6858 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006859
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006860 if (!AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencerc1363cf2011-10-07 19:25:47 +00006861 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006862 << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006863 return;
6864 }
6865
Tim Northover09ca33e2016-04-22 23:23:31 +00006866 // Set up separate thumb disassembler if needed.
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006867 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
6868 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
6869 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006870 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006871 std::unique_ptr<MCInstPrinter> ThumbIP;
6872 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006873 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
6874 struct DisassembleInfo ThumbSymbolizerInfo;
6875 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006876 if (ThumbTarget) {
6877 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
6878 ThumbAsmInfo.reset(
6879 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
6880 ThumbSTI.reset(
Kevin Enderbyf310e622017-09-21 21:45:02 +00006881 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MachOMCPU,
6882 FeaturesStr));
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006883 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
6884 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006885 MCContext *PtrThumbCtx = ThumbCtx.get();
6886 ThumbRelInfo.reset(
6887 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
6888 if (ThumbRelInfo) {
6889 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
6890 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006891 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006892 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
6893 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006894 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
6895 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006896 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
6897 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006898 // Set the display preference for hex vs. decimal immediates.
6899 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006900 }
6901
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006902 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006903 errs() << "error: couldn't initialize disassembler for target "
6904 << ThumbTripleName << '\n';
6905 return;
6906 }
6907
Charles Davis8bdfafd2013-09-01 04:28:48 +00006908 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006909
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006910 // FIXME: Using the -cfg command line option, this code used to be able to
6911 // annotate relocations with the referenced symbol's name, and if this was
6912 // inside a __[cf]string section, the data it points to. This is now replaced
6913 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00006914 std::vector<SectionRef> Sections;
6915 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006916 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00006917 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006918
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00006919 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
Kevin Enderby273ae012013-06-06 17:20:50 +00006920 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006921
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006922 // Sort the symbols by address, just in case they didn't come in that way.
Owen Andersond9243c42011-10-17 21:37:35 +00006923 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006924
Kevin Enderby273ae012013-06-06 17:20:50 +00006925 // Build a data in code table that is sorted on by the address of each entry.
6926 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00006927 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00006928 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00006929 else
6930 BaseAddress = BaseSegmentAddress;
6931 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00006932 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00006933 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006934 uint32_t Offset;
6935 DI->getOffset(Offset);
6936 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6937 }
6938 array_pod_sort(Dices.begin(), Dices.end());
6939
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006940#ifndef NDEBUG
6941 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6942#else
6943 raw_ostream &DebugOut = nulls();
6944#endif
6945
Ahmed Charles56440fd2014-03-06 05:51:42 +00006946 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00006947 ObjectFile *DbgObj = MachOOF;
Benjamin Kramer699128e2011-09-21 01:13:19 +00006948 // Try to find debug info and set up the DIContext for it.
6949 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00006950 // A separate DSym file path was specified, parse it as a macho file,
6951 // get the sections and supply it to the section name parsing machinery.
6952 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00006953 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006954 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00006955 if (std::error_code EC = BufOrErr.getError()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006956 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +00006957 return;
6958 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00006959 DbgObj =
6960 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
6961 .get()
6962 .release();
Benjamin Kramer699128e2011-09-21 01:13:19 +00006963 }
6964
Eric Christopher7370b552012-11-12 21:40:38 +00006965 // Setup the DIContext
Rafael Espindolac398e672017-07-19 22:27:28 +00006966 diContext = DWARFContext::create(*DbgObj);
Benjamin Kramer699128e2011-09-21 01:13:19 +00006967 }
6968
Colin LeMahieufcc32762015-07-29 19:08:10 +00006969 if (FilterSections.size() == 0)
Kevin Enderby95df54c2015-02-04 01:01:38 +00006970 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006971
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006972 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00006973 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00006974 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6975 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006976
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006977 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006978
Rafael Espindolab0f76a42013-04-05 15:15:22 +00006979 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00006980 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006981 continue;
6982
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006983 StringRef BytesStr;
6984 Sections[SectIdx].getContents(BytesStr);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00006985 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6986 BytesStr.size());
Rafael Espindola80291272014-10-08 15:28:58 +00006987 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00006988
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006989 bool symbolTableWorked = false;
6990
Kevin Enderbybf246f52014-09-24 23:08:22 +00006991 // Create a map of symbol addresses to symbol names for use by
6992 // the SymbolizerSymbolLookUp() routine.
6993 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00006994 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006995 for (const SymbolRef &Symbol : MachOOF->symbols()) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006996 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006997 if (!STOrErr)
6998 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006999 SymbolRef::Type ST = *STOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007000 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
7001 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00007002 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007003 Expected<StringRef> SymNameOrErr = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007004 if (!SymNameOrErr)
7005 report_error(MachOOF->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007006 StringRef SymName = *SymNameOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007007 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00007008 if (!DisSymName.empty() && DisSymName == SymName)
7009 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007010 }
7011 }
David Blaikie33dd45d02015-03-23 18:39:02 +00007012 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00007013 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
7014 return;
7015 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007016 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00007017 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007018 SymbolizerInfo.O = MachOOF;
7019 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00007020 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007021 SymbolizerInfo.Sections = &Sections;
7022 SymbolizerInfo.class_name = nullptr;
7023 SymbolizerInfo.selector_name = nullptr;
7024 SymbolizerInfo.method = nullptr;
Kevin Enderby04bf6932014-10-28 23:39:46 +00007025 SymbolizerInfo.demangled_name = nullptr;
Kevin Enderby078be602014-10-23 19:53:12 +00007026 SymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00007027 SymbolizerInfo.adrp_addr = 0;
7028 SymbolizerInfo.adrp_inst = 0;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007029 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00007030 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007031 ThumbSymbolizerInfo.O = MachOOF;
7032 ThumbSymbolizerInfo.S = Sections[SectIdx];
7033 ThumbSymbolizerInfo.AddrMap = &AddrMap;
7034 ThumbSymbolizerInfo.Sections = &Sections;
7035 ThumbSymbolizerInfo.class_name = nullptr;
7036 ThumbSymbolizerInfo.selector_name = nullptr;
7037 ThumbSymbolizerInfo.method = nullptr;
7038 ThumbSymbolizerInfo.demangled_name = nullptr;
7039 ThumbSymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00007040 ThumbSymbolizerInfo.adrp_addr = 0;
7041 ThumbSymbolizerInfo.adrp_inst = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007042
Kevin Enderby4b627be2016-04-28 20:14:13 +00007043 unsigned int Arch = MachOOF->getArch();
7044
Tim Northoverf203ab52016-07-14 22:13:32 +00007045 // Skip all symbols if this is a stubs file.
7046 if (Bytes.size() == 0)
7047 return;
7048
Kevin Enderbyc138da32017-02-06 18:43:18 +00007049 // If the section has symbols but no symbol at the start of the section
7050 // these are used to make sure the bytes before the first symbol are
7051 // disassembled.
7052 bool FirstSymbol = true;
7053 bool FirstSymbolAtSectionStart = true;
7054
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007055 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007056 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007057 Expected<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007058 if (!SymNameOrErr)
7059 report_error(MachOOF->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007060 StringRef SymName = *SymNameOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00007061
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007062 Expected<SymbolRef::Type> STOrErr = Symbols[SymIdx].getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007063 if (!STOrErr)
7064 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00007065 SymbolRef::Type ST = *STOrErr;
Kuba Breckade833222015-11-12 09:40:29 +00007066 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
Owen Andersond9243c42011-10-17 21:37:35 +00007067 continue;
7068
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007069 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00007070 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00007071 if (!containsSym) {
7072 if (!DisSymName.empty() && DisSymName == SymName) {
7073 outs() << "-dis-symname: " << DisSymName << " not in the section\n";
7074 return;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00007075 }
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00007076 continue;
7077 }
7078 // The __mh_execute_header is special and we need to deal with that fact
7079 // this symbol is before the start of the (__TEXT,__text) section and at the
7080 // address of the start of the __TEXT segment. This is because this symbol
7081 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
7082 // start of the section in a standard MH_EXECUTE filetype.
7083 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
7084 outs() << "-dis-symname: __mh_execute_header not in any section\n";
7085 return;
7086 }
Tim Northoverfbefee32016-07-14 23:13:03 +00007087 // When this code is trying to disassemble a symbol at a time and in the
7088 // case there is only the __mh_execute_header symbol left as in a stripped
7089 // executable, we need to deal with this by ignoring this symbol so the
7090 // whole section is disassembled and this symbol is then not displayed.
7091 if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
7092 SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
7093 SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007094 continue;
7095
Kevin Enderby6a221752015-03-17 17:10:57 +00007096 // If we are only disassembling one symbol see if this is that symbol.
7097 if (!DisSymName.empty() && DisSymName != SymName)
7098 continue;
7099
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007100 // Start at the address of the symbol relative to the section's address.
Tim Northoverf203ab52016-07-14 22:13:32 +00007101 uint64_t SectSize = Sections[SectIdx].getSize();
Rafael Espindoladea00162015-07-03 17:44:18 +00007102 uint64_t Start = Symbols[SymIdx].getValue();
Rafael Espindola80291272014-10-08 15:28:58 +00007103 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Cameron Zwarich54478a52012-02-03 05:42:17 +00007104 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00007105
Tim Northoverf203ab52016-07-14 22:13:32 +00007106 if (Start > SectSize) {
7107 outs() << "section data ends, " << SymName
7108 << " lies outside valid range\n";
7109 return;
7110 }
7111
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007112 // Stop disassembling either at the beginning of the next symbol or at
7113 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00007114 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00007115 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007116 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00007117 while (Symbols.size() > NextSymIdx) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007118 Expected<SymbolRef::Type> STOrErr = Symbols[NextSymIdx].getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007119 if (!STOrErr)
7120 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00007121 SymbolRef::Type NextSymType = *STOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00007122 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00007123 containsNextSym =
7124 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Rafael Espindoladea00162015-07-03 17:44:18 +00007125 NextSym = Symbols[NextSymIdx].getValue();
Cameron Zwarich54478a52012-02-03 05:42:17 +00007126 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00007127 break;
7128 }
7129 ++NextSymIdx;
7130 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007131
Tim Northoverf203ab52016-07-14 22:13:32 +00007132 uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00007133 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007134
7135 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00007136
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007137 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
Tim Northover09ca33e2016-04-22 23:23:31 +00007138 bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
7139
7140 // We only need the dedicated Thumb target if there's a real choice
7141 // (i.e. we're not targeting M-class) and the function is Thumb.
7142 bool UseThumbTarget = IsThumb && ThumbTarget;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007143
Kevin Enderbyc138da32017-02-06 18:43:18 +00007144 // If we are not specifying a symbol to start disassembly with and this
7145 // is the first symbol in the section but not at the start of the section
7146 // then move the disassembly index to the start of the section and
7147 // don't print the symbol name just yet. This is so the bytes before the
7148 // first symbol are disassembled.
7149 uint64_t SymbolStart = Start;
7150 if (DisSymName.empty() && FirstSymbol && Start != 0) {
7151 FirstSymbolAtSectionStart = false;
7152 Start = 0;
7153 }
7154 else
7155 outs() << SymName << ":\n";
7156
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007157 DILineInfo lastLine;
7158 for (uint64_t Index = Start; Index < End; Index += Size) {
7159 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00007160
Kevin Enderbyc138da32017-02-06 18:43:18 +00007161 // If this is the first symbol in the section and it was not at the
7162 // start of the section, see if we are at its Index now and if so print
7163 // the symbol name.
7164 if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
7165 outs() << SymName << ":\n";
7166
Kevin Enderbybf246f52014-09-24 23:08:22 +00007167 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00007168 if (!NoLeadingAddr) {
7169 if (FullLeadingAddr) {
7170 if (MachOOF->is64Bit())
7171 outs() << format("%016" PRIx64, PC);
7172 else
7173 outs() << format("%08" PRIx64, PC);
7174 } else {
7175 outs() << format("%8" PRIx64 ":", PC);
7176 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00007177 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00007178 if (!NoShowRawInsn || Arch == Triple::arm)
Kevin Enderbybf246f52014-09-24 23:08:22 +00007179 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00007180
7181 // Check the data in code table here to see if this is data not an
7182 // instruction to be disassembled.
7183 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007184 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007185 dice_table_iterator DTI =
7186 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
7187 compareDiceTableEntries);
7188 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00007189 uint16_t Length;
7190 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00007191 uint16_t Kind;
7192 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00007193 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00007194 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
7195 (PC == (DTI->first + Length - 1)) && (Length & 1))
7196 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00007197 continue;
7198 }
7199
Kevin Enderbybf246f52014-09-24 23:08:22 +00007200 SmallVector<char, 64> AnnotationsBytes;
7201 raw_svector_ostream Annotations(AnnotationsBytes);
7202
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007203 bool gotInst;
Tim Northover09ca33e2016-04-22 23:23:31 +00007204 if (UseThumbTarget)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007205 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007206 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007207 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007208 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00007209 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007210 if (gotInst) {
Kevin Enderby4b627be2016-04-28 20:14:13 +00007211 if (!NoShowRawInsn || Arch == Triple::arm) {
Craig Topper0013be12015-09-21 05:32:41 +00007212 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007213 }
7214 formatted_raw_ostream FormattedOS(outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007215 StringRef AnnotationsStr = Annotations.str();
Tim Northover09ca33e2016-04-22 23:23:31 +00007216 if (UseThumbTarget)
Akira Hatanakab46d0232015-03-27 20:36:02 +00007217 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007218 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00007219 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00007220 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00007221
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007222 // Print debug info.
7223 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007224 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007225 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00007226 if (dli != lastLine && dli.Line != 0)
7227 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
7228 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007229 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007230 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007231 outs() << "\n";
7232 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007233 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007234 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007235 outs() << format("\t.byte 0x%02x #bad opcode\n",
7236 *(Bytes.data() + Index) & 0xff);
7237 Size = 1; // skip exactly one illegible byte and move on.
Tim Northover09ca33e2016-04-22 23:23:31 +00007238 } else if (Arch == Triple::aarch64 ||
7239 (Arch == Triple::arm && !IsThumb)) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007240 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7241 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
7242 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
7243 (*(Bytes.data() + Index + 3) & 0xff) << 24;
7244 outs() << format("\t.long\t0x%08x\n", opcode);
7245 Size = 4;
Tim Northover09ca33e2016-04-22 23:23:31 +00007246 } else if (Arch == Triple::arm) {
7247 assert(IsThumb && "ARM mode should have been dealt with above");
7248 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7249 (*(Bytes.data() + Index + 1) & 0xff) << 8;
7250 outs() << format("\t.short\t0x%04x\n", opcode);
7251 Size = 2;
7252 } else{
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007253 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
7254 if (Size == 0)
7255 Size = 1; // skip illegible bytes
7256 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007257 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007258 }
Kevin Enderbyc138da32017-02-06 18:43:18 +00007259 // Now that we are done disassembled the first symbol set the bool that
7260 // were doing this to false.
7261 FirstSymbol = false;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007262 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007263 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00007264 // Reading the symbol table didn't work, disassemble the whole section.
7265 uint64_t SectAddress = Sections[SectIdx].getAddress();
7266 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00007267 uint64_t InstSize;
7268 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00007269 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00007270
Kevin Enderbybf246f52014-09-24 23:08:22 +00007271 uint64_t PC = SectAddress + Index;
Kevin Enderby02d3a372017-01-31 18:09:10 +00007272 SmallVector<char, 64> AnnotationsBytes;
7273 raw_svector_ostream Annotations(AnnotationsBytes);
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007274 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
Kevin Enderby02d3a372017-01-31 18:09:10 +00007275 DebugOut, Annotations)) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00007276 if (!NoLeadingAddr) {
7277 if (FullLeadingAddr) {
7278 if (MachOOF->is64Bit())
7279 outs() << format("%016" PRIx64, PC);
7280 else
7281 outs() << format("%08" PRIx64, PC);
7282 } else {
7283 outs() << format("%8" PRIx64 ":", PC);
7284 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00007285 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00007286 if (!NoShowRawInsn || Arch == Triple::arm) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00007287 outs() << "\t";
Craig Topper0013be12015-09-21 05:32:41 +00007288 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007289 }
Kevin Enderby02d3a372017-01-31 18:09:10 +00007290 StringRef AnnotationsStr = Annotations.str();
7291 IP->printInst(&Inst, outs(), AnnotationsStr, *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00007292 outs() << "\n";
7293 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007294 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007295 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007296 outs() << format("\t.byte 0x%02x #bad opcode\n",
7297 *(Bytes.data() + Index) & 0xff);
7298 InstSize = 1; // skip exactly one illegible byte and move on.
7299 } else {
7300 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
7301 if (InstSize == 0)
7302 InstSize = 1; // skip illegible bytes
7303 }
Bill Wendling4e68e062012-07-19 00:17:40 +00007304 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00007305 }
7306 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00007307 // The TripleName's need to be reset if we are called again for a different
7308 // archtecture.
7309 TripleName = "";
7310 ThumbTripleName = "";
7311
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007312 if (SymbolizerInfo.method != nullptr)
7313 free(SymbolizerInfo.method);
Kevin Enderby04bf6932014-10-28 23:39:46 +00007314 if (SymbolizerInfo.demangled_name != nullptr)
7315 free(SymbolizerInfo.demangled_name);
Kevin Enderby930fdc72014-11-06 19:00:13 +00007316 if (ThumbSymbolizerInfo.method != nullptr)
7317 free(ThumbSymbolizerInfo.method);
7318 if (ThumbSymbolizerInfo.demangled_name != nullptr)
7319 free(ThumbSymbolizerInfo.demangled_name);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007320 }
7321}
Tim Northover4bd286a2014-08-01 13:07:19 +00007322
Tim Northover39c70bb2014-08-12 11:52:59 +00007323//===----------------------------------------------------------------------===//
7324// __compact_unwind section dumping
7325//===----------------------------------------------------------------------===//
7326
Tim Northover4bd286a2014-08-01 13:07:19 +00007327namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00007328
Tim Northover3a4e1c72018-01-23 13:51:57 +00007329template <typename T>
7330static uint64_t read(StringRef Contents, ptrdiff_t Offset) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007331 using llvm::support::little;
7332 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00007333
Tim Northover3a4e1c72018-01-23 13:51:57 +00007334 if (Offset + sizeof(T) > Contents.size()) {
7335 outs() << "warning: attempt to read past end of buffer\n";
7336 return T();
7337 }
7338
7339 uint64_t Val =
7340 support::endian::read<T, little, unaligned>(Contents.data() + Offset);
7341 return Val;
7342}
7343
7344template <typename T>
7345static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) {
7346 T Val = read<T>(Contents, Offset);
7347 Offset += sizeof(T);
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007348 return Val;
7349}
Tim Northover39c70bb2014-08-12 11:52:59 +00007350
Tim Northover4bd286a2014-08-01 13:07:19 +00007351struct CompactUnwindEntry {
7352 uint32_t OffsetInSection;
7353
7354 uint64_t FunctionAddr;
7355 uint32_t Length;
7356 uint32_t CompactEncoding;
7357 uint64_t PersonalityAddr;
7358 uint64_t LSDAAddr;
7359
7360 RelocationRef FunctionReloc;
7361 RelocationRef PersonalityReloc;
7362 RelocationRef LSDAReloc;
7363
7364 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007365 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007366 if (Is64)
Tim Northover3a4e1c72018-01-23 13:51:57 +00007367 read<uint64_t>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007368 else
Tim Northover3a4e1c72018-01-23 13:51:57 +00007369 read<uint32_t>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007370 }
7371
7372private:
Tim Northover3a4e1c72018-01-23 13:51:57 +00007373 template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) {
7374 FunctionAddr = readNext<UIntPtr>(Contents, Offset);
7375 Length = readNext<uint32_t>(Contents, Offset);
7376 CompactEncoding = readNext<uint32_t>(Contents, Offset);
7377 PersonalityAddr = readNext<UIntPtr>(Contents, Offset);
7378 LSDAAddr = readNext<UIntPtr>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007379 }
7380};
7381}
7382
7383/// Given a relocation from __compact_unwind, consisting of the RelocationRef
7384/// and data being relocated, determine the best base Name and Addend to use for
7385/// display purposes.
7386///
7387/// 1. An Extern relocation will directly reference a symbol (and the data is
7388/// then already an addend), so use that.
7389/// 2. Otherwise the data is an offset in the object file's layout; try to find
7390// a symbol before it in the same section, and use the offset from there.
7391/// 3. Finally, if all that fails, fall back to an offset from the start of the
7392/// referenced section.
7393static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
7394 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007395 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00007396 StringRef &Name, uint64_t &Addend) {
7397 if (Reloc.getSymbol() != Obj->symbol_end()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007398 Expected<StringRef> NameOrErr = Reloc.getSymbol()->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007399 if (!NameOrErr)
7400 report_error(Obj->getFileName(), NameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007401 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007402 Addend = Addr;
7403 return;
7404 }
7405
7406 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
Keno Fischerc780e8e2015-05-21 21:24:32 +00007407 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
Tim Northover4bd286a2014-08-01 13:07:19 +00007408
Rafael Espindola80291272014-10-08 15:28:58 +00007409 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00007410
7411 auto Sym = Symbols.upper_bound(Addr);
7412 if (Sym == Symbols.begin()) {
7413 // The first symbol in the object is after this reference, the best we can
7414 // do is section-relative notation.
7415 RelocSection.getName(Name);
7416 Addend = Addr - SectionAddr;
7417 return;
7418 }
7419
7420 // Go back one so that SymbolAddress <= Addr.
7421 --Sym;
7422
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007423 auto SectOrErr = Sym->second.getSection();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007424 if (!SectOrErr)
7425 report_error(Obj->getFileName(), SectOrErr.takeError());
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007426 section_iterator SymSection = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007427 if (RelocSection == *SymSection) {
7428 // There's a valid symbol in the same section before this reference.
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007429 Expected<StringRef> NameOrErr = Sym->second.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007430 if (!NameOrErr)
7431 report_error(Obj->getFileName(), NameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007432 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007433 Addend = Addr - Sym->first;
7434 return;
7435 }
7436
7437 // There is a symbol before this reference, but it's in a different
7438 // section. Probably not helpful to mention it, so use the section name.
7439 RelocSection.getName(Name);
7440 Addend = Addr - SectionAddr;
7441}
7442
7443static void printUnwindRelocDest(const MachOObjectFile *Obj,
7444 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007445 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007446 StringRef Name;
7447 uint64_t Addend;
7448
Rafael Espindola854038e2015-06-26 14:51:16 +00007449 if (!Reloc.getObject())
Tim Northover0b0add52014-09-09 10:45:06 +00007450 return;
7451
Tim Northover4bd286a2014-08-01 13:07:19 +00007452 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
7453
7454 outs() << Name;
7455 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00007456 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00007457}
7458
7459static void
7460printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7461 std::map<uint64_t, SymbolRef> &Symbols,
7462 const SectionRef &CompactUnwind) {
7463
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007464 if (!Obj->isLittleEndian()) {
7465 outs() << "Skipping big-endian __compact_unwind section\n";
7466 return;
7467 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007468
7469 bool Is64 = Obj->is64Bit();
7470 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7471 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7472
7473 StringRef Contents;
7474 CompactUnwind.getContents(Contents);
7475
7476 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7477
7478 // First populate the initial raw offsets, encodings and so on from the entry.
7479 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007480 CompactUnwindEntry Entry(Contents, Offset, Is64);
Tim Northover4bd286a2014-08-01 13:07:19 +00007481 CompactUnwinds.push_back(Entry);
7482 }
7483
7484 // Next we need to look at the relocations to find out what objects are
7485 // actually being referred to.
7486 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00007487 uint64_t RelocAddress = Reloc.getOffset();
Tim Northover4bd286a2014-08-01 13:07:19 +00007488
7489 uint32_t EntryIdx = RelocAddress / EntrySize;
7490 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7491 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7492
7493 if (OffsetInEntry == 0)
7494 Entry.FunctionReloc = Reloc;
7495 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7496 Entry.PersonalityReloc = Reloc;
7497 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7498 Entry.LSDAReloc = Reloc;
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007499 else {
7500 outs() << "Invalid relocation in __compact_unwind section\n";
7501 return;
7502 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007503 }
7504
7505 // Finally, we're ready to print the data we've gathered.
7506 outs() << "Contents of __compact_unwind section:\n";
7507 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00007508 outs() << " Entry at offset "
7509 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00007510
7511 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007512 outs() << " start: " << format("0x%" PRIx64,
7513 Entry.FunctionAddr) << ' ';
7514 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00007515 outs() << '\n';
7516
7517 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007518 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
7519 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007520 // 3. The 32-bit compact encoding.
7521 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007522 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007523
7524 // 4. The personality function, if present.
Rafael Espindola854038e2015-06-26 14:51:16 +00007525 if (Entry.PersonalityReloc.getObject()) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007526 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007527 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007528 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7529 Entry.PersonalityAddr);
7530 outs() << '\n';
7531 }
7532
7533 // 5. This entry's language-specific data area.
Rafael Espindola854038e2015-06-26 14:51:16 +00007534 if (Entry.LSDAReloc.getObject()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007535 outs() << " LSDA: " << format("0x%" PRIx64,
7536 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007537 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7538 outs() << '\n';
7539 }
7540 }
7541}
7542
Tim Northover39c70bb2014-08-12 11:52:59 +00007543//===----------------------------------------------------------------------===//
7544// __unwind_info section dumping
7545//===----------------------------------------------------------------------===//
7546
Tim Northover3a4e1c72018-01-23 13:51:57 +00007547static void printRegularSecondLevelUnwindPage(StringRef PageData) {
7548 ptrdiff_t Pos = 0;
7549 uint32_t Kind = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007550 (void)Kind;
7551 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7552
Tim Northover3a4e1c72018-01-23 13:51:57 +00007553 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7554 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007555
Tim Northover3a4e1c72018-01-23 13:51:57 +00007556 Pos = EntriesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007557 for (unsigned i = 0; i < NumEntries; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007558 uint32_t FunctionOffset = readNext<uint32_t>(PageData, Pos);
7559 uint32_t Encoding = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007560
7561 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007562 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7563 << ", "
7564 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007565 }
7566}
7567
7568static void printCompressedSecondLevelUnwindPage(
Tim Northover3a4e1c72018-01-23 13:51:57 +00007569 StringRef PageData, uint32_t FunctionBase,
Tim Northover39c70bb2014-08-12 11:52:59 +00007570 const SmallVectorImpl<uint32_t> &CommonEncodings) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007571 ptrdiff_t Pos = 0;
7572 uint32_t Kind = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007573 (void)Kind;
7574 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
7575
Tim Northover3a4e1c72018-01-23 13:51:57 +00007576 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7577 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007578
Tim Northover3a4e1c72018-01-23 13:51:57 +00007579 uint16_t EncodingsStart = readNext<uint16_t>(PageData, Pos);
7580 readNext<uint16_t>(PageData, Pos);
7581 StringRef PageEncodings = PageData.substr(EncodingsStart, StringRef::npos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007582
Tim Northover3a4e1c72018-01-23 13:51:57 +00007583 Pos = EntriesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007584 for (unsigned i = 0; i < NumEntries; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007585 uint32_t Entry = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007586 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
7587 uint32_t EncodingIdx = Entry >> 24;
7588
7589 uint32_t Encoding;
7590 if (EncodingIdx < CommonEncodings.size())
7591 Encoding = CommonEncodings[EncodingIdx];
7592 else
Tim Northover3a4e1c72018-01-23 13:51:57 +00007593 Encoding = read<uint32_t>(PageEncodings,
7594 sizeof(uint32_t) *
7595 (EncodingIdx - CommonEncodings.size()));
Tim Northover39c70bb2014-08-12 11:52:59 +00007596
7597 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007598 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7599 << ", "
7600 << "encoding[" << EncodingIdx
7601 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007602 }
7603}
7604
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007605static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
7606 std::map<uint64_t, SymbolRef> &Symbols,
7607 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00007608
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007609 if (!Obj->isLittleEndian()) {
7610 outs() << "Skipping big-endian __unwind_info section\n";
7611 return;
7612 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007613
7614 outs() << "Contents of __unwind_info section:\n";
7615
7616 StringRef Contents;
7617 UnwindInfo.getContents(Contents);
Tim Northover3a4e1c72018-01-23 13:51:57 +00007618 ptrdiff_t Pos = 0;
Tim Northover39c70bb2014-08-12 11:52:59 +00007619
7620 //===----------------------------------
7621 // Section header
7622 //===----------------------------------
7623
Tim Northover3a4e1c72018-01-23 13:51:57 +00007624 uint32_t Version = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007625 outs() << " Version: "
7626 << format("0x%" PRIx32, Version) << '\n';
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007627 if (Version != 1) {
7628 outs() << " Skipping section with unknown version\n";
7629 return;
7630 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007631
Tim Northover3a4e1c72018-01-23 13:51:57 +00007632 uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007633 outs() << " Common encodings array section offset: "
7634 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007635 uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007636 outs() << " Number of common encodings in array: "
7637 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
7638
Tim Northover3a4e1c72018-01-23 13:51:57 +00007639 uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007640 outs() << " Personality function array section offset: "
7641 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007642 uint32_t NumPersonalities = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007643 outs() << " Number of personality functions in array: "
7644 << format("0x%" PRIx32, NumPersonalities) << '\n';
7645
Tim Northover3a4e1c72018-01-23 13:51:57 +00007646 uint32_t IndicesStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007647 outs() << " Index array section offset: "
7648 << format("0x%" PRIx32, IndicesStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007649 uint32_t NumIndices = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007650 outs() << " Number of indices in array: "
7651 << format("0x%" PRIx32, NumIndices) << '\n';
7652
7653 //===----------------------------------
7654 // A shared list of common encodings
7655 //===----------------------------------
7656
7657 // These occupy indices in the range [0, N] whenever an encoding is referenced
7658 // from a compressed 2nd level index table. In practice the linker only
7659 // creates ~128 of these, so that indices are available to embed encodings in
7660 // the 2nd level index.
7661
7662 SmallVector<uint32_t, 64> CommonEncodings;
7663 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007664 Pos = CommonEncodingsStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007665 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007666 uint32_t Encoding = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007667 CommonEncodings.push_back(Encoding);
7668
7669 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
7670 << '\n';
7671 }
7672
Tim Northover39c70bb2014-08-12 11:52:59 +00007673 //===----------------------------------
7674 // Personality functions used in this executable
7675 //===----------------------------------
7676
7677 // There should be only a handful of these (one per source language,
7678 // roughly). Particularly since they only get 2 bits in the compact encoding.
7679
7680 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007681 Pos = PersonalitiesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007682 for (unsigned i = 0; i < NumPersonalities; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007683 uint32_t PersonalityFn = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007684 outs() << " personality[" << i + 1
7685 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
7686 }
7687
7688 //===----------------------------------
7689 // The level 1 index entries
7690 //===----------------------------------
7691
7692 // These specify an approximate place to start searching for the more detailed
7693 // information, sorted by PC.
7694
7695 struct IndexEntry {
7696 uint32_t FunctionOffset;
7697 uint32_t SecondLevelPageStart;
7698 uint32_t LSDAStart;
7699 };
7700
7701 SmallVector<IndexEntry, 4> IndexEntries;
7702
7703 outs() << " Top level indices: (count = " << NumIndices << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007704 Pos = IndicesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007705 for (unsigned i = 0; i < NumIndices; ++i) {
7706 IndexEntry Entry;
7707
Tim Northover3a4e1c72018-01-23 13:51:57 +00007708 Entry.FunctionOffset = readNext<uint32_t>(Contents, Pos);
7709 Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Pos);
7710 Entry.LSDAStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007711 IndexEntries.push_back(Entry);
7712
7713 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007714 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
7715 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00007716 << "2nd level page offset="
7717 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007718 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007719 }
7720
Tim Northover39c70bb2014-08-12 11:52:59 +00007721 //===----------------------------------
7722 // Next come the LSDA tables
7723 //===----------------------------------
7724
7725 // The LSDA layout is rather implicit: it's a contiguous array of entries from
7726 // the first top-level index's LSDAOffset to the last (sentinel).
7727
7728 outs() << " LSDA descriptors:\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007729 Pos = IndexEntries[0].LSDAStart;
7730 const uint32_t LSDASize = 2 * sizeof(uint32_t);
7731 int NumLSDAs =
7732 (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize;
7733
Tim Northover39c70bb2014-08-12 11:52:59 +00007734 for (int i = 0; i < NumLSDAs; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007735 uint32_t FunctionOffset = readNext<uint32_t>(Contents, Pos);
7736 uint32_t LSDAOffset = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007737 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007738 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7739 << ", "
7740 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007741 }
7742
7743 //===----------------------------------
7744 // Finally, the 2nd level indices
7745 //===----------------------------------
7746
7747 // Generally these are 4K in size, and have 2 possible forms:
7748 // + Regular stores up to 511 entries with disparate encodings
7749 // + Compressed stores up to 1021 entries if few enough compact encoding
7750 // values are used.
7751 outs() << " Second level indices:\n";
7752 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
7753 // The final sentinel top-level index has no associated 2nd level page
7754 if (IndexEntries[i].SecondLevelPageStart == 0)
7755 break;
7756
7757 outs() << " Second level index[" << i << "]: "
7758 << "offset in section="
7759 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
7760 << ", "
7761 << "base function offset="
7762 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
7763
Tim Northover3a4e1c72018-01-23 13:51:57 +00007764 Pos = IndexEntries[i].SecondLevelPageStart;
7765 if (Pos + sizeof(uint32_t) > Contents.size()) {
7766 outs() << "warning: invalid offset for second level page: " << Pos << '\n';
7767 continue;
7768 }
7769
7770 uint32_t Kind =
7771 *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007772 if (Kind == 2)
Tim Northover3a4e1c72018-01-23 13:51:57 +00007773 printRegularSecondLevelUnwindPage(Contents.substr(Pos, 4096));
Tim Northover39c70bb2014-08-12 11:52:59 +00007774 else if (Kind == 3)
Tim Northover3a4e1c72018-01-23 13:51:57 +00007775 printCompressedSecondLevelUnwindPage(Contents.substr(Pos, 4096),
7776 IndexEntries[i].FunctionOffset,
Tim Northover39c70bb2014-08-12 11:52:59 +00007777 CommonEncodings);
7778 else
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007779 outs() << " Skipping 2nd level page with unknown kind " << Kind
7780 << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007781 }
7782}
7783
Tim Northover4bd286a2014-08-01 13:07:19 +00007784void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
7785 std::map<uint64_t, SymbolRef> Symbols;
7786 for (const SymbolRef &SymRef : Obj->symbols()) {
7787 // Discard any undefined or absolute symbols. They're not going to take part
7788 // in the convenience lookup for unwind info and just take up resources.
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007789 auto SectOrErr = SymRef.getSection();
7790 if (!SectOrErr) {
7791 // TODO: Actually report errors helpfully.
7792 consumeError(SectOrErr.takeError());
7793 continue;
7794 }
7795 section_iterator Section = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007796 if (Section == Obj->section_end())
7797 continue;
7798
Rafael Espindoladea00162015-07-03 17:44:18 +00007799 uint64_t Addr = SymRef.getValue();
Tim Northover4bd286a2014-08-01 13:07:19 +00007800 Symbols.insert(std::make_pair(Addr, SymRef));
7801 }
7802
7803 for (const SectionRef &Section : Obj->sections()) {
7804 StringRef SectName;
7805 Section.getName(SectName);
7806 if (SectName == "__compact_unwind")
7807 printMachOCompactUnwindSection(Obj, Symbols, Section);
7808 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00007809 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00007810 }
7811}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007812
7813static void PrintMachHeader(uint32_t magic, uint32_t cputype,
7814 uint32_t cpusubtype, uint32_t filetype,
7815 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
7816 bool verbose) {
7817 outs() << "Mach header\n";
7818 outs() << " magic cputype cpusubtype caps filetype ncmds "
7819 "sizeofcmds flags\n";
7820 if (verbose) {
7821 if (magic == MachO::MH_MAGIC)
7822 outs() << " MH_MAGIC";
7823 else if (magic == MachO::MH_MAGIC_64)
7824 outs() << "MH_MAGIC_64";
7825 else
7826 outs() << format(" 0x%08" PRIx32, magic);
7827 switch (cputype) {
7828 case MachO::CPU_TYPE_I386:
7829 outs() << " I386";
7830 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7831 case MachO::CPU_SUBTYPE_I386_ALL:
7832 outs() << " ALL";
7833 break;
7834 default:
7835 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7836 break;
7837 }
7838 break;
7839 case MachO::CPU_TYPE_X86_64:
7840 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00007841 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7842 case MachO::CPU_SUBTYPE_X86_64_ALL:
7843 outs() << " ALL";
7844 break;
7845 case MachO::CPU_SUBTYPE_X86_64_H:
7846 outs() << " Haswell";
7847 break;
7848 default:
7849 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7850 break;
7851 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007852 break;
7853 case MachO::CPU_TYPE_ARM:
7854 outs() << " ARM";
7855 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7856 case MachO::CPU_SUBTYPE_ARM_ALL:
7857 outs() << " ALL";
7858 break;
7859 case MachO::CPU_SUBTYPE_ARM_V4T:
7860 outs() << " V4T";
7861 break;
7862 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
7863 outs() << " V5TEJ";
7864 break;
7865 case MachO::CPU_SUBTYPE_ARM_XSCALE:
7866 outs() << " XSCALE";
7867 break;
7868 case MachO::CPU_SUBTYPE_ARM_V6:
7869 outs() << " V6";
7870 break;
7871 case MachO::CPU_SUBTYPE_ARM_V6M:
7872 outs() << " V6M";
7873 break;
7874 case MachO::CPU_SUBTYPE_ARM_V7:
7875 outs() << " V7";
7876 break;
7877 case MachO::CPU_SUBTYPE_ARM_V7EM:
7878 outs() << " V7EM";
7879 break;
7880 case MachO::CPU_SUBTYPE_ARM_V7K:
7881 outs() << " V7K";
7882 break;
7883 case MachO::CPU_SUBTYPE_ARM_V7M:
7884 outs() << " V7M";
7885 break;
7886 case MachO::CPU_SUBTYPE_ARM_V7S:
7887 outs() << " V7S";
7888 break;
7889 default:
7890 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7891 break;
7892 }
7893 break;
7894 case MachO::CPU_TYPE_ARM64:
7895 outs() << " ARM64";
7896 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7897 case MachO::CPU_SUBTYPE_ARM64_ALL:
7898 outs() << " ALL";
7899 break;
7900 default:
7901 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7902 break;
7903 }
7904 break;
7905 case MachO::CPU_TYPE_POWERPC:
7906 outs() << " PPC";
7907 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7908 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7909 outs() << " ALL";
7910 break;
7911 default:
7912 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7913 break;
7914 }
7915 break;
7916 case MachO::CPU_TYPE_POWERPC64:
7917 outs() << " PPC64";
7918 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7919 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7920 outs() << " ALL";
7921 break;
7922 default:
7923 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7924 break;
7925 }
7926 break;
Kevin Enderby40fdbf82016-01-26 18:20:49 +00007927 default:
7928 outs() << format(" %7d", cputype);
7929 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7930 break;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007931 }
7932 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007933 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007934 } else {
7935 outs() << format(" 0x%02" PRIx32,
7936 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7937 }
7938 switch (filetype) {
7939 case MachO::MH_OBJECT:
7940 outs() << " OBJECT";
7941 break;
7942 case MachO::MH_EXECUTE:
7943 outs() << " EXECUTE";
7944 break;
7945 case MachO::MH_FVMLIB:
7946 outs() << " FVMLIB";
7947 break;
7948 case MachO::MH_CORE:
7949 outs() << " CORE";
7950 break;
7951 case MachO::MH_PRELOAD:
7952 outs() << " PRELOAD";
7953 break;
7954 case MachO::MH_DYLIB:
7955 outs() << " DYLIB";
7956 break;
7957 case MachO::MH_DYLIB_STUB:
7958 outs() << " DYLIB_STUB";
7959 break;
7960 case MachO::MH_DYLINKER:
7961 outs() << " DYLINKER";
7962 break;
7963 case MachO::MH_BUNDLE:
7964 outs() << " BUNDLE";
7965 break;
7966 case MachO::MH_DSYM:
7967 outs() << " DSYM";
7968 break;
7969 case MachO::MH_KEXT_BUNDLE:
7970 outs() << " KEXTBUNDLE";
7971 break;
7972 default:
7973 outs() << format(" %10u", filetype);
7974 break;
7975 }
7976 outs() << format(" %5u", ncmds);
7977 outs() << format(" %10u", sizeofcmds);
7978 uint32_t f = flags;
7979 if (f & MachO::MH_NOUNDEFS) {
7980 outs() << " NOUNDEFS";
7981 f &= ~MachO::MH_NOUNDEFS;
7982 }
7983 if (f & MachO::MH_INCRLINK) {
7984 outs() << " INCRLINK";
7985 f &= ~MachO::MH_INCRLINK;
7986 }
7987 if (f & MachO::MH_DYLDLINK) {
7988 outs() << " DYLDLINK";
7989 f &= ~MachO::MH_DYLDLINK;
7990 }
7991 if (f & MachO::MH_BINDATLOAD) {
7992 outs() << " BINDATLOAD";
7993 f &= ~MachO::MH_BINDATLOAD;
7994 }
7995 if (f & MachO::MH_PREBOUND) {
7996 outs() << " PREBOUND";
7997 f &= ~MachO::MH_PREBOUND;
7998 }
7999 if (f & MachO::MH_SPLIT_SEGS) {
8000 outs() << " SPLIT_SEGS";
8001 f &= ~MachO::MH_SPLIT_SEGS;
8002 }
8003 if (f & MachO::MH_LAZY_INIT) {
8004 outs() << " LAZY_INIT";
8005 f &= ~MachO::MH_LAZY_INIT;
8006 }
8007 if (f & MachO::MH_TWOLEVEL) {
8008 outs() << " TWOLEVEL";
8009 f &= ~MachO::MH_TWOLEVEL;
8010 }
8011 if (f & MachO::MH_FORCE_FLAT) {
8012 outs() << " FORCE_FLAT";
8013 f &= ~MachO::MH_FORCE_FLAT;
8014 }
8015 if (f & MachO::MH_NOMULTIDEFS) {
8016 outs() << " NOMULTIDEFS";
8017 f &= ~MachO::MH_NOMULTIDEFS;
8018 }
8019 if (f & MachO::MH_NOFIXPREBINDING) {
8020 outs() << " NOFIXPREBINDING";
8021 f &= ~MachO::MH_NOFIXPREBINDING;
8022 }
8023 if (f & MachO::MH_PREBINDABLE) {
8024 outs() << " PREBINDABLE";
8025 f &= ~MachO::MH_PREBINDABLE;
8026 }
8027 if (f & MachO::MH_ALLMODSBOUND) {
8028 outs() << " ALLMODSBOUND";
8029 f &= ~MachO::MH_ALLMODSBOUND;
8030 }
8031 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
8032 outs() << " SUBSECTIONS_VIA_SYMBOLS";
8033 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
8034 }
8035 if (f & MachO::MH_CANONICAL) {
8036 outs() << " CANONICAL";
8037 f &= ~MachO::MH_CANONICAL;
8038 }
8039 if (f & MachO::MH_WEAK_DEFINES) {
8040 outs() << " WEAK_DEFINES";
8041 f &= ~MachO::MH_WEAK_DEFINES;
8042 }
8043 if (f & MachO::MH_BINDS_TO_WEAK) {
8044 outs() << " BINDS_TO_WEAK";
8045 f &= ~MachO::MH_BINDS_TO_WEAK;
8046 }
8047 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
8048 outs() << " ALLOW_STACK_EXECUTION";
8049 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
8050 }
8051 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
8052 outs() << " DEAD_STRIPPABLE_DYLIB";
8053 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
8054 }
8055 if (f & MachO::MH_PIE) {
8056 outs() << " PIE";
8057 f &= ~MachO::MH_PIE;
8058 }
8059 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
8060 outs() << " NO_REEXPORTED_DYLIBS";
8061 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
8062 }
8063 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
8064 outs() << " MH_HAS_TLV_DESCRIPTORS";
8065 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
8066 }
8067 if (f & MachO::MH_NO_HEAP_EXECUTION) {
8068 outs() << " MH_NO_HEAP_EXECUTION";
8069 f &= ~MachO::MH_NO_HEAP_EXECUTION;
8070 }
8071 if (f & MachO::MH_APP_EXTENSION_SAFE) {
8072 outs() << " APP_EXTENSION_SAFE";
8073 f &= ~MachO::MH_APP_EXTENSION_SAFE;
8074 }
Kevin Enderbydf0d6da2017-06-19 19:38:22 +00008075 if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
8076 outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO";
8077 f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO;
8078 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008079 if (f != 0 || flags == 0)
8080 outs() << format(" 0x%08" PRIx32, f);
8081 } else {
8082 outs() << format(" 0x%08" PRIx32, magic);
8083 outs() << format(" %7d", cputype);
8084 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8085 outs() << format(" 0x%02" PRIx32,
8086 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8087 outs() << format(" %10u", filetype);
8088 outs() << format(" %5u", ncmds);
8089 outs() << format(" %10u", sizeofcmds);
8090 outs() << format(" 0x%08" PRIx32, flags);
8091 }
8092 outs() << "\n";
8093}
8094
Kevin Enderby956366c2014-08-29 22:30:52 +00008095static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
8096 StringRef SegName, uint64_t vmaddr,
8097 uint64_t vmsize, uint64_t fileoff,
8098 uint64_t filesize, uint32_t maxprot,
8099 uint32_t initprot, uint32_t nsects,
8100 uint32_t flags, uint32_t object_size,
8101 bool verbose) {
8102 uint64_t expected_cmdsize;
8103 if (cmd == MachO::LC_SEGMENT) {
8104 outs() << " cmd LC_SEGMENT\n";
8105 expected_cmdsize = nsects;
8106 expected_cmdsize *= sizeof(struct MachO::section);
8107 expected_cmdsize += sizeof(struct MachO::segment_command);
8108 } else {
8109 outs() << " cmd LC_SEGMENT_64\n";
8110 expected_cmdsize = nsects;
8111 expected_cmdsize *= sizeof(struct MachO::section_64);
8112 expected_cmdsize += sizeof(struct MachO::segment_command_64);
8113 }
8114 outs() << " cmdsize " << cmdsize;
8115 if (cmdsize != expected_cmdsize)
8116 outs() << " Inconsistent size\n";
8117 else
8118 outs() << "\n";
8119 outs() << " segname " << SegName << "\n";
8120 if (cmd == MachO::LC_SEGMENT_64) {
8121 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
8122 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
8123 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00008124 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
8125 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008126 }
8127 outs() << " fileoff " << fileoff;
8128 if (fileoff > object_size)
8129 outs() << " (past end of file)\n";
8130 else
8131 outs() << "\n";
8132 outs() << " filesize " << filesize;
8133 if (fileoff + filesize > object_size)
8134 outs() << " (past end of file)\n";
8135 else
8136 outs() << "\n";
8137 if (verbose) {
8138 if ((maxprot &
8139 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8140 MachO::VM_PROT_EXECUTE)) != 0)
8141 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
8142 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00008143 outs() << " maxprot ";
8144 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
8145 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8146 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00008147 }
8148 if ((initprot &
8149 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8150 MachO::VM_PROT_EXECUTE)) != 0)
Kevin Enderby41c9c002016-10-21 18:22:35 +00008151 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008152 else {
Kevin Enderby41c9c002016-10-21 18:22:35 +00008153 outs() << " initprot ";
Davide Italiano37ff06a2015-09-02 16:53:25 +00008154 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
8155 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8156 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00008157 }
8158 } else {
8159 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
8160 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
8161 }
8162 outs() << " nsects " << nsects << "\n";
8163 if (verbose) {
8164 outs() << " flags";
8165 if (flags == 0)
8166 outs() << " (none)\n";
8167 else {
8168 if (flags & MachO::SG_HIGHVM) {
8169 outs() << " HIGHVM";
8170 flags &= ~MachO::SG_HIGHVM;
8171 }
8172 if (flags & MachO::SG_FVMLIB) {
8173 outs() << " FVMLIB";
8174 flags &= ~MachO::SG_FVMLIB;
8175 }
8176 if (flags & MachO::SG_NORELOC) {
8177 outs() << " NORELOC";
8178 flags &= ~MachO::SG_NORELOC;
8179 }
8180 if (flags & MachO::SG_PROTECTED_VERSION_1) {
8181 outs() << " PROTECTED_VERSION_1";
8182 flags &= ~MachO::SG_PROTECTED_VERSION_1;
8183 }
8184 if (flags)
8185 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
8186 else
8187 outs() << "\n";
8188 }
8189 } else {
8190 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
8191 }
8192}
8193
8194static void PrintSection(const char *sectname, const char *segname,
8195 uint64_t addr, uint64_t size, uint32_t offset,
8196 uint32_t align, uint32_t reloff, uint32_t nreloc,
8197 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
8198 uint32_t cmd, const char *sg_segname,
8199 uint32_t filetype, uint32_t object_size,
8200 bool verbose) {
8201 outs() << "Section\n";
8202 outs() << " sectname " << format("%.16s\n", sectname);
8203 outs() << " segname " << format("%.16s", segname);
8204 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
8205 outs() << " (does not match segment)\n";
8206 else
8207 outs() << "\n";
8208 if (cmd == MachO::LC_SEGMENT_64) {
8209 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
8210 outs() << " size " << format("0x%016" PRIx64, size);
8211 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00008212 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
8213 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00008214 }
8215 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
8216 outs() << " (past end of file)\n";
8217 else
8218 outs() << "\n";
8219 outs() << " offset " << offset;
8220 if (offset > object_size)
8221 outs() << " (past end of file)\n";
8222 else
8223 outs() << "\n";
8224 uint32_t align_shifted = 1 << align;
8225 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
8226 outs() << " reloff " << reloff;
8227 if (reloff > object_size)
8228 outs() << " (past end of file)\n";
8229 else
8230 outs() << "\n";
8231 outs() << " nreloc " << nreloc;
8232 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
8233 outs() << " (past end of file)\n";
8234 else
8235 outs() << "\n";
8236 uint32_t section_type = flags & MachO::SECTION_TYPE;
8237 if (verbose) {
8238 outs() << " type";
8239 if (section_type == MachO::S_REGULAR)
8240 outs() << " S_REGULAR\n";
8241 else if (section_type == MachO::S_ZEROFILL)
8242 outs() << " S_ZEROFILL\n";
8243 else if (section_type == MachO::S_CSTRING_LITERALS)
8244 outs() << " S_CSTRING_LITERALS\n";
8245 else if (section_type == MachO::S_4BYTE_LITERALS)
8246 outs() << " S_4BYTE_LITERALS\n";
8247 else if (section_type == MachO::S_8BYTE_LITERALS)
8248 outs() << " S_8BYTE_LITERALS\n";
8249 else if (section_type == MachO::S_16BYTE_LITERALS)
8250 outs() << " S_16BYTE_LITERALS\n";
8251 else if (section_type == MachO::S_LITERAL_POINTERS)
8252 outs() << " S_LITERAL_POINTERS\n";
8253 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
8254 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
8255 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
8256 outs() << " S_LAZY_SYMBOL_POINTERS\n";
8257 else if (section_type == MachO::S_SYMBOL_STUBS)
8258 outs() << " S_SYMBOL_STUBS\n";
8259 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
8260 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
8261 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
8262 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
8263 else if (section_type == MachO::S_COALESCED)
8264 outs() << " S_COALESCED\n";
8265 else if (section_type == MachO::S_INTERPOSING)
8266 outs() << " S_INTERPOSING\n";
8267 else if (section_type == MachO::S_DTRACE_DOF)
8268 outs() << " S_DTRACE_DOF\n";
8269 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
8270 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
8271 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
8272 outs() << " S_THREAD_LOCAL_REGULAR\n";
8273 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
8274 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
8275 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
8276 outs() << " S_THREAD_LOCAL_VARIABLES\n";
8277 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8278 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
8279 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
8280 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
8281 else
8282 outs() << format("0x%08" PRIx32, section_type) << "\n";
8283 outs() << "attributes";
8284 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
8285 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
8286 outs() << " PURE_INSTRUCTIONS";
8287 if (section_attributes & MachO::S_ATTR_NO_TOC)
8288 outs() << " NO_TOC";
8289 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
8290 outs() << " STRIP_STATIC_SYMS";
8291 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
8292 outs() << " NO_DEAD_STRIP";
8293 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
8294 outs() << " LIVE_SUPPORT";
8295 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
8296 outs() << " SELF_MODIFYING_CODE";
8297 if (section_attributes & MachO::S_ATTR_DEBUG)
8298 outs() << " DEBUG";
8299 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
8300 outs() << " SOME_INSTRUCTIONS";
8301 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
8302 outs() << " EXT_RELOC";
8303 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
8304 outs() << " LOC_RELOC";
8305 if (section_attributes == 0)
8306 outs() << " (none)";
8307 outs() << "\n";
8308 } else
8309 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
8310 outs() << " reserved1 " << reserved1;
8311 if (section_type == MachO::S_SYMBOL_STUBS ||
8312 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
8313 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
8314 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
8315 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8316 outs() << " (index into indirect symbol table)\n";
8317 else
8318 outs() << "\n";
8319 outs() << " reserved2 " << reserved2;
8320 if (section_type == MachO::S_SYMBOL_STUBS)
8321 outs() << " (size of stubs)\n";
8322 else
8323 outs() << "\n";
8324}
8325
David Majnemer73cc6ff2014-11-13 19:48:56 +00008326static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00008327 uint32_t object_size) {
8328 outs() << " cmd LC_SYMTAB\n";
8329 outs() << " cmdsize " << st.cmdsize;
8330 if (st.cmdsize != sizeof(struct MachO::symtab_command))
8331 outs() << " Incorrect size\n";
8332 else
8333 outs() << "\n";
8334 outs() << " symoff " << st.symoff;
8335 if (st.symoff > object_size)
8336 outs() << " (past end of file)\n";
8337 else
8338 outs() << "\n";
8339 outs() << " nsyms " << st.nsyms;
8340 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00008341 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008342 big_size = st.nsyms;
8343 big_size *= sizeof(struct MachO::nlist_64);
8344 big_size += st.symoff;
8345 if (big_size > object_size)
8346 outs() << " (past end of file)\n";
8347 else
8348 outs() << "\n";
8349 } else {
8350 big_size = st.nsyms;
8351 big_size *= sizeof(struct MachO::nlist);
8352 big_size += st.symoff;
8353 if (big_size > object_size)
8354 outs() << " (past end of file)\n";
8355 else
8356 outs() << "\n";
8357 }
8358 outs() << " stroff " << st.stroff;
8359 if (st.stroff > object_size)
8360 outs() << " (past end of file)\n";
8361 else
8362 outs() << "\n";
8363 outs() << " strsize " << st.strsize;
8364 big_size = st.stroff;
8365 big_size += st.strsize;
8366 if (big_size > object_size)
8367 outs() << " (past end of file)\n";
8368 else
8369 outs() << "\n";
8370}
8371
8372static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
8373 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00008374 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008375 outs() << " cmd LC_DYSYMTAB\n";
8376 outs() << " cmdsize " << dyst.cmdsize;
8377 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
8378 outs() << " Incorrect size\n";
8379 else
8380 outs() << "\n";
8381 outs() << " ilocalsym " << dyst.ilocalsym;
8382 if (dyst.ilocalsym > nsyms)
8383 outs() << " (greater than the number of symbols)\n";
8384 else
8385 outs() << "\n";
8386 outs() << " nlocalsym " << dyst.nlocalsym;
8387 uint64_t big_size;
8388 big_size = dyst.ilocalsym;
8389 big_size += dyst.nlocalsym;
8390 if (big_size > nsyms)
8391 outs() << " (past the end of the symbol table)\n";
8392 else
8393 outs() << "\n";
8394 outs() << " iextdefsym " << dyst.iextdefsym;
8395 if (dyst.iextdefsym > nsyms)
8396 outs() << " (greater than the number of symbols)\n";
8397 else
8398 outs() << "\n";
8399 outs() << " nextdefsym " << dyst.nextdefsym;
8400 big_size = dyst.iextdefsym;
8401 big_size += dyst.nextdefsym;
8402 if (big_size > nsyms)
8403 outs() << " (past the end of the symbol table)\n";
8404 else
8405 outs() << "\n";
8406 outs() << " iundefsym " << dyst.iundefsym;
8407 if (dyst.iundefsym > nsyms)
8408 outs() << " (greater than the number of symbols)\n";
8409 else
8410 outs() << "\n";
8411 outs() << " nundefsym " << dyst.nundefsym;
8412 big_size = dyst.iundefsym;
8413 big_size += dyst.nundefsym;
8414 if (big_size > nsyms)
8415 outs() << " (past the end of the symbol table)\n";
8416 else
8417 outs() << "\n";
8418 outs() << " tocoff " << dyst.tocoff;
8419 if (dyst.tocoff > object_size)
8420 outs() << " (past end of file)\n";
8421 else
8422 outs() << "\n";
8423 outs() << " ntoc " << dyst.ntoc;
8424 big_size = dyst.ntoc;
8425 big_size *= sizeof(struct MachO::dylib_table_of_contents);
8426 big_size += dyst.tocoff;
8427 if (big_size > object_size)
8428 outs() << " (past end of file)\n";
8429 else
8430 outs() << "\n";
8431 outs() << " modtaboff " << dyst.modtaboff;
8432 if (dyst.modtaboff > object_size)
8433 outs() << " (past end of file)\n";
8434 else
8435 outs() << "\n";
8436 outs() << " nmodtab " << dyst.nmodtab;
8437 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00008438 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008439 modtabend = dyst.nmodtab;
8440 modtabend *= sizeof(struct MachO::dylib_module_64);
8441 modtabend += dyst.modtaboff;
8442 } else {
8443 modtabend = dyst.nmodtab;
8444 modtabend *= sizeof(struct MachO::dylib_module);
8445 modtabend += dyst.modtaboff;
8446 }
8447 if (modtabend > object_size)
8448 outs() << " (past end of file)\n";
8449 else
8450 outs() << "\n";
8451 outs() << " extrefsymoff " << dyst.extrefsymoff;
8452 if (dyst.extrefsymoff > object_size)
8453 outs() << " (past end of file)\n";
8454 else
8455 outs() << "\n";
8456 outs() << " nextrefsyms " << dyst.nextrefsyms;
8457 big_size = dyst.nextrefsyms;
8458 big_size *= sizeof(struct MachO::dylib_reference);
8459 big_size += dyst.extrefsymoff;
8460 if (big_size > object_size)
8461 outs() << " (past end of file)\n";
8462 else
8463 outs() << "\n";
8464 outs() << " indirectsymoff " << dyst.indirectsymoff;
8465 if (dyst.indirectsymoff > object_size)
8466 outs() << " (past end of file)\n";
8467 else
8468 outs() << "\n";
8469 outs() << " nindirectsyms " << dyst.nindirectsyms;
8470 big_size = dyst.nindirectsyms;
8471 big_size *= sizeof(uint32_t);
8472 big_size += dyst.indirectsymoff;
8473 if (big_size > object_size)
8474 outs() << " (past end of file)\n";
8475 else
8476 outs() << "\n";
8477 outs() << " extreloff " << dyst.extreloff;
8478 if (dyst.extreloff > object_size)
8479 outs() << " (past end of file)\n";
8480 else
8481 outs() << "\n";
8482 outs() << " nextrel " << dyst.nextrel;
8483 big_size = dyst.nextrel;
8484 big_size *= sizeof(struct MachO::relocation_info);
8485 big_size += dyst.extreloff;
8486 if (big_size > object_size)
8487 outs() << " (past end of file)\n";
8488 else
8489 outs() << "\n";
8490 outs() << " locreloff " << dyst.locreloff;
8491 if (dyst.locreloff > object_size)
8492 outs() << " (past end of file)\n";
8493 else
8494 outs() << "\n";
8495 outs() << " nlocrel " << dyst.nlocrel;
8496 big_size = dyst.nlocrel;
8497 big_size *= sizeof(struct MachO::relocation_info);
8498 big_size += dyst.locreloff;
8499 if (big_size > object_size)
8500 outs() << " (past end of file)\n";
8501 else
8502 outs() << "\n";
8503}
8504
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008505static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8506 uint32_t object_size) {
8507 if (dc.cmd == MachO::LC_DYLD_INFO)
8508 outs() << " cmd LC_DYLD_INFO\n";
8509 else
8510 outs() << " cmd LC_DYLD_INFO_ONLY\n";
8511 outs() << " cmdsize " << dc.cmdsize;
8512 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8513 outs() << " Incorrect size\n";
8514 else
8515 outs() << "\n";
8516 outs() << " rebase_off " << dc.rebase_off;
8517 if (dc.rebase_off > object_size)
8518 outs() << " (past end of file)\n";
8519 else
8520 outs() << "\n";
8521 outs() << " rebase_size " << dc.rebase_size;
8522 uint64_t big_size;
8523 big_size = dc.rebase_off;
8524 big_size += dc.rebase_size;
8525 if (big_size > object_size)
8526 outs() << " (past end of file)\n";
8527 else
8528 outs() << "\n";
8529 outs() << " bind_off " << dc.bind_off;
8530 if (dc.bind_off > object_size)
8531 outs() << " (past end of file)\n";
8532 else
8533 outs() << "\n";
8534 outs() << " bind_size " << dc.bind_size;
8535 big_size = dc.bind_off;
8536 big_size += dc.bind_size;
8537 if (big_size > object_size)
8538 outs() << " (past end of file)\n";
8539 else
8540 outs() << "\n";
8541 outs() << " weak_bind_off " << dc.weak_bind_off;
8542 if (dc.weak_bind_off > object_size)
8543 outs() << " (past end of file)\n";
8544 else
8545 outs() << "\n";
8546 outs() << " weak_bind_size " << dc.weak_bind_size;
8547 big_size = dc.weak_bind_off;
8548 big_size += dc.weak_bind_size;
8549 if (big_size > object_size)
8550 outs() << " (past end of file)\n";
8551 else
8552 outs() << "\n";
8553 outs() << " lazy_bind_off " << dc.lazy_bind_off;
8554 if (dc.lazy_bind_off > object_size)
8555 outs() << " (past end of file)\n";
8556 else
8557 outs() << "\n";
8558 outs() << " lazy_bind_size " << dc.lazy_bind_size;
8559 big_size = dc.lazy_bind_off;
8560 big_size += dc.lazy_bind_size;
8561 if (big_size > object_size)
8562 outs() << " (past end of file)\n";
8563 else
8564 outs() << "\n";
8565 outs() << " export_off " << dc.export_off;
8566 if (dc.export_off > object_size)
8567 outs() << " (past end of file)\n";
8568 else
8569 outs() << "\n";
8570 outs() << " export_size " << dc.export_size;
8571 big_size = dc.export_off;
8572 big_size += dc.export_size;
8573 if (big_size > object_size)
8574 outs() << " (past end of file)\n";
8575 else
8576 outs() << "\n";
8577}
8578
8579static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
8580 const char *Ptr) {
8581 if (dyld.cmd == MachO::LC_ID_DYLINKER)
8582 outs() << " cmd LC_ID_DYLINKER\n";
8583 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
8584 outs() << " cmd LC_LOAD_DYLINKER\n";
8585 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
8586 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
8587 else
8588 outs() << " cmd ?(" << dyld.cmd << ")\n";
8589 outs() << " cmdsize " << dyld.cmdsize;
8590 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
8591 outs() << " Incorrect size\n";
8592 else
8593 outs() << "\n";
8594 if (dyld.name >= dyld.cmdsize)
8595 outs() << " name ?(bad offset " << dyld.name << ")\n";
8596 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008597 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008598 outs() << " name " << P << " (offset " << dyld.name << ")\n";
8599 }
8600}
8601
8602static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
8603 outs() << " cmd LC_UUID\n";
8604 outs() << " cmdsize " << uuid.cmdsize;
8605 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
8606 outs() << " Incorrect size\n";
8607 else
8608 outs() << "\n";
8609 outs() << " uuid ";
Davide Italianoc74277a2015-12-07 00:03:28 +00008610 for (int i = 0; i < 16; ++i) {
8611 outs() << format("%02" PRIX32, uuid.uuid[i]);
8612 if (i == 3 || i == 5 || i == 7 || i == 9)
8613 outs() << "-";
8614 }
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008615 outs() << "\n";
8616}
8617
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008618static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008619 outs() << " cmd LC_RPATH\n";
8620 outs() << " cmdsize " << rpath.cmdsize;
8621 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
8622 outs() << " Incorrect size\n";
8623 else
8624 outs() << "\n";
8625 if (rpath.path >= rpath.cmdsize)
8626 outs() << " path ?(bad offset " << rpath.path << ")\n";
8627 else {
8628 const char *P = (const char *)(Ptr) + rpath.path;
8629 outs() << " path " << P << " (offset " << rpath.path << ")\n";
8630 }
8631}
8632
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008633static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
Tim Northoverbfbfb122015-11-02 21:26:58 +00008634 StringRef LoadCmdName;
8635 switch (vd.cmd) {
8636 case MachO::LC_VERSION_MIN_MACOSX:
8637 LoadCmdName = "LC_VERSION_MIN_MACOSX";
8638 break;
8639 case MachO::LC_VERSION_MIN_IPHONEOS:
8640 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
8641 break;
8642 case MachO::LC_VERSION_MIN_TVOS:
8643 LoadCmdName = "LC_VERSION_MIN_TVOS";
8644 break;
8645 case MachO::LC_VERSION_MIN_WATCHOS:
8646 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
8647 break;
8648 default:
8649 llvm_unreachable("Unknown version min load command");
8650 }
8651
8652 outs() << " cmd " << LoadCmdName << '\n';
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008653 outs() << " cmdsize " << vd.cmdsize;
8654 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
8655 outs() << " Incorrect size\n";
8656 else
8657 outs() << "\n";
Davide Italiano56baef32015-08-26 12:26:11 +00008658 outs() << " version "
8659 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
8660 << MachOObjectFile::getVersionMinMinor(vd, false);
8661 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
8662 if (Update != 0)
8663 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008664 outs() << "\n";
8665 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00008666 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008667 else {
Davide Italiano56baef32015-08-26 12:26:11 +00008668 outs() << " sdk "
8669 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
8670 << MachOObjectFile::getVersionMinMinor(vd, true);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008671 }
Davide Italiano56baef32015-08-26 12:26:11 +00008672 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
8673 if (Update != 0)
8674 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008675 outs() << "\n";
8676}
8677
Kevin Enderbya4579c42017-01-19 17:36:31 +00008678static void PrintNoteLoadCommand(MachO::note_command Nt) {
8679 outs() << " cmd LC_NOTE\n";
8680 outs() << " cmdsize " << Nt.cmdsize;
8681 if (Nt.cmdsize != sizeof(struct MachO::note_command))
8682 outs() << " Incorrect size\n";
8683 else
8684 outs() << "\n";
8685 const char *d = Nt.data_owner;
8686 outs() << "data_owner " << format("%.16s\n", d);
8687 outs() << " offset " << Nt.offset << "\n";
8688 outs() << " size " << Nt.size << "\n";
8689}
8690
Steven Wu5b54a422017-01-23 20:07:55 +00008691static void PrintBuildToolVersion(MachO::build_tool_version bv) {
8692 outs() << " tool " << MachOObjectFile::getBuildTool(bv.tool) << "\n";
8693 outs() << " version " << MachOObjectFile::getVersionString(bv.version)
8694 << "\n";
8695}
8696
8697static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
8698 MachO::build_version_command bd) {
8699 outs() << " cmd LC_BUILD_VERSION\n";
8700 outs() << " cmdsize " << bd.cmdsize;
8701 if (bd.cmdsize !=
8702 sizeof(struct MachO::build_version_command) +
8703 bd.ntools * sizeof(struct MachO::build_tool_version))
8704 outs() << " Incorrect size\n";
8705 else
8706 outs() << "\n";
8707 outs() << " platform " << MachOObjectFile::getBuildPlatform(bd.platform)
8708 << "\n";
8709 if (bd.sdk)
8710 outs() << " sdk " << MachOObjectFile::getVersionString(bd.sdk)
8711 << "\n";
8712 else
8713 outs() << " sdk n/a\n";
8714 outs() << " minos " << MachOObjectFile::getVersionString(bd.minos)
8715 << "\n";
8716 outs() << " ntools " << bd.ntools << "\n";
8717 for (unsigned i = 0; i < bd.ntools; ++i) {
8718 MachO::build_tool_version bv = obj->getBuildToolVersion(i);
8719 PrintBuildToolVersion(bv);
8720 }
8721}
8722
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008723static void PrintSourceVersionCommand(MachO::source_version_command sd) {
8724 outs() << " cmd LC_SOURCE_VERSION\n";
8725 outs() << " cmdsize " << sd.cmdsize;
8726 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
8727 outs() << " Incorrect size\n";
8728 else
8729 outs() << "\n";
8730 uint64_t a = (sd.version >> 40) & 0xffffff;
8731 uint64_t b = (sd.version >> 30) & 0x3ff;
8732 uint64_t c = (sd.version >> 20) & 0x3ff;
8733 uint64_t d = (sd.version >> 10) & 0x3ff;
8734 uint64_t e = sd.version & 0x3ff;
8735 outs() << " version " << a << "." << b;
8736 if (e != 0)
8737 outs() << "." << c << "." << d << "." << e;
8738 else if (d != 0)
8739 outs() << "." << c << "." << d;
8740 else if (c != 0)
8741 outs() << "." << c;
8742 outs() << "\n";
8743}
8744
8745static void PrintEntryPointCommand(MachO::entry_point_command ep) {
8746 outs() << " cmd LC_MAIN\n";
8747 outs() << " cmdsize " << ep.cmdsize;
8748 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
8749 outs() << " Incorrect size\n";
8750 else
8751 outs() << "\n";
8752 outs() << " entryoff " << ep.entryoff << "\n";
8753 outs() << " stacksize " << ep.stacksize << "\n";
8754}
8755
Kevin Enderby0804f4672014-12-16 23:25:52 +00008756static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
8757 uint32_t object_size) {
8758 outs() << " cmd LC_ENCRYPTION_INFO\n";
8759 outs() << " cmdsize " << ec.cmdsize;
8760 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
8761 outs() << " Incorrect size\n";
8762 else
8763 outs() << "\n";
8764 outs() << " cryptoff " << ec.cryptoff;
8765 if (ec.cryptoff > object_size)
8766 outs() << " (past end of file)\n";
8767 else
8768 outs() << "\n";
8769 outs() << " cryptsize " << ec.cryptsize;
8770 if (ec.cryptsize > object_size)
8771 outs() << " (past end of file)\n";
8772 else
8773 outs() << "\n";
8774 outs() << " cryptid " << ec.cryptid << "\n";
8775}
8776
Kevin Enderby57538292014-12-17 01:01:30 +00008777static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008778 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00008779 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
8780 outs() << " cmdsize " << ec.cmdsize;
8781 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
8782 outs() << " Incorrect size\n";
8783 else
8784 outs() << "\n";
8785 outs() << " cryptoff " << ec.cryptoff;
8786 if (ec.cryptoff > object_size)
8787 outs() << " (past end of file)\n";
8788 else
8789 outs() << "\n";
8790 outs() << " cryptsize " << ec.cryptsize;
8791 if (ec.cryptsize > object_size)
8792 outs() << " (past end of file)\n";
8793 else
8794 outs() << "\n";
8795 outs() << " cryptid " << ec.cryptid << "\n";
8796 outs() << " pad " << ec.pad << "\n";
8797}
8798
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008799static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
8800 const char *Ptr) {
8801 outs() << " cmd LC_LINKER_OPTION\n";
8802 outs() << " cmdsize " << lo.cmdsize;
8803 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
8804 outs() << " Incorrect size\n";
8805 else
8806 outs() << "\n";
8807 outs() << " count " << lo.count << "\n";
8808 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
8809 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
8810 uint32_t i = 0;
8811 while (left > 0) {
8812 while (*string == '\0' && left > 0) {
8813 string++;
8814 left--;
8815 }
8816 if (left > 0) {
8817 i++;
8818 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00008819 uint32_t NullPos = StringRef(string, left).find('\0');
8820 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008821 string += len;
8822 left -= len;
8823 }
8824 }
8825 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008826 outs() << " count " << lo.count << " does not match number of strings "
8827 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008828}
8829
Kevin Enderbyb4b79312014-12-18 19:24:35 +00008830static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
8831 const char *Ptr) {
8832 outs() << " cmd LC_SUB_FRAMEWORK\n";
8833 outs() << " cmdsize " << sub.cmdsize;
8834 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
8835 outs() << " Incorrect size\n";
8836 else
8837 outs() << "\n";
8838 if (sub.umbrella < sub.cmdsize) {
8839 const char *P = Ptr + sub.umbrella;
8840 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
8841 } else {
8842 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
8843 }
8844}
8845
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00008846static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
8847 const char *Ptr) {
8848 outs() << " cmd LC_SUB_UMBRELLA\n";
8849 outs() << " cmdsize " << sub.cmdsize;
8850 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
8851 outs() << " Incorrect size\n";
8852 else
8853 outs() << "\n";
8854 if (sub.sub_umbrella < sub.cmdsize) {
8855 const char *P = Ptr + sub.sub_umbrella;
8856 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
8857 } else {
8858 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
8859 }
8860}
8861
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008862static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008863 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008864 outs() << " cmd LC_SUB_LIBRARY\n";
8865 outs() << " cmdsize " << sub.cmdsize;
8866 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
8867 outs() << " Incorrect size\n";
8868 else
8869 outs() << "\n";
8870 if (sub.sub_library < sub.cmdsize) {
8871 const char *P = Ptr + sub.sub_library;
8872 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
8873 } else {
8874 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
8875 }
8876}
8877
Kevin Enderby186eac32014-12-19 21:06:24 +00008878static void PrintSubClientCommand(MachO::sub_client_command sub,
8879 const char *Ptr) {
8880 outs() << " cmd LC_SUB_CLIENT\n";
8881 outs() << " cmdsize " << sub.cmdsize;
8882 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
8883 outs() << " Incorrect size\n";
8884 else
8885 outs() << "\n";
8886 if (sub.client < sub.cmdsize) {
8887 const char *P = Ptr + sub.client;
8888 outs() << " client " << P << " (offset " << sub.client << ")\n";
8889 } else {
8890 outs() << " client ?(bad offset " << sub.client << ")\n";
8891 }
8892}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008893
Kevin Enderby52e4ce42014-12-19 22:25:22 +00008894static void PrintRoutinesCommand(MachO::routines_command r) {
8895 outs() << " cmd LC_ROUTINES\n";
8896 outs() << " cmdsize " << r.cmdsize;
8897 if (r.cmdsize != sizeof(struct MachO::routines_command))
8898 outs() << " Incorrect size\n";
8899 else
8900 outs() << "\n";
8901 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
8902 outs() << " init_module " << r.init_module << "\n";
8903 outs() << " reserved1 " << r.reserved1 << "\n";
8904 outs() << " reserved2 " << r.reserved2 << "\n";
8905 outs() << " reserved3 " << r.reserved3 << "\n";
8906 outs() << " reserved4 " << r.reserved4 << "\n";
8907 outs() << " reserved5 " << r.reserved5 << "\n";
8908 outs() << " reserved6 " << r.reserved6 << "\n";
8909}
8910
8911static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
8912 outs() << " cmd LC_ROUTINES_64\n";
8913 outs() << " cmdsize " << r.cmdsize;
8914 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
8915 outs() << " Incorrect size\n";
8916 else
8917 outs() << "\n";
8918 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
8919 outs() << " init_module " << r.init_module << "\n";
8920 outs() << " reserved1 " << r.reserved1 << "\n";
8921 outs() << " reserved2 " << r.reserved2 << "\n";
8922 outs() << " reserved3 " << r.reserved3 << "\n";
8923 outs() << " reserved4 " << r.reserved4 << "\n";
8924 outs() << " reserved5 " << r.reserved5 << "\n";
8925 outs() << " reserved6 " << r.reserved6 << "\n";
8926}
8927
Kevin Enderbyc3a035d2017-01-23 21:13:29 +00008928static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
8929 outs() << "\t eax " << format("0x%08" PRIx32, cpu32.eax);
8930 outs() << " ebx " << format("0x%08" PRIx32, cpu32.ebx);
8931 outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx);
8932 outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n";
8933 outs() << "\t edi " << format("0x%08" PRIx32, cpu32.edi);
8934 outs() << " esi " << format("0x%08" PRIx32, cpu32.esi);
8935 outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp);
8936 outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n";
8937 outs() << "\t ss " << format("0x%08" PRIx32, cpu32.ss);
8938 outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags);
8939 outs() << " eip " << format("0x%08" PRIx32, cpu32.eip);
8940 outs() << " cs " << format("0x%08" PRIx32, cpu32.cs) << "\n";
8941 outs() << "\t ds " << format("0x%08" PRIx32, cpu32.ds);
8942 outs() << " es " << format("0x%08" PRIx32, cpu32.es);
8943 outs() << " fs " << format("0x%08" PRIx32, cpu32.fs);
8944 outs() << " gs " << format("0x%08" PRIx32, cpu32.gs) << "\n";
8945}
8946
Kevin Enderby48ef5342014-12-23 22:56:39 +00008947static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
8948 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
8949 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
8950 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
8951 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
8952 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
8953 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
8954 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
8955 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
8956 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
8957 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
8958 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
8959 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
8960 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
8961 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
8962 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
8963 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
8964 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
8965 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
8966 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
8967 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
8968 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
8969}
8970
Kevin Enderby227df342014-12-23 23:43:59 +00008971static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008972 uint32_t f;
8973 outs() << "\t mmst_reg ";
8974 for (f = 0; f < 10; f++)
8975 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
8976 outs() << "\n";
8977 outs() << "\t mmst_rsrv ";
8978 for (f = 0; f < 6; f++)
8979 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
8980 outs() << "\n";
8981}
8982
Kevin Enderbyaefb0032014-12-24 00:16:51 +00008983static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008984 uint32_t f;
8985 outs() << "\t xmm_reg ";
8986 for (f = 0; f < 16; f++)
8987 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
8988 outs() << "\n";
8989}
8990
8991static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
8992 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
8993 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
8994 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
8995 outs() << " denorm " << fpu.fpu_fcw.denorm;
8996 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
8997 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
8998 outs() << " undfl " << fpu.fpu_fcw.undfl;
8999 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
9000 outs() << "\t\t pc ";
9001 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
9002 outs() << "FP_PREC_24B ";
9003 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
9004 outs() << "FP_PREC_53B ";
9005 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
9006 outs() << "FP_PREC_64B ";
9007 else
9008 outs() << fpu.fpu_fcw.pc << " ";
9009 outs() << "rc ";
9010 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
9011 outs() << "FP_RND_NEAR ";
9012 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
9013 outs() << "FP_RND_DOWN ";
9014 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
9015 outs() << "FP_RND_UP ";
9016 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009017 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009018 outs() << "\n";
9019 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
9020 outs() << " denorm " << fpu.fpu_fsw.denorm;
9021 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
9022 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
9023 outs() << " undfl " << fpu.fpu_fsw.undfl;
9024 outs() << " precis " << fpu.fpu_fsw.precis;
9025 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
9026 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
9027 outs() << " c0 " << fpu.fpu_fsw.c0;
9028 outs() << " c1 " << fpu.fpu_fsw.c1;
9029 outs() << " c2 " << fpu.fpu_fsw.c2;
9030 outs() << " tos " << fpu.fpu_fsw.tos;
9031 outs() << " c3 " << fpu.fpu_fsw.c3;
9032 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
9033 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
9034 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
9035 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
9036 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
9037 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
9038 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
9039 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
9040 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
9041 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
9042 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
9043 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
9044 outs() << "\n";
9045 outs() << "\t fpu_stmm0:\n";
9046 Print_mmst_reg(fpu.fpu_stmm0);
9047 outs() << "\t fpu_stmm1:\n";
9048 Print_mmst_reg(fpu.fpu_stmm1);
9049 outs() << "\t fpu_stmm2:\n";
9050 Print_mmst_reg(fpu.fpu_stmm2);
9051 outs() << "\t fpu_stmm3:\n";
9052 Print_mmst_reg(fpu.fpu_stmm3);
9053 outs() << "\t fpu_stmm4:\n";
9054 Print_mmst_reg(fpu.fpu_stmm4);
9055 outs() << "\t fpu_stmm5:\n";
9056 Print_mmst_reg(fpu.fpu_stmm5);
9057 outs() << "\t fpu_stmm6:\n";
9058 Print_mmst_reg(fpu.fpu_stmm6);
9059 outs() << "\t fpu_stmm7:\n";
9060 Print_mmst_reg(fpu.fpu_stmm7);
9061 outs() << "\t fpu_xmm0:\n";
9062 Print_xmm_reg(fpu.fpu_xmm0);
9063 outs() << "\t fpu_xmm1:\n";
9064 Print_xmm_reg(fpu.fpu_xmm1);
9065 outs() << "\t fpu_xmm2:\n";
9066 Print_xmm_reg(fpu.fpu_xmm2);
9067 outs() << "\t fpu_xmm3:\n";
9068 Print_xmm_reg(fpu.fpu_xmm3);
9069 outs() << "\t fpu_xmm4:\n";
9070 Print_xmm_reg(fpu.fpu_xmm4);
9071 outs() << "\t fpu_xmm5:\n";
9072 Print_xmm_reg(fpu.fpu_xmm5);
9073 outs() << "\t fpu_xmm6:\n";
9074 Print_xmm_reg(fpu.fpu_xmm6);
9075 outs() << "\t fpu_xmm7:\n";
9076 Print_xmm_reg(fpu.fpu_xmm7);
9077 outs() << "\t fpu_xmm8:\n";
9078 Print_xmm_reg(fpu.fpu_xmm8);
9079 outs() << "\t fpu_xmm9:\n";
9080 Print_xmm_reg(fpu.fpu_xmm9);
9081 outs() << "\t fpu_xmm10:\n";
9082 Print_xmm_reg(fpu.fpu_xmm10);
9083 outs() << "\t fpu_xmm11:\n";
9084 Print_xmm_reg(fpu.fpu_xmm11);
9085 outs() << "\t fpu_xmm12:\n";
9086 Print_xmm_reg(fpu.fpu_xmm12);
9087 outs() << "\t fpu_xmm13:\n";
9088 Print_xmm_reg(fpu.fpu_xmm13);
9089 outs() << "\t fpu_xmm14:\n";
9090 Print_xmm_reg(fpu.fpu_xmm14);
9091 outs() << "\t fpu_xmm15:\n";
9092 Print_xmm_reg(fpu.fpu_xmm15);
9093 outs() << "\t fpu_rsrv4:\n";
9094 for (uint32_t f = 0; f < 6; f++) {
9095 outs() << "\t ";
9096 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009097 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009098 outs() << "\n";
9099 }
9100 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
9101 outs() << "\n";
9102}
9103
9104static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
9105 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
9106 outs() << " err " << format("0x%08" PRIx32, exc64.err);
9107 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
9108}
9109
Kevin Enderby41c9c002016-10-21 18:22:35 +00009110static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
9111 outs() << "\t r0 " << format("0x%08" PRIx32, cpu32.r[0]);
9112 outs() << " r1 " << format("0x%08" PRIx32, cpu32.r[1]);
9113 outs() << " r2 " << format("0x%08" PRIx32, cpu32.r[2]);
9114 outs() << " r3 " << format("0x%08" PRIx32, cpu32.r[3]) << "\n";
9115 outs() << "\t r4 " << format("0x%08" PRIx32, cpu32.r[4]);
9116 outs() << " r5 " << format("0x%08" PRIx32, cpu32.r[5]);
9117 outs() << " r6 " << format("0x%08" PRIx32, cpu32.r[6]);
9118 outs() << " r7 " << format("0x%08" PRIx32, cpu32.r[7]) << "\n";
9119 outs() << "\t r8 " << format("0x%08" PRIx32, cpu32.r[8]);
9120 outs() << " r9 " << format("0x%08" PRIx32, cpu32.r[9]);
9121 outs() << " r10 " << format("0x%08" PRIx32, cpu32.r[10]);
9122 outs() << " r11 " << format("0x%08" PRIx32, cpu32.r[11]) << "\n";
9123 outs() << "\t r12 " << format("0x%08" PRIx32, cpu32.r[12]);
9124 outs() << " sp " << format("0x%08" PRIx32, cpu32.sp);
9125 outs() << " lr " << format("0x%08" PRIx32, cpu32.lr);
9126 outs() << " pc " << format("0x%08" PRIx32, cpu32.pc) << "\n";
9127 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n";
9128}
9129
Kevin Enderby7747cb52016-11-03 20:51:28 +00009130static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
9131 outs() << "\t x0 " << format("0x%016" PRIx64, cpu64.x[0]);
9132 outs() << " x1 " << format("0x%016" PRIx64, cpu64.x[1]);
9133 outs() << " x2 " << format("0x%016" PRIx64, cpu64.x[2]) << "\n";
9134 outs() << "\t x3 " << format("0x%016" PRIx64, cpu64.x[3]);
9135 outs() << " x4 " << format("0x%016" PRIx64, cpu64.x[4]);
9136 outs() << " x5 " << format("0x%016" PRIx64, cpu64.x[5]) << "\n";
9137 outs() << "\t x6 " << format("0x%016" PRIx64, cpu64.x[6]);
9138 outs() << " x7 " << format("0x%016" PRIx64, cpu64.x[7]);
9139 outs() << " x8 " << format("0x%016" PRIx64, cpu64.x[8]) << "\n";
9140 outs() << "\t x9 " << format("0x%016" PRIx64, cpu64.x[9]);
9141 outs() << " x10 " << format("0x%016" PRIx64, cpu64.x[10]);
9142 outs() << " x11 " << format("0x%016" PRIx64, cpu64.x[11]) << "\n";
9143 outs() << "\t x12 " << format("0x%016" PRIx64, cpu64.x[12]);
9144 outs() << " x13 " << format("0x%016" PRIx64, cpu64.x[13]);
9145 outs() << " x14 " << format("0x%016" PRIx64, cpu64.x[14]) << "\n";
9146 outs() << "\t x15 " << format("0x%016" PRIx64, cpu64.x[15]);
9147 outs() << " x16 " << format("0x%016" PRIx64, cpu64.x[16]);
9148 outs() << " x17 " << format("0x%016" PRIx64, cpu64.x[17]) << "\n";
9149 outs() << "\t x18 " << format("0x%016" PRIx64, cpu64.x[18]);
9150 outs() << " x19 " << format("0x%016" PRIx64, cpu64.x[19]);
9151 outs() << " x20 " << format("0x%016" PRIx64, cpu64.x[20]) << "\n";
9152 outs() << "\t x21 " << format("0x%016" PRIx64, cpu64.x[21]);
9153 outs() << " x22 " << format("0x%016" PRIx64, cpu64.x[22]);
9154 outs() << " x23 " << format("0x%016" PRIx64, cpu64.x[23]) << "\n";
9155 outs() << "\t x24 " << format("0x%016" PRIx64, cpu64.x[24]);
9156 outs() << " x25 " << format("0x%016" PRIx64, cpu64.x[25]);
9157 outs() << " x26 " << format("0x%016" PRIx64, cpu64.x[26]) << "\n";
9158 outs() << "\t x27 " << format("0x%016" PRIx64, cpu64.x[27]);
9159 outs() << " x28 " << format("0x%016" PRIx64, cpu64.x[28]);
9160 outs() << " fp " << format("0x%016" PRIx64, cpu64.fp) << "\n";
9161 outs() << "\t lr " << format("0x%016" PRIx64, cpu64.lr);
9162 outs() << " sp " << format("0x%016" PRIx64, cpu64.sp);
9163 outs() << " pc " << format("0x%016" PRIx64, cpu64.pc) << "\n";
9164 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu64.cpsr) << "\n";
9165}
9166
Kevin Enderby48ef5342014-12-23 22:56:39 +00009167static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
9168 bool isLittleEndian, uint32_t cputype) {
9169 if (t.cmd == MachO::LC_THREAD)
9170 outs() << " cmd LC_THREAD\n";
9171 else if (t.cmd == MachO::LC_UNIXTHREAD)
9172 outs() << " cmd LC_UNIXTHREAD\n";
9173 else
9174 outs() << " cmd " << t.cmd << " (unknown)\n";
9175 outs() << " cmdsize " << t.cmdsize;
9176 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
9177 outs() << " Incorrect size\n";
9178 else
9179 outs() << "\n";
9180
9181 const char *begin = Ptr + sizeof(struct MachO::thread_command);
9182 const char *end = Ptr + t.cmdsize;
9183 uint32_t flavor, count, left;
Kevin Enderbyc3a035d2017-01-23 21:13:29 +00009184 if (cputype == MachO::CPU_TYPE_I386) {
9185 while (begin < end) {
9186 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9187 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9188 begin += sizeof(uint32_t);
9189 } else {
9190 flavor = 0;
9191 begin = end;
9192 }
9193 if (isLittleEndian != sys::IsLittleEndianHost)
9194 sys::swapByteOrder(flavor);
9195 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9196 memcpy((char *)&count, begin, sizeof(uint32_t));
9197 begin += sizeof(uint32_t);
9198 } else {
9199 count = 0;
9200 begin = end;
9201 }
9202 if (isLittleEndian != sys::IsLittleEndianHost)
9203 sys::swapByteOrder(count);
9204 if (flavor == MachO::x86_THREAD_STATE32) {
9205 outs() << " flavor i386_THREAD_STATE\n";
9206 if (count == MachO::x86_THREAD_STATE32_COUNT)
9207 outs() << " count i386_THREAD_STATE_COUNT\n";
9208 else
9209 outs() << " count " << count
9210 << " (not x86_THREAD_STATE32_COUNT)\n";
9211 MachO::x86_thread_state32_t cpu32;
9212 left = end - begin;
9213 if (left >= sizeof(MachO::x86_thread_state32_t)) {
9214 memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t));
9215 begin += sizeof(MachO::x86_thread_state32_t);
9216 } else {
9217 memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t));
9218 memcpy(&cpu32, begin, left);
9219 begin += left;
9220 }
9221 if (isLittleEndian != sys::IsLittleEndianHost)
9222 swapStruct(cpu32);
9223 Print_x86_thread_state32_t(cpu32);
9224 } else if (flavor == MachO::x86_THREAD_STATE) {
9225 outs() << " flavor x86_THREAD_STATE\n";
9226 if (count == MachO::x86_THREAD_STATE_COUNT)
9227 outs() << " count x86_THREAD_STATE_COUNT\n";
9228 else
9229 outs() << " count " << count
9230 << " (not x86_THREAD_STATE_COUNT)\n";
9231 struct MachO::x86_thread_state_t ts;
9232 left = end - begin;
9233 if (left >= sizeof(MachO::x86_thread_state_t)) {
9234 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9235 begin += sizeof(MachO::x86_thread_state_t);
9236 } else {
9237 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9238 memcpy(&ts, begin, left);
9239 begin += left;
9240 }
9241 if (isLittleEndian != sys::IsLittleEndianHost)
9242 swapStruct(ts);
9243 if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
9244 outs() << "\t tsh.flavor x86_THREAD_STATE32 ";
9245 if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
9246 outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
9247 else
9248 outs() << "tsh.count " << ts.tsh.count
9249 << " (not x86_THREAD_STATE32_COUNT\n";
9250 Print_x86_thread_state32_t(ts.uts.ts32);
9251 } else {
9252 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9253 << ts.tsh.count << "\n";
9254 }
9255 } else {
9256 outs() << " flavor " << flavor << " (unknown)\n";
9257 outs() << " count " << count << "\n";
9258 outs() << " state (unknown)\n";
9259 begin += count * sizeof(uint32_t);
9260 }
9261 }
9262 } else if (cputype == MachO::CPU_TYPE_X86_64) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009263 while (begin < end) {
9264 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9265 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9266 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009267 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009268 flavor = 0;
9269 begin = end;
9270 }
9271 if (isLittleEndian != sys::IsLittleEndianHost)
9272 sys::swapByteOrder(flavor);
9273 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9274 memcpy((char *)&count, begin, sizeof(uint32_t));
9275 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009276 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009277 count = 0;
9278 begin = end;
9279 }
9280 if (isLittleEndian != sys::IsLittleEndianHost)
9281 sys::swapByteOrder(count);
9282 if (flavor == MachO::x86_THREAD_STATE64) {
9283 outs() << " flavor x86_THREAD_STATE64\n";
9284 if (count == MachO::x86_THREAD_STATE64_COUNT)
9285 outs() << " count x86_THREAD_STATE64_COUNT\n";
9286 else
9287 outs() << " count " << count
9288 << " (not x86_THREAD_STATE64_COUNT)\n";
9289 MachO::x86_thread_state64_t cpu64;
9290 left = end - begin;
9291 if (left >= sizeof(MachO::x86_thread_state64_t)) {
9292 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
9293 begin += sizeof(MachO::x86_thread_state64_t);
9294 } else {
9295 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
9296 memcpy(&cpu64, begin, left);
9297 begin += left;
9298 }
9299 if (isLittleEndian != sys::IsLittleEndianHost)
9300 swapStruct(cpu64);
9301 Print_x86_thread_state64_t(cpu64);
9302 } else if (flavor == MachO::x86_THREAD_STATE) {
9303 outs() << " flavor x86_THREAD_STATE\n";
9304 if (count == MachO::x86_THREAD_STATE_COUNT)
9305 outs() << " count x86_THREAD_STATE_COUNT\n";
9306 else
9307 outs() << " count " << count
9308 << " (not x86_THREAD_STATE_COUNT)\n";
9309 struct MachO::x86_thread_state_t ts;
9310 left = end - begin;
9311 if (left >= sizeof(MachO::x86_thread_state_t)) {
9312 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9313 begin += sizeof(MachO::x86_thread_state_t);
9314 } else {
9315 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9316 memcpy(&ts, begin, left);
9317 begin += left;
9318 }
9319 if (isLittleEndian != sys::IsLittleEndianHost)
9320 swapStruct(ts);
9321 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
9322 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
9323 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
9324 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
9325 else
9326 outs() << "tsh.count " << ts.tsh.count
9327 << " (not x86_THREAD_STATE64_COUNT\n";
9328 Print_x86_thread_state64_t(ts.uts.ts64);
9329 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009330 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9331 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009332 }
9333 } else if (flavor == MachO::x86_FLOAT_STATE) {
9334 outs() << " flavor x86_FLOAT_STATE\n";
9335 if (count == MachO::x86_FLOAT_STATE_COUNT)
9336 outs() << " count x86_FLOAT_STATE_COUNT\n";
9337 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009338 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009339 struct MachO::x86_float_state_t fs;
9340 left = end - begin;
9341 if (left >= sizeof(MachO::x86_float_state_t)) {
9342 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
9343 begin += sizeof(MachO::x86_float_state_t);
9344 } else {
9345 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
9346 memcpy(&fs, begin, left);
9347 begin += left;
9348 }
9349 if (isLittleEndian != sys::IsLittleEndianHost)
9350 swapStruct(fs);
9351 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
9352 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009353 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00009354 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
9355 else
9356 outs() << "fsh.count " << fs.fsh.count
9357 << " (not x86_FLOAT_STATE64_COUNT\n";
9358 Print_x86_float_state_t(fs.ufs.fs64);
9359 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009360 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
9361 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009362 }
9363 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
9364 outs() << " flavor x86_EXCEPTION_STATE\n";
9365 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
9366 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
9367 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009368 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00009369 << " (not x86_EXCEPTION_STATE_COUNT)\n";
9370 struct MachO::x86_exception_state_t es;
9371 left = end - begin;
9372 if (left >= sizeof(MachO::x86_exception_state_t)) {
9373 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
9374 begin += sizeof(MachO::x86_exception_state_t);
9375 } else {
9376 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
9377 memcpy(&es, begin, left);
9378 begin += left;
9379 }
9380 if (isLittleEndian != sys::IsLittleEndianHost)
9381 swapStruct(es);
9382 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
9383 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009384 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00009385 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
9386 else
9387 outs() << "\t esh.count " << es.esh.count
9388 << " (not x86_EXCEPTION_STATE64_COUNT\n";
9389 Print_x86_exception_state_t(es.ues.es64);
9390 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009391 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
9392 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009393 }
9394 } else {
9395 outs() << " flavor " << flavor << " (unknown)\n";
9396 outs() << " count " << count << "\n";
9397 outs() << " state (unknown)\n";
9398 begin += count * sizeof(uint32_t);
9399 }
9400 }
Kevin Enderby41c9c002016-10-21 18:22:35 +00009401 } else if (cputype == MachO::CPU_TYPE_ARM) {
9402 while (begin < end) {
9403 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9404 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9405 begin += sizeof(uint32_t);
9406 } else {
9407 flavor = 0;
9408 begin = end;
9409 }
9410 if (isLittleEndian != sys::IsLittleEndianHost)
9411 sys::swapByteOrder(flavor);
9412 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9413 memcpy((char *)&count, begin, sizeof(uint32_t));
9414 begin += sizeof(uint32_t);
9415 } else {
9416 count = 0;
9417 begin = end;
9418 }
9419 if (isLittleEndian != sys::IsLittleEndianHost)
9420 sys::swapByteOrder(count);
9421 if (flavor == MachO::ARM_THREAD_STATE) {
9422 outs() << " flavor ARM_THREAD_STATE\n";
9423 if (count == MachO::ARM_THREAD_STATE_COUNT)
9424 outs() << " count ARM_THREAD_STATE_COUNT\n";
9425 else
9426 outs() << " count " << count
9427 << " (not ARM_THREAD_STATE_COUNT)\n";
9428 MachO::arm_thread_state32_t cpu32;
9429 left = end - begin;
9430 if (left >= sizeof(MachO::arm_thread_state32_t)) {
9431 memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
9432 begin += sizeof(MachO::arm_thread_state32_t);
9433 } else {
9434 memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
9435 memcpy(&cpu32, begin, left);
9436 begin += left;
9437 }
9438 if (isLittleEndian != sys::IsLittleEndianHost)
9439 swapStruct(cpu32);
9440 Print_arm_thread_state32_t(cpu32);
9441 } else {
9442 outs() << " flavor " << flavor << " (unknown)\n";
9443 outs() << " count " << count << "\n";
9444 outs() << " state (unknown)\n";
9445 begin += count * sizeof(uint32_t);
9446 }
9447 }
Kevin Enderby7747cb52016-11-03 20:51:28 +00009448 } else if (cputype == MachO::CPU_TYPE_ARM64) {
9449 while (begin < end) {
9450 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9451 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9452 begin += sizeof(uint32_t);
9453 } else {
9454 flavor = 0;
9455 begin = end;
9456 }
9457 if (isLittleEndian != sys::IsLittleEndianHost)
9458 sys::swapByteOrder(flavor);
9459 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9460 memcpy((char *)&count, begin, sizeof(uint32_t));
9461 begin += sizeof(uint32_t);
9462 } else {
9463 count = 0;
9464 begin = end;
9465 }
9466 if (isLittleEndian != sys::IsLittleEndianHost)
9467 sys::swapByteOrder(count);
9468 if (flavor == MachO::ARM_THREAD_STATE64) {
9469 outs() << " flavor ARM_THREAD_STATE64\n";
9470 if (count == MachO::ARM_THREAD_STATE64_COUNT)
9471 outs() << " count ARM_THREAD_STATE64_COUNT\n";
9472 else
9473 outs() << " count " << count
9474 << " (not ARM_THREAD_STATE64_COUNT)\n";
9475 MachO::arm_thread_state64_t cpu64;
9476 left = end - begin;
9477 if (left >= sizeof(MachO::arm_thread_state64_t)) {
9478 memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
9479 begin += sizeof(MachO::arm_thread_state64_t);
9480 } else {
9481 memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
9482 memcpy(&cpu64, begin, left);
9483 begin += left;
9484 }
9485 if (isLittleEndian != sys::IsLittleEndianHost)
9486 swapStruct(cpu64);
9487 Print_arm_thread_state64_t(cpu64);
9488 } else {
9489 outs() << " flavor " << flavor << " (unknown)\n";
9490 outs() << " count " << count << "\n";
9491 outs() << " state (unknown)\n";
9492 begin += count * sizeof(uint32_t);
9493 }
9494 }
Kevin Enderby48ef5342014-12-23 22:56:39 +00009495 } else {
9496 while (begin < end) {
9497 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9498 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9499 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009500 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009501 flavor = 0;
9502 begin = end;
9503 }
9504 if (isLittleEndian != sys::IsLittleEndianHost)
9505 sys::swapByteOrder(flavor);
9506 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9507 memcpy((char *)&count, begin, sizeof(uint32_t));
9508 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009509 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009510 count = 0;
9511 begin = end;
9512 }
9513 if (isLittleEndian != sys::IsLittleEndianHost)
9514 sys::swapByteOrder(count);
9515 outs() << " flavor " << flavor << "\n";
9516 outs() << " count " << count << "\n";
9517 outs() << " state (Unknown cputype/cpusubtype)\n";
9518 begin += count * sizeof(uint32_t);
9519 }
9520 }
9521}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009522
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009523static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
9524 if (dl.cmd == MachO::LC_ID_DYLIB)
9525 outs() << " cmd LC_ID_DYLIB\n";
9526 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
9527 outs() << " cmd LC_LOAD_DYLIB\n";
9528 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
9529 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
9530 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
9531 outs() << " cmd LC_REEXPORT_DYLIB\n";
9532 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
9533 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
9534 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
9535 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
9536 else
9537 outs() << " cmd " << dl.cmd << " (unknown)\n";
9538 outs() << " cmdsize " << dl.cmdsize;
9539 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
9540 outs() << " Incorrect size\n";
9541 else
9542 outs() << "\n";
9543 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009544 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009545 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
9546 } else {
9547 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
9548 }
9549 outs() << " time stamp " << dl.dylib.timestamp << " ";
9550 time_t t = dl.dylib.timestamp;
9551 outs() << ctime(&t);
9552 outs() << " current version ";
9553 if (dl.dylib.current_version == 0xffffffff)
9554 outs() << "n/a\n";
9555 else
9556 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
9557 << ((dl.dylib.current_version >> 8) & 0xff) << "."
9558 << (dl.dylib.current_version & 0xff) << "\n";
9559 outs() << "compatibility version ";
9560 if (dl.dylib.compatibility_version == 0xffffffff)
9561 outs() << "n/a\n";
9562 else
9563 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
9564 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
9565 << (dl.dylib.compatibility_version & 0xff) << "\n";
9566}
9567
9568static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
9569 uint32_t object_size) {
9570 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
Kevin Enderby1be37a32016-04-28 21:07:20 +00009571 outs() << " cmd LC_CODE_SIGNATURE\n";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009572 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
9573 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
9574 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
9575 outs() << " cmd LC_FUNCTION_STARTS\n";
9576 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
9577 outs() << " cmd LC_DATA_IN_CODE\n";
9578 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
9579 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
9580 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
9581 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
9582 else
9583 outs() << " cmd " << ld.cmd << " (?)\n";
9584 outs() << " cmdsize " << ld.cmdsize;
9585 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
9586 outs() << " Incorrect size\n";
9587 else
9588 outs() << "\n";
9589 outs() << " dataoff " << ld.dataoff;
9590 if (ld.dataoff > object_size)
9591 outs() << " (past end of file)\n";
9592 else
9593 outs() << "\n";
9594 outs() << " datasize " << ld.datasize;
9595 uint64_t big_size = ld.dataoff;
9596 big_size += ld.datasize;
9597 if (big_size > object_size)
9598 outs() << " (past end of file)\n";
9599 else
9600 outs() << "\n";
9601}
9602
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009603static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
9604 uint32_t cputype, bool verbose) {
Kevin Enderby956366c2014-08-29 22:30:52 +00009605 StringRef Buf = Obj->getData();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009606 unsigned Index = 0;
9607 for (const auto &Command : Obj->load_commands()) {
9608 outs() << "Load command " << Index++ << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00009609 if (Command.C.cmd == MachO::LC_SEGMENT) {
9610 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
9611 const char *sg_segname = SLC.segname;
9612 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
9613 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
9614 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
9615 verbose);
9616 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00009617 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00009618 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
9619 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
9620 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
9621 }
9622 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
9623 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
9624 const char *sg_segname = SLC_64.segname;
9625 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
9626 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
9627 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
9628 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
9629 for (unsigned j = 0; j < SLC_64.nsects; j++) {
9630 MachO::section_64 S_64 = Obj->getSection64(Command, j);
9631 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
9632 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
9633 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
9634 sg_segname, filetype, Buf.size(), verbose);
9635 }
9636 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
9637 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00009638 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009639 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
9640 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
9641 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00009642 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
9643 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009644 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
9645 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
9646 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
9647 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
9648 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
9649 Command.C.cmd == MachO::LC_ID_DYLINKER ||
9650 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
9651 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
9652 PrintDyldLoadCommand(Dyld, Command.Ptr);
9653 } else if (Command.C.cmd == MachO::LC_UUID) {
9654 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
9655 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00009656 } else if (Command.C.cmd == MachO::LC_RPATH) {
9657 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
9658 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00009659 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
Tim Northoverbfbfb122015-11-02 21:26:58 +00009660 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
9661 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
9662 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009663 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
9664 PrintVersionMinLoadCommand(Vd);
Kevin Enderbya4579c42017-01-19 17:36:31 +00009665 } else if (Command.C.cmd == MachO::LC_NOTE) {
9666 MachO::note_command Nt = Obj->getNoteLoadCommand(Command);
9667 PrintNoteLoadCommand(Nt);
Steven Wu5b54a422017-01-23 20:07:55 +00009668 } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
9669 MachO::build_version_command Bv =
9670 Obj->getBuildVersionLoadCommand(Command);
9671 PrintBuildVersionLoadCommand(Obj, Bv);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009672 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
9673 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
9674 PrintSourceVersionCommand(Sd);
9675 } else if (Command.C.cmd == MachO::LC_MAIN) {
9676 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
9677 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009678 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009679 MachO::encryption_info_command Ei =
9680 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009681 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00009682 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009683 MachO::encryption_info_command_64 Ei =
9684 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00009685 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009686 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009687 MachO::linker_option_command Lo =
9688 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009689 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00009690 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
9691 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
9692 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00009693 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
9694 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
9695 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009696 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
9697 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
9698 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00009699 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
9700 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
9701 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00009702 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
9703 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
9704 PrintRoutinesCommand(Rc);
9705 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
9706 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
9707 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00009708 } else if (Command.C.cmd == MachO::LC_THREAD ||
9709 Command.C.cmd == MachO::LC_UNIXTHREAD) {
9710 MachO::thread_command Tc = Obj->getThreadCommand(Command);
9711 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00009712 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
9713 Command.C.cmd == MachO::LC_ID_DYLIB ||
9714 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
9715 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
9716 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
9717 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009718 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
9719 PrintDylibCommand(Dl, Command.Ptr);
9720 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
9721 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
9722 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
9723 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
9724 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
9725 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
9726 MachO::linkedit_data_command Ld =
9727 Obj->getLinkeditDataLoadCommand(Command);
9728 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009729 } else {
9730 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
9731 << ")\n";
9732 outs() << " cmdsize " << Command.C.cmdsize << "\n";
9733 // TODO: get and print the raw bytes of the load command.
9734 }
9735 // TODO: print all the other kinds of load commands.
Kevin Enderby956366c2014-08-29 22:30:52 +00009736 }
9737}
9738
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009739static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009740 if (Obj->is64Bit()) {
9741 MachO::mach_header_64 H_64;
9742 H_64 = Obj->getHeader64();
9743 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
9744 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
9745 } else {
9746 MachO::mach_header H;
9747 H = Obj->getHeader();
9748 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
9749 H.sizeofcmds, H.flags, verbose);
9750 }
9751}
9752
9753void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
9754 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009755 PrintMachHeader(file, !NonVerbose);
9756}
9757
9758void llvm::printMachOLoadCommands(const object::ObjectFile *Obj) {
9759 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00009760 uint32_t filetype = 0;
9761 uint32_t cputype = 0;
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009762 if (file->is64Bit()) {
9763 MachO::mach_header_64 H_64;
9764 H_64 = file->getHeader64();
9765 filetype = H_64.filetype;
9766 cputype = H_64.cputype;
9767 } else {
9768 MachO::mach_header H;
9769 H = file->getHeader();
9770 filetype = H.filetype;
9771 cputype = H.cputype;
9772 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009773 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009774}
Nick Kledzikd04bc352014-08-30 00:20:14 +00009775
9776//===----------------------------------------------------------------------===//
9777// export trie dumping
9778//===----------------------------------------------------------------------===//
9779
9780void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Kevin Enderby0d5ec112017-06-19 21:23:07 +00009781 uint64_t BaseSegmentAddress = 0;
9782 for (const auto &Command : Obj->load_commands()) {
9783 if (Command.C.cmd == MachO::LC_SEGMENT) {
9784 MachO::segment_command Seg = Obj->getSegmentLoadCommand(Command);
9785 if (Seg.fileoff == 0 && Seg.filesize != 0) {
9786 BaseSegmentAddress = Seg.vmaddr;
9787 break;
9788 }
9789 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
9790 MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(Command);
9791 if (Seg.fileoff == 0 && Seg.filesize != 0) {
9792 BaseSegmentAddress = Seg.vmaddr;
9793 break;
9794 }
9795 }
9796 }
Kevin Enderby3e95bd22017-07-20 23:08:41 +00009797 Error Err = Error::success();
Alexander Shaposhnikove5740342017-07-29 00:30:45 +00009798 for (const llvm::object::ExportEntry &Entry : Obj->exports(Err)) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009799 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +00009800 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
9801 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
9802 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9803 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
9804 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9805 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
9806 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
9807 if (ReExport)
9808 outs() << "[re-export] ";
9809 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009810 outs() << format("0x%08llX ",
Kevin Enderby0d5ec112017-06-19 21:23:07 +00009811 Entry.address() + BaseSegmentAddress);
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009812 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +00009813 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009814 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +00009815 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +00009816 if (WeakDef) {
9817 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009818 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009819 }
9820 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009821 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009822 outs() << ", ";
9823 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009824 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009825 }
9826 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009827 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009828 outs() << ", ";
9829 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009830 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009831 }
9832 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009833 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009834 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009835 outs() << format("resolver=0x%08llX", Entry.other());
9836 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009837 }
9838 outs() << "]";
9839 }
9840 if (ReExport) {
9841 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009842 int Ordinal = Entry.other() - 1;
9843 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
9844 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +00009845 outs() << " (from " << DylibName << ")";
9846 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009847 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +00009848 }
9849 outs() << "\n";
9850 }
Kevin Enderby3e95bd22017-07-20 23:08:41 +00009851 if (Err)
9852 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzikd04bc352014-08-30 00:20:14 +00009853}
Nick Kledzikac431442014-09-12 21:34:15 +00009854
Nick Kledzikac431442014-09-12 21:34:15 +00009855//===----------------------------------------------------------------------===//
9856// rebase table dumping
9857//===----------------------------------------------------------------------===//
9858
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009859void llvm::printMachORebaseTable(object::MachOObjectFile *Obj) {
Nick Kledzikac431442014-09-12 21:34:15 +00009860 outs() << "segment section address type\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009861 Error Err = Error::success();
9862 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
9863 StringRef SegmentName = Entry.segmentName();
9864 StringRef SectionName = Entry.sectionName();
9865 uint64_t Address = Entry.address();
Nick Kledzikac431442014-09-12 21:34:15 +00009866
9867 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009868 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
9869 SegmentName.str().c_str(), SectionName.str().c_str(),
9870 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +00009871 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009872 if (Err)
9873 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzikac431442014-09-12 21:34:15 +00009874}
Nick Kledzik56ebef42014-09-16 01:41:51 +00009875
9876static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
9877 StringRef DylibName;
9878 switch (Ordinal) {
9879 case MachO::BIND_SPECIAL_DYLIB_SELF:
9880 return "this-image";
9881 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
9882 return "main-executable";
9883 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
9884 return "flat-namespace";
9885 default:
Nick Kledzikabd29872014-09-16 22:03:13 +00009886 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009887 std::error_code EC =
9888 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +00009889 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +00009890 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +00009891 return DylibName;
9892 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00009893 }
Nick Kledzikabd29872014-09-16 22:03:13 +00009894 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009895}
9896
9897//===----------------------------------------------------------------------===//
9898// bind table dumping
9899//===----------------------------------------------------------------------===//
9900
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009901void llvm::printMachOBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00009902 // Build table of sections so names can used in final output.
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009903 outs() << "segment section address type "
9904 "addend dylib symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009905 Error Err = Error::success();
9906 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009907 StringRef SegmentName = Entry.segmentName();
9908 StringRef SectionName = Entry.sectionName();
9909 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +00009910
9911 // Table lines look like:
9912 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009913 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00009914 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009915 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009916 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009917 << left_justify(SectionName, 18) << " "
9918 << format_hex(Address, 10, true) << " "
9919 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009920 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009921 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009922 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009923 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009924 if (Err)
9925 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzik56ebef42014-09-16 01:41:51 +00009926}
9927
9928//===----------------------------------------------------------------------===//
9929// lazy bind table dumping
9930//===----------------------------------------------------------------------===//
9931
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009932void llvm::printMachOLazyBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009933 outs() << "segment section address "
9934 "dylib symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009935 Error Err = Error::success();
9936 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009937 StringRef SegmentName = Entry.segmentName();
9938 StringRef SectionName = Entry.sectionName();
9939 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +00009940
9941 // Table lines look like:
9942 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009943 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009944 << left_justify(SectionName, 18) << " "
9945 << format_hex(Address, 10, true) << " "
9946 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00009947 << Entry.symbolName() << "\n";
9948 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009949 if (Err)
9950 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzik56ebef42014-09-16 01:41:51 +00009951}
9952
Nick Kledzik56ebef42014-09-16 01:41:51 +00009953//===----------------------------------------------------------------------===//
9954// weak bind table dumping
9955//===----------------------------------------------------------------------===//
9956
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009957void llvm::printMachOWeakBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009958 outs() << "segment section address "
9959 "type addend symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009960 Error Err = Error::success();
9961 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00009962 // Strong symbols don't have a location to update.
9963 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009964 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +00009965 << Entry.symbolName() << "\n";
9966 continue;
9967 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009968 StringRef SegmentName = Entry.segmentName();
9969 StringRef SectionName = Entry.sectionName();
9970 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +00009971
9972 // Table lines look like:
9973 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009974 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009975 << left_justify(SectionName, 18) << " "
9976 << format_hex(Address, 10, true) << " "
9977 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009978 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
9979 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009980 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009981 if (Err)
9982 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzik56ebef42014-09-16 01:41:51 +00009983}
9984
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009985// get_dyld_bind_info_symbolname() is used for disassembly and passed an
9986// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
9987// information for that address. If the address is found its binding symbol
9988// name is returned. If not nullptr is returned.
9989static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
9990 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +00009991 if (info->bindtable == nullptr) {
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00009992 info->bindtable = llvm::make_unique<SymbolAddressMap>();
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009993 Error Err = Error::success();
9994 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009995 uint64_t Address = Entry.address();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009996 StringRef name = Entry.symbolName();
9997 if (!name.empty())
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00009998 (*info->bindtable)[Address] = name;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009999 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010000 if (Err)
10001 report_error(info->O->getFileName(), std::move(Err));
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010002 }
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +000010003 auto name = info->bindtable->lookup(ReferenceValue);
10004 return !name.empty() ? name.data() : nullptr;
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010005}
Michael Trent1854ecc2017-12-05 07:50:00 +000010006