blob: e68a1432249c9d7fe7682885ef566ea3628a51a1 [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"
Pete Cooper23bfa7e2015-12-14 21:39:27 +000016#include "llvm/ADT/Optional.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000017#include "llvm/ADT/STLExtras.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000018#include "llvm/ADT/StringExtras.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000019#include "llvm/ADT/Triple.h"
Kevin Enderby04bf6932014-10-28 23:39:46 +000020#include "llvm/Config/config.h"
Zachary Turner6489d7b2015-04-23 17:37:47 +000021#include "llvm/DebugInfo/DIContext.h"
22#include "llvm/DebugInfo/DWARF/DWARFContext.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000023#include "llvm/MC/MCAsmInfo.h"
Lang Hamesa1bc0f52014-04-15 04:40:56 +000024#include "llvm/MC/MCContext.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000025#include "llvm/MC/MCDisassembler.h"
26#include "llvm/MC/MCInst.h"
27#include "llvm/MC/MCInstPrinter.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000028#include "llvm/MC/MCInstrDesc.h"
29#include "llvm/MC/MCInstrInfo.h"
Jim Grosbachfd93a592012-03-05 19:33:20 +000030#include "llvm/MC/MCRegisterInfo.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000031#include "llvm/MC/MCSubtargetInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000032#include "llvm/Object/MachO.h"
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +000033#include "llvm/Object/MachOUniversal.h"
Rafael Espindola9b709252013-04-13 01:45:40 +000034#include "llvm/Support/Casting.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000035#include "llvm/Support/CommandLine.h"
36#include "llvm/Support/Debug.h"
Tim Northover4bd286a2014-08-01 13:07:19 +000037#include "llvm/Support/Endian.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000038#include "llvm/Support/Format.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000039#include "llvm/Support/FormattedStream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000040#include "llvm/Support/GraphWriter.h"
Kevin Enderby9a509442015-01-27 21:28:24 +000041#include "llvm/Support/LEB128.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000042#include "llvm/Support/MachO.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000043#include "llvm/Support/MemoryBuffer.h"
44#include "llvm/Support/TargetRegistry.h"
45#include "llvm/Support/TargetSelect.h"
46#include "llvm/Support/raw_ostream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000047#include <algorithm>
48#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000049#include <system_error>
Kevin Enderby04bf6932014-10-28 23:39:46 +000050
51#if HAVE_CXXABI_H
52#include <cxxabi.h>
53#endif
54
Benjamin Kramer43a772e2011-09-19 17:56:04 +000055using namespace llvm;
56using namespace object;
57
58static cl::opt<bool>
Kevin Enderbyb28ed012014-10-29 21:28:24 +000059 UseDbg("g",
60 cl::desc("Print line information from debug info if available"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000061
Kevin Enderbyb28ed012014-10-29 21:28:24 +000062static cl::opt<std::string> DSYMFile("dsym",
63 cl::desc("Use .dSYM file for debug info"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000064
Kevin Enderbyb28ed012014-10-29 21:28:24 +000065static cl::opt<bool> FullLeadingAddr("full-leading-addr",
66 cl::desc("Print full leading address"));
Kevin Enderbybf246f52014-09-24 23:08:22 +000067
Kevin Enderbyab5e6c92015-03-17 21:07:39 +000068static cl::opt<bool> NoLeadingAddr("no-leading-addr",
69 cl::desc("Print no leading address"));
70
Kevin Enderby13023a12015-01-15 23:19:11 +000071cl::opt<bool> llvm::UniversalHeaders("universal-headers",
72 cl::desc("Print Mach-O universal headers "
73 "(requires -macho)"));
74
Kevin Enderby131d1772015-01-09 19:22:37 +000075cl::opt<bool>
Kevin Enderby13023a12015-01-15 23:19:11 +000076 llvm::ArchiveHeaders("archive-headers",
77 cl::desc("Print archive headers for Mach-O archives "
78 "(requires -macho)"));
Kevin Enderby131d1772015-01-09 19:22:37 +000079
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +000080cl::opt<bool>
Kevin Enderby8972e482015-04-30 20:30:42 +000081 ArchiveMemberOffsets("archive-member-offsets",
82 cl::desc("Print the offset to each archive member for "
83 "Mach-O archives (requires -macho and "
84 "-archive-headers)"));
85
86cl::opt<bool>
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +000087 llvm::IndirectSymbols("indirect-symbols",
88 cl::desc("Print indirect symbol table for Mach-O "
89 "objects (requires -macho)"));
90
Kevin Enderby69fe98d2015-01-23 18:52:17 +000091cl::opt<bool>
92 llvm::DataInCode("data-in-code",
93 cl::desc("Print the data in code table for Mach-O objects "
94 "(requires -macho)"));
95
Kevin Enderby9a509442015-01-27 21:28:24 +000096cl::opt<bool>
97 llvm::LinkOptHints("link-opt-hints",
98 cl::desc("Print the linker optimization hints for "
99 "Mach-O objects (requires -macho)"));
100
Kevin Enderbycd66be52015-03-11 22:06:32 +0000101cl::opt<bool>
102 llvm::InfoPlist("info-plist",
103 cl::desc("Print the info plist section as strings for "
104 "Mach-O objects (requires -macho)"));
105
Kevin Enderbyf0640752015-03-13 17:56:32 +0000106cl::opt<bool>
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000107 llvm::DylibsUsed("dylibs-used",
108 cl::desc("Print the shared libraries used for linked "
109 "Mach-O files (requires -macho)"));
110
111cl::opt<bool>
112 llvm::DylibId("dylib-id",
113 cl::desc("Print the shared library's id for the dylib Mach-O "
114 "file (requires -macho)"));
115
116cl::opt<bool>
Kevin Enderbyf0640752015-03-13 17:56:32 +0000117 llvm::NonVerbose("non-verbose",
118 cl::desc("Print the info for Mach-O objects in "
119 "non-verbose or numeric form (requires -macho)"));
120
Kevin Enderby0fc11822015-04-01 20:57:01 +0000121cl::opt<bool>
122 llvm::ObjcMetaData("objc-meta-data",
123 cl::desc("Print the Objective-C runtime meta data for "
124 "Mach-O files (requires -macho)"));
125
Kevin Enderby6a221752015-03-17 17:10:57 +0000126cl::opt<std::string> llvm::DisSymName(
127 "dis-symname",
128 cl::desc("disassemble just this symbol's instructions (requires -macho"));
129
Kevin Enderby8e29ec92015-03-17 22:26:11 +0000130static cl::opt<bool> NoSymbolicOperands(
131 "no-symbolic-operands",
132 cl::desc("do not symbolic operands when disassembling (requires -macho)"));
133
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000134static cl::list<std::string>
135 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
136 cl::ZeroOrMore);
Hans Wennborgcc9deb42015-09-29 18:02:48 +0000137
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000138bool ArchAll = false;
139
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000140static std::string ThumbTripleName;
141
142static const Target *GetTarget(const MachOObjectFile *MachOObj,
143 const char **McpuDefault,
144 const Target **ThumbTarget) {
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000145 // Figure out the target triple.
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000146 if (TripleName.empty()) {
147 llvm::Triple TT("unknown-unknown-unknown");
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000148 llvm::Triple ThumbTriple = Triple();
149 TT = MachOObj->getArch(McpuDefault, &ThumbTriple);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000150 TripleName = TT.str();
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000151 ThumbTripleName = ThumbTriple.str();
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000152 }
153
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000154 // Get the target specific parser.
155 std::string Error;
156 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000157 if (TheTarget && ThumbTripleName.empty())
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000158 return TheTarget;
159
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000160 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
161 if (*ThumbTarget)
162 return TheTarget;
163
164 errs() << "llvm-objdump: error: unable to get target for '";
165 if (!TheTarget)
166 errs() << TripleName;
167 else
168 errs() << ThumbTripleName;
169 errs() << "', see --version and --triple.\n";
Craig Toppere6cb63e2014-04-25 04:24:47 +0000170 return nullptr;
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000171}
172
Owen Andersond9243c42011-10-17 21:37:35 +0000173struct SymbolSorter {
174 bool operator()(const SymbolRef &A, const SymbolRef &B) {
Rafael Espindoladea00162015-07-03 17:44:18 +0000175 uint64_t AAddr = (A.getType() != SymbolRef::ST_Function) ? 0 : A.getValue();
176 uint64_t BAddr = (B.getType() != SymbolRef::ST_Function) ? 0 : B.getValue();
Owen Andersond9243c42011-10-17 21:37:35 +0000177 return AAddr < BAddr;
178 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000179};
180
Kevin Enderby273ae012013-06-06 17:20:50 +0000181// Types for the storted data in code table that is built before disassembly
182// and the predicate function to sort them.
183typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
184typedef std::vector<DiceTableEntry> DiceTable;
185typedef DiceTable::iterator dice_table_iterator;
186
Kevin Enderby930fdc72014-11-06 19:00:13 +0000187// This is used to search for a data in code table entry for the PC being
188// disassembled. The j parameter has the PC in j.first. A single data in code
189// table entry can cover many bytes for each of its Kind's. So if the offset,
190// aka the i.first value, of the data in code table entry plus its Length
191// covers the PC being searched for this will return true. If not it will
192// return false.
David Majnemerea9b8ee2014-11-04 08:41:48 +0000193static bool compareDiceTableEntries(const DiceTableEntry &i,
194 const DiceTableEntry &j) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000195 uint16_t Length;
196 i.second.getLength(Length);
197
198 return j.first >= i.first && j.first < i.first + Length;
Kevin Enderby273ae012013-06-06 17:20:50 +0000199}
200
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000201static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
Kevin Enderby930fdc72014-11-06 19:00:13 +0000202 unsigned short Kind) {
203 uint32_t Value, Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000204
205 switch (Kind) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000206 default:
Charles Davis8bdfafd2013-09-01 04:28:48 +0000207 case MachO::DICE_KIND_DATA:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000208 if (Length >= 4) {
209 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000210 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000211 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000212 outs() << "\t.long " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000213 Size = 4;
214 } else if (Length >= 2) {
215 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000216 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000217 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000218 outs() << "\t.short " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000219 Size = 2;
220 } else {
221 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000222 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000223 Value = bytes[0];
224 outs() << "\t.byte " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000225 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000226 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000227 if (Kind == MachO::DICE_KIND_DATA)
228 outs() << "\t@ KIND_DATA\n";
229 else
230 outs() << "\t@ data in code kind = " << Kind << "\n";
Kevin Enderby273ae012013-06-06 17:20:50 +0000231 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000232 case MachO::DICE_KIND_JUMP_TABLE8:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000233 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000234 dumpBytes(makeArrayRef(bytes, 1), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000235 Value = bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000236 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
237 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000238 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000239 case MachO::DICE_KIND_JUMP_TABLE16:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000240 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000241 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000242 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000243 outs() << "\t.short " << format("%5u", Value & 0xffff)
244 << "\t@ KIND_JUMP_TABLE16\n";
245 Size = 2;
Kevin Enderby273ae012013-06-06 17:20:50 +0000246 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000247 case MachO::DICE_KIND_JUMP_TABLE32:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000248 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
249 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000250 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000251 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000252 outs() << "\t.long " << Value;
253 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
254 outs() << "\t@ KIND_JUMP_TABLE32\n";
255 else
256 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
257 Size = 4;
Kevin Enderby273ae012013-06-06 17:20:50 +0000258 break;
259 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000260 return Size;
Kevin Enderby273ae012013-06-06 17:20:50 +0000261}
262
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000263static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000264 std::vector<SectionRef> &Sections,
265 std::vector<SymbolRef> &Symbols,
266 SmallVectorImpl<uint64_t> &FoundFns,
267 uint64_t &BaseSegmentAddress) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000268 for (const SymbolRef &Symbol : MachOObj->symbols()) {
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000269 ErrorOr<StringRef> SymName = Symbol.getName();
270 if (std::error_code EC = SymName.getError())
271 report_fatal_error(EC.message());
272 if (!SymName->startswith("ltmp"))
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000273 Symbols.push_back(Symbol);
274 }
Owen Andersond9243c42011-10-17 21:37:35 +0000275
Alexey Samsonov48803e52014-03-13 14:37:36 +0000276 for (const SectionRef &Section : MachOObj->sections()) {
Owen Andersond9243c42011-10-17 21:37:35 +0000277 StringRef SectName;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000278 Section.getName(SectName);
279 Sections.push_back(Section);
Owen Andersond9243c42011-10-17 21:37:35 +0000280 }
281
Kevin Enderby273ae012013-06-06 17:20:50 +0000282 bool BaseSegmentAddressSet = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000283 for (const auto &Command : MachOObj->load_commands()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000284 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
Benjamin Kramer699128e2011-09-21 01:13:19 +0000285 // We found a function starts segment, parse the addresses for later
286 // consumption.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000287 MachO::linkedit_data_command LLC =
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000288 MachOObj->getLinkeditDataLoadCommand(Command);
Benjamin Kramer699128e2011-09-21 01:13:19 +0000289
Charles Davis8bdfafd2013-09-01 04:28:48 +0000290 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000291 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
292 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000293 StringRef SegName = SLC.segname;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000294 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
Kevin Enderby273ae012013-06-06 17:20:50 +0000295 BaseSegmentAddressSet = true;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000296 BaseSegmentAddress = SLC.vmaddr;
Kevin Enderby273ae012013-06-06 17:20:50 +0000297 }
298 }
Benjamin Kramer8a529dc2011-09-21 22:16:43 +0000299 }
Benjamin Kramer699128e2011-09-21 01:13:19 +0000300}
301
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000302static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
303 uint32_t n, uint32_t count,
304 uint32_t stride, uint64_t addr) {
305 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
306 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
307 if (n > nindirectsyms)
308 outs() << " (entries start past the end of the indirect symbol "
309 "table) (reserved1 field greater than the table size)";
310 else if (n + count > nindirectsyms)
311 outs() << " (entries extends past the end of the indirect symbol "
312 "table)";
313 outs() << "\n";
314 uint32_t cputype = O->getHeader().cputype;
315 if (cputype & MachO::CPU_ARCH_ABI64)
316 outs() << "address index";
317 else
318 outs() << "address index";
319 if (verbose)
320 outs() << " name\n";
321 else
322 outs() << "\n";
323 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
324 if (cputype & MachO::CPU_ARCH_ABI64)
325 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
326 else
327 outs() << format("0x%08" PRIx32, addr + j * stride) << " ";
328 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
329 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
330 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
331 outs() << "LOCAL\n";
332 continue;
333 }
334 if (indirect_symbol ==
335 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
336 outs() << "LOCAL ABSOLUTE\n";
337 continue;
338 }
339 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
340 outs() << "ABSOLUTE\n";
341 continue;
342 }
343 outs() << format("%5u ", indirect_symbol);
Kevin Enderbyf0640752015-03-13 17:56:32 +0000344 if (verbose) {
345 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
346 if (indirect_symbol < Symtab.nsyms) {
347 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
348 SymbolRef Symbol = *Sym;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000349 ErrorOr<StringRef> SymName = Symbol.getName();
350 if (std::error_code EC = SymName.getError())
351 report_fatal_error(EC.message());
352 outs() << *SymName;
Kevin Enderbyf0640752015-03-13 17:56:32 +0000353 } else {
354 outs() << "?";
355 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000356 }
357 outs() << "\n";
358 }
359}
360
361static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000362 for (const auto &Load : O->load_commands()) {
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000363 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
364 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
365 for (unsigned J = 0; J < Seg.nsects; ++J) {
366 MachO::section_64 Sec = O->getSection64(Load, J);
367 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
368 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
369 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
370 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
371 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
372 section_type == MachO::S_SYMBOL_STUBS) {
373 uint32_t stride;
374 if (section_type == MachO::S_SYMBOL_STUBS)
375 stride = Sec.reserved2;
376 else
377 stride = 8;
378 if (stride == 0) {
379 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
380 << Sec.sectname << ") "
381 << "(size of stubs in reserved2 field is zero)\n";
382 continue;
383 }
384 uint32_t count = Sec.size / stride;
385 outs() << "Indirect symbols for (" << Sec.segname << ","
386 << Sec.sectname << ") " << count << " entries";
387 uint32_t n = Sec.reserved1;
388 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
389 }
390 }
391 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
392 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
393 for (unsigned J = 0; J < Seg.nsects; ++J) {
394 MachO::section Sec = O->getSection(Load, J);
395 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
396 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
397 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
398 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
399 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
400 section_type == MachO::S_SYMBOL_STUBS) {
401 uint32_t stride;
402 if (section_type == MachO::S_SYMBOL_STUBS)
403 stride = Sec.reserved2;
404 else
405 stride = 4;
406 if (stride == 0) {
407 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
408 << Sec.sectname << ") "
409 << "(size of stubs in reserved2 field is zero)\n";
410 continue;
411 }
412 uint32_t count = Sec.size / stride;
413 outs() << "Indirect symbols for (" << Sec.segname << ","
414 << Sec.sectname << ") " << count << " entries";
415 uint32_t n = Sec.reserved1;
416 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
417 }
418 }
419 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000420 }
421}
422
Kevin Enderby69fe98d2015-01-23 18:52:17 +0000423static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
424 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
425 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
426 outs() << "Data in code table (" << nentries << " entries)\n";
427 outs() << "offset length kind\n";
428 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
429 ++DI) {
430 uint32_t Offset;
431 DI->getOffset(Offset);
432 outs() << format("0x%08" PRIx32, Offset) << " ";
433 uint16_t Length;
434 DI->getLength(Length);
435 outs() << format("%6u", Length) << " ";
436 uint16_t Kind;
437 DI->getKind(Kind);
438 if (verbose) {
439 switch (Kind) {
440 case MachO::DICE_KIND_DATA:
441 outs() << "DATA";
442 break;
443 case MachO::DICE_KIND_JUMP_TABLE8:
444 outs() << "JUMP_TABLE8";
445 break;
446 case MachO::DICE_KIND_JUMP_TABLE16:
447 outs() << "JUMP_TABLE16";
448 break;
449 case MachO::DICE_KIND_JUMP_TABLE32:
450 outs() << "JUMP_TABLE32";
451 break;
452 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
453 outs() << "ABS_JUMP_TABLE32";
454 break;
455 default:
456 outs() << format("0x%04" PRIx32, Kind);
457 break;
458 }
459 } else
460 outs() << format("0x%04" PRIx32, Kind);
461 outs() << "\n";
462 }
463}
464
Kevin Enderby9a509442015-01-27 21:28:24 +0000465static void PrintLinkOptHints(MachOObjectFile *O) {
466 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
467 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
468 uint32_t nloh = LohLC.datasize;
469 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
470 for (uint32_t i = 0; i < nloh;) {
471 unsigned n;
472 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
473 i += n;
474 outs() << " identifier " << identifier << " ";
475 if (i >= nloh)
476 return;
477 switch (identifier) {
478 case 1:
479 outs() << "AdrpAdrp\n";
480 break;
481 case 2:
482 outs() << "AdrpLdr\n";
483 break;
484 case 3:
485 outs() << "AdrpAddLdr\n";
486 break;
487 case 4:
488 outs() << "AdrpLdrGotLdr\n";
489 break;
490 case 5:
491 outs() << "AdrpAddStr\n";
492 break;
493 case 6:
494 outs() << "AdrpLdrGotStr\n";
495 break;
496 case 7:
497 outs() << "AdrpAdd\n";
498 break;
499 case 8:
500 outs() << "AdrpLdrGot\n";
501 break;
502 default:
503 outs() << "Unknown identifier value\n";
504 break;
505 }
506 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
507 i += n;
508 outs() << " narguments " << narguments << "\n";
509 if (i >= nloh)
510 return;
511
512 for (uint32_t j = 0; j < narguments; j++) {
513 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
514 i += n;
515 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
516 if (i >= nloh)
517 return;
518 }
519 }
520}
521
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000522static void PrintDylibs(MachOObjectFile *O, bool JustId) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000523 unsigned Index = 0;
524 for (const auto &Load : O->load_commands()) {
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000525 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
526 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
527 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
528 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
529 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
530 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
531 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
532 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
533 if (dl.dylib.name < dl.cmdsize) {
534 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
535 if (JustId)
536 outs() << p << "\n";
537 else {
538 outs() << "\t" << p;
539 outs() << " (compatibility version "
540 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
541 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
542 << (dl.dylib.compatibility_version & 0xff) << ",";
543 outs() << " current version "
544 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
545 << ((dl.dylib.current_version >> 8) & 0xff) << "."
546 << (dl.dylib.current_version & 0xff) << ")\n";
547 }
548 } else {
549 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
550 if (Load.C.cmd == MachO::LC_ID_DYLIB)
551 outs() << "LC_ID_DYLIB ";
552 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
553 outs() << "LC_LOAD_DYLIB ";
554 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
555 outs() << "LC_LOAD_WEAK_DYLIB ";
556 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
557 outs() << "LC_LAZY_LOAD_DYLIB ";
558 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
559 outs() << "LC_REEXPORT_DYLIB ";
560 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
561 outs() << "LC_LOAD_UPWARD_DYLIB ";
562 else
563 outs() << "LC_??? ";
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000564 outs() << "command " << Index++ << "\n";
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000565 }
566 }
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000567 }
568}
569
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000570typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
571
572static void CreateSymbolAddressMap(MachOObjectFile *O,
573 SymbolAddressMap *AddrMap) {
574 // Create a map of symbol addresses to symbol names.
575 for (const SymbolRef &Symbol : O->symbols()) {
Rafael Espindola2fa80cc2015-06-26 12:18:49 +0000576 SymbolRef::Type ST = Symbol.getType();
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000577 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
578 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +0000579 uint64_t Address = Symbol.getValue();
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000580 ErrorOr<StringRef> SymNameOrErr = Symbol.getName();
581 if (std::error_code EC = SymNameOrErr.getError())
582 report_fatal_error(EC.message());
583 StringRef SymName = *SymNameOrErr;
Kevin Enderby846c0002015-04-16 17:19:59 +0000584 if (!SymName.startswith(".objc"))
585 (*AddrMap)[Address] = SymName;
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000586 }
587 }
588}
589
590// GuessSymbolName is passed the address of what might be a symbol and a
591// pointer to the SymbolAddressMap. It returns the name of a symbol
592// with that address or nullptr if no symbol is found with that address.
593static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
594 const char *SymbolName = nullptr;
595 // A DenseMap can't lookup up some values.
596 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
597 StringRef name = AddrMap->lookup(value);
598 if (!name.empty())
599 SymbolName = name.data();
600 }
601 return SymbolName;
602}
603
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000604static void DumpCstringChar(const char c) {
605 char p[2];
606 p[0] = c;
607 p[1] = '\0';
608 outs().write_escaped(p);
609}
610
Kevin Enderby10ba0412015-02-04 21:38:42 +0000611static void DumpCstringSection(MachOObjectFile *O, const char *sect,
612 uint32_t sect_size, uint64_t sect_addr,
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000613 bool print_addresses) {
Kevin Enderby10ba0412015-02-04 21:38:42 +0000614 for (uint32_t i = 0; i < sect_size; i++) {
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000615 if (print_addresses) {
616 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000617 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000618 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000619 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000620 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000621 for (; i < sect_size && sect[i] != '\0'; i++)
622 DumpCstringChar(sect[i]);
Kevin Enderby10ba0412015-02-04 21:38:42 +0000623 if (i < sect_size && sect[i] == '\0')
624 outs() << "\n";
625 }
626}
627
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000628static void DumpLiteral4(uint32_t l, float f) {
629 outs() << format("0x%08" PRIx32, l);
630 if ((l & 0x7f800000) != 0x7f800000)
631 outs() << format(" (%.16e)\n", f);
632 else {
633 if (l == 0x7f800000)
634 outs() << " (+Infinity)\n";
635 else if (l == 0xff800000)
636 outs() << " (-Infinity)\n";
637 else if ((l & 0x00400000) == 0x00400000)
638 outs() << " (non-signaling Not-a-Number)\n";
639 else
640 outs() << " (signaling Not-a-Number)\n";
641 }
642}
643
644static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
645 uint32_t sect_size, uint64_t sect_addr,
646 bool print_addresses) {
647 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
648 if (print_addresses) {
649 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000650 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000651 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000652 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000653 }
654 float f;
655 memcpy(&f, sect + i, sizeof(float));
656 if (O->isLittleEndian() != sys::IsLittleEndianHost)
657 sys::swapByteOrder(f);
658 uint32_t l;
659 memcpy(&l, sect + i, sizeof(uint32_t));
660 if (O->isLittleEndian() != sys::IsLittleEndianHost)
661 sys::swapByteOrder(l);
662 DumpLiteral4(l, f);
663 }
664}
665
666static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
667 double d) {
668 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
669 uint32_t Hi, Lo;
Davide Italianob627d9f2015-12-12 21:50:11 +0000670 Hi = (O->isLittleEndian()) ? l1 : l0;
671 Lo = (O->isLittleEndian()) ? l0 : l1;
672
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000673 // Hi is the high word, so this is equivalent to if(isfinite(d))
674 if ((Hi & 0x7ff00000) != 0x7ff00000)
675 outs() << format(" (%.16e)\n", d);
676 else {
677 if (Hi == 0x7ff00000 && Lo == 0)
678 outs() << " (+Infinity)\n";
679 else if (Hi == 0xfff00000 && Lo == 0)
680 outs() << " (-Infinity)\n";
681 else if ((Hi & 0x00080000) == 0x00080000)
682 outs() << " (non-signaling Not-a-Number)\n";
683 else
684 outs() << " (signaling Not-a-Number)\n";
685 }
686}
687
688static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
689 uint32_t sect_size, uint64_t sect_addr,
690 bool print_addresses) {
691 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
692 if (print_addresses) {
693 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000694 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000695 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000696 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000697 }
698 double d;
699 memcpy(&d, sect + i, sizeof(double));
700 if (O->isLittleEndian() != sys::IsLittleEndianHost)
701 sys::swapByteOrder(d);
702 uint32_t l0, l1;
703 memcpy(&l0, sect + i, sizeof(uint32_t));
704 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
705 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
706 sys::swapByteOrder(l0);
707 sys::swapByteOrder(l1);
708 }
709 DumpLiteral8(O, l0, l1, d);
710 }
711}
712
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000713static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
714 outs() << format("0x%08" PRIx32, l0) << " ";
715 outs() << format("0x%08" PRIx32, l1) << " ";
716 outs() << format("0x%08" PRIx32, l2) << " ";
717 outs() << format("0x%08" PRIx32, l3) << "\n";
718}
719
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000720static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
721 uint32_t sect_size, uint64_t sect_addr,
722 bool print_addresses) {
723 for (uint32_t i = 0; i < sect_size; i += 16) {
724 if (print_addresses) {
725 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000726 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000727 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000728 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000729 }
730 uint32_t l0, l1, l2, l3;
731 memcpy(&l0, sect + i, sizeof(uint32_t));
732 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
733 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
734 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
735 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
736 sys::swapByteOrder(l0);
737 sys::swapByteOrder(l1);
738 sys::swapByteOrder(l2);
739 sys::swapByteOrder(l3);
740 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000741 DumpLiteral16(l0, l1, l2, l3);
742 }
743}
744
745static void DumpLiteralPointerSection(MachOObjectFile *O,
746 const SectionRef &Section,
747 const char *sect, uint32_t sect_size,
748 uint64_t sect_addr,
749 bool print_addresses) {
750 // Collect the literal sections in this Mach-O file.
751 std::vector<SectionRef> LiteralSections;
752 for (const SectionRef &Section : O->sections()) {
753 DataRefImpl Ref = Section.getRawDataRefImpl();
754 uint32_t section_type;
755 if (O->is64Bit()) {
756 const MachO::section_64 Sec = O->getSection64(Ref);
757 section_type = Sec.flags & MachO::SECTION_TYPE;
758 } else {
759 const MachO::section Sec = O->getSection(Ref);
760 section_type = Sec.flags & MachO::SECTION_TYPE;
761 }
762 if (section_type == MachO::S_CSTRING_LITERALS ||
763 section_type == MachO::S_4BYTE_LITERALS ||
764 section_type == MachO::S_8BYTE_LITERALS ||
765 section_type == MachO::S_16BYTE_LITERALS)
766 LiteralSections.push_back(Section);
767 }
768
769 // Set the size of the literal pointer.
770 uint32_t lp_size = O->is64Bit() ? 8 : 4;
771
Eric Christopher572e03a2015-06-19 01:53:21 +0000772 // Collect the external relocation symbols for the literal pointers.
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000773 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
774 for (const RelocationRef &Reloc : Section.relocations()) {
775 DataRefImpl Rel;
776 MachO::any_relocation_info RE;
777 bool isExtern = false;
778 Rel = Reloc.getRawDataRefImpl();
779 RE = O->getRelocation(Rel);
780 isExtern = O->getPlainRelocationExternal(RE);
781 if (isExtern) {
Rafael Espindola96d071c2015-06-29 23:29:12 +0000782 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000783 symbol_iterator RelocSym = Reloc.getSymbol();
784 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
785 }
786 }
787 array_pod_sort(Relocs.begin(), Relocs.end());
788
789 // Dump each literal pointer.
790 for (uint32_t i = 0; i < sect_size; i += lp_size) {
791 if (print_addresses) {
792 if (O->is64Bit())
793 outs() << format("%016" PRIx64, sect_addr + i) << " ";
794 else
795 outs() << format("%08" PRIx64, sect_addr + i) << " ";
796 }
797 uint64_t lp;
798 if (O->is64Bit()) {
799 memcpy(&lp, sect + i, sizeof(uint64_t));
800 if (O->isLittleEndian() != sys::IsLittleEndianHost)
801 sys::swapByteOrder(lp);
802 } else {
803 uint32_t li;
804 memcpy(&li, sect + i, sizeof(uint32_t));
805 if (O->isLittleEndian() != sys::IsLittleEndianHost)
806 sys::swapByteOrder(li);
807 lp = li;
808 }
809
810 // First look for an external relocation entry for this literal pointer.
David Blaikie33dd45d02015-03-23 18:39:02 +0000811 auto Reloc = std::find_if(
812 Relocs.begin(), Relocs.end(),
813 [&](const std::pair<uint64_t, SymbolRef> &P) { return P.first == i; });
814 if (Reloc != Relocs.end()) {
815 symbol_iterator RelocSym = Reloc->second;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000816 ErrorOr<StringRef> SymName = RelocSym->getName();
817 if (std::error_code EC = SymName.getError())
818 report_fatal_error(EC.message());
819 outs() << "external relocation entry for symbol:" << *SymName << "\n";
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000820 continue;
David Blaikie33dd45d02015-03-23 18:39:02 +0000821 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000822
823 // For local references see what the section the literal pointer points to.
David Blaikie33dd45d02015-03-23 18:39:02 +0000824 auto Sect = std::find_if(LiteralSections.begin(), LiteralSections.end(),
825 [&](const SectionRef &R) {
826 return lp >= R.getAddress() &&
827 lp < R.getAddress() + R.getSize();
828 });
829 if (Sect == LiteralSections.end()) {
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000830 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
David Blaikie33dd45d02015-03-23 18:39:02 +0000831 continue;
832 }
833
834 uint64_t SectAddress = Sect->getAddress();
835 uint64_t SectSize = Sect->getSize();
836
837 StringRef SectName;
838 Sect->getName(SectName);
839 DataRefImpl Ref = Sect->getRawDataRefImpl();
840 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
841 outs() << SegmentName << ":" << SectName << ":";
842
843 uint32_t section_type;
844 if (O->is64Bit()) {
845 const MachO::section_64 Sec = O->getSection64(Ref);
846 section_type = Sec.flags & MachO::SECTION_TYPE;
847 } else {
848 const MachO::section Sec = O->getSection(Ref);
849 section_type = Sec.flags & MachO::SECTION_TYPE;
850 }
851
852 StringRef BytesStr;
853 Sect->getContents(BytesStr);
854 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
855
856 switch (section_type) {
857 case MachO::S_CSTRING_LITERALS:
858 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
859 i++) {
860 DumpCstringChar(Contents[i]);
861 }
862 outs() << "\n";
863 break;
864 case MachO::S_4BYTE_LITERALS:
865 float f;
866 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
867 uint32_t l;
868 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
869 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
870 sys::swapByteOrder(f);
871 sys::swapByteOrder(l);
872 }
873 DumpLiteral4(l, f);
874 break;
875 case MachO::S_8BYTE_LITERALS: {
876 double d;
877 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
878 uint32_t l0, l1;
879 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
880 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
881 sizeof(uint32_t));
882 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
883 sys::swapByteOrder(f);
884 sys::swapByteOrder(l0);
885 sys::swapByteOrder(l1);
886 }
887 DumpLiteral8(O, l0, l1, d);
888 break;
889 }
890 case MachO::S_16BYTE_LITERALS: {
891 uint32_t l0, l1, l2, l3;
892 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
893 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
894 sizeof(uint32_t));
895 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
896 sizeof(uint32_t));
897 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
898 sizeof(uint32_t));
899 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
900 sys::swapByteOrder(l0);
901 sys::swapByteOrder(l1);
902 sys::swapByteOrder(l2);
903 sys::swapByteOrder(l3);
904 }
905 DumpLiteral16(l0, l1, l2, l3);
906 break;
907 }
908 }
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000909 }
910}
911
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000912static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
913 uint32_t sect_size, uint64_t sect_addr,
914 SymbolAddressMap *AddrMap,
915 bool verbose) {
916 uint32_t stride;
Davide Italiano3eb47e22015-12-15 23:14:21 +0000917 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000918 for (uint32_t i = 0; i < sect_size; i += stride) {
919 const char *SymbolName = nullptr;
920 if (O->is64Bit()) {
921 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
922 uint64_t pointer_value;
923 memcpy(&pointer_value, sect + i, stride);
924 if (O->isLittleEndian() != sys::IsLittleEndianHost)
925 sys::swapByteOrder(pointer_value);
926 outs() << format("0x%016" PRIx64, pointer_value);
927 if (verbose)
928 SymbolName = GuessSymbolName(pointer_value, AddrMap);
929 } else {
930 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
931 uint32_t pointer_value;
932 memcpy(&pointer_value, sect + i, stride);
933 if (O->isLittleEndian() != sys::IsLittleEndianHost)
934 sys::swapByteOrder(pointer_value);
935 outs() << format("0x%08" PRIx32, pointer_value);
936 if (verbose)
937 SymbolName = GuessSymbolName(pointer_value, AddrMap);
938 }
939 if (SymbolName)
940 outs() << " " << SymbolName;
941 outs() << "\n";
942 }
943}
944
945static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
946 uint32_t size, uint64_t addr) {
947 uint32_t cputype = O->getHeader().cputype;
948 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
949 uint32_t j;
950 for (uint32_t i = 0; i < size; i += j, addr += j) {
951 if (O->is64Bit())
952 outs() << format("%016" PRIx64, addr) << "\t";
953 else
Kevin Enderbyf0640752015-03-13 17:56:32 +0000954 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000955 for (j = 0; j < 16 && i + j < size; j++) {
956 uint8_t byte_word = *(sect + i + j);
957 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
958 }
959 outs() << "\n";
960 }
961 } else {
962 uint32_t j;
963 for (uint32_t i = 0; i < size; i += j, addr += j) {
964 if (O->is64Bit())
965 outs() << format("%016" PRIx64, addr) << "\t";
966 else
967 outs() << format("%08" PRIx64, sect) << "\t";
968 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
969 j += sizeof(int32_t)) {
970 if (i + j + sizeof(int32_t) < size) {
971 uint32_t long_word;
972 memcpy(&long_word, sect + i + j, sizeof(int32_t));
973 if (O->isLittleEndian() != sys::IsLittleEndianHost)
974 sys::swapByteOrder(long_word);
975 outs() << format("%08" PRIx32, long_word) << " ";
976 } else {
977 for (uint32_t k = 0; i + j + k < size; k++) {
978 uint8_t byte_word = *(sect + i + j);
979 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
980 }
981 }
982 }
983 outs() << "\n";
984 }
985 }
986}
987
Kevin Enderby95df54c2015-02-04 01:01:38 +0000988static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
989 StringRef DisSegName, StringRef DisSectName);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +0000990static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
991 uint32_t size, uint32_t addr);
Kevin Enderby95df54c2015-02-04 01:01:38 +0000992
993static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
994 bool verbose) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000995 SymbolAddressMap AddrMap;
996 if (verbose)
997 CreateSymbolAddressMap(O, &AddrMap);
998
Colin LeMahieufcc32762015-07-29 19:08:10 +0000999 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1000 StringRef DumpSection = FilterSections[i];
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001001 std::pair<StringRef, StringRef> DumpSegSectName;
1002 DumpSegSectName = DumpSection.split(',');
1003 StringRef DumpSegName, DumpSectName;
1004 if (DumpSegSectName.second.size()) {
1005 DumpSegName = DumpSegSectName.first;
1006 DumpSectName = DumpSegSectName.second;
1007 } else {
1008 DumpSegName = "";
1009 DumpSectName = DumpSegSectName.first;
1010 }
1011 for (const SectionRef &Section : O->sections()) {
1012 StringRef SectName;
1013 Section.getName(SectName);
1014 DataRefImpl Ref = Section.getRawDataRefImpl();
1015 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1016 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1017 (SectName == DumpSectName)) {
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001018
Kevin Enderby95df54c2015-02-04 01:01:38 +00001019 uint32_t section_flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001020 if (O->is64Bit()) {
1021 const MachO::section_64 Sec = O->getSection64(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001022 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001023
1024 } else {
1025 const MachO::section Sec = O->getSection(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001026 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001027 }
Kevin Enderby95df54c2015-02-04 01:01:38 +00001028 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001029
1030 StringRef BytesStr;
1031 Section.getContents(BytesStr);
1032 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1033 uint32_t sect_size = BytesStr.size();
1034 uint64_t sect_addr = Section.getAddress();
1035
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001036 outs() << "Contents of (" << SegName << "," << SectName
1037 << ") section\n";
1038
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001039 if (verbose) {
Kevin Enderby95df54c2015-02-04 01:01:38 +00001040 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1041 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1042 DisassembleMachO(Filename, O, SegName, SectName);
1043 continue;
1044 }
Kevin Enderbycd66be52015-03-11 22:06:32 +00001045 if (SegName == "__TEXT" && SectName == "__info_plist") {
1046 outs() << sect;
1047 continue;
1048 }
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001049 if (SegName == "__OBJC" && SectName == "__protocol") {
1050 DumpProtocolSection(O, sect, sect_size, sect_addr);
1051 continue;
1052 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001053 switch (section_type) {
1054 case MachO::S_REGULAR:
1055 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1056 break;
1057 case MachO::S_ZEROFILL:
1058 outs() << "zerofill section and has no contents in the file\n";
1059 break;
Kevin Enderby10ba0412015-02-04 21:38:42 +00001060 case MachO::S_CSTRING_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001061 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001062 break;
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001063 case MachO::S_4BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001064 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001065 break;
1066 case MachO::S_8BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001067 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001068 break;
1069 case MachO::S_16BYTE_LITERALS:
Kevin Enderby0fc11822015-04-01 20:57:01 +00001070 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1071 break;
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001072 case MachO::S_LITERAL_POINTERS:
1073 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001074 !NoLeadingAddr);
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001075 break;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001076 case MachO::S_MOD_INIT_FUNC_POINTERS:
1077 case MachO::S_MOD_TERM_FUNC_POINTERS:
1078 DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
1079 verbose);
1080 break;
1081 default:
1082 outs() << "Unknown section type ("
1083 << format("0x%08" PRIx32, section_type) << ")\n";
1084 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1085 break;
1086 }
1087 } else {
1088 if (section_type == MachO::S_ZEROFILL)
1089 outs() << "zerofill section and has no contents in the file\n";
1090 else
1091 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1092 }
1093 }
1094 }
1095 }
1096}
1097
Kevin Enderbycd66be52015-03-11 22:06:32 +00001098static void DumpInfoPlistSectionContents(StringRef Filename,
1099 MachOObjectFile *O) {
1100 for (const SectionRef &Section : O->sections()) {
1101 StringRef SectName;
1102 Section.getName(SectName);
1103 DataRefImpl Ref = Section.getRawDataRefImpl();
1104 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1105 if (SegName == "__TEXT" && SectName == "__info_plist") {
1106 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1107 StringRef BytesStr;
1108 Section.getContents(BytesStr);
1109 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1110 outs() << sect;
1111 return;
1112 }
1113 }
1114}
1115
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001116// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1117// and if it is and there is a list of architecture flags is specified then
1118// check to make sure this Mach-O file is one of those architectures or all
1119// architectures were specified. If not then an error is generated and this
1120// routine returns false. Else it returns true.
1121static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1122 if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
1123 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
1124 bool ArchFound = false;
1125 MachO::mach_header H;
1126 MachO::mach_header_64 H_64;
1127 Triple T;
1128 if (MachO->is64Bit()) {
1129 H_64 = MachO->MachOObjectFile::getHeader64();
1130 T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
1131 } else {
1132 H = MachO->MachOObjectFile::getHeader();
1133 T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
1134 }
1135 unsigned i;
1136 for (i = 0; i < ArchFlags.size(); ++i) {
1137 if (ArchFlags[i] == T.getArchName())
1138 ArchFound = true;
1139 break;
1140 }
1141 if (!ArchFound) {
1142 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1143 << "architecture: " + ArchFlags[i] + "\n";
1144 return false;
1145 }
1146 }
1147 return true;
1148}
1149
Kevin Enderby0fc11822015-04-01 20:57:01 +00001150static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1151
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001152// ProcessMachO() is passed a single opened Mach-O file, which may be an
1153// archive member and or in a slice of a universal file. It prints the
1154// the file name and header info and then processes it according to the
1155// command line options.
1156static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
1157 StringRef ArchiveMemberName = StringRef(),
1158 StringRef ArchitectureName = StringRef()) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001159 // If we are doing some processing here on the Mach-O file print the header
1160 // info. And don't print it otherwise like in the case of printing the
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001161 // UniversalHeaders or ArchiveHeaders.
Kevin Enderby131d1772015-01-09 19:22:37 +00001162 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind ||
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001163 LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints ||
Colin LeMahieufcc32762015-07-29 19:08:10 +00001164 DylibsUsed || DylibId || ObjcMetaData || (FilterSections.size() != 0)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001165 outs() << Filename;
1166 if (!ArchiveMemberName.empty())
1167 outs() << '(' << ArchiveMemberName << ')';
1168 if (!ArchitectureName.empty())
1169 outs() << " (architecture " << ArchitectureName << ")";
1170 outs() << ":\n";
1171 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001172
1173 if (Disassemble)
Kevin Enderby95df54c2015-02-04 01:01:38 +00001174 DisassembleMachO(Filename, MachOOF, "__TEXT", "__text");
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001175 if (IndirectSymbols)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001176 PrintIndirectSymbols(MachOOF, !NonVerbose);
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001177 if (DataInCode)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001178 PrintDataInCodeTable(MachOOF, !NonVerbose);
Kevin Enderby9a509442015-01-27 21:28:24 +00001179 if (LinkOptHints)
1180 PrintLinkOptHints(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001181 if (Relocations)
1182 PrintRelocations(MachOOF);
1183 if (SectionHeaders)
1184 PrintSectionHeaders(MachOOF);
1185 if (SectionContents)
1186 PrintSectionContents(MachOOF);
Colin LeMahieufcc32762015-07-29 19:08:10 +00001187 if (FilterSections.size() != 0)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001188 DumpSectionContents(Filename, MachOOF, !NonVerbose);
Kevin Enderbycd66be52015-03-11 22:06:32 +00001189 if (InfoPlist)
1190 DumpInfoPlistSectionContents(Filename, MachOOF);
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001191 if (DylibsUsed)
1192 PrintDylibs(MachOOF, false);
1193 if (DylibId)
1194 PrintDylibs(MachOOF, true);
Kevin Enderby98da6132015-01-20 21:47:46 +00001195 if (SymbolTable)
1196 PrintSymbolTable(MachOOF);
1197 if (UnwindInfo)
1198 printMachOUnwindInfo(MachOOF);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001199 if (PrivateHeaders)
1200 printMachOFileHeader(MachOOF);
Kevin Enderby0fc11822015-04-01 20:57:01 +00001201 if (ObjcMetaData)
1202 printObjcMetaData(MachOOF, !NonVerbose);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001203 if (ExportsTrie)
1204 printExportsTrie(MachOOF);
1205 if (Rebase)
1206 printRebaseTable(MachOOF);
1207 if (Bind)
1208 printBindTable(MachOOF);
1209 if (LazyBind)
1210 printLazyBindTable(MachOOF);
1211 if (WeakBind)
1212 printWeakBindTable(MachOOF);
Pete Cooper6c97f4c2015-12-18 18:51:08 +00001213
1214 if (DwarfDumpType != DIDT_Null) {
1215 std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*MachOOF));
1216 // Dump the complete DWARF structure.
1217 DICtx->dump(outs(), DwarfDumpType, true /* DumpEH */);
1218 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001219}
1220
Kevin Enderby131d1772015-01-09 19:22:37 +00001221// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1222static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1223 outs() << " cputype (" << cputype << ")\n";
1224 outs() << " cpusubtype (" << cpusubtype << ")\n";
1225}
1226
1227// printCPUType() helps print_fat_headers by printing the cputype and
1228// pusubtype (symbolically for the one's it knows about).
1229static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1230 switch (cputype) {
1231 case MachO::CPU_TYPE_I386:
1232 switch (cpusubtype) {
1233 case MachO::CPU_SUBTYPE_I386_ALL:
1234 outs() << " cputype CPU_TYPE_I386\n";
1235 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1236 break;
1237 default:
1238 printUnknownCPUType(cputype, cpusubtype);
1239 break;
1240 }
1241 break;
1242 case MachO::CPU_TYPE_X86_64:
1243 switch (cpusubtype) {
1244 case MachO::CPU_SUBTYPE_X86_64_ALL:
1245 outs() << " cputype CPU_TYPE_X86_64\n";
1246 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1247 break;
1248 case MachO::CPU_SUBTYPE_X86_64_H:
1249 outs() << " cputype CPU_TYPE_X86_64\n";
1250 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1251 break;
1252 default:
1253 printUnknownCPUType(cputype, cpusubtype);
1254 break;
1255 }
1256 break;
1257 case MachO::CPU_TYPE_ARM:
1258 switch (cpusubtype) {
1259 case MachO::CPU_SUBTYPE_ARM_ALL:
1260 outs() << " cputype CPU_TYPE_ARM\n";
1261 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1262 break;
1263 case MachO::CPU_SUBTYPE_ARM_V4T:
1264 outs() << " cputype CPU_TYPE_ARM\n";
1265 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1266 break;
1267 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1268 outs() << " cputype CPU_TYPE_ARM\n";
1269 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1270 break;
1271 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1272 outs() << " cputype CPU_TYPE_ARM\n";
1273 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1274 break;
1275 case MachO::CPU_SUBTYPE_ARM_V6:
1276 outs() << " cputype CPU_TYPE_ARM\n";
1277 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1278 break;
1279 case MachO::CPU_SUBTYPE_ARM_V6M:
1280 outs() << " cputype CPU_TYPE_ARM\n";
1281 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1282 break;
1283 case MachO::CPU_SUBTYPE_ARM_V7:
1284 outs() << " cputype CPU_TYPE_ARM\n";
1285 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1286 break;
1287 case MachO::CPU_SUBTYPE_ARM_V7EM:
1288 outs() << " cputype CPU_TYPE_ARM\n";
1289 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1290 break;
1291 case MachO::CPU_SUBTYPE_ARM_V7K:
1292 outs() << " cputype CPU_TYPE_ARM\n";
1293 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1294 break;
1295 case MachO::CPU_SUBTYPE_ARM_V7M:
1296 outs() << " cputype CPU_TYPE_ARM\n";
1297 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1298 break;
1299 case MachO::CPU_SUBTYPE_ARM_V7S:
1300 outs() << " cputype CPU_TYPE_ARM\n";
1301 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1302 break;
1303 default:
1304 printUnknownCPUType(cputype, cpusubtype);
1305 break;
1306 }
1307 break;
1308 case MachO::CPU_TYPE_ARM64:
1309 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1310 case MachO::CPU_SUBTYPE_ARM64_ALL:
1311 outs() << " cputype CPU_TYPE_ARM64\n";
1312 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1313 break;
1314 default:
1315 printUnknownCPUType(cputype, cpusubtype);
1316 break;
1317 }
1318 break;
1319 default:
1320 printUnknownCPUType(cputype, cpusubtype);
1321 break;
1322 }
1323}
1324
1325static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1326 bool verbose) {
1327 outs() << "Fat headers\n";
1328 if (verbose)
1329 outs() << "fat_magic FAT_MAGIC\n";
1330 else
1331 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1332
1333 uint32_t nfat_arch = UB->getNumberOfObjects();
1334 StringRef Buf = UB->getData();
1335 uint64_t size = Buf.size();
1336 uint64_t big_size = sizeof(struct MachO::fat_header) +
1337 nfat_arch * sizeof(struct MachO::fat_arch);
1338 outs() << "nfat_arch " << UB->getNumberOfObjects();
1339 if (nfat_arch == 0)
1340 outs() << " (malformed, contains zero architecture types)\n";
1341 else if (big_size > size)
1342 outs() << " (malformed, architectures past end of file)\n";
1343 else
1344 outs() << "\n";
1345
1346 for (uint32_t i = 0; i < nfat_arch; ++i) {
1347 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1348 uint32_t cputype = OFA.getCPUType();
1349 uint32_t cpusubtype = OFA.getCPUSubType();
1350 outs() << "architecture ";
1351 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1352 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1353 uint32_t other_cputype = other_OFA.getCPUType();
1354 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
Kevin Enderby0512bd72015-01-09 21:55:03 +00001355 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
Kevin Enderby131d1772015-01-09 19:22:37 +00001356 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
Kevin Enderby0512bd72015-01-09 21:55:03 +00001357 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001358 outs() << "(illegal duplicate architecture) ";
1359 break;
Kevin Enderby0512bd72015-01-09 21:55:03 +00001360 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001361 }
1362 if (verbose) {
1363 outs() << OFA.getArchTypeName() << "\n";
1364 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1365 } else {
1366 outs() << i << "\n";
1367 outs() << " cputype " << cputype << "\n";
1368 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1369 << "\n";
1370 }
1371 if (verbose &&
1372 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1373 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1374 else
1375 outs() << " capabilities "
1376 << format("0x%" PRIx32,
1377 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1378 outs() << " offset " << OFA.getOffset();
1379 if (OFA.getOffset() > size)
1380 outs() << " (past end of file)";
1381 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1382 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1383 outs() << "\n";
1384 outs() << " size " << OFA.getSize();
1385 big_size = OFA.getOffset() + OFA.getSize();
1386 if (big_size > size)
1387 outs() << " (past end of file)";
1388 outs() << "\n";
1389 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1390 << ")\n";
1391 }
1392}
1393
Rafael Espindola266b4fe2015-10-31 22:25:59 +00001394static void printArchiveChild(const Archive::Child &C, bool verbose,
Kevin Enderby13023a12015-01-15 23:19:11 +00001395 bool print_offset) {
1396 if (print_offset)
1397 outs() << C.getChildOffset() << "\t";
1398 sys::fs::perms Mode = C.getAccessMode();
1399 if (verbose) {
1400 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1401 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1402 outs() << "-";
Davide Italianobb9a6cc2015-09-07 20:47:03 +00001403 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1404 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1405 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1406 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1407 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1408 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1409 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1410 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1411 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
Kevin Enderby13023a12015-01-15 23:19:11 +00001412 } else {
1413 outs() << format("0%o ", Mode);
1414 }
1415
1416 unsigned UID = C.getUID();
1417 outs() << format("%3d/", UID);
1418 unsigned GID = C.getGID();
1419 outs() << format("%-3d ", GID);
Kevin Enderby7a969422015-11-05 19:24:56 +00001420 ErrorOr<uint64_t> Size = C.getRawSize();
1421 if (std::error_code EC = Size.getError())
1422 report_fatal_error(EC.message());
1423 outs() << format("%5" PRId64, Size.get()) << " ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001424
1425 StringRef RawLastModified = C.getRawLastModified();
1426 if (verbose) {
1427 unsigned Seconds;
1428 if (RawLastModified.getAsInteger(10, Seconds))
1429 outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
1430 else {
1431 // Since cime(3) returns a 26 character string of the form:
1432 // "Sun Sep 16 01:03:52 1973\n\0"
1433 // just print 24 characters.
1434 time_t t = Seconds;
1435 outs() << format("%.24s ", ctime(&t));
1436 }
1437 } else {
1438 outs() << RawLastModified << " ";
1439 }
1440
1441 if (verbose) {
1442 ErrorOr<StringRef> NameOrErr = C.getName();
1443 if (NameOrErr.getError()) {
1444 StringRef RawName = C.getRawName();
1445 outs() << RawName << "\n";
1446 } else {
1447 StringRef Name = NameOrErr.get();
1448 outs() << Name << "\n";
1449 }
1450 } else {
1451 StringRef RawName = C.getRawName();
1452 outs() << RawName << "\n";
1453 }
1454}
1455
1456static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
Rafael Espindola4a782fb2015-10-31 21:03:29 +00001457 for (Archive::child_iterator I = A->child_begin(false), E = A->child_end();
1458 I != E; ++I) {
Kevin Enderby7a969422015-11-05 19:24:56 +00001459 if (std::error_code EC = I->getError())
1460 report_fatal_error(EC.message());
1461 const Archive::Child &C = **I;
Kevin Enderby13023a12015-01-15 23:19:11 +00001462 printArchiveChild(C, verbose, print_offset);
1463 }
1464}
1465
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001466// ParseInputMachO() parses the named Mach-O file in Filename and handles the
1467// -arch flags selecting just those slices as specified by them and also parses
1468// archive files. Then for each individual Mach-O file ProcessMachO() is
1469// called to process the file based on the command line options.
1470void llvm::ParseInputMachO(StringRef Filename) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001471 // Check for -arch all and verifiy the -arch flags are valid.
1472 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1473 if (ArchFlags[i] == "all") {
1474 ArchAll = true;
1475 } else {
1476 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1477 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1478 "'for the -arch option\n";
1479 return;
1480 }
1481 }
1482 }
1483
1484 // Attempt to open the binary.
1485 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1486 if (std::error_code EC = BinaryOrErr.getError()) {
1487 errs() << "llvm-objdump: '" << Filename << "': " << EC.message() << ".\n";
Rafael Espindolade882cd2014-12-03 23:29:34 +00001488 return;
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001489 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001490 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001491
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001492 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1493 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001494 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001495 printArchiveHeaders(A, !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001496 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
1497 I != E; ++I) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001498 if (std::error_code EC = I->getError())
1499 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001500 auto &C = I->get();
1501 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001502 if (ChildOrErr.getError())
1503 continue;
1504 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1505 if (!checkMachOAndArchFlags(O, Filename))
1506 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001507 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001508 }
1509 }
1510 return;
1511 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001512 if (UniversalHeaders) {
1513 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
Kevin Enderbyf0640752015-03-13 17:56:32 +00001514 printMachOUniversalHeaders(UB, !NonVerbose);
Kevin Enderby131d1772015-01-09 19:22:37 +00001515 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001516 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1517 // If we have a list of architecture flags specified dump only those.
1518 if (!ArchAll && ArchFlags.size() != 0) {
1519 // Look for a slice in the universal binary that matches each ArchFlag.
1520 bool ArchFound;
1521 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1522 ArchFound = false;
1523 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1524 E = UB->end_objects();
1525 I != E; ++I) {
1526 if (ArchFlags[i] == I->getArchTypeName()) {
1527 ArchFound = true;
1528 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
1529 I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001530 std::string ArchitectureName = "";
1531 if (ArchFlags.size() > 1)
1532 ArchitectureName = I->getArchTypeName();
1533 if (ObjOrErr) {
1534 ObjectFile &O = *ObjOrErr.get();
1535 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001536 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001537 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1538 I->getAsArchive()) {
1539 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001540 outs() << "Archive : " << Filename;
1541 if (!ArchitectureName.empty())
1542 outs() << " (architecture " << ArchitectureName << ")";
1543 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001544 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001545 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001546 for (Archive::child_iterator AI = A->child_begin(),
1547 AE = A->child_end();
1548 AI != AE; ++AI) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001549 if (std::error_code EC = AI->getError())
1550 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001551 auto &C = AI->get();
1552 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001553 if (ChildOrErr.getError())
1554 continue;
1555 if (MachOObjectFile *O =
1556 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001557 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001558 }
1559 }
1560 }
1561 }
1562 if (!ArchFound) {
1563 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1564 << "architecture: " + ArchFlags[i] + "\n";
1565 return;
1566 }
1567 }
1568 return;
1569 }
1570 // No architecture flags were specified so if this contains a slice that
1571 // matches the host architecture dump only that.
1572 if (!ArchAll) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001573 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1574 E = UB->end_objects();
1575 I != E; ++I) {
Kevin Enderby0512bd72015-01-09 21:55:03 +00001576 if (MachOObjectFile::getHostArch().getArchName() ==
1577 I->getArchTypeName()) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001578 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001579 std::string ArchiveName;
1580 ArchiveName.clear();
1581 if (ObjOrErr) {
1582 ObjectFile &O = *ObjOrErr.get();
1583 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001584 ProcessMachO(Filename, MachOOF);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001585 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1586 I->getAsArchive()) {
1587 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001588 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001589 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001590 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001591 for (Archive::child_iterator AI = A->child_begin(),
1592 AE = A->child_end();
1593 AI != AE; ++AI) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001594 if (std::error_code EC = AI->getError())
1595 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001596 auto &C = AI->get();
1597 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001598 if (ChildOrErr.getError())
1599 continue;
1600 if (MachOObjectFile *O =
1601 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001602 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001603 }
1604 }
1605 return;
1606 }
1607 }
1608 }
1609 // Either all architectures have been specified or none have been specified
1610 // and this does not contain the host architecture so dump all the slices.
1611 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1612 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1613 E = UB->end_objects();
1614 I != E; ++I) {
1615 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001616 std::string ArchitectureName = "";
1617 if (moreThanOneArch)
1618 ArchitectureName = I->getArchTypeName();
1619 if (ObjOrErr) {
1620 ObjectFile &Obj = *ObjOrErr.get();
1621 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001622 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001623 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
1624 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001625 outs() << "Archive : " << Filename;
1626 if (!ArchitectureName.empty())
1627 outs() << " (architecture " << ArchitectureName << ")";
1628 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001629 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001630 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001631 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
1632 AI != AE; ++AI) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001633 if (std::error_code EC = AI->getError())
1634 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001635 auto &C = AI->get();
1636 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001637 if (ChildOrErr.getError())
1638 continue;
1639 if (MachOObjectFile *O =
1640 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1641 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001642 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1643 ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001644 }
1645 }
1646 }
1647 }
1648 return;
1649 }
1650 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1651 if (!checkMachOAndArchFlags(O, Filename))
1652 return;
1653 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001654 ProcessMachO(Filename, MachOOF);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001655 } else
1656 errs() << "llvm-objdump: '" << Filename << "': "
1657 << "Object is not a Mach-O file type.\n";
1658 } else
1659 errs() << "llvm-objdump: '" << Filename << "': "
1660 << "Unrecognized file type.\n";
Rafael Espindola9b709252013-04-13 01:45:40 +00001661}
1662
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001663typedef std::pair<uint64_t, const char *> BindInfoEntry;
1664typedef std::vector<BindInfoEntry> BindTable;
1665typedef BindTable::iterator bind_table_iterator;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001666
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001667// The block of info used by the Symbolizer call backs.
1668struct DisassembleInfo {
1669 bool verbose;
1670 MachOObjectFile *O;
1671 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001672 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001673 std::vector<SectionRef> *Sections;
1674 const char *class_name;
1675 const char *selector_name;
1676 char *method;
Kevin Enderby04bf6932014-10-28 23:39:46 +00001677 char *demangled_name;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001678 uint64_t adrp_addr;
1679 uint32_t adrp_inst;
Kevin Enderby078be602014-10-23 19:53:12 +00001680 BindTable *bindtable;
Kevin Enderbyaac75382015-10-08 16:56:35 +00001681 uint32_t depth;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001682};
1683
1684// SymbolizerGetOpInfo() is the operand information call back function.
1685// This is called to get the symbolic information for operand(s) of an
1686// instruction when it is being done. This routine does this from
1687// the relocation information, symbol table, etc. That block of information
1688// is a pointer to the struct DisassembleInfo that was passed when the
1689// disassembler context was created and passed to back to here when
1690// called back by the disassembler for instruction operands that could have
1691// relocation information. The address of the instruction containing operand is
1692// at the Pc parameter. The immediate value the operand has is passed in
1693// op_info->Value and is at Offset past the start of the instruction and has a
1694// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1695// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1696// names and addends of the symbolic expression to add for the operand. The
1697// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1698// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001699static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1700 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001701 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1702 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001703 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001704
1705 // Make sure all fields returned are zero if we don't set them.
1706 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1707 op_info->Value = value;
1708
1709 // If the TagType is not the value 1 which it code knows about or if no
1710 // verbose symbolic information is wanted then just return 0, indicating no
1711 // information is being returned.
David Blaikie33dd45d02015-03-23 18:39:02 +00001712 if (TagType != 1 || !info->verbose)
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001713 return 0;
1714
1715 unsigned int Arch = info->O->getArch();
1716 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001717 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1718 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001719 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1720 // TODO:
1721 // Search the external relocation entries of a fully linked image
1722 // (if any) for an entry that matches this segment offset.
1723 // uint32_t seg_offset = (Pc + Offset);
1724 return 0;
1725 }
1726 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1727 // for an entry for this section offset.
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001728 uint32_t sect_addr = info->S.getAddress();
1729 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1730 bool reloc_found = false;
1731 DataRefImpl Rel;
1732 MachO::any_relocation_info RE;
1733 bool isExtern = false;
1734 SymbolRef Symbol;
1735 bool r_scattered = false;
1736 uint32_t r_value, pair_r_value, r_type;
1737 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001738 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001739 if (RelocOffset == sect_offset) {
1740 Rel = Reloc.getRawDataRefImpl();
1741 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00001742 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001743 r_scattered = info->O->isRelocationScattered(RE);
1744 if (r_scattered) {
1745 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001746 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1747 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1748 DataRefImpl RelNext = Rel;
1749 info->O->moveRelocationNext(RelNext);
1750 MachO::any_relocation_info RENext;
1751 RENext = info->O->getRelocation(RelNext);
1752 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00001753 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001754 else
1755 return 0;
1756 }
1757 } else {
1758 isExtern = info->O->getPlainRelocationExternal(RE);
1759 if (isExtern) {
1760 symbol_iterator RelocSym = Reloc.getSymbol();
1761 Symbol = *RelocSym;
1762 }
1763 }
1764 reloc_found = true;
1765 break;
1766 }
1767 }
1768 if (reloc_found && isExtern) {
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001769 ErrorOr<StringRef> SymName = Symbol.getName();
1770 if (std::error_code EC = SymName.getError())
1771 report_fatal_error(EC.message());
1772 const char *name = SymName->data();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001773 op_info->AddSymbol.Present = 1;
1774 op_info->AddSymbol.Name = name;
1775 // For i386 extern relocation entries the value in the instruction is
1776 // the offset from the symbol, and value is already set in op_info->Value.
1777 return 1;
1778 }
1779 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1780 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001781 const char *add = GuessSymbolName(r_value, info->AddrMap);
1782 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001783 uint32_t offset = value - (r_value - pair_r_value);
1784 op_info->AddSymbol.Present = 1;
1785 if (add != nullptr)
1786 op_info->AddSymbol.Name = add;
1787 else
1788 op_info->AddSymbol.Value = r_value;
1789 op_info->SubtractSymbol.Present = 1;
1790 if (sub != nullptr)
1791 op_info->SubtractSymbol.Name = sub;
1792 else
1793 op_info->SubtractSymbol.Value = pair_r_value;
1794 op_info->Value = offset;
1795 return 1;
1796 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001797 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001798 }
1799 if (Arch == Triple::x86_64) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001800 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1801 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001802 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1803 // TODO:
1804 // Search the external relocation entries of a fully linked image
1805 // (if any) for an entry that matches this segment offset.
1806 // uint64_t seg_offset = (Pc + Offset);
1807 return 0;
1808 }
1809 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1810 // for an entry for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00001811 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001812 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1813 bool reloc_found = false;
1814 DataRefImpl Rel;
1815 MachO::any_relocation_info RE;
1816 bool isExtern = false;
1817 SymbolRef Symbol;
1818 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001819 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001820 if (RelocOffset == sect_offset) {
1821 Rel = Reloc.getRawDataRefImpl();
1822 RE = info->O->getRelocation(Rel);
1823 // NOTE: Scattered relocations don't exist on x86_64.
1824 isExtern = info->O->getPlainRelocationExternal(RE);
1825 if (isExtern) {
1826 symbol_iterator RelocSym = Reloc.getSymbol();
1827 Symbol = *RelocSym;
1828 }
1829 reloc_found = true;
1830 break;
1831 }
1832 }
1833 if (reloc_found && isExtern) {
1834 // The Value passed in will be adjusted by the Pc if the instruction
1835 // adds the Pc. But for x86_64 external relocation entries the Value
1836 // is the offset from the external symbol.
1837 if (info->O->getAnyRelocationPCRel(RE))
1838 op_info->Value -= Pc + Offset + Size;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001839 ErrorOr<StringRef> SymName = Symbol.getName();
1840 if (std::error_code EC = SymName.getError())
1841 report_fatal_error(EC.message());
1842 const char *name = SymName->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001843 unsigned Type = info->O->getAnyRelocationType(RE);
1844 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1845 DataRefImpl RelNext = Rel;
1846 info->O->moveRelocationNext(RelNext);
1847 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1848 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1849 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1850 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1851 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1852 op_info->SubtractSymbol.Present = 1;
1853 op_info->SubtractSymbol.Name = name;
1854 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1855 Symbol = *RelocSymNext;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001856 ErrorOr<StringRef> SymNameNext = Symbol.getName();
1857 if (std::error_code EC = SymNameNext.getError())
1858 report_fatal_error(EC.message());
1859 name = SymNameNext->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001860 }
1861 }
1862 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1863 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1864 op_info->AddSymbol.Present = 1;
1865 op_info->AddSymbol.Name = name;
1866 return 1;
1867 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001868 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001869 }
1870 if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00001871 if (Offset != 0 || (Size != 4 && Size != 2))
1872 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001873 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1874 // TODO:
1875 // Search the external relocation entries of a fully linked image
1876 // (if any) for an entry that matches this segment offset.
1877 // uint32_t seg_offset = (Pc + Offset);
1878 return 0;
1879 }
1880 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1881 // for an entry for this section offset.
Kevin Enderby930fdc72014-11-06 19:00:13 +00001882 uint32_t sect_addr = info->S.getAddress();
1883 uint32_t sect_offset = (Pc + Offset) - sect_addr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001884 DataRefImpl Rel;
1885 MachO::any_relocation_info RE;
1886 bool isExtern = false;
1887 SymbolRef Symbol;
1888 bool r_scattered = false;
1889 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
David Blaikie33dd45d02015-03-23 18:39:02 +00001890 auto Reloc =
1891 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
1892 [&](const RelocationRef &Reloc) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001893 uint64_t RelocOffset = Reloc.getOffset();
David Blaikie33dd45d02015-03-23 18:39:02 +00001894 return RelocOffset == sect_offset;
1895 });
1896
1897 if (Reloc == info->S.relocations().end())
1898 return 0;
1899
1900 Rel = Reloc->getRawDataRefImpl();
1901 RE = info->O->getRelocation(Rel);
1902 r_length = info->O->getAnyRelocationLength(RE);
1903 r_scattered = info->O->isRelocationScattered(RE);
1904 if (r_scattered) {
1905 r_value = info->O->getScatteredRelocationValue(RE);
1906 r_type = info->O->getScatteredRelocationType(RE);
1907 } else {
1908 r_type = info->O->getAnyRelocationType(RE);
1909 isExtern = info->O->getPlainRelocationExternal(RE);
1910 if (isExtern) {
1911 symbol_iterator RelocSym = Reloc->getSymbol();
1912 Symbol = *RelocSym;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001913 }
1914 }
David Blaikie33dd45d02015-03-23 18:39:02 +00001915 if (r_type == MachO::ARM_RELOC_HALF ||
1916 r_type == MachO::ARM_RELOC_SECTDIFF ||
1917 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1918 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1919 DataRefImpl RelNext = Rel;
1920 info->O->moveRelocationNext(RelNext);
1921 MachO::any_relocation_info RENext;
1922 RENext = info->O->getRelocation(RelNext);
1923 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
1924 if (info->O->isRelocationScattered(RENext))
1925 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1926 }
1927
1928 if (isExtern) {
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001929 ErrorOr<StringRef> SymName = Symbol.getName();
1930 if (std::error_code EC = SymName.getError())
1931 report_fatal_error(EC.message());
1932 const char *name = SymName->data();
Kevin Enderby930fdc72014-11-06 19:00:13 +00001933 op_info->AddSymbol.Present = 1;
1934 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00001935 switch (r_type) {
1936 case MachO::ARM_RELOC_HALF:
1937 if ((r_length & 0x1) == 1) {
1938 op_info->Value = value << 16 | other_half;
1939 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1940 } else {
1941 op_info->Value = other_half << 16 | value;
1942 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00001943 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00001944 break;
1945 default:
1946 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001947 }
1948 return 1;
1949 }
1950 // If we have a branch that is not an external relocation entry then
1951 // return 0 so the code in tryAddingSymbolicOperand() can use the
1952 // SymbolLookUp call back with the branch target address to look up the
1953 // symbol and possiblity add an annotation for a symbol stub.
David Blaikie33dd45d02015-03-23 18:39:02 +00001954 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
1955 r_type == MachO::ARM_THUMB_RELOC_BR22))
Kevin Enderby930fdc72014-11-06 19:00:13 +00001956 return 0;
1957
1958 uint32_t offset = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001959 if (r_type == MachO::ARM_RELOC_HALF ||
1960 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1961 if ((r_length & 0x1) == 1)
1962 value = value << 16 | other_half;
1963 else
1964 value = other_half << 16 | value;
1965 }
1966 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
1967 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
1968 offset = value - r_value;
1969 value = r_value;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001970 }
1971
David Blaikie33dd45d02015-03-23 18:39:02 +00001972 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00001973 if ((r_length & 0x1) == 1)
1974 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1975 else
1976 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001977 const char *add = GuessSymbolName(r_value, info->AddrMap);
1978 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00001979 int32_t offset = value - (r_value - pair_r_value);
1980 op_info->AddSymbol.Present = 1;
1981 if (add != nullptr)
1982 op_info->AddSymbol.Name = add;
1983 else
1984 op_info->AddSymbol.Value = r_value;
1985 op_info->SubtractSymbol.Present = 1;
1986 if (sub != nullptr)
1987 op_info->SubtractSymbol.Name = sub;
1988 else
1989 op_info->SubtractSymbol.Value = pair_r_value;
1990 op_info->Value = offset;
1991 return 1;
1992 }
1993
Kevin Enderby930fdc72014-11-06 19:00:13 +00001994 op_info->AddSymbol.Present = 1;
1995 op_info->Value = offset;
David Blaikie33dd45d02015-03-23 18:39:02 +00001996 if (r_type == MachO::ARM_RELOC_HALF) {
1997 if ((r_length & 0x1) == 1)
1998 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1999 else
2000 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002001 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002002 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002003 if (add != nullptr) {
2004 op_info->AddSymbol.Name = add;
2005 return 1;
2006 }
2007 op_info->AddSymbol.Value = value;
2008 return 1;
David Blaikie33dd45d02015-03-23 18:39:02 +00002009 }
2010 if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002011 if (Offset != 0 || Size != 4)
2012 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002013 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2014 // TODO:
2015 // Search the external relocation entries of a fully linked image
2016 // (if any) for an entry that matches this segment offset.
2017 // uint64_t seg_offset = (Pc + Offset);
2018 return 0;
2019 }
2020 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2021 // for an entry for this section offset.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002022 uint64_t sect_addr = info->S.getAddress();
2023 uint64_t sect_offset = (Pc + Offset) - sect_addr;
David Blaikie33dd45d02015-03-23 18:39:02 +00002024 auto Reloc =
2025 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
2026 [&](const RelocationRef &Reloc) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002027 uint64_t RelocOffset = Reloc.getOffset();
David Blaikie33dd45d02015-03-23 18:39:02 +00002028 return RelocOffset == sect_offset;
2029 });
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002030
David Blaikie33dd45d02015-03-23 18:39:02 +00002031 if (Reloc == info->S.relocations().end())
2032 return 0;
2033
2034 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2035 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2036 uint32_t r_type = info->O->getAnyRelocationType(RE);
2037 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2038 DataRefImpl RelNext = Rel;
2039 info->O->moveRelocationNext(RelNext);
2040 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2041 if (value == 0) {
2042 value = info->O->getPlainRelocationSymbolNum(RENext);
2043 op_info->Value = value;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002044 }
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002045 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002046 // NOTE: Scattered relocations don't exist on arm64.
2047 if (!info->O->getPlainRelocationExternal(RE))
2048 return 0;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002049 ErrorOr<StringRef> SymName = Reloc->getSymbol()->getName();
2050 if (std::error_code EC = SymName.getError())
2051 report_fatal_error(EC.message());
2052 const char *name = SymName->data();
David Blaikie33dd45d02015-03-23 18:39:02 +00002053 op_info->AddSymbol.Present = 1;
2054 op_info->AddSymbol.Name = name;
2055
2056 switch (r_type) {
2057 case MachO::ARM64_RELOC_PAGE21:
2058 /* @page */
2059 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2060 break;
2061 case MachO::ARM64_RELOC_PAGEOFF12:
2062 /* @pageoff */
2063 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2064 break;
2065 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2066 /* @gotpage */
2067 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2068 break;
2069 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2070 /* @gotpageoff */
2071 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2072 break;
2073 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2074 /* @tvlppage is not implemented in llvm-mc */
2075 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2076 break;
2077 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2078 /* @tvlppageoff is not implemented in llvm-mc */
2079 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2080 break;
2081 default:
2082 case MachO::ARM64_RELOC_BRANCH26:
2083 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2084 break;
2085 }
2086 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002087 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002088 return 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002089}
2090
Kevin Enderbybf246f52014-09-24 23:08:22 +00002091// GuessCstringPointer is passed the address of what might be a pointer to a
2092// literal string in a cstring section. If that address is in a cstring section
2093// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002094static const char *GuessCstringPointer(uint64_t ReferenceValue,
2095 struct DisassembleInfo *info) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002096 for (const auto &Load : info->O->load_commands()) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002097 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2098 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2099 for (unsigned J = 0; J < Seg.nsects; ++J) {
2100 MachO::section_64 Sec = info->O->getSection64(Load, J);
2101 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2102 if (section_type == MachO::S_CSTRING_LITERALS &&
2103 ReferenceValue >= Sec.addr &&
2104 ReferenceValue < Sec.addr + Sec.size) {
2105 uint64_t sect_offset = ReferenceValue - Sec.addr;
2106 uint64_t object_offset = Sec.offset + sect_offset;
2107 StringRef MachOContents = info->O->getData();
2108 uint64_t object_size = MachOContents.size();
2109 const char *object_addr = (const char *)MachOContents.data();
2110 if (object_offset < object_size) {
2111 const char *name = object_addr + object_offset;
2112 return name;
2113 } else {
2114 return nullptr;
2115 }
2116 }
2117 }
2118 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2119 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2120 for (unsigned J = 0; J < Seg.nsects; ++J) {
2121 MachO::section Sec = info->O->getSection(Load, J);
2122 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2123 if (section_type == MachO::S_CSTRING_LITERALS &&
2124 ReferenceValue >= Sec.addr &&
2125 ReferenceValue < Sec.addr + Sec.size) {
2126 uint64_t sect_offset = ReferenceValue - Sec.addr;
2127 uint64_t object_offset = Sec.offset + sect_offset;
2128 StringRef MachOContents = info->O->getData();
2129 uint64_t object_size = MachOContents.size();
2130 const char *object_addr = (const char *)MachOContents.data();
2131 if (object_offset < object_size) {
2132 const char *name = object_addr + object_offset;
2133 return name;
2134 } else {
2135 return nullptr;
2136 }
2137 }
2138 }
2139 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002140 }
2141 return nullptr;
2142}
2143
Kevin Enderby85974882014-09-26 22:20:44 +00002144// GuessIndirectSymbol returns the name of the indirect symbol for the
2145// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2146// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2147// symbol name being referenced by the stub or pointer.
2148static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2149 struct DisassembleInfo *info) {
Kevin Enderby85974882014-09-26 22:20:44 +00002150 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2151 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002152 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby85974882014-09-26 22:20:44 +00002153 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2154 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2155 for (unsigned J = 0; J < Seg.nsects; ++J) {
2156 MachO::section_64 Sec = info->O->getSection64(Load, J);
2157 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2158 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2159 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2160 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2161 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2162 section_type == MachO::S_SYMBOL_STUBS) &&
2163 ReferenceValue >= Sec.addr &&
2164 ReferenceValue < Sec.addr + Sec.size) {
2165 uint32_t stride;
2166 if (section_type == MachO::S_SYMBOL_STUBS)
2167 stride = Sec.reserved2;
2168 else
2169 stride = 8;
2170 if (stride == 0)
2171 return nullptr;
2172 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2173 if (index < Dysymtab.nindirectsyms) {
2174 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002175 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002176 if (indirect_symbol < Symtab.nsyms) {
2177 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2178 SymbolRef Symbol = *Sym;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002179 ErrorOr<StringRef> SymName = Symbol.getName();
2180 if (std::error_code EC = SymName.getError())
2181 report_fatal_error(EC.message());
2182 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002183 return name;
2184 }
2185 }
2186 }
2187 }
2188 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2189 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2190 for (unsigned J = 0; J < Seg.nsects; ++J) {
2191 MachO::section Sec = info->O->getSection(Load, J);
2192 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2193 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2194 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2195 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2196 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2197 section_type == MachO::S_SYMBOL_STUBS) &&
2198 ReferenceValue >= Sec.addr &&
2199 ReferenceValue < Sec.addr + Sec.size) {
2200 uint32_t stride;
2201 if (section_type == MachO::S_SYMBOL_STUBS)
2202 stride = Sec.reserved2;
2203 else
2204 stride = 4;
2205 if (stride == 0)
2206 return nullptr;
2207 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2208 if (index < Dysymtab.nindirectsyms) {
2209 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002210 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002211 if (indirect_symbol < Symtab.nsyms) {
2212 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2213 SymbolRef Symbol = *Sym;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002214 ErrorOr<StringRef> SymName = Symbol.getName();
2215 if (std::error_code EC = SymName.getError())
2216 report_fatal_error(EC.message());
2217 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002218 return name;
2219 }
2220 }
2221 }
2222 }
2223 }
Kevin Enderby85974882014-09-26 22:20:44 +00002224 }
2225 return nullptr;
2226}
2227
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002228// method_reference() is called passing it the ReferenceName that might be
2229// a reference it to an Objective-C method call. If so then it allocates and
2230// assembles a method call string with the values last seen and saved in
2231// the DisassembleInfo's class_name and selector_name fields. This is saved
2232// into the method field of the info and any previous string is free'ed.
2233// Then the class_name field in the info is set to nullptr. The method call
2234// string is set into ReferenceName and ReferenceType is set to
2235// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2236// then both ReferenceType and ReferenceName are left unchanged.
2237static void method_reference(struct DisassembleInfo *info,
2238 uint64_t *ReferenceType,
2239 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002240 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002241 if (*ReferenceName != nullptr) {
2242 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002243 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002244 if (info->method != nullptr)
2245 free(info->method);
2246 if (info->class_name != nullptr) {
2247 info->method = (char *)malloc(5 + strlen(info->class_name) +
2248 strlen(info->selector_name));
2249 if (info->method != nullptr) {
2250 strcpy(info->method, "+[");
2251 strcat(info->method, info->class_name);
2252 strcat(info->method, " ");
2253 strcat(info->method, info->selector_name);
2254 strcat(info->method, "]");
2255 *ReferenceName = info->method;
2256 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2257 }
2258 } else {
2259 info->method = (char *)malloc(9 + strlen(info->selector_name));
2260 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002261 if (Arch == Triple::x86_64)
2262 strcpy(info->method, "-[%rdi ");
2263 else if (Arch == Triple::aarch64)
2264 strcpy(info->method, "-[x0 ");
2265 else
2266 strcpy(info->method, "-[r? ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002267 strcat(info->method, info->selector_name);
2268 strcat(info->method, "]");
2269 *ReferenceName = info->method;
2270 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2271 }
2272 }
2273 info->class_name = nullptr;
2274 }
2275 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002276 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002277 if (info->method != nullptr)
2278 free(info->method);
2279 info->method = (char *)malloc(17 + strlen(info->selector_name));
2280 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002281 if (Arch == Triple::x86_64)
2282 strcpy(info->method, "-[[%rdi super] ");
2283 else if (Arch == Triple::aarch64)
2284 strcpy(info->method, "-[[x0 super] ");
2285 else
2286 strcpy(info->method, "-[[r? super] ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002287 strcat(info->method, info->selector_name);
2288 strcat(info->method, "]");
2289 *ReferenceName = info->method;
2290 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2291 }
2292 info->class_name = nullptr;
2293 }
2294 }
2295 }
2296}
2297
2298// GuessPointerPointer() is passed the address of what might be a pointer to
2299// a reference to an Objective-C class, selector, message ref or cfstring.
2300// If so the value of the pointer is returned and one of the booleans are set
2301// to true. If not zero is returned and all the booleans are set to false.
2302static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2303 struct DisassembleInfo *info,
2304 bool &classref, bool &selref, bool &msgref,
2305 bool &cfstring) {
2306 classref = false;
2307 selref = false;
2308 msgref = false;
2309 cfstring = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002310 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002311 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2312 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2313 for (unsigned J = 0; J < Seg.nsects; ++J) {
2314 MachO::section_64 Sec = info->O->getSection64(Load, J);
2315 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2316 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2317 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2318 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2319 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2320 ReferenceValue >= Sec.addr &&
2321 ReferenceValue < Sec.addr + Sec.size) {
2322 uint64_t sect_offset = ReferenceValue - Sec.addr;
2323 uint64_t object_offset = Sec.offset + sect_offset;
2324 StringRef MachOContents = info->O->getData();
2325 uint64_t object_size = MachOContents.size();
2326 const char *object_addr = (const char *)MachOContents.data();
2327 if (object_offset < object_size) {
2328 uint64_t pointer_value;
2329 memcpy(&pointer_value, object_addr + object_offset,
2330 sizeof(uint64_t));
2331 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2332 sys::swapByteOrder(pointer_value);
2333 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2334 selref = true;
2335 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2336 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2337 classref = true;
2338 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2339 ReferenceValue + 8 < Sec.addr + Sec.size) {
2340 msgref = true;
2341 memcpy(&pointer_value, object_addr + object_offset + 8,
2342 sizeof(uint64_t));
2343 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2344 sys::swapByteOrder(pointer_value);
2345 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2346 cfstring = true;
2347 return pointer_value;
2348 } else {
2349 return 0;
2350 }
2351 }
2352 }
2353 }
2354 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002355 }
2356 return 0;
2357}
2358
2359// get_pointer_64 returns a pointer to the bytes in the object file at the
2360// Address from a section in the Mach-O file. And indirectly returns the
2361// offset into the section, number of bytes left in the section past the offset
2362// and which section is was being referenced. If the Address is not in a
2363// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002364static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2365 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002366 DisassembleInfo *info,
2367 bool objc_only = false) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002368 offset = 0;
2369 left = 0;
2370 S = SectionRef();
2371 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2372 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2373 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
Kevin Enderby46e642f2015-10-08 22:50:55 +00002374 if (SectSize == 0)
2375 continue;
Kevin Enderby846c0002015-04-16 17:19:59 +00002376 if (objc_only) {
2377 StringRef SectName;
2378 ((*(info->Sections))[SectIdx]).getName(SectName);
2379 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2380 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2381 if (SegName != "__OBJC" && SectName != "__cstring")
2382 continue;
2383 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002384 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2385 S = (*(info->Sections))[SectIdx];
2386 offset = Address - SectAddress;
2387 left = SectSize - offset;
2388 StringRef SectContents;
2389 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2390 return SectContents.data() + offset;
2391 }
2392 }
2393 return nullptr;
2394}
2395
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002396static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2397 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002398 DisassembleInfo *info,
2399 bool objc_only = false) {
2400 return get_pointer_64(Address, offset, left, S, info, objc_only);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002401}
2402
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002403// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2404// the symbol indirectly through n_value. Based on the relocation information
2405// for the specified section offset in the specified section reference.
Kevin Enderby0fc11822015-04-01 20:57:01 +00002406// If no relocation information is found and a non-zero ReferenceValue for the
2407// symbol is passed, look up that address in the info's AddrMap.
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00002408static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2409 DisassembleInfo *info, uint64_t &n_value,
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002410 uint64_t ReferenceValue = 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002411 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002412 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002413 return nullptr;
2414
2415 // See if there is an external relocation entry at the sect_offset.
2416 bool reloc_found = false;
2417 DataRefImpl Rel;
2418 MachO::any_relocation_info RE;
2419 bool isExtern = false;
2420 SymbolRef Symbol;
2421 for (const RelocationRef &Reloc : S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002422 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002423 if (RelocOffset == sect_offset) {
2424 Rel = Reloc.getRawDataRefImpl();
2425 RE = info->O->getRelocation(Rel);
2426 if (info->O->isRelocationScattered(RE))
2427 continue;
2428 isExtern = info->O->getPlainRelocationExternal(RE);
2429 if (isExtern) {
2430 symbol_iterator RelocSym = Reloc.getSymbol();
2431 Symbol = *RelocSym;
2432 }
2433 reloc_found = true;
2434 break;
2435 }
2436 }
2437 // If there is an external relocation entry for a symbol in this section
2438 // at this section_offset then use that symbol's value for the n_value
2439 // and return its name.
2440 const char *SymbolName = nullptr;
2441 if (reloc_found && isExtern) {
Rafael Espindoladea00162015-07-03 17:44:18 +00002442 n_value = Symbol.getValue();
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002443 ErrorOr<StringRef> NameOrError = Symbol.getName();
2444 if (std::error_code EC = NameOrError.getError())
2445 report_fatal_error(EC.message());
2446 StringRef Name = *NameOrError;
2447 if (!Name.empty()) {
2448 SymbolName = Name.data();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002449 return SymbolName;
2450 }
2451 }
2452
2453 // TODO: For fully linked images, look through the external relocation
2454 // entries off the dynamic symtab command. For these the r_offset is from the
2455 // start of the first writeable segment in the Mach-O file. So the offset
2456 // to this section from that segment is passed to this routine by the caller,
2457 // as the database_offset. Which is the difference of the section's starting
2458 // address and the first writable segment.
2459 //
2460 // NOTE: need add passing the database_offset to this routine.
2461
Kevin Enderby0fc11822015-04-01 20:57:01 +00002462 // We did not find an external relocation entry so look up the ReferenceValue
2463 // as an address of a symbol and if found return that symbol's name.
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002464 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002465
2466 return SymbolName;
2467}
2468
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002469static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
2470 DisassembleInfo *info,
2471 uint32_t ReferenceValue) {
2472 uint64_t n_value64;
2473 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
2474}
2475
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002476// These are structs in the Objective-C meta data and read to produce the
2477// comments for disassembly. While these are part of the ABI they are no
2478// public defintions. So the are here not in include/llvm/Support/MachO.h .
2479
2480// The cfstring object in a 64-bit Mach-O file.
2481struct cfstring64_t {
2482 uint64_t isa; // class64_t * (64-bit pointer)
2483 uint64_t flags; // flag bits
2484 uint64_t characters; // char * (64-bit pointer)
2485 uint64_t length; // number of non-NULL characters in above
2486};
2487
2488// The class object in a 64-bit Mach-O file.
2489struct class64_t {
2490 uint64_t isa; // class64_t * (64-bit pointer)
2491 uint64_t superclass; // class64_t * (64-bit pointer)
2492 uint64_t cache; // Cache (64-bit pointer)
2493 uint64_t vtable; // IMP * (64-bit pointer)
2494 uint64_t data; // class_ro64_t * (64-bit pointer)
2495};
2496
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002497struct class32_t {
2498 uint32_t isa; /* class32_t * (32-bit pointer) */
2499 uint32_t superclass; /* class32_t * (32-bit pointer) */
2500 uint32_t cache; /* Cache (32-bit pointer) */
2501 uint32_t vtable; /* IMP * (32-bit pointer) */
2502 uint32_t data; /* class_ro32_t * (32-bit pointer) */
2503};
2504
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002505struct class_ro64_t {
2506 uint32_t flags;
2507 uint32_t instanceStart;
2508 uint32_t instanceSize;
2509 uint32_t reserved;
2510 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2511 uint64_t name; // const char * (64-bit pointer)
2512 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2513 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2514 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2515 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2516 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2517};
2518
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002519struct class_ro32_t {
2520 uint32_t flags;
2521 uint32_t instanceStart;
2522 uint32_t instanceSize;
2523 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
2524 uint32_t name; /* const char * (32-bit pointer) */
2525 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
2526 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
2527 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
2528 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
2529 uint32_t baseProperties; /* const struct objc_property_list *
2530 (32-bit pointer) */
2531};
2532
2533/* Values for class_ro{64,32}_t->flags */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002534#define RO_META (1 << 0)
2535#define RO_ROOT (1 << 1)
2536#define RO_HAS_CXX_STRUCTORS (1 << 2)
2537
2538struct method_list64_t {
2539 uint32_t entsize;
2540 uint32_t count;
2541 /* struct method64_t first; These structures follow inline */
2542};
2543
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002544struct method_list32_t {
2545 uint32_t entsize;
2546 uint32_t count;
2547 /* struct method32_t first; These structures follow inline */
2548};
2549
Kevin Enderby0fc11822015-04-01 20:57:01 +00002550struct method64_t {
2551 uint64_t name; /* SEL (64-bit pointer) */
2552 uint64_t types; /* const char * (64-bit pointer) */
2553 uint64_t imp; /* IMP (64-bit pointer) */
2554};
2555
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002556struct method32_t {
2557 uint32_t name; /* SEL (32-bit pointer) */
2558 uint32_t types; /* const char * (32-bit pointer) */
2559 uint32_t imp; /* IMP (32-bit pointer) */
2560};
2561
Kevin Enderby0fc11822015-04-01 20:57:01 +00002562struct protocol_list64_t {
2563 uint64_t count; /* uintptr_t (a 64-bit value) */
2564 /* struct protocol64_t * list[0]; These pointers follow inline */
2565};
2566
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002567struct protocol_list32_t {
2568 uint32_t count; /* uintptr_t (a 32-bit value) */
2569 /* struct protocol32_t * list[0]; These pointers follow inline */
2570};
2571
Kevin Enderby0fc11822015-04-01 20:57:01 +00002572struct protocol64_t {
2573 uint64_t isa; /* id * (64-bit pointer) */
2574 uint64_t name; /* const char * (64-bit pointer) */
2575 uint64_t protocols; /* struct protocol_list64_t *
2576 (64-bit pointer) */
2577 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
2578 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
2579 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
2580 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
2581 uint64_t instanceProperties; /* struct objc_property_list *
2582 (64-bit pointer) */
2583};
2584
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002585struct protocol32_t {
2586 uint32_t isa; /* id * (32-bit pointer) */
2587 uint32_t name; /* const char * (32-bit pointer) */
2588 uint32_t protocols; /* struct protocol_list_t *
2589 (32-bit pointer) */
2590 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
2591 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
2592 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
2593 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
2594 uint32_t instanceProperties; /* struct objc_property_list *
2595 (32-bit pointer) */
2596};
2597
Kevin Enderby0fc11822015-04-01 20:57:01 +00002598struct ivar_list64_t {
2599 uint32_t entsize;
2600 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002601 /* struct ivar64_t first; These structures follow inline */
2602};
2603
2604struct ivar_list32_t {
2605 uint32_t entsize;
2606 uint32_t count;
2607 /* struct ivar32_t first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002608};
2609
2610struct ivar64_t {
2611 uint64_t offset; /* uintptr_t * (64-bit pointer) */
2612 uint64_t name; /* const char * (64-bit pointer) */
2613 uint64_t type; /* const char * (64-bit pointer) */
2614 uint32_t alignment;
2615 uint32_t size;
2616};
2617
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002618struct ivar32_t {
2619 uint32_t offset; /* uintptr_t * (32-bit pointer) */
2620 uint32_t name; /* const char * (32-bit pointer) */
2621 uint32_t type; /* const char * (32-bit pointer) */
2622 uint32_t alignment;
2623 uint32_t size;
2624};
2625
Kevin Enderby0fc11822015-04-01 20:57:01 +00002626struct objc_property_list64 {
2627 uint32_t entsize;
2628 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002629 /* struct objc_property64 first; These structures follow inline */
2630};
2631
2632struct objc_property_list32 {
2633 uint32_t entsize;
2634 uint32_t count;
2635 /* struct objc_property32 first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002636};
2637
2638struct objc_property64 {
2639 uint64_t name; /* const char * (64-bit pointer) */
2640 uint64_t attributes; /* const char * (64-bit pointer) */
2641};
2642
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002643struct objc_property32 {
2644 uint32_t name; /* const char * (32-bit pointer) */
2645 uint32_t attributes; /* const char * (32-bit pointer) */
2646};
2647
Kevin Enderby0fc11822015-04-01 20:57:01 +00002648struct category64_t {
2649 uint64_t name; /* const char * (64-bit pointer) */
2650 uint64_t cls; /* struct class_t * (64-bit pointer) */
2651 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
2652 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
2653 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
2654 uint64_t instanceProperties; /* struct objc_property_list *
2655 (64-bit pointer) */
2656};
2657
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002658struct category32_t {
2659 uint32_t name; /* const char * (32-bit pointer) */
2660 uint32_t cls; /* struct class_t * (32-bit pointer) */
2661 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
2662 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
2663 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
2664 uint32_t instanceProperties; /* struct objc_property_list *
2665 (32-bit pointer) */
2666};
2667
Kevin Enderby0fc11822015-04-01 20:57:01 +00002668struct objc_image_info64 {
2669 uint32_t version;
2670 uint32_t flags;
2671};
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002672struct objc_image_info32 {
2673 uint32_t version;
2674 uint32_t flags;
2675};
Kevin Enderby846c0002015-04-16 17:19:59 +00002676struct imageInfo_t {
2677 uint32_t version;
2678 uint32_t flags;
2679};
Kevin Enderby0fc11822015-04-01 20:57:01 +00002680/* masks for objc_image_info.flags */
2681#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
2682#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
2683
2684struct message_ref64 {
2685 uint64_t imp; /* IMP (64-bit pointer) */
2686 uint64_t sel; /* SEL (64-bit pointer) */
2687};
2688
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002689struct message_ref32 {
2690 uint32_t imp; /* IMP (32-bit pointer) */
2691 uint32_t sel; /* SEL (32-bit pointer) */
2692};
2693
Kevin Enderby846c0002015-04-16 17:19:59 +00002694// Objective-C 1 (32-bit only) meta data structs.
2695
2696struct objc_module_t {
2697 uint32_t version;
2698 uint32_t size;
2699 uint32_t name; /* char * (32-bit pointer) */
2700 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
2701};
2702
2703struct objc_symtab_t {
2704 uint32_t sel_ref_cnt;
2705 uint32_t refs; /* SEL * (32-bit pointer) */
2706 uint16_t cls_def_cnt;
2707 uint16_t cat_def_cnt;
2708 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
2709};
2710
2711struct objc_class_t {
2712 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2713 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
2714 uint32_t name; /* const char * (32-bit pointer) */
2715 int32_t version;
2716 int32_t info;
2717 int32_t instance_size;
2718 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
2719 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
2720 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
2721 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
2722};
2723
2724#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
2725// class is not a metaclass
2726#define CLS_CLASS 0x1
2727// class is a metaclass
2728#define CLS_META 0x2
2729
2730struct objc_category_t {
2731 uint32_t category_name; /* char * (32-bit pointer) */
2732 uint32_t class_name; /* char * (32-bit pointer) */
2733 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
2734 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
2735 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
2736};
2737
2738struct objc_ivar_t {
2739 uint32_t ivar_name; /* char * (32-bit pointer) */
2740 uint32_t ivar_type; /* char * (32-bit pointer) */
2741 int32_t ivar_offset;
2742};
2743
2744struct objc_ivar_list_t {
2745 int32_t ivar_count;
2746 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
2747};
2748
2749struct objc_method_list_t {
2750 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
2751 int32_t method_count;
2752 // struct objc_method_t method_list[1]; /* variable length structure */
2753};
2754
2755struct objc_method_t {
2756 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2757 uint32_t method_types; /* char * (32-bit pointer) */
2758 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
2759 (32-bit pointer) */
2760};
2761
2762struct objc_protocol_list_t {
2763 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
2764 int32_t count;
2765 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
2766 // (32-bit pointer) */
2767};
2768
2769struct objc_protocol_t {
2770 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2771 uint32_t protocol_name; /* char * (32-bit pointer) */
2772 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
2773 uint32_t instance_methods; /* struct objc_method_description_list *
2774 (32-bit pointer) */
2775 uint32_t class_methods; /* struct objc_method_description_list *
2776 (32-bit pointer) */
2777};
2778
2779struct objc_method_description_list_t {
2780 int32_t count;
2781 // struct objc_method_description_t list[1];
2782};
2783
2784struct objc_method_description_t {
2785 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2786 uint32_t types; /* char * (32-bit pointer) */
2787};
2788
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002789inline void swapStruct(struct cfstring64_t &cfs) {
2790 sys::swapByteOrder(cfs.isa);
2791 sys::swapByteOrder(cfs.flags);
2792 sys::swapByteOrder(cfs.characters);
2793 sys::swapByteOrder(cfs.length);
2794}
2795
2796inline void swapStruct(struct class64_t &c) {
2797 sys::swapByteOrder(c.isa);
2798 sys::swapByteOrder(c.superclass);
2799 sys::swapByteOrder(c.cache);
2800 sys::swapByteOrder(c.vtable);
2801 sys::swapByteOrder(c.data);
2802}
2803
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002804inline void swapStruct(struct class32_t &c) {
2805 sys::swapByteOrder(c.isa);
2806 sys::swapByteOrder(c.superclass);
2807 sys::swapByteOrder(c.cache);
2808 sys::swapByteOrder(c.vtable);
2809 sys::swapByteOrder(c.data);
2810}
2811
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002812inline void swapStruct(struct class_ro64_t &cro) {
2813 sys::swapByteOrder(cro.flags);
2814 sys::swapByteOrder(cro.instanceStart);
2815 sys::swapByteOrder(cro.instanceSize);
2816 sys::swapByteOrder(cro.reserved);
2817 sys::swapByteOrder(cro.ivarLayout);
2818 sys::swapByteOrder(cro.name);
2819 sys::swapByteOrder(cro.baseMethods);
2820 sys::swapByteOrder(cro.baseProtocols);
2821 sys::swapByteOrder(cro.ivars);
2822 sys::swapByteOrder(cro.weakIvarLayout);
2823 sys::swapByteOrder(cro.baseProperties);
2824}
2825
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002826inline void swapStruct(struct class_ro32_t &cro) {
2827 sys::swapByteOrder(cro.flags);
2828 sys::swapByteOrder(cro.instanceStart);
2829 sys::swapByteOrder(cro.instanceSize);
2830 sys::swapByteOrder(cro.ivarLayout);
2831 sys::swapByteOrder(cro.name);
2832 sys::swapByteOrder(cro.baseMethods);
2833 sys::swapByteOrder(cro.baseProtocols);
2834 sys::swapByteOrder(cro.ivars);
2835 sys::swapByteOrder(cro.weakIvarLayout);
2836 sys::swapByteOrder(cro.baseProperties);
2837}
2838
Kevin Enderby0fc11822015-04-01 20:57:01 +00002839inline void swapStruct(struct method_list64_t &ml) {
2840 sys::swapByteOrder(ml.entsize);
2841 sys::swapByteOrder(ml.count);
2842}
2843
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002844inline void swapStruct(struct method_list32_t &ml) {
2845 sys::swapByteOrder(ml.entsize);
2846 sys::swapByteOrder(ml.count);
2847}
2848
Kevin Enderby0fc11822015-04-01 20:57:01 +00002849inline void swapStruct(struct method64_t &m) {
2850 sys::swapByteOrder(m.name);
2851 sys::swapByteOrder(m.types);
2852 sys::swapByteOrder(m.imp);
2853}
2854
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002855inline void swapStruct(struct method32_t &m) {
2856 sys::swapByteOrder(m.name);
2857 sys::swapByteOrder(m.types);
2858 sys::swapByteOrder(m.imp);
2859}
2860
Kevin Enderby0fc11822015-04-01 20:57:01 +00002861inline void swapStruct(struct protocol_list64_t &pl) {
2862 sys::swapByteOrder(pl.count);
2863}
2864
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002865inline void swapStruct(struct protocol_list32_t &pl) {
2866 sys::swapByteOrder(pl.count);
2867}
2868
Kevin Enderby0fc11822015-04-01 20:57:01 +00002869inline void swapStruct(struct protocol64_t &p) {
2870 sys::swapByteOrder(p.isa);
2871 sys::swapByteOrder(p.name);
2872 sys::swapByteOrder(p.protocols);
2873 sys::swapByteOrder(p.instanceMethods);
2874 sys::swapByteOrder(p.classMethods);
2875 sys::swapByteOrder(p.optionalInstanceMethods);
2876 sys::swapByteOrder(p.optionalClassMethods);
2877 sys::swapByteOrder(p.instanceProperties);
2878}
2879
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002880inline void swapStruct(struct protocol32_t &p) {
2881 sys::swapByteOrder(p.isa);
2882 sys::swapByteOrder(p.name);
2883 sys::swapByteOrder(p.protocols);
2884 sys::swapByteOrder(p.instanceMethods);
2885 sys::swapByteOrder(p.classMethods);
2886 sys::swapByteOrder(p.optionalInstanceMethods);
2887 sys::swapByteOrder(p.optionalClassMethods);
2888 sys::swapByteOrder(p.instanceProperties);
2889}
2890
Kevin Enderby0fc11822015-04-01 20:57:01 +00002891inline void swapStruct(struct ivar_list64_t &il) {
2892 sys::swapByteOrder(il.entsize);
2893 sys::swapByteOrder(il.count);
2894}
2895
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002896inline void swapStruct(struct ivar_list32_t &il) {
2897 sys::swapByteOrder(il.entsize);
2898 sys::swapByteOrder(il.count);
2899}
2900
Kevin Enderby0fc11822015-04-01 20:57:01 +00002901inline void swapStruct(struct ivar64_t &i) {
2902 sys::swapByteOrder(i.offset);
2903 sys::swapByteOrder(i.name);
2904 sys::swapByteOrder(i.type);
2905 sys::swapByteOrder(i.alignment);
2906 sys::swapByteOrder(i.size);
2907}
2908
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002909inline void swapStruct(struct ivar32_t &i) {
2910 sys::swapByteOrder(i.offset);
2911 sys::swapByteOrder(i.name);
2912 sys::swapByteOrder(i.type);
2913 sys::swapByteOrder(i.alignment);
2914 sys::swapByteOrder(i.size);
2915}
2916
Kevin Enderby0fc11822015-04-01 20:57:01 +00002917inline void swapStruct(struct objc_property_list64 &pl) {
2918 sys::swapByteOrder(pl.entsize);
2919 sys::swapByteOrder(pl.count);
2920}
2921
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002922inline void swapStruct(struct objc_property_list32 &pl) {
2923 sys::swapByteOrder(pl.entsize);
2924 sys::swapByteOrder(pl.count);
2925}
2926
Kevin Enderby0fc11822015-04-01 20:57:01 +00002927inline void swapStruct(struct objc_property64 &op) {
2928 sys::swapByteOrder(op.name);
2929 sys::swapByteOrder(op.attributes);
2930}
2931
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002932inline void swapStruct(struct objc_property32 &op) {
2933 sys::swapByteOrder(op.name);
2934 sys::swapByteOrder(op.attributes);
2935}
2936
Kevin Enderby0fc11822015-04-01 20:57:01 +00002937inline void swapStruct(struct category64_t &c) {
2938 sys::swapByteOrder(c.name);
2939 sys::swapByteOrder(c.cls);
2940 sys::swapByteOrder(c.instanceMethods);
2941 sys::swapByteOrder(c.classMethods);
2942 sys::swapByteOrder(c.protocols);
2943 sys::swapByteOrder(c.instanceProperties);
2944}
2945
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002946inline void swapStruct(struct category32_t &c) {
2947 sys::swapByteOrder(c.name);
2948 sys::swapByteOrder(c.cls);
2949 sys::swapByteOrder(c.instanceMethods);
2950 sys::swapByteOrder(c.classMethods);
2951 sys::swapByteOrder(c.protocols);
2952 sys::swapByteOrder(c.instanceProperties);
2953}
2954
Kevin Enderby0fc11822015-04-01 20:57:01 +00002955inline void swapStruct(struct objc_image_info64 &o) {
2956 sys::swapByteOrder(o.version);
2957 sys::swapByteOrder(o.flags);
2958}
2959
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002960inline void swapStruct(struct objc_image_info32 &o) {
2961 sys::swapByteOrder(o.version);
2962 sys::swapByteOrder(o.flags);
2963}
2964
Kevin Enderby846c0002015-04-16 17:19:59 +00002965inline void swapStruct(struct imageInfo_t &o) {
2966 sys::swapByteOrder(o.version);
2967 sys::swapByteOrder(o.flags);
2968}
2969
Kevin Enderby0fc11822015-04-01 20:57:01 +00002970inline void swapStruct(struct message_ref64 &mr) {
2971 sys::swapByteOrder(mr.imp);
2972 sys::swapByteOrder(mr.sel);
2973}
2974
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002975inline void swapStruct(struct message_ref32 &mr) {
2976 sys::swapByteOrder(mr.imp);
2977 sys::swapByteOrder(mr.sel);
2978}
2979
Kevin Enderby846c0002015-04-16 17:19:59 +00002980inline void swapStruct(struct objc_module_t &module) {
2981 sys::swapByteOrder(module.version);
2982 sys::swapByteOrder(module.size);
2983 sys::swapByteOrder(module.name);
2984 sys::swapByteOrder(module.symtab);
Jingyue Wufedecc42015-04-16 18:43:44 +00002985}
Kevin Enderby846c0002015-04-16 17:19:59 +00002986
2987inline void swapStruct(struct objc_symtab_t &symtab) {
2988 sys::swapByteOrder(symtab.sel_ref_cnt);
2989 sys::swapByteOrder(symtab.refs);
2990 sys::swapByteOrder(symtab.cls_def_cnt);
2991 sys::swapByteOrder(symtab.cat_def_cnt);
Jingyue Wufedecc42015-04-16 18:43:44 +00002992}
Kevin Enderby846c0002015-04-16 17:19:59 +00002993
2994inline void swapStruct(struct objc_class_t &objc_class) {
2995 sys::swapByteOrder(objc_class.isa);
2996 sys::swapByteOrder(objc_class.super_class);
2997 sys::swapByteOrder(objc_class.name);
2998 sys::swapByteOrder(objc_class.version);
2999 sys::swapByteOrder(objc_class.info);
3000 sys::swapByteOrder(objc_class.instance_size);
3001 sys::swapByteOrder(objc_class.ivars);
3002 sys::swapByteOrder(objc_class.methodLists);
3003 sys::swapByteOrder(objc_class.cache);
3004 sys::swapByteOrder(objc_class.protocols);
Jingyue Wufedecc42015-04-16 18:43:44 +00003005}
Kevin Enderby846c0002015-04-16 17:19:59 +00003006
3007inline void swapStruct(struct objc_category_t &objc_category) {
3008 sys::swapByteOrder(objc_category.category_name);
3009 sys::swapByteOrder(objc_category.class_name);
3010 sys::swapByteOrder(objc_category.instance_methods);
3011 sys::swapByteOrder(objc_category.class_methods);
3012 sys::swapByteOrder(objc_category.protocols);
3013}
3014
3015inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3016 sys::swapByteOrder(objc_ivar_list.ivar_count);
3017}
3018
3019inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3020 sys::swapByteOrder(objc_ivar.ivar_name);
3021 sys::swapByteOrder(objc_ivar.ivar_type);
3022 sys::swapByteOrder(objc_ivar.ivar_offset);
Jingyue Wufedecc42015-04-16 18:43:44 +00003023}
Kevin Enderby846c0002015-04-16 17:19:59 +00003024
3025inline void swapStruct(struct objc_method_list_t &method_list) {
3026 sys::swapByteOrder(method_list.obsolete);
3027 sys::swapByteOrder(method_list.method_count);
3028}
3029
3030inline void swapStruct(struct objc_method_t &method) {
3031 sys::swapByteOrder(method.method_name);
3032 sys::swapByteOrder(method.method_types);
3033 sys::swapByteOrder(method.method_imp);
3034}
3035
3036inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3037 sys::swapByteOrder(protocol_list.next);
3038 sys::swapByteOrder(protocol_list.count);
3039}
3040
3041inline void swapStruct(struct objc_protocol_t &protocol) {
3042 sys::swapByteOrder(protocol.isa);
3043 sys::swapByteOrder(protocol.protocol_name);
3044 sys::swapByteOrder(protocol.protocol_list);
3045 sys::swapByteOrder(protocol.instance_methods);
3046 sys::swapByteOrder(protocol.class_methods);
3047}
3048
3049inline void swapStruct(struct objc_method_description_list_t &mdl) {
3050 sys::swapByteOrder(mdl.count);
3051}
3052
3053inline void swapStruct(struct objc_method_description_t &md) {
3054 sys::swapByteOrder(md.name);
3055 sys::swapByteOrder(md.types);
3056}
3057
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003058static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3059 struct DisassembleInfo *info);
3060
3061// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3062// to an Objective-C class and returns the class name. It is also passed the
3063// address of the pointer, so when the pointer is zero as it can be in an .o
3064// file, that is used to look for an external relocation entry with a symbol
3065// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003066static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3067 uint64_t ReferenceValue,
3068 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003069 const char *r;
3070 uint32_t offset, left;
3071 SectionRef S;
3072
3073 // The pointer_value can be 0 in an object file and have a relocation
3074 // entry for the class symbol at the ReferenceValue (the address of the
3075 // pointer).
3076 if (pointer_value == 0) {
3077 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3078 if (r == nullptr || left < sizeof(uint64_t))
3079 return nullptr;
3080 uint64_t n_value;
3081 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3082 if (symbol_name == nullptr)
3083 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00003084 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003085 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3086 return class_name + 2;
3087 else
3088 return nullptr;
3089 }
3090
3091 // The case were the pointer_value is non-zero and points to a class defined
3092 // in this Mach-O file.
3093 r = get_pointer_64(pointer_value, offset, left, S, info);
3094 if (r == nullptr || left < sizeof(struct class64_t))
3095 return nullptr;
3096 struct class64_t c;
3097 memcpy(&c, r, sizeof(struct class64_t));
3098 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3099 swapStruct(c);
3100 if (c.data == 0)
3101 return nullptr;
3102 r = get_pointer_64(c.data, offset, left, S, info);
3103 if (r == nullptr || left < sizeof(struct class_ro64_t))
3104 return nullptr;
3105 struct class_ro64_t cro;
3106 memcpy(&cro, r, sizeof(struct class_ro64_t));
3107 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3108 swapStruct(cro);
3109 if (cro.name == 0)
3110 return nullptr;
3111 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3112 return name;
3113}
3114
3115// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3116// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003117static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3118 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003119 const char *r, *name;
3120 uint32_t offset, left;
3121 SectionRef S;
3122 struct cfstring64_t cfs;
3123 uint64_t cfs_characters;
3124
3125 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3126 if (r == nullptr || left < sizeof(struct cfstring64_t))
3127 return nullptr;
3128 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3129 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3130 swapStruct(cfs);
3131 if (cfs.characters == 0) {
3132 uint64_t n_value;
3133 const char *symbol_name = get_symbol_64(
3134 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3135 if (symbol_name == nullptr)
3136 return nullptr;
3137 cfs_characters = n_value;
3138 } else
3139 cfs_characters = cfs.characters;
3140 name = get_pointer_64(cfs_characters, offset, left, S, info);
3141
3142 return name;
3143}
3144
3145// get_objc2_64bit_selref() is used for disassembly and is passed a the address
3146// of a pointer to an Objective-C selector reference when the pointer value is
3147// zero as in a .o file and is likely to have a external relocation entry with
3148// who's symbol's n_value is the real pointer to the selector name. If that is
3149// the case the real pointer to the selector name is returned else 0 is
3150// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003151static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3152 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003153 uint32_t offset, left;
3154 SectionRef S;
3155
3156 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3157 if (r == nullptr || left < sizeof(uint64_t))
3158 return 0;
3159 uint64_t n_value;
3160 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3161 if (symbol_name == nullptr)
3162 return 0;
3163 return n_value;
3164}
3165
Kevin Enderby0fc11822015-04-01 20:57:01 +00003166static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3167 const char *sectname) {
3168 for (const SectionRef &Section : O->sections()) {
3169 StringRef SectName;
3170 Section.getName(SectName);
3171 DataRefImpl Ref = Section.getRawDataRefImpl();
3172 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3173 if (SegName == segname && SectName == sectname)
3174 return Section;
3175 }
3176 return SectionRef();
3177}
3178
3179static void
3180walk_pointer_list_64(const char *listname, const SectionRef S,
3181 MachOObjectFile *O, struct DisassembleInfo *info,
3182 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3183 if (S == SectionRef())
3184 return;
3185
3186 StringRef SectName;
3187 S.getName(SectName);
3188 DataRefImpl Ref = S.getRawDataRefImpl();
3189 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3190 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3191
3192 StringRef BytesStr;
3193 S.getContents(BytesStr);
3194 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3195
3196 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3197 uint32_t left = S.getSize() - i;
3198 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3199 uint64_t p = 0;
3200 memcpy(&p, Contents + i, size);
3201 if (i + sizeof(uint64_t) > S.getSize())
3202 outs() << listname << " list pointer extends past end of (" << SegName
3203 << "," << SectName << ") section\n";
3204 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3205
3206 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3207 sys::swapByteOrder(p);
3208
3209 uint64_t n_value = 0;
3210 const char *name = get_symbol_64(i, S, info, n_value, p);
3211 if (name == nullptr)
3212 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3213
3214 if (n_value != 0) {
3215 outs() << format("0x%" PRIx64, n_value);
3216 if (p != 0)
3217 outs() << " + " << format("0x%" PRIx64, p);
3218 } else
3219 outs() << format("0x%" PRIx64, p);
3220 if (name != nullptr)
3221 outs() << " " << name;
3222 outs() << "\n";
3223
3224 p += n_value;
3225 if (func)
3226 func(p, info);
3227 }
3228}
3229
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003230static void
3231walk_pointer_list_32(const char *listname, const SectionRef S,
3232 MachOObjectFile *O, struct DisassembleInfo *info,
3233 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3234 if (S == SectionRef())
3235 return;
3236
3237 StringRef SectName;
3238 S.getName(SectName);
3239 DataRefImpl Ref = S.getRawDataRefImpl();
3240 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3241 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3242
3243 StringRef BytesStr;
3244 S.getContents(BytesStr);
3245 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3246
3247 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3248 uint32_t left = S.getSize() - i;
3249 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3250 uint32_t p = 0;
3251 memcpy(&p, Contents + i, size);
3252 if (i + sizeof(uint32_t) > S.getSize())
3253 outs() << listname << " list pointer extends past end of (" << SegName
3254 << "," << SectName << ") section\n";
Kevin Enderbycf261312015-04-06 22:33:43 +00003255 uint32_t Address = S.getAddress() + i;
3256 outs() << format("%08" PRIx32, Address) << " ";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003257
3258 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3259 sys::swapByteOrder(p);
3260 outs() << format("0x%" PRIx32, p);
3261
3262 const char *name = get_symbol_32(i, S, info, p);
3263 if (name != nullptr)
3264 outs() << " " << name;
3265 outs() << "\n";
3266
3267 if (func)
3268 func(p, info);
3269 }
3270}
3271
3272static void print_layout_map(const char *layout_map, uint32_t left) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003273 if (layout_map == nullptr)
3274 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003275 outs() << " layout map: ";
3276 do {
3277 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3278 left--;
3279 layout_map++;
3280 } while (*layout_map != '\0' && left != 0);
3281 outs() << "\n";
3282}
3283
Kevin Enderby0fc11822015-04-01 20:57:01 +00003284static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3285 uint32_t offset, left;
3286 SectionRef S;
3287 const char *layout_map;
3288
3289 if (p == 0)
3290 return;
3291 layout_map = get_pointer_64(p, offset, left, S, info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003292 print_layout_map(layout_map, left);
3293}
3294
3295static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3296 uint32_t offset, left;
3297 SectionRef S;
3298 const char *layout_map;
3299
3300 if (p == 0)
3301 return;
3302 layout_map = get_pointer_32(p, offset, left, S, info);
3303 print_layout_map(layout_map, left);
Kevin Enderby0fc11822015-04-01 20:57:01 +00003304}
3305
3306static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3307 const char *indent) {
3308 struct method_list64_t ml;
3309 struct method64_t m;
3310 const char *r;
3311 uint32_t offset, xoffset, left, i;
3312 SectionRef S, xS;
3313 const char *name, *sym_name;
3314 uint64_t n_value;
3315
3316 r = get_pointer_64(p, offset, left, S, info);
3317 if (r == nullptr)
3318 return;
3319 memset(&ml, '\0', sizeof(struct method_list64_t));
3320 if (left < sizeof(struct method_list64_t)) {
3321 memcpy(&ml, r, left);
3322 outs() << " (method_list_t entends past the end of the section)\n";
3323 } else
3324 memcpy(&ml, r, sizeof(struct method_list64_t));
3325 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3326 swapStruct(ml);
3327 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3328 outs() << indent << "\t\t count " << ml.count << "\n";
3329
3330 p += sizeof(struct method_list64_t);
3331 offset += sizeof(struct method_list64_t);
3332 for (i = 0; i < ml.count; i++) {
3333 r = get_pointer_64(p, offset, left, S, info);
3334 if (r == nullptr)
3335 return;
3336 memset(&m, '\0', sizeof(struct method64_t));
3337 if (left < sizeof(struct method64_t)) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003338 memcpy(&m, r, left);
3339 outs() << indent << " (method_t extends past the end of the section)\n";
Kevin Enderby0fc11822015-04-01 20:57:01 +00003340 } else
3341 memcpy(&m, r, sizeof(struct method64_t));
3342 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3343 swapStruct(m);
3344
3345 outs() << indent << "\t\t name ";
3346 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3347 info, n_value, m.name);
3348 if (n_value != 0) {
3349 if (info->verbose && sym_name != nullptr)
3350 outs() << sym_name;
3351 else
3352 outs() << format("0x%" PRIx64, n_value);
3353 if (m.name != 0)
3354 outs() << " + " << format("0x%" PRIx64, m.name);
3355 } else
3356 outs() << format("0x%" PRIx64, m.name);
3357 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3358 if (name != nullptr)
3359 outs() << format(" %.*s", left, name);
3360 outs() << "\n";
3361
3362 outs() << indent << "\t\t types ";
3363 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3364 info, n_value, m.types);
3365 if (n_value != 0) {
3366 if (info->verbose && sym_name != nullptr)
3367 outs() << sym_name;
3368 else
3369 outs() << format("0x%" PRIx64, n_value);
3370 if (m.types != 0)
3371 outs() << " + " << format("0x%" PRIx64, m.types);
3372 } else
3373 outs() << format("0x%" PRIx64, m.types);
3374 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3375 if (name != nullptr)
3376 outs() << format(" %.*s", left, name);
3377 outs() << "\n";
3378
3379 outs() << indent << "\t\t imp ";
3380 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3381 n_value, m.imp);
3382 if (info->verbose && name == nullptr) {
3383 if (n_value != 0) {
3384 outs() << format("0x%" PRIx64, n_value) << " ";
3385 if (m.imp != 0)
3386 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3387 } else
3388 outs() << format("0x%" PRIx64, m.imp) << " ";
3389 }
3390 if (name != nullptr)
3391 outs() << name;
3392 outs() << "\n";
3393
3394 p += sizeof(struct method64_t);
3395 offset += sizeof(struct method64_t);
3396 }
3397}
3398
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003399static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3400 const char *indent) {
3401 struct method_list32_t ml;
3402 struct method32_t m;
Kevin Enderby846c0002015-04-16 17:19:59 +00003403 const char *r, *name;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003404 uint32_t offset, xoffset, left, i;
3405 SectionRef S, xS;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003406
3407 r = get_pointer_32(p, offset, left, S, info);
3408 if (r == nullptr)
3409 return;
3410 memset(&ml, '\0', sizeof(struct method_list32_t));
3411 if (left < sizeof(struct method_list32_t)) {
3412 memcpy(&ml, r, left);
3413 outs() << " (method_list_t entends past the end of the section)\n";
3414 } else
3415 memcpy(&ml, r, sizeof(struct method_list32_t));
3416 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3417 swapStruct(ml);
3418 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3419 outs() << indent << "\t\t count " << ml.count << "\n";
3420
3421 p += sizeof(struct method_list32_t);
3422 offset += sizeof(struct method_list32_t);
3423 for (i = 0; i < ml.count; i++) {
3424 r = get_pointer_32(p, offset, left, S, info);
3425 if (r == nullptr)
3426 return;
3427 memset(&m, '\0', sizeof(struct method32_t));
3428 if (left < sizeof(struct method32_t)) {
3429 memcpy(&ml, r, left);
3430 outs() << indent << " (method_t entends past the end of the section)\n";
3431 } else
3432 memcpy(&m, r, sizeof(struct method32_t));
3433 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3434 swapStruct(m);
3435
3436 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
3437 name = get_pointer_32(m.name, xoffset, left, xS, info);
3438 if (name != nullptr)
3439 outs() << format(" %.*s", left, name);
3440 outs() << "\n";
3441
3442 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
3443 name = get_pointer_32(m.types, xoffset, left, xS, info);
3444 if (name != nullptr)
3445 outs() << format(" %.*s", left, name);
3446 outs() << "\n";
3447
3448 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
3449 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
3450 m.imp);
3451 if (name != nullptr)
3452 outs() << " " << name;
3453 outs() << "\n";
3454
3455 p += sizeof(struct method32_t);
3456 offset += sizeof(struct method32_t);
3457 }
3458}
3459
Kevin Enderby846c0002015-04-16 17:19:59 +00003460static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
3461 uint32_t offset, left, xleft;
3462 SectionRef S;
3463 struct objc_method_list_t method_list;
3464 struct objc_method_t method;
3465 const char *r, *methods, *name, *SymbolName;
3466 int32_t i;
3467
3468 r = get_pointer_32(p, offset, left, S, info, true);
3469 if (r == nullptr)
3470 return true;
3471
3472 outs() << "\n";
3473 if (left > sizeof(struct objc_method_list_t)) {
3474 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
3475 } else {
3476 outs() << "\t\t objc_method_list extends past end of the section\n";
3477 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
3478 memcpy(&method_list, r, left);
3479 }
3480 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3481 swapStruct(method_list);
3482
3483 outs() << "\t\t obsolete "
3484 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
3485 outs() << "\t\t method_count " << method_list.method_count << "\n";
3486
3487 methods = r + sizeof(struct objc_method_list_t);
3488 for (i = 0; i < method_list.method_count; i++) {
3489 if ((i + 1) * sizeof(struct objc_method_t) > left) {
3490 outs() << "\t\t remaining method's extend past the of the section\n";
3491 break;
3492 }
3493 memcpy(&method, methods + i * sizeof(struct objc_method_t),
3494 sizeof(struct objc_method_t));
3495 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3496 swapStruct(method);
3497
3498 outs() << "\t\t method_name "
3499 << format("0x%08" PRIx32, method.method_name);
3500 if (info->verbose) {
3501 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
3502 if (name != nullptr)
3503 outs() << format(" %.*s", xleft, name);
3504 else
3505 outs() << " (not in an __OBJC section)";
3506 }
3507 outs() << "\n";
3508
3509 outs() << "\t\t method_types "
3510 << format("0x%08" PRIx32, method.method_types);
3511 if (info->verbose) {
3512 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
3513 if (name != nullptr)
3514 outs() << format(" %.*s", xleft, name);
3515 else
3516 outs() << " (not in an __OBJC section)";
3517 }
3518 outs() << "\n";
3519
3520 outs() << "\t\t method_imp "
3521 << format("0x%08" PRIx32, method.method_imp) << " ";
3522 if (info->verbose) {
3523 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
3524 if (SymbolName != nullptr)
3525 outs() << SymbolName;
3526 }
3527 outs() << "\n";
3528 }
3529 return false;
3530}
3531
Kevin Enderby0fc11822015-04-01 20:57:01 +00003532static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
3533 struct protocol_list64_t pl;
3534 uint64_t q, n_value;
3535 struct protocol64_t pc;
3536 const char *r;
3537 uint32_t offset, xoffset, left, i;
3538 SectionRef S, xS;
3539 const char *name, *sym_name;
3540
3541 r = get_pointer_64(p, offset, left, S, info);
3542 if (r == nullptr)
3543 return;
3544 memset(&pl, '\0', sizeof(struct protocol_list64_t));
3545 if (left < sizeof(struct protocol_list64_t)) {
3546 memcpy(&pl, r, left);
3547 outs() << " (protocol_list_t entends past the end of the section)\n";
3548 } else
3549 memcpy(&pl, r, sizeof(struct protocol_list64_t));
3550 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3551 swapStruct(pl);
3552 outs() << " count " << pl.count << "\n";
3553
3554 p += sizeof(struct protocol_list64_t);
3555 offset += sizeof(struct protocol_list64_t);
3556 for (i = 0; i < pl.count; i++) {
3557 r = get_pointer_64(p, offset, left, S, info);
3558 if (r == nullptr)
3559 return;
3560 q = 0;
3561 if (left < sizeof(uint64_t)) {
3562 memcpy(&q, r, left);
3563 outs() << " (protocol_t * entends past the end of the section)\n";
3564 } else
3565 memcpy(&q, r, sizeof(uint64_t));
3566 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3567 sys::swapByteOrder(q);
3568
3569 outs() << "\t\t list[" << i << "] ";
3570 sym_name = get_symbol_64(offset, S, info, n_value, q);
3571 if (n_value != 0) {
3572 if (info->verbose && sym_name != nullptr)
3573 outs() << sym_name;
3574 else
3575 outs() << format("0x%" PRIx64, n_value);
3576 if (q != 0)
3577 outs() << " + " << format("0x%" PRIx64, q);
3578 } else
3579 outs() << format("0x%" PRIx64, q);
3580 outs() << " (struct protocol_t *)\n";
3581
3582 r = get_pointer_64(q + n_value, offset, left, S, info);
3583 if (r == nullptr)
3584 return;
3585 memset(&pc, '\0', sizeof(struct protocol64_t));
3586 if (left < sizeof(struct protocol64_t)) {
3587 memcpy(&pc, r, left);
3588 outs() << " (protocol_t entends past the end of the section)\n";
3589 } else
3590 memcpy(&pc, r, sizeof(struct protocol64_t));
3591 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3592 swapStruct(pc);
3593
3594 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
3595
3596 outs() << "\t\t\t name ";
3597 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
3598 info, n_value, pc.name);
3599 if (n_value != 0) {
3600 if (info->verbose && sym_name != nullptr)
3601 outs() << sym_name;
3602 else
3603 outs() << format("0x%" PRIx64, n_value);
3604 if (pc.name != 0)
3605 outs() << " + " << format("0x%" PRIx64, pc.name);
3606 } else
3607 outs() << format("0x%" PRIx64, pc.name);
3608 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
3609 if (name != nullptr)
3610 outs() << format(" %.*s", left, name);
3611 outs() << "\n";
3612
3613 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
3614
3615 outs() << "\t\t instanceMethods ";
3616 sym_name =
3617 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
3618 S, info, n_value, pc.instanceMethods);
3619 if (n_value != 0) {
3620 if (info->verbose && sym_name != nullptr)
3621 outs() << sym_name;
3622 else
3623 outs() << format("0x%" PRIx64, n_value);
3624 if (pc.instanceMethods != 0)
3625 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
3626 } else
3627 outs() << format("0x%" PRIx64, pc.instanceMethods);
3628 outs() << " (struct method_list_t *)\n";
3629 if (pc.instanceMethods + n_value != 0)
3630 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
3631
3632 outs() << "\t\t classMethods ";
3633 sym_name =
3634 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
3635 info, n_value, pc.classMethods);
3636 if (n_value != 0) {
3637 if (info->verbose && sym_name != nullptr)
3638 outs() << sym_name;
3639 else
3640 outs() << format("0x%" PRIx64, n_value);
3641 if (pc.classMethods != 0)
3642 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
3643 } else
3644 outs() << format("0x%" PRIx64, pc.classMethods);
3645 outs() << " (struct method_list_t *)\n";
3646 if (pc.classMethods + n_value != 0)
3647 print_method_list64_t(pc.classMethods + n_value, info, "\t");
3648
3649 outs() << "\t optionalInstanceMethods "
3650 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
3651 outs() << "\t optionalClassMethods "
3652 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
3653 outs() << "\t instanceProperties "
3654 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
3655
3656 p += sizeof(uint64_t);
3657 offset += sizeof(uint64_t);
3658 }
3659}
3660
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003661static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
3662 struct protocol_list32_t pl;
3663 uint32_t q;
3664 struct protocol32_t pc;
3665 const char *r;
3666 uint32_t offset, xoffset, left, i;
3667 SectionRef S, xS;
3668 const char *name;
3669
3670 r = get_pointer_32(p, offset, left, S, info);
3671 if (r == nullptr)
3672 return;
3673 memset(&pl, '\0', sizeof(struct protocol_list32_t));
3674 if (left < sizeof(struct protocol_list32_t)) {
3675 memcpy(&pl, r, left);
3676 outs() << " (protocol_list_t entends past the end of the section)\n";
3677 } else
3678 memcpy(&pl, r, sizeof(struct protocol_list32_t));
3679 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3680 swapStruct(pl);
3681 outs() << " count " << pl.count << "\n";
3682
3683 p += sizeof(struct protocol_list32_t);
3684 offset += sizeof(struct protocol_list32_t);
3685 for (i = 0; i < pl.count; i++) {
3686 r = get_pointer_32(p, offset, left, S, info);
3687 if (r == nullptr)
3688 return;
3689 q = 0;
3690 if (left < sizeof(uint32_t)) {
3691 memcpy(&q, r, left);
3692 outs() << " (protocol_t * entends past the end of the section)\n";
3693 } else
3694 memcpy(&q, r, sizeof(uint32_t));
3695 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3696 sys::swapByteOrder(q);
3697 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
3698 << " (struct protocol_t *)\n";
3699 r = get_pointer_32(q, offset, left, S, info);
3700 if (r == nullptr)
3701 return;
3702 memset(&pc, '\0', sizeof(struct protocol32_t));
3703 if (left < sizeof(struct protocol32_t)) {
3704 memcpy(&pc, r, left);
3705 outs() << " (protocol_t entends past the end of the section)\n";
3706 } else
3707 memcpy(&pc, r, sizeof(struct protocol32_t));
3708 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3709 swapStruct(pc);
3710 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
3711 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
3712 name = get_pointer_32(pc.name, xoffset, left, xS, info);
3713 if (name != nullptr)
3714 outs() << format(" %.*s", left, name);
3715 outs() << "\n";
3716 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
3717 outs() << "\t\t instanceMethods "
3718 << format("0x%" PRIx32, pc.instanceMethods)
3719 << " (struct method_list_t *)\n";
3720 if (pc.instanceMethods != 0)
3721 print_method_list32_t(pc.instanceMethods, info, "\t");
3722 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
3723 << " (struct method_list_t *)\n";
3724 if (pc.classMethods != 0)
3725 print_method_list32_t(pc.classMethods, info, "\t");
3726 outs() << "\t optionalInstanceMethods "
3727 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
3728 outs() << "\t optionalClassMethods "
3729 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
3730 outs() << "\t instanceProperties "
3731 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
3732 p += sizeof(uint32_t);
3733 offset += sizeof(uint32_t);
3734 }
3735}
3736
Kevin Enderby846c0002015-04-16 17:19:59 +00003737static void print_indent(uint32_t indent) {
3738 for (uint32_t i = 0; i < indent;) {
3739 if (indent - i >= 8) {
3740 outs() << "\t";
3741 i += 8;
3742 } else {
3743 for (uint32_t j = i; j < indent; j++)
3744 outs() << " ";
3745 return;
3746 }
3747 }
3748}
3749
3750static bool print_method_description_list(uint32_t p, uint32_t indent,
3751 struct DisassembleInfo *info) {
3752 uint32_t offset, left, xleft;
3753 SectionRef S;
3754 struct objc_method_description_list_t mdl;
3755 struct objc_method_description_t md;
3756 const char *r, *list, *name;
3757 int32_t i;
3758
3759 r = get_pointer_32(p, offset, left, S, info, true);
3760 if (r == nullptr)
3761 return true;
3762
3763 outs() << "\n";
3764 if (left > sizeof(struct objc_method_description_list_t)) {
3765 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
3766 } else {
3767 print_indent(indent);
3768 outs() << " objc_method_description_list extends past end of the section\n";
3769 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
3770 memcpy(&mdl, r, left);
3771 }
3772 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3773 swapStruct(mdl);
3774
3775 print_indent(indent);
3776 outs() << " count " << mdl.count << "\n";
3777
3778 list = r + sizeof(struct objc_method_description_list_t);
3779 for (i = 0; i < mdl.count; i++) {
3780 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
3781 print_indent(indent);
3782 outs() << " remaining list entries extend past the of the section\n";
3783 break;
3784 }
3785 print_indent(indent);
3786 outs() << " list[" << i << "]\n";
3787 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
3788 sizeof(struct objc_method_description_t));
3789 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3790 swapStruct(md);
3791
3792 print_indent(indent);
3793 outs() << " name " << format("0x%08" PRIx32, md.name);
3794 if (info->verbose) {
3795 name = get_pointer_32(md.name, offset, xleft, S, info, true);
3796 if (name != nullptr)
3797 outs() << format(" %.*s", xleft, name);
3798 else
3799 outs() << " (not in an __OBJC section)";
3800 }
3801 outs() << "\n";
3802
3803 print_indent(indent);
3804 outs() << " types " << format("0x%08" PRIx32, md.types);
3805 if (info->verbose) {
3806 name = get_pointer_32(md.types, offset, xleft, S, info, true);
3807 if (name != nullptr)
3808 outs() << format(" %.*s", xleft, name);
3809 else
3810 outs() << " (not in an __OBJC section)";
3811 }
3812 outs() << "\n";
3813 }
3814 return false;
3815}
3816
3817static bool print_protocol_list(uint32_t p, uint32_t indent,
3818 struct DisassembleInfo *info);
3819
3820static bool print_protocol(uint32_t p, uint32_t indent,
3821 struct DisassembleInfo *info) {
3822 uint32_t offset, left;
3823 SectionRef S;
3824 struct objc_protocol_t protocol;
3825 const char *r, *name;
3826
3827 r = get_pointer_32(p, offset, left, S, info, true);
3828 if (r == nullptr)
3829 return true;
3830
3831 outs() << "\n";
3832 if (left >= sizeof(struct objc_protocol_t)) {
3833 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
3834 } else {
3835 print_indent(indent);
3836 outs() << " Protocol extends past end of the section\n";
3837 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
3838 memcpy(&protocol, r, left);
3839 }
3840 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3841 swapStruct(protocol);
3842
3843 print_indent(indent);
3844 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
3845 << "\n";
3846
3847 print_indent(indent);
3848 outs() << " protocol_name "
3849 << format("0x%08" PRIx32, protocol.protocol_name);
3850 if (info->verbose) {
3851 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
3852 if (name != nullptr)
3853 outs() << format(" %.*s", left, name);
3854 else
3855 outs() << " (not in an __OBJC section)";
3856 }
3857 outs() << "\n";
3858
3859 print_indent(indent);
3860 outs() << " protocol_list "
3861 << format("0x%08" PRIx32, protocol.protocol_list);
3862 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
3863 outs() << " (not in an __OBJC section)\n";
3864
3865 print_indent(indent);
3866 outs() << " instance_methods "
3867 << format("0x%08" PRIx32, protocol.instance_methods);
3868 if (print_method_description_list(protocol.instance_methods, indent, info))
3869 outs() << " (not in an __OBJC section)\n";
3870
3871 print_indent(indent);
3872 outs() << " class_methods "
3873 << format("0x%08" PRIx32, protocol.class_methods);
3874 if (print_method_description_list(protocol.class_methods, indent, info))
3875 outs() << " (not in an __OBJC section)\n";
3876
3877 return false;
3878}
3879
3880static bool print_protocol_list(uint32_t p, uint32_t indent,
3881 struct DisassembleInfo *info) {
3882 uint32_t offset, left, l;
3883 SectionRef S;
3884 struct objc_protocol_list_t protocol_list;
3885 const char *r, *list;
3886 int32_t i;
3887
3888 r = get_pointer_32(p, offset, left, S, info, true);
3889 if (r == nullptr)
3890 return true;
3891
3892 outs() << "\n";
3893 if (left > sizeof(struct objc_protocol_list_t)) {
3894 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
3895 } else {
3896 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
3897 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
3898 memcpy(&protocol_list, r, left);
3899 }
3900 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3901 swapStruct(protocol_list);
3902
3903 print_indent(indent);
3904 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
3905 << "\n";
3906 print_indent(indent);
3907 outs() << " count " << protocol_list.count << "\n";
3908
3909 list = r + sizeof(struct objc_protocol_list_t);
3910 for (i = 0; i < protocol_list.count; i++) {
3911 if ((i + 1) * sizeof(uint32_t) > left) {
3912 outs() << "\t\t remaining list entries extend past the of the section\n";
3913 break;
3914 }
3915 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
3916 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3917 sys::swapByteOrder(l);
3918
3919 print_indent(indent);
3920 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
3921 if (print_protocol(l, indent, info))
3922 outs() << "(not in an __OBJC section)\n";
3923 }
3924 return false;
3925}
3926
Kevin Enderby0fc11822015-04-01 20:57:01 +00003927static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
3928 struct ivar_list64_t il;
3929 struct ivar64_t i;
3930 const char *r;
3931 uint32_t offset, xoffset, left, j;
3932 SectionRef S, xS;
3933 const char *name, *sym_name, *ivar_offset_p;
3934 uint64_t ivar_offset, n_value;
3935
3936 r = get_pointer_64(p, offset, left, S, info);
3937 if (r == nullptr)
3938 return;
3939 memset(&il, '\0', sizeof(struct ivar_list64_t));
3940 if (left < sizeof(struct ivar_list64_t)) {
3941 memcpy(&il, r, left);
3942 outs() << " (ivar_list_t entends past the end of the section)\n";
3943 } else
3944 memcpy(&il, r, sizeof(struct ivar_list64_t));
3945 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3946 swapStruct(il);
3947 outs() << " entsize " << il.entsize << "\n";
3948 outs() << " count " << il.count << "\n";
3949
3950 p += sizeof(struct ivar_list64_t);
3951 offset += sizeof(struct ivar_list64_t);
3952 for (j = 0; j < il.count; j++) {
3953 r = get_pointer_64(p, offset, left, S, info);
3954 if (r == nullptr)
3955 return;
3956 memset(&i, '\0', sizeof(struct ivar64_t));
3957 if (left < sizeof(struct ivar64_t)) {
3958 memcpy(&i, r, left);
3959 outs() << " (ivar_t entends past the end of the section)\n";
3960 } else
3961 memcpy(&i, r, sizeof(struct ivar64_t));
3962 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3963 swapStruct(i);
3964
3965 outs() << "\t\t\t offset ";
3966 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
3967 info, n_value, i.offset);
3968 if (n_value != 0) {
3969 if (info->verbose && sym_name != nullptr)
3970 outs() << sym_name;
3971 else
3972 outs() << format("0x%" PRIx64, n_value);
3973 if (i.offset != 0)
3974 outs() << " + " << format("0x%" PRIx64, i.offset);
3975 } else
3976 outs() << format("0x%" PRIx64, i.offset);
3977 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
3978 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
3979 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
3980 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3981 sys::swapByteOrder(ivar_offset);
3982 outs() << " " << ivar_offset << "\n";
3983 } else
3984 outs() << "\n";
3985
3986 outs() << "\t\t\t name ";
3987 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
3988 n_value, i.name);
3989 if (n_value != 0) {
3990 if (info->verbose && sym_name != nullptr)
3991 outs() << sym_name;
3992 else
3993 outs() << format("0x%" PRIx64, n_value);
3994 if (i.name != 0)
3995 outs() << " + " << format("0x%" PRIx64, i.name);
3996 } else
3997 outs() << format("0x%" PRIx64, i.name);
3998 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
3999 if (name != nullptr)
4000 outs() << format(" %.*s", left, name);
4001 outs() << "\n";
4002
4003 outs() << "\t\t\t type ";
4004 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4005 n_value, i.name);
4006 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4007 if (n_value != 0) {
4008 if (info->verbose && sym_name != nullptr)
4009 outs() << sym_name;
4010 else
4011 outs() << format("0x%" PRIx64, n_value);
4012 if (i.type != 0)
4013 outs() << " + " << format("0x%" PRIx64, i.type);
4014 } else
4015 outs() << format("0x%" PRIx64, i.type);
4016 if (name != nullptr)
4017 outs() << format(" %.*s", left, name);
4018 outs() << "\n";
4019
4020 outs() << "\t\t\talignment " << i.alignment << "\n";
4021 outs() << "\t\t\t size " << i.size << "\n";
4022
4023 p += sizeof(struct ivar64_t);
4024 offset += sizeof(struct ivar64_t);
4025 }
4026}
4027
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004028static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4029 struct ivar_list32_t il;
4030 struct ivar32_t i;
4031 const char *r;
4032 uint32_t offset, xoffset, left, j;
4033 SectionRef S, xS;
4034 const char *name, *ivar_offset_p;
4035 uint32_t ivar_offset;
4036
4037 r = get_pointer_32(p, offset, left, S, info);
4038 if (r == nullptr)
4039 return;
4040 memset(&il, '\0', sizeof(struct ivar_list32_t));
4041 if (left < sizeof(struct ivar_list32_t)) {
4042 memcpy(&il, r, left);
4043 outs() << " (ivar_list_t entends past the end of the section)\n";
4044 } else
4045 memcpy(&il, r, sizeof(struct ivar_list32_t));
4046 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4047 swapStruct(il);
4048 outs() << " entsize " << il.entsize << "\n";
4049 outs() << " count " << il.count << "\n";
4050
4051 p += sizeof(struct ivar_list32_t);
4052 offset += sizeof(struct ivar_list32_t);
4053 for (j = 0; j < il.count; j++) {
4054 r = get_pointer_32(p, offset, left, S, info);
4055 if (r == nullptr)
4056 return;
4057 memset(&i, '\0', sizeof(struct ivar32_t));
4058 if (left < sizeof(struct ivar32_t)) {
4059 memcpy(&i, r, left);
4060 outs() << " (ivar_t entends past the end of the section)\n";
4061 } else
4062 memcpy(&i, r, sizeof(struct ivar32_t));
4063 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4064 swapStruct(i);
4065
4066 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4067 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4068 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4069 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4070 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4071 sys::swapByteOrder(ivar_offset);
4072 outs() << " " << ivar_offset << "\n";
4073 } else
4074 outs() << "\n";
4075
4076 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4077 name = get_pointer_32(i.name, xoffset, left, xS, info);
4078 if (name != nullptr)
4079 outs() << format(" %.*s", left, name);
4080 outs() << "\n";
4081
4082 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4083 name = get_pointer_32(i.type, xoffset, left, xS, info);
4084 if (name != nullptr)
4085 outs() << format(" %.*s", left, name);
4086 outs() << "\n";
4087
4088 outs() << "\t\t\talignment " << i.alignment << "\n";
4089 outs() << "\t\t\t size " << i.size << "\n";
4090
4091 p += sizeof(struct ivar32_t);
4092 offset += sizeof(struct ivar32_t);
4093 }
4094}
4095
Kevin Enderby0fc11822015-04-01 20:57:01 +00004096static void print_objc_property_list64(uint64_t p,
4097 struct DisassembleInfo *info) {
4098 struct objc_property_list64 opl;
4099 struct objc_property64 op;
4100 const char *r;
4101 uint32_t offset, xoffset, left, j;
4102 SectionRef S, xS;
4103 const char *name, *sym_name;
4104 uint64_t n_value;
4105
4106 r = get_pointer_64(p, offset, left, S, info);
4107 if (r == nullptr)
4108 return;
4109 memset(&opl, '\0', sizeof(struct objc_property_list64));
4110 if (left < sizeof(struct objc_property_list64)) {
4111 memcpy(&opl, r, left);
4112 outs() << " (objc_property_list entends past the end of the section)\n";
4113 } else
4114 memcpy(&opl, r, sizeof(struct objc_property_list64));
4115 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4116 swapStruct(opl);
4117 outs() << " entsize " << opl.entsize << "\n";
4118 outs() << " count " << opl.count << "\n";
4119
4120 p += sizeof(struct objc_property_list64);
4121 offset += sizeof(struct objc_property_list64);
4122 for (j = 0; j < opl.count; j++) {
4123 r = get_pointer_64(p, offset, left, S, info);
4124 if (r == nullptr)
4125 return;
4126 memset(&op, '\0', sizeof(struct objc_property64));
4127 if (left < sizeof(struct objc_property64)) {
4128 memcpy(&op, r, left);
4129 outs() << " (objc_property entends past the end of the section)\n";
4130 } else
4131 memcpy(&op, r, sizeof(struct objc_property64));
4132 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4133 swapStruct(op);
4134
4135 outs() << "\t\t\t name ";
4136 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4137 info, n_value, op.name);
4138 if (n_value != 0) {
4139 if (info->verbose && sym_name != nullptr)
4140 outs() << sym_name;
4141 else
4142 outs() << format("0x%" PRIx64, n_value);
4143 if (op.name != 0)
4144 outs() << " + " << format("0x%" PRIx64, op.name);
4145 } else
4146 outs() << format("0x%" PRIx64, op.name);
4147 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4148 if (name != nullptr)
4149 outs() << format(" %.*s", left, name);
4150 outs() << "\n";
4151
4152 outs() << "\t\t\tattributes ";
4153 sym_name =
4154 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4155 info, n_value, op.attributes);
4156 if (n_value != 0) {
4157 if (info->verbose && sym_name != nullptr)
4158 outs() << sym_name;
4159 else
4160 outs() << format("0x%" PRIx64, n_value);
4161 if (op.attributes != 0)
4162 outs() << " + " << format("0x%" PRIx64, op.attributes);
4163 } else
4164 outs() << format("0x%" PRIx64, op.attributes);
4165 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4166 if (name != nullptr)
4167 outs() << format(" %.*s", left, name);
4168 outs() << "\n";
4169
4170 p += sizeof(struct objc_property64);
4171 offset += sizeof(struct objc_property64);
4172 }
4173}
4174
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004175static void print_objc_property_list32(uint32_t p,
4176 struct DisassembleInfo *info) {
4177 struct objc_property_list32 opl;
4178 struct objc_property32 op;
4179 const char *r;
4180 uint32_t offset, xoffset, left, j;
4181 SectionRef S, xS;
4182 const char *name;
4183
4184 r = get_pointer_32(p, offset, left, S, info);
4185 if (r == nullptr)
4186 return;
4187 memset(&opl, '\0', sizeof(struct objc_property_list32));
4188 if (left < sizeof(struct objc_property_list32)) {
4189 memcpy(&opl, r, left);
4190 outs() << " (objc_property_list entends past the end of the section)\n";
4191 } else
4192 memcpy(&opl, r, sizeof(struct objc_property_list32));
4193 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4194 swapStruct(opl);
4195 outs() << " entsize " << opl.entsize << "\n";
4196 outs() << " count " << opl.count << "\n";
4197
4198 p += sizeof(struct objc_property_list32);
4199 offset += sizeof(struct objc_property_list32);
4200 for (j = 0; j < opl.count; j++) {
4201 r = get_pointer_32(p, offset, left, S, info);
4202 if (r == nullptr)
4203 return;
4204 memset(&op, '\0', sizeof(struct objc_property32));
4205 if (left < sizeof(struct objc_property32)) {
4206 memcpy(&op, r, left);
4207 outs() << " (objc_property entends past the end of the section)\n";
4208 } else
4209 memcpy(&op, r, sizeof(struct objc_property32));
4210 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4211 swapStruct(op);
4212
4213 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4214 name = get_pointer_32(op.name, xoffset, left, xS, info);
4215 if (name != nullptr)
4216 outs() << format(" %.*s", left, name);
4217 outs() << "\n";
4218
4219 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4220 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4221 if (name != nullptr)
4222 outs() << format(" %.*s", left, name);
4223 outs() << "\n";
4224
4225 p += sizeof(struct objc_property32);
4226 offset += sizeof(struct objc_property32);
4227 }
4228}
4229
Richard Smith81ff44d2015-10-09 22:09:56 +00004230static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
Kevin Enderby0fc11822015-04-01 20:57:01 +00004231 bool &is_meta_class) {
4232 struct class_ro64_t cro;
4233 const char *r;
4234 uint32_t offset, xoffset, left;
4235 SectionRef S, xS;
4236 const char *name, *sym_name;
4237 uint64_t n_value;
4238
4239 r = get_pointer_64(p, offset, left, S, info);
4240 if (r == nullptr || left < sizeof(struct class_ro64_t))
Richard Smith81ff44d2015-10-09 22:09:56 +00004241 return false;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004242 memset(&cro, '\0', sizeof(struct class_ro64_t));
4243 if (left < sizeof(struct class_ro64_t)) {
4244 memcpy(&cro, r, left);
4245 outs() << " (class_ro_t entends past the end of the section)\n";
4246 } else
4247 memcpy(&cro, r, sizeof(struct class_ro64_t));
4248 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4249 swapStruct(cro);
4250 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4251 if (cro.flags & RO_META)
4252 outs() << " RO_META";
4253 if (cro.flags & RO_ROOT)
4254 outs() << " RO_ROOT";
4255 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4256 outs() << " RO_HAS_CXX_STRUCTORS";
4257 outs() << "\n";
4258 outs() << " instanceStart " << cro.instanceStart << "\n";
4259 outs() << " instanceSize " << cro.instanceSize << "\n";
4260 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4261 << "\n";
4262 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4263 << "\n";
4264 print_layout_map64(cro.ivarLayout, info);
4265
4266 outs() << " name ";
4267 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4268 info, n_value, cro.name);
4269 if (n_value != 0) {
4270 if (info->verbose && sym_name != nullptr)
4271 outs() << sym_name;
4272 else
4273 outs() << format("0x%" PRIx64, n_value);
4274 if (cro.name != 0)
4275 outs() << " + " << format("0x%" PRIx64, cro.name);
4276 } else
4277 outs() << format("0x%" PRIx64, cro.name);
4278 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4279 if (name != nullptr)
4280 outs() << format(" %.*s", left, name);
4281 outs() << "\n";
4282
4283 outs() << " baseMethods ";
4284 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4285 S, info, n_value, cro.baseMethods);
4286 if (n_value != 0) {
4287 if (info->verbose && sym_name != nullptr)
4288 outs() << sym_name;
4289 else
4290 outs() << format("0x%" PRIx64, n_value);
4291 if (cro.baseMethods != 0)
4292 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4293 } else
4294 outs() << format("0x%" PRIx64, cro.baseMethods);
4295 outs() << " (struct method_list_t *)\n";
4296 if (cro.baseMethods + n_value != 0)
4297 print_method_list64_t(cro.baseMethods + n_value, info, "");
4298
4299 outs() << " baseProtocols ";
4300 sym_name =
4301 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4302 info, n_value, cro.baseProtocols);
4303 if (n_value != 0) {
4304 if (info->verbose && sym_name != nullptr)
4305 outs() << sym_name;
4306 else
4307 outs() << format("0x%" PRIx64, n_value);
4308 if (cro.baseProtocols != 0)
4309 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4310 } else
4311 outs() << format("0x%" PRIx64, cro.baseProtocols);
4312 outs() << "\n";
4313 if (cro.baseProtocols + n_value != 0)
4314 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4315
4316 outs() << " ivars ";
4317 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004318 info, n_value, cro.ivars);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004319 if (n_value != 0) {
4320 if (info->verbose && sym_name != nullptr)
4321 outs() << sym_name;
4322 else
4323 outs() << format("0x%" PRIx64, n_value);
4324 if (cro.ivars != 0)
4325 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4326 } else
4327 outs() << format("0x%" PRIx64, cro.ivars);
4328 outs() << "\n";
4329 if (cro.ivars + n_value != 0)
4330 print_ivar_list64_t(cro.ivars + n_value, info);
4331
4332 outs() << " weakIvarLayout ";
4333 sym_name =
4334 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4335 info, n_value, cro.weakIvarLayout);
4336 if (n_value != 0) {
4337 if (info->verbose && sym_name != nullptr)
4338 outs() << sym_name;
4339 else
4340 outs() << format("0x%" PRIx64, n_value);
4341 if (cro.weakIvarLayout != 0)
4342 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4343 } else
4344 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4345 outs() << "\n";
4346 print_layout_map64(cro.weakIvarLayout + n_value, info);
4347
4348 outs() << " baseProperties ";
4349 sym_name =
4350 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4351 info, n_value, cro.baseProperties);
4352 if (n_value != 0) {
4353 if (info->verbose && sym_name != nullptr)
4354 outs() << sym_name;
4355 else
4356 outs() << format("0x%" PRIx64, n_value);
4357 if (cro.baseProperties != 0)
4358 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4359 } else
4360 outs() << format("0x%" PRIx64, cro.baseProperties);
4361 outs() << "\n";
4362 if (cro.baseProperties + n_value != 0)
4363 print_objc_property_list64(cro.baseProperties + n_value, info);
4364
Rafael Espindolab9091322015-10-24 23:19:10 +00004365 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004366 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004367}
4368
Richard Smith81ff44d2015-10-09 22:09:56 +00004369static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004370 bool &is_meta_class) {
4371 struct class_ro32_t cro;
4372 const char *r;
4373 uint32_t offset, xoffset, left;
4374 SectionRef S, xS;
4375 const char *name;
4376
4377 r = get_pointer_32(p, offset, left, S, info);
4378 if (r == nullptr)
Richard Smith81ff44d2015-10-09 22:09:56 +00004379 return false;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004380 memset(&cro, '\0', sizeof(struct class_ro32_t));
4381 if (left < sizeof(struct class_ro32_t)) {
4382 memcpy(&cro, r, left);
4383 outs() << " (class_ro_t entends past the end of the section)\n";
4384 } else
4385 memcpy(&cro, r, sizeof(struct class_ro32_t));
4386 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4387 swapStruct(cro);
4388 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4389 if (cro.flags & RO_META)
4390 outs() << " RO_META";
4391 if (cro.flags & RO_ROOT)
4392 outs() << " RO_ROOT";
4393 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4394 outs() << " RO_HAS_CXX_STRUCTORS";
4395 outs() << "\n";
4396 outs() << " instanceStart " << cro.instanceStart << "\n";
4397 outs() << " instanceSize " << cro.instanceSize << "\n";
4398 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4399 << "\n";
4400 print_layout_map32(cro.ivarLayout, info);
4401
4402 outs() << " name " << format("0x%" PRIx32, cro.name);
4403 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4404 if (name != nullptr)
4405 outs() << format(" %.*s", left, name);
4406 outs() << "\n";
4407
4408 outs() << " baseMethods "
4409 << format("0x%" PRIx32, cro.baseMethods)
4410 << " (struct method_list_t *)\n";
4411 if (cro.baseMethods != 0)
4412 print_method_list32_t(cro.baseMethods, info, "");
4413
4414 outs() << " baseProtocols "
4415 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4416 if (cro.baseProtocols != 0)
4417 print_protocol_list32_t(cro.baseProtocols, info);
4418 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4419 << "\n";
4420 if (cro.ivars != 0)
4421 print_ivar_list32_t(cro.ivars, info);
4422 outs() << " weakIvarLayout "
4423 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4424 print_layout_map32(cro.weakIvarLayout, info);
4425 outs() << " baseProperties "
4426 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4427 if (cro.baseProperties != 0)
4428 print_objc_property_list32(cro.baseProperties, info);
Rafael Espindolab9091322015-10-24 23:19:10 +00004429 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004430 return true;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004431}
4432
Kevin Enderby0fc11822015-04-01 20:57:01 +00004433static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4434 struct class64_t c;
4435 const char *r;
4436 uint32_t offset, left;
4437 SectionRef S;
4438 const char *name;
4439 uint64_t isa_n_value, n_value;
4440
4441 r = get_pointer_64(p, offset, left, S, info);
4442 if (r == nullptr || left < sizeof(struct class64_t))
4443 return;
4444 memset(&c, '\0', sizeof(struct class64_t));
4445 if (left < sizeof(struct class64_t)) {
4446 memcpy(&c, r, left);
4447 outs() << " (class_t entends past the end of the section)\n";
4448 } else
4449 memcpy(&c, r, sizeof(struct class64_t));
4450 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4451 swapStruct(c);
4452
4453 outs() << " isa " << format("0x%" PRIx64, c.isa);
4454 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
4455 isa_n_value, c.isa);
4456 if (name != nullptr)
4457 outs() << " " << name;
4458 outs() << "\n";
4459
4460 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
4461 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
4462 n_value, c.superclass);
4463 if (name != nullptr)
4464 outs() << " " << name;
4465 outs() << "\n";
4466
4467 outs() << " cache " << format("0x%" PRIx64, c.cache);
4468 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
4469 n_value, c.cache);
4470 if (name != nullptr)
4471 outs() << " " << name;
4472 outs() << "\n";
4473
4474 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
4475 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
4476 n_value, c.vtable);
4477 if (name != nullptr)
4478 outs() << " " << name;
4479 outs() << "\n";
4480
4481 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
4482 n_value, c.data);
4483 outs() << " data ";
4484 if (n_value != 0) {
4485 if (info->verbose && name != nullptr)
4486 outs() << name;
4487 else
4488 outs() << format("0x%" PRIx64, n_value);
4489 if (c.data != 0)
4490 outs() << " + " << format("0x%" PRIx64, c.data);
4491 } else
4492 outs() << format("0x%" PRIx64, c.data);
4493 outs() << " (struct class_ro_t *)";
4494
4495 // This is a Swift class if some of the low bits of the pointer are set.
4496 if ((c.data + n_value) & 0x7)
4497 outs() << " Swift class";
4498 outs() << "\n";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004499 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004500 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
4501 return;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004502
Kevin Enderbyaac75382015-10-08 16:56:35 +00004503 if (!is_meta_class &&
4504 c.isa + isa_n_value != p &&
4505 c.isa + isa_n_value != 0 &&
4506 info->depth < 100) {
4507 info->depth++;
4508 outs() << "Meta Class\n";
4509 print_class64_t(c.isa + isa_n_value, info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004510 }
4511}
4512
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004513static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
4514 struct class32_t c;
4515 const char *r;
4516 uint32_t offset, left;
4517 SectionRef S;
4518 const char *name;
4519
4520 r = get_pointer_32(p, offset, left, S, info);
4521 if (r == nullptr)
4522 return;
4523 memset(&c, '\0', sizeof(struct class32_t));
4524 if (left < sizeof(struct class32_t)) {
4525 memcpy(&c, r, left);
4526 outs() << " (class_t entends past the end of the section)\n";
4527 } else
4528 memcpy(&c, r, sizeof(struct class32_t));
4529 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4530 swapStruct(c);
4531
4532 outs() << " isa " << format("0x%" PRIx32, c.isa);
4533 name =
4534 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
4535 if (name != nullptr)
4536 outs() << " " << name;
4537 outs() << "\n";
4538
4539 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
4540 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
4541 c.superclass);
4542 if (name != nullptr)
4543 outs() << " " << name;
4544 outs() << "\n";
4545
4546 outs() << " cache " << format("0x%" PRIx32, c.cache);
4547 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
4548 c.cache);
4549 if (name != nullptr)
4550 outs() << " " << name;
4551 outs() << "\n";
4552
4553 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
4554 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
4555 c.vtable);
4556 if (name != nullptr)
4557 outs() << " " << name;
4558 outs() << "\n";
4559
4560 name =
4561 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
4562 outs() << " data " << format("0x%" PRIx32, c.data)
4563 << " (struct class_ro_t *)";
4564
4565 // This is a Swift class if some of the low bits of the pointer are set.
4566 if (c.data & 0x3)
4567 outs() << " Swift class";
4568 outs() << "\n";
4569 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004570 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
4571 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004572
Hans Wennborgcc9deb42015-09-29 18:02:48 +00004573 if (!is_meta_class) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004574 outs() << "Meta Class\n";
4575 print_class32_t(c.isa, info);
4576 }
4577}
4578
Kevin Enderby846c0002015-04-16 17:19:59 +00004579static void print_objc_class_t(struct objc_class_t *objc_class,
4580 struct DisassembleInfo *info) {
4581 uint32_t offset, left, xleft;
4582 const char *name, *p, *ivar_list;
4583 SectionRef S;
4584 int32_t i;
4585 struct objc_ivar_list_t objc_ivar_list;
4586 struct objc_ivar_t ivar;
4587
4588 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
4589 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
4590 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
4591 if (name != nullptr)
4592 outs() << format(" %.*s", left, name);
4593 else
4594 outs() << " (not in an __OBJC section)";
4595 }
4596 outs() << "\n";
4597
4598 outs() << "\t super_class "
4599 << format("0x%08" PRIx32, objc_class->super_class);
4600 if (info->verbose) {
4601 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
4602 if (name != nullptr)
4603 outs() << format(" %.*s", left, name);
4604 else
4605 outs() << " (not in an __OBJC section)";
4606 }
4607 outs() << "\n";
4608
4609 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
4610 if (info->verbose) {
4611 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
4612 if (name != nullptr)
4613 outs() << format(" %.*s", left, name);
4614 else
4615 outs() << " (not in an __OBJC section)";
4616 }
4617 outs() << "\n";
4618
4619 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
4620 << "\n";
4621
4622 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
4623 if (info->verbose) {
4624 if (CLS_GETINFO(objc_class, CLS_CLASS))
4625 outs() << " CLS_CLASS";
4626 else if (CLS_GETINFO(objc_class, CLS_META))
4627 outs() << " CLS_META";
4628 }
4629 outs() << "\n";
4630
4631 outs() << "\t instance_size "
4632 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
4633
4634 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
4635 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
4636 if (p != nullptr) {
4637 if (left > sizeof(struct objc_ivar_list_t)) {
4638 outs() << "\n";
4639 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
4640 } else {
4641 outs() << " (entends past the end of the section)\n";
4642 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
4643 memcpy(&objc_ivar_list, p, left);
4644 }
4645 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4646 swapStruct(objc_ivar_list);
4647 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
4648 ivar_list = p + sizeof(struct objc_ivar_list_t);
4649 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
4650 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
4651 outs() << "\t\t remaining ivar's extend past the of the section\n";
4652 break;
4653 }
4654 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
4655 sizeof(struct objc_ivar_t));
4656 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4657 swapStruct(ivar);
4658
4659 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
4660 if (info->verbose) {
4661 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
4662 if (name != nullptr)
4663 outs() << format(" %.*s", xleft, name);
4664 else
4665 outs() << " (not in an __OBJC section)";
4666 }
4667 outs() << "\n";
4668
4669 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
4670 if (info->verbose) {
4671 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
4672 if (name != nullptr)
4673 outs() << format(" %.*s", xleft, name);
4674 else
4675 outs() << " (not in an __OBJC section)";
4676 }
4677 outs() << "\n";
4678
4679 outs() << "\t\t ivar_offset "
4680 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
4681 }
4682 } else {
4683 outs() << " (not in an __OBJC section)\n";
4684 }
4685
4686 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
4687 if (print_method_list(objc_class->methodLists, info))
4688 outs() << " (not in an __OBJC section)\n";
4689
4690 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
4691 << "\n";
4692
4693 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
4694 if (print_protocol_list(objc_class->protocols, 16, info))
4695 outs() << " (not in an __OBJC section)\n";
4696}
4697
4698static void print_objc_objc_category_t(struct objc_category_t *objc_category,
4699 struct DisassembleInfo *info) {
4700 uint32_t offset, left;
4701 const char *name;
4702 SectionRef S;
4703
4704 outs() << "\t category name "
4705 << format("0x%08" PRIx32, objc_category->category_name);
4706 if (info->verbose) {
4707 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
4708 true);
4709 if (name != nullptr)
4710 outs() << format(" %.*s", left, name);
4711 else
4712 outs() << " (not in an __OBJC section)";
4713 }
4714 outs() << "\n";
4715
4716 outs() << "\t\t class name "
4717 << format("0x%08" PRIx32, objc_category->class_name);
4718 if (info->verbose) {
4719 name =
4720 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
4721 if (name != nullptr)
4722 outs() << format(" %.*s", left, name);
4723 else
4724 outs() << " (not in an __OBJC section)";
4725 }
4726 outs() << "\n";
4727
4728 outs() << "\t instance methods "
4729 << format("0x%08" PRIx32, objc_category->instance_methods);
4730 if (print_method_list(objc_category->instance_methods, info))
4731 outs() << " (not in an __OBJC section)\n";
4732
4733 outs() << "\t class methods "
4734 << format("0x%08" PRIx32, objc_category->class_methods);
4735 if (print_method_list(objc_category->class_methods, info))
4736 outs() << " (not in an __OBJC section)\n";
4737}
4738
Kevin Enderby0fc11822015-04-01 20:57:01 +00004739static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
4740 struct category64_t c;
4741 const char *r;
4742 uint32_t offset, xoffset, left;
4743 SectionRef S, xS;
4744 const char *name, *sym_name;
4745 uint64_t n_value;
4746
4747 r = get_pointer_64(p, offset, left, S, info);
4748 if (r == nullptr)
4749 return;
4750 memset(&c, '\0', sizeof(struct category64_t));
4751 if (left < sizeof(struct category64_t)) {
4752 memcpy(&c, r, left);
4753 outs() << " (category_t entends past the end of the section)\n";
4754 } else
4755 memcpy(&c, r, sizeof(struct category64_t));
4756 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4757 swapStruct(c);
4758
4759 outs() << " name ";
4760 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
4761 info, n_value, c.name);
4762 if (n_value != 0) {
4763 if (info->verbose && sym_name != nullptr)
4764 outs() << sym_name;
4765 else
4766 outs() << format("0x%" PRIx64, n_value);
4767 if (c.name != 0)
4768 outs() << " + " << format("0x%" PRIx64, c.name);
4769 } else
4770 outs() << format("0x%" PRIx64, c.name);
4771 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
4772 if (name != nullptr)
4773 outs() << format(" %.*s", left, name);
4774 outs() << "\n";
4775
4776 outs() << " cls ";
4777 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
4778 n_value, c.cls);
4779 if (n_value != 0) {
4780 if (info->verbose && sym_name != nullptr)
4781 outs() << sym_name;
4782 else
4783 outs() << format("0x%" PRIx64, n_value);
4784 if (c.cls != 0)
4785 outs() << " + " << format("0x%" PRIx64, c.cls);
4786 } else
4787 outs() << format("0x%" PRIx64, c.cls);
4788 outs() << "\n";
4789 if (c.cls + n_value != 0)
4790 print_class64_t(c.cls + n_value, info);
4791
4792 outs() << " instanceMethods ";
4793 sym_name =
4794 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
4795 info, n_value, c.instanceMethods);
4796 if (n_value != 0) {
4797 if (info->verbose && sym_name != nullptr)
4798 outs() << sym_name;
4799 else
4800 outs() << format("0x%" PRIx64, n_value);
4801 if (c.instanceMethods != 0)
4802 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
4803 } else
4804 outs() << format("0x%" PRIx64, c.instanceMethods);
4805 outs() << "\n";
4806 if (c.instanceMethods + n_value != 0)
4807 print_method_list64_t(c.instanceMethods + n_value, info, "");
4808
4809 outs() << " classMethods ";
4810 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
4811 S, info, n_value, c.classMethods);
4812 if (n_value != 0) {
4813 if (info->verbose && sym_name != nullptr)
4814 outs() << sym_name;
4815 else
4816 outs() << format("0x%" PRIx64, n_value);
4817 if (c.classMethods != 0)
4818 outs() << " + " << format("0x%" PRIx64, c.classMethods);
4819 } else
4820 outs() << format("0x%" PRIx64, c.classMethods);
4821 outs() << "\n";
4822 if (c.classMethods + n_value != 0)
4823 print_method_list64_t(c.classMethods + n_value, info, "");
4824
4825 outs() << " protocols ";
4826 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
4827 info, n_value, c.protocols);
4828 if (n_value != 0) {
4829 if (info->verbose && sym_name != nullptr)
4830 outs() << sym_name;
4831 else
4832 outs() << format("0x%" PRIx64, n_value);
4833 if (c.protocols != 0)
4834 outs() << " + " << format("0x%" PRIx64, c.protocols);
4835 } else
4836 outs() << format("0x%" PRIx64, c.protocols);
4837 outs() << "\n";
4838 if (c.protocols + n_value != 0)
4839 print_protocol_list64_t(c.protocols + n_value, info);
4840
4841 outs() << "instanceProperties ";
4842 sym_name =
4843 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
4844 S, info, n_value, c.instanceProperties);
4845 if (n_value != 0) {
4846 if (info->verbose && sym_name != nullptr)
4847 outs() << sym_name;
4848 else
4849 outs() << format("0x%" PRIx64, n_value);
4850 if (c.instanceProperties != 0)
4851 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
4852 } else
4853 outs() << format("0x%" PRIx64, c.instanceProperties);
4854 outs() << "\n";
4855 if (c.instanceProperties + n_value != 0)
4856 print_objc_property_list64(c.instanceProperties + n_value, info);
4857}
4858
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004859static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
4860 struct category32_t c;
4861 const char *r;
4862 uint32_t offset, left;
4863 SectionRef S, xS;
4864 const char *name;
4865
4866 r = get_pointer_32(p, offset, left, S, info);
4867 if (r == nullptr)
4868 return;
4869 memset(&c, '\0', sizeof(struct category32_t));
4870 if (left < sizeof(struct category32_t)) {
4871 memcpy(&c, r, left);
4872 outs() << " (category_t entends past the end of the section)\n";
4873 } else
4874 memcpy(&c, r, sizeof(struct category32_t));
4875 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4876 swapStruct(c);
4877
4878 outs() << " name " << format("0x%" PRIx32, c.name);
4879 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
4880 c.name);
Hans Wennborgcc9deb42015-09-29 18:02:48 +00004881 if (name)
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004882 outs() << " " << name;
4883 outs() << "\n";
4884
4885 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
4886 if (c.cls != 0)
4887 print_class32_t(c.cls, info);
4888 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
4889 << "\n";
4890 if (c.instanceMethods != 0)
4891 print_method_list32_t(c.instanceMethods, info, "");
4892 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
4893 << "\n";
4894 if (c.classMethods != 0)
4895 print_method_list32_t(c.classMethods, info, "");
4896 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
4897 if (c.protocols != 0)
4898 print_protocol_list32_t(c.protocols, info);
4899 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
4900 << "\n";
4901 if (c.instanceProperties != 0)
4902 print_objc_property_list32(c.instanceProperties, info);
4903}
4904
Kevin Enderby0fc11822015-04-01 20:57:01 +00004905static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
4906 uint32_t i, left, offset, xoffset;
4907 uint64_t p, n_value;
4908 struct message_ref64 mr;
4909 const char *name, *sym_name;
4910 const char *r;
4911 SectionRef xS;
4912
4913 if (S == SectionRef())
4914 return;
4915
4916 StringRef SectName;
4917 S.getName(SectName);
4918 DataRefImpl Ref = S.getRawDataRefImpl();
4919 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
4920 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4921 offset = 0;
4922 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
4923 p = S.getAddress() + i;
4924 r = get_pointer_64(p, offset, left, S, info);
4925 if (r == nullptr)
4926 return;
4927 memset(&mr, '\0', sizeof(struct message_ref64));
4928 if (left < sizeof(struct message_ref64)) {
4929 memcpy(&mr, r, left);
4930 outs() << " (message_ref entends past the end of the section)\n";
4931 } else
4932 memcpy(&mr, r, sizeof(struct message_ref64));
4933 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4934 swapStruct(mr);
4935
4936 outs() << " imp ";
4937 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
4938 n_value, mr.imp);
4939 if (n_value != 0) {
4940 outs() << format("0x%" PRIx64, n_value) << " ";
4941 if (mr.imp != 0)
4942 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
4943 } else
4944 outs() << format("0x%" PRIx64, mr.imp) << " ";
4945 if (name != nullptr)
4946 outs() << " " << name;
4947 outs() << "\n";
4948
4949 outs() << " sel ";
4950 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
4951 info, n_value, mr.sel);
4952 if (n_value != 0) {
4953 if (info->verbose && sym_name != nullptr)
4954 outs() << sym_name;
4955 else
4956 outs() << format("0x%" PRIx64, n_value);
4957 if (mr.sel != 0)
4958 outs() << " + " << format("0x%" PRIx64, mr.sel);
4959 } else
4960 outs() << format("0x%" PRIx64, mr.sel);
4961 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
4962 if (name != nullptr)
4963 outs() << format(" %.*s", left, name);
4964 outs() << "\n";
4965
4966 offset += sizeof(struct message_ref64);
4967 }
4968}
4969
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004970static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
4971 uint32_t i, left, offset, xoffset, p;
4972 struct message_ref32 mr;
4973 const char *name, *r;
4974 SectionRef xS;
4975
4976 if (S == SectionRef())
4977 return;
4978
4979 StringRef SectName;
4980 S.getName(SectName);
4981 DataRefImpl Ref = S.getRawDataRefImpl();
4982 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
4983 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4984 offset = 0;
4985 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
4986 p = S.getAddress() + i;
4987 r = get_pointer_32(p, offset, left, S, info);
4988 if (r == nullptr)
4989 return;
4990 memset(&mr, '\0', sizeof(struct message_ref32));
4991 if (left < sizeof(struct message_ref32)) {
4992 memcpy(&mr, r, left);
4993 outs() << " (message_ref entends past the end of the section)\n";
4994 } else
4995 memcpy(&mr, r, sizeof(struct message_ref32));
4996 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4997 swapStruct(mr);
4998
4999 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5000 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5001 mr.imp);
5002 if (name != nullptr)
5003 outs() << " " << name;
5004 outs() << "\n";
5005
5006 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5007 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5008 if (name != nullptr)
5009 outs() << " " << name;
5010 outs() << "\n";
5011
5012 offset += sizeof(struct message_ref32);
5013 }
5014}
5015
Kevin Enderby0fc11822015-04-01 20:57:01 +00005016static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5017 uint32_t left, offset, swift_version;
5018 uint64_t p;
5019 struct objc_image_info64 o;
5020 const char *r;
5021
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00005022 if (S == SectionRef())
5023 return;
5024
Kevin Enderby0fc11822015-04-01 20:57:01 +00005025 StringRef SectName;
5026 S.getName(SectName);
5027 DataRefImpl Ref = S.getRawDataRefImpl();
5028 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5029 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5030 p = S.getAddress();
5031 r = get_pointer_64(p, offset, left, S, info);
5032 if (r == nullptr)
5033 return;
5034 memset(&o, '\0', sizeof(struct objc_image_info64));
5035 if (left < sizeof(struct objc_image_info64)) {
5036 memcpy(&o, r, left);
5037 outs() << " (objc_image_info entends past the end of the section)\n";
5038 } else
5039 memcpy(&o, r, sizeof(struct objc_image_info64));
5040 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5041 swapStruct(o);
5042 outs() << " version " << o.version << "\n";
5043 outs() << " flags " << format("0x%" PRIx32, o.flags);
5044 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5045 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5046 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5047 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5048 swift_version = (o.flags >> 8) & 0xff;
5049 if (swift_version != 0) {
5050 if (swift_version == 1)
5051 outs() << " Swift 1.0";
5052 else if (swift_version == 2)
5053 outs() << " Swift 1.1";
5054 else
5055 outs() << " unknown future Swift version (" << swift_version << ")";
5056 }
5057 outs() << "\n";
5058}
5059
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005060static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5061 uint32_t left, offset, swift_version, p;
5062 struct objc_image_info32 o;
5063 const char *r;
5064
5065 StringRef SectName;
5066 S.getName(SectName);
5067 DataRefImpl Ref = S.getRawDataRefImpl();
5068 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5069 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5070 p = S.getAddress();
5071 r = get_pointer_32(p, offset, left, S, info);
5072 if (r == nullptr)
5073 return;
5074 memset(&o, '\0', sizeof(struct objc_image_info32));
5075 if (left < sizeof(struct objc_image_info32)) {
5076 memcpy(&o, r, left);
5077 outs() << " (objc_image_info entends past the end of the section)\n";
5078 } else
5079 memcpy(&o, r, sizeof(struct objc_image_info32));
5080 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5081 swapStruct(o);
5082 outs() << " version " << o.version << "\n";
5083 outs() << " flags " << format("0x%" PRIx32, o.flags);
5084 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5085 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5086 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5087 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5088 swift_version = (o.flags >> 8) & 0xff;
5089 if (swift_version != 0) {
5090 if (swift_version == 1)
5091 outs() << " Swift 1.0";
5092 else if (swift_version == 2)
5093 outs() << " Swift 1.1";
5094 else
5095 outs() << " unknown future Swift version (" << swift_version << ")";
5096 }
5097 outs() << "\n";
5098}
5099
Kevin Enderby846c0002015-04-16 17:19:59 +00005100static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5101 uint32_t left, offset, p;
5102 struct imageInfo_t o;
5103 const char *r;
5104
5105 StringRef SectName;
5106 S.getName(SectName);
5107 DataRefImpl Ref = S.getRawDataRefImpl();
5108 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5109 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5110 p = S.getAddress();
5111 r = get_pointer_32(p, offset, left, S, info);
5112 if (r == nullptr)
5113 return;
5114 memset(&o, '\0', sizeof(struct imageInfo_t));
5115 if (left < sizeof(struct imageInfo_t)) {
5116 memcpy(&o, r, left);
5117 outs() << " (imageInfo entends past the end of the section)\n";
5118 } else
5119 memcpy(&o, r, sizeof(struct imageInfo_t));
5120 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5121 swapStruct(o);
5122 outs() << " version " << o.version << "\n";
5123 outs() << " flags " << format("0x%" PRIx32, o.flags);
5124 if (o.flags & 0x1)
5125 outs() << " F&C";
5126 if (o.flags & 0x2)
5127 outs() << " GC";
5128 if (o.flags & 0x4)
5129 outs() << " GC-only";
5130 else
5131 outs() << " RR";
5132 outs() << "\n";
5133}
5134
Kevin Enderby0fc11822015-04-01 20:57:01 +00005135static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5136 SymbolAddressMap AddrMap;
5137 if (verbose)
5138 CreateSymbolAddressMap(O, &AddrMap);
5139
5140 std::vector<SectionRef> Sections;
5141 for (const SectionRef &Section : O->sections()) {
5142 StringRef SectName;
5143 Section.getName(SectName);
5144 Sections.push_back(Section);
5145 }
5146
5147 struct DisassembleInfo info;
5148 // Set up the block of info used by the Symbolizer call backs.
5149 info.verbose = verbose;
5150 info.O = O;
5151 info.AddrMap = &AddrMap;
5152 info.Sections = &Sections;
5153 info.class_name = nullptr;
5154 info.selector_name = nullptr;
5155 info.method = nullptr;
5156 info.demangled_name = nullptr;
5157 info.bindtable = nullptr;
5158 info.adrp_addr = 0;
5159 info.adrp_inst = 0;
5160
Kevin Enderbyaac75382015-10-08 16:56:35 +00005161 info.depth = 0;
Davide Italiano62507042015-12-11 22:27:59 +00005162 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5163 if (CL == SectionRef())
5164 CL = get_section(O, "__DATA", "__objc_classlist");
5165 info.S = CL;
5166 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005167
Davide Italiano62507042015-12-11 22:27:59 +00005168 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5169 if (CR == SectionRef())
5170 CR = get_section(O, "__DATA", "__objc_classrefs");
5171 info.S = CR;
5172 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005173
Davide Italiano62507042015-12-11 22:27:59 +00005174 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5175 if (SR == SectionRef())
5176 SR = get_section(O, "__DATA", "__objc_superrefs");
5177 info.S = SR;
5178 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005179
Davide Italiano62507042015-12-11 22:27:59 +00005180 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5181 if (CA == SectionRef())
5182 CA = get_section(O, "__DATA", "__objc_catlist");
5183 info.S = CA;
5184 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005185
Davide Italiano62507042015-12-11 22:27:59 +00005186 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5187 if (PL == SectionRef())
5188 PL = get_section(O, "__DATA", "__objc_protolist");
5189 info.S = PL;
5190 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005191
Davide Italiano62507042015-12-11 22:27:59 +00005192 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5193 if (MR == SectionRef())
5194 MR = get_section(O, "__DATA", "__objc_msgrefs");
5195 info.S = MR;
5196 print_message_refs64(MR, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005197
Davide Italiano62507042015-12-11 22:27:59 +00005198 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5199 if (II == SectionRef())
5200 II = get_section(O, "__DATA", "__objc_imageinfo");
5201 info.S = II;
5202 print_image_info64(II, &info);
Kevin Enderby0bc6ed42015-04-01 21:50:45 +00005203
5204 if (info.bindtable != nullptr)
5205 delete info.bindtable;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005206}
5207
5208static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005209 SymbolAddressMap AddrMap;
5210 if (verbose)
5211 CreateSymbolAddressMap(O, &AddrMap);
5212
5213 std::vector<SectionRef> Sections;
5214 for (const SectionRef &Section : O->sections()) {
5215 StringRef SectName;
5216 Section.getName(SectName);
5217 Sections.push_back(Section);
5218 }
5219
5220 struct DisassembleInfo info;
5221 // Set up the block of info used by the Symbolizer call backs.
5222 info.verbose = verbose;
5223 info.O = O;
5224 info.AddrMap = &AddrMap;
5225 info.Sections = &Sections;
5226 info.class_name = nullptr;
5227 info.selector_name = nullptr;
5228 info.method = nullptr;
5229 info.demangled_name = nullptr;
5230 info.bindtable = nullptr;
5231 info.adrp_addr = 0;
5232 info.adrp_inst = 0;
5233
5234 const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5235 if (CL != SectionRef()) {
5236 info.S = CL;
5237 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5238 } else {
5239 const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
5240 info.S = CL;
5241 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5242 }
5243
5244 const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5245 if (CR != SectionRef()) {
5246 info.S = CR;
5247 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5248 } else {
5249 const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
5250 info.S = CR;
5251 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5252 }
5253
5254 const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5255 if (SR != SectionRef()) {
5256 info.S = SR;
5257 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5258 } else {
5259 const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
5260 info.S = SR;
5261 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5262 }
5263
5264 const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5265 if (CA != SectionRef()) {
5266 info.S = CA;
5267 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5268 } else {
5269 const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
5270 info.S = CA;
5271 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5272 }
5273
5274 const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5275 if (PL != SectionRef()) {
5276 info.S = PL;
5277 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5278 } else {
5279 const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
5280 info.S = PL;
5281 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5282 }
5283
5284 const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5285 if (MR != SectionRef()) {
5286 info.S = MR;
5287 print_message_refs32(MR, &info);
5288 } else {
5289 const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
5290 info.S = MR;
5291 print_message_refs32(MR, &info);
5292 }
5293
5294 const SectionRef II = get_section(O, "__OBJC2", "__image_info");
5295 if (II != SectionRef()) {
5296 info.S = II;
5297 print_image_info32(II, &info);
5298 } else {
5299 const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
5300 info.S = II;
5301 print_image_info32(II, &info);
5302 }
Kevin Enderby0fc11822015-04-01 20:57:01 +00005303}
5304
5305static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby846c0002015-04-16 17:19:59 +00005306 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5307 const char *r, *name, *defs;
5308 struct objc_module_t module;
5309 SectionRef S, xS;
5310 struct objc_symtab_t symtab;
5311 struct objc_class_t objc_class;
5312 struct objc_category_t objc_category;
5313
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005314 outs() << "Objective-C segment\n";
Kevin Enderby846c0002015-04-16 17:19:59 +00005315 S = get_section(O, "__OBJC", "__module_info");
5316 if (S == SectionRef())
5317 return false;
5318
5319 SymbolAddressMap AddrMap;
5320 if (verbose)
5321 CreateSymbolAddressMap(O, &AddrMap);
5322
5323 std::vector<SectionRef> Sections;
5324 for (const SectionRef &Section : O->sections()) {
5325 StringRef SectName;
5326 Section.getName(SectName);
5327 Sections.push_back(Section);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005328 }
Kevin Enderby846c0002015-04-16 17:19:59 +00005329
5330 struct DisassembleInfo info;
5331 // Set up the block of info used by the Symbolizer call backs.
5332 info.verbose = verbose;
5333 info.O = O;
5334 info.AddrMap = &AddrMap;
5335 info.Sections = &Sections;
5336 info.class_name = nullptr;
5337 info.selector_name = nullptr;
5338 info.method = nullptr;
5339 info.demangled_name = nullptr;
5340 info.bindtable = nullptr;
5341 info.adrp_addr = 0;
5342 info.adrp_inst = 0;
5343
5344 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5345 p = S.getAddress() + i;
5346 r = get_pointer_32(p, offset, left, S, &info, true);
5347 if (r == nullptr)
5348 return true;
5349 memset(&module, '\0', sizeof(struct objc_module_t));
5350 if (left < sizeof(struct objc_module_t)) {
5351 memcpy(&module, r, left);
5352 outs() << " (module extends past end of __module_info section)\n";
5353 } else
5354 memcpy(&module, r, sizeof(struct objc_module_t));
5355 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5356 swapStruct(module);
5357
5358 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5359 outs() << " version " << module.version << "\n";
5360 outs() << " size " << module.size << "\n";
5361 outs() << " name ";
5362 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5363 if (name != nullptr)
5364 outs() << format("%.*s", left, name);
5365 else
5366 outs() << format("0x%08" PRIx32, module.name)
5367 << "(not in an __OBJC section)";
5368 outs() << "\n";
5369
5370 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5371 if (module.symtab == 0 || r == nullptr) {
5372 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5373 << " (not in an __OBJC section)\n";
5374 continue;
5375 }
5376 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5377 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5378 defs_left = 0;
5379 defs = nullptr;
5380 if (left < sizeof(struct objc_symtab_t)) {
5381 memcpy(&symtab, r, left);
5382 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5383 } else {
5384 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5385 if (left > sizeof(struct objc_symtab_t)) {
5386 defs_left = left - sizeof(struct objc_symtab_t);
5387 defs = r + sizeof(struct objc_symtab_t);
5388 }
5389 }
5390 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5391 swapStruct(symtab);
5392
5393 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5394 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5395 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5396 if (r == nullptr)
5397 outs() << " (not in an __OBJC section)";
5398 outs() << "\n";
5399 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5400 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5401 if (symtab.cls_def_cnt > 0)
5402 outs() << "\tClass Definitions\n";
5403 for (j = 0; j < symtab.cls_def_cnt; j++) {
5404 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5405 outs() << "\t(remaining class defs entries entends past the end of the "
5406 << "section)\n";
5407 break;
5408 }
5409 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5410 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5411 sys::swapByteOrder(def);
5412
5413 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5414 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5415 if (r != nullptr) {
5416 if (left > sizeof(struct objc_class_t)) {
5417 outs() << "\n";
5418 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5419 } else {
5420 outs() << " (entends past the end of the section)\n";
5421 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5422 memcpy(&objc_class, r, left);
5423 }
5424 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5425 swapStruct(objc_class);
5426 print_objc_class_t(&objc_class, &info);
5427 } else {
5428 outs() << "(not in an __OBJC section)\n";
5429 }
5430
5431 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
5432 outs() << "\tMeta Class";
5433 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
5434 if (r != nullptr) {
5435 if (left > sizeof(struct objc_class_t)) {
5436 outs() << "\n";
5437 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5438 } else {
5439 outs() << " (entends past the end of the section)\n";
5440 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5441 memcpy(&objc_class, r, left);
5442 }
5443 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5444 swapStruct(objc_class);
5445 print_objc_class_t(&objc_class, &info);
5446 } else {
5447 outs() << "(not in an __OBJC section)\n";
5448 }
5449 }
5450 }
5451 if (symtab.cat_def_cnt > 0)
5452 outs() << "\tCategory Definitions\n";
5453 for (j = 0; j < symtab.cat_def_cnt; j++) {
5454 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
5455 outs() << "\t(remaining category defs entries entends past the end of "
5456 << "the section)\n";
5457 break;
5458 }
5459 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
5460 sizeof(uint32_t));
5461 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5462 sys::swapByteOrder(def);
5463
5464 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5465 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
5466 << format("0x%08" PRIx32, def);
5467 if (r != nullptr) {
5468 if (left > sizeof(struct objc_category_t)) {
5469 outs() << "\n";
5470 memcpy(&objc_category, r, sizeof(struct objc_category_t));
5471 } else {
5472 outs() << " (entends past the end of the section)\n";
5473 memset(&objc_category, '\0', sizeof(struct objc_category_t));
5474 memcpy(&objc_category, r, left);
5475 }
5476 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5477 swapStruct(objc_category);
5478 print_objc_objc_category_t(&objc_category, &info);
5479 } else {
5480 outs() << "(not in an __OBJC section)\n";
5481 }
5482 }
5483 }
5484 const SectionRef II = get_section(O, "__OBJC", "__image_info");
5485 if (II != SectionRef())
5486 print_image_info(II, &info);
5487
5488 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005489}
5490
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00005491static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
5492 uint32_t size, uint32_t addr) {
5493 SymbolAddressMap AddrMap;
5494 CreateSymbolAddressMap(O, &AddrMap);
5495
5496 std::vector<SectionRef> Sections;
5497 for (const SectionRef &Section : O->sections()) {
5498 StringRef SectName;
5499 Section.getName(SectName);
5500 Sections.push_back(Section);
5501 }
5502
5503 struct DisassembleInfo info;
5504 // Set up the block of info used by the Symbolizer call backs.
5505 info.verbose = true;
5506 info.O = O;
5507 info.AddrMap = &AddrMap;
5508 info.Sections = &Sections;
5509 info.class_name = nullptr;
5510 info.selector_name = nullptr;
5511 info.method = nullptr;
5512 info.demangled_name = nullptr;
5513 info.bindtable = nullptr;
5514 info.adrp_addr = 0;
5515 info.adrp_inst = 0;
5516
5517 const char *p;
5518 struct objc_protocol_t protocol;
5519 uint32_t left, paddr;
5520 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
5521 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
5522 left = size - (p - sect);
5523 if (left < sizeof(struct objc_protocol_t)) {
5524 outs() << "Protocol extends past end of __protocol section\n";
5525 memcpy(&protocol, p, left);
5526 } else
5527 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
5528 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5529 swapStruct(protocol);
5530 paddr = addr + (p - sect);
5531 outs() << "Protocol " << format("0x%" PRIx32, paddr);
5532 if (print_protocol(paddr, 0, &info))
5533 outs() << "(not in an __OBJC section)\n";
5534 }
5535}
5536
Kevin Enderby0fc11822015-04-01 20:57:01 +00005537static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
5538 if (O->is64Bit())
5539 printObjc2_64bit_MetaData(O, verbose);
5540 else {
5541 MachO::mach_header H;
5542 H = O->getHeader();
5543 if (H.cputype == MachO::CPU_TYPE_ARM)
5544 printObjc2_32bit_MetaData(O, verbose);
5545 else {
5546 // This is the 32-bit non-arm cputype case. Which is normally
5547 // the first Objective-C ABI. But it may be the case of a
5548 // binary for the iOS simulator which is the second Objective-C
5549 // ABI. In that case printObjc1_32bit_MetaData() will determine that
5550 // and return false.
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005551 if (!printObjc1_32bit_MetaData(O, verbose))
Kevin Enderby0fc11822015-04-01 20:57:01 +00005552 printObjc2_32bit_MetaData(O, verbose);
5553 }
5554 }
5555}
5556
Kevin Enderbybf246f52014-09-24 23:08:22 +00005557// GuessLiteralPointer returns a string which for the item in the Mach-O file
5558// for the address passed in as ReferenceValue for printing as a comment with
5559// the instruction and also returns the corresponding type of that item
5560// indirectly through ReferenceType.
5561//
5562// If ReferenceValue is an address of literal cstring then a pointer to the
5563// cstring is returned and ReferenceType is set to
5564// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
5565//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005566// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
5567// Class ref that name is returned and the ReferenceType is set accordingly.
5568//
5569// Lastly, literals which are Symbol address in a literal pool are looked for
5570// and if found the symbol name is returned and ReferenceType is set to
5571// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
5572//
5573// If there is no item in the Mach-O file for the address passed in as
5574// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00005575static const char *GuessLiteralPointer(uint64_t ReferenceValue,
5576 uint64_t ReferencePC,
5577 uint64_t *ReferenceType,
5578 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00005579 // First see if there is an external relocation entry at the ReferencePC.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00005580 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
5581 uint64_t sect_addr = info->S.getAddress();
5582 uint64_t sect_offset = ReferencePC - sect_addr;
5583 bool reloc_found = false;
5584 DataRefImpl Rel;
5585 MachO::any_relocation_info RE;
5586 bool isExtern = false;
5587 SymbolRef Symbol;
5588 for (const RelocationRef &Reloc : info->S.relocations()) {
5589 uint64_t RelocOffset = Reloc.getOffset();
5590 if (RelocOffset == sect_offset) {
5591 Rel = Reloc.getRawDataRefImpl();
5592 RE = info->O->getRelocation(Rel);
5593 if (info->O->isRelocationScattered(RE))
5594 continue;
5595 isExtern = info->O->getPlainRelocationExternal(RE);
5596 if (isExtern) {
5597 symbol_iterator RelocSym = Reloc.getSymbol();
5598 Symbol = *RelocSym;
5599 }
5600 reloc_found = true;
5601 break;
Kevin Enderbybf246f52014-09-24 23:08:22 +00005602 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005603 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00005604 // If there is an external relocation entry for a symbol in a section
5605 // then used that symbol's value for the value of the reference.
5606 if (reloc_found && isExtern) {
5607 if (info->O->getAnyRelocationPCRel(RE)) {
5608 unsigned Type = info->O->getAnyRelocationType(RE);
5609 if (Type == MachO::X86_64_RELOC_SIGNED) {
5610 ReferenceValue = Symbol.getValue();
5611 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005612 }
5613 }
5614 }
5615
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005616 // Look for literals such as Objective-C CFStrings refs, Selector refs,
5617 // Message refs and Class refs.
5618 bool classref, selref, msgref, cfstring;
5619 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
5620 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00005621 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005622 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
5623 // And the pointer_value in that section is typically zero as it will be
5624 // set by dyld as part of the "bind information".
5625 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
5626 if (name != nullptr) {
5627 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00005628 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005629 if (class_name != nullptr && class_name[1] == '_' &&
5630 class_name[2] != '\0') {
5631 info->class_name = class_name + 2;
5632 return name;
5633 }
5634 }
5635 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005636
David Blaikie33dd45d02015-03-23 18:39:02 +00005637 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005638 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
5639 const char *name =
5640 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
5641 if (name != nullptr)
5642 info->class_name = name;
5643 else
5644 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00005645 return name;
5646 }
5647
David Blaikie33dd45d02015-03-23 18:39:02 +00005648 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005649 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
5650 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
5651 return name;
5652 }
5653
David Blaikie33dd45d02015-03-23 18:39:02 +00005654 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005655 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
5656
5657 if (pointer_value != 0)
5658 ReferenceValue = pointer_value;
5659
5660 const char *name = GuessCstringPointer(ReferenceValue, info);
5661 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00005662 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005663 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
5664 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00005665 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005666 info->class_name = nullptr;
5667 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
5668 info->selector_name = name;
5669 } else
5670 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
5671 return name;
5672 }
5673
5674 // Lastly look for an indirect symbol with this ReferenceValue which is in
5675 // a literal pool. If found return that symbol name.
5676 name = GuessIndirectSymbol(ReferenceValue, info);
5677 if (name) {
5678 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
5679 return name;
5680 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005681
5682 return nullptr;
5683}
5684
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005685// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00005686// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005687// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
5688// is created and returns the symbol name that matches the ReferenceValue or
5689// nullptr if none. The ReferenceType is passed in for the IN type of
5690// reference the instruction is making from the values in defined in the header
5691// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
5692// Out type and the ReferenceName will also be set which is added as a comment
5693// to the disassembled instruction.
5694//
Kevin Enderby04bf6932014-10-28 23:39:46 +00005695#if HAVE_CXXABI_H
5696// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005697// returned through ReferenceName and ReferenceType is set to
5698// LLVMDisassembler_ReferenceType_DeMangled_Name .
Kevin Enderby04bf6932014-10-28 23:39:46 +00005699#endif
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005700//
5701// When this is called to get a symbol name for a branch target then the
5702// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
5703// SymbolValue will be looked for in the indirect symbol table to determine if
5704// it is an address for a symbol stub. If so then the symbol name for that
5705// stub is returned indirectly through ReferenceName and then ReferenceType is
5706// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
5707//
Kevin Enderbybf246f52014-09-24 23:08:22 +00005708// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005709// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
5710// SymbolValue is checked to be an address of literal pointer, symbol pointer,
5711// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005712// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00005713static const char *SymbolizerSymbolLookUp(void *DisInfo,
5714 uint64_t ReferenceValue,
5715 uint64_t *ReferenceType,
5716 uint64_t ReferencePC,
5717 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005718 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00005719 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00005720 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00005721 *ReferenceName = nullptr;
5722 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005723 return nullptr;
5724 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005725
Kevin Enderbyf6d25852015-01-31 00:37:11 +00005726 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00005727
Kevin Enderby85974882014-09-26 22:20:44 +00005728 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
5729 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00005730 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005731 method_reference(info, ReferenceType, ReferenceName);
5732 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
5733 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
5734 } else
Kevin Enderby04bf6932014-10-28 23:39:46 +00005735#if HAVE_CXXABI_H
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005736 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00005737 if (info->demangled_name != nullptr)
5738 free(info->demangled_name);
5739 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005740 info->demangled_name =
5741 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00005742 if (info->demangled_name != nullptr) {
5743 *ReferenceName = info->demangled_name;
5744 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5745 } else
5746 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5747 } else
5748#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005749 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5750 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
5751 *ReferenceName =
5752 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00005753 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005754 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00005755 else
5756 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00005757 // If this is arm64 and the reference is an adrp instruction save the
5758 // instruction, passed in ReferenceValue and the address of the instruction
5759 // for use later if we see and add immediate instruction.
5760 } else if (info->O->getArch() == Triple::aarch64 &&
5761 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
5762 info->adrp_inst = ReferenceValue;
5763 info->adrp_addr = ReferencePC;
5764 SymbolName = nullptr;
5765 *ReferenceName = nullptr;
5766 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5767 // If this is arm64 and reference is an add immediate instruction and we
5768 // have
5769 // seen an adrp instruction just before it and the adrp's Xd register
5770 // matches
5771 // this add's Xn register reconstruct the value being referenced and look to
5772 // see if it is a literal pointer. Note the add immediate instruction is
5773 // passed in ReferenceValue.
5774 } else if (info->O->getArch() == Triple::aarch64 &&
5775 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
5776 ReferencePC - 4 == info->adrp_addr &&
5777 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5778 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5779 uint32_t addxri_inst;
5780 uint64_t adrp_imm, addxri_imm;
5781
5782 adrp_imm =
5783 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5784 if (info->adrp_inst & 0x0200000)
5785 adrp_imm |= 0xfffffffffc000000LL;
5786
5787 addxri_inst = ReferenceValue;
5788 addxri_imm = (addxri_inst >> 10) & 0xfff;
5789 if (((addxri_inst >> 22) & 0x3) == 1)
5790 addxri_imm <<= 12;
5791
5792 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5793 (adrp_imm << 12) + addxri_imm;
5794
5795 *ReferenceName =
5796 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5797 if (*ReferenceName == nullptr)
5798 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5799 // If this is arm64 and the reference is a load register instruction and we
5800 // have seen an adrp instruction just before it and the adrp's Xd register
5801 // matches this add's Xn register reconstruct the value being referenced and
5802 // look to see if it is a literal pointer. Note the load register
5803 // instruction is passed in ReferenceValue.
5804 } else if (info->O->getArch() == Triple::aarch64 &&
5805 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
5806 ReferencePC - 4 == info->adrp_addr &&
5807 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5808 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5809 uint32_t ldrxui_inst;
5810 uint64_t adrp_imm, ldrxui_imm;
5811
5812 adrp_imm =
5813 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5814 if (info->adrp_inst & 0x0200000)
5815 adrp_imm |= 0xfffffffffc000000LL;
5816
5817 ldrxui_inst = ReferenceValue;
5818 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
5819
5820 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5821 (adrp_imm << 12) + (ldrxui_imm << 3);
5822
5823 *ReferenceName =
5824 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5825 if (*ReferenceName == nullptr)
5826 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5827 }
5828 // If this arm64 and is an load register (PC-relative) instruction the
5829 // ReferenceValue is the PC plus the immediate value.
5830 else if (info->O->getArch() == Triple::aarch64 &&
5831 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
5832 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
5833 *ReferenceName =
5834 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5835 if (*ReferenceName == nullptr)
5836 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby85974882014-09-26 22:20:44 +00005837 }
Kevin Enderby04bf6932014-10-28 23:39:46 +00005838#if HAVE_CXXABI_H
5839 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
5840 if (info->demangled_name != nullptr)
5841 free(info->demangled_name);
5842 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005843 info->demangled_name =
5844 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00005845 if (info->demangled_name != nullptr) {
5846 *ReferenceName = info->demangled_name;
5847 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5848 }
5849 }
5850#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005851 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00005852 *ReferenceName = nullptr;
5853 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5854 }
5855
5856 return SymbolName;
5857}
5858
Kevin Enderbybf246f52014-09-24 23:08:22 +00005859/// \brief Emits the comments that are stored in the CommentStream.
5860/// Each comment in the CommentStream must end with a newline.
5861static void emitComments(raw_svector_ostream &CommentStream,
5862 SmallString<128> &CommentsToEmit,
5863 formatted_raw_ostream &FormattedOS,
5864 const MCAsmInfo &MAI) {
5865 // Flush the stream before taking its content.
Kevin Enderbybf246f52014-09-24 23:08:22 +00005866 StringRef Comments = CommentsToEmit.str();
5867 // Get the default information for printing a comment.
5868 const char *CommentBegin = MAI.getCommentString();
5869 unsigned CommentColumn = MAI.getCommentColumn();
5870 bool IsFirst = true;
5871 while (!Comments.empty()) {
5872 if (!IsFirst)
5873 FormattedOS << '\n';
5874 // Emit a line of comments.
5875 FormattedOS.PadToColumn(CommentColumn);
5876 size_t Position = Comments.find('\n');
5877 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
5878 // Move after the newline character.
5879 Comments = Comments.substr(Position + 1);
5880 IsFirst = false;
5881 }
5882 FormattedOS.flush();
5883
5884 // Tell the comment stream that the vector changed underneath it.
5885 CommentsToEmit.clear();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005886}
5887
Kevin Enderby95df54c2015-02-04 01:01:38 +00005888static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
5889 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005890 const char *McpuDefault = nullptr;
5891 const Target *ThumbTarget = nullptr;
5892 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005893 if (!TheTarget) {
5894 // GetTarget prints out stuff.
5895 return;
5896 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005897 if (MCPU.empty() && McpuDefault)
5898 MCPU = McpuDefault;
5899
Ahmed Charles56440fd2014-03-06 05:51:42 +00005900 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005901 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00005902 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005903 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005904
Kevin Enderbyc9595622014-08-06 23:24:41 +00005905 // Package up features to be passed to target/subtarget
5906 std::string FeaturesStr;
5907 if (MAttrs.size()) {
5908 SubtargetFeatures Features;
5909 for (unsigned i = 0; i != MAttrs.size(); ++i)
5910 Features.AddFeature(MAttrs[i]);
5911 FeaturesStr = Features.getString();
5912 }
5913
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005914 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00005915 std::unique_ptr<const MCRegisterInfo> MRI(
5916 TheTarget->createMCRegInfo(TripleName));
5917 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00005918 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00005919 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +00005920 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00005921 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005922 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005923 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005924 std::unique_ptr<MCSymbolizer> Symbolizer;
5925 struct DisassembleInfo SymbolizerInfo;
5926 std::unique_ptr<MCRelocationInfo> RelInfo(
5927 TheTarget->createMCRelocationInfo(TripleName, Ctx));
5928 if (RelInfo) {
5929 Symbolizer.reset(TheTarget->createMCSymbolizer(
5930 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00005931 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005932 DisAsm->setSymbolizer(std::move(Symbolizer));
5933 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005934 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00005935 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00005936 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00005937 // Set the display preference for hex vs. decimal immediates.
5938 IP->setPrintImmHex(PrintImmHex);
5939 // Comment stream and backing vector.
5940 SmallString<128> CommentsToEmit;
5941 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00005942 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
5943 // if it is done then arm64 comments for string literals don't get printed
5944 // and some constant get printed instead and not setting it causes intel
5945 // (32-bit and 64-bit) comments printed with different spacing before the
5946 // comment causing different diffs with the 'C' disassembler library API.
5947 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00005948
Kevin Enderbyae3c1262014-11-14 21:52:18 +00005949 if (!AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencerc1363cf2011-10-07 19:25:47 +00005950 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00005951 << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005952 return;
5953 }
5954
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005955 // Set up thumb disassembler.
5956 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
5957 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
5958 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00005959 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005960 std::unique_ptr<MCInstPrinter> ThumbIP;
5961 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00005962 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
5963 struct DisassembleInfo ThumbSymbolizerInfo;
5964 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005965 if (ThumbTarget) {
5966 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
5967 ThumbAsmInfo.reset(
5968 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
5969 ThumbSTI.reset(
5970 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
5971 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
5972 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00005973 MCContext *PtrThumbCtx = ThumbCtx.get();
5974 ThumbRelInfo.reset(
5975 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
5976 if (ThumbRelInfo) {
5977 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
5978 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00005979 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00005980 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
5981 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005982 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
5983 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00005984 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
5985 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00005986 // Set the display preference for hex vs. decimal immediates.
5987 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005988 }
5989
Kevin Enderbyae3c1262014-11-14 21:52:18 +00005990 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005991 errs() << "error: couldn't initialize disassembler for target "
5992 << ThumbTripleName << '\n';
5993 return;
5994 }
5995
Charles Davis8bdfafd2013-09-01 04:28:48 +00005996 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005997
Ahmed Bougachaaa790682013-05-24 01:07:04 +00005998 // FIXME: Using the -cfg command line option, this code used to be able to
5999 // annotate relocations with the referenced symbol's name, and if this was
6000 // inside a __[cf]string section, the data it points to. This is now replaced
6001 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00006002 std::vector<SectionRef> Sections;
6003 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006004 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00006005 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006006
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00006007 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
Kevin Enderby273ae012013-06-06 17:20:50 +00006008 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006009
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006010 // Sort the symbols by address, just in case they didn't come in that way.
Owen Andersond9243c42011-10-17 21:37:35 +00006011 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006012
Kevin Enderby273ae012013-06-06 17:20:50 +00006013 // Build a data in code table that is sorted on by the address of each entry.
6014 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00006015 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00006016 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00006017 else
6018 BaseAddress = BaseSegmentAddress;
6019 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00006020 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00006021 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006022 uint32_t Offset;
6023 DI->getOffset(Offset);
6024 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6025 }
6026 array_pod_sort(Dices.begin(), Dices.end());
6027
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006028#ifndef NDEBUG
6029 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6030#else
6031 raw_ostream &DebugOut = nulls();
6032#endif
6033
Ahmed Charles56440fd2014-03-06 05:51:42 +00006034 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00006035 ObjectFile *DbgObj = MachOOF;
Benjamin Kramer699128e2011-09-21 01:13:19 +00006036 // Try to find debug info and set up the DIContext for it.
6037 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00006038 // A separate DSym file path was specified, parse it as a macho file,
6039 // get the sections and supply it to the section name parsing machinery.
6040 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00006041 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006042 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00006043 if (std::error_code EC = BufOrErr.getError()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006044 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +00006045 return;
6046 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00006047 DbgObj =
6048 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
6049 .get()
6050 .release();
Benjamin Kramer699128e2011-09-21 01:13:19 +00006051 }
6052
Eric Christopher7370b552012-11-12 21:40:38 +00006053 // Setup the DIContext
Zachary Turner6489d7b2015-04-23 17:37:47 +00006054 diContext.reset(new DWARFContextInMemory(*DbgObj));
Benjamin Kramer699128e2011-09-21 01:13:19 +00006055 }
6056
Colin LeMahieufcc32762015-07-29 19:08:10 +00006057 if (FilterSections.size() == 0)
Kevin Enderby95df54c2015-02-04 01:01:38 +00006058 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006059
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006060 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00006061 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00006062 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6063 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006064
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006065 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006066
Rafael Espindolab0f76a42013-04-05 15:15:22 +00006067 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00006068 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006069 continue;
6070
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006071 StringRef BytesStr;
6072 Sections[SectIdx].getContents(BytesStr);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00006073 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6074 BytesStr.size());
Rafael Espindola80291272014-10-08 15:28:58 +00006075 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00006076
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006077 bool symbolTableWorked = false;
6078
Kevin Enderbybf246f52014-09-24 23:08:22 +00006079 // Create a map of symbol addresses to symbol names for use by
6080 // the SymbolizerSymbolLookUp() routine.
6081 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00006082 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006083 for (const SymbolRef &Symbol : MachOOF->symbols()) {
Rafael Espindola2fa80cc2015-06-26 12:18:49 +00006084 SymbolRef::Type ST = Symbol.getType();
Kevin Enderbybf246f52014-09-24 23:08:22 +00006085 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
6086 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00006087 uint64_t Address = Symbol.getValue();
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006088 ErrorOr<StringRef> SymNameOrErr = Symbol.getName();
6089 if (std::error_code EC = SymNameOrErr.getError())
6090 report_fatal_error(EC.message());
6091 StringRef SymName = *SymNameOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006092 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00006093 if (!DisSymName.empty() && DisSymName == SymName)
6094 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006095 }
6096 }
David Blaikie33dd45d02015-03-23 18:39:02 +00006097 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00006098 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
6099 return;
6100 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006101 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006102 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006103 SymbolizerInfo.O = MachOOF;
6104 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00006105 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006106 SymbolizerInfo.Sections = &Sections;
6107 SymbolizerInfo.class_name = nullptr;
6108 SymbolizerInfo.selector_name = nullptr;
6109 SymbolizerInfo.method = nullptr;
Kevin Enderby04bf6932014-10-28 23:39:46 +00006110 SymbolizerInfo.demangled_name = nullptr;
Kevin Enderby078be602014-10-23 19:53:12 +00006111 SymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006112 SymbolizerInfo.adrp_addr = 0;
6113 SymbolizerInfo.adrp_inst = 0;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006114 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006115 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006116 ThumbSymbolizerInfo.O = MachOOF;
6117 ThumbSymbolizerInfo.S = Sections[SectIdx];
6118 ThumbSymbolizerInfo.AddrMap = &AddrMap;
6119 ThumbSymbolizerInfo.Sections = &Sections;
6120 ThumbSymbolizerInfo.class_name = nullptr;
6121 ThumbSymbolizerInfo.selector_name = nullptr;
6122 ThumbSymbolizerInfo.method = nullptr;
6123 ThumbSymbolizerInfo.demangled_name = nullptr;
6124 ThumbSymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006125 ThumbSymbolizerInfo.adrp_addr = 0;
6126 ThumbSymbolizerInfo.adrp_inst = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006127
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006128 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006129 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006130 ErrorOr<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
6131 if (std::error_code EC = SymNameOrErr.getError())
6132 report_fatal_error(EC.message());
6133 StringRef SymName = *SymNameOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00006134
Rafael Espindola2fa80cc2015-06-26 12:18:49 +00006135 SymbolRef::Type ST = Symbols[SymIdx].getType();
Kuba Breckade833222015-11-12 09:40:29 +00006136 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
Owen Andersond9243c42011-10-17 21:37:35 +00006137 continue;
6138
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006139 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00006140 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Owen Andersond9243c42011-10-17 21:37:35 +00006141 if (!containsSym)
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006142 continue;
6143
Kevin Enderby6a221752015-03-17 17:10:57 +00006144 // If we are only disassembling one symbol see if this is that symbol.
6145 if (!DisSymName.empty() && DisSymName != SymName)
6146 continue;
6147
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006148 // Start at the address of the symbol relative to the section's address.
Rafael Espindoladea00162015-07-03 17:44:18 +00006149 uint64_t Start = Symbols[SymIdx].getValue();
Rafael Espindola80291272014-10-08 15:28:58 +00006150 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006151 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006152
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006153 // Stop disassembling either at the beginning of the next symbol or at
6154 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00006155 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00006156 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006157 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00006158 while (Symbols.size() > NextSymIdx) {
Rafael Espindola2fa80cc2015-06-26 12:18:49 +00006159 SymbolRef::Type NextSymType = Symbols[NextSymIdx].getType();
Owen Andersond9243c42011-10-17 21:37:35 +00006160 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00006161 containsNextSym =
6162 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Rafael Espindoladea00162015-07-03 17:44:18 +00006163 NextSym = Symbols[NextSymIdx].getValue();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006164 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006165 break;
6166 }
6167 ++NextSymIdx;
6168 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006169
Rafael Espindola80291272014-10-08 15:28:58 +00006170 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006171 uint64_t End = containsNextSym ? NextSym : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00006172 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006173
6174 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00006175
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006176 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
6177 bool isThumb =
6178 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
6179
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006180 outs() << SymName << ":\n";
6181 DILineInfo lastLine;
6182 for (uint64_t Index = Start; Index < End; Index += Size) {
6183 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00006184
Kevin Enderbybf246f52014-09-24 23:08:22 +00006185 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006186 if (!NoLeadingAddr) {
6187 if (FullLeadingAddr) {
6188 if (MachOOF->is64Bit())
6189 outs() << format("%016" PRIx64, PC);
6190 else
6191 outs() << format("%08" PRIx64, PC);
6192 } else {
6193 outs() << format("%8" PRIx64 ":", PC);
6194 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006195 }
6196 if (!NoShowRawInsn)
6197 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00006198
6199 // Check the data in code table here to see if this is data not an
6200 // instruction to be disassembled.
6201 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006202 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006203 dice_table_iterator DTI =
6204 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
6205 compareDiceTableEntries);
6206 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006207 uint16_t Length;
6208 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00006209 uint16_t Kind;
6210 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00006211 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00006212 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
6213 (PC == (DTI->first + Length - 1)) && (Length & 1))
6214 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00006215 continue;
6216 }
6217
Kevin Enderbybf246f52014-09-24 23:08:22 +00006218 SmallVector<char, 64> AnnotationsBytes;
6219 raw_svector_ostream Annotations(AnnotationsBytes);
6220
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006221 bool gotInst;
6222 if (isThumb)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006223 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006224 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006225 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006226 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00006227 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006228 if (gotInst) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006229 if (!NoShowRawInsn) {
Craig Topper0013be12015-09-21 05:32:41 +00006230 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006231 }
6232 formatted_raw_ostream FormattedOS(outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006233 StringRef AnnotationsStr = Annotations.str();
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006234 if (isThumb)
Akira Hatanakab46d0232015-03-27 20:36:02 +00006235 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006236 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00006237 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006238 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00006239
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006240 // Print debug info.
6241 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006242 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006243 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00006244 if (dli != lastLine && dli.Line != 0)
6245 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
6246 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006247 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006248 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006249 outs() << "\n";
6250 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006251 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006252 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006253 outs() << format("\t.byte 0x%02x #bad opcode\n",
6254 *(Bytes.data() + Index) & 0xff);
6255 Size = 1; // skip exactly one illegible byte and move on.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006256 } else if (Arch == Triple::aarch64) {
6257 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6258 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
6259 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
6260 (*(Bytes.data() + Index + 3) & 0xff) << 24;
6261 outs() << format("\t.long\t0x%08x\n", opcode);
6262 Size = 4;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006263 } else {
6264 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6265 if (Size == 0)
6266 Size = 1; // skip illegible bytes
6267 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006268 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006269 }
6270 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006271 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00006272 // Reading the symbol table didn't work, disassemble the whole section.
6273 uint64_t SectAddress = Sections[SectIdx].getAddress();
6274 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00006275 uint64_t InstSize;
6276 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00006277 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00006278
Kevin Enderbybf246f52014-09-24 23:08:22 +00006279 uint64_t PC = SectAddress + Index;
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006280 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
6281 DebugOut, nulls())) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006282 if (!NoLeadingAddr) {
6283 if (FullLeadingAddr) {
6284 if (MachOOF->is64Bit())
6285 outs() << format("%016" PRIx64, PC);
6286 else
6287 outs() << format("%08" PRIx64, PC);
6288 } else {
6289 outs() << format("%8" PRIx64 ":", PC);
6290 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006291 }
6292 if (!NoShowRawInsn) {
6293 outs() << "\t";
Craig Topper0013be12015-09-21 05:32:41 +00006294 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006295 }
Akira Hatanaka1d079942015-03-28 20:44:05 +00006296 IP->printInst(&Inst, outs(), "", *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00006297 outs() << "\n";
6298 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006299 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006300 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006301 outs() << format("\t.byte 0x%02x #bad opcode\n",
6302 *(Bytes.data() + Index) & 0xff);
6303 InstSize = 1; // skip exactly one illegible byte and move on.
6304 } else {
6305 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6306 if (InstSize == 0)
6307 InstSize = 1; // skip illegible bytes
6308 }
Bill Wendling4e68e062012-07-19 00:17:40 +00006309 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00006310 }
6311 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006312 // The TripleName's need to be reset if we are called again for a different
6313 // archtecture.
6314 TripleName = "";
6315 ThumbTripleName = "";
6316
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006317 if (SymbolizerInfo.method != nullptr)
6318 free(SymbolizerInfo.method);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006319 if (SymbolizerInfo.demangled_name != nullptr)
6320 free(SymbolizerInfo.demangled_name);
Kevin Enderby078be602014-10-23 19:53:12 +00006321 if (SymbolizerInfo.bindtable != nullptr)
6322 delete SymbolizerInfo.bindtable;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006323 if (ThumbSymbolizerInfo.method != nullptr)
6324 free(ThumbSymbolizerInfo.method);
6325 if (ThumbSymbolizerInfo.demangled_name != nullptr)
6326 free(ThumbSymbolizerInfo.demangled_name);
6327 if (ThumbSymbolizerInfo.bindtable != nullptr)
6328 delete ThumbSymbolizerInfo.bindtable;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006329 }
6330}
Tim Northover4bd286a2014-08-01 13:07:19 +00006331
Tim Northover39c70bb2014-08-12 11:52:59 +00006332//===----------------------------------------------------------------------===//
6333// __compact_unwind section dumping
6334//===----------------------------------------------------------------------===//
6335
Tim Northover4bd286a2014-08-01 13:07:19 +00006336namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00006337
6338template <typename T> static uint64_t readNext(const char *&Buf) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006339 using llvm::support::little;
6340 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00006341
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006342 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
6343 Buf += sizeof(T);
6344 return Val;
6345}
Tim Northover39c70bb2014-08-12 11:52:59 +00006346
Tim Northover4bd286a2014-08-01 13:07:19 +00006347struct CompactUnwindEntry {
6348 uint32_t OffsetInSection;
6349
6350 uint64_t FunctionAddr;
6351 uint32_t Length;
6352 uint32_t CompactEncoding;
6353 uint64_t PersonalityAddr;
6354 uint64_t LSDAAddr;
6355
6356 RelocationRef FunctionReloc;
6357 RelocationRef PersonalityReloc;
6358 RelocationRef LSDAReloc;
6359
6360 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006361 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006362 if (Is64)
6363 read<uint64_t>(Contents.data() + Offset);
6364 else
6365 read<uint32_t>(Contents.data() + Offset);
6366 }
6367
6368private:
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006369 template <typename UIntPtr> void read(const char *Buf) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006370 FunctionAddr = readNext<UIntPtr>(Buf);
6371 Length = readNext<uint32_t>(Buf);
6372 CompactEncoding = readNext<uint32_t>(Buf);
6373 PersonalityAddr = readNext<UIntPtr>(Buf);
6374 LSDAAddr = readNext<UIntPtr>(Buf);
6375 }
6376};
6377}
6378
6379/// Given a relocation from __compact_unwind, consisting of the RelocationRef
6380/// and data being relocated, determine the best base Name and Addend to use for
6381/// display purposes.
6382///
6383/// 1. An Extern relocation will directly reference a symbol (and the data is
6384/// then already an addend), so use that.
6385/// 2. Otherwise the data is an offset in the object file's layout; try to find
6386// a symbol before it in the same section, and use the offset from there.
6387/// 3. Finally, if all that fails, fall back to an offset from the start of the
6388/// referenced section.
6389static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
6390 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006391 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00006392 StringRef &Name, uint64_t &Addend) {
6393 if (Reloc.getSymbol() != Obj->symbol_end()) {
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006394 ErrorOr<StringRef> NameOrErr = Reloc.getSymbol()->getName();
6395 if (std::error_code EC = NameOrErr.getError())
6396 report_fatal_error(EC.message());
6397 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00006398 Addend = Addr;
6399 return;
6400 }
6401
6402 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
Keno Fischerc780e8e2015-05-21 21:24:32 +00006403 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
Tim Northover4bd286a2014-08-01 13:07:19 +00006404
Rafael Espindola80291272014-10-08 15:28:58 +00006405 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00006406
6407 auto Sym = Symbols.upper_bound(Addr);
6408 if (Sym == Symbols.begin()) {
6409 // The first symbol in the object is after this reference, the best we can
6410 // do is section-relative notation.
6411 RelocSection.getName(Name);
6412 Addend = Addr - SectionAddr;
6413 return;
6414 }
6415
6416 // Go back one so that SymbolAddress <= Addr.
6417 --Sym;
6418
Rafael Espindola8bab8892015-08-07 23:27:14 +00006419 section_iterator SymSection = *Sym->second.getSection();
Tim Northover4bd286a2014-08-01 13:07:19 +00006420 if (RelocSection == *SymSection) {
6421 // There's a valid symbol in the same section before this reference.
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006422 ErrorOr<StringRef> NameOrErr = Sym->second.getName();
6423 if (std::error_code EC = NameOrErr.getError())
6424 report_fatal_error(EC.message());
6425 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00006426 Addend = Addr - Sym->first;
6427 return;
6428 }
6429
6430 // There is a symbol before this reference, but it's in a different
6431 // section. Probably not helpful to mention it, so use the section name.
6432 RelocSection.getName(Name);
6433 Addend = Addr - SectionAddr;
6434}
6435
6436static void printUnwindRelocDest(const MachOObjectFile *Obj,
6437 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006438 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006439 StringRef Name;
6440 uint64_t Addend;
6441
Rafael Espindola854038e2015-06-26 14:51:16 +00006442 if (!Reloc.getObject())
Tim Northover0b0add52014-09-09 10:45:06 +00006443 return;
6444
Tim Northover4bd286a2014-08-01 13:07:19 +00006445 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
6446
6447 outs() << Name;
6448 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00006449 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00006450}
6451
6452static void
6453printMachOCompactUnwindSection(const MachOObjectFile *Obj,
6454 std::map<uint64_t, SymbolRef> &Symbols,
6455 const SectionRef &CompactUnwind) {
6456
6457 assert(Obj->isLittleEndian() &&
6458 "There should not be a big-endian .o with __compact_unwind");
6459
6460 bool Is64 = Obj->is64Bit();
6461 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
6462 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
6463
6464 StringRef Contents;
6465 CompactUnwind.getContents(Contents);
6466
6467 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
6468
6469 // First populate the initial raw offsets, encodings and so on from the entry.
6470 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
6471 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
6472 CompactUnwinds.push_back(Entry);
6473 }
6474
6475 // Next we need to look at the relocations to find out what objects are
6476 // actually being referred to.
6477 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00006478 uint64_t RelocAddress = Reloc.getOffset();
Tim Northover4bd286a2014-08-01 13:07:19 +00006479
6480 uint32_t EntryIdx = RelocAddress / EntrySize;
6481 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
6482 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
6483
6484 if (OffsetInEntry == 0)
6485 Entry.FunctionReloc = Reloc;
6486 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
6487 Entry.PersonalityReloc = Reloc;
6488 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
6489 Entry.LSDAReloc = Reloc;
6490 else
6491 llvm_unreachable("Unexpected relocation in __compact_unwind section");
6492 }
6493
6494 // Finally, we're ready to print the data we've gathered.
6495 outs() << "Contents of __compact_unwind section:\n";
6496 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00006497 outs() << " Entry at offset "
6498 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00006499
6500 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006501 outs() << " start: " << format("0x%" PRIx64,
6502 Entry.FunctionAddr) << ' ';
6503 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00006504 outs() << '\n';
6505
6506 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006507 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
6508 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00006509 // 3. The 32-bit compact encoding.
6510 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00006511 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00006512
6513 // 4. The personality function, if present.
Rafael Espindola854038e2015-06-26 14:51:16 +00006514 if (Entry.PersonalityReloc.getObject()) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006515 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00006516 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00006517 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
6518 Entry.PersonalityAddr);
6519 outs() << '\n';
6520 }
6521
6522 // 5. This entry's language-specific data area.
Rafael Espindola854038e2015-06-26 14:51:16 +00006523 if (Entry.LSDAReloc.getObject()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006524 outs() << " LSDA: " << format("0x%" PRIx64,
6525 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00006526 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
6527 outs() << '\n';
6528 }
6529 }
6530}
6531
Tim Northover39c70bb2014-08-12 11:52:59 +00006532//===----------------------------------------------------------------------===//
6533// __unwind_info section dumping
6534//===----------------------------------------------------------------------===//
6535
6536static void printRegularSecondLevelUnwindPage(const char *PageStart) {
6537 const char *Pos = PageStart;
6538 uint32_t Kind = readNext<uint32_t>(Pos);
6539 (void)Kind;
6540 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
6541
6542 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6543 uint16_t NumEntries = readNext<uint16_t>(Pos);
6544
6545 Pos = PageStart + EntriesStart;
6546 for (unsigned i = 0; i < NumEntries; ++i) {
6547 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6548 uint32_t Encoding = readNext<uint32_t>(Pos);
6549
6550 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006551 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6552 << ", "
6553 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006554 }
6555}
6556
6557static void printCompressedSecondLevelUnwindPage(
6558 const char *PageStart, uint32_t FunctionBase,
6559 const SmallVectorImpl<uint32_t> &CommonEncodings) {
6560 const char *Pos = PageStart;
6561 uint32_t Kind = readNext<uint32_t>(Pos);
6562 (void)Kind;
6563 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
6564
6565 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6566 uint16_t NumEntries = readNext<uint16_t>(Pos);
6567
6568 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
6569 readNext<uint16_t>(Pos);
Aaron Ballman80930af2014-08-14 13:53:19 +00006570 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
6571 PageStart + EncodingsStart);
Tim Northover39c70bb2014-08-12 11:52:59 +00006572
6573 Pos = PageStart + EntriesStart;
6574 for (unsigned i = 0; i < NumEntries; ++i) {
6575 uint32_t Entry = readNext<uint32_t>(Pos);
6576 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
6577 uint32_t EncodingIdx = Entry >> 24;
6578
6579 uint32_t Encoding;
6580 if (EncodingIdx < CommonEncodings.size())
6581 Encoding = CommonEncodings[EncodingIdx];
6582 else
6583 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
6584
6585 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006586 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6587 << ", "
6588 << "encoding[" << EncodingIdx
6589 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006590 }
6591}
6592
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006593static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
6594 std::map<uint64_t, SymbolRef> &Symbols,
6595 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00006596
6597 assert(Obj->isLittleEndian() &&
6598 "There should not be a big-endian .o with __unwind_info");
6599
6600 outs() << "Contents of __unwind_info section:\n";
6601
6602 StringRef Contents;
6603 UnwindInfo.getContents(Contents);
6604 const char *Pos = Contents.data();
6605
6606 //===----------------------------------
6607 // Section header
6608 //===----------------------------------
6609
6610 uint32_t Version = readNext<uint32_t>(Pos);
6611 outs() << " Version: "
6612 << format("0x%" PRIx32, Version) << '\n';
6613 assert(Version == 1 && "only understand version 1");
6614
6615 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
6616 outs() << " Common encodings array section offset: "
6617 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
6618 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
6619 outs() << " Number of common encodings in array: "
6620 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
6621
6622 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
6623 outs() << " Personality function array section offset: "
6624 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
6625 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
6626 outs() << " Number of personality functions in array: "
6627 << format("0x%" PRIx32, NumPersonalities) << '\n';
6628
6629 uint32_t IndicesStart = readNext<uint32_t>(Pos);
6630 outs() << " Index array section offset: "
6631 << format("0x%" PRIx32, IndicesStart) << '\n';
6632 uint32_t NumIndices = readNext<uint32_t>(Pos);
6633 outs() << " Number of indices in array: "
6634 << format("0x%" PRIx32, NumIndices) << '\n';
6635
6636 //===----------------------------------
6637 // A shared list of common encodings
6638 //===----------------------------------
6639
6640 // These occupy indices in the range [0, N] whenever an encoding is referenced
6641 // from a compressed 2nd level index table. In practice the linker only
6642 // creates ~128 of these, so that indices are available to embed encodings in
6643 // the 2nd level index.
6644
6645 SmallVector<uint32_t, 64> CommonEncodings;
6646 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
6647 Pos = Contents.data() + CommonEncodingsStart;
6648 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
6649 uint32_t Encoding = readNext<uint32_t>(Pos);
6650 CommonEncodings.push_back(Encoding);
6651
6652 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
6653 << '\n';
6654 }
6655
Tim Northover39c70bb2014-08-12 11:52:59 +00006656 //===----------------------------------
6657 // Personality functions used in this executable
6658 //===----------------------------------
6659
6660 // There should be only a handful of these (one per source language,
6661 // roughly). Particularly since they only get 2 bits in the compact encoding.
6662
6663 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
6664 Pos = Contents.data() + PersonalitiesStart;
6665 for (unsigned i = 0; i < NumPersonalities; ++i) {
6666 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
6667 outs() << " personality[" << i + 1
6668 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
6669 }
6670
6671 //===----------------------------------
6672 // The level 1 index entries
6673 //===----------------------------------
6674
6675 // These specify an approximate place to start searching for the more detailed
6676 // information, sorted by PC.
6677
6678 struct IndexEntry {
6679 uint32_t FunctionOffset;
6680 uint32_t SecondLevelPageStart;
6681 uint32_t LSDAStart;
6682 };
6683
6684 SmallVector<IndexEntry, 4> IndexEntries;
6685
6686 outs() << " Top level indices: (count = " << NumIndices << ")\n";
6687 Pos = Contents.data() + IndicesStart;
6688 for (unsigned i = 0; i < NumIndices; ++i) {
6689 IndexEntry Entry;
6690
6691 Entry.FunctionOffset = readNext<uint32_t>(Pos);
6692 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
6693 Entry.LSDAStart = readNext<uint32_t>(Pos);
6694 IndexEntries.push_back(Entry);
6695
6696 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006697 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
6698 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00006699 << "2nd level page offset="
6700 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006701 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006702 }
6703
Tim Northover39c70bb2014-08-12 11:52:59 +00006704 //===----------------------------------
6705 // Next come the LSDA tables
6706 //===----------------------------------
6707
6708 // The LSDA layout is rather implicit: it's a contiguous array of entries from
6709 // the first top-level index's LSDAOffset to the last (sentinel).
6710
6711 outs() << " LSDA descriptors:\n";
6712 Pos = Contents.data() + IndexEntries[0].LSDAStart;
6713 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
6714 (2 * sizeof(uint32_t));
6715 for (int i = 0; i < NumLSDAs; ++i) {
6716 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6717 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
6718 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006719 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6720 << ", "
6721 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006722 }
6723
6724 //===----------------------------------
6725 // Finally, the 2nd level indices
6726 //===----------------------------------
6727
6728 // Generally these are 4K in size, and have 2 possible forms:
6729 // + Regular stores up to 511 entries with disparate encodings
6730 // + Compressed stores up to 1021 entries if few enough compact encoding
6731 // values are used.
6732 outs() << " Second level indices:\n";
6733 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
6734 // The final sentinel top-level index has no associated 2nd level page
6735 if (IndexEntries[i].SecondLevelPageStart == 0)
6736 break;
6737
6738 outs() << " Second level index[" << i << "]: "
6739 << "offset in section="
6740 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
6741 << ", "
6742 << "base function offset="
6743 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
6744
6745 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
Aaron Ballman80930af2014-08-14 13:53:19 +00006746 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00006747 if (Kind == 2)
6748 printRegularSecondLevelUnwindPage(Pos);
6749 else if (Kind == 3)
6750 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
6751 CommonEncodings);
6752 else
6753 llvm_unreachable("Do not know how to print this kind of 2nd level page");
Tim Northover39c70bb2014-08-12 11:52:59 +00006754 }
6755}
6756
Tim Northover4bd286a2014-08-01 13:07:19 +00006757void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
6758 std::map<uint64_t, SymbolRef> Symbols;
6759 for (const SymbolRef &SymRef : Obj->symbols()) {
6760 // Discard any undefined or absolute symbols. They're not going to take part
6761 // in the convenience lookup for unwind info and just take up resources.
Rafael Espindola8bab8892015-08-07 23:27:14 +00006762 section_iterator Section = *SymRef.getSection();
Tim Northover4bd286a2014-08-01 13:07:19 +00006763 if (Section == Obj->section_end())
6764 continue;
6765
Rafael Espindoladea00162015-07-03 17:44:18 +00006766 uint64_t Addr = SymRef.getValue();
Tim Northover4bd286a2014-08-01 13:07:19 +00006767 Symbols.insert(std::make_pair(Addr, SymRef));
6768 }
6769
6770 for (const SectionRef &Section : Obj->sections()) {
6771 StringRef SectName;
6772 Section.getName(SectName);
6773 if (SectName == "__compact_unwind")
6774 printMachOCompactUnwindSection(Obj, Symbols, Section);
6775 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00006776 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00006777 }
6778}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00006779
6780static void PrintMachHeader(uint32_t magic, uint32_t cputype,
6781 uint32_t cpusubtype, uint32_t filetype,
6782 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
6783 bool verbose) {
6784 outs() << "Mach header\n";
6785 outs() << " magic cputype cpusubtype caps filetype ncmds "
6786 "sizeofcmds flags\n";
6787 if (verbose) {
6788 if (magic == MachO::MH_MAGIC)
6789 outs() << " MH_MAGIC";
6790 else if (magic == MachO::MH_MAGIC_64)
6791 outs() << "MH_MAGIC_64";
6792 else
6793 outs() << format(" 0x%08" PRIx32, magic);
6794 switch (cputype) {
6795 case MachO::CPU_TYPE_I386:
6796 outs() << " I386";
6797 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6798 case MachO::CPU_SUBTYPE_I386_ALL:
6799 outs() << " ALL";
6800 break;
6801 default:
6802 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6803 break;
6804 }
6805 break;
6806 case MachO::CPU_TYPE_X86_64:
6807 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00006808 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6809 case MachO::CPU_SUBTYPE_X86_64_ALL:
6810 outs() << " ALL";
6811 break;
6812 case MachO::CPU_SUBTYPE_X86_64_H:
6813 outs() << " Haswell";
6814 break;
6815 default:
6816 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6817 break;
6818 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00006819 break;
6820 case MachO::CPU_TYPE_ARM:
6821 outs() << " ARM";
6822 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6823 case MachO::CPU_SUBTYPE_ARM_ALL:
6824 outs() << " ALL";
6825 break;
6826 case MachO::CPU_SUBTYPE_ARM_V4T:
6827 outs() << " V4T";
6828 break;
6829 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
6830 outs() << " V5TEJ";
6831 break;
6832 case MachO::CPU_SUBTYPE_ARM_XSCALE:
6833 outs() << " XSCALE";
6834 break;
6835 case MachO::CPU_SUBTYPE_ARM_V6:
6836 outs() << " V6";
6837 break;
6838 case MachO::CPU_SUBTYPE_ARM_V6M:
6839 outs() << " V6M";
6840 break;
6841 case MachO::CPU_SUBTYPE_ARM_V7:
6842 outs() << " V7";
6843 break;
6844 case MachO::CPU_SUBTYPE_ARM_V7EM:
6845 outs() << " V7EM";
6846 break;
6847 case MachO::CPU_SUBTYPE_ARM_V7K:
6848 outs() << " V7K";
6849 break;
6850 case MachO::CPU_SUBTYPE_ARM_V7M:
6851 outs() << " V7M";
6852 break;
6853 case MachO::CPU_SUBTYPE_ARM_V7S:
6854 outs() << " V7S";
6855 break;
6856 default:
6857 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6858 break;
6859 }
6860 break;
6861 case MachO::CPU_TYPE_ARM64:
6862 outs() << " ARM64";
6863 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6864 case MachO::CPU_SUBTYPE_ARM64_ALL:
6865 outs() << " ALL";
6866 break;
6867 default:
6868 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6869 break;
6870 }
6871 break;
6872 case MachO::CPU_TYPE_POWERPC:
6873 outs() << " PPC";
6874 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6875 case MachO::CPU_SUBTYPE_POWERPC_ALL:
6876 outs() << " ALL";
6877 break;
6878 default:
6879 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6880 break;
6881 }
6882 break;
6883 case MachO::CPU_TYPE_POWERPC64:
6884 outs() << " PPC64";
6885 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6886 case MachO::CPU_SUBTYPE_POWERPC_ALL:
6887 outs() << " ALL";
6888 break;
6889 default:
6890 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6891 break;
6892 }
6893 break;
6894 }
6895 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00006896 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00006897 } else {
6898 outs() << format(" 0x%02" PRIx32,
6899 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
6900 }
6901 switch (filetype) {
6902 case MachO::MH_OBJECT:
6903 outs() << " OBJECT";
6904 break;
6905 case MachO::MH_EXECUTE:
6906 outs() << " EXECUTE";
6907 break;
6908 case MachO::MH_FVMLIB:
6909 outs() << " FVMLIB";
6910 break;
6911 case MachO::MH_CORE:
6912 outs() << " CORE";
6913 break;
6914 case MachO::MH_PRELOAD:
6915 outs() << " PRELOAD";
6916 break;
6917 case MachO::MH_DYLIB:
6918 outs() << " DYLIB";
6919 break;
6920 case MachO::MH_DYLIB_STUB:
6921 outs() << " DYLIB_STUB";
6922 break;
6923 case MachO::MH_DYLINKER:
6924 outs() << " DYLINKER";
6925 break;
6926 case MachO::MH_BUNDLE:
6927 outs() << " BUNDLE";
6928 break;
6929 case MachO::MH_DSYM:
6930 outs() << " DSYM";
6931 break;
6932 case MachO::MH_KEXT_BUNDLE:
6933 outs() << " KEXTBUNDLE";
6934 break;
6935 default:
6936 outs() << format(" %10u", filetype);
6937 break;
6938 }
6939 outs() << format(" %5u", ncmds);
6940 outs() << format(" %10u", sizeofcmds);
6941 uint32_t f = flags;
6942 if (f & MachO::MH_NOUNDEFS) {
6943 outs() << " NOUNDEFS";
6944 f &= ~MachO::MH_NOUNDEFS;
6945 }
6946 if (f & MachO::MH_INCRLINK) {
6947 outs() << " INCRLINK";
6948 f &= ~MachO::MH_INCRLINK;
6949 }
6950 if (f & MachO::MH_DYLDLINK) {
6951 outs() << " DYLDLINK";
6952 f &= ~MachO::MH_DYLDLINK;
6953 }
6954 if (f & MachO::MH_BINDATLOAD) {
6955 outs() << " BINDATLOAD";
6956 f &= ~MachO::MH_BINDATLOAD;
6957 }
6958 if (f & MachO::MH_PREBOUND) {
6959 outs() << " PREBOUND";
6960 f &= ~MachO::MH_PREBOUND;
6961 }
6962 if (f & MachO::MH_SPLIT_SEGS) {
6963 outs() << " SPLIT_SEGS";
6964 f &= ~MachO::MH_SPLIT_SEGS;
6965 }
6966 if (f & MachO::MH_LAZY_INIT) {
6967 outs() << " LAZY_INIT";
6968 f &= ~MachO::MH_LAZY_INIT;
6969 }
6970 if (f & MachO::MH_TWOLEVEL) {
6971 outs() << " TWOLEVEL";
6972 f &= ~MachO::MH_TWOLEVEL;
6973 }
6974 if (f & MachO::MH_FORCE_FLAT) {
6975 outs() << " FORCE_FLAT";
6976 f &= ~MachO::MH_FORCE_FLAT;
6977 }
6978 if (f & MachO::MH_NOMULTIDEFS) {
6979 outs() << " NOMULTIDEFS";
6980 f &= ~MachO::MH_NOMULTIDEFS;
6981 }
6982 if (f & MachO::MH_NOFIXPREBINDING) {
6983 outs() << " NOFIXPREBINDING";
6984 f &= ~MachO::MH_NOFIXPREBINDING;
6985 }
6986 if (f & MachO::MH_PREBINDABLE) {
6987 outs() << " PREBINDABLE";
6988 f &= ~MachO::MH_PREBINDABLE;
6989 }
6990 if (f & MachO::MH_ALLMODSBOUND) {
6991 outs() << " ALLMODSBOUND";
6992 f &= ~MachO::MH_ALLMODSBOUND;
6993 }
6994 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
6995 outs() << " SUBSECTIONS_VIA_SYMBOLS";
6996 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
6997 }
6998 if (f & MachO::MH_CANONICAL) {
6999 outs() << " CANONICAL";
7000 f &= ~MachO::MH_CANONICAL;
7001 }
7002 if (f & MachO::MH_WEAK_DEFINES) {
7003 outs() << " WEAK_DEFINES";
7004 f &= ~MachO::MH_WEAK_DEFINES;
7005 }
7006 if (f & MachO::MH_BINDS_TO_WEAK) {
7007 outs() << " BINDS_TO_WEAK";
7008 f &= ~MachO::MH_BINDS_TO_WEAK;
7009 }
7010 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
7011 outs() << " ALLOW_STACK_EXECUTION";
7012 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
7013 }
7014 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
7015 outs() << " DEAD_STRIPPABLE_DYLIB";
7016 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
7017 }
7018 if (f & MachO::MH_PIE) {
7019 outs() << " PIE";
7020 f &= ~MachO::MH_PIE;
7021 }
7022 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
7023 outs() << " NO_REEXPORTED_DYLIBS";
7024 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
7025 }
7026 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
7027 outs() << " MH_HAS_TLV_DESCRIPTORS";
7028 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
7029 }
7030 if (f & MachO::MH_NO_HEAP_EXECUTION) {
7031 outs() << " MH_NO_HEAP_EXECUTION";
7032 f &= ~MachO::MH_NO_HEAP_EXECUTION;
7033 }
7034 if (f & MachO::MH_APP_EXTENSION_SAFE) {
7035 outs() << " APP_EXTENSION_SAFE";
7036 f &= ~MachO::MH_APP_EXTENSION_SAFE;
7037 }
7038 if (f != 0 || flags == 0)
7039 outs() << format(" 0x%08" PRIx32, f);
7040 } else {
7041 outs() << format(" 0x%08" PRIx32, magic);
7042 outs() << format(" %7d", cputype);
7043 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7044 outs() << format(" 0x%02" PRIx32,
7045 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7046 outs() << format(" %10u", filetype);
7047 outs() << format(" %5u", ncmds);
7048 outs() << format(" %10u", sizeofcmds);
7049 outs() << format(" 0x%08" PRIx32, flags);
7050 }
7051 outs() << "\n";
7052}
7053
Kevin Enderby956366c2014-08-29 22:30:52 +00007054static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
7055 StringRef SegName, uint64_t vmaddr,
7056 uint64_t vmsize, uint64_t fileoff,
7057 uint64_t filesize, uint32_t maxprot,
7058 uint32_t initprot, uint32_t nsects,
7059 uint32_t flags, uint32_t object_size,
7060 bool verbose) {
7061 uint64_t expected_cmdsize;
7062 if (cmd == MachO::LC_SEGMENT) {
7063 outs() << " cmd LC_SEGMENT\n";
7064 expected_cmdsize = nsects;
7065 expected_cmdsize *= sizeof(struct MachO::section);
7066 expected_cmdsize += sizeof(struct MachO::segment_command);
7067 } else {
7068 outs() << " cmd LC_SEGMENT_64\n";
7069 expected_cmdsize = nsects;
7070 expected_cmdsize *= sizeof(struct MachO::section_64);
7071 expected_cmdsize += sizeof(struct MachO::segment_command_64);
7072 }
7073 outs() << " cmdsize " << cmdsize;
7074 if (cmdsize != expected_cmdsize)
7075 outs() << " Inconsistent size\n";
7076 else
7077 outs() << "\n";
7078 outs() << " segname " << SegName << "\n";
7079 if (cmd == MachO::LC_SEGMENT_64) {
7080 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
7081 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
7082 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00007083 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
7084 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00007085 }
7086 outs() << " fileoff " << fileoff;
7087 if (fileoff > object_size)
7088 outs() << " (past end of file)\n";
7089 else
7090 outs() << "\n";
7091 outs() << " filesize " << filesize;
7092 if (fileoff + filesize > object_size)
7093 outs() << " (past end of file)\n";
7094 else
7095 outs() << "\n";
7096 if (verbose) {
7097 if ((maxprot &
7098 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7099 MachO::VM_PROT_EXECUTE)) != 0)
7100 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
7101 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00007102 outs() << " maxprot ";
7103 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
7104 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7105 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007106 }
7107 if ((initprot &
7108 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7109 MachO::VM_PROT_EXECUTE)) != 0)
7110 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
7111 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00007112 outs() << " initprot ";
7113 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
7114 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7115 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007116 }
7117 } else {
7118 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
7119 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
7120 }
7121 outs() << " nsects " << nsects << "\n";
7122 if (verbose) {
7123 outs() << " flags";
7124 if (flags == 0)
7125 outs() << " (none)\n";
7126 else {
7127 if (flags & MachO::SG_HIGHVM) {
7128 outs() << " HIGHVM";
7129 flags &= ~MachO::SG_HIGHVM;
7130 }
7131 if (flags & MachO::SG_FVMLIB) {
7132 outs() << " FVMLIB";
7133 flags &= ~MachO::SG_FVMLIB;
7134 }
7135 if (flags & MachO::SG_NORELOC) {
7136 outs() << " NORELOC";
7137 flags &= ~MachO::SG_NORELOC;
7138 }
7139 if (flags & MachO::SG_PROTECTED_VERSION_1) {
7140 outs() << " PROTECTED_VERSION_1";
7141 flags &= ~MachO::SG_PROTECTED_VERSION_1;
7142 }
7143 if (flags)
7144 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
7145 else
7146 outs() << "\n";
7147 }
7148 } else {
7149 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
7150 }
7151}
7152
7153static void PrintSection(const char *sectname, const char *segname,
7154 uint64_t addr, uint64_t size, uint32_t offset,
7155 uint32_t align, uint32_t reloff, uint32_t nreloc,
7156 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
7157 uint32_t cmd, const char *sg_segname,
7158 uint32_t filetype, uint32_t object_size,
7159 bool verbose) {
7160 outs() << "Section\n";
7161 outs() << " sectname " << format("%.16s\n", sectname);
7162 outs() << " segname " << format("%.16s", segname);
7163 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
7164 outs() << " (does not match segment)\n";
7165 else
7166 outs() << "\n";
7167 if (cmd == MachO::LC_SEGMENT_64) {
7168 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
7169 outs() << " size " << format("0x%016" PRIx64, size);
7170 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00007171 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
7172 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00007173 }
7174 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
7175 outs() << " (past end of file)\n";
7176 else
7177 outs() << "\n";
7178 outs() << " offset " << offset;
7179 if (offset > object_size)
7180 outs() << " (past end of file)\n";
7181 else
7182 outs() << "\n";
7183 uint32_t align_shifted = 1 << align;
7184 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
7185 outs() << " reloff " << reloff;
7186 if (reloff > object_size)
7187 outs() << " (past end of file)\n";
7188 else
7189 outs() << "\n";
7190 outs() << " nreloc " << nreloc;
7191 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
7192 outs() << " (past end of file)\n";
7193 else
7194 outs() << "\n";
7195 uint32_t section_type = flags & MachO::SECTION_TYPE;
7196 if (verbose) {
7197 outs() << " type";
7198 if (section_type == MachO::S_REGULAR)
7199 outs() << " S_REGULAR\n";
7200 else if (section_type == MachO::S_ZEROFILL)
7201 outs() << " S_ZEROFILL\n";
7202 else if (section_type == MachO::S_CSTRING_LITERALS)
7203 outs() << " S_CSTRING_LITERALS\n";
7204 else if (section_type == MachO::S_4BYTE_LITERALS)
7205 outs() << " S_4BYTE_LITERALS\n";
7206 else if (section_type == MachO::S_8BYTE_LITERALS)
7207 outs() << " S_8BYTE_LITERALS\n";
7208 else if (section_type == MachO::S_16BYTE_LITERALS)
7209 outs() << " S_16BYTE_LITERALS\n";
7210 else if (section_type == MachO::S_LITERAL_POINTERS)
7211 outs() << " S_LITERAL_POINTERS\n";
7212 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
7213 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
7214 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
7215 outs() << " S_LAZY_SYMBOL_POINTERS\n";
7216 else if (section_type == MachO::S_SYMBOL_STUBS)
7217 outs() << " S_SYMBOL_STUBS\n";
7218 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
7219 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
7220 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
7221 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
7222 else if (section_type == MachO::S_COALESCED)
7223 outs() << " S_COALESCED\n";
7224 else if (section_type == MachO::S_INTERPOSING)
7225 outs() << " S_INTERPOSING\n";
7226 else if (section_type == MachO::S_DTRACE_DOF)
7227 outs() << " S_DTRACE_DOF\n";
7228 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
7229 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
7230 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
7231 outs() << " S_THREAD_LOCAL_REGULAR\n";
7232 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
7233 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
7234 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
7235 outs() << " S_THREAD_LOCAL_VARIABLES\n";
7236 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7237 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
7238 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
7239 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
7240 else
7241 outs() << format("0x%08" PRIx32, section_type) << "\n";
7242 outs() << "attributes";
7243 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
7244 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
7245 outs() << " PURE_INSTRUCTIONS";
7246 if (section_attributes & MachO::S_ATTR_NO_TOC)
7247 outs() << " NO_TOC";
7248 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
7249 outs() << " STRIP_STATIC_SYMS";
7250 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
7251 outs() << " NO_DEAD_STRIP";
7252 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
7253 outs() << " LIVE_SUPPORT";
7254 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
7255 outs() << " SELF_MODIFYING_CODE";
7256 if (section_attributes & MachO::S_ATTR_DEBUG)
7257 outs() << " DEBUG";
7258 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
7259 outs() << " SOME_INSTRUCTIONS";
7260 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
7261 outs() << " EXT_RELOC";
7262 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
7263 outs() << " LOC_RELOC";
7264 if (section_attributes == 0)
7265 outs() << " (none)";
7266 outs() << "\n";
7267 } else
7268 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
7269 outs() << " reserved1 " << reserved1;
7270 if (section_type == MachO::S_SYMBOL_STUBS ||
7271 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
7272 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
7273 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
7274 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7275 outs() << " (index into indirect symbol table)\n";
7276 else
7277 outs() << "\n";
7278 outs() << " reserved2 " << reserved2;
7279 if (section_type == MachO::S_SYMBOL_STUBS)
7280 outs() << " (size of stubs)\n";
7281 else
7282 outs() << "\n";
7283}
7284
David Majnemer73cc6ff2014-11-13 19:48:56 +00007285static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00007286 uint32_t object_size) {
7287 outs() << " cmd LC_SYMTAB\n";
7288 outs() << " cmdsize " << st.cmdsize;
7289 if (st.cmdsize != sizeof(struct MachO::symtab_command))
7290 outs() << " Incorrect size\n";
7291 else
7292 outs() << "\n";
7293 outs() << " symoff " << st.symoff;
7294 if (st.symoff > object_size)
7295 outs() << " (past end of file)\n";
7296 else
7297 outs() << "\n";
7298 outs() << " nsyms " << st.nsyms;
7299 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00007300 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007301 big_size = st.nsyms;
7302 big_size *= sizeof(struct MachO::nlist_64);
7303 big_size += st.symoff;
7304 if (big_size > object_size)
7305 outs() << " (past end of file)\n";
7306 else
7307 outs() << "\n";
7308 } else {
7309 big_size = st.nsyms;
7310 big_size *= sizeof(struct MachO::nlist);
7311 big_size += st.symoff;
7312 if (big_size > object_size)
7313 outs() << " (past end of file)\n";
7314 else
7315 outs() << "\n";
7316 }
7317 outs() << " stroff " << st.stroff;
7318 if (st.stroff > object_size)
7319 outs() << " (past end of file)\n";
7320 else
7321 outs() << "\n";
7322 outs() << " strsize " << st.strsize;
7323 big_size = st.stroff;
7324 big_size += st.strsize;
7325 if (big_size > object_size)
7326 outs() << " (past end of file)\n";
7327 else
7328 outs() << "\n";
7329}
7330
7331static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
7332 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00007333 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007334 outs() << " cmd LC_DYSYMTAB\n";
7335 outs() << " cmdsize " << dyst.cmdsize;
7336 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
7337 outs() << " Incorrect size\n";
7338 else
7339 outs() << "\n";
7340 outs() << " ilocalsym " << dyst.ilocalsym;
7341 if (dyst.ilocalsym > nsyms)
7342 outs() << " (greater than the number of symbols)\n";
7343 else
7344 outs() << "\n";
7345 outs() << " nlocalsym " << dyst.nlocalsym;
7346 uint64_t big_size;
7347 big_size = dyst.ilocalsym;
7348 big_size += dyst.nlocalsym;
7349 if (big_size > nsyms)
7350 outs() << " (past the end of the symbol table)\n";
7351 else
7352 outs() << "\n";
7353 outs() << " iextdefsym " << dyst.iextdefsym;
7354 if (dyst.iextdefsym > nsyms)
7355 outs() << " (greater than the number of symbols)\n";
7356 else
7357 outs() << "\n";
7358 outs() << " nextdefsym " << dyst.nextdefsym;
7359 big_size = dyst.iextdefsym;
7360 big_size += dyst.nextdefsym;
7361 if (big_size > nsyms)
7362 outs() << " (past the end of the symbol table)\n";
7363 else
7364 outs() << "\n";
7365 outs() << " iundefsym " << dyst.iundefsym;
7366 if (dyst.iundefsym > nsyms)
7367 outs() << " (greater than the number of symbols)\n";
7368 else
7369 outs() << "\n";
7370 outs() << " nundefsym " << dyst.nundefsym;
7371 big_size = dyst.iundefsym;
7372 big_size += dyst.nundefsym;
7373 if (big_size > nsyms)
7374 outs() << " (past the end of the symbol table)\n";
7375 else
7376 outs() << "\n";
7377 outs() << " tocoff " << dyst.tocoff;
7378 if (dyst.tocoff > object_size)
7379 outs() << " (past end of file)\n";
7380 else
7381 outs() << "\n";
7382 outs() << " ntoc " << dyst.ntoc;
7383 big_size = dyst.ntoc;
7384 big_size *= sizeof(struct MachO::dylib_table_of_contents);
7385 big_size += dyst.tocoff;
7386 if (big_size > object_size)
7387 outs() << " (past end of file)\n";
7388 else
7389 outs() << "\n";
7390 outs() << " modtaboff " << dyst.modtaboff;
7391 if (dyst.modtaboff > object_size)
7392 outs() << " (past end of file)\n";
7393 else
7394 outs() << "\n";
7395 outs() << " nmodtab " << dyst.nmodtab;
7396 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00007397 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007398 modtabend = dyst.nmodtab;
7399 modtabend *= sizeof(struct MachO::dylib_module_64);
7400 modtabend += dyst.modtaboff;
7401 } else {
7402 modtabend = dyst.nmodtab;
7403 modtabend *= sizeof(struct MachO::dylib_module);
7404 modtabend += dyst.modtaboff;
7405 }
7406 if (modtabend > object_size)
7407 outs() << " (past end of file)\n";
7408 else
7409 outs() << "\n";
7410 outs() << " extrefsymoff " << dyst.extrefsymoff;
7411 if (dyst.extrefsymoff > object_size)
7412 outs() << " (past end of file)\n";
7413 else
7414 outs() << "\n";
7415 outs() << " nextrefsyms " << dyst.nextrefsyms;
7416 big_size = dyst.nextrefsyms;
7417 big_size *= sizeof(struct MachO::dylib_reference);
7418 big_size += dyst.extrefsymoff;
7419 if (big_size > object_size)
7420 outs() << " (past end of file)\n";
7421 else
7422 outs() << "\n";
7423 outs() << " indirectsymoff " << dyst.indirectsymoff;
7424 if (dyst.indirectsymoff > object_size)
7425 outs() << " (past end of file)\n";
7426 else
7427 outs() << "\n";
7428 outs() << " nindirectsyms " << dyst.nindirectsyms;
7429 big_size = dyst.nindirectsyms;
7430 big_size *= sizeof(uint32_t);
7431 big_size += dyst.indirectsymoff;
7432 if (big_size > object_size)
7433 outs() << " (past end of file)\n";
7434 else
7435 outs() << "\n";
7436 outs() << " extreloff " << dyst.extreloff;
7437 if (dyst.extreloff > object_size)
7438 outs() << " (past end of file)\n";
7439 else
7440 outs() << "\n";
7441 outs() << " nextrel " << dyst.nextrel;
7442 big_size = dyst.nextrel;
7443 big_size *= sizeof(struct MachO::relocation_info);
7444 big_size += dyst.extreloff;
7445 if (big_size > object_size)
7446 outs() << " (past end of file)\n";
7447 else
7448 outs() << "\n";
7449 outs() << " locreloff " << dyst.locreloff;
7450 if (dyst.locreloff > object_size)
7451 outs() << " (past end of file)\n";
7452 else
7453 outs() << "\n";
7454 outs() << " nlocrel " << dyst.nlocrel;
7455 big_size = dyst.nlocrel;
7456 big_size *= sizeof(struct MachO::relocation_info);
7457 big_size += dyst.locreloff;
7458 if (big_size > object_size)
7459 outs() << " (past end of file)\n";
7460 else
7461 outs() << "\n";
7462}
7463
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007464static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
7465 uint32_t object_size) {
7466 if (dc.cmd == MachO::LC_DYLD_INFO)
7467 outs() << " cmd LC_DYLD_INFO\n";
7468 else
7469 outs() << " cmd LC_DYLD_INFO_ONLY\n";
7470 outs() << " cmdsize " << dc.cmdsize;
7471 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
7472 outs() << " Incorrect size\n";
7473 else
7474 outs() << "\n";
7475 outs() << " rebase_off " << dc.rebase_off;
7476 if (dc.rebase_off > object_size)
7477 outs() << " (past end of file)\n";
7478 else
7479 outs() << "\n";
7480 outs() << " rebase_size " << dc.rebase_size;
7481 uint64_t big_size;
7482 big_size = dc.rebase_off;
7483 big_size += dc.rebase_size;
7484 if (big_size > object_size)
7485 outs() << " (past end of file)\n";
7486 else
7487 outs() << "\n";
7488 outs() << " bind_off " << dc.bind_off;
7489 if (dc.bind_off > object_size)
7490 outs() << " (past end of file)\n";
7491 else
7492 outs() << "\n";
7493 outs() << " bind_size " << dc.bind_size;
7494 big_size = dc.bind_off;
7495 big_size += dc.bind_size;
7496 if (big_size > object_size)
7497 outs() << " (past end of file)\n";
7498 else
7499 outs() << "\n";
7500 outs() << " weak_bind_off " << dc.weak_bind_off;
7501 if (dc.weak_bind_off > object_size)
7502 outs() << " (past end of file)\n";
7503 else
7504 outs() << "\n";
7505 outs() << " weak_bind_size " << dc.weak_bind_size;
7506 big_size = dc.weak_bind_off;
7507 big_size += dc.weak_bind_size;
7508 if (big_size > object_size)
7509 outs() << " (past end of file)\n";
7510 else
7511 outs() << "\n";
7512 outs() << " lazy_bind_off " << dc.lazy_bind_off;
7513 if (dc.lazy_bind_off > object_size)
7514 outs() << " (past end of file)\n";
7515 else
7516 outs() << "\n";
7517 outs() << " lazy_bind_size " << dc.lazy_bind_size;
7518 big_size = dc.lazy_bind_off;
7519 big_size += dc.lazy_bind_size;
7520 if (big_size > object_size)
7521 outs() << " (past end of file)\n";
7522 else
7523 outs() << "\n";
7524 outs() << " export_off " << dc.export_off;
7525 if (dc.export_off > object_size)
7526 outs() << " (past end of file)\n";
7527 else
7528 outs() << "\n";
7529 outs() << " export_size " << dc.export_size;
7530 big_size = dc.export_off;
7531 big_size += dc.export_size;
7532 if (big_size > object_size)
7533 outs() << " (past end of file)\n";
7534 else
7535 outs() << "\n";
7536}
7537
7538static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
7539 const char *Ptr) {
7540 if (dyld.cmd == MachO::LC_ID_DYLINKER)
7541 outs() << " cmd LC_ID_DYLINKER\n";
7542 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
7543 outs() << " cmd LC_LOAD_DYLINKER\n";
7544 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
7545 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
7546 else
7547 outs() << " cmd ?(" << dyld.cmd << ")\n";
7548 outs() << " cmdsize " << dyld.cmdsize;
7549 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
7550 outs() << " Incorrect size\n";
7551 else
7552 outs() << "\n";
7553 if (dyld.name >= dyld.cmdsize)
7554 outs() << " name ?(bad offset " << dyld.name << ")\n";
7555 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007556 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007557 outs() << " name " << P << " (offset " << dyld.name << ")\n";
7558 }
7559}
7560
7561static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
7562 outs() << " cmd LC_UUID\n";
7563 outs() << " cmdsize " << uuid.cmdsize;
7564 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
7565 outs() << " Incorrect size\n";
7566 else
7567 outs() << "\n";
7568 outs() << " uuid ";
Davide Italianoc74277a2015-12-07 00:03:28 +00007569 for (int i = 0; i < 16; ++i) {
7570 outs() << format("%02" PRIX32, uuid.uuid[i]);
7571 if (i == 3 || i == 5 || i == 7 || i == 9)
7572 outs() << "-";
7573 }
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007574 outs() << "\n";
7575}
7576
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007577static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00007578 outs() << " cmd LC_RPATH\n";
7579 outs() << " cmdsize " << rpath.cmdsize;
7580 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
7581 outs() << " Incorrect size\n";
7582 else
7583 outs() << "\n";
7584 if (rpath.path >= rpath.cmdsize)
7585 outs() << " path ?(bad offset " << rpath.path << ")\n";
7586 else {
7587 const char *P = (const char *)(Ptr) + rpath.path;
7588 outs() << " path " << P << " (offset " << rpath.path << ")\n";
7589 }
7590}
7591
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007592static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
Tim Northoverbfbfb122015-11-02 21:26:58 +00007593 StringRef LoadCmdName;
7594 switch (vd.cmd) {
7595 case MachO::LC_VERSION_MIN_MACOSX:
7596 LoadCmdName = "LC_VERSION_MIN_MACOSX";
7597 break;
7598 case MachO::LC_VERSION_MIN_IPHONEOS:
7599 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
7600 break;
7601 case MachO::LC_VERSION_MIN_TVOS:
7602 LoadCmdName = "LC_VERSION_MIN_TVOS";
7603 break;
7604 case MachO::LC_VERSION_MIN_WATCHOS:
7605 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
7606 break;
7607 default:
7608 llvm_unreachable("Unknown version min load command");
7609 }
7610
7611 outs() << " cmd " << LoadCmdName << '\n';
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007612 outs() << " cmdsize " << vd.cmdsize;
7613 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
7614 outs() << " Incorrect size\n";
7615 else
7616 outs() << "\n";
Davide Italiano56baef32015-08-26 12:26:11 +00007617 outs() << " version "
7618 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
7619 << MachOObjectFile::getVersionMinMinor(vd, false);
7620 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
7621 if (Update != 0)
7622 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007623 outs() << "\n";
7624 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00007625 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007626 else {
Davide Italiano56baef32015-08-26 12:26:11 +00007627 outs() << " sdk "
7628 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
7629 << MachOObjectFile::getVersionMinMinor(vd, true);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007630 }
Davide Italiano56baef32015-08-26 12:26:11 +00007631 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
7632 if (Update != 0)
7633 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007634 outs() << "\n";
7635}
7636
7637static void PrintSourceVersionCommand(MachO::source_version_command sd) {
7638 outs() << " cmd LC_SOURCE_VERSION\n";
7639 outs() << " cmdsize " << sd.cmdsize;
7640 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
7641 outs() << " Incorrect size\n";
7642 else
7643 outs() << "\n";
7644 uint64_t a = (sd.version >> 40) & 0xffffff;
7645 uint64_t b = (sd.version >> 30) & 0x3ff;
7646 uint64_t c = (sd.version >> 20) & 0x3ff;
7647 uint64_t d = (sd.version >> 10) & 0x3ff;
7648 uint64_t e = sd.version & 0x3ff;
7649 outs() << " version " << a << "." << b;
7650 if (e != 0)
7651 outs() << "." << c << "." << d << "." << e;
7652 else if (d != 0)
7653 outs() << "." << c << "." << d;
7654 else if (c != 0)
7655 outs() << "." << c;
7656 outs() << "\n";
7657}
7658
7659static void PrintEntryPointCommand(MachO::entry_point_command ep) {
7660 outs() << " cmd LC_MAIN\n";
7661 outs() << " cmdsize " << ep.cmdsize;
7662 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
7663 outs() << " Incorrect size\n";
7664 else
7665 outs() << "\n";
7666 outs() << " entryoff " << ep.entryoff << "\n";
7667 outs() << " stacksize " << ep.stacksize << "\n";
7668}
7669
Kevin Enderby0804f4672014-12-16 23:25:52 +00007670static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
7671 uint32_t object_size) {
7672 outs() << " cmd LC_ENCRYPTION_INFO\n";
7673 outs() << " cmdsize " << ec.cmdsize;
7674 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
7675 outs() << " Incorrect size\n";
7676 else
7677 outs() << "\n";
7678 outs() << " cryptoff " << ec.cryptoff;
7679 if (ec.cryptoff > object_size)
7680 outs() << " (past end of file)\n";
7681 else
7682 outs() << "\n";
7683 outs() << " cryptsize " << ec.cryptsize;
7684 if (ec.cryptsize > object_size)
7685 outs() << " (past end of file)\n";
7686 else
7687 outs() << "\n";
7688 outs() << " cryptid " << ec.cryptid << "\n";
7689}
7690
Kevin Enderby57538292014-12-17 01:01:30 +00007691static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007692 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00007693 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
7694 outs() << " cmdsize " << ec.cmdsize;
7695 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
7696 outs() << " Incorrect size\n";
7697 else
7698 outs() << "\n";
7699 outs() << " cryptoff " << ec.cryptoff;
7700 if (ec.cryptoff > object_size)
7701 outs() << " (past end of file)\n";
7702 else
7703 outs() << "\n";
7704 outs() << " cryptsize " << ec.cryptsize;
7705 if (ec.cryptsize > object_size)
7706 outs() << " (past end of file)\n";
7707 else
7708 outs() << "\n";
7709 outs() << " cryptid " << ec.cryptid << "\n";
7710 outs() << " pad " << ec.pad << "\n";
7711}
7712
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00007713static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
7714 const char *Ptr) {
7715 outs() << " cmd LC_LINKER_OPTION\n";
7716 outs() << " cmdsize " << lo.cmdsize;
7717 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
7718 outs() << " Incorrect size\n";
7719 else
7720 outs() << "\n";
7721 outs() << " count " << lo.count << "\n";
7722 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
7723 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
7724 uint32_t i = 0;
7725 while (left > 0) {
7726 while (*string == '\0' && left > 0) {
7727 string++;
7728 left--;
7729 }
7730 if (left > 0) {
7731 i++;
7732 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00007733 uint32_t NullPos = StringRef(string, left).find('\0');
7734 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00007735 string += len;
7736 left -= len;
7737 }
7738 }
7739 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007740 outs() << " count " << lo.count << " does not match number of strings "
7741 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00007742}
7743
Kevin Enderbyb4b79312014-12-18 19:24:35 +00007744static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
7745 const char *Ptr) {
7746 outs() << " cmd LC_SUB_FRAMEWORK\n";
7747 outs() << " cmdsize " << sub.cmdsize;
7748 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
7749 outs() << " Incorrect size\n";
7750 else
7751 outs() << "\n";
7752 if (sub.umbrella < sub.cmdsize) {
7753 const char *P = Ptr + sub.umbrella;
7754 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
7755 } else {
7756 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
7757 }
7758}
7759
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00007760static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
7761 const char *Ptr) {
7762 outs() << " cmd LC_SUB_UMBRELLA\n";
7763 outs() << " cmdsize " << sub.cmdsize;
7764 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
7765 outs() << " Incorrect size\n";
7766 else
7767 outs() << "\n";
7768 if (sub.sub_umbrella < sub.cmdsize) {
7769 const char *P = Ptr + sub.sub_umbrella;
7770 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
7771 } else {
7772 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
7773 }
7774}
7775
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00007776static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007777 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00007778 outs() << " cmd LC_SUB_LIBRARY\n";
7779 outs() << " cmdsize " << sub.cmdsize;
7780 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
7781 outs() << " Incorrect size\n";
7782 else
7783 outs() << "\n";
7784 if (sub.sub_library < sub.cmdsize) {
7785 const char *P = Ptr + sub.sub_library;
7786 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
7787 } else {
7788 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
7789 }
7790}
7791
Kevin Enderby186eac32014-12-19 21:06:24 +00007792static void PrintSubClientCommand(MachO::sub_client_command sub,
7793 const char *Ptr) {
7794 outs() << " cmd LC_SUB_CLIENT\n";
7795 outs() << " cmdsize " << sub.cmdsize;
7796 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
7797 outs() << " Incorrect size\n";
7798 else
7799 outs() << "\n";
7800 if (sub.client < sub.cmdsize) {
7801 const char *P = Ptr + sub.client;
7802 outs() << " client " << P << " (offset " << sub.client << ")\n";
7803 } else {
7804 outs() << " client ?(bad offset " << sub.client << ")\n";
7805 }
7806}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00007807
Kevin Enderby52e4ce42014-12-19 22:25:22 +00007808static void PrintRoutinesCommand(MachO::routines_command r) {
7809 outs() << " cmd LC_ROUTINES\n";
7810 outs() << " cmdsize " << r.cmdsize;
7811 if (r.cmdsize != sizeof(struct MachO::routines_command))
7812 outs() << " Incorrect size\n";
7813 else
7814 outs() << "\n";
7815 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
7816 outs() << " init_module " << r.init_module << "\n";
7817 outs() << " reserved1 " << r.reserved1 << "\n";
7818 outs() << " reserved2 " << r.reserved2 << "\n";
7819 outs() << " reserved3 " << r.reserved3 << "\n";
7820 outs() << " reserved4 " << r.reserved4 << "\n";
7821 outs() << " reserved5 " << r.reserved5 << "\n";
7822 outs() << " reserved6 " << r.reserved6 << "\n";
7823}
7824
7825static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
7826 outs() << " cmd LC_ROUTINES_64\n";
7827 outs() << " cmdsize " << r.cmdsize;
7828 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
7829 outs() << " Incorrect size\n";
7830 else
7831 outs() << "\n";
7832 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
7833 outs() << " init_module " << r.init_module << "\n";
7834 outs() << " reserved1 " << r.reserved1 << "\n";
7835 outs() << " reserved2 " << r.reserved2 << "\n";
7836 outs() << " reserved3 " << r.reserved3 << "\n";
7837 outs() << " reserved4 " << r.reserved4 << "\n";
7838 outs() << " reserved5 " << r.reserved5 << "\n";
7839 outs() << " reserved6 " << r.reserved6 << "\n";
7840}
7841
Kevin Enderby48ef5342014-12-23 22:56:39 +00007842static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
7843 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
7844 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
7845 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
7846 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
7847 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
7848 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
7849 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
7850 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
7851 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
7852 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
7853 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
7854 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
7855 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
7856 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
7857 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
7858 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
7859 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
7860 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
7861 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
7862 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
7863 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
7864}
7865
Kevin Enderby227df342014-12-23 23:43:59 +00007866static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00007867 uint32_t f;
7868 outs() << "\t mmst_reg ";
7869 for (f = 0; f < 10; f++)
7870 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
7871 outs() << "\n";
7872 outs() << "\t mmst_rsrv ";
7873 for (f = 0; f < 6; f++)
7874 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
7875 outs() << "\n";
7876}
7877
Kevin Enderbyaefb0032014-12-24 00:16:51 +00007878static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00007879 uint32_t f;
7880 outs() << "\t xmm_reg ";
7881 for (f = 0; f < 16; f++)
7882 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
7883 outs() << "\n";
7884}
7885
7886static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
7887 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
7888 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
7889 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
7890 outs() << " denorm " << fpu.fpu_fcw.denorm;
7891 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
7892 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
7893 outs() << " undfl " << fpu.fpu_fcw.undfl;
7894 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
7895 outs() << "\t\t pc ";
7896 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
7897 outs() << "FP_PREC_24B ";
7898 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
7899 outs() << "FP_PREC_53B ";
7900 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
7901 outs() << "FP_PREC_64B ";
7902 else
7903 outs() << fpu.fpu_fcw.pc << " ";
7904 outs() << "rc ";
7905 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
7906 outs() << "FP_RND_NEAR ";
7907 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
7908 outs() << "FP_RND_DOWN ";
7909 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
7910 outs() << "FP_RND_UP ";
7911 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007912 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00007913 outs() << "\n";
7914 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
7915 outs() << " denorm " << fpu.fpu_fsw.denorm;
7916 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
7917 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
7918 outs() << " undfl " << fpu.fpu_fsw.undfl;
7919 outs() << " precis " << fpu.fpu_fsw.precis;
7920 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
7921 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
7922 outs() << " c0 " << fpu.fpu_fsw.c0;
7923 outs() << " c1 " << fpu.fpu_fsw.c1;
7924 outs() << " c2 " << fpu.fpu_fsw.c2;
7925 outs() << " tos " << fpu.fpu_fsw.tos;
7926 outs() << " c3 " << fpu.fpu_fsw.c3;
7927 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
7928 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
7929 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
7930 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
7931 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
7932 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
7933 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
7934 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
7935 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
7936 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
7937 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
7938 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
7939 outs() << "\n";
7940 outs() << "\t fpu_stmm0:\n";
7941 Print_mmst_reg(fpu.fpu_stmm0);
7942 outs() << "\t fpu_stmm1:\n";
7943 Print_mmst_reg(fpu.fpu_stmm1);
7944 outs() << "\t fpu_stmm2:\n";
7945 Print_mmst_reg(fpu.fpu_stmm2);
7946 outs() << "\t fpu_stmm3:\n";
7947 Print_mmst_reg(fpu.fpu_stmm3);
7948 outs() << "\t fpu_stmm4:\n";
7949 Print_mmst_reg(fpu.fpu_stmm4);
7950 outs() << "\t fpu_stmm5:\n";
7951 Print_mmst_reg(fpu.fpu_stmm5);
7952 outs() << "\t fpu_stmm6:\n";
7953 Print_mmst_reg(fpu.fpu_stmm6);
7954 outs() << "\t fpu_stmm7:\n";
7955 Print_mmst_reg(fpu.fpu_stmm7);
7956 outs() << "\t fpu_xmm0:\n";
7957 Print_xmm_reg(fpu.fpu_xmm0);
7958 outs() << "\t fpu_xmm1:\n";
7959 Print_xmm_reg(fpu.fpu_xmm1);
7960 outs() << "\t fpu_xmm2:\n";
7961 Print_xmm_reg(fpu.fpu_xmm2);
7962 outs() << "\t fpu_xmm3:\n";
7963 Print_xmm_reg(fpu.fpu_xmm3);
7964 outs() << "\t fpu_xmm4:\n";
7965 Print_xmm_reg(fpu.fpu_xmm4);
7966 outs() << "\t fpu_xmm5:\n";
7967 Print_xmm_reg(fpu.fpu_xmm5);
7968 outs() << "\t fpu_xmm6:\n";
7969 Print_xmm_reg(fpu.fpu_xmm6);
7970 outs() << "\t fpu_xmm7:\n";
7971 Print_xmm_reg(fpu.fpu_xmm7);
7972 outs() << "\t fpu_xmm8:\n";
7973 Print_xmm_reg(fpu.fpu_xmm8);
7974 outs() << "\t fpu_xmm9:\n";
7975 Print_xmm_reg(fpu.fpu_xmm9);
7976 outs() << "\t fpu_xmm10:\n";
7977 Print_xmm_reg(fpu.fpu_xmm10);
7978 outs() << "\t fpu_xmm11:\n";
7979 Print_xmm_reg(fpu.fpu_xmm11);
7980 outs() << "\t fpu_xmm12:\n";
7981 Print_xmm_reg(fpu.fpu_xmm12);
7982 outs() << "\t fpu_xmm13:\n";
7983 Print_xmm_reg(fpu.fpu_xmm13);
7984 outs() << "\t fpu_xmm14:\n";
7985 Print_xmm_reg(fpu.fpu_xmm14);
7986 outs() << "\t fpu_xmm15:\n";
7987 Print_xmm_reg(fpu.fpu_xmm15);
7988 outs() << "\t fpu_rsrv4:\n";
7989 for (uint32_t f = 0; f < 6; f++) {
7990 outs() << "\t ";
7991 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007992 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00007993 outs() << "\n";
7994 }
7995 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
7996 outs() << "\n";
7997}
7998
7999static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
8000 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
8001 outs() << " err " << format("0x%08" PRIx32, exc64.err);
8002 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
8003}
8004
8005static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
8006 bool isLittleEndian, uint32_t cputype) {
8007 if (t.cmd == MachO::LC_THREAD)
8008 outs() << " cmd LC_THREAD\n";
8009 else if (t.cmd == MachO::LC_UNIXTHREAD)
8010 outs() << " cmd LC_UNIXTHREAD\n";
8011 else
8012 outs() << " cmd " << t.cmd << " (unknown)\n";
8013 outs() << " cmdsize " << t.cmdsize;
8014 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
8015 outs() << " Incorrect size\n";
8016 else
8017 outs() << "\n";
8018
8019 const char *begin = Ptr + sizeof(struct MachO::thread_command);
8020 const char *end = Ptr + t.cmdsize;
8021 uint32_t flavor, count, left;
8022 if (cputype == MachO::CPU_TYPE_X86_64) {
8023 while (begin < end) {
8024 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8025 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8026 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008027 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008028 flavor = 0;
8029 begin = end;
8030 }
8031 if (isLittleEndian != sys::IsLittleEndianHost)
8032 sys::swapByteOrder(flavor);
8033 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8034 memcpy((char *)&count, begin, sizeof(uint32_t));
8035 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008036 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008037 count = 0;
8038 begin = end;
8039 }
8040 if (isLittleEndian != sys::IsLittleEndianHost)
8041 sys::swapByteOrder(count);
8042 if (flavor == MachO::x86_THREAD_STATE64) {
8043 outs() << " flavor x86_THREAD_STATE64\n";
8044 if (count == MachO::x86_THREAD_STATE64_COUNT)
8045 outs() << " count x86_THREAD_STATE64_COUNT\n";
8046 else
8047 outs() << " count " << count
8048 << " (not x86_THREAD_STATE64_COUNT)\n";
8049 MachO::x86_thread_state64_t cpu64;
8050 left = end - begin;
8051 if (left >= sizeof(MachO::x86_thread_state64_t)) {
8052 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
8053 begin += sizeof(MachO::x86_thread_state64_t);
8054 } else {
8055 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
8056 memcpy(&cpu64, begin, left);
8057 begin += left;
8058 }
8059 if (isLittleEndian != sys::IsLittleEndianHost)
8060 swapStruct(cpu64);
8061 Print_x86_thread_state64_t(cpu64);
8062 } else if (flavor == MachO::x86_THREAD_STATE) {
8063 outs() << " flavor x86_THREAD_STATE\n";
8064 if (count == MachO::x86_THREAD_STATE_COUNT)
8065 outs() << " count x86_THREAD_STATE_COUNT\n";
8066 else
8067 outs() << " count " << count
8068 << " (not x86_THREAD_STATE_COUNT)\n";
8069 struct MachO::x86_thread_state_t ts;
8070 left = end - begin;
8071 if (left >= sizeof(MachO::x86_thread_state_t)) {
8072 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
8073 begin += sizeof(MachO::x86_thread_state_t);
8074 } else {
8075 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
8076 memcpy(&ts, begin, left);
8077 begin += left;
8078 }
8079 if (isLittleEndian != sys::IsLittleEndianHost)
8080 swapStruct(ts);
8081 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
8082 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
8083 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
8084 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
8085 else
8086 outs() << "tsh.count " << ts.tsh.count
8087 << " (not x86_THREAD_STATE64_COUNT\n";
8088 Print_x86_thread_state64_t(ts.uts.ts64);
8089 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008090 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
8091 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008092 }
8093 } else if (flavor == MachO::x86_FLOAT_STATE) {
8094 outs() << " flavor x86_FLOAT_STATE\n";
8095 if (count == MachO::x86_FLOAT_STATE_COUNT)
8096 outs() << " count x86_FLOAT_STATE_COUNT\n";
8097 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008098 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008099 struct MachO::x86_float_state_t fs;
8100 left = end - begin;
8101 if (left >= sizeof(MachO::x86_float_state_t)) {
8102 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
8103 begin += sizeof(MachO::x86_float_state_t);
8104 } else {
8105 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
8106 memcpy(&fs, begin, left);
8107 begin += left;
8108 }
8109 if (isLittleEndian != sys::IsLittleEndianHost)
8110 swapStruct(fs);
8111 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
8112 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008113 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008114 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
8115 else
8116 outs() << "fsh.count " << fs.fsh.count
8117 << " (not x86_FLOAT_STATE64_COUNT\n";
8118 Print_x86_float_state_t(fs.ufs.fs64);
8119 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008120 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
8121 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008122 }
8123 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
8124 outs() << " flavor x86_EXCEPTION_STATE\n";
8125 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
8126 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
8127 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008128 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00008129 << " (not x86_EXCEPTION_STATE_COUNT)\n";
8130 struct MachO::x86_exception_state_t es;
8131 left = end - begin;
8132 if (left >= sizeof(MachO::x86_exception_state_t)) {
8133 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
8134 begin += sizeof(MachO::x86_exception_state_t);
8135 } else {
8136 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
8137 memcpy(&es, begin, left);
8138 begin += left;
8139 }
8140 if (isLittleEndian != sys::IsLittleEndianHost)
8141 swapStruct(es);
8142 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
8143 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008144 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008145 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
8146 else
8147 outs() << "\t esh.count " << es.esh.count
8148 << " (not x86_EXCEPTION_STATE64_COUNT\n";
8149 Print_x86_exception_state_t(es.ues.es64);
8150 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008151 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
8152 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008153 }
8154 } else {
8155 outs() << " flavor " << flavor << " (unknown)\n";
8156 outs() << " count " << count << "\n";
8157 outs() << " state (unknown)\n";
8158 begin += count * sizeof(uint32_t);
8159 }
8160 }
8161 } else {
8162 while (begin < end) {
8163 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8164 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8165 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008166 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008167 flavor = 0;
8168 begin = end;
8169 }
8170 if (isLittleEndian != sys::IsLittleEndianHost)
8171 sys::swapByteOrder(flavor);
8172 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8173 memcpy((char *)&count, begin, sizeof(uint32_t));
8174 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008175 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008176 count = 0;
8177 begin = end;
8178 }
8179 if (isLittleEndian != sys::IsLittleEndianHost)
8180 sys::swapByteOrder(count);
8181 outs() << " flavor " << flavor << "\n";
8182 outs() << " count " << count << "\n";
8183 outs() << " state (Unknown cputype/cpusubtype)\n";
8184 begin += count * sizeof(uint32_t);
8185 }
8186 }
8187}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008188
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008189static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
8190 if (dl.cmd == MachO::LC_ID_DYLIB)
8191 outs() << " cmd LC_ID_DYLIB\n";
8192 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
8193 outs() << " cmd LC_LOAD_DYLIB\n";
8194 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
8195 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
8196 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
8197 outs() << " cmd LC_REEXPORT_DYLIB\n";
8198 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
8199 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
8200 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
8201 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
8202 else
8203 outs() << " cmd " << dl.cmd << " (unknown)\n";
8204 outs() << " cmdsize " << dl.cmdsize;
8205 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
8206 outs() << " Incorrect size\n";
8207 else
8208 outs() << "\n";
8209 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008210 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008211 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
8212 } else {
8213 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
8214 }
8215 outs() << " time stamp " << dl.dylib.timestamp << " ";
8216 time_t t = dl.dylib.timestamp;
8217 outs() << ctime(&t);
8218 outs() << " current version ";
8219 if (dl.dylib.current_version == 0xffffffff)
8220 outs() << "n/a\n";
8221 else
8222 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
8223 << ((dl.dylib.current_version >> 8) & 0xff) << "."
8224 << (dl.dylib.current_version & 0xff) << "\n";
8225 outs() << "compatibility version ";
8226 if (dl.dylib.compatibility_version == 0xffffffff)
8227 outs() << "n/a\n";
8228 else
8229 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
8230 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
8231 << (dl.dylib.compatibility_version & 0xff) << "\n";
8232}
8233
8234static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
8235 uint32_t object_size) {
8236 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
8237 outs() << " cmd LC_FUNCTION_STARTS\n";
8238 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
8239 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
8240 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
8241 outs() << " cmd LC_FUNCTION_STARTS\n";
8242 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
8243 outs() << " cmd LC_DATA_IN_CODE\n";
8244 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
8245 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
8246 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
8247 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
8248 else
8249 outs() << " cmd " << ld.cmd << " (?)\n";
8250 outs() << " cmdsize " << ld.cmdsize;
8251 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
8252 outs() << " Incorrect size\n";
8253 else
8254 outs() << "\n";
8255 outs() << " dataoff " << ld.dataoff;
8256 if (ld.dataoff > object_size)
8257 outs() << " (past end of file)\n";
8258 else
8259 outs() << "\n";
8260 outs() << " datasize " << ld.datasize;
8261 uint64_t big_size = ld.dataoff;
8262 big_size += ld.datasize;
8263 if (big_size > object_size)
8264 outs() << " (past end of file)\n";
8265 else
8266 outs() << "\n";
8267}
8268
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008269static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
8270 uint32_t cputype, bool verbose) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008271 StringRef Buf = Obj->getData();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008272 unsigned Index = 0;
8273 for (const auto &Command : Obj->load_commands()) {
8274 outs() << "Load command " << Index++ << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008275 if (Command.C.cmd == MachO::LC_SEGMENT) {
8276 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
8277 const char *sg_segname = SLC.segname;
8278 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
8279 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
8280 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
8281 verbose);
8282 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00008283 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00008284 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
8285 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
8286 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
8287 }
8288 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
8289 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
8290 const char *sg_segname = SLC_64.segname;
8291 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
8292 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
8293 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
8294 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
8295 for (unsigned j = 0; j < SLC_64.nsects; j++) {
8296 MachO::section_64 S_64 = Obj->getSection64(Command, j);
8297 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
8298 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
8299 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
8300 sg_segname, filetype, Buf.size(), verbose);
8301 }
8302 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
8303 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00008304 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00008305 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
8306 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
8307 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00008308 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
8309 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008310 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
8311 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
8312 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
8313 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
8314 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
8315 Command.C.cmd == MachO::LC_ID_DYLINKER ||
8316 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
8317 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
8318 PrintDyldLoadCommand(Dyld, Command.Ptr);
8319 } else if (Command.C.cmd == MachO::LC_UUID) {
8320 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
8321 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008322 } else if (Command.C.cmd == MachO::LC_RPATH) {
8323 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
8324 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00008325 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
Tim Northoverbfbfb122015-11-02 21:26:58 +00008326 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
8327 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
8328 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008329 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
8330 PrintVersionMinLoadCommand(Vd);
8331 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
8332 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
8333 PrintSourceVersionCommand(Sd);
8334 } else if (Command.C.cmd == MachO::LC_MAIN) {
8335 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
8336 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00008337 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008338 MachO::encryption_info_command Ei =
8339 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00008340 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00008341 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008342 MachO::encryption_info_command_64 Ei =
8343 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00008344 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008345 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008346 MachO::linker_option_command Lo =
8347 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008348 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00008349 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
8350 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
8351 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00008352 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
8353 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
8354 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008355 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
8356 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
8357 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00008358 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
8359 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
8360 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00008361 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
8362 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
8363 PrintRoutinesCommand(Rc);
8364 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
8365 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
8366 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00008367 } else if (Command.C.cmd == MachO::LC_THREAD ||
8368 Command.C.cmd == MachO::LC_UNIXTHREAD) {
8369 MachO::thread_command Tc = Obj->getThreadCommand(Command);
8370 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00008371 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
8372 Command.C.cmd == MachO::LC_ID_DYLIB ||
8373 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
8374 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
8375 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
8376 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008377 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
8378 PrintDylibCommand(Dl, Command.Ptr);
8379 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
8380 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
8381 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
8382 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
8383 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
8384 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
8385 MachO::linkedit_data_command Ld =
8386 Obj->getLinkeditDataLoadCommand(Command);
8387 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00008388 } else {
8389 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
8390 << ")\n";
8391 outs() << " cmdsize " << Command.C.cmdsize << "\n";
8392 // TODO: get and print the raw bytes of the load command.
8393 }
8394 // TODO: print all the other kinds of load commands.
Kevin Enderby956366c2014-08-29 22:30:52 +00008395 }
8396}
8397
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008398static void getAndPrintMachHeader(const MachOObjectFile *Obj,
Kevin Enderby956366c2014-08-29 22:30:52 +00008399 uint32_t &filetype, uint32_t &cputype,
8400 bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008401 if (Obj->is64Bit()) {
8402 MachO::mach_header_64 H_64;
8403 H_64 = Obj->getHeader64();
8404 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
8405 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
Kevin Enderby956366c2014-08-29 22:30:52 +00008406 filetype = H_64.filetype;
8407 cputype = H_64.cputype;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008408 } else {
8409 MachO::mach_header H;
8410 H = Obj->getHeader();
8411 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
8412 H.sizeofcmds, H.flags, verbose);
Kevin Enderby956366c2014-08-29 22:30:52 +00008413 filetype = H.filetype;
8414 cputype = H.cputype;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008415 }
8416}
8417
8418void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
8419 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00008420 uint32_t filetype = 0;
8421 uint32_t cputype = 0;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008422 getAndPrintMachHeader(file, filetype, cputype, !NonVerbose);
8423 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008424}
Nick Kledzikd04bc352014-08-30 00:20:14 +00008425
8426//===----------------------------------------------------------------------===//
8427// export trie dumping
8428//===----------------------------------------------------------------------===//
8429
8430void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008431 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
8432 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +00008433 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
8434 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
8435 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8436 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
8437 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8438 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
8439 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
8440 if (ReExport)
8441 outs() << "[re-export] ";
8442 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008443 outs() << format("0x%08llX ",
8444 Entry.address()); // FIXME:add in base address
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008445 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +00008446 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008447 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +00008448 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +00008449 if (WeakDef) {
8450 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008451 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008452 }
8453 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008454 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00008455 outs() << ", ";
8456 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008457 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008458 }
8459 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008460 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00008461 outs() << ", ";
8462 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008463 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008464 }
8465 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008466 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00008467 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008468 outs() << format("resolver=0x%08llX", Entry.other());
8469 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008470 }
8471 outs() << "]";
8472 }
8473 if (ReExport) {
8474 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008475 int Ordinal = Entry.other() - 1;
8476 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
8477 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +00008478 outs() << " (from " << DylibName << ")";
8479 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008480 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +00008481 }
8482 outs() << "\n";
8483 }
8484}
Nick Kledzikac431442014-09-12 21:34:15 +00008485
Nick Kledzikac431442014-09-12 21:34:15 +00008486//===----------------------------------------------------------------------===//
8487// rebase table dumping
8488//===----------------------------------------------------------------------===//
8489
8490namespace {
8491class SegInfo {
8492public:
8493 SegInfo(const object::MachOObjectFile *Obj);
8494
8495 StringRef segmentName(uint32_t SegIndex);
8496 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
8497 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00008498 bool isValidSegIndexAndOffset(uint32_t SegIndex, uint64_t SegOffset);
Nick Kledzikac431442014-09-12 21:34:15 +00008499
8500private:
8501 struct SectionInfo {
8502 uint64_t Address;
8503 uint64_t Size;
8504 StringRef SectionName;
8505 StringRef SegmentName;
8506 uint64_t OffsetInSegment;
8507 uint64_t SegmentStartAddress;
8508 uint32_t SegmentIndex;
8509 };
8510 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
8511 SmallVector<SectionInfo, 32> Sections;
8512};
8513}
8514
8515SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
8516 // Build table of sections so segIndex/offset pairs can be translated.
Nick Kledzik56ebef42014-09-16 01:41:51 +00008517 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
Nick Kledzikac431442014-09-12 21:34:15 +00008518 StringRef CurSegName;
8519 uint64_t CurSegAddress;
8520 for (const SectionRef &Section : Obj->sections()) {
8521 SectionInfo Info;
Davide Italianoccd53fe2015-08-05 07:18:31 +00008522 error(Section.getName(Info.SectionName));
Rafael Espindola80291272014-10-08 15:28:58 +00008523 Info.Address = Section.getAddress();
8524 Info.Size = Section.getSize();
Nick Kledzikac431442014-09-12 21:34:15 +00008525 Info.SegmentName =
8526 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
8527 if (!Info.SegmentName.equals(CurSegName)) {
8528 ++CurSegIndex;
8529 CurSegName = Info.SegmentName;
8530 CurSegAddress = Info.Address;
8531 }
8532 Info.SegmentIndex = CurSegIndex - 1;
8533 Info.OffsetInSegment = Info.Address - CurSegAddress;
8534 Info.SegmentStartAddress = CurSegAddress;
8535 Sections.push_back(Info);
8536 }
8537}
8538
8539StringRef SegInfo::segmentName(uint32_t SegIndex) {
8540 for (const SectionInfo &SI : Sections) {
8541 if (SI.SegmentIndex == SegIndex)
8542 return SI.SegmentName;
8543 }
8544 llvm_unreachable("invalid segIndex");
8545}
8546
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00008547bool SegInfo::isValidSegIndexAndOffset(uint32_t SegIndex,
8548 uint64_t OffsetInSeg) {
8549 for (const SectionInfo &SI : Sections) {
8550 if (SI.SegmentIndex != SegIndex)
8551 continue;
8552 if (SI.OffsetInSegment > OffsetInSeg)
8553 continue;
8554 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
8555 continue;
8556 return true;
8557 }
8558 return false;
8559}
8560
Nick Kledzikac431442014-09-12 21:34:15 +00008561const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
8562 uint64_t OffsetInSeg) {
8563 for (const SectionInfo &SI : Sections) {
8564 if (SI.SegmentIndex != SegIndex)
8565 continue;
8566 if (SI.OffsetInSegment > OffsetInSeg)
8567 continue;
8568 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
8569 continue;
8570 return SI;
8571 }
8572 llvm_unreachable("segIndex and offset not in any section");
8573}
8574
8575StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
8576 return findSection(SegIndex, OffsetInSeg).SectionName;
8577}
8578
8579uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
8580 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
8581 return SI.SegmentStartAddress + OffsetInSeg;
8582}
8583
8584void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
8585 // Build table of sections so names can used in final output.
8586 SegInfo sectionTable(Obj);
8587
8588 outs() << "segment section address type\n";
8589 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
8590 uint32_t SegIndex = Entry.segmentIndex();
8591 uint64_t OffsetInSeg = Entry.segmentOffset();
8592 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8593 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8594 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8595
8596 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008597 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
8598 SegmentName.str().c_str(), SectionName.str().c_str(),
8599 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +00008600 }
8601}
Nick Kledzik56ebef42014-09-16 01:41:51 +00008602
8603static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
8604 StringRef DylibName;
8605 switch (Ordinal) {
8606 case MachO::BIND_SPECIAL_DYLIB_SELF:
8607 return "this-image";
8608 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
8609 return "main-executable";
8610 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
8611 return "flat-namespace";
8612 default:
Nick Kledzikabd29872014-09-16 22:03:13 +00008613 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008614 std::error_code EC =
8615 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +00008616 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +00008617 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +00008618 return DylibName;
8619 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00008620 }
Nick Kledzikabd29872014-09-16 22:03:13 +00008621 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008622}
8623
8624//===----------------------------------------------------------------------===//
8625// bind table dumping
8626//===----------------------------------------------------------------------===//
8627
8628void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
8629 // Build table of sections so names can used in final output.
8630 SegInfo sectionTable(Obj);
8631
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008632 outs() << "segment section address type "
8633 "addend dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008634 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
8635 uint32_t SegIndex = Entry.segmentIndex();
8636 uint64_t OffsetInSeg = Entry.segmentOffset();
8637 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8638 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8639 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8640
8641 // Table lines look like:
8642 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008643 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00008644 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008645 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008646 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008647 << left_justify(SectionName, 18) << " "
8648 << format_hex(Address, 10, true) << " "
8649 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008650 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008651 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008652 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008653 }
8654}
8655
8656//===----------------------------------------------------------------------===//
8657// lazy bind table dumping
8658//===----------------------------------------------------------------------===//
8659
8660void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
8661 // Build table of sections so names can used in final output.
8662 SegInfo sectionTable(Obj);
8663
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008664 outs() << "segment section address "
8665 "dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008666 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
8667 uint32_t SegIndex = Entry.segmentIndex();
8668 uint64_t OffsetInSeg = Entry.segmentOffset();
8669 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8670 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8671 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8672
8673 // Table lines look like:
8674 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008675 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008676 << left_justify(SectionName, 18) << " "
8677 << format_hex(Address, 10, true) << " "
8678 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00008679 << Entry.symbolName() << "\n";
8680 }
8681}
8682
Nick Kledzik56ebef42014-09-16 01:41:51 +00008683//===----------------------------------------------------------------------===//
8684// weak bind table dumping
8685//===----------------------------------------------------------------------===//
8686
8687void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
8688 // Build table of sections so names can used in final output.
8689 SegInfo sectionTable(Obj);
8690
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008691 outs() << "segment section address "
8692 "type addend symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008693 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
8694 // Strong symbols don't have a location to update.
8695 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008696 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +00008697 << Entry.symbolName() << "\n";
8698 continue;
8699 }
8700 uint32_t SegIndex = Entry.segmentIndex();
8701 uint64_t OffsetInSeg = Entry.segmentOffset();
8702 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8703 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8704 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8705
8706 // Table lines look like:
8707 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008708 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008709 << left_justify(SectionName, 18) << " "
8710 << format_hex(Address, 10, true) << " "
8711 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008712 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
8713 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008714 }
8715}
8716
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008717// get_dyld_bind_info_symbolname() is used for disassembly and passed an
8718// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
8719// information for that address. If the address is found its binding symbol
8720// name is returned. If not nullptr is returned.
8721static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
8722 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +00008723 if (info->bindtable == nullptr) {
8724 info->bindtable = new (BindTable);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008725 SegInfo sectionTable(info->O);
8726 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
8727 uint32_t SegIndex = Entry.segmentIndex();
8728 uint64_t OffsetInSeg = Entry.segmentOffset();
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00008729 if (!sectionTable.isValidSegIndexAndOffset(SegIndex, OffsetInSeg))
8730 continue;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008731 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8732 const char *SymbolName = nullptr;
8733 StringRef name = Entry.symbolName();
8734 if (!name.empty())
8735 SymbolName = name.data();
Kevin Enderby078be602014-10-23 19:53:12 +00008736 info->bindtable->push_back(std::make_pair(Address, SymbolName));
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008737 }
8738 }
Kevin Enderby078be602014-10-23 19:53:12 +00008739 for (bind_table_iterator BI = info->bindtable->begin(),
8740 BE = info->bindtable->end();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008741 BI != BE; ++BI) {
8742 uint64_t Address = BI->first;
8743 if (ReferenceValue == Address) {
8744 const char *SymbolName = BI->second;
8745 return SymbolName;
8746 }
8747 }
8748 return nullptr;
8749}