blob: 0d5993ccd2a1d5351e08be4f756c15369f804a4c [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
Kevin Enderby13023a12015-01-15 23:19:11 +00001394static void printArchiveChild(Archive::Child &C, bool verbose,
1395 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 Enderbyc12718932015-01-16 22:10:36 +00001420 uint64_t Size = C.getRawSize();
Kevin Enderby479ee612015-01-23 21:02:44 +00001421 outs() << format("%5" PRId64, Size) << " ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001422
1423 StringRef RawLastModified = C.getRawLastModified();
1424 if (verbose) {
1425 unsigned Seconds;
1426 if (RawLastModified.getAsInteger(10, Seconds))
1427 outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
1428 else {
1429 // Since cime(3) returns a 26 character string of the form:
1430 // "Sun Sep 16 01:03:52 1973\n\0"
1431 // just print 24 characters.
1432 time_t t = Seconds;
1433 outs() << format("%.24s ", ctime(&t));
1434 }
1435 } else {
1436 outs() << RawLastModified << " ";
1437 }
1438
1439 if (verbose) {
1440 ErrorOr<StringRef> NameOrErr = C.getName();
1441 if (NameOrErr.getError()) {
1442 StringRef RawName = C.getRawName();
1443 outs() << RawName << "\n";
1444 } else {
1445 StringRef Name = NameOrErr.get();
1446 outs() << Name << "\n";
1447 }
1448 } else {
1449 StringRef RawName = C.getRawName();
1450 outs() << RawName << "\n";
1451 }
1452}
1453
1454static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
1455 if (A->hasSymbolTable()) {
1456 Archive::child_iterator S = A->getSymbolTableChild();
1457 Archive::Child C = *S;
1458 printArchiveChild(C, verbose, print_offset);
1459 }
1460 for (Archive::child_iterator I = A->child_begin(), E = A->child_end(); I != E;
1461 ++I) {
1462 Archive::Child C = *I;
1463 printArchiveChild(C, verbose, print_offset);
1464 }
1465}
1466
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001467// ParseInputMachO() parses the named Mach-O file in Filename and handles the
1468// -arch flags selecting just those slices as specified by them and also parses
1469// archive files. Then for each individual Mach-O file ProcessMachO() is
1470// called to process the file based on the command line options.
1471void llvm::ParseInputMachO(StringRef Filename) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001472 // Check for -arch all and verifiy the -arch flags are valid.
1473 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1474 if (ArchFlags[i] == "all") {
1475 ArchAll = true;
1476 } else {
1477 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1478 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1479 "'for the -arch option\n";
1480 return;
1481 }
1482 }
1483 }
1484
1485 // Attempt to open the binary.
1486 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1487 if (std::error_code EC = BinaryOrErr.getError()) {
1488 errs() << "llvm-objdump: '" << Filename << "': " << EC.message() << ".\n";
Rafael Espindolade882cd2014-12-03 23:29:34 +00001489 return;
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001490 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001491 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001492
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001493 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1494 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001495 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001496 printArchiveHeaders(A, !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001497 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
1498 I != E; ++I) {
1499 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = I->getAsBinary();
1500 if (ChildOrErr.getError())
1501 continue;
1502 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1503 if (!checkMachOAndArchFlags(O, Filename))
1504 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001505 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001506 }
1507 }
1508 return;
1509 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001510 if (UniversalHeaders) {
1511 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
Kevin Enderbyf0640752015-03-13 17:56:32 +00001512 printMachOUniversalHeaders(UB, !NonVerbose);
Kevin Enderby131d1772015-01-09 19:22:37 +00001513 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001514 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1515 // If we have a list of architecture flags specified dump only those.
1516 if (!ArchAll && ArchFlags.size() != 0) {
1517 // Look for a slice in the universal binary that matches each ArchFlag.
1518 bool ArchFound;
1519 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1520 ArchFound = false;
1521 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1522 E = UB->end_objects();
1523 I != E; ++I) {
1524 if (ArchFlags[i] == I->getArchTypeName()) {
1525 ArchFound = true;
1526 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
1527 I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001528 std::string ArchitectureName = "";
1529 if (ArchFlags.size() > 1)
1530 ArchitectureName = I->getArchTypeName();
1531 if (ObjOrErr) {
1532 ObjectFile &O = *ObjOrErr.get();
1533 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001534 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001535 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1536 I->getAsArchive()) {
1537 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001538 outs() << "Archive : " << Filename;
1539 if (!ArchitectureName.empty())
1540 outs() << " (architecture " << ArchitectureName << ")";
1541 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001542 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001543 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001544 for (Archive::child_iterator AI = A->child_begin(),
1545 AE = A->child_end();
1546 AI != AE; ++AI) {
1547 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1548 if (ChildOrErr.getError())
1549 continue;
1550 if (MachOObjectFile *O =
1551 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001552 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001553 }
1554 }
1555 }
1556 }
1557 if (!ArchFound) {
1558 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1559 << "architecture: " + ArchFlags[i] + "\n";
1560 return;
1561 }
1562 }
1563 return;
1564 }
1565 // No architecture flags were specified so if this contains a slice that
1566 // matches the host architecture dump only that.
1567 if (!ArchAll) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001568 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1569 E = UB->end_objects();
1570 I != E; ++I) {
Kevin Enderby0512bd72015-01-09 21:55:03 +00001571 if (MachOObjectFile::getHostArch().getArchName() ==
1572 I->getArchTypeName()) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001573 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001574 std::string ArchiveName;
1575 ArchiveName.clear();
1576 if (ObjOrErr) {
1577 ObjectFile &O = *ObjOrErr.get();
1578 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001579 ProcessMachO(Filename, MachOOF);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001580 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1581 I->getAsArchive()) {
1582 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001583 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001584 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001585 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001586 for (Archive::child_iterator AI = A->child_begin(),
1587 AE = A->child_end();
1588 AI != AE; ++AI) {
1589 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1590 if (ChildOrErr.getError())
1591 continue;
1592 if (MachOObjectFile *O =
1593 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001594 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001595 }
1596 }
1597 return;
1598 }
1599 }
1600 }
1601 // Either all architectures have been specified or none have been specified
1602 // and this does not contain the host architecture so dump all the slices.
1603 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1604 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1605 E = UB->end_objects();
1606 I != E; ++I) {
1607 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001608 std::string ArchitectureName = "";
1609 if (moreThanOneArch)
1610 ArchitectureName = I->getArchTypeName();
1611 if (ObjOrErr) {
1612 ObjectFile &Obj = *ObjOrErr.get();
1613 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001614 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001615 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
1616 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001617 outs() << "Archive : " << Filename;
1618 if (!ArchitectureName.empty())
1619 outs() << " (architecture " << ArchitectureName << ")";
1620 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001621 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001622 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001623 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
1624 AI != AE; ++AI) {
1625 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1626 if (ChildOrErr.getError())
1627 continue;
1628 if (MachOObjectFile *O =
1629 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1630 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001631 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1632 ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001633 }
1634 }
1635 }
1636 }
1637 return;
1638 }
1639 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1640 if (!checkMachOAndArchFlags(O, Filename))
1641 return;
1642 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001643 ProcessMachO(Filename, MachOOF);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001644 } else
1645 errs() << "llvm-objdump: '" << Filename << "': "
1646 << "Object is not a Mach-O file type.\n";
1647 } else
1648 errs() << "llvm-objdump: '" << Filename << "': "
1649 << "Unrecognized file type.\n";
Rafael Espindola9b709252013-04-13 01:45:40 +00001650}
1651
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001652typedef std::pair<uint64_t, const char *> BindInfoEntry;
1653typedef std::vector<BindInfoEntry> BindTable;
1654typedef BindTable::iterator bind_table_iterator;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001655
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001656// The block of info used by the Symbolizer call backs.
1657struct DisassembleInfo {
1658 bool verbose;
1659 MachOObjectFile *O;
1660 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001661 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001662 std::vector<SectionRef> *Sections;
1663 const char *class_name;
1664 const char *selector_name;
1665 char *method;
Kevin Enderby04bf6932014-10-28 23:39:46 +00001666 char *demangled_name;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001667 uint64_t adrp_addr;
1668 uint32_t adrp_inst;
Kevin Enderby078be602014-10-23 19:53:12 +00001669 BindTable *bindtable;
Kevin Enderbyaac75382015-10-08 16:56:35 +00001670 uint32_t depth;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001671};
1672
1673// SymbolizerGetOpInfo() is the operand information call back function.
1674// This is called to get the symbolic information for operand(s) of an
1675// instruction when it is being done. This routine does this from
1676// the relocation information, symbol table, etc. That block of information
1677// is a pointer to the struct DisassembleInfo that was passed when the
1678// disassembler context was created and passed to back to here when
1679// called back by the disassembler for instruction operands that could have
1680// relocation information. The address of the instruction containing operand is
1681// at the Pc parameter. The immediate value the operand has is passed in
1682// op_info->Value and is at Offset past the start of the instruction and has a
1683// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1684// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1685// names and addends of the symbolic expression to add for the operand. The
1686// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1687// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001688static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1689 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001690 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1691 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001692 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001693
1694 // Make sure all fields returned are zero if we don't set them.
1695 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1696 op_info->Value = value;
1697
1698 // If the TagType is not the value 1 which it code knows about or if no
1699 // verbose symbolic information is wanted then just return 0, indicating no
1700 // information is being returned.
David Blaikie33dd45d02015-03-23 18:39:02 +00001701 if (TagType != 1 || !info->verbose)
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001702 return 0;
1703
1704 unsigned int Arch = info->O->getArch();
1705 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001706 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1707 return 0;
1708 // First search the section's relocation entries (if any) for an entry
1709 // for this section offset.
1710 uint32_t sect_addr = info->S.getAddress();
1711 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1712 bool reloc_found = false;
1713 DataRefImpl Rel;
1714 MachO::any_relocation_info RE;
1715 bool isExtern = false;
1716 SymbolRef Symbol;
1717 bool r_scattered = false;
1718 uint32_t r_value, pair_r_value, r_type;
1719 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001720 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001721 if (RelocOffset == sect_offset) {
1722 Rel = Reloc.getRawDataRefImpl();
1723 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00001724 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001725 r_scattered = info->O->isRelocationScattered(RE);
1726 if (r_scattered) {
1727 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001728 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1729 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1730 DataRefImpl RelNext = Rel;
1731 info->O->moveRelocationNext(RelNext);
1732 MachO::any_relocation_info RENext;
1733 RENext = info->O->getRelocation(RelNext);
1734 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00001735 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001736 else
1737 return 0;
1738 }
1739 } else {
1740 isExtern = info->O->getPlainRelocationExternal(RE);
1741 if (isExtern) {
1742 symbol_iterator RelocSym = Reloc.getSymbol();
1743 Symbol = *RelocSym;
1744 }
1745 }
1746 reloc_found = true;
1747 break;
1748 }
1749 }
1750 if (reloc_found && isExtern) {
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001751 ErrorOr<StringRef> SymName = Symbol.getName();
1752 if (std::error_code EC = SymName.getError())
1753 report_fatal_error(EC.message());
1754 const char *name = SymName->data();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001755 op_info->AddSymbol.Present = 1;
1756 op_info->AddSymbol.Name = name;
1757 // For i386 extern relocation entries the value in the instruction is
1758 // the offset from the symbol, and value is already set in op_info->Value.
1759 return 1;
1760 }
1761 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1762 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001763 const char *add = GuessSymbolName(r_value, info->AddrMap);
1764 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001765 uint32_t offset = value - (r_value - pair_r_value);
1766 op_info->AddSymbol.Present = 1;
1767 if (add != nullptr)
1768 op_info->AddSymbol.Name = add;
1769 else
1770 op_info->AddSymbol.Value = r_value;
1771 op_info->SubtractSymbol.Present = 1;
1772 if (sub != nullptr)
1773 op_info->SubtractSymbol.Name = sub;
1774 else
1775 op_info->SubtractSymbol.Value = pair_r_value;
1776 op_info->Value = offset;
1777 return 1;
1778 }
1779 // TODO:
1780 // Second search the external relocation entries of a fully linked image
1781 // (if any) for an entry that matches this segment offset.
1782 // uint32_t seg_offset = (Pc + Offset);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001783 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001784 }
1785 if (Arch == Triple::x86_64) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001786 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1787 return 0;
1788 // First search the section's relocation entries (if any) for an entry
1789 // for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00001790 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001791 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1792 bool reloc_found = false;
1793 DataRefImpl Rel;
1794 MachO::any_relocation_info RE;
1795 bool isExtern = false;
1796 SymbolRef Symbol;
1797 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001798 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001799 if (RelocOffset == sect_offset) {
1800 Rel = Reloc.getRawDataRefImpl();
1801 RE = info->O->getRelocation(Rel);
1802 // NOTE: Scattered relocations don't exist on x86_64.
1803 isExtern = info->O->getPlainRelocationExternal(RE);
1804 if (isExtern) {
1805 symbol_iterator RelocSym = Reloc.getSymbol();
1806 Symbol = *RelocSym;
1807 }
1808 reloc_found = true;
1809 break;
1810 }
1811 }
1812 if (reloc_found && isExtern) {
1813 // The Value passed in will be adjusted by the Pc if the instruction
1814 // adds the Pc. But for x86_64 external relocation entries the Value
1815 // is the offset from the external symbol.
1816 if (info->O->getAnyRelocationPCRel(RE))
1817 op_info->Value -= Pc + Offset + Size;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001818 ErrorOr<StringRef> SymName = Symbol.getName();
1819 if (std::error_code EC = SymName.getError())
1820 report_fatal_error(EC.message());
1821 const char *name = SymName->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001822 unsigned Type = info->O->getAnyRelocationType(RE);
1823 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1824 DataRefImpl RelNext = Rel;
1825 info->O->moveRelocationNext(RelNext);
1826 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1827 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1828 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1829 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1830 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1831 op_info->SubtractSymbol.Present = 1;
1832 op_info->SubtractSymbol.Name = name;
1833 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1834 Symbol = *RelocSymNext;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001835 ErrorOr<StringRef> SymNameNext = Symbol.getName();
1836 if (std::error_code EC = SymNameNext.getError())
1837 report_fatal_error(EC.message());
1838 name = SymNameNext->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001839 }
1840 }
1841 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1842 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1843 op_info->AddSymbol.Present = 1;
1844 op_info->AddSymbol.Name = name;
1845 return 1;
1846 }
1847 // TODO:
1848 // Second search the external relocation entries of a fully linked image
1849 // (if any) for an entry that matches this segment offset.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001850 // uint64_t seg_offset = (Pc + Offset);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001851 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001852 }
1853 if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00001854 if (Offset != 0 || (Size != 4 && Size != 2))
1855 return 0;
1856 // First search the section's relocation entries (if any) for an entry
1857 // for this section offset.
1858 uint32_t sect_addr = info->S.getAddress();
1859 uint32_t sect_offset = (Pc + Offset) - sect_addr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001860 DataRefImpl Rel;
1861 MachO::any_relocation_info RE;
1862 bool isExtern = false;
1863 SymbolRef Symbol;
1864 bool r_scattered = false;
1865 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
David Blaikie33dd45d02015-03-23 18:39:02 +00001866 auto Reloc =
1867 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
1868 [&](const RelocationRef &Reloc) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001869 uint64_t RelocOffset = Reloc.getOffset();
David Blaikie33dd45d02015-03-23 18:39:02 +00001870 return RelocOffset == sect_offset;
1871 });
1872
1873 if (Reloc == info->S.relocations().end())
1874 return 0;
1875
1876 Rel = Reloc->getRawDataRefImpl();
1877 RE = info->O->getRelocation(Rel);
1878 r_length = info->O->getAnyRelocationLength(RE);
1879 r_scattered = info->O->isRelocationScattered(RE);
1880 if (r_scattered) {
1881 r_value = info->O->getScatteredRelocationValue(RE);
1882 r_type = info->O->getScatteredRelocationType(RE);
1883 } else {
1884 r_type = info->O->getAnyRelocationType(RE);
1885 isExtern = info->O->getPlainRelocationExternal(RE);
1886 if (isExtern) {
1887 symbol_iterator RelocSym = Reloc->getSymbol();
1888 Symbol = *RelocSym;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001889 }
1890 }
David Blaikie33dd45d02015-03-23 18:39:02 +00001891 if (r_type == MachO::ARM_RELOC_HALF ||
1892 r_type == MachO::ARM_RELOC_SECTDIFF ||
1893 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1894 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1895 DataRefImpl RelNext = Rel;
1896 info->O->moveRelocationNext(RelNext);
1897 MachO::any_relocation_info RENext;
1898 RENext = info->O->getRelocation(RelNext);
1899 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
1900 if (info->O->isRelocationScattered(RENext))
1901 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1902 }
1903
1904 if (isExtern) {
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001905 ErrorOr<StringRef> SymName = Symbol.getName();
1906 if (std::error_code EC = SymName.getError())
1907 report_fatal_error(EC.message());
1908 const char *name = SymName->data();
Kevin Enderby930fdc72014-11-06 19:00:13 +00001909 op_info->AddSymbol.Present = 1;
1910 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00001911 switch (r_type) {
1912 case MachO::ARM_RELOC_HALF:
1913 if ((r_length & 0x1) == 1) {
1914 op_info->Value = value << 16 | other_half;
1915 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1916 } else {
1917 op_info->Value = other_half << 16 | value;
1918 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00001919 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00001920 break;
1921 default:
1922 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001923 }
1924 return 1;
1925 }
1926 // If we have a branch that is not an external relocation entry then
1927 // return 0 so the code in tryAddingSymbolicOperand() can use the
1928 // SymbolLookUp call back with the branch target address to look up the
1929 // symbol and possiblity add an annotation for a symbol stub.
David Blaikie33dd45d02015-03-23 18:39:02 +00001930 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
1931 r_type == MachO::ARM_THUMB_RELOC_BR22))
Kevin Enderby930fdc72014-11-06 19:00:13 +00001932 return 0;
1933
1934 uint32_t offset = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001935 if (r_type == MachO::ARM_RELOC_HALF ||
1936 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1937 if ((r_length & 0x1) == 1)
1938 value = value << 16 | other_half;
1939 else
1940 value = other_half << 16 | value;
1941 }
1942 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
1943 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
1944 offset = value - r_value;
1945 value = r_value;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001946 }
1947
David Blaikie33dd45d02015-03-23 18:39:02 +00001948 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00001949 if ((r_length & 0x1) == 1)
1950 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1951 else
1952 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001953 const char *add = GuessSymbolName(r_value, info->AddrMap);
1954 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00001955 int32_t offset = value - (r_value - pair_r_value);
1956 op_info->AddSymbol.Present = 1;
1957 if (add != nullptr)
1958 op_info->AddSymbol.Name = add;
1959 else
1960 op_info->AddSymbol.Value = r_value;
1961 op_info->SubtractSymbol.Present = 1;
1962 if (sub != nullptr)
1963 op_info->SubtractSymbol.Name = sub;
1964 else
1965 op_info->SubtractSymbol.Value = pair_r_value;
1966 op_info->Value = offset;
1967 return 1;
1968 }
1969
Kevin Enderby930fdc72014-11-06 19:00:13 +00001970 op_info->AddSymbol.Present = 1;
1971 op_info->Value = offset;
David Blaikie33dd45d02015-03-23 18:39:02 +00001972 if (r_type == MachO::ARM_RELOC_HALF) {
1973 if ((r_length & 0x1) == 1)
1974 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1975 else
1976 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001977 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001978 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00001979 if (add != nullptr) {
1980 op_info->AddSymbol.Name = add;
1981 return 1;
1982 }
1983 op_info->AddSymbol.Value = value;
1984 return 1;
David Blaikie33dd45d02015-03-23 18:39:02 +00001985 }
1986 if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001987 if (Offset != 0 || Size != 4)
1988 return 0;
1989 // First search the section's relocation entries (if any) for an entry
1990 // for this section offset.
1991 uint64_t sect_addr = info->S.getAddress();
1992 uint64_t sect_offset = (Pc + Offset) - sect_addr;
David Blaikie33dd45d02015-03-23 18:39:02 +00001993 auto Reloc =
1994 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
1995 [&](const RelocationRef &Reloc) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001996 uint64_t RelocOffset = Reloc.getOffset();
David Blaikie33dd45d02015-03-23 18:39:02 +00001997 return RelocOffset == sect_offset;
1998 });
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001999
David Blaikie33dd45d02015-03-23 18:39:02 +00002000 if (Reloc == info->S.relocations().end())
2001 return 0;
2002
2003 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2004 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2005 uint32_t r_type = info->O->getAnyRelocationType(RE);
2006 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2007 DataRefImpl RelNext = Rel;
2008 info->O->moveRelocationNext(RelNext);
2009 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2010 if (value == 0) {
2011 value = info->O->getPlainRelocationSymbolNum(RENext);
2012 op_info->Value = value;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002013 }
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002014 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002015 // NOTE: Scattered relocations don't exist on arm64.
2016 if (!info->O->getPlainRelocationExternal(RE))
2017 return 0;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002018 ErrorOr<StringRef> SymName = Reloc->getSymbol()->getName();
2019 if (std::error_code EC = SymName.getError())
2020 report_fatal_error(EC.message());
2021 const char *name = SymName->data();
David Blaikie33dd45d02015-03-23 18:39:02 +00002022 op_info->AddSymbol.Present = 1;
2023 op_info->AddSymbol.Name = name;
2024
2025 switch (r_type) {
2026 case MachO::ARM64_RELOC_PAGE21:
2027 /* @page */
2028 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2029 break;
2030 case MachO::ARM64_RELOC_PAGEOFF12:
2031 /* @pageoff */
2032 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2033 break;
2034 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2035 /* @gotpage */
2036 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2037 break;
2038 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2039 /* @gotpageoff */
2040 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2041 break;
2042 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2043 /* @tvlppage is not implemented in llvm-mc */
2044 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2045 break;
2046 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2047 /* @tvlppageoff is not implemented in llvm-mc */
2048 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2049 break;
2050 default:
2051 case MachO::ARM64_RELOC_BRANCH26:
2052 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2053 break;
2054 }
2055 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002056 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002057 return 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002058}
2059
Kevin Enderbybf246f52014-09-24 23:08:22 +00002060// GuessCstringPointer is passed the address of what might be a pointer to a
2061// literal string in a cstring section. If that address is in a cstring section
2062// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002063static const char *GuessCstringPointer(uint64_t ReferenceValue,
2064 struct DisassembleInfo *info) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002065 for (const auto &Load : info->O->load_commands()) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002066 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2067 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2068 for (unsigned J = 0; J < Seg.nsects; ++J) {
2069 MachO::section_64 Sec = info->O->getSection64(Load, J);
2070 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2071 if (section_type == MachO::S_CSTRING_LITERALS &&
2072 ReferenceValue >= Sec.addr &&
2073 ReferenceValue < Sec.addr + Sec.size) {
2074 uint64_t sect_offset = ReferenceValue - Sec.addr;
2075 uint64_t object_offset = Sec.offset + sect_offset;
2076 StringRef MachOContents = info->O->getData();
2077 uint64_t object_size = MachOContents.size();
2078 const char *object_addr = (const char *)MachOContents.data();
2079 if (object_offset < object_size) {
2080 const char *name = object_addr + object_offset;
2081 return name;
2082 } else {
2083 return nullptr;
2084 }
2085 }
2086 }
2087 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2088 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2089 for (unsigned J = 0; J < Seg.nsects; ++J) {
2090 MachO::section Sec = info->O->getSection(Load, J);
2091 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2092 if (section_type == MachO::S_CSTRING_LITERALS &&
2093 ReferenceValue >= Sec.addr &&
2094 ReferenceValue < Sec.addr + Sec.size) {
2095 uint64_t sect_offset = ReferenceValue - Sec.addr;
2096 uint64_t object_offset = Sec.offset + sect_offset;
2097 StringRef MachOContents = info->O->getData();
2098 uint64_t object_size = MachOContents.size();
2099 const char *object_addr = (const char *)MachOContents.data();
2100 if (object_offset < object_size) {
2101 const char *name = object_addr + object_offset;
2102 return name;
2103 } else {
2104 return nullptr;
2105 }
2106 }
2107 }
2108 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002109 }
2110 return nullptr;
2111}
2112
Kevin Enderby85974882014-09-26 22:20:44 +00002113// GuessIndirectSymbol returns the name of the indirect symbol for the
2114// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2115// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2116// symbol name being referenced by the stub or pointer.
2117static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2118 struct DisassembleInfo *info) {
Kevin Enderby85974882014-09-26 22:20:44 +00002119 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2120 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002121 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby85974882014-09-26 22:20:44 +00002122 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2123 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2124 for (unsigned J = 0; J < Seg.nsects; ++J) {
2125 MachO::section_64 Sec = info->O->getSection64(Load, J);
2126 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2127 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2128 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2129 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2130 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2131 section_type == MachO::S_SYMBOL_STUBS) &&
2132 ReferenceValue >= Sec.addr &&
2133 ReferenceValue < Sec.addr + Sec.size) {
2134 uint32_t stride;
2135 if (section_type == MachO::S_SYMBOL_STUBS)
2136 stride = Sec.reserved2;
2137 else
2138 stride = 8;
2139 if (stride == 0)
2140 return nullptr;
2141 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2142 if (index < Dysymtab.nindirectsyms) {
2143 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002144 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002145 if (indirect_symbol < Symtab.nsyms) {
2146 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2147 SymbolRef Symbol = *Sym;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002148 ErrorOr<StringRef> SymName = Symbol.getName();
2149 if (std::error_code EC = SymName.getError())
2150 report_fatal_error(EC.message());
2151 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002152 return name;
2153 }
2154 }
2155 }
2156 }
2157 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2158 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2159 for (unsigned J = 0; J < Seg.nsects; ++J) {
2160 MachO::section Sec = info->O->getSection(Load, J);
2161 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2162 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2163 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2164 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2165 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2166 section_type == MachO::S_SYMBOL_STUBS) &&
2167 ReferenceValue >= Sec.addr &&
2168 ReferenceValue < Sec.addr + Sec.size) {
2169 uint32_t stride;
2170 if (section_type == MachO::S_SYMBOL_STUBS)
2171 stride = Sec.reserved2;
2172 else
2173 stride = 4;
2174 if (stride == 0)
2175 return nullptr;
2176 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2177 if (index < Dysymtab.nindirectsyms) {
2178 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002179 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002180 if (indirect_symbol < Symtab.nsyms) {
2181 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2182 SymbolRef Symbol = *Sym;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002183 ErrorOr<StringRef> SymName = Symbol.getName();
2184 if (std::error_code EC = SymName.getError())
2185 report_fatal_error(EC.message());
2186 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002187 return name;
2188 }
2189 }
2190 }
2191 }
2192 }
Kevin Enderby85974882014-09-26 22:20:44 +00002193 }
2194 return nullptr;
2195}
2196
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002197// method_reference() is called passing it the ReferenceName that might be
2198// a reference it to an Objective-C method call. If so then it allocates and
2199// assembles a method call string with the values last seen and saved in
2200// the DisassembleInfo's class_name and selector_name fields. This is saved
2201// into the method field of the info and any previous string is free'ed.
2202// Then the class_name field in the info is set to nullptr. The method call
2203// string is set into ReferenceName and ReferenceType is set to
2204// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2205// then both ReferenceType and ReferenceName are left unchanged.
2206static void method_reference(struct DisassembleInfo *info,
2207 uint64_t *ReferenceType,
2208 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002209 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002210 if (*ReferenceName != nullptr) {
2211 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002212 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002213 if (info->method != nullptr)
2214 free(info->method);
2215 if (info->class_name != nullptr) {
2216 info->method = (char *)malloc(5 + strlen(info->class_name) +
2217 strlen(info->selector_name));
2218 if (info->method != nullptr) {
2219 strcpy(info->method, "+[");
2220 strcat(info->method, info->class_name);
2221 strcat(info->method, " ");
2222 strcat(info->method, info->selector_name);
2223 strcat(info->method, "]");
2224 *ReferenceName = info->method;
2225 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2226 }
2227 } else {
2228 info->method = (char *)malloc(9 + strlen(info->selector_name));
2229 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002230 if (Arch == Triple::x86_64)
2231 strcpy(info->method, "-[%rdi ");
2232 else if (Arch == Triple::aarch64)
2233 strcpy(info->method, "-[x0 ");
2234 else
2235 strcpy(info->method, "-[r? ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002236 strcat(info->method, info->selector_name);
2237 strcat(info->method, "]");
2238 *ReferenceName = info->method;
2239 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2240 }
2241 }
2242 info->class_name = nullptr;
2243 }
2244 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002245 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002246 if (info->method != nullptr)
2247 free(info->method);
2248 info->method = (char *)malloc(17 + strlen(info->selector_name));
2249 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002250 if (Arch == Triple::x86_64)
2251 strcpy(info->method, "-[[%rdi super] ");
2252 else if (Arch == Triple::aarch64)
2253 strcpy(info->method, "-[[x0 super] ");
2254 else
2255 strcpy(info->method, "-[[r? super] ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002256 strcat(info->method, info->selector_name);
2257 strcat(info->method, "]");
2258 *ReferenceName = info->method;
2259 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2260 }
2261 info->class_name = nullptr;
2262 }
2263 }
2264 }
2265}
2266
2267// GuessPointerPointer() is passed the address of what might be a pointer to
2268// a reference to an Objective-C class, selector, message ref or cfstring.
2269// If so the value of the pointer is returned and one of the booleans are set
2270// to true. If not zero is returned and all the booleans are set to false.
2271static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2272 struct DisassembleInfo *info,
2273 bool &classref, bool &selref, bool &msgref,
2274 bool &cfstring) {
2275 classref = false;
2276 selref = false;
2277 msgref = false;
2278 cfstring = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002279 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002280 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2281 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2282 for (unsigned J = 0; J < Seg.nsects; ++J) {
2283 MachO::section_64 Sec = info->O->getSection64(Load, J);
2284 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2285 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2286 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2287 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2288 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2289 ReferenceValue >= Sec.addr &&
2290 ReferenceValue < Sec.addr + Sec.size) {
2291 uint64_t sect_offset = ReferenceValue - Sec.addr;
2292 uint64_t object_offset = Sec.offset + sect_offset;
2293 StringRef MachOContents = info->O->getData();
2294 uint64_t object_size = MachOContents.size();
2295 const char *object_addr = (const char *)MachOContents.data();
2296 if (object_offset < object_size) {
2297 uint64_t pointer_value;
2298 memcpy(&pointer_value, object_addr + object_offset,
2299 sizeof(uint64_t));
2300 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2301 sys::swapByteOrder(pointer_value);
2302 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2303 selref = true;
2304 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2305 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2306 classref = true;
2307 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2308 ReferenceValue + 8 < Sec.addr + Sec.size) {
2309 msgref = true;
2310 memcpy(&pointer_value, object_addr + object_offset + 8,
2311 sizeof(uint64_t));
2312 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2313 sys::swapByteOrder(pointer_value);
2314 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2315 cfstring = true;
2316 return pointer_value;
2317 } else {
2318 return 0;
2319 }
2320 }
2321 }
2322 }
2323 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002324 }
2325 return 0;
2326}
2327
2328// get_pointer_64 returns a pointer to the bytes in the object file at the
2329// Address from a section in the Mach-O file. And indirectly returns the
2330// offset into the section, number of bytes left in the section past the offset
2331// and which section is was being referenced. If the Address is not in a
2332// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002333static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2334 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002335 DisassembleInfo *info,
2336 bool objc_only = false) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002337 offset = 0;
2338 left = 0;
2339 S = SectionRef();
2340 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2341 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2342 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
Kevin Enderby46e642f2015-10-08 22:50:55 +00002343 if (SectSize == 0)
2344 continue;
Kevin Enderby846c0002015-04-16 17:19:59 +00002345 if (objc_only) {
2346 StringRef SectName;
2347 ((*(info->Sections))[SectIdx]).getName(SectName);
2348 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2349 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2350 if (SegName != "__OBJC" && SectName != "__cstring")
2351 continue;
2352 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002353 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2354 S = (*(info->Sections))[SectIdx];
2355 offset = Address - SectAddress;
2356 left = SectSize - offset;
2357 StringRef SectContents;
2358 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2359 return SectContents.data() + offset;
2360 }
2361 }
2362 return nullptr;
2363}
2364
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002365static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2366 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002367 DisassembleInfo *info,
2368 bool objc_only = false) {
2369 return get_pointer_64(Address, offset, left, S, info, objc_only);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002370}
2371
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002372// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2373// the symbol indirectly through n_value. Based on the relocation information
2374// for the specified section offset in the specified section reference.
Kevin Enderby0fc11822015-04-01 20:57:01 +00002375// If no relocation information is found and a non-zero ReferenceValue for the
2376// symbol is passed, look up that address in the info's AddrMap.
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00002377static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2378 DisassembleInfo *info, uint64_t &n_value,
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002379 uint64_t ReferenceValue = 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002380 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002381 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002382 return nullptr;
2383
2384 // See if there is an external relocation entry at the sect_offset.
2385 bool reloc_found = false;
2386 DataRefImpl Rel;
2387 MachO::any_relocation_info RE;
2388 bool isExtern = false;
2389 SymbolRef Symbol;
2390 for (const RelocationRef &Reloc : S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002391 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002392 if (RelocOffset == sect_offset) {
2393 Rel = Reloc.getRawDataRefImpl();
2394 RE = info->O->getRelocation(Rel);
2395 if (info->O->isRelocationScattered(RE))
2396 continue;
2397 isExtern = info->O->getPlainRelocationExternal(RE);
2398 if (isExtern) {
2399 symbol_iterator RelocSym = Reloc.getSymbol();
2400 Symbol = *RelocSym;
2401 }
2402 reloc_found = true;
2403 break;
2404 }
2405 }
2406 // If there is an external relocation entry for a symbol in this section
2407 // at this section_offset then use that symbol's value for the n_value
2408 // and return its name.
2409 const char *SymbolName = nullptr;
2410 if (reloc_found && isExtern) {
Rafael Espindoladea00162015-07-03 17:44:18 +00002411 n_value = Symbol.getValue();
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002412 ErrorOr<StringRef> NameOrError = Symbol.getName();
2413 if (std::error_code EC = NameOrError.getError())
2414 report_fatal_error(EC.message());
2415 StringRef Name = *NameOrError;
2416 if (!Name.empty()) {
2417 SymbolName = Name.data();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002418 return SymbolName;
2419 }
2420 }
2421
2422 // TODO: For fully linked images, look through the external relocation
2423 // entries off the dynamic symtab command. For these the r_offset is from the
2424 // start of the first writeable segment in the Mach-O file. So the offset
2425 // to this section from that segment is passed to this routine by the caller,
2426 // as the database_offset. Which is the difference of the section's starting
2427 // address and the first writable segment.
2428 //
2429 // NOTE: need add passing the database_offset to this routine.
2430
Kevin Enderby0fc11822015-04-01 20:57:01 +00002431 // We did not find an external relocation entry so look up the ReferenceValue
2432 // as an address of a symbol and if found return that symbol's name.
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002433 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002434
2435 return SymbolName;
2436}
2437
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002438static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
2439 DisassembleInfo *info,
2440 uint32_t ReferenceValue) {
2441 uint64_t n_value64;
2442 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
2443}
2444
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002445// These are structs in the Objective-C meta data and read to produce the
2446// comments for disassembly. While these are part of the ABI they are no
2447// public defintions. So the are here not in include/llvm/Support/MachO.h .
2448
2449// The cfstring object in a 64-bit Mach-O file.
2450struct cfstring64_t {
2451 uint64_t isa; // class64_t * (64-bit pointer)
2452 uint64_t flags; // flag bits
2453 uint64_t characters; // char * (64-bit pointer)
2454 uint64_t length; // number of non-NULL characters in above
2455};
2456
2457// The class object in a 64-bit Mach-O file.
2458struct class64_t {
2459 uint64_t isa; // class64_t * (64-bit pointer)
2460 uint64_t superclass; // class64_t * (64-bit pointer)
2461 uint64_t cache; // Cache (64-bit pointer)
2462 uint64_t vtable; // IMP * (64-bit pointer)
2463 uint64_t data; // class_ro64_t * (64-bit pointer)
2464};
2465
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002466struct class32_t {
2467 uint32_t isa; /* class32_t * (32-bit pointer) */
2468 uint32_t superclass; /* class32_t * (32-bit pointer) */
2469 uint32_t cache; /* Cache (32-bit pointer) */
2470 uint32_t vtable; /* IMP * (32-bit pointer) */
2471 uint32_t data; /* class_ro32_t * (32-bit pointer) */
2472};
2473
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002474struct class_ro64_t {
2475 uint32_t flags;
2476 uint32_t instanceStart;
2477 uint32_t instanceSize;
2478 uint32_t reserved;
2479 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2480 uint64_t name; // const char * (64-bit pointer)
2481 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2482 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2483 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2484 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2485 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2486};
2487
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002488struct class_ro32_t {
2489 uint32_t flags;
2490 uint32_t instanceStart;
2491 uint32_t instanceSize;
2492 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
2493 uint32_t name; /* const char * (32-bit pointer) */
2494 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
2495 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
2496 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
2497 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
2498 uint32_t baseProperties; /* const struct objc_property_list *
2499 (32-bit pointer) */
2500};
2501
2502/* Values for class_ro{64,32}_t->flags */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002503#define RO_META (1 << 0)
2504#define RO_ROOT (1 << 1)
2505#define RO_HAS_CXX_STRUCTORS (1 << 2)
2506
2507struct method_list64_t {
2508 uint32_t entsize;
2509 uint32_t count;
2510 /* struct method64_t first; These structures follow inline */
2511};
2512
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002513struct method_list32_t {
2514 uint32_t entsize;
2515 uint32_t count;
2516 /* struct method32_t first; These structures follow inline */
2517};
2518
Kevin Enderby0fc11822015-04-01 20:57:01 +00002519struct method64_t {
2520 uint64_t name; /* SEL (64-bit pointer) */
2521 uint64_t types; /* const char * (64-bit pointer) */
2522 uint64_t imp; /* IMP (64-bit pointer) */
2523};
2524
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002525struct method32_t {
2526 uint32_t name; /* SEL (32-bit pointer) */
2527 uint32_t types; /* const char * (32-bit pointer) */
2528 uint32_t imp; /* IMP (32-bit pointer) */
2529};
2530
Kevin Enderby0fc11822015-04-01 20:57:01 +00002531struct protocol_list64_t {
2532 uint64_t count; /* uintptr_t (a 64-bit value) */
2533 /* struct protocol64_t * list[0]; These pointers follow inline */
2534};
2535
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002536struct protocol_list32_t {
2537 uint32_t count; /* uintptr_t (a 32-bit value) */
2538 /* struct protocol32_t * list[0]; These pointers follow inline */
2539};
2540
Kevin Enderby0fc11822015-04-01 20:57:01 +00002541struct protocol64_t {
2542 uint64_t isa; /* id * (64-bit pointer) */
2543 uint64_t name; /* const char * (64-bit pointer) */
2544 uint64_t protocols; /* struct protocol_list64_t *
2545 (64-bit pointer) */
2546 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
2547 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
2548 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
2549 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
2550 uint64_t instanceProperties; /* struct objc_property_list *
2551 (64-bit pointer) */
2552};
2553
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002554struct protocol32_t {
2555 uint32_t isa; /* id * (32-bit pointer) */
2556 uint32_t name; /* const char * (32-bit pointer) */
2557 uint32_t protocols; /* struct protocol_list_t *
2558 (32-bit pointer) */
2559 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
2560 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
2561 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
2562 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
2563 uint32_t instanceProperties; /* struct objc_property_list *
2564 (32-bit pointer) */
2565};
2566
Kevin Enderby0fc11822015-04-01 20:57:01 +00002567struct ivar_list64_t {
2568 uint32_t entsize;
2569 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002570 /* struct ivar64_t first; These structures follow inline */
2571};
2572
2573struct ivar_list32_t {
2574 uint32_t entsize;
2575 uint32_t count;
2576 /* struct ivar32_t first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002577};
2578
2579struct ivar64_t {
2580 uint64_t offset; /* uintptr_t * (64-bit pointer) */
2581 uint64_t name; /* const char * (64-bit pointer) */
2582 uint64_t type; /* const char * (64-bit pointer) */
2583 uint32_t alignment;
2584 uint32_t size;
2585};
2586
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002587struct ivar32_t {
2588 uint32_t offset; /* uintptr_t * (32-bit pointer) */
2589 uint32_t name; /* const char * (32-bit pointer) */
2590 uint32_t type; /* const char * (32-bit pointer) */
2591 uint32_t alignment;
2592 uint32_t size;
2593};
2594
Kevin Enderby0fc11822015-04-01 20:57:01 +00002595struct objc_property_list64 {
2596 uint32_t entsize;
2597 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002598 /* struct objc_property64 first; These structures follow inline */
2599};
2600
2601struct objc_property_list32 {
2602 uint32_t entsize;
2603 uint32_t count;
2604 /* struct objc_property32 first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002605};
2606
2607struct objc_property64 {
2608 uint64_t name; /* const char * (64-bit pointer) */
2609 uint64_t attributes; /* const char * (64-bit pointer) */
2610};
2611
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002612struct objc_property32 {
2613 uint32_t name; /* const char * (32-bit pointer) */
2614 uint32_t attributes; /* const char * (32-bit pointer) */
2615};
2616
Kevin Enderby0fc11822015-04-01 20:57:01 +00002617struct category64_t {
2618 uint64_t name; /* const char * (64-bit pointer) */
2619 uint64_t cls; /* struct class_t * (64-bit pointer) */
2620 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
2621 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
2622 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
2623 uint64_t instanceProperties; /* struct objc_property_list *
2624 (64-bit pointer) */
2625};
2626
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002627struct category32_t {
2628 uint32_t name; /* const char * (32-bit pointer) */
2629 uint32_t cls; /* struct class_t * (32-bit pointer) */
2630 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
2631 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
2632 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
2633 uint32_t instanceProperties; /* struct objc_property_list *
2634 (32-bit pointer) */
2635};
2636
Kevin Enderby0fc11822015-04-01 20:57:01 +00002637struct objc_image_info64 {
2638 uint32_t version;
2639 uint32_t flags;
2640};
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002641struct objc_image_info32 {
2642 uint32_t version;
2643 uint32_t flags;
2644};
Kevin Enderby846c0002015-04-16 17:19:59 +00002645struct imageInfo_t {
2646 uint32_t version;
2647 uint32_t flags;
2648};
Kevin Enderby0fc11822015-04-01 20:57:01 +00002649/* masks for objc_image_info.flags */
2650#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
2651#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
2652
2653struct message_ref64 {
2654 uint64_t imp; /* IMP (64-bit pointer) */
2655 uint64_t sel; /* SEL (64-bit pointer) */
2656};
2657
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002658struct message_ref32 {
2659 uint32_t imp; /* IMP (32-bit pointer) */
2660 uint32_t sel; /* SEL (32-bit pointer) */
2661};
2662
Kevin Enderby846c0002015-04-16 17:19:59 +00002663// Objective-C 1 (32-bit only) meta data structs.
2664
2665struct objc_module_t {
2666 uint32_t version;
2667 uint32_t size;
2668 uint32_t name; /* char * (32-bit pointer) */
2669 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
2670};
2671
2672struct objc_symtab_t {
2673 uint32_t sel_ref_cnt;
2674 uint32_t refs; /* SEL * (32-bit pointer) */
2675 uint16_t cls_def_cnt;
2676 uint16_t cat_def_cnt;
2677 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
2678};
2679
2680struct objc_class_t {
2681 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2682 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
2683 uint32_t name; /* const char * (32-bit pointer) */
2684 int32_t version;
2685 int32_t info;
2686 int32_t instance_size;
2687 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
2688 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
2689 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
2690 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
2691};
2692
2693#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
2694// class is not a metaclass
2695#define CLS_CLASS 0x1
2696// class is a metaclass
2697#define CLS_META 0x2
2698
2699struct objc_category_t {
2700 uint32_t category_name; /* char * (32-bit pointer) */
2701 uint32_t class_name; /* char * (32-bit pointer) */
2702 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
2703 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
2704 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
2705};
2706
2707struct objc_ivar_t {
2708 uint32_t ivar_name; /* char * (32-bit pointer) */
2709 uint32_t ivar_type; /* char * (32-bit pointer) */
2710 int32_t ivar_offset;
2711};
2712
2713struct objc_ivar_list_t {
2714 int32_t ivar_count;
2715 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
2716};
2717
2718struct objc_method_list_t {
2719 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
2720 int32_t method_count;
2721 // struct objc_method_t method_list[1]; /* variable length structure */
2722};
2723
2724struct objc_method_t {
2725 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2726 uint32_t method_types; /* char * (32-bit pointer) */
2727 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
2728 (32-bit pointer) */
2729};
2730
2731struct objc_protocol_list_t {
2732 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
2733 int32_t count;
2734 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
2735 // (32-bit pointer) */
2736};
2737
2738struct objc_protocol_t {
2739 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2740 uint32_t protocol_name; /* char * (32-bit pointer) */
2741 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
2742 uint32_t instance_methods; /* struct objc_method_description_list *
2743 (32-bit pointer) */
2744 uint32_t class_methods; /* struct objc_method_description_list *
2745 (32-bit pointer) */
2746};
2747
2748struct objc_method_description_list_t {
2749 int32_t count;
2750 // struct objc_method_description_t list[1];
2751};
2752
2753struct objc_method_description_t {
2754 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2755 uint32_t types; /* char * (32-bit pointer) */
2756};
2757
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002758inline void swapStruct(struct cfstring64_t &cfs) {
2759 sys::swapByteOrder(cfs.isa);
2760 sys::swapByteOrder(cfs.flags);
2761 sys::swapByteOrder(cfs.characters);
2762 sys::swapByteOrder(cfs.length);
2763}
2764
2765inline void swapStruct(struct class64_t &c) {
2766 sys::swapByteOrder(c.isa);
2767 sys::swapByteOrder(c.superclass);
2768 sys::swapByteOrder(c.cache);
2769 sys::swapByteOrder(c.vtable);
2770 sys::swapByteOrder(c.data);
2771}
2772
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002773inline void swapStruct(struct class32_t &c) {
2774 sys::swapByteOrder(c.isa);
2775 sys::swapByteOrder(c.superclass);
2776 sys::swapByteOrder(c.cache);
2777 sys::swapByteOrder(c.vtable);
2778 sys::swapByteOrder(c.data);
2779}
2780
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002781inline void swapStruct(struct class_ro64_t &cro) {
2782 sys::swapByteOrder(cro.flags);
2783 sys::swapByteOrder(cro.instanceStart);
2784 sys::swapByteOrder(cro.instanceSize);
2785 sys::swapByteOrder(cro.reserved);
2786 sys::swapByteOrder(cro.ivarLayout);
2787 sys::swapByteOrder(cro.name);
2788 sys::swapByteOrder(cro.baseMethods);
2789 sys::swapByteOrder(cro.baseProtocols);
2790 sys::swapByteOrder(cro.ivars);
2791 sys::swapByteOrder(cro.weakIvarLayout);
2792 sys::swapByteOrder(cro.baseProperties);
2793}
2794
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002795inline void swapStruct(struct class_ro32_t &cro) {
2796 sys::swapByteOrder(cro.flags);
2797 sys::swapByteOrder(cro.instanceStart);
2798 sys::swapByteOrder(cro.instanceSize);
2799 sys::swapByteOrder(cro.ivarLayout);
2800 sys::swapByteOrder(cro.name);
2801 sys::swapByteOrder(cro.baseMethods);
2802 sys::swapByteOrder(cro.baseProtocols);
2803 sys::swapByteOrder(cro.ivars);
2804 sys::swapByteOrder(cro.weakIvarLayout);
2805 sys::swapByteOrder(cro.baseProperties);
2806}
2807
Kevin Enderby0fc11822015-04-01 20:57:01 +00002808inline void swapStruct(struct method_list64_t &ml) {
2809 sys::swapByteOrder(ml.entsize);
2810 sys::swapByteOrder(ml.count);
2811}
2812
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002813inline void swapStruct(struct method_list32_t &ml) {
2814 sys::swapByteOrder(ml.entsize);
2815 sys::swapByteOrder(ml.count);
2816}
2817
Kevin Enderby0fc11822015-04-01 20:57:01 +00002818inline void swapStruct(struct method64_t &m) {
2819 sys::swapByteOrder(m.name);
2820 sys::swapByteOrder(m.types);
2821 sys::swapByteOrder(m.imp);
2822}
2823
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002824inline void swapStruct(struct method32_t &m) {
2825 sys::swapByteOrder(m.name);
2826 sys::swapByteOrder(m.types);
2827 sys::swapByteOrder(m.imp);
2828}
2829
Kevin Enderby0fc11822015-04-01 20:57:01 +00002830inline void swapStruct(struct protocol_list64_t &pl) {
2831 sys::swapByteOrder(pl.count);
2832}
2833
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002834inline void swapStruct(struct protocol_list32_t &pl) {
2835 sys::swapByteOrder(pl.count);
2836}
2837
Kevin Enderby0fc11822015-04-01 20:57:01 +00002838inline void swapStruct(struct protocol64_t &p) {
2839 sys::swapByteOrder(p.isa);
2840 sys::swapByteOrder(p.name);
2841 sys::swapByteOrder(p.protocols);
2842 sys::swapByteOrder(p.instanceMethods);
2843 sys::swapByteOrder(p.classMethods);
2844 sys::swapByteOrder(p.optionalInstanceMethods);
2845 sys::swapByteOrder(p.optionalClassMethods);
2846 sys::swapByteOrder(p.instanceProperties);
2847}
2848
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002849inline void swapStruct(struct protocol32_t &p) {
2850 sys::swapByteOrder(p.isa);
2851 sys::swapByteOrder(p.name);
2852 sys::swapByteOrder(p.protocols);
2853 sys::swapByteOrder(p.instanceMethods);
2854 sys::swapByteOrder(p.classMethods);
2855 sys::swapByteOrder(p.optionalInstanceMethods);
2856 sys::swapByteOrder(p.optionalClassMethods);
2857 sys::swapByteOrder(p.instanceProperties);
2858}
2859
Kevin Enderby0fc11822015-04-01 20:57:01 +00002860inline void swapStruct(struct ivar_list64_t &il) {
2861 sys::swapByteOrder(il.entsize);
2862 sys::swapByteOrder(il.count);
2863}
2864
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002865inline void swapStruct(struct ivar_list32_t &il) {
2866 sys::swapByteOrder(il.entsize);
2867 sys::swapByteOrder(il.count);
2868}
2869
Kevin Enderby0fc11822015-04-01 20:57:01 +00002870inline void swapStruct(struct ivar64_t &i) {
2871 sys::swapByteOrder(i.offset);
2872 sys::swapByteOrder(i.name);
2873 sys::swapByteOrder(i.type);
2874 sys::swapByteOrder(i.alignment);
2875 sys::swapByteOrder(i.size);
2876}
2877
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002878inline void swapStruct(struct ivar32_t &i) {
2879 sys::swapByteOrder(i.offset);
2880 sys::swapByteOrder(i.name);
2881 sys::swapByteOrder(i.type);
2882 sys::swapByteOrder(i.alignment);
2883 sys::swapByteOrder(i.size);
2884}
2885
Kevin Enderby0fc11822015-04-01 20:57:01 +00002886inline void swapStruct(struct objc_property_list64 &pl) {
2887 sys::swapByteOrder(pl.entsize);
2888 sys::swapByteOrder(pl.count);
2889}
2890
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002891inline void swapStruct(struct objc_property_list32 &pl) {
2892 sys::swapByteOrder(pl.entsize);
2893 sys::swapByteOrder(pl.count);
2894}
2895
Kevin Enderby0fc11822015-04-01 20:57:01 +00002896inline void swapStruct(struct objc_property64 &op) {
2897 sys::swapByteOrder(op.name);
2898 sys::swapByteOrder(op.attributes);
2899}
2900
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002901inline void swapStruct(struct objc_property32 &op) {
2902 sys::swapByteOrder(op.name);
2903 sys::swapByteOrder(op.attributes);
2904}
2905
Kevin Enderby0fc11822015-04-01 20:57:01 +00002906inline void swapStruct(struct category64_t &c) {
2907 sys::swapByteOrder(c.name);
2908 sys::swapByteOrder(c.cls);
2909 sys::swapByteOrder(c.instanceMethods);
2910 sys::swapByteOrder(c.classMethods);
2911 sys::swapByteOrder(c.protocols);
2912 sys::swapByteOrder(c.instanceProperties);
2913}
2914
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002915inline void swapStruct(struct category32_t &c) {
2916 sys::swapByteOrder(c.name);
2917 sys::swapByteOrder(c.cls);
2918 sys::swapByteOrder(c.instanceMethods);
2919 sys::swapByteOrder(c.classMethods);
2920 sys::swapByteOrder(c.protocols);
2921 sys::swapByteOrder(c.instanceProperties);
2922}
2923
Kevin Enderby0fc11822015-04-01 20:57:01 +00002924inline void swapStruct(struct objc_image_info64 &o) {
2925 sys::swapByteOrder(o.version);
2926 sys::swapByteOrder(o.flags);
2927}
2928
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002929inline void swapStruct(struct objc_image_info32 &o) {
2930 sys::swapByteOrder(o.version);
2931 sys::swapByteOrder(o.flags);
2932}
2933
Kevin Enderby846c0002015-04-16 17:19:59 +00002934inline void swapStruct(struct imageInfo_t &o) {
2935 sys::swapByteOrder(o.version);
2936 sys::swapByteOrder(o.flags);
2937}
2938
Kevin Enderby0fc11822015-04-01 20:57:01 +00002939inline void swapStruct(struct message_ref64 &mr) {
2940 sys::swapByteOrder(mr.imp);
2941 sys::swapByteOrder(mr.sel);
2942}
2943
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002944inline void swapStruct(struct message_ref32 &mr) {
2945 sys::swapByteOrder(mr.imp);
2946 sys::swapByteOrder(mr.sel);
2947}
2948
Kevin Enderby846c0002015-04-16 17:19:59 +00002949inline void swapStruct(struct objc_module_t &module) {
2950 sys::swapByteOrder(module.version);
2951 sys::swapByteOrder(module.size);
2952 sys::swapByteOrder(module.name);
2953 sys::swapByteOrder(module.symtab);
Jingyue Wufedecc42015-04-16 18:43:44 +00002954}
Kevin Enderby846c0002015-04-16 17:19:59 +00002955
2956inline void swapStruct(struct objc_symtab_t &symtab) {
2957 sys::swapByteOrder(symtab.sel_ref_cnt);
2958 sys::swapByteOrder(symtab.refs);
2959 sys::swapByteOrder(symtab.cls_def_cnt);
2960 sys::swapByteOrder(symtab.cat_def_cnt);
Jingyue Wufedecc42015-04-16 18:43:44 +00002961}
Kevin Enderby846c0002015-04-16 17:19:59 +00002962
2963inline void swapStruct(struct objc_class_t &objc_class) {
2964 sys::swapByteOrder(objc_class.isa);
2965 sys::swapByteOrder(objc_class.super_class);
2966 sys::swapByteOrder(objc_class.name);
2967 sys::swapByteOrder(objc_class.version);
2968 sys::swapByteOrder(objc_class.info);
2969 sys::swapByteOrder(objc_class.instance_size);
2970 sys::swapByteOrder(objc_class.ivars);
2971 sys::swapByteOrder(objc_class.methodLists);
2972 sys::swapByteOrder(objc_class.cache);
2973 sys::swapByteOrder(objc_class.protocols);
Jingyue Wufedecc42015-04-16 18:43:44 +00002974}
Kevin Enderby846c0002015-04-16 17:19:59 +00002975
2976inline void swapStruct(struct objc_category_t &objc_category) {
2977 sys::swapByteOrder(objc_category.category_name);
2978 sys::swapByteOrder(objc_category.class_name);
2979 sys::swapByteOrder(objc_category.instance_methods);
2980 sys::swapByteOrder(objc_category.class_methods);
2981 sys::swapByteOrder(objc_category.protocols);
2982}
2983
2984inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
2985 sys::swapByteOrder(objc_ivar_list.ivar_count);
2986}
2987
2988inline void swapStruct(struct objc_ivar_t &objc_ivar) {
2989 sys::swapByteOrder(objc_ivar.ivar_name);
2990 sys::swapByteOrder(objc_ivar.ivar_type);
2991 sys::swapByteOrder(objc_ivar.ivar_offset);
Jingyue Wufedecc42015-04-16 18:43:44 +00002992}
Kevin Enderby846c0002015-04-16 17:19:59 +00002993
2994inline void swapStruct(struct objc_method_list_t &method_list) {
2995 sys::swapByteOrder(method_list.obsolete);
2996 sys::swapByteOrder(method_list.method_count);
2997}
2998
2999inline void swapStruct(struct objc_method_t &method) {
3000 sys::swapByteOrder(method.method_name);
3001 sys::swapByteOrder(method.method_types);
3002 sys::swapByteOrder(method.method_imp);
3003}
3004
3005inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3006 sys::swapByteOrder(protocol_list.next);
3007 sys::swapByteOrder(protocol_list.count);
3008}
3009
3010inline void swapStruct(struct objc_protocol_t &protocol) {
3011 sys::swapByteOrder(protocol.isa);
3012 sys::swapByteOrder(protocol.protocol_name);
3013 sys::swapByteOrder(protocol.protocol_list);
3014 sys::swapByteOrder(protocol.instance_methods);
3015 sys::swapByteOrder(protocol.class_methods);
3016}
3017
3018inline void swapStruct(struct objc_method_description_list_t &mdl) {
3019 sys::swapByteOrder(mdl.count);
3020}
3021
3022inline void swapStruct(struct objc_method_description_t &md) {
3023 sys::swapByteOrder(md.name);
3024 sys::swapByteOrder(md.types);
3025}
3026
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003027static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3028 struct DisassembleInfo *info);
3029
3030// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3031// to an Objective-C class and returns the class name. It is also passed the
3032// address of the pointer, so when the pointer is zero as it can be in an .o
3033// file, that is used to look for an external relocation entry with a symbol
3034// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003035static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3036 uint64_t ReferenceValue,
3037 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003038 const char *r;
3039 uint32_t offset, left;
3040 SectionRef S;
3041
3042 // The pointer_value can be 0 in an object file and have a relocation
3043 // entry for the class symbol at the ReferenceValue (the address of the
3044 // pointer).
3045 if (pointer_value == 0) {
3046 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3047 if (r == nullptr || left < sizeof(uint64_t))
3048 return nullptr;
3049 uint64_t n_value;
3050 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3051 if (symbol_name == nullptr)
3052 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00003053 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003054 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3055 return class_name + 2;
3056 else
3057 return nullptr;
3058 }
3059
3060 // The case were the pointer_value is non-zero and points to a class defined
3061 // in this Mach-O file.
3062 r = get_pointer_64(pointer_value, offset, left, S, info);
3063 if (r == nullptr || left < sizeof(struct class64_t))
3064 return nullptr;
3065 struct class64_t c;
3066 memcpy(&c, r, sizeof(struct class64_t));
3067 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3068 swapStruct(c);
3069 if (c.data == 0)
3070 return nullptr;
3071 r = get_pointer_64(c.data, offset, left, S, info);
3072 if (r == nullptr || left < sizeof(struct class_ro64_t))
3073 return nullptr;
3074 struct class_ro64_t cro;
3075 memcpy(&cro, r, sizeof(struct class_ro64_t));
3076 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3077 swapStruct(cro);
3078 if (cro.name == 0)
3079 return nullptr;
3080 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3081 return name;
3082}
3083
3084// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3085// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003086static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3087 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003088 const char *r, *name;
3089 uint32_t offset, left;
3090 SectionRef S;
3091 struct cfstring64_t cfs;
3092 uint64_t cfs_characters;
3093
3094 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3095 if (r == nullptr || left < sizeof(struct cfstring64_t))
3096 return nullptr;
3097 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3098 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3099 swapStruct(cfs);
3100 if (cfs.characters == 0) {
3101 uint64_t n_value;
3102 const char *symbol_name = get_symbol_64(
3103 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3104 if (symbol_name == nullptr)
3105 return nullptr;
3106 cfs_characters = n_value;
3107 } else
3108 cfs_characters = cfs.characters;
3109 name = get_pointer_64(cfs_characters, offset, left, S, info);
3110
3111 return name;
3112}
3113
3114// get_objc2_64bit_selref() is used for disassembly and is passed a the address
3115// of a pointer to an Objective-C selector reference when the pointer value is
3116// zero as in a .o file and is likely to have a external relocation entry with
3117// who's symbol's n_value is the real pointer to the selector name. If that is
3118// the case the real pointer to the selector name is returned else 0 is
3119// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003120static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3121 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003122 uint32_t offset, left;
3123 SectionRef S;
3124
3125 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3126 if (r == nullptr || left < sizeof(uint64_t))
3127 return 0;
3128 uint64_t n_value;
3129 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3130 if (symbol_name == nullptr)
3131 return 0;
3132 return n_value;
3133}
3134
Kevin Enderby0fc11822015-04-01 20:57:01 +00003135static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3136 const char *sectname) {
3137 for (const SectionRef &Section : O->sections()) {
3138 StringRef SectName;
3139 Section.getName(SectName);
3140 DataRefImpl Ref = Section.getRawDataRefImpl();
3141 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3142 if (SegName == segname && SectName == sectname)
3143 return Section;
3144 }
3145 return SectionRef();
3146}
3147
3148static void
3149walk_pointer_list_64(const char *listname, const SectionRef S,
3150 MachOObjectFile *O, struct DisassembleInfo *info,
3151 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3152 if (S == SectionRef())
3153 return;
3154
3155 StringRef SectName;
3156 S.getName(SectName);
3157 DataRefImpl Ref = S.getRawDataRefImpl();
3158 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3159 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3160
3161 StringRef BytesStr;
3162 S.getContents(BytesStr);
3163 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3164
3165 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3166 uint32_t left = S.getSize() - i;
3167 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3168 uint64_t p = 0;
3169 memcpy(&p, Contents + i, size);
3170 if (i + sizeof(uint64_t) > S.getSize())
3171 outs() << listname << " list pointer extends past end of (" << SegName
3172 << "," << SectName << ") section\n";
3173 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3174
3175 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3176 sys::swapByteOrder(p);
3177
3178 uint64_t n_value = 0;
3179 const char *name = get_symbol_64(i, S, info, n_value, p);
3180 if (name == nullptr)
3181 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3182
3183 if (n_value != 0) {
3184 outs() << format("0x%" PRIx64, n_value);
3185 if (p != 0)
3186 outs() << " + " << format("0x%" PRIx64, p);
3187 } else
3188 outs() << format("0x%" PRIx64, p);
3189 if (name != nullptr)
3190 outs() << " " << name;
3191 outs() << "\n";
3192
3193 p += n_value;
3194 if (func)
3195 func(p, info);
3196 }
3197}
3198
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003199static void
3200walk_pointer_list_32(const char *listname, const SectionRef S,
3201 MachOObjectFile *O, struct DisassembleInfo *info,
3202 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3203 if (S == SectionRef())
3204 return;
3205
3206 StringRef SectName;
3207 S.getName(SectName);
3208 DataRefImpl Ref = S.getRawDataRefImpl();
3209 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3210 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3211
3212 StringRef BytesStr;
3213 S.getContents(BytesStr);
3214 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3215
3216 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3217 uint32_t left = S.getSize() - i;
3218 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3219 uint32_t p = 0;
3220 memcpy(&p, Contents + i, size);
3221 if (i + sizeof(uint32_t) > S.getSize())
3222 outs() << listname << " list pointer extends past end of (" << SegName
3223 << "," << SectName << ") section\n";
Kevin Enderbycf261312015-04-06 22:33:43 +00003224 uint32_t Address = S.getAddress() + i;
3225 outs() << format("%08" PRIx32, Address) << " ";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003226
3227 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3228 sys::swapByteOrder(p);
3229 outs() << format("0x%" PRIx32, p);
3230
3231 const char *name = get_symbol_32(i, S, info, p);
3232 if (name != nullptr)
3233 outs() << " " << name;
3234 outs() << "\n";
3235
3236 if (func)
3237 func(p, info);
3238 }
3239}
3240
3241static void print_layout_map(const char *layout_map, uint32_t left) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003242 if (layout_map == nullptr)
3243 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003244 outs() << " layout map: ";
3245 do {
3246 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3247 left--;
3248 layout_map++;
3249 } while (*layout_map != '\0' && left != 0);
3250 outs() << "\n";
3251}
3252
Kevin Enderby0fc11822015-04-01 20:57:01 +00003253static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3254 uint32_t offset, left;
3255 SectionRef S;
3256 const char *layout_map;
3257
3258 if (p == 0)
3259 return;
3260 layout_map = get_pointer_64(p, offset, left, S, info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003261 print_layout_map(layout_map, left);
3262}
3263
3264static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3265 uint32_t offset, left;
3266 SectionRef S;
3267 const char *layout_map;
3268
3269 if (p == 0)
3270 return;
3271 layout_map = get_pointer_32(p, offset, left, S, info);
3272 print_layout_map(layout_map, left);
Kevin Enderby0fc11822015-04-01 20:57:01 +00003273}
3274
3275static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3276 const char *indent) {
3277 struct method_list64_t ml;
3278 struct method64_t m;
3279 const char *r;
3280 uint32_t offset, xoffset, left, i;
3281 SectionRef S, xS;
3282 const char *name, *sym_name;
3283 uint64_t n_value;
3284
3285 r = get_pointer_64(p, offset, left, S, info);
3286 if (r == nullptr)
3287 return;
3288 memset(&ml, '\0', sizeof(struct method_list64_t));
3289 if (left < sizeof(struct method_list64_t)) {
3290 memcpy(&ml, r, left);
3291 outs() << " (method_list_t entends past the end of the section)\n";
3292 } else
3293 memcpy(&ml, r, sizeof(struct method_list64_t));
3294 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3295 swapStruct(ml);
3296 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3297 outs() << indent << "\t\t count " << ml.count << "\n";
3298
3299 p += sizeof(struct method_list64_t);
3300 offset += sizeof(struct method_list64_t);
3301 for (i = 0; i < ml.count; i++) {
3302 r = get_pointer_64(p, offset, left, S, info);
3303 if (r == nullptr)
3304 return;
3305 memset(&m, '\0', sizeof(struct method64_t));
3306 if (left < sizeof(struct method64_t)) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003307 memcpy(&m, r, left);
3308 outs() << indent << " (method_t extends past the end of the section)\n";
Kevin Enderby0fc11822015-04-01 20:57:01 +00003309 } else
3310 memcpy(&m, r, sizeof(struct method64_t));
3311 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3312 swapStruct(m);
3313
3314 outs() << indent << "\t\t name ";
3315 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3316 info, n_value, m.name);
3317 if (n_value != 0) {
3318 if (info->verbose && sym_name != nullptr)
3319 outs() << sym_name;
3320 else
3321 outs() << format("0x%" PRIx64, n_value);
3322 if (m.name != 0)
3323 outs() << " + " << format("0x%" PRIx64, m.name);
3324 } else
3325 outs() << format("0x%" PRIx64, m.name);
3326 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3327 if (name != nullptr)
3328 outs() << format(" %.*s", left, name);
3329 outs() << "\n";
3330
3331 outs() << indent << "\t\t types ";
3332 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3333 info, n_value, m.types);
3334 if (n_value != 0) {
3335 if (info->verbose && sym_name != nullptr)
3336 outs() << sym_name;
3337 else
3338 outs() << format("0x%" PRIx64, n_value);
3339 if (m.types != 0)
3340 outs() << " + " << format("0x%" PRIx64, m.types);
3341 } else
3342 outs() << format("0x%" PRIx64, m.types);
3343 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3344 if (name != nullptr)
3345 outs() << format(" %.*s", left, name);
3346 outs() << "\n";
3347
3348 outs() << indent << "\t\t imp ";
3349 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3350 n_value, m.imp);
3351 if (info->verbose && name == nullptr) {
3352 if (n_value != 0) {
3353 outs() << format("0x%" PRIx64, n_value) << " ";
3354 if (m.imp != 0)
3355 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3356 } else
3357 outs() << format("0x%" PRIx64, m.imp) << " ";
3358 }
3359 if (name != nullptr)
3360 outs() << name;
3361 outs() << "\n";
3362
3363 p += sizeof(struct method64_t);
3364 offset += sizeof(struct method64_t);
3365 }
3366}
3367
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003368static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3369 const char *indent) {
3370 struct method_list32_t ml;
3371 struct method32_t m;
Kevin Enderby846c0002015-04-16 17:19:59 +00003372 const char *r, *name;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003373 uint32_t offset, xoffset, left, i;
3374 SectionRef S, xS;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003375
3376 r = get_pointer_32(p, offset, left, S, info);
3377 if (r == nullptr)
3378 return;
3379 memset(&ml, '\0', sizeof(struct method_list32_t));
3380 if (left < sizeof(struct method_list32_t)) {
3381 memcpy(&ml, r, left);
3382 outs() << " (method_list_t entends past the end of the section)\n";
3383 } else
3384 memcpy(&ml, r, sizeof(struct method_list32_t));
3385 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3386 swapStruct(ml);
3387 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3388 outs() << indent << "\t\t count " << ml.count << "\n";
3389
3390 p += sizeof(struct method_list32_t);
3391 offset += sizeof(struct method_list32_t);
3392 for (i = 0; i < ml.count; i++) {
3393 r = get_pointer_32(p, offset, left, S, info);
3394 if (r == nullptr)
3395 return;
3396 memset(&m, '\0', sizeof(struct method32_t));
3397 if (left < sizeof(struct method32_t)) {
3398 memcpy(&ml, r, left);
3399 outs() << indent << " (method_t entends past the end of the section)\n";
3400 } else
3401 memcpy(&m, r, sizeof(struct method32_t));
3402 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3403 swapStruct(m);
3404
3405 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
3406 name = get_pointer_32(m.name, xoffset, left, xS, info);
3407 if (name != nullptr)
3408 outs() << format(" %.*s", left, name);
3409 outs() << "\n";
3410
3411 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
3412 name = get_pointer_32(m.types, xoffset, left, xS, info);
3413 if (name != nullptr)
3414 outs() << format(" %.*s", left, name);
3415 outs() << "\n";
3416
3417 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
3418 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
3419 m.imp);
3420 if (name != nullptr)
3421 outs() << " " << name;
3422 outs() << "\n";
3423
3424 p += sizeof(struct method32_t);
3425 offset += sizeof(struct method32_t);
3426 }
3427}
3428
Kevin Enderby846c0002015-04-16 17:19:59 +00003429static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
3430 uint32_t offset, left, xleft;
3431 SectionRef S;
3432 struct objc_method_list_t method_list;
3433 struct objc_method_t method;
3434 const char *r, *methods, *name, *SymbolName;
3435 int32_t i;
3436
3437 r = get_pointer_32(p, offset, left, S, info, true);
3438 if (r == nullptr)
3439 return true;
3440
3441 outs() << "\n";
3442 if (left > sizeof(struct objc_method_list_t)) {
3443 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
3444 } else {
3445 outs() << "\t\t objc_method_list extends past end of the section\n";
3446 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
3447 memcpy(&method_list, r, left);
3448 }
3449 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3450 swapStruct(method_list);
3451
3452 outs() << "\t\t obsolete "
3453 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
3454 outs() << "\t\t method_count " << method_list.method_count << "\n";
3455
3456 methods = r + sizeof(struct objc_method_list_t);
3457 for (i = 0; i < method_list.method_count; i++) {
3458 if ((i + 1) * sizeof(struct objc_method_t) > left) {
3459 outs() << "\t\t remaining method's extend past the of the section\n";
3460 break;
3461 }
3462 memcpy(&method, methods + i * sizeof(struct objc_method_t),
3463 sizeof(struct objc_method_t));
3464 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3465 swapStruct(method);
3466
3467 outs() << "\t\t method_name "
3468 << format("0x%08" PRIx32, method.method_name);
3469 if (info->verbose) {
3470 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
3471 if (name != nullptr)
3472 outs() << format(" %.*s", xleft, name);
3473 else
3474 outs() << " (not in an __OBJC section)";
3475 }
3476 outs() << "\n";
3477
3478 outs() << "\t\t method_types "
3479 << format("0x%08" PRIx32, method.method_types);
3480 if (info->verbose) {
3481 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
3482 if (name != nullptr)
3483 outs() << format(" %.*s", xleft, name);
3484 else
3485 outs() << " (not in an __OBJC section)";
3486 }
3487 outs() << "\n";
3488
3489 outs() << "\t\t method_imp "
3490 << format("0x%08" PRIx32, method.method_imp) << " ";
3491 if (info->verbose) {
3492 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
3493 if (SymbolName != nullptr)
3494 outs() << SymbolName;
3495 }
3496 outs() << "\n";
3497 }
3498 return false;
3499}
3500
Kevin Enderby0fc11822015-04-01 20:57:01 +00003501static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
3502 struct protocol_list64_t pl;
3503 uint64_t q, n_value;
3504 struct protocol64_t pc;
3505 const char *r;
3506 uint32_t offset, xoffset, left, i;
3507 SectionRef S, xS;
3508 const char *name, *sym_name;
3509
3510 r = get_pointer_64(p, offset, left, S, info);
3511 if (r == nullptr)
3512 return;
3513 memset(&pl, '\0', sizeof(struct protocol_list64_t));
3514 if (left < sizeof(struct protocol_list64_t)) {
3515 memcpy(&pl, r, left);
3516 outs() << " (protocol_list_t entends past the end of the section)\n";
3517 } else
3518 memcpy(&pl, r, sizeof(struct protocol_list64_t));
3519 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3520 swapStruct(pl);
3521 outs() << " count " << pl.count << "\n";
3522
3523 p += sizeof(struct protocol_list64_t);
3524 offset += sizeof(struct protocol_list64_t);
3525 for (i = 0; i < pl.count; i++) {
3526 r = get_pointer_64(p, offset, left, S, info);
3527 if (r == nullptr)
3528 return;
3529 q = 0;
3530 if (left < sizeof(uint64_t)) {
3531 memcpy(&q, r, left);
3532 outs() << " (protocol_t * entends past the end of the section)\n";
3533 } else
3534 memcpy(&q, r, sizeof(uint64_t));
3535 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3536 sys::swapByteOrder(q);
3537
3538 outs() << "\t\t list[" << i << "] ";
3539 sym_name = get_symbol_64(offset, S, info, n_value, q);
3540 if (n_value != 0) {
3541 if (info->verbose && sym_name != nullptr)
3542 outs() << sym_name;
3543 else
3544 outs() << format("0x%" PRIx64, n_value);
3545 if (q != 0)
3546 outs() << " + " << format("0x%" PRIx64, q);
3547 } else
3548 outs() << format("0x%" PRIx64, q);
3549 outs() << " (struct protocol_t *)\n";
3550
3551 r = get_pointer_64(q + n_value, offset, left, S, info);
3552 if (r == nullptr)
3553 return;
3554 memset(&pc, '\0', sizeof(struct protocol64_t));
3555 if (left < sizeof(struct protocol64_t)) {
3556 memcpy(&pc, r, left);
3557 outs() << " (protocol_t entends past the end of the section)\n";
3558 } else
3559 memcpy(&pc, r, sizeof(struct protocol64_t));
3560 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3561 swapStruct(pc);
3562
3563 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
3564
3565 outs() << "\t\t\t name ";
3566 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
3567 info, n_value, pc.name);
3568 if (n_value != 0) {
3569 if (info->verbose && sym_name != nullptr)
3570 outs() << sym_name;
3571 else
3572 outs() << format("0x%" PRIx64, n_value);
3573 if (pc.name != 0)
3574 outs() << " + " << format("0x%" PRIx64, pc.name);
3575 } else
3576 outs() << format("0x%" PRIx64, pc.name);
3577 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
3578 if (name != nullptr)
3579 outs() << format(" %.*s", left, name);
3580 outs() << "\n";
3581
3582 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
3583
3584 outs() << "\t\t instanceMethods ";
3585 sym_name =
3586 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
3587 S, info, n_value, pc.instanceMethods);
3588 if (n_value != 0) {
3589 if (info->verbose && sym_name != nullptr)
3590 outs() << sym_name;
3591 else
3592 outs() << format("0x%" PRIx64, n_value);
3593 if (pc.instanceMethods != 0)
3594 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
3595 } else
3596 outs() << format("0x%" PRIx64, pc.instanceMethods);
3597 outs() << " (struct method_list_t *)\n";
3598 if (pc.instanceMethods + n_value != 0)
3599 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
3600
3601 outs() << "\t\t classMethods ";
3602 sym_name =
3603 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
3604 info, n_value, pc.classMethods);
3605 if (n_value != 0) {
3606 if (info->verbose && sym_name != nullptr)
3607 outs() << sym_name;
3608 else
3609 outs() << format("0x%" PRIx64, n_value);
3610 if (pc.classMethods != 0)
3611 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
3612 } else
3613 outs() << format("0x%" PRIx64, pc.classMethods);
3614 outs() << " (struct method_list_t *)\n";
3615 if (pc.classMethods + n_value != 0)
3616 print_method_list64_t(pc.classMethods + n_value, info, "\t");
3617
3618 outs() << "\t optionalInstanceMethods "
3619 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
3620 outs() << "\t optionalClassMethods "
3621 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
3622 outs() << "\t instanceProperties "
3623 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
3624
3625 p += sizeof(uint64_t);
3626 offset += sizeof(uint64_t);
3627 }
3628}
3629
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003630static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
3631 struct protocol_list32_t pl;
3632 uint32_t q;
3633 struct protocol32_t pc;
3634 const char *r;
3635 uint32_t offset, xoffset, left, i;
3636 SectionRef S, xS;
3637 const char *name;
3638
3639 r = get_pointer_32(p, offset, left, S, info);
3640 if (r == nullptr)
3641 return;
3642 memset(&pl, '\0', sizeof(struct protocol_list32_t));
3643 if (left < sizeof(struct protocol_list32_t)) {
3644 memcpy(&pl, r, left);
3645 outs() << " (protocol_list_t entends past the end of the section)\n";
3646 } else
3647 memcpy(&pl, r, sizeof(struct protocol_list32_t));
3648 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3649 swapStruct(pl);
3650 outs() << " count " << pl.count << "\n";
3651
3652 p += sizeof(struct protocol_list32_t);
3653 offset += sizeof(struct protocol_list32_t);
3654 for (i = 0; i < pl.count; i++) {
3655 r = get_pointer_32(p, offset, left, S, info);
3656 if (r == nullptr)
3657 return;
3658 q = 0;
3659 if (left < sizeof(uint32_t)) {
3660 memcpy(&q, r, left);
3661 outs() << " (protocol_t * entends past the end of the section)\n";
3662 } else
3663 memcpy(&q, r, sizeof(uint32_t));
3664 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3665 sys::swapByteOrder(q);
3666 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
3667 << " (struct protocol_t *)\n";
3668 r = get_pointer_32(q, offset, left, S, info);
3669 if (r == nullptr)
3670 return;
3671 memset(&pc, '\0', sizeof(struct protocol32_t));
3672 if (left < sizeof(struct protocol32_t)) {
3673 memcpy(&pc, r, left);
3674 outs() << " (protocol_t entends past the end of the section)\n";
3675 } else
3676 memcpy(&pc, r, sizeof(struct protocol32_t));
3677 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3678 swapStruct(pc);
3679 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
3680 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
3681 name = get_pointer_32(pc.name, xoffset, left, xS, info);
3682 if (name != nullptr)
3683 outs() << format(" %.*s", left, name);
3684 outs() << "\n";
3685 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
3686 outs() << "\t\t instanceMethods "
3687 << format("0x%" PRIx32, pc.instanceMethods)
3688 << " (struct method_list_t *)\n";
3689 if (pc.instanceMethods != 0)
3690 print_method_list32_t(pc.instanceMethods, info, "\t");
3691 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
3692 << " (struct method_list_t *)\n";
3693 if (pc.classMethods != 0)
3694 print_method_list32_t(pc.classMethods, info, "\t");
3695 outs() << "\t optionalInstanceMethods "
3696 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
3697 outs() << "\t optionalClassMethods "
3698 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
3699 outs() << "\t instanceProperties "
3700 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
3701 p += sizeof(uint32_t);
3702 offset += sizeof(uint32_t);
3703 }
3704}
3705
Kevin Enderby846c0002015-04-16 17:19:59 +00003706static void print_indent(uint32_t indent) {
3707 for (uint32_t i = 0; i < indent;) {
3708 if (indent - i >= 8) {
3709 outs() << "\t";
3710 i += 8;
3711 } else {
3712 for (uint32_t j = i; j < indent; j++)
3713 outs() << " ";
3714 return;
3715 }
3716 }
3717}
3718
3719static bool print_method_description_list(uint32_t p, uint32_t indent,
3720 struct DisassembleInfo *info) {
3721 uint32_t offset, left, xleft;
3722 SectionRef S;
3723 struct objc_method_description_list_t mdl;
3724 struct objc_method_description_t md;
3725 const char *r, *list, *name;
3726 int32_t i;
3727
3728 r = get_pointer_32(p, offset, left, S, info, true);
3729 if (r == nullptr)
3730 return true;
3731
3732 outs() << "\n";
3733 if (left > sizeof(struct objc_method_description_list_t)) {
3734 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
3735 } else {
3736 print_indent(indent);
3737 outs() << " objc_method_description_list extends past end of the section\n";
3738 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
3739 memcpy(&mdl, r, left);
3740 }
3741 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3742 swapStruct(mdl);
3743
3744 print_indent(indent);
3745 outs() << " count " << mdl.count << "\n";
3746
3747 list = r + sizeof(struct objc_method_description_list_t);
3748 for (i = 0; i < mdl.count; i++) {
3749 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
3750 print_indent(indent);
3751 outs() << " remaining list entries extend past the of the section\n";
3752 break;
3753 }
3754 print_indent(indent);
3755 outs() << " list[" << i << "]\n";
3756 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
3757 sizeof(struct objc_method_description_t));
3758 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3759 swapStruct(md);
3760
3761 print_indent(indent);
3762 outs() << " name " << format("0x%08" PRIx32, md.name);
3763 if (info->verbose) {
3764 name = get_pointer_32(md.name, offset, xleft, S, info, true);
3765 if (name != nullptr)
3766 outs() << format(" %.*s", xleft, name);
3767 else
3768 outs() << " (not in an __OBJC section)";
3769 }
3770 outs() << "\n";
3771
3772 print_indent(indent);
3773 outs() << " types " << format("0x%08" PRIx32, md.types);
3774 if (info->verbose) {
3775 name = get_pointer_32(md.types, offset, xleft, S, info, true);
3776 if (name != nullptr)
3777 outs() << format(" %.*s", xleft, name);
3778 else
3779 outs() << " (not in an __OBJC section)";
3780 }
3781 outs() << "\n";
3782 }
3783 return false;
3784}
3785
3786static bool print_protocol_list(uint32_t p, uint32_t indent,
3787 struct DisassembleInfo *info);
3788
3789static bool print_protocol(uint32_t p, uint32_t indent,
3790 struct DisassembleInfo *info) {
3791 uint32_t offset, left;
3792 SectionRef S;
3793 struct objc_protocol_t protocol;
3794 const char *r, *name;
3795
3796 r = get_pointer_32(p, offset, left, S, info, true);
3797 if (r == nullptr)
3798 return true;
3799
3800 outs() << "\n";
3801 if (left >= sizeof(struct objc_protocol_t)) {
3802 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
3803 } else {
3804 print_indent(indent);
3805 outs() << " Protocol extends past end of the section\n";
3806 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
3807 memcpy(&protocol, r, left);
3808 }
3809 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3810 swapStruct(protocol);
3811
3812 print_indent(indent);
3813 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
3814 << "\n";
3815
3816 print_indent(indent);
3817 outs() << " protocol_name "
3818 << format("0x%08" PRIx32, protocol.protocol_name);
3819 if (info->verbose) {
3820 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
3821 if (name != nullptr)
3822 outs() << format(" %.*s", left, name);
3823 else
3824 outs() << " (not in an __OBJC section)";
3825 }
3826 outs() << "\n";
3827
3828 print_indent(indent);
3829 outs() << " protocol_list "
3830 << format("0x%08" PRIx32, protocol.protocol_list);
3831 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
3832 outs() << " (not in an __OBJC section)\n";
3833
3834 print_indent(indent);
3835 outs() << " instance_methods "
3836 << format("0x%08" PRIx32, protocol.instance_methods);
3837 if (print_method_description_list(protocol.instance_methods, indent, info))
3838 outs() << " (not in an __OBJC section)\n";
3839
3840 print_indent(indent);
3841 outs() << " class_methods "
3842 << format("0x%08" PRIx32, protocol.class_methods);
3843 if (print_method_description_list(protocol.class_methods, indent, info))
3844 outs() << " (not in an __OBJC section)\n";
3845
3846 return false;
3847}
3848
3849static bool print_protocol_list(uint32_t p, uint32_t indent,
3850 struct DisassembleInfo *info) {
3851 uint32_t offset, left, l;
3852 SectionRef S;
3853 struct objc_protocol_list_t protocol_list;
3854 const char *r, *list;
3855 int32_t i;
3856
3857 r = get_pointer_32(p, offset, left, S, info, true);
3858 if (r == nullptr)
3859 return true;
3860
3861 outs() << "\n";
3862 if (left > sizeof(struct objc_protocol_list_t)) {
3863 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
3864 } else {
3865 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
3866 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
3867 memcpy(&protocol_list, r, left);
3868 }
3869 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3870 swapStruct(protocol_list);
3871
3872 print_indent(indent);
3873 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
3874 << "\n";
3875 print_indent(indent);
3876 outs() << " count " << protocol_list.count << "\n";
3877
3878 list = r + sizeof(struct objc_protocol_list_t);
3879 for (i = 0; i < protocol_list.count; i++) {
3880 if ((i + 1) * sizeof(uint32_t) > left) {
3881 outs() << "\t\t remaining list entries extend past the of the section\n";
3882 break;
3883 }
3884 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
3885 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3886 sys::swapByteOrder(l);
3887
3888 print_indent(indent);
3889 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
3890 if (print_protocol(l, indent, info))
3891 outs() << "(not in an __OBJC section)\n";
3892 }
3893 return false;
3894}
3895
Kevin Enderby0fc11822015-04-01 20:57:01 +00003896static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
3897 struct ivar_list64_t il;
3898 struct ivar64_t i;
3899 const char *r;
3900 uint32_t offset, xoffset, left, j;
3901 SectionRef S, xS;
3902 const char *name, *sym_name, *ivar_offset_p;
3903 uint64_t ivar_offset, n_value;
3904
3905 r = get_pointer_64(p, offset, left, S, info);
3906 if (r == nullptr)
3907 return;
3908 memset(&il, '\0', sizeof(struct ivar_list64_t));
3909 if (left < sizeof(struct ivar_list64_t)) {
3910 memcpy(&il, r, left);
3911 outs() << " (ivar_list_t entends past the end of the section)\n";
3912 } else
3913 memcpy(&il, r, sizeof(struct ivar_list64_t));
3914 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3915 swapStruct(il);
3916 outs() << " entsize " << il.entsize << "\n";
3917 outs() << " count " << il.count << "\n";
3918
3919 p += sizeof(struct ivar_list64_t);
3920 offset += sizeof(struct ivar_list64_t);
3921 for (j = 0; j < il.count; j++) {
3922 r = get_pointer_64(p, offset, left, S, info);
3923 if (r == nullptr)
3924 return;
3925 memset(&i, '\0', sizeof(struct ivar64_t));
3926 if (left < sizeof(struct ivar64_t)) {
3927 memcpy(&i, r, left);
3928 outs() << " (ivar_t entends past the end of the section)\n";
3929 } else
3930 memcpy(&i, r, sizeof(struct ivar64_t));
3931 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3932 swapStruct(i);
3933
3934 outs() << "\t\t\t offset ";
3935 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
3936 info, n_value, i.offset);
3937 if (n_value != 0) {
3938 if (info->verbose && sym_name != nullptr)
3939 outs() << sym_name;
3940 else
3941 outs() << format("0x%" PRIx64, n_value);
3942 if (i.offset != 0)
3943 outs() << " + " << format("0x%" PRIx64, i.offset);
3944 } else
3945 outs() << format("0x%" PRIx64, i.offset);
3946 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
3947 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
3948 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
3949 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3950 sys::swapByteOrder(ivar_offset);
3951 outs() << " " << ivar_offset << "\n";
3952 } else
3953 outs() << "\n";
3954
3955 outs() << "\t\t\t name ";
3956 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
3957 n_value, i.name);
3958 if (n_value != 0) {
3959 if (info->verbose && sym_name != nullptr)
3960 outs() << sym_name;
3961 else
3962 outs() << format("0x%" PRIx64, n_value);
3963 if (i.name != 0)
3964 outs() << " + " << format("0x%" PRIx64, i.name);
3965 } else
3966 outs() << format("0x%" PRIx64, i.name);
3967 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
3968 if (name != nullptr)
3969 outs() << format(" %.*s", left, name);
3970 outs() << "\n";
3971
3972 outs() << "\t\t\t type ";
3973 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
3974 n_value, i.name);
3975 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
3976 if (n_value != 0) {
3977 if (info->verbose && sym_name != nullptr)
3978 outs() << sym_name;
3979 else
3980 outs() << format("0x%" PRIx64, n_value);
3981 if (i.type != 0)
3982 outs() << " + " << format("0x%" PRIx64, i.type);
3983 } else
3984 outs() << format("0x%" PRIx64, i.type);
3985 if (name != nullptr)
3986 outs() << format(" %.*s", left, name);
3987 outs() << "\n";
3988
3989 outs() << "\t\t\talignment " << i.alignment << "\n";
3990 outs() << "\t\t\t size " << i.size << "\n";
3991
3992 p += sizeof(struct ivar64_t);
3993 offset += sizeof(struct ivar64_t);
3994 }
3995}
3996
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003997static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
3998 struct ivar_list32_t il;
3999 struct ivar32_t i;
4000 const char *r;
4001 uint32_t offset, xoffset, left, j;
4002 SectionRef S, xS;
4003 const char *name, *ivar_offset_p;
4004 uint32_t ivar_offset;
4005
4006 r = get_pointer_32(p, offset, left, S, info);
4007 if (r == nullptr)
4008 return;
4009 memset(&il, '\0', sizeof(struct ivar_list32_t));
4010 if (left < sizeof(struct ivar_list32_t)) {
4011 memcpy(&il, r, left);
4012 outs() << " (ivar_list_t entends past the end of the section)\n";
4013 } else
4014 memcpy(&il, r, sizeof(struct ivar_list32_t));
4015 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4016 swapStruct(il);
4017 outs() << " entsize " << il.entsize << "\n";
4018 outs() << " count " << il.count << "\n";
4019
4020 p += sizeof(struct ivar_list32_t);
4021 offset += sizeof(struct ivar_list32_t);
4022 for (j = 0; j < il.count; j++) {
4023 r = get_pointer_32(p, offset, left, S, info);
4024 if (r == nullptr)
4025 return;
4026 memset(&i, '\0', sizeof(struct ivar32_t));
4027 if (left < sizeof(struct ivar32_t)) {
4028 memcpy(&i, r, left);
4029 outs() << " (ivar_t entends past the end of the section)\n";
4030 } else
4031 memcpy(&i, r, sizeof(struct ivar32_t));
4032 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4033 swapStruct(i);
4034
4035 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4036 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4037 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4038 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4039 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4040 sys::swapByteOrder(ivar_offset);
4041 outs() << " " << ivar_offset << "\n";
4042 } else
4043 outs() << "\n";
4044
4045 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4046 name = get_pointer_32(i.name, xoffset, left, xS, info);
4047 if (name != nullptr)
4048 outs() << format(" %.*s", left, name);
4049 outs() << "\n";
4050
4051 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4052 name = get_pointer_32(i.type, xoffset, left, xS, info);
4053 if (name != nullptr)
4054 outs() << format(" %.*s", left, name);
4055 outs() << "\n";
4056
4057 outs() << "\t\t\talignment " << i.alignment << "\n";
4058 outs() << "\t\t\t size " << i.size << "\n";
4059
4060 p += sizeof(struct ivar32_t);
4061 offset += sizeof(struct ivar32_t);
4062 }
4063}
4064
Kevin Enderby0fc11822015-04-01 20:57:01 +00004065static void print_objc_property_list64(uint64_t p,
4066 struct DisassembleInfo *info) {
4067 struct objc_property_list64 opl;
4068 struct objc_property64 op;
4069 const char *r;
4070 uint32_t offset, xoffset, left, j;
4071 SectionRef S, xS;
4072 const char *name, *sym_name;
4073 uint64_t n_value;
4074
4075 r = get_pointer_64(p, offset, left, S, info);
4076 if (r == nullptr)
4077 return;
4078 memset(&opl, '\0', sizeof(struct objc_property_list64));
4079 if (left < sizeof(struct objc_property_list64)) {
4080 memcpy(&opl, r, left);
4081 outs() << " (objc_property_list entends past the end of the section)\n";
4082 } else
4083 memcpy(&opl, r, sizeof(struct objc_property_list64));
4084 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4085 swapStruct(opl);
4086 outs() << " entsize " << opl.entsize << "\n";
4087 outs() << " count " << opl.count << "\n";
4088
4089 p += sizeof(struct objc_property_list64);
4090 offset += sizeof(struct objc_property_list64);
4091 for (j = 0; j < opl.count; j++) {
4092 r = get_pointer_64(p, offset, left, S, info);
4093 if (r == nullptr)
4094 return;
4095 memset(&op, '\0', sizeof(struct objc_property64));
4096 if (left < sizeof(struct objc_property64)) {
4097 memcpy(&op, r, left);
4098 outs() << " (objc_property entends past the end of the section)\n";
4099 } else
4100 memcpy(&op, r, sizeof(struct objc_property64));
4101 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4102 swapStruct(op);
4103
4104 outs() << "\t\t\t name ";
4105 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4106 info, n_value, op.name);
4107 if (n_value != 0) {
4108 if (info->verbose && sym_name != nullptr)
4109 outs() << sym_name;
4110 else
4111 outs() << format("0x%" PRIx64, n_value);
4112 if (op.name != 0)
4113 outs() << " + " << format("0x%" PRIx64, op.name);
4114 } else
4115 outs() << format("0x%" PRIx64, op.name);
4116 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4117 if (name != nullptr)
4118 outs() << format(" %.*s", left, name);
4119 outs() << "\n";
4120
4121 outs() << "\t\t\tattributes ";
4122 sym_name =
4123 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4124 info, n_value, op.attributes);
4125 if (n_value != 0) {
4126 if (info->verbose && sym_name != nullptr)
4127 outs() << sym_name;
4128 else
4129 outs() << format("0x%" PRIx64, n_value);
4130 if (op.attributes != 0)
4131 outs() << " + " << format("0x%" PRIx64, op.attributes);
4132 } else
4133 outs() << format("0x%" PRIx64, op.attributes);
4134 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4135 if (name != nullptr)
4136 outs() << format(" %.*s", left, name);
4137 outs() << "\n";
4138
4139 p += sizeof(struct objc_property64);
4140 offset += sizeof(struct objc_property64);
4141 }
4142}
4143
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004144static void print_objc_property_list32(uint32_t p,
4145 struct DisassembleInfo *info) {
4146 struct objc_property_list32 opl;
4147 struct objc_property32 op;
4148 const char *r;
4149 uint32_t offset, xoffset, left, j;
4150 SectionRef S, xS;
4151 const char *name;
4152
4153 r = get_pointer_32(p, offset, left, S, info);
4154 if (r == nullptr)
4155 return;
4156 memset(&opl, '\0', sizeof(struct objc_property_list32));
4157 if (left < sizeof(struct objc_property_list32)) {
4158 memcpy(&opl, r, left);
4159 outs() << " (objc_property_list entends past the end of the section)\n";
4160 } else
4161 memcpy(&opl, r, sizeof(struct objc_property_list32));
4162 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4163 swapStruct(opl);
4164 outs() << " entsize " << opl.entsize << "\n";
4165 outs() << " count " << opl.count << "\n";
4166
4167 p += sizeof(struct objc_property_list32);
4168 offset += sizeof(struct objc_property_list32);
4169 for (j = 0; j < opl.count; j++) {
4170 r = get_pointer_32(p, offset, left, S, info);
4171 if (r == nullptr)
4172 return;
4173 memset(&op, '\0', sizeof(struct objc_property32));
4174 if (left < sizeof(struct objc_property32)) {
4175 memcpy(&op, r, left);
4176 outs() << " (objc_property entends past the end of the section)\n";
4177 } else
4178 memcpy(&op, r, sizeof(struct objc_property32));
4179 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4180 swapStruct(op);
4181
4182 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4183 name = get_pointer_32(op.name, xoffset, left, xS, info);
4184 if (name != nullptr)
4185 outs() << format(" %.*s", left, name);
4186 outs() << "\n";
4187
4188 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4189 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4190 if (name != nullptr)
4191 outs() << format(" %.*s", left, name);
4192 outs() << "\n";
4193
4194 p += sizeof(struct objc_property32);
4195 offset += sizeof(struct objc_property32);
4196 }
4197}
4198
Richard Smith81ff44d2015-10-09 22:09:56 +00004199static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
Kevin Enderby0fc11822015-04-01 20:57:01 +00004200 bool &is_meta_class) {
4201 struct class_ro64_t cro;
4202 const char *r;
4203 uint32_t offset, xoffset, left;
4204 SectionRef S, xS;
4205 const char *name, *sym_name;
4206 uint64_t n_value;
4207
4208 r = get_pointer_64(p, offset, left, S, info);
4209 if (r == nullptr || left < sizeof(struct class_ro64_t))
Richard Smith81ff44d2015-10-09 22:09:56 +00004210 return false;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004211 memset(&cro, '\0', sizeof(struct class_ro64_t));
4212 if (left < sizeof(struct class_ro64_t)) {
4213 memcpy(&cro, r, left);
4214 outs() << " (class_ro_t entends past the end of the section)\n";
4215 } else
4216 memcpy(&cro, r, sizeof(struct class_ro64_t));
4217 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4218 swapStruct(cro);
4219 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4220 if (cro.flags & RO_META)
4221 outs() << " RO_META";
4222 if (cro.flags & RO_ROOT)
4223 outs() << " RO_ROOT";
4224 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4225 outs() << " RO_HAS_CXX_STRUCTORS";
4226 outs() << "\n";
4227 outs() << " instanceStart " << cro.instanceStart << "\n";
4228 outs() << " instanceSize " << cro.instanceSize << "\n";
4229 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4230 << "\n";
4231 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4232 << "\n";
4233 print_layout_map64(cro.ivarLayout, info);
4234
4235 outs() << " name ";
4236 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4237 info, n_value, cro.name);
4238 if (n_value != 0) {
4239 if (info->verbose && sym_name != nullptr)
4240 outs() << sym_name;
4241 else
4242 outs() << format("0x%" PRIx64, n_value);
4243 if (cro.name != 0)
4244 outs() << " + " << format("0x%" PRIx64, cro.name);
4245 } else
4246 outs() << format("0x%" PRIx64, cro.name);
4247 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4248 if (name != nullptr)
4249 outs() << format(" %.*s", left, name);
4250 outs() << "\n";
4251
4252 outs() << " baseMethods ";
4253 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4254 S, info, n_value, cro.baseMethods);
4255 if (n_value != 0) {
4256 if (info->verbose && sym_name != nullptr)
4257 outs() << sym_name;
4258 else
4259 outs() << format("0x%" PRIx64, n_value);
4260 if (cro.baseMethods != 0)
4261 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4262 } else
4263 outs() << format("0x%" PRIx64, cro.baseMethods);
4264 outs() << " (struct method_list_t *)\n";
4265 if (cro.baseMethods + n_value != 0)
4266 print_method_list64_t(cro.baseMethods + n_value, info, "");
4267
4268 outs() << " baseProtocols ";
4269 sym_name =
4270 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4271 info, n_value, cro.baseProtocols);
4272 if (n_value != 0) {
4273 if (info->verbose && sym_name != nullptr)
4274 outs() << sym_name;
4275 else
4276 outs() << format("0x%" PRIx64, n_value);
4277 if (cro.baseProtocols != 0)
4278 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4279 } else
4280 outs() << format("0x%" PRIx64, cro.baseProtocols);
4281 outs() << "\n";
4282 if (cro.baseProtocols + n_value != 0)
4283 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4284
4285 outs() << " ivars ";
4286 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004287 info, n_value, cro.ivars);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004288 if (n_value != 0) {
4289 if (info->verbose && sym_name != nullptr)
4290 outs() << sym_name;
4291 else
4292 outs() << format("0x%" PRIx64, n_value);
4293 if (cro.ivars != 0)
4294 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4295 } else
4296 outs() << format("0x%" PRIx64, cro.ivars);
4297 outs() << "\n";
4298 if (cro.ivars + n_value != 0)
4299 print_ivar_list64_t(cro.ivars + n_value, info);
4300
4301 outs() << " weakIvarLayout ";
4302 sym_name =
4303 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4304 info, n_value, cro.weakIvarLayout);
4305 if (n_value != 0) {
4306 if (info->verbose && sym_name != nullptr)
4307 outs() << sym_name;
4308 else
4309 outs() << format("0x%" PRIx64, n_value);
4310 if (cro.weakIvarLayout != 0)
4311 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4312 } else
4313 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4314 outs() << "\n";
4315 print_layout_map64(cro.weakIvarLayout + n_value, info);
4316
4317 outs() << " baseProperties ";
4318 sym_name =
4319 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4320 info, n_value, cro.baseProperties);
4321 if (n_value != 0) {
4322 if (info->verbose && sym_name != nullptr)
4323 outs() << sym_name;
4324 else
4325 outs() << format("0x%" PRIx64, n_value);
4326 if (cro.baseProperties != 0)
4327 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4328 } else
4329 outs() << format("0x%" PRIx64, cro.baseProperties);
4330 outs() << "\n";
4331 if (cro.baseProperties + n_value != 0)
4332 print_objc_property_list64(cro.baseProperties + n_value, info);
4333
4334 is_meta_class = (cro.flags & RO_META) ? true : false;
Richard Smith81ff44d2015-10-09 22:09:56 +00004335 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004336}
4337
Richard Smith81ff44d2015-10-09 22:09:56 +00004338static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004339 bool &is_meta_class) {
4340 struct class_ro32_t cro;
4341 const char *r;
4342 uint32_t offset, xoffset, left;
4343 SectionRef S, xS;
4344 const char *name;
4345
4346 r = get_pointer_32(p, offset, left, S, info);
4347 if (r == nullptr)
Richard Smith81ff44d2015-10-09 22:09:56 +00004348 return false;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004349 memset(&cro, '\0', sizeof(struct class_ro32_t));
4350 if (left < sizeof(struct class_ro32_t)) {
4351 memcpy(&cro, r, left);
4352 outs() << " (class_ro_t entends past the end of the section)\n";
4353 } else
4354 memcpy(&cro, r, sizeof(struct class_ro32_t));
4355 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4356 swapStruct(cro);
4357 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4358 if (cro.flags & RO_META)
4359 outs() << " RO_META";
4360 if (cro.flags & RO_ROOT)
4361 outs() << " RO_ROOT";
4362 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4363 outs() << " RO_HAS_CXX_STRUCTORS";
4364 outs() << "\n";
4365 outs() << " instanceStart " << cro.instanceStart << "\n";
4366 outs() << " instanceSize " << cro.instanceSize << "\n";
4367 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4368 << "\n";
4369 print_layout_map32(cro.ivarLayout, info);
4370
4371 outs() << " name " << format("0x%" PRIx32, cro.name);
4372 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4373 if (name != nullptr)
4374 outs() << format(" %.*s", left, name);
4375 outs() << "\n";
4376
4377 outs() << " baseMethods "
4378 << format("0x%" PRIx32, cro.baseMethods)
4379 << " (struct method_list_t *)\n";
4380 if (cro.baseMethods != 0)
4381 print_method_list32_t(cro.baseMethods, info, "");
4382
4383 outs() << " baseProtocols "
4384 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4385 if (cro.baseProtocols != 0)
4386 print_protocol_list32_t(cro.baseProtocols, info);
4387 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4388 << "\n";
4389 if (cro.ivars != 0)
4390 print_ivar_list32_t(cro.ivars, info);
4391 outs() << " weakIvarLayout "
4392 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4393 print_layout_map32(cro.weakIvarLayout, info);
4394 outs() << " baseProperties "
4395 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4396 if (cro.baseProperties != 0)
4397 print_objc_property_list32(cro.baseProperties, info);
4398 is_meta_class = (cro.flags & RO_META) ? true : false;
Richard Smith81ff44d2015-10-09 22:09:56 +00004399 return true;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004400}
4401
Kevin Enderby0fc11822015-04-01 20:57:01 +00004402static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4403 struct class64_t c;
4404 const char *r;
4405 uint32_t offset, left;
4406 SectionRef S;
4407 const char *name;
4408 uint64_t isa_n_value, n_value;
4409
4410 r = get_pointer_64(p, offset, left, S, info);
4411 if (r == nullptr || left < sizeof(struct class64_t))
4412 return;
4413 memset(&c, '\0', sizeof(struct class64_t));
4414 if (left < sizeof(struct class64_t)) {
4415 memcpy(&c, r, left);
4416 outs() << " (class_t entends past the end of the section)\n";
4417 } else
4418 memcpy(&c, r, sizeof(struct class64_t));
4419 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4420 swapStruct(c);
4421
4422 outs() << " isa " << format("0x%" PRIx64, c.isa);
4423 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
4424 isa_n_value, c.isa);
4425 if (name != nullptr)
4426 outs() << " " << name;
4427 outs() << "\n";
4428
4429 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
4430 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
4431 n_value, c.superclass);
4432 if (name != nullptr)
4433 outs() << " " << name;
4434 outs() << "\n";
4435
4436 outs() << " cache " << format("0x%" PRIx64, c.cache);
4437 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
4438 n_value, c.cache);
4439 if (name != nullptr)
4440 outs() << " " << name;
4441 outs() << "\n";
4442
4443 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
4444 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
4445 n_value, c.vtable);
4446 if (name != nullptr)
4447 outs() << " " << name;
4448 outs() << "\n";
4449
4450 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
4451 n_value, c.data);
4452 outs() << " data ";
4453 if (n_value != 0) {
4454 if (info->verbose && name != nullptr)
4455 outs() << name;
4456 else
4457 outs() << format("0x%" PRIx64, n_value);
4458 if (c.data != 0)
4459 outs() << " + " << format("0x%" PRIx64, c.data);
4460 } else
4461 outs() << format("0x%" PRIx64, c.data);
4462 outs() << " (struct class_ro_t *)";
4463
4464 // This is a Swift class if some of the low bits of the pointer are set.
4465 if ((c.data + n_value) & 0x7)
4466 outs() << " Swift class";
4467 outs() << "\n";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004468 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004469 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
4470 return;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004471
Kevin Enderbyaac75382015-10-08 16:56:35 +00004472 if (!is_meta_class &&
4473 c.isa + isa_n_value != p &&
4474 c.isa + isa_n_value != 0 &&
4475 info->depth < 100) {
4476 info->depth++;
4477 outs() << "Meta Class\n";
4478 print_class64_t(c.isa + isa_n_value, info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004479 }
4480}
4481
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004482static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
4483 struct class32_t c;
4484 const char *r;
4485 uint32_t offset, left;
4486 SectionRef S;
4487 const char *name;
4488
4489 r = get_pointer_32(p, offset, left, S, info);
4490 if (r == nullptr)
4491 return;
4492 memset(&c, '\0', sizeof(struct class32_t));
4493 if (left < sizeof(struct class32_t)) {
4494 memcpy(&c, r, left);
4495 outs() << " (class_t entends past the end of the section)\n";
4496 } else
4497 memcpy(&c, r, sizeof(struct class32_t));
4498 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4499 swapStruct(c);
4500
4501 outs() << " isa " << format("0x%" PRIx32, c.isa);
4502 name =
4503 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
4504 if (name != nullptr)
4505 outs() << " " << name;
4506 outs() << "\n";
4507
4508 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
4509 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
4510 c.superclass);
4511 if (name != nullptr)
4512 outs() << " " << name;
4513 outs() << "\n";
4514
4515 outs() << " cache " << format("0x%" PRIx32, c.cache);
4516 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
4517 c.cache);
4518 if (name != nullptr)
4519 outs() << " " << name;
4520 outs() << "\n";
4521
4522 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
4523 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
4524 c.vtable);
4525 if (name != nullptr)
4526 outs() << " " << name;
4527 outs() << "\n";
4528
4529 name =
4530 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
4531 outs() << " data " << format("0x%" PRIx32, c.data)
4532 << " (struct class_ro_t *)";
4533
4534 // This is a Swift class if some of the low bits of the pointer are set.
4535 if (c.data & 0x3)
4536 outs() << " Swift class";
4537 outs() << "\n";
4538 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004539 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
4540 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004541
Hans Wennborgcc9deb42015-09-29 18:02:48 +00004542 if (!is_meta_class) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004543 outs() << "Meta Class\n";
4544 print_class32_t(c.isa, info);
4545 }
4546}
4547
Kevin Enderby846c0002015-04-16 17:19:59 +00004548static void print_objc_class_t(struct objc_class_t *objc_class,
4549 struct DisassembleInfo *info) {
4550 uint32_t offset, left, xleft;
4551 const char *name, *p, *ivar_list;
4552 SectionRef S;
4553 int32_t i;
4554 struct objc_ivar_list_t objc_ivar_list;
4555 struct objc_ivar_t ivar;
4556
4557 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
4558 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
4559 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
4560 if (name != nullptr)
4561 outs() << format(" %.*s", left, name);
4562 else
4563 outs() << " (not in an __OBJC section)";
4564 }
4565 outs() << "\n";
4566
4567 outs() << "\t super_class "
4568 << format("0x%08" PRIx32, objc_class->super_class);
4569 if (info->verbose) {
4570 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
4571 if (name != nullptr)
4572 outs() << format(" %.*s", left, name);
4573 else
4574 outs() << " (not in an __OBJC section)";
4575 }
4576 outs() << "\n";
4577
4578 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
4579 if (info->verbose) {
4580 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
4581 if (name != nullptr)
4582 outs() << format(" %.*s", left, name);
4583 else
4584 outs() << " (not in an __OBJC section)";
4585 }
4586 outs() << "\n";
4587
4588 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
4589 << "\n";
4590
4591 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
4592 if (info->verbose) {
4593 if (CLS_GETINFO(objc_class, CLS_CLASS))
4594 outs() << " CLS_CLASS";
4595 else if (CLS_GETINFO(objc_class, CLS_META))
4596 outs() << " CLS_META";
4597 }
4598 outs() << "\n";
4599
4600 outs() << "\t instance_size "
4601 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
4602
4603 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
4604 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
4605 if (p != nullptr) {
4606 if (left > sizeof(struct objc_ivar_list_t)) {
4607 outs() << "\n";
4608 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
4609 } else {
4610 outs() << " (entends past the end of the section)\n";
4611 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
4612 memcpy(&objc_ivar_list, p, left);
4613 }
4614 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4615 swapStruct(objc_ivar_list);
4616 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
4617 ivar_list = p + sizeof(struct objc_ivar_list_t);
4618 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
4619 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
4620 outs() << "\t\t remaining ivar's extend past the of the section\n";
4621 break;
4622 }
4623 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
4624 sizeof(struct objc_ivar_t));
4625 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4626 swapStruct(ivar);
4627
4628 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
4629 if (info->verbose) {
4630 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
4631 if (name != nullptr)
4632 outs() << format(" %.*s", xleft, name);
4633 else
4634 outs() << " (not in an __OBJC section)";
4635 }
4636 outs() << "\n";
4637
4638 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
4639 if (info->verbose) {
4640 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
4641 if (name != nullptr)
4642 outs() << format(" %.*s", xleft, name);
4643 else
4644 outs() << " (not in an __OBJC section)";
4645 }
4646 outs() << "\n";
4647
4648 outs() << "\t\t ivar_offset "
4649 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
4650 }
4651 } else {
4652 outs() << " (not in an __OBJC section)\n";
4653 }
4654
4655 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
4656 if (print_method_list(objc_class->methodLists, info))
4657 outs() << " (not in an __OBJC section)\n";
4658
4659 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
4660 << "\n";
4661
4662 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
4663 if (print_protocol_list(objc_class->protocols, 16, info))
4664 outs() << " (not in an __OBJC section)\n";
4665}
4666
4667static void print_objc_objc_category_t(struct objc_category_t *objc_category,
4668 struct DisassembleInfo *info) {
4669 uint32_t offset, left;
4670 const char *name;
4671 SectionRef S;
4672
4673 outs() << "\t category name "
4674 << format("0x%08" PRIx32, objc_category->category_name);
4675 if (info->verbose) {
4676 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
4677 true);
4678 if (name != nullptr)
4679 outs() << format(" %.*s", left, name);
4680 else
4681 outs() << " (not in an __OBJC section)";
4682 }
4683 outs() << "\n";
4684
4685 outs() << "\t\t class name "
4686 << format("0x%08" PRIx32, objc_category->class_name);
4687 if (info->verbose) {
4688 name =
4689 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
4690 if (name != nullptr)
4691 outs() << format(" %.*s", left, name);
4692 else
4693 outs() << " (not in an __OBJC section)";
4694 }
4695 outs() << "\n";
4696
4697 outs() << "\t instance methods "
4698 << format("0x%08" PRIx32, objc_category->instance_methods);
4699 if (print_method_list(objc_category->instance_methods, info))
4700 outs() << " (not in an __OBJC section)\n";
4701
4702 outs() << "\t class methods "
4703 << format("0x%08" PRIx32, objc_category->class_methods);
4704 if (print_method_list(objc_category->class_methods, info))
4705 outs() << " (not in an __OBJC section)\n";
4706}
4707
Kevin Enderby0fc11822015-04-01 20:57:01 +00004708static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
4709 struct category64_t c;
4710 const char *r;
4711 uint32_t offset, xoffset, left;
4712 SectionRef S, xS;
4713 const char *name, *sym_name;
4714 uint64_t n_value;
4715
4716 r = get_pointer_64(p, offset, left, S, info);
4717 if (r == nullptr)
4718 return;
4719 memset(&c, '\0', sizeof(struct category64_t));
4720 if (left < sizeof(struct category64_t)) {
4721 memcpy(&c, r, left);
4722 outs() << " (category_t entends past the end of the section)\n";
4723 } else
4724 memcpy(&c, r, sizeof(struct category64_t));
4725 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4726 swapStruct(c);
4727
4728 outs() << " name ";
4729 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
4730 info, n_value, c.name);
4731 if (n_value != 0) {
4732 if (info->verbose && sym_name != nullptr)
4733 outs() << sym_name;
4734 else
4735 outs() << format("0x%" PRIx64, n_value);
4736 if (c.name != 0)
4737 outs() << " + " << format("0x%" PRIx64, c.name);
4738 } else
4739 outs() << format("0x%" PRIx64, c.name);
4740 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
4741 if (name != nullptr)
4742 outs() << format(" %.*s", left, name);
4743 outs() << "\n";
4744
4745 outs() << " cls ";
4746 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
4747 n_value, c.cls);
4748 if (n_value != 0) {
4749 if (info->verbose && sym_name != nullptr)
4750 outs() << sym_name;
4751 else
4752 outs() << format("0x%" PRIx64, n_value);
4753 if (c.cls != 0)
4754 outs() << " + " << format("0x%" PRIx64, c.cls);
4755 } else
4756 outs() << format("0x%" PRIx64, c.cls);
4757 outs() << "\n";
4758 if (c.cls + n_value != 0)
4759 print_class64_t(c.cls + n_value, info);
4760
4761 outs() << " instanceMethods ";
4762 sym_name =
4763 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
4764 info, n_value, c.instanceMethods);
4765 if (n_value != 0) {
4766 if (info->verbose && sym_name != nullptr)
4767 outs() << sym_name;
4768 else
4769 outs() << format("0x%" PRIx64, n_value);
4770 if (c.instanceMethods != 0)
4771 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
4772 } else
4773 outs() << format("0x%" PRIx64, c.instanceMethods);
4774 outs() << "\n";
4775 if (c.instanceMethods + n_value != 0)
4776 print_method_list64_t(c.instanceMethods + n_value, info, "");
4777
4778 outs() << " classMethods ";
4779 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
4780 S, info, n_value, c.classMethods);
4781 if (n_value != 0) {
4782 if (info->verbose && sym_name != nullptr)
4783 outs() << sym_name;
4784 else
4785 outs() << format("0x%" PRIx64, n_value);
4786 if (c.classMethods != 0)
4787 outs() << " + " << format("0x%" PRIx64, c.classMethods);
4788 } else
4789 outs() << format("0x%" PRIx64, c.classMethods);
4790 outs() << "\n";
4791 if (c.classMethods + n_value != 0)
4792 print_method_list64_t(c.classMethods + n_value, info, "");
4793
4794 outs() << " protocols ";
4795 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
4796 info, n_value, c.protocols);
4797 if (n_value != 0) {
4798 if (info->verbose && sym_name != nullptr)
4799 outs() << sym_name;
4800 else
4801 outs() << format("0x%" PRIx64, n_value);
4802 if (c.protocols != 0)
4803 outs() << " + " << format("0x%" PRIx64, c.protocols);
4804 } else
4805 outs() << format("0x%" PRIx64, c.protocols);
4806 outs() << "\n";
4807 if (c.protocols + n_value != 0)
4808 print_protocol_list64_t(c.protocols + n_value, info);
4809
4810 outs() << "instanceProperties ";
4811 sym_name =
4812 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
4813 S, info, n_value, c.instanceProperties);
4814 if (n_value != 0) {
4815 if (info->verbose && sym_name != nullptr)
4816 outs() << sym_name;
4817 else
4818 outs() << format("0x%" PRIx64, n_value);
4819 if (c.instanceProperties != 0)
4820 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
4821 } else
4822 outs() << format("0x%" PRIx64, c.instanceProperties);
4823 outs() << "\n";
4824 if (c.instanceProperties + n_value != 0)
4825 print_objc_property_list64(c.instanceProperties + n_value, info);
4826}
4827
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004828static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
4829 struct category32_t c;
4830 const char *r;
4831 uint32_t offset, left;
4832 SectionRef S, xS;
4833 const char *name;
4834
4835 r = get_pointer_32(p, offset, left, S, info);
4836 if (r == nullptr)
4837 return;
4838 memset(&c, '\0', sizeof(struct category32_t));
4839 if (left < sizeof(struct category32_t)) {
4840 memcpy(&c, r, left);
4841 outs() << " (category_t entends past the end of the section)\n";
4842 } else
4843 memcpy(&c, r, sizeof(struct category32_t));
4844 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4845 swapStruct(c);
4846
4847 outs() << " name " << format("0x%" PRIx32, c.name);
4848 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
4849 c.name);
Hans Wennborgcc9deb42015-09-29 18:02:48 +00004850 if (name)
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004851 outs() << " " << name;
4852 outs() << "\n";
4853
4854 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
4855 if (c.cls != 0)
4856 print_class32_t(c.cls, info);
4857 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
4858 << "\n";
4859 if (c.instanceMethods != 0)
4860 print_method_list32_t(c.instanceMethods, info, "");
4861 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
4862 << "\n";
4863 if (c.classMethods != 0)
4864 print_method_list32_t(c.classMethods, info, "");
4865 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
4866 if (c.protocols != 0)
4867 print_protocol_list32_t(c.protocols, info);
4868 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
4869 << "\n";
4870 if (c.instanceProperties != 0)
4871 print_objc_property_list32(c.instanceProperties, info);
4872}
4873
Kevin Enderby0fc11822015-04-01 20:57:01 +00004874static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
4875 uint32_t i, left, offset, xoffset;
4876 uint64_t p, n_value;
4877 struct message_ref64 mr;
4878 const char *name, *sym_name;
4879 const char *r;
4880 SectionRef xS;
4881
4882 if (S == SectionRef())
4883 return;
4884
4885 StringRef SectName;
4886 S.getName(SectName);
4887 DataRefImpl Ref = S.getRawDataRefImpl();
4888 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
4889 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4890 offset = 0;
4891 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
4892 p = S.getAddress() + i;
4893 r = get_pointer_64(p, offset, left, S, info);
4894 if (r == nullptr)
4895 return;
4896 memset(&mr, '\0', sizeof(struct message_ref64));
4897 if (left < sizeof(struct message_ref64)) {
4898 memcpy(&mr, r, left);
4899 outs() << " (message_ref entends past the end of the section)\n";
4900 } else
4901 memcpy(&mr, r, sizeof(struct message_ref64));
4902 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4903 swapStruct(mr);
4904
4905 outs() << " imp ";
4906 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
4907 n_value, mr.imp);
4908 if (n_value != 0) {
4909 outs() << format("0x%" PRIx64, n_value) << " ";
4910 if (mr.imp != 0)
4911 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
4912 } else
4913 outs() << format("0x%" PRIx64, mr.imp) << " ";
4914 if (name != nullptr)
4915 outs() << " " << name;
4916 outs() << "\n";
4917
4918 outs() << " sel ";
4919 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
4920 info, n_value, mr.sel);
4921 if (n_value != 0) {
4922 if (info->verbose && sym_name != nullptr)
4923 outs() << sym_name;
4924 else
4925 outs() << format("0x%" PRIx64, n_value);
4926 if (mr.sel != 0)
4927 outs() << " + " << format("0x%" PRIx64, mr.sel);
4928 } else
4929 outs() << format("0x%" PRIx64, mr.sel);
4930 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
4931 if (name != nullptr)
4932 outs() << format(" %.*s", left, name);
4933 outs() << "\n";
4934
4935 offset += sizeof(struct message_ref64);
4936 }
4937}
4938
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004939static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
4940 uint32_t i, left, offset, xoffset, p;
4941 struct message_ref32 mr;
4942 const char *name, *r;
4943 SectionRef xS;
4944
4945 if (S == SectionRef())
4946 return;
4947
4948 StringRef SectName;
4949 S.getName(SectName);
4950 DataRefImpl Ref = S.getRawDataRefImpl();
4951 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
4952 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4953 offset = 0;
4954 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
4955 p = S.getAddress() + i;
4956 r = get_pointer_32(p, offset, left, S, info);
4957 if (r == nullptr)
4958 return;
4959 memset(&mr, '\0', sizeof(struct message_ref32));
4960 if (left < sizeof(struct message_ref32)) {
4961 memcpy(&mr, r, left);
4962 outs() << " (message_ref entends past the end of the section)\n";
4963 } else
4964 memcpy(&mr, r, sizeof(struct message_ref32));
4965 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4966 swapStruct(mr);
4967
4968 outs() << " imp " << format("0x%" PRIx32, mr.imp);
4969 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
4970 mr.imp);
4971 if (name != nullptr)
4972 outs() << " " << name;
4973 outs() << "\n";
4974
4975 outs() << " sel " << format("0x%" PRIx32, mr.sel);
4976 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
4977 if (name != nullptr)
4978 outs() << " " << name;
4979 outs() << "\n";
4980
4981 offset += sizeof(struct message_ref32);
4982 }
4983}
4984
Kevin Enderby0fc11822015-04-01 20:57:01 +00004985static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
4986 uint32_t left, offset, swift_version;
4987 uint64_t p;
4988 struct objc_image_info64 o;
4989 const char *r;
4990
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00004991 if (S == SectionRef())
4992 return;
4993
Kevin Enderby0fc11822015-04-01 20:57:01 +00004994 StringRef SectName;
4995 S.getName(SectName);
4996 DataRefImpl Ref = S.getRawDataRefImpl();
4997 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
4998 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4999 p = S.getAddress();
5000 r = get_pointer_64(p, offset, left, S, info);
5001 if (r == nullptr)
5002 return;
5003 memset(&o, '\0', sizeof(struct objc_image_info64));
5004 if (left < sizeof(struct objc_image_info64)) {
5005 memcpy(&o, r, left);
5006 outs() << " (objc_image_info entends past the end of the section)\n";
5007 } else
5008 memcpy(&o, r, sizeof(struct objc_image_info64));
5009 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5010 swapStruct(o);
5011 outs() << " version " << o.version << "\n";
5012 outs() << " flags " << format("0x%" PRIx32, o.flags);
5013 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5014 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5015 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5016 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5017 swift_version = (o.flags >> 8) & 0xff;
5018 if (swift_version != 0) {
5019 if (swift_version == 1)
5020 outs() << " Swift 1.0";
5021 else if (swift_version == 2)
5022 outs() << " Swift 1.1";
5023 else
5024 outs() << " unknown future Swift version (" << swift_version << ")";
5025 }
5026 outs() << "\n";
5027}
5028
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005029static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5030 uint32_t left, offset, swift_version, p;
5031 struct objc_image_info32 o;
5032 const char *r;
5033
5034 StringRef SectName;
5035 S.getName(SectName);
5036 DataRefImpl Ref = S.getRawDataRefImpl();
5037 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5038 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5039 p = S.getAddress();
5040 r = get_pointer_32(p, offset, left, S, info);
5041 if (r == nullptr)
5042 return;
5043 memset(&o, '\0', sizeof(struct objc_image_info32));
5044 if (left < sizeof(struct objc_image_info32)) {
5045 memcpy(&o, r, left);
5046 outs() << " (objc_image_info entends past the end of the section)\n";
5047 } else
5048 memcpy(&o, r, sizeof(struct objc_image_info32));
5049 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5050 swapStruct(o);
5051 outs() << " version " << o.version << "\n";
5052 outs() << " flags " << format("0x%" PRIx32, o.flags);
5053 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5054 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5055 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5056 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5057 swift_version = (o.flags >> 8) & 0xff;
5058 if (swift_version != 0) {
5059 if (swift_version == 1)
5060 outs() << " Swift 1.0";
5061 else if (swift_version == 2)
5062 outs() << " Swift 1.1";
5063 else
5064 outs() << " unknown future Swift version (" << swift_version << ")";
5065 }
5066 outs() << "\n";
5067}
5068
Kevin Enderby846c0002015-04-16 17:19:59 +00005069static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5070 uint32_t left, offset, p;
5071 struct imageInfo_t o;
5072 const char *r;
5073
5074 StringRef SectName;
5075 S.getName(SectName);
5076 DataRefImpl Ref = S.getRawDataRefImpl();
5077 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5078 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5079 p = S.getAddress();
5080 r = get_pointer_32(p, offset, left, S, info);
5081 if (r == nullptr)
5082 return;
5083 memset(&o, '\0', sizeof(struct imageInfo_t));
5084 if (left < sizeof(struct imageInfo_t)) {
5085 memcpy(&o, r, left);
5086 outs() << " (imageInfo entends past the end of the section)\n";
5087 } else
5088 memcpy(&o, r, sizeof(struct imageInfo_t));
5089 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5090 swapStruct(o);
5091 outs() << " version " << o.version << "\n";
5092 outs() << " flags " << format("0x%" PRIx32, o.flags);
5093 if (o.flags & 0x1)
5094 outs() << " F&C";
5095 if (o.flags & 0x2)
5096 outs() << " GC";
5097 if (o.flags & 0x4)
5098 outs() << " GC-only";
5099 else
5100 outs() << " RR";
5101 outs() << "\n";
5102}
5103
Kevin Enderby0fc11822015-04-01 20:57:01 +00005104static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5105 SymbolAddressMap AddrMap;
5106 if (verbose)
5107 CreateSymbolAddressMap(O, &AddrMap);
5108
5109 std::vector<SectionRef> Sections;
5110 for (const SectionRef &Section : O->sections()) {
5111 StringRef SectName;
5112 Section.getName(SectName);
5113 Sections.push_back(Section);
5114 }
5115
5116 struct DisassembleInfo info;
5117 // Set up the block of info used by the Symbolizer call backs.
5118 info.verbose = verbose;
5119 info.O = O;
5120 info.AddrMap = &AddrMap;
5121 info.Sections = &Sections;
5122 info.class_name = nullptr;
5123 info.selector_name = nullptr;
5124 info.method = nullptr;
5125 info.demangled_name = nullptr;
5126 info.bindtable = nullptr;
5127 info.adrp_addr = 0;
5128 info.adrp_inst = 0;
5129
Kevin Enderbyaac75382015-10-08 16:56:35 +00005130 info.depth = 0;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005131 const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5132 if (CL != SectionRef()) {
5133 info.S = CL;
5134 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
5135 } else {
5136 const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
5137 info.S = CL;
5138 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
5139 }
5140
5141 const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5142 if (CR != SectionRef()) {
5143 info.S = CR;
5144 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
5145 } else {
5146 const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
5147 info.S = CR;
5148 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
5149 }
5150
5151 const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5152 if (SR != SectionRef()) {
5153 info.S = SR;
5154 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
5155 } else {
5156 const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
5157 info.S = SR;
5158 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
5159 }
5160
5161 const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5162 if (CA != SectionRef()) {
5163 info.S = CA;
5164 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
5165 } else {
5166 const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
5167 info.S = CA;
5168 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
5169 }
5170
5171 const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5172 if (PL != SectionRef()) {
5173 info.S = PL;
5174 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
5175 } else {
5176 const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
5177 info.S = PL;
5178 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
5179 }
5180
5181 const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5182 if (MR != SectionRef()) {
5183 info.S = MR;
5184 print_message_refs64(MR, &info);
5185 } else {
5186 const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
5187 info.S = MR;
5188 print_message_refs64(MR, &info);
5189 }
5190
5191 const SectionRef II = get_section(O, "__OBJC2", "__image_info");
5192 if (II != SectionRef()) {
5193 info.S = II;
5194 print_image_info64(II, &info);
5195 } else {
5196 const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
5197 info.S = II;
5198 print_image_info64(II, &info);
5199 }
Kevin Enderby0bc6ed42015-04-01 21:50:45 +00005200
5201 if (info.bindtable != nullptr)
5202 delete info.bindtable;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005203}
5204
5205static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005206 SymbolAddressMap AddrMap;
5207 if (verbose)
5208 CreateSymbolAddressMap(O, &AddrMap);
5209
5210 std::vector<SectionRef> Sections;
5211 for (const SectionRef &Section : O->sections()) {
5212 StringRef SectName;
5213 Section.getName(SectName);
5214 Sections.push_back(Section);
5215 }
5216
5217 struct DisassembleInfo info;
5218 // Set up the block of info used by the Symbolizer call backs.
5219 info.verbose = verbose;
5220 info.O = O;
5221 info.AddrMap = &AddrMap;
5222 info.Sections = &Sections;
5223 info.class_name = nullptr;
5224 info.selector_name = nullptr;
5225 info.method = nullptr;
5226 info.demangled_name = nullptr;
5227 info.bindtable = nullptr;
5228 info.adrp_addr = 0;
5229 info.adrp_inst = 0;
5230
5231 const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5232 if (CL != SectionRef()) {
5233 info.S = CL;
5234 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5235 } else {
5236 const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
5237 info.S = CL;
5238 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5239 }
5240
5241 const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5242 if (CR != SectionRef()) {
5243 info.S = CR;
5244 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5245 } else {
5246 const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
5247 info.S = CR;
5248 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5249 }
5250
5251 const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5252 if (SR != SectionRef()) {
5253 info.S = SR;
5254 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5255 } else {
5256 const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
5257 info.S = SR;
5258 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5259 }
5260
5261 const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5262 if (CA != SectionRef()) {
5263 info.S = CA;
5264 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5265 } else {
5266 const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
5267 info.S = CA;
5268 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5269 }
5270
5271 const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5272 if (PL != SectionRef()) {
5273 info.S = PL;
5274 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5275 } else {
5276 const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
5277 info.S = PL;
5278 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5279 }
5280
5281 const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5282 if (MR != SectionRef()) {
5283 info.S = MR;
5284 print_message_refs32(MR, &info);
5285 } else {
5286 const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
5287 info.S = MR;
5288 print_message_refs32(MR, &info);
5289 }
5290
5291 const SectionRef II = get_section(O, "__OBJC2", "__image_info");
5292 if (II != SectionRef()) {
5293 info.S = II;
5294 print_image_info32(II, &info);
5295 } else {
5296 const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
5297 info.S = II;
5298 print_image_info32(II, &info);
5299 }
Kevin Enderby0fc11822015-04-01 20:57:01 +00005300}
5301
5302static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby846c0002015-04-16 17:19:59 +00005303 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5304 const char *r, *name, *defs;
5305 struct objc_module_t module;
5306 SectionRef S, xS;
5307 struct objc_symtab_t symtab;
5308 struct objc_class_t objc_class;
5309 struct objc_category_t objc_category;
5310
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005311 outs() << "Objective-C segment\n";
Kevin Enderby846c0002015-04-16 17:19:59 +00005312 S = get_section(O, "__OBJC", "__module_info");
5313 if (S == SectionRef())
5314 return false;
5315
5316 SymbolAddressMap AddrMap;
5317 if (verbose)
5318 CreateSymbolAddressMap(O, &AddrMap);
5319
5320 std::vector<SectionRef> Sections;
5321 for (const SectionRef &Section : O->sections()) {
5322 StringRef SectName;
5323 Section.getName(SectName);
5324 Sections.push_back(Section);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005325 }
Kevin Enderby846c0002015-04-16 17:19:59 +00005326
5327 struct DisassembleInfo info;
5328 // Set up the block of info used by the Symbolizer call backs.
5329 info.verbose = verbose;
5330 info.O = O;
5331 info.AddrMap = &AddrMap;
5332 info.Sections = &Sections;
5333 info.class_name = nullptr;
5334 info.selector_name = nullptr;
5335 info.method = nullptr;
5336 info.demangled_name = nullptr;
5337 info.bindtable = nullptr;
5338 info.adrp_addr = 0;
5339 info.adrp_inst = 0;
5340
5341 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5342 p = S.getAddress() + i;
5343 r = get_pointer_32(p, offset, left, S, &info, true);
5344 if (r == nullptr)
5345 return true;
5346 memset(&module, '\0', sizeof(struct objc_module_t));
5347 if (left < sizeof(struct objc_module_t)) {
5348 memcpy(&module, r, left);
5349 outs() << " (module extends past end of __module_info section)\n";
5350 } else
5351 memcpy(&module, r, sizeof(struct objc_module_t));
5352 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5353 swapStruct(module);
5354
5355 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5356 outs() << " version " << module.version << "\n";
5357 outs() << " size " << module.size << "\n";
5358 outs() << " name ";
5359 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5360 if (name != nullptr)
5361 outs() << format("%.*s", left, name);
5362 else
5363 outs() << format("0x%08" PRIx32, module.name)
5364 << "(not in an __OBJC section)";
5365 outs() << "\n";
5366
5367 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5368 if (module.symtab == 0 || r == nullptr) {
5369 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5370 << " (not in an __OBJC section)\n";
5371 continue;
5372 }
5373 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5374 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5375 defs_left = 0;
5376 defs = nullptr;
5377 if (left < sizeof(struct objc_symtab_t)) {
5378 memcpy(&symtab, r, left);
5379 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5380 } else {
5381 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5382 if (left > sizeof(struct objc_symtab_t)) {
5383 defs_left = left - sizeof(struct objc_symtab_t);
5384 defs = r + sizeof(struct objc_symtab_t);
5385 }
5386 }
5387 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5388 swapStruct(symtab);
5389
5390 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5391 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5392 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5393 if (r == nullptr)
5394 outs() << " (not in an __OBJC section)";
5395 outs() << "\n";
5396 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5397 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5398 if (symtab.cls_def_cnt > 0)
5399 outs() << "\tClass Definitions\n";
5400 for (j = 0; j < symtab.cls_def_cnt; j++) {
5401 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5402 outs() << "\t(remaining class defs entries entends past the end of the "
5403 << "section)\n";
5404 break;
5405 }
5406 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5407 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5408 sys::swapByteOrder(def);
5409
5410 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5411 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5412 if (r != nullptr) {
5413 if (left > sizeof(struct objc_class_t)) {
5414 outs() << "\n";
5415 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5416 } else {
5417 outs() << " (entends past the end of the section)\n";
5418 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5419 memcpy(&objc_class, r, left);
5420 }
5421 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5422 swapStruct(objc_class);
5423 print_objc_class_t(&objc_class, &info);
5424 } else {
5425 outs() << "(not in an __OBJC section)\n";
5426 }
5427
5428 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
5429 outs() << "\tMeta Class";
5430 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
5431 if (r != nullptr) {
5432 if (left > sizeof(struct objc_class_t)) {
5433 outs() << "\n";
5434 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5435 } else {
5436 outs() << " (entends past the end of the section)\n";
5437 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5438 memcpy(&objc_class, r, left);
5439 }
5440 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5441 swapStruct(objc_class);
5442 print_objc_class_t(&objc_class, &info);
5443 } else {
5444 outs() << "(not in an __OBJC section)\n";
5445 }
5446 }
5447 }
5448 if (symtab.cat_def_cnt > 0)
5449 outs() << "\tCategory Definitions\n";
5450 for (j = 0; j < symtab.cat_def_cnt; j++) {
5451 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
5452 outs() << "\t(remaining category defs entries entends past the end of "
5453 << "the section)\n";
5454 break;
5455 }
5456 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
5457 sizeof(uint32_t));
5458 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5459 sys::swapByteOrder(def);
5460
5461 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5462 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
5463 << format("0x%08" PRIx32, def);
5464 if (r != nullptr) {
5465 if (left > sizeof(struct objc_category_t)) {
5466 outs() << "\n";
5467 memcpy(&objc_category, r, sizeof(struct objc_category_t));
5468 } else {
5469 outs() << " (entends past the end of the section)\n";
5470 memset(&objc_category, '\0', sizeof(struct objc_category_t));
5471 memcpy(&objc_category, r, left);
5472 }
5473 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5474 swapStruct(objc_category);
5475 print_objc_objc_category_t(&objc_category, &info);
5476 } else {
5477 outs() << "(not in an __OBJC section)\n";
5478 }
5479 }
5480 }
5481 const SectionRef II = get_section(O, "__OBJC", "__image_info");
5482 if (II != SectionRef())
5483 print_image_info(II, &info);
5484
5485 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005486}
5487
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00005488static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
5489 uint32_t size, uint32_t addr) {
5490 SymbolAddressMap AddrMap;
5491 CreateSymbolAddressMap(O, &AddrMap);
5492
5493 std::vector<SectionRef> Sections;
5494 for (const SectionRef &Section : O->sections()) {
5495 StringRef SectName;
5496 Section.getName(SectName);
5497 Sections.push_back(Section);
5498 }
5499
5500 struct DisassembleInfo info;
5501 // Set up the block of info used by the Symbolizer call backs.
5502 info.verbose = true;
5503 info.O = O;
5504 info.AddrMap = &AddrMap;
5505 info.Sections = &Sections;
5506 info.class_name = nullptr;
5507 info.selector_name = nullptr;
5508 info.method = nullptr;
5509 info.demangled_name = nullptr;
5510 info.bindtable = nullptr;
5511 info.adrp_addr = 0;
5512 info.adrp_inst = 0;
5513
5514 const char *p;
5515 struct objc_protocol_t protocol;
5516 uint32_t left, paddr;
5517 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
5518 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
5519 left = size - (p - sect);
5520 if (left < sizeof(struct objc_protocol_t)) {
5521 outs() << "Protocol extends past end of __protocol section\n";
5522 memcpy(&protocol, p, left);
5523 } else
5524 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
5525 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5526 swapStruct(protocol);
5527 paddr = addr + (p - sect);
5528 outs() << "Protocol " << format("0x%" PRIx32, paddr);
5529 if (print_protocol(paddr, 0, &info))
5530 outs() << "(not in an __OBJC section)\n";
5531 }
5532}
5533
Kevin Enderby0fc11822015-04-01 20:57:01 +00005534static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
5535 if (O->is64Bit())
5536 printObjc2_64bit_MetaData(O, verbose);
5537 else {
5538 MachO::mach_header H;
5539 H = O->getHeader();
5540 if (H.cputype == MachO::CPU_TYPE_ARM)
5541 printObjc2_32bit_MetaData(O, verbose);
5542 else {
5543 // This is the 32-bit non-arm cputype case. Which is normally
5544 // the first Objective-C ABI. But it may be the case of a
5545 // binary for the iOS simulator which is the second Objective-C
5546 // ABI. In that case printObjc1_32bit_MetaData() will determine that
5547 // and return false.
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005548 if (!printObjc1_32bit_MetaData(O, verbose))
Kevin Enderby0fc11822015-04-01 20:57:01 +00005549 printObjc2_32bit_MetaData(O, verbose);
5550 }
5551 }
5552}
5553
Kevin Enderbybf246f52014-09-24 23:08:22 +00005554// GuessLiteralPointer returns a string which for the item in the Mach-O file
5555// for the address passed in as ReferenceValue for printing as a comment with
5556// the instruction and also returns the corresponding type of that item
5557// indirectly through ReferenceType.
5558//
5559// If ReferenceValue is an address of literal cstring then a pointer to the
5560// cstring is returned and ReferenceType is set to
5561// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
5562//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005563// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
5564// Class ref that name is returned and the ReferenceType is set accordingly.
5565//
5566// Lastly, literals which are Symbol address in a literal pool are looked for
5567// and if found the symbol name is returned and ReferenceType is set to
5568// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
5569//
5570// If there is no item in the Mach-O file for the address passed in as
5571// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00005572static const char *GuessLiteralPointer(uint64_t ReferenceValue,
5573 uint64_t ReferencePC,
5574 uint64_t *ReferenceType,
5575 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00005576 // First see if there is an external relocation entry at the ReferencePC.
Rafael Espindola80291272014-10-08 15:28:58 +00005577 uint64_t sect_addr = info->S.getAddress();
Kevin Enderbybf246f52014-09-24 23:08:22 +00005578 uint64_t sect_offset = ReferencePC - sect_addr;
5579 bool reloc_found = false;
5580 DataRefImpl Rel;
5581 MachO::any_relocation_info RE;
5582 bool isExtern = false;
5583 SymbolRef Symbol;
5584 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00005585 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderbybf246f52014-09-24 23:08:22 +00005586 if (RelocOffset == sect_offset) {
5587 Rel = Reloc.getRawDataRefImpl();
5588 RE = info->O->getRelocation(Rel);
5589 if (info->O->isRelocationScattered(RE))
5590 continue;
5591 isExtern = info->O->getPlainRelocationExternal(RE);
5592 if (isExtern) {
5593 symbol_iterator RelocSym = Reloc.getSymbol();
5594 Symbol = *RelocSym;
5595 }
5596 reloc_found = true;
5597 break;
5598 }
5599 }
5600 // If there is an external relocation entry for a symbol in a section
5601 // then used that symbol's value for the value of the reference.
5602 if (reloc_found && isExtern) {
5603 if (info->O->getAnyRelocationPCRel(RE)) {
5604 unsigned Type = info->O->getAnyRelocationType(RE);
5605 if (Type == MachO::X86_64_RELOC_SIGNED) {
Rafael Espindoladea00162015-07-03 17:44:18 +00005606 ReferenceValue = Symbol.getValue();
Kevin Enderbybf246f52014-09-24 23:08:22 +00005607 }
5608 }
5609 }
5610
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005611 // Look for literals such as Objective-C CFStrings refs, Selector refs,
5612 // Message refs and Class refs.
5613 bool classref, selref, msgref, cfstring;
5614 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
5615 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00005616 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005617 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
5618 // And the pointer_value in that section is typically zero as it will be
5619 // set by dyld as part of the "bind information".
5620 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
5621 if (name != nullptr) {
5622 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00005623 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005624 if (class_name != nullptr && class_name[1] == '_' &&
5625 class_name[2] != '\0') {
5626 info->class_name = class_name + 2;
5627 return name;
5628 }
5629 }
5630 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005631
David Blaikie33dd45d02015-03-23 18:39:02 +00005632 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005633 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
5634 const char *name =
5635 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
5636 if (name != nullptr)
5637 info->class_name = name;
5638 else
5639 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00005640 return name;
5641 }
5642
David Blaikie33dd45d02015-03-23 18:39:02 +00005643 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005644 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
5645 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
5646 return name;
5647 }
5648
David Blaikie33dd45d02015-03-23 18:39:02 +00005649 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005650 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
5651
5652 if (pointer_value != 0)
5653 ReferenceValue = pointer_value;
5654
5655 const char *name = GuessCstringPointer(ReferenceValue, info);
5656 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00005657 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005658 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
5659 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00005660 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005661 info->class_name = nullptr;
5662 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
5663 info->selector_name = name;
5664 } else
5665 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
5666 return name;
5667 }
5668
5669 // Lastly look for an indirect symbol with this ReferenceValue which is in
5670 // a literal pool. If found return that symbol name.
5671 name = GuessIndirectSymbol(ReferenceValue, info);
5672 if (name) {
5673 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
5674 return name;
5675 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005676
5677 return nullptr;
5678}
5679
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005680// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00005681// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005682// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
5683// is created and returns the symbol name that matches the ReferenceValue or
5684// nullptr if none. The ReferenceType is passed in for the IN type of
5685// reference the instruction is making from the values in defined in the header
5686// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
5687// Out type and the ReferenceName will also be set which is added as a comment
5688// to the disassembled instruction.
5689//
Kevin Enderby04bf6932014-10-28 23:39:46 +00005690#if HAVE_CXXABI_H
5691// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005692// returned through ReferenceName and ReferenceType is set to
5693// LLVMDisassembler_ReferenceType_DeMangled_Name .
Kevin Enderby04bf6932014-10-28 23:39:46 +00005694#endif
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005695//
5696// When this is called to get a symbol name for a branch target then the
5697// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
5698// SymbolValue will be looked for in the indirect symbol table to determine if
5699// it is an address for a symbol stub. If so then the symbol name for that
5700// stub is returned indirectly through ReferenceName and then ReferenceType is
5701// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
5702//
Kevin Enderbybf246f52014-09-24 23:08:22 +00005703// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005704// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
5705// SymbolValue is checked to be an address of literal pointer, symbol pointer,
5706// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005707// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00005708static const char *SymbolizerSymbolLookUp(void *DisInfo,
5709 uint64_t ReferenceValue,
5710 uint64_t *ReferenceType,
5711 uint64_t ReferencePC,
5712 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005713 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00005714 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00005715 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00005716 *ReferenceName = nullptr;
5717 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005718 return nullptr;
5719 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005720
Kevin Enderbyf6d25852015-01-31 00:37:11 +00005721 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00005722
Kevin Enderby85974882014-09-26 22:20:44 +00005723 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
5724 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00005725 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005726 method_reference(info, ReferenceType, ReferenceName);
5727 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
5728 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
5729 } else
Kevin Enderby04bf6932014-10-28 23:39:46 +00005730#if HAVE_CXXABI_H
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005731 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00005732 if (info->demangled_name != nullptr)
5733 free(info->demangled_name);
5734 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005735 info->demangled_name =
5736 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00005737 if (info->demangled_name != nullptr) {
5738 *ReferenceName = info->demangled_name;
5739 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5740 } else
5741 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5742 } else
5743#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005744 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5745 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
5746 *ReferenceName =
5747 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00005748 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005749 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00005750 else
5751 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00005752 // If this is arm64 and the reference is an adrp instruction save the
5753 // instruction, passed in ReferenceValue and the address of the instruction
5754 // for use later if we see and add immediate instruction.
5755 } else if (info->O->getArch() == Triple::aarch64 &&
5756 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
5757 info->adrp_inst = ReferenceValue;
5758 info->adrp_addr = ReferencePC;
5759 SymbolName = nullptr;
5760 *ReferenceName = nullptr;
5761 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5762 // If this is arm64 and reference is an add immediate instruction and we
5763 // have
5764 // seen an adrp instruction just before it and the adrp's Xd register
5765 // matches
5766 // this add's Xn register reconstruct the value being referenced and look to
5767 // see if it is a literal pointer. Note the add immediate instruction is
5768 // passed in ReferenceValue.
5769 } else if (info->O->getArch() == Triple::aarch64 &&
5770 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
5771 ReferencePC - 4 == info->adrp_addr &&
5772 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5773 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5774 uint32_t addxri_inst;
5775 uint64_t adrp_imm, addxri_imm;
5776
5777 adrp_imm =
5778 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5779 if (info->adrp_inst & 0x0200000)
5780 adrp_imm |= 0xfffffffffc000000LL;
5781
5782 addxri_inst = ReferenceValue;
5783 addxri_imm = (addxri_inst >> 10) & 0xfff;
5784 if (((addxri_inst >> 22) & 0x3) == 1)
5785 addxri_imm <<= 12;
5786
5787 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5788 (adrp_imm << 12) + addxri_imm;
5789
5790 *ReferenceName =
5791 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5792 if (*ReferenceName == nullptr)
5793 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5794 // If this is arm64 and the reference is a load register instruction and we
5795 // have seen an adrp instruction just before it and the adrp's Xd register
5796 // matches this add's Xn register reconstruct the value being referenced and
5797 // look to see if it is a literal pointer. Note the load register
5798 // instruction is passed in ReferenceValue.
5799 } else if (info->O->getArch() == Triple::aarch64 &&
5800 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
5801 ReferencePC - 4 == info->adrp_addr &&
5802 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5803 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5804 uint32_t ldrxui_inst;
5805 uint64_t adrp_imm, ldrxui_imm;
5806
5807 adrp_imm =
5808 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5809 if (info->adrp_inst & 0x0200000)
5810 adrp_imm |= 0xfffffffffc000000LL;
5811
5812 ldrxui_inst = ReferenceValue;
5813 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
5814
5815 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5816 (adrp_imm << 12) + (ldrxui_imm << 3);
5817
5818 *ReferenceName =
5819 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5820 if (*ReferenceName == nullptr)
5821 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5822 }
5823 // If this arm64 and is an load register (PC-relative) instruction the
5824 // ReferenceValue is the PC plus the immediate value.
5825 else if (info->O->getArch() == Triple::aarch64 &&
5826 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
5827 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
5828 *ReferenceName =
5829 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5830 if (*ReferenceName == nullptr)
5831 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby85974882014-09-26 22:20:44 +00005832 }
Kevin Enderby04bf6932014-10-28 23:39:46 +00005833#if HAVE_CXXABI_H
5834 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
5835 if (info->demangled_name != nullptr)
5836 free(info->demangled_name);
5837 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005838 info->demangled_name =
5839 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00005840 if (info->demangled_name != nullptr) {
5841 *ReferenceName = info->demangled_name;
5842 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5843 }
5844 }
5845#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005846 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00005847 *ReferenceName = nullptr;
5848 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5849 }
5850
5851 return SymbolName;
5852}
5853
Kevin Enderbybf246f52014-09-24 23:08:22 +00005854/// \brief Emits the comments that are stored in the CommentStream.
5855/// Each comment in the CommentStream must end with a newline.
5856static void emitComments(raw_svector_ostream &CommentStream,
5857 SmallString<128> &CommentsToEmit,
5858 formatted_raw_ostream &FormattedOS,
5859 const MCAsmInfo &MAI) {
5860 // Flush the stream before taking its content.
Kevin Enderbybf246f52014-09-24 23:08:22 +00005861 StringRef Comments = CommentsToEmit.str();
5862 // Get the default information for printing a comment.
5863 const char *CommentBegin = MAI.getCommentString();
5864 unsigned CommentColumn = MAI.getCommentColumn();
5865 bool IsFirst = true;
5866 while (!Comments.empty()) {
5867 if (!IsFirst)
5868 FormattedOS << '\n';
5869 // Emit a line of comments.
5870 FormattedOS.PadToColumn(CommentColumn);
5871 size_t Position = Comments.find('\n');
5872 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
5873 // Move after the newline character.
5874 Comments = Comments.substr(Position + 1);
5875 IsFirst = false;
5876 }
5877 FormattedOS.flush();
5878
5879 // Tell the comment stream that the vector changed underneath it.
5880 CommentsToEmit.clear();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005881}
5882
Kevin Enderby95df54c2015-02-04 01:01:38 +00005883static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
5884 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005885 const char *McpuDefault = nullptr;
5886 const Target *ThumbTarget = nullptr;
5887 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005888 if (!TheTarget) {
5889 // GetTarget prints out stuff.
5890 return;
5891 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005892 if (MCPU.empty() && McpuDefault)
5893 MCPU = McpuDefault;
5894
Ahmed Charles56440fd2014-03-06 05:51:42 +00005895 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005896 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00005897 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005898 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005899
Kevin Enderbyc9595622014-08-06 23:24:41 +00005900 // Package up features to be passed to target/subtarget
5901 std::string FeaturesStr;
5902 if (MAttrs.size()) {
5903 SubtargetFeatures Features;
5904 for (unsigned i = 0; i != MAttrs.size(); ++i)
5905 Features.AddFeature(MAttrs[i]);
5906 FeaturesStr = Features.getString();
5907 }
5908
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005909 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00005910 std::unique_ptr<const MCRegisterInfo> MRI(
5911 TheTarget->createMCRegInfo(TripleName));
5912 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00005913 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00005914 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +00005915 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00005916 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005917 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005918 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005919 std::unique_ptr<MCSymbolizer> Symbolizer;
5920 struct DisassembleInfo SymbolizerInfo;
5921 std::unique_ptr<MCRelocationInfo> RelInfo(
5922 TheTarget->createMCRelocationInfo(TripleName, Ctx));
5923 if (RelInfo) {
5924 Symbolizer.reset(TheTarget->createMCSymbolizer(
5925 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00005926 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005927 DisAsm->setSymbolizer(std::move(Symbolizer));
5928 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005929 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00005930 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00005931 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00005932 // Set the display preference for hex vs. decimal immediates.
5933 IP->setPrintImmHex(PrintImmHex);
5934 // Comment stream and backing vector.
5935 SmallString<128> CommentsToEmit;
5936 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00005937 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
5938 // if it is done then arm64 comments for string literals don't get printed
5939 // and some constant get printed instead and not setting it causes intel
5940 // (32-bit and 64-bit) comments printed with different spacing before the
5941 // comment causing different diffs with the 'C' disassembler library API.
5942 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00005943
Kevin Enderbyae3c1262014-11-14 21:52:18 +00005944 if (!AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencerc1363cf2011-10-07 19:25:47 +00005945 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00005946 << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005947 return;
5948 }
5949
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005950 // Set up thumb disassembler.
5951 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
5952 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
5953 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00005954 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005955 std::unique_ptr<MCInstPrinter> ThumbIP;
5956 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00005957 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
5958 struct DisassembleInfo ThumbSymbolizerInfo;
5959 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005960 if (ThumbTarget) {
5961 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
5962 ThumbAsmInfo.reset(
5963 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
5964 ThumbSTI.reset(
5965 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
5966 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
5967 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00005968 MCContext *PtrThumbCtx = ThumbCtx.get();
5969 ThumbRelInfo.reset(
5970 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
5971 if (ThumbRelInfo) {
5972 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
5973 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00005974 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00005975 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
5976 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005977 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
5978 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00005979 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
5980 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00005981 // Set the display preference for hex vs. decimal immediates.
5982 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005983 }
5984
Kevin Enderbyae3c1262014-11-14 21:52:18 +00005985 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005986 errs() << "error: couldn't initialize disassembler for target "
5987 << ThumbTripleName << '\n';
5988 return;
5989 }
5990
Charles Davis8bdfafd2013-09-01 04:28:48 +00005991 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005992
Ahmed Bougachaaa790682013-05-24 01:07:04 +00005993 // FIXME: Using the -cfg command line option, this code used to be able to
5994 // annotate relocations with the referenced symbol's name, and if this was
5995 // inside a __[cf]string section, the data it points to. This is now replaced
5996 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00005997 std::vector<SectionRef> Sections;
5998 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005999 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00006000 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006001
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00006002 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
Kevin Enderby273ae012013-06-06 17:20:50 +00006003 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006004
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006005 // Sort the symbols by address, just in case they didn't come in that way.
Owen Andersond9243c42011-10-17 21:37:35 +00006006 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006007
Kevin Enderby273ae012013-06-06 17:20:50 +00006008 // Build a data in code table that is sorted on by the address of each entry.
6009 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00006010 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00006011 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00006012 else
6013 BaseAddress = BaseSegmentAddress;
6014 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00006015 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00006016 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006017 uint32_t Offset;
6018 DI->getOffset(Offset);
6019 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6020 }
6021 array_pod_sort(Dices.begin(), Dices.end());
6022
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006023#ifndef NDEBUG
6024 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6025#else
6026 raw_ostream &DebugOut = nulls();
6027#endif
6028
Ahmed Charles56440fd2014-03-06 05:51:42 +00006029 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00006030 ObjectFile *DbgObj = MachOOF;
Benjamin Kramer699128e2011-09-21 01:13:19 +00006031 // Try to find debug info and set up the DIContext for it.
6032 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00006033 // A separate DSym file path was specified, parse it as a macho file,
6034 // get the sections and supply it to the section name parsing machinery.
6035 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00006036 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006037 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00006038 if (std::error_code EC = BufOrErr.getError()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006039 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +00006040 return;
6041 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00006042 DbgObj =
6043 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
6044 .get()
6045 .release();
Benjamin Kramer699128e2011-09-21 01:13:19 +00006046 }
6047
Eric Christopher7370b552012-11-12 21:40:38 +00006048 // Setup the DIContext
Zachary Turner6489d7b2015-04-23 17:37:47 +00006049 diContext.reset(new DWARFContextInMemory(*DbgObj));
Benjamin Kramer699128e2011-09-21 01:13:19 +00006050 }
6051
Colin LeMahieufcc32762015-07-29 19:08:10 +00006052 if (FilterSections.size() == 0)
Kevin Enderby95df54c2015-02-04 01:01:38 +00006053 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006054
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006055 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00006056 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00006057 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6058 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006059
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006060 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006061
Rafael Espindolab0f76a42013-04-05 15:15:22 +00006062 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00006063 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006064 continue;
6065
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006066 StringRef BytesStr;
6067 Sections[SectIdx].getContents(BytesStr);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00006068 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6069 BytesStr.size());
Rafael Espindola80291272014-10-08 15:28:58 +00006070 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00006071
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006072 bool symbolTableWorked = false;
6073
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006074 // Parse relocations.
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00006075 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
6076 for (const RelocationRef &Reloc : Sections[SectIdx].relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00006077 uint64_t RelocOffset = Reloc.getOffset();
Rafael Espindola80291272014-10-08 15:28:58 +00006078 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Owen Andersond9243c42011-10-17 21:37:35 +00006079 RelocOffset -= SectionAddress;
6080
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00006081 symbol_iterator RelocSym = Reloc.getSymbol();
Owen Andersond9243c42011-10-17 21:37:35 +00006082
Rafael Espindola806f0062013-06-05 01:33:53 +00006083 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006084 }
6085 array_pod_sort(Relocs.begin(), Relocs.end());
6086
Kevin Enderbybf246f52014-09-24 23:08:22 +00006087 // Create a map of symbol addresses to symbol names for use by
6088 // the SymbolizerSymbolLookUp() routine.
6089 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00006090 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006091 for (const SymbolRef &Symbol : MachOOF->symbols()) {
Rafael Espindola2fa80cc2015-06-26 12:18:49 +00006092 SymbolRef::Type ST = Symbol.getType();
Kevin Enderbybf246f52014-09-24 23:08:22 +00006093 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
6094 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00006095 uint64_t Address = Symbol.getValue();
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006096 ErrorOr<StringRef> SymNameOrErr = Symbol.getName();
6097 if (std::error_code EC = SymNameOrErr.getError())
6098 report_fatal_error(EC.message());
6099 StringRef SymName = *SymNameOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006100 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00006101 if (!DisSymName.empty() && DisSymName == SymName)
6102 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006103 }
6104 }
David Blaikie33dd45d02015-03-23 18:39:02 +00006105 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00006106 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
6107 return;
6108 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006109 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006110 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006111 SymbolizerInfo.O = MachOOF;
6112 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00006113 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006114 SymbolizerInfo.Sections = &Sections;
6115 SymbolizerInfo.class_name = nullptr;
6116 SymbolizerInfo.selector_name = nullptr;
6117 SymbolizerInfo.method = nullptr;
Kevin Enderby04bf6932014-10-28 23:39:46 +00006118 SymbolizerInfo.demangled_name = nullptr;
Kevin Enderby078be602014-10-23 19:53:12 +00006119 SymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006120 SymbolizerInfo.adrp_addr = 0;
6121 SymbolizerInfo.adrp_inst = 0;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006122 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006123 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006124 ThumbSymbolizerInfo.O = MachOOF;
6125 ThumbSymbolizerInfo.S = Sections[SectIdx];
6126 ThumbSymbolizerInfo.AddrMap = &AddrMap;
6127 ThumbSymbolizerInfo.Sections = &Sections;
6128 ThumbSymbolizerInfo.class_name = nullptr;
6129 ThumbSymbolizerInfo.selector_name = nullptr;
6130 ThumbSymbolizerInfo.method = nullptr;
6131 ThumbSymbolizerInfo.demangled_name = nullptr;
6132 ThumbSymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006133 ThumbSymbolizerInfo.adrp_addr = 0;
6134 ThumbSymbolizerInfo.adrp_inst = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006135
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006136 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006137 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006138 ErrorOr<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
6139 if (std::error_code EC = SymNameOrErr.getError())
6140 report_fatal_error(EC.message());
6141 StringRef SymName = *SymNameOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00006142
Rafael Espindola2fa80cc2015-06-26 12:18:49 +00006143 SymbolRef::Type ST = Symbols[SymIdx].getType();
Owen Andersond9243c42011-10-17 21:37:35 +00006144 if (ST != SymbolRef::ST_Function)
6145 continue;
6146
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006147 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00006148 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Owen Andersond9243c42011-10-17 21:37:35 +00006149 if (!containsSym)
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006150 continue;
6151
Kevin Enderby6a221752015-03-17 17:10:57 +00006152 // If we are only disassembling one symbol see if this is that symbol.
6153 if (!DisSymName.empty() && DisSymName != SymName)
6154 continue;
6155
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006156 // Start at the address of the symbol relative to the section's address.
Rafael Espindoladea00162015-07-03 17:44:18 +00006157 uint64_t Start = Symbols[SymIdx].getValue();
Rafael Espindola80291272014-10-08 15:28:58 +00006158 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006159 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006160
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006161 // Stop disassembling either at the beginning of the next symbol or at
6162 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00006163 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00006164 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006165 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00006166 while (Symbols.size() > NextSymIdx) {
Rafael Espindola2fa80cc2015-06-26 12:18:49 +00006167 SymbolRef::Type NextSymType = Symbols[NextSymIdx].getType();
Owen Andersond9243c42011-10-17 21:37:35 +00006168 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00006169 containsNextSym =
6170 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Rafael Espindoladea00162015-07-03 17:44:18 +00006171 NextSym = Symbols[NextSymIdx].getValue();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006172 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006173 break;
6174 }
6175 ++NextSymIdx;
6176 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006177
Rafael Espindola80291272014-10-08 15:28:58 +00006178 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006179 uint64_t End = containsNextSym ? NextSym : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00006180 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006181
6182 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00006183
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006184 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
6185 bool isThumb =
6186 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
6187
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006188 outs() << SymName << ":\n";
6189 DILineInfo lastLine;
6190 for (uint64_t Index = Start; Index < End; Index += Size) {
6191 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00006192
Kevin Enderbybf246f52014-09-24 23:08:22 +00006193 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006194 if (!NoLeadingAddr) {
6195 if (FullLeadingAddr) {
6196 if (MachOOF->is64Bit())
6197 outs() << format("%016" PRIx64, PC);
6198 else
6199 outs() << format("%08" PRIx64, PC);
6200 } else {
6201 outs() << format("%8" PRIx64 ":", PC);
6202 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006203 }
6204 if (!NoShowRawInsn)
6205 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00006206
6207 // Check the data in code table here to see if this is data not an
6208 // instruction to be disassembled.
6209 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006210 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006211 dice_table_iterator DTI =
6212 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
6213 compareDiceTableEntries);
6214 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006215 uint16_t Length;
6216 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00006217 uint16_t Kind;
6218 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00006219 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00006220 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
6221 (PC == (DTI->first + Length - 1)) && (Length & 1))
6222 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00006223 continue;
6224 }
6225
Kevin Enderbybf246f52014-09-24 23:08:22 +00006226 SmallVector<char, 64> AnnotationsBytes;
6227 raw_svector_ostream Annotations(AnnotationsBytes);
6228
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006229 bool gotInst;
6230 if (isThumb)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006231 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006232 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006233 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006234 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00006235 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006236 if (gotInst) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006237 if (!NoShowRawInsn) {
Craig Topper0013be12015-09-21 05:32:41 +00006238 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006239 }
6240 formatted_raw_ostream FormattedOS(outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006241 StringRef AnnotationsStr = Annotations.str();
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006242 if (isThumb)
Akira Hatanakab46d0232015-03-27 20:36:02 +00006243 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006244 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00006245 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006246 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00006247
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006248 // Print debug info.
6249 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006250 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006251 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00006252 if (dli != lastLine && dli.Line != 0)
6253 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
6254 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006255 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006256 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006257 outs() << "\n";
6258 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006259 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006260 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006261 outs() << format("\t.byte 0x%02x #bad opcode\n",
6262 *(Bytes.data() + Index) & 0xff);
6263 Size = 1; // skip exactly one illegible byte and move on.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006264 } else if (Arch == Triple::aarch64) {
6265 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6266 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
6267 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
6268 (*(Bytes.data() + Index + 3) & 0xff) << 24;
6269 outs() << format("\t.long\t0x%08x\n", opcode);
6270 Size = 4;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006271 } else {
6272 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6273 if (Size == 0)
6274 Size = 1; // skip illegible bytes
6275 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006276 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006277 }
6278 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006279 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00006280 // Reading the symbol table didn't work, disassemble the whole section.
6281 uint64_t SectAddress = Sections[SectIdx].getAddress();
6282 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00006283 uint64_t InstSize;
6284 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00006285 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00006286
Kevin Enderbybf246f52014-09-24 23:08:22 +00006287 uint64_t PC = SectAddress + Index;
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006288 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
6289 DebugOut, nulls())) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006290 if (!NoLeadingAddr) {
6291 if (FullLeadingAddr) {
6292 if (MachOOF->is64Bit())
6293 outs() << format("%016" PRIx64, PC);
6294 else
6295 outs() << format("%08" PRIx64, PC);
6296 } else {
6297 outs() << format("%8" PRIx64 ":", PC);
6298 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006299 }
6300 if (!NoShowRawInsn) {
6301 outs() << "\t";
Craig Topper0013be12015-09-21 05:32:41 +00006302 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006303 }
Akira Hatanaka1d079942015-03-28 20:44:05 +00006304 IP->printInst(&Inst, outs(), "", *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00006305 outs() << "\n";
6306 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006307 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006308 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006309 outs() << format("\t.byte 0x%02x #bad opcode\n",
6310 *(Bytes.data() + Index) & 0xff);
6311 InstSize = 1; // skip exactly one illegible byte and move on.
6312 } else {
6313 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6314 if (InstSize == 0)
6315 InstSize = 1; // skip illegible bytes
6316 }
Bill Wendling4e68e062012-07-19 00:17:40 +00006317 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00006318 }
6319 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006320 // The TripleName's need to be reset if we are called again for a different
6321 // archtecture.
6322 TripleName = "";
6323 ThumbTripleName = "";
6324
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006325 if (SymbolizerInfo.method != nullptr)
6326 free(SymbolizerInfo.method);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006327 if (SymbolizerInfo.demangled_name != nullptr)
6328 free(SymbolizerInfo.demangled_name);
Kevin Enderby078be602014-10-23 19:53:12 +00006329 if (SymbolizerInfo.bindtable != nullptr)
6330 delete SymbolizerInfo.bindtable;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006331 if (ThumbSymbolizerInfo.method != nullptr)
6332 free(ThumbSymbolizerInfo.method);
6333 if (ThumbSymbolizerInfo.demangled_name != nullptr)
6334 free(ThumbSymbolizerInfo.demangled_name);
6335 if (ThumbSymbolizerInfo.bindtable != nullptr)
6336 delete ThumbSymbolizerInfo.bindtable;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006337 }
6338}
Tim Northover4bd286a2014-08-01 13:07:19 +00006339
Tim Northover39c70bb2014-08-12 11:52:59 +00006340//===----------------------------------------------------------------------===//
6341// __compact_unwind section dumping
6342//===----------------------------------------------------------------------===//
6343
Tim Northover4bd286a2014-08-01 13:07:19 +00006344namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00006345
6346template <typename T> static uint64_t readNext(const char *&Buf) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006347 using llvm::support::little;
6348 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00006349
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006350 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
6351 Buf += sizeof(T);
6352 return Val;
6353}
Tim Northover39c70bb2014-08-12 11:52:59 +00006354
Tim Northover4bd286a2014-08-01 13:07:19 +00006355struct CompactUnwindEntry {
6356 uint32_t OffsetInSection;
6357
6358 uint64_t FunctionAddr;
6359 uint32_t Length;
6360 uint32_t CompactEncoding;
6361 uint64_t PersonalityAddr;
6362 uint64_t LSDAAddr;
6363
6364 RelocationRef FunctionReloc;
6365 RelocationRef PersonalityReloc;
6366 RelocationRef LSDAReloc;
6367
6368 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006369 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006370 if (Is64)
6371 read<uint64_t>(Contents.data() + Offset);
6372 else
6373 read<uint32_t>(Contents.data() + Offset);
6374 }
6375
6376private:
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006377 template <typename UIntPtr> void read(const char *Buf) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006378 FunctionAddr = readNext<UIntPtr>(Buf);
6379 Length = readNext<uint32_t>(Buf);
6380 CompactEncoding = readNext<uint32_t>(Buf);
6381 PersonalityAddr = readNext<UIntPtr>(Buf);
6382 LSDAAddr = readNext<UIntPtr>(Buf);
6383 }
6384};
6385}
6386
6387/// Given a relocation from __compact_unwind, consisting of the RelocationRef
6388/// and data being relocated, determine the best base Name and Addend to use for
6389/// display purposes.
6390///
6391/// 1. An Extern relocation will directly reference a symbol (and the data is
6392/// then already an addend), so use that.
6393/// 2. Otherwise the data is an offset in the object file's layout; try to find
6394// a symbol before it in the same section, and use the offset from there.
6395/// 3. Finally, if all that fails, fall back to an offset from the start of the
6396/// referenced section.
6397static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
6398 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006399 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00006400 StringRef &Name, uint64_t &Addend) {
6401 if (Reloc.getSymbol() != Obj->symbol_end()) {
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006402 ErrorOr<StringRef> NameOrErr = Reloc.getSymbol()->getName();
6403 if (std::error_code EC = NameOrErr.getError())
6404 report_fatal_error(EC.message());
6405 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00006406 Addend = Addr;
6407 return;
6408 }
6409
6410 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
Keno Fischerc780e8e2015-05-21 21:24:32 +00006411 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
Tim Northover4bd286a2014-08-01 13:07:19 +00006412
Rafael Espindola80291272014-10-08 15:28:58 +00006413 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00006414
6415 auto Sym = Symbols.upper_bound(Addr);
6416 if (Sym == Symbols.begin()) {
6417 // The first symbol in the object is after this reference, the best we can
6418 // do is section-relative notation.
6419 RelocSection.getName(Name);
6420 Addend = Addr - SectionAddr;
6421 return;
6422 }
6423
6424 // Go back one so that SymbolAddress <= Addr.
6425 --Sym;
6426
Rafael Espindola8bab8892015-08-07 23:27:14 +00006427 section_iterator SymSection = *Sym->second.getSection();
Tim Northover4bd286a2014-08-01 13:07:19 +00006428 if (RelocSection == *SymSection) {
6429 // There's a valid symbol in the same section before this reference.
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006430 ErrorOr<StringRef> NameOrErr = Sym->second.getName();
6431 if (std::error_code EC = NameOrErr.getError())
6432 report_fatal_error(EC.message());
6433 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00006434 Addend = Addr - Sym->first;
6435 return;
6436 }
6437
6438 // There is a symbol before this reference, but it's in a different
6439 // section. Probably not helpful to mention it, so use the section name.
6440 RelocSection.getName(Name);
6441 Addend = Addr - SectionAddr;
6442}
6443
6444static void printUnwindRelocDest(const MachOObjectFile *Obj,
6445 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006446 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006447 StringRef Name;
6448 uint64_t Addend;
6449
Rafael Espindola854038e2015-06-26 14:51:16 +00006450 if (!Reloc.getObject())
Tim Northover0b0add52014-09-09 10:45:06 +00006451 return;
6452
Tim Northover4bd286a2014-08-01 13:07:19 +00006453 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
6454
6455 outs() << Name;
6456 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00006457 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00006458}
6459
6460static void
6461printMachOCompactUnwindSection(const MachOObjectFile *Obj,
6462 std::map<uint64_t, SymbolRef> &Symbols,
6463 const SectionRef &CompactUnwind) {
6464
6465 assert(Obj->isLittleEndian() &&
6466 "There should not be a big-endian .o with __compact_unwind");
6467
6468 bool Is64 = Obj->is64Bit();
6469 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
6470 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
6471
6472 StringRef Contents;
6473 CompactUnwind.getContents(Contents);
6474
6475 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
6476
6477 // First populate the initial raw offsets, encodings and so on from the entry.
6478 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
6479 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
6480 CompactUnwinds.push_back(Entry);
6481 }
6482
6483 // Next we need to look at the relocations to find out what objects are
6484 // actually being referred to.
6485 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00006486 uint64_t RelocAddress = Reloc.getOffset();
Tim Northover4bd286a2014-08-01 13:07:19 +00006487
6488 uint32_t EntryIdx = RelocAddress / EntrySize;
6489 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
6490 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
6491
6492 if (OffsetInEntry == 0)
6493 Entry.FunctionReloc = Reloc;
6494 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
6495 Entry.PersonalityReloc = Reloc;
6496 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
6497 Entry.LSDAReloc = Reloc;
6498 else
6499 llvm_unreachable("Unexpected relocation in __compact_unwind section");
6500 }
6501
6502 // Finally, we're ready to print the data we've gathered.
6503 outs() << "Contents of __compact_unwind section:\n";
6504 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00006505 outs() << " Entry at offset "
6506 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00006507
6508 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006509 outs() << " start: " << format("0x%" PRIx64,
6510 Entry.FunctionAddr) << ' ';
6511 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00006512 outs() << '\n';
6513
6514 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006515 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
6516 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00006517 // 3. The 32-bit compact encoding.
6518 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00006519 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00006520
6521 // 4. The personality function, if present.
Rafael Espindola854038e2015-06-26 14:51:16 +00006522 if (Entry.PersonalityReloc.getObject()) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006523 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00006524 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00006525 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
6526 Entry.PersonalityAddr);
6527 outs() << '\n';
6528 }
6529
6530 // 5. This entry's language-specific data area.
Rafael Espindola854038e2015-06-26 14:51:16 +00006531 if (Entry.LSDAReloc.getObject()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006532 outs() << " LSDA: " << format("0x%" PRIx64,
6533 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00006534 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
6535 outs() << '\n';
6536 }
6537 }
6538}
6539
Tim Northover39c70bb2014-08-12 11:52:59 +00006540//===----------------------------------------------------------------------===//
6541// __unwind_info section dumping
6542//===----------------------------------------------------------------------===//
6543
6544static void printRegularSecondLevelUnwindPage(const char *PageStart) {
6545 const char *Pos = PageStart;
6546 uint32_t Kind = readNext<uint32_t>(Pos);
6547 (void)Kind;
6548 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
6549
6550 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6551 uint16_t NumEntries = readNext<uint16_t>(Pos);
6552
6553 Pos = PageStart + EntriesStart;
6554 for (unsigned i = 0; i < NumEntries; ++i) {
6555 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6556 uint32_t Encoding = readNext<uint32_t>(Pos);
6557
6558 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006559 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6560 << ", "
6561 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006562 }
6563}
6564
6565static void printCompressedSecondLevelUnwindPage(
6566 const char *PageStart, uint32_t FunctionBase,
6567 const SmallVectorImpl<uint32_t> &CommonEncodings) {
6568 const char *Pos = PageStart;
6569 uint32_t Kind = readNext<uint32_t>(Pos);
6570 (void)Kind;
6571 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
6572
6573 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6574 uint16_t NumEntries = readNext<uint16_t>(Pos);
6575
6576 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
6577 readNext<uint16_t>(Pos);
Aaron Ballman80930af2014-08-14 13:53:19 +00006578 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
6579 PageStart + EncodingsStart);
Tim Northover39c70bb2014-08-12 11:52:59 +00006580
6581 Pos = PageStart + EntriesStart;
6582 for (unsigned i = 0; i < NumEntries; ++i) {
6583 uint32_t Entry = readNext<uint32_t>(Pos);
6584 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
6585 uint32_t EncodingIdx = Entry >> 24;
6586
6587 uint32_t Encoding;
6588 if (EncodingIdx < CommonEncodings.size())
6589 Encoding = CommonEncodings[EncodingIdx];
6590 else
6591 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
6592
6593 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006594 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6595 << ", "
6596 << "encoding[" << EncodingIdx
6597 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006598 }
6599}
6600
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006601static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
6602 std::map<uint64_t, SymbolRef> &Symbols,
6603 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00006604
6605 assert(Obj->isLittleEndian() &&
6606 "There should not be a big-endian .o with __unwind_info");
6607
6608 outs() << "Contents of __unwind_info section:\n";
6609
6610 StringRef Contents;
6611 UnwindInfo.getContents(Contents);
6612 const char *Pos = Contents.data();
6613
6614 //===----------------------------------
6615 // Section header
6616 //===----------------------------------
6617
6618 uint32_t Version = readNext<uint32_t>(Pos);
6619 outs() << " Version: "
6620 << format("0x%" PRIx32, Version) << '\n';
6621 assert(Version == 1 && "only understand version 1");
6622
6623 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
6624 outs() << " Common encodings array section offset: "
6625 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
6626 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
6627 outs() << " Number of common encodings in array: "
6628 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
6629
6630 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
6631 outs() << " Personality function array section offset: "
6632 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
6633 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
6634 outs() << " Number of personality functions in array: "
6635 << format("0x%" PRIx32, NumPersonalities) << '\n';
6636
6637 uint32_t IndicesStart = readNext<uint32_t>(Pos);
6638 outs() << " Index array section offset: "
6639 << format("0x%" PRIx32, IndicesStart) << '\n';
6640 uint32_t NumIndices = readNext<uint32_t>(Pos);
6641 outs() << " Number of indices in array: "
6642 << format("0x%" PRIx32, NumIndices) << '\n';
6643
6644 //===----------------------------------
6645 // A shared list of common encodings
6646 //===----------------------------------
6647
6648 // These occupy indices in the range [0, N] whenever an encoding is referenced
6649 // from a compressed 2nd level index table. In practice the linker only
6650 // creates ~128 of these, so that indices are available to embed encodings in
6651 // the 2nd level index.
6652
6653 SmallVector<uint32_t, 64> CommonEncodings;
6654 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
6655 Pos = Contents.data() + CommonEncodingsStart;
6656 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
6657 uint32_t Encoding = readNext<uint32_t>(Pos);
6658 CommonEncodings.push_back(Encoding);
6659
6660 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
6661 << '\n';
6662 }
6663
Tim Northover39c70bb2014-08-12 11:52:59 +00006664 //===----------------------------------
6665 // Personality functions used in this executable
6666 //===----------------------------------
6667
6668 // There should be only a handful of these (one per source language,
6669 // roughly). Particularly since they only get 2 bits in the compact encoding.
6670
6671 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
6672 Pos = Contents.data() + PersonalitiesStart;
6673 for (unsigned i = 0; i < NumPersonalities; ++i) {
6674 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
6675 outs() << " personality[" << i + 1
6676 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
6677 }
6678
6679 //===----------------------------------
6680 // The level 1 index entries
6681 //===----------------------------------
6682
6683 // These specify an approximate place to start searching for the more detailed
6684 // information, sorted by PC.
6685
6686 struct IndexEntry {
6687 uint32_t FunctionOffset;
6688 uint32_t SecondLevelPageStart;
6689 uint32_t LSDAStart;
6690 };
6691
6692 SmallVector<IndexEntry, 4> IndexEntries;
6693
6694 outs() << " Top level indices: (count = " << NumIndices << ")\n";
6695 Pos = Contents.data() + IndicesStart;
6696 for (unsigned i = 0; i < NumIndices; ++i) {
6697 IndexEntry Entry;
6698
6699 Entry.FunctionOffset = readNext<uint32_t>(Pos);
6700 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
6701 Entry.LSDAStart = readNext<uint32_t>(Pos);
6702 IndexEntries.push_back(Entry);
6703
6704 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006705 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
6706 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00006707 << "2nd level page offset="
6708 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006709 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006710 }
6711
Tim Northover39c70bb2014-08-12 11:52:59 +00006712 //===----------------------------------
6713 // Next come the LSDA tables
6714 //===----------------------------------
6715
6716 // The LSDA layout is rather implicit: it's a contiguous array of entries from
6717 // the first top-level index's LSDAOffset to the last (sentinel).
6718
6719 outs() << " LSDA descriptors:\n";
6720 Pos = Contents.data() + IndexEntries[0].LSDAStart;
6721 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
6722 (2 * sizeof(uint32_t));
6723 for (int i = 0; i < NumLSDAs; ++i) {
6724 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6725 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
6726 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006727 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6728 << ", "
6729 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006730 }
6731
6732 //===----------------------------------
6733 // Finally, the 2nd level indices
6734 //===----------------------------------
6735
6736 // Generally these are 4K in size, and have 2 possible forms:
6737 // + Regular stores up to 511 entries with disparate encodings
6738 // + Compressed stores up to 1021 entries if few enough compact encoding
6739 // values are used.
6740 outs() << " Second level indices:\n";
6741 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
6742 // The final sentinel top-level index has no associated 2nd level page
6743 if (IndexEntries[i].SecondLevelPageStart == 0)
6744 break;
6745
6746 outs() << " Second level index[" << i << "]: "
6747 << "offset in section="
6748 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
6749 << ", "
6750 << "base function offset="
6751 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
6752
6753 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
Aaron Ballman80930af2014-08-14 13:53:19 +00006754 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00006755 if (Kind == 2)
6756 printRegularSecondLevelUnwindPage(Pos);
6757 else if (Kind == 3)
6758 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
6759 CommonEncodings);
6760 else
6761 llvm_unreachable("Do not know how to print this kind of 2nd level page");
Tim Northover39c70bb2014-08-12 11:52:59 +00006762 }
6763}
6764
Tim Northover4bd286a2014-08-01 13:07:19 +00006765void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
6766 std::map<uint64_t, SymbolRef> Symbols;
6767 for (const SymbolRef &SymRef : Obj->symbols()) {
6768 // Discard any undefined or absolute symbols. They're not going to take part
6769 // in the convenience lookup for unwind info and just take up resources.
Rafael Espindola8bab8892015-08-07 23:27:14 +00006770 section_iterator Section = *SymRef.getSection();
Tim Northover4bd286a2014-08-01 13:07:19 +00006771 if (Section == Obj->section_end())
6772 continue;
6773
Rafael Espindoladea00162015-07-03 17:44:18 +00006774 uint64_t Addr = SymRef.getValue();
Tim Northover4bd286a2014-08-01 13:07:19 +00006775 Symbols.insert(std::make_pair(Addr, SymRef));
6776 }
6777
6778 for (const SectionRef &Section : Obj->sections()) {
6779 StringRef SectName;
6780 Section.getName(SectName);
6781 if (SectName == "__compact_unwind")
6782 printMachOCompactUnwindSection(Obj, Symbols, Section);
6783 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00006784 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00006785 else if (SectName == "__eh_frame")
6786 outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00006787 }
6788}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00006789
6790static void PrintMachHeader(uint32_t magic, uint32_t cputype,
6791 uint32_t cpusubtype, uint32_t filetype,
6792 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
6793 bool verbose) {
6794 outs() << "Mach header\n";
6795 outs() << " magic cputype cpusubtype caps filetype ncmds "
6796 "sizeofcmds flags\n";
6797 if (verbose) {
6798 if (magic == MachO::MH_MAGIC)
6799 outs() << " MH_MAGIC";
6800 else if (magic == MachO::MH_MAGIC_64)
6801 outs() << "MH_MAGIC_64";
6802 else
6803 outs() << format(" 0x%08" PRIx32, magic);
6804 switch (cputype) {
6805 case MachO::CPU_TYPE_I386:
6806 outs() << " I386";
6807 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6808 case MachO::CPU_SUBTYPE_I386_ALL:
6809 outs() << " ALL";
6810 break;
6811 default:
6812 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6813 break;
6814 }
6815 break;
6816 case MachO::CPU_TYPE_X86_64:
6817 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00006818 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6819 case MachO::CPU_SUBTYPE_X86_64_ALL:
6820 outs() << " ALL";
6821 break;
6822 case MachO::CPU_SUBTYPE_X86_64_H:
6823 outs() << " Haswell";
6824 break;
6825 default:
6826 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6827 break;
6828 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00006829 break;
6830 case MachO::CPU_TYPE_ARM:
6831 outs() << " ARM";
6832 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6833 case MachO::CPU_SUBTYPE_ARM_ALL:
6834 outs() << " ALL";
6835 break;
6836 case MachO::CPU_SUBTYPE_ARM_V4T:
6837 outs() << " V4T";
6838 break;
6839 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
6840 outs() << " V5TEJ";
6841 break;
6842 case MachO::CPU_SUBTYPE_ARM_XSCALE:
6843 outs() << " XSCALE";
6844 break;
6845 case MachO::CPU_SUBTYPE_ARM_V6:
6846 outs() << " V6";
6847 break;
6848 case MachO::CPU_SUBTYPE_ARM_V6M:
6849 outs() << " V6M";
6850 break;
6851 case MachO::CPU_SUBTYPE_ARM_V7:
6852 outs() << " V7";
6853 break;
6854 case MachO::CPU_SUBTYPE_ARM_V7EM:
6855 outs() << " V7EM";
6856 break;
6857 case MachO::CPU_SUBTYPE_ARM_V7K:
6858 outs() << " V7K";
6859 break;
6860 case MachO::CPU_SUBTYPE_ARM_V7M:
6861 outs() << " V7M";
6862 break;
6863 case MachO::CPU_SUBTYPE_ARM_V7S:
6864 outs() << " V7S";
6865 break;
6866 default:
6867 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6868 break;
6869 }
6870 break;
6871 case MachO::CPU_TYPE_ARM64:
6872 outs() << " ARM64";
6873 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6874 case MachO::CPU_SUBTYPE_ARM64_ALL:
6875 outs() << " ALL";
6876 break;
6877 default:
6878 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6879 break;
6880 }
6881 break;
6882 case MachO::CPU_TYPE_POWERPC:
6883 outs() << " PPC";
6884 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6885 case MachO::CPU_SUBTYPE_POWERPC_ALL:
6886 outs() << " ALL";
6887 break;
6888 default:
6889 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6890 break;
6891 }
6892 break;
6893 case MachO::CPU_TYPE_POWERPC64:
6894 outs() << " PPC64";
6895 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6896 case MachO::CPU_SUBTYPE_POWERPC_ALL:
6897 outs() << " ALL";
6898 break;
6899 default:
6900 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6901 break;
6902 }
6903 break;
6904 }
6905 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00006906 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00006907 } else {
6908 outs() << format(" 0x%02" PRIx32,
6909 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
6910 }
6911 switch (filetype) {
6912 case MachO::MH_OBJECT:
6913 outs() << " OBJECT";
6914 break;
6915 case MachO::MH_EXECUTE:
6916 outs() << " EXECUTE";
6917 break;
6918 case MachO::MH_FVMLIB:
6919 outs() << " FVMLIB";
6920 break;
6921 case MachO::MH_CORE:
6922 outs() << " CORE";
6923 break;
6924 case MachO::MH_PRELOAD:
6925 outs() << " PRELOAD";
6926 break;
6927 case MachO::MH_DYLIB:
6928 outs() << " DYLIB";
6929 break;
6930 case MachO::MH_DYLIB_STUB:
6931 outs() << " DYLIB_STUB";
6932 break;
6933 case MachO::MH_DYLINKER:
6934 outs() << " DYLINKER";
6935 break;
6936 case MachO::MH_BUNDLE:
6937 outs() << " BUNDLE";
6938 break;
6939 case MachO::MH_DSYM:
6940 outs() << " DSYM";
6941 break;
6942 case MachO::MH_KEXT_BUNDLE:
6943 outs() << " KEXTBUNDLE";
6944 break;
6945 default:
6946 outs() << format(" %10u", filetype);
6947 break;
6948 }
6949 outs() << format(" %5u", ncmds);
6950 outs() << format(" %10u", sizeofcmds);
6951 uint32_t f = flags;
6952 if (f & MachO::MH_NOUNDEFS) {
6953 outs() << " NOUNDEFS";
6954 f &= ~MachO::MH_NOUNDEFS;
6955 }
6956 if (f & MachO::MH_INCRLINK) {
6957 outs() << " INCRLINK";
6958 f &= ~MachO::MH_INCRLINK;
6959 }
6960 if (f & MachO::MH_DYLDLINK) {
6961 outs() << " DYLDLINK";
6962 f &= ~MachO::MH_DYLDLINK;
6963 }
6964 if (f & MachO::MH_BINDATLOAD) {
6965 outs() << " BINDATLOAD";
6966 f &= ~MachO::MH_BINDATLOAD;
6967 }
6968 if (f & MachO::MH_PREBOUND) {
6969 outs() << " PREBOUND";
6970 f &= ~MachO::MH_PREBOUND;
6971 }
6972 if (f & MachO::MH_SPLIT_SEGS) {
6973 outs() << " SPLIT_SEGS";
6974 f &= ~MachO::MH_SPLIT_SEGS;
6975 }
6976 if (f & MachO::MH_LAZY_INIT) {
6977 outs() << " LAZY_INIT";
6978 f &= ~MachO::MH_LAZY_INIT;
6979 }
6980 if (f & MachO::MH_TWOLEVEL) {
6981 outs() << " TWOLEVEL";
6982 f &= ~MachO::MH_TWOLEVEL;
6983 }
6984 if (f & MachO::MH_FORCE_FLAT) {
6985 outs() << " FORCE_FLAT";
6986 f &= ~MachO::MH_FORCE_FLAT;
6987 }
6988 if (f & MachO::MH_NOMULTIDEFS) {
6989 outs() << " NOMULTIDEFS";
6990 f &= ~MachO::MH_NOMULTIDEFS;
6991 }
6992 if (f & MachO::MH_NOFIXPREBINDING) {
6993 outs() << " NOFIXPREBINDING";
6994 f &= ~MachO::MH_NOFIXPREBINDING;
6995 }
6996 if (f & MachO::MH_PREBINDABLE) {
6997 outs() << " PREBINDABLE";
6998 f &= ~MachO::MH_PREBINDABLE;
6999 }
7000 if (f & MachO::MH_ALLMODSBOUND) {
7001 outs() << " ALLMODSBOUND";
7002 f &= ~MachO::MH_ALLMODSBOUND;
7003 }
7004 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
7005 outs() << " SUBSECTIONS_VIA_SYMBOLS";
7006 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
7007 }
7008 if (f & MachO::MH_CANONICAL) {
7009 outs() << " CANONICAL";
7010 f &= ~MachO::MH_CANONICAL;
7011 }
7012 if (f & MachO::MH_WEAK_DEFINES) {
7013 outs() << " WEAK_DEFINES";
7014 f &= ~MachO::MH_WEAK_DEFINES;
7015 }
7016 if (f & MachO::MH_BINDS_TO_WEAK) {
7017 outs() << " BINDS_TO_WEAK";
7018 f &= ~MachO::MH_BINDS_TO_WEAK;
7019 }
7020 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
7021 outs() << " ALLOW_STACK_EXECUTION";
7022 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
7023 }
7024 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
7025 outs() << " DEAD_STRIPPABLE_DYLIB";
7026 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
7027 }
7028 if (f & MachO::MH_PIE) {
7029 outs() << " PIE";
7030 f &= ~MachO::MH_PIE;
7031 }
7032 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
7033 outs() << " NO_REEXPORTED_DYLIBS";
7034 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
7035 }
7036 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
7037 outs() << " MH_HAS_TLV_DESCRIPTORS";
7038 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
7039 }
7040 if (f & MachO::MH_NO_HEAP_EXECUTION) {
7041 outs() << " MH_NO_HEAP_EXECUTION";
7042 f &= ~MachO::MH_NO_HEAP_EXECUTION;
7043 }
7044 if (f & MachO::MH_APP_EXTENSION_SAFE) {
7045 outs() << " APP_EXTENSION_SAFE";
7046 f &= ~MachO::MH_APP_EXTENSION_SAFE;
7047 }
7048 if (f != 0 || flags == 0)
7049 outs() << format(" 0x%08" PRIx32, f);
7050 } else {
7051 outs() << format(" 0x%08" PRIx32, magic);
7052 outs() << format(" %7d", cputype);
7053 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7054 outs() << format(" 0x%02" PRIx32,
7055 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7056 outs() << format(" %10u", filetype);
7057 outs() << format(" %5u", ncmds);
7058 outs() << format(" %10u", sizeofcmds);
7059 outs() << format(" 0x%08" PRIx32, flags);
7060 }
7061 outs() << "\n";
7062}
7063
Kevin Enderby956366c2014-08-29 22:30:52 +00007064static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
7065 StringRef SegName, uint64_t vmaddr,
7066 uint64_t vmsize, uint64_t fileoff,
7067 uint64_t filesize, uint32_t maxprot,
7068 uint32_t initprot, uint32_t nsects,
7069 uint32_t flags, uint32_t object_size,
7070 bool verbose) {
7071 uint64_t expected_cmdsize;
7072 if (cmd == MachO::LC_SEGMENT) {
7073 outs() << " cmd LC_SEGMENT\n";
7074 expected_cmdsize = nsects;
7075 expected_cmdsize *= sizeof(struct MachO::section);
7076 expected_cmdsize += sizeof(struct MachO::segment_command);
7077 } else {
7078 outs() << " cmd LC_SEGMENT_64\n";
7079 expected_cmdsize = nsects;
7080 expected_cmdsize *= sizeof(struct MachO::section_64);
7081 expected_cmdsize += sizeof(struct MachO::segment_command_64);
7082 }
7083 outs() << " cmdsize " << cmdsize;
7084 if (cmdsize != expected_cmdsize)
7085 outs() << " Inconsistent size\n";
7086 else
7087 outs() << "\n";
7088 outs() << " segname " << SegName << "\n";
7089 if (cmd == MachO::LC_SEGMENT_64) {
7090 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
7091 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
7092 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00007093 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
7094 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00007095 }
7096 outs() << " fileoff " << fileoff;
7097 if (fileoff > object_size)
7098 outs() << " (past end of file)\n";
7099 else
7100 outs() << "\n";
7101 outs() << " filesize " << filesize;
7102 if (fileoff + filesize > object_size)
7103 outs() << " (past end of file)\n";
7104 else
7105 outs() << "\n";
7106 if (verbose) {
7107 if ((maxprot &
7108 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7109 MachO::VM_PROT_EXECUTE)) != 0)
7110 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
7111 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00007112 outs() << " maxprot ";
7113 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
7114 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7115 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007116 }
7117 if ((initprot &
7118 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7119 MachO::VM_PROT_EXECUTE)) != 0)
7120 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
7121 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00007122 outs() << " initprot ";
7123 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
7124 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7125 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007126 }
7127 } else {
7128 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
7129 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
7130 }
7131 outs() << " nsects " << nsects << "\n";
7132 if (verbose) {
7133 outs() << " flags";
7134 if (flags == 0)
7135 outs() << " (none)\n";
7136 else {
7137 if (flags & MachO::SG_HIGHVM) {
7138 outs() << " HIGHVM";
7139 flags &= ~MachO::SG_HIGHVM;
7140 }
7141 if (flags & MachO::SG_FVMLIB) {
7142 outs() << " FVMLIB";
7143 flags &= ~MachO::SG_FVMLIB;
7144 }
7145 if (flags & MachO::SG_NORELOC) {
7146 outs() << " NORELOC";
7147 flags &= ~MachO::SG_NORELOC;
7148 }
7149 if (flags & MachO::SG_PROTECTED_VERSION_1) {
7150 outs() << " PROTECTED_VERSION_1";
7151 flags &= ~MachO::SG_PROTECTED_VERSION_1;
7152 }
7153 if (flags)
7154 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
7155 else
7156 outs() << "\n";
7157 }
7158 } else {
7159 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
7160 }
7161}
7162
7163static void PrintSection(const char *sectname, const char *segname,
7164 uint64_t addr, uint64_t size, uint32_t offset,
7165 uint32_t align, uint32_t reloff, uint32_t nreloc,
7166 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
7167 uint32_t cmd, const char *sg_segname,
7168 uint32_t filetype, uint32_t object_size,
7169 bool verbose) {
7170 outs() << "Section\n";
7171 outs() << " sectname " << format("%.16s\n", sectname);
7172 outs() << " segname " << format("%.16s", segname);
7173 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
7174 outs() << " (does not match segment)\n";
7175 else
7176 outs() << "\n";
7177 if (cmd == MachO::LC_SEGMENT_64) {
7178 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
7179 outs() << " size " << format("0x%016" PRIx64, size);
7180 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00007181 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
7182 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00007183 }
7184 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
7185 outs() << " (past end of file)\n";
7186 else
7187 outs() << "\n";
7188 outs() << " offset " << offset;
7189 if (offset > object_size)
7190 outs() << " (past end of file)\n";
7191 else
7192 outs() << "\n";
7193 uint32_t align_shifted = 1 << align;
7194 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
7195 outs() << " reloff " << reloff;
7196 if (reloff > object_size)
7197 outs() << " (past end of file)\n";
7198 else
7199 outs() << "\n";
7200 outs() << " nreloc " << nreloc;
7201 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
7202 outs() << " (past end of file)\n";
7203 else
7204 outs() << "\n";
7205 uint32_t section_type = flags & MachO::SECTION_TYPE;
7206 if (verbose) {
7207 outs() << " type";
7208 if (section_type == MachO::S_REGULAR)
7209 outs() << " S_REGULAR\n";
7210 else if (section_type == MachO::S_ZEROFILL)
7211 outs() << " S_ZEROFILL\n";
7212 else if (section_type == MachO::S_CSTRING_LITERALS)
7213 outs() << " S_CSTRING_LITERALS\n";
7214 else if (section_type == MachO::S_4BYTE_LITERALS)
7215 outs() << " S_4BYTE_LITERALS\n";
7216 else if (section_type == MachO::S_8BYTE_LITERALS)
7217 outs() << " S_8BYTE_LITERALS\n";
7218 else if (section_type == MachO::S_16BYTE_LITERALS)
7219 outs() << " S_16BYTE_LITERALS\n";
7220 else if (section_type == MachO::S_LITERAL_POINTERS)
7221 outs() << " S_LITERAL_POINTERS\n";
7222 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
7223 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
7224 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
7225 outs() << " S_LAZY_SYMBOL_POINTERS\n";
7226 else if (section_type == MachO::S_SYMBOL_STUBS)
7227 outs() << " S_SYMBOL_STUBS\n";
7228 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
7229 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
7230 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
7231 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
7232 else if (section_type == MachO::S_COALESCED)
7233 outs() << " S_COALESCED\n";
7234 else if (section_type == MachO::S_INTERPOSING)
7235 outs() << " S_INTERPOSING\n";
7236 else if (section_type == MachO::S_DTRACE_DOF)
7237 outs() << " S_DTRACE_DOF\n";
7238 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
7239 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
7240 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
7241 outs() << " S_THREAD_LOCAL_REGULAR\n";
7242 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
7243 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
7244 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
7245 outs() << " S_THREAD_LOCAL_VARIABLES\n";
7246 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7247 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
7248 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
7249 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
7250 else
7251 outs() << format("0x%08" PRIx32, section_type) << "\n";
7252 outs() << "attributes";
7253 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
7254 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
7255 outs() << " PURE_INSTRUCTIONS";
7256 if (section_attributes & MachO::S_ATTR_NO_TOC)
7257 outs() << " NO_TOC";
7258 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
7259 outs() << " STRIP_STATIC_SYMS";
7260 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
7261 outs() << " NO_DEAD_STRIP";
7262 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
7263 outs() << " LIVE_SUPPORT";
7264 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
7265 outs() << " SELF_MODIFYING_CODE";
7266 if (section_attributes & MachO::S_ATTR_DEBUG)
7267 outs() << " DEBUG";
7268 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
7269 outs() << " SOME_INSTRUCTIONS";
7270 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
7271 outs() << " EXT_RELOC";
7272 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
7273 outs() << " LOC_RELOC";
7274 if (section_attributes == 0)
7275 outs() << " (none)";
7276 outs() << "\n";
7277 } else
7278 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
7279 outs() << " reserved1 " << reserved1;
7280 if (section_type == MachO::S_SYMBOL_STUBS ||
7281 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
7282 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
7283 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
7284 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7285 outs() << " (index into indirect symbol table)\n";
7286 else
7287 outs() << "\n";
7288 outs() << " reserved2 " << reserved2;
7289 if (section_type == MachO::S_SYMBOL_STUBS)
7290 outs() << " (size of stubs)\n";
7291 else
7292 outs() << "\n";
7293}
7294
David Majnemer73cc6ff2014-11-13 19:48:56 +00007295static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00007296 uint32_t object_size) {
7297 outs() << " cmd LC_SYMTAB\n";
7298 outs() << " cmdsize " << st.cmdsize;
7299 if (st.cmdsize != sizeof(struct MachO::symtab_command))
7300 outs() << " Incorrect size\n";
7301 else
7302 outs() << "\n";
7303 outs() << " symoff " << st.symoff;
7304 if (st.symoff > object_size)
7305 outs() << " (past end of file)\n";
7306 else
7307 outs() << "\n";
7308 outs() << " nsyms " << st.nsyms;
7309 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00007310 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007311 big_size = st.nsyms;
7312 big_size *= sizeof(struct MachO::nlist_64);
7313 big_size += st.symoff;
7314 if (big_size > object_size)
7315 outs() << " (past end of file)\n";
7316 else
7317 outs() << "\n";
7318 } else {
7319 big_size = st.nsyms;
7320 big_size *= sizeof(struct MachO::nlist);
7321 big_size += st.symoff;
7322 if (big_size > object_size)
7323 outs() << " (past end of file)\n";
7324 else
7325 outs() << "\n";
7326 }
7327 outs() << " stroff " << st.stroff;
7328 if (st.stroff > object_size)
7329 outs() << " (past end of file)\n";
7330 else
7331 outs() << "\n";
7332 outs() << " strsize " << st.strsize;
7333 big_size = st.stroff;
7334 big_size += st.strsize;
7335 if (big_size > object_size)
7336 outs() << " (past end of file)\n";
7337 else
7338 outs() << "\n";
7339}
7340
7341static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
7342 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00007343 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007344 outs() << " cmd LC_DYSYMTAB\n";
7345 outs() << " cmdsize " << dyst.cmdsize;
7346 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
7347 outs() << " Incorrect size\n";
7348 else
7349 outs() << "\n";
7350 outs() << " ilocalsym " << dyst.ilocalsym;
7351 if (dyst.ilocalsym > nsyms)
7352 outs() << " (greater than the number of symbols)\n";
7353 else
7354 outs() << "\n";
7355 outs() << " nlocalsym " << dyst.nlocalsym;
7356 uint64_t big_size;
7357 big_size = dyst.ilocalsym;
7358 big_size += dyst.nlocalsym;
7359 if (big_size > nsyms)
7360 outs() << " (past the end of the symbol table)\n";
7361 else
7362 outs() << "\n";
7363 outs() << " iextdefsym " << dyst.iextdefsym;
7364 if (dyst.iextdefsym > nsyms)
7365 outs() << " (greater than the number of symbols)\n";
7366 else
7367 outs() << "\n";
7368 outs() << " nextdefsym " << dyst.nextdefsym;
7369 big_size = dyst.iextdefsym;
7370 big_size += dyst.nextdefsym;
7371 if (big_size > nsyms)
7372 outs() << " (past the end of the symbol table)\n";
7373 else
7374 outs() << "\n";
7375 outs() << " iundefsym " << dyst.iundefsym;
7376 if (dyst.iundefsym > nsyms)
7377 outs() << " (greater than the number of symbols)\n";
7378 else
7379 outs() << "\n";
7380 outs() << " nundefsym " << dyst.nundefsym;
7381 big_size = dyst.iundefsym;
7382 big_size += dyst.nundefsym;
7383 if (big_size > nsyms)
7384 outs() << " (past the end of the symbol table)\n";
7385 else
7386 outs() << "\n";
7387 outs() << " tocoff " << dyst.tocoff;
7388 if (dyst.tocoff > object_size)
7389 outs() << " (past end of file)\n";
7390 else
7391 outs() << "\n";
7392 outs() << " ntoc " << dyst.ntoc;
7393 big_size = dyst.ntoc;
7394 big_size *= sizeof(struct MachO::dylib_table_of_contents);
7395 big_size += dyst.tocoff;
7396 if (big_size > object_size)
7397 outs() << " (past end of file)\n";
7398 else
7399 outs() << "\n";
7400 outs() << " modtaboff " << dyst.modtaboff;
7401 if (dyst.modtaboff > object_size)
7402 outs() << " (past end of file)\n";
7403 else
7404 outs() << "\n";
7405 outs() << " nmodtab " << dyst.nmodtab;
7406 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00007407 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007408 modtabend = dyst.nmodtab;
7409 modtabend *= sizeof(struct MachO::dylib_module_64);
7410 modtabend += dyst.modtaboff;
7411 } else {
7412 modtabend = dyst.nmodtab;
7413 modtabend *= sizeof(struct MachO::dylib_module);
7414 modtabend += dyst.modtaboff;
7415 }
7416 if (modtabend > object_size)
7417 outs() << " (past end of file)\n";
7418 else
7419 outs() << "\n";
7420 outs() << " extrefsymoff " << dyst.extrefsymoff;
7421 if (dyst.extrefsymoff > object_size)
7422 outs() << " (past end of file)\n";
7423 else
7424 outs() << "\n";
7425 outs() << " nextrefsyms " << dyst.nextrefsyms;
7426 big_size = dyst.nextrefsyms;
7427 big_size *= sizeof(struct MachO::dylib_reference);
7428 big_size += dyst.extrefsymoff;
7429 if (big_size > object_size)
7430 outs() << " (past end of file)\n";
7431 else
7432 outs() << "\n";
7433 outs() << " indirectsymoff " << dyst.indirectsymoff;
7434 if (dyst.indirectsymoff > object_size)
7435 outs() << " (past end of file)\n";
7436 else
7437 outs() << "\n";
7438 outs() << " nindirectsyms " << dyst.nindirectsyms;
7439 big_size = dyst.nindirectsyms;
7440 big_size *= sizeof(uint32_t);
7441 big_size += dyst.indirectsymoff;
7442 if (big_size > object_size)
7443 outs() << " (past end of file)\n";
7444 else
7445 outs() << "\n";
7446 outs() << " extreloff " << dyst.extreloff;
7447 if (dyst.extreloff > object_size)
7448 outs() << " (past end of file)\n";
7449 else
7450 outs() << "\n";
7451 outs() << " nextrel " << dyst.nextrel;
7452 big_size = dyst.nextrel;
7453 big_size *= sizeof(struct MachO::relocation_info);
7454 big_size += dyst.extreloff;
7455 if (big_size > object_size)
7456 outs() << " (past end of file)\n";
7457 else
7458 outs() << "\n";
7459 outs() << " locreloff " << dyst.locreloff;
7460 if (dyst.locreloff > object_size)
7461 outs() << " (past end of file)\n";
7462 else
7463 outs() << "\n";
7464 outs() << " nlocrel " << dyst.nlocrel;
7465 big_size = dyst.nlocrel;
7466 big_size *= sizeof(struct MachO::relocation_info);
7467 big_size += dyst.locreloff;
7468 if (big_size > object_size)
7469 outs() << " (past end of file)\n";
7470 else
7471 outs() << "\n";
7472}
7473
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007474static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
7475 uint32_t object_size) {
7476 if (dc.cmd == MachO::LC_DYLD_INFO)
7477 outs() << " cmd LC_DYLD_INFO\n";
7478 else
7479 outs() << " cmd LC_DYLD_INFO_ONLY\n";
7480 outs() << " cmdsize " << dc.cmdsize;
7481 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
7482 outs() << " Incorrect size\n";
7483 else
7484 outs() << "\n";
7485 outs() << " rebase_off " << dc.rebase_off;
7486 if (dc.rebase_off > object_size)
7487 outs() << " (past end of file)\n";
7488 else
7489 outs() << "\n";
7490 outs() << " rebase_size " << dc.rebase_size;
7491 uint64_t big_size;
7492 big_size = dc.rebase_off;
7493 big_size += dc.rebase_size;
7494 if (big_size > object_size)
7495 outs() << " (past end of file)\n";
7496 else
7497 outs() << "\n";
7498 outs() << " bind_off " << dc.bind_off;
7499 if (dc.bind_off > object_size)
7500 outs() << " (past end of file)\n";
7501 else
7502 outs() << "\n";
7503 outs() << " bind_size " << dc.bind_size;
7504 big_size = dc.bind_off;
7505 big_size += dc.bind_size;
7506 if (big_size > object_size)
7507 outs() << " (past end of file)\n";
7508 else
7509 outs() << "\n";
7510 outs() << " weak_bind_off " << dc.weak_bind_off;
7511 if (dc.weak_bind_off > object_size)
7512 outs() << " (past end of file)\n";
7513 else
7514 outs() << "\n";
7515 outs() << " weak_bind_size " << dc.weak_bind_size;
7516 big_size = dc.weak_bind_off;
7517 big_size += dc.weak_bind_size;
7518 if (big_size > object_size)
7519 outs() << " (past end of file)\n";
7520 else
7521 outs() << "\n";
7522 outs() << " lazy_bind_off " << dc.lazy_bind_off;
7523 if (dc.lazy_bind_off > object_size)
7524 outs() << " (past end of file)\n";
7525 else
7526 outs() << "\n";
7527 outs() << " lazy_bind_size " << dc.lazy_bind_size;
7528 big_size = dc.lazy_bind_off;
7529 big_size += dc.lazy_bind_size;
7530 if (big_size > object_size)
7531 outs() << " (past end of file)\n";
7532 else
7533 outs() << "\n";
7534 outs() << " export_off " << dc.export_off;
7535 if (dc.export_off > object_size)
7536 outs() << " (past end of file)\n";
7537 else
7538 outs() << "\n";
7539 outs() << " export_size " << dc.export_size;
7540 big_size = dc.export_off;
7541 big_size += dc.export_size;
7542 if (big_size > object_size)
7543 outs() << " (past end of file)\n";
7544 else
7545 outs() << "\n";
7546}
7547
7548static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
7549 const char *Ptr) {
7550 if (dyld.cmd == MachO::LC_ID_DYLINKER)
7551 outs() << " cmd LC_ID_DYLINKER\n";
7552 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
7553 outs() << " cmd LC_LOAD_DYLINKER\n";
7554 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
7555 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
7556 else
7557 outs() << " cmd ?(" << dyld.cmd << ")\n";
7558 outs() << " cmdsize " << dyld.cmdsize;
7559 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
7560 outs() << " Incorrect size\n";
7561 else
7562 outs() << "\n";
7563 if (dyld.name >= dyld.cmdsize)
7564 outs() << " name ?(bad offset " << dyld.name << ")\n";
7565 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007566 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007567 outs() << " name " << P << " (offset " << dyld.name << ")\n";
7568 }
7569}
7570
7571static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
7572 outs() << " cmd LC_UUID\n";
7573 outs() << " cmdsize " << uuid.cmdsize;
7574 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
7575 outs() << " Incorrect size\n";
7576 else
7577 outs() << "\n";
7578 outs() << " uuid ";
7579 outs() << format("%02" PRIX32, uuid.uuid[0]);
7580 outs() << format("%02" PRIX32, uuid.uuid[1]);
7581 outs() << format("%02" PRIX32, uuid.uuid[2]);
7582 outs() << format("%02" PRIX32, uuid.uuid[3]);
7583 outs() << "-";
7584 outs() << format("%02" PRIX32, uuid.uuid[4]);
7585 outs() << format("%02" PRIX32, uuid.uuid[5]);
7586 outs() << "-";
7587 outs() << format("%02" PRIX32, uuid.uuid[6]);
7588 outs() << format("%02" PRIX32, uuid.uuid[7]);
7589 outs() << "-";
7590 outs() << format("%02" PRIX32, uuid.uuid[8]);
7591 outs() << format("%02" PRIX32, uuid.uuid[9]);
7592 outs() << "-";
7593 outs() << format("%02" PRIX32, uuid.uuid[10]);
7594 outs() << format("%02" PRIX32, uuid.uuid[11]);
7595 outs() << format("%02" PRIX32, uuid.uuid[12]);
7596 outs() << format("%02" PRIX32, uuid.uuid[13]);
7597 outs() << format("%02" PRIX32, uuid.uuid[14]);
7598 outs() << format("%02" PRIX32, uuid.uuid[15]);
7599 outs() << "\n";
7600}
7601
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007602static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00007603 outs() << " cmd LC_RPATH\n";
7604 outs() << " cmdsize " << rpath.cmdsize;
7605 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
7606 outs() << " Incorrect size\n";
7607 else
7608 outs() << "\n";
7609 if (rpath.path >= rpath.cmdsize)
7610 outs() << " path ?(bad offset " << rpath.path << ")\n";
7611 else {
7612 const char *P = (const char *)(Ptr) + rpath.path;
7613 outs() << " path " << P << " (offset " << rpath.path << ")\n";
7614 }
7615}
7616
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007617static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
7618 if (vd.cmd == MachO::LC_VERSION_MIN_MACOSX)
7619 outs() << " cmd LC_VERSION_MIN_MACOSX\n";
7620 else if (vd.cmd == MachO::LC_VERSION_MIN_IPHONEOS)
7621 outs() << " cmd LC_VERSION_MIN_IPHONEOS\n";
7622 else
7623 outs() << " cmd " << vd.cmd << " (?)\n";
7624 outs() << " cmdsize " << vd.cmdsize;
7625 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
7626 outs() << " Incorrect size\n";
7627 else
7628 outs() << "\n";
Davide Italiano56baef32015-08-26 12:26:11 +00007629 outs() << " version "
7630 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
7631 << MachOObjectFile::getVersionMinMinor(vd, false);
7632 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
7633 if (Update != 0)
7634 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007635 outs() << "\n";
7636 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00007637 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007638 else {
Davide Italiano56baef32015-08-26 12:26:11 +00007639 outs() << " sdk "
7640 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
7641 << MachOObjectFile::getVersionMinMinor(vd, true);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007642 }
Davide Italiano56baef32015-08-26 12:26:11 +00007643 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
7644 if (Update != 0)
7645 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007646 outs() << "\n";
7647}
7648
7649static void PrintSourceVersionCommand(MachO::source_version_command sd) {
7650 outs() << " cmd LC_SOURCE_VERSION\n";
7651 outs() << " cmdsize " << sd.cmdsize;
7652 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
7653 outs() << " Incorrect size\n";
7654 else
7655 outs() << "\n";
7656 uint64_t a = (sd.version >> 40) & 0xffffff;
7657 uint64_t b = (sd.version >> 30) & 0x3ff;
7658 uint64_t c = (sd.version >> 20) & 0x3ff;
7659 uint64_t d = (sd.version >> 10) & 0x3ff;
7660 uint64_t e = sd.version & 0x3ff;
7661 outs() << " version " << a << "." << b;
7662 if (e != 0)
7663 outs() << "." << c << "." << d << "." << e;
7664 else if (d != 0)
7665 outs() << "." << c << "." << d;
7666 else if (c != 0)
7667 outs() << "." << c;
7668 outs() << "\n";
7669}
7670
7671static void PrintEntryPointCommand(MachO::entry_point_command ep) {
7672 outs() << " cmd LC_MAIN\n";
7673 outs() << " cmdsize " << ep.cmdsize;
7674 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
7675 outs() << " Incorrect size\n";
7676 else
7677 outs() << "\n";
7678 outs() << " entryoff " << ep.entryoff << "\n";
7679 outs() << " stacksize " << ep.stacksize << "\n";
7680}
7681
Kevin Enderby0804f4672014-12-16 23:25:52 +00007682static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
7683 uint32_t object_size) {
7684 outs() << " cmd LC_ENCRYPTION_INFO\n";
7685 outs() << " cmdsize " << ec.cmdsize;
7686 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
7687 outs() << " Incorrect size\n";
7688 else
7689 outs() << "\n";
7690 outs() << " cryptoff " << ec.cryptoff;
7691 if (ec.cryptoff > object_size)
7692 outs() << " (past end of file)\n";
7693 else
7694 outs() << "\n";
7695 outs() << " cryptsize " << ec.cryptsize;
7696 if (ec.cryptsize > object_size)
7697 outs() << " (past end of file)\n";
7698 else
7699 outs() << "\n";
7700 outs() << " cryptid " << ec.cryptid << "\n";
7701}
7702
Kevin Enderby57538292014-12-17 01:01:30 +00007703static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007704 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00007705 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
7706 outs() << " cmdsize " << ec.cmdsize;
7707 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
7708 outs() << " Incorrect size\n";
7709 else
7710 outs() << "\n";
7711 outs() << " cryptoff " << ec.cryptoff;
7712 if (ec.cryptoff > object_size)
7713 outs() << " (past end of file)\n";
7714 else
7715 outs() << "\n";
7716 outs() << " cryptsize " << ec.cryptsize;
7717 if (ec.cryptsize > object_size)
7718 outs() << " (past end of file)\n";
7719 else
7720 outs() << "\n";
7721 outs() << " cryptid " << ec.cryptid << "\n";
7722 outs() << " pad " << ec.pad << "\n";
7723}
7724
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00007725static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
7726 const char *Ptr) {
7727 outs() << " cmd LC_LINKER_OPTION\n";
7728 outs() << " cmdsize " << lo.cmdsize;
7729 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
7730 outs() << " Incorrect size\n";
7731 else
7732 outs() << "\n";
7733 outs() << " count " << lo.count << "\n";
7734 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
7735 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
7736 uint32_t i = 0;
7737 while (left > 0) {
7738 while (*string == '\0' && left > 0) {
7739 string++;
7740 left--;
7741 }
7742 if (left > 0) {
7743 i++;
7744 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00007745 uint32_t NullPos = StringRef(string, left).find('\0');
7746 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00007747 string += len;
7748 left -= len;
7749 }
7750 }
7751 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007752 outs() << " count " << lo.count << " does not match number of strings "
7753 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00007754}
7755
Kevin Enderbyb4b79312014-12-18 19:24:35 +00007756static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
7757 const char *Ptr) {
7758 outs() << " cmd LC_SUB_FRAMEWORK\n";
7759 outs() << " cmdsize " << sub.cmdsize;
7760 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
7761 outs() << " Incorrect size\n";
7762 else
7763 outs() << "\n";
7764 if (sub.umbrella < sub.cmdsize) {
7765 const char *P = Ptr + sub.umbrella;
7766 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
7767 } else {
7768 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
7769 }
7770}
7771
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00007772static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
7773 const char *Ptr) {
7774 outs() << " cmd LC_SUB_UMBRELLA\n";
7775 outs() << " cmdsize " << sub.cmdsize;
7776 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
7777 outs() << " Incorrect size\n";
7778 else
7779 outs() << "\n";
7780 if (sub.sub_umbrella < sub.cmdsize) {
7781 const char *P = Ptr + sub.sub_umbrella;
7782 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
7783 } else {
7784 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
7785 }
7786}
7787
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00007788static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007789 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00007790 outs() << " cmd LC_SUB_LIBRARY\n";
7791 outs() << " cmdsize " << sub.cmdsize;
7792 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
7793 outs() << " Incorrect size\n";
7794 else
7795 outs() << "\n";
7796 if (sub.sub_library < sub.cmdsize) {
7797 const char *P = Ptr + sub.sub_library;
7798 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
7799 } else {
7800 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
7801 }
7802}
7803
Kevin Enderby186eac32014-12-19 21:06:24 +00007804static void PrintSubClientCommand(MachO::sub_client_command sub,
7805 const char *Ptr) {
7806 outs() << " cmd LC_SUB_CLIENT\n";
7807 outs() << " cmdsize " << sub.cmdsize;
7808 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
7809 outs() << " Incorrect size\n";
7810 else
7811 outs() << "\n";
7812 if (sub.client < sub.cmdsize) {
7813 const char *P = Ptr + sub.client;
7814 outs() << " client " << P << " (offset " << sub.client << ")\n";
7815 } else {
7816 outs() << " client ?(bad offset " << sub.client << ")\n";
7817 }
7818}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00007819
Kevin Enderby52e4ce42014-12-19 22:25:22 +00007820static void PrintRoutinesCommand(MachO::routines_command r) {
7821 outs() << " cmd LC_ROUTINES\n";
7822 outs() << " cmdsize " << r.cmdsize;
7823 if (r.cmdsize != sizeof(struct MachO::routines_command))
7824 outs() << " Incorrect size\n";
7825 else
7826 outs() << "\n";
7827 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
7828 outs() << " init_module " << r.init_module << "\n";
7829 outs() << " reserved1 " << r.reserved1 << "\n";
7830 outs() << " reserved2 " << r.reserved2 << "\n";
7831 outs() << " reserved3 " << r.reserved3 << "\n";
7832 outs() << " reserved4 " << r.reserved4 << "\n";
7833 outs() << " reserved5 " << r.reserved5 << "\n";
7834 outs() << " reserved6 " << r.reserved6 << "\n";
7835}
7836
7837static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
7838 outs() << " cmd LC_ROUTINES_64\n";
7839 outs() << " cmdsize " << r.cmdsize;
7840 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
7841 outs() << " Incorrect size\n";
7842 else
7843 outs() << "\n";
7844 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
7845 outs() << " init_module " << r.init_module << "\n";
7846 outs() << " reserved1 " << r.reserved1 << "\n";
7847 outs() << " reserved2 " << r.reserved2 << "\n";
7848 outs() << " reserved3 " << r.reserved3 << "\n";
7849 outs() << " reserved4 " << r.reserved4 << "\n";
7850 outs() << " reserved5 " << r.reserved5 << "\n";
7851 outs() << " reserved6 " << r.reserved6 << "\n";
7852}
7853
Kevin Enderby48ef5342014-12-23 22:56:39 +00007854static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
7855 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
7856 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
7857 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
7858 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
7859 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
7860 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
7861 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
7862 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
7863 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
7864 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
7865 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
7866 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
7867 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
7868 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
7869 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
7870 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
7871 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
7872 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
7873 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
7874 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
7875 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
7876}
7877
Kevin Enderby227df342014-12-23 23:43:59 +00007878static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00007879 uint32_t f;
7880 outs() << "\t mmst_reg ";
7881 for (f = 0; f < 10; f++)
7882 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
7883 outs() << "\n";
7884 outs() << "\t mmst_rsrv ";
7885 for (f = 0; f < 6; f++)
7886 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
7887 outs() << "\n";
7888}
7889
Kevin Enderbyaefb0032014-12-24 00:16:51 +00007890static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00007891 uint32_t f;
7892 outs() << "\t xmm_reg ";
7893 for (f = 0; f < 16; f++)
7894 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
7895 outs() << "\n";
7896}
7897
7898static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
7899 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
7900 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
7901 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
7902 outs() << " denorm " << fpu.fpu_fcw.denorm;
7903 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
7904 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
7905 outs() << " undfl " << fpu.fpu_fcw.undfl;
7906 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
7907 outs() << "\t\t pc ";
7908 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
7909 outs() << "FP_PREC_24B ";
7910 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
7911 outs() << "FP_PREC_53B ";
7912 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
7913 outs() << "FP_PREC_64B ";
7914 else
7915 outs() << fpu.fpu_fcw.pc << " ";
7916 outs() << "rc ";
7917 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
7918 outs() << "FP_RND_NEAR ";
7919 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
7920 outs() << "FP_RND_DOWN ";
7921 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
7922 outs() << "FP_RND_UP ";
7923 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007924 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00007925 outs() << "\n";
7926 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
7927 outs() << " denorm " << fpu.fpu_fsw.denorm;
7928 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
7929 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
7930 outs() << " undfl " << fpu.fpu_fsw.undfl;
7931 outs() << " precis " << fpu.fpu_fsw.precis;
7932 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
7933 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
7934 outs() << " c0 " << fpu.fpu_fsw.c0;
7935 outs() << " c1 " << fpu.fpu_fsw.c1;
7936 outs() << " c2 " << fpu.fpu_fsw.c2;
7937 outs() << " tos " << fpu.fpu_fsw.tos;
7938 outs() << " c3 " << fpu.fpu_fsw.c3;
7939 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
7940 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
7941 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
7942 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
7943 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
7944 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
7945 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
7946 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
7947 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
7948 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
7949 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
7950 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
7951 outs() << "\n";
7952 outs() << "\t fpu_stmm0:\n";
7953 Print_mmst_reg(fpu.fpu_stmm0);
7954 outs() << "\t fpu_stmm1:\n";
7955 Print_mmst_reg(fpu.fpu_stmm1);
7956 outs() << "\t fpu_stmm2:\n";
7957 Print_mmst_reg(fpu.fpu_stmm2);
7958 outs() << "\t fpu_stmm3:\n";
7959 Print_mmst_reg(fpu.fpu_stmm3);
7960 outs() << "\t fpu_stmm4:\n";
7961 Print_mmst_reg(fpu.fpu_stmm4);
7962 outs() << "\t fpu_stmm5:\n";
7963 Print_mmst_reg(fpu.fpu_stmm5);
7964 outs() << "\t fpu_stmm6:\n";
7965 Print_mmst_reg(fpu.fpu_stmm6);
7966 outs() << "\t fpu_stmm7:\n";
7967 Print_mmst_reg(fpu.fpu_stmm7);
7968 outs() << "\t fpu_xmm0:\n";
7969 Print_xmm_reg(fpu.fpu_xmm0);
7970 outs() << "\t fpu_xmm1:\n";
7971 Print_xmm_reg(fpu.fpu_xmm1);
7972 outs() << "\t fpu_xmm2:\n";
7973 Print_xmm_reg(fpu.fpu_xmm2);
7974 outs() << "\t fpu_xmm3:\n";
7975 Print_xmm_reg(fpu.fpu_xmm3);
7976 outs() << "\t fpu_xmm4:\n";
7977 Print_xmm_reg(fpu.fpu_xmm4);
7978 outs() << "\t fpu_xmm5:\n";
7979 Print_xmm_reg(fpu.fpu_xmm5);
7980 outs() << "\t fpu_xmm6:\n";
7981 Print_xmm_reg(fpu.fpu_xmm6);
7982 outs() << "\t fpu_xmm7:\n";
7983 Print_xmm_reg(fpu.fpu_xmm7);
7984 outs() << "\t fpu_xmm8:\n";
7985 Print_xmm_reg(fpu.fpu_xmm8);
7986 outs() << "\t fpu_xmm9:\n";
7987 Print_xmm_reg(fpu.fpu_xmm9);
7988 outs() << "\t fpu_xmm10:\n";
7989 Print_xmm_reg(fpu.fpu_xmm10);
7990 outs() << "\t fpu_xmm11:\n";
7991 Print_xmm_reg(fpu.fpu_xmm11);
7992 outs() << "\t fpu_xmm12:\n";
7993 Print_xmm_reg(fpu.fpu_xmm12);
7994 outs() << "\t fpu_xmm13:\n";
7995 Print_xmm_reg(fpu.fpu_xmm13);
7996 outs() << "\t fpu_xmm14:\n";
7997 Print_xmm_reg(fpu.fpu_xmm14);
7998 outs() << "\t fpu_xmm15:\n";
7999 Print_xmm_reg(fpu.fpu_xmm15);
8000 outs() << "\t fpu_rsrv4:\n";
8001 for (uint32_t f = 0; f < 6; f++) {
8002 outs() << "\t ";
8003 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008004 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008005 outs() << "\n";
8006 }
8007 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
8008 outs() << "\n";
8009}
8010
8011static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
8012 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
8013 outs() << " err " << format("0x%08" PRIx32, exc64.err);
8014 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
8015}
8016
8017static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
8018 bool isLittleEndian, uint32_t cputype) {
8019 if (t.cmd == MachO::LC_THREAD)
8020 outs() << " cmd LC_THREAD\n";
8021 else if (t.cmd == MachO::LC_UNIXTHREAD)
8022 outs() << " cmd LC_UNIXTHREAD\n";
8023 else
8024 outs() << " cmd " << t.cmd << " (unknown)\n";
8025 outs() << " cmdsize " << t.cmdsize;
8026 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
8027 outs() << " Incorrect size\n";
8028 else
8029 outs() << "\n";
8030
8031 const char *begin = Ptr + sizeof(struct MachO::thread_command);
8032 const char *end = Ptr + t.cmdsize;
8033 uint32_t flavor, count, left;
8034 if (cputype == MachO::CPU_TYPE_X86_64) {
8035 while (begin < end) {
8036 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8037 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8038 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008039 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008040 flavor = 0;
8041 begin = end;
8042 }
8043 if (isLittleEndian != sys::IsLittleEndianHost)
8044 sys::swapByteOrder(flavor);
8045 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8046 memcpy((char *)&count, begin, sizeof(uint32_t));
8047 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008048 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008049 count = 0;
8050 begin = end;
8051 }
8052 if (isLittleEndian != sys::IsLittleEndianHost)
8053 sys::swapByteOrder(count);
8054 if (flavor == MachO::x86_THREAD_STATE64) {
8055 outs() << " flavor x86_THREAD_STATE64\n";
8056 if (count == MachO::x86_THREAD_STATE64_COUNT)
8057 outs() << " count x86_THREAD_STATE64_COUNT\n";
8058 else
8059 outs() << " count " << count
8060 << " (not x86_THREAD_STATE64_COUNT)\n";
8061 MachO::x86_thread_state64_t cpu64;
8062 left = end - begin;
8063 if (left >= sizeof(MachO::x86_thread_state64_t)) {
8064 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
8065 begin += sizeof(MachO::x86_thread_state64_t);
8066 } else {
8067 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
8068 memcpy(&cpu64, begin, left);
8069 begin += left;
8070 }
8071 if (isLittleEndian != sys::IsLittleEndianHost)
8072 swapStruct(cpu64);
8073 Print_x86_thread_state64_t(cpu64);
8074 } else if (flavor == MachO::x86_THREAD_STATE) {
8075 outs() << " flavor x86_THREAD_STATE\n";
8076 if (count == MachO::x86_THREAD_STATE_COUNT)
8077 outs() << " count x86_THREAD_STATE_COUNT\n";
8078 else
8079 outs() << " count " << count
8080 << " (not x86_THREAD_STATE_COUNT)\n";
8081 struct MachO::x86_thread_state_t ts;
8082 left = end - begin;
8083 if (left >= sizeof(MachO::x86_thread_state_t)) {
8084 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
8085 begin += sizeof(MachO::x86_thread_state_t);
8086 } else {
8087 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
8088 memcpy(&ts, begin, left);
8089 begin += left;
8090 }
8091 if (isLittleEndian != sys::IsLittleEndianHost)
8092 swapStruct(ts);
8093 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
8094 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
8095 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
8096 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
8097 else
8098 outs() << "tsh.count " << ts.tsh.count
8099 << " (not x86_THREAD_STATE64_COUNT\n";
8100 Print_x86_thread_state64_t(ts.uts.ts64);
8101 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008102 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
8103 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008104 }
8105 } else if (flavor == MachO::x86_FLOAT_STATE) {
8106 outs() << " flavor x86_FLOAT_STATE\n";
8107 if (count == MachO::x86_FLOAT_STATE_COUNT)
8108 outs() << " count x86_FLOAT_STATE_COUNT\n";
8109 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008110 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008111 struct MachO::x86_float_state_t fs;
8112 left = end - begin;
8113 if (left >= sizeof(MachO::x86_float_state_t)) {
8114 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
8115 begin += sizeof(MachO::x86_float_state_t);
8116 } else {
8117 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
8118 memcpy(&fs, begin, left);
8119 begin += left;
8120 }
8121 if (isLittleEndian != sys::IsLittleEndianHost)
8122 swapStruct(fs);
8123 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
8124 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008125 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008126 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
8127 else
8128 outs() << "fsh.count " << fs.fsh.count
8129 << " (not x86_FLOAT_STATE64_COUNT\n";
8130 Print_x86_float_state_t(fs.ufs.fs64);
8131 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008132 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
8133 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008134 }
8135 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
8136 outs() << " flavor x86_EXCEPTION_STATE\n";
8137 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
8138 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
8139 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008140 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00008141 << " (not x86_EXCEPTION_STATE_COUNT)\n";
8142 struct MachO::x86_exception_state_t es;
8143 left = end - begin;
8144 if (left >= sizeof(MachO::x86_exception_state_t)) {
8145 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
8146 begin += sizeof(MachO::x86_exception_state_t);
8147 } else {
8148 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
8149 memcpy(&es, begin, left);
8150 begin += left;
8151 }
8152 if (isLittleEndian != sys::IsLittleEndianHost)
8153 swapStruct(es);
8154 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
8155 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008156 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008157 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
8158 else
8159 outs() << "\t esh.count " << es.esh.count
8160 << " (not x86_EXCEPTION_STATE64_COUNT\n";
8161 Print_x86_exception_state_t(es.ues.es64);
8162 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008163 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
8164 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008165 }
8166 } else {
8167 outs() << " flavor " << flavor << " (unknown)\n";
8168 outs() << " count " << count << "\n";
8169 outs() << " state (unknown)\n";
8170 begin += count * sizeof(uint32_t);
8171 }
8172 }
8173 } else {
8174 while (begin < end) {
8175 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8176 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8177 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008178 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008179 flavor = 0;
8180 begin = end;
8181 }
8182 if (isLittleEndian != sys::IsLittleEndianHost)
8183 sys::swapByteOrder(flavor);
8184 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8185 memcpy((char *)&count, begin, sizeof(uint32_t));
8186 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008187 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008188 count = 0;
8189 begin = end;
8190 }
8191 if (isLittleEndian != sys::IsLittleEndianHost)
8192 sys::swapByteOrder(count);
8193 outs() << " flavor " << flavor << "\n";
8194 outs() << " count " << count << "\n";
8195 outs() << " state (Unknown cputype/cpusubtype)\n";
8196 begin += count * sizeof(uint32_t);
8197 }
8198 }
8199}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008200
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008201static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
8202 if (dl.cmd == MachO::LC_ID_DYLIB)
8203 outs() << " cmd LC_ID_DYLIB\n";
8204 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
8205 outs() << " cmd LC_LOAD_DYLIB\n";
8206 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
8207 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
8208 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
8209 outs() << " cmd LC_REEXPORT_DYLIB\n";
8210 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
8211 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
8212 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
8213 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
8214 else
8215 outs() << " cmd " << dl.cmd << " (unknown)\n";
8216 outs() << " cmdsize " << dl.cmdsize;
8217 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
8218 outs() << " Incorrect size\n";
8219 else
8220 outs() << "\n";
8221 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008222 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008223 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
8224 } else {
8225 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
8226 }
8227 outs() << " time stamp " << dl.dylib.timestamp << " ";
8228 time_t t = dl.dylib.timestamp;
8229 outs() << ctime(&t);
8230 outs() << " current version ";
8231 if (dl.dylib.current_version == 0xffffffff)
8232 outs() << "n/a\n";
8233 else
8234 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
8235 << ((dl.dylib.current_version >> 8) & 0xff) << "."
8236 << (dl.dylib.current_version & 0xff) << "\n";
8237 outs() << "compatibility version ";
8238 if (dl.dylib.compatibility_version == 0xffffffff)
8239 outs() << "n/a\n";
8240 else
8241 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
8242 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
8243 << (dl.dylib.compatibility_version & 0xff) << "\n";
8244}
8245
8246static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
8247 uint32_t object_size) {
8248 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
8249 outs() << " cmd LC_FUNCTION_STARTS\n";
8250 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
8251 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
8252 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
8253 outs() << " cmd LC_FUNCTION_STARTS\n";
8254 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
8255 outs() << " cmd LC_DATA_IN_CODE\n";
8256 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
8257 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
8258 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
8259 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
8260 else
8261 outs() << " cmd " << ld.cmd << " (?)\n";
8262 outs() << " cmdsize " << ld.cmdsize;
8263 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
8264 outs() << " Incorrect size\n";
8265 else
8266 outs() << "\n";
8267 outs() << " dataoff " << ld.dataoff;
8268 if (ld.dataoff > object_size)
8269 outs() << " (past end of file)\n";
8270 else
8271 outs() << "\n";
8272 outs() << " datasize " << ld.datasize;
8273 uint64_t big_size = ld.dataoff;
8274 big_size += ld.datasize;
8275 if (big_size > object_size)
8276 outs() << " (past end of file)\n";
8277 else
8278 outs() << "\n";
8279}
8280
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008281static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
8282 uint32_t cputype, bool verbose) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008283 StringRef Buf = Obj->getData();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008284 unsigned Index = 0;
8285 for (const auto &Command : Obj->load_commands()) {
8286 outs() << "Load command " << Index++ << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008287 if (Command.C.cmd == MachO::LC_SEGMENT) {
8288 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
8289 const char *sg_segname = SLC.segname;
8290 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
8291 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
8292 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
8293 verbose);
8294 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00008295 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00008296 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
8297 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
8298 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
8299 }
8300 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
8301 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
8302 const char *sg_segname = SLC_64.segname;
8303 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
8304 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
8305 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
8306 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
8307 for (unsigned j = 0; j < SLC_64.nsects; j++) {
8308 MachO::section_64 S_64 = Obj->getSection64(Command, j);
8309 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
8310 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
8311 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
8312 sg_segname, filetype, Buf.size(), verbose);
8313 }
8314 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
8315 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00008316 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00008317 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
8318 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
8319 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00008320 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
8321 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008322 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
8323 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
8324 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
8325 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
8326 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
8327 Command.C.cmd == MachO::LC_ID_DYLINKER ||
8328 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
8329 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
8330 PrintDyldLoadCommand(Dyld, Command.Ptr);
8331 } else if (Command.C.cmd == MachO::LC_UUID) {
8332 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
8333 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008334 } else if (Command.C.cmd == MachO::LC_RPATH) {
8335 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
8336 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00008337 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
8338 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008339 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
8340 PrintVersionMinLoadCommand(Vd);
8341 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
8342 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
8343 PrintSourceVersionCommand(Sd);
8344 } else if (Command.C.cmd == MachO::LC_MAIN) {
8345 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
8346 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00008347 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008348 MachO::encryption_info_command Ei =
8349 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00008350 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00008351 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008352 MachO::encryption_info_command_64 Ei =
8353 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00008354 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008355 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008356 MachO::linker_option_command Lo =
8357 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008358 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00008359 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
8360 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
8361 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00008362 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
8363 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
8364 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008365 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
8366 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
8367 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00008368 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
8369 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
8370 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00008371 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
8372 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
8373 PrintRoutinesCommand(Rc);
8374 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
8375 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
8376 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00008377 } else if (Command.C.cmd == MachO::LC_THREAD ||
8378 Command.C.cmd == MachO::LC_UNIXTHREAD) {
8379 MachO::thread_command Tc = Obj->getThreadCommand(Command);
8380 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00008381 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
8382 Command.C.cmd == MachO::LC_ID_DYLIB ||
8383 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
8384 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
8385 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
8386 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008387 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
8388 PrintDylibCommand(Dl, Command.Ptr);
8389 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
8390 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
8391 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
8392 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
8393 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
8394 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
8395 MachO::linkedit_data_command Ld =
8396 Obj->getLinkeditDataLoadCommand(Command);
8397 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00008398 } else {
8399 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
8400 << ")\n";
8401 outs() << " cmdsize " << Command.C.cmdsize << "\n";
8402 // TODO: get and print the raw bytes of the load command.
8403 }
8404 // TODO: print all the other kinds of load commands.
Kevin Enderby956366c2014-08-29 22:30:52 +00008405 }
8406}
8407
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008408static void getAndPrintMachHeader(const MachOObjectFile *Obj,
Kevin Enderby956366c2014-08-29 22:30:52 +00008409 uint32_t &filetype, uint32_t &cputype,
8410 bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008411 if (Obj->is64Bit()) {
8412 MachO::mach_header_64 H_64;
8413 H_64 = Obj->getHeader64();
8414 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
8415 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
Kevin Enderby956366c2014-08-29 22:30:52 +00008416 filetype = H_64.filetype;
8417 cputype = H_64.cputype;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008418 } else {
8419 MachO::mach_header H;
8420 H = Obj->getHeader();
8421 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
8422 H.sizeofcmds, H.flags, verbose);
Kevin Enderby956366c2014-08-29 22:30:52 +00008423 filetype = H.filetype;
8424 cputype = H.cputype;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008425 }
8426}
8427
8428void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
8429 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00008430 uint32_t filetype = 0;
8431 uint32_t cputype = 0;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008432 getAndPrintMachHeader(file, filetype, cputype, !NonVerbose);
8433 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008434}
Nick Kledzikd04bc352014-08-30 00:20:14 +00008435
8436//===----------------------------------------------------------------------===//
8437// export trie dumping
8438//===----------------------------------------------------------------------===//
8439
8440void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008441 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
8442 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +00008443 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
8444 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
8445 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8446 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
8447 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8448 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
8449 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
8450 if (ReExport)
8451 outs() << "[re-export] ";
8452 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008453 outs() << format("0x%08llX ",
8454 Entry.address()); // FIXME:add in base address
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008455 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +00008456 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008457 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +00008458 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +00008459 if (WeakDef) {
8460 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008461 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008462 }
8463 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008464 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00008465 outs() << ", ";
8466 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008467 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008468 }
8469 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008470 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00008471 outs() << ", ";
8472 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008473 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008474 }
8475 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008476 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00008477 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008478 outs() << format("resolver=0x%08llX", Entry.other());
8479 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008480 }
8481 outs() << "]";
8482 }
8483 if (ReExport) {
8484 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008485 int Ordinal = Entry.other() - 1;
8486 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
8487 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +00008488 outs() << " (from " << DylibName << ")";
8489 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008490 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +00008491 }
8492 outs() << "\n";
8493 }
8494}
Nick Kledzikac431442014-09-12 21:34:15 +00008495
Nick Kledzikac431442014-09-12 21:34:15 +00008496//===----------------------------------------------------------------------===//
8497// rebase table dumping
8498//===----------------------------------------------------------------------===//
8499
8500namespace {
8501class SegInfo {
8502public:
8503 SegInfo(const object::MachOObjectFile *Obj);
8504
8505 StringRef segmentName(uint32_t SegIndex);
8506 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
8507 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00008508 bool isValidSegIndexAndOffset(uint32_t SegIndex, uint64_t SegOffset);
Nick Kledzikac431442014-09-12 21:34:15 +00008509
8510private:
8511 struct SectionInfo {
8512 uint64_t Address;
8513 uint64_t Size;
8514 StringRef SectionName;
8515 StringRef SegmentName;
8516 uint64_t OffsetInSegment;
8517 uint64_t SegmentStartAddress;
8518 uint32_t SegmentIndex;
8519 };
8520 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
8521 SmallVector<SectionInfo, 32> Sections;
8522};
8523}
8524
8525SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
8526 // Build table of sections so segIndex/offset pairs can be translated.
Nick Kledzik56ebef42014-09-16 01:41:51 +00008527 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
Nick Kledzikac431442014-09-12 21:34:15 +00008528 StringRef CurSegName;
8529 uint64_t CurSegAddress;
8530 for (const SectionRef &Section : Obj->sections()) {
8531 SectionInfo Info;
Davide Italianoccd53fe2015-08-05 07:18:31 +00008532 error(Section.getName(Info.SectionName));
Rafael Espindola80291272014-10-08 15:28:58 +00008533 Info.Address = Section.getAddress();
8534 Info.Size = Section.getSize();
Nick Kledzikac431442014-09-12 21:34:15 +00008535 Info.SegmentName =
8536 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
8537 if (!Info.SegmentName.equals(CurSegName)) {
8538 ++CurSegIndex;
8539 CurSegName = Info.SegmentName;
8540 CurSegAddress = Info.Address;
8541 }
8542 Info.SegmentIndex = CurSegIndex - 1;
8543 Info.OffsetInSegment = Info.Address - CurSegAddress;
8544 Info.SegmentStartAddress = CurSegAddress;
8545 Sections.push_back(Info);
8546 }
8547}
8548
8549StringRef SegInfo::segmentName(uint32_t SegIndex) {
8550 for (const SectionInfo &SI : Sections) {
8551 if (SI.SegmentIndex == SegIndex)
8552 return SI.SegmentName;
8553 }
8554 llvm_unreachable("invalid segIndex");
8555}
8556
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00008557bool SegInfo::isValidSegIndexAndOffset(uint32_t SegIndex,
8558 uint64_t OffsetInSeg) {
8559 for (const SectionInfo &SI : Sections) {
8560 if (SI.SegmentIndex != SegIndex)
8561 continue;
8562 if (SI.OffsetInSegment > OffsetInSeg)
8563 continue;
8564 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
8565 continue;
8566 return true;
8567 }
8568 return false;
8569}
8570
Nick Kledzikac431442014-09-12 21:34:15 +00008571const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
8572 uint64_t OffsetInSeg) {
8573 for (const SectionInfo &SI : Sections) {
8574 if (SI.SegmentIndex != SegIndex)
8575 continue;
8576 if (SI.OffsetInSegment > OffsetInSeg)
8577 continue;
8578 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
8579 continue;
8580 return SI;
8581 }
8582 llvm_unreachable("segIndex and offset not in any section");
8583}
8584
8585StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
8586 return findSection(SegIndex, OffsetInSeg).SectionName;
8587}
8588
8589uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
8590 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
8591 return SI.SegmentStartAddress + OffsetInSeg;
8592}
8593
8594void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
8595 // Build table of sections so names can used in final output.
8596 SegInfo sectionTable(Obj);
8597
8598 outs() << "segment section address type\n";
8599 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
8600 uint32_t SegIndex = Entry.segmentIndex();
8601 uint64_t OffsetInSeg = Entry.segmentOffset();
8602 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8603 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8604 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8605
8606 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008607 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
8608 SegmentName.str().c_str(), SectionName.str().c_str(),
8609 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +00008610 }
8611}
Nick Kledzik56ebef42014-09-16 01:41:51 +00008612
8613static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
8614 StringRef DylibName;
8615 switch (Ordinal) {
8616 case MachO::BIND_SPECIAL_DYLIB_SELF:
8617 return "this-image";
8618 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
8619 return "main-executable";
8620 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
8621 return "flat-namespace";
8622 default:
Nick Kledzikabd29872014-09-16 22:03:13 +00008623 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008624 std::error_code EC =
8625 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +00008626 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +00008627 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +00008628 return DylibName;
8629 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00008630 }
Nick Kledzikabd29872014-09-16 22:03:13 +00008631 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008632}
8633
8634//===----------------------------------------------------------------------===//
8635// bind table dumping
8636//===----------------------------------------------------------------------===//
8637
8638void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
8639 // Build table of sections so names can used in final output.
8640 SegInfo sectionTable(Obj);
8641
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008642 outs() << "segment section address type "
8643 "addend dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008644 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
8645 uint32_t SegIndex = Entry.segmentIndex();
8646 uint64_t OffsetInSeg = Entry.segmentOffset();
8647 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8648 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8649 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8650
8651 // Table lines look like:
8652 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008653 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00008654 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008655 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008656 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008657 << left_justify(SectionName, 18) << " "
8658 << format_hex(Address, 10, true) << " "
8659 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008660 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008661 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008662 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008663 }
8664}
8665
8666//===----------------------------------------------------------------------===//
8667// lazy bind table dumping
8668//===----------------------------------------------------------------------===//
8669
8670void llvm::printMachOLazyBindTable(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 "
8675 "dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008676 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
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 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008685 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008686 << left_justify(SectionName, 18) << " "
8687 << format_hex(Address, 10, true) << " "
8688 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00008689 << Entry.symbolName() << "\n";
8690 }
8691}
8692
Nick Kledzik56ebef42014-09-16 01:41:51 +00008693//===----------------------------------------------------------------------===//
8694// weak bind table dumping
8695//===----------------------------------------------------------------------===//
8696
8697void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
8698 // Build table of sections so names can used in final output.
8699 SegInfo sectionTable(Obj);
8700
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008701 outs() << "segment section address "
8702 "type addend symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008703 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
8704 // Strong symbols don't have a location to update.
8705 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008706 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +00008707 << Entry.symbolName() << "\n";
8708 continue;
8709 }
8710 uint32_t SegIndex = Entry.segmentIndex();
8711 uint64_t OffsetInSeg = Entry.segmentOffset();
8712 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8713 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8714 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8715
8716 // Table lines look like:
8717 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008718 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008719 << left_justify(SectionName, 18) << " "
8720 << format_hex(Address, 10, true) << " "
8721 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008722 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
8723 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008724 }
8725}
8726
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008727// get_dyld_bind_info_symbolname() is used for disassembly and passed an
8728// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
8729// information for that address. If the address is found its binding symbol
8730// name is returned. If not nullptr is returned.
8731static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
8732 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +00008733 if (info->bindtable == nullptr) {
8734 info->bindtable = new (BindTable);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008735 SegInfo sectionTable(info->O);
8736 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
8737 uint32_t SegIndex = Entry.segmentIndex();
8738 uint64_t OffsetInSeg = Entry.segmentOffset();
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00008739 if (!sectionTable.isValidSegIndexAndOffset(SegIndex, OffsetInSeg))
8740 continue;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008741 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8742 const char *SymbolName = nullptr;
8743 StringRef name = Entry.symbolName();
8744 if (!name.empty())
8745 SymbolName = name.data();
Kevin Enderby078be602014-10-23 19:53:12 +00008746 info->bindtable->push_back(std::make_pair(Address, SymbolName));
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008747 }
8748 }
Kevin Enderby078be602014-10-23 19:53:12 +00008749 for (bind_table_iterator BI = info->bindtable->begin(),
8750 BE = info->bindtable->end();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008751 BI != BE; ++BI) {
8752 uint64_t Address = BI->first;
8753 if (ReferenceValue == Address) {
8754 const char *SymbolName = BI->second;
8755 return SymbolName;
8756 }
8757 }
8758 return nullptr;
8759}