blob: b270057151e12ad89cca122dfbd4ea5004a6a16c [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 Turner6489d7b2015-04-23 17:37:47 +000020#include "llvm/DebugInfo/DIContext.h"
21#include "llvm/DebugInfo/DWARF/DWARFContext.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000022#include "llvm/MC/MCAsmInfo.h"
Lang Hamesa1bc0f52014-04-15 04:40:56 +000023#include "llvm/MC/MCContext.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000024#include "llvm/MC/MCDisassembler.h"
25#include "llvm/MC/MCInst.h"
26#include "llvm/MC/MCInstPrinter.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000027#include "llvm/MC/MCInstrDesc.h"
28#include "llvm/MC/MCInstrInfo.h"
Jim Grosbachfd93a592012-03-05 19:33:20 +000029#include "llvm/MC/MCRegisterInfo.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000030#include "llvm/MC/MCSubtargetInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000031#include "llvm/Object/MachO.h"
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +000032#include "llvm/Object/MachOUniversal.h"
Rafael Espindola9b709252013-04-13 01:45:40 +000033#include "llvm/Support/Casting.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000034#include "llvm/Support/CommandLine.h"
35#include "llvm/Support/Debug.h"
Tim Northover4bd286a2014-08-01 13:07:19 +000036#include "llvm/Support/Endian.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000037#include "llvm/Support/Format.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000038#include "llvm/Support/FormattedStream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000039#include "llvm/Support/GraphWriter.h"
Kevin Enderby9a509442015-01-27 21:28:24 +000040#include "llvm/Support/LEB128.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000041#include "llvm/Support/MachO.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000042#include "llvm/Support/MemoryBuffer.h"
43#include "llvm/Support/TargetRegistry.h"
44#include "llvm/Support/TargetSelect.h"
45#include "llvm/Support/raw_ostream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000046#include <algorithm>
47#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000048#include <system_error>
Kevin Enderby04bf6932014-10-28 23:39:46 +000049
50#if HAVE_CXXABI_H
51#include <cxxabi.h>
52#endif
53
Benjamin Kramer43a772e2011-09-19 17:56:04 +000054using namespace llvm;
55using namespace object;
56
57static cl::opt<bool>
Kevin Enderbyb28ed012014-10-29 21:28:24 +000058 UseDbg("g",
59 cl::desc("Print line information from debug info if available"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000060
Kevin Enderbyb28ed012014-10-29 21:28:24 +000061static cl::opt<std::string> DSYMFile("dsym",
62 cl::desc("Use .dSYM file for debug info"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000063
Kevin Enderbyb28ed012014-10-29 21:28:24 +000064static cl::opt<bool> FullLeadingAddr("full-leading-addr",
65 cl::desc("Print full leading address"));
Kevin Enderbybf246f52014-09-24 23:08:22 +000066
Kevin Enderbyab5e6c92015-03-17 21:07:39 +000067static cl::opt<bool> NoLeadingAddr("no-leading-addr",
68 cl::desc("Print no leading address"));
69
Kevin Enderby13023a12015-01-15 23:19:11 +000070cl::opt<bool> llvm::UniversalHeaders("universal-headers",
71 cl::desc("Print Mach-O universal headers "
72 "(requires -macho)"));
73
Kevin Enderby131d1772015-01-09 19:22:37 +000074cl::opt<bool>
Kevin Enderby13023a12015-01-15 23:19:11 +000075 llvm::ArchiveHeaders("archive-headers",
76 cl::desc("Print archive headers for Mach-O archives "
77 "(requires -macho)"));
Kevin Enderby131d1772015-01-09 19:22:37 +000078
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +000079cl::opt<bool>
Kevin Enderby8972e482015-04-30 20:30:42 +000080 ArchiveMemberOffsets("archive-member-offsets",
81 cl::desc("Print the offset to each archive member for "
82 "Mach-O archives (requires -macho and "
83 "-archive-headers)"));
84
85cl::opt<bool>
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +000086 llvm::IndirectSymbols("indirect-symbols",
87 cl::desc("Print indirect symbol table for Mach-O "
88 "objects (requires -macho)"));
89
Kevin Enderby69fe98d2015-01-23 18:52:17 +000090cl::opt<bool>
91 llvm::DataInCode("data-in-code",
92 cl::desc("Print the data in code table for Mach-O objects "
93 "(requires -macho)"));
94
Kevin Enderby9a509442015-01-27 21:28:24 +000095cl::opt<bool>
96 llvm::LinkOptHints("link-opt-hints",
97 cl::desc("Print the linker optimization hints for "
98 "Mach-O objects (requires -macho)"));
99
Kevin Enderbycd66be52015-03-11 22:06:32 +0000100cl::opt<bool>
101 llvm::InfoPlist("info-plist",
102 cl::desc("Print the info plist section as strings for "
103 "Mach-O objects (requires -macho)"));
104
Kevin Enderbyf0640752015-03-13 17:56:32 +0000105cl::opt<bool>
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000106 llvm::DylibsUsed("dylibs-used",
107 cl::desc("Print the shared libraries used for linked "
108 "Mach-O files (requires -macho)"));
109
110cl::opt<bool>
111 llvm::DylibId("dylib-id",
112 cl::desc("Print the shared library's id for the dylib Mach-O "
113 "file (requires -macho)"));
114
115cl::opt<bool>
Kevin Enderbyf0640752015-03-13 17:56:32 +0000116 llvm::NonVerbose("non-verbose",
117 cl::desc("Print the info for Mach-O objects in "
118 "non-verbose or numeric form (requires -macho)"));
119
Kevin Enderby0fc11822015-04-01 20:57:01 +0000120cl::opt<bool>
121 llvm::ObjcMetaData("objc-meta-data",
122 cl::desc("Print the Objective-C runtime meta data for "
123 "Mach-O files (requires -macho)"));
124
Kevin Enderby6a221752015-03-17 17:10:57 +0000125cl::opt<std::string> llvm::DisSymName(
126 "dis-symname",
127 cl::desc("disassemble just this symbol's instructions (requires -macho"));
128
Kevin Enderby8e29ec92015-03-17 22:26:11 +0000129static cl::opt<bool> NoSymbolicOperands(
130 "no-symbolic-operands",
131 cl::desc("do not symbolic operands when disassembling (requires -macho)"));
132
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000133static cl::list<std::string>
134 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
135 cl::ZeroOrMore);
Hans Wennborgcc9deb42015-09-29 18:02:48 +0000136
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000137bool ArchAll = false;
138
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000139static std::string ThumbTripleName;
140
141static const Target *GetTarget(const MachOObjectFile *MachOObj,
142 const char **McpuDefault,
143 const Target **ThumbTarget) {
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000144 // Figure out the target triple.
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000145 if (TripleName.empty()) {
146 llvm::Triple TT("unknown-unknown-unknown");
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000147 llvm::Triple ThumbTriple = Triple();
148 TT = MachOObj->getArch(McpuDefault, &ThumbTriple);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000149 TripleName = TT.str();
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000150 ThumbTripleName = ThumbTriple.str();
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000151 }
152
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000153 // Get the target specific parser.
154 std::string Error;
155 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000156 if (TheTarget && ThumbTripleName.empty())
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000157 return TheTarget;
158
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000159 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
160 if (*ThumbTarget)
161 return TheTarget;
162
163 errs() << "llvm-objdump: error: unable to get target for '";
164 if (!TheTarget)
165 errs() << TripleName;
166 else
167 errs() << ThumbTripleName;
168 errs() << "', see --version and --triple.\n";
Craig Toppere6cb63e2014-04-25 04:24:47 +0000169 return nullptr;
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000170}
171
Owen Andersond9243c42011-10-17 21:37:35 +0000172struct SymbolSorter {
173 bool operator()(const SymbolRef &A, const SymbolRef &B) {
Rafael Espindoladea00162015-07-03 17:44:18 +0000174 uint64_t AAddr = (A.getType() != SymbolRef::ST_Function) ? 0 : A.getValue();
175 uint64_t BAddr = (B.getType() != SymbolRef::ST_Function) ? 0 : B.getValue();
Owen Andersond9243c42011-10-17 21:37:35 +0000176 return AAddr < BAddr;
177 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000178};
179
Kevin Enderby273ae012013-06-06 17:20:50 +0000180// Types for the storted data in code table that is built before disassembly
181// and the predicate function to sort them.
182typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
183typedef std::vector<DiceTableEntry> DiceTable;
184typedef DiceTable::iterator dice_table_iterator;
185
Kevin Enderby930fdc72014-11-06 19:00:13 +0000186// This is used to search for a data in code table entry for the PC being
187// disassembled. The j parameter has the PC in j.first. A single data in code
188// table entry can cover many bytes for each of its Kind's. So if the offset,
189// aka the i.first value, of the data in code table entry plus its Length
190// covers the PC being searched for this will return true. If not it will
191// return false.
David Majnemerea9b8ee2014-11-04 08:41:48 +0000192static bool compareDiceTableEntries(const DiceTableEntry &i,
193 const DiceTableEntry &j) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000194 uint16_t Length;
195 i.second.getLength(Length);
196
197 return j.first >= i.first && j.first < i.first + Length;
Kevin Enderby273ae012013-06-06 17:20:50 +0000198}
199
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000200static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
Kevin Enderby930fdc72014-11-06 19:00:13 +0000201 unsigned short Kind) {
202 uint32_t Value, Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000203
204 switch (Kind) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000205 default:
Charles Davis8bdfafd2013-09-01 04:28:48 +0000206 case MachO::DICE_KIND_DATA:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000207 if (Length >= 4) {
208 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000209 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000210 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000211 outs() << "\t.long " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000212 Size = 4;
213 } else if (Length >= 2) {
214 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000215 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000216 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000217 outs() << "\t.short " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000218 Size = 2;
219 } else {
220 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000221 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000222 Value = bytes[0];
223 outs() << "\t.byte " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000224 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000225 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000226 if (Kind == MachO::DICE_KIND_DATA)
227 outs() << "\t@ KIND_DATA\n";
228 else
229 outs() << "\t@ data in code kind = " << Kind << "\n";
Kevin Enderby273ae012013-06-06 17:20:50 +0000230 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000231 case MachO::DICE_KIND_JUMP_TABLE8:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000232 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000233 dumpBytes(makeArrayRef(bytes, 1), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000234 Value = bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000235 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
236 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000237 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000238 case MachO::DICE_KIND_JUMP_TABLE16:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000239 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000240 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000241 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000242 outs() << "\t.short " << format("%5u", Value & 0xffff)
243 << "\t@ KIND_JUMP_TABLE16\n";
244 Size = 2;
Kevin Enderby273ae012013-06-06 17:20:50 +0000245 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000246 case MachO::DICE_KIND_JUMP_TABLE32:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000247 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
248 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000249 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000250 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000251 outs() << "\t.long " << Value;
252 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
253 outs() << "\t@ KIND_JUMP_TABLE32\n";
254 else
255 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
256 Size = 4;
Kevin Enderby273ae012013-06-06 17:20:50 +0000257 break;
258 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000259 return Size;
Kevin Enderby273ae012013-06-06 17:20:50 +0000260}
261
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000262static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000263 std::vector<SectionRef> &Sections,
264 std::vector<SymbolRef> &Symbols,
265 SmallVectorImpl<uint64_t> &FoundFns,
266 uint64_t &BaseSegmentAddress) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000267 for (const SymbolRef &Symbol : MachOObj->symbols()) {
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000268 ErrorOr<StringRef> SymName = Symbol.getName();
269 if (std::error_code EC = SymName.getError())
270 report_fatal_error(EC.message());
271 if (!SymName->startswith("ltmp"))
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000272 Symbols.push_back(Symbol);
273 }
Owen Andersond9243c42011-10-17 21:37:35 +0000274
Alexey Samsonov48803e52014-03-13 14:37:36 +0000275 for (const SectionRef &Section : MachOObj->sections()) {
Owen Andersond9243c42011-10-17 21:37:35 +0000276 StringRef SectName;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000277 Section.getName(SectName);
278 Sections.push_back(Section);
Owen Andersond9243c42011-10-17 21:37:35 +0000279 }
280
Kevin Enderby273ae012013-06-06 17:20:50 +0000281 bool BaseSegmentAddressSet = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000282 for (const auto &Command : MachOObj->load_commands()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000283 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
Benjamin Kramer699128e2011-09-21 01:13:19 +0000284 // We found a function starts segment, parse the addresses for later
285 // consumption.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000286 MachO::linkedit_data_command LLC =
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000287 MachOObj->getLinkeditDataLoadCommand(Command);
Benjamin Kramer699128e2011-09-21 01:13:19 +0000288
Charles Davis8bdfafd2013-09-01 04:28:48 +0000289 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000290 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
291 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000292 StringRef SegName = SLC.segname;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000293 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
Kevin Enderby273ae012013-06-06 17:20:50 +0000294 BaseSegmentAddressSet = true;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000295 BaseSegmentAddress = SLC.vmaddr;
Kevin Enderby273ae012013-06-06 17:20:50 +0000296 }
297 }
Benjamin Kramer8a529dc2011-09-21 22:16:43 +0000298 }
Benjamin Kramer699128e2011-09-21 01:13:19 +0000299}
300
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000301static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
302 uint32_t n, uint32_t count,
303 uint32_t stride, uint64_t addr) {
304 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
305 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
306 if (n > nindirectsyms)
307 outs() << " (entries start past the end of the indirect symbol "
308 "table) (reserved1 field greater than the table size)";
309 else if (n + count > nindirectsyms)
310 outs() << " (entries extends past the end of the indirect symbol "
311 "table)";
312 outs() << "\n";
313 uint32_t cputype = O->getHeader().cputype;
314 if (cputype & MachO::CPU_ARCH_ABI64)
315 outs() << "address index";
316 else
317 outs() << "address index";
318 if (verbose)
319 outs() << " name\n";
320 else
321 outs() << "\n";
322 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
323 if (cputype & MachO::CPU_ARCH_ABI64)
324 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
325 else
326 outs() << format("0x%08" PRIx32, addr + j * stride) << " ";
327 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
328 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
329 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
330 outs() << "LOCAL\n";
331 continue;
332 }
333 if (indirect_symbol ==
334 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
335 outs() << "LOCAL ABSOLUTE\n";
336 continue;
337 }
338 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
339 outs() << "ABSOLUTE\n";
340 continue;
341 }
342 outs() << format("%5u ", indirect_symbol);
Kevin Enderbyf0640752015-03-13 17:56:32 +0000343 if (verbose) {
344 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
345 if (indirect_symbol < Symtab.nsyms) {
346 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
347 SymbolRef Symbol = *Sym;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000348 ErrorOr<StringRef> SymName = Symbol.getName();
349 if (std::error_code EC = SymName.getError())
350 report_fatal_error(EC.message());
351 outs() << *SymName;
Kevin Enderbyf0640752015-03-13 17:56:32 +0000352 } else {
353 outs() << "?";
354 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000355 }
356 outs() << "\n";
357 }
358}
359
360static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000361 for (const auto &Load : O->load_commands()) {
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000362 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
363 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
364 for (unsigned J = 0; J < Seg.nsects; ++J) {
365 MachO::section_64 Sec = O->getSection64(Load, J);
366 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
367 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
368 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
369 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
370 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
371 section_type == MachO::S_SYMBOL_STUBS) {
372 uint32_t stride;
373 if (section_type == MachO::S_SYMBOL_STUBS)
374 stride = Sec.reserved2;
375 else
376 stride = 8;
377 if (stride == 0) {
378 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
379 << Sec.sectname << ") "
380 << "(size of stubs in reserved2 field is zero)\n";
381 continue;
382 }
383 uint32_t count = Sec.size / stride;
384 outs() << "Indirect symbols for (" << Sec.segname << ","
385 << Sec.sectname << ") " << count << " entries";
386 uint32_t n = Sec.reserved1;
387 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
388 }
389 }
390 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
391 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
392 for (unsigned J = 0; J < Seg.nsects; ++J) {
393 MachO::section Sec = O->getSection(Load, J);
394 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
395 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
396 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
397 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
398 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
399 section_type == MachO::S_SYMBOL_STUBS) {
400 uint32_t stride;
401 if (section_type == MachO::S_SYMBOL_STUBS)
402 stride = Sec.reserved2;
403 else
404 stride = 4;
405 if (stride == 0) {
406 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
407 << Sec.sectname << ") "
408 << "(size of stubs in reserved2 field is zero)\n";
409 continue;
410 }
411 uint32_t count = Sec.size / stride;
412 outs() << "Indirect symbols for (" << Sec.segname << ","
413 << Sec.sectname << ") " << count << " entries";
414 uint32_t n = Sec.reserved1;
415 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
416 }
417 }
418 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000419 }
420}
421
Kevin Enderby69fe98d2015-01-23 18:52:17 +0000422static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
423 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
424 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
425 outs() << "Data in code table (" << nentries << " entries)\n";
426 outs() << "offset length kind\n";
427 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
428 ++DI) {
429 uint32_t Offset;
430 DI->getOffset(Offset);
431 outs() << format("0x%08" PRIx32, Offset) << " ";
432 uint16_t Length;
433 DI->getLength(Length);
434 outs() << format("%6u", Length) << " ";
435 uint16_t Kind;
436 DI->getKind(Kind);
437 if (verbose) {
438 switch (Kind) {
439 case MachO::DICE_KIND_DATA:
440 outs() << "DATA";
441 break;
442 case MachO::DICE_KIND_JUMP_TABLE8:
443 outs() << "JUMP_TABLE8";
444 break;
445 case MachO::DICE_KIND_JUMP_TABLE16:
446 outs() << "JUMP_TABLE16";
447 break;
448 case MachO::DICE_KIND_JUMP_TABLE32:
449 outs() << "JUMP_TABLE32";
450 break;
451 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
452 outs() << "ABS_JUMP_TABLE32";
453 break;
454 default:
455 outs() << format("0x%04" PRIx32, Kind);
456 break;
457 }
458 } else
459 outs() << format("0x%04" PRIx32, Kind);
460 outs() << "\n";
461 }
462}
463
Kevin Enderby9a509442015-01-27 21:28:24 +0000464static void PrintLinkOptHints(MachOObjectFile *O) {
465 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
466 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
467 uint32_t nloh = LohLC.datasize;
468 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
469 for (uint32_t i = 0; i < nloh;) {
470 unsigned n;
471 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
472 i += n;
473 outs() << " identifier " << identifier << " ";
474 if (i >= nloh)
475 return;
476 switch (identifier) {
477 case 1:
478 outs() << "AdrpAdrp\n";
479 break;
480 case 2:
481 outs() << "AdrpLdr\n";
482 break;
483 case 3:
484 outs() << "AdrpAddLdr\n";
485 break;
486 case 4:
487 outs() << "AdrpLdrGotLdr\n";
488 break;
489 case 5:
490 outs() << "AdrpAddStr\n";
491 break;
492 case 6:
493 outs() << "AdrpLdrGotStr\n";
494 break;
495 case 7:
496 outs() << "AdrpAdd\n";
497 break;
498 case 8:
499 outs() << "AdrpLdrGot\n";
500 break;
501 default:
502 outs() << "Unknown identifier value\n";
503 break;
504 }
505 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
506 i += n;
507 outs() << " narguments " << narguments << "\n";
508 if (i >= nloh)
509 return;
510
511 for (uint32_t j = 0; j < narguments; j++) {
512 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
513 i += n;
514 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
515 if (i >= nloh)
516 return;
517 }
518 }
519}
520
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000521static void PrintDylibs(MachOObjectFile *O, bool JustId) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000522 unsigned Index = 0;
523 for (const auto &Load : O->load_commands()) {
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000524 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
525 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
526 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
527 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
528 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
529 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
530 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
531 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
532 if (dl.dylib.name < dl.cmdsize) {
533 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
534 if (JustId)
535 outs() << p << "\n";
536 else {
537 outs() << "\t" << p;
538 outs() << " (compatibility version "
539 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
540 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
541 << (dl.dylib.compatibility_version & 0xff) << ",";
542 outs() << " current version "
543 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
544 << ((dl.dylib.current_version >> 8) & 0xff) << "."
545 << (dl.dylib.current_version & 0xff) << ")\n";
546 }
547 } else {
548 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
549 if (Load.C.cmd == MachO::LC_ID_DYLIB)
550 outs() << "LC_ID_DYLIB ";
551 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
552 outs() << "LC_LOAD_DYLIB ";
553 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
554 outs() << "LC_LOAD_WEAK_DYLIB ";
555 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
556 outs() << "LC_LAZY_LOAD_DYLIB ";
557 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
558 outs() << "LC_REEXPORT_DYLIB ";
559 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
560 outs() << "LC_LOAD_UPWARD_DYLIB ";
561 else
562 outs() << "LC_??? ";
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000563 outs() << "command " << Index++ << "\n";
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000564 }
565 }
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000566 }
567}
568
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000569typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
570
571static void CreateSymbolAddressMap(MachOObjectFile *O,
572 SymbolAddressMap *AddrMap) {
573 // Create a map of symbol addresses to symbol names.
574 for (const SymbolRef &Symbol : O->symbols()) {
Rafael Espindola2fa80cc2015-06-26 12:18:49 +0000575 SymbolRef::Type ST = Symbol.getType();
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000576 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
577 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +0000578 uint64_t Address = Symbol.getValue();
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000579 ErrorOr<StringRef> SymNameOrErr = Symbol.getName();
580 if (std::error_code EC = SymNameOrErr.getError())
581 report_fatal_error(EC.message());
582 StringRef SymName = *SymNameOrErr;
Kevin Enderby846c0002015-04-16 17:19:59 +0000583 if (!SymName.startswith(".objc"))
584 (*AddrMap)[Address] = SymName;
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000585 }
586 }
587}
588
589// GuessSymbolName is passed the address of what might be a symbol and a
590// pointer to the SymbolAddressMap. It returns the name of a symbol
591// with that address or nullptr if no symbol is found with that address.
592static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
593 const char *SymbolName = nullptr;
594 // A DenseMap can't lookup up some values.
595 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
596 StringRef name = AddrMap->lookup(value);
597 if (!name.empty())
598 SymbolName = name.data();
599 }
600 return SymbolName;
601}
602
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000603static void DumpCstringChar(const char c) {
604 char p[2];
605 p[0] = c;
606 p[1] = '\0';
607 outs().write_escaped(p);
608}
609
Kevin Enderby10ba0412015-02-04 21:38:42 +0000610static void DumpCstringSection(MachOObjectFile *O, const char *sect,
611 uint32_t sect_size, uint64_t sect_addr,
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000612 bool print_addresses) {
Kevin Enderby10ba0412015-02-04 21:38:42 +0000613 for (uint32_t i = 0; i < sect_size; i++) {
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000614 if (print_addresses) {
615 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000616 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000617 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000618 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000619 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000620 for (; i < sect_size && sect[i] != '\0'; i++)
621 DumpCstringChar(sect[i]);
Kevin Enderby10ba0412015-02-04 21:38:42 +0000622 if (i < sect_size && sect[i] == '\0')
623 outs() << "\n";
624 }
625}
626
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000627static void DumpLiteral4(uint32_t l, float f) {
628 outs() << format("0x%08" PRIx32, l);
629 if ((l & 0x7f800000) != 0x7f800000)
630 outs() << format(" (%.16e)\n", f);
631 else {
632 if (l == 0x7f800000)
633 outs() << " (+Infinity)\n";
634 else if (l == 0xff800000)
635 outs() << " (-Infinity)\n";
636 else if ((l & 0x00400000) == 0x00400000)
637 outs() << " (non-signaling Not-a-Number)\n";
638 else
639 outs() << " (signaling Not-a-Number)\n";
640 }
641}
642
643static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
644 uint32_t sect_size, uint64_t sect_addr,
645 bool print_addresses) {
646 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
647 if (print_addresses) {
648 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000649 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000650 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000651 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000652 }
653 float f;
654 memcpy(&f, sect + i, sizeof(float));
655 if (O->isLittleEndian() != sys::IsLittleEndianHost)
656 sys::swapByteOrder(f);
657 uint32_t l;
658 memcpy(&l, sect + i, sizeof(uint32_t));
659 if (O->isLittleEndian() != sys::IsLittleEndianHost)
660 sys::swapByteOrder(l);
661 DumpLiteral4(l, f);
662 }
663}
664
665static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
666 double d) {
667 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
668 uint32_t Hi, Lo;
669 if (O->isLittleEndian()) {
670 Hi = l1;
671 Lo = l0;
672 } else {
673 Hi = l0;
674 Lo = l1;
675 }
676 // Hi is the high word, so this is equivalent to if(isfinite(d))
677 if ((Hi & 0x7ff00000) != 0x7ff00000)
678 outs() << format(" (%.16e)\n", d);
679 else {
680 if (Hi == 0x7ff00000 && Lo == 0)
681 outs() << " (+Infinity)\n";
682 else if (Hi == 0xfff00000 && Lo == 0)
683 outs() << " (-Infinity)\n";
684 else if ((Hi & 0x00080000) == 0x00080000)
685 outs() << " (non-signaling Not-a-Number)\n";
686 else
687 outs() << " (signaling Not-a-Number)\n";
688 }
689}
690
691static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
692 uint32_t sect_size, uint64_t sect_addr,
693 bool print_addresses) {
694 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
695 if (print_addresses) {
696 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000697 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000698 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000699 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000700 }
701 double d;
702 memcpy(&d, sect + i, sizeof(double));
703 if (O->isLittleEndian() != sys::IsLittleEndianHost)
704 sys::swapByteOrder(d);
705 uint32_t l0, l1;
706 memcpy(&l0, sect + i, sizeof(uint32_t));
707 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
708 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
709 sys::swapByteOrder(l0);
710 sys::swapByteOrder(l1);
711 }
712 DumpLiteral8(O, l0, l1, d);
713 }
714}
715
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000716static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
717 outs() << format("0x%08" PRIx32, l0) << " ";
718 outs() << format("0x%08" PRIx32, l1) << " ";
719 outs() << format("0x%08" PRIx32, l2) << " ";
720 outs() << format("0x%08" PRIx32, l3) << "\n";
721}
722
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000723static void DumpLiteral16Section(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 += 16) {
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 uint32_t l0, l1, l2, l3;
734 memcpy(&l0, sect + i, sizeof(uint32_t));
735 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
736 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
737 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
738 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
739 sys::swapByteOrder(l0);
740 sys::swapByteOrder(l1);
741 sys::swapByteOrder(l2);
742 sys::swapByteOrder(l3);
743 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000744 DumpLiteral16(l0, l1, l2, l3);
745 }
746}
747
748static void DumpLiteralPointerSection(MachOObjectFile *O,
749 const SectionRef &Section,
750 const char *sect, uint32_t sect_size,
751 uint64_t sect_addr,
752 bool print_addresses) {
753 // Collect the literal sections in this Mach-O file.
754 std::vector<SectionRef> LiteralSections;
755 for (const SectionRef &Section : O->sections()) {
756 DataRefImpl Ref = Section.getRawDataRefImpl();
757 uint32_t section_type;
758 if (O->is64Bit()) {
759 const MachO::section_64 Sec = O->getSection64(Ref);
760 section_type = Sec.flags & MachO::SECTION_TYPE;
761 } else {
762 const MachO::section Sec = O->getSection(Ref);
763 section_type = Sec.flags & MachO::SECTION_TYPE;
764 }
765 if (section_type == MachO::S_CSTRING_LITERALS ||
766 section_type == MachO::S_4BYTE_LITERALS ||
767 section_type == MachO::S_8BYTE_LITERALS ||
768 section_type == MachO::S_16BYTE_LITERALS)
769 LiteralSections.push_back(Section);
770 }
771
772 // Set the size of the literal pointer.
773 uint32_t lp_size = O->is64Bit() ? 8 : 4;
774
Eric Christopher572e03a2015-06-19 01:53:21 +0000775 // Collect the external relocation symbols for the literal pointers.
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000776 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
777 for (const RelocationRef &Reloc : Section.relocations()) {
778 DataRefImpl Rel;
779 MachO::any_relocation_info RE;
780 bool isExtern = false;
781 Rel = Reloc.getRawDataRefImpl();
782 RE = O->getRelocation(Rel);
783 isExtern = O->getPlainRelocationExternal(RE);
784 if (isExtern) {
Rafael Espindola96d071c2015-06-29 23:29:12 +0000785 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000786 symbol_iterator RelocSym = Reloc.getSymbol();
787 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
788 }
789 }
790 array_pod_sort(Relocs.begin(), Relocs.end());
791
792 // Dump each literal pointer.
793 for (uint32_t i = 0; i < sect_size; i += lp_size) {
794 if (print_addresses) {
795 if (O->is64Bit())
796 outs() << format("%016" PRIx64, sect_addr + i) << " ";
797 else
798 outs() << format("%08" PRIx64, sect_addr + i) << " ";
799 }
800 uint64_t lp;
801 if (O->is64Bit()) {
802 memcpy(&lp, sect + i, sizeof(uint64_t));
803 if (O->isLittleEndian() != sys::IsLittleEndianHost)
804 sys::swapByteOrder(lp);
805 } else {
806 uint32_t li;
807 memcpy(&li, sect + i, sizeof(uint32_t));
808 if (O->isLittleEndian() != sys::IsLittleEndianHost)
809 sys::swapByteOrder(li);
810 lp = li;
811 }
812
813 // First look for an external relocation entry for this literal pointer.
David Blaikie33dd45d02015-03-23 18:39:02 +0000814 auto Reloc = std::find_if(
815 Relocs.begin(), Relocs.end(),
816 [&](const std::pair<uint64_t, SymbolRef> &P) { return P.first == i; });
817 if (Reloc != Relocs.end()) {
818 symbol_iterator RelocSym = Reloc->second;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000819 ErrorOr<StringRef> SymName = RelocSym->getName();
820 if (std::error_code EC = SymName.getError())
821 report_fatal_error(EC.message());
822 outs() << "external relocation entry for symbol:" << *SymName << "\n";
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000823 continue;
David Blaikie33dd45d02015-03-23 18:39:02 +0000824 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000825
826 // For local references see what the section the literal pointer points to.
David Blaikie33dd45d02015-03-23 18:39:02 +0000827 auto Sect = std::find_if(LiteralSections.begin(), LiteralSections.end(),
828 [&](const SectionRef &R) {
829 return lp >= R.getAddress() &&
830 lp < R.getAddress() + R.getSize();
831 });
832 if (Sect == LiteralSections.end()) {
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000833 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
David Blaikie33dd45d02015-03-23 18:39:02 +0000834 continue;
835 }
836
837 uint64_t SectAddress = Sect->getAddress();
838 uint64_t SectSize = Sect->getSize();
839
840 StringRef SectName;
841 Sect->getName(SectName);
842 DataRefImpl Ref = Sect->getRawDataRefImpl();
843 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
844 outs() << SegmentName << ":" << SectName << ":";
845
846 uint32_t section_type;
847 if (O->is64Bit()) {
848 const MachO::section_64 Sec = O->getSection64(Ref);
849 section_type = Sec.flags & MachO::SECTION_TYPE;
850 } else {
851 const MachO::section Sec = O->getSection(Ref);
852 section_type = Sec.flags & MachO::SECTION_TYPE;
853 }
854
855 StringRef BytesStr;
856 Sect->getContents(BytesStr);
857 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
858
859 switch (section_type) {
860 case MachO::S_CSTRING_LITERALS:
861 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
862 i++) {
863 DumpCstringChar(Contents[i]);
864 }
865 outs() << "\n";
866 break;
867 case MachO::S_4BYTE_LITERALS:
868 float f;
869 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
870 uint32_t l;
871 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
872 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
873 sys::swapByteOrder(f);
874 sys::swapByteOrder(l);
875 }
876 DumpLiteral4(l, f);
877 break;
878 case MachO::S_8BYTE_LITERALS: {
879 double d;
880 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
881 uint32_t l0, l1;
882 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
883 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
884 sizeof(uint32_t));
885 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
886 sys::swapByteOrder(f);
887 sys::swapByteOrder(l0);
888 sys::swapByteOrder(l1);
889 }
890 DumpLiteral8(O, l0, l1, d);
891 break;
892 }
893 case MachO::S_16BYTE_LITERALS: {
894 uint32_t l0, l1, l2, l3;
895 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
896 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
897 sizeof(uint32_t));
898 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
899 sizeof(uint32_t));
900 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
901 sizeof(uint32_t));
902 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
903 sys::swapByteOrder(l0);
904 sys::swapByteOrder(l1);
905 sys::swapByteOrder(l2);
906 sys::swapByteOrder(l3);
907 }
908 DumpLiteral16(l0, l1, l2, l3);
909 break;
910 }
911 }
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000912 }
913}
914
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000915static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
916 uint32_t sect_size, uint64_t sect_addr,
917 SymbolAddressMap *AddrMap,
918 bool verbose) {
919 uint32_t stride;
920 if (O->is64Bit())
921 stride = sizeof(uint64_t);
922 else
923 stride = sizeof(uint32_t);
924 for (uint32_t i = 0; i < sect_size; i += stride) {
925 const char *SymbolName = nullptr;
926 if (O->is64Bit()) {
927 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
928 uint64_t pointer_value;
929 memcpy(&pointer_value, sect + i, stride);
930 if (O->isLittleEndian() != sys::IsLittleEndianHost)
931 sys::swapByteOrder(pointer_value);
932 outs() << format("0x%016" PRIx64, pointer_value);
933 if (verbose)
934 SymbolName = GuessSymbolName(pointer_value, AddrMap);
935 } else {
936 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
937 uint32_t pointer_value;
938 memcpy(&pointer_value, sect + i, stride);
939 if (O->isLittleEndian() != sys::IsLittleEndianHost)
940 sys::swapByteOrder(pointer_value);
941 outs() << format("0x%08" PRIx32, pointer_value);
942 if (verbose)
943 SymbolName = GuessSymbolName(pointer_value, AddrMap);
944 }
945 if (SymbolName)
946 outs() << " " << SymbolName;
947 outs() << "\n";
948 }
949}
950
951static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
952 uint32_t size, uint64_t addr) {
953 uint32_t cputype = O->getHeader().cputype;
954 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
955 uint32_t j;
956 for (uint32_t i = 0; i < size; i += j, addr += j) {
957 if (O->is64Bit())
958 outs() << format("%016" PRIx64, addr) << "\t";
959 else
Kevin Enderbyf0640752015-03-13 17:56:32 +0000960 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000961 for (j = 0; j < 16 && i + j < size; j++) {
962 uint8_t byte_word = *(sect + i + j);
963 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
964 }
965 outs() << "\n";
966 }
967 } else {
968 uint32_t j;
969 for (uint32_t i = 0; i < size; i += j, addr += j) {
970 if (O->is64Bit())
971 outs() << format("%016" PRIx64, addr) << "\t";
972 else
973 outs() << format("%08" PRIx64, sect) << "\t";
974 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
975 j += sizeof(int32_t)) {
976 if (i + j + sizeof(int32_t) < size) {
977 uint32_t long_word;
978 memcpy(&long_word, sect + i + j, sizeof(int32_t));
979 if (O->isLittleEndian() != sys::IsLittleEndianHost)
980 sys::swapByteOrder(long_word);
981 outs() << format("%08" PRIx32, long_word) << " ";
982 } else {
983 for (uint32_t k = 0; i + j + k < size; k++) {
984 uint8_t byte_word = *(sect + i + j);
985 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
986 }
987 }
988 }
989 outs() << "\n";
990 }
991 }
992}
993
Kevin Enderby95df54c2015-02-04 01:01:38 +0000994static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
995 StringRef DisSegName, StringRef DisSectName);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +0000996static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
997 uint32_t size, uint32_t addr);
Kevin Enderby95df54c2015-02-04 01:01:38 +0000998
999static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1000 bool verbose) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001001 SymbolAddressMap AddrMap;
1002 if (verbose)
1003 CreateSymbolAddressMap(O, &AddrMap);
1004
Colin LeMahieufcc32762015-07-29 19:08:10 +00001005 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1006 StringRef DumpSection = FilterSections[i];
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001007 std::pair<StringRef, StringRef> DumpSegSectName;
1008 DumpSegSectName = DumpSection.split(',');
1009 StringRef DumpSegName, DumpSectName;
1010 if (DumpSegSectName.second.size()) {
1011 DumpSegName = DumpSegSectName.first;
1012 DumpSectName = DumpSegSectName.second;
1013 } else {
1014 DumpSegName = "";
1015 DumpSectName = DumpSegSectName.first;
1016 }
1017 for (const SectionRef &Section : O->sections()) {
1018 StringRef SectName;
1019 Section.getName(SectName);
1020 DataRefImpl Ref = Section.getRawDataRefImpl();
1021 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1022 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1023 (SectName == DumpSectName)) {
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001024
Kevin Enderby95df54c2015-02-04 01:01:38 +00001025 uint32_t section_flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001026 if (O->is64Bit()) {
1027 const MachO::section_64 Sec = O->getSection64(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001028 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001029
1030 } else {
1031 const MachO::section Sec = O->getSection(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001032 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001033 }
Kevin Enderby95df54c2015-02-04 01:01:38 +00001034 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001035
1036 StringRef BytesStr;
1037 Section.getContents(BytesStr);
1038 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1039 uint32_t sect_size = BytesStr.size();
1040 uint64_t sect_addr = Section.getAddress();
1041
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001042 outs() << "Contents of (" << SegName << "," << SectName
1043 << ") section\n";
1044
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001045 if (verbose) {
Kevin Enderby95df54c2015-02-04 01:01:38 +00001046 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1047 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1048 DisassembleMachO(Filename, O, SegName, SectName);
1049 continue;
1050 }
Kevin Enderbycd66be52015-03-11 22:06:32 +00001051 if (SegName == "__TEXT" && SectName == "__info_plist") {
1052 outs() << sect;
1053 continue;
1054 }
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001055 if (SegName == "__OBJC" && SectName == "__protocol") {
1056 DumpProtocolSection(O, sect, sect_size, sect_addr);
1057 continue;
1058 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001059 switch (section_type) {
1060 case MachO::S_REGULAR:
1061 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1062 break;
1063 case MachO::S_ZEROFILL:
1064 outs() << "zerofill section and has no contents in the file\n";
1065 break;
Kevin Enderby10ba0412015-02-04 21:38:42 +00001066 case MachO::S_CSTRING_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001067 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001068 break;
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001069 case MachO::S_4BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001070 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001071 break;
1072 case MachO::S_8BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001073 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001074 break;
1075 case MachO::S_16BYTE_LITERALS:
Kevin Enderby0fc11822015-04-01 20:57:01 +00001076 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1077 break;
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001078 case MachO::S_LITERAL_POINTERS:
1079 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001080 !NoLeadingAddr);
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001081 break;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001082 case MachO::S_MOD_INIT_FUNC_POINTERS:
1083 case MachO::S_MOD_TERM_FUNC_POINTERS:
1084 DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
1085 verbose);
1086 break;
1087 default:
1088 outs() << "Unknown section type ("
1089 << format("0x%08" PRIx32, section_type) << ")\n";
1090 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1091 break;
1092 }
1093 } else {
1094 if (section_type == MachO::S_ZEROFILL)
1095 outs() << "zerofill section and has no contents in the file\n";
1096 else
1097 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1098 }
1099 }
1100 }
1101 }
1102}
1103
Kevin Enderbycd66be52015-03-11 22:06:32 +00001104static void DumpInfoPlistSectionContents(StringRef Filename,
1105 MachOObjectFile *O) {
1106 for (const SectionRef &Section : O->sections()) {
1107 StringRef SectName;
1108 Section.getName(SectName);
1109 DataRefImpl Ref = Section.getRawDataRefImpl();
1110 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1111 if (SegName == "__TEXT" && SectName == "__info_plist") {
1112 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1113 StringRef BytesStr;
1114 Section.getContents(BytesStr);
1115 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1116 outs() << sect;
1117 return;
1118 }
1119 }
1120}
1121
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001122// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1123// and if it is and there is a list of architecture flags is specified then
1124// check to make sure this Mach-O file is one of those architectures or all
1125// architectures were specified. If not then an error is generated and this
1126// routine returns false. Else it returns true.
1127static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1128 if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
1129 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
1130 bool ArchFound = false;
1131 MachO::mach_header H;
1132 MachO::mach_header_64 H_64;
1133 Triple T;
1134 if (MachO->is64Bit()) {
1135 H_64 = MachO->MachOObjectFile::getHeader64();
1136 T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
1137 } else {
1138 H = MachO->MachOObjectFile::getHeader();
1139 T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
1140 }
1141 unsigned i;
1142 for (i = 0; i < ArchFlags.size(); ++i) {
1143 if (ArchFlags[i] == T.getArchName())
1144 ArchFound = true;
1145 break;
1146 }
1147 if (!ArchFound) {
1148 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1149 << "architecture: " + ArchFlags[i] + "\n";
1150 return false;
1151 }
1152 }
1153 return true;
1154}
1155
Kevin Enderby0fc11822015-04-01 20:57:01 +00001156static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1157
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001158// ProcessMachO() is passed a single opened Mach-O file, which may be an
1159// archive member and or in a slice of a universal file. It prints the
1160// the file name and header info and then processes it according to the
1161// command line options.
1162static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
1163 StringRef ArchiveMemberName = StringRef(),
1164 StringRef ArchitectureName = StringRef()) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001165 // If we are doing some processing here on the Mach-O file print the header
1166 // info. And don't print it otherwise like in the case of printing the
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001167 // UniversalHeaders or ArchiveHeaders.
Kevin Enderby131d1772015-01-09 19:22:37 +00001168 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind ||
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001169 LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints ||
Colin LeMahieufcc32762015-07-29 19:08:10 +00001170 DylibsUsed || DylibId || ObjcMetaData || (FilterSections.size() != 0)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001171 outs() << Filename;
1172 if (!ArchiveMemberName.empty())
1173 outs() << '(' << ArchiveMemberName << ')';
1174 if (!ArchitectureName.empty())
1175 outs() << " (architecture " << ArchitectureName << ")";
1176 outs() << ":\n";
1177 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001178
1179 if (Disassemble)
Kevin Enderby95df54c2015-02-04 01:01:38 +00001180 DisassembleMachO(Filename, MachOOF, "__TEXT", "__text");
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001181 if (IndirectSymbols)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001182 PrintIndirectSymbols(MachOOF, !NonVerbose);
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001183 if (DataInCode)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001184 PrintDataInCodeTable(MachOOF, !NonVerbose);
Kevin Enderby9a509442015-01-27 21:28:24 +00001185 if (LinkOptHints)
1186 PrintLinkOptHints(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001187 if (Relocations)
1188 PrintRelocations(MachOOF);
1189 if (SectionHeaders)
1190 PrintSectionHeaders(MachOOF);
1191 if (SectionContents)
1192 PrintSectionContents(MachOOF);
Colin LeMahieufcc32762015-07-29 19:08:10 +00001193 if (FilterSections.size() != 0)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001194 DumpSectionContents(Filename, MachOOF, !NonVerbose);
Kevin Enderbycd66be52015-03-11 22:06:32 +00001195 if (InfoPlist)
1196 DumpInfoPlistSectionContents(Filename, MachOOF);
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001197 if (DylibsUsed)
1198 PrintDylibs(MachOOF, false);
1199 if (DylibId)
1200 PrintDylibs(MachOOF, true);
Kevin Enderby98da6132015-01-20 21:47:46 +00001201 if (SymbolTable)
1202 PrintSymbolTable(MachOOF);
1203 if (UnwindInfo)
1204 printMachOUnwindInfo(MachOOF);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001205 if (PrivateHeaders)
1206 printMachOFileHeader(MachOOF);
Kevin Enderby0fc11822015-04-01 20:57:01 +00001207 if (ObjcMetaData)
1208 printObjcMetaData(MachOOF, !NonVerbose);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001209 if (ExportsTrie)
1210 printExportsTrie(MachOOF);
1211 if (Rebase)
1212 printRebaseTable(MachOOF);
1213 if (Bind)
1214 printBindTable(MachOOF);
1215 if (LazyBind)
1216 printLazyBindTable(MachOOF);
1217 if (WeakBind)
1218 printWeakBindTable(MachOOF);
1219}
1220
Kevin Enderby131d1772015-01-09 19:22:37 +00001221// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1222static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1223 outs() << " cputype (" << cputype << ")\n";
1224 outs() << " cpusubtype (" << cpusubtype << ")\n";
1225}
1226
1227// printCPUType() helps print_fat_headers by printing the cputype and
1228// pusubtype (symbolically for the one's it knows about).
1229static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1230 switch (cputype) {
1231 case MachO::CPU_TYPE_I386:
1232 switch (cpusubtype) {
1233 case MachO::CPU_SUBTYPE_I386_ALL:
1234 outs() << " cputype CPU_TYPE_I386\n";
1235 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1236 break;
1237 default:
1238 printUnknownCPUType(cputype, cpusubtype);
1239 break;
1240 }
1241 break;
1242 case MachO::CPU_TYPE_X86_64:
1243 switch (cpusubtype) {
1244 case MachO::CPU_SUBTYPE_X86_64_ALL:
1245 outs() << " cputype CPU_TYPE_X86_64\n";
1246 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1247 break;
1248 case MachO::CPU_SUBTYPE_X86_64_H:
1249 outs() << " cputype CPU_TYPE_X86_64\n";
1250 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1251 break;
1252 default:
1253 printUnknownCPUType(cputype, cpusubtype);
1254 break;
1255 }
1256 break;
1257 case MachO::CPU_TYPE_ARM:
1258 switch (cpusubtype) {
1259 case MachO::CPU_SUBTYPE_ARM_ALL:
1260 outs() << " cputype CPU_TYPE_ARM\n";
1261 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1262 break;
1263 case MachO::CPU_SUBTYPE_ARM_V4T:
1264 outs() << " cputype CPU_TYPE_ARM\n";
1265 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1266 break;
1267 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1268 outs() << " cputype CPU_TYPE_ARM\n";
1269 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1270 break;
1271 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1272 outs() << " cputype CPU_TYPE_ARM\n";
1273 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1274 break;
1275 case MachO::CPU_SUBTYPE_ARM_V6:
1276 outs() << " cputype CPU_TYPE_ARM\n";
1277 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1278 break;
1279 case MachO::CPU_SUBTYPE_ARM_V6M:
1280 outs() << " cputype CPU_TYPE_ARM\n";
1281 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1282 break;
1283 case MachO::CPU_SUBTYPE_ARM_V7:
1284 outs() << " cputype CPU_TYPE_ARM\n";
1285 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1286 break;
1287 case MachO::CPU_SUBTYPE_ARM_V7EM:
1288 outs() << " cputype CPU_TYPE_ARM\n";
1289 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1290 break;
1291 case MachO::CPU_SUBTYPE_ARM_V7K:
1292 outs() << " cputype CPU_TYPE_ARM\n";
1293 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1294 break;
1295 case MachO::CPU_SUBTYPE_ARM_V7M:
1296 outs() << " cputype CPU_TYPE_ARM\n";
1297 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1298 break;
1299 case MachO::CPU_SUBTYPE_ARM_V7S:
1300 outs() << " cputype CPU_TYPE_ARM\n";
1301 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1302 break;
1303 default:
1304 printUnknownCPUType(cputype, cpusubtype);
1305 break;
1306 }
1307 break;
1308 case MachO::CPU_TYPE_ARM64:
1309 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1310 case MachO::CPU_SUBTYPE_ARM64_ALL:
1311 outs() << " cputype CPU_TYPE_ARM64\n";
1312 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1313 break;
1314 default:
1315 printUnknownCPUType(cputype, cpusubtype);
1316 break;
1317 }
1318 break;
1319 default:
1320 printUnknownCPUType(cputype, cpusubtype);
1321 break;
1322 }
1323}
1324
1325static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1326 bool verbose) {
1327 outs() << "Fat headers\n";
1328 if (verbose)
1329 outs() << "fat_magic FAT_MAGIC\n";
1330 else
1331 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1332
1333 uint32_t nfat_arch = UB->getNumberOfObjects();
1334 StringRef Buf = UB->getData();
1335 uint64_t size = Buf.size();
1336 uint64_t big_size = sizeof(struct MachO::fat_header) +
1337 nfat_arch * sizeof(struct MachO::fat_arch);
1338 outs() << "nfat_arch " << UB->getNumberOfObjects();
1339 if (nfat_arch == 0)
1340 outs() << " (malformed, contains zero architecture types)\n";
1341 else if (big_size > size)
1342 outs() << " (malformed, architectures past end of file)\n";
1343 else
1344 outs() << "\n";
1345
1346 for (uint32_t i = 0; i < nfat_arch; ++i) {
1347 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1348 uint32_t cputype = OFA.getCPUType();
1349 uint32_t cpusubtype = OFA.getCPUSubType();
1350 outs() << "architecture ";
1351 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1352 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1353 uint32_t other_cputype = other_OFA.getCPUType();
1354 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
Kevin Enderby0512bd72015-01-09 21:55:03 +00001355 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
Kevin Enderby131d1772015-01-09 19:22:37 +00001356 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
Kevin Enderby0512bd72015-01-09 21:55:03 +00001357 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001358 outs() << "(illegal duplicate architecture) ";
1359 break;
Kevin Enderby0512bd72015-01-09 21:55:03 +00001360 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001361 }
1362 if (verbose) {
1363 outs() << OFA.getArchTypeName() << "\n";
1364 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1365 } else {
1366 outs() << i << "\n";
1367 outs() << " cputype " << cputype << "\n";
1368 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1369 << "\n";
1370 }
1371 if (verbose &&
1372 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1373 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1374 else
1375 outs() << " capabilities "
1376 << format("0x%" PRIx32,
1377 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1378 outs() << " offset " << OFA.getOffset();
1379 if (OFA.getOffset() > size)
1380 outs() << " (past end of file)";
1381 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1382 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1383 outs() << "\n";
1384 outs() << " size " << OFA.getSize();
1385 big_size = OFA.getOffset() + OFA.getSize();
1386 if (big_size > size)
1387 outs() << " (past end of file)";
1388 outs() << "\n";
1389 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1390 << ")\n";
1391 }
1392}
1393
Rafael Espindola266b4fe2015-10-31 22:25:59 +00001394static void printArchiveChild(const Archive::Child &C, bool verbose,
Kevin Enderby13023a12015-01-15 23:19:11 +00001395 bool print_offset) {
1396 if (print_offset)
1397 outs() << C.getChildOffset() << "\t";
1398 sys::fs::perms Mode = C.getAccessMode();
1399 if (verbose) {
1400 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1401 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1402 outs() << "-";
Davide Italianobb9a6cc2015-09-07 20:47:03 +00001403 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1404 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1405 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1406 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1407 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1408 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1409 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1410 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1411 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
Kevin Enderby13023a12015-01-15 23:19:11 +00001412 } else {
1413 outs() << format("0%o ", Mode);
1414 }
1415
1416 unsigned UID = C.getUID();
1417 outs() << format("%3d/", UID);
1418 unsigned GID = C.getGID();
1419 outs() << format("%-3d ", GID);
Kevin Enderby7a969422015-11-05 19:24:56 +00001420 ErrorOr<uint64_t> Size = C.getRawSize();
1421 if (std::error_code EC = Size.getError())
1422 report_fatal_error(EC.message());
1423 outs() << format("%5" PRId64, Size.get()) << " ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001424
1425 StringRef RawLastModified = C.getRawLastModified();
1426 if (verbose) {
1427 unsigned Seconds;
1428 if (RawLastModified.getAsInteger(10, Seconds))
1429 outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
1430 else {
1431 // Since cime(3) returns a 26 character string of the form:
1432 // "Sun Sep 16 01:03:52 1973\n\0"
1433 // just print 24 characters.
1434 time_t t = Seconds;
1435 outs() << format("%.24s ", ctime(&t));
1436 }
1437 } else {
1438 outs() << RawLastModified << " ";
1439 }
1440
1441 if (verbose) {
1442 ErrorOr<StringRef> NameOrErr = C.getName();
1443 if (NameOrErr.getError()) {
1444 StringRef RawName = C.getRawName();
1445 outs() << RawName << "\n";
1446 } else {
1447 StringRef Name = NameOrErr.get();
1448 outs() << Name << "\n";
1449 }
1450 } else {
1451 StringRef RawName = C.getRawName();
1452 outs() << RawName << "\n";
1453 }
1454}
1455
1456static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
Rafael Espindola4a782fb2015-10-31 21:03:29 +00001457 for (Archive::child_iterator I = A->child_begin(false), E = A->child_end();
1458 I != E; ++I) {
Kevin Enderby7a969422015-11-05 19:24:56 +00001459 if (std::error_code EC = I->getError())
1460 report_fatal_error(EC.message());
1461 const Archive::Child &C = **I;
Kevin Enderby13023a12015-01-15 23:19:11 +00001462 printArchiveChild(C, verbose, print_offset);
1463 }
1464}
1465
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001466// ParseInputMachO() parses the named Mach-O file in Filename and handles the
1467// -arch flags selecting just those slices as specified by them and also parses
1468// archive files. Then for each individual Mach-O file ProcessMachO() is
1469// called to process the file based on the command line options.
1470void llvm::ParseInputMachO(StringRef Filename) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001471 // Check for -arch all and verifiy the -arch flags are valid.
1472 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1473 if (ArchFlags[i] == "all") {
1474 ArchAll = true;
1475 } else {
1476 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1477 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1478 "'for the -arch option\n";
1479 return;
1480 }
1481 }
1482 }
1483
1484 // Attempt to open the binary.
1485 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1486 if (std::error_code EC = BinaryOrErr.getError()) {
1487 errs() << "llvm-objdump: '" << Filename << "': " << EC.message() << ".\n";
Rafael Espindolade882cd2014-12-03 23:29:34 +00001488 return;
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001489 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001490 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001491
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001492 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1493 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001494 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001495 printArchiveHeaders(A, !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001496 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
1497 I != E; ++I) {
Kevin Enderby7a969422015-11-05 19:24:56 +00001498 if (std::error_code EC = I->getError()) {
1499 errs() << "llvm-objdump: '" << Filename << "': " << EC.message()
1500 << ".\n";
1501 exit(1);
1502 }
1503 auto &C = I->get();
1504 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001505 if (ChildOrErr.getError())
1506 continue;
1507 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1508 if (!checkMachOAndArchFlags(O, Filename))
1509 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001510 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001511 }
1512 }
1513 return;
1514 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001515 if (UniversalHeaders) {
1516 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
Kevin Enderbyf0640752015-03-13 17:56:32 +00001517 printMachOUniversalHeaders(UB, !NonVerbose);
Kevin Enderby131d1772015-01-09 19:22:37 +00001518 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001519 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1520 // If we have a list of architecture flags specified dump only those.
1521 if (!ArchAll && ArchFlags.size() != 0) {
1522 // Look for a slice in the universal binary that matches each ArchFlag.
1523 bool ArchFound;
1524 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1525 ArchFound = false;
1526 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1527 E = UB->end_objects();
1528 I != E; ++I) {
1529 if (ArchFlags[i] == I->getArchTypeName()) {
1530 ArchFound = true;
1531 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
1532 I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001533 std::string ArchitectureName = "";
1534 if (ArchFlags.size() > 1)
1535 ArchitectureName = I->getArchTypeName();
1536 if (ObjOrErr) {
1537 ObjectFile &O = *ObjOrErr.get();
1538 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001539 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001540 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1541 I->getAsArchive()) {
1542 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001543 outs() << "Archive : " << Filename;
1544 if (!ArchitectureName.empty())
1545 outs() << " (architecture " << ArchitectureName << ")";
1546 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001547 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001548 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001549 for (Archive::child_iterator AI = A->child_begin(),
1550 AE = A->child_end();
1551 AI != AE; ++AI) {
Kevin Enderby7a969422015-11-05 19:24:56 +00001552 if (std::error_code EC = AI->getError()) {
1553 errs() << "llvm-objdump: '" << Filename
1554 << "': " << EC.message() << ".\n";
1555 exit(1);
1556 }
1557 auto &C = AI->get();
1558 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001559 if (ChildOrErr.getError())
1560 continue;
1561 if (MachOObjectFile *O =
1562 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001563 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001564 }
1565 }
1566 }
1567 }
1568 if (!ArchFound) {
1569 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1570 << "architecture: " + ArchFlags[i] + "\n";
1571 return;
1572 }
1573 }
1574 return;
1575 }
1576 // No architecture flags were specified so if this contains a slice that
1577 // matches the host architecture dump only that.
1578 if (!ArchAll) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001579 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1580 E = UB->end_objects();
1581 I != E; ++I) {
Kevin Enderby0512bd72015-01-09 21:55:03 +00001582 if (MachOObjectFile::getHostArch().getArchName() ==
1583 I->getArchTypeName()) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001584 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001585 std::string ArchiveName;
1586 ArchiveName.clear();
1587 if (ObjOrErr) {
1588 ObjectFile &O = *ObjOrErr.get();
1589 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001590 ProcessMachO(Filename, MachOOF);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001591 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1592 I->getAsArchive()) {
1593 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001594 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001595 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001596 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001597 for (Archive::child_iterator AI = A->child_begin(),
1598 AE = A->child_end();
1599 AI != AE; ++AI) {
Kevin Enderby7a969422015-11-05 19:24:56 +00001600 if (std::error_code EC = AI->getError()) {
1601 errs() << "llvm-objdump: '" << Filename << "': " << EC.message()
1602 << ".\n";
1603 exit(1);
1604 }
1605 auto &C = AI->get();
1606 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001607 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());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001612 }
1613 }
1614 return;
1615 }
1616 }
1617 }
1618 // Either all architectures have been specified or none have been specified
1619 // and this does not contain the host architecture so dump all the slices.
1620 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1621 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1622 E = UB->end_objects();
1623 I != E; ++I) {
1624 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001625 std::string ArchitectureName = "";
1626 if (moreThanOneArch)
1627 ArchitectureName = I->getArchTypeName();
1628 if (ObjOrErr) {
1629 ObjectFile &Obj = *ObjOrErr.get();
1630 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001631 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001632 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
1633 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001634 outs() << "Archive : " << Filename;
1635 if (!ArchitectureName.empty())
1636 outs() << " (architecture " << ArchitectureName << ")";
1637 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001638 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001639 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001640 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
1641 AI != AE; ++AI) {
Kevin Enderby7a969422015-11-05 19:24:56 +00001642 if (std::error_code EC = AI->getError()) {
1643 errs() << "llvm-objdump: '" << Filename << "': " << EC.message()
1644 << ".\n";
1645 exit(1);
1646 }
1647 auto &C = AI->get();
1648 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001649 if (ChildOrErr.getError())
1650 continue;
1651 if (MachOObjectFile *O =
1652 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1653 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001654 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1655 ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001656 }
1657 }
1658 }
1659 }
1660 return;
1661 }
1662 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1663 if (!checkMachOAndArchFlags(O, Filename))
1664 return;
1665 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001666 ProcessMachO(Filename, MachOOF);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001667 } else
1668 errs() << "llvm-objdump: '" << Filename << "': "
1669 << "Object is not a Mach-O file type.\n";
1670 } else
1671 errs() << "llvm-objdump: '" << Filename << "': "
1672 << "Unrecognized file type.\n";
Rafael Espindola9b709252013-04-13 01:45:40 +00001673}
1674
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001675typedef std::pair<uint64_t, const char *> BindInfoEntry;
1676typedef std::vector<BindInfoEntry> BindTable;
1677typedef BindTable::iterator bind_table_iterator;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001678
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001679// The block of info used by the Symbolizer call backs.
1680struct DisassembleInfo {
1681 bool verbose;
1682 MachOObjectFile *O;
1683 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001684 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001685 std::vector<SectionRef> *Sections;
1686 const char *class_name;
1687 const char *selector_name;
1688 char *method;
Kevin Enderby04bf6932014-10-28 23:39:46 +00001689 char *demangled_name;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001690 uint64_t adrp_addr;
1691 uint32_t adrp_inst;
Kevin Enderby078be602014-10-23 19:53:12 +00001692 BindTable *bindtable;
Kevin Enderbyaac75382015-10-08 16:56:35 +00001693 uint32_t depth;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001694};
1695
1696// SymbolizerGetOpInfo() is the operand information call back function.
1697// This is called to get the symbolic information for operand(s) of an
1698// instruction when it is being done. This routine does this from
1699// the relocation information, symbol table, etc. That block of information
1700// is a pointer to the struct DisassembleInfo that was passed when the
1701// disassembler context was created and passed to back to here when
1702// called back by the disassembler for instruction operands that could have
1703// relocation information. The address of the instruction containing operand is
1704// at the Pc parameter. The immediate value the operand has is passed in
1705// op_info->Value and is at Offset past the start of the instruction and has a
1706// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1707// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1708// names and addends of the symbolic expression to add for the operand. The
1709// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1710// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001711static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1712 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001713 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1714 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001715 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001716
1717 // Make sure all fields returned are zero if we don't set them.
1718 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1719 op_info->Value = value;
1720
1721 // If the TagType is not the value 1 which it code knows about or if no
1722 // verbose symbolic information is wanted then just return 0, indicating no
1723 // information is being returned.
David Blaikie33dd45d02015-03-23 18:39:02 +00001724 if (TagType != 1 || !info->verbose)
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001725 return 0;
1726
1727 unsigned int Arch = info->O->getArch();
1728 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001729 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1730 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001731 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1732 // TODO:
1733 // Search the external relocation entries of a fully linked image
1734 // (if any) for an entry that matches this segment offset.
1735 // uint32_t seg_offset = (Pc + Offset);
1736 return 0;
1737 }
1738 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1739 // for an entry for this section offset.
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001740 uint32_t sect_addr = info->S.getAddress();
1741 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1742 bool reloc_found = false;
1743 DataRefImpl Rel;
1744 MachO::any_relocation_info RE;
1745 bool isExtern = false;
1746 SymbolRef Symbol;
1747 bool r_scattered = false;
1748 uint32_t r_value, pair_r_value, r_type;
1749 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001750 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001751 if (RelocOffset == sect_offset) {
1752 Rel = Reloc.getRawDataRefImpl();
1753 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00001754 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001755 r_scattered = info->O->isRelocationScattered(RE);
1756 if (r_scattered) {
1757 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001758 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1759 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1760 DataRefImpl RelNext = Rel;
1761 info->O->moveRelocationNext(RelNext);
1762 MachO::any_relocation_info RENext;
1763 RENext = info->O->getRelocation(RelNext);
1764 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00001765 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001766 else
1767 return 0;
1768 }
1769 } else {
1770 isExtern = info->O->getPlainRelocationExternal(RE);
1771 if (isExtern) {
1772 symbol_iterator RelocSym = Reloc.getSymbol();
1773 Symbol = *RelocSym;
1774 }
1775 }
1776 reloc_found = true;
1777 break;
1778 }
1779 }
1780 if (reloc_found && isExtern) {
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001781 ErrorOr<StringRef> SymName = Symbol.getName();
1782 if (std::error_code EC = SymName.getError())
1783 report_fatal_error(EC.message());
1784 const char *name = SymName->data();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001785 op_info->AddSymbol.Present = 1;
1786 op_info->AddSymbol.Name = name;
1787 // For i386 extern relocation entries the value in the instruction is
1788 // the offset from the symbol, and value is already set in op_info->Value.
1789 return 1;
1790 }
1791 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1792 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001793 const char *add = GuessSymbolName(r_value, info->AddrMap);
1794 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001795 uint32_t offset = value - (r_value - pair_r_value);
1796 op_info->AddSymbol.Present = 1;
1797 if (add != nullptr)
1798 op_info->AddSymbol.Name = add;
1799 else
1800 op_info->AddSymbol.Value = r_value;
1801 op_info->SubtractSymbol.Present = 1;
1802 if (sub != nullptr)
1803 op_info->SubtractSymbol.Name = sub;
1804 else
1805 op_info->SubtractSymbol.Value = pair_r_value;
1806 op_info->Value = offset;
1807 return 1;
1808 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001809 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001810 }
1811 if (Arch == Triple::x86_64) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001812 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1813 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001814 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1815 // TODO:
1816 // Search the external relocation entries of a fully linked image
1817 // (if any) for an entry that matches this segment offset.
1818 // uint64_t seg_offset = (Pc + Offset);
1819 return 0;
1820 }
1821 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1822 // for an entry for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00001823 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001824 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1825 bool reloc_found = false;
1826 DataRefImpl Rel;
1827 MachO::any_relocation_info RE;
1828 bool isExtern = false;
1829 SymbolRef Symbol;
1830 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001831 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001832 if (RelocOffset == sect_offset) {
1833 Rel = Reloc.getRawDataRefImpl();
1834 RE = info->O->getRelocation(Rel);
1835 // NOTE: Scattered relocations don't exist on x86_64.
1836 isExtern = info->O->getPlainRelocationExternal(RE);
1837 if (isExtern) {
1838 symbol_iterator RelocSym = Reloc.getSymbol();
1839 Symbol = *RelocSym;
1840 }
1841 reloc_found = true;
1842 break;
1843 }
1844 }
1845 if (reloc_found && isExtern) {
1846 // The Value passed in will be adjusted by the Pc if the instruction
1847 // adds the Pc. But for x86_64 external relocation entries the Value
1848 // is the offset from the external symbol.
1849 if (info->O->getAnyRelocationPCRel(RE))
1850 op_info->Value -= Pc + Offset + Size;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001851 ErrorOr<StringRef> SymName = Symbol.getName();
1852 if (std::error_code EC = SymName.getError())
1853 report_fatal_error(EC.message());
1854 const char *name = SymName->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001855 unsigned Type = info->O->getAnyRelocationType(RE);
1856 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1857 DataRefImpl RelNext = Rel;
1858 info->O->moveRelocationNext(RelNext);
1859 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1860 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1861 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1862 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1863 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1864 op_info->SubtractSymbol.Present = 1;
1865 op_info->SubtractSymbol.Name = name;
1866 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1867 Symbol = *RelocSymNext;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001868 ErrorOr<StringRef> SymNameNext = Symbol.getName();
1869 if (std::error_code EC = SymNameNext.getError())
1870 report_fatal_error(EC.message());
1871 name = SymNameNext->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001872 }
1873 }
1874 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1875 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1876 op_info->AddSymbol.Present = 1;
1877 op_info->AddSymbol.Name = name;
1878 return 1;
1879 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001880 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001881 }
1882 if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00001883 if (Offset != 0 || (Size != 4 && Size != 2))
1884 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001885 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1886 // TODO:
1887 // Search the external relocation entries of a fully linked image
1888 // (if any) for an entry that matches this segment offset.
1889 // uint32_t seg_offset = (Pc + Offset);
1890 return 0;
1891 }
1892 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1893 // for an entry for this section offset.
Kevin Enderby930fdc72014-11-06 19:00:13 +00001894 uint32_t sect_addr = info->S.getAddress();
1895 uint32_t sect_offset = (Pc + Offset) - sect_addr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001896 DataRefImpl Rel;
1897 MachO::any_relocation_info RE;
1898 bool isExtern = false;
1899 SymbolRef Symbol;
1900 bool r_scattered = false;
1901 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
David Blaikie33dd45d02015-03-23 18:39:02 +00001902 auto Reloc =
1903 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
1904 [&](const RelocationRef &Reloc) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001905 uint64_t RelocOffset = Reloc.getOffset();
David Blaikie33dd45d02015-03-23 18:39:02 +00001906 return RelocOffset == sect_offset;
1907 });
1908
1909 if (Reloc == info->S.relocations().end())
1910 return 0;
1911
1912 Rel = Reloc->getRawDataRefImpl();
1913 RE = info->O->getRelocation(Rel);
1914 r_length = info->O->getAnyRelocationLength(RE);
1915 r_scattered = info->O->isRelocationScattered(RE);
1916 if (r_scattered) {
1917 r_value = info->O->getScatteredRelocationValue(RE);
1918 r_type = info->O->getScatteredRelocationType(RE);
1919 } else {
1920 r_type = info->O->getAnyRelocationType(RE);
1921 isExtern = info->O->getPlainRelocationExternal(RE);
1922 if (isExtern) {
1923 symbol_iterator RelocSym = Reloc->getSymbol();
1924 Symbol = *RelocSym;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001925 }
1926 }
David Blaikie33dd45d02015-03-23 18:39:02 +00001927 if (r_type == MachO::ARM_RELOC_HALF ||
1928 r_type == MachO::ARM_RELOC_SECTDIFF ||
1929 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1930 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1931 DataRefImpl RelNext = Rel;
1932 info->O->moveRelocationNext(RelNext);
1933 MachO::any_relocation_info RENext;
1934 RENext = info->O->getRelocation(RelNext);
1935 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
1936 if (info->O->isRelocationScattered(RENext))
1937 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1938 }
1939
1940 if (isExtern) {
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001941 ErrorOr<StringRef> SymName = Symbol.getName();
1942 if (std::error_code EC = SymName.getError())
1943 report_fatal_error(EC.message());
1944 const char *name = SymName->data();
Kevin Enderby930fdc72014-11-06 19:00:13 +00001945 op_info->AddSymbol.Present = 1;
1946 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00001947 switch (r_type) {
1948 case MachO::ARM_RELOC_HALF:
1949 if ((r_length & 0x1) == 1) {
1950 op_info->Value = value << 16 | other_half;
1951 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1952 } else {
1953 op_info->Value = other_half << 16 | value;
1954 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00001955 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00001956 break;
1957 default:
1958 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001959 }
1960 return 1;
1961 }
1962 // If we have a branch that is not an external relocation entry then
1963 // return 0 so the code in tryAddingSymbolicOperand() can use the
1964 // SymbolLookUp call back with the branch target address to look up the
1965 // symbol and possiblity add an annotation for a symbol stub.
David Blaikie33dd45d02015-03-23 18:39:02 +00001966 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
1967 r_type == MachO::ARM_THUMB_RELOC_BR22))
Kevin Enderby930fdc72014-11-06 19:00:13 +00001968 return 0;
1969
1970 uint32_t offset = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001971 if (r_type == MachO::ARM_RELOC_HALF ||
1972 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1973 if ((r_length & 0x1) == 1)
1974 value = value << 16 | other_half;
1975 else
1976 value = other_half << 16 | value;
1977 }
1978 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
1979 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
1980 offset = value - r_value;
1981 value = r_value;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001982 }
1983
David Blaikie33dd45d02015-03-23 18:39:02 +00001984 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00001985 if ((r_length & 0x1) == 1)
1986 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1987 else
1988 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001989 const char *add = GuessSymbolName(r_value, info->AddrMap);
1990 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00001991 int32_t offset = value - (r_value - pair_r_value);
1992 op_info->AddSymbol.Present = 1;
1993 if (add != nullptr)
1994 op_info->AddSymbol.Name = add;
1995 else
1996 op_info->AddSymbol.Value = r_value;
1997 op_info->SubtractSymbol.Present = 1;
1998 if (sub != nullptr)
1999 op_info->SubtractSymbol.Name = sub;
2000 else
2001 op_info->SubtractSymbol.Value = pair_r_value;
2002 op_info->Value = offset;
2003 return 1;
2004 }
2005
Kevin Enderby930fdc72014-11-06 19:00:13 +00002006 op_info->AddSymbol.Present = 1;
2007 op_info->Value = offset;
David Blaikie33dd45d02015-03-23 18:39:02 +00002008 if (r_type == MachO::ARM_RELOC_HALF) {
2009 if ((r_length & 0x1) == 1)
2010 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2011 else
2012 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002013 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002014 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002015 if (add != nullptr) {
2016 op_info->AddSymbol.Name = add;
2017 return 1;
2018 }
2019 op_info->AddSymbol.Value = value;
2020 return 1;
David Blaikie33dd45d02015-03-23 18:39:02 +00002021 }
2022 if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002023 if (Offset != 0 || Size != 4)
2024 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002025 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2026 // TODO:
2027 // Search the external relocation entries of a fully linked image
2028 // (if any) for an entry that matches this segment offset.
2029 // uint64_t seg_offset = (Pc + Offset);
2030 return 0;
2031 }
2032 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2033 // for an entry for this section offset.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002034 uint64_t sect_addr = info->S.getAddress();
2035 uint64_t sect_offset = (Pc + Offset) - sect_addr;
David Blaikie33dd45d02015-03-23 18:39:02 +00002036 auto Reloc =
2037 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
2038 [&](const RelocationRef &Reloc) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002039 uint64_t RelocOffset = Reloc.getOffset();
David Blaikie33dd45d02015-03-23 18:39:02 +00002040 return RelocOffset == sect_offset;
2041 });
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002042
David Blaikie33dd45d02015-03-23 18:39:02 +00002043 if (Reloc == info->S.relocations().end())
2044 return 0;
2045
2046 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2047 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2048 uint32_t r_type = info->O->getAnyRelocationType(RE);
2049 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2050 DataRefImpl RelNext = Rel;
2051 info->O->moveRelocationNext(RelNext);
2052 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2053 if (value == 0) {
2054 value = info->O->getPlainRelocationSymbolNum(RENext);
2055 op_info->Value = value;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002056 }
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002057 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002058 // NOTE: Scattered relocations don't exist on arm64.
2059 if (!info->O->getPlainRelocationExternal(RE))
2060 return 0;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002061 ErrorOr<StringRef> SymName = Reloc->getSymbol()->getName();
2062 if (std::error_code EC = SymName.getError())
2063 report_fatal_error(EC.message());
2064 const char *name = SymName->data();
David Blaikie33dd45d02015-03-23 18:39:02 +00002065 op_info->AddSymbol.Present = 1;
2066 op_info->AddSymbol.Name = name;
2067
2068 switch (r_type) {
2069 case MachO::ARM64_RELOC_PAGE21:
2070 /* @page */
2071 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2072 break;
2073 case MachO::ARM64_RELOC_PAGEOFF12:
2074 /* @pageoff */
2075 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2076 break;
2077 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2078 /* @gotpage */
2079 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2080 break;
2081 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2082 /* @gotpageoff */
2083 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2084 break;
2085 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2086 /* @tvlppage is not implemented in llvm-mc */
2087 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2088 break;
2089 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2090 /* @tvlppageoff is not implemented in llvm-mc */
2091 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2092 break;
2093 default:
2094 case MachO::ARM64_RELOC_BRANCH26:
2095 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2096 break;
2097 }
2098 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002099 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002100 return 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002101}
2102
Kevin Enderbybf246f52014-09-24 23:08:22 +00002103// GuessCstringPointer is passed the address of what might be a pointer to a
2104// literal string in a cstring section. If that address is in a cstring section
2105// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002106static const char *GuessCstringPointer(uint64_t ReferenceValue,
2107 struct DisassembleInfo *info) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002108 for (const auto &Load : info->O->load_commands()) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002109 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2110 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2111 for (unsigned J = 0; J < Seg.nsects; ++J) {
2112 MachO::section_64 Sec = info->O->getSection64(Load, J);
2113 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2114 if (section_type == MachO::S_CSTRING_LITERALS &&
2115 ReferenceValue >= Sec.addr &&
2116 ReferenceValue < Sec.addr + Sec.size) {
2117 uint64_t sect_offset = ReferenceValue - Sec.addr;
2118 uint64_t object_offset = Sec.offset + sect_offset;
2119 StringRef MachOContents = info->O->getData();
2120 uint64_t object_size = MachOContents.size();
2121 const char *object_addr = (const char *)MachOContents.data();
2122 if (object_offset < object_size) {
2123 const char *name = object_addr + object_offset;
2124 return name;
2125 } else {
2126 return nullptr;
2127 }
2128 }
2129 }
2130 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2131 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2132 for (unsigned J = 0; J < Seg.nsects; ++J) {
2133 MachO::section Sec = info->O->getSection(Load, J);
2134 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2135 if (section_type == MachO::S_CSTRING_LITERALS &&
2136 ReferenceValue >= Sec.addr &&
2137 ReferenceValue < Sec.addr + Sec.size) {
2138 uint64_t sect_offset = ReferenceValue - Sec.addr;
2139 uint64_t object_offset = Sec.offset + sect_offset;
2140 StringRef MachOContents = info->O->getData();
2141 uint64_t object_size = MachOContents.size();
2142 const char *object_addr = (const char *)MachOContents.data();
2143 if (object_offset < object_size) {
2144 const char *name = object_addr + object_offset;
2145 return name;
2146 } else {
2147 return nullptr;
2148 }
2149 }
2150 }
2151 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002152 }
2153 return nullptr;
2154}
2155
Kevin Enderby85974882014-09-26 22:20:44 +00002156// GuessIndirectSymbol returns the name of the indirect symbol for the
2157// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2158// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2159// symbol name being referenced by the stub or pointer.
2160static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2161 struct DisassembleInfo *info) {
Kevin Enderby85974882014-09-26 22:20:44 +00002162 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2163 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002164 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby85974882014-09-26 22:20:44 +00002165 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2166 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2167 for (unsigned J = 0; J < Seg.nsects; ++J) {
2168 MachO::section_64 Sec = info->O->getSection64(Load, J);
2169 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2170 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2171 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2172 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2173 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2174 section_type == MachO::S_SYMBOL_STUBS) &&
2175 ReferenceValue >= Sec.addr &&
2176 ReferenceValue < Sec.addr + Sec.size) {
2177 uint32_t stride;
2178 if (section_type == MachO::S_SYMBOL_STUBS)
2179 stride = Sec.reserved2;
2180 else
2181 stride = 8;
2182 if (stride == 0)
2183 return nullptr;
2184 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2185 if (index < Dysymtab.nindirectsyms) {
2186 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002187 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002188 if (indirect_symbol < Symtab.nsyms) {
2189 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2190 SymbolRef Symbol = *Sym;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002191 ErrorOr<StringRef> SymName = Symbol.getName();
2192 if (std::error_code EC = SymName.getError())
2193 report_fatal_error(EC.message());
2194 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002195 return name;
2196 }
2197 }
2198 }
2199 }
2200 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2201 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2202 for (unsigned J = 0; J < Seg.nsects; ++J) {
2203 MachO::section Sec = info->O->getSection(Load, J);
2204 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2205 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2206 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2207 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2208 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2209 section_type == MachO::S_SYMBOL_STUBS) &&
2210 ReferenceValue >= Sec.addr &&
2211 ReferenceValue < Sec.addr + Sec.size) {
2212 uint32_t stride;
2213 if (section_type == MachO::S_SYMBOL_STUBS)
2214 stride = Sec.reserved2;
2215 else
2216 stride = 4;
2217 if (stride == 0)
2218 return nullptr;
2219 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2220 if (index < Dysymtab.nindirectsyms) {
2221 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002222 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002223 if (indirect_symbol < Symtab.nsyms) {
2224 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2225 SymbolRef Symbol = *Sym;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002226 ErrorOr<StringRef> SymName = Symbol.getName();
2227 if (std::error_code EC = SymName.getError())
2228 report_fatal_error(EC.message());
2229 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002230 return name;
2231 }
2232 }
2233 }
2234 }
2235 }
Kevin Enderby85974882014-09-26 22:20:44 +00002236 }
2237 return nullptr;
2238}
2239
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002240// method_reference() is called passing it the ReferenceName that might be
2241// a reference it to an Objective-C method call. If so then it allocates and
2242// assembles a method call string with the values last seen and saved in
2243// the DisassembleInfo's class_name and selector_name fields. This is saved
2244// into the method field of the info and any previous string is free'ed.
2245// Then the class_name field in the info is set to nullptr. The method call
2246// string is set into ReferenceName and ReferenceType is set to
2247// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2248// then both ReferenceType and ReferenceName are left unchanged.
2249static void method_reference(struct DisassembleInfo *info,
2250 uint64_t *ReferenceType,
2251 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002252 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002253 if (*ReferenceName != nullptr) {
2254 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002255 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002256 if (info->method != nullptr)
2257 free(info->method);
2258 if (info->class_name != nullptr) {
2259 info->method = (char *)malloc(5 + strlen(info->class_name) +
2260 strlen(info->selector_name));
2261 if (info->method != nullptr) {
2262 strcpy(info->method, "+[");
2263 strcat(info->method, info->class_name);
2264 strcat(info->method, " ");
2265 strcat(info->method, info->selector_name);
2266 strcat(info->method, "]");
2267 *ReferenceName = info->method;
2268 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2269 }
2270 } else {
2271 info->method = (char *)malloc(9 + strlen(info->selector_name));
2272 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002273 if (Arch == Triple::x86_64)
2274 strcpy(info->method, "-[%rdi ");
2275 else if (Arch == Triple::aarch64)
2276 strcpy(info->method, "-[x0 ");
2277 else
2278 strcpy(info->method, "-[r? ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002279 strcat(info->method, info->selector_name);
2280 strcat(info->method, "]");
2281 *ReferenceName = info->method;
2282 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2283 }
2284 }
2285 info->class_name = nullptr;
2286 }
2287 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002288 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002289 if (info->method != nullptr)
2290 free(info->method);
2291 info->method = (char *)malloc(17 + strlen(info->selector_name));
2292 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002293 if (Arch == Triple::x86_64)
2294 strcpy(info->method, "-[[%rdi super] ");
2295 else if (Arch == Triple::aarch64)
2296 strcpy(info->method, "-[[x0 super] ");
2297 else
2298 strcpy(info->method, "-[[r? super] ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002299 strcat(info->method, info->selector_name);
2300 strcat(info->method, "]");
2301 *ReferenceName = info->method;
2302 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2303 }
2304 info->class_name = nullptr;
2305 }
2306 }
2307 }
2308}
2309
2310// GuessPointerPointer() is passed the address of what might be a pointer to
2311// a reference to an Objective-C class, selector, message ref or cfstring.
2312// If so the value of the pointer is returned and one of the booleans are set
2313// to true. If not zero is returned and all the booleans are set to false.
2314static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2315 struct DisassembleInfo *info,
2316 bool &classref, bool &selref, bool &msgref,
2317 bool &cfstring) {
2318 classref = false;
2319 selref = false;
2320 msgref = false;
2321 cfstring = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002322 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002323 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2324 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2325 for (unsigned J = 0; J < Seg.nsects; ++J) {
2326 MachO::section_64 Sec = info->O->getSection64(Load, J);
2327 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2328 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2329 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2330 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2331 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2332 ReferenceValue >= Sec.addr &&
2333 ReferenceValue < Sec.addr + Sec.size) {
2334 uint64_t sect_offset = ReferenceValue - Sec.addr;
2335 uint64_t object_offset = Sec.offset + sect_offset;
2336 StringRef MachOContents = info->O->getData();
2337 uint64_t object_size = MachOContents.size();
2338 const char *object_addr = (const char *)MachOContents.data();
2339 if (object_offset < object_size) {
2340 uint64_t pointer_value;
2341 memcpy(&pointer_value, object_addr + object_offset,
2342 sizeof(uint64_t));
2343 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2344 sys::swapByteOrder(pointer_value);
2345 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2346 selref = true;
2347 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2348 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2349 classref = true;
2350 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2351 ReferenceValue + 8 < Sec.addr + Sec.size) {
2352 msgref = true;
2353 memcpy(&pointer_value, object_addr + object_offset + 8,
2354 sizeof(uint64_t));
2355 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2356 sys::swapByteOrder(pointer_value);
2357 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2358 cfstring = true;
2359 return pointer_value;
2360 } else {
2361 return 0;
2362 }
2363 }
2364 }
2365 }
2366 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002367 }
2368 return 0;
2369}
2370
2371// get_pointer_64 returns a pointer to the bytes in the object file at the
2372// Address from a section in the Mach-O file. And indirectly returns the
2373// offset into the section, number of bytes left in the section past the offset
2374// and which section is was being referenced. If the Address is not in a
2375// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002376static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2377 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002378 DisassembleInfo *info,
2379 bool objc_only = false) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002380 offset = 0;
2381 left = 0;
2382 S = SectionRef();
2383 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2384 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2385 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
Kevin Enderby46e642f2015-10-08 22:50:55 +00002386 if (SectSize == 0)
2387 continue;
Kevin Enderby846c0002015-04-16 17:19:59 +00002388 if (objc_only) {
2389 StringRef SectName;
2390 ((*(info->Sections))[SectIdx]).getName(SectName);
2391 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2392 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2393 if (SegName != "__OBJC" && SectName != "__cstring")
2394 continue;
2395 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002396 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2397 S = (*(info->Sections))[SectIdx];
2398 offset = Address - SectAddress;
2399 left = SectSize - offset;
2400 StringRef SectContents;
2401 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2402 return SectContents.data() + offset;
2403 }
2404 }
2405 return nullptr;
2406}
2407
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002408static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2409 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002410 DisassembleInfo *info,
2411 bool objc_only = false) {
2412 return get_pointer_64(Address, offset, left, S, info, objc_only);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002413}
2414
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002415// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2416// the symbol indirectly through n_value. Based on the relocation information
2417// for the specified section offset in the specified section reference.
Kevin Enderby0fc11822015-04-01 20:57:01 +00002418// If no relocation information is found and a non-zero ReferenceValue for the
2419// symbol is passed, look up that address in the info's AddrMap.
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00002420static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2421 DisassembleInfo *info, uint64_t &n_value,
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002422 uint64_t ReferenceValue = 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002423 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002424 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002425 return nullptr;
2426
2427 // See if there is an external relocation entry at the sect_offset.
2428 bool reloc_found = false;
2429 DataRefImpl Rel;
2430 MachO::any_relocation_info RE;
2431 bool isExtern = false;
2432 SymbolRef Symbol;
2433 for (const RelocationRef &Reloc : S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002434 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002435 if (RelocOffset == sect_offset) {
2436 Rel = Reloc.getRawDataRefImpl();
2437 RE = info->O->getRelocation(Rel);
2438 if (info->O->isRelocationScattered(RE))
2439 continue;
2440 isExtern = info->O->getPlainRelocationExternal(RE);
2441 if (isExtern) {
2442 symbol_iterator RelocSym = Reloc.getSymbol();
2443 Symbol = *RelocSym;
2444 }
2445 reloc_found = true;
2446 break;
2447 }
2448 }
2449 // If there is an external relocation entry for a symbol in this section
2450 // at this section_offset then use that symbol's value for the n_value
2451 // and return its name.
2452 const char *SymbolName = nullptr;
2453 if (reloc_found && isExtern) {
Rafael Espindoladea00162015-07-03 17:44:18 +00002454 n_value = Symbol.getValue();
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002455 ErrorOr<StringRef> NameOrError = Symbol.getName();
2456 if (std::error_code EC = NameOrError.getError())
2457 report_fatal_error(EC.message());
2458 StringRef Name = *NameOrError;
2459 if (!Name.empty()) {
2460 SymbolName = Name.data();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002461 return SymbolName;
2462 }
2463 }
2464
2465 // TODO: For fully linked images, look through the external relocation
2466 // entries off the dynamic symtab command. For these the r_offset is from the
2467 // start of the first writeable segment in the Mach-O file. So the offset
2468 // to this section from that segment is passed to this routine by the caller,
2469 // as the database_offset. Which is the difference of the section's starting
2470 // address and the first writable segment.
2471 //
2472 // NOTE: need add passing the database_offset to this routine.
2473
Kevin Enderby0fc11822015-04-01 20:57:01 +00002474 // We did not find an external relocation entry so look up the ReferenceValue
2475 // as an address of a symbol and if found return that symbol's name.
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002476 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002477
2478 return SymbolName;
2479}
2480
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002481static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
2482 DisassembleInfo *info,
2483 uint32_t ReferenceValue) {
2484 uint64_t n_value64;
2485 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
2486}
2487
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002488// These are structs in the Objective-C meta data and read to produce the
2489// comments for disassembly. While these are part of the ABI they are no
2490// public defintions. So the are here not in include/llvm/Support/MachO.h .
2491
2492// The cfstring object in a 64-bit Mach-O file.
2493struct cfstring64_t {
2494 uint64_t isa; // class64_t * (64-bit pointer)
2495 uint64_t flags; // flag bits
2496 uint64_t characters; // char * (64-bit pointer)
2497 uint64_t length; // number of non-NULL characters in above
2498};
2499
2500// The class object in a 64-bit Mach-O file.
2501struct class64_t {
2502 uint64_t isa; // class64_t * (64-bit pointer)
2503 uint64_t superclass; // class64_t * (64-bit pointer)
2504 uint64_t cache; // Cache (64-bit pointer)
2505 uint64_t vtable; // IMP * (64-bit pointer)
2506 uint64_t data; // class_ro64_t * (64-bit pointer)
2507};
2508
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002509struct class32_t {
2510 uint32_t isa; /* class32_t * (32-bit pointer) */
2511 uint32_t superclass; /* class32_t * (32-bit pointer) */
2512 uint32_t cache; /* Cache (32-bit pointer) */
2513 uint32_t vtable; /* IMP * (32-bit pointer) */
2514 uint32_t data; /* class_ro32_t * (32-bit pointer) */
2515};
2516
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002517struct class_ro64_t {
2518 uint32_t flags;
2519 uint32_t instanceStart;
2520 uint32_t instanceSize;
2521 uint32_t reserved;
2522 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2523 uint64_t name; // const char * (64-bit pointer)
2524 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2525 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2526 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2527 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2528 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2529};
2530
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002531struct class_ro32_t {
2532 uint32_t flags;
2533 uint32_t instanceStart;
2534 uint32_t instanceSize;
2535 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
2536 uint32_t name; /* const char * (32-bit pointer) */
2537 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
2538 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
2539 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
2540 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
2541 uint32_t baseProperties; /* const struct objc_property_list *
2542 (32-bit pointer) */
2543};
2544
2545/* Values for class_ro{64,32}_t->flags */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002546#define RO_META (1 << 0)
2547#define RO_ROOT (1 << 1)
2548#define RO_HAS_CXX_STRUCTORS (1 << 2)
2549
2550struct method_list64_t {
2551 uint32_t entsize;
2552 uint32_t count;
2553 /* struct method64_t first; These structures follow inline */
2554};
2555
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002556struct method_list32_t {
2557 uint32_t entsize;
2558 uint32_t count;
2559 /* struct method32_t first; These structures follow inline */
2560};
2561
Kevin Enderby0fc11822015-04-01 20:57:01 +00002562struct method64_t {
2563 uint64_t name; /* SEL (64-bit pointer) */
2564 uint64_t types; /* const char * (64-bit pointer) */
2565 uint64_t imp; /* IMP (64-bit pointer) */
2566};
2567
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002568struct method32_t {
2569 uint32_t name; /* SEL (32-bit pointer) */
2570 uint32_t types; /* const char * (32-bit pointer) */
2571 uint32_t imp; /* IMP (32-bit pointer) */
2572};
2573
Kevin Enderby0fc11822015-04-01 20:57:01 +00002574struct protocol_list64_t {
2575 uint64_t count; /* uintptr_t (a 64-bit value) */
2576 /* struct protocol64_t * list[0]; These pointers follow inline */
2577};
2578
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002579struct protocol_list32_t {
2580 uint32_t count; /* uintptr_t (a 32-bit value) */
2581 /* struct protocol32_t * list[0]; These pointers follow inline */
2582};
2583
Kevin Enderby0fc11822015-04-01 20:57:01 +00002584struct protocol64_t {
2585 uint64_t isa; /* id * (64-bit pointer) */
2586 uint64_t name; /* const char * (64-bit pointer) */
2587 uint64_t protocols; /* struct protocol_list64_t *
2588 (64-bit pointer) */
2589 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
2590 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
2591 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
2592 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
2593 uint64_t instanceProperties; /* struct objc_property_list *
2594 (64-bit pointer) */
2595};
2596
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002597struct protocol32_t {
2598 uint32_t isa; /* id * (32-bit pointer) */
2599 uint32_t name; /* const char * (32-bit pointer) */
2600 uint32_t protocols; /* struct protocol_list_t *
2601 (32-bit pointer) */
2602 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
2603 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
2604 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
2605 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
2606 uint32_t instanceProperties; /* struct objc_property_list *
2607 (32-bit pointer) */
2608};
2609
Kevin Enderby0fc11822015-04-01 20:57:01 +00002610struct ivar_list64_t {
2611 uint32_t entsize;
2612 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002613 /* struct ivar64_t first; These structures follow inline */
2614};
2615
2616struct ivar_list32_t {
2617 uint32_t entsize;
2618 uint32_t count;
2619 /* struct ivar32_t first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002620};
2621
2622struct ivar64_t {
2623 uint64_t offset; /* uintptr_t * (64-bit pointer) */
2624 uint64_t name; /* const char * (64-bit pointer) */
2625 uint64_t type; /* const char * (64-bit pointer) */
2626 uint32_t alignment;
2627 uint32_t size;
2628};
2629
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002630struct ivar32_t {
2631 uint32_t offset; /* uintptr_t * (32-bit pointer) */
2632 uint32_t name; /* const char * (32-bit pointer) */
2633 uint32_t type; /* const char * (32-bit pointer) */
2634 uint32_t alignment;
2635 uint32_t size;
2636};
2637
Kevin Enderby0fc11822015-04-01 20:57:01 +00002638struct objc_property_list64 {
2639 uint32_t entsize;
2640 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002641 /* struct objc_property64 first; These structures follow inline */
2642};
2643
2644struct objc_property_list32 {
2645 uint32_t entsize;
2646 uint32_t count;
2647 /* struct objc_property32 first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002648};
2649
2650struct objc_property64 {
2651 uint64_t name; /* const char * (64-bit pointer) */
2652 uint64_t attributes; /* const char * (64-bit pointer) */
2653};
2654
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002655struct objc_property32 {
2656 uint32_t name; /* const char * (32-bit pointer) */
2657 uint32_t attributes; /* const char * (32-bit pointer) */
2658};
2659
Kevin Enderby0fc11822015-04-01 20:57:01 +00002660struct category64_t {
2661 uint64_t name; /* const char * (64-bit pointer) */
2662 uint64_t cls; /* struct class_t * (64-bit pointer) */
2663 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
2664 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
2665 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
2666 uint64_t instanceProperties; /* struct objc_property_list *
2667 (64-bit pointer) */
2668};
2669
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002670struct category32_t {
2671 uint32_t name; /* const char * (32-bit pointer) */
2672 uint32_t cls; /* struct class_t * (32-bit pointer) */
2673 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
2674 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
2675 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
2676 uint32_t instanceProperties; /* struct objc_property_list *
2677 (32-bit pointer) */
2678};
2679
Kevin Enderby0fc11822015-04-01 20:57:01 +00002680struct objc_image_info64 {
2681 uint32_t version;
2682 uint32_t flags;
2683};
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002684struct objc_image_info32 {
2685 uint32_t version;
2686 uint32_t flags;
2687};
Kevin Enderby846c0002015-04-16 17:19:59 +00002688struct imageInfo_t {
2689 uint32_t version;
2690 uint32_t flags;
2691};
Kevin Enderby0fc11822015-04-01 20:57:01 +00002692/* masks for objc_image_info.flags */
2693#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
2694#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
2695
2696struct message_ref64 {
2697 uint64_t imp; /* IMP (64-bit pointer) */
2698 uint64_t sel; /* SEL (64-bit pointer) */
2699};
2700
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002701struct message_ref32 {
2702 uint32_t imp; /* IMP (32-bit pointer) */
2703 uint32_t sel; /* SEL (32-bit pointer) */
2704};
2705
Kevin Enderby846c0002015-04-16 17:19:59 +00002706// Objective-C 1 (32-bit only) meta data structs.
2707
2708struct objc_module_t {
2709 uint32_t version;
2710 uint32_t size;
2711 uint32_t name; /* char * (32-bit pointer) */
2712 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
2713};
2714
2715struct objc_symtab_t {
2716 uint32_t sel_ref_cnt;
2717 uint32_t refs; /* SEL * (32-bit pointer) */
2718 uint16_t cls_def_cnt;
2719 uint16_t cat_def_cnt;
2720 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
2721};
2722
2723struct objc_class_t {
2724 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2725 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
2726 uint32_t name; /* const char * (32-bit pointer) */
2727 int32_t version;
2728 int32_t info;
2729 int32_t instance_size;
2730 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
2731 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
2732 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
2733 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
2734};
2735
2736#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
2737// class is not a metaclass
2738#define CLS_CLASS 0x1
2739// class is a metaclass
2740#define CLS_META 0x2
2741
2742struct objc_category_t {
2743 uint32_t category_name; /* char * (32-bit pointer) */
2744 uint32_t class_name; /* char * (32-bit pointer) */
2745 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
2746 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
2747 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
2748};
2749
2750struct objc_ivar_t {
2751 uint32_t ivar_name; /* char * (32-bit pointer) */
2752 uint32_t ivar_type; /* char * (32-bit pointer) */
2753 int32_t ivar_offset;
2754};
2755
2756struct objc_ivar_list_t {
2757 int32_t ivar_count;
2758 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
2759};
2760
2761struct objc_method_list_t {
2762 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
2763 int32_t method_count;
2764 // struct objc_method_t method_list[1]; /* variable length structure */
2765};
2766
2767struct objc_method_t {
2768 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2769 uint32_t method_types; /* char * (32-bit pointer) */
2770 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
2771 (32-bit pointer) */
2772};
2773
2774struct objc_protocol_list_t {
2775 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
2776 int32_t count;
2777 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
2778 // (32-bit pointer) */
2779};
2780
2781struct objc_protocol_t {
2782 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2783 uint32_t protocol_name; /* char * (32-bit pointer) */
2784 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
2785 uint32_t instance_methods; /* struct objc_method_description_list *
2786 (32-bit pointer) */
2787 uint32_t class_methods; /* struct objc_method_description_list *
2788 (32-bit pointer) */
2789};
2790
2791struct objc_method_description_list_t {
2792 int32_t count;
2793 // struct objc_method_description_t list[1];
2794};
2795
2796struct objc_method_description_t {
2797 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2798 uint32_t types; /* char * (32-bit pointer) */
2799};
2800
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002801inline void swapStruct(struct cfstring64_t &cfs) {
2802 sys::swapByteOrder(cfs.isa);
2803 sys::swapByteOrder(cfs.flags);
2804 sys::swapByteOrder(cfs.characters);
2805 sys::swapByteOrder(cfs.length);
2806}
2807
2808inline void swapStruct(struct class64_t &c) {
2809 sys::swapByteOrder(c.isa);
2810 sys::swapByteOrder(c.superclass);
2811 sys::swapByteOrder(c.cache);
2812 sys::swapByteOrder(c.vtable);
2813 sys::swapByteOrder(c.data);
2814}
2815
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002816inline void swapStruct(struct class32_t &c) {
2817 sys::swapByteOrder(c.isa);
2818 sys::swapByteOrder(c.superclass);
2819 sys::swapByteOrder(c.cache);
2820 sys::swapByteOrder(c.vtable);
2821 sys::swapByteOrder(c.data);
2822}
2823
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002824inline void swapStruct(struct class_ro64_t &cro) {
2825 sys::swapByteOrder(cro.flags);
2826 sys::swapByteOrder(cro.instanceStart);
2827 sys::swapByteOrder(cro.instanceSize);
2828 sys::swapByteOrder(cro.reserved);
2829 sys::swapByteOrder(cro.ivarLayout);
2830 sys::swapByteOrder(cro.name);
2831 sys::swapByteOrder(cro.baseMethods);
2832 sys::swapByteOrder(cro.baseProtocols);
2833 sys::swapByteOrder(cro.ivars);
2834 sys::swapByteOrder(cro.weakIvarLayout);
2835 sys::swapByteOrder(cro.baseProperties);
2836}
2837
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002838inline void swapStruct(struct class_ro32_t &cro) {
2839 sys::swapByteOrder(cro.flags);
2840 sys::swapByteOrder(cro.instanceStart);
2841 sys::swapByteOrder(cro.instanceSize);
2842 sys::swapByteOrder(cro.ivarLayout);
2843 sys::swapByteOrder(cro.name);
2844 sys::swapByteOrder(cro.baseMethods);
2845 sys::swapByteOrder(cro.baseProtocols);
2846 sys::swapByteOrder(cro.ivars);
2847 sys::swapByteOrder(cro.weakIvarLayout);
2848 sys::swapByteOrder(cro.baseProperties);
2849}
2850
Kevin Enderby0fc11822015-04-01 20:57:01 +00002851inline void swapStruct(struct method_list64_t &ml) {
2852 sys::swapByteOrder(ml.entsize);
2853 sys::swapByteOrder(ml.count);
2854}
2855
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002856inline void swapStruct(struct method_list32_t &ml) {
2857 sys::swapByteOrder(ml.entsize);
2858 sys::swapByteOrder(ml.count);
2859}
2860
Kevin Enderby0fc11822015-04-01 20:57:01 +00002861inline void swapStruct(struct method64_t &m) {
2862 sys::swapByteOrder(m.name);
2863 sys::swapByteOrder(m.types);
2864 sys::swapByteOrder(m.imp);
2865}
2866
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002867inline void swapStruct(struct method32_t &m) {
2868 sys::swapByteOrder(m.name);
2869 sys::swapByteOrder(m.types);
2870 sys::swapByteOrder(m.imp);
2871}
2872
Kevin Enderby0fc11822015-04-01 20:57:01 +00002873inline void swapStruct(struct protocol_list64_t &pl) {
2874 sys::swapByteOrder(pl.count);
2875}
2876
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002877inline void swapStruct(struct protocol_list32_t &pl) {
2878 sys::swapByteOrder(pl.count);
2879}
2880
Kevin Enderby0fc11822015-04-01 20:57:01 +00002881inline void swapStruct(struct protocol64_t &p) {
2882 sys::swapByteOrder(p.isa);
2883 sys::swapByteOrder(p.name);
2884 sys::swapByteOrder(p.protocols);
2885 sys::swapByteOrder(p.instanceMethods);
2886 sys::swapByteOrder(p.classMethods);
2887 sys::swapByteOrder(p.optionalInstanceMethods);
2888 sys::swapByteOrder(p.optionalClassMethods);
2889 sys::swapByteOrder(p.instanceProperties);
2890}
2891
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002892inline void swapStruct(struct protocol32_t &p) {
2893 sys::swapByteOrder(p.isa);
2894 sys::swapByteOrder(p.name);
2895 sys::swapByteOrder(p.protocols);
2896 sys::swapByteOrder(p.instanceMethods);
2897 sys::swapByteOrder(p.classMethods);
2898 sys::swapByteOrder(p.optionalInstanceMethods);
2899 sys::swapByteOrder(p.optionalClassMethods);
2900 sys::swapByteOrder(p.instanceProperties);
2901}
2902
Kevin Enderby0fc11822015-04-01 20:57:01 +00002903inline void swapStruct(struct ivar_list64_t &il) {
2904 sys::swapByteOrder(il.entsize);
2905 sys::swapByteOrder(il.count);
2906}
2907
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002908inline void swapStruct(struct ivar_list32_t &il) {
2909 sys::swapByteOrder(il.entsize);
2910 sys::swapByteOrder(il.count);
2911}
2912
Kevin Enderby0fc11822015-04-01 20:57:01 +00002913inline void swapStruct(struct ivar64_t &i) {
2914 sys::swapByteOrder(i.offset);
2915 sys::swapByteOrder(i.name);
2916 sys::swapByteOrder(i.type);
2917 sys::swapByteOrder(i.alignment);
2918 sys::swapByteOrder(i.size);
2919}
2920
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002921inline void swapStruct(struct ivar32_t &i) {
2922 sys::swapByteOrder(i.offset);
2923 sys::swapByteOrder(i.name);
2924 sys::swapByteOrder(i.type);
2925 sys::swapByteOrder(i.alignment);
2926 sys::swapByteOrder(i.size);
2927}
2928
Kevin Enderby0fc11822015-04-01 20:57:01 +00002929inline void swapStruct(struct objc_property_list64 &pl) {
2930 sys::swapByteOrder(pl.entsize);
2931 sys::swapByteOrder(pl.count);
2932}
2933
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002934inline void swapStruct(struct objc_property_list32 &pl) {
2935 sys::swapByteOrder(pl.entsize);
2936 sys::swapByteOrder(pl.count);
2937}
2938
Kevin Enderby0fc11822015-04-01 20:57:01 +00002939inline void swapStruct(struct objc_property64 &op) {
2940 sys::swapByteOrder(op.name);
2941 sys::swapByteOrder(op.attributes);
2942}
2943
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002944inline void swapStruct(struct objc_property32 &op) {
2945 sys::swapByteOrder(op.name);
2946 sys::swapByteOrder(op.attributes);
2947}
2948
Kevin Enderby0fc11822015-04-01 20:57:01 +00002949inline void swapStruct(struct category64_t &c) {
2950 sys::swapByteOrder(c.name);
2951 sys::swapByteOrder(c.cls);
2952 sys::swapByteOrder(c.instanceMethods);
2953 sys::swapByteOrder(c.classMethods);
2954 sys::swapByteOrder(c.protocols);
2955 sys::swapByteOrder(c.instanceProperties);
2956}
2957
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002958inline void swapStruct(struct category32_t &c) {
2959 sys::swapByteOrder(c.name);
2960 sys::swapByteOrder(c.cls);
2961 sys::swapByteOrder(c.instanceMethods);
2962 sys::swapByteOrder(c.classMethods);
2963 sys::swapByteOrder(c.protocols);
2964 sys::swapByteOrder(c.instanceProperties);
2965}
2966
Kevin Enderby0fc11822015-04-01 20:57:01 +00002967inline void swapStruct(struct objc_image_info64 &o) {
2968 sys::swapByteOrder(o.version);
2969 sys::swapByteOrder(o.flags);
2970}
2971
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002972inline void swapStruct(struct objc_image_info32 &o) {
2973 sys::swapByteOrder(o.version);
2974 sys::swapByteOrder(o.flags);
2975}
2976
Kevin Enderby846c0002015-04-16 17:19:59 +00002977inline void swapStruct(struct imageInfo_t &o) {
2978 sys::swapByteOrder(o.version);
2979 sys::swapByteOrder(o.flags);
2980}
2981
Kevin Enderby0fc11822015-04-01 20:57:01 +00002982inline void swapStruct(struct message_ref64 &mr) {
2983 sys::swapByteOrder(mr.imp);
2984 sys::swapByteOrder(mr.sel);
2985}
2986
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002987inline void swapStruct(struct message_ref32 &mr) {
2988 sys::swapByteOrder(mr.imp);
2989 sys::swapByteOrder(mr.sel);
2990}
2991
Kevin Enderby846c0002015-04-16 17:19:59 +00002992inline void swapStruct(struct objc_module_t &module) {
2993 sys::swapByteOrder(module.version);
2994 sys::swapByteOrder(module.size);
2995 sys::swapByteOrder(module.name);
2996 sys::swapByteOrder(module.symtab);
Jingyue Wufedecc42015-04-16 18:43:44 +00002997}
Kevin Enderby846c0002015-04-16 17:19:59 +00002998
2999inline void swapStruct(struct objc_symtab_t &symtab) {
3000 sys::swapByteOrder(symtab.sel_ref_cnt);
3001 sys::swapByteOrder(symtab.refs);
3002 sys::swapByteOrder(symtab.cls_def_cnt);
3003 sys::swapByteOrder(symtab.cat_def_cnt);
Jingyue Wufedecc42015-04-16 18:43:44 +00003004}
Kevin Enderby846c0002015-04-16 17:19:59 +00003005
3006inline void swapStruct(struct objc_class_t &objc_class) {
3007 sys::swapByteOrder(objc_class.isa);
3008 sys::swapByteOrder(objc_class.super_class);
3009 sys::swapByteOrder(objc_class.name);
3010 sys::swapByteOrder(objc_class.version);
3011 sys::swapByteOrder(objc_class.info);
3012 sys::swapByteOrder(objc_class.instance_size);
3013 sys::swapByteOrder(objc_class.ivars);
3014 sys::swapByteOrder(objc_class.methodLists);
3015 sys::swapByteOrder(objc_class.cache);
3016 sys::swapByteOrder(objc_class.protocols);
Jingyue Wufedecc42015-04-16 18:43:44 +00003017}
Kevin Enderby846c0002015-04-16 17:19:59 +00003018
3019inline void swapStruct(struct objc_category_t &objc_category) {
3020 sys::swapByteOrder(objc_category.category_name);
3021 sys::swapByteOrder(objc_category.class_name);
3022 sys::swapByteOrder(objc_category.instance_methods);
3023 sys::swapByteOrder(objc_category.class_methods);
3024 sys::swapByteOrder(objc_category.protocols);
3025}
3026
3027inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3028 sys::swapByteOrder(objc_ivar_list.ivar_count);
3029}
3030
3031inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3032 sys::swapByteOrder(objc_ivar.ivar_name);
3033 sys::swapByteOrder(objc_ivar.ivar_type);
3034 sys::swapByteOrder(objc_ivar.ivar_offset);
Jingyue Wufedecc42015-04-16 18:43:44 +00003035}
Kevin Enderby846c0002015-04-16 17:19:59 +00003036
3037inline void swapStruct(struct objc_method_list_t &method_list) {
3038 sys::swapByteOrder(method_list.obsolete);
3039 sys::swapByteOrder(method_list.method_count);
3040}
3041
3042inline void swapStruct(struct objc_method_t &method) {
3043 sys::swapByteOrder(method.method_name);
3044 sys::swapByteOrder(method.method_types);
3045 sys::swapByteOrder(method.method_imp);
3046}
3047
3048inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3049 sys::swapByteOrder(protocol_list.next);
3050 sys::swapByteOrder(protocol_list.count);
3051}
3052
3053inline void swapStruct(struct objc_protocol_t &protocol) {
3054 sys::swapByteOrder(protocol.isa);
3055 sys::swapByteOrder(protocol.protocol_name);
3056 sys::swapByteOrder(protocol.protocol_list);
3057 sys::swapByteOrder(protocol.instance_methods);
3058 sys::swapByteOrder(protocol.class_methods);
3059}
3060
3061inline void swapStruct(struct objc_method_description_list_t &mdl) {
3062 sys::swapByteOrder(mdl.count);
3063}
3064
3065inline void swapStruct(struct objc_method_description_t &md) {
3066 sys::swapByteOrder(md.name);
3067 sys::swapByteOrder(md.types);
3068}
3069
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003070static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3071 struct DisassembleInfo *info);
3072
3073// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3074// to an Objective-C class and returns the class name. It is also passed the
3075// address of the pointer, so when the pointer is zero as it can be in an .o
3076// file, that is used to look for an external relocation entry with a symbol
3077// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003078static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3079 uint64_t ReferenceValue,
3080 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003081 const char *r;
3082 uint32_t offset, left;
3083 SectionRef S;
3084
3085 // The pointer_value can be 0 in an object file and have a relocation
3086 // entry for the class symbol at the ReferenceValue (the address of the
3087 // pointer).
3088 if (pointer_value == 0) {
3089 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3090 if (r == nullptr || left < sizeof(uint64_t))
3091 return nullptr;
3092 uint64_t n_value;
3093 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3094 if (symbol_name == nullptr)
3095 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00003096 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003097 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3098 return class_name + 2;
3099 else
3100 return nullptr;
3101 }
3102
3103 // The case were the pointer_value is non-zero and points to a class defined
3104 // in this Mach-O file.
3105 r = get_pointer_64(pointer_value, offset, left, S, info);
3106 if (r == nullptr || left < sizeof(struct class64_t))
3107 return nullptr;
3108 struct class64_t c;
3109 memcpy(&c, r, sizeof(struct class64_t));
3110 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3111 swapStruct(c);
3112 if (c.data == 0)
3113 return nullptr;
3114 r = get_pointer_64(c.data, offset, left, S, info);
3115 if (r == nullptr || left < sizeof(struct class_ro64_t))
3116 return nullptr;
3117 struct class_ro64_t cro;
3118 memcpy(&cro, r, sizeof(struct class_ro64_t));
3119 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3120 swapStruct(cro);
3121 if (cro.name == 0)
3122 return nullptr;
3123 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3124 return name;
3125}
3126
3127// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3128// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003129static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3130 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003131 const char *r, *name;
3132 uint32_t offset, left;
3133 SectionRef S;
3134 struct cfstring64_t cfs;
3135 uint64_t cfs_characters;
3136
3137 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3138 if (r == nullptr || left < sizeof(struct cfstring64_t))
3139 return nullptr;
3140 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3141 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3142 swapStruct(cfs);
3143 if (cfs.characters == 0) {
3144 uint64_t n_value;
3145 const char *symbol_name = get_symbol_64(
3146 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3147 if (symbol_name == nullptr)
3148 return nullptr;
3149 cfs_characters = n_value;
3150 } else
3151 cfs_characters = cfs.characters;
3152 name = get_pointer_64(cfs_characters, offset, left, S, info);
3153
3154 return name;
3155}
3156
3157// get_objc2_64bit_selref() is used for disassembly and is passed a the address
3158// of a pointer to an Objective-C selector reference when the pointer value is
3159// zero as in a .o file and is likely to have a external relocation entry with
3160// who's symbol's n_value is the real pointer to the selector name. If that is
3161// the case the real pointer to the selector name is returned else 0 is
3162// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003163static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3164 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003165 uint32_t offset, left;
3166 SectionRef S;
3167
3168 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3169 if (r == nullptr || left < sizeof(uint64_t))
3170 return 0;
3171 uint64_t n_value;
3172 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3173 if (symbol_name == nullptr)
3174 return 0;
3175 return n_value;
3176}
3177
Kevin Enderby0fc11822015-04-01 20:57:01 +00003178static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3179 const char *sectname) {
3180 for (const SectionRef &Section : O->sections()) {
3181 StringRef SectName;
3182 Section.getName(SectName);
3183 DataRefImpl Ref = Section.getRawDataRefImpl();
3184 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3185 if (SegName == segname && SectName == sectname)
3186 return Section;
3187 }
3188 return SectionRef();
3189}
3190
3191static void
3192walk_pointer_list_64(const char *listname, const SectionRef S,
3193 MachOObjectFile *O, struct DisassembleInfo *info,
3194 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3195 if (S == SectionRef())
3196 return;
3197
3198 StringRef SectName;
3199 S.getName(SectName);
3200 DataRefImpl Ref = S.getRawDataRefImpl();
3201 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3202 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3203
3204 StringRef BytesStr;
3205 S.getContents(BytesStr);
3206 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3207
3208 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3209 uint32_t left = S.getSize() - i;
3210 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3211 uint64_t p = 0;
3212 memcpy(&p, Contents + i, size);
3213 if (i + sizeof(uint64_t) > S.getSize())
3214 outs() << listname << " list pointer extends past end of (" << SegName
3215 << "," << SectName << ") section\n";
3216 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3217
3218 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3219 sys::swapByteOrder(p);
3220
3221 uint64_t n_value = 0;
3222 const char *name = get_symbol_64(i, S, info, n_value, p);
3223 if (name == nullptr)
3224 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3225
3226 if (n_value != 0) {
3227 outs() << format("0x%" PRIx64, n_value);
3228 if (p != 0)
3229 outs() << " + " << format("0x%" PRIx64, p);
3230 } else
3231 outs() << format("0x%" PRIx64, p);
3232 if (name != nullptr)
3233 outs() << " " << name;
3234 outs() << "\n";
3235
3236 p += n_value;
3237 if (func)
3238 func(p, info);
3239 }
3240}
3241
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003242static void
3243walk_pointer_list_32(const char *listname, const SectionRef S,
3244 MachOObjectFile *O, struct DisassembleInfo *info,
3245 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3246 if (S == SectionRef())
3247 return;
3248
3249 StringRef SectName;
3250 S.getName(SectName);
3251 DataRefImpl Ref = S.getRawDataRefImpl();
3252 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3253 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3254
3255 StringRef BytesStr;
3256 S.getContents(BytesStr);
3257 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3258
3259 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3260 uint32_t left = S.getSize() - i;
3261 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3262 uint32_t p = 0;
3263 memcpy(&p, Contents + i, size);
3264 if (i + sizeof(uint32_t) > S.getSize())
3265 outs() << listname << " list pointer extends past end of (" << SegName
3266 << "," << SectName << ") section\n";
Kevin Enderbycf261312015-04-06 22:33:43 +00003267 uint32_t Address = S.getAddress() + i;
3268 outs() << format("%08" PRIx32, Address) << " ";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003269
3270 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3271 sys::swapByteOrder(p);
3272 outs() << format("0x%" PRIx32, p);
3273
3274 const char *name = get_symbol_32(i, S, info, p);
3275 if (name != nullptr)
3276 outs() << " " << name;
3277 outs() << "\n";
3278
3279 if (func)
3280 func(p, info);
3281 }
3282}
3283
3284static void print_layout_map(const char *layout_map, uint32_t left) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003285 if (layout_map == nullptr)
3286 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003287 outs() << " layout map: ";
3288 do {
3289 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3290 left--;
3291 layout_map++;
3292 } while (*layout_map != '\0' && left != 0);
3293 outs() << "\n";
3294}
3295
Kevin Enderby0fc11822015-04-01 20:57:01 +00003296static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3297 uint32_t offset, left;
3298 SectionRef S;
3299 const char *layout_map;
3300
3301 if (p == 0)
3302 return;
3303 layout_map = get_pointer_64(p, offset, left, S, info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003304 print_layout_map(layout_map, left);
3305}
3306
3307static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3308 uint32_t offset, left;
3309 SectionRef S;
3310 const char *layout_map;
3311
3312 if (p == 0)
3313 return;
3314 layout_map = get_pointer_32(p, offset, left, S, info);
3315 print_layout_map(layout_map, left);
Kevin Enderby0fc11822015-04-01 20:57:01 +00003316}
3317
3318static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3319 const char *indent) {
3320 struct method_list64_t ml;
3321 struct method64_t m;
3322 const char *r;
3323 uint32_t offset, xoffset, left, i;
3324 SectionRef S, xS;
3325 const char *name, *sym_name;
3326 uint64_t n_value;
3327
3328 r = get_pointer_64(p, offset, left, S, info);
3329 if (r == nullptr)
3330 return;
3331 memset(&ml, '\0', sizeof(struct method_list64_t));
3332 if (left < sizeof(struct method_list64_t)) {
3333 memcpy(&ml, r, left);
3334 outs() << " (method_list_t entends past the end of the section)\n";
3335 } else
3336 memcpy(&ml, r, sizeof(struct method_list64_t));
3337 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3338 swapStruct(ml);
3339 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3340 outs() << indent << "\t\t count " << ml.count << "\n";
3341
3342 p += sizeof(struct method_list64_t);
3343 offset += sizeof(struct method_list64_t);
3344 for (i = 0; i < ml.count; i++) {
3345 r = get_pointer_64(p, offset, left, S, info);
3346 if (r == nullptr)
3347 return;
3348 memset(&m, '\0', sizeof(struct method64_t));
3349 if (left < sizeof(struct method64_t)) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003350 memcpy(&m, r, left);
3351 outs() << indent << " (method_t extends past the end of the section)\n";
Kevin Enderby0fc11822015-04-01 20:57:01 +00003352 } else
3353 memcpy(&m, r, sizeof(struct method64_t));
3354 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3355 swapStruct(m);
3356
3357 outs() << indent << "\t\t name ";
3358 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3359 info, n_value, m.name);
3360 if (n_value != 0) {
3361 if (info->verbose && sym_name != nullptr)
3362 outs() << sym_name;
3363 else
3364 outs() << format("0x%" PRIx64, n_value);
3365 if (m.name != 0)
3366 outs() << " + " << format("0x%" PRIx64, m.name);
3367 } else
3368 outs() << format("0x%" PRIx64, m.name);
3369 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3370 if (name != nullptr)
3371 outs() << format(" %.*s", left, name);
3372 outs() << "\n";
3373
3374 outs() << indent << "\t\t types ";
3375 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3376 info, n_value, m.types);
3377 if (n_value != 0) {
3378 if (info->verbose && sym_name != nullptr)
3379 outs() << sym_name;
3380 else
3381 outs() << format("0x%" PRIx64, n_value);
3382 if (m.types != 0)
3383 outs() << " + " << format("0x%" PRIx64, m.types);
3384 } else
3385 outs() << format("0x%" PRIx64, m.types);
3386 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3387 if (name != nullptr)
3388 outs() << format(" %.*s", left, name);
3389 outs() << "\n";
3390
3391 outs() << indent << "\t\t imp ";
3392 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3393 n_value, m.imp);
3394 if (info->verbose && name == nullptr) {
3395 if (n_value != 0) {
3396 outs() << format("0x%" PRIx64, n_value) << " ";
3397 if (m.imp != 0)
3398 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3399 } else
3400 outs() << format("0x%" PRIx64, m.imp) << " ";
3401 }
3402 if (name != nullptr)
3403 outs() << name;
3404 outs() << "\n";
3405
3406 p += sizeof(struct method64_t);
3407 offset += sizeof(struct method64_t);
3408 }
3409}
3410
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003411static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3412 const char *indent) {
3413 struct method_list32_t ml;
3414 struct method32_t m;
Kevin Enderby846c0002015-04-16 17:19:59 +00003415 const char *r, *name;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003416 uint32_t offset, xoffset, left, i;
3417 SectionRef S, xS;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003418
3419 r = get_pointer_32(p, offset, left, S, info);
3420 if (r == nullptr)
3421 return;
3422 memset(&ml, '\0', sizeof(struct method_list32_t));
3423 if (left < sizeof(struct method_list32_t)) {
3424 memcpy(&ml, r, left);
3425 outs() << " (method_list_t entends past the end of the section)\n";
3426 } else
3427 memcpy(&ml, r, sizeof(struct method_list32_t));
3428 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3429 swapStruct(ml);
3430 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3431 outs() << indent << "\t\t count " << ml.count << "\n";
3432
3433 p += sizeof(struct method_list32_t);
3434 offset += sizeof(struct method_list32_t);
3435 for (i = 0; i < ml.count; i++) {
3436 r = get_pointer_32(p, offset, left, S, info);
3437 if (r == nullptr)
3438 return;
3439 memset(&m, '\0', sizeof(struct method32_t));
3440 if (left < sizeof(struct method32_t)) {
3441 memcpy(&ml, r, left);
3442 outs() << indent << " (method_t entends past the end of the section)\n";
3443 } else
3444 memcpy(&m, r, sizeof(struct method32_t));
3445 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3446 swapStruct(m);
3447
3448 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
3449 name = get_pointer_32(m.name, xoffset, left, xS, info);
3450 if (name != nullptr)
3451 outs() << format(" %.*s", left, name);
3452 outs() << "\n";
3453
3454 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
3455 name = get_pointer_32(m.types, xoffset, left, xS, info);
3456 if (name != nullptr)
3457 outs() << format(" %.*s", left, name);
3458 outs() << "\n";
3459
3460 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
3461 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
3462 m.imp);
3463 if (name != nullptr)
3464 outs() << " " << name;
3465 outs() << "\n";
3466
3467 p += sizeof(struct method32_t);
3468 offset += sizeof(struct method32_t);
3469 }
3470}
3471
Kevin Enderby846c0002015-04-16 17:19:59 +00003472static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
3473 uint32_t offset, left, xleft;
3474 SectionRef S;
3475 struct objc_method_list_t method_list;
3476 struct objc_method_t method;
3477 const char *r, *methods, *name, *SymbolName;
3478 int32_t i;
3479
3480 r = get_pointer_32(p, offset, left, S, info, true);
3481 if (r == nullptr)
3482 return true;
3483
3484 outs() << "\n";
3485 if (left > sizeof(struct objc_method_list_t)) {
3486 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
3487 } else {
3488 outs() << "\t\t objc_method_list extends past end of the section\n";
3489 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
3490 memcpy(&method_list, r, left);
3491 }
3492 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3493 swapStruct(method_list);
3494
3495 outs() << "\t\t obsolete "
3496 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
3497 outs() << "\t\t method_count " << method_list.method_count << "\n";
3498
3499 methods = r + sizeof(struct objc_method_list_t);
3500 for (i = 0; i < method_list.method_count; i++) {
3501 if ((i + 1) * sizeof(struct objc_method_t) > left) {
3502 outs() << "\t\t remaining method's extend past the of the section\n";
3503 break;
3504 }
3505 memcpy(&method, methods + i * sizeof(struct objc_method_t),
3506 sizeof(struct objc_method_t));
3507 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3508 swapStruct(method);
3509
3510 outs() << "\t\t method_name "
3511 << format("0x%08" PRIx32, method.method_name);
3512 if (info->verbose) {
3513 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
3514 if (name != nullptr)
3515 outs() << format(" %.*s", xleft, name);
3516 else
3517 outs() << " (not in an __OBJC section)";
3518 }
3519 outs() << "\n";
3520
3521 outs() << "\t\t method_types "
3522 << format("0x%08" PRIx32, method.method_types);
3523 if (info->verbose) {
3524 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
3525 if (name != nullptr)
3526 outs() << format(" %.*s", xleft, name);
3527 else
3528 outs() << " (not in an __OBJC section)";
3529 }
3530 outs() << "\n";
3531
3532 outs() << "\t\t method_imp "
3533 << format("0x%08" PRIx32, method.method_imp) << " ";
3534 if (info->verbose) {
3535 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
3536 if (SymbolName != nullptr)
3537 outs() << SymbolName;
3538 }
3539 outs() << "\n";
3540 }
3541 return false;
3542}
3543
Kevin Enderby0fc11822015-04-01 20:57:01 +00003544static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
3545 struct protocol_list64_t pl;
3546 uint64_t q, n_value;
3547 struct protocol64_t pc;
3548 const char *r;
3549 uint32_t offset, xoffset, left, i;
3550 SectionRef S, xS;
3551 const char *name, *sym_name;
3552
3553 r = get_pointer_64(p, offset, left, S, info);
3554 if (r == nullptr)
3555 return;
3556 memset(&pl, '\0', sizeof(struct protocol_list64_t));
3557 if (left < sizeof(struct protocol_list64_t)) {
3558 memcpy(&pl, r, left);
3559 outs() << " (protocol_list_t entends past the end of the section)\n";
3560 } else
3561 memcpy(&pl, r, sizeof(struct protocol_list64_t));
3562 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3563 swapStruct(pl);
3564 outs() << " count " << pl.count << "\n";
3565
3566 p += sizeof(struct protocol_list64_t);
3567 offset += sizeof(struct protocol_list64_t);
3568 for (i = 0; i < pl.count; i++) {
3569 r = get_pointer_64(p, offset, left, S, info);
3570 if (r == nullptr)
3571 return;
3572 q = 0;
3573 if (left < sizeof(uint64_t)) {
3574 memcpy(&q, r, left);
3575 outs() << " (protocol_t * entends past the end of the section)\n";
3576 } else
3577 memcpy(&q, r, sizeof(uint64_t));
3578 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3579 sys::swapByteOrder(q);
3580
3581 outs() << "\t\t list[" << i << "] ";
3582 sym_name = get_symbol_64(offset, S, info, n_value, q);
3583 if (n_value != 0) {
3584 if (info->verbose && sym_name != nullptr)
3585 outs() << sym_name;
3586 else
3587 outs() << format("0x%" PRIx64, n_value);
3588 if (q != 0)
3589 outs() << " + " << format("0x%" PRIx64, q);
3590 } else
3591 outs() << format("0x%" PRIx64, q);
3592 outs() << " (struct protocol_t *)\n";
3593
3594 r = get_pointer_64(q + n_value, offset, left, S, info);
3595 if (r == nullptr)
3596 return;
3597 memset(&pc, '\0', sizeof(struct protocol64_t));
3598 if (left < sizeof(struct protocol64_t)) {
3599 memcpy(&pc, r, left);
3600 outs() << " (protocol_t entends past the end of the section)\n";
3601 } else
3602 memcpy(&pc, r, sizeof(struct protocol64_t));
3603 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3604 swapStruct(pc);
3605
3606 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
3607
3608 outs() << "\t\t\t name ";
3609 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
3610 info, n_value, pc.name);
3611 if (n_value != 0) {
3612 if (info->verbose && sym_name != nullptr)
3613 outs() << sym_name;
3614 else
3615 outs() << format("0x%" PRIx64, n_value);
3616 if (pc.name != 0)
3617 outs() << " + " << format("0x%" PRIx64, pc.name);
3618 } else
3619 outs() << format("0x%" PRIx64, pc.name);
3620 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
3621 if (name != nullptr)
3622 outs() << format(" %.*s", left, name);
3623 outs() << "\n";
3624
3625 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
3626
3627 outs() << "\t\t instanceMethods ";
3628 sym_name =
3629 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
3630 S, info, n_value, pc.instanceMethods);
3631 if (n_value != 0) {
3632 if (info->verbose && sym_name != nullptr)
3633 outs() << sym_name;
3634 else
3635 outs() << format("0x%" PRIx64, n_value);
3636 if (pc.instanceMethods != 0)
3637 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
3638 } else
3639 outs() << format("0x%" PRIx64, pc.instanceMethods);
3640 outs() << " (struct method_list_t *)\n";
3641 if (pc.instanceMethods + n_value != 0)
3642 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
3643
3644 outs() << "\t\t classMethods ";
3645 sym_name =
3646 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
3647 info, n_value, pc.classMethods);
3648 if (n_value != 0) {
3649 if (info->verbose && sym_name != nullptr)
3650 outs() << sym_name;
3651 else
3652 outs() << format("0x%" PRIx64, n_value);
3653 if (pc.classMethods != 0)
3654 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
3655 } else
3656 outs() << format("0x%" PRIx64, pc.classMethods);
3657 outs() << " (struct method_list_t *)\n";
3658 if (pc.classMethods + n_value != 0)
3659 print_method_list64_t(pc.classMethods + n_value, info, "\t");
3660
3661 outs() << "\t optionalInstanceMethods "
3662 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
3663 outs() << "\t optionalClassMethods "
3664 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
3665 outs() << "\t instanceProperties "
3666 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
3667
3668 p += sizeof(uint64_t);
3669 offset += sizeof(uint64_t);
3670 }
3671}
3672
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003673static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
3674 struct protocol_list32_t pl;
3675 uint32_t q;
3676 struct protocol32_t pc;
3677 const char *r;
3678 uint32_t offset, xoffset, left, i;
3679 SectionRef S, xS;
3680 const char *name;
3681
3682 r = get_pointer_32(p, offset, left, S, info);
3683 if (r == nullptr)
3684 return;
3685 memset(&pl, '\0', sizeof(struct protocol_list32_t));
3686 if (left < sizeof(struct protocol_list32_t)) {
3687 memcpy(&pl, r, left);
3688 outs() << " (protocol_list_t entends past the end of the section)\n";
3689 } else
3690 memcpy(&pl, r, sizeof(struct protocol_list32_t));
3691 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3692 swapStruct(pl);
3693 outs() << " count " << pl.count << "\n";
3694
3695 p += sizeof(struct protocol_list32_t);
3696 offset += sizeof(struct protocol_list32_t);
3697 for (i = 0; i < pl.count; i++) {
3698 r = get_pointer_32(p, offset, left, S, info);
3699 if (r == nullptr)
3700 return;
3701 q = 0;
3702 if (left < sizeof(uint32_t)) {
3703 memcpy(&q, r, left);
3704 outs() << " (protocol_t * entends past the end of the section)\n";
3705 } else
3706 memcpy(&q, r, sizeof(uint32_t));
3707 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3708 sys::swapByteOrder(q);
3709 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
3710 << " (struct protocol_t *)\n";
3711 r = get_pointer_32(q, offset, left, S, info);
3712 if (r == nullptr)
3713 return;
3714 memset(&pc, '\0', sizeof(struct protocol32_t));
3715 if (left < sizeof(struct protocol32_t)) {
3716 memcpy(&pc, r, left);
3717 outs() << " (protocol_t entends past the end of the section)\n";
3718 } else
3719 memcpy(&pc, r, sizeof(struct protocol32_t));
3720 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3721 swapStruct(pc);
3722 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
3723 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
3724 name = get_pointer_32(pc.name, xoffset, left, xS, info);
3725 if (name != nullptr)
3726 outs() << format(" %.*s", left, name);
3727 outs() << "\n";
3728 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
3729 outs() << "\t\t instanceMethods "
3730 << format("0x%" PRIx32, pc.instanceMethods)
3731 << " (struct method_list_t *)\n";
3732 if (pc.instanceMethods != 0)
3733 print_method_list32_t(pc.instanceMethods, info, "\t");
3734 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
3735 << " (struct method_list_t *)\n";
3736 if (pc.classMethods != 0)
3737 print_method_list32_t(pc.classMethods, info, "\t");
3738 outs() << "\t optionalInstanceMethods "
3739 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
3740 outs() << "\t optionalClassMethods "
3741 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
3742 outs() << "\t instanceProperties "
3743 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
3744 p += sizeof(uint32_t);
3745 offset += sizeof(uint32_t);
3746 }
3747}
3748
Kevin Enderby846c0002015-04-16 17:19:59 +00003749static void print_indent(uint32_t indent) {
3750 for (uint32_t i = 0; i < indent;) {
3751 if (indent - i >= 8) {
3752 outs() << "\t";
3753 i += 8;
3754 } else {
3755 for (uint32_t j = i; j < indent; j++)
3756 outs() << " ";
3757 return;
3758 }
3759 }
3760}
3761
3762static bool print_method_description_list(uint32_t p, uint32_t indent,
3763 struct DisassembleInfo *info) {
3764 uint32_t offset, left, xleft;
3765 SectionRef S;
3766 struct objc_method_description_list_t mdl;
3767 struct objc_method_description_t md;
3768 const char *r, *list, *name;
3769 int32_t i;
3770
3771 r = get_pointer_32(p, offset, left, S, info, true);
3772 if (r == nullptr)
3773 return true;
3774
3775 outs() << "\n";
3776 if (left > sizeof(struct objc_method_description_list_t)) {
3777 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
3778 } else {
3779 print_indent(indent);
3780 outs() << " objc_method_description_list extends past end of the section\n";
3781 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
3782 memcpy(&mdl, r, left);
3783 }
3784 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3785 swapStruct(mdl);
3786
3787 print_indent(indent);
3788 outs() << " count " << mdl.count << "\n";
3789
3790 list = r + sizeof(struct objc_method_description_list_t);
3791 for (i = 0; i < mdl.count; i++) {
3792 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
3793 print_indent(indent);
3794 outs() << " remaining list entries extend past the of the section\n";
3795 break;
3796 }
3797 print_indent(indent);
3798 outs() << " list[" << i << "]\n";
3799 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
3800 sizeof(struct objc_method_description_t));
3801 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3802 swapStruct(md);
3803
3804 print_indent(indent);
3805 outs() << " name " << format("0x%08" PRIx32, md.name);
3806 if (info->verbose) {
3807 name = get_pointer_32(md.name, offset, xleft, S, info, true);
3808 if (name != nullptr)
3809 outs() << format(" %.*s", xleft, name);
3810 else
3811 outs() << " (not in an __OBJC section)";
3812 }
3813 outs() << "\n";
3814
3815 print_indent(indent);
3816 outs() << " types " << format("0x%08" PRIx32, md.types);
3817 if (info->verbose) {
3818 name = get_pointer_32(md.types, offset, xleft, S, info, true);
3819 if (name != nullptr)
3820 outs() << format(" %.*s", xleft, name);
3821 else
3822 outs() << " (not in an __OBJC section)";
3823 }
3824 outs() << "\n";
3825 }
3826 return false;
3827}
3828
3829static bool print_protocol_list(uint32_t p, uint32_t indent,
3830 struct DisassembleInfo *info);
3831
3832static bool print_protocol(uint32_t p, uint32_t indent,
3833 struct DisassembleInfo *info) {
3834 uint32_t offset, left;
3835 SectionRef S;
3836 struct objc_protocol_t protocol;
3837 const char *r, *name;
3838
3839 r = get_pointer_32(p, offset, left, S, info, true);
3840 if (r == nullptr)
3841 return true;
3842
3843 outs() << "\n";
3844 if (left >= sizeof(struct objc_protocol_t)) {
3845 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
3846 } else {
3847 print_indent(indent);
3848 outs() << " Protocol extends past end of the section\n";
3849 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
3850 memcpy(&protocol, r, left);
3851 }
3852 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3853 swapStruct(protocol);
3854
3855 print_indent(indent);
3856 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
3857 << "\n";
3858
3859 print_indent(indent);
3860 outs() << " protocol_name "
3861 << format("0x%08" PRIx32, protocol.protocol_name);
3862 if (info->verbose) {
3863 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
3864 if (name != nullptr)
3865 outs() << format(" %.*s", left, name);
3866 else
3867 outs() << " (not in an __OBJC section)";
3868 }
3869 outs() << "\n";
3870
3871 print_indent(indent);
3872 outs() << " protocol_list "
3873 << format("0x%08" PRIx32, protocol.protocol_list);
3874 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
3875 outs() << " (not in an __OBJC section)\n";
3876
3877 print_indent(indent);
3878 outs() << " instance_methods "
3879 << format("0x%08" PRIx32, protocol.instance_methods);
3880 if (print_method_description_list(protocol.instance_methods, indent, info))
3881 outs() << " (not in an __OBJC section)\n";
3882
3883 print_indent(indent);
3884 outs() << " class_methods "
3885 << format("0x%08" PRIx32, protocol.class_methods);
3886 if (print_method_description_list(protocol.class_methods, indent, info))
3887 outs() << " (not in an __OBJC section)\n";
3888
3889 return false;
3890}
3891
3892static bool print_protocol_list(uint32_t p, uint32_t indent,
3893 struct DisassembleInfo *info) {
3894 uint32_t offset, left, l;
3895 SectionRef S;
3896 struct objc_protocol_list_t protocol_list;
3897 const char *r, *list;
3898 int32_t i;
3899
3900 r = get_pointer_32(p, offset, left, S, info, true);
3901 if (r == nullptr)
3902 return true;
3903
3904 outs() << "\n";
3905 if (left > sizeof(struct objc_protocol_list_t)) {
3906 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
3907 } else {
3908 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
3909 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
3910 memcpy(&protocol_list, r, left);
3911 }
3912 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3913 swapStruct(protocol_list);
3914
3915 print_indent(indent);
3916 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
3917 << "\n";
3918 print_indent(indent);
3919 outs() << " count " << protocol_list.count << "\n";
3920
3921 list = r + sizeof(struct objc_protocol_list_t);
3922 for (i = 0; i < protocol_list.count; i++) {
3923 if ((i + 1) * sizeof(uint32_t) > left) {
3924 outs() << "\t\t remaining list entries extend past the of the section\n";
3925 break;
3926 }
3927 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
3928 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3929 sys::swapByteOrder(l);
3930
3931 print_indent(indent);
3932 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
3933 if (print_protocol(l, indent, info))
3934 outs() << "(not in an __OBJC section)\n";
3935 }
3936 return false;
3937}
3938
Kevin Enderby0fc11822015-04-01 20:57:01 +00003939static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
3940 struct ivar_list64_t il;
3941 struct ivar64_t i;
3942 const char *r;
3943 uint32_t offset, xoffset, left, j;
3944 SectionRef S, xS;
3945 const char *name, *sym_name, *ivar_offset_p;
3946 uint64_t ivar_offset, n_value;
3947
3948 r = get_pointer_64(p, offset, left, S, info);
3949 if (r == nullptr)
3950 return;
3951 memset(&il, '\0', sizeof(struct ivar_list64_t));
3952 if (left < sizeof(struct ivar_list64_t)) {
3953 memcpy(&il, r, left);
3954 outs() << " (ivar_list_t entends past the end of the section)\n";
3955 } else
3956 memcpy(&il, r, sizeof(struct ivar_list64_t));
3957 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3958 swapStruct(il);
3959 outs() << " entsize " << il.entsize << "\n";
3960 outs() << " count " << il.count << "\n";
3961
3962 p += sizeof(struct ivar_list64_t);
3963 offset += sizeof(struct ivar_list64_t);
3964 for (j = 0; j < il.count; j++) {
3965 r = get_pointer_64(p, offset, left, S, info);
3966 if (r == nullptr)
3967 return;
3968 memset(&i, '\0', sizeof(struct ivar64_t));
3969 if (left < sizeof(struct ivar64_t)) {
3970 memcpy(&i, r, left);
3971 outs() << " (ivar_t entends past the end of the section)\n";
3972 } else
3973 memcpy(&i, r, sizeof(struct ivar64_t));
3974 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3975 swapStruct(i);
3976
3977 outs() << "\t\t\t offset ";
3978 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
3979 info, n_value, i.offset);
3980 if (n_value != 0) {
3981 if (info->verbose && sym_name != nullptr)
3982 outs() << sym_name;
3983 else
3984 outs() << format("0x%" PRIx64, n_value);
3985 if (i.offset != 0)
3986 outs() << " + " << format("0x%" PRIx64, i.offset);
3987 } else
3988 outs() << format("0x%" PRIx64, i.offset);
3989 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
3990 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
3991 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
3992 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3993 sys::swapByteOrder(ivar_offset);
3994 outs() << " " << ivar_offset << "\n";
3995 } else
3996 outs() << "\n";
3997
3998 outs() << "\t\t\t name ";
3999 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4000 n_value, i.name);
4001 if (n_value != 0) {
4002 if (info->verbose && sym_name != nullptr)
4003 outs() << sym_name;
4004 else
4005 outs() << format("0x%" PRIx64, n_value);
4006 if (i.name != 0)
4007 outs() << " + " << format("0x%" PRIx64, i.name);
4008 } else
4009 outs() << format("0x%" PRIx64, i.name);
4010 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4011 if (name != nullptr)
4012 outs() << format(" %.*s", left, name);
4013 outs() << "\n";
4014
4015 outs() << "\t\t\t type ";
4016 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4017 n_value, i.name);
4018 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4019 if (n_value != 0) {
4020 if (info->verbose && sym_name != nullptr)
4021 outs() << sym_name;
4022 else
4023 outs() << format("0x%" PRIx64, n_value);
4024 if (i.type != 0)
4025 outs() << " + " << format("0x%" PRIx64, i.type);
4026 } else
4027 outs() << format("0x%" PRIx64, i.type);
4028 if (name != nullptr)
4029 outs() << format(" %.*s", left, name);
4030 outs() << "\n";
4031
4032 outs() << "\t\t\talignment " << i.alignment << "\n";
4033 outs() << "\t\t\t size " << i.size << "\n";
4034
4035 p += sizeof(struct ivar64_t);
4036 offset += sizeof(struct ivar64_t);
4037 }
4038}
4039
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004040static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4041 struct ivar_list32_t il;
4042 struct ivar32_t i;
4043 const char *r;
4044 uint32_t offset, xoffset, left, j;
4045 SectionRef S, xS;
4046 const char *name, *ivar_offset_p;
4047 uint32_t ivar_offset;
4048
4049 r = get_pointer_32(p, offset, left, S, info);
4050 if (r == nullptr)
4051 return;
4052 memset(&il, '\0', sizeof(struct ivar_list32_t));
4053 if (left < sizeof(struct ivar_list32_t)) {
4054 memcpy(&il, r, left);
4055 outs() << " (ivar_list_t entends past the end of the section)\n";
4056 } else
4057 memcpy(&il, r, sizeof(struct ivar_list32_t));
4058 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4059 swapStruct(il);
4060 outs() << " entsize " << il.entsize << "\n";
4061 outs() << " count " << il.count << "\n";
4062
4063 p += sizeof(struct ivar_list32_t);
4064 offset += sizeof(struct ivar_list32_t);
4065 for (j = 0; j < il.count; j++) {
4066 r = get_pointer_32(p, offset, left, S, info);
4067 if (r == nullptr)
4068 return;
4069 memset(&i, '\0', sizeof(struct ivar32_t));
4070 if (left < sizeof(struct ivar32_t)) {
4071 memcpy(&i, r, left);
4072 outs() << " (ivar_t entends past the end of the section)\n";
4073 } else
4074 memcpy(&i, r, sizeof(struct ivar32_t));
4075 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4076 swapStruct(i);
4077
4078 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4079 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4080 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4081 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4082 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4083 sys::swapByteOrder(ivar_offset);
4084 outs() << " " << ivar_offset << "\n";
4085 } else
4086 outs() << "\n";
4087
4088 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4089 name = get_pointer_32(i.name, xoffset, left, xS, info);
4090 if (name != nullptr)
4091 outs() << format(" %.*s", left, name);
4092 outs() << "\n";
4093
4094 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4095 name = get_pointer_32(i.type, xoffset, left, xS, info);
4096 if (name != nullptr)
4097 outs() << format(" %.*s", left, name);
4098 outs() << "\n";
4099
4100 outs() << "\t\t\talignment " << i.alignment << "\n";
4101 outs() << "\t\t\t size " << i.size << "\n";
4102
4103 p += sizeof(struct ivar32_t);
4104 offset += sizeof(struct ivar32_t);
4105 }
4106}
4107
Kevin Enderby0fc11822015-04-01 20:57:01 +00004108static void print_objc_property_list64(uint64_t p,
4109 struct DisassembleInfo *info) {
4110 struct objc_property_list64 opl;
4111 struct objc_property64 op;
4112 const char *r;
4113 uint32_t offset, xoffset, left, j;
4114 SectionRef S, xS;
4115 const char *name, *sym_name;
4116 uint64_t n_value;
4117
4118 r = get_pointer_64(p, offset, left, S, info);
4119 if (r == nullptr)
4120 return;
4121 memset(&opl, '\0', sizeof(struct objc_property_list64));
4122 if (left < sizeof(struct objc_property_list64)) {
4123 memcpy(&opl, r, left);
4124 outs() << " (objc_property_list entends past the end of the section)\n";
4125 } else
4126 memcpy(&opl, r, sizeof(struct objc_property_list64));
4127 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4128 swapStruct(opl);
4129 outs() << " entsize " << opl.entsize << "\n";
4130 outs() << " count " << opl.count << "\n";
4131
4132 p += sizeof(struct objc_property_list64);
4133 offset += sizeof(struct objc_property_list64);
4134 for (j = 0; j < opl.count; j++) {
4135 r = get_pointer_64(p, offset, left, S, info);
4136 if (r == nullptr)
4137 return;
4138 memset(&op, '\0', sizeof(struct objc_property64));
4139 if (left < sizeof(struct objc_property64)) {
4140 memcpy(&op, r, left);
4141 outs() << " (objc_property entends past the end of the section)\n";
4142 } else
4143 memcpy(&op, r, sizeof(struct objc_property64));
4144 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4145 swapStruct(op);
4146
4147 outs() << "\t\t\t name ";
4148 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4149 info, n_value, op.name);
4150 if (n_value != 0) {
4151 if (info->verbose && sym_name != nullptr)
4152 outs() << sym_name;
4153 else
4154 outs() << format("0x%" PRIx64, n_value);
4155 if (op.name != 0)
4156 outs() << " + " << format("0x%" PRIx64, op.name);
4157 } else
4158 outs() << format("0x%" PRIx64, op.name);
4159 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4160 if (name != nullptr)
4161 outs() << format(" %.*s", left, name);
4162 outs() << "\n";
4163
4164 outs() << "\t\t\tattributes ";
4165 sym_name =
4166 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4167 info, n_value, op.attributes);
4168 if (n_value != 0) {
4169 if (info->verbose && sym_name != nullptr)
4170 outs() << sym_name;
4171 else
4172 outs() << format("0x%" PRIx64, n_value);
4173 if (op.attributes != 0)
4174 outs() << " + " << format("0x%" PRIx64, op.attributes);
4175 } else
4176 outs() << format("0x%" PRIx64, op.attributes);
4177 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4178 if (name != nullptr)
4179 outs() << format(" %.*s", left, name);
4180 outs() << "\n";
4181
4182 p += sizeof(struct objc_property64);
4183 offset += sizeof(struct objc_property64);
4184 }
4185}
4186
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004187static void print_objc_property_list32(uint32_t p,
4188 struct DisassembleInfo *info) {
4189 struct objc_property_list32 opl;
4190 struct objc_property32 op;
4191 const char *r;
4192 uint32_t offset, xoffset, left, j;
4193 SectionRef S, xS;
4194 const char *name;
4195
4196 r = get_pointer_32(p, offset, left, S, info);
4197 if (r == nullptr)
4198 return;
4199 memset(&opl, '\0', sizeof(struct objc_property_list32));
4200 if (left < sizeof(struct objc_property_list32)) {
4201 memcpy(&opl, r, left);
4202 outs() << " (objc_property_list entends past the end of the section)\n";
4203 } else
4204 memcpy(&opl, r, sizeof(struct objc_property_list32));
4205 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4206 swapStruct(opl);
4207 outs() << " entsize " << opl.entsize << "\n";
4208 outs() << " count " << opl.count << "\n";
4209
4210 p += sizeof(struct objc_property_list32);
4211 offset += sizeof(struct objc_property_list32);
4212 for (j = 0; j < opl.count; j++) {
4213 r = get_pointer_32(p, offset, left, S, info);
4214 if (r == nullptr)
4215 return;
4216 memset(&op, '\0', sizeof(struct objc_property32));
4217 if (left < sizeof(struct objc_property32)) {
4218 memcpy(&op, r, left);
4219 outs() << " (objc_property entends past the end of the section)\n";
4220 } else
4221 memcpy(&op, r, sizeof(struct objc_property32));
4222 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4223 swapStruct(op);
4224
4225 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4226 name = get_pointer_32(op.name, xoffset, left, xS, info);
4227 if (name != nullptr)
4228 outs() << format(" %.*s", left, name);
4229 outs() << "\n";
4230
4231 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4232 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4233 if (name != nullptr)
4234 outs() << format(" %.*s", left, name);
4235 outs() << "\n";
4236
4237 p += sizeof(struct objc_property32);
4238 offset += sizeof(struct objc_property32);
4239 }
4240}
4241
Richard Smith81ff44d2015-10-09 22:09:56 +00004242static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
Kevin Enderby0fc11822015-04-01 20:57:01 +00004243 bool &is_meta_class) {
4244 struct class_ro64_t cro;
4245 const char *r;
4246 uint32_t offset, xoffset, left;
4247 SectionRef S, xS;
4248 const char *name, *sym_name;
4249 uint64_t n_value;
4250
4251 r = get_pointer_64(p, offset, left, S, info);
4252 if (r == nullptr || left < sizeof(struct class_ro64_t))
Richard Smith81ff44d2015-10-09 22:09:56 +00004253 return false;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004254 memset(&cro, '\0', sizeof(struct class_ro64_t));
4255 if (left < sizeof(struct class_ro64_t)) {
4256 memcpy(&cro, r, left);
4257 outs() << " (class_ro_t entends past the end of the section)\n";
4258 } else
4259 memcpy(&cro, r, sizeof(struct class_ro64_t));
4260 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4261 swapStruct(cro);
4262 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4263 if (cro.flags & RO_META)
4264 outs() << " RO_META";
4265 if (cro.flags & RO_ROOT)
4266 outs() << " RO_ROOT";
4267 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4268 outs() << " RO_HAS_CXX_STRUCTORS";
4269 outs() << "\n";
4270 outs() << " instanceStart " << cro.instanceStart << "\n";
4271 outs() << " instanceSize " << cro.instanceSize << "\n";
4272 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4273 << "\n";
4274 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4275 << "\n";
4276 print_layout_map64(cro.ivarLayout, info);
4277
4278 outs() << " name ";
4279 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4280 info, n_value, cro.name);
4281 if (n_value != 0) {
4282 if (info->verbose && sym_name != nullptr)
4283 outs() << sym_name;
4284 else
4285 outs() << format("0x%" PRIx64, n_value);
4286 if (cro.name != 0)
4287 outs() << " + " << format("0x%" PRIx64, cro.name);
4288 } else
4289 outs() << format("0x%" PRIx64, cro.name);
4290 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4291 if (name != nullptr)
4292 outs() << format(" %.*s", left, name);
4293 outs() << "\n";
4294
4295 outs() << " baseMethods ";
4296 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4297 S, info, n_value, cro.baseMethods);
4298 if (n_value != 0) {
4299 if (info->verbose && sym_name != nullptr)
4300 outs() << sym_name;
4301 else
4302 outs() << format("0x%" PRIx64, n_value);
4303 if (cro.baseMethods != 0)
4304 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4305 } else
4306 outs() << format("0x%" PRIx64, cro.baseMethods);
4307 outs() << " (struct method_list_t *)\n";
4308 if (cro.baseMethods + n_value != 0)
4309 print_method_list64_t(cro.baseMethods + n_value, info, "");
4310
4311 outs() << " baseProtocols ";
4312 sym_name =
4313 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4314 info, n_value, cro.baseProtocols);
4315 if (n_value != 0) {
4316 if (info->verbose && sym_name != nullptr)
4317 outs() << sym_name;
4318 else
4319 outs() << format("0x%" PRIx64, n_value);
4320 if (cro.baseProtocols != 0)
4321 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4322 } else
4323 outs() << format("0x%" PRIx64, cro.baseProtocols);
4324 outs() << "\n";
4325 if (cro.baseProtocols + n_value != 0)
4326 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4327
4328 outs() << " ivars ";
4329 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004330 info, n_value, cro.ivars);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004331 if (n_value != 0) {
4332 if (info->verbose && sym_name != nullptr)
4333 outs() << sym_name;
4334 else
4335 outs() << format("0x%" PRIx64, n_value);
4336 if (cro.ivars != 0)
4337 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4338 } else
4339 outs() << format("0x%" PRIx64, cro.ivars);
4340 outs() << "\n";
4341 if (cro.ivars + n_value != 0)
4342 print_ivar_list64_t(cro.ivars + n_value, info);
4343
4344 outs() << " weakIvarLayout ";
4345 sym_name =
4346 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4347 info, n_value, cro.weakIvarLayout);
4348 if (n_value != 0) {
4349 if (info->verbose && sym_name != nullptr)
4350 outs() << sym_name;
4351 else
4352 outs() << format("0x%" PRIx64, n_value);
4353 if (cro.weakIvarLayout != 0)
4354 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4355 } else
4356 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4357 outs() << "\n";
4358 print_layout_map64(cro.weakIvarLayout + n_value, info);
4359
4360 outs() << " baseProperties ";
4361 sym_name =
4362 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4363 info, n_value, cro.baseProperties);
4364 if (n_value != 0) {
4365 if (info->verbose && sym_name != nullptr)
4366 outs() << sym_name;
4367 else
4368 outs() << format("0x%" PRIx64, n_value);
4369 if (cro.baseProperties != 0)
4370 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4371 } else
4372 outs() << format("0x%" PRIx64, cro.baseProperties);
4373 outs() << "\n";
4374 if (cro.baseProperties + n_value != 0)
4375 print_objc_property_list64(cro.baseProperties + n_value, info);
4376
Rafael Espindolab9091322015-10-24 23:19:10 +00004377 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004378 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004379}
4380
Richard Smith81ff44d2015-10-09 22:09:56 +00004381static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004382 bool &is_meta_class) {
4383 struct class_ro32_t cro;
4384 const char *r;
4385 uint32_t offset, xoffset, left;
4386 SectionRef S, xS;
4387 const char *name;
4388
4389 r = get_pointer_32(p, offset, left, S, info);
4390 if (r == nullptr)
Richard Smith81ff44d2015-10-09 22:09:56 +00004391 return false;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004392 memset(&cro, '\0', sizeof(struct class_ro32_t));
4393 if (left < sizeof(struct class_ro32_t)) {
4394 memcpy(&cro, r, left);
4395 outs() << " (class_ro_t entends past the end of the section)\n";
4396 } else
4397 memcpy(&cro, r, sizeof(struct class_ro32_t));
4398 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4399 swapStruct(cro);
4400 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4401 if (cro.flags & RO_META)
4402 outs() << " RO_META";
4403 if (cro.flags & RO_ROOT)
4404 outs() << " RO_ROOT";
4405 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4406 outs() << " RO_HAS_CXX_STRUCTORS";
4407 outs() << "\n";
4408 outs() << " instanceStart " << cro.instanceStart << "\n";
4409 outs() << " instanceSize " << cro.instanceSize << "\n";
4410 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4411 << "\n";
4412 print_layout_map32(cro.ivarLayout, info);
4413
4414 outs() << " name " << format("0x%" PRIx32, cro.name);
4415 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4416 if (name != nullptr)
4417 outs() << format(" %.*s", left, name);
4418 outs() << "\n";
4419
4420 outs() << " baseMethods "
4421 << format("0x%" PRIx32, cro.baseMethods)
4422 << " (struct method_list_t *)\n";
4423 if (cro.baseMethods != 0)
4424 print_method_list32_t(cro.baseMethods, info, "");
4425
4426 outs() << " baseProtocols "
4427 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4428 if (cro.baseProtocols != 0)
4429 print_protocol_list32_t(cro.baseProtocols, info);
4430 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4431 << "\n";
4432 if (cro.ivars != 0)
4433 print_ivar_list32_t(cro.ivars, info);
4434 outs() << " weakIvarLayout "
4435 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4436 print_layout_map32(cro.weakIvarLayout, info);
4437 outs() << " baseProperties "
4438 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4439 if (cro.baseProperties != 0)
4440 print_objc_property_list32(cro.baseProperties, info);
Rafael Espindolab9091322015-10-24 23:19:10 +00004441 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004442 return true;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004443}
4444
Kevin Enderby0fc11822015-04-01 20:57:01 +00004445static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4446 struct class64_t c;
4447 const char *r;
4448 uint32_t offset, left;
4449 SectionRef S;
4450 const char *name;
4451 uint64_t isa_n_value, n_value;
4452
4453 r = get_pointer_64(p, offset, left, S, info);
4454 if (r == nullptr || left < sizeof(struct class64_t))
4455 return;
4456 memset(&c, '\0', sizeof(struct class64_t));
4457 if (left < sizeof(struct class64_t)) {
4458 memcpy(&c, r, left);
4459 outs() << " (class_t entends past the end of the section)\n";
4460 } else
4461 memcpy(&c, r, sizeof(struct class64_t));
4462 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4463 swapStruct(c);
4464
4465 outs() << " isa " << format("0x%" PRIx64, c.isa);
4466 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
4467 isa_n_value, c.isa);
4468 if (name != nullptr)
4469 outs() << " " << name;
4470 outs() << "\n";
4471
4472 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
4473 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
4474 n_value, c.superclass);
4475 if (name != nullptr)
4476 outs() << " " << name;
4477 outs() << "\n";
4478
4479 outs() << " cache " << format("0x%" PRIx64, c.cache);
4480 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
4481 n_value, c.cache);
4482 if (name != nullptr)
4483 outs() << " " << name;
4484 outs() << "\n";
4485
4486 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
4487 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
4488 n_value, c.vtable);
4489 if (name != nullptr)
4490 outs() << " " << name;
4491 outs() << "\n";
4492
4493 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
4494 n_value, c.data);
4495 outs() << " data ";
4496 if (n_value != 0) {
4497 if (info->verbose && name != nullptr)
4498 outs() << name;
4499 else
4500 outs() << format("0x%" PRIx64, n_value);
4501 if (c.data != 0)
4502 outs() << " + " << format("0x%" PRIx64, c.data);
4503 } else
4504 outs() << format("0x%" PRIx64, c.data);
4505 outs() << " (struct class_ro_t *)";
4506
4507 // This is a Swift class if some of the low bits of the pointer are set.
4508 if ((c.data + n_value) & 0x7)
4509 outs() << " Swift class";
4510 outs() << "\n";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004511 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004512 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
4513 return;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004514
Kevin Enderbyaac75382015-10-08 16:56:35 +00004515 if (!is_meta_class &&
4516 c.isa + isa_n_value != p &&
4517 c.isa + isa_n_value != 0 &&
4518 info->depth < 100) {
4519 info->depth++;
4520 outs() << "Meta Class\n";
4521 print_class64_t(c.isa + isa_n_value, info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004522 }
4523}
4524
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004525static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
4526 struct class32_t c;
4527 const char *r;
4528 uint32_t offset, left;
4529 SectionRef S;
4530 const char *name;
4531
4532 r = get_pointer_32(p, offset, left, S, info);
4533 if (r == nullptr)
4534 return;
4535 memset(&c, '\0', sizeof(struct class32_t));
4536 if (left < sizeof(struct class32_t)) {
4537 memcpy(&c, r, left);
4538 outs() << " (class_t entends past the end of the section)\n";
4539 } else
4540 memcpy(&c, r, sizeof(struct class32_t));
4541 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4542 swapStruct(c);
4543
4544 outs() << " isa " << format("0x%" PRIx32, c.isa);
4545 name =
4546 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
4547 if (name != nullptr)
4548 outs() << " " << name;
4549 outs() << "\n";
4550
4551 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
4552 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
4553 c.superclass);
4554 if (name != nullptr)
4555 outs() << " " << name;
4556 outs() << "\n";
4557
4558 outs() << " cache " << format("0x%" PRIx32, c.cache);
4559 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
4560 c.cache);
4561 if (name != nullptr)
4562 outs() << " " << name;
4563 outs() << "\n";
4564
4565 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
4566 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
4567 c.vtable);
4568 if (name != nullptr)
4569 outs() << " " << name;
4570 outs() << "\n";
4571
4572 name =
4573 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
4574 outs() << " data " << format("0x%" PRIx32, c.data)
4575 << " (struct class_ro_t *)";
4576
4577 // This is a Swift class if some of the low bits of the pointer are set.
4578 if (c.data & 0x3)
4579 outs() << " Swift class";
4580 outs() << "\n";
4581 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004582 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
4583 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004584
Hans Wennborgcc9deb42015-09-29 18:02:48 +00004585 if (!is_meta_class) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004586 outs() << "Meta Class\n";
4587 print_class32_t(c.isa, info);
4588 }
4589}
4590
Kevin Enderby846c0002015-04-16 17:19:59 +00004591static void print_objc_class_t(struct objc_class_t *objc_class,
4592 struct DisassembleInfo *info) {
4593 uint32_t offset, left, xleft;
4594 const char *name, *p, *ivar_list;
4595 SectionRef S;
4596 int32_t i;
4597 struct objc_ivar_list_t objc_ivar_list;
4598 struct objc_ivar_t ivar;
4599
4600 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
4601 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
4602 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
4603 if (name != nullptr)
4604 outs() << format(" %.*s", left, name);
4605 else
4606 outs() << " (not in an __OBJC section)";
4607 }
4608 outs() << "\n";
4609
4610 outs() << "\t super_class "
4611 << format("0x%08" PRIx32, objc_class->super_class);
4612 if (info->verbose) {
4613 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
4614 if (name != nullptr)
4615 outs() << format(" %.*s", left, name);
4616 else
4617 outs() << " (not in an __OBJC section)";
4618 }
4619 outs() << "\n";
4620
4621 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
4622 if (info->verbose) {
4623 name = get_pointer_32(objc_class->name, 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\t version " << format("0x%08" PRIx32, objc_class->version)
4632 << "\n";
4633
4634 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
4635 if (info->verbose) {
4636 if (CLS_GETINFO(objc_class, CLS_CLASS))
4637 outs() << " CLS_CLASS";
4638 else if (CLS_GETINFO(objc_class, CLS_META))
4639 outs() << " CLS_META";
4640 }
4641 outs() << "\n";
4642
4643 outs() << "\t instance_size "
4644 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
4645
4646 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
4647 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
4648 if (p != nullptr) {
4649 if (left > sizeof(struct objc_ivar_list_t)) {
4650 outs() << "\n";
4651 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
4652 } else {
4653 outs() << " (entends past the end of the section)\n";
4654 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
4655 memcpy(&objc_ivar_list, p, left);
4656 }
4657 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4658 swapStruct(objc_ivar_list);
4659 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
4660 ivar_list = p + sizeof(struct objc_ivar_list_t);
4661 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
4662 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
4663 outs() << "\t\t remaining ivar's extend past the of the section\n";
4664 break;
4665 }
4666 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
4667 sizeof(struct objc_ivar_t));
4668 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4669 swapStruct(ivar);
4670
4671 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
4672 if (info->verbose) {
4673 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
4674 if (name != nullptr)
4675 outs() << format(" %.*s", xleft, name);
4676 else
4677 outs() << " (not in an __OBJC section)";
4678 }
4679 outs() << "\n";
4680
4681 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
4682 if (info->verbose) {
4683 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
4684 if (name != nullptr)
4685 outs() << format(" %.*s", xleft, name);
4686 else
4687 outs() << " (not in an __OBJC section)";
4688 }
4689 outs() << "\n";
4690
4691 outs() << "\t\t ivar_offset "
4692 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
4693 }
4694 } else {
4695 outs() << " (not in an __OBJC section)\n";
4696 }
4697
4698 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
4699 if (print_method_list(objc_class->methodLists, info))
4700 outs() << " (not in an __OBJC section)\n";
4701
4702 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
4703 << "\n";
4704
4705 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
4706 if (print_protocol_list(objc_class->protocols, 16, info))
4707 outs() << " (not in an __OBJC section)\n";
4708}
4709
4710static void print_objc_objc_category_t(struct objc_category_t *objc_category,
4711 struct DisassembleInfo *info) {
4712 uint32_t offset, left;
4713 const char *name;
4714 SectionRef S;
4715
4716 outs() << "\t category name "
4717 << format("0x%08" PRIx32, objc_category->category_name);
4718 if (info->verbose) {
4719 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
4720 true);
4721 if (name != nullptr)
4722 outs() << format(" %.*s", left, name);
4723 else
4724 outs() << " (not in an __OBJC section)";
4725 }
4726 outs() << "\n";
4727
4728 outs() << "\t\t class name "
4729 << format("0x%08" PRIx32, objc_category->class_name);
4730 if (info->verbose) {
4731 name =
4732 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
4733 if (name != nullptr)
4734 outs() << format(" %.*s", left, name);
4735 else
4736 outs() << " (not in an __OBJC section)";
4737 }
4738 outs() << "\n";
4739
4740 outs() << "\t instance methods "
4741 << format("0x%08" PRIx32, objc_category->instance_methods);
4742 if (print_method_list(objc_category->instance_methods, info))
4743 outs() << " (not in an __OBJC section)\n";
4744
4745 outs() << "\t class methods "
4746 << format("0x%08" PRIx32, objc_category->class_methods);
4747 if (print_method_list(objc_category->class_methods, info))
4748 outs() << " (not in an __OBJC section)\n";
4749}
4750
Kevin Enderby0fc11822015-04-01 20:57:01 +00004751static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
4752 struct category64_t c;
4753 const char *r;
4754 uint32_t offset, xoffset, left;
4755 SectionRef S, xS;
4756 const char *name, *sym_name;
4757 uint64_t n_value;
4758
4759 r = get_pointer_64(p, offset, left, S, info);
4760 if (r == nullptr)
4761 return;
4762 memset(&c, '\0', sizeof(struct category64_t));
4763 if (left < sizeof(struct category64_t)) {
4764 memcpy(&c, r, left);
4765 outs() << " (category_t entends past the end of the section)\n";
4766 } else
4767 memcpy(&c, r, sizeof(struct category64_t));
4768 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4769 swapStruct(c);
4770
4771 outs() << " name ";
4772 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
4773 info, n_value, c.name);
4774 if (n_value != 0) {
4775 if (info->verbose && sym_name != nullptr)
4776 outs() << sym_name;
4777 else
4778 outs() << format("0x%" PRIx64, n_value);
4779 if (c.name != 0)
4780 outs() << " + " << format("0x%" PRIx64, c.name);
4781 } else
4782 outs() << format("0x%" PRIx64, c.name);
4783 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
4784 if (name != nullptr)
4785 outs() << format(" %.*s", left, name);
4786 outs() << "\n";
4787
4788 outs() << " cls ";
4789 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
4790 n_value, c.cls);
4791 if (n_value != 0) {
4792 if (info->verbose && sym_name != nullptr)
4793 outs() << sym_name;
4794 else
4795 outs() << format("0x%" PRIx64, n_value);
4796 if (c.cls != 0)
4797 outs() << " + " << format("0x%" PRIx64, c.cls);
4798 } else
4799 outs() << format("0x%" PRIx64, c.cls);
4800 outs() << "\n";
4801 if (c.cls + n_value != 0)
4802 print_class64_t(c.cls + n_value, info);
4803
4804 outs() << " instanceMethods ";
4805 sym_name =
4806 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
4807 info, n_value, c.instanceMethods);
4808 if (n_value != 0) {
4809 if (info->verbose && sym_name != nullptr)
4810 outs() << sym_name;
4811 else
4812 outs() << format("0x%" PRIx64, n_value);
4813 if (c.instanceMethods != 0)
4814 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
4815 } else
4816 outs() << format("0x%" PRIx64, c.instanceMethods);
4817 outs() << "\n";
4818 if (c.instanceMethods + n_value != 0)
4819 print_method_list64_t(c.instanceMethods + n_value, info, "");
4820
4821 outs() << " classMethods ";
4822 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
4823 S, info, n_value, c.classMethods);
4824 if (n_value != 0) {
4825 if (info->verbose && sym_name != nullptr)
4826 outs() << sym_name;
4827 else
4828 outs() << format("0x%" PRIx64, n_value);
4829 if (c.classMethods != 0)
4830 outs() << " + " << format("0x%" PRIx64, c.classMethods);
4831 } else
4832 outs() << format("0x%" PRIx64, c.classMethods);
4833 outs() << "\n";
4834 if (c.classMethods + n_value != 0)
4835 print_method_list64_t(c.classMethods + n_value, info, "");
4836
4837 outs() << " protocols ";
4838 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
4839 info, n_value, c.protocols);
4840 if (n_value != 0) {
4841 if (info->verbose && sym_name != nullptr)
4842 outs() << sym_name;
4843 else
4844 outs() << format("0x%" PRIx64, n_value);
4845 if (c.protocols != 0)
4846 outs() << " + " << format("0x%" PRIx64, c.protocols);
4847 } else
4848 outs() << format("0x%" PRIx64, c.protocols);
4849 outs() << "\n";
4850 if (c.protocols + n_value != 0)
4851 print_protocol_list64_t(c.protocols + n_value, info);
4852
4853 outs() << "instanceProperties ";
4854 sym_name =
4855 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
4856 S, info, n_value, c.instanceProperties);
4857 if (n_value != 0) {
4858 if (info->verbose && sym_name != nullptr)
4859 outs() << sym_name;
4860 else
4861 outs() << format("0x%" PRIx64, n_value);
4862 if (c.instanceProperties != 0)
4863 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
4864 } else
4865 outs() << format("0x%" PRIx64, c.instanceProperties);
4866 outs() << "\n";
4867 if (c.instanceProperties + n_value != 0)
4868 print_objc_property_list64(c.instanceProperties + n_value, info);
4869}
4870
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004871static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
4872 struct category32_t c;
4873 const char *r;
4874 uint32_t offset, left;
4875 SectionRef S, xS;
4876 const char *name;
4877
4878 r = get_pointer_32(p, offset, left, S, info);
4879 if (r == nullptr)
4880 return;
4881 memset(&c, '\0', sizeof(struct category32_t));
4882 if (left < sizeof(struct category32_t)) {
4883 memcpy(&c, r, left);
4884 outs() << " (category_t entends past the end of the section)\n";
4885 } else
4886 memcpy(&c, r, sizeof(struct category32_t));
4887 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4888 swapStruct(c);
4889
4890 outs() << " name " << format("0x%" PRIx32, c.name);
4891 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
4892 c.name);
Hans Wennborgcc9deb42015-09-29 18:02:48 +00004893 if (name)
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004894 outs() << " " << name;
4895 outs() << "\n";
4896
4897 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
4898 if (c.cls != 0)
4899 print_class32_t(c.cls, info);
4900 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
4901 << "\n";
4902 if (c.instanceMethods != 0)
4903 print_method_list32_t(c.instanceMethods, info, "");
4904 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
4905 << "\n";
4906 if (c.classMethods != 0)
4907 print_method_list32_t(c.classMethods, info, "");
4908 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
4909 if (c.protocols != 0)
4910 print_protocol_list32_t(c.protocols, info);
4911 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
4912 << "\n";
4913 if (c.instanceProperties != 0)
4914 print_objc_property_list32(c.instanceProperties, info);
4915}
4916
Kevin Enderby0fc11822015-04-01 20:57:01 +00004917static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
4918 uint32_t i, left, offset, xoffset;
4919 uint64_t p, n_value;
4920 struct message_ref64 mr;
4921 const char *name, *sym_name;
4922 const char *r;
4923 SectionRef xS;
4924
4925 if (S == SectionRef())
4926 return;
4927
4928 StringRef SectName;
4929 S.getName(SectName);
4930 DataRefImpl Ref = S.getRawDataRefImpl();
4931 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
4932 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4933 offset = 0;
4934 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
4935 p = S.getAddress() + i;
4936 r = get_pointer_64(p, offset, left, S, info);
4937 if (r == nullptr)
4938 return;
4939 memset(&mr, '\0', sizeof(struct message_ref64));
4940 if (left < sizeof(struct message_ref64)) {
4941 memcpy(&mr, r, left);
4942 outs() << " (message_ref entends past the end of the section)\n";
4943 } else
4944 memcpy(&mr, r, sizeof(struct message_ref64));
4945 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4946 swapStruct(mr);
4947
4948 outs() << " imp ";
4949 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
4950 n_value, mr.imp);
4951 if (n_value != 0) {
4952 outs() << format("0x%" PRIx64, n_value) << " ";
4953 if (mr.imp != 0)
4954 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
4955 } else
4956 outs() << format("0x%" PRIx64, mr.imp) << " ";
4957 if (name != nullptr)
4958 outs() << " " << name;
4959 outs() << "\n";
4960
4961 outs() << " sel ";
4962 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
4963 info, n_value, mr.sel);
4964 if (n_value != 0) {
4965 if (info->verbose && sym_name != nullptr)
4966 outs() << sym_name;
4967 else
4968 outs() << format("0x%" PRIx64, n_value);
4969 if (mr.sel != 0)
4970 outs() << " + " << format("0x%" PRIx64, mr.sel);
4971 } else
4972 outs() << format("0x%" PRIx64, mr.sel);
4973 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
4974 if (name != nullptr)
4975 outs() << format(" %.*s", left, name);
4976 outs() << "\n";
4977
4978 offset += sizeof(struct message_ref64);
4979 }
4980}
4981
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004982static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
4983 uint32_t i, left, offset, xoffset, p;
4984 struct message_ref32 mr;
4985 const char *name, *r;
4986 SectionRef xS;
4987
4988 if (S == SectionRef())
4989 return;
4990
4991 StringRef SectName;
4992 S.getName(SectName);
4993 DataRefImpl Ref = S.getRawDataRefImpl();
4994 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
4995 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4996 offset = 0;
4997 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
4998 p = S.getAddress() + i;
4999 r = get_pointer_32(p, offset, left, S, info);
5000 if (r == nullptr)
5001 return;
5002 memset(&mr, '\0', sizeof(struct message_ref32));
5003 if (left < sizeof(struct message_ref32)) {
5004 memcpy(&mr, r, left);
5005 outs() << " (message_ref entends past the end of the section)\n";
5006 } else
5007 memcpy(&mr, r, sizeof(struct message_ref32));
5008 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5009 swapStruct(mr);
5010
5011 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5012 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5013 mr.imp);
5014 if (name != nullptr)
5015 outs() << " " << name;
5016 outs() << "\n";
5017
5018 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5019 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5020 if (name != nullptr)
5021 outs() << " " << name;
5022 outs() << "\n";
5023
5024 offset += sizeof(struct message_ref32);
5025 }
5026}
5027
Kevin Enderby0fc11822015-04-01 20:57:01 +00005028static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5029 uint32_t left, offset, swift_version;
5030 uint64_t p;
5031 struct objc_image_info64 o;
5032 const char *r;
5033
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00005034 if (S == SectionRef())
5035 return;
5036
Kevin Enderby0fc11822015-04-01 20:57:01 +00005037 StringRef SectName;
5038 S.getName(SectName);
5039 DataRefImpl Ref = S.getRawDataRefImpl();
5040 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5041 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5042 p = S.getAddress();
5043 r = get_pointer_64(p, offset, left, S, info);
5044 if (r == nullptr)
5045 return;
5046 memset(&o, '\0', sizeof(struct objc_image_info64));
5047 if (left < sizeof(struct objc_image_info64)) {
5048 memcpy(&o, r, left);
5049 outs() << " (objc_image_info entends past the end of the section)\n";
5050 } else
5051 memcpy(&o, r, sizeof(struct objc_image_info64));
5052 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5053 swapStruct(o);
5054 outs() << " version " << o.version << "\n";
5055 outs() << " flags " << format("0x%" PRIx32, o.flags);
5056 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5057 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5058 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5059 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5060 swift_version = (o.flags >> 8) & 0xff;
5061 if (swift_version != 0) {
5062 if (swift_version == 1)
5063 outs() << " Swift 1.0";
5064 else if (swift_version == 2)
5065 outs() << " Swift 1.1";
5066 else
5067 outs() << " unknown future Swift version (" << swift_version << ")";
5068 }
5069 outs() << "\n";
5070}
5071
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005072static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5073 uint32_t left, offset, swift_version, p;
5074 struct objc_image_info32 o;
5075 const char *r;
5076
5077 StringRef SectName;
5078 S.getName(SectName);
5079 DataRefImpl Ref = S.getRawDataRefImpl();
5080 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5081 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5082 p = S.getAddress();
5083 r = get_pointer_32(p, offset, left, S, info);
5084 if (r == nullptr)
5085 return;
5086 memset(&o, '\0', sizeof(struct objc_image_info32));
5087 if (left < sizeof(struct objc_image_info32)) {
5088 memcpy(&o, r, left);
5089 outs() << " (objc_image_info entends past the end of the section)\n";
5090 } else
5091 memcpy(&o, r, sizeof(struct objc_image_info32));
5092 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5093 swapStruct(o);
5094 outs() << " version " << o.version << "\n";
5095 outs() << " flags " << format("0x%" PRIx32, o.flags);
5096 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5097 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5098 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5099 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5100 swift_version = (o.flags >> 8) & 0xff;
5101 if (swift_version != 0) {
5102 if (swift_version == 1)
5103 outs() << " Swift 1.0";
5104 else if (swift_version == 2)
5105 outs() << " Swift 1.1";
5106 else
5107 outs() << " unknown future Swift version (" << swift_version << ")";
5108 }
5109 outs() << "\n";
5110}
5111
Kevin Enderby846c0002015-04-16 17:19:59 +00005112static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5113 uint32_t left, offset, p;
5114 struct imageInfo_t o;
5115 const char *r;
5116
5117 StringRef SectName;
5118 S.getName(SectName);
5119 DataRefImpl Ref = S.getRawDataRefImpl();
5120 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5121 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5122 p = S.getAddress();
5123 r = get_pointer_32(p, offset, left, S, info);
5124 if (r == nullptr)
5125 return;
5126 memset(&o, '\0', sizeof(struct imageInfo_t));
5127 if (left < sizeof(struct imageInfo_t)) {
5128 memcpy(&o, r, left);
5129 outs() << " (imageInfo entends past the end of the section)\n";
5130 } else
5131 memcpy(&o, r, sizeof(struct imageInfo_t));
5132 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5133 swapStruct(o);
5134 outs() << " version " << o.version << "\n";
5135 outs() << " flags " << format("0x%" PRIx32, o.flags);
5136 if (o.flags & 0x1)
5137 outs() << " F&C";
5138 if (o.flags & 0x2)
5139 outs() << " GC";
5140 if (o.flags & 0x4)
5141 outs() << " GC-only";
5142 else
5143 outs() << " RR";
5144 outs() << "\n";
5145}
5146
Kevin Enderby0fc11822015-04-01 20:57:01 +00005147static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5148 SymbolAddressMap AddrMap;
5149 if (verbose)
5150 CreateSymbolAddressMap(O, &AddrMap);
5151
5152 std::vector<SectionRef> Sections;
5153 for (const SectionRef &Section : O->sections()) {
5154 StringRef SectName;
5155 Section.getName(SectName);
5156 Sections.push_back(Section);
5157 }
5158
5159 struct DisassembleInfo info;
5160 // Set up the block of info used by the Symbolizer call backs.
5161 info.verbose = verbose;
5162 info.O = O;
5163 info.AddrMap = &AddrMap;
5164 info.Sections = &Sections;
5165 info.class_name = nullptr;
5166 info.selector_name = nullptr;
5167 info.method = nullptr;
5168 info.demangled_name = nullptr;
5169 info.bindtable = nullptr;
5170 info.adrp_addr = 0;
5171 info.adrp_inst = 0;
5172
Kevin Enderbyaac75382015-10-08 16:56:35 +00005173 info.depth = 0;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005174 const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5175 if (CL != SectionRef()) {
5176 info.S = CL;
5177 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
5178 } else {
5179 const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
5180 info.S = CL;
5181 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
5182 }
5183
5184 const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5185 if (CR != SectionRef()) {
5186 info.S = CR;
5187 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
5188 } else {
5189 const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
5190 info.S = CR;
5191 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
5192 }
5193
5194 const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5195 if (SR != SectionRef()) {
5196 info.S = SR;
5197 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
5198 } else {
5199 const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
5200 info.S = SR;
5201 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
5202 }
5203
5204 const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5205 if (CA != SectionRef()) {
5206 info.S = CA;
5207 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
5208 } else {
5209 const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
5210 info.S = CA;
5211 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
5212 }
5213
5214 const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5215 if (PL != SectionRef()) {
5216 info.S = PL;
5217 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
5218 } else {
5219 const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
5220 info.S = PL;
5221 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
5222 }
5223
5224 const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5225 if (MR != SectionRef()) {
5226 info.S = MR;
5227 print_message_refs64(MR, &info);
5228 } else {
5229 const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
5230 info.S = MR;
5231 print_message_refs64(MR, &info);
5232 }
5233
5234 const SectionRef II = get_section(O, "__OBJC2", "__image_info");
5235 if (II != SectionRef()) {
5236 info.S = II;
5237 print_image_info64(II, &info);
5238 } else {
5239 const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
5240 info.S = II;
5241 print_image_info64(II, &info);
5242 }
Kevin Enderby0bc6ed42015-04-01 21:50:45 +00005243
5244 if (info.bindtable != nullptr)
5245 delete info.bindtable;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005246}
5247
5248static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005249 SymbolAddressMap AddrMap;
5250 if (verbose)
5251 CreateSymbolAddressMap(O, &AddrMap);
5252
5253 std::vector<SectionRef> Sections;
5254 for (const SectionRef &Section : O->sections()) {
5255 StringRef SectName;
5256 Section.getName(SectName);
5257 Sections.push_back(Section);
5258 }
5259
5260 struct DisassembleInfo info;
5261 // Set up the block of info used by the Symbolizer call backs.
5262 info.verbose = verbose;
5263 info.O = O;
5264 info.AddrMap = &AddrMap;
5265 info.Sections = &Sections;
5266 info.class_name = nullptr;
5267 info.selector_name = nullptr;
5268 info.method = nullptr;
5269 info.demangled_name = nullptr;
5270 info.bindtable = nullptr;
5271 info.adrp_addr = 0;
5272 info.adrp_inst = 0;
5273
5274 const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5275 if (CL != SectionRef()) {
5276 info.S = CL;
5277 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5278 } else {
5279 const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
5280 info.S = CL;
5281 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5282 }
5283
5284 const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5285 if (CR != SectionRef()) {
5286 info.S = CR;
5287 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5288 } else {
5289 const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
5290 info.S = CR;
5291 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5292 }
5293
5294 const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5295 if (SR != SectionRef()) {
5296 info.S = SR;
5297 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5298 } else {
5299 const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
5300 info.S = SR;
5301 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5302 }
5303
5304 const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5305 if (CA != SectionRef()) {
5306 info.S = CA;
5307 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5308 } else {
5309 const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
5310 info.S = CA;
5311 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5312 }
5313
5314 const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5315 if (PL != SectionRef()) {
5316 info.S = PL;
5317 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5318 } else {
5319 const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
5320 info.S = PL;
5321 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5322 }
5323
5324 const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5325 if (MR != SectionRef()) {
5326 info.S = MR;
5327 print_message_refs32(MR, &info);
5328 } else {
5329 const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
5330 info.S = MR;
5331 print_message_refs32(MR, &info);
5332 }
5333
5334 const SectionRef II = get_section(O, "__OBJC2", "__image_info");
5335 if (II != SectionRef()) {
5336 info.S = II;
5337 print_image_info32(II, &info);
5338 } else {
5339 const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
5340 info.S = II;
5341 print_image_info32(II, &info);
5342 }
Kevin Enderby0fc11822015-04-01 20:57:01 +00005343}
5344
5345static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby846c0002015-04-16 17:19:59 +00005346 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5347 const char *r, *name, *defs;
5348 struct objc_module_t module;
5349 SectionRef S, xS;
5350 struct objc_symtab_t symtab;
5351 struct objc_class_t objc_class;
5352 struct objc_category_t objc_category;
5353
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005354 outs() << "Objective-C segment\n";
Kevin Enderby846c0002015-04-16 17:19:59 +00005355 S = get_section(O, "__OBJC", "__module_info");
5356 if (S == SectionRef())
5357 return false;
5358
5359 SymbolAddressMap AddrMap;
5360 if (verbose)
5361 CreateSymbolAddressMap(O, &AddrMap);
5362
5363 std::vector<SectionRef> Sections;
5364 for (const SectionRef &Section : O->sections()) {
5365 StringRef SectName;
5366 Section.getName(SectName);
5367 Sections.push_back(Section);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005368 }
Kevin Enderby846c0002015-04-16 17:19:59 +00005369
5370 struct DisassembleInfo info;
5371 // Set up the block of info used by the Symbolizer call backs.
5372 info.verbose = verbose;
5373 info.O = O;
5374 info.AddrMap = &AddrMap;
5375 info.Sections = &Sections;
5376 info.class_name = nullptr;
5377 info.selector_name = nullptr;
5378 info.method = nullptr;
5379 info.demangled_name = nullptr;
5380 info.bindtable = nullptr;
5381 info.adrp_addr = 0;
5382 info.adrp_inst = 0;
5383
5384 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5385 p = S.getAddress() + i;
5386 r = get_pointer_32(p, offset, left, S, &info, true);
5387 if (r == nullptr)
5388 return true;
5389 memset(&module, '\0', sizeof(struct objc_module_t));
5390 if (left < sizeof(struct objc_module_t)) {
5391 memcpy(&module, r, left);
5392 outs() << " (module extends past end of __module_info section)\n";
5393 } else
5394 memcpy(&module, r, sizeof(struct objc_module_t));
5395 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5396 swapStruct(module);
5397
5398 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5399 outs() << " version " << module.version << "\n";
5400 outs() << " size " << module.size << "\n";
5401 outs() << " name ";
5402 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5403 if (name != nullptr)
5404 outs() << format("%.*s", left, name);
5405 else
5406 outs() << format("0x%08" PRIx32, module.name)
5407 << "(not in an __OBJC section)";
5408 outs() << "\n";
5409
5410 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5411 if (module.symtab == 0 || r == nullptr) {
5412 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5413 << " (not in an __OBJC section)\n";
5414 continue;
5415 }
5416 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5417 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5418 defs_left = 0;
5419 defs = nullptr;
5420 if (left < sizeof(struct objc_symtab_t)) {
5421 memcpy(&symtab, r, left);
5422 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5423 } else {
5424 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5425 if (left > sizeof(struct objc_symtab_t)) {
5426 defs_left = left - sizeof(struct objc_symtab_t);
5427 defs = r + sizeof(struct objc_symtab_t);
5428 }
5429 }
5430 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5431 swapStruct(symtab);
5432
5433 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5434 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5435 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5436 if (r == nullptr)
5437 outs() << " (not in an __OBJC section)";
5438 outs() << "\n";
5439 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5440 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5441 if (symtab.cls_def_cnt > 0)
5442 outs() << "\tClass Definitions\n";
5443 for (j = 0; j < symtab.cls_def_cnt; j++) {
5444 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5445 outs() << "\t(remaining class defs entries entends past the end of the "
5446 << "section)\n";
5447 break;
5448 }
5449 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5450 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5451 sys::swapByteOrder(def);
5452
5453 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5454 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5455 if (r != nullptr) {
5456 if (left > sizeof(struct objc_class_t)) {
5457 outs() << "\n";
5458 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5459 } else {
5460 outs() << " (entends past the end of the section)\n";
5461 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5462 memcpy(&objc_class, r, left);
5463 }
5464 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5465 swapStruct(objc_class);
5466 print_objc_class_t(&objc_class, &info);
5467 } else {
5468 outs() << "(not in an __OBJC section)\n";
5469 }
5470
5471 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
5472 outs() << "\tMeta Class";
5473 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
5474 if (r != nullptr) {
5475 if (left > sizeof(struct objc_class_t)) {
5476 outs() << "\n";
5477 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5478 } else {
5479 outs() << " (entends past the end of the section)\n";
5480 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5481 memcpy(&objc_class, r, left);
5482 }
5483 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5484 swapStruct(objc_class);
5485 print_objc_class_t(&objc_class, &info);
5486 } else {
5487 outs() << "(not in an __OBJC section)\n";
5488 }
5489 }
5490 }
5491 if (symtab.cat_def_cnt > 0)
5492 outs() << "\tCategory Definitions\n";
5493 for (j = 0; j < symtab.cat_def_cnt; j++) {
5494 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
5495 outs() << "\t(remaining category defs entries entends past the end of "
5496 << "the section)\n";
5497 break;
5498 }
5499 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
5500 sizeof(uint32_t));
5501 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5502 sys::swapByteOrder(def);
5503
5504 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5505 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
5506 << format("0x%08" PRIx32, def);
5507 if (r != nullptr) {
5508 if (left > sizeof(struct objc_category_t)) {
5509 outs() << "\n";
5510 memcpy(&objc_category, r, sizeof(struct objc_category_t));
5511 } else {
5512 outs() << " (entends past the end of the section)\n";
5513 memset(&objc_category, '\0', sizeof(struct objc_category_t));
5514 memcpy(&objc_category, r, left);
5515 }
5516 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5517 swapStruct(objc_category);
5518 print_objc_objc_category_t(&objc_category, &info);
5519 } else {
5520 outs() << "(not in an __OBJC section)\n";
5521 }
5522 }
5523 }
5524 const SectionRef II = get_section(O, "__OBJC", "__image_info");
5525 if (II != SectionRef())
5526 print_image_info(II, &info);
5527
5528 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005529}
5530
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00005531static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
5532 uint32_t size, uint32_t addr) {
5533 SymbolAddressMap AddrMap;
5534 CreateSymbolAddressMap(O, &AddrMap);
5535
5536 std::vector<SectionRef> Sections;
5537 for (const SectionRef &Section : O->sections()) {
5538 StringRef SectName;
5539 Section.getName(SectName);
5540 Sections.push_back(Section);
5541 }
5542
5543 struct DisassembleInfo info;
5544 // Set up the block of info used by the Symbolizer call backs.
5545 info.verbose = true;
5546 info.O = O;
5547 info.AddrMap = &AddrMap;
5548 info.Sections = &Sections;
5549 info.class_name = nullptr;
5550 info.selector_name = nullptr;
5551 info.method = nullptr;
5552 info.demangled_name = nullptr;
5553 info.bindtable = nullptr;
5554 info.adrp_addr = 0;
5555 info.adrp_inst = 0;
5556
5557 const char *p;
5558 struct objc_protocol_t protocol;
5559 uint32_t left, paddr;
5560 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
5561 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
5562 left = size - (p - sect);
5563 if (left < sizeof(struct objc_protocol_t)) {
5564 outs() << "Protocol extends past end of __protocol section\n";
5565 memcpy(&protocol, p, left);
5566 } else
5567 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
5568 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5569 swapStruct(protocol);
5570 paddr = addr + (p - sect);
5571 outs() << "Protocol " << format("0x%" PRIx32, paddr);
5572 if (print_protocol(paddr, 0, &info))
5573 outs() << "(not in an __OBJC section)\n";
5574 }
5575}
5576
Kevin Enderby0fc11822015-04-01 20:57:01 +00005577static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
5578 if (O->is64Bit())
5579 printObjc2_64bit_MetaData(O, verbose);
5580 else {
5581 MachO::mach_header H;
5582 H = O->getHeader();
5583 if (H.cputype == MachO::CPU_TYPE_ARM)
5584 printObjc2_32bit_MetaData(O, verbose);
5585 else {
5586 // This is the 32-bit non-arm cputype case. Which is normally
5587 // the first Objective-C ABI. But it may be the case of a
5588 // binary for the iOS simulator which is the second Objective-C
5589 // ABI. In that case printObjc1_32bit_MetaData() will determine that
5590 // and return false.
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005591 if (!printObjc1_32bit_MetaData(O, verbose))
Kevin Enderby0fc11822015-04-01 20:57:01 +00005592 printObjc2_32bit_MetaData(O, verbose);
5593 }
5594 }
5595}
5596
Kevin Enderbybf246f52014-09-24 23:08:22 +00005597// GuessLiteralPointer returns a string which for the item in the Mach-O file
5598// for the address passed in as ReferenceValue for printing as a comment with
5599// the instruction and also returns the corresponding type of that item
5600// indirectly through ReferenceType.
5601//
5602// If ReferenceValue is an address of literal cstring then a pointer to the
5603// cstring is returned and ReferenceType is set to
5604// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
5605//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005606// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
5607// Class ref that name is returned and the ReferenceType is set accordingly.
5608//
5609// Lastly, literals which are Symbol address in a literal pool are looked for
5610// and if found the symbol name is returned and ReferenceType is set to
5611// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
5612//
5613// If there is no item in the Mach-O file for the address passed in as
5614// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00005615static const char *GuessLiteralPointer(uint64_t ReferenceValue,
5616 uint64_t ReferencePC,
5617 uint64_t *ReferenceType,
5618 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00005619 // First see if there is an external relocation entry at the ReferencePC.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00005620 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
5621 uint64_t sect_addr = info->S.getAddress();
5622 uint64_t sect_offset = ReferencePC - sect_addr;
5623 bool reloc_found = false;
5624 DataRefImpl Rel;
5625 MachO::any_relocation_info RE;
5626 bool isExtern = false;
5627 SymbolRef Symbol;
5628 for (const RelocationRef &Reloc : info->S.relocations()) {
5629 uint64_t RelocOffset = Reloc.getOffset();
5630 if (RelocOffset == sect_offset) {
5631 Rel = Reloc.getRawDataRefImpl();
5632 RE = info->O->getRelocation(Rel);
5633 if (info->O->isRelocationScattered(RE))
5634 continue;
5635 isExtern = info->O->getPlainRelocationExternal(RE);
5636 if (isExtern) {
5637 symbol_iterator RelocSym = Reloc.getSymbol();
5638 Symbol = *RelocSym;
5639 }
5640 reloc_found = true;
5641 break;
Kevin Enderbybf246f52014-09-24 23:08:22 +00005642 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005643 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00005644 // If there is an external relocation entry for a symbol in a section
5645 // then used that symbol's value for the value of the reference.
5646 if (reloc_found && isExtern) {
5647 if (info->O->getAnyRelocationPCRel(RE)) {
5648 unsigned Type = info->O->getAnyRelocationType(RE);
5649 if (Type == MachO::X86_64_RELOC_SIGNED) {
5650 ReferenceValue = Symbol.getValue();
5651 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005652 }
5653 }
5654 }
5655
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005656 // Look for literals such as Objective-C CFStrings refs, Selector refs,
5657 // Message refs and Class refs.
5658 bool classref, selref, msgref, cfstring;
5659 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
5660 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00005661 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005662 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
5663 // And the pointer_value in that section is typically zero as it will be
5664 // set by dyld as part of the "bind information".
5665 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
5666 if (name != nullptr) {
5667 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00005668 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005669 if (class_name != nullptr && class_name[1] == '_' &&
5670 class_name[2] != '\0') {
5671 info->class_name = class_name + 2;
5672 return name;
5673 }
5674 }
5675 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005676
David Blaikie33dd45d02015-03-23 18:39:02 +00005677 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005678 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
5679 const char *name =
5680 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
5681 if (name != nullptr)
5682 info->class_name = name;
5683 else
5684 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00005685 return name;
5686 }
5687
David Blaikie33dd45d02015-03-23 18:39:02 +00005688 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005689 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
5690 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
5691 return name;
5692 }
5693
David Blaikie33dd45d02015-03-23 18:39:02 +00005694 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005695 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
5696
5697 if (pointer_value != 0)
5698 ReferenceValue = pointer_value;
5699
5700 const char *name = GuessCstringPointer(ReferenceValue, info);
5701 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00005702 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005703 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
5704 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00005705 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005706 info->class_name = nullptr;
5707 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
5708 info->selector_name = name;
5709 } else
5710 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
5711 return name;
5712 }
5713
5714 // Lastly look for an indirect symbol with this ReferenceValue which is in
5715 // a literal pool. If found return that symbol name.
5716 name = GuessIndirectSymbol(ReferenceValue, info);
5717 if (name) {
5718 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
5719 return name;
5720 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005721
5722 return nullptr;
5723}
5724
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005725// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00005726// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005727// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
5728// is created and returns the symbol name that matches the ReferenceValue or
5729// nullptr if none. The ReferenceType is passed in for the IN type of
5730// reference the instruction is making from the values in defined in the header
5731// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
5732// Out type and the ReferenceName will also be set which is added as a comment
5733// to the disassembled instruction.
5734//
Kevin Enderby04bf6932014-10-28 23:39:46 +00005735#if HAVE_CXXABI_H
5736// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005737// returned through ReferenceName and ReferenceType is set to
5738// LLVMDisassembler_ReferenceType_DeMangled_Name .
Kevin Enderby04bf6932014-10-28 23:39:46 +00005739#endif
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005740//
5741// When this is called to get a symbol name for a branch target then the
5742// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
5743// SymbolValue will be looked for in the indirect symbol table to determine if
5744// it is an address for a symbol stub. If so then the symbol name for that
5745// stub is returned indirectly through ReferenceName and then ReferenceType is
5746// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
5747//
Kevin Enderbybf246f52014-09-24 23:08:22 +00005748// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005749// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
5750// SymbolValue is checked to be an address of literal pointer, symbol pointer,
5751// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005752// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00005753static const char *SymbolizerSymbolLookUp(void *DisInfo,
5754 uint64_t ReferenceValue,
5755 uint64_t *ReferenceType,
5756 uint64_t ReferencePC,
5757 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005758 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00005759 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00005760 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00005761 *ReferenceName = nullptr;
5762 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005763 return nullptr;
5764 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005765
Kevin Enderbyf6d25852015-01-31 00:37:11 +00005766 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00005767
Kevin Enderby85974882014-09-26 22:20:44 +00005768 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
5769 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00005770 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005771 method_reference(info, ReferenceType, ReferenceName);
5772 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
5773 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
5774 } else
Kevin Enderby04bf6932014-10-28 23:39:46 +00005775#if HAVE_CXXABI_H
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005776 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00005777 if (info->demangled_name != nullptr)
5778 free(info->demangled_name);
5779 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005780 info->demangled_name =
5781 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00005782 if (info->demangled_name != nullptr) {
5783 *ReferenceName = info->demangled_name;
5784 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5785 } else
5786 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5787 } else
5788#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005789 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5790 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
5791 *ReferenceName =
5792 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00005793 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005794 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00005795 else
5796 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00005797 // If this is arm64 and the reference is an adrp instruction save the
5798 // instruction, passed in ReferenceValue and the address of the instruction
5799 // for use later if we see and add immediate instruction.
5800 } else if (info->O->getArch() == Triple::aarch64 &&
5801 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
5802 info->adrp_inst = ReferenceValue;
5803 info->adrp_addr = ReferencePC;
5804 SymbolName = nullptr;
5805 *ReferenceName = nullptr;
5806 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5807 // If this is arm64 and reference is an add immediate instruction and we
5808 // have
5809 // seen an adrp instruction just before it and the adrp's Xd register
5810 // matches
5811 // this add's Xn register reconstruct the value being referenced and look to
5812 // see if it is a literal pointer. Note the add immediate instruction is
5813 // passed in ReferenceValue.
5814 } else if (info->O->getArch() == Triple::aarch64 &&
5815 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
5816 ReferencePC - 4 == info->adrp_addr &&
5817 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5818 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5819 uint32_t addxri_inst;
5820 uint64_t adrp_imm, addxri_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 addxri_inst = ReferenceValue;
5828 addxri_imm = (addxri_inst >> 10) & 0xfff;
5829 if (((addxri_inst >> 22) & 0x3) == 1)
5830 addxri_imm <<= 12;
5831
5832 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5833 (adrp_imm << 12) + addxri_imm;
5834
5835 *ReferenceName =
5836 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5837 if (*ReferenceName == nullptr)
5838 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5839 // If this is arm64 and the reference is a load register instruction and we
5840 // have seen an adrp instruction just before it and the adrp's Xd register
5841 // matches this add's Xn register reconstruct the value being referenced and
5842 // look to see if it is a literal pointer. Note the load register
5843 // instruction is passed in ReferenceValue.
5844 } else if (info->O->getArch() == Triple::aarch64 &&
5845 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
5846 ReferencePC - 4 == info->adrp_addr &&
5847 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5848 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5849 uint32_t ldrxui_inst;
5850 uint64_t adrp_imm, ldrxui_imm;
5851
5852 adrp_imm =
5853 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5854 if (info->adrp_inst & 0x0200000)
5855 adrp_imm |= 0xfffffffffc000000LL;
5856
5857 ldrxui_inst = ReferenceValue;
5858 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
5859
5860 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5861 (adrp_imm << 12) + (ldrxui_imm << 3);
5862
5863 *ReferenceName =
5864 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5865 if (*ReferenceName == nullptr)
5866 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5867 }
5868 // If this arm64 and is an load register (PC-relative) instruction the
5869 // ReferenceValue is the PC plus the immediate value.
5870 else if (info->O->getArch() == Triple::aarch64 &&
5871 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
5872 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
5873 *ReferenceName =
5874 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5875 if (*ReferenceName == nullptr)
5876 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby85974882014-09-26 22:20:44 +00005877 }
Kevin Enderby04bf6932014-10-28 23:39:46 +00005878#if HAVE_CXXABI_H
5879 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
5880 if (info->demangled_name != nullptr)
5881 free(info->demangled_name);
5882 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005883 info->demangled_name =
5884 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00005885 if (info->demangled_name != nullptr) {
5886 *ReferenceName = info->demangled_name;
5887 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5888 }
5889 }
5890#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005891 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00005892 *ReferenceName = nullptr;
5893 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5894 }
5895
5896 return SymbolName;
5897}
5898
Kevin Enderbybf246f52014-09-24 23:08:22 +00005899/// \brief Emits the comments that are stored in the CommentStream.
5900/// Each comment in the CommentStream must end with a newline.
5901static void emitComments(raw_svector_ostream &CommentStream,
5902 SmallString<128> &CommentsToEmit,
5903 formatted_raw_ostream &FormattedOS,
5904 const MCAsmInfo &MAI) {
5905 // Flush the stream before taking its content.
Kevin Enderbybf246f52014-09-24 23:08:22 +00005906 StringRef Comments = CommentsToEmit.str();
5907 // Get the default information for printing a comment.
5908 const char *CommentBegin = MAI.getCommentString();
5909 unsigned CommentColumn = MAI.getCommentColumn();
5910 bool IsFirst = true;
5911 while (!Comments.empty()) {
5912 if (!IsFirst)
5913 FormattedOS << '\n';
5914 // Emit a line of comments.
5915 FormattedOS.PadToColumn(CommentColumn);
5916 size_t Position = Comments.find('\n');
5917 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
5918 // Move after the newline character.
5919 Comments = Comments.substr(Position + 1);
5920 IsFirst = false;
5921 }
5922 FormattedOS.flush();
5923
5924 // Tell the comment stream that the vector changed underneath it.
5925 CommentsToEmit.clear();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005926}
5927
Kevin Enderby95df54c2015-02-04 01:01:38 +00005928static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
5929 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005930 const char *McpuDefault = nullptr;
5931 const Target *ThumbTarget = nullptr;
5932 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005933 if (!TheTarget) {
5934 // GetTarget prints out stuff.
5935 return;
5936 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005937 if (MCPU.empty() && McpuDefault)
5938 MCPU = McpuDefault;
5939
Ahmed Charles56440fd2014-03-06 05:51:42 +00005940 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005941 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00005942 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005943 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005944
Kevin Enderbyc9595622014-08-06 23:24:41 +00005945 // Package up features to be passed to target/subtarget
5946 std::string FeaturesStr;
5947 if (MAttrs.size()) {
5948 SubtargetFeatures Features;
5949 for (unsigned i = 0; i != MAttrs.size(); ++i)
5950 Features.AddFeature(MAttrs[i]);
5951 FeaturesStr = Features.getString();
5952 }
5953
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005954 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00005955 std::unique_ptr<const MCRegisterInfo> MRI(
5956 TheTarget->createMCRegInfo(TripleName));
5957 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00005958 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00005959 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +00005960 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00005961 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005962 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005963 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005964 std::unique_ptr<MCSymbolizer> Symbolizer;
5965 struct DisassembleInfo SymbolizerInfo;
5966 std::unique_ptr<MCRelocationInfo> RelInfo(
5967 TheTarget->createMCRelocationInfo(TripleName, Ctx));
5968 if (RelInfo) {
5969 Symbolizer.reset(TheTarget->createMCSymbolizer(
5970 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00005971 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005972 DisAsm->setSymbolizer(std::move(Symbolizer));
5973 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005974 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00005975 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00005976 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00005977 // Set the display preference for hex vs. decimal immediates.
5978 IP->setPrintImmHex(PrintImmHex);
5979 // Comment stream and backing vector.
5980 SmallString<128> CommentsToEmit;
5981 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00005982 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
5983 // if it is done then arm64 comments for string literals don't get printed
5984 // and some constant get printed instead and not setting it causes intel
5985 // (32-bit and 64-bit) comments printed with different spacing before the
5986 // comment causing different diffs with the 'C' disassembler library API.
5987 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00005988
Kevin Enderbyae3c1262014-11-14 21:52:18 +00005989 if (!AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencerc1363cf2011-10-07 19:25:47 +00005990 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00005991 << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005992 return;
5993 }
5994
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005995 // Set up thumb disassembler.
5996 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
5997 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
5998 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00005999 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006000 std::unique_ptr<MCInstPrinter> ThumbIP;
6001 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006002 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
6003 struct DisassembleInfo ThumbSymbolizerInfo;
6004 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006005 if (ThumbTarget) {
6006 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
6007 ThumbAsmInfo.reset(
6008 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
6009 ThumbSTI.reset(
6010 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
6011 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
6012 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006013 MCContext *PtrThumbCtx = ThumbCtx.get();
6014 ThumbRelInfo.reset(
6015 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
6016 if (ThumbRelInfo) {
6017 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
6018 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006019 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006020 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
6021 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006022 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
6023 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006024 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
6025 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006026 // Set the display preference for hex vs. decimal immediates.
6027 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006028 }
6029
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006030 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006031 errs() << "error: couldn't initialize disassembler for target "
6032 << ThumbTripleName << '\n';
6033 return;
6034 }
6035
Charles Davis8bdfafd2013-09-01 04:28:48 +00006036 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006037
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006038 // FIXME: Using the -cfg command line option, this code used to be able to
6039 // annotate relocations with the referenced symbol's name, and if this was
6040 // inside a __[cf]string section, the data it points to. This is now replaced
6041 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00006042 std::vector<SectionRef> Sections;
6043 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006044 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00006045 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006046
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00006047 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
Kevin Enderby273ae012013-06-06 17:20:50 +00006048 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006049
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006050 // Sort the symbols by address, just in case they didn't come in that way.
Owen Andersond9243c42011-10-17 21:37:35 +00006051 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006052
Kevin Enderby273ae012013-06-06 17:20:50 +00006053 // Build a data in code table that is sorted on by the address of each entry.
6054 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00006055 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00006056 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00006057 else
6058 BaseAddress = BaseSegmentAddress;
6059 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00006060 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00006061 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006062 uint32_t Offset;
6063 DI->getOffset(Offset);
6064 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6065 }
6066 array_pod_sort(Dices.begin(), Dices.end());
6067
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006068#ifndef NDEBUG
6069 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6070#else
6071 raw_ostream &DebugOut = nulls();
6072#endif
6073
Ahmed Charles56440fd2014-03-06 05:51:42 +00006074 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00006075 ObjectFile *DbgObj = MachOOF;
Benjamin Kramer699128e2011-09-21 01:13:19 +00006076 // Try to find debug info and set up the DIContext for it.
6077 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00006078 // A separate DSym file path was specified, parse it as a macho file,
6079 // get the sections and supply it to the section name parsing machinery.
6080 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00006081 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006082 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00006083 if (std::error_code EC = BufOrErr.getError()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006084 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +00006085 return;
6086 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00006087 DbgObj =
6088 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
6089 .get()
6090 .release();
Benjamin Kramer699128e2011-09-21 01:13:19 +00006091 }
6092
Eric Christopher7370b552012-11-12 21:40:38 +00006093 // Setup the DIContext
Zachary Turner6489d7b2015-04-23 17:37:47 +00006094 diContext.reset(new DWARFContextInMemory(*DbgObj));
Benjamin Kramer699128e2011-09-21 01:13:19 +00006095 }
6096
Colin LeMahieufcc32762015-07-29 19:08:10 +00006097 if (FilterSections.size() == 0)
Kevin Enderby95df54c2015-02-04 01:01:38 +00006098 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006099
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006100 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00006101 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00006102 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6103 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006104
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006105 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006106
Rafael Espindolab0f76a42013-04-05 15:15:22 +00006107 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00006108 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006109 continue;
6110
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006111 StringRef BytesStr;
6112 Sections[SectIdx].getContents(BytesStr);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00006113 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6114 BytesStr.size());
Rafael Espindola80291272014-10-08 15:28:58 +00006115 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00006116
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006117 bool symbolTableWorked = false;
6118
Kevin Enderbybf246f52014-09-24 23:08:22 +00006119 // Create a map of symbol addresses to symbol names for use by
6120 // the SymbolizerSymbolLookUp() routine.
6121 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00006122 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006123 for (const SymbolRef &Symbol : MachOOF->symbols()) {
Rafael Espindola2fa80cc2015-06-26 12:18:49 +00006124 SymbolRef::Type ST = Symbol.getType();
Kevin Enderbybf246f52014-09-24 23:08:22 +00006125 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
6126 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00006127 uint64_t Address = Symbol.getValue();
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006128 ErrorOr<StringRef> SymNameOrErr = Symbol.getName();
6129 if (std::error_code EC = SymNameOrErr.getError())
6130 report_fatal_error(EC.message());
6131 StringRef SymName = *SymNameOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006132 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00006133 if (!DisSymName.empty() && DisSymName == SymName)
6134 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006135 }
6136 }
David Blaikie33dd45d02015-03-23 18:39:02 +00006137 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00006138 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
6139 return;
6140 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006141 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006142 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006143 SymbolizerInfo.O = MachOOF;
6144 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00006145 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006146 SymbolizerInfo.Sections = &Sections;
6147 SymbolizerInfo.class_name = nullptr;
6148 SymbolizerInfo.selector_name = nullptr;
6149 SymbolizerInfo.method = nullptr;
Kevin Enderby04bf6932014-10-28 23:39:46 +00006150 SymbolizerInfo.demangled_name = nullptr;
Kevin Enderby078be602014-10-23 19:53:12 +00006151 SymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006152 SymbolizerInfo.adrp_addr = 0;
6153 SymbolizerInfo.adrp_inst = 0;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006154 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006155 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006156 ThumbSymbolizerInfo.O = MachOOF;
6157 ThumbSymbolizerInfo.S = Sections[SectIdx];
6158 ThumbSymbolizerInfo.AddrMap = &AddrMap;
6159 ThumbSymbolizerInfo.Sections = &Sections;
6160 ThumbSymbolizerInfo.class_name = nullptr;
6161 ThumbSymbolizerInfo.selector_name = nullptr;
6162 ThumbSymbolizerInfo.method = nullptr;
6163 ThumbSymbolizerInfo.demangled_name = nullptr;
6164 ThumbSymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006165 ThumbSymbolizerInfo.adrp_addr = 0;
6166 ThumbSymbolizerInfo.adrp_inst = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006167
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006168 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006169 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006170 ErrorOr<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
6171 if (std::error_code EC = SymNameOrErr.getError())
6172 report_fatal_error(EC.message());
6173 StringRef SymName = *SymNameOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00006174
Rafael Espindola2fa80cc2015-06-26 12:18:49 +00006175 SymbolRef::Type ST = Symbols[SymIdx].getType();
Kuba Breckade833222015-11-12 09:40:29 +00006176 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
Owen Andersond9243c42011-10-17 21:37:35 +00006177 continue;
6178
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006179 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00006180 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Owen Andersond9243c42011-10-17 21:37:35 +00006181 if (!containsSym)
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006182 continue;
6183
Kevin Enderby6a221752015-03-17 17:10:57 +00006184 // If we are only disassembling one symbol see if this is that symbol.
6185 if (!DisSymName.empty() && DisSymName != SymName)
6186 continue;
6187
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006188 // Start at the address of the symbol relative to the section's address.
Rafael Espindoladea00162015-07-03 17:44:18 +00006189 uint64_t Start = Symbols[SymIdx].getValue();
Rafael Espindola80291272014-10-08 15:28:58 +00006190 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006191 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006192
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006193 // Stop disassembling either at the beginning of the next symbol or at
6194 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00006195 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00006196 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006197 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00006198 while (Symbols.size() > NextSymIdx) {
Rafael Espindola2fa80cc2015-06-26 12:18:49 +00006199 SymbolRef::Type NextSymType = Symbols[NextSymIdx].getType();
Owen Andersond9243c42011-10-17 21:37:35 +00006200 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00006201 containsNextSym =
6202 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Rafael Espindoladea00162015-07-03 17:44:18 +00006203 NextSym = Symbols[NextSymIdx].getValue();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006204 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006205 break;
6206 }
6207 ++NextSymIdx;
6208 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006209
Rafael Espindola80291272014-10-08 15:28:58 +00006210 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006211 uint64_t End = containsNextSym ? NextSym : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00006212 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006213
6214 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00006215
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006216 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
6217 bool isThumb =
6218 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
6219
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006220 outs() << SymName << ":\n";
6221 DILineInfo lastLine;
6222 for (uint64_t Index = Start; Index < End; Index += Size) {
6223 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00006224
Kevin Enderbybf246f52014-09-24 23:08:22 +00006225 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006226 if (!NoLeadingAddr) {
6227 if (FullLeadingAddr) {
6228 if (MachOOF->is64Bit())
6229 outs() << format("%016" PRIx64, PC);
6230 else
6231 outs() << format("%08" PRIx64, PC);
6232 } else {
6233 outs() << format("%8" PRIx64 ":", PC);
6234 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006235 }
6236 if (!NoShowRawInsn)
6237 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00006238
6239 // Check the data in code table here to see if this is data not an
6240 // instruction to be disassembled.
6241 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006242 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006243 dice_table_iterator DTI =
6244 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
6245 compareDiceTableEntries);
6246 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006247 uint16_t Length;
6248 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00006249 uint16_t Kind;
6250 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00006251 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00006252 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
6253 (PC == (DTI->first + Length - 1)) && (Length & 1))
6254 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00006255 continue;
6256 }
6257
Kevin Enderbybf246f52014-09-24 23:08:22 +00006258 SmallVector<char, 64> AnnotationsBytes;
6259 raw_svector_ostream Annotations(AnnotationsBytes);
6260
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006261 bool gotInst;
6262 if (isThumb)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006263 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006264 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006265 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006266 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00006267 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006268 if (gotInst) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006269 if (!NoShowRawInsn) {
Craig Topper0013be12015-09-21 05:32:41 +00006270 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006271 }
6272 formatted_raw_ostream FormattedOS(outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006273 StringRef AnnotationsStr = Annotations.str();
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006274 if (isThumb)
Akira Hatanakab46d0232015-03-27 20:36:02 +00006275 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006276 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00006277 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006278 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00006279
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006280 // Print debug info.
6281 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006282 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006283 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00006284 if (dli != lastLine && dli.Line != 0)
6285 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
6286 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006287 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006288 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006289 outs() << "\n";
6290 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006291 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006292 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006293 outs() << format("\t.byte 0x%02x #bad opcode\n",
6294 *(Bytes.data() + Index) & 0xff);
6295 Size = 1; // skip exactly one illegible byte and move on.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006296 } else if (Arch == Triple::aarch64) {
6297 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6298 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
6299 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
6300 (*(Bytes.data() + Index + 3) & 0xff) << 24;
6301 outs() << format("\t.long\t0x%08x\n", opcode);
6302 Size = 4;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006303 } else {
6304 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6305 if (Size == 0)
6306 Size = 1; // skip illegible bytes
6307 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006308 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006309 }
6310 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006311 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00006312 // Reading the symbol table didn't work, disassemble the whole section.
6313 uint64_t SectAddress = Sections[SectIdx].getAddress();
6314 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00006315 uint64_t InstSize;
6316 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00006317 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00006318
Kevin Enderbybf246f52014-09-24 23:08:22 +00006319 uint64_t PC = SectAddress + Index;
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006320 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
6321 DebugOut, nulls())) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006322 if (!NoLeadingAddr) {
6323 if (FullLeadingAddr) {
6324 if (MachOOF->is64Bit())
6325 outs() << format("%016" PRIx64, PC);
6326 else
6327 outs() << format("%08" PRIx64, PC);
6328 } else {
6329 outs() << format("%8" PRIx64 ":", PC);
6330 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006331 }
6332 if (!NoShowRawInsn) {
6333 outs() << "\t";
Craig Topper0013be12015-09-21 05:32:41 +00006334 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006335 }
Akira Hatanaka1d079942015-03-28 20:44:05 +00006336 IP->printInst(&Inst, outs(), "", *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00006337 outs() << "\n";
6338 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006339 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006340 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006341 outs() << format("\t.byte 0x%02x #bad opcode\n",
6342 *(Bytes.data() + Index) & 0xff);
6343 InstSize = 1; // skip exactly one illegible byte and move on.
6344 } else {
6345 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6346 if (InstSize == 0)
6347 InstSize = 1; // skip illegible bytes
6348 }
Bill Wendling4e68e062012-07-19 00:17:40 +00006349 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00006350 }
6351 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006352 // The TripleName's need to be reset if we are called again for a different
6353 // archtecture.
6354 TripleName = "";
6355 ThumbTripleName = "";
6356
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006357 if (SymbolizerInfo.method != nullptr)
6358 free(SymbolizerInfo.method);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006359 if (SymbolizerInfo.demangled_name != nullptr)
6360 free(SymbolizerInfo.demangled_name);
Kevin Enderby078be602014-10-23 19:53:12 +00006361 if (SymbolizerInfo.bindtable != nullptr)
6362 delete SymbolizerInfo.bindtable;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006363 if (ThumbSymbolizerInfo.method != nullptr)
6364 free(ThumbSymbolizerInfo.method);
6365 if (ThumbSymbolizerInfo.demangled_name != nullptr)
6366 free(ThumbSymbolizerInfo.demangled_name);
6367 if (ThumbSymbolizerInfo.bindtable != nullptr)
6368 delete ThumbSymbolizerInfo.bindtable;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006369 }
6370}
Tim Northover4bd286a2014-08-01 13:07:19 +00006371
Tim Northover39c70bb2014-08-12 11:52:59 +00006372//===----------------------------------------------------------------------===//
6373// __compact_unwind section dumping
6374//===----------------------------------------------------------------------===//
6375
Tim Northover4bd286a2014-08-01 13:07:19 +00006376namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00006377
6378template <typename T> static uint64_t readNext(const char *&Buf) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006379 using llvm::support::little;
6380 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00006381
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006382 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
6383 Buf += sizeof(T);
6384 return Val;
6385}
Tim Northover39c70bb2014-08-12 11:52:59 +00006386
Tim Northover4bd286a2014-08-01 13:07:19 +00006387struct CompactUnwindEntry {
6388 uint32_t OffsetInSection;
6389
6390 uint64_t FunctionAddr;
6391 uint32_t Length;
6392 uint32_t CompactEncoding;
6393 uint64_t PersonalityAddr;
6394 uint64_t LSDAAddr;
6395
6396 RelocationRef FunctionReloc;
6397 RelocationRef PersonalityReloc;
6398 RelocationRef LSDAReloc;
6399
6400 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006401 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006402 if (Is64)
6403 read<uint64_t>(Contents.data() + Offset);
6404 else
6405 read<uint32_t>(Contents.data() + Offset);
6406 }
6407
6408private:
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006409 template <typename UIntPtr> void read(const char *Buf) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006410 FunctionAddr = readNext<UIntPtr>(Buf);
6411 Length = readNext<uint32_t>(Buf);
6412 CompactEncoding = readNext<uint32_t>(Buf);
6413 PersonalityAddr = readNext<UIntPtr>(Buf);
6414 LSDAAddr = readNext<UIntPtr>(Buf);
6415 }
6416};
6417}
6418
6419/// Given a relocation from __compact_unwind, consisting of the RelocationRef
6420/// and data being relocated, determine the best base Name and Addend to use for
6421/// display purposes.
6422///
6423/// 1. An Extern relocation will directly reference a symbol (and the data is
6424/// then already an addend), so use that.
6425/// 2. Otherwise the data is an offset in the object file's layout; try to find
6426// a symbol before it in the same section, and use the offset from there.
6427/// 3. Finally, if all that fails, fall back to an offset from the start of the
6428/// referenced section.
6429static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
6430 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006431 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00006432 StringRef &Name, uint64_t &Addend) {
6433 if (Reloc.getSymbol() != Obj->symbol_end()) {
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006434 ErrorOr<StringRef> NameOrErr = Reloc.getSymbol()->getName();
6435 if (std::error_code EC = NameOrErr.getError())
6436 report_fatal_error(EC.message());
6437 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00006438 Addend = Addr;
6439 return;
6440 }
6441
6442 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
Keno Fischerc780e8e2015-05-21 21:24:32 +00006443 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
Tim Northover4bd286a2014-08-01 13:07:19 +00006444
Rafael Espindola80291272014-10-08 15:28:58 +00006445 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00006446
6447 auto Sym = Symbols.upper_bound(Addr);
6448 if (Sym == Symbols.begin()) {
6449 // The first symbol in the object is after this reference, the best we can
6450 // do is section-relative notation.
6451 RelocSection.getName(Name);
6452 Addend = Addr - SectionAddr;
6453 return;
6454 }
6455
6456 // Go back one so that SymbolAddress <= Addr.
6457 --Sym;
6458
Rafael Espindola8bab8892015-08-07 23:27:14 +00006459 section_iterator SymSection = *Sym->second.getSection();
Tim Northover4bd286a2014-08-01 13:07:19 +00006460 if (RelocSection == *SymSection) {
6461 // There's a valid symbol in the same section before this reference.
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006462 ErrorOr<StringRef> NameOrErr = Sym->second.getName();
6463 if (std::error_code EC = NameOrErr.getError())
6464 report_fatal_error(EC.message());
6465 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00006466 Addend = Addr - Sym->first;
6467 return;
6468 }
6469
6470 // There is a symbol before this reference, but it's in a different
6471 // section. Probably not helpful to mention it, so use the section name.
6472 RelocSection.getName(Name);
6473 Addend = Addr - SectionAddr;
6474}
6475
6476static void printUnwindRelocDest(const MachOObjectFile *Obj,
6477 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006478 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006479 StringRef Name;
6480 uint64_t Addend;
6481
Rafael Espindola854038e2015-06-26 14:51:16 +00006482 if (!Reloc.getObject())
Tim Northover0b0add52014-09-09 10:45:06 +00006483 return;
6484
Tim Northover4bd286a2014-08-01 13:07:19 +00006485 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
6486
6487 outs() << Name;
6488 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00006489 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00006490}
6491
6492static void
6493printMachOCompactUnwindSection(const MachOObjectFile *Obj,
6494 std::map<uint64_t, SymbolRef> &Symbols,
6495 const SectionRef &CompactUnwind) {
6496
6497 assert(Obj->isLittleEndian() &&
6498 "There should not be a big-endian .o with __compact_unwind");
6499
6500 bool Is64 = Obj->is64Bit();
6501 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
6502 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
6503
6504 StringRef Contents;
6505 CompactUnwind.getContents(Contents);
6506
6507 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
6508
6509 // First populate the initial raw offsets, encodings and so on from the entry.
6510 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
6511 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
6512 CompactUnwinds.push_back(Entry);
6513 }
6514
6515 // Next we need to look at the relocations to find out what objects are
6516 // actually being referred to.
6517 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00006518 uint64_t RelocAddress = Reloc.getOffset();
Tim Northover4bd286a2014-08-01 13:07:19 +00006519
6520 uint32_t EntryIdx = RelocAddress / EntrySize;
6521 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
6522 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
6523
6524 if (OffsetInEntry == 0)
6525 Entry.FunctionReloc = Reloc;
6526 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
6527 Entry.PersonalityReloc = Reloc;
6528 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
6529 Entry.LSDAReloc = Reloc;
6530 else
6531 llvm_unreachable("Unexpected relocation in __compact_unwind section");
6532 }
6533
6534 // Finally, we're ready to print the data we've gathered.
6535 outs() << "Contents of __compact_unwind section:\n";
6536 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00006537 outs() << " Entry at offset "
6538 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00006539
6540 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006541 outs() << " start: " << format("0x%" PRIx64,
6542 Entry.FunctionAddr) << ' ';
6543 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00006544 outs() << '\n';
6545
6546 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006547 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
6548 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00006549 // 3. The 32-bit compact encoding.
6550 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00006551 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00006552
6553 // 4. The personality function, if present.
Rafael Espindola854038e2015-06-26 14:51:16 +00006554 if (Entry.PersonalityReloc.getObject()) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006555 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00006556 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00006557 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
6558 Entry.PersonalityAddr);
6559 outs() << '\n';
6560 }
6561
6562 // 5. This entry's language-specific data area.
Rafael Espindola854038e2015-06-26 14:51:16 +00006563 if (Entry.LSDAReloc.getObject()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006564 outs() << " LSDA: " << format("0x%" PRIx64,
6565 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00006566 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
6567 outs() << '\n';
6568 }
6569 }
6570}
6571
Tim Northover39c70bb2014-08-12 11:52:59 +00006572//===----------------------------------------------------------------------===//
6573// __unwind_info section dumping
6574//===----------------------------------------------------------------------===//
6575
6576static void printRegularSecondLevelUnwindPage(const char *PageStart) {
6577 const char *Pos = PageStart;
6578 uint32_t Kind = readNext<uint32_t>(Pos);
6579 (void)Kind;
6580 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
6581
6582 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6583 uint16_t NumEntries = readNext<uint16_t>(Pos);
6584
6585 Pos = PageStart + EntriesStart;
6586 for (unsigned i = 0; i < NumEntries; ++i) {
6587 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6588 uint32_t Encoding = readNext<uint32_t>(Pos);
6589
6590 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006591 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6592 << ", "
6593 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006594 }
6595}
6596
6597static void printCompressedSecondLevelUnwindPage(
6598 const char *PageStart, uint32_t FunctionBase,
6599 const SmallVectorImpl<uint32_t> &CommonEncodings) {
6600 const char *Pos = PageStart;
6601 uint32_t Kind = readNext<uint32_t>(Pos);
6602 (void)Kind;
6603 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
6604
6605 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6606 uint16_t NumEntries = readNext<uint16_t>(Pos);
6607
6608 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
6609 readNext<uint16_t>(Pos);
Aaron Ballman80930af2014-08-14 13:53:19 +00006610 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
6611 PageStart + EncodingsStart);
Tim Northover39c70bb2014-08-12 11:52:59 +00006612
6613 Pos = PageStart + EntriesStart;
6614 for (unsigned i = 0; i < NumEntries; ++i) {
6615 uint32_t Entry = readNext<uint32_t>(Pos);
6616 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
6617 uint32_t EncodingIdx = Entry >> 24;
6618
6619 uint32_t Encoding;
6620 if (EncodingIdx < CommonEncodings.size())
6621 Encoding = CommonEncodings[EncodingIdx];
6622 else
6623 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
6624
6625 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006626 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6627 << ", "
6628 << "encoding[" << EncodingIdx
6629 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006630 }
6631}
6632
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006633static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
6634 std::map<uint64_t, SymbolRef> &Symbols,
6635 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00006636
6637 assert(Obj->isLittleEndian() &&
6638 "There should not be a big-endian .o with __unwind_info");
6639
6640 outs() << "Contents of __unwind_info section:\n";
6641
6642 StringRef Contents;
6643 UnwindInfo.getContents(Contents);
6644 const char *Pos = Contents.data();
6645
6646 //===----------------------------------
6647 // Section header
6648 //===----------------------------------
6649
6650 uint32_t Version = readNext<uint32_t>(Pos);
6651 outs() << " Version: "
6652 << format("0x%" PRIx32, Version) << '\n';
6653 assert(Version == 1 && "only understand version 1");
6654
6655 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
6656 outs() << " Common encodings array section offset: "
6657 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
6658 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
6659 outs() << " Number of common encodings in array: "
6660 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
6661
6662 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
6663 outs() << " Personality function array section offset: "
6664 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
6665 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
6666 outs() << " Number of personality functions in array: "
6667 << format("0x%" PRIx32, NumPersonalities) << '\n';
6668
6669 uint32_t IndicesStart = readNext<uint32_t>(Pos);
6670 outs() << " Index array section offset: "
6671 << format("0x%" PRIx32, IndicesStart) << '\n';
6672 uint32_t NumIndices = readNext<uint32_t>(Pos);
6673 outs() << " Number of indices in array: "
6674 << format("0x%" PRIx32, NumIndices) << '\n';
6675
6676 //===----------------------------------
6677 // A shared list of common encodings
6678 //===----------------------------------
6679
6680 // These occupy indices in the range [0, N] whenever an encoding is referenced
6681 // from a compressed 2nd level index table. In practice the linker only
6682 // creates ~128 of these, so that indices are available to embed encodings in
6683 // the 2nd level index.
6684
6685 SmallVector<uint32_t, 64> CommonEncodings;
6686 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
6687 Pos = Contents.data() + CommonEncodingsStart;
6688 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
6689 uint32_t Encoding = readNext<uint32_t>(Pos);
6690 CommonEncodings.push_back(Encoding);
6691
6692 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
6693 << '\n';
6694 }
6695
Tim Northover39c70bb2014-08-12 11:52:59 +00006696 //===----------------------------------
6697 // Personality functions used in this executable
6698 //===----------------------------------
6699
6700 // There should be only a handful of these (one per source language,
6701 // roughly). Particularly since they only get 2 bits in the compact encoding.
6702
6703 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
6704 Pos = Contents.data() + PersonalitiesStart;
6705 for (unsigned i = 0; i < NumPersonalities; ++i) {
6706 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
6707 outs() << " personality[" << i + 1
6708 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
6709 }
6710
6711 //===----------------------------------
6712 // The level 1 index entries
6713 //===----------------------------------
6714
6715 // These specify an approximate place to start searching for the more detailed
6716 // information, sorted by PC.
6717
6718 struct IndexEntry {
6719 uint32_t FunctionOffset;
6720 uint32_t SecondLevelPageStart;
6721 uint32_t LSDAStart;
6722 };
6723
6724 SmallVector<IndexEntry, 4> IndexEntries;
6725
6726 outs() << " Top level indices: (count = " << NumIndices << ")\n";
6727 Pos = Contents.data() + IndicesStart;
6728 for (unsigned i = 0; i < NumIndices; ++i) {
6729 IndexEntry Entry;
6730
6731 Entry.FunctionOffset = readNext<uint32_t>(Pos);
6732 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
6733 Entry.LSDAStart = readNext<uint32_t>(Pos);
6734 IndexEntries.push_back(Entry);
6735
6736 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006737 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
6738 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00006739 << "2nd level page offset="
6740 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006741 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006742 }
6743
Tim Northover39c70bb2014-08-12 11:52:59 +00006744 //===----------------------------------
6745 // Next come the LSDA tables
6746 //===----------------------------------
6747
6748 // The LSDA layout is rather implicit: it's a contiguous array of entries from
6749 // the first top-level index's LSDAOffset to the last (sentinel).
6750
6751 outs() << " LSDA descriptors:\n";
6752 Pos = Contents.data() + IndexEntries[0].LSDAStart;
6753 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
6754 (2 * sizeof(uint32_t));
6755 for (int i = 0; i < NumLSDAs; ++i) {
6756 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6757 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
6758 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006759 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6760 << ", "
6761 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006762 }
6763
6764 //===----------------------------------
6765 // Finally, the 2nd level indices
6766 //===----------------------------------
6767
6768 // Generally these are 4K in size, and have 2 possible forms:
6769 // + Regular stores up to 511 entries with disparate encodings
6770 // + Compressed stores up to 1021 entries if few enough compact encoding
6771 // values are used.
6772 outs() << " Second level indices:\n";
6773 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
6774 // The final sentinel top-level index has no associated 2nd level page
6775 if (IndexEntries[i].SecondLevelPageStart == 0)
6776 break;
6777
6778 outs() << " Second level index[" << i << "]: "
6779 << "offset in section="
6780 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
6781 << ", "
6782 << "base function offset="
6783 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
6784
6785 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
Aaron Ballman80930af2014-08-14 13:53:19 +00006786 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00006787 if (Kind == 2)
6788 printRegularSecondLevelUnwindPage(Pos);
6789 else if (Kind == 3)
6790 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
6791 CommonEncodings);
6792 else
6793 llvm_unreachable("Do not know how to print this kind of 2nd level page");
Tim Northover39c70bb2014-08-12 11:52:59 +00006794 }
6795}
6796
Tim Northover4bd286a2014-08-01 13:07:19 +00006797void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
6798 std::map<uint64_t, SymbolRef> Symbols;
6799 for (const SymbolRef &SymRef : Obj->symbols()) {
6800 // Discard any undefined or absolute symbols. They're not going to take part
6801 // in the convenience lookup for unwind info and just take up resources.
Rafael Espindola8bab8892015-08-07 23:27:14 +00006802 section_iterator Section = *SymRef.getSection();
Tim Northover4bd286a2014-08-01 13:07:19 +00006803 if (Section == Obj->section_end())
6804 continue;
6805
Rafael Espindoladea00162015-07-03 17:44:18 +00006806 uint64_t Addr = SymRef.getValue();
Tim Northover4bd286a2014-08-01 13:07:19 +00006807 Symbols.insert(std::make_pair(Addr, SymRef));
6808 }
6809
6810 for (const SectionRef &Section : Obj->sections()) {
6811 StringRef SectName;
6812 Section.getName(SectName);
6813 if (SectName == "__compact_unwind")
6814 printMachOCompactUnwindSection(Obj, Symbols, Section);
6815 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00006816 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00006817 else if (SectName == "__eh_frame")
6818 outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00006819 }
6820}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00006821
6822static void PrintMachHeader(uint32_t magic, uint32_t cputype,
6823 uint32_t cpusubtype, uint32_t filetype,
6824 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
6825 bool verbose) {
6826 outs() << "Mach header\n";
6827 outs() << " magic cputype cpusubtype caps filetype ncmds "
6828 "sizeofcmds flags\n";
6829 if (verbose) {
6830 if (magic == MachO::MH_MAGIC)
6831 outs() << " MH_MAGIC";
6832 else if (magic == MachO::MH_MAGIC_64)
6833 outs() << "MH_MAGIC_64";
6834 else
6835 outs() << format(" 0x%08" PRIx32, magic);
6836 switch (cputype) {
6837 case MachO::CPU_TYPE_I386:
6838 outs() << " I386";
6839 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6840 case MachO::CPU_SUBTYPE_I386_ALL:
6841 outs() << " ALL";
6842 break;
6843 default:
6844 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6845 break;
6846 }
6847 break;
6848 case MachO::CPU_TYPE_X86_64:
6849 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00006850 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6851 case MachO::CPU_SUBTYPE_X86_64_ALL:
6852 outs() << " ALL";
6853 break;
6854 case MachO::CPU_SUBTYPE_X86_64_H:
6855 outs() << " Haswell";
6856 break;
6857 default:
6858 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6859 break;
6860 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00006861 break;
6862 case MachO::CPU_TYPE_ARM:
6863 outs() << " ARM";
6864 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6865 case MachO::CPU_SUBTYPE_ARM_ALL:
6866 outs() << " ALL";
6867 break;
6868 case MachO::CPU_SUBTYPE_ARM_V4T:
6869 outs() << " V4T";
6870 break;
6871 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
6872 outs() << " V5TEJ";
6873 break;
6874 case MachO::CPU_SUBTYPE_ARM_XSCALE:
6875 outs() << " XSCALE";
6876 break;
6877 case MachO::CPU_SUBTYPE_ARM_V6:
6878 outs() << " V6";
6879 break;
6880 case MachO::CPU_SUBTYPE_ARM_V6M:
6881 outs() << " V6M";
6882 break;
6883 case MachO::CPU_SUBTYPE_ARM_V7:
6884 outs() << " V7";
6885 break;
6886 case MachO::CPU_SUBTYPE_ARM_V7EM:
6887 outs() << " V7EM";
6888 break;
6889 case MachO::CPU_SUBTYPE_ARM_V7K:
6890 outs() << " V7K";
6891 break;
6892 case MachO::CPU_SUBTYPE_ARM_V7M:
6893 outs() << " V7M";
6894 break;
6895 case MachO::CPU_SUBTYPE_ARM_V7S:
6896 outs() << " V7S";
6897 break;
6898 default:
6899 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6900 break;
6901 }
6902 break;
6903 case MachO::CPU_TYPE_ARM64:
6904 outs() << " ARM64";
6905 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6906 case MachO::CPU_SUBTYPE_ARM64_ALL:
6907 outs() << " ALL";
6908 break;
6909 default:
6910 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6911 break;
6912 }
6913 break;
6914 case MachO::CPU_TYPE_POWERPC:
6915 outs() << " PPC";
6916 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6917 case MachO::CPU_SUBTYPE_POWERPC_ALL:
6918 outs() << " ALL";
6919 break;
6920 default:
6921 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6922 break;
6923 }
6924 break;
6925 case MachO::CPU_TYPE_POWERPC64:
6926 outs() << " PPC64";
6927 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6928 case MachO::CPU_SUBTYPE_POWERPC_ALL:
6929 outs() << " ALL";
6930 break;
6931 default:
6932 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6933 break;
6934 }
6935 break;
6936 }
6937 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00006938 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00006939 } else {
6940 outs() << format(" 0x%02" PRIx32,
6941 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
6942 }
6943 switch (filetype) {
6944 case MachO::MH_OBJECT:
6945 outs() << " OBJECT";
6946 break;
6947 case MachO::MH_EXECUTE:
6948 outs() << " EXECUTE";
6949 break;
6950 case MachO::MH_FVMLIB:
6951 outs() << " FVMLIB";
6952 break;
6953 case MachO::MH_CORE:
6954 outs() << " CORE";
6955 break;
6956 case MachO::MH_PRELOAD:
6957 outs() << " PRELOAD";
6958 break;
6959 case MachO::MH_DYLIB:
6960 outs() << " DYLIB";
6961 break;
6962 case MachO::MH_DYLIB_STUB:
6963 outs() << " DYLIB_STUB";
6964 break;
6965 case MachO::MH_DYLINKER:
6966 outs() << " DYLINKER";
6967 break;
6968 case MachO::MH_BUNDLE:
6969 outs() << " BUNDLE";
6970 break;
6971 case MachO::MH_DSYM:
6972 outs() << " DSYM";
6973 break;
6974 case MachO::MH_KEXT_BUNDLE:
6975 outs() << " KEXTBUNDLE";
6976 break;
6977 default:
6978 outs() << format(" %10u", filetype);
6979 break;
6980 }
6981 outs() << format(" %5u", ncmds);
6982 outs() << format(" %10u", sizeofcmds);
6983 uint32_t f = flags;
6984 if (f & MachO::MH_NOUNDEFS) {
6985 outs() << " NOUNDEFS";
6986 f &= ~MachO::MH_NOUNDEFS;
6987 }
6988 if (f & MachO::MH_INCRLINK) {
6989 outs() << " INCRLINK";
6990 f &= ~MachO::MH_INCRLINK;
6991 }
6992 if (f & MachO::MH_DYLDLINK) {
6993 outs() << " DYLDLINK";
6994 f &= ~MachO::MH_DYLDLINK;
6995 }
6996 if (f & MachO::MH_BINDATLOAD) {
6997 outs() << " BINDATLOAD";
6998 f &= ~MachO::MH_BINDATLOAD;
6999 }
7000 if (f & MachO::MH_PREBOUND) {
7001 outs() << " PREBOUND";
7002 f &= ~MachO::MH_PREBOUND;
7003 }
7004 if (f & MachO::MH_SPLIT_SEGS) {
7005 outs() << " SPLIT_SEGS";
7006 f &= ~MachO::MH_SPLIT_SEGS;
7007 }
7008 if (f & MachO::MH_LAZY_INIT) {
7009 outs() << " LAZY_INIT";
7010 f &= ~MachO::MH_LAZY_INIT;
7011 }
7012 if (f & MachO::MH_TWOLEVEL) {
7013 outs() << " TWOLEVEL";
7014 f &= ~MachO::MH_TWOLEVEL;
7015 }
7016 if (f & MachO::MH_FORCE_FLAT) {
7017 outs() << " FORCE_FLAT";
7018 f &= ~MachO::MH_FORCE_FLAT;
7019 }
7020 if (f & MachO::MH_NOMULTIDEFS) {
7021 outs() << " NOMULTIDEFS";
7022 f &= ~MachO::MH_NOMULTIDEFS;
7023 }
7024 if (f & MachO::MH_NOFIXPREBINDING) {
7025 outs() << " NOFIXPREBINDING";
7026 f &= ~MachO::MH_NOFIXPREBINDING;
7027 }
7028 if (f & MachO::MH_PREBINDABLE) {
7029 outs() << " PREBINDABLE";
7030 f &= ~MachO::MH_PREBINDABLE;
7031 }
7032 if (f & MachO::MH_ALLMODSBOUND) {
7033 outs() << " ALLMODSBOUND";
7034 f &= ~MachO::MH_ALLMODSBOUND;
7035 }
7036 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
7037 outs() << " SUBSECTIONS_VIA_SYMBOLS";
7038 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
7039 }
7040 if (f & MachO::MH_CANONICAL) {
7041 outs() << " CANONICAL";
7042 f &= ~MachO::MH_CANONICAL;
7043 }
7044 if (f & MachO::MH_WEAK_DEFINES) {
7045 outs() << " WEAK_DEFINES";
7046 f &= ~MachO::MH_WEAK_DEFINES;
7047 }
7048 if (f & MachO::MH_BINDS_TO_WEAK) {
7049 outs() << " BINDS_TO_WEAK";
7050 f &= ~MachO::MH_BINDS_TO_WEAK;
7051 }
7052 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
7053 outs() << " ALLOW_STACK_EXECUTION";
7054 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
7055 }
7056 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
7057 outs() << " DEAD_STRIPPABLE_DYLIB";
7058 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
7059 }
7060 if (f & MachO::MH_PIE) {
7061 outs() << " PIE";
7062 f &= ~MachO::MH_PIE;
7063 }
7064 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
7065 outs() << " NO_REEXPORTED_DYLIBS";
7066 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
7067 }
7068 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
7069 outs() << " MH_HAS_TLV_DESCRIPTORS";
7070 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
7071 }
7072 if (f & MachO::MH_NO_HEAP_EXECUTION) {
7073 outs() << " MH_NO_HEAP_EXECUTION";
7074 f &= ~MachO::MH_NO_HEAP_EXECUTION;
7075 }
7076 if (f & MachO::MH_APP_EXTENSION_SAFE) {
7077 outs() << " APP_EXTENSION_SAFE";
7078 f &= ~MachO::MH_APP_EXTENSION_SAFE;
7079 }
7080 if (f != 0 || flags == 0)
7081 outs() << format(" 0x%08" PRIx32, f);
7082 } else {
7083 outs() << format(" 0x%08" PRIx32, magic);
7084 outs() << format(" %7d", cputype);
7085 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7086 outs() << format(" 0x%02" PRIx32,
7087 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7088 outs() << format(" %10u", filetype);
7089 outs() << format(" %5u", ncmds);
7090 outs() << format(" %10u", sizeofcmds);
7091 outs() << format(" 0x%08" PRIx32, flags);
7092 }
7093 outs() << "\n";
7094}
7095
Kevin Enderby956366c2014-08-29 22:30:52 +00007096static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
7097 StringRef SegName, uint64_t vmaddr,
7098 uint64_t vmsize, uint64_t fileoff,
7099 uint64_t filesize, uint32_t maxprot,
7100 uint32_t initprot, uint32_t nsects,
7101 uint32_t flags, uint32_t object_size,
7102 bool verbose) {
7103 uint64_t expected_cmdsize;
7104 if (cmd == MachO::LC_SEGMENT) {
7105 outs() << " cmd LC_SEGMENT\n";
7106 expected_cmdsize = nsects;
7107 expected_cmdsize *= sizeof(struct MachO::section);
7108 expected_cmdsize += sizeof(struct MachO::segment_command);
7109 } else {
7110 outs() << " cmd LC_SEGMENT_64\n";
7111 expected_cmdsize = nsects;
7112 expected_cmdsize *= sizeof(struct MachO::section_64);
7113 expected_cmdsize += sizeof(struct MachO::segment_command_64);
7114 }
7115 outs() << " cmdsize " << cmdsize;
7116 if (cmdsize != expected_cmdsize)
7117 outs() << " Inconsistent size\n";
7118 else
7119 outs() << "\n";
7120 outs() << " segname " << SegName << "\n";
7121 if (cmd == MachO::LC_SEGMENT_64) {
7122 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
7123 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
7124 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00007125 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
7126 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00007127 }
7128 outs() << " fileoff " << fileoff;
7129 if (fileoff > object_size)
7130 outs() << " (past end of file)\n";
7131 else
7132 outs() << "\n";
7133 outs() << " filesize " << filesize;
7134 if (fileoff + filesize > object_size)
7135 outs() << " (past end of file)\n";
7136 else
7137 outs() << "\n";
7138 if (verbose) {
7139 if ((maxprot &
7140 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7141 MachO::VM_PROT_EXECUTE)) != 0)
7142 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
7143 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00007144 outs() << " maxprot ";
7145 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
7146 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7147 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007148 }
7149 if ((initprot &
7150 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7151 MachO::VM_PROT_EXECUTE)) != 0)
7152 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
7153 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00007154 outs() << " initprot ";
7155 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
7156 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7157 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007158 }
7159 } else {
7160 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
7161 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
7162 }
7163 outs() << " nsects " << nsects << "\n";
7164 if (verbose) {
7165 outs() << " flags";
7166 if (flags == 0)
7167 outs() << " (none)\n";
7168 else {
7169 if (flags & MachO::SG_HIGHVM) {
7170 outs() << " HIGHVM";
7171 flags &= ~MachO::SG_HIGHVM;
7172 }
7173 if (flags & MachO::SG_FVMLIB) {
7174 outs() << " FVMLIB";
7175 flags &= ~MachO::SG_FVMLIB;
7176 }
7177 if (flags & MachO::SG_NORELOC) {
7178 outs() << " NORELOC";
7179 flags &= ~MachO::SG_NORELOC;
7180 }
7181 if (flags & MachO::SG_PROTECTED_VERSION_1) {
7182 outs() << " PROTECTED_VERSION_1";
7183 flags &= ~MachO::SG_PROTECTED_VERSION_1;
7184 }
7185 if (flags)
7186 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
7187 else
7188 outs() << "\n";
7189 }
7190 } else {
7191 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
7192 }
7193}
7194
7195static void PrintSection(const char *sectname, const char *segname,
7196 uint64_t addr, uint64_t size, uint32_t offset,
7197 uint32_t align, uint32_t reloff, uint32_t nreloc,
7198 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
7199 uint32_t cmd, const char *sg_segname,
7200 uint32_t filetype, uint32_t object_size,
7201 bool verbose) {
7202 outs() << "Section\n";
7203 outs() << " sectname " << format("%.16s\n", sectname);
7204 outs() << " segname " << format("%.16s", segname);
7205 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
7206 outs() << " (does not match segment)\n";
7207 else
7208 outs() << "\n";
7209 if (cmd == MachO::LC_SEGMENT_64) {
7210 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
7211 outs() << " size " << format("0x%016" PRIx64, size);
7212 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00007213 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
7214 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00007215 }
7216 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
7217 outs() << " (past end of file)\n";
7218 else
7219 outs() << "\n";
7220 outs() << " offset " << offset;
7221 if (offset > object_size)
7222 outs() << " (past end of file)\n";
7223 else
7224 outs() << "\n";
7225 uint32_t align_shifted = 1 << align;
7226 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
7227 outs() << " reloff " << reloff;
7228 if (reloff > object_size)
7229 outs() << " (past end of file)\n";
7230 else
7231 outs() << "\n";
7232 outs() << " nreloc " << nreloc;
7233 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
7234 outs() << " (past end of file)\n";
7235 else
7236 outs() << "\n";
7237 uint32_t section_type = flags & MachO::SECTION_TYPE;
7238 if (verbose) {
7239 outs() << " type";
7240 if (section_type == MachO::S_REGULAR)
7241 outs() << " S_REGULAR\n";
7242 else if (section_type == MachO::S_ZEROFILL)
7243 outs() << " S_ZEROFILL\n";
7244 else if (section_type == MachO::S_CSTRING_LITERALS)
7245 outs() << " S_CSTRING_LITERALS\n";
7246 else if (section_type == MachO::S_4BYTE_LITERALS)
7247 outs() << " S_4BYTE_LITERALS\n";
7248 else if (section_type == MachO::S_8BYTE_LITERALS)
7249 outs() << " S_8BYTE_LITERALS\n";
7250 else if (section_type == MachO::S_16BYTE_LITERALS)
7251 outs() << " S_16BYTE_LITERALS\n";
7252 else if (section_type == MachO::S_LITERAL_POINTERS)
7253 outs() << " S_LITERAL_POINTERS\n";
7254 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
7255 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
7256 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
7257 outs() << " S_LAZY_SYMBOL_POINTERS\n";
7258 else if (section_type == MachO::S_SYMBOL_STUBS)
7259 outs() << " S_SYMBOL_STUBS\n";
7260 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
7261 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
7262 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
7263 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
7264 else if (section_type == MachO::S_COALESCED)
7265 outs() << " S_COALESCED\n";
7266 else if (section_type == MachO::S_INTERPOSING)
7267 outs() << " S_INTERPOSING\n";
7268 else if (section_type == MachO::S_DTRACE_DOF)
7269 outs() << " S_DTRACE_DOF\n";
7270 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
7271 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
7272 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
7273 outs() << " S_THREAD_LOCAL_REGULAR\n";
7274 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
7275 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
7276 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
7277 outs() << " S_THREAD_LOCAL_VARIABLES\n";
7278 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7279 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
7280 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
7281 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
7282 else
7283 outs() << format("0x%08" PRIx32, section_type) << "\n";
7284 outs() << "attributes";
7285 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
7286 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
7287 outs() << " PURE_INSTRUCTIONS";
7288 if (section_attributes & MachO::S_ATTR_NO_TOC)
7289 outs() << " NO_TOC";
7290 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
7291 outs() << " STRIP_STATIC_SYMS";
7292 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
7293 outs() << " NO_DEAD_STRIP";
7294 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
7295 outs() << " LIVE_SUPPORT";
7296 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
7297 outs() << " SELF_MODIFYING_CODE";
7298 if (section_attributes & MachO::S_ATTR_DEBUG)
7299 outs() << " DEBUG";
7300 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
7301 outs() << " SOME_INSTRUCTIONS";
7302 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
7303 outs() << " EXT_RELOC";
7304 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
7305 outs() << " LOC_RELOC";
7306 if (section_attributes == 0)
7307 outs() << " (none)";
7308 outs() << "\n";
7309 } else
7310 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
7311 outs() << " reserved1 " << reserved1;
7312 if (section_type == MachO::S_SYMBOL_STUBS ||
7313 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
7314 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
7315 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
7316 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7317 outs() << " (index into indirect symbol table)\n";
7318 else
7319 outs() << "\n";
7320 outs() << " reserved2 " << reserved2;
7321 if (section_type == MachO::S_SYMBOL_STUBS)
7322 outs() << " (size of stubs)\n";
7323 else
7324 outs() << "\n";
7325}
7326
David Majnemer73cc6ff2014-11-13 19:48:56 +00007327static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00007328 uint32_t object_size) {
7329 outs() << " cmd LC_SYMTAB\n";
7330 outs() << " cmdsize " << st.cmdsize;
7331 if (st.cmdsize != sizeof(struct MachO::symtab_command))
7332 outs() << " Incorrect size\n";
7333 else
7334 outs() << "\n";
7335 outs() << " symoff " << st.symoff;
7336 if (st.symoff > object_size)
7337 outs() << " (past end of file)\n";
7338 else
7339 outs() << "\n";
7340 outs() << " nsyms " << st.nsyms;
7341 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00007342 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007343 big_size = st.nsyms;
7344 big_size *= sizeof(struct MachO::nlist_64);
7345 big_size += st.symoff;
7346 if (big_size > object_size)
7347 outs() << " (past end of file)\n";
7348 else
7349 outs() << "\n";
7350 } else {
7351 big_size = st.nsyms;
7352 big_size *= sizeof(struct MachO::nlist);
7353 big_size += st.symoff;
7354 if (big_size > object_size)
7355 outs() << " (past end of file)\n";
7356 else
7357 outs() << "\n";
7358 }
7359 outs() << " stroff " << st.stroff;
7360 if (st.stroff > object_size)
7361 outs() << " (past end of file)\n";
7362 else
7363 outs() << "\n";
7364 outs() << " strsize " << st.strsize;
7365 big_size = st.stroff;
7366 big_size += st.strsize;
7367 if (big_size > object_size)
7368 outs() << " (past end of file)\n";
7369 else
7370 outs() << "\n";
7371}
7372
7373static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
7374 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00007375 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007376 outs() << " cmd LC_DYSYMTAB\n";
7377 outs() << " cmdsize " << dyst.cmdsize;
7378 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
7379 outs() << " Incorrect size\n";
7380 else
7381 outs() << "\n";
7382 outs() << " ilocalsym " << dyst.ilocalsym;
7383 if (dyst.ilocalsym > nsyms)
7384 outs() << " (greater than the number of symbols)\n";
7385 else
7386 outs() << "\n";
7387 outs() << " nlocalsym " << dyst.nlocalsym;
7388 uint64_t big_size;
7389 big_size = dyst.ilocalsym;
7390 big_size += dyst.nlocalsym;
7391 if (big_size > nsyms)
7392 outs() << " (past the end of the symbol table)\n";
7393 else
7394 outs() << "\n";
7395 outs() << " iextdefsym " << dyst.iextdefsym;
7396 if (dyst.iextdefsym > nsyms)
7397 outs() << " (greater than the number of symbols)\n";
7398 else
7399 outs() << "\n";
7400 outs() << " nextdefsym " << dyst.nextdefsym;
7401 big_size = dyst.iextdefsym;
7402 big_size += dyst.nextdefsym;
7403 if (big_size > nsyms)
7404 outs() << " (past the end of the symbol table)\n";
7405 else
7406 outs() << "\n";
7407 outs() << " iundefsym " << dyst.iundefsym;
7408 if (dyst.iundefsym > nsyms)
7409 outs() << " (greater than the number of symbols)\n";
7410 else
7411 outs() << "\n";
7412 outs() << " nundefsym " << dyst.nundefsym;
7413 big_size = dyst.iundefsym;
7414 big_size += dyst.nundefsym;
7415 if (big_size > nsyms)
7416 outs() << " (past the end of the symbol table)\n";
7417 else
7418 outs() << "\n";
7419 outs() << " tocoff " << dyst.tocoff;
7420 if (dyst.tocoff > object_size)
7421 outs() << " (past end of file)\n";
7422 else
7423 outs() << "\n";
7424 outs() << " ntoc " << dyst.ntoc;
7425 big_size = dyst.ntoc;
7426 big_size *= sizeof(struct MachO::dylib_table_of_contents);
7427 big_size += dyst.tocoff;
7428 if (big_size > object_size)
7429 outs() << " (past end of file)\n";
7430 else
7431 outs() << "\n";
7432 outs() << " modtaboff " << dyst.modtaboff;
7433 if (dyst.modtaboff > object_size)
7434 outs() << " (past end of file)\n";
7435 else
7436 outs() << "\n";
7437 outs() << " nmodtab " << dyst.nmodtab;
7438 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00007439 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007440 modtabend = dyst.nmodtab;
7441 modtabend *= sizeof(struct MachO::dylib_module_64);
7442 modtabend += dyst.modtaboff;
7443 } else {
7444 modtabend = dyst.nmodtab;
7445 modtabend *= sizeof(struct MachO::dylib_module);
7446 modtabend += dyst.modtaboff;
7447 }
7448 if (modtabend > object_size)
7449 outs() << " (past end of file)\n";
7450 else
7451 outs() << "\n";
7452 outs() << " extrefsymoff " << dyst.extrefsymoff;
7453 if (dyst.extrefsymoff > object_size)
7454 outs() << " (past end of file)\n";
7455 else
7456 outs() << "\n";
7457 outs() << " nextrefsyms " << dyst.nextrefsyms;
7458 big_size = dyst.nextrefsyms;
7459 big_size *= sizeof(struct MachO::dylib_reference);
7460 big_size += dyst.extrefsymoff;
7461 if (big_size > object_size)
7462 outs() << " (past end of file)\n";
7463 else
7464 outs() << "\n";
7465 outs() << " indirectsymoff " << dyst.indirectsymoff;
7466 if (dyst.indirectsymoff > object_size)
7467 outs() << " (past end of file)\n";
7468 else
7469 outs() << "\n";
7470 outs() << " nindirectsyms " << dyst.nindirectsyms;
7471 big_size = dyst.nindirectsyms;
7472 big_size *= sizeof(uint32_t);
7473 big_size += dyst.indirectsymoff;
7474 if (big_size > object_size)
7475 outs() << " (past end of file)\n";
7476 else
7477 outs() << "\n";
7478 outs() << " extreloff " << dyst.extreloff;
7479 if (dyst.extreloff > object_size)
7480 outs() << " (past end of file)\n";
7481 else
7482 outs() << "\n";
7483 outs() << " nextrel " << dyst.nextrel;
7484 big_size = dyst.nextrel;
7485 big_size *= sizeof(struct MachO::relocation_info);
7486 big_size += dyst.extreloff;
7487 if (big_size > object_size)
7488 outs() << " (past end of file)\n";
7489 else
7490 outs() << "\n";
7491 outs() << " locreloff " << dyst.locreloff;
7492 if (dyst.locreloff > object_size)
7493 outs() << " (past end of file)\n";
7494 else
7495 outs() << "\n";
7496 outs() << " nlocrel " << dyst.nlocrel;
7497 big_size = dyst.nlocrel;
7498 big_size *= sizeof(struct MachO::relocation_info);
7499 big_size += dyst.locreloff;
7500 if (big_size > object_size)
7501 outs() << " (past end of file)\n";
7502 else
7503 outs() << "\n";
7504}
7505
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007506static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
7507 uint32_t object_size) {
7508 if (dc.cmd == MachO::LC_DYLD_INFO)
7509 outs() << " cmd LC_DYLD_INFO\n";
7510 else
7511 outs() << " cmd LC_DYLD_INFO_ONLY\n";
7512 outs() << " cmdsize " << dc.cmdsize;
7513 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
7514 outs() << " Incorrect size\n";
7515 else
7516 outs() << "\n";
7517 outs() << " rebase_off " << dc.rebase_off;
7518 if (dc.rebase_off > object_size)
7519 outs() << " (past end of file)\n";
7520 else
7521 outs() << "\n";
7522 outs() << " rebase_size " << dc.rebase_size;
7523 uint64_t big_size;
7524 big_size = dc.rebase_off;
7525 big_size += dc.rebase_size;
7526 if (big_size > object_size)
7527 outs() << " (past end of file)\n";
7528 else
7529 outs() << "\n";
7530 outs() << " bind_off " << dc.bind_off;
7531 if (dc.bind_off > object_size)
7532 outs() << " (past end of file)\n";
7533 else
7534 outs() << "\n";
7535 outs() << " bind_size " << dc.bind_size;
7536 big_size = dc.bind_off;
7537 big_size += dc.bind_size;
7538 if (big_size > object_size)
7539 outs() << " (past end of file)\n";
7540 else
7541 outs() << "\n";
7542 outs() << " weak_bind_off " << dc.weak_bind_off;
7543 if (dc.weak_bind_off > object_size)
7544 outs() << " (past end of file)\n";
7545 else
7546 outs() << "\n";
7547 outs() << " weak_bind_size " << dc.weak_bind_size;
7548 big_size = dc.weak_bind_off;
7549 big_size += dc.weak_bind_size;
7550 if (big_size > object_size)
7551 outs() << " (past end of file)\n";
7552 else
7553 outs() << "\n";
7554 outs() << " lazy_bind_off " << dc.lazy_bind_off;
7555 if (dc.lazy_bind_off > object_size)
7556 outs() << " (past end of file)\n";
7557 else
7558 outs() << "\n";
7559 outs() << " lazy_bind_size " << dc.lazy_bind_size;
7560 big_size = dc.lazy_bind_off;
7561 big_size += dc.lazy_bind_size;
7562 if (big_size > object_size)
7563 outs() << " (past end of file)\n";
7564 else
7565 outs() << "\n";
7566 outs() << " export_off " << dc.export_off;
7567 if (dc.export_off > object_size)
7568 outs() << " (past end of file)\n";
7569 else
7570 outs() << "\n";
7571 outs() << " export_size " << dc.export_size;
7572 big_size = dc.export_off;
7573 big_size += dc.export_size;
7574 if (big_size > object_size)
7575 outs() << " (past end of file)\n";
7576 else
7577 outs() << "\n";
7578}
7579
7580static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
7581 const char *Ptr) {
7582 if (dyld.cmd == MachO::LC_ID_DYLINKER)
7583 outs() << " cmd LC_ID_DYLINKER\n";
7584 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
7585 outs() << " cmd LC_LOAD_DYLINKER\n";
7586 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
7587 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
7588 else
7589 outs() << " cmd ?(" << dyld.cmd << ")\n";
7590 outs() << " cmdsize " << dyld.cmdsize;
7591 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
7592 outs() << " Incorrect size\n";
7593 else
7594 outs() << "\n";
7595 if (dyld.name >= dyld.cmdsize)
7596 outs() << " name ?(bad offset " << dyld.name << ")\n";
7597 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007598 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007599 outs() << " name " << P << " (offset " << dyld.name << ")\n";
7600 }
7601}
7602
7603static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
7604 outs() << " cmd LC_UUID\n";
7605 outs() << " cmdsize " << uuid.cmdsize;
7606 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
7607 outs() << " Incorrect size\n";
7608 else
7609 outs() << "\n";
7610 outs() << " uuid ";
Davide Italianoc74277a2015-12-07 00:03:28 +00007611 for (int i = 0; i < 16; ++i) {
7612 outs() << format("%02" PRIX32, uuid.uuid[i]);
7613 if (i == 3 || i == 5 || i == 7 || i == 9)
7614 outs() << "-";
7615 }
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007616 outs() << "\n";
7617}
7618
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007619static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00007620 outs() << " cmd LC_RPATH\n";
7621 outs() << " cmdsize " << rpath.cmdsize;
7622 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
7623 outs() << " Incorrect size\n";
7624 else
7625 outs() << "\n";
7626 if (rpath.path >= rpath.cmdsize)
7627 outs() << " path ?(bad offset " << rpath.path << ")\n";
7628 else {
7629 const char *P = (const char *)(Ptr) + rpath.path;
7630 outs() << " path " << P << " (offset " << rpath.path << ")\n";
7631 }
7632}
7633
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007634static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
Tim Northoverbfbfb122015-11-02 21:26:58 +00007635 StringRef LoadCmdName;
7636 switch (vd.cmd) {
7637 case MachO::LC_VERSION_MIN_MACOSX:
7638 LoadCmdName = "LC_VERSION_MIN_MACOSX";
7639 break;
7640 case MachO::LC_VERSION_MIN_IPHONEOS:
7641 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
7642 break;
7643 case MachO::LC_VERSION_MIN_TVOS:
7644 LoadCmdName = "LC_VERSION_MIN_TVOS";
7645 break;
7646 case MachO::LC_VERSION_MIN_WATCHOS:
7647 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
7648 break;
7649 default:
7650 llvm_unreachable("Unknown version min load command");
7651 }
7652
7653 outs() << " cmd " << LoadCmdName << '\n';
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007654 outs() << " cmdsize " << vd.cmdsize;
7655 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
7656 outs() << " Incorrect size\n";
7657 else
7658 outs() << "\n";
Davide Italiano56baef32015-08-26 12:26:11 +00007659 outs() << " version "
7660 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
7661 << MachOObjectFile::getVersionMinMinor(vd, false);
7662 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
7663 if (Update != 0)
7664 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007665 outs() << "\n";
7666 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00007667 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007668 else {
Davide Italiano56baef32015-08-26 12:26:11 +00007669 outs() << " sdk "
7670 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
7671 << MachOObjectFile::getVersionMinMinor(vd, true);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007672 }
Davide Italiano56baef32015-08-26 12:26:11 +00007673 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
7674 if (Update != 0)
7675 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007676 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
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008311static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
8312 uint32_t cputype, bool verbose) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008313 StringRef Buf = Obj->getData();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008314 unsigned Index = 0;
8315 for (const auto &Command : Obj->load_commands()) {
8316 outs() << "Load command " << Index++ << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008317 if (Command.C.cmd == MachO::LC_SEGMENT) {
8318 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
8319 const char *sg_segname = SLC.segname;
8320 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
8321 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
8322 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
8323 verbose);
8324 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00008325 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00008326 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
8327 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
8328 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
8329 }
8330 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
8331 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
8332 const char *sg_segname = SLC_64.segname;
8333 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
8334 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
8335 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
8336 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
8337 for (unsigned j = 0; j < SLC_64.nsects; j++) {
8338 MachO::section_64 S_64 = Obj->getSection64(Command, j);
8339 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
8340 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
8341 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
8342 sg_segname, filetype, Buf.size(), verbose);
8343 }
8344 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
8345 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00008346 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00008347 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
8348 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
8349 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00008350 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
8351 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008352 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
8353 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
8354 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
8355 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
8356 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
8357 Command.C.cmd == MachO::LC_ID_DYLINKER ||
8358 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
8359 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
8360 PrintDyldLoadCommand(Dyld, Command.Ptr);
8361 } else if (Command.C.cmd == MachO::LC_UUID) {
8362 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
8363 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008364 } else if (Command.C.cmd == MachO::LC_RPATH) {
8365 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
8366 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00008367 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
Tim Northoverbfbfb122015-11-02 21:26:58 +00008368 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
8369 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
8370 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008371 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
8372 PrintVersionMinLoadCommand(Vd);
8373 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
8374 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
8375 PrintSourceVersionCommand(Sd);
8376 } else if (Command.C.cmd == MachO::LC_MAIN) {
8377 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
8378 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00008379 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008380 MachO::encryption_info_command Ei =
8381 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00008382 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00008383 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008384 MachO::encryption_info_command_64 Ei =
8385 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00008386 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008387 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008388 MachO::linker_option_command Lo =
8389 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008390 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00008391 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
8392 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
8393 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00008394 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
8395 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
8396 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008397 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
8398 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
8399 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00008400 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
8401 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
8402 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00008403 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
8404 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
8405 PrintRoutinesCommand(Rc);
8406 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
8407 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
8408 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00008409 } else if (Command.C.cmd == MachO::LC_THREAD ||
8410 Command.C.cmd == MachO::LC_UNIXTHREAD) {
8411 MachO::thread_command Tc = Obj->getThreadCommand(Command);
8412 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00008413 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
8414 Command.C.cmd == MachO::LC_ID_DYLIB ||
8415 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
8416 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
8417 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
8418 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008419 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
8420 PrintDylibCommand(Dl, Command.Ptr);
8421 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
8422 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
8423 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
8424 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
8425 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
8426 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
8427 MachO::linkedit_data_command Ld =
8428 Obj->getLinkeditDataLoadCommand(Command);
8429 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00008430 } else {
8431 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
8432 << ")\n";
8433 outs() << " cmdsize " << Command.C.cmdsize << "\n";
8434 // TODO: get and print the raw bytes of the load command.
8435 }
8436 // TODO: print all the other kinds of load commands.
Kevin Enderby956366c2014-08-29 22:30:52 +00008437 }
8438}
8439
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008440static void getAndPrintMachHeader(const MachOObjectFile *Obj,
Kevin Enderby956366c2014-08-29 22:30:52 +00008441 uint32_t &filetype, uint32_t &cputype,
8442 bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008443 if (Obj->is64Bit()) {
8444 MachO::mach_header_64 H_64;
8445 H_64 = Obj->getHeader64();
8446 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
8447 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
Kevin Enderby956366c2014-08-29 22:30:52 +00008448 filetype = H_64.filetype;
8449 cputype = H_64.cputype;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008450 } else {
8451 MachO::mach_header H;
8452 H = Obj->getHeader();
8453 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
8454 H.sizeofcmds, H.flags, verbose);
Kevin Enderby956366c2014-08-29 22:30:52 +00008455 filetype = H.filetype;
8456 cputype = H.cputype;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008457 }
8458}
8459
8460void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
8461 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00008462 uint32_t filetype = 0;
8463 uint32_t cputype = 0;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008464 getAndPrintMachHeader(file, filetype, cputype, !NonVerbose);
8465 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008466}
Nick Kledzikd04bc352014-08-30 00:20:14 +00008467
8468//===----------------------------------------------------------------------===//
8469// export trie dumping
8470//===----------------------------------------------------------------------===//
8471
8472void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008473 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
8474 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +00008475 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
8476 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
8477 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8478 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
8479 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8480 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
8481 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
8482 if (ReExport)
8483 outs() << "[re-export] ";
8484 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008485 outs() << format("0x%08llX ",
8486 Entry.address()); // FIXME:add in base address
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008487 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +00008488 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008489 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +00008490 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +00008491 if (WeakDef) {
8492 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008493 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008494 }
8495 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008496 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00008497 outs() << ", ";
8498 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008499 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008500 }
8501 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008502 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00008503 outs() << ", ";
8504 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008505 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008506 }
8507 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008508 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00008509 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008510 outs() << format("resolver=0x%08llX", Entry.other());
8511 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008512 }
8513 outs() << "]";
8514 }
8515 if (ReExport) {
8516 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008517 int Ordinal = Entry.other() - 1;
8518 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
8519 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +00008520 outs() << " (from " << DylibName << ")";
8521 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008522 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +00008523 }
8524 outs() << "\n";
8525 }
8526}
Nick Kledzikac431442014-09-12 21:34:15 +00008527
Nick Kledzikac431442014-09-12 21:34:15 +00008528//===----------------------------------------------------------------------===//
8529// rebase table dumping
8530//===----------------------------------------------------------------------===//
8531
8532namespace {
8533class SegInfo {
8534public:
8535 SegInfo(const object::MachOObjectFile *Obj);
8536
8537 StringRef segmentName(uint32_t SegIndex);
8538 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
8539 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00008540 bool isValidSegIndexAndOffset(uint32_t SegIndex, uint64_t SegOffset);
Nick Kledzikac431442014-09-12 21:34:15 +00008541
8542private:
8543 struct SectionInfo {
8544 uint64_t Address;
8545 uint64_t Size;
8546 StringRef SectionName;
8547 StringRef SegmentName;
8548 uint64_t OffsetInSegment;
8549 uint64_t SegmentStartAddress;
8550 uint32_t SegmentIndex;
8551 };
8552 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
8553 SmallVector<SectionInfo, 32> Sections;
8554};
8555}
8556
8557SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
8558 // Build table of sections so segIndex/offset pairs can be translated.
Nick Kledzik56ebef42014-09-16 01:41:51 +00008559 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
Nick Kledzikac431442014-09-12 21:34:15 +00008560 StringRef CurSegName;
8561 uint64_t CurSegAddress;
8562 for (const SectionRef &Section : Obj->sections()) {
8563 SectionInfo Info;
Davide Italianoccd53fe2015-08-05 07:18:31 +00008564 error(Section.getName(Info.SectionName));
Rafael Espindola80291272014-10-08 15:28:58 +00008565 Info.Address = Section.getAddress();
8566 Info.Size = Section.getSize();
Nick Kledzikac431442014-09-12 21:34:15 +00008567 Info.SegmentName =
8568 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
8569 if (!Info.SegmentName.equals(CurSegName)) {
8570 ++CurSegIndex;
8571 CurSegName = Info.SegmentName;
8572 CurSegAddress = Info.Address;
8573 }
8574 Info.SegmentIndex = CurSegIndex - 1;
8575 Info.OffsetInSegment = Info.Address - CurSegAddress;
8576 Info.SegmentStartAddress = CurSegAddress;
8577 Sections.push_back(Info);
8578 }
8579}
8580
8581StringRef SegInfo::segmentName(uint32_t SegIndex) {
8582 for (const SectionInfo &SI : Sections) {
8583 if (SI.SegmentIndex == SegIndex)
8584 return SI.SegmentName;
8585 }
8586 llvm_unreachable("invalid segIndex");
8587}
8588
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00008589bool SegInfo::isValidSegIndexAndOffset(uint32_t SegIndex,
8590 uint64_t OffsetInSeg) {
8591 for (const SectionInfo &SI : Sections) {
8592 if (SI.SegmentIndex != SegIndex)
8593 continue;
8594 if (SI.OffsetInSegment > OffsetInSeg)
8595 continue;
8596 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
8597 continue;
8598 return true;
8599 }
8600 return false;
8601}
8602
Nick Kledzikac431442014-09-12 21:34:15 +00008603const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
8604 uint64_t OffsetInSeg) {
8605 for (const SectionInfo &SI : Sections) {
8606 if (SI.SegmentIndex != SegIndex)
8607 continue;
8608 if (SI.OffsetInSegment > OffsetInSeg)
8609 continue;
8610 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
8611 continue;
8612 return SI;
8613 }
8614 llvm_unreachable("segIndex and offset not in any section");
8615}
8616
8617StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
8618 return findSection(SegIndex, OffsetInSeg).SectionName;
8619}
8620
8621uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
8622 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
8623 return SI.SegmentStartAddress + OffsetInSeg;
8624}
8625
8626void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
8627 // Build table of sections so names can used in final output.
8628 SegInfo sectionTable(Obj);
8629
8630 outs() << "segment section address type\n";
8631 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
8632 uint32_t SegIndex = Entry.segmentIndex();
8633 uint64_t OffsetInSeg = Entry.segmentOffset();
8634 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8635 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8636 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8637
8638 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008639 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
8640 SegmentName.str().c_str(), SectionName.str().c_str(),
8641 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +00008642 }
8643}
Nick Kledzik56ebef42014-09-16 01:41:51 +00008644
8645static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
8646 StringRef DylibName;
8647 switch (Ordinal) {
8648 case MachO::BIND_SPECIAL_DYLIB_SELF:
8649 return "this-image";
8650 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
8651 return "main-executable";
8652 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
8653 return "flat-namespace";
8654 default:
Nick Kledzikabd29872014-09-16 22:03:13 +00008655 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008656 std::error_code EC =
8657 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +00008658 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +00008659 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +00008660 return DylibName;
8661 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00008662 }
Nick Kledzikabd29872014-09-16 22:03:13 +00008663 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008664}
8665
8666//===----------------------------------------------------------------------===//
8667// bind table dumping
8668//===----------------------------------------------------------------------===//
8669
8670void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
8671 // Build table of sections so names can used in final output.
8672 SegInfo sectionTable(Obj);
8673
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008674 outs() << "segment section address type "
8675 "addend dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008676 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
8677 uint32_t SegIndex = Entry.segmentIndex();
8678 uint64_t OffsetInSeg = Entry.segmentOffset();
8679 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8680 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8681 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8682
8683 // Table lines look like:
8684 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008685 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00008686 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008687 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008688 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008689 << left_justify(SectionName, 18) << " "
8690 << format_hex(Address, 10, true) << " "
8691 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008692 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008693 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008694 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008695 }
8696}
8697
8698//===----------------------------------------------------------------------===//
8699// lazy bind table dumping
8700//===----------------------------------------------------------------------===//
8701
8702void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
8703 // Build table of sections so names can used in final output.
8704 SegInfo sectionTable(Obj);
8705
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008706 outs() << "segment section address "
8707 "dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008708 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
8709 uint32_t SegIndex = Entry.segmentIndex();
8710 uint64_t OffsetInSeg = Entry.segmentOffset();
8711 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8712 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8713 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8714
8715 // Table lines look like:
8716 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008717 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008718 << left_justify(SectionName, 18) << " "
8719 << format_hex(Address, 10, true) << " "
8720 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00008721 << Entry.symbolName() << "\n";
8722 }
8723}
8724
Nick Kledzik56ebef42014-09-16 01:41:51 +00008725//===----------------------------------------------------------------------===//
8726// weak bind table dumping
8727//===----------------------------------------------------------------------===//
8728
8729void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
8730 // Build table of sections so names can used in final output.
8731 SegInfo sectionTable(Obj);
8732
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008733 outs() << "segment section address "
8734 "type addend symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008735 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
8736 // Strong symbols don't have a location to update.
8737 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008738 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +00008739 << Entry.symbolName() << "\n";
8740 continue;
8741 }
8742 uint32_t SegIndex = Entry.segmentIndex();
8743 uint64_t OffsetInSeg = Entry.segmentOffset();
8744 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8745 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8746 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8747
8748 // Table lines look like:
8749 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008750 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008751 << left_justify(SectionName, 18) << " "
8752 << format_hex(Address, 10, true) << " "
8753 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008754 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
8755 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008756 }
8757}
8758
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008759// get_dyld_bind_info_symbolname() is used for disassembly and passed an
8760// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
8761// information for that address. If the address is found its binding symbol
8762// name is returned. If not nullptr is returned.
8763static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
8764 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +00008765 if (info->bindtable == nullptr) {
8766 info->bindtable = new (BindTable);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008767 SegInfo sectionTable(info->O);
8768 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
8769 uint32_t SegIndex = Entry.segmentIndex();
8770 uint64_t OffsetInSeg = Entry.segmentOffset();
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00008771 if (!sectionTable.isValidSegIndexAndOffset(SegIndex, OffsetInSeg))
8772 continue;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008773 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8774 const char *SymbolName = nullptr;
8775 StringRef name = Entry.symbolName();
8776 if (!name.empty())
8777 SymbolName = name.data();
Kevin Enderby078be602014-10-23 19:53:12 +00008778 info->bindtable->push_back(std::make_pair(Address, SymbolName));
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008779 }
8780 }
Kevin Enderby078be602014-10-23 19:53:12 +00008781 for (bind_table_iterator BI = info->bindtable->begin(),
8782 BE = info->bindtable->end();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008783 BI != BE; ++BI) {
8784 uint64_t Address = BI->first;
8785 if (ReferenceValue == Address) {
8786 const char *SymbolName = BI->second;
8787 return SymbolName;
8788 }
8789 }
8790 return nullptr;
8791}