blob: 258c0b520a3d4f6ecfcb9f864d9bf9668679fcf7 [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 Enderby0ae163f2016-01-13 00:25:36 +00001199 if (PrivateHeaders) {
1200 printMachOFileHeader(MachOOF);
1201 printMachOLoadCommands(MachOOF);
1202 }
1203 if (FirstPrivateHeader)
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001204 printMachOFileHeader(MachOOF);
Kevin Enderby0fc11822015-04-01 20:57:01 +00001205 if (ObjcMetaData)
1206 printObjcMetaData(MachOOF, !NonVerbose);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001207 if (ExportsTrie)
1208 printExportsTrie(MachOOF);
1209 if (Rebase)
1210 printRebaseTable(MachOOF);
1211 if (Bind)
1212 printBindTable(MachOOF);
1213 if (LazyBind)
1214 printLazyBindTable(MachOOF);
1215 if (WeakBind)
1216 printWeakBindTable(MachOOF);
1217}
1218
Kevin Enderby131d1772015-01-09 19:22:37 +00001219// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1220static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1221 outs() << " cputype (" << cputype << ")\n";
1222 outs() << " cpusubtype (" << cpusubtype << ")\n";
1223}
1224
1225// printCPUType() helps print_fat_headers by printing the cputype and
1226// pusubtype (symbolically for the one's it knows about).
1227static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1228 switch (cputype) {
1229 case MachO::CPU_TYPE_I386:
1230 switch (cpusubtype) {
1231 case MachO::CPU_SUBTYPE_I386_ALL:
1232 outs() << " cputype CPU_TYPE_I386\n";
1233 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1234 break;
1235 default:
1236 printUnknownCPUType(cputype, cpusubtype);
1237 break;
1238 }
1239 break;
1240 case MachO::CPU_TYPE_X86_64:
1241 switch (cpusubtype) {
1242 case MachO::CPU_SUBTYPE_X86_64_ALL:
1243 outs() << " cputype CPU_TYPE_X86_64\n";
1244 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1245 break;
1246 case MachO::CPU_SUBTYPE_X86_64_H:
1247 outs() << " cputype CPU_TYPE_X86_64\n";
1248 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1249 break;
1250 default:
1251 printUnknownCPUType(cputype, cpusubtype);
1252 break;
1253 }
1254 break;
1255 case MachO::CPU_TYPE_ARM:
1256 switch (cpusubtype) {
1257 case MachO::CPU_SUBTYPE_ARM_ALL:
1258 outs() << " cputype CPU_TYPE_ARM\n";
1259 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1260 break;
1261 case MachO::CPU_SUBTYPE_ARM_V4T:
1262 outs() << " cputype CPU_TYPE_ARM\n";
1263 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1264 break;
1265 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1266 outs() << " cputype CPU_TYPE_ARM\n";
1267 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1268 break;
1269 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1270 outs() << " cputype CPU_TYPE_ARM\n";
1271 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1272 break;
1273 case MachO::CPU_SUBTYPE_ARM_V6:
1274 outs() << " cputype CPU_TYPE_ARM\n";
1275 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1276 break;
1277 case MachO::CPU_SUBTYPE_ARM_V6M:
1278 outs() << " cputype CPU_TYPE_ARM\n";
1279 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1280 break;
1281 case MachO::CPU_SUBTYPE_ARM_V7:
1282 outs() << " cputype CPU_TYPE_ARM\n";
1283 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1284 break;
1285 case MachO::CPU_SUBTYPE_ARM_V7EM:
1286 outs() << " cputype CPU_TYPE_ARM\n";
1287 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1288 break;
1289 case MachO::CPU_SUBTYPE_ARM_V7K:
1290 outs() << " cputype CPU_TYPE_ARM\n";
1291 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1292 break;
1293 case MachO::CPU_SUBTYPE_ARM_V7M:
1294 outs() << " cputype CPU_TYPE_ARM\n";
1295 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1296 break;
1297 case MachO::CPU_SUBTYPE_ARM_V7S:
1298 outs() << " cputype CPU_TYPE_ARM\n";
1299 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1300 break;
1301 default:
1302 printUnknownCPUType(cputype, cpusubtype);
1303 break;
1304 }
1305 break;
1306 case MachO::CPU_TYPE_ARM64:
1307 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1308 case MachO::CPU_SUBTYPE_ARM64_ALL:
1309 outs() << " cputype CPU_TYPE_ARM64\n";
1310 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1311 break;
1312 default:
1313 printUnknownCPUType(cputype, cpusubtype);
1314 break;
1315 }
1316 break;
1317 default:
1318 printUnknownCPUType(cputype, cpusubtype);
1319 break;
1320 }
1321}
1322
1323static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1324 bool verbose) {
1325 outs() << "Fat headers\n";
1326 if (verbose)
1327 outs() << "fat_magic FAT_MAGIC\n";
1328 else
1329 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1330
1331 uint32_t nfat_arch = UB->getNumberOfObjects();
1332 StringRef Buf = UB->getData();
1333 uint64_t size = Buf.size();
1334 uint64_t big_size = sizeof(struct MachO::fat_header) +
1335 nfat_arch * sizeof(struct MachO::fat_arch);
1336 outs() << "nfat_arch " << UB->getNumberOfObjects();
1337 if (nfat_arch == 0)
1338 outs() << " (malformed, contains zero architecture types)\n";
1339 else if (big_size > size)
1340 outs() << " (malformed, architectures past end of file)\n";
1341 else
1342 outs() << "\n";
1343
1344 for (uint32_t i = 0; i < nfat_arch; ++i) {
1345 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1346 uint32_t cputype = OFA.getCPUType();
1347 uint32_t cpusubtype = OFA.getCPUSubType();
1348 outs() << "architecture ";
1349 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1350 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1351 uint32_t other_cputype = other_OFA.getCPUType();
1352 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
Kevin Enderby0512bd72015-01-09 21:55:03 +00001353 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
Kevin Enderby131d1772015-01-09 19:22:37 +00001354 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
Kevin Enderby0512bd72015-01-09 21:55:03 +00001355 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001356 outs() << "(illegal duplicate architecture) ";
1357 break;
Kevin Enderby0512bd72015-01-09 21:55:03 +00001358 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001359 }
1360 if (verbose) {
1361 outs() << OFA.getArchTypeName() << "\n";
1362 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1363 } else {
1364 outs() << i << "\n";
1365 outs() << " cputype " << cputype << "\n";
1366 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1367 << "\n";
1368 }
1369 if (verbose &&
1370 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1371 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1372 else
1373 outs() << " capabilities "
1374 << format("0x%" PRIx32,
1375 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1376 outs() << " offset " << OFA.getOffset();
1377 if (OFA.getOffset() > size)
1378 outs() << " (past end of file)";
1379 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1380 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1381 outs() << "\n";
1382 outs() << " size " << OFA.getSize();
1383 big_size = OFA.getOffset() + OFA.getSize();
1384 if (big_size > size)
1385 outs() << " (past end of file)";
1386 outs() << "\n";
1387 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1388 << ")\n";
1389 }
1390}
1391
Rafael Espindola266b4fe2015-10-31 22:25:59 +00001392static void printArchiveChild(const Archive::Child &C, bool verbose,
Kevin Enderby13023a12015-01-15 23:19:11 +00001393 bool print_offset) {
1394 if (print_offset)
1395 outs() << C.getChildOffset() << "\t";
1396 sys::fs::perms Mode = C.getAccessMode();
1397 if (verbose) {
1398 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1399 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1400 outs() << "-";
Davide Italianobb9a6cc2015-09-07 20:47:03 +00001401 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1402 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1403 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1404 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1405 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1406 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1407 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1408 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1409 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
Kevin Enderby13023a12015-01-15 23:19:11 +00001410 } else {
1411 outs() << format("0%o ", Mode);
1412 }
1413
1414 unsigned UID = C.getUID();
1415 outs() << format("%3d/", UID);
1416 unsigned GID = C.getGID();
1417 outs() << format("%-3d ", GID);
Kevin Enderby7a969422015-11-05 19:24:56 +00001418 ErrorOr<uint64_t> Size = C.getRawSize();
1419 if (std::error_code EC = Size.getError())
1420 report_fatal_error(EC.message());
1421 outs() << format("%5" PRId64, Size.get()) << " ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001422
1423 StringRef RawLastModified = C.getRawLastModified();
1424 if (verbose) {
1425 unsigned Seconds;
1426 if (RawLastModified.getAsInteger(10, Seconds))
1427 outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
1428 else {
1429 // Since cime(3) returns a 26 character string of the form:
1430 // "Sun Sep 16 01:03:52 1973\n\0"
1431 // just print 24 characters.
1432 time_t t = Seconds;
1433 outs() << format("%.24s ", ctime(&t));
1434 }
1435 } else {
1436 outs() << RawLastModified << " ";
1437 }
1438
1439 if (verbose) {
1440 ErrorOr<StringRef> NameOrErr = C.getName();
1441 if (NameOrErr.getError()) {
1442 StringRef RawName = C.getRawName();
1443 outs() << RawName << "\n";
1444 } else {
1445 StringRef Name = NameOrErr.get();
1446 outs() << Name << "\n";
1447 }
1448 } else {
1449 StringRef RawName = C.getRawName();
1450 outs() << RawName << "\n";
1451 }
1452}
1453
1454static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
Rafael Espindola4a782fb2015-10-31 21:03:29 +00001455 for (Archive::child_iterator I = A->child_begin(false), E = A->child_end();
1456 I != E; ++I) {
Kevin Enderby7a969422015-11-05 19:24:56 +00001457 if (std::error_code EC = I->getError())
1458 report_fatal_error(EC.message());
1459 const Archive::Child &C = **I;
Kevin Enderby13023a12015-01-15 23:19:11 +00001460 printArchiveChild(C, verbose, print_offset);
1461 }
1462}
1463
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001464// ParseInputMachO() parses the named Mach-O file in Filename and handles the
1465// -arch flags selecting just those slices as specified by them and also parses
1466// archive files. Then for each individual Mach-O file ProcessMachO() is
1467// called to process the file based on the command line options.
1468void llvm::ParseInputMachO(StringRef Filename) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001469 // Check for -arch all and verifiy the -arch flags are valid.
1470 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1471 if (ArchFlags[i] == "all") {
1472 ArchAll = true;
1473 } else {
1474 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1475 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1476 "'for the -arch option\n";
1477 return;
1478 }
1479 }
1480 }
1481
1482 // Attempt to open the binary.
1483 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
Davide Italiano3806c5c2016-01-13 02:03:31 +00001484 if (std::error_code EC = BinaryOrErr.getError())
1485 report_error(Filename, EC);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001486 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001487
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001488 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1489 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001490 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001491 printArchiveHeaders(A, !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001492 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
1493 I != E; ++I) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001494 if (std::error_code EC = I->getError())
1495 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001496 auto &C = I->get();
1497 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001498 if (ChildOrErr.getError())
1499 continue;
1500 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1501 if (!checkMachOAndArchFlags(O, Filename))
1502 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001503 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001504 }
1505 }
1506 return;
1507 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001508 if (UniversalHeaders) {
1509 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
Kevin Enderbyf0640752015-03-13 17:56:32 +00001510 printMachOUniversalHeaders(UB, !NonVerbose);
Kevin Enderby131d1772015-01-09 19:22:37 +00001511 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001512 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1513 // If we have a list of architecture flags specified dump only those.
1514 if (!ArchAll && ArchFlags.size() != 0) {
1515 // Look for a slice in the universal binary that matches each ArchFlag.
1516 bool ArchFound;
1517 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1518 ArchFound = false;
1519 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1520 E = UB->end_objects();
1521 I != E; ++I) {
1522 if (ArchFlags[i] == I->getArchTypeName()) {
1523 ArchFound = true;
1524 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
1525 I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001526 std::string ArchitectureName = "";
1527 if (ArchFlags.size() > 1)
1528 ArchitectureName = I->getArchTypeName();
1529 if (ObjOrErr) {
1530 ObjectFile &O = *ObjOrErr.get();
1531 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001532 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001533 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1534 I->getAsArchive()) {
1535 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001536 outs() << "Archive : " << Filename;
1537 if (!ArchitectureName.empty())
1538 outs() << " (architecture " << ArchitectureName << ")";
1539 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001540 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001541 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001542 for (Archive::child_iterator AI = A->child_begin(),
1543 AE = A->child_end();
1544 AI != AE; ++AI) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001545 if (std::error_code EC = AI->getError())
1546 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001547 auto &C = AI->get();
1548 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001549 if (ChildOrErr.getError())
1550 continue;
1551 if (MachOObjectFile *O =
1552 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001553 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001554 }
1555 }
1556 }
1557 }
1558 if (!ArchFound) {
1559 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1560 << "architecture: " + ArchFlags[i] + "\n";
1561 return;
1562 }
1563 }
1564 return;
1565 }
1566 // No architecture flags were specified so if this contains a slice that
1567 // matches the host architecture dump only that.
1568 if (!ArchAll) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001569 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1570 E = UB->end_objects();
1571 I != E; ++I) {
Kevin Enderby0512bd72015-01-09 21:55:03 +00001572 if (MachOObjectFile::getHostArch().getArchName() ==
1573 I->getArchTypeName()) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001574 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001575 std::string ArchiveName;
1576 ArchiveName.clear();
1577 if (ObjOrErr) {
1578 ObjectFile &O = *ObjOrErr.get();
1579 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001580 ProcessMachO(Filename, MachOOF);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001581 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1582 I->getAsArchive()) {
1583 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001584 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001585 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001586 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001587 for (Archive::child_iterator AI = A->child_begin(),
1588 AE = A->child_end();
1589 AI != AE; ++AI) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001590 if (std::error_code EC = AI->getError())
1591 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001592 auto &C = AI->get();
1593 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001594 if (ChildOrErr.getError())
1595 continue;
1596 if (MachOObjectFile *O =
1597 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001598 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001599 }
1600 }
1601 return;
1602 }
1603 }
1604 }
1605 // Either all architectures have been specified or none have been specified
1606 // and this does not contain the host architecture so dump all the slices.
1607 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1608 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1609 E = UB->end_objects();
1610 I != E; ++I) {
1611 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001612 std::string ArchitectureName = "";
1613 if (moreThanOneArch)
1614 ArchitectureName = I->getArchTypeName();
1615 if (ObjOrErr) {
1616 ObjectFile &Obj = *ObjOrErr.get();
1617 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001618 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001619 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
1620 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001621 outs() << "Archive : " << Filename;
1622 if (!ArchitectureName.empty())
1623 outs() << " (architecture " << ArchitectureName << ")";
1624 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001625 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001626 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001627 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
1628 AI != AE; ++AI) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001629 if (std::error_code EC = AI->getError())
1630 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001631 auto &C = AI->get();
1632 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001633 if (ChildOrErr.getError())
1634 continue;
1635 if (MachOObjectFile *O =
1636 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1637 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001638 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1639 ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001640 }
1641 }
1642 }
1643 }
1644 return;
1645 }
1646 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1647 if (!checkMachOAndArchFlags(O, Filename))
1648 return;
1649 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001650 ProcessMachO(Filename, MachOOF);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001651 } else
1652 errs() << "llvm-objdump: '" << Filename << "': "
1653 << "Object is not a Mach-O file type.\n";
Davide Italiano25d84582016-01-13 04:11:36 +00001654 return;
1655 }
1656 llvm_unreachable("Input object can't be invalid at this point");
Rafael Espindola9b709252013-04-13 01:45:40 +00001657}
1658
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001659typedef std::pair<uint64_t, const char *> BindInfoEntry;
1660typedef std::vector<BindInfoEntry> BindTable;
1661typedef BindTable::iterator bind_table_iterator;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001662
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001663// The block of info used by the Symbolizer call backs.
1664struct DisassembleInfo {
1665 bool verbose;
1666 MachOObjectFile *O;
1667 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001668 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001669 std::vector<SectionRef> *Sections;
1670 const char *class_name;
1671 const char *selector_name;
1672 char *method;
Kevin Enderby04bf6932014-10-28 23:39:46 +00001673 char *demangled_name;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001674 uint64_t adrp_addr;
1675 uint32_t adrp_inst;
Kevin Enderby078be602014-10-23 19:53:12 +00001676 BindTable *bindtable;
Kevin Enderbyaac75382015-10-08 16:56:35 +00001677 uint32_t depth;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001678};
1679
1680// SymbolizerGetOpInfo() is the operand information call back function.
1681// This is called to get the symbolic information for operand(s) of an
1682// instruction when it is being done. This routine does this from
1683// the relocation information, symbol table, etc. That block of information
1684// is a pointer to the struct DisassembleInfo that was passed when the
1685// disassembler context was created and passed to back to here when
1686// called back by the disassembler for instruction operands that could have
1687// relocation information. The address of the instruction containing operand is
1688// at the Pc parameter. The immediate value the operand has is passed in
1689// op_info->Value and is at Offset past the start of the instruction and has a
1690// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1691// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1692// names and addends of the symbolic expression to add for the operand. The
1693// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1694// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001695static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1696 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001697 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1698 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001699 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001700
1701 // Make sure all fields returned are zero if we don't set them.
1702 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1703 op_info->Value = value;
1704
1705 // If the TagType is not the value 1 which it code knows about or if no
1706 // verbose symbolic information is wanted then just return 0, indicating no
1707 // information is being returned.
David Blaikie33dd45d02015-03-23 18:39:02 +00001708 if (TagType != 1 || !info->verbose)
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001709 return 0;
1710
1711 unsigned int Arch = info->O->getArch();
1712 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001713 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1714 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001715 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1716 // TODO:
1717 // Search the external relocation entries of a fully linked image
1718 // (if any) for an entry that matches this segment offset.
1719 // uint32_t seg_offset = (Pc + Offset);
1720 return 0;
1721 }
1722 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1723 // for an entry for this section offset.
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001724 uint32_t sect_addr = info->S.getAddress();
1725 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1726 bool reloc_found = false;
1727 DataRefImpl Rel;
1728 MachO::any_relocation_info RE;
1729 bool isExtern = false;
1730 SymbolRef Symbol;
1731 bool r_scattered = false;
1732 uint32_t r_value, pair_r_value, r_type;
1733 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001734 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001735 if (RelocOffset == sect_offset) {
1736 Rel = Reloc.getRawDataRefImpl();
1737 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00001738 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001739 r_scattered = info->O->isRelocationScattered(RE);
1740 if (r_scattered) {
1741 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001742 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1743 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1744 DataRefImpl RelNext = Rel;
1745 info->O->moveRelocationNext(RelNext);
1746 MachO::any_relocation_info RENext;
1747 RENext = info->O->getRelocation(RelNext);
1748 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00001749 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001750 else
1751 return 0;
1752 }
1753 } else {
1754 isExtern = info->O->getPlainRelocationExternal(RE);
1755 if (isExtern) {
1756 symbol_iterator RelocSym = Reloc.getSymbol();
1757 Symbol = *RelocSym;
1758 }
1759 }
1760 reloc_found = true;
1761 break;
1762 }
1763 }
1764 if (reloc_found && isExtern) {
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001765 ErrorOr<StringRef> SymName = Symbol.getName();
1766 if (std::error_code EC = SymName.getError())
1767 report_fatal_error(EC.message());
1768 const char *name = SymName->data();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001769 op_info->AddSymbol.Present = 1;
1770 op_info->AddSymbol.Name = name;
1771 // For i386 extern relocation entries the value in the instruction is
1772 // the offset from the symbol, and value is already set in op_info->Value.
1773 return 1;
1774 }
1775 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1776 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001777 const char *add = GuessSymbolName(r_value, info->AddrMap);
1778 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001779 uint32_t offset = value - (r_value - pair_r_value);
1780 op_info->AddSymbol.Present = 1;
1781 if (add != nullptr)
1782 op_info->AddSymbol.Name = add;
1783 else
1784 op_info->AddSymbol.Value = r_value;
1785 op_info->SubtractSymbol.Present = 1;
1786 if (sub != nullptr)
1787 op_info->SubtractSymbol.Name = sub;
1788 else
1789 op_info->SubtractSymbol.Value = pair_r_value;
1790 op_info->Value = offset;
1791 return 1;
1792 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001793 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001794 }
1795 if (Arch == Triple::x86_64) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001796 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1797 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001798 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1799 // TODO:
1800 // Search the external relocation entries of a fully linked image
1801 // (if any) for an entry that matches this segment offset.
1802 // uint64_t seg_offset = (Pc + Offset);
1803 return 0;
1804 }
1805 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1806 // for an entry for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00001807 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001808 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1809 bool reloc_found = false;
1810 DataRefImpl Rel;
1811 MachO::any_relocation_info RE;
1812 bool isExtern = false;
1813 SymbolRef Symbol;
1814 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001815 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001816 if (RelocOffset == sect_offset) {
1817 Rel = Reloc.getRawDataRefImpl();
1818 RE = info->O->getRelocation(Rel);
1819 // NOTE: Scattered relocations don't exist on x86_64.
1820 isExtern = info->O->getPlainRelocationExternal(RE);
1821 if (isExtern) {
1822 symbol_iterator RelocSym = Reloc.getSymbol();
1823 Symbol = *RelocSym;
1824 }
1825 reloc_found = true;
1826 break;
1827 }
1828 }
1829 if (reloc_found && isExtern) {
1830 // The Value passed in will be adjusted by the Pc if the instruction
1831 // adds the Pc. But for x86_64 external relocation entries the Value
1832 // is the offset from the external symbol.
1833 if (info->O->getAnyRelocationPCRel(RE))
1834 op_info->Value -= Pc + Offset + Size;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001835 ErrorOr<StringRef> SymName = Symbol.getName();
1836 if (std::error_code EC = SymName.getError())
1837 report_fatal_error(EC.message());
1838 const char *name = SymName->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001839 unsigned Type = info->O->getAnyRelocationType(RE);
1840 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1841 DataRefImpl RelNext = Rel;
1842 info->O->moveRelocationNext(RelNext);
1843 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1844 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1845 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1846 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1847 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1848 op_info->SubtractSymbol.Present = 1;
1849 op_info->SubtractSymbol.Name = name;
1850 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1851 Symbol = *RelocSymNext;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001852 ErrorOr<StringRef> SymNameNext = Symbol.getName();
1853 if (std::error_code EC = SymNameNext.getError())
1854 report_fatal_error(EC.message());
1855 name = SymNameNext->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001856 }
1857 }
1858 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1859 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1860 op_info->AddSymbol.Present = 1;
1861 op_info->AddSymbol.Name = name;
1862 return 1;
1863 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001864 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001865 }
1866 if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00001867 if (Offset != 0 || (Size != 4 && Size != 2))
1868 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001869 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1870 // TODO:
1871 // Search the external relocation entries of a fully linked image
1872 // (if any) for an entry that matches this segment offset.
1873 // uint32_t seg_offset = (Pc + Offset);
1874 return 0;
1875 }
1876 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1877 // for an entry for this section offset.
Kevin Enderby930fdc72014-11-06 19:00:13 +00001878 uint32_t sect_addr = info->S.getAddress();
1879 uint32_t sect_offset = (Pc + Offset) - sect_addr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001880 DataRefImpl Rel;
1881 MachO::any_relocation_info RE;
1882 bool isExtern = false;
1883 SymbolRef Symbol;
1884 bool r_scattered = false;
1885 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
David Blaikie33dd45d02015-03-23 18:39:02 +00001886 auto Reloc =
1887 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
1888 [&](const RelocationRef &Reloc) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001889 uint64_t RelocOffset = Reloc.getOffset();
David Blaikie33dd45d02015-03-23 18:39:02 +00001890 return RelocOffset == sect_offset;
1891 });
1892
1893 if (Reloc == info->S.relocations().end())
1894 return 0;
1895
1896 Rel = Reloc->getRawDataRefImpl();
1897 RE = info->O->getRelocation(Rel);
1898 r_length = info->O->getAnyRelocationLength(RE);
1899 r_scattered = info->O->isRelocationScattered(RE);
1900 if (r_scattered) {
1901 r_value = info->O->getScatteredRelocationValue(RE);
1902 r_type = info->O->getScatteredRelocationType(RE);
1903 } else {
1904 r_type = info->O->getAnyRelocationType(RE);
1905 isExtern = info->O->getPlainRelocationExternal(RE);
1906 if (isExtern) {
1907 symbol_iterator RelocSym = Reloc->getSymbol();
1908 Symbol = *RelocSym;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001909 }
1910 }
David Blaikie33dd45d02015-03-23 18:39:02 +00001911 if (r_type == MachO::ARM_RELOC_HALF ||
1912 r_type == MachO::ARM_RELOC_SECTDIFF ||
1913 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1914 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1915 DataRefImpl RelNext = Rel;
1916 info->O->moveRelocationNext(RelNext);
1917 MachO::any_relocation_info RENext;
1918 RENext = info->O->getRelocation(RelNext);
1919 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
1920 if (info->O->isRelocationScattered(RENext))
1921 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1922 }
1923
1924 if (isExtern) {
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001925 ErrorOr<StringRef> SymName = Symbol.getName();
1926 if (std::error_code EC = SymName.getError())
1927 report_fatal_error(EC.message());
1928 const char *name = SymName->data();
Kevin Enderby930fdc72014-11-06 19:00:13 +00001929 op_info->AddSymbol.Present = 1;
1930 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00001931 switch (r_type) {
1932 case MachO::ARM_RELOC_HALF:
1933 if ((r_length & 0x1) == 1) {
1934 op_info->Value = value << 16 | other_half;
1935 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1936 } else {
1937 op_info->Value = other_half << 16 | value;
1938 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00001939 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00001940 break;
1941 default:
1942 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001943 }
1944 return 1;
1945 }
1946 // If we have a branch that is not an external relocation entry then
1947 // return 0 so the code in tryAddingSymbolicOperand() can use the
1948 // SymbolLookUp call back with the branch target address to look up the
1949 // symbol and possiblity add an annotation for a symbol stub.
David Blaikie33dd45d02015-03-23 18:39:02 +00001950 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
1951 r_type == MachO::ARM_THUMB_RELOC_BR22))
Kevin Enderby930fdc72014-11-06 19:00:13 +00001952 return 0;
1953
1954 uint32_t offset = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001955 if (r_type == MachO::ARM_RELOC_HALF ||
1956 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1957 if ((r_length & 0x1) == 1)
1958 value = value << 16 | other_half;
1959 else
1960 value = other_half << 16 | value;
1961 }
1962 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
1963 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
1964 offset = value - r_value;
1965 value = r_value;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001966 }
1967
David Blaikie33dd45d02015-03-23 18:39:02 +00001968 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00001969 if ((r_length & 0x1) == 1)
1970 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1971 else
1972 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001973 const char *add = GuessSymbolName(r_value, info->AddrMap);
1974 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00001975 int32_t offset = value - (r_value - pair_r_value);
1976 op_info->AddSymbol.Present = 1;
1977 if (add != nullptr)
1978 op_info->AddSymbol.Name = add;
1979 else
1980 op_info->AddSymbol.Value = r_value;
1981 op_info->SubtractSymbol.Present = 1;
1982 if (sub != nullptr)
1983 op_info->SubtractSymbol.Name = sub;
1984 else
1985 op_info->SubtractSymbol.Value = pair_r_value;
1986 op_info->Value = offset;
1987 return 1;
1988 }
1989
Kevin Enderby930fdc72014-11-06 19:00:13 +00001990 op_info->AddSymbol.Present = 1;
1991 op_info->Value = offset;
David Blaikie33dd45d02015-03-23 18:39:02 +00001992 if (r_type == MachO::ARM_RELOC_HALF) {
1993 if ((r_length & 0x1) == 1)
1994 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1995 else
1996 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001997 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001998 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00001999 if (add != nullptr) {
2000 op_info->AddSymbol.Name = add;
2001 return 1;
2002 }
2003 op_info->AddSymbol.Value = value;
2004 return 1;
David Blaikie33dd45d02015-03-23 18:39:02 +00002005 }
2006 if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002007 if (Offset != 0 || Size != 4)
2008 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002009 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2010 // TODO:
2011 // Search the external relocation entries of a fully linked image
2012 // (if any) for an entry that matches this segment offset.
2013 // uint64_t seg_offset = (Pc + Offset);
2014 return 0;
2015 }
2016 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2017 // for an entry for this section offset.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002018 uint64_t sect_addr = info->S.getAddress();
2019 uint64_t sect_offset = (Pc + Offset) - sect_addr;
David Blaikie33dd45d02015-03-23 18:39:02 +00002020 auto Reloc =
2021 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
2022 [&](const RelocationRef &Reloc) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002023 uint64_t RelocOffset = Reloc.getOffset();
David Blaikie33dd45d02015-03-23 18:39:02 +00002024 return RelocOffset == sect_offset;
2025 });
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002026
David Blaikie33dd45d02015-03-23 18:39:02 +00002027 if (Reloc == info->S.relocations().end())
2028 return 0;
2029
2030 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2031 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2032 uint32_t r_type = info->O->getAnyRelocationType(RE);
2033 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2034 DataRefImpl RelNext = Rel;
2035 info->O->moveRelocationNext(RelNext);
2036 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2037 if (value == 0) {
2038 value = info->O->getPlainRelocationSymbolNum(RENext);
2039 op_info->Value = value;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002040 }
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002041 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002042 // NOTE: Scattered relocations don't exist on arm64.
2043 if (!info->O->getPlainRelocationExternal(RE))
2044 return 0;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002045 ErrorOr<StringRef> SymName = Reloc->getSymbol()->getName();
2046 if (std::error_code EC = SymName.getError())
2047 report_fatal_error(EC.message());
2048 const char *name = SymName->data();
David Blaikie33dd45d02015-03-23 18:39:02 +00002049 op_info->AddSymbol.Present = 1;
2050 op_info->AddSymbol.Name = name;
2051
2052 switch (r_type) {
2053 case MachO::ARM64_RELOC_PAGE21:
2054 /* @page */
2055 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2056 break;
2057 case MachO::ARM64_RELOC_PAGEOFF12:
2058 /* @pageoff */
2059 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2060 break;
2061 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2062 /* @gotpage */
2063 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2064 break;
2065 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2066 /* @gotpageoff */
2067 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2068 break;
2069 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2070 /* @tvlppage is not implemented in llvm-mc */
2071 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2072 break;
2073 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2074 /* @tvlppageoff is not implemented in llvm-mc */
2075 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2076 break;
2077 default:
2078 case MachO::ARM64_RELOC_BRANCH26:
2079 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2080 break;
2081 }
2082 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002083 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002084 return 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002085}
2086
Kevin Enderbybf246f52014-09-24 23:08:22 +00002087// GuessCstringPointer is passed the address of what might be a pointer to a
2088// literal string in a cstring section. If that address is in a cstring section
2089// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002090static const char *GuessCstringPointer(uint64_t ReferenceValue,
2091 struct DisassembleInfo *info) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002092 for (const auto &Load : info->O->load_commands()) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002093 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2094 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2095 for (unsigned J = 0; J < Seg.nsects; ++J) {
2096 MachO::section_64 Sec = info->O->getSection64(Load, J);
2097 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2098 if (section_type == MachO::S_CSTRING_LITERALS &&
2099 ReferenceValue >= Sec.addr &&
2100 ReferenceValue < Sec.addr + Sec.size) {
2101 uint64_t sect_offset = ReferenceValue - Sec.addr;
2102 uint64_t object_offset = Sec.offset + sect_offset;
2103 StringRef MachOContents = info->O->getData();
2104 uint64_t object_size = MachOContents.size();
2105 const char *object_addr = (const char *)MachOContents.data();
2106 if (object_offset < object_size) {
2107 const char *name = object_addr + object_offset;
2108 return name;
2109 } else {
2110 return nullptr;
2111 }
2112 }
2113 }
2114 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2115 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2116 for (unsigned J = 0; J < Seg.nsects; ++J) {
2117 MachO::section Sec = info->O->getSection(Load, J);
2118 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2119 if (section_type == MachO::S_CSTRING_LITERALS &&
2120 ReferenceValue >= Sec.addr &&
2121 ReferenceValue < Sec.addr + Sec.size) {
2122 uint64_t sect_offset = ReferenceValue - Sec.addr;
2123 uint64_t object_offset = Sec.offset + sect_offset;
2124 StringRef MachOContents = info->O->getData();
2125 uint64_t object_size = MachOContents.size();
2126 const char *object_addr = (const char *)MachOContents.data();
2127 if (object_offset < object_size) {
2128 const char *name = object_addr + object_offset;
2129 return name;
2130 } else {
2131 return nullptr;
2132 }
2133 }
2134 }
2135 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002136 }
2137 return nullptr;
2138}
2139
Kevin Enderby85974882014-09-26 22:20:44 +00002140// GuessIndirectSymbol returns the name of the indirect symbol for the
2141// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2142// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2143// symbol name being referenced by the stub or pointer.
2144static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2145 struct DisassembleInfo *info) {
Kevin Enderby85974882014-09-26 22:20:44 +00002146 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2147 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002148 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby85974882014-09-26 22:20:44 +00002149 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2150 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2151 for (unsigned J = 0; J < Seg.nsects; ++J) {
2152 MachO::section_64 Sec = info->O->getSection64(Load, J);
2153 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2154 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2155 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2156 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2157 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2158 section_type == MachO::S_SYMBOL_STUBS) &&
2159 ReferenceValue >= Sec.addr &&
2160 ReferenceValue < Sec.addr + Sec.size) {
2161 uint32_t stride;
2162 if (section_type == MachO::S_SYMBOL_STUBS)
2163 stride = Sec.reserved2;
2164 else
2165 stride = 8;
2166 if (stride == 0)
2167 return nullptr;
2168 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2169 if (index < Dysymtab.nindirectsyms) {
2170 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002171 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002172 if (indirect_symbol < Symtab.nsyms) {
2173 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2174 SymbolRef Symbol = *Sym;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002175 ErrorOr<StringRef> SymName = Symbol.getName();
2176 if (std::error_code EC = SymName.getError())
2177 report_fatal_error(EC.message());
2178 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002179 return name;
2180 }
2181 }
2182 }
2183 }
2184 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2185 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2186 for (unsigned J = 0; J < Seg.nsects; ++J) {
2187 MachO::section Sec = info->O->getSection(Load, J);
2188 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2189 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2190 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2191 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2192 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2193 section_type == MachO::S_SYMBOL_STUBS) &&
2194 ReferenceValue >= Sec.addr &&
2195 ReferenceValue < Sec.addr + Sec.size) {
2196 uint32_t stride;
2197 if (section_type == MachO::S_SYMBOL_STUBS)
2198 stride = Sec.reserved2;
2199 else
2200 stride = 4;
2201 if (stride == 0)
2202 return nullptr;
2203 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2204 if (index < Dysymtab.nindirectsyms) {
2205 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002206 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002207 if (indirect_symbol < Symtab.nsyms) {
2208 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2209 SymbolRef Symbol = *Sym;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002210 ErrorOr<StringRef> SymName = Symbol.getName();
2211 if (std::error_code EC = SymName.getError())
2212 report_fatal_error(EC.message());
2213 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002214 return name;
2215 }
2216 }
2217 }
2218 }
2219 }
Kevin Enderby85974882014-09-26 22:20:44 +00002220 }
2221 return nullptr;
2222}
2223
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002224// method_reference() is called passing it the ReferenceName that might be
2225// a reference it to an Objective-C method call. If so then it allocates and
2226// assembles a method call string with the values last seen and saved in
2227// the DisassembleInfo's class_name and selector_name fields. This is saved
2228// into the method field of the info and any previous string is free'ed.
2229// Then the class_name field in the info is set to nullptr. The method call
2230// string is set into ReferenceName and ReferenceType is set to
2231// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2232// then both ReferenceType and ReferenceName are left unchanged.
2233static void method_reference(struct DisassembleInfo *info,
2234 uint64_t *ReferenceType,
2235 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002236 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002237 if (*ReferenceName != nullptr) {
2238 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002239 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002240 if (info->method != nullptr)
2241 free(info->method);
2242 if (info->class_name != nullptr) {
2243 info->method = (char *)malloc(5 + strlen(info->class_name) +
2244 strlen(info->selector_name));
2245 if (info->method != nullptr) {
2246 strcpy(info->method, "+[");
2247 strcat(info->method, info->class_name);
2248 strcat(info->method, " ");
2249 strcat(info->method, info->selector_name);
2250 strcat(info->method, "]");
2251 *ReferenceName = info->method;
2252 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2253 }
2254 } else {
2255 info->method = (char *)malloc(9 + strlen(info->selector_name));
2256 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002257 if (Arch == Triple::x86_64)
2258 strcpy(info->method, "-[%rdi ");
2259 else if (Arch == Triple::aarch64)
2260 strcpy(info->method, "-[x0 ");
2261 else
2262 strcpy(info->method, "-[r? ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002263 strcat(info->method, info->selector_name);
2264 strcat(info->method, "]");
2265 *ReferenceName = info->method;
2266 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2267 }
2268 }
2269 info->class_name = nullptr;
2270 }
2271 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002272 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002273 if (info->method != nullptr)
2274 free(info->method);
2275 info->method = (char *)malloc(17 + strlen(info->selector_name));
2276 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002277 if (Arch == Triple::x86_64)
2278 strcpy(info->method, "-[[%rdi super] ");
2279 else if (Arch == Triple::aarch64)
2280 strcpy(info->method, "-[[x0 super] ");
2281 else
2282 strcpy(info->method, "-[[r? super] ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002283 strcat(info->method, info->selector_name);
2284 strcat(info->method, "]");
2285 *ReferenceName = info->method;
2286 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2287 }
2288 info->class_name = nullptr;
2289 }
2290 }
2291 }
2292}
2293
2294// GuessPointerPointer() is passed the address of what might be a pointer to
2295// a reference to an Objective-C class, selector, message ref or cfstring.
2296// If so the value of the pointer is returned and one of the booleans are set
2297// to true. If not zero is returned and all the booleans are set to false.
2298static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2299 struct DisassembleInfo *info,
2300 bool &classref, bool &selref, bool &msgref,
2301 bool &cfstring) {
2302 classref = false;
2303 selref = false;
2304 msgref = false;
2305 cfstring = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002306 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002307 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2308 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2309 for (unsigned J = 0; J < Seg.nsects; ++J) {
2310 MachO::section_64 Sec = info->O->getSection64(Load, J);
2311 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2312 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2313 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2314 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2315 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2316 ReferenceValue >= Sec.addr &&
2317 ReferenceValue < Sec.addr + Sec.size) {
2318 uint64_t sect_offset = ReferenceValue - Sec.addr;
2319 uint64_t object_offset = Sec.offset + sect_offset;
2320 StringRef MachOContents = info->O->getData();
2321 uint64_t object_size = MachOContents.size();
2322 const char *object_addr = (const char *)MachOContents.data();
2323 if (object_offset < object_size) {
2324 uint64_t pointer_value;
2325 memcpy(&pointer_value, object_addr + object_offset,
2326 sizeof(uint64_t));
2327 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2328 sys::swapByteOrder(pointer_value);
2329 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2330 selref = true;
2331 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2332 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2333 classref = true;
2334 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2335 ReferenceValue + 8 < Sec.addr + Sec.size) {
2336 msgref = true;
2337 memcpy(&pointer_value, object_addr + object_offset + 8,
2338 sizeof(uint64_t));
2339 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2340 sys::swapByteOrder(pointer_value);
2341 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2342 cfstring = true;
2343 return pointer_value;
2344 } else {
2345 return 0;
2346 }
2347 }
2348 }
2349 }
2350 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002351 }
2352 return 0;
2353}
2354
2355// get_pointer_64 returns a pointer to the bytes in the object file at the
2356// Address from a section in the Mach-O file. And indirectly returns the
2357// offset into the section, number of bytes left in the section past the offset
2358// and which section is was being referenced. If the Address is not in a
2359// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002360static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2361 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002362 DisassembleInfo *info,
2363 bool objc_only = false) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002364 offset = 0;
2365 left = 0;
2366 S = SectionRef();
2367 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2368 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2369 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
Kevin Enderby46e642f2015-10-08 22:50:55 +00002370 if (SectSize == 0)
2371 continue;
Kevin Enderby846c0002015-04-16 17:19:59 +00002372 if (objc_only) {
2373 StringRef SectName;
2374 ((*(info->Sections))[SectIdx]).getName(SectName);
2375 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2376 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2377 if (SegName != "__OBJC" && SectName != "__cstring")
2378 continue;
2379 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002380 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2381 S = (*(info->Sections))[SectIdx];
2382 offset = Address - SectAddress;
2383 left = SectSize - offset;
2384 StringRef SectContents;
2385 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2386 return SectContents.data() + offset;
2387 }
2388 }
2389 return nullptr;
2390}
2391
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002392static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2393 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002394 DisassembleInfo *info,
2395 bool objc_only = false) {
2396 return get_pointer_64(Address, offset, left, S, info, objc_only);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002397}
2398
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002399// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2400// the symbol indirectly through n_value. Based on the relocation information
2401// for the specified section offset in the specified section reference.
Kevin Enderby0fc11822015-04-01 20:57:01 +00002402// If no relocation information is found and a non-zero ReferenceValue for the
2403// symbol is passed, look up that address in the info's AddrMap.
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00002404static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2405 DisassembleInfo *info, uint64_t &n_value,
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002406 uint64_t ReferenceValue = 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002407 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002408 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002409 return nullptr;
2410
2411 // See if there is an external relocation entry at the sect_offset.
2412 bool reloc_found = false;
2413 DataRefImpl Rel;
2414 MachO::any_relocation_info RE;
2415 bool isExtern = false;
2416 SymbolRef Symbol;
2417 for (const RelocationRef &Reloc : S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002418 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002419 if (RelocOffset == sect_offset) {
2420 Rel = Reloc.getRawDataRefImpl();
2421 RE = info->O->getRelocation(Rel);
2422 if (info->O->isRelocationScattered(RE))
2423 continue;
2424 isExtern = info->O->getPlainRelocationExternal(RE);
2425 if (isExtern) {
2426 symbol_iterator RelocSym = Reloc.getSymbol();
2427 Symbol = *RelocSym;
2428 }
2429 reloc_found = true;
2430 break;
2431 }
2432 }
2433 // If there is an external relocation entry for a symbol in this section
2434 // at this section_offset then use that symbol's value for the n_value
2435 // and return its name.
2436 const char *SymbolName = nullptr;
2437 if (reloc_found && isExtern) {
Rafael Espindoladea00162015-07-03 17:44:18 +00002438 n_value = Symbol.getValue();
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002439 ErrorOr<StringRef> NameOrError = Symbol.getName();
2440 if (std::error_code EC = NameOrError.getError())
2441 report_fatal_error(EC.message());
2442 StringRef Name = *NameOrError;
2443 if (!Name.empty()) {
2444 SymbolName = Name.data();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002445 return SymbolName;
2446 }
2447 }
2448
2449 // TODO: For fully linked images, look through the external relocation
2450 // entries off the dynamic symtab command. For these the r_offset is from the
2451 // start of the first writeable segment in the Mach-O file. So the offset
2452 // to this section from that segment is passed to this routine by the caller,
2453 // as the database_offset. Which is the difference of the section's starting
2454 // address and the first writable segment.
2455 //
2456 // NOTE: need add passing the database_offset to this routine.
2457
Kevin Enderby0fc11822015-04-01 20:57:01 +00002458 // We did not find an external relocation entry so look up the ReferenceValue
2459 // as an address of a symbol and if found return that symbol's name.
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002460 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002461
2462 return SymbolName;
2463}
2464
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002465static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
2466 DisassembleInfo *info,
2467 uint32_t ReferenceValue) {
2468 uint64_t n_value64;
2469 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
2470}
2471
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002472// These are structs in the Objective-C meta data and read to produce the
2473// comments for disassembly. While these are part of the ABI they are no
2474// public defintions. So the are here not in include/llvm/Support/MachO.h .
2475
2476// The cfstring object in a 64-bit Mach-O file.
2477struct cfstring64_t {
2478 uint64_t isa; // class64_t * (64-bit pointer)
2479 uint64_t flags; // flag bits
2480 uint64_t characters; // char * (64-bit pointer)
2481 uint64_t length; // number of non-NULL characters in above
2482};
2483
2484// The class object in a 64-bit Mach-O file.
2485struct class64_t {
2486 uint64_t isa; // class64_t * (64-bit pointer)
2487 uint64_t superclass; // class64_t * (64-bit pointer)
2488 uint64_t cache; // Cache (64-bit pointer)
2489 uint64_t vtable; // IMP * (64-bit pointer)
2490 uint64_t data; // class_ro64_t * (64-bit pointer)
2491};
2492
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002493struct class32_t {
2494 uint32_t isa; /* class32_t * (32-bit pointer) */
2495 uint32_t superclass; /* class32_t * (32-bit pointer) */
2496 uint32_t cache; /* Cache (32-bit pointer) */
2497 uint32_t vtable; /* IMP * (32-bit pointer) */
2498 uint32_t data; /* class_ro32_t * (32-bit pointer) */
2499};
2500
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002501struct class_ro64_t {
2502 uint32_t flags;
2503 uint32_t instanceStart;
2504 uint32_t instanceSize;
2505 uint32_t reserved;
2506 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2507 uint64_t name; // const char * (64-bit pointer)
2508 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2509 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2510 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2511 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2512 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2513};
2514
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002515struct class_ro32_t {
2516 uint32_t flags;
2517 uint32_t instanceStart;
2518 uint32_t instanceSize;
2519 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
2520 uint32_t name; /* const char * (32-bit pointer) */
2521 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
2522 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
2523 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
2524 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
2525 uint32_t baseProperties; /* const struct objc_property_list *
2526 (32-bit pointer) */
2527};
2528
2529/* Values for class_ro{64,32}_t->flags */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002530#define RO_META (1 << 0)
2531#define RO_ROOT (1 << 1)
2532#define RO_HAS_CXX_STRUCTORS (1 << 2)
2533
2534struct method_list64_t {
2535 uint32_t entsize;
2536 uint32_t count;
2537 /* struct method64_t first; These structures follow inline */
2538};
2539
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002540struct method_list32_t {
2541 uint32_t entsize;
2542 uint32_t count;
2543 /* struct method32_t first; These structures follow inline */
2544};
2545
Kevin Enderby0fc11822015-04-01 20:57:01 +00002546struct method64_t {
2547 uint64_t name; /* SEL (64-bit pointer) */
2548 uint64_t types; /* const char * (64-bit pointer) */
2549 uint64_t imp; /* IMP (64-bit pointer) */
2550};
2551
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002552struct method32_t {
2553 uint32_t name; /* SEL (32-bit pointer) */
2554 uint32_t types; /* const char * (32-bit pointer) */
2555 uint32_t imp; /* IMP (32-bit pointer) */
2556};
2557
Kevin Enderby0fc11822015-04-01 20:57:01 +00002558struct protocol_list64_t {
2559 uint64_t count; /* uintptr_t (a 64-bit value) */
2560 /* struct protocol64_t * list[0]; These pointers follow inline */
2561};
2562
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002563struct protocol_list32_t {
2564 uint32_t count; /* uintptr_t (a 32-bit value) */
2565 /* struct protocol32_t * list[0]; These pointers follow inline */
2566};
2567
Kevin Enderby0fc11822015-04-01 20:57:01 +00002568struct protocol64_t {
2569 uint64_t isa; /* id * (64-bit pointer) */
2570 uint64_t name; /* const char * (64-bit pointer) */
2571 uint64_t protocols; /* struct protocol_list64_t *
2572 (64-bit pointer) */
2573 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
2574 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
2575 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
2576 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
2577 uint64_t instanceProperties; /* struct objc_property_list *
2578 (64-bit pointer) */
2579};
2580
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002581struct protocol32_t {
2582 uint32_t isa; /* id * (32-bit pointer) */
2583 uint32_t name; /* const char * (32-bit pointer) */
2584 uint32_t protocols; /* struct protocol_list_t *
2585 (32-bit pointer) */
2586 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
2587 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
2588 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
2589 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
2590 uint32_t instanceProperties; /* struct objc_property_list *
2591 (32-bit pointer) */
2592};
2593
Kevin Enderby0fc11822015-04-01 20:57:01 +00002594struct ivar_list64_t {
2595 uint32_t entsize;
2596 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002597 /* struct ivar64_t first; These structures follow inline */
2598};
2599
2600struct ivar_list32_t {
2601 uint32_t entsize;
2602 uint32_t count;
2603 /* struct ivar32_t first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002604};
2605
2606struct ivar64_t {
2607 uint64_t offset; /* uintptr_t * (64-bit pointer) */
2608 uint64_t name; /* const char * (64-bit pointer) */
2609 uint64_t type; /* const char * (64-bit pointer) */
2610 uint32_t alignment;
2611 uint32_t size;
2612};
2613
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002614struct ivar32_t {
2615 uint32_t offset; /* uintptr_t * (32-bit pointer) */
2616 uint32_t name; /* const char * (32-bit pointer) */
2617 uint32_t type; /* const char * (32-bit pointer) */
2618 uint32_t alignment;
2619 uint32_t size;
2620};
2621
Kevin Enderby0fc11822015-04-01 20:57:01 +00002622struct objc_property_list64 {
2623 uint32_t entsize;
2624 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002625 /* struct objc_property64 first; These structures follow inline */
2626};
2627
2628struct objc_property_list32 {
2629 uint32_t entsize;
2630 uint32_t count;
2631 /* struct objc_property32 first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002632};
2633
2634struct objc_property64 {
2635 uint64_t name; /* const char * (64-bit pointer) */
2636 uint64_t attributes; /* const char * (64-bit pointer) */
2637};
2638
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002639struct objc_property32 {
2640 uint32_t name; /* const char * (32-bit pointer) */
2641 uint32_t attributes; /* const char * (32-bit pointer) */
2642};
2643
Kevin Enderby0fc11822015-04-01 20:57:01 +00002644struct category64_t {
2645 uint64_t name; /* const char * (64-bit pointer) */
2646 uint64_t cls; /* struct class_t * (64-bit pointer) */
2647 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
2648 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
2649 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
2650 uint64_t instanceProperties; /* struct objc_property_list *
2651 (64-bit pointer) */
2652};
2653
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002654struct category32_t {
2655 uint32_t name; /* const char * (32-bit pointer) */
2656 uint32_t cls; /* struct class_t * (32-bit pointer) */
2657 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
2658 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
2659 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
2660 uint32_t instanceProperties; /* struct objc_property_list *
2661 (32-bit pointer) */
2662};
2663
Kevin Enderby0fc11822015-04-01 20:57:01 +00002664struct objc_image_info64 {
2665 uint32_t version;
2666 uint32_t flags;
2667};
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002668struct objc_image_info32 {
2669 uint32_t version;
2670 uint32_t flags;
2671};
Kevin Enderby846c0002015-04-16 17:19:59 +00002672struct imageInfo_t {
2673 uint32_t version;
2674 uint32_t flags;
2675};
Kevin Enderby0fc11822015-04-01 20:57:01 +00002676/* masks for objc_image_info.flags */
2677#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
2678#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
2679
2680struct message_ref64 {
2681 uint64_t imp; /* IMP (64-bit pointer) */
2682 uint64_t sel; /* SEL (64-bit pointer) */
2683};
2684
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002685struct message_ref32 {
2686 uint32_t imp; /* IMP (32-bit pointer) */
2687 uint32_t sel; /* SEL (32-bit pointer) */
2688};
2689
Kevin Enderby846c0002015-04-16 17:19:59 +00002690// Objective-C 1 (32-bit only) meta data structs.
2691
2692struct objc_module_t {
2693 uint32_t version;
2694 uint32_t size;
2695 uint32_t name; /* char * (32-bit pointer) */
2696 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
2697};
2698
2699struct objc_symtab_t {
2700 uint32_t sel_ref_cnt;
2701 uint32_t refs; /* SEL * (32-bit pointer) */
2702 uint16_t cls_def_cnt;
2703 uint16_t cat_def_cnt;
2704 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
2705};
2706
2707struct objc_class_t {
2708 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2709 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
2710 uint32_t name; /* const char * (32-bit pointer) */
2711 int32_t version;
2712 int32_t info;
2713 int32_t instance_size;
2714 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
2715 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
2716 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
2717 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
2718};
2719
2720#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
2721// class is not a metaclass
2722#define CLS_CLASS 0x1
2723// class is a metaclass
2724#define CLS_META 0x2
2725
2726struct objc_category_t {
2727 uint32_t category_name; /* char * (32-bit pointer) */
2728 uint32_t class_name; /* char * (32-bit pointer) */
2729 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
2730 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
2731 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
2732};
2733
2734struct objc_ivar_t {
2735 uint32_t ivar_name; /* char * (32-bit pointer) */
2736 uint32_t ivar_type; /* char * (32-bit pointer) */
2737 int32_t ivar_offset;
2738};
2739
2740struct objc_ivar_list_t {
2741 int32_t ivar_count;
2742 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
2743};
2744
2745struct objc_method_list_t {
2746 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
2747 int32_t method_count;
2748 // struct objc_method_t method_list[1]; /* variable length structure */
2749};
2750
2751struct objc_method_t {
2752 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2753 uint32_t method_types; /* char * (32-bit pointer) */
2754 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
2755 (32-bit pointer) */
2756};
2757
2758struct objc_protocol_list_t {
2759 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
2760 int32_t count;
2761 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
2762 // (32-bit pointer) */
2763};
2764
2765struct objc_protocol_t {
2766 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2767 uint32_t protocol_name; /* char * (32-bit pointer) */
2768 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
2769 uint32_t instance_methods; /* struct objc_method_description_list *
2770 (32-bit pointer) */
2771 uint32_t class_methods; /* struct objc_method_description_list *
2772 (32-bit pointer) */
2773};
2774
2775struct objc_method_description_list_t {
2776 int32_t count;
2777 // struct objc_method_description_t list[1];
2778};
2779
2780struct objc_method_description_t {
2781 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2782 uint32_t types; /* char * (32-bit pointer) */
2783};
2784
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002785inline void swapStruct(struct cfstring64_t &cfs) {
2786 sys::swapByteOrder(cfs.isa);
2787 sys::swapByteOrder(cfs.flags);
2788 sys::swapByteOrder(cfs.characters);
2789 sys::swapByteOrder(cfs.length);
2790}
2791
2792inline void swapStruct(struct class64_t &c) {
2793 sys::swapByteOrder(c.isa);
2794 sys::swapByteOrder(c.superclass);
2795 sys::swapByteOrder(c.cache);
2796 sys::swapByteOrder(c.vtable);
2797 sys::swapByteOrder(c.data);
2798}
2799
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002800inline void swapStruct(struct class32_t &c) {
2801 sys::swapByteOrder(c.isa);
2802 sys::swapByteOrder(c.superclass);
2803 sys::swapByteOrder(c.cache);
2804 sys::swapByteOrder(c.vtable);
2805 sys::swapByteOrder(c.data);
2806}
2807
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002808inline void swapStruct(struct class_ro64_t &cro) {
2809 sys::swapByteOrder(cro.flags);
2810 sys::swapByteOrder(cro.instanceStart);
2811 sys::swapByteOrder(cro.instanceSize);
2812 sys::swapByteOrder(cro.reserved);
2813 sys::swapByteOrder(cro.ivarLayout);
2814 sys::swapByteOrder(cro.name);
2815 sys::swapByteOrder(cro.baseMethods);
2816 sys::swapByteOrder(cro.baseProtocols);
2817 sys::swapByteOrder(cro.ivars);
2818 sys::swapByteOrder(cro.weakIvarLayout);
2819 sys::swapByteOrder(cro.baseProperties);
2820}
2821
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002822inline void swapStruct(struct class_ro32_t &cro) {
2823 sys::swapByteOrder(cro.flags);
2824 sys::swapByteOrder(cro.instanceStart);
2825 sys::swapByteOrder(cro.instanceSize);
2826 sys::swapByteOrder(cro.ivarLayout);
2827 sys::swapByteOrder(cro.name);
2828 sys::swapByteOrder(cro.baseMethods);
2829 sys::swapByteOrder(cro.baseProtocols);
2830 sys::swapByteOrder(cro.ivars);
2831 sys::swapByteOrder(cro.weakIvarLayout);
2832 sys::swapByteOrder(cro.baseProperties);
2833}
2834
Kevin Enderby0fc11822015-04-01 20:57:01 +00002835inline void swapStruct(struct method_list64_t &ml) {
2836 sys::swapByteOrder(ml.entsize);
2837 sys::swapByteOrder(ml.count);
2838}
2839
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002840inline void swapStruct(struct method_list32_t &ml) {
2841 sys::swapByteOrder(ml.entsize);
2842 sys::swapByteOrder(ml.count);
2843}
2844
Kevin Enderby0fc11822015-04-01 20:57:01 +00002845inline void swapStruct(struct method64_t &m) {
2846 sys::swapByteOrder(m.name);
2847 sys::swapByteOrder(m.types);
2848 sys::swapByteOrder(m.imp);
2849}
2850
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002851inline void swapStruct(struct method32_t &m) {
2852 sys::swapByteOrder(m.name);
2853 sys::swapByteOrder(m.types);
2854 sys::swapByteOrder(m.imp);
2855}
2856
Kevin Enderby0fc11822015-04-01 20:57:01 +00002857inline void swapStruct(struct protocol_list64_t &pl) {
2858 sys::swapByteOrder(pl.count);
2859}
2860
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002861inline void swapStruct(struct protocol_list32_t &pl) {
2862 sys::swapByteOrder(pl.count);
2863}
2864
Kevin Enderby0fc11822015-04-01 20:57:01 +00002865inline void swapStruct(struct protocol64_t &p) {
2866 sys::swapByteOrder(p.isa);
2867 sys::swapByteOrder(p.name);
2868 sys::swapByteOrder(p.protocols);
2869 sys::swapByteOrder(p.instanceMethods);
2870 sys::swapByteOrder(p.classMethods);
2871 sys::swapByteOrder(p.optionalInstanceMethods);
2872 sys::swapByteOrder(p.optionalClassMethods);
2873 sys::swapByteOrder(p.instanceProperties);
2874}
2875
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002876inline void swapStruct(struct protocol32_t &p) {
2877 sys::swapByteOrder(p.isa);
2878 sys::swapByteOrder(p.name);
2879 sys::swapByteOrder(p.protocols);
2880 sys::swapByteOrder(p.instanceMethods);
2881 sys::swapByteOrder(p.classMethods);
2882 sys::swapByteOrder(p.optionalInstanceMethods);
2883 sys::swapByteOrder(p.optionalClassMethods);
2884 sys::swapByteOrder(p.instanceProperties);
2885}
2886
Kevin Enderby0fc11822015-04-01 20:57:01 +00002887inline void swapStruct(struct ivar_list64_t &il) {
2888 sys::swapByteOrder(il.entsize);
2889 sys::swapByteOrder(il.count);
2890}
2891
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002892inline void swapStruct(struct ivar_list32_t &il) {
2893 sys::swapByteOrder(il.entsize);
2894 sys::swapByteOrder(il.count);
2895}
2896
Kevin Enderby0fc11822015-04-01 20:57:01 +00002897inline void swapStruct(struct ivar64_t &i) {
2898 sys::swapByteOrder(i.offset);
2899 sys::swapByteOrder(i.name);
2900 sys::swapByteOrder(i.type);
2901 sys::swapByteOrder(i.alignment);
2902 sys::swapByteOrder(i.size);
2903}
2904
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002905inline void swapStruct(struct ivar32_t &i) {
2906 sys::swapByteOrder(i.offset);
2907 sys::swapByteOrder(i.name);
2908 sys::swapByteOrder(i.type);
2909 sys::swapByteOrder(i.alignment);
2910 sys::swapByteOrder(i.size);
2911}
2912
Kevin Enderby0fc11822015-04-01 20:57:01 +00002913inline void swapStruct(struct objc_property_list64 &pl) {
2914 sys::swapByteOrder(pl.entsize);
2915 sys::swapByteOrder(pl.count);
2916}
2917
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002918inline void swapStruct(struct objc_property_list32 &pl) {
2919 sys::swapByteOrder(pl.entsize);
2920 sys::swapByteOrder(pl.count);
2921}
2922
Kevin Enderby0fc11822015-04-01 20:57:01 +00002923inline void swapStruct(struct objc_property64 &op) {
2924 sys::swapByteOrder(op.name);
2925 sys::swapByteOrder(op.attributes);
2926}
2927
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002928inline void swapStruct(struct objc_property32 &op) {
2929 sys::swapByteOrder(op.name);
2930 sys::swapByteOrder(op.attributes);
2931}
2932
Kevin Enderby0fc11822015-04-01 20:57:01 +00002933inline void swapStruct(struct category64_t &c) {
2934 sys::swapByteOrder(c.name);
2935 sys::swapByteOrder(c.cls);
2936 sys::swapByteOrder(c.instanceMethods);
2937 sys::swapByteOrder(c.classMethods);
2938 sys::swapByteOrder(c.protocols);
2939 sys::swapByteOrder(c.instanceProperties);
2940}
2941
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002942inline void swapStruct(struct category32_t &c) {
2943 sys::swapByteOrder(c.name);
2944 sys::swapByteOrder(c.cls);
2945 sys::swapByteOrder(c.instanceMethods);
2946 sys::swapByteOrder(c.classMethods);
2947 sys::swapByteOrder(c.protocols);
2948 sys::swapByteOrder(c.instanceProperties);
2949}
2950
Kevin Enderby0fc11822015-04-01 20:57:01 +00002951inline void swapStruct(struct objc_image_info64 &o) {
2952 sys::swapByteOrder(o.version);
2953 sys::swapByteOrder(o.flags);
2954}
2955
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002956inline void swapStruct(struct objc_image_info32 &o) {
2957 sys::swapByteOrder(o.version);
2958 sys::swapByteOrder(o.flags);
2959}
2960
Kevin Enderby846c0002015-04-16 17:19:59 +00002961inline void swapStruct(struct imageInfo_t &o) {
2962 sys::swapByteOrder(o.version);
2963 sys::swapByteOrder(o.flags);
2964}
2965
Kevin Enderby0fc11822015-04-01 20:57:01 +00002966inline void swapStruct(struct message_ref64 &mr) {
2967 sys::swapByteOrder(mr.imp);
2968 sys::swapByteOrder(mr.sel);
2969}
2970
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002971inline void swapStruct(struct message_ref32 &mr) {
2972 sys::swapByteOrder(mr.imp);
2973 sys::swapByteOrder(mr.sel);
2974}
2975
Kevin Enderby846c0002015-04-16 17:19:59 +00002976inline void swapStruct(struct objc_module_t &module) {
2977 sys::swapByteOrder(module.version);
2978 sys::swapByteOrder(module.size);
2979 sys::swapByteOrder(module.name);
2980 sys::swapByteOrder(module.symtab);
Jingyue Wufedecc42015-04-16 18:43:44 +00002981}
Kevin Enderby846c0002015-04-16 17:19:59 +00002982
2983inline void swapStruct(struct objc_symtab_t &symtab) {
2984 sys::swapByteOrder(symtab.sel_ref_cnt);
2985 sys::swapByteOrder(symtab.refs);
2986 sys::swapByteOrder(symtab.cls_def_cnt);
2987 sys::swapByteOrder(symtab.cat_def_cnt);
Jingyue Wufedecc42015-04-16 18:43:44 +00002988}
Kevin Enderby846c0002015-04-16 17:19:59 +00002989
2990inline void swapStruct(struct objc_class_t &objc_class) {
2991 sys::swapByteOrder(objc_class.isa);
2992 sys::swapByteOrder(objc_class.super_class);
2993 sys::swapByteOrder(objc_class.name);
2994 sys::swapByteOrder(objc_class.version);
2995 sys::swapByteOrder(objc_class.info);
2996 sys::swapByteOrder(objc_class.instance_size);
2997 sys::swapByteOrder(objc_class.ivars);
2998 sys::swapByteOrder(objc_class.methodLists);
2999 sys::swapByteOrder(objc_class.cache);
3000 sys::swapByteOrder(objc_class.protocols);
Jingyue Wufedecc42015-04-16 18:43:44 +00003001}
Kevin Enderby846c0002015-04-16 17:19:59 +00003002
3003inline void swapStruct(struct objc_category_t &objc_category) {
3004 sys::swapByteOrder(objc_category.category_name);
3005 sys::swapByteOrder(objc_category.class_name);
3006 sys::swapByteOrder(objc_category.instance_methods);
3007 sys::swapByteOrder(objc_category.class_methods);
3008 sys::swapByteOrder(objc_category.protocols);
3009}
3010
3011inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3012 sys::swapByteOrder(objc_ivar_list.ivar_count);
3013}
3014
3015inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3016 sys::swapByteOrder(objc_ivar.ivar_name);
3017 sys::swapByteOrder(objc_ivar.ivar_type);
3018 sys::swapByteOrder(objc_ivar.ivar_offset);
Jingyue Wufedecc42015-04-16 18:43:44 +00003019}
Kevin Enderby846c0002015-04-16 17:19:59 +00003020
3021inline void swapStruct(struct objc_method_list_t &method_list) {
3022 sys::swapByteOrder(method_list.obsolete);
3023 sys::swapByteOrder(method_list.method_count);
3024}
3025
3026inline void swapStruct(struct objc_method_t &method) {
3027 sys::swapByteOrder(method.method_name);
3028 sys::swapByteOrder(method.method_types);
3029 sys::swapByteOrder(method.method_imp);
3030}
3031
3032inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3033 sys::swapByteOrder(protocol_list.next);
3034 sys::swapByteOrder(protocol_list.count);
3035}
3036
3037inline void swapStruct(struct objc_protocol_t &protocol) {
3038 sys::swapByteOrder(protocol.isa);
3039 sys::swapByteOrder(protocol.protocol_name);
3040 sys::swapByteOrder(protocol.protocol_list);
3041 sys::swapByteOrder(protocol.instance_methods);
3042 sys::swapByteOrder(protocol.class_methods);
3043}
3044
3045inline void swapStruct(struct objc_method_description_list_t &mdl) {
3046 sys::swapByteOrder(mdl.count);
3047}
3048
3049inline void swapStruct(struct objc_method_description_t &md) {
3050 sys::swapByteOrder(md.name);
3051 sys::swapByteOrder(md.types);
3052}
3053
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003054static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3055 struct DisassembleInfo *info);
3056
3057// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3058// to an Objective-C class and returns the class name. It is also passed the
3059// address of the pointer, so when the pointer is zero as it can be in an .o
3060// file, that is used to look for an external relocation entry with a symbol
3061// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003062static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3063 uint64_t ReferenceValue,
3064 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003065 const char *r;
3066 uint32_t offset, left;
3067 SectionRef S;
3068
3069 // The pointer_value can be 0 in an object file and have a relocation
3070 // entry for the class symbol at the ReferenceValue (the address of the
3071 // pointer).
3072 if (pointer_value == 0) {
3073 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3074 if (r == nullptr || left < sizeof(uint64_t))
3075 return nullptr;
3076 uint64_t n_value;
3077 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3078 if (symbol_name == nullptr)
3079 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00003080 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003081 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3082 return class_name + 2;
3083 else
3084 return nullptr;
3085 }
3086
3087 // The case were the pointer_value is non-zero and points to a class defined
3088 // in this Mach-O file.
3089 r = get_pointer_64(pointer_value, offset, left, S, info);
3090 if (r == nullptr || left < sizeof(struct class64_t))
3091 return nullptr;
3092 struct class64_t c;
3093 memcpy(&c, r, sizeof(struct class64_t));
3094 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3095 swapStruct(c);
3096 if (c.data == 0)
3097 return nullptr;
3098 r = get_pointer_64(c.data, offset, left, S, info);
3099 if (r == nullptr || left < sizeof(struct class_ro64_t))
3100 return nullptr;
3101 struct class_ro64_t cro;
3102 memcpy(&cro, r, sizeof(struct class_ro64_t));
3103 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3104 swapStruct(cro);
3105 if (cro.name == 0)
3106 return nullptr;
3107 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3108 return name;
3109}
3110
3111// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3112// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003113static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3114 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003115 const char *r, *name;
3116 uint32_t offset, left;
3117 SectionRef S;
3118 struct cfstring64_t cfs;
3119 uint64_t cfs_characters;
3120
3121 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3122 if (r == nullptr || left < sizeof(struct cfstring64_t))
3123 return nullptr;
3124 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3125 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3126 swapStruct(cfs);
3127 if (cfs.characters == 0) {
3128 uint64_t n_value;
3129 const char *symbol_name = get_symbol_64(
3130 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3131 if (symbol_name == nullptr)
3132 return nullptr;
3133 cfs_characters = n_value;
3134 } else
3135 cfs_characters = cfs.characters;
3136 name = get_pointer_64(cfs_characters, offset, left, S, info);
3137
3138 return name;
3139}
3140
3141// get_objc2_64bit_selref() is used for disassembly and is passed a the address
3142// of a pointer to an Objective-C selector reference when the pointer value is
3143// zero as in a .o file and is likely to have a external relocation entry with
3144// who's symbol's n_value is the real pointer to the selector name. If that is
3145// the case the real pointer to the selector name is returned else 0 is
3146// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003147static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3148 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003149 uint32_t offset, left;
3150 SectionRef S;
3151
3152 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3153 if (r == nullptr || left < sizeof(uint64_t))
3154 return 0;
3155 uint64_t n_value;
3156 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3157 if (symbol_name == nullptr)
3158 return 0;
3159 return n_value;
3160}
3161
Kevin Enderby0fc11822015-04-01 20:57:01 +00003162static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3163 const char *sectname) {
3164 for (const SectionRef &Section : O->sections()) {
3165 StringRef SectName;
3166 Section.getName(SectName);
3167 DataRefImpl Ref = Section.getRawDataRefImpl();
3168 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3169 if (SegName == segname && SectName == sectname)
3170 return Section;
3171 }
3172 return SectionRef();
3173}
3174
3175static void
3176walk_pointer_list_64(const char *listname, const SectionRef S,
3177 MachOObjectFile *O, struct DisassembleInfo *info,
3178 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3179 if (S == SectionRef())
3180 return;
3181
3182 StringRef SectName;
3183 S.getName(SectName);
3184 DataRefImpl Ref = S.getRawDataRefImpl();
3185 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3186 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3187
3188 StringRef BytesStr;
3189 S.getContents(BytesStr);
3190 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3191
3192 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3193 uint32_t left = S.getSize() - i;
3194 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3195 uint64_t p = 0;
3196 memcpy(&p, Contents + i, size);
3197 if (i + sizeof(uint64_t) > S.getSize())
3198 outs() << listname << " list pointer extends past end of (" << SegName
3199 << "," << SectName << ") section\n";
3200 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3201
3202 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3203 sys::swapByteOrder(p);
3204
3205 uint64_t n_value = 0;
3206 const char *name = get_symbol_64(i, S, info, n_value, p);
3207 if (name == nullptr)
3208 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3209
3210 if (n_value != 0) {
3211 outs() << format("0x%" PRIx64, n_value);
3212 if (p != 0)
3213 outs() << " + " << format("0x%" PRIx64, p);
3214 } else
3215 outs() << format("0x%" PRIx64, p);
3216 if (name != nullptr)
3217 outs() << " " << name;
3218 outs() << "\n";
3219
3220 p += n_value;
3221 if (func)
3222 func(p, info);
3223 }
3224}
3225
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003226static void
3227walk_pointer_list_32(const char *listname, const SectionRef S,
3228 MachOObjectFile *O, struct DisassembleInfo *info,
3229 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3230 if (S == SectionRef())
3231 return;
3232
3233 StringRef SectName;
3234 S.getName(SectName);
3235 DataRefImpl Ref = S.getRawDataRefImpl();
3236 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3237 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3238
3239 StringRef BytesStr;
3240 S.getContents(BytesStr);
3241 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3242
3243 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3244 uint32_t left = S.getSize() - i;
3245 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3246 uint32_t p = 0;
3247 memcpy(&p, Contents + i, size);
3248 if (i + sizeof(uint32_t) > S.getSize())
3249 outs() << listname << " list pointer extends past end of (" << SegName
3250 << "," << SectName << ") section\n";
Kevin Enderbycf261312015-04-06 22:33:43 +00003251 uint32_t Address = S.getAddress() + i;
3252 outs() << format("%08" PRIx32, Address) << " ";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003253
3254 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3255 sys::swapByteOrder(p);
3256 outs() << format("0x%" PRIx32, p);
3257
3258 const char *name = get_symbol_32(i, S, info, p);
3259 if (name != nullptr)
3260 outs() << " " << name;
3261 outs() << "\n";
3262
3263 if (func)
3264 func(p, info);
3265 }
3266}
3267
3268static void print_layout_map(const char *layout_map, uint32_t left) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003269 if (layout_map == nullptr)
3270 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003271 outs() << " layout map: ";
3272 do {
3273 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3274 left--;
3275 layout_map++;
3276 } while (*layout_map != '\0' && left != 0);
3277 outs() << "\n";
3278}
3279
Kevin Enderby0fc11822015-04-01 20:57:01 +00003280static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3281 uint32_t offset, left;
3282 SectionRef S;
3283 const char *layout_map;
3284
3285 if (p == 0)
3286 return;
3287 layout_map = get_pointer_64(p, offset, left, S, info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003288 print_layout_map(layout_map, left);
3289}
3290
3291static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3292 uint32_t offset, left;
3293 SectionRef S;
3294 const char *layout_map;
3295
3296 if (p == 0)
3297 return;
3298 layout_map = get_pointer_32(p, offset, left, S, info);
3299 print_layout_map(layout_map, left);
Kevin Enderby0fc11822015-04-01 20:57:01 +00003300}
3301
3302static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3303 const char *indent) {
3304 struct method_list64_t ml;
3305 struct method64_t m;
3306 const char *r;
3307 uint32_t offset, xoffset, left, i;
3308 SectionRef S, xS;
3309 const char *name, *sym_name;
3310 uint64_t n_value;
3311
3312 r = get_pointer_64(p, offset, left, S, info);
3313 if (r == nullptr)
3314 return;
3315 memset(&ml, '\0', sizeof(struct method_list64_t));
3316 if (left < sizeof(struct method_list64_t)) {
3317 memcpy(&ml, r, left);
3318 outs() << " (method_list_t entends past the end of the section)\n";
3319 } else
3320 memcpy(&ml, r, sizeof(struct method_list64_t));
3321 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3322 swapStruct(ml);
3323 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3324 outs() << indent << "\t\t count " << ml.count << "\n";
3325
3326 p += sizeof(struct method_list64_t);
3327 offset += sizeof(struct method_list64_t);
3328 for (i = 0; i < ml.count; i++) {
3329 r = get_pointer_64(p, offset, left, S, info);
3330 if (r == nullptr)
3331 return;
3332 memset(&m, '\0', sizeof(struct method64_t));
3333 if (left < sizeof(struct method64_t)) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003334 memcpy(&m, r, left);
3335 outs() << indent << " (method_t extends past the end of the section)\n";
Kevin Enderby0fc11822015-04-01 20:57:01 +00003336 } else
3337 memcpy(&m, r, sizeof(struct method64_t));
3338 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3339 swapStruct(m);
3340
3341 outs() << indent << "\t\t name ";
3342 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3343 info, n_value, m.name);
3344 if (n_value != 0) {
3345 if (info->verbose && sym_name != nullptr)
3346 outs() << sym_name;
3347 else
3348 outs() << format("0x%" PRIx64, n_value);
3349 if (m.name != 0)
3350 outs() << " + " << format("0x%" PRIx64, m.name);
3351 } else
3352 outs() << format("0x%" PRIx64, m.name);
3353 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3354 if (name != nullptr)
3355 outs() << format(" %.*s", left, name);
3356 outs() << "\n";
3357
3358 outs() << indent << "\t\t types ";
3359 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3360 info, n_value, m.types);
3361 if (n_value != 0) {
3362 if (info->verbose && sym_name != nullptr)
3363 outs() << sym_name;
3364 else
3365 outs() << format("0x%" PRIx64, n_value);
3366 if (m.types != 0)
3367 outs() << " + " << format("0x%" PRIx64, m.types);
3368 } else
3369 outs() << format("0x%" PRIx64, m.types);
3370 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3371 if (name != nullptr)
3372 outs() << format(" %.*s", left, name);
3373 outs() << "\n";
3374
3375 outs() << indent << "\t\t imp ";
3376 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3377 n_value, m.imp);
3378 if (info->verbose && name == nullptr) {
3379 if (n_value != 0) {
3380 outs() << format("0x%" PRIx64, n_value) << " ";
3381 if (m.imp != 0)
3382 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3383 } else
3384 outs() << format("0x%" PRIx64, m.imp) << " ";
3385 }
3386 if (name != nullptr)
3387 outs() << name;
3388 outs() << "\n";
3389
3390 p += sizeof(struct method64_t);
3391 offset += sizeof(struct method64_t);
3392 }
3393}
3394
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003395static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3396 const char *indent) {
3397 struct method_list32_t ml;
3398 struct method32_t m;
Kevin Enderby846c0002015-04-16 17:19:59 +00003399 const char *r, *name;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003400 uint32_t offset, xoffset, left, i;
3401 SectionRef S, xS;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003402
3403 r = get_pointer_32(p, offset, left, S, info);
3404 if (r == nullptr)
3405 return;
3406 memset(&ml, '\0', sizeof(struct method_list32_t));
3407 if (left < sizeof(struct method_list32_t)) {
3408 memcpy(&ml, r, left);
3409 outs() << " (method_list_t entends past the end of the section)\n";
3410 } else
3411 memcpy(&ml, r, sizeof(struct method_list32_t));
3412 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3413 swapStruct(ml);
3414 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3415 outs() << indent << "\t\t count " << ml.count << "\n";
3416
3417 p += sizeof(struct method_list32_t);
3418 offset += sizeof(struct method_list32_t);
3419 for (i = 0; i < ml.count; i++) {
3420 r = get_pointer_32(p, offset, left, S, info);
3421 if (r == nullptr)
3422 return;
3423 memset(&m, '\0', sizeof(struct method32_t));
3424 if (left < sizeof(struct method32_t)) {
3425 memcpy(&ml, r, left);
3426 outs() << indent << " (method_t entends past the end of the section)\n";
3427 } else
3428 memcpy(&m, r, sizeof(struct method32_t));
3429 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3430 swapStruct(m);
3431
3432 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
3433 name = get_pointer_32(m.name, xoffset, left, xS, info);
3434 if (name != nullptr)
3435 outs() << format(" %.*s", left, name);
3436 outs() << "\n";
3437
3438 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
3439 name = get_pointer_32(m.types, xoffset, left, xS, info);
3440 if (name != nullptr)
3441 outs() << format(" %.*s", left, name);
3442 outs() << "\n";
3443
3444 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
3445 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
3446 m.imp);
3447 if (name != nullptr)
3448 outs() << " " << name;
3449 outs() << "\n";
3450
3451 p += sizeof(struct method32_t);
3452 offset += sizeof(struct method32_t);
3453 }
3454}
3455
Kevin Enderby846c0002015-04-16 17:19:59 +00003456static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
3457 uint32_t offset, left, xleft;
3458 SectionRef S;
3459 struct objc_method_list_t method_list;
3460 struct objc_method_t method;
3461 const char *r, *methods, *name, *SymbolName;
3462 int32_t i;
3463
3464 r = get_pointer_32(p, offset, left, S, info, true);
3465 if (r == nullptr)
3466 return true;
3467
3468 outs() << "\n";
3469 if (left > sizeof(struct objc_method_list_t)) {
3470 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
3471 } else {
3472 outs() << "\t\t objc_method_list extends past end of the section\n";
3473 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
3474 memcpy(&method_list, r, left);
3475 }
3476 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3477 swapStruct(method_list);
3478
3479 outs() << "\t\t obsolete "
3480 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
3481 outs() << "\t\t method_count " << method_list.method_count << "\n";
3482
3483 methods = r + sizeof(struct objc_method_list_t);
3484 for (i = 0; i < method_list.method_count; i++) {
3485 if ((i + 1) * sizeof(struct objc_method_t) > left) {
3486 outs() << "\t\t remaining method's extend past the of the section\n";
3487 break;
3488 }
3489 memcpy(&method, methods + i * sizeof(struct objc_method_t),
3490 sizeof(struct objc_method_t));
3491 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3492 swapStruct(method);
3493
3494 outs() << "\t\t method_name "
3495 << format("0x%08" PRIx32, method.method_name);
3496 if (info->verbose) {
3497 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
3498 if (name != nullptr)
3499 outs() << format(" %.*s", xleft, name);
3500 else
3501 outs() << " (not in an __OBJC section)";
3502 }
3503 outs() << "\n";
3504
3505 outs() << "\t\t method_types "
3506 << format("0x%08" PRIx32, method.method_types);
3507 if (info->verbose) {
3508 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
3509 if (name != nullptr)
3510 outs() << format(" %.*s", xleft, name);
3511 else
3512 outs() << " (not in an __OBJC section)";
3513 }
3514 outs() << "\n";
3515
3516 outs() << "\t\t method_imp "
3517 << format("0x%08" PRIx32, method.method_imp) << " ";
3518 if (info->verbose) {
3519 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
3520 if (SymbolName != nullptr)
3521 outs() << SymbolName;
3522 }
3523 outs() << "\n";
3524 }
3525 return false;
3526}
3527
Kevin Enderby0fc11822015-04-01 20:57:01 +00003528static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
3529 struct protocol_list64_t pl;
3530 uint64_t q, n_value;
3531 struct protocol64_t pc;
3532 const char *r;
3533 uint32_t offset, xoffset, left, i;
3534 SectionRef S, xS;
3535 const char *name, *sym_name;
3536
3537 r = get_pointer_64(p, offset, left, S, info);
3538 if (r == nullptr)
3539 return;
3540 memset(&pl, '\0', sizeof(struct protocol_list64_t));
3541 if (left < sizeof(struct protocol_list64_t)) {
3542 memcpy(&pl, r, left);
3543 outs() << " (protocol_list_t entends past the end of the section)\n";
3544 } else
3545 memcpy(&pl, r, sizeof(struct protocol_list64_t));
3546 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3547 swapStruct(pl);
3548 outs() << " count " << pl.count << "\n";
3549
3550 p += sizeof(struct protocol_list64_t);
3551 offset += sizeof(struct protocol_list64_t);
3552 for (i = 0; i < pl.count; i++) {
3553 r = get_pointer_64(p, offset, left, S, info);
3554 if (r == nullptr)
3555 return;
3556 q = 0;
3557 if (left < sizeof(uint64_t)) {
3558 memcpy(&q, r, left);
3559 outs() << " (protocol_t * entends past the end of the section)\n";
3560 } else
3561 memcpy(&q, r, sizeof(uint64_t));
3562 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3563 sys::swapByteOrder(q);
3564
3565 outs() << "\t\t list[" << i << "] ";
3566 sym_name = get_symbol_64(offset, S, info, n_value, q);
3567 if (n_value != 0) {
3568 if (info->verbose && sym_name != nullptr)
3569 outs() << sym_name;
3570 else
3571 outs() << format("0x%" PRIx64, n_value);
3572 if (q != 0)
3573 outs() << " + " << format("0x%" PRIx64, q);
3574 } else
3575 outs() << format("0x%" PRIx64, q);
3576 outs() << " (struct protocol_t *)\n";
3577
3578 r = get_pointer_64(q + n_value, offset, left, S, info);
3579 if (r == nullptr)
3580 return;
3581 memset(&pc, '\0', sizeof(struct protocol64_t));
3582 if (left < sizeof(struct protocol64_t)) {
3583 memcpy(&pc, r, left);
3584 outs() << " (protocol_t entends past the end of the section)\n";
3585 } else
3586 memcpy(&pc, r, sizeof(struct protocol64_t));
3587 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3588 swapStruct(pc);
3589
3590 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
3591
3592 outs() << "\t\t\t name ";
3593 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
3594 info, n_value, pc.name);
3595 if (n_value != 0) {
3596 if (info->verbose && sym_name != nullptr)
3597 outs() << sym_name;
3598 else
3599 outs() << format("0x%" PRIx64, n_value);
3600 if (pc.name != 0)
3601 outs() << " + " << format("0x%" PRIx64, pc.name);
3602 } else
3603 outs() << format("0x%" PRIx64, pc.name);
3604 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
3605 if (name != nullptr)
3606 outs() << format(" %.*s", left, name);
3607 outs() << "\n";
3608
3609 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
3610
3611 outs() << "\t\t instanceMethods ";
3612 sym_name =
3613 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
3614 S, info, n_value, pc.instanceMethods);
3615 if (n_value != 0) {
3616 if (info->verbose && sym_name != nullptr)
3617 outs() << sym_name;
3618 else
3619 outs() << format("0x%" PRIx64, n_value);
3620 if (pc.instanceMethods != 0)
3621 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
3622 } else
3623 outs() << format("0x%" PRIx64, pc.instanceMethods);
3624 outs() << " (struct method_list_t *)\n";
3625 if (pc.instanceMethods + n_value != 0)
3626 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
3627
3628 outs() << "\t\t classMethods ";
3629 sym_name =
3630 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
3631 info, n_value, pc.classMethods);
3632 if (n_value != 0) {
3633 if (info->verbose && sym_name != nullptr)
3634 outs() << sym_name;
3635 else
3636 outs() << format("0x%" PRIx64, n_value);
3637 if (pc.classMethods != 0)
3638 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
3639 } else
3640 outs() << format("0x%" PRIx64, pc.classMethods);
3641 outs() << " (struct method_list_t *)\n";
3642 if (pc.classMethods + n_value != 0)
3643 print_method_list64_t(pc.classMethods + n_value, info, "\t");
3644
3645 outs() << "\t optionalInstanceMethods "
3646 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
3647 outs() << "\t optionalClassMethods "
3648 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
3649 outs() << "\t instanceProperties "
3650 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
3651
3652 p += sizeof(uint64_t);
3653 offset += sizeof(uint64_t);
3654 }
3655}
3656
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003657static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
3658 struct protocol_list32_t pl;
3659 uint32_t q;
3660 struct protocol32_t pc;
3661 const char *r;
3662 uint32_t offset, xoffset, left, i;
3663 SectionRef S, xS;
3664 const char *name;
3665
3666 r = get_pointer_32(p, offset, left, S, info);
3667 if (r == nullptr)
3668 return;
3669 memset(&pl, '\0', sizeof(struct protocol_list32_t));
3670 if (left < sizeof(struct protocol_list32_t)) {
3671 memcpy(&pl, r, left);
3672 outs() << " (protocol_list_t entends past the end of the section)\n";
3673 } else
3674 memcpy(&pl, r, sizeof(struct protocol_list32_t));
3675 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3676 swapStruct(pl);
3677 outs() << " count " << pl.count << "\n";
3678
3679 p += sizeof(struct protocol_list32_t);
3680 offset += sizeof(struct protocol_list32_t);
3681 for (i = 0; i < pl.count; i++) {
3682 r = get_pointer_32(p, offset, left, S, info);
3683 if (r == nullptr)
3684 return;
3685 q = 0;
3686 if (left < sizeof(uint32_t)) {
3687 memcpy(&q, r, left);
3688 outs() << " (protocol_t * entends past the end of the section)\n";
3689 } else
3690 memcpy(&q, r, sizeof(uint32_t));
3691 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3692 sys::swapByteOrder(q);
3693 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
3694 << " (struct protocol_t *)\n";
3695 r = get_pointer_32(q, offset, left, S, info);
3696 if (r == nullptr)
3697 return;
3698 memset(&pc, '\0', sizeof(struct protocol32_t));
3699 if (left < sizeof(struct protocol32_t)) {
3700 memcpy(&pc, r, left);
3701 outs() << " (protocol_t entends past the end of the section)\n";
3702 } else
3703 memcpy(&pc, r, sizeof(struct protocol32_t));
3704 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3705 swapStruct(pc);
3706 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
3707 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
3708 name = get_pointer_32(pc.name, xoffset, left, xS, info);
3709 if (name != nullptr)
3710 outs() << format(" %.*s", left, name);
3711 outs() << "\n";
3712 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
3713 outs() << "\t\t instanceMethods "
3714 << format("0x%" PRIx32, pc.instanceMethods)
3715 << " (struct method_list_t *)\n";
3716 if (pc.instanceMethods != 0)
3717 print_method_list32_t(pc.instanceMethods, info, "\t");
3718 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
3719 << " (struct method_list_t *)\n";
3720 if (pc.classMethods != 0)
3721 print_method_list32_t(pc.classMethods, info, "\t");
3722 outs() << "\t optionalInstanceMethods "
3723 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
3724 outs() << "\t optionalClassMethods "
3725 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
3726 outs() << "\t instanceProperties "
3727 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
3728 p += sizeof(uint32_t);
3729 offset += sizeof(uint32_t);
3730 }
3731}
3732
Kevin Enderby846c0002015-04-16 17:19:59 +00003733static void print_indent(uint32_t indent) {
3734 for (uint32_t i = 0; i < indent;) {
3735 if (indent - i >= 8) {
3736 outs() << "\t";
3737 i += 8;
3738 } else {
3739 for (uint32_t j = i; j < indent; j++)
3740 outs() << " ";
3741 return;
3742 }
3743 }
3744}
3745
3746static bool print_method_description_list(uint32_t p, uint32_t indent,
3747 struct DisassembleInfo *info) {
3748 uint32_t offset, left, xleft;
3749 SectionRef S;
3750 struct objc_method_description_list_t mdl;
3751 struct objc_method_description_t md;
3752 const char *r, *list, *name;
3753 int32_t i;
3754
3755 r = get_pointer_32(p, offset, left, S, info, true);
3756 if (r == nullptr)
3757 return true;
3758
3759 outs() << "\n";
3760 if (left > sizeof(struct objc_method_description_list_t)) {
3761 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
3762 } else {
3763 print_indent(indent);
3764 outs() << " objc_method_description_list extends past end of the section\n";
3765 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
3766 memcpy(&mdl, r, left);
3767 }
3768 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3769 swapStruct(mdl);
3770
3771 print_indent(indent);
3772 outs() << " count " << mdl.count << "\n";
3773
3774 list = r + sizeof(struct objc_method_description_list_t);
3775 for (i = 0; i < mdl.count; i++) {
3776 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
3777 print_indent(indent);
3778 outs() << " remaining list entries extend past the of the section\n";
3779 break;
3780 }
3781 print_indent(indent);
3782 outs() << " list[" << i << "]\n";
3783 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
3784 sizeof(struct objc_method_description_t));
3785 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3786 swapStruct(md);
3787
3788 print_indent(indent);
3789 outs() << " name " << format("0x%08" PRIx32, md.name);
3790 if (info->verbose) {
3791 name = get_pointer_32(md.name, offset, xleft, S, info, true);
3792 if (name != nullptr)
3793 outs() << format(" %.*s", xleft, name);
3794 else
3795 outs() << " (not in an __OBJC section)";
3796 }
3797 outs() << "\n";
3798
3799 print_indent(indent);
3800 outs() << " types " << format("0x%08" PRIx32, md.types);
3801 if (info->verbose) {
3802 name = get_pointer_32(md.types, offset, xleft, S, info, true);
3803 if (name != nullptr)
3804 outs() << format(" %.*s", xleft, name);
3805 else
3806 outs() << " (not in an __OBJC section)";
3807 }
3808 outs() << "\n";
3809 }
3810 return false;
3811}
3812
3813static bool print_protocol_list(uint32_t p, uint32_t indent,
3814 struct DisassembleInfo *info);
3815
3816static bool print_protocol(uint32_t p, uint32_t indent,
3817 struct DisassembleInfo *info) {
3818 uint32_t offset, left;
3819 SectionRef S;
3820 struct objc_protocol_t protocol;
3821 const char *r, *name;
3822
3823 r = get_pointer_32(p, offset, left, S, info, true);
3824 if (r == nullptr)
3825 return true;
3826
3827 outs() << "\n";
3828 if (left >= sizeof(struct objc_protocol_t)) {
3829 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
3830 } else {
3831 print_indent(indent);
3832 outs() << " Protocol extends past end of the section\n";
3833 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
3834 memcpy(&protocol, r, left);
3835 }
3836 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3837 swapStruct(protocol);
3838
3839 print_indent(indent);
3840 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
3841 << "\n";
3842
3843 print_indent(indent);
3844 outs() << " protocol_name "
3845 << format("0x%08" PRIx32, protocol.protocol_name);
3846 if (info->verbose) {
3847 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
3848 if (name != nullptr)
3849 outs() << format(" %.*s", left, name);
3850 else
3851 outs() << " (not in an __OBJC section)";
3852 }
3853 outs() << "\n";
3854
3855 print_indent(indent);
3856 outs() << " protocol_list "
3857 << format("0x%08" PRIx32, protocol.protocol_list);
3858 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
3859 outs() << " (not in an __OBJC section)\n";
3860
3861 print_indent(indent);
3862 outs() << " instance_methods "
3863 << format("0x%08" PRIx32, protocol.instance_methods);
3864 if (print_method_description_list(protocol.instance_methods, indent, info))
3865 outs() << " (not in an __OBJC section)\n";
3866
3867 print_indent(indent);
3868 outs() << " class_methods "
3869 << format("0x%08" PRIx32, protocol.class_methods);
3870 if (print_method_description_list(protocol.class_methods, indent, info))
3871 outs() << " (not in an __OBJC section)\n";
3872
3873 return false;
3874}
3875
3876static bool print_protocol_list(uint32_t p, uint32_t indent,
3877 struct DisassembleInfo *info) {
3878 uint32_t offset, left, l;
3879 SectionRef S;
3880 struct objc_protocol_list_t protocol_list;
3881 const char *r, *list;
3882 int32_t i;
3883
3884 r = get_pointer_32(p, offset, left, S, info, true);
3885 if (r == nullptr)
3886 return true;
3887
3888 outs() << "\n";
3889 if (left > sizeof(struct objc_protocol_list_t)) {
3890 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
3891 } else {
3892 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
3893 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
3894 memcpy(&protocol_list, r, left);
3895 }
3896 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3897 swapStruct(protocol_list);
3898
3899 print_indent(indent);
3900 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
3901 << "\n";
3902 print_indent(indent);
3903 outs() << " count " << protocol_list.count << "\n";
3904
3905 list = r + sizeof(struct objc_protocol_list_t);
3906 for (i = 0; i < protocol_list.count; i++) {
3907 if ((i + 1) * sizeof(uint32_t) > left) {
3908 outs() << "\t\t remaining list entries extend past the of the section\n";
3909 break;
3910 }
3911 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
3912 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3913 sys::swapByteOrder(l);
3914
3915 print_indent(indent);
3916 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
3917 if (print_protocol(l, indent, info))
3918 outs() << "(not in an __OBJC section)\n";
3919 }
3920 return false;
3921}
3922
Kevin Enderby0fc11822015-04-01 20:57:01 +00003923static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
3924 struct ivar_list64_t il;
3925 struct ivar64_t i;
3926 const char *r;
3927 uint32_t offset, xoffset, left, j;
3928 SectionRef S, xS;
3929 const char *name, *sym_name, *ivar_offset_p;
3930 uint64_t ivar_offset, n_value;
3931
3932 r = get_pointer_64(p, offset, left, S, info);
3933 if (r == nullptr)
3934 return;
3935 memset(&il, '\0', sizeof(struct ivar_list64_t));
3936 if (left < sizeof(struct ivar_list64_t)) {
3937 memcpy(&il, r, left);
3938 outs() << " (ivar_list_t entends past the end of the section)\n";
3939 } else
3940 memcpy(&il, r, sizeof(struct ivar_list64_t));
3941 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3942 swapStruct(il);
3943 outs() << " entsize " << il.entsize << "\n";
3944 outs() << " count " << il.count << "\n";
3945
3946 p += sizeof(struct ivar_list64_t);
3947 offset += sizeof(struct ivar_list64_t);
3948 for (j = 0; j < il.count; j++) {
3949 r = get_pointer_64(p, offset, left, S, info);
3950 if (r == nullptr)
3951 return;
3952 memset(&i, '\0', sizeof(struct ivar64_t));
3953 if (left < sizeof(struct ivar64_t)) {
3954 memcpy(&i, r, left);
3955 outs() << " (ivar_t entends past the end of the section)\n";
3956 } else
3957 memcpy(&i, r, sizeof(struct ivar64_t));
3958 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3959 swapStruct(i);
3960
3961 outs() << "\t\t\t offset ";
3962 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
3963 info, n_value, i.offset);
3964 if (n_value != 0) {
3965 if (info->verbose && sym_name != nullptr)
3966 outs() << sym_name;
3967 else
3968 outs() << format("0x%" PRIx64, n_value);
3969 if (i.offset != 0)
3970 outs() << " + " << format("0x%" PRIx64, i.offset);
3971 } else
3972 outs() << format("0x%" PRIx64, i.offset);
3973 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
3974 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
3975 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
3976 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3977 sys::swapByteOrder(ivar_offset);
3978 outs() << " " << ivar_offset << "\n";
3979 } else
3980 outs() << "\n";
3981
3982 outs() << "\t\t\t name ";
3983 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
3984 n_value, i.name);
3985 if (n_value != 0) {
3986 if (info->verbose && sym_name != nullptr)
3987 outs() << sym_name;
3988 else
3989 outs() << format("0x%" PRIx64, n_value);
3990 if (i.name != 0)
3991 outs() << " + " << format("0x%" PRIx64, i.name);
3992 } else
3993 outs() << format("0x%" PRIx64, i.name);
3994 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
3995 if (name != nullptr)
3996 outs() << format(" %.*s", left, name);
3997 outs() << "\n";
3998
3999 outs() << "\t\t\t type ";
4000 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4001 n_value, i.name);
4002 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4003 if (n_value != 0) {
4004 if (info->verbose && sym_name != nullptr)
4005 outs() << sym_name;
4006 else
4007 outs() << format("0x%" PRIx64, n_value);
4008 if (i.type != 0)
4009 outs() << " + " << format("0x%" PRIx64, i.type);
4010 } else
4011 outs() << format("0x%" PRIx64, i.type);
4012 if (name != nullptr)
4013 outs() << format(" %.*s", left, name);
4014 outs() << "\n";
4015
4016 outs() << "\t\t\talignment " << i.alignment << "\n";
4017 outs() << "\t\t\t size " << i.size << "\n";
4018
4019 p += sizeof(struct ivar64_t);
4020 offset += sizeof(struct ivar64_t);
4021 }
4022}
4023
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004024static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4025 struct ivar_list32_t il;
4026 struct ivar32_t i;
4027 const char *r;
4028 uint32_t offset, xoffset, left, j;
4029 SectionRef S, xS;
4030 const char *name, *ivar_offset_p;
4031 uint32_t ivar_offset;
4032
4033 r = get_pointer_32(p, offset, left, S, info);
4034 if (r == nullptr)
4035 return;
4036 memset(&il, '\0', sizeof(struct ivar_list32_t));
4037 if (left < sizeof(struct ivar_list32_t)) {
4038 memcpy(&il, r, left);
4039 outs() << " (ivar_list_t entends past the end of the section)\n";
4040 } else
4041 memcpy(&il, r, sizeof(struct ivar_list32_t));
4042 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4043 swapStruct(il);
4044 outs() << " entsize " << il.entsize << "\n";
4045 outs() << " count " << il.count << "\n";
4046
4047 p += sizeof(struct ivar_list32_t);
4048 offset += sizeof(struct ivar_list32_t);
4049 for (j = 0; j < il.count; j++) {
4050 r = get_pointer_32(p, offset, left, S, info);
4051 if (r == nullptr)
4052 return;
4053 memset(&i, '\0', sizeof(struct ivar32_t));
4054 if (left < sizeof(struct ivar32_t)) {
4055 memcpy(&i, r, left);
4056 outs() << " (ivar_t entends past the end of the section)\n";
4057 } else
4058 memcpy(&i, r, sizeof(struct ivar32_t));
4059 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4060 swapStruct(i);
4061
4062 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4063 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4064 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4065 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4066 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4067 sys::swapByteOrder(ivar_offset);
4068 outs() << " " << ivar_offset << "\n";
4069 } else
4070 outs() << "\n";
4071
4072 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4073 name = get_pointer_32(i.name, xoffset, left, xS, info);
4074 if (name != nullptr)
4075 outs() << format(" %.*s", left, name);
4076 outs() << "\n";
4077
4078 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4079 name = get_pointer_32(i.type, xoffset, left, xS, info);
4080 if (name != nullptr)
4081 outs() << format(" %.*s", left, name);
4082 outs() << "\n";
4083
4084 outs() << "\t\t\talignment " << i.alignment << "\n";
4085 outs() << "\t\t\t size " << i.size << "\n";
4086
4087 p += sizeof(struct ivar32_t);
4088 offset += sizeof(struct ivar32_t);
4089 }
4090}
4091
Kevin Enderby0fc11822015-04-01 20:57:01 +00004092static void print_objc_property_list64(uint64_t p,
4093 struct DisassembleInfo *info) {
4094 struct objc_property_list64 opl;
4095 struct objc_property64 op;
4096 const char *r;
4097 uint32_t offset, xoffset, left, j;
4098 SectionRef S, xS;
4099 const char *name, *sym_name;
4100 uint64_t n_value;
4101
4102 r = get_pointer_64(p, offset, left, S, info);
4103 if (r == nullptr)
4104 return;
4105 memset(&opl, '\0', sizeof(struct objc_property_list64));
4106 if (left < sizeof(struct objc_property_list64)) {
4107 memcpy(&opl, r, left);
4108 outs() << " (objc_property_list entends past the end of the section)\n";
4109 } else
4110 memcpy(&opl, r, sizeof(struct objc_property_list64));
4111 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4112 swapStruct(opl);
4113 outs() << " entsize " << opl.entsize << "\n";
4114 outs() << " count " << opl.count << "\n";
4115
4116 p += sizeof(struct objc_property_list64);
4117 offset += sizeof(struct objc_property_list64);
4118 for (j = 0; j < opl.count; j++) {
4119 r = get_pointer_64(p, offset, left, S, info);
4120 if (r == nullptr)
4121 return;
4122 memset(&op, '\0', sizeof(struct objc_property64));
4123 if (left < sizeof(struct objc_property64)) {
4124 memcpy(&op, r, left);
4125 outs() << " (objc_property entends past the end of the section)\n";
4126 } else
4127 memcpy(&op, r, sizeof(struct objc_property64));
4128 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4129 swapStruct(op);
4130
4131 outs() << "\t\t\t name ";
4132 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4133 info, n_value, op.name);
4134 if (n_value != 0) {
4135 if (info->verbose && sym_name != nullptr)
4136 outs() << sym_name;
4137 else
4138 outs() << format("0x%" PRIx64, n_value);
4139 if (op.name != 0)
4140 outs() << " + " << format("0x%" PRIx64, op.name);
4141 } else
4142 outs() << format("0x%" PRIx64, op.name);
4143 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4144 if (name != nullptr)
4145 outs() << format(" %.*s", left, name);
4146 outs() << "\n";
4147
4148 outs() << "\t\t\tattributes ";
4149 sym_name =
4150 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4151 info, n_value, op.attributes);
4152 if (n_value != 0) {
4153 if (info->verbose && sym_name != nullptr)
4154 outs() << sym_name;
4155 else
4156 outs() << format("0x%" PRIx64, n_value);
4157 if (op.attributes != 0)
4158 outs() << " + " << format("0x%" PRIx64, op.attributes);
4159 } else
4160 outs() << format("0x%" PRIx64, op.attributes);
4161 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4162 if (name != nullptr)
4163 outs() << format(" %.*s", left, name);
4164 outs() << "\n";
4165
4166 p += sizeof(struct objc_property64);
4167 offset += sizeof(struct objc_property64);
4168 }
4169}
4170
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004171static void print_objc_property_list32(uint32_t p,
4172 struct DisassembleInfo *info) {
4173 struct objc_property_list32 opl;
4174 struct objc_property32 op;
4175 const char *r;
4176 uint32_t offset, xoffset, left, j;
4177 SectionRef S, xS;
4178 const char *name;
4179
4180 r = get_pointer_32(p, offset, left, S, info);
4181 if (r == nullptr)
4182 return;
4183 memset(&opl, '\0', sizeof(struct objc_property_list32));
4184 if (left < sizeof(struct objc_property_list32)) {
4185 memcpy(&opl, r, left);
4186 outs() << " (objc_property_list entends past the end of the section)\n";
4187 } else
4188 memcpy(&opl, r, sizeof(struct objc_property_list32));
4189 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4190 swapStruct(opl);
4191 outs() << " entsize " << opl.entsize << "\n";
4192 outs() << " count " << opl.count << "\n";
4193
4194 p += sizeof(struct objc_property_list32);
4195 offset += sizeof(struct objc_property_list32);
4196 for (j = 0; j < opl.count; j++) {
4197 r = get_pointer_32(p, offset, left, S, info);
4198 if (r == nullptr)
4199 return;
4200 memset(&op, '\0', sizeof(struct objc_property32));
4201 if (left < sizeof(struct objc_property32)) {
4202 memcpy(&op, r, left);
4203 outs() << " (objc_property entends past the end of the section)\n";
4204 } else
4205 memcpy(&op, r, sizeof(struct objc_property32));
4206 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4207 swapStruct(op);
4208
4209 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4210 name = get_pointer_32(op.name, xoffset, left, xS, info);
4211 if (name != nullptr)
4212 outs() << format(" %.*s", left, name);
4213 outs() << "\n";
4214
4215 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4216 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4217 if (name != nullptr)
4218 outs() << format(" %.*s", left, name);
4219 outs() << "\n";
4220
4221 p += sizeof(struct objc_property32);
4222 offset += sizeof(struct objc_property32);
4223 }
4224}
4225
Richard Smith81ff44d2015-10-09 22:09:56 +00004226static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
Kevin Enderby0fc11822015-04-01 20:57:01 +00004227 bool &is_meta_class) {
4228 struct class_ro64_t cro;
4229 const char *r;
4230 uint32_t offset, xoffset, left;
4231 SectionRef S, xS;
4232 const char *name, *sym_name;
4233 uint64_t n_value;
4234
4235 r = get_pointer_64(p, offset, left, S, info);
4236 if (r == nullptr || left < sizeof(struct class_ro64_t))
Richard Smith81ff44d2015-10-09 22:09:56 +00004237 return false;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004238 memset(&cro, '\0', sizeof(struct class_ro64_t));
4239 if (left < sizeof(struct class_ro64_t)) {
4240 memcpy(&cro, r, left);
4241 outs() << " (class_ro_t entends past the end of the section)\n";
4242 } else
4243 memcpy(&cro, r, sizeof(struct class_ro64_t));
4244 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4245 swapStruct(cro);
4246 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4247 if (cro.flags & RO_META)
4248 outs() << " RO_META";
4249 if (cro.flags & RO_ROOT)
4250 outs() << " RO_ROOT";
4251 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4252 outs() << " RO_HAS_CXX_STRUCTORS";
4253 outs() << "\n";
4254 outs() << " instanceStart " << cro.instanceStart << "\n";
4255 outs() << " instanceSize " << cro.instanceSize << "\n";
4256 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4257 << "\n";
4258 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4259 << "\n";
4260 print_layout_map64(cro.ivarLayout, info);
4261
4262 outs() << " name ";
4263 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4264 info, n_value, cro.name);
4265 if (n_value != 0) {
4266 if (info->verbose && sym_name != nullptr)
4267 outs() << sym_name;
4268 else
4269 outs() << format("0x%" PRIx64, n_value);
4270 if (cro.name != 0)
4271 outs() << " + " << format("0x%" PRIx64, cro.name);
4272 } else
4273 outs() << format("0x%" PRIx64, cro.name);
4274 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4275 if (name != nullptr)
4276 outs() << format(" %.*s", left, name);
4277 outs() << "\n";
4278
4279 outs() << " baseMethods ";
4280 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4281 S, info, n_value, cro.baseMethods);
4282 if (n_value != 0) {
4283 if (info->verbose && sym_name != nullptr)
4284 outs() << sym_name;
4285 else
4286 outs() << format("0x%" PRIx64, n_value);
4287 if (cro.baseMethods != 0)
4288 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4289 } else
4290 outs() << format("0x%" PRIx64, cro.baseMethods);
4291 outs() << " (struct method_list_t *)\n";
4292 if (cro.baseMethods + n_value != 0)
4293 print_method_list64_t(cro.baseMethods + n_value, info, "");
4294
4295 outs() << " baseProtocols ";
4296 sym_name =
4297 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4298 info, n_value, cro.baseProtocols);
4299 if (n_value != 0) {
4300 if (info->verbose && sym_name != nullptr)
4301 outs() << sym_name;
4302 else
4303 outs() << format("0x%" PRIx64, n_value);
4304 if (cro.baseProtocols != 0)
4305 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4306 } else
4307 outs() << format("0x%" PRIx64, cro.baseProtocols);
4308 outs() << "\n";
4309 if (cro.baseProtocols + n_value != 0)
4310 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4311
4312 outs() << " ivars ";
4313 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004314 info, n_value, cro.ivars);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004315 if (n_value != 0) {
4316 if (info->verbose && sym_name != nullptr)
4317 outs() << sym_name;
4318 else
4319 outs() << format("0x%" PRIx64, n_value);
4320 if (cro.ivars != 0)
4321 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4322 } else
4323 outs() << format("0x%" PRIx64, cro.ivars);
4324 outs() << "\n";
4325 if (cro.ivars + n_value != 0)
4326 print_ivar_list64_t(cro.ivars + n_value, info);
4327
4328 outs() << " weakIvarLayout ";
4329 sym_name =
4330 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4331 info, n_value, cro.weakIvarLayout);
4332 if (n_value != 0) {
4333 if (info->verbose && sym_name != nullptr)
4334 outs() << sym_name;
4335 else
4336 outs() << format("0x%" PRIx64, n_value);
4337 if (cro.weakIvarLayout != 0)
4338 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4339 } else
4340 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4341 outs() << "\n";
4342 print_layout_map64(cro.weakIvarLayout + n_value, info);
4343
4344 outs() << " baseProperties ";
4345 sym_name =
4346 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4347 info, n_value, cro.baseProperties);
4348 if (n_value != 0) {
4349 if (info->verbose && sym_name != nullptr)
4350 outs() << sym_name;
4351 else
4352 outs() << format("0x%" PRIx64, n_value);
4353 if (cro.baseProperties != 0)
4354 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4355 } else
4356 outs() << format("0x%" PRIx64, cro.baseProperties);
4357 outs() << "\n";
4358 if (cro.baseProperties + n_value != 0)
4359 print_objc_property_list64(cro.baseProperties + n_value, info);
4360
Rafael Espindolab9091322015-10-24 23:19:10 +00004361 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004362 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004363}
4364
Richard Smith81ff44d2015-10-09 22:09:56 +00004365static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004366 bool &is_meta_class) {
4367 struct class_ro32_t cro;
4368 const char *r;
4369 uint32_t offset, xoffset, left;
4370 SectionRef S, xS;
4371 const char *name;
4372
4373 r = get_pointer_32(p, offset, left, S, info);
4374 if (r == nullptr)
Richard Smith81ff44d2015-10-09 22:09:56 +00004375 return false;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004376 memset(&cro, '\0', sizeof(struct class_ro32_t));
4377 if (left < sizeof(struct class_ro32_t)) {
4378 memcpy(&cro, r, left);
4379 outs() << " (class_ro_t entends past the end of the section)\n";
4380 } else
4381 memcpy(&cro, r, sizeof(struct class_ro32_t));
4382 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4383 swapStruct(cro);
4384 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4385 if (cro.flags & RO_META)
4386 outs() << " RO_META";
4387 if (cro.flags & RO_ROOT)
4388 outs() << " RO_ROOT";
4389 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4390 outs() << " RO_HAS_CXX_STRUCTORS";
4391 outs() << "\n";
4392 outs() << " instanceStart " << cro.instanceStart << "\n";
4393 outs() << " instanceSize " << cro.instanceSize << "\n";
4394 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4395 << "\n";
4396 print_layout_map32(cro.ivarLayout, info);
4397
4398 outs() << " name " << format("0x%" PRIx32, cro.name);
4399 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4400 if (name != nullptr)
4401 outs() << format(" %.*s", left, name);
4402 outs() << "\n";
4403
4404 outs() << " baseMethods "
4405 << format("0x%" PRIx32, cro.baseMethods)
4406 << " (struct method_list_t *)\n";
4407 if (cro.baseMethods != 0)
4408 print_method_list32_t(cro.baseMethods, info, "");
4409
4410 outs() << " baseProtocols "
4411 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4412 if (cro.baseProtocols != 0)
4413 print_protocol_list32_t(cro.baseProtocols, info);
4414 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4415 << "\n";
4416 if (cro.ivars != 0)
4417 print_ivar_list32_t(cro.ivars, info);
4418 outs() << " weakIvarLayout "
4419 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4420 print_layout_map32(cro.weakIvarLayout, info);
4421 outs() << " baseProperties "
4422 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4423 if (cro.baseProperties != 0)
4424 print_objc_property_list32(cro.baseProperties, info);
Rafael Espindolab9091322015-10-24 23:19:10 +00004425 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004426 return true;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004427}
4428
Kevin Enderby0fc11822015-04-01 20:57:01 +00004429static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4430 struct class64_t c;
4431 const char *r;
4432 uint32_t offset, left;
4433 SectionRef S;
4434 const char *name;
4435 uint64_t isa_n_value, n_value;
4436
4437 r = get_pointer_64(p, offset, left, S, info);
4438 if (r == nullptr || left < sizeof(struct class64_t))
4439 return;
4440 memset(&c, '\0', sizeof(struct class64_t));
4441 if (left < sizeof(struct class64_t)) {
4442 memcpy(&c, r, left);
4443 outs() << " (class_t entends past the end of the section)\n";
4444 } else
4445 memcpy(&c, r, sizeof(struct class64_t));
4446 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4447 swapStruct(c);
4448
4449 outs() << " isa " << format("0x%" PRIx64, c.isa);
4450 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
4451 isa_n_value, c.isa);
4452 if (name != nullptr)
4453 outs() << " " << name;
4454 outs() << "\n";
4455
4456 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
4457 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
4458 n_value, c.superclass);
4459 if (name != nullptr)
4460 outs() << " " << name;
4461 outs() << "\n";
4462
4463 outs() << " cache " << format("0x%" PRIx64, c.cache);
4464 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
4465 n_value, c.cache);
4466 if (name != nullptr)
4467 outs() << " " << name;
4468 outs() << "\n";
4469
4470 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
4471 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
4472 n_value, c.vtable);
4473 if (name != nullptr)
4474 outs() << " " << name;
4475 outs() << "\n";
4476
4477 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
4478 n_value, c.data);
4479 outs() << " data ";
4480 if (n_value != 0) {
4481 if (info->verbose && name != nullptr)
4482 outs() << name;
4483 else
4484 outs() << format("0x%" PRIx64, n_value);
4485 if (c.data != 0)
4486 outs() << " + " << format("0x%" PRIx64, c.data);
4487 } else
4488 outs() << format("0x%" PRIx64, c.data);
4489 outs() << " (struct class_ro_t *)";
4490
4491 // This is a Swift class if some of the low bits of the pointer are set.
4492 if ((c.data + n_value) & 0x7)
4493 outs() << " Swift class";
4494 outs() << "\n";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004495 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004496 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
4497 return;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004498
Kevin Enderbyaac75382015-10-08 16:56:35 +00004499 if (!is_meta_class &&
4500 c.isa + isa_n_value != p &&
4501 c.isa + isa_n_value != 0 &&
4502 info->depth < 100) {
4503 info->depth++;
4504 outs() << "Meta Class\n";
4505 print_class64_t(c.isa + isa_n_value, info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004506 }
4507}
4508
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004509static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
4510 struct class32_t c;
4511 const char *r;
4512 uint32_t offset, left;
4513 SectionRef S;
4514 const char *name;
4515
4516 r = get_pointer_32(p, offset, left, S, info);
4517 if (r == nullptr)
4518 return;
4519 memset(&c, '\0', sizeof(struct class32_t));
4520 if (left < sizeof(struct class32_t)) {
4521 memcpy(&c, r, left);
4522 outs() << " (class_t entends past the end of the section)\n";
4523 } else
4524 memcpy(&c, r, sizeof(struct class32_t));
4525 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4526 swapStruct(c);
4527
4528 outs() << " isa " << format("0x%" PRIx32, c.isa);
4529 name =
4530 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
4531 if (name != nullptr)
4532 outs() << " " << name;
4533 outs() << "\n";
4534
4535 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
4536 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
4537 c.superclass);
4538 if (name != nullptr)
4539 outs() << " " << name;
4540 outs() << "\n";
4541
4542 outs() << " cache " << format("0x%" PRIx32, c.cache);
4543 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
4544 c.cache);
4545 if (name != nullptr)
4546 outs() << " " << name;
4547 outs() << "\n";
4548
4549 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
4550 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
4551 c.vtable);
4552 if (name != nullptr)
4553 outs() << " " << name;
4554 outs() << "\n";
4555
4556 name =
4557 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
4558 outs() << " data " << format("0x%" PRIx32, c.data)
4559 << " (struct class_ro_t *)";
4560
4561 // This is a Swift class if some of the low bits of the pointer are set.
4562 if (c.data & 0x3)
4563 outs() << " Swift class";
4564 outs() << "\n";
4565 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004566 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
4567 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004568
Hans Wennborgcc9deb42015-09-29 18:02:48 +00004569 if (!is_meta_class) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004570 outs() << "Meta Class\n";
4571 print_class32_t(c.isa, info);
4572 }
4573}
4574
Kevin Enderby846c0002015-04-16 17:19:59 +00004575static void print_objc_class_t(struct objc_class_t *objc_class,
4576 struct DisassembleInfo *info) {
4577 uint32_t offset, left, xleft;
4578 const char *name, *p, *ivar_list;
4579 SectionRef S;
4580 int32_t i;
4581 struct objc_ivar_list_t objc_ivar_list;
4582 struct objc_ivar_t ivar;
4583
4584 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
4585 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
4586 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
4587 if (name != nullptr)
4588 outs() << format(" %.*s", left, name);
4589 else
4590 outs() << " (not in an __OBJC section)";
4591 }
4592 outs() << "\n";
4593
4594 outs() << "\t super_class "
4595 << format("0x%08" PRIx32, objc_class->super_class);
4596 if (info->verbose) {
4597 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
4598 if (name != nullptr)
4599 outs() << format(" %.*s", left, name);
4600 else
4601 outs() << " (not in an __OBJC section)";
4602 }
4603 outs() << "\n";
4604
4605 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
4606 if (info->verbose) {
4607 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
4608 if (name != nullptr)
4609 outs() << format(" %.*s", left, name);
4610 else
4611 outs() << " (not in an __OBJC section)";
4612 }
4613 outs() << "\n";
4614
4615 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
4616 << "\n";
4617
4618 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
4619 if (info->verbose) {
4620 if (CLS_GETINFO(objc_class, CLS_CLASS))
4621 outs() << " CLS_CLASS";
4622 else if (CLS_GETINFO(objc_class, CLS_META))
4623 outs() << " CLS_META";
4624 }
4625 outs() << "\n";
4626
4627 outs() << "\t instance_size "
4628 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
4629
4630 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
4631 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
4632 if (p != nullptr) {
4633 if (left > sizeof(struct objc_ivar_list_t)) {
4634 outs() << "\n";
4635 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
4636 } else {
4637 outs() << " (entends past the end of the section)\n";
4638 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
4639 memcpy(&objc_ivar_list, p, left);
4640 }
4641 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4642 swapStruct(objc_ivar_list);
4643 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
4644 ivar_list = p + sizeof(struct objc_ivar_list_t);
4645 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
4646 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
4647 outs() << "\t\t remaining ivar's extend past the of the section\n";
4648 break;
4649 }
4650 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
4651 sizeof(struct objc_ivar_t));
4652 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4653 swapStruct(ivar);
4654
4655 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
4656 if (info->verbose) {
4657 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
4658 if (name != nullptr)
4659 outs() << format(" %.*s", xleft, name);
4660 else
4661 outs() << " (not in an __OBJC section)";
4662 }
4663 outs() << "\n";
4664
4665 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
4666 if (info->verbose) {
4667 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
4668 if (name != nullptr)
4669 outs() << format(" %.*s", xleft, name);
4670 else
4671 outs() << " (not in an __OBJC section)";
4672 }
4673 outs() << "\n";
4674
4675 outs() << "\t\t ivar_offset "
4676 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
4677 }
4678 } else {
4679 outs() << " (not in an __OBJC section)\n";
4680 }
4681
4682 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
4683 if (print_method_list(objc_class->methodLists, info))
4684 outs() << " (not in an __OBJC section)\n";
4685
4686 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
4687 << "\n";
4688
4689 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
4690 if (print_protocol_list(objc_class->protocols, 16, info))
4691 outs() << " (not in an __OBJC section)\n";
4692}
4693
4694static void print_objc_objc_category_t(struct objc_category_t *objc_category,
4695 struct DisassembleInfo *info) {
4696 uint32_t offset, left;
4697 const char *name;
4698 SectionRef S;
4699
4700 outs() << "\t category name "
4701 << format("0x%08" PRIx32, objc_category->category_name);
4702 if (info->verbose) {
4703 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
4704 true);
4705 if (name != nullptr)
4706 outs() << format(" %.*s", left, name);
4707 else
4708 outs() << " (not in an __OBJC section)";
4709 }
4710 outs() << "\n";
4711
4712 outs() << "\t\t class name "
4713 << format("0x%08" PRIx32, objc_category->class_name);
4714 if (info->verbose) {
4715 name =
4716 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
4717 if (name != nullptr)
4718 outs() << format(" %.*s", left, name);
4719 else
4720 outs() << " (not in an __OBJC section)";
4721 }
4722 outs() << "\n";
4723
4724 outs() << "\t instance methods "
4725 << format("0x%08" PRIx32, objc_category->instance_methods);
4726 if (print_method_list(objc_category->instance_methods, info))
4727 outs() << " (not in an __OBJC section)\n";
4728
4729 outs() << "\t class methods "
4730 << format("0x%08" PRIx32, objc_category->class_methods);
4731 if (print_method_list(objc_category->class_methods, info))
4732 outs() << " (not in an __OBJC section)\n";
4733}
4734
Kevin Enderby0fc11822015-04-01 20:57:01 +00004735static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
4736 struct category64_t c;
4737 const char *r;
4738 uint32_t offset, xoffset, left;
4739 SectionRef S, xS;
4740 const char *name, *sym_name;
4741 uint64_t n_value;
4742
4743 r = get_pointer_64(p, offset, left, S, info);
4744 if (r == nullptr)
4745 return;
4746 memset(&c, '\0', sizeof(struct category64_t));
4747 if (left < sizeof(struct category64_t)) {
4748 memcpy(&c, r, left);
4749 outs() << " (category_t entends past the end of the section)\n";
4750 } else
4751 memcpy(&c, r, sizeof(struct category64_t));
4752 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4753 swapStruct(c);
4754
4755 outs() << " name ";
4756 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
4757 info, n_value, c.name);
4758 if (n_value != 0) {
4759 if (info->verbose && sym_name != nullptr)
4760 outs() << sym_name;
4761 else
4762 outs() << format("0x%" PRIx64, n_value);
4763 if (c.name != 0)
4764 outs() << " + " << format("0x%" PRIx64, c.name);
4765 } else
4766 outs() << format("0x%" PRIx64, c.name);
4767 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
4768 if (name != nullptr)
4769 outs() << format(" %.*s", left, name);
4770 outs() << "\n";
4771
4772 outs() << " cls ";
4773 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
4774 n_value, c.cls);
4775 if (n_value != 0) {
4776 if (info->verbose && sym_name != nullptr)
4777 outs() << sym_name;
4778 else
4779 outs() << format("0x%" PRIx64, n_value);
4780 if (c.cls != 0)
4781 outs() << " + " << format("0x%" PRIx64, c.cls);
4782 } else
4783 outs() << format("0x%" PRIx64, c.cls);
4784 outs() << "\n";
4785 if (c.cls + n_value != 0)
4786 print_class64_t(c.cls + n_value, info);
4787
4788 outs() << " instanceMethods ";
4789 sym_name =
4790 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
4791 info, n_value, c.instanceMethods);
4792 if (n_value != 0) {
4793 if (info->verbose && sym_name != nullptr)
4794 outs() << sym_name;
4795 else
4796 outs() << format("0x%" PRIx64, n_value);
4797 if (c.instanceMethods != 0)
4798 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
4799 } else
4800 outs() << format("0x%" PRIx64, c.instanceMethods);
4801 outs() << "\n";
4802 if (c.instanceMethods + n_value != 0)
4803 print_method_list64_t(c.instanceMethods + n_value, info, "");
4804
4805 outs() << " classMethods ";
4806 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
4807 S, info, n_value, c.classMethods);
4808 if (n_value != 0) {
4809 if (info->verbose && sym_name != nullptr)
4810 outs() << sym_name;
4811 else
4812 outs() << format("0x%" PRIx64, n_value);
4813 if (c.classMethods != 0)
4814 outs() << " + " << format("0x%" PRIx64, c.classMethods);
4815 } else
4816 outs() << format("0x%" PRIx64, c.classMethods);
4817 outs() << "\n";
4818 if (c.classMethods + n_value != 0)
4819 print_method_list64_t(c.classMethods + n_value, info, "");
4820
4821 outs() << " protocols ";
4822 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
4823 info, n_value, c.protocols);
4824 if (n_value != 0) {
4825 if (info->verbose && sym_name != nullptr)
4826 outs() << sym_name;
4827 else
4828 outs() << format("0x%" PRIx64, n_value);
4829 if (c.protocols != 0)
4830 outs() << " + " << format("0x%" PRIx64, c.protocols);
4831 } else
4832 outs() << format("0x%" PRIx64, c.protocols);
4833 outs() << "\n";
4834 if (c.protocols + n_value != 0)
4835 print_protocol_list64_t(c.protocols + n_value, info);
4836
4837 outs() << "instanceProperties ";
4838 sym_name =
4839 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
4840 S, info, n_value, c.instanceProperties);
4841 if (n_value != 0) {
4842 if (info->verbose && sym_name != nullptr)
4843 outs() << sym_name;
4844 else
4845 outs() << format("0x%" PRIx64, n_value);
4846 if (c.instanceProperties != 0)
4847 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
4848 } else
4849 outs() << format("0x%" PRIx64, c.instanceProperties);
4850 outs() << "\n";
4851 if (c.instanceProperties + n_value != 0)
4852 print_objc_property_list64(c.instanceProperties + n_value, info);
4853}
4854
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004855static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
4856 struct category32_t c;
4857 const char *r;
4858 uint32_t offset, left;
4859 SectionRef S, xS;
4860 const char *name;
4861
4862 r = get_pointer_32(p, offset, left, S, info);
4863 if (r == nullptr)
4864 return;
4865 memset(&c, '\0', sizeof(struct category32_t));
4866 if (left < sizeof(struct category32_t)) {
4867 memcpy(&c, r, left);
4868 outs() << " (category_t entends past the end of the section)\n";
4869 } else
4870 memcpy(&c, r, sizeof(struct category32_t));
4871 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4872 swapStruct(c);
4873
4874 outs() << " name " << format("0x%" PRIx32, c.name);
4875 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
4876 c.name);
Hans Wennborgcc9deb42015-09-29 18:02:48 +00004877 if (name)
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004878 outs() << " " << name;
4879 outs() << "\n";
4880
4881 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
4882 if (c.cls != 0)
4883 print_class32_t(c.cls, info);
4884 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
4885 << "\n";
4886 if (c.instanceMethods != 0)
4887 print_method_list32_t(c.instanceMethods, info, "");
4888 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
4889 << "\n";
4890 if (c.classMethods != 0)
4891 print_method_list32_t(c.classMethods, info, "");
4892 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
4893 if (c.protocols != 0)
4894 print_protocol_list32_t(c.protocols, info);
4895 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
4896 << "\n";
4897 if (c.instanceProperties != 0)
4898 print_objc_property_list32(c.instanceProperties, info);
4899}
4900
Kevin Enderby0fc11822015-04-01 20:57:01 +00004901static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
4902 uint32_t i, left, offset, xoffset;
4903 uint64_t p, n_value;
4904 struct message_ref64 mr;
4905 const char *name, *sym_name;
4906 const char *r;
4907 SectionRef xS;
4908
4909 if (S == SectionRef())
4910 return;
4911
4912 StringRef SectName;
4913 S.getName(SectName);
4914 DataRefImpl Ref = S.getRawDataRefImpl();
4915 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
4916 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4917 offset = 0;
4918 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
4919 p = S.getAddress() + i;
4920 r = get_pointer_64(p, offset, left, S, info);
4921 if (r == nullptr)
4922 return;
4923 memset(&mr, '\0', sizeof(struct message_ref64));
4924 if (left < sizeof(struct message_ref64)) {
4925 memcpy(&mr, r, left);
4926 outs() << " (message_ref entends past the end of the section)\n";
4927 } else
4928 memcpy(&mr, r, sizeof(struct message_ref64));
4929 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4930 swapStruct(mr);
4931
4932 outs() << " imp ";
4933 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
4934 n_value, mr.imp);
4935 if (n_value != 0) {
4936 outs() << format("0x%" PRIx64, n_value) << " ";
4937 if (mr.imp != 0)
4938 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
4939 } else
4940 outs() << format("0x%" PRIx64, mr.imp) << " ";
4941 if (name != nullptr)
4942 outs() << " " << name;
4943 outs() << "\n";
4944
4945 outs() << " sel ";
4946 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
4947 info, n_value, mr.sel);
4948 if (n_value != 0) {
4949 if (info->verbose && sym_name != nullptr)
4950 outs() << sym_name;
4951 else
4952 outs() << format("0x%" PRIx64, n_value);
4953 if (mr.sel != 0)
4954 outs() << " + " << format("0x%" PRIx64, mr.sel);
4955 } else
4956 outs() << format("0x%" PRIx64, mr.sel);
4957 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
4958 if (name != nullptr)
4959 outs() << format(" %.*s", left, name);
4960 outs() << "\n";
4961
4962 offset += sizeof(struct message_ref64);
4963 }
4964}
4965
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004966static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
4967 uint32_t i, left, offset, xoffset, p;
4968 struct message_ref32 mr;
4969 const char *name, *r;
4970 SectionRef xS;
4971
4972 if (S == SectionRef())
4973 return;
4974
4975 StringRef SectName;
4976 S.getName(SectName);
4977 DataRefImpl Ref = S.getRawDataRefImpl();
4978 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
4979 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4980 offset = 0;
4981 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
4982 p = S.getAddress() + i;
4983 r = get_pointer_32(p, offset, left, S, info);
4984 if (r == nullptr)
4985 return;
4986 memset(&mr, '\0', sizeof(struct message_ref32));
4987 if (left < sizeof(struct message_ref32)) {
4988 memcpy(&mr, r, left);
4989 outs() << " (message_ref entends past the end of the section)\n";
4990 } else
4991 memcpy(&mr, r, sizeof(struct message_ref32));
4992 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4993 swapStruct(mr);
4994
4995 outs() << " imp " << format("0x%" PRIx32, mr.imp);
4996 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
4997 mr.imp);
4998 if (name != nullptr)
4999 outs() << " " << name;
5000 outs() << "\n";
5001
5002 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5003 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5004 if (name != nullptr)
5005 outs() << " " << name;
5006 outs() << "\n";
5007
5008 offset += sizeof(struct message_ref32);
5009 }
5010}
5011
Kevin Enderby0fc11822015-04-01 20:57:01 +00005012static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5013 uint32_t left, offset, swift_version;
5014 uint64_t p;
5015 struct objc_image_info64 o;
5016 const char *r;
5017
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00005018 if (S == SectionRef())
5019 return;
5020
Kevin Enderby0fc11822015-04-01 20:57:01 +00005021 StringRef SectName;
5022 S.getName(SectName);
5023 DataRefImpl Ref = S.getRawDataRefImpl();
5024 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5025 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5026 p = S.getAddress();
5027 r = get_pointer_64(p, offset, left, S, info);
5028 if (r == nullptr)
5029 return;
5030 memset(&o, '\0', sizeof(struct objc_image_info64));
5031 if (left < sizeof(struct objc_image_info64)) {
5032 memcpy(&o, r, left);
5033 outs() << " (objc_image_info entends past the end of the section)\n";
5034 } else
5035 memcpy(&o, r, sizeof(struct objc_image_info64));
5036 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5037 swapStruct(o);
5038 outs() << " version " << o.version << "\n";
5039 outs() << " flags " << format("0x%" PRIx32, o.flags);
5040 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5041 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5042 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5043 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5044 swift_version = (o.flags >> 8) & 0xff;
5045 if (swift_version != 0) {
5046 if (swift_version == 1)
5047 outs() << " Swift 1.0";
5048 else if (swift_version == 2)
5049 outs() << " Swift 1.1";
5050 else
5051 outs() << " unknown future Swift version (" << swift_version << ")";
5052 }
5053 outs() << "\n";
5054}
5055
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005056static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5057 uint32_t left, offset, swift_version, p;
5058 struct objc_image_info32 o;
5059 const char *r;
5060
5061 StringRef SectName;
5062 S.getName(SectName);
5063 DataRefImpl Ref = S.getRawDataRefImpl();
5064 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5065 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5066 p = S.getAddress();
5067 r = get_pointer_32(p, offset, left, S, info);
5068 if (r == nullptr)
5069 return;
5070 memset(&o, '\0', sizeof(struct objc_image_info32));
5071 if (left < sizeof(struct objc_image_info32)) {
5072 memcpy(&o, r, left);
5073 outs() << " (objc_image_info entends past the end of the section)\n";
5074 } else
5075 memcpy(&o, r, sizeof(struct objc_image_info32));
5076 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5077 swapStruct(o);
5078 outs() << " version " << o.version << "\n";
5079 outs() << " flags " << format("0x%" PRIx32, o.flags);
5080 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5081 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5082 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5083 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5084 swift_version = (o.flags >> 8) & 0xff;
5085 if (swift_version != 0) {
5086 if (swift_version == 1)
5087 outs() << " Swift 1.0";
5088 else if (swift_version == 2)
5089 outs() << " Swift 1.1";
5090 else
5091 outs() << " unknown future Swift version (" << swift_version << ")";
5092 }
5093 outs() << "\n";
5094}
5095
Kevin Enderby846c0002015-04-16 17:19:59 +00005096static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5097 uint32_t left, offset, p;
5098 struct imageInfo_t o;
5099 const char *r;
5100
5101 StringRef SectName;
5102 S.getName(SectName);
5103 DataRefImpl Ref = S.getRawDataRefImpl();
5104 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5105 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5106 p = S.getAddress();
5107 r = get_pointer_32(p, offset, left, S, info);
5108 if (r == nullptr)
5109 return;
5110 memset(&o, '\0', sizeof(struct imageInfo_t));
5111 if (left < sizeof(struct imageInfo_t)) {
5112 memcpy(&o, r, left);
5113 outs() << " (imageInfo entends past the end of the section)\n";
5114 } else
5115 memcpy(&o, r, sizeof(struct imageInfo_t));
5116 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5117 swapStruct(o);
5118 outs() << " version " << o.version << "\n";
5119 outs() << " flags " << format("0x%" PRIx32, o.flags);
5120 if (o.flags & 0x1)
5121 outs() << " F&C";
5122 if (o.flags & 0x2)
5123 outs() << " GC";
5124 if (o.flags & 0x4)
5125 outs() << " GC-only";
5126 else
5127 outs() << " RR";
5128 outs() << "\n";
5129}
5130
Kevin Enderby0fc11822015-04-01 20:57:01 +00005131static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5132 SymbolAddressMap AddrMap;
5133 if (verbose)
5134 CreateSymbolAddressMap(O, &AddrMap);
5135
5136 std::vector<SectionRef> Sections;
5137 for (const SectionRef &Section : O->sections()) {
5138 StringRef SectName;
5139 Section.getName(SectName);
5140 Sections.push_back(Section);
5141 }
5142
5143 struct DisassembleInfo info;
5144 // Set up the block of info used by the Symbolizer call backs.
5145 info.verbose = verbose;
5146 info.O = O;
5147 info.AddrMap = &AddrMap;
5148 info.Sections = &Sections;
5149 info.class_name = nullptr;
5150 info.selector_name = nullptr;
5151 info.method = nullptr;
5152 info.demangled_name = nullptr;
5153 info.bindtable = nullptr;
5154 info.adrp_addr = 0;
5155 info.adrp_inst = 0;
5156
Kevin Enderbyaac75382015-10-08 16:56:35 +00005157 info.depth = 0;
Davide Italiano62507042015-12-11 22:27:59 +00005158 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5159 if (CL == SectionRef())
5160 CL = get_section(O, "__DATA", "__objc_classlist");
5161 info.S = CL;
5162 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005163
Davide Italiano62507042015-12-11 22:27:59 +00005164 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5165 if (CR == SectionRef())
5166 CR = get_section(O, "__DATA", "__objc_classrefs");
5167 info.S = CR;
5168 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005169
Davide Italiano62507042015-12-11 22:27:59 +00005170 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5171 if (SR == SectionRef())
5172 SR = get_section(O, "__DATA", "__objc_superrefs");
5173 info.S = SR;
5174 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005175
Davide Italiano62507042015-12-11 22:27:59 +00005176 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5177 if (CA == SectionRef())
5178 CA = get_section(O, "__DATA", "__objc_catlist");
5179 info.S = CA;
5180 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005181
Davide Italiano62507042015-12-11 22:27:59 +00005182 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5183 if (PL == SectionRef())
5184 PL = get_section(O, "__DATA", "__objc_protolist");
5185 info.S = PL;
5186 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005187
Davide Italiano62507042015-12-11 22:27:59 +00005188 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5189 if (MR == SectionRef())
5190 MR = get_section(O, "__DATA", "__objc_msgrefs");
5191 info.S = MR;
5192 print_message_refs64(MR, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005193
Davide Italiano62507042015-12-11 22:27:59 +00005194 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5195 if (II == SectionRef())
5196 II = get_section(O, "__DATA", "__objc_imageinfo");
5197 info.S = II;
5198 print_image_info64(II, &info);
Kevin Enderby0bc6ed42015-04-01 21:50:45 +00005199
5200 if (info.bindtable != nullptr)
5201 delete info.bindtable;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005202}
5203
5204static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005205 SymbolAddressMap AddrMap;
5206 if (verbose)
5207 CreateSymbolAddressMap(O, &AddrMap);
5208
5209 std::vector<SectionRef> Sections;
5210 for (const SectionRef &Section : O->sections()) {
5211 StringRef SectName;
5212 Section.getName(SectName);
5213 Sections.push_back(Section);
5214 }
5215
5216 struct DisassembleInfo info;
5217 // Set up the block of info used by the Symbolizer call backs.
5218 info.verbose = verbose;
5219 info.O = O;
5220 info.AddrMap = &AddrMap;
5221 info.Sections = &Sections;
5222 info.class_name = nullptr;
5223 info.selector_name = nullptr;
5224 info.method = nullptr;
5225 info.demangled_name = nullptr;
5226 info.bindtable = nullptr;
5227 info.adrp_addr = 0;
5228 info.adrp_inst = 0;
5229
5230 const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5231 if (CL != SectionRef()) {
5232 info.S = CL;
5233 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5234 } else {
5235 const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
5236 info.S = CL;
5237 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5238 }
5239
5240 const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5241 if (CR != SectionRef()) {
5242 info.S = CR;
5243 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5244 } else {
5245 const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
5246 info.S = CR;
5247 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5248 }
5249
5250 const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5251 if (SR != SectionRef()) {
5252 info.S = SR;
5253 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5254 } else {
5255 const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
5256 info.S = SR;
5257 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5258 }
5259
5260 const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5261 if (CA != SectionRef()) {
5262 info.S = CA;
5263 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5264 } else {
5265 const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
5266 info.S = CA;
5267 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5268 }
5269
5270 const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5271 if (PL != SectionRef()) {
5272 info.S = PL;
5273 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5274 } else {
5275 const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
5276 info.S = PL;
5277 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5278 }
5279
5280 const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5281 if (MR != SectionRef()) {
5282 info.S = MR;
5283 print_message_refs32(MR, &info);
5284 } else {
5285 const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
5286 info.S = MR;
5287 print_message_refs32(MR, &info);
5288 }
5289
5290 const SectionRef II = get_section(O, "__OBJC2", "__image_info");
5291 if (II != SectionRef()) {
5292 info.S = II;
5293 print_image_info32(II, &info);
5294 } else {
5295 const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
5296 info.S = II;
5297 print_image_info32(II, &info);
5298 }
Kevin Enderby0fc11822015-04-01 20:57:01 +00005299}
5300
5301static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby846c0002015-04-16 17:19:59 +00005302 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5303 const char *r, *name, *defs;
5304 struct objc_module_t module;
5305 SectionRef S, xS;
5306 struct objc_symtab_t symtab;
5307 struct objc_class_t objc_class;
5308 struct objc_category_t objc_category;
5309
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005310 outs() << "Objective-C segment\n";
Kevin Enderby846c0002015-04-16 17:19:59 +00005311 S = get_section(O, "__OBJC", "__module_info");
5312 if (S == SectionRef())
5313 return false;
5314
5315 SymbolAddressMap AddrMap;
5316 if (verbose)
5317 CreateSymbolAddressMap(O, &AddrMap);
5318
5319 std::vector<SectionRef> Sections;
5320 for (const SectionRef &Section : O->sections()) {
5321 StringRef SectName;
5322 Section.getName(SectName);
5323 Sections.push_back(Section);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005324 }
Kevin Enderby846c0002015-04-16 17:19:59 +00005325
5326 struct DisassembleInfo info;
5327 // Set up the block of info used by the Symbolizer call backs.
5328 info.verbose = verbose;
5329 info.O = O;
5330 info.AddrMap = &AddrMap;
5331 info.Sections = &Sections;
5332 info.class_name = nullptr;
5333 info.selector_name = nullptr;
5334 info.method = nullptr;
5335 info.demangled_name = nullptr;
5336 info.bindtable = nullptr;
5337 info.adrp_addr = 0;
5338 info.adrp_inst = 0;
5339
5340 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5341 p = S.getAddress() + i;
5342 r = get_pointer_32(p, offset, left, S, &info, true);
5343 if (r == nullptr)
5344 return true;
5345 memset(&module, '\0', sizeof(struct objc_module_t));
5346 if (left < sizeof(struct objc_module_t)) {
5347 memcpy(&module, r, left);
5348 outs() << " (module extends past end of __module_info section)\n";
5349 } else
5350 memcpy(&module, r, sizeof(struct objc_module_t));
5351 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5352 swapStruct(module);
5353
5354 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5355 outs() << " version " << module.version << "\n";
5356 outs() << " size " << module.size << "\n";
5357 outs() << " name ";
5358 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5359 if (name != nullptr)
5360 outs() << format("%.*s", left, name);
5361 else
5362 outs() << format("0x%08" PRIx32, module.name)
5363 << "(not in an __OBJC section)";
5364 outs() << "\n";
5365
5366 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5367 if (module.symtab == 0 || r == nullptr) {
5368 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5369 << " (not in an __OBJC section)\n";
5370 continue;
5371 }
5372 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5373 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5374 defs_left = 0;
5375 defs = nullptr;
5376 if (left < sizeof(struct objc_symtab_t)) {
5377 memcpy(&symtab, r, left);
5378 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5379 } else {
5380 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5381 if (left > sizeof(struct objc_symtab_t)) {
5382 defs_left = left - sizeof(struct objc_symtab_t);
5383 defs = r + sizeof(struct objc_symtab_t);
5384 }
5385 }
5386 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5387 swapStruct(symtab);
5388
5389 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5390 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5391 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5392 if (r == nullptr)
5393 outs() << " (not in an __OBJC section)";
5394 outs() << "\n";
5395 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5396 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5397 if (symtab.cls_def_cnt > 0)
5398 outs() << "\tClass Definitions\n";
5399 for (j = 0; j < symtab.cls_def_cnt; j++) {
5400 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5401 outs() << "\t(remaining class defs entries entends past the end of the "
5402 << "section)\n";
5403 break;
5404 }
5405 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5406 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5407 sys::swapByteOrder(def);
5408
5409 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5410 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5411 if (r != nullptr) {
5412 if (left > sizeof(struct objc_class_t)) {
5413 outs() << "\n";
5414 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5415 } else {
5416 outs() << " (entends past the end of the section)\n";
5417 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5418 memcpy(&objc_class, r, left);
5419 }
5420 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5421 swapStruct(objc_class);
5422 print_objc_class_t(&objc_class, &info);
5423 } else {
5424 outs() << "(not in an __OBJC section)\n";
5425 }
5426
5427 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
5428 outs() << "\tMeta Class";
5429 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
5430 if (r != nullptr) {
5431 if (left > sizeof(struct objc_class_t)) {
5432 outs() << "\n";
5433 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5434 } else {
5435 outs() << " (entends past the end of the section)\n";
5436 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5437 memcpy(&objc_class, r, left);
5438 }
5439 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5440 swapStruct(objc_class);
5441 print_objc_class_t(&objc_class, &info);
5442 } else {
5443 outs() << "(not in an __OBJC section)\n";
5444 }
5445 }
5446 }
5447 if (symtab.cat_def_cnt > 0)
5448 outs() << "\tCategory Definitions\n";
5449 for (j = 0; j < symtab.cat_def_cnt; j++) {
5450 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
5451 outs() << "\t(remaining category defs entries entends past the end of "
5452 << "the section)\n";
5453 break;
5454 }
5455 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
5456 sizeof(uint32_t));
5457 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5458 sys::swapByteOrder(def);
5459
5460 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5461 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
5462 << format("0x%08" PRIx32, def);
5463 if (r != nullptr) {
5464 if (left > sizeof(struct objc_category_t)) {
5465 outs() << "\n";
5466 memcpy(&objc_category, r, sizeof(struct objc_category_t));
5467 } else {
5468 outs() << " (entends past the end of the section)\n";
5469 memset(&objc_category, '\0', sizeof(struct objc_category_t));
5470 memcpy(&objc_category, r, left);
5471 }
5472 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5473 swapStruct(objc_category);
5474 print_objc_objc_category_t(&objc_category, &info);
5475 } else {
5476 outs() << "(not in an __OBJC section)\n";
5477 }
5478 }
5479 }
5480 const SectionRef II = get_section(O, "__OBJC", "__image_info");
5481 if (II != SectionRef())
5482 print_image_info(II, &info);
5483
5484 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005485}
5486
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00005487static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
5488 uint32_t size, uint32_t addr) {
5489 SymbolAddressMap AddrMap;
5490 CreateSymbolAddressMap(O, &AddrMap);
5491
5492 std::vector<SectionRef> Sections;
5493 for (const SectionRef &Section : O->sections()) {
5494 StringRef SectName;
5495 Section.getName(SectName);
5496 Sections.push_back(Section);
5497 }
5498
5499 struct DisassembleInfo info;
5500 // Set up the block of info used by the Symbolizer call backs.
5501 info.verbose = true;
5502 info.O = O;
5503 info.AddrMap = &AddrMap;
5504 info.Sections = &Sections;
5505 info.class_name = nullptr;
5506 info.selector_name = nullptr;
5507 info.method = nullptr;
5508 info.demangled_name = nullptr;
5509 info.bindtable = nullptr;
5510 info.adrp_addr = 0;
5511 info.adrp_inst = 0;
5512
5513 const char *p;
5514 struct objc_protocol_t protocol;
5515 uint32_t left, paddr;
5516 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
5517 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
5518 left = size - (p - sect);
5519 if (left < sizeof(struct objc_protocol_t)) {
5520 outs() << "Protocol extends past end of __protocol section\n";
5521 memcpy(&protocol, p, left);
5522 } else
5523 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
5524 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5525 swapStruct(protocol);
5526 paddr = addr + (p - sect);
5527 outs() << "Protocol " << format("0x%" PRIx32, paddr);
5528 if (print_protocol(paddr, 0, &info))
5529 outs() << "(not in an __OBJC section)\n";
5530 }
5531}
5532
Kevin Enderby0fc11822015-04-01 20:57:01 +00005533static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
5534 if (O->is64Bit())
5535 printObjc2_64bit_MetaData(O, verbose);
5536 else {
5537 MachO::mach_header H;
5538 H = O->getHeader();
5539 if (H.cputype == MachO::CPU_TYPE_ARM)
5540 printObjc2_32bit_MetaData(O, verbose);
5541 else {
5542 // This is the 32-bit non-arm cputype case. Which is normally
5543 // the first Objective-C ABI. But it may be the case of a
5544 // binary for the iOS simulator which is the second Objective-C
5545 // ABI. In that case printObjc1_32bit_MetaData() will determine that
5546 // and return false.
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005547 if (!printObjc1_32bit_MetaData(O, verbose))
Kevin Enderby0fc11822015-04-01 20:57:01 +00005548 printObjc2_32bit_MetaData(O, verbose);
5549 }
5550 }
5551}
5552
Kevin Enderbybf246f52014-09-24 23:08:22 +00005553// GuessLiteralPointer returns a string which for the item in the Mach-O file
5554// for the address passed in as ReferenceValue for printing as a comment with
5555// the instruction and also returns the corresponding type of that item
5556// indirectly through ReferenceType.
5557//
5558// If ReferenceValue is an address of literal cstring then a pointer to the
5559// cstring is returned and ReferenceType is set to
5560// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
5561//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005562// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
5563// Class ref that name is returned and the ReferenceType is set accordingly.
5564//
5565// Lastly, literals which are Symbol address in a literal pool are looked for
5566// and if found the symbol name is returned and ReferenceType is set to
5567// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
5568//
5569// If there is no item in the Mach-O file for the address passed in as
5570// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00005571static const char *GuessLiteralPointer(uint64_t ReferenceValue,
5572 uint64_t ReferencePC,
5573 uint64_t *ReferenceType,
5574 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00005575 // First see if there is an external relocation entry at the ReferencePC.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00005576 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
5577 uint64_t sect_addr = info->S.getAddress();
5578 uint64_t sect_offset = ReferencePC - sect_addr;
5579 bool reloc_found = false;
5580 DataRefImpl Rel;
5581 MachO::any_relocation_info RE;
5582 bool isExtern = false;
5583 SymbolRef Symbol;
5584 for (const RelocationRef &Reloc : info->S.relocations()) {
5585 uint64_t RelocOffset = Reloc.getOffset();
5586 if (RelocOffset == sect_offset) {
5587 Rel = Reloc.getRawDataRefImpl();
5588 RE = info->O->getRelocation(Rel);
5589 if (info->O->isRelocationScattered(RE))
5590 continue;
5591 isExtern = info->O->getPlainRelocationExternal(RE);
5592 if (isExtern) {
5593 symbol_iterator RelocSym = Reloc.getSymbol();
5594 Symbol = *RelocSym;
5595 }
5596 reloc_found = true;
5597 break;
Kevin Enderbybf246f52014-09-24 23:08:22 +00005598 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005599 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00005600 // If there is an external relocation entry for a symbol in a section
5601 // then used that symbol's value for the value of the reference.
5602 if (reloc_found && isExtern) {
5603 if (info->O->getAnyRelocationPCRel(RE)) {
5604 unsigned Type = info->O->getAnyRelocationType(RE);
5605 if (Type == MachO::X86_64_RELOC_SIGNED) {
5606 ReferenceValue = Symbol.getValue();
5607 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005608 }
5609 }
5610 }
5611
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005612 // Look for literals such as Objective-C CFStrings refs, Selector refs,
5613 // Message refs and Class refs.
5614 bool classref, selref, msgref, cfstring;
5615 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
5616 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00005617 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005618 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
5619 // And the pointer_value in that section is typically zero as it will be
5620 // set by dyld as part of the "bind information".
5621 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
5622 if (name != nullptr) {
5623 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00005624 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005625 if (class_name != nullptr && class_name[1] == '_' &&
5626 class_name[2] != '\0') {
5627 info->class_name = class_name + 2;
5628 return name;
5629 }
5630 }
5631 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005632
David Blaikie33dd45d02015-03-23 18:39:02 +00005633 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005634 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
5635 const char *name =
5636 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
5637 if (name != nullptr)
5638 info->class_name = name;
5639 else
5640 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00005641 return name;
5642 }
5643
David Blaikie33dd45d02015-03-23 18:39:02 +00005644 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005645 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
5646 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
5647 return name;
5648 }
5649
David Blaikie33dd45d02015-03-23 18:39:02 +00005650 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005651 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
5652
5653 if (pointer_value != 0)
5654 ReferenceValue = pointer_value;
5655
5656 const char *name = GuessCstringPointer(ReferenceValue, info);
5657 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00005658 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005659 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
5660 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00005661 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005662 info->class_name = nullptr;
5663 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
5664 info->selector_name = name;
5665 } else
5666 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
5667 return name;
5668 }
5669
5670 // Lastly look for an indirect symbol with this ReferenceValue which is in
5671 // a literal pool. If found return that symbol name.
5672 name = GuessIndirectSymbol(ReferenceValue, info);
5673 if (name) {
5674 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
5675 return name;
5676 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005677
5678 return nullptr;
5679}
5680
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005681// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00005682// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005683// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
5684// is created and returns the symbol name that matches the ReferenceValue or
5685// nullptr if none. The ReferenceType is passed in for the IN type of
5686// reference the instruction is making from the values in defined in the header
5687// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
5688// Out type and the ReferenceName will also be set which is added as a comment
5689// to the disassembled instruction.
5690//
Kevin Enderby04bf6932014-10-28 23:39:46 +00005691#if HAVE_CXXABI_H
5692// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005693// returned through ReferenceName and ReferenceType is set to
5694// LLVMDisassembler_ReferenceType_DeMangled_Name .
Kevin Enderby04bf6932014-10-28 23:39:46 +00005695#endif
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005696//
5697// When this is called to get a symbol name for a branch target then the
5698// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
5699// SymbolValue will be looked for in the indirect symbol table to determine if
5700// it is an address for a symbol stub. If so then the symbol name for that
5701// stub is returned indirectly through ReferenceName and then ReferenceType is
5702// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
5703//
Kevin Enderbybf246f52014-09-24 23:08:22 +00005704// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005705// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
5706// SymbolValue is checked to be an address of literal pointer, symbol pointer,
5707// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005708// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00005709static const char *SymbolizerSymbolLookUp(void *DisInfo,
5710 uint64_t ReferenceValue,
5711 uint64_t *ReferenceType,
5712 uint64_t ReferencePC,
5713 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005714 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00005715 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00005716 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00005717 *ReferenceName = nullptr;
5718 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005719 return nullptr;
5720 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005721
Kevin Enderbyf6d25852015-01-31 00:37:11 +00005722 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00005723
Kevin Enderby85974882014-09-26 22:20:44 +00005724 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
5725 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00005726 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005727 method_reference(info, ReferenceType, ReferenceName);
5728 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
5729 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
5730 } else
Kevin Enderby04bf6932014-10-28 23:39:46 +00005731#if HAVE_CXXABI_H
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005732 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00005733 if (info->demangled_name != nullptr)
5734 free(info->demangled_name);
5735 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005736 info->demangled_name =
5737 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00005738 if (info->demangled_name != nullptr) {
5739 *ReferenceName = info->demangled_name;
5740 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5741 } else
5742 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5743 } else
5744#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005745 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5746 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
5747 *ReferenceName =
5748 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00005749 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005750 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00005751 else
5752 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00005753 // If this is arm64 and the reference is an adrp instruction save the
5754 // instruction, passed in ReferenceValue and the address of the instruction
5755 // for use later if we see and add immediate instruction.
5756 } else if (info->O->getArch() == Triple::aarch64 &&
5757 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
5758 info->adrp_inst = ReferenceValue;
5759 info->adrp_addr = ReferencePC;
5760 SymbolName = nullptr;
5761 *ReferenceName = nullptr;
5762 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5763 // If this is arm64 and reference is an add immediate instruction and we
5764 // have
5765 // seen an adrp instruction just before it and the adrp's Xd register
5766 // matches
5767 // this add's Xn register reconstruct the value being referenced and look to
5768 // see if it is a literal pointer. Note the add immediate instruction is
5769 // passed in ReferenceValue.
5770 } else if (info->O->getArch() == Triple::aarch64 &&
5771 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
5772 ReferencePC - 4 == info->adrp_addr &&
5773 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5774 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5775 uint32_t addxri_inst;
5776 uint64_t adrp_imm, addxri_imm;
5777
5778 adrp_imm =
5779 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5780 if (info->adrp_inst & 0x0200000)
5781 adrp_imm |= 0xfffffffffc000000LL;
5782
5783 addxri_inst = ReferenceValue;
5784 addxri_imm = (addxri_inst >> 10) & 0xfff;
5785 if (((addxri_inst >> 22) & 0x3) == 1)
5786 addxri_imm <<= 12;
5787
5788 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5789 (adrp_imm << 12) + addxri_imm;
5790
5791 *ReferenceName =
5792 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5793 if (*ReferenceName == nullptr)
5794 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5795 // If this is arm64 and the reference is a load register instruction and we
5796 // have seen an adrp instruction just before it and the adrp's Xd register
5797 // matches this add's Xn register reconstruct the value being referenced and
5798 // look to see if it is a literal pointer. Note the load register
5799 // instruction is passed in ReferenceValue.
5800 } else if (info->O->getArch() == Triple::aarch64 &&
5801 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
5802 ReferencePC - 4 == info->adrp_addr &&
5803 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5804 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5805 uint32_t ldrxui_inst;
5806 uint64_t adrp_imm, ldrxui_imm;
5807
5808 adrp_imm =
5809 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5810 if (info->adrp_inst & 0x0200000)
5811 adrp_imm |= 0xfffffffffc000000LL;
5812
5813 ldrxui_inst = ReferenceValue;
5814 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
5815
5816 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5817 (adrp_imm << 12) + (ldrxui_imm << 3);
5818
5819 *ReferenceName =
5820 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5821 if (*ReferenceName == nullptr)
5822 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5823 }
5824 // If this arm64 and is an load register (PC-relative) instruction the
5825 // ReferenceValue is the PC plus the immediate value.
5826 else if (info->O->getArch() == Triple::aarch64 &&
5827 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
5828 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
5829 *ReferenceName =
5830 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5831 if (*ReferenceName == nullptr)
5832 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby85974882014-09-26 22:20:44 +00005833 }
Kevin Enderby04bf6932014-10-28 23:39:46 +00005834#if HAVE_CXXABI_H
5835 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
5836 if (info->demangled_name != nullptr)
5837 free(info->demangled_name);
5838 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005839 info->demangled_name =
5840 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00005841 if (info->demangled_name != nullptr) {
5842 *ReferenceName = info->demangled_name;
5843 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5844 }
5845 }
5846#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005847 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00005848 *ReferenceName = nullptr;
5849 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5850 }
5851
5852 return SymbolName;
5853}
5854
Kevin Enderbybf246f52014-09-24 23:08:22 +00005855/// \brief Emits the comments that are stored in the CommentStream.
5856/// Each comment in the CommentStream must end with a newline.
5857static void emitComments(raw_svector_ostream &CommentStream,
5858 SmallString<128> &CommentsToEmit,
5859 formatted_raw_ostream &FormattedOS,
5860 const MCAsmInfo &MAI) {
5861 // Flush the stream before taking its content.
Kevin Enderbybf246f52014-09-24 23:08:22 +00005862 StringRef Comments = CommentsToEmit.str();
5863 // Get the default information for printing a comment.
5864 const char *CommentBegin = MAI.getCommentString();
5865 unsigned CommentColumn = MAI.getCommentColumn();
5866 bool IsFirst = true;
5867 while (!Comments.empty()) {
5868 if (!IsFirst)
5869 FormattedOS << '\n';
5870 // Emit a line of comments.
5871 FormattedOS.PadToColumn(CommentColumn);
5872 size_t Position = Comments.find('\n');
5873 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
5874 // Move after the newline character.
5875 Comments = Comments.substr(Position + 1);
5876 IsFirst = false;
5877 }
5878 FormattedOS.flush();
5879
5880 // Tell the comment stream that the vector changed underneath it.
5881 CommentsToEmit.clear();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005882}
5883
Kevin Enderby95df54c2015-02-04 01:01:38 +00005884static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
5885 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005886 const char *McpuDefault = nullptr;
5887 const Target *ThumbTarget = nullptr;
5888 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005889 if (!TheTarget) {
5890 // GetTarget prints out stuff.
5891 return;
5892 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005893 if (MCPU.empty() && McpuDefault)
5894 MCPU = McpuDefault;
5895
Ahmed Charles56440fd2014-03-06 05:51:42 +00005896 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005897 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00005898 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005899 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005900
Kevin Enderbyc9595622014-08-06 23:24:41 +00005901 // Package up features to be passed to target/subtarget
5902 std::string FeaturesStr;
5903 if (MAttrs.size()) {
5904 SubtargetFeatures Features;
5905 for (unsigned i = 0; i != MAttrs.size(); ++i)
5906 Features.AddFeature(MAttrs[i]);
5907 FeaturesStr = Features.getString();
5908 }
5909
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005910 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00005911 std::unique_ptr<const MCRegisterInfo> MRI(
5912 TheTarget->createMCRegInfo(TripleName));
5913 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00005914 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00005915 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +00005916 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00005917 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005918 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005919 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005920 std::unique_ptr<MCSymbolizer> Symbolizer;
5921 struct DisassembleInfo SymbolizerInfo;
5922 std::unique_ptr<MCRelocationInfo> RelInfo(
5923 TheTarget->createMCRelocationInfo(TripleName, Ctx));
5924 if (RelInfo) {
5925 Symbolizer.reset(TheTarget->createMCSymbolizer(
5926 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00005927 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005928 DisAsm->setSymbolizer(std::move(Symbolizer));
5929 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005930 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00005931 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00005932 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00005933 // Set the display preference for hex vs. decimal immediates.
5934 IP->setPrintImmHex(PrintImmHex);
5935 // Comment stream and backing vector.
5936 SmallString<128> CommentsToEmit;
5937 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00005938 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
5939 // if it is done then arm64 comments for string literals don't get printed
5940 // and some constant get printed instead and not setting it causes intel
5941 // (32-bit and 64-bit) comments printed with different spacing before the
5942 // comment causing different diffs with the 'C' disassembler library API.
5943 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00005944
Kevin Enderbyae3c1262014-11-14 21:52:18 +00005945 if (!AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencerc1363cf2011-10-07 19:25:47 +00005946 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00005947 << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005948 return;
5949 }
5950
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005951 // Set up thumb disassembler.
5952 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
5953 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
5954 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00005955 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005956 std::unique_ptr<MCInstPrinter> ThumbIP;
5957 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00005958 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
5959 struct DisassembleInfo ThumbSymbolizerInfo;
5960 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005961 if (ThumbTarget) {
5962 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
5963 ThumbAsmInfo.reset(
5964 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
5965 ThumbSTI.reset(
5966 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
5967 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
5968 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00005969 MCContext *PtrThumbCtx = ThumbCtx.get();
5970 ThumbRelInfo.reset(
5971 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
5972 if (ThumbRelInfo) {
5973 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
5974 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00005975 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00005976 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
5977 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005978 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
5979 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00005980 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
5981 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00005982 // Set the display preference for hex vs. decimal immediates.
5983 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005984 }
5985
Kevin Enderbyae3c1262014-11-14 21:52:18 +00005986 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005987 errs() << "error: couldn't initialize disassembler for target "
5988 << ThumbTripleName << '\n';
5989 return;
5990 }
5991
Charles Davis8bdfafd2013-09-01 04:28:48 +00005992 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005993
Ahmed Bougachaaa790682013-05-24 01:07:04 +00005994 // FIXME: Using the -cfg command line option, this code used to be able to
5995 // annotate relocations with the referenced symbol's name, and if this was
5996 // inside a __[cf]string section, the data it points to. This is now replaced
5997 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00005998 std::vector<SectionRef> Sections;
5999 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006000 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00006001 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006002
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00006003 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
Kevin Enderby273ae012013-06-06 17:20:50 +00006004 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006005
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006006 // Sort the symbols by address, just in case they didn't come in that way.
Owen Andersond9243c42011-10-17 21:37:35 +00006007 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006008
Kevin Enderby273ae012013-06-06 17:20:50 +00006009 // Build a data in code table that is sorted on by the address of each entry.
6010 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00006011 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00006012 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00006013 else
6014 BaseAddress = BaseSegmentAddress;
6015 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00006016 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00006017 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006018 uint32_t Offset;
6019 DI->getOffset(Offset);
6020 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6021 }
6022 array_pod_sort(Dices.begin(), Dices.end());
6023
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006024#ifndef NDEBUG
6025 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6026#else
6027 raw_ostream &DebugOut = nulls();
6028#endif
6029
Ahmed Charles56440fd2014-03-06 05:51:42 +00006030 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00006031 ObjectFile *DbgObj = MachOOF;
Benjamin Kramer699128e2011-09-21 01:13:19 +00006032 // Try to find debug info and set up the DIContext for it.
6033 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00006034 // A separate DSym file path was specified, parse it as a macho file,
6035 // get the sections and supply it to the section name parsing machinery.
6036 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00006037 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006038 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00006039 if (std::error_code EC = BufOrErr.getError()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006040 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +00006041 return;
6042 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00006043 DbgObj =
6044 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
6045 .get()
6046 .release();
Benjamin Kramer699128e2011-09-21 01:13:19 +00006047 }
6048
Eric Christopher7370b552012-11-12 21:40:38 +00006049 // Setup the DIContext
Zachary Turner6489d7b2015-04-23 17:37:47 +00006050 diContext.reset(new DWARFContextInMemory(*DbgObj));
Benjamin Kramer699128e2011-09-21 01:13:19 +00006051 }
6052
Colin LeMahieufcc32762015-07-29 19:08:10 +00006053 if (FilterSections.size() == 0)
Kevin Enderby95df54c2015-02-04 01:01:38 +00006054 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006055
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006056 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00006057 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00006058 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6059 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006060
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006061 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006062
Rafael Espindolab0f76a42013-04-05 15:15:22 +00006063 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00006064 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006065 continue;
6066
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006067 StringRef BytesStr;
6068 Sections[SectIdx].getContents(BytesStr);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00006069 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6070 BytesStr.size());
Rafael Espindola80291272014-10-08 15:28:58 +00006071 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00006072
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006073 bool symbolTableWorked = false;
6074
Kevin Enderbybf246f52014-09-24 23:08:22 +00006075 // Create a map of symbol addresses to symbol names for use by
6076 // the SymbolizerSymbolLookUp() routine.
6077 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00006078 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006079 for (const SymbolRef &Symbol : MachOOF->symbols()) {
Rafael Espindola2fa80cc2015-06-26 12:18:49 +00006080 SymbolRef::Type ST = Symbol.getType();
Kevin Enderbybf246f52014-09-24 23:08:22 +00006081 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
6082 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00006083 uint64_t Address = Symbol.getValue();
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006084 ErrorOr<StringRef> SymNameOrErr = Symbol.getName();
6085 if (std::error_code EC = SymNameOrErr.getError())
6086 report_fatal_error(EC.message());
6087 StringRef SymName = *SymNameOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006088 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00006089 if (!DisSymName.empty() && DisSymName == SymName)
6090 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006091 }
6092 }
David Blaikie33dd45d02015-03-23 18:39:02 +00006093 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00006094 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
6095 return;
6096 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006097 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006098 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006099 SymbolizerInfo.O = MachOOF;
6100 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00006101 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006102 SymbolizerInfo.Sections = &Sections;
6103 SymbolizerInfo.class_name = nullptr;
6104 SymbolizerInfo.selector_name = nullptr;
6105 SymbolizerInfo.method = nullptr;
Kevin Enderby04bf6932014-10-28 23:39:46 +00006106 SymbolizerInfo.demangled_name = nullptr;
Kevin Enderby078be602014-10-23 19:53:12 +00006107 SymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006108 SymbolizerInfo.adrp_addr = 0;
6109 SymbolizerInfo.adrp_inst = 0;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006110 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006111 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006112 ThumbSymbolizerInfo.O = MachOOF;
6113 ThumbSymbolizerInfo.S = Sections[SectIdx];
6114 ThumbSymbolizerInfo.AddrMap = &AddrMap;
6115 ThumbSymbolizerInfo.Sections = &Sections;
6116 ThumbSymbolizerInfo.class_name = nullptr;
6117 ThumbSymbolizerInfo.selector_name = nullptr;
6118 ThumbSymbolizerInfo.method = nullptr;
6119 ThumbSymbolizerInfo.demangled_name = nullptr;
6120 ThumbSymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006121 ThumbSymbolizerInfo.adrp_addr = 0;
6122 ThumbSymbolizerInfo.adrp_inst = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006123
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006124 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006125 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006126 ErrorOr<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
6127 if (std::error_code EC = SymNameOrErr.getError())
6128 report_fatal_error(EC.message());
6129 StringRef SymName = *SymNameOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00006130
Rafael Espindola2fa80cc2015-06-26 12:18:49 +00006131 SymbolRef::Type ST = Symbols[SymIdx].getType();
Kuba Breckade833222015-11-12 09:40:29 +00006132 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
Owen Andersond9243c42011-10-17 21:37:35 +00006133 continue;
6134
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006135 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00006136 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Owen Andersond9243c42011-10-17 21:37:35 +00006137 if (!containsSym)
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006138 continue;
6139
Kevin Enderby6a221752015-03-17 17:10:57 +00006140 // If we are only disassembling one symbol see if this is that symbol.
6141 if (!DisSymName.empty() && DisSymName != SymName)
6142 continue;
6143
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006144 // Start at the address of the symbol relative to the section's address.
Rafael Espindoladea00162015-07-03 17:44:18 +00006145 uint64_t Start = Symbols[SymIdx].getValue();
Rafael Espindola80291272014-10-08 15:28:58 +00006146 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006147 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006148
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006149 // Stop disassembling either at the beginning of the next symbol or at
6150 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00006151 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00006152 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006153 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00006154 while (Symbols.size() > NextSymIdx) {
Rafael Espindola2fa80cc2015-06-26 12:18:49 +00006155 SymbolRef::Type NextSymType = Symbols[NextSymIdx].getType();
Owen Andersond9243c42011-10-17 21:37:35 +00006156 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00006157 containsNextSym =
6158 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Rafael Espindoladea00162015-07-03 17:44:18 +00006159 NextSym = Symbols[NextSymIdx].getValue();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006160 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006161 break;
6162 }
6163 ++NextSymIdx;
6164 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006165
Rafael Espindola80291272014-10-08 15:28:58 +00006166 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006167 uint64_t End = containsNextSym ? NextSym : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00006168 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006169
6170 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00006171
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006172 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
6173 bool isThumb =
6174 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
6175
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006176 outs() << SymName << ":\n";
6177 DILineInfo lastLine;
6178 for (uint64_t Index = Start; Index < End; Index += Size) {
6179 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00006180
Kevin Enderbybf246f52014-09-24 23:08:22 +00006181 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006182 if (!NoLeadingAddr) {
6183 if (FullLeadingAddr) {
6184 if (MachOOF->is64Bit())
6185 outs() << format("%016" PRIx64, PC);
6186 else
6187 outs() << format("%08" PRIx64, PC);
6188 } else {
6189 outs() << format("%8" PRIx64 ":", PC);
6190 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006191 }
6192 if (!NoShowRawInsn)
6193 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00006194
6195 // Check the data in code table here to see if this is data not an
6196 // instruction to be disassembled.
6197 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006198 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006199 dice_table_iterator DTI =
6200 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
6201 compareDiceTableEntries);
6202 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006203 uint16_t Length;
6204 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00006205 uint16_t Kind;
6206 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00006207 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00006208 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
6209 (PC == (DTI->first + Length - 1)) && (Length & 1))
6210 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00006211 continue;
6212 }
6213
Kevin Enderbybf246f52014-09-24 23:08:22 +00006214 SmallVector<char, 64> AnnotationsBytes;
6215 raw_svector_ostream Annotations(AnnotationsBytes);
6216
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006217 bool gotInst;
6218 if (isThumb)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006219 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006220 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006221 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006222 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00006223 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006224 if (gotInst) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006225 if (!NoShowRawInsn) {
Craig Topper0013be12015-09-21 05:32:41 +00006226 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006227 }
6228 formatted_raw_ostream FormattedOS(outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006229 StringRef AnnotationsStr = Annotations.str();
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006230 if (isThumb)
Akira Hatanakab46d0232015-03-27 20:36:02 +00006231 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006232 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00006233 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006234 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00006235
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006236 // Print debug info.
6237 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006238 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006239 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00006240 if (dli != lastLine && dli.Line != 0)
6241 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
6242 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006243 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006244 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006245 outs() << "\n";
6246 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006247 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006248 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006249 outs() << format("\t.byte 0x%02x #bad opcode\n",
6250 *(Bytes.data() + Index) & 0xff);
6251 Size = 1; // skip exactly one illegible byte and move on.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006252 } else if (Arch == Triple::aarch64) {
6253 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6254 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
6255 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
6256 (*(Bytes.data() + Index + 3) & 0xff) << 24;
6257 outs() << format("\t.long\t0x%08x\n", opcode);
6258 Size = 4;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006259 } else {
6260 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6261 if (Size == 0)
6262 Size = 1; // skip illegible bytes
6263 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006264 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006265 }
6266 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006267 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00006268 // Reading the symbol table didn't work, disassemble the whole section.
6269 uint64_t SectAddress = Sections[SectIdx].getAddress();
6270 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00006271 uint64_t InstSize;
6272 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00006273 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00006274
Kevin Enderbybf246f52014-09-24 23:08:22 +00006275 uint64_t PC = SectAddress + Index;
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006276 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
6277 DebugOut, nulls())) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006278 if (!NoLeadingAddr) {
6279 if (FullLeadingAddr) {
6280 if (MachOOF->is64Bit())
6281 outs() << format("%016" PRIx64, PC);
6282 else
6283 outs() << format("%08" PRIx64, PC);
6284 } else {
6285 outs() << format("%8" PRIx64 ":", PC);
6286 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006287 }
6288 if (!NoShowRawInsn) {
6289 outs() << "\t";
Craig Topper0013be12015-09-21 05:32:41 +00006290 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006291 }
Akira Hatanaka1d079942015-03-28 20:44:05 +00006292 IP->printInst(&Inst, outs(), "", *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00006293 outs() << "\n";
6294 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006295 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006296 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006297 outs() << format("\t.byte 0x%02x #bad opcode\n",
6298 *(Bytes.data() + Index) & 0xff);
6299 InstSize = 1; // skip exactly one illegible byte and move on.
6300 } else {
6301 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6302 if (InstSize == 0)
6303 InstSize = 1; // skip illegible bytes
6304 }
Bill Wendling4e68e062012-07-19 00:17:40 +00006305 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00006306 }
6307 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006308 // The TripleName's need to be reset if we are called again for a different
6309 // archtecture.
6310 TripleName = "";
6311 ThumbTripleName = "";
6312
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006313 if (SymbolizerInfo.method != nullptr)
6314 free(SymbolizerInfo.method);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006315 if (SymbolizerInfo.demangled_name != nullptr)
6316 free(SymbolizerInfo.demangled_name);
Kevin Enderby078be602014-10-23 19:53:12 +00006317 if (SymbolizerInfo.bindtable != nullptr)
6318 delete SymbolizerInfo.bindtable;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006319 if (ThumbSymbolizerInfo.method != nullptr)
6320 free(ThumbSymbolizerInfo.method);
6321 if (ThumbSymbolizerInfo.demangled_name != nullptr)
6322 free(ThumbSymbolizerInfo.demangled_name);
6323 if (ThumbSymbolizerInfo.bindtable != nullptr)
6324 delete ThumbSymbolizerInfo.bindtable;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006325 }
6326}
Tim Northover4bd286a2014-08-01 13:07:19 +00006327
Tim Northover39c70bb2014-08-12 11:52:59 +00006328//===----------------------------------------------------------------------===//
6329// __compact_unwind section dumping
6330//===----------------------------------------------------------------------===//
6331
Tim Northover4bd286a2014-08-01 13:07:19 +00006332namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00006333
6334template <typename T> static uint64_t readNext(const char *&Buf) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006335 using llvm::support::little;
6336 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00006337
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006338 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
6339 Buf += sizeof(T);
6340 return Val;
6341}
Tim Northover39c70bb2014-08-12 11:52:59 +00006342
Tim Northover4bd286a2014-08-01 13:07:19 +00006343struct CompactUnwindEntry {
6344 uint32_t OffsetInSection;
6345
6346 uint64_t FunctionAddr;
6347 uint32_t Length;
6348 uint32_t CompactEncoding;
6349 uint64_t PersonalityAddr;
6350 uint64_t LSDAAddr;
6351
6352 RelocationRef FunctionReloc;
6353 RelocationRef PersonalityReloc;
6354 RelocationRef LSDAReloc;
6355
6356 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006357 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006358 if (Is64)
6359 read<uint64_t>(Contents.data() + Offset);
6360 else
6361 read<uint32_t>(Contents.data() + Offset);
6362 }
6363
6364private:
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006365 template <typename UIntPtr> void read(const char *Buf) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006366 FunctionAddr = readNext<UIntPtr>(Buf);
6367 Length = readNext<uint32_t>(Buf);
6368 CompactEncoding = readNext<uint32_t>(Buf);
6369 PersonalityAddr = readNext<UIntPtr>(Buf);
6370 LSDAAddr = readNext<UIntPtr>(Buf);
6371 }
6372};
6373}
6374
6375/// Given a relocation from __compact_unwind, consisting of the RelocationRef
6376/// and data being relocated, determine the best base Name and Addend to use for
6377/// display purposes.
6378///
6379/// 1. An Extern relocation will directly reference a symbol (and the data is
6380/// then already an addend), so use that.
6381/// 2. Otherwise the data is an offset in the object file's layout; try to find
6382// a symbol before it in the same section, and use the offset from there.
6383/// 3. Finally, if all that fails, fall back to an offset from the start of the
6384/// referenced section.
6385static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
6386 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006387 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00006388 StringRef &Name, uint64_t &Addend) {
6389 if (Reloc.getSymbol() != Obj->symbol_end()) {
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006390 ErrorOr<StringRef> NameOrErr = Reloc.getSymbol()->getName();
6391 if (std::error_code EC = NameOrErr.getError())
6392 report_fatal_error(EC.message());
6393 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00006394 Addend = Addr;
6395 return;
6396 }
6397
6398 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
Keno Fischerc780e8e2015-05-21 21:24:32 +00006399 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
Tim Northover4bd286a2014-08-01 13:07:19 +00006400
Rafael Espindola80291272014-10-08 15:28:58 +00006401 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00006402
6403 auto Sym = Symbols.upper_bound(Addr);
6404 if (Sym == Symbols.begin()) {
6405 // The first symbol in the object is after this reference, the best we can
6406 // do is section-relative notation.
6407 RelocSection.getName(Name);
6408 Addend = Addr - SectionAddr;
6409 return;
6410 }
6411
6412 // Go back one so that SymbolAddress <= Addr.
6413 --Sym;
6414
Rafael Espindola8bab8892015-08-07 23:27:14 +00006415 section_iterator SymSection = *Sym->second.getSection();
Tim Northover4bd286a2014-08-01 13:07:19 +00006416 if (RelocSection == *SymSection) {
6417 // There's a valid symbol in the same section before this reference.
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006418 ErrorOr<StringRef> NameOrErr = Sym->second.getName();
6419 if (std::error_code EC = NameOrErr.getError())
6420 report_fatal_error(EC.message());
6421 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00006422 Addend = Addr - Sym->first;
6423 return;
6424 }
6425
6426 // There is a symbol before this reference, but it's in a different
6427 // section. Probably not helpful to mention it, so use the section name.
6428 RelocSection.getName(Name);
6429 Addend = Addr - SectionAddr;
6430}
6431
6432static void printUnwindRelocDest(const MachOObjectFile *Obj,
6433 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006434 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006435 StringRef Name;
6436 uint64_t Addend;
6437
Rafael Espindola854038e2015-06-26 14:51:16 +00006438 if (!Reloc.getObject())
Tim Northover0b0add52014-09-09 10:45:06 +00006439 return;
6440
Tim Northover4bd286a2014-08-01 13:07:19 +00006441 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
6442
6443 outs() << Name;
6444 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00006445 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00006446}
6447
6448static void
6449printMachOCompactUnwindSection(const MachOObjectFile *Obj,
6450 std::map<uint64_t, SymbolRef> &Symbols,
6451 const SectionRef &CompactUnwind) {
6452
6453 assert(Obj->isLittleEndian() &&
6454 "There should not be a big-endian .o with __compact_unwind");
6455
6456 bool Is64 = Obj->is64Bit();
6457 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
6458 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
6459
6460 StringRef Contents;
6461 CompactUnwind.getContents(Contents);
6462
6463 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
6464
6465 // First populate the initial raw offsets, encodings and so on from the entry.
6466 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
6467 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
6468 CompactUnwinds.push_back(Entry);
6469 }
6470
6471 // Next we need to look at the relocations to find out what objects are
6472 // actually being referred to.
6473 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00006474 uint64_t RelocAddress = Reloc.getOffset();
Tim Northover4bd286a2014-08-01 13:07:19 +00006475
6476 uint32_t EntryIdx = RelocAddress / EntrySize;
6477 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
6478 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
6479
6480 if (OffsetInEntry == 0)
6481 Entry.FunctionReloc = Reloc;
6482 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
6483 Entry.PersonalityReloc = Reloc;
6484 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
6485 Entry.LSDAReloc = Reloc;
6486 else
6487 llvm_unreachable("Unexpected relocation in __compact_unwind section");
6488 }
6489
6490 // Finally, we're ready to print the data we've gathered.
6491 outs() << "Contents of __compact_unwind section:\n";
6492 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00006493 outs() << " Entry at offset "
6494 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00006495
6496 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006497 outs() << " start: " << format("0x%" PRIx64,
6498 Entry.FunctionAddr) << ' ';
6499 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00006500 outs() << '\n';
6501
6502 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006503 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
6504 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00006505 // 3. The 32-bit compact encoding.
6506 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00006507 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00006508
6509 // 4. The personality function, if present.
Rafael Espindola854038e2015-06-26 14:51:16 +00006510 if (Entry.PersonalityReloc.getObject()) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006511 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00006512 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00006513 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
6514 Entry.PersonalityAddr);
6515 outs() << '\n';
6516 }
6517
6518 // 5. This entry's language-specific data area.
Rafael Espindola854038e2015-06-26 14:51:16 +00006519 if (Entry.LSDAReloc.getObject()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006520 outs() << " LSDA: " << format("0x%" PRIx64,
6521 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00006522 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
6523 outs() << '\n';
6524 }
6525 }
6526}
6527
Tim Northover39c70bb2014-08-12 11:52:59 +00006528//===----------------------------------------------------------------------===//
6529// __unwind_info section dumping
6530//===----------------------------------------------------------------------===//
6531
6532static void printRegularSecondLevelUnwindPage(const char *PageStart) {
6533 const char *Pos = PageStart;
6534 uint32_t Kind = readNext<uint32_t>(Pos);
6535 (void)Kind;
6536 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
6537
6538 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6539 uint16_t NumEntries = readNext<uint16_t>(Pos);
6540
6541 Pos = PageStart + EntriesStart;
6542 for (unsigned i = 0; i < NumEntries; ++i) {
6543 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6544 uint32_t Encoding = readNext<uint32_t>(Pos);
6545
6546 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006547 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6548 << ", "
6549 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006550 }
6551}
6552
6553static void printCompressedSecondLevelUnwindPage(
6554 const char *PageStart, uint32_t FunctionBase,
6555 const SmallVectorImpl<uint32_t> &CommonEncodings) {
6556 const char *Pos = PageStart;
6557 uint32_t Kind = readNext<uint32_t>(Pos);
6558 (void)Kind;
6559 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
6560
6561 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6562 uint16_t NumEntries = readNext<uint16_t>(Pos);
6563
6564 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
6565 readNext<uint16_t>(Pos);
Aaron Ballman80930af2014-08-14 13:53:19 +00006566 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
6567 PageStart + EncodingsStart);
Tim Northover39c70bb2014-08-12 11:52:59 +00006568
6569 Pos = PageStart + EntriesStart;
6570 for (unsigned i = 0; i < NumEntries; ++i) {
6571 uint32_t Entry = readNext<uint32_t>(Pos);
6572 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
6573 uint32_t EncodingIdx = Entry >> 24;
6574
6575 uint32_t Encoding;
6576 if (EncodingIdx < CommonEncodings.size())
6577 Encoding = CommonEncodings[EncodingIdx];
6578 else
6579 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
6580
6581 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006582 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6583 << ", "
6584 << "encoding[" << EncodingIdx
6585 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006586 }
6587}
6588
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006589static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
6590 std::map<uint64_t, SymbolRef> &Symbols,
6591 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00006592
6593 assert(Obj->isLittleEndian() &&
6594 "There should not be a big-endian .o with __unwind_info");
6595
6596 outs() << "Contents of __unwind_info section:\n";
6597
6598 StringRef Contents;
6599 UnwindInfo.getContents(Contents);
6600 const char *Pos = Contents.data();
6601
6602 //===----------------------------------
6603 // Section header
6604 //===----------------------------------
6605
6606 uint32_t Version = readNext<uint32_t>(Pos);
6607 outs() << " Version: "
6608 << format("0x%" PRIx32, Version) << '\n';
6609 assert(Version == 1 && "only understand version 1");
6610
6611 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
6612 outs() << " Common encodings array section offset: "
6613 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
6614 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
6615 outs() << " Number of common encodings in array: "
6616 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
6617
6618 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
6619 outs() << " Personality function array section offset: "
6620 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
6621 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
6622 outs() << " Number of personality functions in array: "
6623 << format("0x%" PRIx32, NumPersonalities) << '\n';
6624
6625 uint32_t IndicesStart = readNext<uint32_t>(Pos);
6626 outs() << " Index array section offset: "
6627 << format("0x%" PRIx32, IndicesStart) << '\n';
6628 uint32_t NumIndices = readNext<uint32_t>(Pos);
6629 outs() << " Number of indices in array: "
6630 << format("0x%" PRIx32, NumIndices) << '\n';
6631
6632 //===----------------------------------
6633 // A shared list of common encodings
6634 //===----------------------------------
6635
6636 // These occupy indices in the range [0, N] whenever an encoding is referenced
6637 // from a compressed 2nd level index table. In practice the linker only
6638 // creates ~128 of these, so that indices are available to embed encodings in
6639 // the 2nd level index.
6640
6641 SmallVector<uint32_t, 64> CommonEncodings;
6642 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
6643 Pos = Contents.data() + CommonEncodingsStart;
6644 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
6645 uint32_t Encoding = readNext<uint32_t>(Pos);
6646 CommonEncodings.push_back(Encoding);
6647
6648 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
6649 << '\n';
6650 }
6651
Tim Northover39c70bb2014-08-12 11:52:59 +00006652 //===----------------------------------
6653 // Personality functions used in this executable
6654 //===----------------------------------
6655
6656 // There should be only a handful of these (one per source language,
6657 // roughly). Particularly since they only get 2 bits in the compact encoding.
6658
6659 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
6660 Pos = Contents.data() + PersonalitiesStart;
6661 for (unsigned i = 0; i < NumPersonalities; ++i) {
6662 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
6663 outs() << " personality[" << i + 1
6664 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
6665 }
6666
6667 //===----------------------------------
6668 // The level 1 index entries
6669 //===----------------------------------
6670
6671 // These specify an approximate place to start searching for the more detailed
6672 // information, sorted by PC.
6673
6674 struct IndexEntry {
6675 uint32_t FunctionOffset;
6676 uint32_t SecondLevelPageStart;
6677 uint32_t LSDAStart;
6678 };
6679
6680 SmallVector<IndexEntry, 4> IndexEntries;
6681
6682 outs() << " Top level indices: (count = " << NumIndices << ")\n";
6683 Pos = Contents.data() + IndicesStart;
6684 for (unsigned i = 0; i < NumIndices; ++i) {
6685 IndexEntry Entry;
6686
6687 Entry.FunctionOffset = readNext<uint32_t>(Pos);
6688 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
6689 Entry.LSDAStart = readNext<uint32_t>(Pos);
6690 IndexEntries.push_back(Entry);
6691
6692 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006693 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
6694 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00006695 << "2nd level page offset="
6696 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006697 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006698 }
6699
Tim Northover39c70bb2014-08-12 11:52:59 +00006700 //===----------------------------------
6701 // Next come the LSDA tables
6702 //===----------------------------------
6703
6704 // The LSDA layout is rather implicit: it's a contiguous array of entries from
6705 // the first top-level index's LSDAOffset to the last (sentinel).
6706
6707 outs() << " LSDA descriptors:\n";
6708 Pos = Contents.data() + IndexEntries[0].LSDAStart;
6709 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
6710 (2 * sizeof(uint32_t));
6711 for (int i = 0; i < NumLSDAs; ++i) {
6712 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6713 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
6714 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006715 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6716 << ", "
6717 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006718 }
6719
6720 //===----------------------------------
6721 // Finally, the 2nd level indices
6722 //===----------------------------------
6723
6724 // Generally these are 4K in size, and have 2 possible forms:
6725 // + Regular stores up to 511 entries with disparate encodings
6726 // + Compressed stores up to 1021 entries if few enough compact encoding
6727 // values are used.
6728 outs() << " Second level indices:\n";
6729 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
6730 // The final sentinel top-level index has no associated 2nd level page
6731 if (IndexEntries[i].SecondLevelPageStart == 0)
6732 break;
6733
6734 outs() << " Second level index[" << i << "]: "
6735 << "offset in section="
6736 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
6737 << ", "
6738 << "base function offset="
6739 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
6740
6741 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
Aaron Ballman80930af2014-08-14 13:53:19 +00006742 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00006743 if (Kind == 2)
6744 printRegularSecondLevelUnwindPage(Pos);
6745 else if (Kind == 3)
6746 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
6747 CommonEncodings);
6748 else
6749 llvm_unreachable("Do not know how to print this kind of 2nd level page");
Tim Northover39c70bb2014-08-12 11:52:59 +00006750 }
6751}
6752
Pete Cooper98052532015-12-18 19:45:38 +00006753static unsigned getSizeForEncoding(bool is64Bit,
6754 unsigned symbolEncoding) {
6755 unsigned format = symbolEncoding & 0x0f;
6756 switch (format) {
6757 default: llvm_unreachable("Unknown Encoding");
6758 case dwarf::DW_EH_PE_absptr:
6759 case dwarf::DW_EH_PE_signed:
6760 return is64Bit ? 8 : 4;
6761 case dwarf::DW_EH_PE_udata2:
6762 case dwarf::DW_EH_PE_sdata2:
6763 return 2;
6764 case dwarf::DW_EH_PE_udata4:
6765 case dwarf::DW_EH_PE_sdata4:
6766 return 4;
6767 case dwarf::DW_EH_PE_udata8:
6768 case dwarf::DW_EH_PE_sdata8:
6769 return 8;
6770 }
6771}
6772
6773static uint64_t readPointer(const char *&Pos, bool is64Bit, unsigned Encoding) {
6774 switch (getSizeForEncoding(is64Bit, Encoding)) {
6775 case 2:
6776 return readNext<uint16_t>(Pos);
6777 break;
6778 case 4:
6779 return readNext<uint32_t>(Pos);
6780 break;
6781 case 8:
6782 return readNext<uint64_t>(Pos);
6783 break;
6784 default:
6785 llvm_unreachable("Illegal data size");
6786 }
6787}
6788
6789static void printMachOEHFrameSection(const MachOObjectFile *Obj,
6790 std::map<uint64_t, SymbolRef> &Symbols,
6791 const SectionRef &EHFrame) {
6792 if (!Obj->isLittleEndian()) {
6793 outs() << "warning: cannot handle big endian __eh_frame section\n";
6794 return;
6795 }
6796
6797 bool is64Bit = Obj->is64Bit();
6798
6799 outs() << "Contents of __eh_frame section:\n";
6800
6801 StringRef Contents;
6802 EHFrame.getContents(Contents);
6803
6804 /// A few fields of the CIE are used when decoding the FDE's. This struct
6805 /// will cache those fields we need so that we don't have to decode it
6806 /// repeatedly for each FDE that references it.
6807 struct DecodedCIE {
6808 Optional<uint32_t> FDEPointerEncoding;
6809 Optional<uint32_t> LSDAPointerEncoding;
6810 bool hasAugmentationLength;
6811 };
6812
6813 // Map from the start offset of the CIE to the cached data for that CIE.
6814 DenseMap<uint64_t, DecodedCIE> CachedCIEs;
6815
6816 for (const char *Pos = Contents.data(), *End = Contents.end(); Pos != End; ) {
6817
6818 const char *EntryStartPos = Pos;
6819
6820 uint64_t Length = readNext<uint32_t>(Pos);
6821 if (Length == 0xffffffff)
6822 Length = readNext<uint64_t>(Pos);
6823
6824 // Save the Pos so that we can check the length we encoded against what we
6825 // end up decoding.
6826 const char *PosAfterLength = Pos;
6827 const char *EntryEndPos = PosAfterLength + Length;
6828
6829 assert(EntryEndPos <= End &&
6830 "__eh_frame entry length exceeds section size");
6831
6832 uint32_t ID = readNext<uint32_t>(Pos);
6833 if (ID == 0) {
6834 // This is a CIE.
6835
6836 uint32_t Version = readNext<uint8_t>(Pos);
6837
6838 // Parse a null terminated augmentation string
6839 SmallString<8> AugmentationString;
6840 for (uint8_t Char = readNext<uint8_t>(Pos); Char;
6841 Char = readNext<uint8_t>(Pos))
6842 AugmentationString.push_back(Char);
6843
6844 // Optionally parse the EH data if the augmentation string says it's there.
6845 Optional<uint64_t> EHData;
6846 if (StringRef(AugmentationString).count("eh"))
6847 EHData = is64Bit ? readNext<uint64_t>(Pos) : readNext<uint32_t>(Pos);
6848
6849 unsigned ULEBByteCount;
6850 uint64_t CodeAlignmentFactor = decodeULEB128((const uint8_t *)Pos,
6851 &ULEBByteCount);
6852 Pos += ULEBByteCount;
6853
6854 int64_t DataAlignmentFactor = decodeSLEB128((const uint8_t *)Pos,
6855 &ULEBByteCount);
6856 Pos += ULEBByteCount;
6857
6858 uint32_t ReturnAddressRegister = readNext<uint8_t>(Pos);
6859
6860 Optional<uint64_t> AugmentationLength;
6861 Optional<uint32_t> LSDAPointerEncoding;
6862 Optional<uint32_t> PersonalityEncoding;
6863 Optional<uint64_t> Personality;
6864 Optional<uint32_t> FDEPointerEncoding;
6865 if (!AugmentationString.empty() && AugmentationString.front() == 'z') {
6866 AugmentationLength = decodeULEB128((const uint8_t *)Pos,
6867 &ULEBByteCount);
6868 Pos += ULEBByteCount;
6869
6870 // Walk the augmentation string to get all the augmentation data.
6871 for (unsigned i = 1, e = AugmentationString.size(); i != e; ++i) {
6872 char Char = AugmentationString[i];
6873 switch (Char) {
6874 case 'e':
6875 assert((i + 1) != e && AugmentationString[i + 1] == 'h' &&
6876 "Expected 'eh' in augmentation string");
6877 break;
6878 case 'L':
6879 assert(!LSDAPointerEncoding && "Duplicate LSDA encoding");
6880 LSDAPointerEncoding = readNext<uint8_t>(Pos);
6881 break;
6882 case 'P': {
6883 assert(!Personality && "Duplicate personality");
6884 PersonalityEncoding = readNext<uint8_t>(Pos);
6885 Personality = readPointer(Pos, is64Bit, *PersonalityEncoding);
6886 break;
6887 }
6888 case 'R':
6889 assert(!FDEPointerEncoding && "Duplicate FDE encoding");
6890 FDEPointerEncoding = readNext<uint8_t>(Pos);
6891 break;
6892 case 'z':
6893 llvm_unreachable("'z' must be first in the augmentation string");
6894 }
6895 }
6896 }
6897
6898 outs() << "CIE:\n";
6899 outs() << " Length: " << Length << "\n";
6900 outs() << " CIE ID: " << ID << "\n";
6901 outs() << " Version: " << Version << "\n";
6902 outs() << " Augmentation String: " << AugmentationString << "\n";
6903 if (EHData)
6904 outs() << " EHData: " << *EHData << "\n";
6905 outs() << " Code Alignment Factor: " << CodeAlignmentFactor << "\n";
6906 outs() << " Data Alignment Factor: " << DataAlignmentFactor << "\n";
6907 outs() << " Return Address Register: " << ReturnAddressRegister << "\n";
6908 if (AugmentationLength) {
6909 outs() << " Augmentation Data Length: " << *AugmentationLength << "\n";
6910 if (LSDAPointerEncoding) {
6911 outs() << " FDE LSDA Pointer Encoding: "
6912 << *LSDAPointerEncoding << "\n";
6913 }
6914 if (Personality) {
6915 outs() << " Personality Encoding: " << *PersonalityEncoding << "\n";
6916 outs() << " Personality: " << *Personality << "\n";
6917 }
6918 if (FDEPointerEncoding) {
6919 outs() << " FDE Address Pointer Encoding: "
6920 << *FDEPointerEncoding << "\n";
6921 }
6922 }
6923 // FIXME: Handle instructions.
6924 // For now just emit some bytes
6925 outs() << " Instructions:\n ";
6926 dumpBytes(makeArrayRef((const uint8_t*)Pos, (const uint8_t*)EntryEndPos),
6927 outs());
6928 outs() << "\n";
6929 Pos = EntryEndPos;
6930
6931 // Cache this entry.
6932 uint64_t Offset = EntryStartPos - Contents.data();
6933 CachedCIEs[Offset] = { FDEPointerEncoding, LSDAPointerEncoding,
6934 AugmentationLength.hasValue() };
6935 continue;
6936 }
6937
6938 // This is an FDE.
6939 // The CIE pointer for an FDE is the same location as the ID which we
6940 // already read.
6941 uint32_t CIEPointer = ID;
6942
6943 const char *CIEStart = PosAfterLength - CIEPointer;
6944 assert(CIEStart >= Contents.data() &&
6945 "FDE points to CIE before the __eh_frame start");
6946
6947 uint64_t CIEOffset = CIEStart - Contents.data();
6948 auto CIEIt = CachedCIEs.find(CIEOffset);
6949 if (CIEIt == CachedCIEs.end())
6950 llvm_unreachable("Couldn't find CIE at offset in to __eh_frame section");
6951
6952 const DecodedCIE &CIE = CIEIt->getSecond();
6953 assert(CIE.FDEPointerEncoding &&
6954 "FDE references CIE which did not set pointer encoding");
6955
6956 uint64_t PCPointerSize = getSizeForEncoding(is64Bit,
6957 *CIE.FDEPointerEncoding);
6958
6959 uint64_t PCBegin = readPointer(Pos, is64Bit, *CIE.FDEPointerEncoding);
6960 uint64_t PCRange = readPointer(Pos, is64Bit, *CIE.FDEPointerEncoding);
6961
6962 Optional<uint64_t> AugmentationLength;
6963 uint32_t LSDAPointerSize;
6964 Optional<uint64_t> LSDAPointer;
6965 if (CIE.hasAugmentationLength) {
6966 unsigned ULEBByteCount;
6967 AugmentationLength = decodeULEB128((const uint8_t *)Pos,
6968 &ULEBByteCount);
6969 Pos += ULEBByteCount;
6970
6971 // Decode the LSDA if the CIE augmentation string said we should.
6972 if (CIE.LSDAPointerEncoding) {
6973 LSDAPointerSize = getSizeForEncoding(is64Bit, *CIE.LSDAPointerEncoding);
6974 LSDAPointer = readPointer(Pos, is64Bit, *CIE.LSDAPointerEncoding);
6975 }
6976 }
6977
6978 outs() << "FDE:\n";
6979 outs() << " Length: " << Length << "\n";
6980 outs() << " CIE Offset: " << CIEOffset << "\n";
6981
6982 if (PCPointerSize == 8) {
6983 outs() << format(" PC Begin: %016" PRIx64, PCBegin) << "\n";
6984 outs() << format(" PC Range: %016" PRIx64, PCRange) << "\n";
6985 } else {
6986 outs() << format(" PC Begin: %08" PRIx64, PCBegin) << "\n";
6987 outs() << format(" PC Range: %08" PRIx64, PCRange) << "\n";
6988 }
6989 if (AugmentationLength) {
6990 outs() << " Augmentation Data Length: " << *AugmentationLength << "\n";
6991 if (LSDAPointer) {
6992 if (LSDAPointerSize == 8)
6993 outs() << format(" LSDA Pointer: %016\n" PRIx64, *LSDAPointer);
6994 else
6995 outs() << format(" LSDA Pointer: %08\n" PRIx64, *LSDAPointer);
6996 }
6997 }
6998
6999 // FIXME: Handle instructions.
7000 // For now just emit some bytes
7001 outs() << " Instructions:\n ";
7002 dumpBytes(makeArrayRef((const uint8_t*)Pos, (const uint8_t*)EntryEndPos),
7003 outs());
7004 outs() << "\n";
7005 Pos = EntryEndPos;
7006 }
7007}
7008
Tim Northover4bd286a2014-08-01 13:07:19 +00007009void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
7010 std::map<uint64_t, SymbolRef> Symbols;
7011 for (const SymbolRef &SymRef : Obj->symbols()) {
7012 // Discard any undefined or absolute symbols. They're not going to take part
7013 // in the convenience lookup for unwind info and just take up resources.
Rafael Espindola8bab8892015-08-07 23:27:14 +00007014 section_iterator Section = *SymRef.getSection();
Tim Northover4bd286a2014-08-01 13:07:19 +00007015 if (Section == Obj->section_end())
7016 continue;
7017
Rafael Espindoladea00162015-07-03 17:44:18 +00007018 uint64_t Addr = SymRef.getValue();
Tim Northover4bd286a2014-08-01 13:07:19 +00007019 Symbols.insert(std::make_pair(Addr, SymRef));
7020 }
7021
7022 for (const SectionRef &Section : Obj->sections()) {
7023 StringRef SectName;
7024 Section.getName(SectName);
7025 if (SectName == "__compact_unwind")
7026 printMachOCompactUnwindSection(Obj, Symbols, Section);
7027 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00007028 printMachOUnwindInfoSection(Obj, Symbols, Section);
Pete Cooper98052532015-12-18 19:45:38 +00007029 else if (SectName == "__eh_frame")
7030 printMachOEHFrameSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00007031 }
7032}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007033
7034static void PrintMachHeader(uint32_t magic, uint32_t cputype,
7035 uint32_t cpusubtype, uint32_t filetype,
7036 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
7037 bool verbose) {
7038 outs() << "Mach header\n";
7039 outs() << " magic cputype cpusubtype caps filetype ncmds "
7040 "sizeofcmds flags\n";
7041 if (verbose) {
7042 if (magic == MachO::MH_MAGIC)
7043 outs() << " MH_MAGIC";
7044 else if (magic == MachO::MH_MAGIC_64)
7045 outs() << "MH_MAGIC_64";
7046 else
7047 outs() << format(" 0x%08" PRIx32, magic);
7048 switch (cputype) {
7049 case MachO::CPU_TYPE_I386:
7050 outs() << " I386";
7051 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7052 case MachO::CPU_SUBTYPE_I386_ALL:
7053 outs() << " ALL";
7054 break;
7055 default:
7056 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7057 break;
7058 }
7059 break;
7060 case MachO::CPU_TYPE_X86_64:
7061 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00007062 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7063 case MachO::CPU_SUBTYPE_X86_64_ALL:
7064 outs() << " ALL";
7065 break;
7066 case MachO::CPU_SUBTYPE_X86_64_H:
7067 outs() << " Haswell";
7068 break;
7069 default:
7070 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7071 break;
7072 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007073 break;
7074 case MachO::CPU_TYPE_ARM:
7075 outs() << " ARM";
7076 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7077 case MachO::CPU_SUBTYPE_ARM_ALL:
7078 outs() << " ALL";
7079 break;
7080 case MachO::CPU_SUBTYPE_ARM_V4T:
7081 outs() << " V4T";
7082 break;
7083 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
7084 outs() << " V5TEJ";
7085 break;
7086 case MachO::CPU_SUBTYPE_ARM_XSCALE:
7087 outs() << " XSCALE";
7088 break;
7089 case MachO::CPU_SUBTYPE_ARM_V6:
7090 outs() << " V6";
7091 break;
7092 case MachO::CPU_SUBTYPE_ARM_V6M:
7093 outs() << " V6M";
7094 break;
7095 case MachO::CPU_SUBTYPE_ARM_V7:
7096 outs() << " V7";
7097 break;
7098 case MachO::CPU_SUBTYPE_ARM_V7EM:
7099 outs() << " V7EM";
7100 break;
7101 case MachO::CPU_SUBTYPE_ARM_V7K:
7102 outs() << " V7K";
7103 break;
7104 case MachO::CPU_SUBTYPE_ARM_V7M:
7105 outs() << " V7M";
7106 break;
7107 case MachO::CPU_SUBTYPE_ARM_V7S:
7108 outs() << " V7S";
7109 break;
7110 default:
7111 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7112 break;
7113 }
7114 break;
7115 case MachO::CPU_TYPE_ARM64:
7116 outs() << " ARM64";
7117 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7118 case MachO::CPU_SUBTYPE_ARM64_ALL:
7119 outs() << " ALL";
7120 break;
7121 default:
7122 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7123 break;
7124 }
7125 break;
7126 case MachO::CPU_TYPE_POWERPC:
7127 outs() << " PPC";
7128 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7129 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7130 outs() << " ALL";
7131 break;
7132 default:
7133 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7134 break;
7135 }
7136 break;
7137 case MachO::CPU_TYPE_POWERPC64:
7138 outs() << " PPC64";
7139 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7140 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7141 outs() << " ALL";
7142 break;
7143 default:
7144 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7145 break;
7146 }
7147 break;
7148 }
7149 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007150 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007151 } else {
7152 outs() << format(" 0x%02" PRIx32,
7153 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7154 }
7155 switch (filetype) {
7156 case MachO::MH_OBJECT:
7157 outs() << " OBJECT";
7158 break;
7159 case MachO::MH_EXECUTE:
7160 outs() << " EXECUTE";
7161 break;
7162 case MachO::MH_FVMLIB:
7163 outs() << " FVMLIB";
7164 break;
7165 case MachO::MH_CORE:
7166 outs() << " CORE";
7167 break;
7168 case MachO::MH_PRELOAD:
7169 outs() << " PRELOAD";
7170 break;
7171 case MachO::MH_DYLIB:
7172 outs() << " DYLIB";
7173 break;
7174 case MachO::MH_DYLIB_STUB:
7175 outs() << " DYLIB_STUB";
7176 break;
7177 case MachO::MH_DYLINKER:
7178 outs() << " DYLINKER";
7179 break;
7180 case MachO::MH_BUNDLE:
7181 outs() << " BUNDLE";
7182 break;
7183 case MachO::MH_DSYM:
7184 outs() << " DSYM";
7185 break;
7186 case MachO::MH_KEXT_BUNDLE:
7187 outs() << " KEXTBUNDLE";
7188 break;
7189 default:
7190 outs() << format(" %10u", filetype);
7191 break;
7192 }
7193 outs() << format(" %5u", ncmds);
7194 outs() << format(" %10u", sizeofcmds);
7195 uint32_t f = flags;
7196 if (f & MachO::MH_NOUNDEFS) {
7197 outs() << " NOUNDEFS";
7198 f &= ~MachO::MH_NOUNDEFS;
7199 }
7200 if (f & MachO::MH_INCRLINK) {
7201 outs() << " INCRLINK";
7202 f &= ~MachO::MH_INCRLINK;
7203 }
7204 if (f & MachO::MH_DYLDLINK) {
7205 outs() << " DYLDLINK";
7206 f &= ~MachO::MH_DYLDLINK;
7207 }
7208 if (f & MachO::MH_BINDATLOAD) {
7209 outs() << " BINDATLOAD";
7210 f &= ~MachO::MH_BINDATLOAD;
7211 }
7212 if (f & MachO::MH_PREBOUND) {
7213 outs() << " PREBOUND";
7214 f &= ~MachO::MH_PREBOUND;
7215 }
7216 if (f & MachO::MH_SPLIT_SEGS) {
7217 outs() << " SPLIT_SEGS";
7218 f &= ~MachO::MH_SPLIT_SEGS;
7219 }
7220 if (f & MachO::MH_LAZY_INIT) {
7221 outs() << " LAZY_INIT";
7222 f &= ~MachO::MH_LAZY_INIT;
7223 }
7224 if (f & MachO::MH_TWOLEVEL) {
7225 outs() << " TWOLEVEL";
7226 f &= ~MachO::MH_TWOLEVEL;
7227 }
7228 if (f & MachO::MH_FORCE_FLAT) {
7229 outs() << " FORCE_FLAT";
7230 f &= ~MachO::MH_FORCE_FLAT;
7231 }
7232 if (f & MachO::MH_NOMULTIDEFS) {
7233 outs() << " NOMULTIDEFS";
7234 f &= ~MachO::MH_NOMULTIDEFS;
7235 }
7236 if (f & MachO::MH_NOFIXPREBINDING) {
7237 outs() << " NOFIXPREBINDING";
7238 f &= ~MachO::MH_NOFIXPREBINDING;
7239 }
7240 if (f & MachO::MH_PREBINDABLE) {
7241 outs() << " PREBINDABLE";
7242 f &= ~MachO::MH_PREBINDABLE;
7243 }
7244 if (f & MachO::MH_ALLMODSBOUND) {
7245 outs() << " ALLMODSBOUND";
7246 f &= ~MachO::MH_ALLMODSBOUND;
7247 }
7248 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
7249 outs() << " SUBSECTIONS_VIA_SYMBOLS";
7250 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
7251 }
7252 if (f & MachO::MH_CANONICAL) {
7253 outs() << " CANONICAL";
7254 f &= ~MachO::MH_CANONICAL;
7255 }
7256 if (f & MachO::MH_WEAK_DEFINES) {
7257 outs() << " WEAK_DEFINES";
7258 f &= ~MachO::MH_WEAK_DEFINES;
7259 }
7260 if (f & MachO::MH_BINDS_TO_WEAK) {
7261 outs() << " BINDS_TO_WEAK";
7262 f &= ~MachO::MH_BINDS_TO_WEAK;
7263 }
7264 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
7265 outs() << " ALLOW_STACK_EXECUTION";
7266 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
7267 }
7268 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
7269 outs() << " DEAD_STRIPPABLE_DYLIB";
7270 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
7271 }
7272 if (f & MachO::MH_PIE) {
7273 outs() << " PIE";
7274 f &= ~MachO::MH_PIE;
7275 }
7276 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
7277 outs() << " NO_REEXPORTED_DYLIBS";
7278 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
7279 }
7280 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
7281 outs() << " MH_HAS_TLV_DESCRIPTORS";
7282 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
7283 }
7284 if (f & MachO::MH_NO_HEAP_EXECUTION) {
7285 outs() << " MH_NO_HEAP_EXECUTION";
7286 f &= ~MachO::MH_NO_HEAP_EXECUTION;
7287 }
7288 if (f & MachO::MH_APP_EXTENSION_SAFE) {
7289 outs() << " APP_EXTENSION_SAFE";
7290 f &= ~MachO::MH_APP_EXTENSION_SAFE;
7291 }
7292 if (f != 0 || flags == 0)
7293 outs() << format(" 0x%08" PRIx32, f);
7294 } else {
7295 outs() << format(" 0x%08" PRIx32, magic);
7296 outs() << format(" %7d", cputype);
7297 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7298 outs() << format(" 0x%02" PRIx32,
7299 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7300 outs() << format(" %10u", filetype);
7301 outs() << format(" %5u", ncmds);
7302 outs() << format(" %10u", sizeofcmds);
7303 outs() << format(" 0x%08" PRIx32, flags);
7304 }
7305 outs() << "\n";
7306}
7307
Kevin Enderby956366c2014-08-29 22:30:52 +00007308static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
7309 StringRef SegName, uint64_t vmaddr,
7310 uint64_t vmsize, uint64_t fileoff,
7311 uint64_t filesize, uint32_t maxprot,
7312 uint32_t initprot, uint32_t nsects,
7313 uint32_t flags, uint32_t object_size,
7314 bool verbose) {
7315 uint64_t expected_cmdsize;
7316 if (cmd == MachO::LC_SEGMENT) {
7317 outs() << " cmd LC_SEGMENT\n";
7318 expected_cmdsize = nsects;
7319 expected_cmdsize *= sizeof(struct MachO::section);
7320 expected_cmdsize += sizeof(struct MachO::segment_command);
7321 } else {
7322 outs() << " cmd LC_SEGMENT_64\n";
7323 expected_cmdsize = nsects;
7324 expected_cmdsize *= sizeof(struct MachO::section_64);
7325 expected_cmdsize += sizeof(struct MachO::segment_command_64);
7326 }
7327 outs() << " cmdsize " << cmdsize;
7328 if (cmdsize != expected_cmdsize)
7329 outs() << " Inconsistent size\n";
7330 else
7331 outs() << "\n";
7332 outs() << " segname " << SegName << "\n";
7333 if (cmd == MachO::LC_SEGMENT_64) {
7334 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
7335 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
7336 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00007337 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
7338 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00007339 }
7340 outs() << " fileoff " << fileoff;
7341 if (fileoff > object_size)
7342 outs() << " (past end of file)\n";
7343 else
7344 outs() << "\n";
7345 outs() << " filesize " << filesize;
7346 if (fileoff + filesize > object_size)
7347 outs() << " (past end of file)\n";
7348 else
7349 outs() << "\n";
7350 if (verbose) {
7351 if ((maxprot &
7352 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7353 MachO::VM_PROT_EXECUTE)) != 0)
7354 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
7355 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00007356 outs() << " maxprot ";
7357 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
7358 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7359 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007360 }
7361 if ((initprot &
7362 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7363 MachO::VM_PROT_EXECUTE)) != 0)
7364 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
7365 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00007366 outs() << " initprot ";
7367 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
7368 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7369 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007370 }
7371 } else {
7372 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
7373 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
7374 }
7375 outs() << " nsects " << nsects << "\n";
7376 if (verbose) {
7377 outs() << " flags";
7378 if (flags == 0)
7379 outs() << " (none)\n";
7380 else {
7381 if (flags & MachO::SG_HIGHVM) {
7382 outs() << " HIGHVM";
7383 flags &= ~MachO::SG_HIGHVM;
7384 }
7385 if (flags & MachO::SG_FVMLIB) {
7386 outs() << " FVMLIB";
7387 flags &= ~MachO::SG_FVMLIB;
7388 }
7389 if (flags & MachO::SG_NORELOC) {
7390 outs() << " NORELOC";
7391 flags &= ~MachO::SG_NORELOC;
7392 }
7393 if (flags & MachO::SG_PROTECTED_VERSION_1) {
7394 outs() << " PROTECTED_VERSION_1";
7395 flags &= ~MachO::SG_PROTECTED_VERSION_1;
7396 }
7397 if (flags)
7398 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
7399 else
7400 outs() << "\n";
7401 }
7402 } else {
7403 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
7404 }
7405}
7406
7407static void PrintSection(const char *sectname, const char *segname,
7408 uint64_t addr, uint64_t size, uint32_t offset,
7409 uint32_t align, uint32_t reloff, uint32_t nreloc,
7410 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
7411 uint32_t cmd, const char *sg_segname,
7412 uint32_t filetype, uint32_t object_size,
7413 bool verbose) {
7414 outs() << "Section\n";
7415 outs() << " sectname " << format("%.16s\n", sectname);
7416 outs() << " segname " << format("%.16s", segname);
7417 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
7418 outs() << " (does not match segment)\n";
7419 else
7420 outs() << "\n";
7421 if (cmd == MachO::LC_SEGMENT_64) {
7422 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
7423 outs() << " size " << format("0x%016" PRIx64, size);
7424 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00007425 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
7426 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00007427 }
7428 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
7429 outs() << " (past end of file)\n";
7430 else
7431 outs() << "\n";
7432 outs() << " offset " << offset;
7433 if (offset > object_size)
7434 outs() << " (past end of file)\n";
7435 else
7436 outs() << "\n";
7437 uint32_t align_shifted = 1 << align;
7438 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
7439 outs() << " reloff " << reloff;
7440 if (reloff > object_size)
7441 outs() << " (past end of file)\n";
7442 else
7443 outs() << "\n";
7444 outs() << " nreloc " << nreloc;
7445 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
7446 outs() << " (past end of file)\n";
7447 else
7448 outs() << "\n";
7449 uint32_t section_type = flags & MachO::SECTION_TYPE;
7450 if (verbose) {
7451 outs() << " type";
7452 if (section_type == MachO::S_REGULAR)
7453 outs() << " S_REGULAR\n";
7454 else if (section_type == MachO::S_ZEROFILL)
7455 outs() << " S_ZEROFILL\n";
7456 else if (section_type == MachO::S_CSTRING_LITERALS)
7457 outs() << " S_CSTRING_LITERALS\n";
7458 else if (section_type == MachO::S_4BYTE_LITERALS)
7459 outs() << " S_4BYTE_LITERALS\n";
7460 else if (section_type == MachO::S_8BYTE_LITERALS)
7461 outs() << " S_8BYTE_LITERALS\n";
7462 else if (section_type == MachO::S_16BYTE_LITERALS)
7463 outs() << " S_16BYTE_LITERALS\n";
7464 else if (section_type == MachO::S_LITERAL_POINTERS)
7465 outs() << " S_LITERAL_POINTERS\n";
7466 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
7467 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
7468 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
7469 outs() << " S_LAZY_SYMBOL_POINTERS\n";
7470 else if (section_type == MachO::S_SYMBOL_STUBS)
7471 outs() << " S_SYMBOL_STUBS\n";
7472 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
7473 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
7474 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
7475 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
7476 else if (section_type == MachO::S_COALESCED)
7477 outs() << " S_COALESCED\n";
7478 else if (section_type == MachO::S_INTERPOSING)
7479 outs() << " S_INTERPOSING\n";
7480 else if (section_type == MachO::S_DTRACE_DOF)
7481 outs() << " S_DTRACE_DOF\n";
7482 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
7483 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
7484 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
7485 outs() << " S_THREAD_LOCAL_REGULAR\n";
7486 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
7487 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
7488 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
7489 outs() << " S_THREAD_LOCAL_VARIABLES\n";
7490 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7491 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
7492 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
7493 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
7494 else
7495 outs() << format("0x%08" PRIx32, section_type) << "\n";
7496 outs() << "attributes";
7497 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
7498 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
7499 outs() << " PURE_INSTRUCTIONS";
7500 if (section_attributes & MachO::S_ATTR_NO_TOC)
7501 outs() << " NO_TOC";
7502 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
7503 outs() << " STRIP_STATIC_SYMS";
7504 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
7505 outs() << " NO_DEAD_STRIP";
7506 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
7507 outs() << " LIVE_SUPPORT";
7508 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
7509 outs() << " SELF_MODIFYING_CODE";
7510 if (section_attributes & MachO::S_ATTR_DEBUG)
7511 outs() << " DEBUG";
7512 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
7513 outs() << " SOME_INSTRUCTIONS";
7514 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
7515 outs() << " EXT_RELOC";
7516 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
7517 outs() << " LOC_RELOC";
7518 if (section_attributes == 0)
7519 outs() << " (none)";
7520 outs() << "\n";
7521 } else
7522 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
7523 outs() << " reserved1 " << reserved1;
7524 if (section_type == MachO::S_SYMBOL_STUBS ||
7525 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
7526 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
7527 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
7528 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7529 outs() << " (index into indirect symbol table)\n";
7530 else
7531 outs() << "\n";
7532 outs() << " reserved2 " << reserved2;
7533 if (section_type == MachO::S_SYMBOL_STUBS)
7534 outs() << " (size of stubs)\n";
7535 else
7536 outs() << "\n";
7537}
7538
David Majnemer73cc6ff2014-11-13 19:48:56 +00007539static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00007540 uint32_t object_size) {
7541 outs() << " cmd LC_SYMTAB\n";
7542 outs() << " cmdsize " << st.cmdsize;
7543 if (st.cmdsize != sizeof(struct MachO::symtab_command))
7544 outs() << " Incorrect size\n";
7545 else
7546 outs() << "\n";
7547 outs() << " symoff " << st.symoff;
7548 if (st.symoff > object_size)
7549 outs() << " (past end of file)\n";
7550 else
7551 outs() << "\n";
7552 outs() << " nsyms " << st.nsyms;
7553 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00007554 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007555 big_size = st.nsyms;
7556 big_size *= sizeof(struct MachO::nlist_64);
7557 big_size += st.symoff;
7558 if (big_size > object_size)
7559 outs() << " (past end of file)\n";
7560 else
7561 outs() << "\n";
7562 } else {
7563 big_size = st.nsyms;
7564 big_size *= sizeof(struct MachO::nlist);
7565 big_size += st.symoff;
7566 if (big_size > object_size)
7567 outs() << " (past end of file)\n";
7568 else
7569 outs() << "\n";
7570 }
7571 outs() << " stroff " << st.stroff;
7572 if (st.stroff > object_size)
7573 outs() << " (past end of file)\n";
7574 else
7575 outs() << "\n";
7576 outs() << " strsize " << st.strsize;
7577 big_size = st.stroff;
7578 big_size += st.strsize;
7579 if (big_size > object_size)
7580 outs() << " (past end of file)\n";
7581 else
7582 outs() << "\n";
7583}
7584
7585static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
7586 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00007587 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007588 outs() << " cmd LC_DYSYMTAB\n";
7589 outs() << " cmdsize " << dyst.cmdsize;
7590 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
7591 outs() << " Incorrect size\n";
7592 else
7593 outs() << "\n";
7594 outs() << " ilocalsym " << dyst.ilocalsym;
7595 if (dyst.ilocalsym > nsyms)
7596 outs() << " (greater than the number of symbols)\n";
7597 else
7598 outs() << "\n";
7599 outs() << " nlocalsym " << dyst.nlocalsym;
7600 uint64_t big_size;
7601 big_size = dyst.ilocalsym;
7602 big_size += dyst.nlocalsym;
7603 if (big_size > nsyms)
7604 outs() << " (past the end of the symbol table)\n";
7605 else
7606 outs() << "\n";
7607 outs() << " iextdefsym " << dyst.iextdefsym;
7608 if (dyst.iextdefsym > nsyms)
7609 outs() << " (greater than the number of symbols)\n";
7610 else
7611 outs() << "\n";
7612 outs() << " nextdefsym " << dyst.nextdefsym;
7613 big_size = dyst.iextdefsym;
7614 big_size += dyst.nextdefsym;
7615 if (big_size > nsyms)
7616 outs() << " (past the end of the symbol table)\n";
7617 else
7618 outs() << "\n";
7619 outs() << " iundefsym " << dyst.iundefsym;
7620 if (dyst.iundefsym > nsyms)
7621 outs() << " (greater than the number of symbols)\n";
7622 else
7623 outs() << "\n";
7624 outs() << " nundefsym " << dyst.nundefsym;
7625 big_size = dyst.iundefsym;
7626 big_size += dyst.nundefsym;
7627 if (big_size > nsyms)
7628 outs() << " (past the end of the symbol table)\n";
7629 else
7630 outs() << "\n";
7631 outs() << " tocoff " << dyst.tocoff;
7632 if (dyst.tocoff > object_size)
7633 outs() << " (past end of file)\n";
7634 else
7635 outs() << "\n";
7636 outs() << " ntoc " << dyst.ntoc;
7637 big_size = dyst.ntoc;
7638 big_size *= sizeof(struct MachO::dylib_table_of_contents);
7639 big_size += dyst.tocoff;
7640 if (big_size > object_size)
7641 outs() << " (past end of file)\n";
7642 else
7643 outs() << "\n";
7644 outs() << " modtaboff " << dyst.modtaboff;
7645 if (dyst.modtaboff > object_size)
7646 outs() << " (past end of file)\n";
7647 else
7648 outs() << "\n";
7649 outs() << " nmodtab " << dyst.nmodtab;
7650 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00007651 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007652 modtabend = dyst.nmodtab;
7653 modtabend *= sizeof(struct MachO::dylib_module_64);
7654 modtabend += dyst.modtaboff;
7655 } else {
7656 modtabend = dyst.nmodtab;
7657 modtabend *= sizeof(struct MachO::dylib_module);
7658 modtabend += dyst.modtaboff;
7659 }
7660 if (modtabend > object_size)
7661 outs() << " (past end of file)\n";
7662 else
7663 outs() << "\n";
7664 outs() << " extrefsymoff " << dyst.extrefsymoff;
7665 if (dyst.extrefsymoff > object_size)
7666 outs() << " (past end of file)\n";
7667 else
7668 outs() << "\n";
7669 outs() << " nextrefsyms " << dyst.nextrefsyms;
7670 big_size = dyst.nextrefsyms;
7671 big_size *= sizeof(struct MachO::dylib_reference);
7672 big_size += dyst.extrefsymoff;
7673 if (big_size > object_size)
7674 outs() << " (past end of file)\n";
7675 else
7676 outs() << "\n";
7677 outs() << " indirectsymoff " << dyst.indirectsymoff;
7678 if (dyst.indirectsymoff > object_size)
7679 outs() << " (past end of file)\n";
7680 else
7681 outs() << "\n";
7682 outs() << " nindirectsyms " << dyst.nindirectsyms;
7683 big_size = dyst.nindirectsyms;
7684 big_size *= sizeof(uint32_t);
7685 big_size += dyst.indirectsymoff;
7686 if (big_size > object_size)
7687 outs() << " (past end of file)\n";
7688 else
7689 outs() << "\n";
7690 outs() << " extreloff " << dyst.extreloff;
7691 if (dyst.extreloff > object_size)
7692 outs() << " (past end of file)\n";
7693 else
7694 outs() << "\n";
7695 outs() << " nextrel " << dyst.nextrel;
7696 big_size = dyst.nextrel;
7697 big_size *= sizeof(struct MachO::relocation_info);
7698 big_size += dyst.extreloff;
7699 if (big_size > object_size)
7700 outs() << " (past end of file)\n";
7701 else
7702 outs() << "\n";
7703 outs() << " locreloff " << dyst.locreloff;
7704 if (dyst.locreloff > object_size)
7705 outs() << " (past end of file)\n";
7706 else
7707 outs() << "\n";
7708 outs() << " nlocrel " << dyst.nlocrel;
7709 big_size = dyst.nlocrel;
7710 big_size *= sizeof(struct MachO::relocation_info);
7711 big_size += dyst.locreloff;
7712 if (big_size > object_size)
7713 outs() << " (past end of file)\n";
7714 else
7715 outs() << "\n";
7716}
7717
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007718static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
7719 uint32_t object_size) {
7720 if (dc.cmd == MachO::LC_DYLD_INFO)
7721 outs() << " cmd LC_DYLD_INFO\n";
7722 else
7723 outs() << " cmd LC_DYLD_INFO_ONLY\n";
7724 outs() << " cmdsize " << dc.cmdsize;
7725 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
7726 outs() << " Incorrect size\n";
7727 else
7728 outs() << "\n";
7729 outs() << " rebase_off " << dc.rebase_off;
7730 if (dc.rebase_off > object_size)
7731 outs() << " (past end of file)\n";
7732 else
7733 outs() << "\n";
7734 outs() << " rebase_size " << dc.rebase_size;
7735 uint64_t big_size;
7736 big_size = dc.rebase_off;
7737 big_size += dc.rebase_size;
7738 if (big_size > object_size)
7739 outs() << " (past end of file)\n";
7740 else
7741 outs() << "\n";
7742 outs() << " bind_off " << dc.bind_off;
7743 if (dc.bind_off > object_size)
7744 outs() << " (past end of file)\n";
7745 else
7746 outs() << "\n";
7747 outs() << " bind_size " << dc.bind_size;
7748 big_size = dc.bind_off;
7749 big_size += dc.bind_size;
7750 if (big_size > object_size)
7751 outs() << " (past end of file)\n";
7752 else
7753 outs() << "\n";
7754 outs() << " weak_bind_off " << dc.weak_bind_off;
7755 if (dc.weak_bind_off > object_size)
7756 outs() << " (past end of file)\n";
7757 else
7758 outs() << "\n";
7759 outs() << " weak_bind_size " << dc.weak_bind_size;
7760 big_size = dc.weak_bind_off;
7761 big_size += dc.weak_bind_size;
7762 if (big_size > object_size)
7763 outs() << " (past end of file)\n";
7764 else
7765 outs() << "\n";
7766 outs() << " lazy_bind_off " << dc.lazy_bind_off;
7767 if (dc.lazy_bind_off > object_size)
7768 outs() << " (past end of file)\n";
7769 else
7770 outs() << "\n";
7771 outs() << " lazy_bind_size " << dc.lazy_bind_size;
7772 big_size = dc.lazy_bind_off;
7773 big_size += dc.lazy_bind_size;
7774 if (big_size > object_size)
7775 outs() << " (past end of file)\n";
7776 else
7777 outs() << "\n";
7778 outs() << " export_off " << dc.export_off;
7779 if (dc.export_off > object_size)
7780 outs() << " (past end of file)\n";
7781 else
7782 outs() << "\n";
7783 outs() << " export_size " << dc.export_size;
7784 big_size = dc.export_off;
7785 big_size += dc.export_size;
7786 if (big_size > object_size)
7787 outs() << " (past end of file)\n";
7788 else
7789 outs() << "\n";
7790}
7791
7792static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
7793 const char *Ptr) {
7794 if (dyld.cmd == MachO::LC_ID_DYLINKER)
7795 outs() << " cmd LC_ID_DYLINKER\n";
7796 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
7797 outs() << " cmd LC_LOAD_DYLINKER\n";
7798 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
7799 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
7800 else
7801 outs() << " cmd ?(" << dyld.cmd << ")\n";
7802 outs() << " cmdsize " << dyld.cmdsize;
7803 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
7804 outs() << " Incorrect size\n";
7805 else
7806 outs() << "\n";
7807 if (dyld.name >= dyld.cmdsize)
7808 outs() << " name ?(bad offset " << dyld.name << ")\n";
7809 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007810 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007811 outs() << " name " << P << " (offset " << dyld.name << ")\n";
7812 }
7813}
7814
7815static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
7816 outs() << " cmd LC_UUID\n";
7817 outs() << " cmdsize " << uuid.cmdsize;
7818 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
7819 outs() << " Incorrect size\n";
7820 else
7821 outs() << "\n";
7822 outs() << " uuid ";
Davide Italianoc74277a2015-12-07 00:03:28 +00007823 for (int i = 0; i < 16; ++i) {
7824 outs() << format("%02" PRIX32, uuid.uuid[i]);
7825 if (i == 3 || i == 5 || i == 7 || i == 9)
7826 outs() << "-";
7827 }
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007828 outs() << "\n";
7829}
7830
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007831static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00007832 outs() << " cmd LC_RPATH\n";
7833 outs() << " cmdsize " << rpath.cmdsize;
7834 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
7835 outs() << " Incorrect size\n";
7836 else
7837 outs() << "\n";
7838 if (rpath.path >= rpath.cmdsize)
7839 outs() << " path ?(bad offset " << rpath.path << ")\n";
7840 else {
7841 const char *P = (const char *)(Ptr) + rpath.path;
7842 outs() << " path " << P << " (offset " << rpath.path << ")\n";
7843 }
7844}
7845
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007846static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
Tim Northoverbfbfb122015-11-02 21:26:58 +00007847 StringRef LoadCmdName;
7848 switch (vd.cmd) {
7849 case MachO::LC_VERSION_MIN_MACOSX:
7850 LoadCmdName = "LC_VERSION_MIN_MACOSX";
7851 break;
7852 case MachO::LC_VERSION_MIN_IPHONEOS:
7853 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
7854 break;
7855 case MachO::LC_VERSION_MIN_TVOS:
7856 LoadCmdName = "LC_VERSION_MIN_TVOS";
7857 break;
7858 case MachO::LC_VERSION_MIN_WATCHOS:
7859 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
7860 break;
7861 default:
7862 llvm_unreachable("Unknown version min load command");
7863 }
7864
7865 outs() << " cmd " << LoadCmdName << '\n';
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007866 outs() << " cmdsize " << vd.cmdsize;
7867 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
7868 outs() << " Incorrect size\n";
7869 else
7870 outs() << "\n";
Davide Italiano56baef32015-08-26 12:26:11 +00007871 outs() << " version "
7872 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
7873 << MachOObjectFile::getVersionMinMinor(vd, false);
7874 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
7875 if (Update != 0)
7876 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007877 outs() << "\n";
7878 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00007879 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007880 else {
Davide Italiano56baef32015-08-26 12:26:11 +00007881 outs() << " sdk "
7882 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
7883 << MachOObjectFile::getVersionMinMinor(vd, true);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007884 }
Davide Italiano56baef32015-08-26 12:26:11 +00007885 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
7886 if (Update != 0)
7887 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007888 outs() << "\n";
7889}
7890
7891static void PrintSourceVersionCommand(MachO::source_version_command sd) {
7892 outs() << " cmd LC_SOURCE_VERSION\n";
7893 outs() << " cmdsize " << sd.cmdsize;
7894 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
7895 outs() << " Incorrect size\n";
7896 else
7897 outs() << "\n";
7898 uint64_t a = (sd.version >> 40) & 0xffffff;
7899 uint64_t b = (sd.version >> 30) & 0x3ff;
7900 uint64_t c = (sd.version >> 20) & 0x3ff;
7901 uint64_t d = (sd.version >> 10) & 0x3ff;
7902 uint64_t e = sd.version & 0x3ff;
7903 outs() << " version " << a << "." << b;
7904 if (e != 0)
7905 outs() << "." << c << "." << d << "." << e;
7906 else if (d != 0)
7907 outs() << "." << c << "." << d;
7908 else if (c != 0)
7909 outs() << "." << c;
7910 outs() << "\n";
7911}
7912
7913static void PrintEntryPointCommand(MachO::entry_point_command ep) {
7914 outs() << " cmd LC_MAIN\n";
7915 outs() << " cmdsize " << ep.cmdsize;
7916 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
7917 outs() << " Incorrect size\n";
7918 else
7919 outs() << "\n";
7920 outs() << " entryoff " << ep.entryoff << "\n";
7921 outs() << " stacksize " << ep.stacksize << "\n";
7922}
7923
Kevin Enderby0804f4672014-12-16 23:25:52 +00007924static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
7925 uint32_t object_size) {
7926 outs() << " cmd LC_ENCRYPTION_INFO\n";
7927 outs() << " cmdsize " << ec.cmdsize;
7928 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
7929 outs() << " Incorrect size\n";
7930 else
7931 outs() << "\n";
7932 outs() << " cryptoff " << ec.cryptoff;
7933 if (ec.cryptoff > object_size)
7934 outs() << " (past end of file)\n";
7935 else
7936 outs() << "\n";
7937 outs() << " cryptsize " << ec.cryptsize;
7938 if (ec.cryptsize > object_size)
7939 outs() << " (past end of file)\n";
7940 else
7941 outs() << "\n";
7942 outs() << " cryptid " << ec.cryptid << "\n";
7943}
7944
Kevin Enderby57538292014-12-17 01:01:30 +00007945static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007946 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00007947 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
7948 outs() << " cmdsize " << ec.cmdsize;
7949 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
7950 outs() << " Incorrect size\n";
7951 else
7952 outs() << "\n";
7953 outs() << " cryptoff " << ec.cryptoff;
7954 if (ec.cryptoff > object_size)
7955 outs() << " (past end of file)\n";
7956 else
7957 outs() << "\n";
7958 outs() << " cryptsize " << ec.cryptsize;
7959 if (ec.cryptsize > object_size)
7960 outs() << " (past end of file)\n";
7961 else
7962 outs() << "\n";
7963 outs() << " cryptid " << ec.cryptid << "\n";
7964 outs() << " pad " << ec.pad << "\n";
7965}
7966
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00007967static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
7968 const char *Ptr) {
7969 outs() << " cmd LC_LINKER_OPTION\n";
7970 outs() << " cmdsize " << lo.cmdsize;
7971 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
7972 outs() << " Incorrect size\n";
7973 else
7974 outs() << "\n";
7975 outs() << " count " << lo.count << "\n";
7976 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
7977 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
7978 uint32_t i = 0;
7979 while (left > 0) {
7980 while (*string == '\0' && left > 0) {
7981 string++;
7982 left--;
7983 }
7984 if (left > 0) {
7985 i++;
7986 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00007987 uint32_t NullPos = StringRef(string, left).find('\0');
7988 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00007989 string += len;
7990 left -= len;
7991 }
7992 }
7993 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007994 outs() << " count " << lo.count << " does not match number of strings "
7995 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00007996}
7997
Kevin Enderbyb4b79312014-12-18 19:24:35 +00007998static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
7999 const char *Ptr) {
8000 outs() << " cmd LC_SUB_FRAMEWORK\n";
8001 outs() << " cmdsize " << sub.cmdsize;
8002 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
8003 outs() << " Incorrect size\n";
8004 else
8005 outs() << "\n";
8006 if (sub.umbrella < sub.cmdsize) {
8007 const char *P = Ptr + sub.umbrella;
8008 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
8009 } else {
8010 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
8011 }
8012}
8013
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00008014static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
8015 const char *Ptr) {
8016 outs() << " cmd LC_SUB_UMBRELLA\n";
8017 outs() << " cmdsize " << sub.cmdsize;
8018 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
8019 outs() << " Incorrect size\n";
8020 else
8021 outs() << "\n";
8022 if (sub.sub_umbrella < sub.cmdsize) {
8023 const char *P = Ptr + sub.sub_umbrella;
8024 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
8025 } else {
8026 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
8027 }
8028}
8029
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008030static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008031 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008032 outs() << " cmd LC_SUB_LIBRARY\n";
8033 outs() << " cmdsize " << sub.cmdsize;
8034 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
8035 outs() << " Incorrect size\n";
8036 else
8037 outs() << "\n";
8038 if (sub.sub_library < sub.cmdsize) {
8039 const char *P = Ptr + sub.sub_library;
8040 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
8041 } else {
8042 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
8043 }
8044}
8045
Kevin Enderby186eac32014-12-19 21:06:24 +00008046static void PrintSubClientCommand(MachO::sub_client_command sub,
8047 const char *Ptr) {
8048 outs() << " cmd LC_SUB_CLIENT\n";
8049 outs() << " cmdsize " << sub.cmdsize;
8050 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
8051 outs() << " Incorrect size\n";
8052 else
8053 outs() << "\n";
8054 if (sub.client < sub.cmdsize) {
8055 const char *P = Ptr + sub.client;
8056 outs() << " client " << P << " (offset " << sub.client << ")\n";
8057 } else {
8058 outs() << " client ?(bad offset " << sub.client << ")\n";
8059 }
8060}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008061
Kevin Enderby52e4ce42014-12-19 22:25:22 +00008062static void PrintRoutinesCommand(MachO::routines_command r) {
8063 outs() << " cmd LC_ROUTINES\n";
8064 outs() << " cmdsize " << r.cmdsize;
8065 if (r.cmdsize != sizeof(struct MachO::routines_command))
8066 outs() << " Incorrect size\n";
8067 else
8068 outs() << "\n";
8069 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
8070 outs() << " init_module " << r.init_module << "\n";
8071 outs() << " reserved1 " << r.reserved1 << "\n";
8072 outs() << " reserved2 " << r.reserved2 << "\n";
8073 outs() << " reserved3 " << r.reserved3 << "\n";
8074 outs() << " reserved4 " << r.reserved4 << "\n";
8075 outs() << " reserved5 " << r.reserved5 << "\n";
8076 outs() << " reserved6 " << r.reserved6 << "\n";
8077}
8078
8079static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
8080 outs() << " cmd LC_ROUTINES_64\n";
8081 outs() << " cmdsize " << r.cmdsize;
8082 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
8083 outs() << " Incorrect size\n";
8084 else
8085 outs() << "\n";
8086 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
8087 outs() << " init_module " << r.init_module << "\n";
8088 outs() << " reserved1 " << r.reserved1 << "\n";
8089 outs() << " reserved2 " << r.reserved2 << "\n";
8090 outs() << " reserved3 " << r.reserved3 << "\n";
8091 outs() << " reserved4 " << r.reserved4 << "\n";
8092 outs() << " reserved5 " << r.reserved5 << "\n";
8093 outs() << " reserved6 " << r.reserved6 << "\n";
8094}
8095
Kevin Enderby48ef5342014-12-23 22:56:39 +00008096static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
8097 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
8098 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
8099 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
8100 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
8101 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
8102 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
8103 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
8104 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
8105 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
8106 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
8107 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
8108 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
8109 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
8110 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
8111 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
8112 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
8113 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
8114 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
8115 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
8116 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
8117 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
8118}
8119
Kevin Enderby227df342014-12-23 23:43:59 +00008120static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008121 uint32_t f;
8122 outs() << "\t mmst_reg ";
8123 for (f = 0; f < 10; f++)
8124 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
8125 outs() << "\n";
8126 outs() << "\t mmst_rsrv ";
8127 for (f = 0; f < 6; f++)
8128 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
8129 outs() << "\n";
8130}
8131
Kevin Enderbyaefb0032014-12-24 00:16:51 +00008132static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008133 uint32_t f;
8134 outs() << "\t xmm_reg ";
8135 for (f = 0; f < 16; f++)
8136 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
8137 outs() << "\n";
8138}
8139
8140static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
8141 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
8142 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
8143 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
8144 outs() << " denorm " << fpu.fpu_fcw.denorm;
8145 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
8146 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
8147 outs() << " undfl " << fpu.fpu_fcw.undfl;
8148 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
8149 outs() << "\t\t pc ";
8150 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
8151 outs() << "FP_PREC_24B ";
8152 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
8153 outs() << "FP_PREC_53B ";
8154 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
8155 outs() << "FP_PREC_64B ";
8156 else
8157 outs() << fpu.fpu_fcw.pc << " ";
8158 outs() << "rc ";
8159 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
8160 outs() << "FP_RND_NEAR ";
8161 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
8162 outs() << "FP_RND_DOWN ";
8163 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
8164 outs() << "FP_RND_UP ";
8165 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008166 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008167 outs() << "\n";
8168 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
8169 outs() << " denorm " << fpu.fpu_fsw.denorm;
8170 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
8171 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
8172 outs() << " undfl " << fpu.fpu_fsw.undfl;
8173 outs() << " precis " << fpu.fpu_fsw.precis;
8174 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
8175 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
8176 outs() << " c0 " << fpu.fpu_fsw.c0;
8177 outs() << " c1 " << fpu.fpu_fsw.c1;
8178 outs() << " c2 " << fpu.fpu_fsw.c2;
8179 outs() << " tos " << fpu.fpu_fsw.tos;
8180 outs() << " c3 " << fpu.fpu_fsw.c3;
8181 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
8182 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
8183 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
8184 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
8185 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
8186 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
8187 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
8188 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
8189 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
8190 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
8191 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
8192 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
8193 outs() << "\n";
8194 outs() << "\t fpu_stmm0:\n";
8195 Print_mmst_reg(fpu.fpu_stmm0);
8196 outs() << "\t fpu_stmm1:\n";
8197 Print_mmst_reg(fpu.fpu_stmm1);
8198 outs() << "\t fpu_stmm2:\n";
8199 Print_mmst_reg(fpu.fpu_stmm2);
8200 outs() << "\t fpu_stmm3:\n";
8201 Print_mmst_reg(fpu.fpu_stmm3);
8202 outs() << "\t fpu_stmm4:\n";
8203 Print_mmst_reg(fpu.fpu_stmm4);
8204 outs() << "\t fpu_stmm5:\n";
8205 Print_mmst_reg(fpu.fpu_stmm5);
8206 outs() << "\t fpu_stmm6:\n";
8207 Print_mmst_reg(fpu.fpu_stmm6);
8208 outs() << "\t fpu_stmm7:\n";
8209 Print_mmst_reg(fpu.fpu_stmm7);
8210 outs() << "\t fpu_xmm0:\n";
8211 Print_xmm_reg(fpu.fpu_xmm0);
8212 outs() << "\t fpu_xmm1:\n";
8213 Print_xmm_reg(fpu.fpu_xmm1);
8214 outs() << "\t fpu_xmm2:\n";
8215 Print_xmm_reg(fpu.fpu_xmm2);
8216 outs() << "\t fpu_xmm3:\n";
8217 Print_xmm_reg(fpu.fpu_xmm3);
8218 outs() << "\t fpu_xmm4:\n";
8219 Print_xmm_reg(fpu.fpu_xmm4);
8220 outs() << "\t fpu_xmm5:\n";
8221 Print_xmm_reg(fpu.fpu_xmm5);
8222 outs() << "\t fpu_xmm6:\n";
8223 Print_xmm_reg(fpu.fpu_xmm6);
8224 outs() << "\t fpu_xmm7:\n";
8225 Print_xmm_reg(fpu.fpu_xmm7);
8226 outs() << "\t fpu_xmm8:\n";
8227 Print_xmm_reg(fpu.fpu_xmm8);
8228 outs() << "\t fpu_xmm9:\n";
8229 Print_xmm_reg(fpu.fpu_xmm9);
8230 outs() << "\t fpu_xmm10:\n";
8231 Print_xmm_reg(fpu.fpu_xmm10);
8232 outs() << "\t fpu_xmm11:\n";
8233 Print_xmm_reg(fpu.fpu_xmm11);
8234 outs() << "\t fpu_xmm12:\n";
8235 Print_xmm_reg(fpu.fpu_xmm12);
8236 outs() << "\t fpu_xmm13:\n";
8237 Print_xmm_reg(fpu.fpu_xmm13);
8238 outs() << "\t fpu_xmm14:\n";
8239 Print_xmm_reg(fpu.fpu_xmm14);
8240 outs() << "\t fpu_xmm15:\n";
8241 Print_xmm_reg(fpu.fpu_xmm15);
8242 outs() << "\t fpu_rsrv4:\n";
8243 for (uint32_t f = 0; f < 6; f++) {
8244 outs() << "\t ";
8245 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008246 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008247 outs() << "\n";
8248 }
8249 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
8250 outs() << "\n";
8251}
8252
8253static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
8254 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
8255 outs() << " err " << format("0x%08" PRIx32, exc64.err);
8256 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
8257}
8258
8259static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
8260 bool isLittleEndian, uint32_t cputype) {
8261 if (t.cmd == MachO::LC_THREAD)
8262 outs() << " cmd LC_THREAD\n";
8263 else if (t.cmd == MachO::LC_UNIXTHREAD)
8264 outs() << " cmd LC_UNIXTHREAD\n";
8265 else
8266 outs() << " cmd " << t.cmd << " (unknown)\n";
8267 outs() << " cmdsize " << t.cmdsize;
8268 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
8269 outs() << " Incorrect size\n";
8270 else
8271 outs() << "\n";
8272
8273 const char *begin = Ptr + sizeof(struct MachO::thread_command);
8274 const char *end = Ptr + t.cmdsize;
8275 uint32_t flavor, count, left;
8276 if (cputype == MachO::CPU_TYPE_X86_64) {
8277 while (begin < end) {
8278 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8279 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8280 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008281 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008282 flavor = 0;
8283 begin = end;
8284 }
8285 if (isLittleEndian != sys::IsLittleEndianHost)
8286 sys::swapByteOrder(flavor);
8287 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8288 memcpy((char *)&count, begin, sizeof(uint32_t));
8289 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008290 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008291 count = 0;
8292 begin = end;
8293 }
8294 if (isLittleEndian != sys::IsLittleEndianHost)
8295 sys::swapByteOrder(count);
8296 if (flavor == MachO::x86_THREAD_STATE64) {
8297 outs() << " flavor x86_THREAD_STATE64\n";
8298 if (count == MachO::x86_THREAD_STATE64_COUNT)
8299 outs() << " count x86_THREAD_STATE64_COUNT\n";
8300 else
8301 outs() << " count " << count
8302 << " (not x86_THREAD_STATE64_COUNT)\n";
8303 MachO::x86_thread_state64_t cpu64;
8304 left = end - begin;
8305 if (left >= sizeof(MachO::x86_thread_state64_t)) {
8306 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
8307 begin += sizeof(MachO::x86_thread_state64_t);
8308 } else {
8309 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
8310 memcpy(&cpu64, begin, left);
8311 begin += left;
8312 }
8313 if (isLittleEndian != sys::IsLittleEndianHost)
8314 swapStruct(cpu64);
8315 Print_x86_thread_state64_t(cpu64);
8316 } else if (flavor == MachO::x86_THREAD_STATE) {
8317 outs() << " flavor x86_THREAD_STATE\n";
8318 if (count == MachO::x86_THREAD_STATE_COUNT)
8319 outs() << " count x86_THREAD_STATE_COUNT\n";
8320 else
8321 outs() << " count " << count
8322 << " (not x86_THREAD_STATE_COUNT)\n";
8323 struct MachO::x86_thread_state_t ts;
8324 left = end - begin;
8325 if (left >= sizeof(MachO::x86_thread_state_t)) {
8326 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
8327 begin += sizeof(MachO::x86_thread_state_t);
8328 } else {
8329 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
8330 memcpy(&ts, begin, left);
8331 begin += left;
8332 }
8333 if (isLittleEndian != sys::IsLittleEndianHost)
8334 swapStruct(ts);
8335 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
8336 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
8337 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
8338 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
8339 else
8340 outs() << "tsh.count " << ts.tsh.count
8341 << " (not x86_THREAD_STATE64_COUNT\n";
8342 Print_x86_thread_state64_t(ts.uts.ts64);
8343 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008344 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
8345 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008346 }
8347 } else if (flavor == MachO::x86_FLOAT_STATE) {
8348 outs() << " flavor x86_FLOAT_STATE\n";
8349 if (count == MachO::x86_FLOAT_STATE_COUNT)
8350 outs() << " count x86_FLOAT_STATE_COUNT\n";
8351 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008352 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008353 struct MachO::x86_float_state_t fs;
8354 left = end - begin;
8355 if (left >= sizeof(MachO::x86_float_state_t)) {
8356 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
8357 begin += sizeof(MachO::x86_float_state_t);
8358 } else {
8359 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
8360 memcpy(&fs, begin, left);
8361 begin += left;
8362 }
8363 if (isLittleEndian != sys::IsLittleEndianHost)
8364 swapStruct(fs);
8365 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
8366 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008367 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008368 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
8369 else
8370 outs() << "fsh.count " << fs.fsh.count
8371 << " (not x86_FLOAT_STATE64_COUNT\n";
8372 Print_x86_float_state_t(fs.ufs.fs64);
8373 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008374 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
8375 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008376 }
8377 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
8378 outs() << " flavor x86_EXCEPTION_STATE\n";
8379 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
8380 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
8381 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008382 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00008383 << " (not x86_EXCEPTION_STATE_COUNT)\n";
8384 struct MachO::x86_exception_state_t es;
8385 left = end - begin;
8386 if (left >= sizeof(MachO::x86_exception_state_t)) {
8387 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
8388 begin += sizeof(MachO::x86_exception_state_t);
8389 } else {
8390 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
8391 memcpy(&es, begin, left);
8392 begin += left;
8393 }
8394 if (isLittleEndian != sys::IsLittleEndianHost)
8395 swapStruct(es);
8396 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
8397 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008398 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008399 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
8400 else
8401 outs() << "\t esh.count " << es.esh.count
8402 << " (not x86_EXCEPTION_STATE64_COUNT\n";
8403 Print_x86_exception_state_t(es.ues.es64);
8404 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008405 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
8406 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008407 }
8408 } else {
8409 outs() << " flavor " << flavor << " (unknown)\n";
8410 outs() << " count " << count << "\n";
8411 outs() << " state (unknown)\n";
8412 begin += count * sizeof(uint32_t);
8413 }
8414 }
8415 } else {
8416 while (begin < end) {
8417 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8418 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8419 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008420 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008421 flavor = 0;
8422 begin = end;
8423 }
8424 if (isLittleEndian != sys::IsLittleEndianHost)
8425 sys::swapByteOrder(flavor);
8426 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8427 memcpy((char *)&count, begin, sizeof(uint32_t));
8428 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008429 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008430 count = 0;
8431 begin = end;
8432 }
8433 if (isLittleEndian != sys::IsLittleEndianHost)
8434 sys::swapByteOrder(count);
8435 outs() << " flavor " << flavor << "\n";
8436 outs() << " count " << count << "\n";
8437 outs() << " state (Unknown cputype/cpusubtype)\n";
8438 begin += count * sizeof(uint32_t);
8439 }
8440 }
8441}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008442
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008443static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
8444 if (dl.cmd == MachO::LC_ID_DYLIB)
8445 outs() << " cmd LC_ID_DYLIB\n";
8446 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
8447 outs() << " cmd LC_LOAD_DYLIB\n";
8448 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
8449 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
8450 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
8451 outs() << " cmd LC_REEXPORT_DYLIB\n";
8452 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
8453 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
8454 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
8455 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
8456 else
8457 outs() << " cmd " << dl.cmd << " (unknown)\n";
8458 outs() << " cmdsize " << dl.cmdsize;
8459 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
8460 outs() << " Incorrect size\n";
8461 else
8462 outs() << "\n";
8463 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008464 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008465 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
8466 } else {
8467 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
8468 }
8469 outs() << " time stamp " << dl.dylib.timestamp << " ";
8470 time_t t = dl.dylib.timestamp;
8471 outs() << ctime(&t);
8472 outs() << " current version ";
8473 if (dl.dylib.current_version == 0xffffffff)
8474 outs() << "n/a\n";
8475 else
8476 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
8477 << ((dl.dylib.current_version >> 8) & 0xff) << "."
8478 << (dl.dylib.current_version & 0xff) << "\n";
8479 outs() << "compatibility version ";
8480 if (dl.dylib.compatibility_version == 0xffffffff)
8481 outs() << "n/a\n";
8482 else
8483 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
8484 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
8485 << (dl.dylib.compatibility_version & 0xff) << "\n";
8486}
8487
8488static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
8489 uint32_t object_size) {
8490 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
8491 outs() << " cmd LC_FUNCTION_STARTS\n";
8492 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
8493 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
8494 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
8495 outs() << " cmd LC_FUNCTION_STARTS\n";
8496 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
8497 outs() << " cmd LC_DATA_IN_CODE\n";
8498 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
8499 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
8500 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
8501 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
8502 else
8503 outs() << " cmd " << ld.cmd << " (?)\n";
8504 outs() << " cmdsize " << ld.cmdsize;
8505 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
8506 outs() << " Incorrect size\n";
8507 else
8508 outs() << "\n";
8509 outs() << " dataoff " << ld.dataoff;
8510 if (ld.dataoff > object_size)
8511 outs() << " (past end of file)\n";
8512 else
8513 outs() << "\n";
8514 outs() << " datasize " << ld.datasize;
8515 uint64_t big_size = ld.dataoff;
8516 big_size += ld.datasize;
8517 if (big_size > object_size)
8518 outs() << " (past end of file)\n";
8519 else
8520 outs() << "\n";
8521}
8522
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008523static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
8524 uint32_t cputype, bool verbose) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008525 StringRef Buf = Obj->getData();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008526 unsigned Index = 0;
8527 for (const auto &Command : Obj->load_commands()) {
8528 outs() << "Load command " << Index++ << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008529 if (Command.C.cmd == MachO::LC_SEGMENT) {
8530 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
8531 const char *sg_segname = SLC.segname;
8532 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
8533 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
8534 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
8535 verbose);
8536 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00008537 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00008538 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
8539 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
8540 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
8541 }
8542 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
8543 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
8544 const char *sg_segname = SLC_64.segname;
8545 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
8546 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
8547 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
8548 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
8549 for (unsigned j = 0; j < SLC_64.nsects; j++) {
8550 MachO::section_64 S_64 = Obj->getSection64(Command, j);
8551 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
8552 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
8553 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
8554 sg_segname, filetype, Buf.size(), verbose);
8555 }
8556 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
8557 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00008558 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00008559 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
8560 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
8561 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00008562 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
8563 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008564 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
8565 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
8566 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
8567 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
8568 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
8569 Command.C.cmd == MachO::LC_ID_DYLINKER ||
8570 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
8571 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
8572 PrintDyldLoadCommand(Dyld, Command.Ptr);
8573 } else if (Command.C.cmd == MachO::LC_UUID) {
8574 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
8575 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008576 } else if (Command.C.cmd == MachO::LC_RPATH) {
8577 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
8578 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00008579 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
Tim Northoverbfbfb122015-11-02 21:26:58 +00008580 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
8581 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
8582 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008583 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
8584 PrintVersionMinLoadCommand(Vd);
8585 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
8586 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
8587 PrintSourceVersionCommand(Sd);
8588 } else if (Command.C.cmd == MachO::LC_MAIN) {
8589 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
8590 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00008591 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008592 MachO::encryption_info_command Ei =
8593 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00008594 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00008595 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008596 MachO::encryption_info_command_64 Ei =
8597 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00008598 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008599 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008600 MachO::linker_option_command Lo =
8601 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008602 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00008603 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
8604 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
8605 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00008606 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
8607 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
8608 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008609 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
8610 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
8611 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00008612 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
8613 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
8614 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00008615 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
8616 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
8617 PrintRoutinesCommand(Rc);
8618 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
8619 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
8620 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00008621 } else if (Command.C.cmd == MachO::LC_THREAD ||
8622 Command.C.cmd == MachO::LC_UNIXTHREAD) {
8623 MachO::thread_command Tc = Obj->getThreadCommand(Command);
8624 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00008625 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
8626 Command.C.cmd == MachO::LC_ID_DYLIB ||
8627 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
8628 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
8629 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
8630 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008631 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
8632 PrintDylibCommand(Dl, Command.Ptr);
8633 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
8634 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
8635 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
8636 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
8637 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
8638 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
8639 MachO::linkedit_data_command Ld =
8640 Obj->getLinkeditDataLoadCommand(Command);
8641 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00008642 } else {
8643 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
8644 << ")\n";
8645 outs() << " cmdsize " << Command.C.cmdsize << "\n";
8646 // TODO: get and print the raw bytes of the load command.
8647 }
8648 // TODO: print all the other kinds of load commands.
Kevin Enderby956366c2014-08-29 22:30:52 +00008649 }
8650}
8651
Kevin Enderby0ae163f2016-01-13 00:25:36 +00008652static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008653 if (Obj->is64Bit()) {
8654 MachO::mach_header_64 H_64;
8655 H_64 = Obj->getHeader64();
8656 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
8657 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
8658 } else {
8659 MachO::mach_header H;
8660 H = Obj->getHeader();
8661 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
8662 H.sizeofcmds, H.flags, verbose);
8663 }
8664}
8665
8666void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
8667 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00008668 PrintMachHeader(file, !NonVerbose);
8669}
8670
8671void llvm::printMachOLoadCommands(const object::ObjectFile *Obj) {
8672 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00008673 uint32_t filetype = 0;
8674 uint32_t cputype = 0;
Kevin Enderby0ae163f2016-01-13 00:25:36 +00008675 if (file->is64Bit()) {
8676 MachO::mach_header_64 H_64;
8677 H_64 = file->getHeader64();
8678 filetype = H_64.filetype;
8679 cputype = H_64.cputype;
8680 } else {
8681 MachO::mach_header H;
8682 H = file->getHeader();
8683 filetype = H.filetype;
8684 cputype = H.cputype;
8685 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008686 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008687}
Nick Kledzikd04bc352014-08-30 00:20:14 +00008688
8689//===----------------------------------------------------------------------===//
8690// export trie dumping
8691//===----------------------------------------------------------------------===//
8692
8693void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008694 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
8695 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +00008696 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
8697 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
8698 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8699 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
8700 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8701 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
8702 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
8703 if (ReExport)
8704 outs() << "[re-export] ";
8705 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008706 outs() << format("0x%08llX ",
8707 Entry.address()); // FIXME:add in base address
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008708 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +00008709 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008710 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +00008711 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +00008712 if (WeakDef) {
8713 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008714 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008715 }
8716 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008717 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00008718 outs() << ", ";
8719 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008720 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008721 }
8722 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008723 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00008724 outs() << ", ";
8725 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008726 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008727 }
8728 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008729 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00008730 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008731 outs() << format("resolver=0x%08llX", Entry.other());
8732 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008733 }
8734 outs() << "]";
8735 }
8736 if (ReExport) {
8737 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008738 int Ordinal = Entry.other() - 1;
8739 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
8740 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +00008741 outs() << " (from " << DylibName << ")";
8742 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008743 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +00008744 }
8745 outs() << "\n";
8746 }
8747}
Nick Kledzikac431442014-09-12 21:34:15 +00008748
Nick Kledzikac431442014-09-12 21:34:15 +00008749//===----------------------------------------------------------------------===//
8750// rebase table dumping
8751//===----------------------------------------------------------------------===//
8752
8753namespace {
8754class SegInfo {
8755public:
8756 SegInfo(const object::MachOObjectFile *Obj);
8757
8758 StringRef segmentName(uint32_t SegIndex);
8759 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
8760 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00008761 bool isValidSegIndexAndOffset(uint32_t SegIndex, uint64_t SegOffset);
Nick Kledzikac431442014-09-12 21:34:15 +00008762
8763private:
8764 struct SectionInfo {
8765 uint64_t Address;
8766 uint64_t Size;
8767 StringRef SectionName;
8768 StringRef SegmentName;
8769 uint64_t OffsetInSegment;
8770 uint64_t SegmentStartAddress;
8771 uint32_t SegmentIndex;
8772 };
8773 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
8774 SmallVector<SectionInfo, 32> Sections;
8775};
8776}
8777
8778SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
8779 // Build table of sections so segIndex/offset pairs can be translated.
Nick Kledzik56ebef42014-09-16 01:41:51 +00008780 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
Nick Kledzikac431442014-09-12 21:34:15 +00008781 StringRef CurSegName;
8782 uint64_t CurSegAddress;
8783 for (const SectionRef &Section : Obj->sections()) {
8784 SectionInfo Info;
Davide Italianoccd53fe2015-08-05 07:18:31 +00008785 error(Section.getName(Info.SectionName));
Rafael Espindola80291272014-10-08 15:28:58 +00008786 Info.Address = Section.getAddress();
8787 Info.Size = Section.getSize();
Nick Kledzikac431442014-09-12 21:34:15 +00008788 Info.SegmentName =
8789 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
8790 if (!Info.SegmentName.equals(CurSegName)) {
8791 ++CurSegIndex;
8792 CurSegName = Info.SegmentName;
8793 CurSegAddress = Info.Address;
8794 }
8795 Info.SegmentIndex = CurSegIndex - 1;
8796 Info.OffsetInSegment = Info.Address - CurSegAddress;
8797 Info.SegmentStartAddress = CurSegAddress;
8798 Sections.push_back(Info);
8799 }
8800}
8801
8802StringRef SegInfo::segmentName(uint32_t SegIndex) {
8803 for (const SectionInfo &SI : Sections) {
8804 if (SI.SegmentIndex == SegIndex)
8805 return SI.SegmentName;
8806 }
8807 llvm_unreachable("invalid segIndex");
8808}
8809
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00008810bool SegInfo::isValidSegIndexAndOffset(uint32_t SegIndex,
8811 uint64_t OffsetInSeg) {
8812 for (const SectionInfo &SI : Sections) {
8813 if (SI.SegmentIndex != SegIndex)
8814 continue;
8815 if (SI.OffsetInSegment > OffsetInSeg)
8816 continue;
8817 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
8818 continue;
8819 return true;
8820 }
8821 return false;
8822}
8823
Nick Kledzikac431442014-09-12 21:34:15 +00008824const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
8825 uint64_t OffsetInSeg) {
8826 for (const SectionInfo &SI : Sections) {
8827 if (SI.SegmentIndex != SegIndex)
8828 continue;
8829 if (SI.OffsetInSegment > OffsetInSeg)
8830 continue;
8831 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
8832 continue;
8833 return SI;
8834 }
8835 llvm_unreachable("segIndex and offset not in any section");
8836}
8837
8838StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
8839 return findSection(SegIndex, OffsetInSeg).SectionName;
8840}
8841
8842uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
8843 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
8844 return SI.SegmentStartAddress + OffsetInSeg;
8845}
8846
8847void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
8848 // Build table of sections so names can used in final output.
8849 SegInfo sectionTable(Obj);
8850
8851 outs() << "segment section address type\n";
8852 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
8853 uint32_t SegIndex = Entry.segmentIndex();
8854 uint64_t OffsetInSeg = Entry.segmentOffset();
8855 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8856 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8857 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8858
8859 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008860 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
8861 SegmentName.str().c_str(), SectionName.str().c_str(),
8862 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +00008863 }
8864}
Nick Kledzik56ebef42014-09-16 01:41:51 +00008865
8866static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
8867 StringRef DylibName;
8868 switch (Ordinal) {
8869 case MachO::BIND_SPECIAL_DYLIB_SELF:
8870 return "this-image";
8871 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
8872 return "main-executable";
8873 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
8874 return "flat-namespace";
8875 default:
Nick Kledzikabd29872014-09-16 22:03:13 +00008876 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008877 std::error_code EC =
8878 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +00008879 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +00008880 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +00008881 return DylibName;
8882 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00008883 }
Nick Kledzikabd29872014-09-16 22:03:13 +00008884 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008885}
8886
8887//===----------------------------------------------------------------------===//
8888// bind table dumping
8889//===----------------------------------------------------------------------===//
8890
8891void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
8892 // Build table of sections so names can used in final output.
8893 SegInfo sectionTable(Obj);
8894
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008895 outs() << "segment section address type "
8896 "addend dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008897 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
8898 uint32_t SegIndex = Entry.segmentIndex();
8899 uint64_t OffsetInSeg = Entry.segmentOffset();
8900 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8901 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8902 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8903
8904 // Table lines look like:
8905 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008906 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00008907 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008908 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008909 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008910 << left_justify(SectionName, 18) << " "
8911 << format_hex(Address, 10, true) << " "
8912 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008913 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008914 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008915 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008916 }
8917}
8918
8919//===----------------------------------------------------------------------===//
8920// lazy bind table dumping
8921//===----------------------------------------------------------------------===//
8922
8923void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
8924 // Build table of sections so names can used in final output.
8925 SegInfo sectionTable(Obj);
8926
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008927 outs() << "segment section address "
8928 "dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008929 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
8930 uint32_t SegIndex = Entry.segmentIndex();
8931 uint64_t OffsetInSeg = Entry.segmentOffset();
8932 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8933 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8934 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8935
8936 // Table lines look like:
8937 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008938 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008939 << left_justify(SectionName, 18) << " "
8940 << format_hex(Address, 10, true) << " "
8941 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00008942 << Entry.symbolName() << "\n";
8943 }
8944}
8945
Nick Kledzik56ebef42014-09-16 01:41:51 +00008946//===----------------------------------------------------------------------===//
8947// weak bind table dumping
8948//===----------------------------------------------------------------------===//
8949
8950void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
8951 // Build table of sections so names can used in final output.
8952 SegInfo sectionTable(Obj);
8953
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008954 outs() << "segment section address "
8955 "type addend symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008956 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
8957 // Strong symbols don't have a location to update.
8958 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008959 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +00008960 << Entry.symbolName() << "\n";
8961 continue;
8962 }
8963 uint32_t SegIndex = Entry.segmentIndex();
8964 uint64_t OffsetInSeg = Entry.segmentOffset();
8965 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8966 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8967 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8968
8969 // Table lines look like:
8970 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008971 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008972 << left_justify(SectionName, 18) << " "
8973 << format_hex(Address, 10, true) << " "
8974 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008975 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
8976 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008977 }
8978}
8979
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008980// get_dyld_bind_info_symbolname() is used for disassembly and passed an
8981// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
8982// information for that address. If the address is found its binding symbol
8983// name is returned. If not nullptr is returned.
8984static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
8985 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +00008986 if (info->bindtable == nullptr) {
8987 info->bindtable = new (BindTable);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008988 SegInfo sectionTable(info->O);
8989 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
8990 uint32_t SegIndex = Entry.segmentIndex();
8991 uint64_t OffsetInSeg = Entry.segmentOffset();
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00008992 if (!sectionTable.isValidSegIndexAndOffset(SegIndex, OffsetInSeg))
8993 continue;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008994 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8995 const char *SymbolName = nullptr;
8996 StringRef name = Entry.symbolName();
8997 if (!name.empty())
8998 SymbolName = name.data();
Kevin Enderby078be602014-10-23 19:53:12 +00008999 info->bindtable->push_back(std::make_pair(Address, SymbolName));
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009000 }
9001 }
Kevin Enderby078be602014-10-23 19:53:12 +00009002 for (bind_table_iterator BI = info->bindtable->begin(),
9003 BE = info->bindtable->end();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009004 BI != BE; ++BI) {
9005 uint64_t Address = BI->first;
9006 if (ReferenceValue == Address) {
9007 const char *SymbolName = BI->second;
9008 return SymbolName;
9009 }
9010 }
9011 return nullptr;
9012}