blob: 281ce9cc1f2b8f21563b0ca1edff81c73cac7cd5 [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"
Kevin Enderby04bf6932014-10-28 23:39:46 +000019#include "llvm/Config/config.h"
Zachary Turner82af9432015-01-30 18:07:45 +000020#include "llvm/DebugInfo/DWARF/DIContext.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000021#include "llvm/MC/MCAsmInfo.h"
Lang Hamesa1bc0f52014-04-15 04:40:56 +000022#include "llvm/MC/MCContext.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000023#include "llvm/MC/MCDisassembler.h"
24#include "llvm/MC/MCInst.h"
25#include "llvm/MC/MCInstPrinter.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000026#include "llvm/MC/MCInstrDesc.h"
27#include "llvm/MC/MCInstrInfo.h"
Jim Grosbachfd93a592012-03-05 19:33:20 +000028#include "llvm/MC/MCRegisterInfo.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000029#include "llvm/MC/MCSubtargetInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000030#include "llvm/Object/MachO.h"
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +000031#include "llvm/Object/MachOUniversal.h"
Rafael Espindola9b709252013-04-13 01:45:40 +000032#include "llvm/Support/Casting.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000033#include "llvm/Support/CommandLine.h"
34#include "llvm/Support/Debug.h"
Tim Northover4bd286a2014-08-01 13:07:19 +000035#include "llvm/Support/Endian.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000036#include "llvm/Support/Format.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000037#include "llvm/Support/FormattedStream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000038#include "llvm/Support/GraphWriter.h"
Kevin Enderby9a509442015-01-27 21:28:24 +000039#include "llvm/Support/LEB128.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000040#include "llvm/Support/MachO.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000041#include "llvm/Support/MemoryBuffer.h"
42#include "llvm/Support/TargetRegistry.h"
43#include "llvm/Support/TargetSelect.h"
44#include "llvm/Support/raw_ostream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000045#include <algorithm>
46#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000047#include <system_error>
Kevin Enderby04bf6932014-10-28 23:39:46 +000048
49#if HAVE_CXXABI_H
50#include <cxxabi.h>
51#endif
52
Benjamin Kramer43a772e2011-09-19 17:56:04 +000053using namespace llvm;
54using namespace object;
55
56static cl::opt<bool>
Kevin Enderbyb28ed012014-10-29 21:28:24 +000057 UseDbg("g",
58 cl::desc("Print line information from debug info if available"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000059
Kevin Enderbyb28ed012014-10-29 21:28:24 +000060static cl::opt<std::string> DSYMFile("dsym",
61 cl::desc("Use .dSYM file for debug info"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000062
Kevin Enderbyb28ed012014-10-29 21:28:24 +000063static cl::opt<bool> FullLeadingAddr("full-leading-addr",
64 cl::desc("Print full leading address"));
Kevin Enderbybf246f52014-09-24 23:08:22 +000065
Kevin Enderbyab5e6c92015-03-17 21:07:39 +000066static cl::opt<bool> NoLeadingAddr("no-leading-addr",
67 cl::desc("Print no leading address"));
68
Kevin Enderbybf246f52014-09-24 23:08:22 +000069static cl::opt<bool>
70 PrintImmHex("print-imm-hex",
71 cl::desc("Use hex format for immediate values"));
72
Kevin Enderby13023a12015-01-15 23:19:11 +000073cl::opt<bool> llvm::UniversalHeaders("universal-headers",
74 cl::desc("Print Mach-O universal headers "
75 "(requires -macho)"));
76
Kevin Enderby131d1772015-01-09 19:22:37 +000077cl::opt<bool>
Kevin Enderby13023a12015-01-15 23:19:11 +000078 llvm::ArchiveHeaders("archive-headers",
79 cl::desc("Print archive headers for Mach-O archives "
80 "(requires -macho)"));
Kevin Enderby131d1772015-01-09 19:22:37 +000081
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +000082cl::opt<bool>
83 llvm::IndirectSymbols("indirect-symbols",
84 cl::desc("Print indirect symbol table for Mach-O "
85 "objects (requires -macho)"));
86
Kevin Enderby69fe98d2015-01-23 18:52:17 +000087cl::opt<bool>
88 llvm::DataInCode("data-in-code",
89 cl::desc("Print the data in code table for Mach-O objects "
90 "(requires -macho)"));
91
Kevin Enderby9a509442015-01-27 21:28:24 +000092cl::opt<bool>
93 llvm::LinkOptHints("link-opt-hints",
94 cl::desc("Print the linker optimization hints for "
95 "Mach-O objects (requires -macho)"));
96
Kevin Enderbyf6d25852015-01-31 00:37:11 +000097cl::list<std::string>
98 llvm::DumpSections("section",
99 cl::desc("Prints the specified segment,section for "
100 "Mach-O objects (requires -macho)"));
101
Adrian Prantlc2401dd2015-03-27 17:31:15 +0000102cl::opt<bool> llvm::Raw("raw",
103 cl::desc("Have -section dump the raw binary contents"));
104
Kevin Enderbycd66be52015-03-11 22:06:32 +0000105cl::opt<bool>
106 llvm::InfoPlist("info-plist",
107 cl::desc("Print the info plist section as strings for "
108 "Mach-O objects (requires -macho)"));
109
Kevin Enderbyf0640752015-03-13 17:56:32 +0000110cl::opt<bool>
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000111 llvm::DylibsUsed("dylibs-used",
112 cl::desc("Print the shared libraries used for linked "
113 "Mach-O files (requires -macho)"));
114
115cl::opt<bool>
116 llvm::DylibId("dylib-id",
117 cl::desc("Print the shared library's id for the dylib Mach-O "
118 "file (requires -macho)"));
119
120cl::opt<bool>
Kevin Enderbyf0640752015-03-13 17:56:32 +0000121 llvm::NonVerbose("non-verbose",
122 cl::desc("Print the info for Mach-O objects in "
123 "non-verbose or numeric form (requires -macho)"));
124
Kevin Enderby0fc11822015-04-01 20:57:01 +0000125cl::opt<bool>
126 llvm::ObjcMetaData("objc-meta-data",
127 cl::desc("Print the Objective-C runtime meta data for "
128 "Mach-O files (requires -macho)"));
129
Kevin Enderby6a221752015-03-17 17:10:57 +0000130cl::opt<std::string> llvm::DisSymName(
131 "dis-symname",
132 cl::desc("disassemble just this symbol's instructions (requires -macho"));
133
Kevin Enderby8e29ec92015-03-17 22:26:11 +0000134static cl::opt<bool> NoSymbolicOperands(
135 "no-symbolic-operands",
136 cl::desc("do not symbolic operands when disassembling (requires -macho)"));
137
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000138static cl::list<std::string>
139 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
140 cl::ZeroOrMore);
141bool 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.
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000149 if (TripleName.empty()) {
150 llvm::Triple TT("unknown-unknown-unknown");
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000151 llvm::Triple ThumbTriple = Triple();
152 TT = MachOObj->getArch(McpuDefault, &ThumbTriple);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000153 TripleName = TT.str();
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000154 ThumbTripleName = ThumbTriple.str();
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000155 }
156
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000157 // Get the target specific parser.
158 std::string Error;
159 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000160 if (TheTarget && ThumbTripleName.empty())
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000161 return TheTarget;
162
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000163 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
164 if (*ThumbTarget)
165 return TheTarget;
166
167 errs() << "llvm-objdump: error: unable to get target for '";
168 if (!TheTarget)
169 errs() << TripleName;
170 else
171 errs() << ThumbTripleName;
172 errs() << "', see --version and --triple.\n";
Craig Toppere6cb63e2014-04-25 04:24:47 +0000173 return nullptr;
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000174}
175
Owen Andersond9243c42011-10-17 21:37:35 +0000176struct SymbolSorter {
177 bool operator()(const SymbolRef &A, const SymbolRef &B) {
178 SymbolRef::Type AType, BType;
179 A.getType(AType);
180 B.getType(BType);
181
182 uint64_t AAddr, BAddr;
183 if (AType != SymbolRef::ST_Function)
184 AAddr = 0;
185 else
186 A.getAddress(AAddr);
187 if (BType != SymbolRef::ST_Function)
188 BAddr = 0;
189 else
190 B.getAddress(BAddr);
191 return AAddr < BAddr;
192 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000193};
194
Kevin Enderby273ae012013-06-06 17:20:50 +0000195// Types for the storted data in code table that is built before disassembly
196// and the predicate function to sort them.
197typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
198typedef std::vector<DiceTableEntry> DiceTable;
199typedef DiceTable::iterator dice_table_iterator;
200
Kevin Enderby930fdc72014-11-06 19:00:13 +0000201// This is used to search for a data in code table entry for the PC being
202// disassembled. The j parameter has the PC in j.first. A single data in code
203// table entry can cover many bytes for each of its Kind's. So if the offset,
204// aka the i.first value, of the data in code table entry plus its Length
205// covers the PC being searched for this will return true. If not it will
206// return false.
David Majnemerea9b8ee2014-11-04 08:41:48 +0000207static bool compareDiceTableEntries(const DiceTableEntry &i,
208 const DiceTableEntry &j) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000209 uint16_t Length;
210 i.second.getLength(Length);
211
212 return j.first >= i.first && j.first < i.first + Length;
Kevin Enderby273ae012013-06-06 17:20:50 +0000213}
214
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000215static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
Kevin Enderby930fdc72014-11-06 19:00:13 +0000216 unsigned short Kind) {
217 uint32_t Value, Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000218
219 switch (Kind) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000220 default:
Charles Davis8bdfafd2013-09-01 04:28:48 +0000221 case MachO::DICE_KIND_DATA:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000222 if (Length >= 4) {
223 if (!NoShowRawInsn)
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000224 DumpBytes(ArrayRef<uint8_t>(bytes, 4));
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000225 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000226 outs() << "\t.long " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000227 Size = 4;
228 } else if (Length >= 2) {
229 if (!NoShowRawInsn)
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000230 DumpBytes(ArrayRef<uint8_t>(bytes, 2));
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000231 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000232 outs() << "\t.short " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000233 Size = 2;
234 } else {
235 if (!NoShowRawInsn)
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000236 DumpBytes(ArrayRef<uint8_t>(bytes, 2));
Kevin Enderby273ae012013-06-06 17:20:50 +0000237 Value = bytes[0];
238 outs() << "\t.byte " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000239 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000240 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000241 if (Kind == MachO::DICE_KIND_DATA)
242 outs() << "\t@ KIND_DATA\n";
243 else
244 outs() << "\t@ data in code kind = " << Kind << "\n";
Kevin Enderby273ae012013-06-06 17:20:50 +0000245 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000246 case MachO::DICE_KIND_JUMP_TABLE8:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000247 if (!NoShowRawInsn)
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000248 DumpBytes(ArrayRef<uint8_t>(bytes, 1));
Kevin Enderby273ae012013-06-06 17:20:50 +0000249 Value = bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000250 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
251 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000252 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000253 case MachO::DICE_KIND_JUMP_TABLE16:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000254 if (!NoShowRawInsn)
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000255 DumpBytes(ArrayRef<uint8_t>(bytes, 2));
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000256 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000257 outs() << "\t.short " << format("%5u", Value & 0xffff)
258 << "\t@ KIND_JUMP_TABLE16\n";
259 Size = 2;
Kevin Enderby273ae012013-06-06 17:20:50 +0000260 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000261 case MachO::DICE_KIND_JUMP_TABLE32:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000262 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
263 if (!NoShowRawInsn)
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000264 DumpBytes(ArrayRef<uint8_t>(bytes, 4));
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000265 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000266 outs() << "\t.long " << Value;
267 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
268 outs() << "\t@ KIND_JUMP_TABLE32\n";
269 else
270 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
271 Size = 4;
Kevin Enderby273ae012013-06-06 17:20:50 +0000272 break;
273 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000274 return Size;
Kevin Enderby273ae012013-06-06 17:20:50 +0000275}
276
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000277static void getSectionsAndSymbols(const MachO::mach_header Header,
278 MachOObjectFile *MachOObj,
279 std::vector<SectionRef> &Sections,
280 std::vector<SymbolRef> &Symbols,
281 SmallVectorImpl<uint64_t> &FoundFns,
282 uint64_t &BaseSegmentAddress) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000283 for (const SymbolRef &Symbol : MachOObj->symbols()) {
284 StringRef SymName;
285 Symbol.getName(SymName);
286 if (!SymName.startswith("ltmp"))
287 Symbols.push_back(Symbol);
288 }
Owen Andersond9243c42011-10-17 21:37:35 +0000289
Alexey Samsonov48803e52014-03-13 14:37:36 +0000290 for (const SectionRef &Section : MachOObj->sections()) {
Owen Andersond9243c42011-10-17 21:37:35 +0000291 StringRef SectName;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000292 Section.getName(SectName);
293 Sections.push_back(Section);
Owen Andersond9243c42011-10-17 21:37:35 +0000294 }
295
Rafael Espindola56f976f2013-04-18 18:08:55 +0000296 MachOObjectFile::LoadCommandInfo Command =
Alexey Samsonov48803e52014-03-13 14:37:36 +0000297 MachOObj->getFirstLoadCommandInfo();
Kevin Enderby273ae012013-06-06 17:20:50 +0000298 bool BaseSegmentAddressSet = false;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000299 for (unsigned i = 0;; ++i) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000300 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
Benjamin Kramer699128e2011-09-21 01:13:19 +0000301 // We found a function starts segment, parse the addresses for later
302 // consumption.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000303 MachO::linkedit_data_command LLC =
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000304 MachOObj->getLinkeditDataLoadCommand(Command);
Benjamin Kramer699128e2011-09-21 01:13:19 +0000305
Charles Davis8bdfafd2013-09-01 04:28:48 +0000306 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000307 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
308 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000309 StringRef SegName = SLC.segname;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000310 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
Kevin Enderby273ae012013-06-06 17:20:50 +0000311 BaseSegmentAddressSet = true;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000312 BaseSegmentAddress = SLC.vmaddr;
Kevin Enderby273ae012013-06-06 17:20:50 +0000313 }
314 }
Rafael Espindolafeef8c22013-04-19 11:36:47 +0000315
Charles Davis8bdfafd2013-09-01 04:28:48 +0000316 if (i == Header.ncmds - 1)
Rafael Espindolafeef8c22013-04-19 11:36:47 +0000317 break;
318 else
319 Command = MachOObj->getNextLoadCommandInfo(Command);
Benjamin Kramer8a529dc2011-09-21 22:16:43 +0000320 }
Benjamin Kramer699128e2011-09-21 01:13:19 +0000321}
322
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000323static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
324 uint32_t n, uint32_t count,
325 uint32_t stride, uint64_t addr) {
326 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
327 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
328 if (n > nindirectsyms)
329 outs() << " (entries start past the end of the indirect symbol "
330 "table) (reserved1 field greater than the table size)";
331 else if (n + count > nindirectsyms)
332 outs() << " (entries extends past the end of the indirect symbol "
333 "table)";
334 outs() << "\n";
335 uint32_t cputype = O->getHeader().cputype;
336 if (cputype & MachO::CPU_ARCH_ABI64)
337 outs() << "address index";
338 else
339 outs() << "address index";
340 if (verbose)
341 outs() << " name\n";
342 else
343 outs() << "\n";
344 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
345 if (cputype & MachO::CPU_ARCH_ABI64)
346 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
347 else
348 outs() << format("0x%08" PRIx32, addr + j * stride) << " ";
349 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
350 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
351 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
352 outs() << "LOCAL\n";
353 continue;
354 }
355 if (indirect_symbol ==
356 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
357 outs() << "LOCAL ABSOLUTE\n";
358 continue;
359 }
360 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
361 outs() << "ABSOLUTE\n";
362 continue;
363 }
364 outs() << format("%5u ", indirect_symbol);
Kevin Enderbyf0640752015-03-13 17:56:32 +0000365 if (verbose) {
366 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
367 if (indirect_symbol < Symtab.nsyms) {
368 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
369 SymbolRef Symbol = *Sym;
370 StringRef SymName;
371 Symbol.getName(SymName);
372 outs() << SymName;
373 } else {
374 outs() << "?";
375 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000376 }
377 outs() << "\n";
378 }
379}
380
381static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
382 uint32_t LoadCommandCount = O->getHeader().ncmds;
383 MachOObjectFile::LoadCommandInfo Load = O->getFirstLoadCommandInfo();
384 for (unsigned I = 0;; ++I) {
385 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
386 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
387 for (unsigned J = 0; J < Seg.nsects; ++J) {
388 MachO::section_64 Sec = O->getSection64(Load, J);
389 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
390 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
391 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
392 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
393 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
394 section_type == MachO::S_SYMBOL_STUBS) {
395 uint32_t stride;
396 if (section_type == MachO::S_SYMBOL_STUBS)
397 stride = Sec.reserved2;
398 else
399 stride = 8;
400 if (stride == 0) {
401 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
402 << Sec.sectname << ") "
403 << "(size of stubs in reserved2 field is zero)\n";
404 continue;
405 }
406 uint32_t count = Sec.size / stride;
407 outs() << "Indirect symbols for (" << Sec.segname << ","
408 << Sec.sectname << ") " << count << " entries";
409 uint32_t n = Sec.reserved1;
410 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
411 }
412 }
413 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
414 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
415 for (unsigned J = 0; J < Seg.nsects; ++J) {
416 MachO::section Sec = O->getSection(Load, J);
417 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
418 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
419 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
420 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
421 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
422 section_type == MachO::S_SYMBOL_STUBS) {
423 uint32_t stride;
424 if (section_type == MachO::S_SYMBOL_STUBS)
425 stride = Sec.reserved2;
426 else
427 stride = 4;
428 if (stride == 0) {
429 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
430 << Sec.sectname << ") "
431 << "(size of stubs in reserved2 field is zero)\n";
432 continue;
433 }
434 uint32_t count = Sec.size / stride;
435 outs() << "Indirect symbols for (" << Sec.segname << ","
436 << Sec.sectname << ") " << count << " entries";
437 uint32_t n = Sec.reserved1;
438 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
439 }
440 }
441 }
442 if (I == LoadCommandCount - 1)
443 break;
444 else
445 Load = O->getNextLoadCommandInfo(Load);
446 }
447}
448
Kevin Enderby69fe98d2015-01-23 18:52:17 +0000449static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
450 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
451 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
452 outs() << "Data in code table (" << nentries << " entries)\n";
453 outs() << "offset length kind\n";
454 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
455 ++DI) {
456 uint32_t Offset;
457 DI->getOffset(Offset);
458 outs() << format("0x%08" PRIx32, Offset) << " ";
459 uint16_t Length;
460 DI->getLength(Length);
461 outs() << format("%6u", Length) << " ";
462 uint16_t Kind;
463 DI->getKind(Kind);
464 if (verbose) {
465 switch (Kind) {
466 case MachO::DICE_KIND_DATA:
467 outs() << "DATA";
468 break;
469 case MachO::DICE_KIND_JUMP_TABLE8:
470 outs() << "JUMP_TABLE8";
471 break;
472 case MachO::DICE_KIND_JUMP_TABLE16:
473 outs() << "JUMP_TABLE16";
474 break;
475 case MachO::DICE_KIND_JUMP_TABLE32:
476 outs() << "JUMP_TABLE32";
477 break;
478 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
479 outs() << "ABS_JUMP_TABLE32";
480 break;
481 default:
482 outs() << format("0x%04" PRIx32, Kind);
483 break;
484 }
485 } else
486 outs() << format("0x%04" PRIx32, Kind);
487 outs() << "\n";
488 }
489}
490
Kevin Enderby9a509442015-01-27 21:28:24 +0000491static void PrintLinkOptHints(MachOObjectFile *O) {
492 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
493 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
494 uint32_t nloh = LohLC.datasize;
495 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
496 for (uint32_t i = 0; i < nloh;) {
497 unsigned n;
498 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
499 i += n;
500 outs() << " identifier " << identifier << " ";
501 if (i >= nloh)
502 return;
503 switch (identifier) {
504 case 1:
505 outs() << "AdrpAdrp\n";
506 break;
507 case 2:
508 outs() << "AdrpLdr\n";
509 break;
510 case 3:
511 outs() << "AdrpAddLdr\n";
512 break;
513 case 4:
514 outs() << "AdrpLdrGotLdr\n";
515 break;
516 case 5:
517 outs() << "AdrpAddStr\n";
518 break;
519 case 6:
520 outs() << "AdrpLdrGotStr\n";
521 break;
522 case 7:
523 outs() << "AdrpAdd\n";
524 break;
525 case 8:
526 outs() << "AdrpLdrGot\n";
527 break;
528 default:
529 outs() << "Unknown identifier value\n";
530 break;
531 }
532 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
533 i += n;
534 outs() << " narguments " << narguments << "\n";
535 if (i >= nloh)
536 return;
537
538 for (uint32_t j = 0; j < narguments; j++) {
539 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
540 i += n;
541 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
542 if (i >= nloh)
543 return;
544 }
545 }
546}
547
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000548static void PrintDylibs(MachOObjectFile *O, bool JustId) {
549 uint32_t LoadCommandCount = O->getHeader().ncmds;
550 MachOObjectFile::LoadCommandInfo Load = O->getFirstLoadCommandInfo();
551 for (unsigned I = 0;; ++I) {
552 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
553 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
554 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
555 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
556 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
557 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
558 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
559 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
560 if (dl.dylib.name < dl.cmdsize) {
561 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
562 if (JustId)
563 outs() << p << "\n";
564 else {
565 outs() << "\t" << p;
566 outs() << " (compatibility version "
567 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
568 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
569 << (dl.dylib.compatibility_version & 0xff) << ",";
570 outs() << " current version "
571 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
572 << ((dl.dylib.current_version >> 8) & 0xff) << "."
573 << (dl.dylib.current_version & 0xff) << ")\n";
574 }
575 } else {
576 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
577 if (Load.C.cmd == MachO::LC_ID_DYLIB)
578 outs() << "LC_ID_DYLIB ";
579 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
580 outs() << "LC_LOAD_DYLIB ";
581 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
582 outs() << "LC_LOAD_WEAK_DYLIB ";
583 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
584 outs() << "LC_LAZY_LOAD_DYLIB ";
585 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
586 outs() << "LC_REEXPORT_DYLIB ";
587 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
588 outs() << "LC_LOAD_UPWARD_DYLIB ";
589 else
590 outs() << "LC_??? ";
591 outs() << "command " << I << "\n";
592 }
593 }
594 if (I == LoadCommandCount - 1)
595 break;
596 else
597 Load = O->getNextLoadCommandInfo(Load);
598 }
599}
600
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000601typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
602
603static void CreateSymbolAddressMap(MachOObjectFile *O,
604 SymbolAddressMap *AddrMap) {
605 // Create a map of symbol addresses to symbol names.
606 for (const SymbolRef &Symbol : O->symbols()) {
607 SymbolRef::Type ST;
608 Symbol.getType(ST);
609 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
610 ST == SymbolRef::ST_Other) {
611 uint64_t Address;
612 Symbol.getAddress(Address);
613 StringRef SymName;
614 Symbol.getName(SymName);
Kevin Enderby846c0002015-04-16 17:19:59 +0000615 if (!SymName.startswith(".objc"))
616 (*AddrMap)[Address] = SymName;
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000617 }
618 }
619}
620
621// GuessSymbolName is passed the address of what might be a symbol and a
622// pointer to the SymbolAddressMap. It returns the name of a symbol
623// with that address or nullptr if no symbol is found with that address.
624static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
625 const char *SymbolName = nullptr;
626 // A DenseMap can't lookup up some values.
627 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
628 StringRef name = AddrMap->lookup(value);
629 if (!name.empty())
630 SymbolName = name.data();
631 }
632 return SymbolName;
633}
634
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000635static void DumpCstringChar(const char c) {
636 char p[2];
637 p[0] = c;
638 p[1] = '\0';
639 outs().write_escaped(p);
640}
641
Kevin Enderby10ba0412015-02-04 21:38:42 +0000642static void DumpCstringSection(MachOObjectFile *O, const char *sect,
643 uint32_t sect_size, uint64_t sect_addr,
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000644 bool print_addresses) {
Kevin Enderby10ba0412015-02-04 21:38:42 +0000645 for (uint32_t i = 0; i < sect_size; i++) {
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000646 if (print_addresses) {
647 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000648 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000649 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000650 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000651 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000652 for (; i < sect_size && sect[i] != '\0'; i++)
653 DumpCstringChar(sect[i]);
Kevin Enderby10ba0412015-02-04 21:38:42 +0000654 if (i < sect_size && sect[i] == '\0')
655 outs() << "\n";
656 }
657}
658
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000659static void DumpLiteral4(uint32_t l, float f) {
660 outs() << format("0x%08" PRIx32, l);
661 if ((l & 0x7f800000) != 0x7f800000)
662 outs() << format(" (%.16e)\n", f);
663 else {
664 if (l == 0x7f800000)
665 outs() << " (+Infinity)\n";
666 else if (l == 0xff800000)
667 outs() << " (-Infinity)\n";
668 else if ((l & 0x00400000) == 0x00400000)
669 outs() << " (non-signaling Not-a-Number)\n";
670 else
671 outs() << " (signaling Not-a-Number)\n";
672 }
673}
674
675static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
676 uint32_t sect_size, uint64_t sect_addr,
677 bool print_addresses) {
678 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
679 if (print_addresses) {
680 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000681 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000682 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000683 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000684 }
685 float f;
686 memcpy(&f, sect + i, sizeof(float));
687 if (O->isLittleEndian() != sys::IsLittleEndianHost)
688 sys::swapByteOrder(f);
689 uint32_t l;
690 memcpy(&l, sect + i, sizeof(uint32_t));
691 if (O->isLittleEndian() != sys::IsLittleEndianHost)
692 sys::swapByteOrder(l);
693 DumpLiteral4(l, f);
694 }
695}
696
697static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
698 double d) {
699 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
700 uint32_t Hi, Lo;
701 if (O->isLittleEndian()) {
702 Hi = l1;
703 Lo = l0;
704 } else {
705 Hi = l0;
706 Lo = l1;
707 }
708 // Hi is the high word, so this is equivalent to if(isfinite(d))
709 if ((Hi & 0x7ff00000) != 0x7ff00000)
710 outs() << format(" (%.16e)\n", d);
711 else {
712 if (Hi == 0x7ff00000 && Lo == 0)
713 outs() << " (+Infinity)\n";
714 else if (Hi == 0xfff00000 && Lo == 0)
715 outs() << " (-Infinity)\n";
716 else if ((Hi & 0x00080000) == 0x00080000)
717 outs() << " (non-signaling Not-a-Number)\n";
718 else
719 outs() << " (signaling Not-a-Number)\n";
720 }
721}
722
723static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
724 uint32_t sect_size, uint64_t sect_addr,
725 bool print_addresses) {
726 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
727 if (print_addresses) {
728 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000729 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000730 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000731 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000732 }
733 double d;
734 memcpy(&d, sect + i, sizeof(double));
735 if (O->isLittleEndian() != sys::IsLittleEndianHost)
736 sys::swapByteOrder(d);
737 uint32_t l0, l1;
738 memcpy(&l0, sect + i, sizeof(uint32_t));
739 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
740 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
741 sys::swapByteOrder(l0);
742 sys::swapByteOrder(l1);
743 }
744 DumpLiteral8(O, l0, l1, d);
745 }
746}
747
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000748static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
749 outs() << format("0x%08" PRIx32, l0) << " ";
750 outs() << format("0x%08" PRIx32, l1) << " ";
751 outs() << format("0x%08" PRIx32, l2) << " ";
752 outs() << format("0x%08" PRIx32, l3) << "\n";
753}
754
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000755static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
756 uint32_t sect_size, uint64_t sect_addr,
757 bool print_addresses) {
758 for (uint32_t i = 0; i < sect_size; i += 16) {
759 if (print_addresses) {
760 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000761 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000762 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000763 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000764 }
765 uint32_t l0, l1, l2, l3;
766 memcpy(&l0, sect + i, sizeof(uint32_t));
767 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
768 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
769 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
770 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
771 sys::swapByteOrder(l0);
772 sys::swapByteOrder(l1);
773 sys::swapByteOrder(l2);
774 sys::swapByteOrder(l3);
775 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000776 DumpLiteral16(l0, l1, l2, l3);
777 }
778}
779
780static void DumpLiteralPointerSection(MachOObjectFile *O,
781 const SectionRef &Section,
782 const char *sect, uint32_t sect_size,
783 uint64_t sect_addr,
784 bool print_addresses) {
785 // Collect the literal sections in this Mach-O file.
786 std::vector<SectionRef> LiteralSections;
787 for (const SectionRef &Section : O->sections()) {
788 DataRefImpl Ref = Section.getRawDataRefImpl();
789 uint32_t section_type;
790 if (O->is64Bit()) {
791 const MachO::section_64 Sec = O->getSection64(Ref);
792 section_type = Sec.flags & MachO::SECTION_TYPE;
793 } else {
794 const MachO::section Sec = O->getSection(Ref);
795 section_type = Sec.flags & MachO::SECTION_TYPE;
796 }
797 if (section_type == MachO::S_CSTRING_LITERALS ||
798 section_type == MachO::S_4BYTE_LITERALS ||
799 section_type == MachO::S_8BYTE_LITERALS ||
800 section_type == MachO::S_16BYTE_LITERALS)
801 LiteralSections.push_back(Section);
802 }
803
804 // Set the size of the literal pointer.
805 uint32_t lp_size = O->is64Bit() ? 8 : 4;
806
807 // Collect the external relocation symbols for the the literal pointers.
808 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
809 for (const RelocationRef &Reloc : Section.relocations()) {
810 DataRefImpl Rel;
811 MachO::any_relocation_info RE;
812 bool isExtern = false;
813 Rel = Reloc.getRawDataRefImpl();
814 RE = O->getRelocation(Rel);
815 isExtern = O->getPlainRelocationExternal(RE);
816 if (isExtern) {
817 uint64_t RelocOffset;
818 Reloc.getOffset(RelocOffset);
819 symbol_iterator RelocSym = Reloc.getSymbol();
820 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
821 }
822 }
823 array_pod_sort(Relocs.begin(), Relocs.end());
824
825 // Dump each literal pointer.
826 for (uint32_t i = 0; i < sect_size; i += lp_size) {
827 if (print_addresses) {
828 if (O->is64Bit())
829 outs() << format("%016" PRIx64, sect_addr + i) << " ";
830 else
831 outs() << format("%08" PRIx64, sect_addr + i) << " ";
832 }
833 uint64_t lp;
834 if (O->is64Bit()) {
835 memcpy(&lp, sect + i, sizeof(uint64_t));
836 if (O->isLittleEndian() != sys::IsLittleEndianHost)
837 sys::swapByteOrder(lp);
838 } else {
839 uint32_t li;
840 memcpy(&li, sect + i, sizeof(uint32_t));
841 if (O->isLittleEndian() != sys::IsLittleEndianHost)
842 sys::swapByteOrder(li);
843 lp = li;
844 }
845
846 // First look for an external relocation entry for this literal pointer.
David Blaikie33dd45d02015-03-23 18:39:02 +0000847 auto Reloc = std::find_if(
848 Relocs.begin(), Relocs.end(),
849 [&](const std::pair<uint64_t, SymbolRef> &P) { return P.first == i; });
850 if (Reloc != Relocs.end()) {
851 symbol_iterator RelocSym = Reloc->second;
852 StringRef SymName;
853 RelocSym->getName(SymName);
854 outs() << "external relocation entry for symbol:" << SymName << "\n";
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000855 continue;
David Blaikie33dd45d02015-03-23 18:39:02 +0000856 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000857
858 // For local references see what the section the literal pointer points to.
David Blaikie33dd45d02015-03-23 18:39:02 +0000859 auto Sect = std::find_if(LiteralSections.begin(), LiteralSections.end(),
860 [&](const SectionRef &R) {
861 return lp >= R.getAddress() &&
862 lp < R.getAddress() + R.getSize();
863 });
864 if (Sect == LiteralSections.end()) {
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000865 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
David Blaikie33dd45d02015-03-23 18:39:02 +0000866 continue;
867 }
868
869 uint64_t SectAddress = Sect->getAddress();
870 uint64_t SectSize = Sect->getSize();
871
872 StringRef SectName;
873 Sect->getName(SectName);
874 DataRefImpl Ref = Sect->getRawDataRefImpl();
875 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
876 outs() << SegmentName << ":" << SectName << ":";
877
878 uint32_t section_type;
879 if (O->is64Bit()) {
880 const MachO::section_64 Sec = O->getSection64(Ref);
881 section_type = Sec.flags & MachO::SECTION_TYPE;
882 } else {
883 const MachO::section Sec = O->getSection(Ref);
884 section_type = Sec.flags & MachO::SECTION_TYPE;
885 }
886
887 StringRef BytesStr;
888 Sect->getContents(BytesStr);
889 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
890
891 switch (section_type) {
892 case MachO::S_CSTRING_LITERALS:
893 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
894 i++) {
895 DumpCstringChar(Contents[i]);
896 }
897 outs() << "\n";
898 break;
899 case MachO::S_4BYTE_LITERALS:
900 float f;
901 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
902 uint32_t l;
903 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
904 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
905 sys::swapByteOrder(f);
906 sys::swapByteOrder(l);
907 }
908 DumpLiteral4(l, f);
909 break;
910 case MachO::S_8BYTE_LITERALS: {
911 double d;
912 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
913 uint32_t l0, l1;
914 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
915 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
916 sizeof(uint32_t));
917 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
918 sys::swapByteOrder(f);
919 sys::swapByteOrder(l0);
920 sys::swapByteOrder(l1);
921 }
922 DumpLiteral8(O, l0, l1, d);
923 break;
924 }
925 case MachO::S_16BYTE_LITERALS: {
926 uint32_t l0, l1, l2, l3;
927 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
928 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
929 sizeof(uint32_t));
930 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
931 sizeof(uint32_t));
932 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
933 sizeof(uint32_t));
934 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
935 sys::swapByteOrder(l0);
936 sys::swapByteOrder(l1);
937 sys::swapByteOrder(l2);
938 sys::swapByteOrder(l3);
939 }
940 DumpLiteral16(l0, l1, l2, l3);
941 break;
942 }
943 }
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000944 }
945}
946
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000947static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
948 uint32_t sect_size, uint64_t sect_addr,
949 SymbolAddressMap *AddrMap,
950 bool verbose) {
951 uint32_t stride;
952 if (O->is64Bit())
953 stride = sizeof(uint64_t);
954 else
955 stride = sizeof(uint32_t);
956 for (uint32_t i = 0; i < sect_size; i += stride) {
957 const char *SymbolName = nullptr;
958 if (O->is64Bit()) {
959 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
960 uint64_t pointer_value;
961 memcpy(&pointer_value, sect + i, stride);
962 if (O->isLittleEndian() != sys::IsLittleEndianHost)
963 sys::swapByteOrder(pointer_value);
964 outs() << format("0x%016" PRIx64, pointer_value);
965 if (verbose)
966 SymbolName = GuessSymbolName(pointer_value, AddrMap);
967 } else {
968 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
969 uint32_t pointer_value;
970 memcpy(&pointer_value, sect + i, stride);
971 if (O->isLittleEndian() != sys::IsLittleEndianHost)
972 sys::swapByteOrder(pointer_value);
973 outs() << format("0x%08" PRIx32, pointer_value);
974 if (verbose)
975 SymbolName = GuessSymbolName(pointer_value, AddrMap);
976 }
977 if (SymbolName)
978 outs() << " " << SymbolName;
979 outs() << "\n";
980 }
981}
982
983static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
984 uint32_t size, uint64_t addr) {
985 uint32_t cputype = O->getHeader().cputype;
986 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
987 uint32_t j;
988 for (uint32_t i = 0; i < size; i += j, addr += j) {
989 if (O->is64Bit())
990 outs() << format("%016" PRIx64, addr) << "\t";
991 else
Kevin Enderbyf0640752015-03-13 17:56:32 +0000992 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000993 for (j = 0; j < 16 && i + j < size; j++) {
994 uint8_t byte_word = *(sect + i + j);
995 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
996 }
997 outs() << "\n";
998 }
999 } else {
1000 uint32_t j;
1001 for (uint32_t i = 0; i < size; i += j, addr += j) {
1002 if (O->is64Bit())
1003 outs() << format("%016" PRIx64, addr) << "\t";
1004 else
1005 outs() << format("%08" PRIx64, sect) << "\t";
1006 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1007 j += sizeof(int32_t)) {
1008 if (i + j + sizeof(int32_t) < size) {
1009 uint32_t long_word;
1010 memcpy(&long_word, sect + i + j, sizeof(int32_t));
1011 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1012 sys::swapByteOrder(long_word);
1013 outs() << format("%08" PRIx32, long_word) << " ";
1014 } else {
1015 for (uint32_t k = 0; i + j + k < size; k++) {
1016 uint8_t byte_word = *(sect + i + j);
1017 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1018 }
1019 }
1020 }
1021 outs() << "\n";
1022 }
1023 }
1024}
1025
Kevin Enderby95df54c2015-02-04 01:01:38 +00001026static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1027 StringRef DisSegName, StringRef DisSectName);
1028
1029static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1030 bool verbose) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001031 SymbolAddressMap AddrMap;
1032 if (verbose)
1033 CreateSymbolAddressMap(O, &AddrMap);
1034
1035 for (unsigned i = 0; i < DumpSections.size(); ++i) {
1036 StringRef DumpSection = DumpSections[i];
1037 std::pair<StringRef, StringRef> DumpSegSectName;
1038 DumpSegSectName = DumpSection.split(',');
1039 StringRef DumpSegName, DumpSectName;
1040 if (DumpSegSectName.second.size()) {
1041 DumpSegName = DumpSegSectName.first;
1042 DumpSectName = DumpSegSectName.second;
1043 } else {
1044 DumpSegName = "";
1045 DumpSectName = DumpSegSectName.first;
1046 }
1047 for (const SectionRef &Section : O->sections()) {
1048 StringRef SectName;
1049 Section.getName(SectName);
1050 DataRefImpl Ref = Section.getRawDataRefImpl();
1051 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1052 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1053 (SectName == DumpSectName)) {
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001054
Kevin Enderby95df54c2015-02-04 01:01:38 +00001055 uint32_t section_flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001056 if (O->is64Bit()) {
1057 const MachO::section_64 Sec = O->getSection64(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001058 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001059
1060 } else {
1061 const MachO::section Sec = O->getSection(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001062 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001063 }
Kevin Enderby95df54c2015-02-04 01:01:38 +00001064 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001065
1066 StringRef BytesStr;
1067 Section.getContents(BytesStr);
1068 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1069 uint32_t sect_size = BytesStr.size();
1070 uint64_t sect_addr = Section.getAddress();
1071
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001072 if (Raw) {
1073 outs().write(BytesStr.data(), BytesStr.size());
1074 continue;
1075 }
1076
1077 outs() << "Contents of (" << SegName << "," << SectName
1078 << ") section\n";
1079
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001080 if (verbose) {
Kevin Enderby95df54c2015-02-04 01:01:38 +00001081 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1082 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1083 DisassembleMachO(Filename, O, SegName, SectName);
1084 continue;
1085 }
Kevin Enderbycd66be52015-03-11 22:06:32 +00001086 if (SegName == "__TEXT" && SectName == "__info_plist") {
1087 outs() << sect;
1088 continue;
1089 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001090 switch (section_type) {
1091 case MachO::S_REGULAR:
1092 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1093 break;
1094 case MachO::S_ZEROFILL:
1095 outs() << "zerofill section and has no contents in the file\n";
1096 break;
Kevin Enderby10ba0412015-02-04 21:38:42 +00001097 case MachO::S_CSTRING_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001098 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001099 break;
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001100 case MachO::S_4BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001101 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001102 break;
1103 case MachO::S_8BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001104 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001105 break;
1106 case MachO::S_16BYTE_LITERALS:
Kevin Enderby0fc11822015-04-01 20:57:01 +00001107 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1108 break;
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001109 case MachO::S_LITERAL_POINTERS:
1110 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001111 !NoLeadingAddr);
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001112 break;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001113 case MachO::S_MOD_INIT_FUNC_POINTERS:
1114 case MachO::S_MOD_TERM_FUNC_POINTERS:
1115 DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
1116 verbose);
1117 break;
1118 default:
1119 outs() << "Unknown section type ("
1120 << format("0x%08" PRIx32, section_type) << ")\n";
1121 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1122 break;
1123 }
1124 } else {
1125 if (section_type == MachO::S_ZEROFILL)
1126 outs() << "zerofill section and has no contents in the file\n";
1127 else
1128 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1129 }
1130 }
1131 }
1132 }
1133}
1134
Kevin Enderbycd66be52015-03-11 22:06:32 +00001135static void DumpInfoPlistSectionContents(StringRef Filename,
1136 MachOObjectFile *O) {
1137 for (const SectionRef &Section : O->sections()) {
1138 StringRef SectName;
1139 Section.getName(SectName);
1140 DataRefImpl Ref = Section.getRawDataRefImpl();
1141 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1142 if (SegName == "__TEXT" && SectName == "__info_plist") {
1143 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1144 StringRef BytesStr;
1145 Section.getContents(BytesStr);
1146 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1147 outs() << sect;
1148 return;
1149 }
1150 }
1151}
1152
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001153// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1154// and if it is and there is a list of architecture flags is specified then
1155// check to make sure this Mach-O file is one of those architectures or all
1156// architectures were specified. If not then an error is generated and this
1157// routine returns false. Else it returns true.
1158static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1159 if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
1160 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
1161 bool ArchFound = false;
1162 MachO::mach_header H;
1163 MachO::mach_header_64 H_64;
1164 Triple T;
1165 if (MachO->is64Bit()) {
1166 H_64 = MachO->MachOObjectFile::getHeader64();
1167 T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
1168 } else {
1169 H = MachO->MachOObjectFile::getHeader();
1170 T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
1171 }
1172 unsigned i;
1173 for (i = 0; i < ArchFlags.size(); ++i) {
1174 if (ArchFlags[i] == T.getArchName())
1175 ArchFound = true;
1176 break;
1177 }
1178 if (!ArchFound) {
1179 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1180 << "architecture: " + ArchFlags[i] + "\n";
1181 return false;
1182 }
1183 }
1184 return true;
1185}
1186
Kevin Enderby0fc11822015-04-01 20:57:01 +00001187static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1188
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001189// ProcessMachO() is passed a single opened Mach-O file, which may be an
1190// archive member and or in a slice of a universal file. It prints the
1191// the file name and header info and then processes it according to the
1192// command line options.
1193static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
1194 StringRef ArchiveMemberName = StringRef(),
1195 StringRef ArchitectureName = StringRef()) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001196 // If we are doing some processing here on the Mach-O file print the header
1197 // info. And don't print it otherwise like in the case of printing the
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001198 // UniversalHeaders or ArchiveHeaders.
Kevin Enderby131d1772015-01-09 19:22:37 +00001199 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind ||
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001200 LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints ||
Kevin Enderby0fc11822015-04-01 20:57:01 +00001201 DylibsUsed || DylibId || ObjcMetaData ||
1202 (DumpSections.size() != 0 && !Raw)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001203 outs() << Filename;
1204 if (!ArchiveMemberName.empty())
1205 outs() << '(' << ArchiveMemberName << ')';
1206 if (!ArchitectureName.empty())
1207 outs() << " (architecture " << ArchitectureName << ")";
1208 outs() << ":\n";
1209 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001210
1211 if (Disassemble)
Kevin Enderby95df54c2015-02-04 01:01:38 +00001212 DisassembleMachO(Filename, MachOOF, "__TEXT", "__text");
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001213 if (IndirectSymbols)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001214 PrintIndirectSymbols(MachOOF, !NonVerbose);
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001215 if (DataInCode)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001216 PrintDataInCodeTable(MachOOF, !NonVerbose);
Kevin Enderby9a509442015-01-27 21:28:24 +00001217 if (LinkOptHints)
1218 PrintLinkOptHints(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001219 if (Relocations)
1220 PrintRelocations(MachOOF);
1221 if (SectionHeaders)
1222 PrintSectionHeaders(MachOOF);
1223 if (SectionContents)
1224 PrintSectionContents(MachOOF);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001225 if (DumpSections.size() != 0)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001226 DumpSectionContents(Filename, MachOOF, !NonVerbose);
Kevin Enderbycd66be52015-03-11 22:06:32 +00001227 if (InfoPlist)
1228 DumpInfoPlistSectionContents(Filename, MachOOF);
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001229 if (DylibsUsed)
1230 PrintDylibs(MachOOF, false);
1231 if (DylibId)
1232 PrintDylibs(MachOOF, true);
Kevin Enderby98da6132015-01-20 21:47:46 +00001233 if (SymbolTable)
1234 PrintSymbolTable(MachOOF);
1235 if (UnwindInfo)
1236 printMachOUnwindInfo(MachOOF);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001237 if (PrivateHeaders)
1238 printMachOFileHeader(MachOOF);
Kevin Enderby0fc11822015-04-01 20:57:01 +00001239 if (ObjcMetaData)
1240 printObjcMetaData(MachOOF, !NonVerbose);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001241 if (ExportsTrie)
1242 printExportsTrie(MachOOF);
1243 if (Rebase)
1244 printRebaseTable(MachOOF);
1245 if (Bind)
1246 printBindTable(MachOOF);
1247 if (LazyBind)
1248 printLazyBindTable(MachOOF);
1249 if (WeakBind)
1250 printWeakBindTable(MachOOF);
1251}
1252
Kevin Enderby131d1772015-01-09 19:22:37 +00001253// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1254static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1255 outs() << " cputype (" << cputype << ")\n";
1256 outs() << " cpusubtype (" << cpusubtype << ")\n";
1257}
1258
1259// printCPUType() helps print_fat_headers by printing the cputype and
1260// pusubtype (symbolically for the one's it knows about).
1261static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1262 switch (cputype) {
1263 case MachO::CPU_TYPE_I386:
1264 switch (cpusubtype) {
1265 case MachO::CPU_SUBTYPE_I386_ALL:
1266 outs() << " cputype CPU_TYPE_I386\n";
1267 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1268 break;
1269 default:
1270 printUnknownCPUType(cputype, cpusubtype);
1271 break;
1272 }
1273 break;
1274 case MachO::CPU_TYPE_X86_64:
1275 switch (cpusubtype) {
1276 case MachO::CPU_SUBTYPE_X86_64_ALL:
1277 outs() << " cputype CPU_TYPE_X86_64\n";
1278 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1279 break;
1280 case MachO::CPU_SUBTYPE_X86_64_H:
1281 outs() << " cputype CPU_TYPE_X86_64\n";
1282 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1283 break;
1284 default:
1285 printUnknownCPUType(cputype, cpusubtype);
1286 break;
1287 }
1288 break;
1289 case MachO::CPU_TYPE_ARM:
1290 switch (cpusubtype) {
1291 case MachO::CPU_SUBTYPE_ARM_ALL:
1292 outs() << " cputype CPU_TYPE_ARM\n";
1293 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1294 break;
1295 case MachO::CPU_SUBTYPE_ARM_V4T:
1296 outs() << " cputype CPU_TYPE_ARM\n";
1297 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1298 break;
1299 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1300 outs() << " cputype CPU_TYPE_ARM\n";
1301 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1302 break;
1303 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1304 outs() << " cputype CPU_TYPE_ARM\n";
1305 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1306 break;
1307 case MachO::CPU_SUBTYPE_ARM_V6:
1308 outs() << " cputype CPU_TYPE_ARM\n";
1309 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1310 break;
1311 case MachO::CPU_SUBTYPE_ARM_V6M:
1312 outs() << " cputype CPU_TYPE_ARM\n";
1313 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1314 break;
1315 case MachO::CPU_SUBTYPE_ARM_V7:
1316 outs() << " cputype CPU_TYPE_ARM\n";
1317 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1318 break;
1319 case MachO::CPU_SUBTYPE_ARM_V7EM:
1320 outs() << " cputype CPU_TYPE_ARM\n";
1321 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1322 break;
1323 case MachO::CPU_SUBTYPE_ARM_V7K:
1324 outs() << " cputype CPU_TYPE_ARM\n";
1325 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1326 break;
1327 case MachO::CPU_SUBTYPE_ARM_V7M:
1328 outs() << " cputype CPU_TYPE_ARM\n";
1329 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1330 break;
1331 case MachO::CPU_SUBTYPE_ARM_V7S:
1332 outs() << " cputype CPU_TYPE_ARM\n";
1333 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1334 break;
1335 default:
1336 printUnknownCPUType(cputype, cpusubtype);
1337 break;
1338 }
1339 break;
1340 case MachO::CPU_TYPE_ARM64:
1341 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1342 case MachO::CPU_SUBTYPE_ARM64_ALL:
1343 outs() << " cputype CPU_TYPE_ARM64\n";
1344 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1345 break;
1346 default:
1347 printUnknownCPUType(cputype, cpusubtype);
1348 break;
1349 }
1350 break;
1351 default:
1352 printUnknownCPUType(cputype, cpusubtype);
1353 break;
1354 }
1355}
1356
1357static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1358 bool verbose) {
1359 outs() << "Fat headers\n";
1360 if (verbose)
1361 outs() << "fat_magic FAT_MAGIC\n";
1362 else
1363 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1364
1365 uint32_t nfat_arch = UB->getNumberOfObjects();
1366 StringRef Buf = UB->getData();
1367 uint64_t size = Buf.size();
1368 uint64_t big_size = sizeof(struct MachO::fat_header) +
1369 nfat_arch * sizeof(struct MachO::fat_arch);
1370 outs() << "nfat_arch " << UB->getNumberOfObjects();
1371 if (nfat_arch == 0)
1372 outs() << " (malformed, contains zero architecture types)\n";
1373 else if (big_size > size)
1374 outs() << " (malformed, architectures past end of file)\n";
1375 else
1376 outs() << "\n";
1377
1378 for (uint32_t i = 0; i < nfat_arch; ++i) {
1379 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1380 uint32_t cputype = OFA.getCPUType();
1381 uint32_t cpusubtype = OFA.getCPUSubType();
1382 outs() << "architecture ";
1383 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1384 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1385 uint32_t other_cputype = other_OFA.getCPUType();
1386 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
Kevin Enderby0512bd72015-01-09 21:55:03 +00001387 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
Kevin Enderby131d1772015-01-09 19:22:37 +00001388 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
Kevin Enderby0512bd72015-01-09 21:55:03 +00001389 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001390 outs() << "(illegal duplicate architecture) ";
1391 break;
Kevin Enderby0512bd72015-01-09 21:55:03 +00001392 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001393 }
1394 if (verbose) {
1395 outs() << OFA.getArchTypeName() << "\n";
1396 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1397 } else {
1398 outs() << i << "\n";
1399 outs() << " cputype " << cputype << "\n";
1400 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1401 << "\n";
1402 }
1403 if (verbose &&
1404 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1405 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1406 else
1407 outs() << " capabilities "
1408 << format("0x%" PRIx32,
1409 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1410 outs() << " offset " << OFA.getOffset();
1411 if (OFA.getOffset() > size)
1412 outs() << " (past end of file)";
1413 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1414 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1415 outs() << "\n";
1416 outs() << " size " << OFA.getSize();
1417 big_size = OFA.getOffset() + OFA.getSize();
1418 if (big_size > size)
1419 outs() << " (past end of file)";
1420 outs() << "\n";
1421 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1422 << ")\n";
1423 }
1424}
1425
Kevin Enderby13023a12015-01-15 23:19:11 +00001426static void printArchiveChild(Archive::Child &C, bool verbose,
1427 bool print_offset) {
1428 if (print_offset)
1429 outs() << C.getChildOffset() << "\t";
1430 sys::fs::perms Mode = C.getAccessMode();
1431 if (verbose) {
1432 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1433 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1434 outs() << "-";
1435 if (Mode & sys::fs::owner_read)
1436 outs() << "r";
1437 else
1438 outs() << "-";
1439 if (Mode & sys::fs::owner_write)
1440 outs() << "w";
1441 else
1442 outs() << "-";
1443 if (Mode & sys::fs::owner_exe)
1444 outs() << "x";
1445 else
1446 outs() << "-";
1447 if (Mode & sys::fs::group_read)
1448 outs() << "r";
1449 else
1450 outs() << "-";
1451 if (Mode & sys::fs::group_write)
1452 outs() << "w";
1453 else
1454 outs() << "-";
1455 if (Mode & sys::fs::group_exe)
1456 outs() << "x";
1457 else
1458 outs() << "-";
1459 if (Mode & sys::fs::others_read)
1460 outs() << "r";
1461 else
1462 outs() << "-";
1463 if (Mode & sys::fs::others_write)
1464 outs() << "w";
1465 else
1466 outs() << "-";
1467 if (Mode & sys::fs::others_exe)
1468 outs() << "x";
1469 else
1470 outs() << "-";
1471 } else {
1472 outs() << format("0%o ", Mode);
1473 }
1474
1475 unsigned UID = C.getUID();
1476 outs() << format("%3d/", UID);
1477 unsigned GID = C.getGID();
1478 outs() << format("%-3d ", GID);
Kevin Enderbyc12718932015-01-16 22:10:36 +00001479 uint64_t Size = C.getRawSize();
Kevin Enderby479ee612015-01-23 21:02:44 +00001480 outs() << format("%5" PRId64, Size) << " ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001481
1482 StringRef RawLastModified = C.getRawLastModified();
1483 if (verbose) {
1484 unsigned Seconds;
1485 if (RawLastModified.getAsInteger(10, Seconds))
1486 outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
1487 else {
1488 // Since cime(3) returns a 26 character string of the form:
1489 // "Sun Sep 16 01:03:52 1973\n\0"
1490 // just print 24 characters.
1491 time_t t = Seconds;
1492 outs() << format("%.24s ", ctime(&t));
1493 }
1494 } else {
1495 outs() << RawLastModified << " ";
1496 }
1497
1498 if (verbose) {
1499 ErrorOr<StringRef> NameOrErr = C.getName();
1500 if (NameOrErr.getError()) {
1501 StringRef RawName = C.getRawName();
1502 outs() << RawName << "\n";
1503 } else {
1504 StringRef Name = NameOrErr.get();
1505 outs() << Name << "\n";
1506 }
1507 } else {
1508 StringRef RawName = C.getRawName();
1509 outs() << RawName << "\n";
1510 }
1511}
1512
1513static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
1514 if (A->hasSymbolTable()) {
1515 Archive::child_iterator S = A->getSymbolTableChild();
1516 Archive::Child C = *S;
1517 printArchiveChild(C, verbose, print_offset);
1518 }
1519 for (Archive::child_iterator I = A->child_begin(), E = A->child_end(); I != E;
1520 ++I) {
1521 Archive::Child C = *I;
1522 printArchiveChild(C, verbose, print_offset);
1523 }
1524}
1525
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001526// ParseInputMachO() parses the named Mach-O file in Filename and handles the
1527// -arch flags selecting just those slices as specified by them and also parses
1528// archive files. Then for each individual Mach-O file ProcessMachO() is
1529// called to process the file based on the command line options.
1530void llvm::ParseInputMachO(StringRef Filename) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001531 // Check for -arch all and verifiy the -arch flags are valid.
1532 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1533 if (ArchFlags[i] == "all") {
1534 ArchAll = true;
1535 } else {
1536 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1537 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1538 "'for the -arch option\n";
1539 return;
1540 }
1541 }
1542 }
1543
1544 // Attempt to open the binary.
1545 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1546 if (std::error_code EC = BinaryOrErr.getError()) {
1547 errs() << "llvm-objdump: '" << Filename << "': " << EC.message() << ".\n";
Rafael Espindolade882cd2014-12-03 23:29:34 +00001548 return;
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001549 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001550 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001551
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001552 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1553 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001554 if (ArchiveHeaders)
1555 printArchiveHeaders(A, true, false);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001556 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
1557 I != E; ++I) {
1558 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = I->getAsBinary();
1559 if (ChildOrErr.getError())
1560 continue;
1561 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1562 if (!checkMachOAndArchFlags(O, Filename))
1563 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001564 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001565 }
1566 }
1567 return;
1568 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001569 if (UniversalHeaders) {
1570 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
Kevin Enderbyf0640752015-03-13 17:56:32 +00001571 printMachOUniversalHeaders(UB, !NonVerbose);
Kevin Enderby131d1772015-01-09 19:22:37 +00001572 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001573 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1574 // If we have a list of architecture flags specified dump only those.
1575 if (!ArchAll && ArchFlags.size() != 0) {
1576 // Look for a slice in the universal binary that matches each ArchFlag.
1577 bool ArchFound;
1578 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1579 ArchFound = false;
1580 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1581 E = UB->end_objects();
1582 I != E; ++I) {
1583 if (ArchFlags[i] == I->getArchTypeName()) {
1584 ArchFound = true;
1585 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
1586 I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001587 std::string ArchitectureName = "";
1588 if (ArchFlags.size() > 1)
1589 ArchitectureName = I->getArchTypeName();
1590 if (ObjOrErr) {
1591 ObjectFile &O = *ObjOrErr.get();
1592 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001593 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001594 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1595 I->getAsArchive()) {
1596 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001597 outs() << "Archive : " << Filename;
1598 if (!ArchitectureName.empty())
1599 outs() << " (architecture " << ArchitectureName << ")";
1600 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001601 if (ArchiveHeaders)
1602 printArchiveHeaders(A.get(), true, false);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001603 for (Archive::child_iterator AI = A->child_begin(),
1604 AE = A->child_end();
1605 AI != AE; ++AI) {
1606 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1607 if (ChildOrErr.getError())
1608 continue;
1609 if (MachOObjectFile *O =
1610 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001611 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001612 }
1613 }
1614 }
1615 }
1616 if (!ArchFound) {
1617 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1618 << "architecture: " + ArchFlags[i] + "\n";
1619 return;
1620 }
1621 }
1622 return;
1623 }
1624 // No architecture flags were specified so if this contains a slice that
1625 // matches the host architecture dump only that.
1626 if (!ArchAll) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001627 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1628 E = UB->end_objects();
1629 I != E; ++I) {
Kevin Enderby0512bd72015-01-09 21:55:03 +00001630 if (MachOObjectFile::getHostArch().getArchName() ==
1631 I->getArchTypeName()) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001632 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001633 std::string ArchiveName;
1634 ArchiveName.clear();
1635 if (ObjOrErr) {
1636 ObjectFile &O = *ObjOrErr.get();
1637 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001638 ProcessMachO(Filename, MachOOF);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001639 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1640 I->getAsArchive()) {
1641 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001642 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001643 if (ArchiveHeaders)
1644 printArchiveHeaders(A.get(), true, false);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001645 for (Archive::child_iterator AI = A->child_begin(),
1646 AE = A->child_end();
1647 AI != AE; ++AI) {
1648 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1649 if (ChildOrErr.getError())
1650 continue;
1651 if (MachOObjectFile *O =
1652 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001653 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001654 }
1655 }
1656 return;
1657 }
1658 }
1659 }
1660 // Either all architectures have been specified or none have been specified
1661 // and this does not contain the host architecture so dump all the slices.
1662 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1663 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1664 E = UB->end_objects();
1665 I != E; ++I) {
1666 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001667 std::string ArchitectureName = "";
1668 if (moreThanOneArch)
1669 ArchitectureName = I->getArchTypeName();
1670 if (ObjOrErr) {
1671 ObjectFile &Obj = *ObjOrErr.get();
1672 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001673 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001674 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
1675 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001676 outs() << "Archive : " << Filename;
1677 if (!ArchitectureName.empty())
1678 outs() << " (architecture " << ArchitectureName << ")";
1679 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001680 if (ArchiveHeaders)
1681 printArchiveHeaders(A.get(), true, false);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001682 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
1683 AI != AE; ++AI) {
1684 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1685 if (ChildOrErr.getError())
1686 continue;
1687 if (MachOObjectFile *O =
1688 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1689 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001690 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1691 ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001692 }
1693 }
1694 }
1695 }
1696 return;
1697 }
1698 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1699 if (!checkMachOAndArchFlags(O, Filename))
1700 return;
1701 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001702 ProcessMachO(Filename, MachOOF);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001703 } else
1704 errs() << "llvm-objdump: '" << Filename << "': "
1705 << "Object is not a Mach-O file type.\n";
1706 } else
1707 errs() << "llvm-objdump: '" << Filename << "': "
1708 << "Unrecognized file type.\n";
Rafael Espindola9b709252013-04-13 01:45:40 +00001709}
1710
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001711typedef std::pair<uint64_t, const char *> BindInfoEntry;
1712typedef std::vector<BindInfoEntry> BindTable;
1713typedef BindTable::iterator bind_table_iterator;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001714
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001715// The block of info used by the Symbolizer call backs.
1716struct DisassembleInfo {
1717 bool verbose;
1718 MachOObjectFile *O;
1719 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001720 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001721 std::vector<SectionRef> *Sections;
1722 const char *class_name;
1723 const char *selector_name;
1724 char *method;
Kevin Enderby04bf6932014-10-28 23:39:46 +00001725 char *demangled_name;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001726 uint64_t adrp_addr;
1727 uint32_t adrp_inst;
Kevin Enderby078be602014-10-23 19:53:12 +00001728 BindTable *bindtable;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001729};
1730
1731// SymbolizerGetOpInfo() is the operand information call back function.
1732// This is called to get the symbolic information for operand(s) of an
1733// instruction when it is being done. This routine does this from
1734// the relocation information, symbol table, etc. That block of information
1735// is a pointer to the struct DisassembleInfo that was passed when the
1736// disassembler context was created and passed to back to here when
1737// called back by the disassembler for instruction operands that could have
1738// relocation information. The address of the instruction containing operand is
1739// at the Pc parameter. The immediate value the operand has is passed in
1740// op_info->Value and is at Offset past the start of the instruction and has a
1741// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1742// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1743// names and addends of the symbolic expression to add for the operand. The
1744// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1745// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001746static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1747 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001748 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1749 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001750 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001751
1752 // Make sure all fields returned are zero if we don't set them.
1753 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1754 op_info->Value = value;
1755
1756 // If the TagType is not the value 1 which it code knows about or if no
1757 // verbose symbolic information is wanted then just return 0, indicating no
1758 // information is being returned.
David Blaikie33dd45d02015-03-23 18:39:02 +00001759 if (TagType != 1 || !info->verbose)
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001760 return 0;
1761
1762 unsigned int Arch = info->O->getArch();
1763 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001764 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1765 return 0;
1766 // First search the section's relocation entries (if any) for an entry
1767 // for this section offset.
1768 uint32_t sect_addr = info->S.getAddress();
1769 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1770 bool reloc_found = false;
1771 DataRefImpl Rel;
1772 MachO::any_relocation_info RE;
1773 bool isExtern = false;
1774 SymbolRef Symbol;
1775 bool r_scattered = false;
1776 uint32_t r_value, pair_r_value, r_type;
1777 for (const RelocationRef &Reloc : info->S.relocations()) {
1778 uint64_t RelocOffset;
1779 Reloc.getOffset(RelocOffset);
1780 if (RelocOffset == sect_offset) {
1781 Rel = Reloc.getRawDataRefImpl();
1782 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00001783 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001784 r_scattered = info->O->isRelocationScattered(RE);
1785 if (r_scattered) {
1786 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001787 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1788 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1789 DataRefImpl RelNext = Rel;
1790 info->O->moveRelocationNext(RelNext);
1791 MachO::any_relocation_info RENext;
1792 RENext = info->O->getRelocation(RelNext);
1793 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00001794 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001795 else
1796 return 0;
1797 }
1798 } else {
1799 isExtern = info->O->getPlainRelocationExternal(RE);
1800 if (isExtern) {
1801 symbol_iterator RelocSym = Reloc.getSymbol();
1802 Symbol = *RelocSym;
1803 }
1804 }
1805 reloc_found = true;
1806 break;
1807 }
1808 }
1809 if (reloc_found && isExtern) {
1810 StringRef SymName;
1811 Symbol.getName(SymName);
1812 const char *name = SymName.data();
1813 op_info->AddSymbol.Present = 1;
1814 op_info->AddSymbol.Name = name;
1815 // For i386 extern relocation entries the value in the instruction is
1816 // the offset from the symbol, and value is already set in op_info->Value.
1817 return 1;
1818 }
1819 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1820 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001821 const char *add = GuessSymbolName(r_value, info->AddrMap);
1822 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001823 uint32_t offset = value - (r_value - pair_r_value);
1824 op_info->AddSymbol.Present = 1;
1825 if (add != nullptr)
1826 op_info->AddSymbol.Name = add;
1827 else
1828 op_info->AddSymbol.Value = r_value;
1829 op_info->SubtractSymbol.Present = 1;
1830 if (sub != nullptr)
1831 op_info->SubtractSymbol.Name = sub;
1832 else
1833 op_info->SubtractSymbol.Value = pair_r_value;
1834 op_info->Value = offset;
1835 return 1;
1836 }
1837 // TODO:
1838 // Second search the external relocation entries of a fully linked image
1839 // (if any) for an entry that matches this segment offset.
1840 // uint32_t seg_offset = (Pc + Offset);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001841 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001842 }
1843 if (Arch == Triple::x86_64) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001844 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1845 return 0;
1846 // First search the section's relocation entries (if any) for an entry
1847 // for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00001848 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001849 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1850 bool reloc_found = false;
1851 DataRefImpl Rel;
1852 MachO::any_relocation_info RE;
1853 bool isExtern = false;
1854 SymbolRef Symbol;
1855 for (const RelocationRef &Reloc : info->S.relocations()) {
1856 uint64_t RelocOffset;
1857 Reloc.getOffset(RelocOffset);
1858 if (RelocOffset == sect_offset) {
1859 Rel = Reloc.getRawDataRefImpl();
1860 RE = info->O->getRelocation(Rel);
1861 // NOTE: Scattered relocations don't exist on x86_64.
1862 isExtern = info->O->getPlainRelocationExternal(RE);
1863 if (isExtern) {
1864 symbol_iterator RelocSym = Reloc.getSymbol();
1865 Symbol = *RelocSym;
1866 }
1867 reloc_found = true;
1868 break;
1869 }
1870 }
1871 if (reloc_found && isExtern) {
1872 // The Value passed in will be adjusted by the Pc if the instruction
1873 // adds the Pc. But for x86_64 external relocation entries the Value
1874 // is the offset from the external symbol.
1875 if (info->O->getAnyRelocationPCRel(RE))
1876 op_info->Value -= Pc + Offset + Size;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001877 StringRef SymName;
1878 Symbol.getName(SymName);
1879 const char *name = SymName.data();
1880 unsigned Type = info->O->getAnyRelocationType(RE);
1881 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1882 DataRefImpl RelNext = Rel;
1883 info->O->moveRelocationNext(RelNext);
1884 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1885 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1886 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1887 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1888 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1889 op_info->SubtractSymbol.Present = 1;
1890 op_info->SubtractSymbol.Name = name;
1891 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1892 Symbol = *RelocSymNext;
1893 StringRef SymNameNext;
1894 Symbol.getName(SymNameNext);
1895 name = SymNameNext.data();
1896 }
1897 }
1898 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1899 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1900 op_info->AddSymbol.Present = 1;
1901 op_info->AddSymbol.Name = name;
1902 return 1;
1903 }
1904 // TODO:
1905 // Second search the external relocation entries of a fully linked image
1906 // (if any) for an entry that matches this segment offset.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001907 // uint64_t seg_offset = (Pc + Offset);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001908 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001909 }
1910 if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00001911 if (Offset != 0 || (Size != 4 && Size != 2))
1912 return 0;
1913 // First search the section's relocation entries (if any) for an entry
1914 // for this section offset.
1915 uint32_t sect_addr = info->S.getAddress();
1916 uint32_t sect_offset = (Pc + Offset) - sect_addr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001917 DataRefImpl Rel;
1918 MachO::any_relocation_info RE;
1919 bool isExtern = false;
1920 SymbolRef Symbol;
1921 bool r_scattered = false;
1922 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
David Blaikie33dd45d02015-03-23 18:39:02 +00001923 auto Reloc =
1924 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
1925 [&](const RelocationRef &Reloc) {
1926 uint64_t RelocOffset;
1927 Reloc.getOffset(RelocOffset);
1928 return RelocOffset == sect_offset;
1929 });
1930
1931 if (Reloc == info->S.relocations().end())
1932 return 0;
1933
1934 Rel = Reloc->getRawDataRefImpl();
1935 RE = info->O->getRelocation(Rel);
1936 r_length = info->O->getAnyRelocationLength(RE);
1937 r_scattered = info->O->isRelocationScattered(RE);
1938 if (r_scattered) {
1939 r_value = info->O->getScatteredRelocationValue(RE);
1940 r_type = info->O->getScatteredRelocationType(RE);
1941 } else {
1942 r_type = info->O->getAnyRelocationType(RE);
1943 isExtern = info->O->getPlainRelocationExternal(RE);
1944 if (isExtern) {
1945 symbol_iterator RelocSym = Reloc->getSymbol();
1946 Symbol = *RelocSym;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001947 }
1948 }
David Blaikie33dd45d02015-03-23 18:39:02 +00001949 if (r_type == MachO::ARM_RELOC_HALF ||
1950 r_type == MachO::ARM_RELOC_SECTDIFF ||
1951 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1952 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1953 DataRefImpl RelNext = Rel;
1954 info->O->moveRelocationNext(RelNext);
1955 MachO::any_relocation_info RENext;
1956 RENext = info->O->getRelocation(RelNext);
1957 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
1958 if (info->O->isRelocationScattered(RENext))
1959 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1960 }
1961
1962 if (isExtern) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00001963 StringRef SymName;
1964 Symbol.getName(SymName);
1965 const char *name = SymName.data();
1966 op_info->AddSymbol.Present = 1;
1967 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00001968 switch (r_type) {
1969 case MachO::ARM_RELOC_HALF:
1970 if ((r_length & 0x1) == 1) {
1971 op_info->Value = value << 16 | other_half;
1972 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1973 } else {
1974 op_info->Value = other_half << 16 | value;
1975 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00001976 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00001977 break;
1978 default:
1979 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001980 }
1981 return 1;
1982 }
1983 // If we have a branch that is not an external relocation entry then
1984 // return 0 so the code in tryAddingSymbolicOperand() can use the
1985 // SymbolLookUp call back with the branch target address to look up the
1986 // symbol and possiblity add an annotation for a symbol stub.
David Blaikie33dd45d02015-03-23 18:39:02 +00001987 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
1988 r_type == MachO::ARM_THUMB_RELOC_BR22))
Kevin Enderby930fdc72014-11-06 19:00:13 +00001989 return 0;
1990
1991 uint32_t offset = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001992 if (r_type == MachO::ARM_RELOC_HALF ||
1993 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1994 if ((r_length & 0x1) == 1)
1995 value = value << 16 | other_half;
1996 else
1997 value = other_half << 16 | value;
1998 }
1999 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2000 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2001 offset = value - r_value;
2002 value = r_value;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002003 }
2004
David Blaikie33dd45d02015-03-23 18:39:02 +00002005 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002006 if ((r_length & 0x1) == 1)
2007 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2008 else
2009 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002010 const char *add = GuessSymbolName(r_value, info->AddrMap);
2011 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002012 int32_t offset = value - (r_value - pair_r_value);
2013 op_info->AddSymbol.Present = 1;
2014 if (add != nullptr)
2015 op_info->AddSymbol.Name = add;
2016 else
2017 op_info->AddSymbol.Value = r_value;
2018 op_info->SubtractSymbol.Present = 1;
2019 if (sub != nullptr)
2020 op_info->SubtractSymbol.Name = sub;
2021 else
2022 op_info->SubtractSymbol.Value = pair_r_value;
2023 op_info->Value = offset;
2024 return 1;
2025 }
2026
Kevin Enderby930fdc72014-11-06 19:00:13 +00002027 op_info->AddSymbol.Present = 1;
2028 op_info->Value = offset;
David Blaikie33dd45d02015-03-23 18:39:02 +00002029 if (r_type == MachO::ARM_RELOC_HALF) {
2030 if ((r_length & 0x1) == 1)
2031 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2032 else
2033 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002034 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002035 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002036 if (add != nullptr) {
2037 op_info->AddSymbol.Name = add;
2038 return 1;
2039 }
2040 op_info->AddSymbol.Value = value;
2041 return 1;
David Blaikie33dd45d02015-03-23 18:39:02 +00002042 }
2043 if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002044 if (Offset != 0 || Size != 4)
2045 return 0;
2046 // First search the section's relocation entries (if any) for an entry
2047 // for this section offset.
2048 uint64_t sect_addr = info->S.getAddress();
2049 uint64_t sect_offset = (Pc + Offset) - sect_addr;
David Blaikie33dd45d02015-03-23 18:39:02 +00002050 auto Reloc =
2051 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
2052 [&](const RelocationRef &Reloc) {
2053 uint64_t RelocOffset;
2054 Reloc.getOffset(RelocOffset);
2055 return RelocOffset == sect_offset;
2056 });
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002057
David Blaikie33dd45d02015-03-23 18:39:02 +00002058 if (Reloc == info->S.relocations().end())
2059 return 0;
2060
2061 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2062 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2063 uint32_t r_type = info->O->getAnyRelocationType(RE);
2064 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2065 DataRefImpl RelNext = Rel;
2066 info->O->moveRelocationNext(RelNext);
2067 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2068 if (value == 0) {
2069 value = info->O->getPlainRelocationSymbolNum(RENext);
2070 op_info->Value = value;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002071 }
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002072 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002073 // NOTE: Scattered relocations don't exist on arm64.
2074 if (!info->O->getPlainRelocationExternal(RE))
2075 return 0;
2076 StringRef SymName;
2077 Reloc->getSymbol()->getName(SymName);
2078 const char *name = SymName.data();
2079 op_info->AddSymbol.Present = 1;
2080 op_info->AddSymbol.Name = name;
2081
2082 switch (r_type) {
2083 case MachO::ARM64_RELOC_PAGE21:
2084 /* @page */
2085 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2086 break;
2087 case MachO::ARM64_RELOC_PAGEOFF12:
2088 /* @pageoff */
2089 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2090 break;
2091 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2092 /* @gotpage */
2093 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2094 break;
2095 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2096 /* @gotpageoff */
2097 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2098 break;
2099 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2100 /* @tvlppage is not implemented in llvm-mc */
2101 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2102 break;
2103 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2104 /* @tvlppageoff is not implemented in llvm-mc */
2105 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2106 break;
2107 default:
2108 case MachO::ARM64_RELOC_BRANCH26:
2109 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2110 break;
2111 }
2112 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002113 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002114 return 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002115}
2116
Kevin Enderbybf246f52014-09-24 23:08:22 +00002117// GuessCstringPointer is passed the address of what might be a pointer to a
2118// literal string in a cstring section. If that address is in a cstring section
2119// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002120static const char *GuessCstringPointer(uint64_t ReferenceValue,
2121 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002122 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
2123 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
2124 for (unsigned I = 0;; ++I) {
2125 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2126 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2127 for (unsigned J = 0; J < Seg.nsects; ++J) {
2128 MachO::section_64 Sec = info->O->getSection64(Load, J);
2129 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2130 if (section_type == MachO::S_CSTRING_LITERALS &&
2131 ReferenceValue >= Sec.addr &&
2132 ReferenceValue < Sec.addr + Sec.size) {
2133 uint64_t sect_offset = ReferenceValue - Sec.addr;
2134 uint64_t object_offset = Sec.offset + sect_offset;
2135 StringRef MachOContents = info->O->getData();
2136 uint64_t object_size = MachOContents.size();
2137 const char *object_addr = (const char *)MachOContents.data();
2138 if (object_offset < object_size) {
2139 const char *name = object_addr + object_offset;
2140 return name;
2141 } else {
2142 return nullptr;
2143 }
2144 }
2145 }
2146 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2147 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2148 for (unsigned J = 0; J < Seg.nsects; ++J) {
2149 MachO::section Sec = info->O->getSection(Load, J);
2150 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2151 if (section_type == MachO::S_CSTRING_LITERALS &&
2152 ReferenceValue >= Sec.addr &&
2153 ReferenceValue < Sec.addr + Sec.size) {
2154 uint64_t sect_offset = ReferenceValue - Sec.addr;
2155 uint64_t object_offset = Sec.offset + sect_offset;
2156 StringRef MachOContents = info->O->getData();
2157 uint64_t object_size = MachOContents.size();
2158 const char *object_addr = (const char *)MachOContents.data();
2159 if (object_offset < object_size) {
2160 const char *name = object_addr + object_offset;
2161 return name;
2162 } else {
2163 return nullptr;
2164 }
2165 }
2166 }
2167 }
2168 if (I == LoadCommandCount - 1)
2169 break;
2170 else
2171 Load = info->O->getNextLoadCommandInfo(Load);
2172 }
2173 return nullptr;
2174}
2175
Kevin Enderby85974882014-09-26 22:20:44 +00002176// GuessIndirectSymbol returns the name of the indirect symbol for the
2177// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2178// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2179// symbol name being referenced by the stub or pointer.
2180static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2181 struct DisassembleInfo *info) {
2182 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
2183 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
2184 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2185 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
2186 for (unsigned I = 0;; ++I) {
2187 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2188 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2189 for (unsigned J = 0; J < Seg.nsects; ++J) {
2190 MachO::section_64 Sec = info->O->getSection64(Load, J);
2191 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2192 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2193 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2194 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2195 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2196 section_type == MachO::S_SYMBOL_STUBS) &&
2197 ReferenceValue >= Sec.addr &&
2198 ReferenceValue < Sec.addr + Sec.size) {
2199 uint32_t stride;
2200 if (section_type == MachO::S_SYMBOL_STUBS)
2201 stride = Sec.reserved2;
2202 else
2203 stride = 8;
2204 if (stride == 0)
2205 return nullptr;
2206 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2207 if (index < Dysymtab.nindirectsyms) {
2208 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002209 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002210 if (indirect_symbol < Symtab.nsyms) {
2211 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2212 SymbolRef Symbol = *Sym;
2213 StringRef SymName;
2214 Symbol.getName(SymName);
2215 const char *name = SymName.data();
2216 return name;
2217 }
2218 }
2219 }
2220 }
2221 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2222 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2223 for (unsigned J = 0; J < Seg.nsects; ++J) {
2224 MachO::section Sec = info->O->getSection(Load, J);
2225 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2226 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2227 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2228 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2229 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2230 section_type == MachO::S_SYMBOL_STUBS) &&
2231 ReferenceValue >= Sec.addr &&
2232 ReferenceValue < Sec.addr + Sec.size) {
2233 uint32_t stride;
2234 if (section_type == MachO::S_SYMBOL_STUBS)
2235 stride = Sec.reserved2;
2236 else
2237 stride = 4;
2238 if (stride == 0)
2239 return nullptr;
2240 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2241 if (index < Dysymtab.nindirectsyms) {
2242 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002243 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002244 if (indirect_symbol < Symtab.nsyms) {
2245 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2246 SymbolRef Symbol = *Sym;
2247 StringRef SymName;
2248 Symbol.getName(SymName);
2249 const char *name = SymName.data();
2250 return name;
2251 }
2252 }
2253 }
2254 }
2255 }
2256 if (I == LoadCommandCount - 1)
2257 break;
2258 else
2259 Load = info->O->getNextLoadCommandInfo(Load);
2260 }
2261 return nullptr;
2262}
2263
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002264// method_reference() is called passing it the ReferenceName that might be
2265// a reference it to an Objective-C method call. If so then it allocates and
2266// assembles a method call string with the values last seen and saved in
2267// the DisassembleInfo's class_name and selector_name fields. This is saved
2268// into the method field of the info and any previous string is free'ed.
2269// Then the class_name field in the info is set to nullptr. The method call
2270// string is set into ReferenceName and ReferenceType is set to
2271// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2272// then both ReferenceType and ReferenceName are left unchanged.
2273static void method_reference(struct DisassembleInfo *info,
2274 uint64_t *ReferenceType,
2275 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002276 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002277 if (*ReferenceName != nullptr) {
2278 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002279 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002280 if (info->method != nullptr)
2281 free(info->method);
2282 if (info->class_name != nullptr) {
2283 info->method = (char *)malloc(5 + strlen(info->class_name) +
2284 strlen(info->selector_name));
2285 if (info->method != nullptr) {
2286 strcpy(info->method, "+[");
2287 strcat(info->method, info->class_name);
2288 strcat(info->method, " ");
2289 strcat(info->method, info->selector_name);
2290 strcat(info->method, "]");
2291 *ReferenceName = info->method;
2292 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2293 }
2294 } else {
2295 info->method = (char *)malloc(9 + strlen(info->selector_name));
2296 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002297 if (Arch == Triple::x86_64)
2298 strcpy(info->method, "-[%rdi ");
2299 else if (Arch == Triple::aarch64)
2300 strcpy(info->method, "-[x0 ");
2301 else
2302 strcpy(info->method, "-[r? ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002303 strcat(info->method, info->selector_name);
2304 strcat(info->method, "]");
2305 *ReferenceName = info->method;
2306 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2307 }
2308 }
2309 info->class_name = nullptr;
2310 }
2311 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002312 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002313 if (info->method != nullptr)
2314 free(info->method);
2315 info->method = (char *)malloc(17 + strlen(info->selector_name));
2316 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002317 if (Arch == Triple::x86_64)
2318 strcpy(info->method, "-[[%rdi super] ");
2319 else if (Arch == Triple::aarch64)
2320 strcpy(info->method, "-[[x0 super] ");
2321 else
2322 strcpy(info->method, "-[[r? super] ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002323 strcat(info->method, info->selector_name);
2324 strcat(info->method, "]");
2325 *ReferenceName = info->method;
2326 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2327 }
2328 info->class_name = nullptr;
2329 }
2330 }
2331 }
2332}
2333
2334// GuessPointerPointer() is passed the address of what might be a pointer to
2335// a reference to an Objective-C class, selector, message ref or cfstring.
2336// If so the value of the pointer is returned and one of the booleans are set
2337// to true. If not zero is returned and all the booleans are set to false.
2338static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2339 struct DisassembleInfo *info,
2340 bool &classref, bool &selref, bool &msgref,
2341 bool &cfstring) {
2342 classref = false;
2343 selref = false;
2344 msgref = false;
2345 cfstring = false;
2346 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
2347 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
2348 for (unsigned I = 0;; ++I) {
2349 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2350 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2351 for (unsigned J = 0; J < Seg.nsects; ++J) {
2352 MachO::section_64 Sec = info->O->getSection64(Load, J);
2353 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2354 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2355 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2356 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2357 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2358 ReferenceValue >= Sec.addr &&
2359 ReferenceValue < Sec.addr + Sec.size) {
2360 uint64_t sect_offset = ReferenceValue - Sec.addr;
2361 uint64_t object_offset = Sec.offset + sect_offset;
2362 StringRef MachOContents = info->O->getData();
2363 uint64_t object_size = MachOContents.size();
2364 const char *object_addr = (const char *)MachOContents.data();
2365 if (object_offset < object_size) {
2366 uint64_t pointer_value;
2367 memcpy(&pointer_value, object_addr + object_offset,
2368 sizeof(uint64_t));
2369 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2370 sys::swapByteOrder(pointer_value);
2371 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2372 selref = true;
2373 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2374 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2375 classref = true;
2376 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2377 ReferenceValue + 8 < Sec.addr + Sec.size) {
2378 msgref = true;
2379 memcpy(&pointer_value, object_addr + object_offset + 8,
2380 sizeof(uint64_t));
2381 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2382 sys::swapByteOrder(pointer_value);
2383 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2384 cfstring = true;
2385 return pointer_value;
2386 } else {
2387 return 0;
2388 }
2389 }
2390 }
2391 }
2392 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
2393 if (I == LoadCommandCount - 1)
2394 break;
2395 else
2396 Load = info->O->getNextLoadCommandInfo(Load);
2397 }
2398 return 0;
2399}
2400
2401// get_pointer_64 returns a pointer to the bytes in the object file at the
2402// Address from a section in the Mach-O file. And indirectly returns the
2403// offset into the section, number of bytes left in the section past the offset
2404// and which section is was being referenced. If the Address is not in a
2405// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002406static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2407 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002408 DisassembleInfo *info,
2409 bool objc_only = false) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002410 offset = 0;
2411 left = 0;
2412 S = SectionRef();
2413 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2414 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2415 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
Kevin Enderby846c0002015-04-16 17:19:59 +00002416 if (objc_only) {
2417 StringRef SectName;
2418 ((*(info->Sections))[SectIdx]).getName(SectName);
2419 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2420 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2421 if (SegName != "__OBJC" && SectName != "__cstring")
2422 continue;
2423 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002424 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2425 S = (*(info->Sections))[SectIdx];
2426 offset = Address - SectAddress;
2427 left = SectSize - offset;
2428 StringRef SectContents;
2429 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2430 return SectContents.data() + offset;
2431 }
2432 }
2433 return nullptr;
2434}
2435
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002436static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2437 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002438 DisassembleInfo *info,
2439 bool objc_only = false) {
2440 return get_pointer_64(Address, offset, left, S, info, objc_only);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002441}
2442
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002443// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2444// the symbol indirectly through n_value. Based on the relocation information
2445// for the specified section offset in the specified section reference.
Kevin Enderby0fc11822015-04-01 20:57:01 +00002446// If no relocation information is found and a non-zero ReferenceValue for the
2447// symbol is passed, look up that address in the info's AddrMap.
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002448static const char *
2449get_symbol_64(uint32_t sect_offset, SectionRef S, DisassembleInfo *info,
2450 uint64_t &n_value,
2451 uint64_t ReferenceValue = UnknownAddressOrSize) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002452 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002453 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002454 return nullptr;
2455
2456 // See if there is an external relocation entry at the sect_offset.
2457 bool reloc_found = false;
2458 DataRefImpl Rel;
2459 MachO::any_relocation_info RE;
2460 bool isExtern = false;
2461 SymbolRef Symbol;
2462 for (const RelocationRef &Reloc : S.relocations()) {
2463 uint64_t RelocOffset;
2464 Reloc.getOffset(RelocOffset);
2465 if (RelocOffset == sect_offset) {
2466 Rel = Reloc.getRawDataRefImpl();
2467 RE = info->O->getRelocation(Rel);
2468 if (info->O->isRelocationScattered(RE))
2469 continue;
2470 isExtern = info->O->getPlainRelocationExternal(RE);
2471 if (isExtern) {
2472 symbol_iterator RelocSym = Reloc.getSymbol();
2473 Symbol = *RelocSym;
2474 }
2475 reloc_found = true;
2476 break;
2477 }
2478 }
2479 // If there is an external relocation entry for a symbol in this section
2480 // at this section_offset then use that symbol's value for the n_value
2481 // and return its name.
2482 const char *SymbolName = nullptr;
2483 if (reloc_found && isExtern) {
2484 Symbol.getAddress(n_value);
Kevin Enderby0fc11822015-04-01 20:57:01 +00002485 if (n_value == UnknownAddressOrSize)
2486 n_value = 0;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002487 StringRef name;
2488 Symbol.getName(name);
2489 if (!name.empty()) {
2490 SymbolName = name.data();
2491 return SymbolName;
2492 }
2493 }
2494
2495 // TODO: For fully linked images, look through the external relocation
2496 // entries off the dynamic symtab command. For these the r_offset is from the
2497 // start of the first writeable segment in the Mach-O file. So the offset
2498 // to this section from that segment is passed to this routine by the caller,
2499 // as the database_offset. Which is the difference of the section's starting
2500 // address and the first writable segment.
2501 //
2502 // NOTE: need add passing the database_offset to this routine.
2503
Kevin Enderby0fc11822015-04-01 20:57:01 +00002504 // We did not find an external relocation entry so look up the ReferenceValue
2505 // as an address of a symbol and if found return that symbol's name.
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002506 if (ReferenceValue != UnknownAddressOrSize)
Kevin Enderby0fc11822015-04-01 20:57:01 +00002507 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002508
2509 return SymbolName;
2510}
2511
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002512static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
2513 DisassembleInfo *info,
2514 uint32_t ReferenceValue) {
2515 uint64_t n_value64;
2516 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
2517}
2518
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002519// These are structs in the Objective-C meta data and read to produce the
2520// comments for disassembly. While these are part of the ABI they are no
2521// public defintions. So the are here not in include/llvm/Support/MachO.h .
2522
2523// The cfstring object in a 64-bit Mach-O file.
2524struct cfstring64_t {
2525 uint64_t isa; // class64_t * (64-bit pointer)
2526 uint64_t flags; // flag bits
2527 uint64_t characters; // char * (64-bit pointer)
2528 uint64_t length; // number of non-NULL characters in above
2529};
2530
2531// The class object in a 64-bit Mach-O file.
2532struct class64_t {
2533 uint64_t isa; // class64_t * (64-bit pointer)
2534 uint64_t superclass; // class64_t * (64-bit pointer)
2535 uint64_t cache; // Cache (64-bit pointer)
2536 uint64_t vtable; // IMP * (64-bit pointer)
2537 uint64_t data; // class_ro64_t * (64-bit pointer)
2538};
2539
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002540struct class32_t {
2541 uint32_t isa; /* class32_t * (32-bit pointer) */
2542 uint32_t superclass; /* class32_t * (32-bit pointer) */
2543 uint32_t cache; /* Cache (32-bit pointer) */
2544 uint32_t vtable; /* IMP * (32-bit pointer) */
2545 uint32_t data; /* class_ro32_t * (32-bit pointer) */
2546};
2547
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002548struct class_ro64_t {
2549 uint32_t flags;
2550 uint32_t instanceStart;
2551 uint32_t instanceSize;
2552 uint32_t reserved;
2553 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2554 uint64_t name; // const char * (64-bit pointer)
2555 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2556 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2557 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2558 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2559 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2560};
2561
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002562struct class_ro32_t {
2563 uint32_t flags;
2564 uint32_t instanceStart;
2565 uint32_t instanceSize;
2566 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
2567 uint32_t name; /* const char * (32-bit pointer) */
2568 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
2569 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
2570 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
2571 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
2572 uint32_t baseProperties; /* const struct objc_property_list *
2573 (32-bit pointer) */
2574};
2575
2576/* Values for class_ro{64,32}_t->flags */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002577#define RO_META (1 << 0)
2578#define RO_ROOT (1 << 1)
2579#define RO_HAS_CXX_STRUCTORS (1 << 2)
2580
2581struct method_list64_t {
2582 uint32_t entsize;
2583 uint32_t count;
2584 /* struct method64_t first; These structures follow inline */
2585};
2586
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002587struct method_list32_t {
2588 uint32_t entsize;
2589 uint32_t count;
2590 /* struct method32_t first; These structures follow inline */
2591};
2592
Kevin Enderby0fc11822015-04-01 20:57:01 +00002593struct method64_t {
2594 uint64_t name; /* SEL (64-bit pointer) */
2595 uint64_t types; /* const char * (64-bit pointer) */
2596 uint64_t imp; /* IMP (64-bit pointer) */
2597};
2598
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002599struct method32_t {
2600 uint32_t name; /* SEL (32-bit pointer) */
2601 uint32_t types; /* const char * (32-bit pointer) */
2602 uint32_t imp; /* IMP (32-bit pointer) */
2603};
2604
Kevin Enderby0fc11822015-04-01 20:57:01 +00002605struct protocol_list64_t {
2606 uint64_t count; /* uintptr_t (a 64-bit value) */
2607 /* struct protocol64_t * list[0]; These pointers follow inline */
2608};
2609
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002610struct protocol_list32_t {
2611 uint32_t count; /* uintptr_t (a 32-bit value) */
2612 /* struct protocol32_t * list[0]; These pointers follow inline */
2613};
2614
Kevin Enderby0fc11822015-04-01 20:57:01 +00002615struct protocol64_t {
2616 uint64_t isa; /* id * (64-bit pointer) */
2617 uint64_t name; /* const char * (64-bit pointer) */
2618 uint64_t protocols; /* struct protocol_list64_t *
2619 (64-bit pointer) */
2620 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
2621 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
2622 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
2623 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
2624 uint64_t instanceProperties; /* struct objc_property_list *
2625 (64-bit pointer) */
2626};
2627
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002628struct protocol32_t {
2629 uint32_t isa; /* id * (32-bit pointer) */
2630 uint32_t name; /* const char * (32-bit pointer) */
2631 uint32_t protocols; /* struct protocol_list_t *
2632 (32-bit pointer) */
2633 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
2634 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
2635 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
2636 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
2637 uint32_t instanceProperties; /* struct objc_property_list *
2638 (32-bit pointer) */
2639};
2640
Kevin Enderby0fc11822015-04-01 20:57:01 +00002641struct ivar_list64_t {
2642 uint32_t entsize;
2643 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002644 /* struct ivar64_t first; These structures follow inline */
2645};
2646
2647struct ivar_list32_t {
2648 uint32_t entsize;
2649 uint32_t count;
2650 /* struct ivar32_t first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002651};
2652
2653struct ivar64_t {
2654 uint64_t offset; /* uintptr_t * (64-bit pointer) */
2655 uint64_t name; /* const char * (64-bit pointer) */
2656 uint64_t type; /* const char * (64-bit pointer) */
2657 uint32_t alignment;
2658 uint32_t size;
2659};
2660
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002661struct ivar32_t {
2662 uint32_t offset; /* uintptr_t * (32-bit pointer) */
2663 uint32_t name; /* const char * (32-bit pointer) */
2664 uint32_t type; /* const char * (32-bit pointer) */
2665 uint32_t alignment;
2666 uint32_t size;
2667};
2668
Kevin Enderby0fc11822015-04-01 20:57:01 +00002669struct objc_property_list64 {
2670 uint32_t entsize;
2671 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002672 /* struct objc_property64 first; These structures follow inline */
2673};
2674
2675struct objc_property_list32 {
2676 uint32_t entsize;
2677 uint32_t count;
2678 /* struct objc_property32 first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002679};
2680
2681struct objc_property64 {
2682 uint64_t name; /* const char * (64-bit pointer) */
2683 uint64_t attributes; /* const char * (64-bit pointer) */
2684};
2685
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002686struct objc_property32 {
2687 uint32_t name; /* const char * (32-bit pointer) */
2688 uint32_t attributes; /* const char * (32-bit pointer) */
2689};
2690
Kevin Enderby0fc11822015-04-01 20:57:01 +00002691struct category64_t {
2692 uint64_t name; /* const char * (64-bit pointer) */
2693 uint64_t cls; /* struct class_t * (64-bit pointer) */
2694 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
2695 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
2696 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
2697 uint64_t instanceProperties; /* struct objc_property_list *
2698 (64-bit pointer) */
2699};
2700
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002701struct category32_t {
2702 uint32_t name; /* const char * (32-bit pointer) */
2703 uint32_t cls; /* struct class_t * (32-bit pointer) */
2704 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
2705 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
2706 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
2707 uint32_t instanceProperties; /* struct objc_property_list *
2708 (32-bit pointer) */
2709};
2710
Kevin Enderby0fc11822015-04-01 20:57:01 +00002711struct objc_image_info64 {
2712 uint32_t version;
2713 uint32_t flags;
2714};
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002715struct objc_image_info32 {
2716 uint32_t version;
2717 uint32_t flags;
2718};
Kevin Enderby846c0002015-04-16 17:19:59 +00002719struct imageInfo_t {
2720 uint32_t version;
2721 uint32_t flags;
2722};
Kevin Enderby0fc11822015-04-01 20:57:01 +00002723/* masks for objc_image_info.flags */
2724#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
2725#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
2726
2727struct message_ref64 {
2728 uint64_t imp; /* IMP (64-bit pointer) */
2729 uint64_t sel; /* SEL (64-bit pointer) */
2730};
2731
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002732struct message_ref32 {
2733 uint32_t imp; /* IMP (32-bit pointer) */
2734 uint32_t sel; /* SEL (32-bit pointer) */
2735};
2736
Kevin Enderby846c0002015-04-16 17:19:59 +00002737// Objective-C 1 (32-bit only) meta data structs.
2738
2739struct objc_module_t {
2740 uint32_t version;
2741 uint32_t size;
2742 uint32_t name; /* char * (32-bit pointer) */
2743 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
2744};
2745
2746struct objc_symtab_t {
2747 uint32_t sel_ref_cnt;
2748 uint32_t refs; /* SEL * (32-bit pointer) */
2749 uint16_t cls_def_cnt;
2750 uint16_t cat_def_cnt;
2751 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
2752};
2753
2754struct objc_class_t {
2755 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2756 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
2757 uint32_t name; /* const char * (32-bit pointer) */
2758 int32_t version;
2759 int32_t info;
2760 int32_t instance_size;
2761 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
2762 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
2763 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
2764 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
2765};
2766
2767#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
2768// class is not a metaclass
2769#define CLS_CLASS 0x1
2770// class is a metaclass
2771#define CLS_META 0x2
2772
2773struct objc_category_t {
2774 uint32_t category_name; /* char * (32-bit pointer) */
2775 uint32_t class_name; /* char * (32-bit pointer) */
2776 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
2777 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
2778 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
2779};
2780
2781struct objc_ivar_t {
2782 uint32_t ivar_name; /* char * (32-bit pointer) */
2783 uint32_t ivar_type; /* char * (32-bit pointer) */
2784 int32_t ivar_offset;
2785};
2786
2787struct objc_ivar_list_t {
2788 int32_t ivar_count;
2789 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
2790};
2791
2792struct objc_method_list_t {
2793 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
2794 int32_t method_count;
2795 // struct objc_method_t method_list[1]; /* variable length structure */
2796};
2797
2798struct objc_method_t {
2799 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2800 uint32_t method_types; /* char * (32-bit pointer) */
2801 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
2802 (32-bit pointer) */
2803};
2804
2805struct objc_protocol_list_t {
2806 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
2807 int32_t count;
2808 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
2809 // (32-bit pointer) */
2810};
2811
2812struct objc_protocol_t {
2813 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2814 uint32_t protocol_name; /* char * (32-bit pointer) */
2815 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
2816 uint32_t instance_methods; /* struct objc_method_description_list *
2817 (32-bit pointer) */
2818 uint32_t class_methods; /* struct objc_method_description_list *
2819 (32-bit pointer) */
2820};
2821
2822struct objc_method_description_list_t {
2823 int32_t count;
2824 // struct objc_method_description_t list[1];
2825};
2826
2827struct objc_method_description_t {
2828 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2829 uint32_t types; /* char * (32-bit pointer) */
2830};
2831
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002832inline void swapStruct(struct cfstring64_t &cfs) {
2833 sys::swapByteOrder(cfs.isa);
2834 sys::swapByteOrder(cfs.flags);
2835 sys::swapByteOrder(cfs.characters);
2836 sys::swapByteOrder(cfs.length);
2837}
2838
2839inline void swapStruct(struct class64_t &c) {
2840 sys::swapByteOrder(c.isa);
2841 sys::swapByteOrder(c.superclass);
2842 sys::swapByteOrder(c.cache);
2843 sys::swapByteOrder(c.vtable);
2844 sys::swapByteOrder(c.data);
2845}
2846
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002847inline void swapStruct(struct class32_t &c) {
2848 sys::swapByteOrder(c.isa);
2849 sys::swapByteOrder(c.superclass);
2850 sys::swapByteOrder(c.cache);
2851 sys::swapByteOrder(c.vtable);
2852 sys::swapByteOrder(c.data);
2853}
2854
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002855inline void swapStruct(struct class_ro64_t &cro) {
2856 sys::swapByteOrder(cro.flags);
2857 sys::swapByteOrder(cro.instanceStart);
2858 sys::swapByteOrder(cro.instanceSize);
2859 sys::swapByteOrder(cro.reserved);
2860 sys::swapByteOrder(cro.ivarLayout);
2861 sys::swapByteOrder(cro.name);
2862 sys::swapByteOrder(cro.baseMethods);
2863 sys::swapByteOrder(cro.baseProtocols);
2864 sys::swapByteOrder(cro.ivars);
2865 sys::swapByteOrder(cro.weakIvarLayout);
2866 sys::swapByteOrder(cro.baseProperties);
2867}
2868
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002869inline void swapStruct(struct class_ro32_t &cro) {
2870 sys::swapByteOrder(cro.flags);
2871 sys::swapByteOrder(cro.instanceStart);
2872 sys::swapByteOrder(cro.instanceSize);
2873 sys::swapByteOrder(cro.ivarLayout);
2874 sys::swapByteOrder(cro.name);
2875 sys::swapByteOrder(cro.baseMethods);
2876 sys::swapByteOrder(cro.baseProtocols);
2877 sys::swapByteOrder(cro.ivars);
2878 sys::swapByteOrder(cro.weakIvarLayout);
2879 sys::swapByteOrder(cro.baseProperties);
2880}
2881
Kevin Enderby0fc11822015-04-01 20:57:01 +00002882inline void swapStruct(struct method_list64_t &ml) {
2883 sys::swapByteOrder(ml.entsize);
2884 sys::swapByteOrder(ml.count);
2885}
2886
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002887inline void swapStruct(struct method_list32_t &ml) {
2888 sys::swapByteOrder(ml.entsize);
2889 sys::swapByteOrder(ml.count);
2890}
2891
Kevin Enderby0fc11822015-04-01 20:57:01 +00002892inline void swapStruct(struct method64_t &m) {
2893 sys::swapByteOrder(m.name);
2894 sys::swapByteOrder(m.types);
2895 sys::swapByteOrder(m.imp);
2896}
2897
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002898inline void swapStruct(struct method32_t &m) {
2899 sys::swapByteOrder(m.name);
2900 sys::swapByteOrder(m.types);
2901 sys::swapByteOrder(m.imp);
2902}
2903
Kevin Enderby0fc11822015-04-01 20:57:01 +00002904inline void swapStruct(struct protocol_list64_t &pl) {
2905 sys::swapByteOrder(pl.count);
2906}
2907
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002908inline void swapStruct(struct protocol_list32_t &pl) {
2909 sys::swapByteOrder(pl.count);
2910}
2911
Kevin Enderby0fc11822015-04-01 20:57:01 +00002912inline void swapStruct(struct protocol64_t &p) {
2913 sys::swapByteOrder(p.isa);
2914 sys::swapByteOrder(p.name);
2915 sys::swapByteOrder(p.protocols);
2916 sys::swapByteOrder(p.instanceMethods);
2917 sys::swapByteOrder(p.classMethods);
2918 sys::swapByteOrder(p.optionalInstanceMethods);
2919 sys::swapByteOrder(p.optionalClassMethods);
2920 sys::swapByteOrder(p.instanceProperties);
2921}
2922
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002923inline void swapStruct(struct protocol32_t &p) {
2924 sys::swapByteOrder(p.isa);
2925 sys::swapByteOrder(p.name);
2926 sys::swapByteOrder(p.protocols);
2927 sys::swapByteOrder(p.instanceMethods);
2928 sys::swapByteOrder(p.classMethods);
2929 sys::swapByteOrder(p.optionalInstanceMethods);
2930 sys::swapByteOrder(p.optionalClassMethods);
2931 sys::swapByteOrder(p.instanceProperties);
2932}
2933
Kevin Enderby0fc11822015-04-01 20:57:01 +00002934inline void swapStruct(struct ivar_list64_t &il) {
2935 sys::swapByteOrder(il.entsize);
2936 sys::swapByteOrder(il.count);
2937}
2938
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002939inline void swapStruct(struct ivar_list32_t &il) {
2940 sys::swapByteOrder(il.entsize);
2941 sys::swapByteOrder(il.count);
2942}
2943
Kevin Enderby0fc11822015-04-01 20:57:01 +00002944inline void swapStruct(struct ivar64_t &i) {
2945 sys::swapByteOrder(i.offset);
2946 sys::swapByteOrder(i.name);
2947 sys::swapByteOrder(i.type);
2948 sys::swapByteOrder(i.alignment);
2949 sys::swapByteOrder(i.size);
2950}
2951
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002952inline void swapStruct(struct ivar32_t &i) {
2953 sys::swapByteOrder(i.offset);
2954 sys::swapByteOrder(i.name);
2955 sys::swapByteOrder(i.type);
2956 sys::swapByteOrder(i.alignment);
2957 sys::swapByteOrder(i.size);
2958}
2959
Kevin Enderby0fc11822015-04-01 20:57:01 +00002960inline void swapStruct(struct objc_property_list64 &pl) {
2961 sys::swapByteOrder(pl.entsize);
2962 sys::swapByteOrder(pl.count);
2963}
2964
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002965inline void swapStruct(struct objc_property_list32 &pl) {
2966 sys::swapByteOrder(pl.entsize);
2967 sys::swapByteOrder(pl.count);
2968}
2969
Kevin Enderby0fc11822015-04-01 20:57:01 +00002970inline void swapStruct(struct objc_property64 &op) {
2971 sys::swapByteOrder(op.name);
2972 sys::swapByteOrder(op.attributes);
2973}
2974
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002975inline void swapStruct(struct objc_property32 &op) {
2976 sys::swapByteOrder(op.name);
2977 sys::swapByteOrder(op.attributes);
2978}
2979
Kevin Enderby0fc11822015-04-01 20:57:01 +00002980inline void swapStruct(struct category64_t &c) {
2981 sys::swapByteOrder(c.name);
2982 sys::swapByteOrder(c.cls);
2983 sys::swapByteOrder(c.instanceMethods);
2984 sys::swapByteOrder(c.classMethods);
2985 sys::swapByteOrder(c.protocols);
2986 sys::swapByteOrder(c.instanceProperties);
2987}
2988
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002989inline void swapStruct(struct category32_t &c) {
2990 sys::swapByteOrder(c.name);
2991 sys::swapByteOrder(c.cls);
2992 sys::swapByteOrder(c.instanceMethods);
2993 sys::swapByteOrder(c.classMethods);
2994 sys::swapByteOrder(c.protocols);
2995 sys::swapByteOrder(c.instanceProperties);
2996}
2997
Kevin Enderby0fc11822015-04-01 20:57:01 +00002998inline void swapStruct(struct objc_image_info64 &o) {
2999 sys::swapByteOrder(o.version);
3000 sys::swapByteOrder(o.flags);
3001}
3002
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003003inline void swapStruct(struct objc_image_info32 &o) {
3004 sys::swapByteOrder(o.version);
3005 sys::swapByteOrder(o.flags);
3006}
3007
Kevin Enderby846c0002015-04-16 17:19:59 +00003008inline void swapStruct(struct imageInfo_t &o) {
3009 sys::swapByteOrder(o.version);
3010 sys::swapByteOrder(o.flags);
3011}
3012
Kevin Enderby0fc11822015-04-01 20:57:01 +00003013inline void swapStruct(struct message_ref64 &mr) {
3014 sys::swapByteOrder(mr.imp);
3015 sys::swapByteOrder(mr.sel);
3016}
3017
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003018inline void swapStruct(struct message_ref32 &mr) {
3019 sys::swapByteOrder(mr.imp);
3020 sys::swapByteOrder(mr.sel);
3021}
3022
Kevin Enderby846c0002015-04-16 17:19:59 +00003023inline void swapStruct(struct objc_module_t &module) {
3024 sys::swapByteOrder(module.version);
3025 sys::swapByteOrder(module.size);
3026 sys::swapByteOrder(module.name);
3027 sys::swapByteOrder(module.symtab);
Jingyue Wufedecc42015-04-16 18:43:44 +00003028}
Kevin Enderby846c0002015-04-16 17:19:59 +00003029
3030inline void swapStruct(struct objc_symtab_t &symtab) {
3031 sys::swapByteOrder(symtab.sel_ref_cnt);
3032 sys::swapByteOrder(symtab.refs);
3033 sys::swapByteOrder(symtab.cls_def_cnt);
3034 sys::swapByteOrder(symtab.cat_def_cnt);
Jingyue Wufedecc42015-04-16 18:43:44 +00003035}
Kevin Enderby846c0002015-04-16 17:19:59 +00003036
3037inline void swapStruct(struct objc_class_t &objc_class) {
3038 sys::swapByteOrder(objc_class.isa);
3039 sys::swapByteOrder(objc_class.super_class);
3040 sys::swapByteOrder(objc_class.name);
3041 sys::swapByteOrder(objc_class.version);
3042 sys::swapByteOrder(objc_class.info);
3043 sys::swapByteOrder(objc_class.instance_size);
3044 sys::swapByteOrder(objc_class.ivars);
3045 sys::swapByteOrder(objc_class.methodLists);
3046 sys::swapByteOrder(objc_class.cache);
3047 sys::swapByteOrder(objc_class.protocols);
Jingyue Wufedecc42015-04-16 18:43:44 +00003048}
Kevin Enderby846c0002015-04-16 17:19:59 +00003049
3050inline void swapStruct(struct objc_category_t &objc_category) {
3051 sys::swapByteOrder(objc_category.category_name);
3052 sys::swapByteOrder(objc_category.class_name);
3053 sys::swapByteOrder(objc_category.instance_methods);
3054 sys::swapByteOrder(objc_category.class_methods);
3055 sys::swapByteOrder(objc_category.protocols);
3056}
3057
3058inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3059 sys::swapByteOrder(objc_ivar_list.ivar_count);
3060}
3061
3062inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3063 sys::swapByteOrder(objc_ivar.ivar_name);
3064 sys::swapByteOrder(objc_ivar.ivar_type);
3065 sys::swapByteOrder(objc_ivar.ivar_offset);
Jingyue Wufedecc42015-04-16 18:43:44 +00003066}
Kevin Enderby846c0002015-04-16 17:19:59 +00003067
3068inline void swapStruct(struct objc_method_list_t &method_list) {
3069 sys::swapByteOrder(method_list.obsolete);
3070 sys::swapByteOrder(method_list.method_count);
3071}
3072
3073inline void swapStruct(struct objc_method_t &method) {
3074 sys::swapByteOrder(method.method_name);
3075 sys::swapByteOrder(method.method_types);
3076 sys::swapByteOrder(method.method_imp);
3077}
3078
3079inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3080 sys::swapByteOrder(protocol_list.next);
3081 sys::swapByteOrder(protocol_list.count);
3082}
3083
3084inline void swapStruct(struct objc_protocol_t &protocol) {
3085 sys::swapByteOrder(protocol.isa);
3086 sys::swapByteOrder(protocol.protocol_name);
3087 sys::swapByteOrder(protocol.protocol_list);
3088 sys::swapByteOrder(protocol.instance_methods);
3089 sys::swapByteOrder(protocol.class_methods);
3090}
3091
3092inline void swapStruct(struct objc_method_description_list_t &mdl) {
3093 sys::swapByteOrder(mdl.count);
3094}
3095
3096inline void swapStruct(struct objc_method_description_t &md) {
3097 sys::swapByteOrder(md.name);
3098 sys::swapByteOrder(md.types);
3099}
3100
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003101static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3102 struct DisassembleInfo *info);
3103
3104// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3105// to an Objective-C class and returns the class name. It is also passed the
3106// address of the pointer, so when the pointer is zero as it can be in an .o
3107// file, that is used to look for an external relocation entry with a symbol
3108// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003109static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3110 uint64_t ReferenceValue,
3111 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003112 const char *r;
3113 uint32_t offset, left;
3114 SectionRef S;
3115
3116 // The pointer_value can be 0 in an object file and have a relocation
3117 // entry for the class symbol at the ReferenceValue (the address of the
3118 // pointer).
3119 if (pointer_value == 0) {
3120 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3121 if (r == nullptr || left < sizeof(uint64_t))
3122 return nullptr;
3123 uint64_t n_value;
3124 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3125 if (symbol_name == nullptr)
3126 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00003127 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003128 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3129 return class_name + 2;
3130 else
3131 return nullptr;
3132 }
3133
3134 // The case were the pointer_value is non-zero and points to a class defined
3135 // in this Mach-O file.
3136 r = get_pointer_64(pointer_value, offset, left, S, info);
3137 if (r == nullptr || left < sizeof(struct class64_t))
3138 return nullptr;
3139 struct class64_t c;
3140 memcpy(&c, r, sizeof(struct class64_t));
3141 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3142 swapStruct(c);
3143 if (c.data == 0)
3144 return nullptr;
3145 r = get_pointer_64(c.data, offset, left, S, info);
3146 if (r == nullptr || left < sizeof(struct class_ro64_t))
3147 return nullptr;
3148 struct class_ro64_t cro;
3149 memcpy(&cro, r, sizeof(struct class_ro64_t));
3150 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3151 swapStruct(cro);
3152 if (cro.name == 0)
3153 return nullptr;
3154 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3155 return name;
3156}
3157
3158// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3159// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003160static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3161 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003162 const char *r, *name;
3163 uint32_t offset, left;
3164 SectionRef S;
3165 struct cfstring64_t cfs;
3166 uint64_t cfs_characters;
3167
3168 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3169 if (r == nullptr || left < sizeof(struct cfstring64_t))
3170 return nullptr;
3171 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3172 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3173 swapStruct(cfs);
3174 if (cfs.characters == 0) {
3175 uint64_t n_value;
3176 const char *symbol_name = get_symbol_64(
3177 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3178 if (symbol_name == nullptr)
3179 return nullptr;
3180 cfs_characters = n_value;
3181 } else
3182 cfs_characters = cfs.characters;
3183 name = get_pointer_64(cfs_characters, offset, left, S, info);
3184
3185 return name;
3186}
3187
3188// get_objc2_64bit_selref() is used for disassembly and is passed a the address
3189// of a pointer to an Objective-C selector reference when the pointer value is
3190// zero as in a .o file and is likely to have a external relocation entry with
3191// who's symbol's n_value is the real pointer to the selector name. If that is
3192// the case the real pointer to the selector name is returned else 0 is
3193// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003194static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3195 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003196 uint32_t offset, left;
3197 SectionRef S;
3198
3199 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3200 if (r == nullptr || left < sizeof(uint64_t))
3201 return 0;
3202 uint64_t n_value;
3203 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3204 if (symbol_name == nullptr)
3205 return 0;
3206 return n_value;
3207}
3208
Kevin Enderby0fc11822015-04-01 20:57:01 +00003209static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3210 const char *sectname) {
3211 for (const SectionRef &Section : O->sections()) {
3212 StringRef SectName;
3213 Section.getName(SectName);
3214 DataRefImpl Ref = Section.getRawDataRefImpl();
3215 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3216 if (SegName == segname && SectName == sectname)
3217 return Section;
3218 }
3219 return SectionRef();
3220}
3221
3222static void
3223walk_pointer_list_64(const char *listname, const SectionRef S,
3224 MachOObjectFile *O, struct DisassembleInfo *info,
3225 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3226 if (S == SectionRef())
3227 return;
3228
3229 StringRef SectName;
3230 S.getName(SectName);
3231 DataRefImpl Ref = S.getRawDataRefImpl();
3232 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3233 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3234
3235 StringRef BytesStr;
3236 S.getContents(BytesStr);
3237 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3238
3239 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3240 uint32_t left = S.getSize() - i;
3241 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3242 uint64_t p = 0;
3243 memcpy(&p, Contents + i, size);
3244 if (i + sizeof(uint64_t) > S.getSize())
3245 outs() << listname << " list pointer extends past end of (" << SegName
3246 << "," << SectName << ") section\n";
3247 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3248
3249 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3250 sys::swapByteOrder(p);
3251
3252 uint64_t n_value = 0;
3253 const char *name = get_symbol_64(i, S, info, n_value, p);
3254 if (name == nullptr)
3255 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3256
3257 if (n_value != 0) {
3258 outs() << format("0x%" PRIx64, n_value);
3259 if (p != 0)
3260 outs() << " + " << format("0x%" PRIx64, p);
3261 } else
3262 outs() << format("0x%" PRIx64, p);
3263 if (name != nullptr)
3264 outs() << " " << name;
3265 outs() << "\n";
3266
3267 p += n_value;
3268 if (func)
3269 func(p, info);
3270 }
3271}
3272
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003273static void
3274walk_pointer_list_32(const char *listname, const SectionRef S,
3275 MachOObjectFile *O, struct DisassembleInfo *info,
3276 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3277 if (S == SectionRef())
3278 return;
3279
3280 StringRef SectName;
3281 S.getName(SectName);
3282 DataRefImpl Ref = S.getRawDataRefImpl();
3283 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3284 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3285
3286 StringRef BytesStr;
3287 S.getContents(BytesStr);
3288 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3289
3290 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3291 uint32_t left = S.getSize() - i;
3292 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3293 uint32_t p = 0;
3294 memcpy(&p, Contents + i, size);
3295 if (i + sizeof(uint32_t) > S.getSize())
3296 outs() << listname << " list pointer extends past end of (" << SegName
3297 << "," << SectName << ") section\n";
Kevin Enderbycf261312015-04-06 22:33:43 +00003298 uint32_t Address = S.getAddress() + i;
3299 outs() << format("%08" PRIx32, Address) << " ";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003300
3301 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3302 sys::swapByteOrder(p);
3303 outs() << format("0x%" PRIx32, p);
3304
3305 const char *name = get_symbol_32(i, S, info, p);
3306 if (name != nullptr)
3307 outs() << " " << name;
3308 outs() << "\n";
3309
3310 if (func)
3311 func(p, info);
3312 }
3313}
3314
3315static void print_layout_map(const char *layout_map, uint32_t left) {
3316 outs() << " layout map: ";
3317 do {
3318 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3319 left--;
3320 layout_map++;
3321 } while (*layout_map != '\0' && left != 0);
3322 outs() << "\n";
3323}
3324
Kevin Enderby0fc11822015-04-01 20:57:01 +00003325static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3326 uint32_t offset, left;
3327 SectionRef S;
3328 const char *layout_map;
3329
3330 if (p == 0)
3331 return;
3332 layout_map = get_pointer_64(p, offset, left, S, info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003333 print_layout_map(layout_map, left);
3334}
3335
3336static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3337 uint32_t offset, left;
3338 SectionRef S;
3339 const char *layout_map;
3340
3341 if (p == 0)
3342 return;
3343 layout_map = get_pointer_32(p, offset, left, S, info);
3344 print_layout_map(layout_map, left);
Kevin Enderby0fc11822015-04-01 20:57:01 +00003345}
3346
3347static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3348 const char *indent) {
3349 struct method_list64_t ml;
3350 struct method64_t m;
3351 const char *r;
3352 uint32_t offset, xoffset, left, i;
3353 SectionRef S, xS;
3354 const char *name, *sym_name;
3355 uint64_t n_value;
3356
3357 r = get_pointer_64(p, offset, left, S, info);
3358 if (r == nullptr)
3359 return;
3360 memset(&ml, '\0', sizeof(struct method_list64_t));
3361 if (left < sizeof(struct method_list64_t)) {
3362 memcpy(&ml, r, left);
3363 outs() << " (method_list_t entends past the end of the section)\n";
3364 } else
3365 memcpy(&ml, r, sizeof(struct method_list64_t));
3366 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3367 swapStruct(ml);
3368 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3369 outs() << indent << "\t\t count " << ml.count << "\n";
3370
3371 p += sizeof(struct method_list64_t);
3372 offset += sizeof(struct method_list64_t);
3373 for (i = 0; i < ml.count; i++) {
3374 r = get_pointer_64(p, offset, left, S, info);
3375 if (r == nullptr)
3376 return;
3377 memset(&m, '\0', sizeof(struct method64_t));
3378 if (left < sizeof(struct method64_t)) {
3379 memcpy(&ml, r, left);
3380 outs() << indent << " (method_t entends past the end of the section)\n";
3381 } else
3382 memcpy(&m, r, sizeof(struct method64_t));
3383 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3384 swapStruct(m);
3385
3386 outs() << indent << "\t\t name ";
3387 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3388 info, n_value, m.name);
3389 if (n_value != 0) {
3390 if (info->verbose && sym_name != nullptr)
3391 outs() << sym_name;
3392 else
3393 outs() << format("0x%" PRIx64, n_value);
3394 if (m.name != 0)
3395 outs() << " + " << format("0x%" PRIx64, m.name);
3396 } else
3397 outs() << format("0x%" PRIx64, m.name);
3398 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3399 if (name != nullptr)
3400 outs() << format(" %.*s", left, name);
3401 outs() << "\n";
3402
3403 outs() << indent << "\t\t types ";
3404 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3405 info, n_value, m.types);
3406 if (n_value != 0) {
3407 if (info->verbose && sym_name != nullptr)
3408 outs() << sym_name;
3409 else
3410 outs() << format("0x%" PRIx64, n_value);
3411 if (m.types != 0)
3412 outs() << " + " << format("0x%" PRIx64, m.types);
3413 } else
3414 outs() << format("0x%" PRIx64, m.types);
3415 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3416 if (name != nullptr)
3417 outs() << format(" %.*s", left, name);
3418 outs() << "\n";
3419
3420 outs() << indent << "\t\t imp ";
3421 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3422 n_value, m.imp);
3423 if (info->verbose && name == nullptr) {
3424 if (n_value != 0) {
3425 outs() << format("0x%" PRIx64, n_value) << " ";
3426 if (m.imp != 0)
3427 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3428 } else
3429 outs() << format("0x%" PRIx64, m.imp) << " ";
3430 }
3431 if (name != nullptr)
3432 outs() << name;
3433 outs() << "\n";
3434
3435 p += sizeof(struct method64_t);
3436 offset += sizeof(struct method64_t);
3437 }
3438}
3439
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003440static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3441 const char *indent) {
3442 struct method_list32_t ml;
3443 struct method32_t m;
Kevin Enderby846c0002015-04-16 17:19:59 +00003444 const char *r, *name;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003445 uint32_t offset, xoffset, left, i;
3446 SectionRef S, xS;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003447
3448 r = get_pointer_32(p, offset, left, S, info);
3449 if (r == nullptr)
3450 return;
3451 memset(&ml, '\0', sizeof(struct method_list32_t));
3452 if (left < sizeof(struct method_list32_t)) {
3453 memcpy(&ml, r, left);
3454 outs() << " (method_list_t entends past the end of the section)\n";
3455 } else
3456 memcpy(&ml, r, sizeof(struct method_list32_t));
3457 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3458 swapStruct(ml);
3459 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3460 outs() << indent << "\t\t count " << ml.count << "\n";
3461
3462 p += sizeof(struct method_list32_t);
3463 offset += sizeof(struct method_list32_t);
3464 for (i = 0; i < ml.count; i++) {
3465 r = get_pointer_32(p, offset, left, S, info);
3466 if (r == nullptr)
3467 return;
3468 memset(&m, '\0', sizeof(struct method32_t));
3469 if (left < sizeof(struct method32_t)) {
3470 memcpy(&ml, r, left);
3471 outs() << indent << " (method_t entends past the end of the section)\n";
3472 } else
3473 memcpy(&m, r, sizeof(struct method32_t));
3474 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3475 swapStruct(m);
3476
3477 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
3478 name = get_pointer_32(m.name, xoffset, left, xS, info);
3479 if (name != nullptr)
3480 outs() << format(" %.*s", left, name);
3481 outs() << "\n";
3482
3483 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
3484 name = get_pointer_32(m.types, xoffset, left, xS, info);
3485 if (name != nullptr)
3486 outs() << format(" %.*s", left, name);
3487 outs() << "\n";
3488
3489 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
3490 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
3491 m.imp);
3492 if (name != nullptr)
3493 outs() << " " << name;
3494 outs() << "\n";
3495
3496 p += sizeof(struct method32_t);
3497 offset += sizeof(struct method32_t);
3498 }
3499}
3500
Kevin Enderby846c0002015-04-16 17:19:59 +00003501static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
3502 uint32_t offset, left, xleft;
3503 SectionRef S;
3504 struct objc_method_list_t method_list;
3505 struct objc_method_t method;
3506 const char *r, *methods, *name, *SymbolName;
3507 int32_t i;
3508
3509 r = get_pointer_32(p, offset, left, S, info, true);
3510 if (r == nullptr)
3511 return true;
3512
3513 outs() << "\n";
3514 if (left > sizeof(struct objc_method_list_t)) {
3515 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
3516 } else {
3517 outs() << "\t\t objc_method_list extends past end of the section\n";
3518 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
3519 memcpy(&method_list, r, left);
3520 }
3521 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3522 swapStruct(method_list);
3523
3524 outs() << "\t\t obsolete "
3525 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
3526 outs() << "\t\t method_count " << method_list.method_count << "\n";
3527
3528 methods = r + sizeof(struct objc_method_list_t);
3529 for (i = 0; i < method_list.method_count; i++) {
3530 if ((i + 1) * sizeof(struct objc_method_t) > left) {
3531 outs() << "\t\t remaining method's extend past the of the section\n";
3532 break;
3533 }
3534 memcpy(&method, methods + i * sizeof(struct objc_method_t),
3535 sizeof(struct objc_method_t));
3536 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3537 swapStruct(method);
3538
3539 outs() << "\t\t method_name "
3540 << format("0x%08" PRIx32, method.method_name);
3541 if (info->verbose) {
3542 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
3543 if (name != nullptr)
3544 outs() << format(" %.*s", xleft, name);
3545 else
3546 outs() << " (not in an __OBJC section)";
3547 }
3548 outs() << "\n";
3549
3550 outs() << "\t\t method_types "
3551 << format("0x%08" PRIx32, method.method_types);
3552 if (info->verbose) {
3553 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
3554 if (name != nullptr)
3555 outs() << format(" %.*s", xleft, name);
3556 else
3557 outs() << " (not in an __OBJC section)";
3558 }
3559 outs() << "\n";
3560
3561 outs() << "\t\t method_imp "
3562 << format("0x%08" PRIx32, method.method_imp) << " ";
3563 if (info->verbose) {
3564 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
3565 if (SymbolName != nullptr)
3566 outs() << SymbolName;
3567 }
3568 outs() << "\n";
3569 }
3570 return false;
3571}
3572
Kevin Enderby0fc11822015-04-01 20:57:01 +00003573static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
3574 struct protocol_list64_t pl;
3575 uint64_t q, n_value;
3576 struct protocol64_t pc;
3577 const char *r;
3578 uint32_t offset, xoffset, left, i;
3579 SectionRef S, xS;
3580 const char *name, *sym_name;
3581
3582 r = get_pointer_64(p, offset, left, S, info);
3583 if (r == nullptr)
3584 return;
3585 memset(&pl, '\0', sizeof(struct protocol_list64_t));
3586 if (left < sizeof(struct protocol_list64_t)) {
3587 memcpy(&pl, r, left);
3588 outs() << " (protocol_list_t entends past the end of the section)\n";
3589 } else
3590 memcpy(&pl, r, sizeof(struct protocol_list64_t));
3591 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3592 swapStruct(pl);
3593 outs() << " count " << pl.count << "\n";
3594
3595 p += sizeof(struct protocol_list64_t);
3596 offset += sizeof(struct protocol_list64_t);
3597 for (i = 0; i < pl.count; i++) {
3598 r = get_pointer_64(p, offset, left, S, info);
3599 if (r == nullptr)
3600 return;
3601 q = 0;
3602 if (left < sizeof(uint64_t)) {
3603 memcpy(&q, r, left);
3604 outs() << " (protocol_t * entends past the end of the section)\n";
3605 } else
3606 memcpy(&q, r, sizeof(uint64_t));
3607 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3608 sys::swapByteOrder(q);
3609
3610 outs() << "\t\t list[" << i << "] ";
3611 sym_name = get_symbol_64(offset, S, info, n_value, q);
3612 if (n_value != 0) {
3613 if (info->verbose && sym_name != nullptr)
3614 outs() << sym_name;
3615 else
3616 outs() << format("0x%" PRIx64, n_value);
3617 if (q != 0)
3618 outs() << " + " << format("0x%" PRIx64, q);
3619 } else
3620 outs() << format("0x%" PRIx64, q);
3621 outs() << " (struct protocol_t *)\n";
3622
3623 r = get_pointer_64(q + n_value, offset, left, S, info);
3624 if (r == nullptr)
3625 return;
3626 memset(&pc, '\0', sizeof(struct protocol64_t));
3627 if (left < sizeof(struct protocol64_t)) {
3628 memcpy(&pc, r, left);
3629 outs() << " (protocol_t entends past the end of the section)\n";
3630 } else
3631 memcpy(&pc, r, sizeof(struct protocol64_t));
3632 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3633 swapStruct(pc);
3634
3635 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
3636
3637 outs() << "\t\t\t name ";
3638 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
3639 info, n_value, pc.name);
3640 if (n_value != 0) {
3641 if (info->verbose && sym_name != nullptr)
3642 outs() << sym_name;
3643 else
3644 outs() << format("0x%" PRIx64, n_value);
3645 if (pc.name != 0)
3646 outs() << " + " << format("0x%" PRIx64, pc.name);
3647 } else
3648 outs() << format("0x%" PRIx64, pc.name);
3649 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
3650 if (name != nullptr)
3651 outs() << format(" %.*s", left, name);
3652 outs() << "\n";
3653
3654 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
3655
3656 outs() << "\t\t instanceMethods ";
3657 sym_name =
3658 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
3659 S, info, n_value, pc.instanceMethods);
3660 if (n_value != 0) {
3661 if (info->verbose && sym_name != nullptr)
3662 outs() << sym_name;
3663 else
3664 outs() << format("0x%" PRIx64, n_value);
3665 if (pc.instanceMethods != 0)
3666 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
3667 } else
3668 outs() << format("0x%" PRIx64, pc.instanceMethods);
3669 outs() << " (struct method_list_t *)\n";
3670 if (pc.instanceMethods + n_value != 0)
3671 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
3672
3673 outs() << "\t\t classMethods ";
3674 sym_name =
3675 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
3676 info, n_value, pc.classMethods);
3677 if (n_value != 0) {
3678 if (info->verbose && sym_name != nullptr)
3679 outs() << sym_name;
3680 else
3681 outs() << format("0x%" PRIx64, n_value);
3682 if (pc.classMethods != 0)
3683 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
3684 } else
3685 outs() << format("0x%" PRIx64, pc.classMethods);
3686 outs() << " (struct method_list_t *)\n";
3687 if (pc.classMethods + n_value != 0)
3688 print_method_list64_t(pc.classMethods + n_value, info, "\t");
3689
3690 outs() << "\t optionalInstanceMethods "
3691 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
3692 outs() << "\t optionalClassMethods "
3693 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
3694 outs() << "\t instanceProperties "
3695 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
3696
3697 p += sizeof(uint64_t);
3698 offset += sizeof(uint64_t);
3699 }
3700}
3701
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003702static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
3703 struct protocol_list32_t pl;
3704 uint32_t q;
3705 struct protocol32_t pc;
3706 const char *r;
3707 uint32_t offset, xoffset, left, i;
3708 SectionRef S, xS;
3709 const char *name;
3710
3711 r = get_pointer_32(p, offset, left, S, info);
3712 if (r == nullptr)
3713 return;
3714 memset(&pl, '\0', sizeof(struct protocol_list32_t));
3715 if (left < sizeof(struct protocol_list32_t)) {
3716 memcpy(&pl, r, left);
3717 outs() << " (protocol_list_t entends past the end of the section)\n";
3718 } else
3719 memcpy(&pl, r, sizeof(struct protocol_list32_t));
3720 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3721 swapStruct(pl);
3722 outs() << " count " << pl.count << "\n";
3723
3724 p += sizeof(struct protocol_list32_t);
3725 offset += sizeof(struct protocol_list32_t);
3726 for (i = 0; i < pl.count; i++) {
3727 r = get_pointer_32(p, offset, left, S, info);
3728 if (r == nullptr)
3729 return;
3730 q = 0;
3731 if (left < sizeof(uint32_t)) {
3732 memcpy(&q, r, left);
3733 outs() << " (protocol_t * entends past the end of the section)\n";
3734 } else
3735 memcpy(&q, r, sizeof(uint32_t));
3736 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3737 sys::swapByteOrder(q);
3738 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
3739 << " (struct protocol_t *)\n";
3740 r = get_pointer_32(q, offset, left, S, info);
3741 if (r == nullptr)
3742 return;
3743 memset(&pc, '\0', sizeof(struct protocol32_t));
3744 if (left < sizeof(struct protocol32_t)) {
3745 memcpy(&pc, r, left);
3746 outs() << " (protocol_t entends past the end of the section)\n";
3747 } else
3748 memcpy(&pc, r, sizeof(struct protocol32_t));
3749 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3750 swapStruct(pc);
3751 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
3752 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
3753 name = get_pointer_32(pc.name, xoffset, left, xS, info);
3754 if (name != nullptr)
3755 outs() << format(" %.*s", left, name);
3756 outs() << "\n";
3757 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
3758 outs() << "\t\t instanceMethods "
3759 << format("0x%" PRIx32, pc.instanceMethods)
3760 << " (struct method_list_t *)\n";
3761 if (pc.instanceMethods != 0)
3762 print_method_list32_t(pc.instanceMethods, info, "\t");
3763 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
3764 << " (struct method_list_t *)\n";
3765 if (pc.classMethods != 0)
3766 print_method_list32_t(pc.classMethods, info, "\t");
3767 outs() << "\t optionalInstanceMethods "
3768 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
3769 outs() << "\t optionalClassMethods "
3770 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
3771 outs() << "\t instanceProperties "
3772 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
3773 p += sizeof(uint32_t);
3774 offset += sizeof(uint32_t);
3775 }
3776}
3777
Kevin Enderby846c0002015-04-16 17:19:59 +00003778static void print_indent(uint32_t indent) {
3779 for (uint32_t i = 0; i < indent;) {
3780 if (indent - i >= 8) {
3781 outs() << "\t";
3782 i += 8;
3783 } else {
3784 for (uint32_t j = i; j < indent; j++)
3785 outs() << " ";
3786 return;
3787 }
3788 }
3789}
3790
3791static bool print_method_description_list(uint32_t p, uint32_t indent,
3792 struct DisassembleInfo *info) {
3793 uint32_t offset, left, xleft;
3794 SectionRef S;
3795 struct objc_method_description_list_t mdl;
3796 struct objc_method_description_t md;
3797 const char *r, *list, *name;
3798 int32_t i;
3799
3800 r = get_pointer_32(p, offset, left, S, info, true);
3801 if (r == nullptr)
3802 return true;
3803
3804 outs() << "\n";
3805 if (left > sizeof(struct objc_method_description_list_t)) {
3806 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
3807 } else {
3808 print_indent(indent);
3809 outs() << " objc_method_description_list extends past end of the section\n";
3810 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
3811 memcpy(&mdl, r, left);
3812 }
3813 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3814 swapStruct(mdl);
3815
3816 print_indent(indent);
3817 outs() << " count " << mdl.count << "\n";
3818
3819 list = r + sizeof(struct objc_method_description_list_t);
3820 for (i = 0; i < mdl.count; i++) {
3821 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
3822 print_indent(indent);
3823 outs() << " remaining list entries extend past the of the section\n";
3824 break;
3825 }
3826 print_indent(indent);
3827 outs() << " list[" << i << "]\n";
3828 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
3829 sizeof(struct objc_method_description_t));
3830 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3831 swapStruct(md);
3832
3833 print_indent(indent);
3834 outs() << " name " << format("0x%08" PRIx32, md.name);
3835 if (info->verbose) {
3836 name = get_pointer_32(md.name, offset, xleft, S, info, true);
3837 if (name != nullptr)
3838 outs() << format(" %.*s", xleft, name);
3839 else
3840 outs() << " (not in an __OBJC section)";
3841 }
3842 outs() << "\n";
3843
3844 print_indent(indent);
3845 outs() << " types " << format("0x%08" PRIx32, md.types);
3846 if (info->verbose) {
3847 name = get_pointer_32(md.types, offset, xleft, S, info, true);
3848 if (name != nullptr)
3849 outs() << format(" %.*s", xleft, name);
3850 else
3851 outs() << " (not in an __OBJC section)";
3852 }
3853 outs() << "\n";
3854 }
3855 return false;
3856}
3857
3858static bool print_protocol_list(uint32_t p, uint32_t indent,
3859 struct DisassembleInfo *info);
3860
3861static bool print_protocol(uint32_t p, uint32_t indent,
3862 struct DisassembleInfo *info) {
3863 uint32_t offset, left;
3864 SectionRef S;
3865 struct objc_protocol_t protocol;
3866 const char *r, *name;
3867
3868 r = get_pointer_32(p, offset, left, S, info, true);
3869 if (r == nullptr)
3870 return true;
3871
3872 outs() << "\n";
3873 if (left >= sizeof(struct objc_protocol_t)) {
3874 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
3875 } else {
3876 print_indent(indent);
3877 outs() << " Protocol extends past end of the section\n";
3878 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
3879 memcpy(&protocol, r, left);
3880 }
3881 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3882 swapStruct(protocol);
3883
3884 print_indent(indent);
3885 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
3886 << "\n";
3887
3888 print_indent(indent);
3889 outs() << " protocol_name "
3890 << format("0x%08" PRIx32, protocol.protocol_name);
3891 if (info->verbose) {
3892 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
3893 if (name != nullptr)
3894 outs() << format(" %.*s", left, name);
3895 else
3896 outs() << " (not in an __OBJC section)";
3897 }
3898 outs() << "\n";
3899
3900 print_indent(indent);
3901 outs() << " protocol_list "
3902 << format("0x%08" PRIx32, protocol.protocol_list);
3903 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
3904 outs() << " (not in an __OBJC section)\n";
3905
3906 print_indent(indent);
3907 outs() << " instance_methods "
3908 << format("0x%08" PRIx32, protocol.instance_methods);
3909 if (print_method_description_list(protocol.instance_methods, indent, info))
3910 outs() << " (not in an __OBJC section)\n";
3911
3912 print_indent(indent);
3913 outs() << " class_methods "
3914 << format("0x%08" PRIx32, protocol.class_methods);
3915 if (print_method_description_list(protocol.class_methods, indent, info))
3916 outs() << " (not in an __OBJC section)\n";
3917
3918 return false;
3919}
3920
3921static bool print_protocol_list(uint32_t p, uint32_t indent,
3922 struct DisassembleInfo *info) {
3923 uint32_t offset, left, l;
3924 SectionRef S;
3925 struct objc_protocol_list_t protocol_list;
3926 const char *r, *list;
3927 int32_t i;
3928
3929 r = get_pointer_32(p, offset, left, S, info, true);
3930 if (r == nullptr)
3931 return true;
3932
3933 outs() << "\n";
3934 if (left > sizeof(struct objc_protocol_list_t)) {
3935 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
3936 } else {
3937 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
3938 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
3939 memcpy(&protocol_list, r, left);
3940 }
3941 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3942 swapStruct(protocol_list);
3943
3944 print_indent(indent);
3945 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
3946 << "\n";
3947 print_indent(indent);
3948 outs() << " count " << protocol_list.count << "\n";
3949
3950 list = r + sizeof(struct objc_protocol_list_t);
3951 for (i = 0; i < protocol_list.count; i++) {
3952 if ((i + 1) * sizeof(uint32_t) > left) {
3953 outs() << "\t\t remaining list entries extend past the of the section\n";
3954 break;
3955 }
3956 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
3957 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3958 sys::swapByteOrder(l);
3959
3960 print_indent(indent);
3961 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
3962 if (print_protocol(l, indent, info))
3963 outs() << "(not in an __OBJC section)\n";
3964 }
3965 return false;
3966}
3967
Kevin Enderby0fc11822015-04-01 20:57:01 +00003968static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
3969 struct ivar_list64_t il;
3970 struct ivar64_t i;
3971 const char *r;
3972 uint32_t offset, xoffset, left, j;
3973 SectionRef S, xS;
3974 const char *name, *sym_name, *ivar_offset_p;
3975 uint64_t ivar_offset, n_value;
3976
3977 r = get_pointer_64(p, offset, left, S, info);
3978 if (r == nullptr)
3979 return;
3980 memset(&il, '\0', sizeof(struct ivar_list64_t));
3981 if (left < sizeof(struct ivar_list64_t)) {
3982 memcpy(&il, r, left);
3983 outs() << " (ivar_list_t entends past the end of the section)\n";
3984 } else
3985 memcpy(&il, r, sizeof(struct ivar_list64_t));
3986 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3987 swapStruct(il);
3988 outs() << " entsize " << il.entsize << "\n";
3989 outs() << " count " << il.count << "\n";
3990
3991 p += sizeof(struct ivar_list64_t);
3992 offset += sizeof(struct ivar_list64_t);
3993 for (j = 0; j < il.count; j++) {
3994 r = get_pointer_64(p, offset, left, S, info);
3995 if (r == nullptr)
3996 return;
3997 memset(&i, '\0', sizeof(struct ivar64_t));
3998 if (left < sizeof(struct ivar64_t)) {
3999 memcpy(&i, r, left);
4000 outs() << " (ivar_t entends past the end of the section)\n";
4001 } else
4002 memcpy(&i, r, sizeof(struct ivar64_t));
4003 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4004 swapStruct(i);
4005
4006 outs() << "\t\t\t offset ";
4007 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4008 info, n_value, i.offset);
4009 if (n_value != 0) {
4010 if (info->verbose && sym_name != nullptr)
4011 outs() << sym_name;
4012 else
4013 outs() << format("0x%" PRIx64, n_value);
4014 if (i.offset != 0)
4015 outs() << " + " << format("0x%" PRIx64, i.offset);
4016 } else
4017 outs() << format("0x%" PRIx64, i.offset);
4018 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4019 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4020 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4021 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4022 sys::swapByteOrder(ivar_offset);
4023 outs() << " " << ivar_offset << "\n";
4024 } else
4025 outs() << "\n";
4026
4027 outs() << "\t\t\t name ";
4028 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4029 n_value, i.name);
4030 if (n_value != 0) {
4031 if (info->verbose && sym_name != nullptr)
4032 outs() << sym_name;
4033 else
4034 outs() << format("0x%" PRIx64, n_value);
4035 if (i.name != 0)
4036 outs() << " + " << format("0x%" PRIx64, i.name);
4037 } else
4038 outs() << format("0x%" PRIx64, i.name);
4039 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4040 if (name != nullptr)
4041 outs() << format(" %.*s", left, name);
4042 outs() << "\n";
4043
4044 outs() << "\t\t\t type ";
4045 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4046 n_value, i.name);
4047 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4048 if (n_value != 0) {
4049 if (info->verbose && sym_name != nullptr)
4050 outs() << sym_name;
4051 else
4052 outs() << format("0x%" PRIx64, n_value);
4053 if (i.type != 0)
4054 outs() << " + " << format("0x%" PRIx64, i.type);
4055 } else
4056 outs() << format("0x%" PRIx64, i.type);
4057 if (name != nullptr)
4058 outs() << format(" %.*s", left, name);
4059 outs() << "\n";
4060
4061 outs() << "\t\t\talignment " << i.alignment << "\n";
4062 outs() << "\t\t\t size " << i.size << "\n";
4063
4064 p += sizeof(struct ivar64_t);
4065 offset += sizeof(struct ivar64_t);
4066 }
4067}
4068
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004069static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4070 struct ivar_list32_t il;
4071 struct ivar32_t i;
4072 const char *r;
4073 uint32_t offset, xoffset, left, j;
4074 SectionRef S, xS;
4075 const char *name, *ivar_offset_p;
4076 uint32_t ivar_offset;
4077
4078 r = get_pointer_32(p, offset, left, S, info);
4079 if (r == nullptr)
4080 return;
4081 memset(&il, '\0', sizeof(struct ivar_list32_t));
4082 if (left < sizeof(struct ivar_list32_t)) {
4083 memcpy(&il, r, left);
4084 outs() << " (ivar_list_t entends past the end of the section)\n";
4085 } else
4086 memcpy(&il, r, sizeof(struct ivar_list32_t));
4087 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4088 swapStruct(il);
4089 outs() << " entsize " << il.entsize << "\n";
4090 outs() << " count " << il.count << "\n";
4091
4092 p += sizeof(struct ivar_list32_t);
4093 offset += sizeof(struct ivar_list32_t);
4094 for (j = 0; j < il.count; j++) {
4095 r = get_pointer_32(p, offset, left, S, info);
4096 if (r == nullptr)
4097 return;
4098 memset(&i, '\0', sizeof(struct ivar32_t));
4099 if (left < sizeof(struct ivar32_t)) {
4100 memcpy(&i, r, left);
4101 outs() << " (ivar_t entends past the end of the section)\n";
4102 } else
4103 memcpy(&i, r, sizeof(struct ivar32_t));
4104 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4105 swapStruct(i);
4106
4107 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4108 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4109 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4110 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4111 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4112 sys::swapByteOrder(ivar_offset);
4113 outs() << " " << ivar_offset << "\n";
4114 } else
4115 outs() << "\n";
4116
4117 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4118 name = get_pointer_32(i.name, xoffset, left, xS, info);
4119 if (name != nullptr)
4120 outs() << format(" %.*s", left, name);
4121 outs() << "\n";
4122
4123 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4124 name = get_pointer_32(i.type, xoffset, left, xS, info);
4125 if (name != nullptr)
4126 outs() << format(" %.*s", left, name);
4127 outs() << "\n";
4128
4129 outs() << "\t\t\talignment " << i.alignment << "\n";
4130 outs() << "\t\t\t size " << i.size << "\n";
4131
4132 p += sizeof(struct ivar32_t);
4133 offset += sizeof(struct ivar32_t);
4134 }
4135}
4136
Kevin Enderby0fc11822015-04-01 20:57:01 +00004137static void print_objc_property_list64(uint64_t p,
4138 struct DisassembleInfo *info) {
4139 struct objc_property_list64 opl;
4140 struct objc_property64 op;
4141 const char *r;
4142 uint32_t offset, xoffset, left, j;
4143 SectionRef S, xS;
4144 const char *name, *sym_name;
4145 uint64_t n_value;
4146
4147 r = get_pointer_64(p, offset, left, S, info);
4148 if (r == nullptr)
4149 return;
4150 memset(&opl, '\0', sizeof(struct objc_property_list64));
4151 if (left < sizeof(struct objc_property_list64)) {
4152 memcpy(&opl, r, left);
4153 outs() << " (objc_property_list entends past the end of the section)\n";
4154 } else
4155 memcpy(&opl, r, sizeof(struct objc_property_list64));
4156 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4157 swapStruct(opl);
4158 outs() << " entsize " << opl.entsize << "\n";
4159 outs() << " count " << opl.count << "\n";
4160
4161 p += sizeof(struct objc_property_list64);
4162 offset += sizeof(struct objc_property_list64);
4163 for (j = 0; j < opl.count; j++) {
4164 r = get_pointer_64(p, offset, left, S, info);
4165 if (r == nullptr)
4166 return;
4167 memset(&op, '\0', sizeof(struct objc_property64));
4168 if (left < sizeof(struct objc_property64)) {
4169 memcpy(&op, r, left);
4170 outs() << " (objc_property entends past the end of the section)\n";
4171 } else
4172 memcpy(&op, r, sizeof(struct objc_property64));
4173 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4174 swapStruct(op);
4175
4176 outs() << "\t\t\t name ";
4177 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4178 info, n_value, op.name);
4179 if (n_value != 0) {
4180 if (info->verbose && sym_name != nullptr)
4181 outs() << sym_name;
4182 else
4183 outs() << format("0x%" PRIx64, n_value);
4184 if (op.name != 0)
4185 outs() << " + " << format("0x%" PRIx64, op.name);
4186 } else
4187 outs() << format("0x%" PRIx64, op.name);
4188 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4189 if (name != nullptr)
4190 outs() << format(" %.*s", left, name);
4191 outs() << "\n";
4192
4193 outs() << "\t\t\tattributes ";
4194 sym_name =
4195 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4196 info, n_value, op.attributes);
4197 if (n_value != 0) {
4198 if (info->verbose && sym_name != nullptr)
4199 outs() << sym_name;
4200 else
4201 outs() << format("0x%" PRIx64, n_value);
4202 if (op.attributes != 0)
4203 outs() << " + " << format("0x%" PRIx64, op.attributes);
4204 } else
4205 outs() << format("0x%" PRIx64, op.attributes);
4206 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4207 if (name != nullptr)
4208 outs() << format(" %.*s", left, name);
4209 outs() << "\n";
4210
4211 p += sizeof(struct objc_property64);
4212 offset += sizeof(struct objc_property64);
4213 }
4214}
4215
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004216static void print_objc_property_list32(uint32_t p,
4217 struct DisassembleInfo *info) {
4218 struct objc_property_list32 opl;
4219 struct objc_property32 op;
4220 const char *r;
4221 uint32_t offset, xoffset, left, j;
4222 SectionRef S, xS;
4223 const char *name;
4224
4225 r = get_pointer_32(p, offset, left, S, info);
4226 if (r == nullptr)
4227 return;
4228 memset(&opl, '\0', sizeof(struct objc_property_list32));
4229 if (left < sizeof(struct objc_property_list32)) {
4230 memcpy(&opl, r, left);
4231 outs() << " (objc_property_list entends past the end of the section)\n";
4232 } else
4233 memcpy(&opl, r, sizeof(struct objc_property_list32));
4234 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4235 swapStruct(opl);
4236 outs() << " entsize " << opl.entsize << "\n";
4237 outs() << " count " << opl.count << "\n";
4238
4239 p += sizeof(struct objc_property_list32);
4240 offset += sizeof(struct objc_property_list32);
4241 for (j = 0; j < opl.count; j++) {
4242 r = get_pointer_32(p, offset, left, S, info);
4243 if (r == nullptr)
4244 return;
4245 memset(&op, '\0', sizeof(struct objc_property32));
4246 if (left < sizeof(struct objc_property32)) {
4247 memcpy(&op, r, left);
4248 outs() << " (objc_property entends past the end of the section)\n";
4249 } else
4250 memcpy(&op, r, sizeof(struct objc_property32));
4251 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4252 swapStruct(op);
4253
4254 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4255 name = get_pointer_32(op.name, xoffset, left, xS, info);
4256 if (name != nullptr)
4257 outs() << format(" %.*s", left, name);
4258 outs() << "\n";
4259
4260 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4261 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4262 if (name != nullptr)
4263 outs() << format(" %.*s", left, name);
4264 outs() << "\n";
4265
4266 p += sizeof(struct objc_property32);
4267 offset += sizeof(struct objc_property32);
4268 }
4269}
4270
Kevin Enderby0fc11822015-04-01 20:57:01 +00004271static void print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
4272 bool &is_meta_class) {
4273 struct class_ro64_t cro;
4274 const char *r;
4275 uint32_t offset, xoffset, left;
4276 SectionRef S, xS;
4277 const char *name, *sym_name;
4278 uint64_t n_value;
4279
4280 r = get_pointer_64(p, offset, left, S, info);
4281 if (r == nullptr || left < sizeof(struct class_ro64_t))
4282 return;
4283 memset(&cro, '\0', sizeof(struct class_ro64_t));
4284 if (left < sizeof(struct class_ro64_t)) {
4285 memcpy(&cro, r, left);
4286 outs() << " (class_ro_t entends past the end of the section)\n";
4287 } else
4288 memcpy(&cro, r, sizeof(struct class_ro64_t));
4289 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4290 swapStruct(cro);
4291 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4292 if (cro.flags & RO_META)
4293 outs() << " RO_META";
4294 if (cro.flags & RO_ROOT)
4295 outs() << " RO_ROOT";
4296 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4297 outs() << " RO_HAS_CXX_STRUCTORS";
4298 outs() << "\n";
4299 outs() << " instanceStart " << cro.instanceStart << "\n";
4300 outs() << " instanceSize " << cro.instanceSize << "\n";
4301 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4302 << "\n";
4303 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4304 << "\n";
4305 print_layout_map64(cro.ivarLayout, info);
4306
4307 outs() << " name ";
4308 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4309 info, n_value, cro.name);
4310 if (n_value != 0) {
4311 if (info->verbose && sym_name != nullptr)
4312 outs() << sym_name;
4313 else
4314 outs() << format("0x%" PRIx64, n_value);
4315 if (cro.name != 0)
4316 outs() << " + " << format("0x%" PRIx64, cro.name);
4317 } else
4318 outs() << format("0x%" PRIx64, cro.name);
4319 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4320 if (name != nullptr)
4321 outs() << format(" %.*s", left, name);
4322 outs() << "\n";
4323
4324 outs() << " baseMethods ";
4325 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4326 S, info, n_value, cro.baseMethods);
4327 if (n_value != 0) {
4328 if (info->verbose && sym_name != nullptr)
4329 outs() << sym_name;
4330 else
4331 outs() << format("0x%" PRIx64, n_value);
4332 if (cro.baseMethods != 0)
4333 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4334 } else
4335 outs() << format("0x%" PRIx64, cro.baseMethods);
4336 outs() << " (struct method_list_t *)\n";
4337 if (cro.baseMethods + n_value != 0)
4338 print_method_list64_t(cro.baseMethods + n_value, info, "");
4339
4340 outs() << " baseProtocols ";
4341 sym_name =
4342 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4343 info, n_value, cro.baseProtocols);
4344 if (n_value != 0) {
4345 if (info->verbose && sym_name != nullptr)
4346 outs() << sym_name;
4347 else
4348 outs() << format("0x%" PRIx64, n_value);
4349 if (cro.baseProtocols != 0)
4350 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4351 } else
4352 outs() << format("0x%" PRIx64, cro.baseProtocols);
4353 outs() << "\n";
4354 if (cro.baseProtocols + n_value != 0)
4355 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4356
4357 outs() << " ivars ";
4358 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004359 info, n_value, cro.ivars);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004360 if (n_value != 0) {
4361 if (info->verbose && sym_name != nullptr)
4362 outs() << sym_name;
4363 else
4364 outs() << format("0x%" PRIx64, n_value);
4365 if (cro.ivars != 0)
4366 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4367 } else
4368 outs() << format("0x%" PRIx64, cro.ivars);
4369 outs() << "\n";
4370 if (cro.ivars + n_value != 0)
4371 print_ivar_list64_t(cro.ivars + n_value, info);
4372
4373 outs() << " weakIvarLayout ";
4374 sym_name =
4375 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4376 info, n_value, cro.weakIvarLayout);
4377 if (n_value != 0) {
4378 if (info->verbose && sym_name != nullptr)
4379 outs() << sym_name;
4380 else
4381 outs() << format("0x%" PRIx64, n_value);
4382 if (cro.weakIvarLayout != 0)
4383 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4384 } else
4385 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4386 outs() << "\n";
4387 print_layout_map64(cro.weakIvarLayout + n_value, info);
4388
4389 outs() << " baseProperties ";
4390 sym_name =
4391 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4392 info, n_value, cro.baseProperties);
4393 if (n_value != 0) {
4394 if (info->verbose && sym_name != nullptr)
4395 outs() << sym_name;
4396 else
4397 outs() << format("0x%" PRIx64, n_value);
4398 if (cro.baseProperties != 0)
4399 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4400 } else
4401 outs() << format("0x%" PRIx64, cro.baseProperties);
4402 outs() << "\n";
4403 if (cro.baseProperties + n_value != 0)
4404 print_objc_property_list64(cro.baseProperties + n_value, info);
4405
4406 is_meta_class = (cro.flags & RO_META) ? true : false;
4407}
4408
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004409static void print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
4410 bool &is_meta_class) {
4411 struct class_ro32_t cro;
4412 const char *r;
4413 uint32_t offset, xoffset, left;
4414 SectionRef S, xS;
4415 const char *name;
4416
4417 r = get_pointer_32(p, offset, left, S, info);
4418 if (r == nullptr)
4419 return;
4420 memset(&cro, '\0', sizeof(struct class_ro32_t));
4421 if (left < sizeof(struct class_ro32_t)) {
4422 memcpy(&cro, r, left);
4423 outs() << " (class_ro_t entends past the end of the section)\n";
4424 } else
4425 memcpy(&cro, r, sizeof(struct class_ro32_t));
4426 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4427 swapStruct(cro);
4428 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4429 if (cro.flags & RO_META)
4430 outs() << " RO_META";
4431 if (cro.flags & RO_ROOT)
4432 outs() << " RO_ROOT";
4433 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4434 outs() << " RO_HAS_CXX_STRUCTORS";
4435 outs() << "\n";
4436 outs() << " instanceStart " << cro.instanceStart << "\n";
4437 outs() << " instanceSize " << cro.instanceSize << "\n";
4438 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4439 << "\n";
4440 print_layout_map32(cro.ivarLayout, info);
4441
4442 outs() << " name " << format("0x%" PRIx32, cro.name);
4443 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4444 if (name != nullptr)
4445 outs() << format(" %.*s", left, name);
4446 outs() << "\n";
4447
4448 outs() << " baseMethods "
4449 << format("0x%" PRIx32, cro.baseMethods)
4450 << " (struct method_list_t *)\n";
4451 if (cro.baseMethods != 0)
4452 print_method_list32_t(cro.baseMethods, info, "");
4453
4454 outs() << " baseProtocols "
4455 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4456 if (cro.baseProtocols != 0)
4457 print_protocol_list32_t(cro.baseProtocols, info);
4458 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4459 << "\n";
4460 if (cro.ivars != 0)
4461 print_ivar_list32_t(cro.ivars, info);
4462 outs() << " weakIvarLayout "
4463 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4464 print_layout_map32(cro.weakIvarLayout, info);
4465 outs() << " baseProperties "
4466 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4467 if (cro.baseProperties != 0)
4468 print_objc_property_list32(cro.baseProperties, info);
4469 is_meta_class = (cro.flags & RO_META) ? true : false;
4470}
4471
Kevin Enderby0fc11822015-04-01 20:57:01 +00004472static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4473 struct class64_t c;
4474 const char *r;
4475 uint32_t offset, left;
4476 SectionRef S;
4477 const char *name;
4478 uint64_t isa_n_value, n_value;
4479
4480 r = get_pointer_64(p, offset, left, S, info);
4481 if (r == nullptr || left < sizeof(struct class64_t))
4482 return;
4483 memset(&c, '\0', sizeof(struct class64_t));
4484 if (left < sizeof(struct class64_t)) {
4485 memcpy(&c, r, left);
4486 outs() << " (class_t entends past the end of the section)\n";
4487 } else
4488 memcpy(&c, r, sizeof(struct class64_t));
4489 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4490 swapStruct(c);
4491
4492 outs() << " isa " << format("0x%" PRIx64, c.isa);
4493 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
4494 isa_n_value, c.isa);
4495 if (name != nullptr)
4496 outs() << " " << name;
4497 outs() << "\n";
4498
4499 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
4500 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
4501 n_value, c.superclass);
4502 if (name != nullptr)
4503 outs() << " " << name;
4504 outs() << "\n";
4505
4506 outs() << " cache " << format("0x%" PRIx64, c.cache);
4507 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
4508 n_value, c.cache);
4509 if (name != nullptr)
4510 outs() << " " << name;
4511 outs() << "\n";
4512
4513 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
4514 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
4515 n_value, c.vtable);
4516 if (name != nullptr)
4517 outs() << " " << name;
4518 outs() << "\n";
4519
4520 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
4521 n_value, c.data);
4522 outs() << " data ";
4523 if (n_value != 0) {
4524 if (info->verbose && name != nullptr)
4525 outs() << name;
4526 else
4527 outs() << format("0x%" PRIx64, n_value);
4528 if (c.data != 0)
4529 outs() << " + " << format("0x%" PRIx64, c.data);
4530 } else
4531 outs() << format("0x%" PRIx64, c.data);
4532 outs() << " (struct class_ro_t *)";
4533
4534 // This is a Swift class if some of the low bits of the pointer are set.
4535 if ((c.data + n_value) & 0x7)
4536 outs() << " Swift class";
4537 outs() << "\n";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004538 bool is_meta_class;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004539 print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class);
4540
4541 if (is_meta_class == false) {
4542 outs() << "Meta Class\n";
4543 print_class64_t(c.isa + isa_n_value, info);
4544 }
4545}
4546
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004547static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
4548 struct class32_t c;
4549 const char *r;
4550 uint32_t offset, left;
4551 SectionRef S;
4552 const char *name;
4553
4554 r = get_pointer_32(p, offset, left, S, info);
4555 if (r == nullptr)
4556 return;
4557 memset(&c, '\0', sizeof(struct class32_t));
4558 if (left < sizeof(struct class32_t)) {
4559 memcpy(&c, r, left);
4560 outs() << " (class_t entends past the end of the section)\n";
4561 } else
4562 memcpy(&c, r, sizeof(struct class32_t));
4563 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4564 swapStruct(c);
4565
4566 outs() << " isa " << format("0x%" PRIx32, c.isa);
4567 name =
4568 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
4569 if (name != nullptr)
4570 outs() << " " << name;
4571 outs() << "\n";
4572
4573 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
4574 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
4575 c.superclass);
4576 if (name != nullptr)
4577 outs() << " " << name;
4578 outs() << "\n";
4579
4580 outs() << " cache " << format("0x%" PRIx32, c.cache);
4581 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
4582 c.cache);
4583 if (name != nullptr)
4584 outs() << " " << name;
4585 outs() << "\n";
4586
4587 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
4588 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
4589 c.vtable);
4590 if (name != nullptr)
4591 outs() << " " << name;
4592 outs() << "\n";
4593
4594 name =
4595 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
4596 outs() << " data " << format("0x%" PRIx32, c.data)
4597 << " (struct class_ro_t *)";
4598
4599 // This is a Swift class if some of the low bits of the pointer are set.
4600 if (c.data & 0x3)
4601 outs() << " Swift class";
4602 outs() << "\n";
4603 bool is_meta_class;
4604 print_class_ro32_t(c.data & ~0x3, info, is_meta_class);
4605
4606 if (is_meta_class == false) {
4607 outs() << "Meta Class\n";
4608 print_class32_t(c.isa, info);
4609 }
4610}
4611
Kevin Enderby846c0002015-04-16 17:19:59 +00004612static void print_objc_class_t(struct objc_class_t *objc_class,
4613 struct DisassembleInfo *info) {
4614 uint32_t offset, left, xleft;
4615 const char *name, *p, *ivar_list;
4616 SectionRef S;
4617 int32_t i;
4618 struct objc_ivar_list_t objc_ivar_list;
4619 struct objc_ivar_t ivar;
4620
4621 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
4622 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
4623 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
4624 if (name != nullptr)
4625 outs() << format(" %.*s", left, name);
4626 else
4627 outs() << " (not in an __OBJC section)";
4628 }
4629 outs() << "\n";
4630
4631 outs() << "\t super_class "
4632 << format("0x%08" PRIx32, objc_class->super_class);
4633 if (info->verbose) {
4634 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
4635 if (name != nullptr)
4636 outs() << format(" %.*s", left, name);
4637 else
4638 outs() << " (not in an __OBJC section)";
4639 }
4640 outs() << "\n";
4641
4642 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
4643 if (info->verbose) {
4644 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
4645 if (name != nullptr)
4646 outs() << format(" %.*s", left, name);
4647 else
4648 outs() << " (not in an __OBJC section)";
4649 }
4650 outs() << "\n";
4651
4652 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
4653 << "\n";
4654
4655 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
4656 if (info->verbose) {
4657 if (CLS_GETINFO(objc_class, CLS_CLASS))
4658 outs() << " CLS_CLASS";
4659 else if (CLS_GETINFO(objc_class, CLS_META))
4660 outs() << " CLS_META";
4661 }
4662 outs() << "\n";
4663
4664 outs() << "\t instance_size "
4665 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
4666
4667 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
4668 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
4669 if (p != nullptr) {
4670 if (left > sizeof(struct objc_ivar_list_t)) {
4671 outs() << "\n";
4672 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
4673 } else {
4674 outs() << " (entends past the end of the section)\n";
4675 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
4676 memcpy(&objc_ivar_list, p, left);
4677 }
4678 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4679 swapStruct(objc_ivar_list);
4680 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
4681 ivar_list = p + sizeof(struct objc_ivar_list_t);
4682 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
4683 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
4684 outs() << "\t\t remaining ivar's extend past the of the section\n";
4685 break;
4686 }
4687 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
4688 sizeof(struct objc_ivar_t));
4689 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4690 swapStruct(ivar);
4691
4692 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
4693 if (info->verbose) {
4694 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
4695 if (name != nullptr)
4696 outs() << format(" %.*s", xleft, name);
4697 else
4698 outs() << " (not in an __OBJC section)";
4699 }
4700 outs() << "\n";
4701
4702 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
4703 if (info->verbose) {
4704 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
4705 if (name != nullptr)
4706 outs() << format(" %.*s", xleft, name);
4707 else
4708 outs() << " (not in an __OBJC section)";
4709 }
4710 outs() << "\n";
4711
4712 outs() << "\t\t ivar_offset "
4713 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
4714 }
4715 } else {
4716 outs() << " (not in an __OBJC section)\n";
4717 }
4718
4719 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
4720 if (print_method_list(objc_class->methodLists, info))
4721 outs() << " (not in an __OBJC section)\n";
4722
4723 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
4724 << "\n";
4725
4726 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
4727 if (print_protocol_list(objc_class->protocols, 16, info))
4728 outs() << " (not in an __OBJC section)\n";
4729}
4730
4731static void print_objc_objc_category_t(struct objc_category_t *objc_category,
4732 struct DisassembleInfo *info) {
4733 uint32_t offset, left;
4734 const char *name;
4735 SectionRef S;
4736
4737 outs() << "\t category name "
4738 << format("0x%08" PRIx32, objc_category->category_name);
4739 if (info->verbose) {
4740 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
4741 true);
4742 if (name != nullptr)
4743 outs() << format(" %.*s", left, name);
4744 else
4745 outs() << " (not in an __OBJC section)";
4746 }
4747 outs() << "\n";
4748
4749 outs() << "\t\t class name "
4750 << format("0x%08" PRIx32, objc_category->class_name);
4751 if (info->verbose) {
4752 name =
4753 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
4754 if (name != nullptr)
4755 outs() << format(" %.*s", left, name);
4756 else
4757 outs() << " (not in an __OBJC section)";
4758 }
4759 outs() << "\n";
4760
4761 outs() << "\t instance methods "
4762 << format("0x%08" PRIx32, objc_category->instance_methods);
4763 if (print_method_list(objc_category->instance_methods, info))
4764 outs() << " (not in an __OBJC section)\n";
4765
4766 outs() << "\t class methods "
4767 << format("0x%08" PRIx32, objc_category->class_methods);
4768 if (print_method_list(objc_category->class_methods, info))
4769 outs() << " (not in an __OBJC section)\n";
4770}
4771
Kevin Enderby0fc11822015-04-01 20:57:01 +00004772static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
4773 struct category64_t c;
4774 const char *r;
4775 uint32_t offset, xoffset, left;
4776 SectionRef S, xS;
4777 const char *name, *sym_name;
4778 uint64_t n_value;
4779
4780 r = get_pointer_64(p, offset, left, S, info);
4781 if (r == nullptr)
4782 return;
4783 memset(&c, '\0', sizeof(struct category64_t));
4784 if (left < sizeof(struct category64_t)) {
4785 memcpy(&c, r, left);
4786 outs() << " (category_t entends past the end of the section)\n";
4787 } else
4788 memcpy(&c, r, sizeof(struct category64_t));
4789 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4790 swapStruct(c);
4791
4792 outs() << " name ";
4793 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
4794 info, n_value, c.name);
4795 if (n_value != 0) {
4796 if (info->verbose && sym_name != nullptr)
4797 outs() << sym_name;
4798 else
4799 outs() << format("0x%" PRIx64, n_value);
4800 if (c.name != 0)
4801 outs() << " + " << format("0x%" PRIx64, c.name);
4802 } else
4803 outs() << format("0x%" PRIx64, c.name);
4804 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
4805 if (name != nullptr)
4806 outs() << format(" %.*s", left, name);
4807 outs() << "\n";
4808
4809 outs() << " cls ";
4810 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
4811 n_value, c.cls);
4812 if (n_value != 0) {
4813 if (info->verbose && sym_name != nullptr)
4814 outs() << sym_name;
4815 else
4816 outs() << format("0x%" PRIx64, n_value);
4817 if (c.cls != 0)
4818 outs() << " + " << format("0x%" PRIx64, c.cls);
4819 } else
4820 outs() << format("0x%" PRIx64, c.cls);
4821 outs() << "\n";
4822 if (c.cls + n_value != 0)
4823 print_class64_t(c.cls + n_value, info);
4824
4825 outs() << " instanceMethods ";
4826 sym_name =
4827 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
4828 info, n_value, c.instanceMethods);
4829 if (n_value != 0) {
4830 if (info->verbose && sym_name != nullptr)
4831 outs() << sym_name;
4832 else
4833 outs() << format("0x%" PRIx64, n_value);
4834 if (c.instanceMethods != 0)
4835 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
4836 } else
4837 outs() << format("0x%" PRIx64, c.instanceMethods);
4838 outs() << "\n";
4839 if (c.instanceMethods + n_value != 0)
4840 print_method_list64_t(c.instanceMethods + n_value, info, "");
4841
4842 outs() << " classMethods ";
4843 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
4844 S, info, n_value, c.classMethods);
4845 if (n_value != 0) {
4846 if (info->verbose && sym_name != nullptr)
4847 outs() << sym_name;
4848 else
4849 outs() << format("0x%" PRIx64, n_value);
4850 if (c.classMethods != 0)
4851 outs() << " + " << format("0x%" PRIx64, c.classMethods);
4852 } else
4853 outs() << format("0x%" PRIx64, c.classMethods);
4854 outs() << "\n";
4855 if (c.classMethods + n_value != 0)
4856 print_method_list64_t(c.classMethods + n_value, info, "");
4857
4858 outs() << " protocols ";
4859 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
4860 info, n_value, c.protocols);
4861 if (n_value != 0) {
4862 if (info->verbose && sym_name != nullptr)
4863 outs() << sym_name;
4864 else
4865 outs() << format("0x%" PRIx64, n_value);
4866 if (c.protocols != 0)
4867 outs() << " + " << format("0x%" PRIx64, c.protocols);
4868 } else
4869 outs() << format("0x%" PRIx64, c.protocols);
4870 outs() << "\n";
4871 if (c.protocols + n_value != 0)
4872 print_protocol_list64_t(c.protocols + n_value, info);
4873
4874 outs() << "instanceProperties ";
4875 sym_name =
4876 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
4877 S, info, n_value, c.instanceProperties);
4878 if (n_value != 0) {
4879 if (info->verbose && sym_name != nullptr)
4880 outs() << sym_name;
4881 else
4882 outs() << format("0x%" PRIx64, n_value);
4883 if (c.instanceProperties != 0)
4884 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
4885 } else
4886 outs() << format("0x%" PRIx64, c.instanceProperties);
4887 outs() << "\n";
4888 if (c.instanceProperties + n_value != 0)
4889 print_objc_property_list64(c.instanceProperties + n_value, info);
4890}
4891
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004892static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
4893 struct category32_t c;
4894 const char *r;
4895 uint32_t offset, left;
4896 SectionRef S, xS;
4897 const char *name;
4898
4899 r = get_pointer_32(p, offset, left, S, info);
4900 if (r == nullptr)
4901 return;
4902 memset(&c, '\0', sizeof(struct category32_t));
4903 if (left < sizeof(struct category32_t)) {
4904 memcpy(&c, r, left);
4905 outs() << " (category_t entends past the end of the section)\n";
4906 } else
4907 memcpy(&c, r, sizeof(struct category32_t));
4908 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4909 swapStruct(c);
4910
4911 outs() << " name " << format("0x%" PRIx32, c.name);
4912 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
4913 c.name);
4914 if (name != NULL)
4915 outs() << " " << name;
4916 outs() << "\n";
4917
4918 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
4919 if (c.cls != 0)
4920 print_class32_t(c.cls, info);
4921 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
4922 << "\n";
4923 if (c.instanceMethods != 0)
4924 print_method_list32_t(c.instanceMethods, info, "");
4925 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
4926 << "\n";
4927 if (c.classMethods != 0)
4928 print_method_list32_t(c.classMethods, info, "");
4929 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
4930 if (c.protocols != 0)
4931 print_protocol_list32_t(c.protocols, info);
4932 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
4933 << "\n";
4934 if (c.instanceProperties != 0)
4935 print_objc_property_list32(c.instanceProperties, info);
4936}
4937
Kevin Enderby0fc11822015-04-01 20:57:01 +00004938static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
4939 uint32_t i, left, offset, xoffset;
4940 uint64_t p, n_value;
4941 struct message_ref64 mr;
4942 const char *name, *sym_name;
4943 const char *r;
4944 SectionRef xS;
4945
4946 if (S == SectionRef())
4947 return;
4948
4949 StringRef SectName;
4950 S.getName(SectName);
4951 DataRefImpl Ref = S.getRawDataRefImpl();
4952 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
4953 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4954 offset = 0;
4955 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
4956 p = S.getAddress() + i;
4957 r = get_pointer_64(p, offset, left, S, info);
4958 if (r == nullptr)
4959 return;
4960 memset(&mr, '\0', sizeof(struct message_ref64));
4961 if (left < sizeof(struct message_ref64)) {
4962 memcpy(&mr, r, left);
4963 outs() << " (message_ref entends past the end of the section)\n";
4964 } else
4965 memcpy(&mr, r, sizeof(struct message_ref64));
4966 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4967 swapStruct(mr);
4968
4969 outs() << " imp ";
4970 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
4971 n_value, mr.imp);
4972 if (n_value != 0) {
4973 outs() << format("0x%" PRIx64, n_value) << " ";
4974 if (mr.imp != 0)
4975 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
4976 } else
4977 outs() << format("0x%" PRIx64, mr.imp) << " ";
4978 if (name != nullptr)
4979 outs() << " " << name;
4980 outs() << "\n";
4981
4982 outs() << " sel ";
4983 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
4984 info, n_value, mr.sel);
4985 if (n_value != 0) {
4986 if (info->verbose && sym_name != nullptr)
4987 outs() << sym_name;
4988 else
4989 outs() << format("0x%" PRIx64, n_value);
4990 if (mr.sel != 0)
4991 outs() << " + " << format("0x%" PRIx64, mr.sel);
4992 } else
4993 outs() << format("0x%" PRIx64, mr.sel);
4994 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
4995 if (name != nullptr)
4996 outs() << format(" %.*s", left, name);
4997 outs() << "\n";
4998
4999 offset += sizeof(struct message_ref64);
5000 }
5001}
5002
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005003static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5004 uint32_t i, left, offset, xoffset, p;
5005 struct message_ref32 mr;
5006 const char *name, *r;
5007 SectionRef xS;
5008
5009 if (S == SectionRef())
5010 return;
5011
5012 StringRef SectName;
5013 S.getName(SectName);
5014 DataRefImpl Ref = S.getRawDataRefImpl();
5015 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5016 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5017 offset = 0;
5018 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5019 p = S.getAddress() + i;
5020 r = get_pointer_32(p, offset, left, S, info);
5021 if (r == nullptr)
5022 return;
5023 memset(&mr, '\0', sizeof(struct message_ref32));
5024 if (left < sizeof(struct message_ref32)) {
5025 memcpy(&mr, r, left);
5026 outs() << " (message_ref entends past the end of the section)\n";
5027 } else
5028 memcpy(&mr, r, sizeof(struct message_ref32));
5029 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5030 swapStruct(mr);
5031
5032 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5033 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5034 mr.imp);
5035 if (name != nullptr)
5036 outs() << " " << name;
5037 outs() << "\n";
5038
5039 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5040 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5041 if (name != nullptr)
5042 outs() << " " << name;
5043 outs() << "\n";
5044
5045 offset += sizeof(struct message_ref32);
5046 }
5047}
5048
Kevin Enderby0fc11822015-04-01 20:57:01 +00005049static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5050 uint32_t left, offset, swift_version;
5051 uint64_t p;
5052 struct objc_image_info64 o;
5053 const char *r;
5054
5055 StringRef SectName;
5056 S.getName(SectName);
5057 DataRefImpl Ref = S.getRawDataRefImpl();
5058 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5059 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5060 p = S.getAddress();
5061 r = get_pointer_64(p, offset, left, S, info);
5062 if (r == nullptr)
5063 return;
5064 memset(&o, '\0', sizeof(struct objc_image_info64));
5065 if (left < sizeof(struct objc_image_info64)) {
5066 memcpy(&o, r, left);
5067 outs() << " (objc_image_info entends past the end of the section)\n";
5068 } else
5069 memcpy(&o, r, sizeof(struct objc_image_info64));
5070 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5071 swapStruct(o);
5072 outs() << " version " << o.version << "\n";
5073 outs() << " flags " << format("0x%" PRIx32, o.flags);
5074 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5075 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5076 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5077 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5078 swift_version = (o.flags >> 8) & 0xff;
5079 if (swift_version != 0) {
5080 if (swift_version == 1)
5081 outs() << " Swift 1.0";
5082 else if (swift_version == 2)
5083 outs() << " Swift 1.1";
5084 else
5085 outs() << " unknown future Swift version (" << swift_version << ")";
5086 }
5087 outs() << "\n";
5088}
5089
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005090static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5091 uint32_t left, offset, swift_version, p;
5092 struct objc_image_info32 o;
5093 const char *r;
5094
5095 StringRef SectName;
5096 S.getName(SectName);
5097 DataRefImpl Ref = S.getRawDataRefImpl();
5098 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5099 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5100 p = S.getAddress();
5101 r = get_pointer_32(p, offset, left, S, info);
5102 if (r == nullptr)
5103 return;
5104 memset(&o, '\0', sizeof(struct objc_image_info32));
5105 if (left < sizeof(struct objc_image_info32)) {
5106 memcpy(&o, r, left);
5107 outs() << " (objc_image_info entends past the end of the section)\n";
5108 } else
5109 memcpy(&o, r, sizeof(struct objc_image_info32));
5110 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5111 swapStruct(o);
5112 outs() << " version " << o.version << "\n";
5113 outs() << " flags " << format("0x%" PRIx32, o.flags);
5114 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5115 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5116 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5117 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5118 swift_version = (o.flags >> 8) & 0xff;
5119 if (swift_version != 0) {
5120 if (swift_version == 1)
5121 outs() << " Swift 1.0";
5122 else if (swift_version == 2)
5123 outs() << " Swift 1.1";
5124 else
5125 outs() << " unknown future Swift version (" << swift_version << ")";
5126 }
5127 outs() << "\n";
5128}
5129
Kevin Enderby846c0002015-04-16 17:19:59 +00005130static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5131 uint32_t left, offset, p;
5132 struct imageInfo_t o;
5133 const char *r;
5134
5135 StringRef SectName;
5136 S.getName(SectName);
5137 DataRefImpl Ref = S.getRawDataRefImpl();
5138 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5139 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5140 p = S.getAddress();
5141 r = get_pointer_32(p, offset, left, S, info);
5142 if (r == nullptr)
5143 return;
5144 memset(&o, '\0', sizeof(struct imageInfo_t));
5145 if (left < sizeof(struct imageInfo_t)) {
5146 memcpy(&o, r, left);
5147 outs() << " (imageInfo entends past the end of the section)\n";
5148 } else
5149 memcpy(&o, r, sizeof(struct imageInfo_t));
5150 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5151 swapStruct(o);
5152 outs() << " version " << o.version << "\n";
5153 outs() << " flags " << format("0x%" PRIx32, o.flags);
5154 if (o.flags & 0x1)
5155 outs() << " F&C";
5156 if (o.flags & 0x2)
5157 outs() << " GC";
5158 if (o.flags & 0x4)
5159 outs() << " GC-only";
5160 else
5161 outs() << " RR";
5162 outs() << "\n";
5163}
5164
Kevin Enderby0fc11822015-04-01 20:57:01 +00005165static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5166 SymbolAddressMap AddrMap;
5167 if (verbose)
5168 CreateSymbolAddressMap(O, &AddrMap);
5169
5170 std::vector<SectionRef> Sections;
5171 for (const SectionRef &Section : O->sections()) {
5172 StringRef SectName;
5173 Section.getName(SectName);
5174 Sections.push_back(Section);
5175 }
5176
5177 struct DisassembleInfo info;
5178 // Set up the block of info used by the Symbolizer call backs.
5179 info.verbose = verbose;
5180 info.O = O;
5181 info.AddrMap = &AddrMap;
5182 info.Sections = &Sections;
5183 info.class_name = nullptr;
5184 info.selector_name = nullptr;
5185 info.method = nullptr;
5186 info.demangled_name = nullptr;
5187 info.bindtable = nullptr;
5188 info.adrp_addr = 0;
5189 info.adrp_inst = 0;
5190
5191 const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5192 if (CL != SectionRef()) {
5193 info.S = CL;
5194 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
5195 } else {
5196 const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
5197 info.S = CL;
5198 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
5199 }
5200
5201 const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5202 if (CR != SectionRef()) {
5203 info.S = CR;
5204 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
5205 } else {
5206 const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
5207 info.S = CR;
5208 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
5209 }
5210
5211 const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5212 if (SR != SectionRef()) {
5213 info.S = SR;
5214 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
5215 } else {
5216 const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
5217 info.S = SR;
5218 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
5219 }
5220
5221 const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5222 if (CA != SectionRef()) {
5223 info.S = CA;
5224 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
5225 } else {
5226 const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
5227 info.S = CA;
5228 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
5229 }
5230
5231 const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5232 if (PL != SectionRef()) {
5233 info.S = PL;
5234 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
5235 } else {
5236 const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
5237 info.S = PL;
5238 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
5239 }
5240
5241 const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5242 if (MR != SectionRef()) {
5243 info.S = MR;
5244 print_message_refs64(MR, &info);
5245 } else {
5246 const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
5247 info.S = MR;
5248 print_message_refs64(MR, &info);
5249 }
5250
5251 const SectionRef II = get_section(O, "__OBJC2", "__image_info");
5252 if (II != SectionRef()) {
5253 info.S = II;
5254 print_image_info64(II, &info);
5255 } else {
5256 const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
5257 info.S = II;
5258 print_image_info64(II, &info);
5259 }
Kevin Enderby0bc6ed42015-04-01 21:50:45 +00005260
5261 if (info.bindtable != nullptr)
5262 delete info.bindtable;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005263}
5264
5265static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005266 SymbolAddressMap AddrMap;
5267 if (verbose)
5268 CreateSymbolAddressMap(O, &AddrMap);
5269
5270 std::vector<SectionRef> Sections;
5271 for (const SectionRef &Section : O->sections()) {
5272 StringRef SectName;
5273 Section.getName(SectName);
5274 Sections.push_back(Section);
5275 }
5276
5277 struct DisassembleInfo info;
5278 // Set up the block of info used by the Symbolizer call backs.
5279 info.verbose = verbose;
5280 info.O = O;
5281 info.AddrMap = &AddrMap;
5282 info.Sections = &Sections;
5283 info.class_name = nullptr;
5284 info.selector_name = nullptr;
5285 info.method = nullptr;
5286 info.demangled_name = nullptr;
5287 info.bindtable = nullptr;
5288 info.adrp_addr = 0;
5289 info.adrp_inst = 0;
5290
5291 const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5292 if (CL != SectionRef()) {
5293 info.S = CL;
5294 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5295 } else {
5296 const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
5297 info.S = CL;
5298 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5299 }
5300
5301 const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5302 if (CR != SectionRef()) {
5303 info.S = CR;
5304 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5305 } else {
5306 const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
5307 info.S = CR;
5308 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5309 }
5310
5311 const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5312 if (SR != SectionRef()) {
5313 info.S = SR;
5314 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5315 } else {
5316 const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
5317 info.S = SR;
5318 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5319 }
5320
5321 const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5322 if (CA != SectionRef()) {
5323 info.S = CA;
5324 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5325 } else {
5326 const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
5327 info.S = CA;
5328 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5329 }
5330
5331 const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5332 if (PL != SectionRef()) {
5333 info.S = PL;
5334 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5335 } else {
5336 const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
5337 info.S = PL;
5338 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5339 }
5340
5341 const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5342 if (MR != SectionRef()) {
5343 info.S = MR;
5344 print_message_refs32(MR, &info);
5345 } else {
5346 const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
5347 info.S = MR;
5348 print_message_refs32(MR, &info);
5349 }
5350
5351 const SectionRef II = get_section(O, "__OBJC2", "__image_info");
5352 if (II != SectionRef()) {
5353 info.S = II;
5354 print_image_info32(II, &info);
5355 } else {
5356 const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
5357 info.S = II;
5358 print_image_info32(II, &info);
5359 }
Kevin Enderby0fc11822015-04-01 20:57:01 +00005360}
5361
5362static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby846c0002015-04-16 17:19:59 +00005363 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5364 const char *r, *name, *defs;
5365 struct objc_module_t module;
5366 SectionRef S, xS;
5367 struct objc_symtab_t symtab;
5368 struct objc_class_t objc_class;
5369 struct objc_category_t objc_category;
5370
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005371 outs() << "Objective-C segment\n";
Kevin Enderby846c0002015-04-16 17:19:59 +00005372 S = get_section(O, "__OBJC", "__module_info");
5373 if (S == SectionRef())
5374 return false;
5375
5376 SymbolAddressMap AddrMap;
5377 if (verbose)
5378 CreateSymbolAddressMap(O, &AddrMap);
5379
5380 std::vector<SectionRef> Sections;
5381 for (const SectionRef &Section : O->sections()) {
5382 StringRef SectName;
5383 Section.getName(SectName);
5384 Sections.push_back(Section);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005385 }
Kevin Enderby846c0002015-04-16 17:19:59 +00005386
5387 struct DisassembleInfo info;
5388 // Set up the block of info used by the Symbolizer call backs.
5389 info.verbose = verbose;
5390 info.O = O;
5391 info.AddrMap = &AddrMap;
5392 info.Sections = &Sections;
5393 info.class_name = nullptr;
5394 info.selector_name = nullptr;
5395 info.method = nullptr;
5396 info.demangled_name = nullptr;
5397 info.bindtable = nullptr;
5398 info.adrp_addr = 0;
5399 info.adrp_inst = 0;
5400
5401 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5402 p = S.getAddress() + i;
5403 r = get_pointer_32(p, offset, left, S, &info, true);
5404 if (r == nullptr)
5405 return true;
5406 memset(&module, '\0', sizeof(struct objc_module_t));
5407 if (left < sizeof(struct objc_module_t)) {
5408 memcpy(&module, r, left);
5409 outs() << " (module extends past end of __module_info section)\n";
5410 } else
5411 memcpy(&module, r, sizeof(struct objc_module_t));
5412 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5413 swapStruct(module);
5414
5415 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5416 outs() << " version " << module.version << "\n";
5417 outs() << " size " << module.size << "\n";
5418 outs() << " name ";
5419 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5420 if (name != nullptr)
5421 outs() << format("%.*s", left, name);
5422 else
5423 outs() << format("0x%08" PRIx32, module.name)
5424 << "(not in an __OBJC section)";
5425 outs() << "\n";
5426
5427 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5428 if (module.symtab == 0 || r == nullptr) {
5429 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5430 << " (not in an __OBJC section)\n";
5431 continue;
5432 }
5433 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5434 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5435 defs_left = 0;
5436 defs = nullptr;
5437 if (left < sizeof(struct objc_symtab_t)) {
5438 memcpy(&symtab, r, left);
5439 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5440 } else {
5441 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5442 if (left > sizeof(struct objc_symtab_t)) {
5443 defs_left = left - sizeof(struct objc_symtab_t);
5444 defs = r + sizeof(struct objc_symtab_t);
5445 }
5446 }
5447 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5448 swapStruct(symtab);
5449
5450 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5451 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5452 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5453 if (r == nullptr)
5454 outs() << " (not in an __OBJC section)";
5455 outs() << "\n";
5456 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5457 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5458 if (symtab.cls_def_cnt > 0)
5459 outs() << "\tClass Definitions\n";
5460 for (j = 0; j < symtab.cls_def_cnt; j++) {
5461 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5462 outs() << "\t(remaining class defs entries entends past the end of the "
5463 << "section)\n";
5464 break;
5465 }
5466 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5467 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5468 sys::swapByteOrder(def);
5469
5470 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5471 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5472 if (r != nullptr) {
5473 if (left > sizeof(struct objc_class_t)) {
5474 outs() << "\n";
5475 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5476 } else {
5477 outs() << " (entends past the end of the section)\n";
5478 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5479 memcpy(&objc_class, r, left);
5480 }
5481 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5482 swapStruct(objc_class);
5483 print_objc_class_t(&objc_class, &info);
5484 } else {
5485 outs() << "(not in an __OBJC section)\n";
5486 }
5487
5488 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
5489 outs() << "\tMeta Class";
5490 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
5491 if (r != nullptr) {
5492 if (left > sizeof(struct objc_class_t)) {
5493 outs() << "\n";
5494 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5495 } else {
5496 outs() << " (entends past the end of the section)\n";
5497 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5498 memcpy(&objc_class, r, left);
5499 }
5500 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5501 swapStruct(objc_class);
5502 print_objc_class_t(&objc_class, &info);
5503 } else {
5504 outs() << "(not in an __OBJC section)\n";
5505 }
5506 }
5507 }
5508 if (symtab.cat_def_cnt > 0)
5509 outs() << "\tCategory Definitions\n";
5510 for (j = 0; j < symtab.cat_def_cnt; j++) {
5511 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
5512 outs() << "\t(remaining category defs entries entends past the end of "
5513 << "the section)\n";
5514 break;
5515 }
5516 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
5517 sizeof(uint32_t));
5518 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5519 sys::swapByteOrder(def);
5520
5521 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5522 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
5523 << format("0x%08" PRIx32, def);
5524 if (r != nullptr) {
5525 if (left > sizeof(struct objc_category_t)) {
5526 outs() << "\n";
5527 memcpy(&objc_category, r, sizeof(struct objc_category_t));
5528 } else {
5529 outs() << " (entends past the end of the section)\n";
5530 memset(&objc_category, '\0', sizeof(struct objc_category_t));
5531 memcpy(&objc_category, r, left);
5532 }
5533 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5534 swapStruct(objc_category);
5535 print_objc_objc_category_t(&objc_category, &info);
5536 } else {
5537 outs() << "(not in an __OBJC section)\n";
5538 }
5539 }
5540 }
5541 const SectionRef II = get_section(O, "__OBJC", "__image_info");
5542 if (II != SectionRef())
5543 print_image_info(II, &info);
5544
5545 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005546}
5547
5548static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
5549 if (O->is64Bit())
5550 printObjc2_64bit_MetaData(O, verbose);
5551 else {
5552 MachO::mach_header H;
5553 H = O->getHeader();
5554 if (H.cputype == MachO::CPU_TYPE_ARM)
5555 printObjc2_32bit_MetaData(O, verbose);
5556 else {
5557 // This is the 32-bit non-arm cputype case. Which is normally
5558 // the first Objective-C ABI. But it may be the case of a
5559 // binary for the iOS simulator which is the second Objective-C
5560 // ABI. In that case printObjc1_32bit_MetaData() will determine that
5561 // and return false.
5562 if (printObjc1_32bit_MetaData(O, verbose) == false)
5563 printObjc2_32bit_MetaData(O, verbose);
5564 }
5565 }
5566}
5567
Kevin Enderbybf246f52014-09-24 23:08:22 +00005568// GuessLiteralPointer returns a string which for the item in the Mach-O file
5569// for the address passed in as ReferenceValue for printing as a comment with
5570// the instruction and also returns the corresponding type of that item
5571// indirectly through ReferenceType.
5572//
5573// If ReferenceValue is an address of literal cstring then a pointer to the
5574// cstring is returned and ReferenceType is set to
5575// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
5576//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005577// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
5578// Class ref that name is returned and the ReferenceType is set accordingly.
5579//
5580// Lastly, literals which are Symbol address in a literal pool are looked for
5581// and if found the symbol name is returned and ReferenceType is set to
5582// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
5583//
5584// If there is no item in the Mach-O file for the address passed in as
5585// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00005586static const char *GuessLiteralPointer(uint64_t ReferenceValue,
5587 uint64_t ReferencePC,
5588 uint64_t *ReferenceType,
5589 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00005590 // First see if there is an external relocation entry at the ReferencePC.
Rafael Espindola80291272014-10-08 15:28:58 +00005591 uint64_t sect_addr = info->S.getAddress();
Kevin Enderbybf246f52014-09-24 23:08:22 +00005592 uint64_t sect_offset = ReferencePC - sect_addr;
5593 bool reloc_found = false;
5594 DataRefImpl Rel;
5595 MachO::any_relocation_info RE;
5596 bool isExtern = false;
5597 SymbolRef Symbol;
5598 for (const RelocationRef &Reloc : info->S.relocations()) {
5599 uint64_t RelocOffset;
5600 Reloc.getOffset(RelocOffset);
5601 if (RelocOffset == sect_offset) {
5602 Rel = Reloc.getRawDataRefImpl();
5603 RE = info->O->getRelocation(Rel);
5604 if (info->O->isRelocationScattered(RE))
5605 continue;
5606 isExtern = info->O->getPlainRelocationExternal(RE);
5607 if (isExtern) {
5608 symbol_iterator RelocSym = Reloc.getSymbol();
5609 Symbol = *RelocSym;
5610 }
5611 reloc_found = true;
5612 break;
5613 }
5614 }
5615 // If there is an external relocation entry for a symbol in a section
5616 // then used that symbol's value for the value of the reference.
5617 if (reloc_found && isExtern) {
5618 if (info->O->getAnyRelocationPCRel(RE)) {
5619 unsigned Type = info->O->getAnyRelocationType(RE);
5620 if (Type == MachO::X86_64_RELOC_SIGNED) {
5621 Symbol.getAddress(ReferenceValue);
5622 }
5623 }
5624 }
5625
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005626 // Look for literals such as Objective-C CFStrings refs, Selector refs,
5627 // Message refs and Class refs.
5628 bool classref, selref, msgref, cfstring;
5629 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
5630 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00005631 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005632 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
5633 // And the pointer_value in that section is typically zero as it will be
5634 // set by dyld as part of the "bind information".
5635 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
5636 if (name != nullptr) {
5637 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00005638 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005639 if (class_name != nullptr && class_name[1] == '_' &&
5640 class_name[2] != '\0') {
5641 info->class_name = class_name + 2;
5642 return name;
5643 }
5644 }
5645 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005646
David Blaikie33dd45d02015-03-23 18:39:02 +00005647 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005648 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
5649 const char *name =
5650 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
5651 if (name != nullptr)
5652 info->class_name = name;
5653 else
5654 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00005655 return name;
5656 }
5657
David Blaikie33dd45d02015-03-23 18:39:02 +00005658 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005659 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
5660 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
5661 return name;
5662 }
5663
David Blaikie33dd45d02015-03-23 18:39:02 +00005664 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005665 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
5666
5667 if (pointer_value != 0)
5668 ReferenceValue = pointer_value;
5669
5670 const char *name = GuessCstringPointer(ReferenceValue, info);
5671 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00005672 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005673 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
5674 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00005675 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005676 info->class_name = nullptr;
5677 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
5678 info->selector_name = name;
5679 } else
5680 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
5681 return name;
5682 }
5683
5684 // Lastly look for an indirect symbol with this ReferenceValue which is in
5685 // a literal pool. If found return that symbol name.
5686 name = GuessIndirectSymbol(ReferenceValue, info);
5687 if (name) {
5688 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
5689 return name;
5690 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005691
5692 return nullptr;
5693}
5694
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005695// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00005696// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005697// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
5698// is created and returns the symbol name that matches the ReferenceValue or
5699// nullptr if none. The ReferenceType is passed in for the IN type of
5700// reference the instruction is making from the values in defined in the header
5701// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
5702// Out type and the ReferenceName will also be set which is added as a comment
5703// to the disassembled instruction.
5704//
Kevin Enderby04bf6932014-10-28 23:39:46 +00005705#if HAVE_CXXABI_H
5706// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005707// returned through ReferenceName and ReferenceType is set to
5708// LLVMDisassembler_ReferenceType_DeMangled_Name .
Kevin Enderby04bf6932014-10-28 23:39:46 +00005709#endif
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005710//
5711// When this is called to get a symbol name for a branch target then the
5712// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
5713// SymbolValue will be looked for in the indirect symbol table to determine if
5714// it is an address for a symbol stub. If so then the symbol name for that
5715// stub is returned indirectly through ReferenceName and then ReferenceType is
5716// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
5717//
Kevin Enderbybf246f52014-09-24 23:08:22 +00005718// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005719// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
5720// SymbolValue is checked to be an address of literal pointer, symbol pointer,
5721// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005722// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00005723static const char *SymbolizerSymbolLookUp(void *DisInfo,
5724 uint64_t ReferenceValue,
5725 uint64_t *ReferenceType,
5726 uint64_t ReferencePC,
5727 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005728 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00005729 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00005730 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00005731 *ReferenceName = nullptr;
5732 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005733 return nullptr;
5734 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005735
Kevin Enderbyf6d25852015-01-31 00:37:11 +00005736 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00005737
Kevin Enderby85974882014-09-26 22:20:44 +00005738 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
5739 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00005740 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005741 method_reference(info, ReferenceType, ReferenceName);
5742 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
5743 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
5744 } else
Kevin Enderby04bf6932014-10-28 23:39:46 +00005745#if HAVE_CXXABI_H
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005746 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00005747 if (info->demangled_name != nullptr)
5748 free(info->demangled_name);
5749 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005750 info->demangled_name =
5751 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00005752 if (info->demangled_name != nullptr) {
5753 *ReferenceName = info->demangled_name;
5754 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5755 } else
5756 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5757 } else
5758#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005759 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5760 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
5761 *ReferenceName =
5762 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00005763 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005764 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00005765 else
5766 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00005767 // If this is arm64 and the reference is an adrp instruction save the
5768 // instruction, passed in ReferenceValue and the address of the instruction
5769 // for use later if we see and add immediate instruction.
5770 } else if (info->O->getArch() == Triple::aarch64 &&
5771 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
5772 info->adrp_inst = ReferenceValue;
5773 info->adrp_addr = ReferencePC;
5774 SymbolName = nullptr;
5775 *ReferenceName = nullptr;
5776 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5777 // If this is arm64 and reference is an add immediate instruction and we
5778 // have
5779 // seen an adrp instruction just before it and the adrp's Xd register
5780 // matches
5781 // this add's Xn register reconstruct the value being referenced and look to
5782 // see if it is a literal pointer. Note the add immediate instruction is
5783 // passed in ReferenceValue.
5784 } else if (info->O->getArch() == Triple::aarch64 &&
5785 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
5786 ReferencePC - 4 == info->adrp_addr &&
5787 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5788 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5789 uint32_t addxri_inst;
5790 uint64_t adrp_imm, addxri_imm;
5791
5792 adrp_imm =
5793 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5794 if (info->adrp_inst & 0x0200000)
5795 adrp_imm |= 0xfffffffffc000000LL;
5796
5797 addxri_inst = ReferenceValue;
5798 addxri_imm = (addxri_inst >> 10) & 0xfff;
5799 if (((addxri_inst >> 22) & 0x3) == 1)
5800 addxri_imm <<= 12;
5801
5802 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5803 (adrp_imm << 12) + addxri_imm;
5804
5805 *ReferenceName =
5806 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5807 if (*ReferenceName == nullptr)
5808 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5809 // If this is arm64 and the reference is a load register instruction and we
5810 // have seen an adrp instruction just before it and the adrp's Xd register
5811 // matches this add's Xn register reconstruct the value being referenced and
5812 // look to see if it is a literal pointer. Note the load register
5813 // instruction is passed in ReferenceValue.
5814 } else if (info->O->getArch() == Triple::aarch64 &&
5815 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
5816 ReferencePC - 4 == info->adrp_addr &&
5817 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5818 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5819 uint32_t ldrxui_inst;
5820 uint64_t adrp_imm, ldrxui_imm;
5821
5822 adrp_imm =
5823 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5824 if (info->adrp_inst & 0x0200000)
5825 adrp_imm |= 0xfffffffffc000000LL;
5826
5827 ldrxui_inst = ReferenceValue;
5828 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
5829
5830 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5831 (adrp_imm << 12) + (ldrxui_imm << 3);
5832
5833 *ReferenceName =
5834 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5835 if (*ReferenceName == nullptr)
5836 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5837 }
5838 // If this arm64 and is an load register (PC-relative) instruction the
5839 // ReferenceValue is the PC plus the immediate value.
5840 else if (info->O->getArch() == Triple::aarch64 &&
5841 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
5842 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
5843 *ReferenceName =
5844 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5845 if (*ReferenceName == nullptr)
5846 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby85974882014-09-26 22:20:44 +00005847 }
Kevin Enderby04bf6932014-10-28 23:39:46 +00005848#if HAVE_CXXABI_H
5849 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
5850 if (info->demangled_name != nullptr)
5851 free(info->demangled_name);
5852 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005853 info->demangled_name =
5854 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00005855 if (info->demangled_name != nullptr) {
5856 *ReferenceName = info->demangled_name;
5857 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5858 }
5859 }
5860#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005861 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00005862 *ReferenceName = nullptr;
5863 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5864 }
5865
5866 return SymbolName;
5867}
5868
Kevin Enderbybf246f52014-09-24 23:08:22 +00005869/// \brief Emits the comments that are stored in the CommentStream.
5870/// Each comment in the CommentStream must end with a newline.
5871static void emitComments(raw_svector_ostream &CommentStream,
5872 SmallString<128> &CommentsToEmit,
5873 formatted_raw_ostream &FormattedOS,
5874 const MCAsmInfo &MAI) {
5875 // Flush the stream before taking its content.
5876 CommentStream.flush();
5877 StringRef Comments = CommentsToEmit.str();
5878 // Get the default information for printing a comment.
5879 const char *CommentBegin = MAI.getCommentString();
5880 unsigned CommentColumn = MAI.getCommentColumn();
5881 bool IsFirst = true;
5882 while (!Comments.empty()) {
5883 if (!IsFirst)
5884 FormattedOS << '\n';
5885 // Emit a line of comments.
5886 FormattedOS.PadToColumn(CommentColumn);
5887 size_t Position = Comments.find('\n');
5888 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
5889 // Move after the newline character.
5890 Comments = Comments.substr(Position + 1);
5891 IsFirst = false;
5892 }
5893 FormattedOS.flush();
5894
5895 // Tell the comment stream that the vector changed underneath it.
5896 CommentsToEmit.clear();
5897 CommentStream.resync();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005898}
5899
Kevin Enderby95df54c2015-02-04 01:01:38 +00005900static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
5901 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005902 const char *McpuDefault = nullptr;
5903 const Target *ThumbTarget = nullptr;
5904 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005905 if (!TheTarget) {
5906 // GetTarget prints out stuff.
5907 return;
5908 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005909 if (MCPU.empty() && McpuDefault)
5910 MCPU = McpuDefault;
5911
Ahmed Charles56440fd2014-03-06 05:51:42 +00005912 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005913 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00005914 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005915 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005916
Kevin Enderbyc9595622014-08-06 23:24:41 +00005917 // Package up features to be passed to target/subtarget
5918 std::string FeaturesStr;
5919 if (MAttrs.size()) {
5920 SubtargetFeatures Features;
5921 for (unsigned i = 0; i != MAttrs.size(); ++i)
5922 Features.AddFeature(MAttrs[i]);
5923 FeaturesStr = Features.getString();
5924 }
5925
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005926 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00005927 std::unique_ptr<const MCRegisterInfo> MRI(
5928 TheTarget->createMCRegInfo(TripleName));
5929 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00005930 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00005931 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +00005932 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00005933 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005934 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005935 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005936 std::unique_ptr<MCSymbolizer> Symbolizer;
5937 struct DisassembleInfo SymbolizerInfo;
5938 std::unique_ptr<MCRelocationInfo> RelInfo(
5939 TheTarget->createMCRelocationInfo(TripleName, Ctx));
5940 if (RelInfo) {
5941 Symbolizer.reset(TheTarget->createMCSymbolizer(
5942 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00005943 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005944 DisAsm->setSymbolizer(std::move(Symbolizer));
5945 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005946 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00005947 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Eric Christopherf8019402015-03-31 00:10:04 +00005948 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00005949 // Set the display preference for hex vs. decimal immediates.
5950 IP->setPrintImmHex(PrintImmHex);
5951 // Comment stream and backing vector.
5952 SmallString<128> CommentsToEmit;
5953 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00005954 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
5955 // if it is done then arm64 comments for string literals don't get printed
5956 // and some constant get printed instead and not setting it causes intel
5957 // (32-bit and 64-bit) comments printed with different spacing before the
5958 // comment causing different diffs with the 'C' disassembler library API.
5959 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00005960
Kevin Enderbyae3c1262014-11-14 21:52:18 +00005961 if (!AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencerc1363cf2011-10-07 19:25:47 +00005962 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00005963 << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005964 return;
5965 }
5966
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005967 // Set up thumb disassembler.
5968 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
5969 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
5970 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00005971 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005972 std::unique_ptr<MCInstPrinter> ThumbIP;
5973 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00005974 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
5975 struct DisassembleInfo ThumbSymbolizerInfo;
5976 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005977 if (ThumbTarget) {
5978 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
5979 ThumbAsmInfo.reset(
5980 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
5981 ThumbSTI.reset(
5982 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
5983 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
5984 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00005985 MCContext *PtrThumbCtx = ThumbCtx.get();
5986 ThumbRelInfo.reset(
5987 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
5988 if (ThumbRelInfo) {
5989 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
5990 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00005991 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00005992 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
5993 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005994 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
5995 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Eric Christopherf8019402015-03-31 00:10:04 +00005996 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
5997 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00005998 // Set the display preference for hex vs. decimal immediates.
5999 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006000 }
6001
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006002 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006003 errs() << "error: couldn't initialize disassembler for target "
6004 << ThumbTripleName << '\n';
6005 return;
6006 }
6007
Charles Davis8bdfafd2013-09-01 04:28:48 +00006008 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006009
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006010 // FIXME: Using the -cfg command line option, this code used to be able to
6011 // annotate relocations with the referenced symbol's name, and if this was
6012 // inside a __[cf]string section, the data it points to. This is now replaced
6013 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00006014 std::vector<SectionRef> Sections;
6015 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006016 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00006017 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006018
Kevin Enderby273ae012013-06-06 17:20:50 +00006019 getSectionsAndSymbols(Header, MachOOF, Sections, Symbols, FoundFns,
6020 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006021
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006022 // Sort the symbols by address, just in case they didn't come in that way.
Owen Andersond9243c42011-10-17 21:37:35 +00006023 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006024
Kevin Enderby273ae012013-06-06 17:20:50 +00006025 // Build a data in code table that is sorted on by the address of each entry.
6026 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00006027 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00006028 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00006029 else
6030 BaseAddress = BaseSegmentAddress;
6031 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00006032 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00006033 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006034 uint32_t Offset;
6035 DI->getOffset(Offset);
6036 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6037 }
6038 array_pod_sort(Dices.begin(), Dices.end());
6039
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006040#ifndef NDEBUG
6041 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6042#else
6043 raw_ostream &DebugOut = nulls();
6044#endif
6045
Ahmed Charles56440fd2014-03-06 05:51:42 +00006046 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00006047 ObjectFile *DbgObj = MachOOF;
Benjamin Kramer699128e2011-09-21 01:13:19 +00006048 // Try to find debug info and set up the DIContext for it.
6049 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00006050 // A separate DSym file path was specified, parse it as a macho file,
6051 // get the sections and supply it to the section name parsing machinery.
6052 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00006053 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006054 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00006055 if (std::error_code EC = BufOrErr.getError()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006056 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +00006057 return;
6058 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00006059 DbgObj =
6060 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
6061 .get()
6062 .release();
Benjamin Kramer699128e2011-09-21 01:13:19 +00006063 }
6064
Eric Christopher7370b552012-11-12 21:40:38 +00006065 // Setup the DIContext
Rafael Espindolaa04bb5b2014-07-31 20:19:36 +00006066 diContext.reset(DIContext::getDWARFContext(*DbgObj));
Benjamin Kramer699128e2011-09-21 01:13:19 +00006067 }
6068
Kevin Enderby95df54c2015-02-04 01:01:38 +00006069 if (DumpSections.size() == 0)
6070 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006071
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006072 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00006073 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00006074 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6075 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006076
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006077 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006078
Rafael Espindolab0f76a42013-04-05 15:15:22 +00006079 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00006080 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006081 continue;
6082
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006083 StringRef BytesStr;
6084 Sections[SectIdx].getContents(BytesStr);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00006085 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6086 BytesStr.size());
Rafael Espindola80291272014-10-08 15:28:58 +00006087 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00006088
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006089 bool symbolTableWorked = false;
6090
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006091 // Parse relocations.
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00006092 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
6093 for (const RelocationRef &Reloc : Sections[SectIdx].relocations()) {
Rafael Espindola80291272014-10-08 15:28:58 +00006094 uint64_t RelocOffset;
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00006095 Reloc.getOffset(RelocOffset);
Rafael Espindola80291272014-10-08 15:28:58 +00006096 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Owen Andersond9243c42011-10-17 21:37:35 +00006097 RelocOffset -= SectionAddress;
6098
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00006099 symbol_iterator RelocSym = Reloc.getSymbol();
Owen Andersond9243c42011-10-17 21:37:35 +00006100
Rafael Espindola806f0062013-06-05 01:33:53 +00006101 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006102 }
6103 array_pod_sort(Relocs.begin(), Relocs.end());
6104
Kevin Enderbybf246f52014-09-24 23:08:22 +00006105 // Create a map of symbol addresses to symbol names for use by
6106 // the SymbolizerSymbolLookUp() routine.
6107 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00006108 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006109 for (const SymbolRef &Symbol : MachOOF->symbols()) {
6110 SymbolRef::Type ST;
6111 Symbol.getType(ST);
6112 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
6113 ST == SymbolRef::ST_Other) {
6114 uint64_t Address;
6115 Symbol.getAddress(Address);
6116 StringRef SymName;
6117 Symbol.getName(SymName);
6118 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00006119 if (!DisSymName.empty() && DisSymName == SymName)
6120 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006121 }
6122 }
David Blaikie33dd45d02015-03-23 18:39:02 +00006123 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00006124 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
6125 return;
6126 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006127 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006128 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006129 SymbolizerInfo.O = MachOOF;
6130 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00006131 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006132 SymbolizerInfo.Sections = &Sections;
6133 SymbolizerInfo.class_name = nullptr;
6134 SymbolizerInfo.selector_name = nullptr;
6135 SymbolizerInfo.method = nullptr;
Kevin Enderby04bf6932014-10-28 23:39:46 +00006136 SymbolizerInfo.demangled_name = nullptr;
Kevin Enderby078be602014-10-23 19:53:12 +00006137 SymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006138 SymbolizerInfo.adrp_addr = 0;
6139 SymbolizerInfo.adrp_inst = 0;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006140 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006141 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006142 ThumbSymbolizerInfo.O = MachOOF;
6143 ThumbSymbolizerInfo.S = Sections[SectIdx];
6144 ThumbSymbolizerInfo.AddrMap = &AddrMap;
6145 ThumbSymbolizerInfo.Sections = &Sections;
6146 ThumbSymbolizerInfo.class_name = nullptr;
6147 ThumbSymbolizerInfo.selector_name = nullptr;
6148 ThumbSymbolizerInfo.method = nullptr;
6149 ThumbSymbolizerInfo.demangled_name = nullptr;
6150 ThumbSymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006151 ThumbSymbolizerInfo.adrp_addr = 0;
6152 ThumbSymbolizerInfo.adrp_inst = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006153
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006154 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006155 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00006156 StringRef SymName;
6157 Symbols[SymIdx].getName(SymName);
6158
6159 SymbolRef::Type ST;
6160 Symbols[SymIdx].getType(ST);
6161 if (ST != SymbolRef::ST_Function)
6162 continue;
6163
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006164 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00006165 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Owen Andersond9243c42011-10-17 21:37:35 +00006166 if (!containsSym)
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006167 continue;
6168
Kevin Enderby6a221752015-03-17 17:10:57 +00006169 // If we are only disassembling one symbol see if this is that symbol.
6170 if (!DisSymName.empty() && DisSymName != SymName)
6171 continue;
6172
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006173 // Start at the address of the symbol relative to the section's address.
Owen Andersond9243c42011-10-17 21:37:35 +00006174 uint64_t Start = 0;
Rafael Espindola80291272014-10-08 15:28:58 +00006175 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Danil Malyshevcbe72fc2011-11-29 17:40:10 +00006176 Symbols[SymIdx].getAddress(Start);
Cameron Zwarich54478a52012-02-03 05:42:17 +00006177 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006178
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006179 // Stop disassembling either at the beginning of the next symbol or at
6180 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00006181 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00006182 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006183 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00006184 while (Symbols.size() > NextSymIdx) {
6185 SymbolRef::Type NextSymType;
6186 Symbols[NextSymIdx].getType(NextSymType);
6187 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00006188 containsNextSym =
6189 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Danil Malyshevcbe72fc2011-11-29 17:40:10 +00006190 Symbols[NextSymIdx].getAddress(NextSym);
Cameron Zwarich54478a52012-02-03 05:42:17 +00006191 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006192 break;
6193 }
6194 ++NextSymIdx;
6195 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006196
Rafael Espindola80291272014-10-08 15:28:58 +00006197 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006198 uint64_t End = containsNextSym ? NextSym : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00006199 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006200
6201 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00006202
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006203 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
6204 bool isThumb =
6205 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
6206
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006207 outs() << SymName << ":\n";
6208 DILineInfo lastLine;
6209 for (uint64_t Index = Start; Index < End; Index += Size) {
6210 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00006211
Kevin Enderbybf246f52014-09-24 23:08:22 +00006212 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006213 if (!NoLeadingAddr) {
6214 if (FullLeadingAddr) {
6215 if (MachOOF->is64Bit())
6216 outs() << format("%016" PRIx64, PC);
6217 else
6218 outs() << format("%08" PRIx64, PC);
6219 } else {
6220 outs() << format("%8" PRIx64 ":", PC);
6221 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006222 }
6223 if (!NoShowRawInsn)
6224 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00006225
6226 // Check the data in code table here to see if this is data not an
6227 // instruction to be disassembled.
6228 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006229 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006230 dice_table_iterator DTI =
6231 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
6232 compareDiceTableEntries);
6233 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006234 uint16_t Length;
6235 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00006236 uint16_t Kind;
6237 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00006238 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00006239 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
6240 (PC == (DTI->first + Length - 1)) && (Length & 1))
6241 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00006242 continue;
6243 }
6244
Kevin Enderbybf246f52014-09-24 23:08:22 +00006245 SmallVector<char, 64> AnnotationsBytes;
6246 raw_svector_ostream Annotations(AnnotationsBytes);
6247
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006248 bool gotInst;
6249 if (isThumb)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006250 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006251 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006252 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006253 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00006254 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006255 if (gotInst) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006256 if (!NoShowRawInsn) {
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00006257 DumpBytes(ArrayRef<uint8_t>(Bytes.data() + Index, Size));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006258 }
6259 formatted_raw_ostream FormattedOS(outs());
6260 Annotations.flush();
6261 StringRef AnnotationsStr = Annotations.str();
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006262 if (isThumb)
Akira Hatanakab46d0232015-03-27 20:36:02 +00006263 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006264 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00006265 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006266 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00006267
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006268 // Print debug info.
6269 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006270 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006271 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00006272 if (dli != lastLine && dli.Line != 0)
6273 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
6274 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006275 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006276 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006277 outs() << "\n";
6278 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006279 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006280 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006281 outs() << format("\t.byte 0x%02x #bad opcode\n",
6282 *(Bytes.data() + Index) & 0xff);
6283 Size = 1; // skip exactly one illegible byte and move on.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006284 } else if (Arch == Triple::aarch64) {
6285 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6286 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
6287 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
6288 (*(Bytes.data() + Index + 3) & 0xff) << 24;
6289 outs() << format("\t.long\t0x%08x\n", opcode);
6290 Size = 4;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006291 } else {
6292 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6293 if (Size == 0)
6294 Size = 1; // skip illegible bytes
6295 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006296 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006297 }
6298 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006299 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00006300 // Reading the symbol table didn't work, disassemble the whole section.
6301 uint64_t SectAddress = Sections[SectIdx].getAddress();
6302 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00006303 uint64_t InstSize;
6304 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00006305 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00006306
Kevin Enderbybf246f52014-09-24 23:08:22 +00006307 uint64_t PC = SectAddress + Index;
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006308 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
6309 DebugOut, nulls())) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006310 if (!NoLeadingAddr) {
6311 if (FullLeadingAddr) {
6312 if (MachOOF->is64Bit())
6313 outs() << format("%016" PRIx64, PC);
6314 else
6315 outs() << format("%08" PRIx64, PC);
6316 } else {
6317 outs() << format("%8" PRIx64 ":", PC);
6318 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006319 }
6320 if (!NoShowRawInsn) {
6321 outs() << "\t";
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00006322 DumpBytes(ArrayRef<uint8_t>(Bytes.data() + Index, InstSize));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006323 }
Akira Hatanaka1d079942015-03-28 20:44:05 +00006324 IP->printInst(&Inst, outs(), "", *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00006325 outs() << "\n";
6326 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006327 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006328 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006329 outs() << format("\t.byte 0x%02x #bad opcode\n",
6330 *(Bytes.data() + Index) & 0xff);
6331 InstSize = 1; // skip exactly one illegible byte and move on.
6332 } else {
6333 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6334 if (InstSize == 0)
6335 InstSize = 1; // skip illegible bytes
6336 }
Bill Wendling4e68e062012-07-19 00:17:40 +00006337 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00006338 }
6339 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006340 // The TripleName's need to be reset if we are called again for a different
6341 // archtecture.
6342 TripleName = "";
6343 ThumbTripleName = "";
6344
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006345 if (SymbolizerInfo.method != nullptr)
6346 free(SymbolizerInfo.method);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006347 if (SymbolizerInfo.demangled_name != nullptr)
6348 free(SymbolizerInfo.demangled_name);
Kevin Enderby078be602014-10-23 19:53:12 +00006349 if (SymbolizerInfo.bindtable != nullptr)
6350 delete SymbolizerInfo.bindtable;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006351 if (ThumbSymbolizerInfo.method != nullptr)
6352 free(ThumbSymbolizerInfo.method);
6353 if (ThumbSymbolizerInfo.demangled_name != nullptr)
6354 free(ThumbSymbolizerInfo.demangled_name);
6355 if (ThumbSymbolizerInfo.bindtable != nullptr)
6356 delete ThumbSymbolizerInfo.bindtable;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006357 }
6358}
Tim Northover4bd286a2014-08-01 13:07:19 +00006359
Tim Northover39c70bb2014-08-12 11:52:59 +00006360//===----------------------------------------------------------------------===//
6361// __compact_unwind section dumping
6362//===----------------------------------------------------------------------===//
6363
Tim Northover4bd286a2014-08-01 13:07:19 +00006364namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00006365
6366template <typename T> static uint64_t readNext(const char *&Buf) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006367 using llvm::support::little;
6368 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00006369
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006370 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
6371 Buf += sizeof(T);
6372 return Val;
6373}
Tim Northover39c70bb2014-08-12 11:52:59 +00006374
Tim Northover4bd286a2014-08-01 13:07:19 +00006375struct CompactUnwindEntry {
6376 uint32_t OffsetInSection;
6377
6378 uint64_t FunctionAddr;
6379 uint32_t Length;
6380 uint32_t CompactEncoding;
6381 uint64_t PersonalityAddr;
6382 uint64_t LSDAAddr;
6383
6384 RelocationRef FunctionReloc;
6385 RelocationRef PersonalityReloc;
6386 RelocationRef LSDAReloc;
6387
6388 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006389 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006390 if (Is64)
6391 read<uint64_t>(Contents.data() + Offset);
6392 else
6393 read<uint32_t>(Contents.data() + Offset);
6394 }
6395
6396private:
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006397 template <typename UIntPtr> void read(const char *Buf) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006398 FunctionAddr = readNext<UIntPtr>(Buf);
6399 Length = readNext<uint32_t>(Buf);
6400 CompactEncoding = readNext<uint32_t>(Buf);
6401 PersonalityAddr = readNext<UIntPtr>(Buf);
6402 LSDAAddr = readNext<UIntPtr>(Buf);
6403 }
6404};
6405}
6406
6407/// Given a relocation from __compact_unwind, consisting of the RelocationRef
6408/// and data being relocated, determine the best base Name and Addend to use for
6409/// display purposes.
6410///
6411/// 1. An Extern relocation will directly reference a symbol (and the data is
6412/// then already an addend), so use that.
6413/// 2. Otherwise the data is an offset in the object file's layout; try to find
6414// a symbol before it in the same section, and use the offset from there.
6415/// 3. Finally, if all that fails, fall back to an offset from the start of the
6416/// referenced section.
6417static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
6418 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006419 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00006420 StringRef &Name, uint64_t &Addend) {
6421 if (Reloc.getSymbol() != Obj->symbol_end()) {
6422 Reloc.getSymbol()->getName(Name);
6423 Addend = Addr;
6424 return;
6425 }
6426
6427 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
6428 SectionRef RelocSection = Obj->getRelocationSection(RE);
6429
Rafael Espindola80291272014-10-08 15:28:58 +00006430 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00006431
6432 auto Sym = Symbols.upper_bound(Addr);
6433 if (Sym == Symbols.begin()) {
6434 // The first symbol in the object is after this reference, the best we can
6435 // do is section-relative notation.
6436 RelocSection.getName(Name);
6437 Addend = Addr - SectionAddr;
6438 return;
6439 }
6440
6441 // Go back one so that SymbolAddress <= Addr.
6442 --Sym;
6443
6444 section_iterator SymSection = Obj->section_end();
6445 Sym->second.getSection(SymSection);
6446 if (RelocSection == *SymSection) {
6447 // There's a valid symbol in the same section before this reference.
6448 Sym->second.getName(Name);
6449 Addend = Addr - Sym->first;
6450 return;
6451 }
6452
6453 // There is a symbol before this reference, but it's in a different
6454 // section. Probably not helpful to mention it, so use the section name.
6455 RelocSection.getName(Name);
6456 Addend = Addr - SectionAddr;
6457}
6458
6459static void printUnwindRelocDest(const MachOObjectFile *Obj,
6460 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006461 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006462 StringRef Name;
6463 uint64_t Addend;
6464
Tim Northover0b0add52014-09-09 10:45:06 +00006465 if (!Reloc.getObjectFile())
6466 return;
6467
Tim Northover4bd286a2014-08-01 13:07:19 +00006468 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
6469
6470 outs() << Name;
6471 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00006472 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00006473}
6474
6475static void
6476printMachOCompactUnwindSection(const MachOObjectFile *Obj,
6477 std::map<uint64_t, SymbolRef> &Symbols,
6478 const SectionRef &CompactUnwind) {
6479
6480 assert(Obj->isLittleEndian() &&
6481 "There should not be a big-endian .o with __compact_unwind");
6482
6483 bool Is64 = Obj->is64Bit();
6484 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
6485 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
6486
6487 StringRef Contents;
6488 CompactUnwind.getContents(Contents);
6489
6490 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
6491
6492 // First populate the initial raw offsets, encodings and so on from the entry.
6493 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
6494 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
6495 CompactUnwinds.push_back(Entry);
6496 }
6497
6498 // Next we need to look at the relocations to find out what objects are
6499 // actually being referred to.
6500 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
6501 uint64_t RelocAddress;
6502 Reloc.getOffset(RelocAddress);
6503
6504 uint32_t EntryIdx = RelocAddress / EntrySize;
6505 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
6506 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
6507
6508 if (OffsetInEntry == 0)
6509 Entry.FunctionReloc = Reloc;
6510 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
6511 Entry.PersonalityReloc = Reloc;
6512 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
6513 Entry.LSDAReloc = Reloc;
6514 else
6515 llvm_unreachable("Unexpected relocation in __compact_unwind section");
6516 }
6517
6518 // Finally, we're ready to print the data we've gathered.
6519 outs() << "Contents of __compact_unwind section:\n";
6520 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00006521 outs() << " Entry at offset "
6522 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00006523
6524 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006525 outs() << " start: " << format("0x%" PRIx64,
6526 Entry.FunctionAddr) << ' ';
6527 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00006528 outs() << '\n';
6529
6530 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006531 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
6532 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00006533 // 3. The 32-bit compact encoding.
6534 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00006535 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00006536
6537 // 4. The personality function, if present.
6538 if (Entry.PersonalityReloc.getObjectFile()) {
6539 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00006540 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00006541 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
6542 Entry.PersonalityAddr);
6543 outs() << '\n';
6544 }
6545
6546 // 5. This entry's language-specific data area.
6547 if (Entry.LSDAReloc.getObjectFile()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006548 outs() << " LSDA: " << format("0x%" PRIx64,
6549 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00006550 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
6551 outs() << '\n';
6552 }
6553 }
6554}
6555
Tim Northover39c70bb2014-08-12 11:52:59 +00006556//===----------------------------------------------------------------------===//
6557// __unwind_info section dumping
6558//===----------------------------------------------------------------------===//
6559
6560static void printRegularSecondLevelUnwindPage(const char *PageStart) {
6561 const char *Pos = PageStart;
6562 uint32_t Kind = readNext<uint32_t>(Pos);
6563 (void)Kind;
6564 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
6565
6566 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6567 uint16_t NumEntries = readNext<uint16_t>(Pos);
6568
6569 Pos = PageStart + EntriesStart;
6570 for (unsigned i = 0; i < NumEntries; ++i) {
6571 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6572 uint32_t Encoding = readNext<uint32_t>(Pos);
6573
6574 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006575 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6576 << ", "
6577 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006578 }
6579}
6580
6581static void printCompressedSecondLevelUnwindPage(
6582 const char *PageStart, uint32_t FunctionBase,
6583 const SmallVectorImpl<uint32_t> &CommonEncodings) {
6584 const char *Pos = PageStart;
6585 uint32_t Kind = readNext<uint32_t>(Pos);
6586 (void)Kind;
6587 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
6588
6589 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6590 uint16_t NumEntries = readNext<uint16_t>(Pos);
6591
6592 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
6593 readNext<uint16_t>(Pos);
Aaron Ballman80930af2014-08-14 13:53:19 +00006594 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
6595 PageStart + EncodingsStart);
Tim Northover39c70bb2014-08-12 11:52:59 +00006596
6597 Pos = PageStart + EntriesStart;
6598 for (unsigned i = 0; i < NumEntries; ++i) {
6599 uint32_t Entry = readNext<uint32_t>(Pos);
6600 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
6601 uint32_t EncodingIdx = Entry >> 24;
6602
6603 uint32_t Encoding;
6604 if (EncodingIdx < CommonEncodings.size())
6605 Encoding = CommonEncodings[EncodingIdx];
6606 else
6607 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
6608
6609 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006610 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6611 << ", "
6612 << "encoding[" << EncodingIdx
6613 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006614 }
6615}
6616
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006617static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
6618 std::map<uint64_t, SymbolRef> &Symbols,
6619 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00006620
6621 assert(Obj->isLittleEndian() &&
6622 "There should not be a big-endian .o with __unwind_info");
6623
6624 outs() << "Contents of __unwind_info section:\n";
6625
6626 StringRef Contents;
6627 UnwindInfo.getContents(Contents);
6628 const char *Pos = Contents.data();
6629
6630 //===----------------------------------
6631 // Section header
6632 //===----------------------------------
6633
6634 uint32_t Version = readNext<uint32_t>(Pos);
6635 outs() << " Version: "
6636 << format("0x%" PRIx32, Version) << '\n';
6637 assert(Version == 1 && "only understand version 1");
6638
6639 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
6640 outs() << " Common encodings array section offset: "
6641 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
6642 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
6643 outs() << " Number of common encodings in array: "
6644 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
6645
6646 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
6647 outs() << " Personality function array section offset: "
6648 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
6649 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
6650 outs() << " Number of personality functions in array: "
6651 << format("0x%" PRIx32, NumPersonalities) << '\n';
6652
6653 uint32_t IndicesStart = readNext<uint32_t>(Pos);
6654 outs() << " Index array section offset: "
6655 << format("0x%" PRIx32, IndicesStart) << '\n';
6656 uint32_t NumIndices = readNext<uint32_t>(Pos);
6657 outs() << " Number of indices in array: "
6658 << format("0x%" PRIx32, NumIndices) << '\n';
6659
6660 //===----------------------------------
6661 // A shared list of common encodings
6662 //===----------------------------------
6663
6664 // These occupy indices in the range [0, N] whenever an encoding is referenced
6665 // from a compressed 2nd level index table. In practice the linker only
6666 // creates ~128 of these, so that indices are available to embed encodings in
6667 // the 2nd level index.
6668
6669 SmallVector<uint32_t, 64> CommonEncodings;
6670 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
6671 Pos = Contents.data() + CommonEncodingsStart;
6672 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
6673 uint32_t Encoding = readNext<uint32_t>(Pos);
6674 CommonEncodings.push_back(Encoding);
6675
6676 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
6677 << '\n';
6678 }
6679
Tim Northover39c70bb2014-08-12 11:52:59 +00006680 //===----------------------------------
6681 // Personality functions used in this executable
6682 //===----------------------------------
6683
6684 // There should be only a handful of these (one per source language,
6685 // roughly). Particularly since they only get 2 bits in the compact encoding.
6686
6687 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
6688 Pos = Contents.data() + PersonalitiesStart;
6689 for (unsigned i = 0; i < NumPersonalities; ++i) {
6690 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
6691 outs() << " personality[" << i + 1
6692 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
6693 }
6694
6695 //===----------------------------------
6696 // The level 1 index entries
6697 //===----------------------------------
6698
6699 // These specify an approximate place to start searching for the more detailed
6700 // information, sorted by PC.
6701
6702 struct IndexEntry {
6703 uint32_t FunctionOffset;
6704 uint32_t SecondLevelPageStart;
6705 uint32_t LSDAStart;
6706 };
6707
6708 SmallVector<IndexEntry, 4> IndexEntries;
6709
6710 outs() << " Top level indices: (count = " << NumIndices << ")\n";
6711 Pos = Contents.data() + IndicesStart;
6712 for (unsigned i = 0; i < NumIndices; ++i) {
6713 IndexEntry Entry;
6714
6715 Entry.FunctionOffset = readNext<uint32_t>(Pos);
6716 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
6717 Entry.LSDAStart = readNext<uint32_t>(Pos);
6718 IndexEntries.push_back(Entry);
6719
6720 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006721 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
6722 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00006723 << "2nd level page offset="
6724 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006725 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006726 }
6727
Tim Northover39c70bb2014-08-12 11:52:59 +00006728 //===----------------------------------
6729 // Next come the LSDA tables
6730 //===----------------------------------
6731
6732 // The LSDA layout is rather implicit: it's a contiguous array of entries from
6733 // the first top-level index's LSDAOffset to the last (sentinel).
6734
6735 outs() << " LSDA descriptors:\n";
6736 Pos = Contents.data() + IndexEntries[0].LSDAStart;
6737 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
6738 (2 * sizeof(uint32_t));
6739 for (int i = 0; i < NumLSDAs; ++i) {
6740 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6741 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
6742 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006743 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6744 << ", "
6745 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006746 }
6747
6748 //===----------------------------------
6749 // Finally, the 2nd level indices
6750 //===----------------------------------
6751
6752 // Generally these are 4K in size, and have 2 possible forms:
6753 // + Regular stores up to 511 entries with disparate encodings
6754 // + Compressed stores up to 1021 entries if few enough compact encoding
6755 // values are used.
6756 outs() << " Second level indices:\n";
6757 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
6758 // The final sentinel top-level index has no associated 2nd level page
6759 if (IndexEntries[i].SecondLevelPageStart == 0)
6760 break;
6761
6762 outs() << " Second level index[" << i << "]: "
6763 << "offset in section="
6764 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
6765 << ", "
6766 << "base function offset="
6767 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
6768
6769 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
Aaron Ballman80930af2014-08-14 13:53:19 +00006770 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00006771 if (Kind == 2)
6772 printRegularSecondLevelUnwindPage(Pos);
6773 else if (Kind == 3)
6774 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
6775 CommonEncodings);
6776 else
6777 llvm_unreachable("Do not know how to print this kind of 2nd level page");
Tim Northover39c70bb2014-08-12 11:52:59 +00006778 }
6779}
6780
Tim Northover4bd286a2014-08-01 13:07:19 +00006781void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
6782 std::map<uint64_t, SymbolRef> Symbols;
6783 for (const SymbolRef &SymRef : Obj->symbols()) {
6784 // Discard any undefined or absolute symbols. They're not going to take part
6785 // in the convenience lookup for unwind info and just take up resources.
6786 section_iterator Section = Obj->section_end();
6787 SymRef.getSection(Section);
6788 if (Section == Obj->section_end())
6789 continue;
6790
6791 uint64_t Addr;
6792 SymRef.getAddress(Addr);
6793 Symbols.insert(std::make_pair(Addr, SymRef));
6794 }
6795
6796 for (const SectionRef &Section : Obj->sections()) {
6797 StringRef SectName;
6798 Section.getName(SectName);
6799 if (SectName == "__compact_unwind")
6800 printMachOCompactUnwindSection(Obj, Symbols, Section);
6801 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00006802 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00006803 else if (SectName == "__eh_frame")
6804 outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00006805 }
6806}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00006807
6808static void PrintMachHeader(uint32_t magic, uint32_t cputype,
6809 uint32_t cpusubtype, uint32_t filetype,
6810 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
6811 bool verbose) {
6812 outs() << "Mach header\n";
6813 outs() << " magic cputype cpusubtype caps filetype ncmds "
6814 "sizeofcmds flags\n";
6815 if (verbose) {
6816 if (magic == MachO::MH_MAGIC)
6817 outs() << " MH_MAGIC";
6818 else if (magic == MachO::MH_MAGIC_64)
6819 outs() << "MH_MAGIC_64";
6820 else
6821 outs() << format(" 0x%08" PRIx32, magic);
6822 switch (cputype) {
6823 case MachO::CPU_TYPE_I386:
6824 outs() << " I386";
6825 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6826 case MachO::CPU_SUBTYPE_I386_ALL:
6827 outs() << " ALL";
6828 break;
6829 default:
6830 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6831 break;
6832 }
6833 break;
6834 case MachO::CPU_TYPE_X86_64:
6835 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00006836 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6837 case MachO::CPU_SUBTYPE_X86_64_ALL:
6838 outs() << " ALL";
6839 break;
6840 case MachO::CPU_SUBTYPE_X86_64_H:
6841 outs() << " Haswell";
6842 break;
6843 default:
6844 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6845 break;
6846 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00006847 break;
6848 case MachO::CPU_TYPE_ARM:
6849 outs() << " ARM";
6850 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6851 case MachO::CPU_SUBTYPE_ARM_ALL:
6852 outs() << " ALL";
6853 break;
6854 case MachO::CPU_SUBTYPE_ARM_V4T:
6855 outs() << " V4T";
6856 break;
6857 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
6858 outs() << " V5TEJ";
6859 break;
6860 case MachO::CPU_SUBTYPE_ARM_XSCALE:
6861 outs() << " XSCALE";
6862 break;
6863 case MachO::CPU_SUBTYPE_ARM_V6:
6864 outs() << " V6";
6865 break;
6866 case MachO::CPU_SUBTYPE_ARM_V6M:
6867 outs() << " V6M";
6868 break;
6869 case MachO::CPU_SUBTYPE_ARM_V7:
6870 outs() << " V7";
6871 break;
6872 case MachO::CPU_SUBTYPE_ARM_V7EM:
6873 outs() << " V7EM";
6874 break;
6875 case MachO::CPU_SUBTYPE_ARM_V7K:
6876 outs() << " V7K";
6877 break;
6878 case MachO::CPU_SUBTYPE_ARM_V7M:
6879 outs() << " V7M";
6880 break;
6881 case MachO::CPU_SUBTYPE_ARM_V7S:
6882 outs() << " V7S";
6883 break;
6884 default:
6885 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6886 break;
6887 }
6888 break;
6889 case MachO::CPU_TYPE_ARM64:
6890 outs() << " ARM64";
6891 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6892 case MachO::CPU_SUBTYPE_ARM64_ALL:
6893 outs() << " ALL";
6894 break;
6895 default:
6896 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6897 break;
6898 }
6899 break;
6900 case MachO::CPU_TYPE_POWERPC:
6901 outs() << " PPC";
6902 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6903 case MachO::CPU_SUBTYPE_POWERPC_ALL:
6904 outs() << " ALL";
6905 break;
6906 default:
6907 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6908 break;
6909 }
6910 break;
6911 case MachO::CPU_TYPE_POWERPC64:
6912 outs() << " PPC64";
6913 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6914 case MachO::CPU_SUBTYPE_POWERPC_ALL:
6915 outs() << " ALL";
6916 break;
6917 default:
6918 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6919 break;
6920 }
6921 break;
6922 }
6923 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00006924 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00006925 } else {
6926 outs() << format(" 0x%02" PRIx32,
6927 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
6928 }
6929 switch (filetype) {
6930 case MachO::MH_OBJECT:
6931 outs() << " OBJECT";
6932 break;
6933 case MachO::MH_EXECUTE:
6934 outs() << " EXECUTE";
6935 break;
6936 case MachO::MH_FVMLIB:
6937 outs() << " FVMLIB";
6938 break;
6939 case MachO::MH_CORE:
6940 outs() << " CORE";
6941 break;
6942 case MachO::MH_PRELOAD:
6943 outs() << " PRELOAD";
6944 break;
6945 case MachO::MH_DYLIB:
6946 outs() << " DYLIB";
6947 break;
6948 case MachO::MH_DYLIB_STUB:
6949 outs() << " DYLIB_STUB";
6950 break;
6951 case MachO::MH_DYLINKER:
6952 outs() << " DYLINKER";
6953 break;
6954 case MachO::MH_BUNDLE:
6955 outs() << " BUNDLE";
6956 break;
6957 case MachO::MH_DSYM:
6958 outs() << " DSYM";
6959 break;
6960 case MachO::MH_KEXT_BUNDLE:
6961 outs() << " KEXTBUNDLE";
6962 break;
6963 default:
6964 outs() << format(" %10u", filetype);
6965 break;
6966 }
6967 outs() << format(" %5u", ncmds);
6968 outs() << format(" %10u", sizeofcmds);
6969 uint32_t f = flags;
6970 if (f & MachO::MH_NOUNDEFS) {
6971 outs() << " NOUNDEFS";
6972 f &= ~MachO::MH_NOUNDEFS;
6973 }
6974 if (f & MachO::MH_INCRLINK) {
6975 outs() << " INCRLINK";
6976 f &= ~MachO::MH_INCRLINK;
6977 }
6978 if (f & MachO::MH_DYLDLINK) {
6979 outs() << " DYLDLINK";
6980 f &= ~MachO::MH_DYLDLINK;
6981 }
6982 if (f & MachO::MH_BINDATLOAD) {
6983 outs() << " BINDATLOAD";
6984 f &= ~MachO::MH_BINDATLOAD;
6985 }
6986 if (f & MachO::MH_PREBOUND) {
6987 outs() << " PREBOUND";
6988 f &= ~MachO::MH_PREBOUND;
6989 }
6990 if (f & MachO::MH_SPLIT_SEGS) {
6991 outs() << " SPLIT_SEGS";
6992 f &= ~MachO::MH_SPLIT_SEGS;
6993 }
6994 if (f & MachO::MH_LAZY_INIT) {
6995 outs() << " LAZY_INIT";
6996 f &= ~MachO::MH_LAZY_INIT;
6997 }
6998 if (f & MachO::MH_TWOLEVEL) {
6999 outs() << " TWOLEVEL";
7000 f &= ~MachO::MH_TWOLEVEL;
7001 }
7002 if (f & MachO::MH_FORCE_FLAT) {
7003 outs() << " FORCE_FLAT";
7004 f &= ~MachO::MH_FORCE_FLAT;
7005 }
7006 if (f & MachO::MH_NOMULTIDEFS) {
7007 outs() << " NOMULTIDEFS";
7008 f &= ~MachO::MH_NOMULTIDEFS;
7009 }
7010 if (f & MachO::MH_NOFIXPREBINDING) {
7011 outs() << " NOFIXPREBINDING";
7012 f &= ~MachO::MH_NOFIXPREBINDING;
7013 }
7014 if (f & MachO::MH_PREBINDABLE) {
7015 outs() << " PREBINDABLE";
7016 f &= ~MachO::MH_PREBINDABLE;
7017 }
7018 if (f & MachO::MH_ALLMODSBOUND) {
7019 outs() << " ALLMODSBOUND";
7020 f &= ~MachO::MH_ALLMODSBOUND;
7021 }
7022 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
7023 outs() << " SUBSECTIONS_VIA_SYMBOLS";
7024 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
7025 }
7026 if (f & MachO::MH_CANONICAL) {
7027 outs() << " CANONICAL";
7028 f &= ~MachO::MH_CANONICAL;
7029 }
7030 if (f & MachO::MH_WEAK_DEFINES) {
7031 outs() << " WEAK_DEFINES";
7032 f &= ~MachO::MH_WEAK_DEFINES;
7033 }
7034 if (f & MachO::MH_BINDS_TO_WEAK) {
7035 outs() << " BINDS_TO_WEAK";
7036 f &= ~MachO::MH_BINDS_TO_WEAK;
7037 }
7038 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
7039 outs() << " ALLOW_STACK_EXECUTION";
7040 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
7041 }
7042 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
7043 outs() << " DEAD_STRIPPABLE_DYLIB";
7044 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
7045 }
7046 if (f & MachO::MH_PIE) {
7047 outs() << " PIE";
7048 f &= ~MachO::MH_PIE;
7049 }
7050 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
7051 outs() << " NO_REEXPORTED_DYLIBS";
7052 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
7053 }
7054 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
7055 outs() << " MH_HAS_TLV_DESCRIPTORS";
7056 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
7057 }
7058 if (f & MachO::MH_NO_HEAP_EXECUTION) {
7059 outs() << " MH_NO_HEAP_EXECUTION";
7060 f &= ~MachO::MH_NO_HEAP_EXECUTION;
7061 }
7062 if (f & MachO::MH_APP_EXTENSION_SAFE) {
7063 outs() << " APP_EXTENSION_SAFE";
7064 f &= ~MachO::MH_APP_EXTENSION_SAFE;
7065 }
7066 if (f != 0 || flags == 0)
7067 outs() << format(" 0x%08" PRIx32, f);
7068 } else {
7069 outs() << format(" 0x%08" PRIx32, magic);
7070 outs() << format(" %7d", cputype);
7071 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7072 outs() << format(" 0x%02" PRIx32,
7073 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7074 outs() << format(" %10u", filetype);
7075 outs() << format(" %5u", ncmds);
7076 outs() << format(" %10u", sizeofcmds);
7077 outs() << format(" 0x%08" PRIx32, flags);
7078 }
7079 outs() << "\n";
7080}
7081
Kevin Enderby956366c2014-08-29 22:30:52 +00007082static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
7083 StringRef SegName, uint64_t vmaddr,
7084 uint64_t vmsize, uint64_t fileoff,
7085 uint64_t filesize, uint32_t maxprot,
7086 uint32_t initprot, uint32_t nsects,
7087 uint32_t flags, uint32_t object_size,
7088 bool verbose) {
7089 uint64_t expected_cmdsize;
7090 if (cmd == MachO::LC_SEGMENT) {
7091 outs() << " cmd LC_SEGMENT\n";
7092 expected_cmdsize = nsects;
7093 expected_cmdsize *= sizeof(struct MachO::section);
7094 expected_cmdsize += sizeof(struct MachO::segment_command);
7095 } else {
7096 outs() << " cmd LC_SEGMENT_64\n";
7097 expected_cmdsize = nsects;
7098 expected_cmdsize *= sizeof(struct MachO::section_64);
7099 expected_cmdsize += sizeof(struct MachO::segment_command_64);
7100 }
7101 outs() << " cmdsize " << cmdsize;
7102 if (cmdsize != expected_cmdsize)
7103 outs() << " Inconsistent size\n";
7104 else
7105 outs() << "\n";
7106 outs() << " segname " << SegName << "\n";
7107 if (cmd == MachO::LC_SEGMENT_64) {
7108 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
7109 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
7110 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00007111 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
7112 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00007113 }
7114 outs() << " fileoff " << fileoff;
7115 if (fileoff > object_size)
7116 outs() << " (past end of file)\n";
7117 else
7118 outs() << "\n";
7119 outs() << " filesize " << filesize;
7120 if (fileoff + filesize > object_size)
7121 outs() << " (past end of file)\n";
7122 else
7123 outs() << "\n";
7124 if (verbose) {
7125 if ((maxprot &
7126 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7127 MachO::VM_PROT_EXECUTE)) != 0)
7128 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
7129 else {
7130 if (maxprot & MachO::VM_PROT_READ)
7131 outs() << " maxprot r";
7132 else
7133 outs() << " maxprot -";
7134 if (maxprot & MachO::VM_PROT_WRITE)
7135 outs() << "w";
7136 else
7137 outs() << "-";
7138 if (maxprot & MachO::VM_PROT_EXECUTE)
7139 outs() << "x\n";
7140 else
7141 outs() << "-\n";
7142 }
7143 if ((initprot &
7144 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7145 MachO::VM_PROT_EXECUTE)) != 0)
7146 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
7147 else {
7148 if (initprot & MachO::VM_PROT_READ)
7149 outs() << " initprot r";
7150 else
7151 outs() << " initprot -";
7152 if (initprot & MachO::VM_PROT_WRITE)
7153 outs() << "w";
7154 else
7155 outs() << "-";
7156 if (initprot & MachO::VM_PROT_EXECUTE)
7157 outs() << "x\n";
7158 else
7159 outs() << "-\n";
7160 }
7161 } else {
7162 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
7163 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
7164 }
7165 outs() << " nsects " << nsects << "\n";
7166 if (verbose) {
7167 outs() << " flags";
7168 if (flags == 0)
7169 outs() << " (none)\n";
7170 else {
7171 if (flags & MachO::SG_HIGHVM) {
7172 outs() << " HIGHVM";
7173 flags &= ~MachO::SG_HIGHVM;
7174 }
7175 if (flags & MachO::SG_FVMLIB) {
7176 outs() << " FVMLIB";
7177 flags &= ~MachO::SG_FVMLIB;
7178 }
7179 if (flags & MachO::SG_NORELOC) {
7180 outs() << " NORELOC";
7181 flags &= ~MachO::SG_NORELOC;
7182 }
7183 if (flags & MachO::SG_PROTECTED_VERSION_1) {
7184 outs() << " PROTECTED_VERSION_1";
7185 flags &= ~MachO::SG_PROTECTED_VERSION_1;
7186 }
7187 if (flags)
7188 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
7189 else
7190 outs() << "\n";
7191 }
7192 } else {
7193 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
7194 }
7195}
7196
7197static void PrintSection(const char *sectname, const char *segname,
7198 uint64_t addr, uint64_t size, uint32_t offset,
7199 uint32_t align, uint32_t reloff, uint32_t nreloc,
7200 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
7201 uint32_t cmd, const char *sg_segname,
7202 uint32_t filetype, uint32_t object_size,
7203 bool verbose) {
7204 outs() << "Section\n";
7205 outs() << " sectname " << format("%.16s\n", sectname);
7206 outs() << " segname " << format("%.16s", segname);
7207 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
7208 outs() << " (does not match segment)\n";
7209 else
7210 outs() << "\n";
7211 if (cmd == MachO::LC_SEGMENT_64) {
7212 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
7213 outs() << " size " << format("0x%016" PRIx64, size);
7214 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00007215 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
7216 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00007217 }
7218 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
7219 outs() << " (past end of file)\n";
7220 else
7221 outs() << "\n";
7222 outs() << " offset " << offset;
7223 if (offset > object_size)
7224 outs() << " (past end of file)\n";
7225 else
7226 outs() << "\n";
7227 uint32_t align_shifted = 1 << align;
7228 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
7229 outs() << " reloff " << reloff;
7230 if (reloff > object_size)
7231 outs() << " (past end of file)\n";
7232 else
7233 outs() << "\n";
7234 outs() << " nreloc " << nreloc;
7235 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
7236 outs() << " (past end of file)\n";
7237 else
7238 outs() << "\n";
7239 uint32_t section_type = flags & MachO::SECTION_TYPE;
7240 if (verbose) {
7241 outs() << " type";
7242 if (section_type == MachO::S_REGULAR)
7243 outs() << " S_REGULAR\n";
7244 else if (section_type == MachO::S_ZEROFILL)
7245 outs() << " S_ZEROFILL\n";
7246 else if (section_type == MachO::S_CSTRING_LITERALS)
7247 outs() << " S_CSTRING_LITERALS\n";
7248 else if (section_type == MachO::S_4BYTE_LITERALS)
7249 outs() << " S_4BYTE_LITERALS\n";
7250 else if (section_type == MachO::S_8BYTE_LITERALS)
7251 outs() << " S_8BYTE_LITERALS\n";
7252 else if (section_type == MachO::S_16BYTE_LITERALS)
7253 outs() << " S_16BYTE_LITERALS\n";
7254 else if (section_type == MachO::S_LITERAL_POINTERS)
7255 outs() << " S_LITERAL_POINTERS\n";
7256 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
7257 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
7258 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
7259 outs() << " S_LAZY_SYMBOL_POINTERS\n";
7260 else if (section_type == MachO::S_SYMBOL_STUBS)
7261 outs() << " S_SYMBOL_STUBS\n";
7262 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
7263 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
7264 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
7265 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
7266 else if (section_type == MachO::S_COALESCED)
7267 outs() << " S_COALESCED\n";
7268 else if (section_type == MachO::S_INTERPOSING)
7269 outs() << " S_INTERPOSING\n";
7270 else if (section_type == MachO::S_DTRACE_DOF)
7271 outs() << " S_DTRACE_DOF\n";
7272 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
7273 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
7274 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
7275 outs() << " S_THREAD_LOCAL_REGULAR\n";
7276 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
7277 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
7278 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
7279 outs() << " S_THREAD_LOCAL_VARIABLES\n";
7280 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7281 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
7282 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
7283 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
7284 else
7285 outs() << format("0x%08" PRIx32, section_type) << "\n";
7286 outs() << "attributes";
7287 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
7288 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
7289 outs() << " PURE_INSTRUCTIONS";
7290 if (section_attributes & MachO::S_ATTR_NO_TOC)
7291 outs() << " NO_TOC";
7292 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
7293 outs() << " STRIP_STATIC_SYMS";
7294 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
7295 outs() << " NO_DEAD_STRIP";
7296 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
7297 outs() << " LIVE_SUPPORT";
7298 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
7299 outs() << " SELF_MODIFYING_CODE";
7300 if (section_attributes & MachO::S_ATTR_DEBUG)
7301 outs() << " DEBUG";
7302 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
7303 outs() << " SOME_INSTRUCTIONS";
7304 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
7305 outs() << " EXT_RELOC";
7306 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
7307 outs() << " LOC_RELOC";
7308 if (section_attributes == 0)
7309 outs() << " (none)";
7310 outs() << "\n";
7311 } else
7312 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
7313 outs() << " reserved1 " << reserved1;
7314 if (section_type == MachO::S_SYMBOL_STUBS ||
7315 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
7316 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
7317 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
7318 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7319 outs() << " (index into indirect symbol table)\n";
7320 else
7321 outs() << "\n";
7322 outs() << " reserved2 " << reserved2;
7323 if (section_type == MachO::S_SYMBOL_STUBS)
7324 outs() << " (size of stubs)\n";
7325 else
7326 outs() << "\n";
7327}
7328
David Majnemer73cc6ff2014-11-13 19:48:56 +00007329static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00007330 uint32_t object_size) {
7331 outs() << " cmd LC_SYMTAB\n";
7332 outs() << " cmdsize " << st.cmdsize;
7333 if (st.cmdsize != sizeof(struct MachO::symtab_command))
7334 outs() << " Incorrect size\n";
7335 else
7336 outs() << "\n";
7337 outs() << " symoff " << st.symoff;
7338 if (st.symoff > object_size)
7339 outs() << " (past end of file)\n";
7340 else
7341 outs() << "\n";
7342 outs() << " nsyms " << st.nsyms;
7343 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00007344 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007345 big_size = st.nsyms;
7346 big_size *= sizeof(struct MachO::nlist_64);
7347 big_size += st.symoff;
7348 if (big_size > object_size)
7349 outs() << " (past end of file)\n";
7350 else
7351 outs() << "\n";
7352 } else {
7353 big_size = st.nsyms;
7354 big_size *= sizeof(struct MachO::nlist);
7355 big_size += st.symoff;
7356 if (big_size > object_size)
7357 outs() << " (past end of file)\n";
7358 else
7359 outs() << "\n";
7360 }
7361 outs() << " stroff " << st.stroff;
7362 if (st.stroff > object_size)
7363 outs() << " (past end of file)\n";
7364 else
7365 outs() << "\n";
7366 outs() << " strsize " << st.strsize;
7367 big_size = st.stroff;
7368 big_size += st.strsize;
7369 if (big_size > object_size)
7370 outs() << " (past end of file)\n";
7371 else
7372 outs() << "\n";
7373}
7374
7375static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
7376 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00007377 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007378 outs() << " cmd LC_DYSYMTAB\n";
7379 outs() << " cmdsize " << dyst.cmdsize;
7380 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
7381 outs() << " Incorrect size\n";
7382 else
7383 outs() << "\n";
7384 outs() << " ilocalsym " << dyst.ilocalsym;
7385 if (dyst.ilocalsym > nsyms)
7386 outs() << " (greater than the number of symbols)\n";
7387 else
7388 outs() << "\n";
7389 outs() << " nlocalsym " << dyst.nlocalsym;
7390 uint64_t big_size;
7391 big_size = dyst.ilocalsym;
7392 big_size += dyst.nlocalsym;
7393 if (big_size > nsyms)
7394 outs() << " (past the end of the symbol table)\n";
7395 else
7396 outs() << "\n";
7397 outs() << " iextdefsym " << dyst.iextdefsym;
7398 if (dyst.iextdefsym > nsyms)
7399 outs() << " (greater than the number of symbols)\n";
7400 else
7401 outs() << "\n";
7402 outs() << " nextdefsym " << dyst.nextdefsym;
7403 big_size = dyst.iextdefsym;
7404 big_size += dyst.nextdefsym;
7405 if (big_size > nsyms)
7406 outs() << " (past the end of the symbol table)\n";
7407 else
7408 outs() << "\n";
7409 outs() << " iundefsym " << dyst.iundefsym;
7410 if (dyst.iundefsym > nsyms)
7411 outs() << " (greater than the number of symbols)\n";
7412 else
7413 outs() << "\n";
7414 outs() << " nundefsym " << dyst.nundefsym;
7415 big_size = dyst.iundefsym;
7416 big_size += dyst.nundefsym;
7417 if (big_size > nsyms)
7418 outs() << " (past the end of the symbol table)\n";
7419 else
7420 outs() << "\n";
7421 outs() << " tocoff " << dyst.tocoff;
7422 if (dyst.tocoff > object_size)
7423 outs() << " (past end of file)\n";
7424 else
7425 outs() << "\n";
7426 outs() << " ntoc " << dyst.ntoc;
7427 big_size = dyst.ntoc;
7428 big_size *= sizeof(struct MachO::dylib_table_of_contents);
7429 big_size += dyst.tocoff;
7430 if (big_size > object_size)
7431 outs() << " (past end of file)\n";
7432 else
7433 outs() << "\n";
7434 outs() << " modtaboff " << dyst.modtaboff;
7435 if (dyst.modtaboff > object_size)
7436 outs() << " (past end of file)\n";
7437 else
7438 outs() << "\n";
7439 outs() << " nmodtab " << dyst.nmodtab;
7440 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00007441 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007442 modtabend = dyst.nmodtab;
7443 modtabend *= sizeof(struct MachO::dylib_module_64);
7444 modtabend += dyst.modtaboff;
7445 } else {
7446 modtabend = dyst.nmodtab;
7447 modtabend *= sizeof(struct MachO::dylib_module);
7448 modtabend += dyst.modtaboff;
7449 }
7450 if (modtabend > object_size)
7451 outs() << " (past end of file)\n";
7452 else
7453 outs() << "\n";
7454 outs() << " extrefsymoff " << dyst.extrefsymoff;
7455 if (dyst.extrefsymoff > object_size)
7456 outs() << " (past end of file)\n";
7457 else
7458 outs() << "\n";
7459 outs() << " nextrefsyms " << dyst.nextrefsyms;
7460 big_size = dyst.nextrefsyms;
7461 big_size *= sizeof(struct MachO::dylib_reference);
7462 big_size += dyst.extrefsymoff;
7463 if (big_size > object_size)
7464 outs() << " (past end of file)\n";
7465 else
7466 outs() << "\n";
7467 outs() << " indirectsymoff " << dyst.indirectsymoff;
7468 if (dyst.indirectsymoff > object_size)
7469 outs() << " (past end of file)\n";
7470 else
7471 outs() << "\n";
7472 outs() << " nindirectsyms " << dyst.nindirectsyms;
7473 big_size = dyst.nindirectsyms;
7474 big_size *= sizeof(uint32_t);
7475 big_size += dyst.indirectsymoff;
7476 if (big_size > object_size)
7477 outs() << " (past end of file)\n";
7478 else
7479 outs() << "\n";
7480 outs() << " extreloff " << dyst.extreloff;
7481 if (dyst.extreloff > object_size)
7482 outs() << " (past end of file)\n";
7483 else
7484 outs() << "\n";
7485 outs() << " nextrel " << dyst.nextrel;
7486 big_size = dyst.nextrel;
7487 big_size *= sizeof(struct MachO::relocation_info);
7488 big_size += dyst.extreloff;
7489 if (big_size > object_size)
7490 outs() << " (past end of file)\n";
7491 else
7492 outs() << "\n";
7493 outs() << " locreloff " << dyst.locreloff;
7494 if (dyst.locreloff > object_size)
7495 outs() << " (past end of file)\n";
7496 else
7497 outs() << "\n";
7498 outs() << " nlocrel " << dyst.nlocrel;
7499 big_size = dyst.nlocrel;
7500 big_size *= sizeof(struct MachO::relocation_info);
7501 big_size += dyst.locreloff;
7502 if (big_size > object_size)
7503 outs() << " (past end of file)\n";
7504 else
7505 outs() << "\n";
7506}
7507
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007508static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
7509 uint32_t object_size) {
7510 if (dc.cmd == MachO::LC_DYLD_INFO)
7511 outs() << " cmd LC_DYLD_INFO\n";
7512 else
7513 outs() << " cmd LC_DYLD_INFO_ONLY\n";
7514 outs() << " cmdsize " << dc.cmdsize;
7515 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
7516 outs() << " Incorrect size\n";
7517 else
7518 outs() << "\n";
7519 outs() << " rebase_off " << dc.rebase_off;
7520 if (dc.rebase_off > object_size)
7521 outs() << " (past end of file)\n";
7522 else
7523 outs() << "\n";
7524 outs() << " rebase_size " << dc.rebase_size;
7525 uint64_t big_size;
7526 big_size = dc.rebase_off;
7527 big_size += dc.rebase_size;
7528 if (big_size > object_size)
7529 outs() << " (past end of file)\n";
7530 else
7531 outs() << "\n";
7532 outs() << " bind_off " << dc.bind_off;
7533 if (dc.bind_off > object_size)
7534 outs() << " (past end of file)\n";
7535 else
7536 outs() << "\n";
7537 outs() << " bind_size " << dc.bind_size;
7538 big_size = dc.bind_off;
7539 big_size += dc.bind_size;
7540 if (big_size > object_size)
7541 outs() << " (past end of file)\n";
7542 else
7543 outs() << "\n";
7544 outs() << " weak_bind_off " << dc.weak_bind_off;
7545 if (dc.weak_bind_off > object_size)
7546 outs() << " (past end of file)\n";
7547 else
7548 outs() << "\n";
7549 outs() << " weak_bind_size " << dc.weak_bind_size;
7550 big_size = dc.weak_bind_off;
7551 big_size += dc.weak_bind_size;
7552 if (big_size > object_size)
7553 outs() << " (past end of file)\n";
7554 else
7555 outs() << "\n";
7556 outs() << " lazy_bind_off " << dc.lazy_bind_off;
7557 if (dc.lazy_bind_off > object_size)
7558 outs() << " (past end of file)\n";
7559 else
7560 outs() << "\n";
7561 outs() << " lazy_bind_size " << dc.lazy_bind_size;
7562 big_size = dc.lazy_bind_off;
7563 big_size += dc.lazy_bind_size;
7564 if (big_size > object_size)
7565 outs() << " (past end of file)\n";
7566 else
7567 outs() << "\n";
7568 outs() << " export_off " << dc.export_off;
7569 if (dc.export_off > object_size)
7570 outs() << " (past end of file)\n";
7571 else
7572 outs() << "\n";
7573 outs() << " export_size " << dc.export_size;
7574 big_size = dc.export_off;
7575 big_size += dc.export_size;
7576 if (big_size > object_size)
7577 outs() << " (past end of file)\n";
7578 else
7579 outs() << "\n";
7580}
7581
7582static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
7583 const char *Ptr) {
7584 if (dyld.cmd == MachO::LC_ID_DYLINKER)
7585 outs() << " cmd LC_ID_DYLINKER\n";
7586 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
7587 outs() << " cmd LC_LOAD_DYLINKER\n";
7588 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
7589 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
7590 else
7591 outs() << " cmd ?(" << dyld.cmd << ")\n";
7592 outs() << " cmdsize " << dyld.cmdsize;
7593 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
7594 outs() << " Incorrect size\n";
7595 else
7596 outs() << "\n";
7597 if (dyld.name >= dyld.cmdsize)
7598 outs() << " name ?(bad offset " << dyld.name << ")\n";
7599 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007600 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007601 outs() << " name " << P << " (offset " << dyld.name << ")\n";
7602 }
7603}
7604
7605static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
7606 outs() << " cmd LC_UUID\n";
7607 outs() << " cmdsize " << uuid.cmdsize;
7608 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
7609 outs() << " Incorrect size\n";
7610 else
7611 outs() << "\n";
7612 outs() << " uuid ";
7613 outs() << format("%02" PRIX32, uuid.uuid[0]);
7614 outs() << format("%02" PRIX32, uuid.uuid[1]);
7615 outs() << format("%02" PRIX32, uuid.uuid[2]);
7616 outs() << format("%02" PRIX32, uuid.uuid[3]);
7617 outs() << "-";
7618 outs() << format("%02" PRIX32, uuid.uuid[4]);
7619 outs() << format("%02" PRIX32, uuid.uuid[5]);
7620 outs() << "-";
7621 outs() << format("%02" PRIX32, uuid.uuid[6]);
7622 outs() << format("%02" PRIX32, uuid.uuid[7]);
7623 outs() << "-";
7624 outs() << format("%02" PRIX32, uuid.uuid[8]);
7625 outs() << format("%02" PRIX32, uuid.uuid[9]);
7626 outs() << "-";
7627 outs() << format("%02" PRIX32, uuid.uuid[10]);
7628 outs() << format("%02" PRIX32, uuid.uuid[11]);
7629 outs() << format("%02" PRIX32, uuid.uuid[12]);
7630 outs() << format("%02" PRIX32, uuid.uuid[13]);
7631 outs() << format("%02" PRIX32, uuid.uuid[14]);
7632 outs() << format("%02" PRIX32, uuid.uuid[15]);
7633 outs() << "\n";
7634}
7635
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007636static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00007637 outs() << " cmd LC_RPATH\n";
7638 outs() << " cmdsize " << rpath.cmdsize;
7639 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
7640 outs() << " Incorrect size\n";
7641 else
7642 outs() << "\n";
7643 if (rpath.path >= rpath.cmdsize)
7644 outs() << " path ?(bad offset " << rpath.path << ")\n";
7645 else {
7646 const char *P = (const char *)(Ptr) + rpath.path;
7647 outs() << " path " << P << " (offset " << rpath.path << ")\n";
7648 }
7649}
7650
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007651static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
7652 if (vd.cmd == MachO::LC_VERSION_MIN_MACOSX)
7653 outs() << " cmd LC_VERSION_MIN_MACOSX\n";
7654 else if (vd.cmd == MachO::LC_VERSION_MIN_IPHONEOS)
7655 outs() << " cmd LC_VERSION_MIN_IPHONEOS\n";
7656 else
7657 outs() << " cmd " << vd.cmd << " (?)\n";
7658 outs() << " cmdsize " << vd.cmdsize;
7659 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
7660 outs() << " Incorrect size\n";
7661 else
7662 outs() << "\n";
7663 outs() << " version " << ((vd.version >> 16) & 0xffff) << "."
7664 << ((vd.version >> 8) & 0xff);
7665 if ((vd.version & 0xff) != 0)
7666 outs() << "." << (vd.version & 0xff);
7667 outs() << "\n";
7668 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00007669 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007670 else {
7671 outs() << " sdk " << ((vd.sdk >> 16) & 0xffff) << "."
7672 << ((vd.sdk >> 8) & 0xff);
7673 }
7674 if ((vd.sdk & 0xff) != 0)
7675 outs() << "." << (vd.sdk & 0xff);
7676 outs() << "\n";
7677}
7678
7679static void PrintSourceVersionCommand(MachO::source_version_command sd) {
7680 outs() << " cmd LC_SOURCE_VERSION\n";
7681 outs() << " cmdsize " << sd.cmdsize;
7682 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
7683 outs() << " Incorrect size\n";
7684 else
7685 outs() << "\n";
7686 uint64_t a = (sd.version >> 40) & 0xffffff;
7687 uint64_t b = (sd.version >> 30) & 0x3ff;
7688 uint64_t c = (sd.version >> 20) & 0x3ff;
7689 uint64_t d = (sd.version >> 10) & 0x3ff;
7690 uint64_t e = sd.version & 0x3ff;
7691 outs() << " version " << a << "." << b;
7692 if (e != 0)
7693 outs() << "." << c << "." << d << "." << e;
7694 else if (d != 0)
7695 outs() << "." << c << "." << d;
7696 else if (c != 0)
7697 outs() << "." << c;
7698 outs() << "\n";
7699}
7700
7701static void PrintEntryPointCommand(MachO::entry_point_command ep) {
7702 outs() << " cmd LC_MAIN\n";
7703 outs() << " cmdsize " << ep.cmdsize;
7704 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
7705 outs() << " Incorrect size\n";
7706 else
7707 outs() << "\n";
7708 outs() << " entryoff " << ep.entryoff << "\n";
7709 outs() << " stacksize " << ep.stacksize << "\n";
7710}
7711
Kevin Enderby0804f4672014-12-16 23:25:52 +00007712static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
7713 uint32_t object_size) {
7714 outs() << " cmd LC_ENCRYPTION_INFO\n";
7715 outs() << " cmdsize " << ec.cmdsize;
7716 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
7717 outs() << " Incorrect size\n";
7718 else
7719 outs() << "\n";
7720 outs() << " cryptoff " << ec.cryptoff;
7721 if (ec.cryptoff > object_size)
7722 outs() << " (past end of file)\n";
7723 else
7724 outs() << "\n";
7725 outs() << " cryptsize " << ec.cryptsize;
7726 if (ec.cryptsize > object_size)
7727 outs() << " (past end of file)\n";
7728 else
7729 outs() << "\n";
7730 outs() << " cryptid " << ec.cryptid << "\n";
7731}
7732
Kevin Enderby57538292014-12-17 01:01:30 +00007733static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007734 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00007735 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
7736 outs() << " cmdsize " << ec.cmdsize;
7737 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
7738 outs() << " Incorrect size\n";
7739 else
7740 outs() << "\n";
7741 outs() << " cryptoff " << ec.cryptoff;
7742 if (ec.cryptoff > object_size)
7743 outs() << " (past end of file)\n";
7744 else
7745 outs() << "\n";
7746 outs() << " cryptsize " << ec.cryptsize;
7747 if (ec.cryptsize > object_size)
7748 outs() << " (past end of file)\n";
7749 else
7750 outs() << "\n";
7751 outs() << " cryptid " << ec.cryptid << "\n";
7752 outs() << " pad " << ec.pad << "\n";
7753}
7754
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00007755static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
7756 const char *Ptr) {
7757 outs() << " cmd LC_LINKER_OPTION\n";
7758 outs() << " cmdsize " << lo.cmdsize;
7759 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
7760 outs() << " Incorrect size\n";
7761 else
7762 outs() << "\n";
7763 outs() << " count " << lo.count << "\n";
7764 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
7765 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
7766 uint32_t i = 0;
7767 while (left > 0) {
7768 while (*string == '\0' && left > 0) {
7769 string++;
7770 left--;
7771 }
7772 if (left > 0) {
7773 i++;
7774 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00007775 uint32_t NullPos = StringRef(string, left).find('\0');
7776 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00007777 string += len;
7778 left -= len;
7779 }
7780 }
7781 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007782 outs() << " count " << lo.count << " does not match number of strings "
7783 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00007784}
7785
Kevin Enderbyb4b79312014-12-18 19:24:35 +00007786static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
7787 const char *Ptr) {
7788 outs() << " cmd LC_SUB_FRAMEWORK\n";
7789 outs() << " cmdsize " << sub.cmdsize;
7790 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
7791 outs() << " Incorrect size\n";
7792 else
7793 outs() << "\n";
7794 if (sub.umbrella < sub.cmdsize) {
7795 const char *P = Ptr + sub.umbrella;
7796 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
7797 } else {
7798 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
7799 }
7800}
7801
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00007802static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
7803 const char *Ptr) {
7804 outs() << " cmd LC_SUB_UMBRELLA\n";
7805 outs() << " cmdsize " << sub.cmdsize;
7806 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
7807 outs() << " Incorrect size\n";
7808 else
7809 outs() << "\n";
7810 if (sub.sub_umbrella < sub.cmdsize) {
7811 const char *P = Ptr + sub.sub_umbrella;
7812 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
7813 } else {
7814 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
7815 }
7816}
7817
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00007818static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007819 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00007820 outs() << " cmd LC_SUB_LIBRARY\n";
7821 outs() << " cmdsize " << sub.cmdsize;
7822 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
7823 outs() << " Incorrect size\n";
7824 else
7825 outs() << "\n";
7826 if (sub.sub_library < sub.cmdsize) {
7827 const char *P = Ptr + sub.sub_library;
7828 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
7829 } else {
7830 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
7831 }
7832}
7833
Kevin Enderby186eac32014-12-19 21:06:24 +00007834static void PrintSubClientCommand(MachO::sub_client_command sub,
7835 const char *Ptr) {
7836 outs() << " cmd LC_SUB_CLIENT\n";
7837 outs() << " cmdsize " << sub.cmdsize;
7838 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
7839 outs() << " Incorrect size\n";
7840 else
7841 outs() << "\n";
7842 if (sub.client < sub.cmdsize) {
7843 const char *P = Ptr + sub.client;
7844 outs() << " client " << P << " (offset " << sub.client << ")\n";
7845 } else {
7846 outs() << " client ?(bad offset " << sub.client << ")\n";
7847 }
7848}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00007849
Kevin Enderby52e4ce42014-12-19 22:25:22 +00007850static void PrintRoutinesCommand(MachO::routines_command r) {
7851 outs() << " cmd LC_ROUTINES\n";
7852 outs() << " cmdsize " << r.cmdsize;
7853 if (r.cmdsize != sizeof(struct MachO::routines_command))
7854 outs() << " Incorrect size\n";
7855 else
7856 outs() << "\n";
7857 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
7858 outs() << " init_module " << r.init_module << "\n";
7859 outs() << " reserved1 " << r.reserved1 << "\n";
7860 outs() << " reserved2 " << r.reserved2 << "\n";
7861 outs() << " reserved3 " << r.reserved3 << "\n";
7862 outs() << " reserved4 " << r.reserved4 << "\n";
7863 outs() << " reserved5 " << r.reserved5 << "\n";
7864 outs() << " reserved6 " << r.reserved6 << "\n";
7865}
7866
7867static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
7868 outs() << " cmd LC_ROUTINES_64\n";
7869 outs() << " cmdsize " << r.cmdsize;
7870 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
7871 outs() << " Incorrect size\n";
7872 else
7873 outs() << "\n";
7874 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
7875 outs() << " init_module " << r.init_module << "\n";
7876 outs() << " reserved1 " << r.reserved1 << "\n";
7877 outs() << " reserved2 " << r.reserved2 << "\n";
7878 outs() << " reserved3 " << r.reserved3 << "\n";
7879 outs() << " reserved4 " << r.reserved4 << "\n";
7880 outs() << " reserved5 " << r.reserved5 << "\n";
7881 outs() << " reserved6 " << r.reserved6 << "\n";
7882}
7883
Kevin Enderby48ef5342014-12-23 22:56:39 +00007884static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
7885 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
7886 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
7887 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
7888 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
7889 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
7890 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
7891 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
7892 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
7893 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
7894 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
7895 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
7896 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
7897 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
7898 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
7899 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
7900 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
7901 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
7902 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
7903 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
7904 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
7905 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
7906}
7907
Kevin Enderby227df342014-12-23 23:43:59 +00007908static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00007909 uint32_t f;
7910 outs() << "\t mmst_reg ";
7911 for (f = 0; f < 10; f++)
7912 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
7913 outs() << "\n";
7914 outs() << "\t mmst_rsrv ";
7915 for (f = 0; f < 6; f++)
7916 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
7917 outs() << "\n";
7918}
7919
Kevin Enderbyaefb0032014-12-24 00:16:51 +00007920static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00007921 uint32_t f;
7922 outs() << "\t xmm_reg ";
7923 for (f = 0; f < 16; f++)
7924 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
7925 outs() << "\n";
7926}
7927
7928static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
7929 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
7930 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
7931 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
7932 outs() << " denorm " << fpu.fpu_fcw.denorm;
7933 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
7934 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
7935 outs() << " undfl " << fpu.fpu_fcw.undfl;
7936 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
7937 outs() << "\t\t pc ";
7938 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
7939 outs() << "FP_PREC_24B ";
7940 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
7941 outs() << "FP_PREC_53B ";
7942 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
7943 outs() << "FP_PREC_64B ";
7944 else
7945 outs() << fpu.fpu_fcw.pc << " ";
7946 outs() << "rc ";
7947 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
7948 outs() << "FP_RND_NEAR ";
7949 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
7950 outs() << "FP_RND_DOWN ";
7951 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
7952 outs() << "FP_RND_UP ";
7953 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007954 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00007955 outs() << "\n";
7956 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
7957 outs() << " denorm " << fpu.fpu_fsw.denorm;
7958 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
7959 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
7960 outs() << " undfl " << fpu.fpu_fsw.undfl;
7961 outs() << " precis " << fpu.fpu_fsw.precis;
7962 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
7963 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
7964 outs() << " c0 " << fpu.fpu_fsw.c0;
7965 outs() << " c1 " << fpu.fpu_fsw.c1;
7966 outs() << " c2 " << fpu.fpu_fsw.c2;
7967 outs() << " tos " << fpu.fpu_fsw.tos;
7968 outs() << " c3 " << fpu.fpu_fsw.c3;
7969 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
7970 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
7971 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
7972 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
7973 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
7974 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
7975 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
7976 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
7977 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
7978 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
7979 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
7980 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
7981 outs() << "\n";
7982 outs() << "\t fpu_stmm0:\n";
7983 Print_mmst_reg(fpu.fpu_stmm0);
7984 outs() << "\t fpu_stmm1:\n";
7985 Print_mmst_reg(fpu.fpu_stmm1);
7986 outs() << "\t fpu_stmm2:\n";
7987 Print_mmst_reg(fpu.fpu_stmm2);
7988 outs() << "\t fpu_stmm3:\n";
7989 Print_mmst_reg(fpu.fpu_stmm3);
7990 outs() << "\t fpu_stmm4:\n";
7991 Print_mmst_reg(fpu.fpu_stmm4);
7992 outs() << "\t fpu_stmm5:\n";
7993 Print_mmst_reg(fpu.fpu_stmm5);
7994 outs() << "\t fpu_stmm6:\n";
7995 Print_mmst_reg(fpu.fpu_stmm6);
7996 outs() << "\t fpu_stmm7:\n";
7997 Print_mmst_reg(fpu.fpu_stmm7);
7998 outs() << "\t fpu_xmm0:\n";
7999 Print_xmm_reg(fpu.fpu_xmm0);
8000 outs() << "\t fpu_xmm1:\n";
8001 Print_xmm_reg(fpu.fpu_xmm1);
8002 outs() << "\t fpu_xmm2:\n";
8003 Print_xmm_reg(fpu.fpu_xmm2);
8004 outs() << "\t fpu_xmm3:\n";
8005 Print_xmm_reg(fpu.fpu_xmm3);
8006 outs() << "\t fpu_xmm4:\n";
8007 Print_xmm_reg(fpu.fpu_xmm4);
8008 outs() << "\t fpu_xmm5:\n";
8009 Print_xmm_reg(fpu.fpu_xmm5);
8010 outs() << "\t fpu_xmm6:\n";
8011 Print_xmm_reg(fpu.fpu_xmm6);
8012 outs() << "\t fpu_xmm7:\n";
8013 Print_xmm_reg(fpu.fpu_xmm7);
8014 outs() << "\t fpu_xmm8:\n";
8015 Print_xmm_reg(fpu.fpu_xmm8);
8016 outs() << "\t fpu_xmm9:\n";
8017 Print_xmm_reg(fpu.fpu_xmm9);
8018 outs() << "\t fpu_xmm10:\n";
8019 Print_xmm_reg(fpu.fpu_xmm10);
8020 outs() << "\t fpu_xmm11:\n";
8021 Print_xmm_reg(fpu.fpu_xmm11);
8022 outs() << "\t fpu_xmm12:\n";
8023 Print_xmm_reg(fpu.fpu_xmm12);
8024 outs() << "\t fpu_xmm13:\n";
8025 Print_xmm_reg(fpu.fpu_xmm13);
8026 outs() << "\t fpu_xmm14:\n";
8027 Print_xmm_reg(fpu.fpu_xmm14);
8028 outs() << "\t fpu_xmm15:\n";
8029 Print_xmm_reg(fpu.fpu_xmm15);
8030 outs() << "\t fpu_rsrv4:\n";
8031 for (uint32_t f = 0; f < 6; f++) {
8032 outs() << "\t ";
8033 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008034 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008035 outs() << "\n";
8036 }
8037 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
8038 outs() << "\n";
8039}
8040
8041static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
8042 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
8043 outs() << " err " << format("0x%08" PRIx32, exc64.err);
8044 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
8045}
8046
8047static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
8048 bool isLittleEndian, uint32_t cputype) {
8049 if (t.cmd == MachO::LC_THREAD)
8050 outs() << " cmd LC_THREAD\n";
8051 else if (t.cmd == MachO::LC_UNIXTHREAD)
8052 outs() << " cmd LC_UNIXTHREAD\n";
8053 else
8054 outs() << " cmd " << t.cmd << " (unknown)\n";
8055 outs() << " cmdsize " << t.cmdsize;
8056 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
8057 outs() << " Incorrect size\n";
8058 else
8059 outs() << "\n";
8060
8061 const char *begin = Ptr + sizeof(struct MachO::thread_command);
8062 const char *end = Ptr + t.cmdsize;
8063 uint32_t flavor, count, left;
8064 if (cputype == MachO::CPU_TYPE_X86_64) {
8065 while (begin < end) {
8066 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8067 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8068 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008069 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008070 flavor = 0;
8071 begin = end;
8072 }
8073 if (isLittleEndian != sys::IsLittleEndianHost)
8074 sys::swapByteOrder(flavor);
8075 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8076 memcpy((char *)&count, begin, sizeof(uint32_t));
8077 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008078 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008079 count = 0;
8080 begin = end;
8081 }
8082 if (isLittleEndian != sys::IsLittleEndianHost)
8083 sys::swapByteOrder(count);
8084 if (flavor == MachO::x86_THREAD_STATE64) {
8085 outs() << " flavor x86_THREAD_STATE64\n";
8086 if (count == MachO::x86_THREAD_STATE64_COUNT)
8087 outs() << " count x86_THREAD_STATE64_COUNT\n";
8088 else
8089 outs() << " count " << count
8090 << " (not x86_THREAD_STATE64_COUNT)\n";
8091 MachO::x86_thread_state64_t cpu64;
8092 left = end - begin;
8093 if (left >= sizeof(MachO::x86_thread_state64_t)) {
8094 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
8095 begin += sizeof(MachO::x86_thread_state64_t);
8096 } else {
8097 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
8098 memcpy(&cpu64, begin, left);
8099 begin += left;
8100 }
8101 if (isLittleEndian != sys::IsLittleEndianHost)
8102 swapStruct(cpu64);
8103 Print_x86_thread_state64_t(cpu64);
8104 } else if (flavor == MachO::x86_THREAD_STATE) {
8105 outs() << " flavor x86_THREAD_STATE\n";
8106 if (count == MachO::x86_THREAD_STATE_COUNT)
8107 outs() << " count x86_THREAD_STATE_COUNT\n";
8108 else
8109 outs() << " count " << count
8110 << " (not x86_THREAD_STATE_COUNT)\n";
8111 struct MachO::x86_thread_state_t ts;
8112 left = end - begin;
8113 if (left >= sizeof(MachO::x86_thread_state_t)) {
8114 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
8115 begin += sizeof(MachO::x86_thread_state_t);
8116 } else {
8117 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
8118 memcpy(&ts, begin, left);
8119 begin += left;
8120 }
8121 if (isLittleEndian != sys::IsLittleEndianHost)
8122 swapStruct(ts);
8123 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
8124 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
8125 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
8126 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
8127 else
8128 outs() << "tsh.count " << ts.tsh.count
8129 << " (not x86_THREAD_STATE64_COUNT\n";
8130 Print_x86_thread_state64_t(ts.uts.ts64);
8131 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008132 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
8133 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008134 }
8135 } else if (flavor == MachO::x86_FLOAT_STATE) {
8136 outs() << " flavor x86_FLOAT_STATE\n";
8137 if (count == MachO::x86_FLOAT_STATE_COUNT)
8138 outs() << " count x86_FLOAT_STATE_COUNT\n";
8139 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008140 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008141 struct MachO::x86_float_state_t fs;
8142 left = end - begin;
8143 if (left >= sizeof(MachO::x86_float_state_t)) {
8144 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
8145 begin += sizeof(MachO::x86_float_state_t);
8146 } else {
8147 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
8148 memcpy(&fs, begin, left);
8149 begin += left;
8150 }
8151 if (isLittleEndian != sys::IsLittleEndianHost)
8152 swapStruct(fs);
8153 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
8154 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008155 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008156 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
8157 else
8158 outs() << "fsh.count " << fs.fsh.count
8159 << " (not x86_FLOAT_STATE64_COUNT\n";
8160 Print_x86_float_state_t(fs.ufs.fs64);
8161 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008162 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
8163 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008164 }
8165 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
8166 outs() << " flavor x86_EXCEPTION_STATE\n";
8167 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
8168 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
8169 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008170 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00008171 << " (not x86_EXCEPTION_STATE_COUNT)\n";
8172 struct MachO::x86_exception_state_t es;
8173 left = end - begin;
8174 if (left >= sizeof(MachO::x86_exception_state_t)) {
8175 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
8176 begin += sizeof(MachO::x86_exception_state_t);
8177 } else {
8178 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
8179 memcpy(&es, begin, left);
8180 begin += left;
8181 }
8182 if (isLittleEndian != sys::IsLittleEndianHost)
8183 swapStruct(es);
8184 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
8185 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008186 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008187 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
8188 else
8189 outs() << "\t esh.count " << es.esh.count
8190 << " (not x86_EXCEPTION_STATE64_COUNT\n";
8191 Print_x86_exception_state_t(es.ues.es64);
8192 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008193 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
8194 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008195 }
8196 } else {
8197 outs() << " flavor " << flavor << " (unknown)\n";
8198 outs() << " count " << count << "\n";
8199 outs() << " state (unknown)\n";
8200 begin += count * sizeof(uint32_t);
8201 }
8202 }
8203 } else {
8204 while (begin < end) {
8205 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8206 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8207 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008208 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008209 flavor = 0;
8210 begin = end;
8211 }
8212 if (isLittleEndian != sys::IsLittleEndianHost)
8213 sys::swapByteOrder(flavor);
8214 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8215 memcpy((char *)&count, begin, sizeof(uint32_t));
8216 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008217 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008218 count = 0;
8219 begin = end;
8220 }
8221 if (isLittleEndian != sys::IsLittleEndianHost)
8222 sys::swapByteOrder(count);
8223 outs() << " flavor " << flavor << "\n";
8224 outs() << " count " << count << "\n";
8225 outs() << " state (Unknown cputype/cpusubtype)\n";
8226 begin += count * sizeof(uint32_t);
8227 }
8228 }
8229}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008230
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008231static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
8232 if (dl.cmd == MachO::LC_ID_DYLIB)
8233 outs() << " cmd LC_ID_DYLIB\n";
8234 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
8235 outs() << " cmd LC_LOAD_DYLIB\n";
8236 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
8237 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
8238 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
8239 outs() << " cmd LC_REEXPORT_DYLIB\n";
8240 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
8241 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
8242 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
8243 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
8244 else
8245 outs() << " cmd " << dl.cmd << " (unknown)\n";
8246 outs() << " cmdsize " << dl.cmdsize;
8247 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
8248 outs() << " Incorrect size\n";
8249 else
8250 outs() << "\n";
8251 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008252 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008253 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
8254 } else {
8255 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
8256 }
8257 outs() << " time stamp " << dl.dylib.timestamp << " ";
8258 time_t t = dl.dylib.timestamp;
8259 outs() << ctime(&t);
8260 outs() << " current version ";
8261 if (dl.dylib.current_version == 0xffffffff)
8262 outs() << "n/a\n";
8263 else
8264 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
8265 << ((dl.dylib.current_version >> 8) & 0xff) << "."
8266 << (dl.dylib.current_version & 0xff) << "\n";
8267 outs() << "compatibility version ";
8268 if (dl.dylib.compatibility_version == 0xffffffff)
8269 outs() << "n/a\n";
8270 else
8271 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
8272 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
8273 << (dl.dylib.compatibility_version & 0xff) << "\n";
8274}
8275
8276static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
8277 uint32_t object_size) {
8278 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
8279 outs() << " cmd LC_FUNCTION_STARTS\n";
8280 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
8281 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
8282 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
8283 outs() << " cmd LC_FUNCTION_STARTS\n";
8284 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
8285 outs() << " cmd LC_DATA_IN_CODE\n";
8286 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
8287 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
8288 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
8289 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
8290 else
8291 outs() << " cmd " << ld.cmd << " (?)\n";
8292 outs() << " cmdsize " << ld.cmdsize;
8293 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
8294 outs() << " Incorrect size\n";
8295 else
8296 outs() << "\n";
8297 outs() << " dataoff " << ld.dataoff;
8298 if (ld.dataoff > object_size)
8299 outs() << " (past end of file)\n";
8300 else
8301 outs() << "\n";
8302 outs() << " datasize " << ld.datasize;
8303 uint64_t big_size = ld.dataoff;
8304 big_size += ld.datasize;
8305 if (big_size > object_size)
8306 outs() << " (past end of file)\n";
8307 else
8308 outs() << "\n";
8309}
8310
Kevin Enderby956366c2014-08-29 22:30:52 +00008311static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t ncmds,
8312 uint32_t filetype, uint32_t cputype,
8313 bool verbose) {
Filipe Cabecinhase71bd0c2015-01-06 17:08:26 +00008314 if (ncmds == 0)
8315 return;
Kevin Enderby956366c2014-08-29 22:30:52 +00008316 StringRef Buf = Obj->getData();
8317 MachOObjectFile::LoadCommandInfo Command = Obj->getFirstLoadCommandInfo();
8318 for (unsigned i = 0;; ++i) {
8319 outs() << "Load command " << i << "\n";
8320 if (Command.C.cmd == MachO::LC_SEGMENT) {
8321 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
8322 const char *sg_segname = SLC.segname;
8323 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
8324 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
8325 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
8326 verbose);
8327 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00008328 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00008329 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
8330 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
8331 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
8332 }
8333 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
8334 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
8335 const char *sg_segname = SLC_64.segname;
8336 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
8337 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
8338 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
8339 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
8340 for (unsigned j = 0; j < SLC_64.nsects; j++) {
8341 MachO::section_64 S_64 = Obj->getSection64(Command, j);
8342 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
8343 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
8344 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
8345 sg_segname, filetype, Buf.size(), verbose);
8346 }
8347 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
8348 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00008349 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00008350 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
8351 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
8352 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00008353 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
8354 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008355 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
8356 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
8357 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
8358 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
8359 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
8360 Command.C.cmd == MachO::LC_ID_DYLINKER ||
8361 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
8362 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
8363 PrintDyldLoadCommand(Dyld, Command.Ptr);
8364 } else if (Command.C.cmd == MachO::LC_UUID) {
8365 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
8366 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008367 } else if (Command.C.cmd == MachO::LC_RPATH) {
8368 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
8369 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00008370 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
8371 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008372 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
8373 PrintVersionMinLoadCommand(Vd);
8374 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
8375 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
8376 PrintSourceVersionCommand(Sd);
8377 } else if (Command.C.cmd == MachO::LC_MAIN) {
8378 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
8379 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00008380 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008381 MachO::encryption_info_command Ei =
8382 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00008383 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00008384 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008385 MachO::encryption_info_command_64 Ei =
8386 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00008387 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008388 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008389 MachO::linker_option_command Lo =
8390 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008391 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00008392 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
8393 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
8394 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00008395 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
8396 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
8397 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008398 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
8399 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
8400 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00008401 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
8402 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
8403 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00008404 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
8405 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
8406 PrintRoutinesCommand(Rc);
8407 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
8408 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
8409 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00008410 } else if (Command.C.cmd == MachO::LC_THREAD ||
8411 Command.C.cmd == MachO::LC_UNIXTHREAD) {
8412 MachO::thread_command Tc = Obj->getThreadCommand(Command);
8413 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00008414 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
8415 Command.C.cmd == MachO::LC_ID_DYLIB ||
8416 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
8417 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
8418 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
8419 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008420 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
8421 PrintDylibCommand(Dl, Command.Ptr);
8422 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
8423 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
8424 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
8425 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
8426 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
8427 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
8428 MachO::linkedit_data_command Ld =
8429 Obj->getLinkeditDataLoadCommand(Command);
8430 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00008431 } else {
8432 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
8433 << ")\n";
8434 outs() << " cmdsize " << Command.C.cmdsize << "\n";
8435 // TODO: get and print the raw bytes of the load command.
8436 }
8437 // TODO: print all the other kinds of load commands.
8438 if (i == ncmds - 1)
8439 break;
8440 else
8441 Command = Obj->getNextLoadCommandInfo(Command);
8442 }
8443}
8444
8445static void getAndPrintMachHeader(const MachOObjectFile *Obj, uint32_t &ncmds,
8446 uint32_t &filetype, uint32_t &cputype,
8447 bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008448 if (Obj->is64Bit()) {
8449 MachO::mach_header_64 H_64;
8450 H_64 = Obj->getHeader64();
8451 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
8452 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
Kevin Enderby956366c2014-08-29 22:30:52 +00008453 ncmds = H_64.ncmds;
8454 filetype = H_64.filetype;
8455 cputype = H_64.cputype;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008456 } else {
8457 MachO::mach_header H;
8458 H = Obj->getHeader();
8459 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
8460 H.sizeofcmds, H.flags, verbose);
Kevin Enderby956366c2014-08-29 22:30:52 +00008461 ncmds = H.ncmds;
8462 filetype = H.filetype;
8463 cputype = H.cputype;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008464 }
8465}
8466
8467void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
8468 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00008469 uint32_t ncmds = 0;
8470 uint32_t filetype = 0;
8471 uint32_t cputype = 0;
Kevin Enderbyf0640752015-03-13 17:56:32 +00008472 getAndPrintMachHeader(file, ncmds, filetype, cputype, !NonVerbose);
8473 PrintLoadCommands(file, ncmds, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008474}
Nick Kledzikd04bc352014-08-30 00:20:14 +00008475
8476//===----------------------------------------------------------------------===//
8477// export trie dumping
8478//===----------------------------------------------------------------------===//
8479
8480void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008481 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
8482 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +00008483 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
8484 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
8485 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8486 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
8487 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8488 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
8489 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
8490 if (ReExport)
8491 outs() << "[re-export] ";
8492 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008493 outs() << format("0x%08llX ",
8494 Entry.address()); // FIXME:add in base address
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008495 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +00008496 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008497 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +00008498 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +00008499 if (WeakDef) {
8500 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008501 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008502 }
8503 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008504 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00008505 outs() << ", ";
8506 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008507 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008508 }
8509 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008510 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00008511 outs() << ", ";
8512 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008513 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008514 }
8515 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008516 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00008517 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008518 outs() << format("resolver=0x%08llX", Entry.other());
8519 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008520 }
8521 outs() << "]";
8522 }
8523 if (ReExport) {
8524 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008525 int Ordinal = Entry.other() - 1;
8526 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
8527 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +00008528 outs() << " (from " << DylibName << ")";
8529 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008530 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +00008531 }
8532 outs() << "\n";
8533 }
8534}
Nick Kledzikac431442014-09-12 21:34:15 +00008535
Nick Kledzikac431442014-09-12 21:34:15 +00008536//===----------------------------------------------------------------------===//
8537// rebase table dumping
8538//===----------------------------------------------------------------------===//
8539
8540namespace {
8541class SegInfo {
8542public:
8543 SegInfo(const object::MachOObjectFile *Obj);
8544
8545 StringRef segmentName(uint32_t SegIndex);
8546 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
8547 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
8548
8549private:
8550 struct SectionInfo {
8551 uint64_t Address;
8552 uint64_t Size;
8553 StringRef SectionName;
8554 StringRef SegmentName;
8555 uint64_t OffsetInSegment;
8556 uint64_t SegmentStartAddress;
8557 uint32_t SegmentIndex;
8558 };
8559 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
8560 SmallVector<SectionInfo, 32> Sections;
8561};
8562}
8563
8564SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
8565 // Build table of sections so segIndex/offset pairs can be translated.
Nick Kledzik56ebef42014-09-16 01:41:51 +00008566 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
Nick Kledzikac431442014-09-12 21:34:15 +00008567 StringRef CurSegName;
8568 uint64_t CurSegAddress;
8569 for (const SectionRef &Section : Obj->sections()) {
8570 SectionInfo Info;
8571 if (error(Section.getName(Info.SectionName)))
8572 return;
Rafael Espindola80291272014-10-08 15:28:58 +00008573 Info.Address = Section.getAddress();
8574 Info.Size = Section.getSize();
Nick Kledzikac431442014-09-12 21:34:15 +00008575 Info.SegmentName =
8576 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
8577 if (!Info.SegmentName.equals(CurSegName)) {
8578 ++CurSegIndex;
8579 CurSegName = Info.SegmentName;
8580 CurSegAddress = Info.Address;
8581 }
8582 Info.SegmentIndex = CurSegIndex - 1;
8583 Info.OffsetInSegment = Info.Address - CurSegAddress;
8584 Info.SegmentStartAddress = CurSegAddress;
8585 Sections.push_back(Info);
8586 }
8587}
8588
8589StringRef SegInfo::segmentName(uint32_t SegIndex) {
8590 for (const SectionInfo &SI : Sections) {
8591 if (SI.SegmentIndex == SegIndex)
8592 return SI.SegmentName;
8593 }
8594 llvm_unreachable("invalid segIndex");
8595}
8596
8597const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
8598 uint64_t OffsetInSeg) {
8599 for (const SectionInfo &SI : Sections) {
8600 if (SI.SegmentIndex != SegIndex)
8601 continue;
8602 if (SI.OffsetInSegment > OffsetInSeg)
8603 continue;
8604 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
8605 continue;
8606 return SI;
8607 }
8608 llvm_unreachable("segIndex and offset not in any section");
8609}
8610
8611StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
8612 return findSection(SegIndex, OffsetInSeg).SectionName;
8613}
8614
8615uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
8616 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
8617 return SI.SegmentStartAddress + OffsetInSeg;
8618}
8619
8620void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
8621 // Build table of sections so names can used in final output.
8622 SegInfo sectionTable(Obj);
8623
8624 outs() << "segment section address type\n";
8625 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
8626 uint32_t SegIndex = Entry.segmentIndex();
8627 uint64_t OffsetInSeg = Entry.segmentOffset();
8628 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8629 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8630 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8631
8632 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008633 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
8634 SegmentName.str().c_str(), SectionName.str().c_str(),
8635 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +00008636 }
8637}
Nick Kledzik56ebef42014-09-16 01:41:51 +00008638
8639static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
8640 StringRef DylibName;
8641 switch (Ordinal) {
8642 case MachO::BIND_SPECIAL_DYLIB_SELF:
8643 return "this-image";
8644 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
8645 return "main-executable";
8646 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
8647 return "flat-namespace";
8648 default:
Nick Kledzikabd29872014-09-16 22:03:13 +00008649 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008650 std::error_code EC =
8651 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +00008652 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +00008653 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +00008654 return DylibName;
8655 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00008656 }
Nick Kledzikabd29872014-09-16 22:03:13 +00008657 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008658}
8659
8660//===----------------------------------------------------------------------===//
8661// bind table dumping
8662//===----------------------------------------------------------------------===//
8663
8664void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
8665 // Build table of sections so names can used in final output.
8666 SegInfo sectionTable(Obj);
8667
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008668 outs() << "segment section address type "
8669 "addend dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008670 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
8671 uint32_t SegIndex = Entry.segmentIndex();
8672 uint64_t OffsetInSeg = Entry.segmentOffset();
8673 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8674 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8675 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8676
8677 // Table lines look like:
8678 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008679 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00008680 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008681 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008682 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008683 << left_justify(SectionName, 18) << " "
8684 << format_hex(Address, 10, true) << " "
8685 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008686 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008687 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008688 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008689 }
8690}
8691
8692//===----------------------------------------------------------------------===//
8693// lazy bind table dumping
8694//===----------------------------------------------------------------------===//
8695
8696void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
8697 // Build table of sections so names can used in final output.
8698 SegInfo sectionTable(Obj);
8699
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008700 outs() << "segment section address "
8701 "dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008702 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
8703 uint32_t SegIndex = Entry.segmentIndex();
8704 uint64_t OffsetInSeg = Entry.segmentOffset();
8705 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8706 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8707 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8708
8709 // Table lines look like:
8710 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008711 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008712 << left_justify(SectionName, 18) << " "
8713 << format_hex(Address, 10, true) << " "
8714 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00008715 << Entry.symbolName() << "\n";
8716 }
8717}
8718
Nick Kledzik56ebef42014-09-16 01:41:51 +00008719//===----------------------------------------------------------------------===//
8720// weak bind table dumping
8721//===----------------------------------------------------------------------===//
8722
8723void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
8724 // Build table of sections so names can used in final output.
8725 SegInfo sectionTable(Obj);
8726
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008727 outs() << "segment section address "
8728 "type addend symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008729 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
8730 // Strong symbols don't have a location to update.
8731 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008732 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +00008733 << Entry.symbolName() << "\n";
8734 continue;
8735 }
8736 uint32_t SegIndex = Entry.segmentIndex();
8737 uint64_t OffsetInSeg = Entry.segmentOffset();
8738 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8739 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8740 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8741
8742 // Table lines look like:
8743 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008744 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008745 << left_justify(SectionName, 18) << " "
8746 << format_hex(Address, 10, true) << " "
8747 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008748 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
8749 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008750 }
8751}
8752
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008753// get_dyld_bind_info_symbolname() is used for disassembly and passed an
8754// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
8755// information for that address. If the address is found its binding symbol
8756// name is returned. If not nullptr is returned.
8757static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
8758 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +00008759 if (info->bindtable == nullptr) {
8760 info->bindtable = new (BindTable);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008761 SegInfo sectionTable(info->O);
8762 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
8763 uint32_t SegIndex = Entry.segmentIndex();
8764 uint64_t OffsetInSeg = Entry.segmentOffset();
8765 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8766 const char *SymbolName = nullptr;
8767 StringRef name = Entry.symbolName();
8768 if (!name.empty())
8769 SymbolName = name.data();
Kevin Enderby078be602014-10-23 19:53:12 +00008770 info->bindtable->push_back(std::make_pair(Address, SymbolName));
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008771 }
8772 }
Kevin Enderby078be602014-10-23 19:53:12 +00008773 for (bind_table_iterator BI = info->bindtable->begin(),
8774 BE = info->bindtable->end();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008775 BI != BE; ++BI) {
8776 uint64_t Address = BI->first;
8777 if (ReferenceValue == Address) {
8778 const char *SymbolName = BI->second;
8779 return SymbolName;
8780 }
8781 }
8782 return nullptr;
8783}