blob: ecf6b35914692cdce8a0ea311b5a653649eed447 [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
Mehdi Aminib550cb12016-04-18 09:17:29 +000014#include "llvm/Object/MachO.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000015#include "llvm-objdump.h"
Kevin Enderby98c9acc2014-09-16 18:00:57 +000016#include "llvm-c/Disassembler.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 Kramerf57c1972016-01-26 16:44:37 +000025#include "llvm/MC/MCDisassembler/MCDisassembler.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000026#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"
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +000032#include "llvm/Object/MachOUniversal.h"
Rafael Espindola9b709252013-04-13 01:45:40 +000033#include "llvm/Support/Casting.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000034#include "llvm/Support/CommandLine.h"
35#include "llvm/Support/Debug.h"
Tim Northover4bd286a2014-08-01 13:07:19 +000036#include "llvm/Support/Endian.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000037#include "llvm/Support/Format.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000038#include "llvm/Support/FormattedStream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000039#include "llvm/Support/GraphWriter.h"
Kevin Enderby9a509442015-01-27 21:28:24 +000040#include "llvm/Support/LEB128.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000041#include "llvm/Support/MachO.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000042#include "llvm/Support/MemoryBuffer.h"
43#include "llvm/Support/TargetRegistry.h"
44#include "llvm/Support/TargetSelect.h"
45#include "llvm/Support/raw_ostream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000046#include <algorithm>
47#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000048#include <system_error>
Kevin Enderby04bf6932014-10-28 23:39:46 +000049
50#if HAVE_CXXABI_H
51#include <cxxabi.h>
52#endif
53
Benjamin Kramer43a772e2011-09-19 17:56:04 +000054using namespace llvm;
55using namespace object;
56
57static cl::opt<bool>
Kevin Enderbyb28ed012014-10-29 21:28:24 +000058 UseDbg("g",
59 cl::desc("Print line information from debug info if available"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000060
Kevin Enderbyb28ed012014-10-29 21:28:24 +000061static cl::opt<std::string> DSYMFile("dsym",
62 cl::desc("Use .dSYM file for debug info"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000063
Kevin Enderbyb28ed012014-10-29 21:28:24 +000064static cl::opt<bool> FullLeadingAddr("full-leading-addr",
65 cl::desc("Print full leading address"));
Kevin Enderbybf246f52014-09-24 23:08:22 +000066
Kevin Enderbyab5e6c92015-03-17 21:07:39 +000067static cl::opt<bool> NoLeadingAddr("no-leading-addr",
68 cl::desc("Print no leading address"));
69
Kevin Enderby13023a12015-01-15 23:19:11 +000070cl::opt<bool> llvm::UniversalHeaders("universal-headers",
71 cl::desc("Print Mach-O universal headers "
72 "(requires -macho)"));
73
Kevin Enderby131d1772015-01-09 19:22:37 +000074cl::opt<bool>
Kevin Enderby13023a12015-01-15 23:19:11 +000075 llvm::ArchiveHeaders("archive-headers",
76 cl::desc("Print archive headers for Mach-O archives "
77 "(requires -macho)"));
Kevin Enderby131d1772015-01-09 19:22:37 +000078
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +000079cl::opt<bool>
Kevin Enderby8972e482015-04-30 20:30:42 +000080 ArchiveMemberOffsets("archive-member-offsets",
81 cl::desc("Print the offset to each archive member for "
82 "Mach-O archives (requires -macho and "
83 "-archive-headers)"));
84
85cl::opt<bool>
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +000086 llvm::IndirectSymbols("indirect-symbols",
87 cl::desc("Print indirect symbol table for Mach-O "
88 "objects (requires -macho)"));
89
Kevin Enderby69fe98d2015-01-23 18:52:17 +000090cl::opt<bool>
91 llvm::DataInCode("data-in-code",
92 cl::desc("Print the data in code table for Mach-O objects "
93 "(requires -macho)"));
94
Kevin Enderby9a509442015-01-27 21:28:24 +000095cl::opt<bool>
96 llvm::LinkOptHints("link-opt-hints",
97 cl::desc("Print the linker optimization hints for "
98 "Mach-O objects (requires -macho)"));
99
Kevin Enderbycd66be52015-03-11 22:06:32 +0000100cl::opt<bool>
101 llvm::InfoPlist("info-plist",
102 cl::desc("Print the info plist section as strings for "
103 "Mach-O objects (requires -macho)"));
104
Kevin Enderbyf0640752015-03-13 17:56:32 +0000105cl::opt<bool>
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000106 llvm::DylibsUsed("dylibs-used",
107 cl::desc("Print the shared libraries used for linked "
108 "Mach-O files (requires -macho)"));
109
110cl::opt<bool>
111 llvm::DylibId("dylib-id",
112 cl::desc("Print the shared library's id for the dylib Mach-O "
113 "file (requires -macho)"));
114
115cl::opt<bool>
Kevin Enderbyf0640752015-03-13 17:56:32 +0000116 llvm::NonVerbose("non-verbose",
117 cl::desc("Print the info for Mach-O objects in "
118 "non-verbose or numeric form (requires -macho)"));
119
Kevin Enderby0fc11822015-04-01 20:57:01 +0000120cl::opt<bool>
121 llvm::ObjcMetaData("objc-meta-data",
122 cl::desc("Print the Objective-C runtime meta data for "
123 "Mach-O files (requires -macho)"));
124
Kevin Enderby6a221752015-03-17 17:10:57 +0000125cl::opt<std::string> llvm::DisSymName(
126 "dis-symname",
127 cl::desc("disassemble just this symbol's instructions (requires -macho"));
128
Kevin Enderby8e29ec92015-03-17 22:26:11 +0000129static cl::opt<bool> NoSymbolicOperands(
130 "no-symbolic-operands",
131 cl::desc("do not symbolic operands when disassembling (requires -macho)"));
132
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000133static cl::list<std::string>
134 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
135 cl::ZeroOrMore);
Hans Wennborgcc9deb42015-09-29 18:02:48 +0000136
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000137bool ArchAll = false;
138
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000139static std::string ThumbTripleName;
140
141static const Target *GetTarget(const MachOObjectFile *MachOObj,
142 const char **McpuDefault,
143 const Target **ThumbTarget) {
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000144 // Figure out the target triple.
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000145 if (TripleName.empty()) {
146 llvm::Triple TT("unknown-unknown-unknown");
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000147 llvm::Triple ThumbTriple = Triple();
148 TT = MachOObj->getArch(McpuDefault, &ThumbTriple);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000149 TripleName = TT.str();
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000150 ThumbTripleName = ThumbTriple.str();
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000151 }
152
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000153 // Get the target specific parser.
154 std::string Error;
155 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000156 if (TheTarget && ThumbTripleName.empty())
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000157 return TheTarget;
158
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000159 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
160 if (*ThumbTarget)
161 return TheTarget;
162
163 errs() << "llvm-objdump: error: unable to get target for '";
164 if (!TheTarget)
165 errs() << TripleName;
166 else
167 errs() << ThumbTripleName;
168 errs() << "', see --version and --triple.\n";
Craig Toppere6cb63e2014-04-25 04:24:47 +0000169 return nullptr;
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000170}
171
Owen Andersond9243c42011-10-17 21:37:35 +0000172struct SymbolSorter {
173 bool operator()(const SymbolRef &A, const SymbolRef &B) {
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000174 ErrorOr<SymbolRef::Type> ATypeOrErr = A.getType();
175 if (std::error_code EC = ATypeOrErr.getError())
176 report_fatal_error(EC.message());
177 SymbolRef::Type AType = *ATypeOrErr;
178 ErrorOr<SymbolRef::Type> BTypeOrErr = B.getType();
179 if (std::error_code EC = BTypeOrErr.getError())
180 report_fatal_error(EC.message());
Kevin Enderby74f58d42016-03-23 21:45:21 +0000181 SymbolRef::Type BType = *BTypeOrErr;
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000182 uint64_t AAddr = (AType != SymbolRef::ST_Function) ? 0 : A.getValue();
183 uint64_t BAddr = (BType != SymbolRef::ST_Function) ? 0 : B.getValue();
Owen Andersond9243c42011-10-17 21:37:35 +0000184 return AAddr < BAddr;
185 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000186};
187
Kevin Enderby273ae012013-06-06 17:20:50 +0000188// Types for the storted data in code table that is built before disassembly
189// and the predicate function to sort them.
190typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
191typedef std::vector<DiceTableEntry> DiceTable;
192typedef DiceTable::iterator dice_table_iterator;
193
Kevin Enderby930fdc72014-11-06 19:00:13 +0000194// This is used to search for a data in code table entry for the PC being
195// disassembled. The j parameter has the PC in j.first. A single data in code
196// table entry can cover many bytes for each of its Kind's. So if the offset,
197// aka the i.first value, of the data in code table entry plus its Length
198// covers the PC being searched for this will return true. If not it will
199// return false.
David Majnemerea9b8ee2014-11-04 08:41:48 +0000200static bool compareDiceTableEntries(const DiceTableEntry &i,
201 const DiceTableEntry &j) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000202 uint16_t Length;
203 i.second.getLength(Length);
204
205 return j.first >= i.first && j.first < i.first + Length;
Kevin Enderby273ae012013-06-06 17:20:50 +0000206}
207
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000208static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
Kevin Enderby930fdc72014-11-06 19:00:13 +0000209 unsigned short Kind) {
210 uint32_t Value, Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000211
212 switch (Kind) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000213 default:
Charles Davis8bdfafd2013-09-01 04:28:48 +0000214 case MachO::DICE_KIND_DATA:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000215 if (Length >= 4) {
216 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000217 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000218 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000219 outs() << "\t.long " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000220 Size = 4;
221 } else if (Length >= 2) {
222 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000223 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000224 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000225 outs() << "\t.short " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000226 Size = 2;
227 } else {
228 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000229 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000230 Value = bytes[0];
231 outs() << "\t.byte " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000232 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000233 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000234 if (Kind == MachO::DICE_KIND_DATA)
235 outs() << "\t@ KIND_DATA\n";
236 else
237 outs() << "\t@ data in code kind = " << Kind << "\n";
Kevin Enderby273ae012013-06-06 17:20:50 +0000238 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000239 case MachO::DICE_KIND_JUMP_TABLE8:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000240 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000241 dumpBytes(makeArrayRef(bytes, 1), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000242 Value = bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000243 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
244 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000245 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000246 case MachO::DICE_KIND_JUMP_TABLE16:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000247 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000248 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000249 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000250 outs() << "\t.short " << format("%5u", Value & 0xffff)
251 << "\t@ KIND_JUMP_TABLE16\n";
252 Size = 2;
Kevin Enderby273ae012013-06-06 17:20:50 +0000253 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000254 case MachO::DICE_KIND_JUMP_TABLE32:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000255 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
256 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000257 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000258 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000259 outs() << "\t.long " << Value;
260 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
261 outs() << "\t@ KIND_JUMP_TABLE32\n";
262 else
263 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
264 Size = 4;
Kevin Enderby273ae012013-06-06 17:20:50 +0000265 break;
266 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000267 return Size;
Kevin Enderby273ae012013-06-06 17:20:50 +0000268}
269
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000270static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000271 std::vector<SectionRef> &Sections,
272 std::vector<SymbolRef> &Symbols,
273 SmallVectorImpl<uint64_t> &FoundFns,
274 uint64_t &BaseSegmentAddress) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000275 for (const SymbolRef &Symbol : MachOObj->symbols()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000276 Expected<StringRef> SymName = Symbol.getName();
277 if (!SymName) {
278 std::string Buf;
279 raw_string_ostream OS(Buf);
280 logAllUnhandledErrors(SymName.takeError(), OS, "");
281 OS.flush();
282 report_fatal_error(Buf);
283 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000284 if (!SymName->startswith("ltmp"))
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000285 Symbols.push_back(Symbol);
286 }
Owen Andersond9243c42011-10-17 21:37:35 +0000287
Alexey Samsonov48803e52014-03-13 14:37:36 +0000288 for (const SectionRef &Section : MachOObj->sections()) {
Owen Andersond9243c42011-10-17 21:37:35 +0000289 StringRef SectName;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000290 Section.getName(SectName);
291 Sections.push_back(Section);
Owen Andersond9243c42011-10-17 21:37:35 +0000292 }
293
Kevin Enderby273ae012013-06-06 17:20:50 +0000294 bool BaseSegmentAddressSet = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000295 for (const auto &Command : MachOObj->load_commands()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000296 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
Benjamin Kramer699128e2011-09-21 01:13:19 +0000297 // We found a function starts segment, parse the addresses for later
298 // consumption.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000299 MachO::linkedit_data_command LLC =
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000300 MachOObj->getLinkeditDataLoadCommand(Command);
Benjamin Kramer699128e2011-09-21 01:13:19 +0000301
Charles Davis8bdfafd2013-09-01 04:28:48 +0000302 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000303 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
304 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000305 StringRef SegName = SLC.segname;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000306 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
Kevin Enderby273ae012013-06-06 17:20:50 +0000307 BaseSegmentAddressSet = true;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000308 BaseSegmentAddress = SLC.vmaddr;
Kevin Enderby273ae012013-06-06 17:20:50 +0000309 }
310 }
Benjamin Kramer8a529dc2011-09-21 22:16:43 +0000311 }
Benjamin Kramer699128e2011-09-21 01:13:19 +0000312}
313
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000314static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
315 uint32_t n, uint32_t count,
316 uint32_t stride, uint64_t addr) {
317 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
318 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
319 if (n > nindirectsyms)
320 outs() << " (entries start past the end of the indirect symbol "
321 "table) (reserved1 field greater than the table size)";
322 else if (n + count > nindirectsyms)
323 outs() << " (entries extends past the end of the indirect symbol "
324 "table)";
325 outs() << "\n";
326 uint32_t cputype = O->getHeader().cputype;
327 if (cputype & MachO::CPU_ARCH_ABI64)
328 outs() << "address index";
329 else
330 outs() << "address index";
331 if (verbose)
332 outs() << " name\n";
333 else
334 outs() << "\n";
335 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
336 if (cputype & MachO::CPU_ARCH_ABI64)
337 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
338 else
339 outs() << format("0x%08" PRIx32, addr + j * stride) << " ";
340 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
341 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
342 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
343 outs() << "LOCAL\n";
344 continue;
345 }
346 if (indirect_symbol ==
347 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
348 outs() << "LOCAL ABSOLUTE\n";
349 continue;
350 }
351 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
352 outs() << "ABSOLUTE\n";
353 continue;
354 }
355 outs() << format("%5u ", indirect_symbol);
Kevin Enderbyf0640752015-03-13 17:56:32 +0000356 if (verbose) {
357 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
358 if (indirect_symbol < Symtab.nsyms) {
359 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
360 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000361 Expected<StringRef> SymName = Symbol.getName();
362 if (!SymName) {
363 std::string Buf;
364 raw_string_ostream OS(Buf);
365 logAllUnhandledErrors(SymName.takeError(), OS, "");
366 OS.flush();
367 report_fatal_error(Buf);
368 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000369 outs() << *SymName;
Kevin Enderbyf0640752015-03-13 17:56:32 +0000370 } else {
371 outs() << "?";
372 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000373 }
374 outs() << "\n";
375 }
376}
377
378static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000379 for (const auto &Load : O->load_commands()) {
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000380 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
381 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
382 for (unsigned J = 0; J < Seg.nsects; ++J) {
383 MachO::section_64 Sec = O->getSection64(Load, J);
384 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
385 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
386 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
387 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
388 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
389 section_type == MachO::S_SYMBOL_STUBS) {
390 uint32_t stride;
391 if (section_type == MachO::S_SYMBOL_STUBS)
392 stride = Sec.reserved2;
393 else
394 stride = 8;
395 if (stride == 0) {
396 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
397 << Sec.sectname << ") "
398 << "(size of stubs in reserved2 field is zero)\n";
399 continue;
400 }
401 uint32_t count = Sec.size / stride;
402 outs() << "Indirect symbols for (" << Sec.segname << ","
403 << Sec.sectname << ") " << count << " entries";
404 uint32_t n = Sec.reserved1;
405 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
406 }
407 }
408 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
409 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
410 for (unsigned J = 0; J < Seg.nsects; ++J) {
411 MachO::section Sec = O->getSection(Load, J);
412 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
413 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
414 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
415 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
416 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
417 section_type == MachO::S_SYMBOL_STUBS) {
418 uint32_t stride;
419 if (section_type == MachO::S_SYMBOL_STUBS)
420 stride = Sec.reserved2;
421 else
422 stride = 4;
423 if (stride == 0) {
424 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
425 << Sec.sectname << ") "
426 << "(size of stubs in reserved2 field is zero)\n";
427 continue;
428 }
429 uint32_t count = Sec.size / stride;
430 outs() << "Indirect symbols for (" << Sec.segname << ","
431 << Sec.sectname << ") " << count << " entries";
432 uint32_t n = Sec.reserved1;
433 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
434 }
435 }
436 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000437 }
438}
439
Kevin Enderby69fe98d2015-01-23 18:52:17 +0000440static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
441 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
442 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
443 outs() << "Data in code table (" << nentries << " entries)\n";
444 outs() << "offset length kind\n";
445 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
446 ++DI) {
447 uint32_t Offset;
448 DI->getOffset(Offset);
449 outs() << format("0x%08" PRIx32, Offset) << " ";
450 uint16_t Length;
451 DI->getLength(Length);
452 outs() << format("%6u", Length) << " ";
453 uint16_t Kind;
454 DI->getKind(Kind);
455 if (verbose) {
456 switch (Kind) {
457 case MachO::DICE_KIND_DATA:
458 outs() << "DATA";
459 break;
460 case MachO::DICE_KIND_JUMP_TABLE8:
461 outs() << "JUMP_TABLE8";
462 break;
463 case MachO::DICE_KIND_JUMP_TABLE16:
464 outs() << "JUMP_TABLE16";
465 break;
466 case MachO::DICE_KIND_JUMP_TABLE32:
467 outs() << "JUMP_TABLE32";
468 break;
469 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
470 outs() << "ABS_JUMP_TABLE32";
471 break;
472 default:
473 outs() << format("0x%04" PRIx32, Kind);
474 break;
475 }
476 } else
477 outs() << format("0x%04" PRIx32, Kind);
478 outs() << "\n";
479 }
480}
481
Kevin Enderby9a509442015-01-27 21:28:24 +0000482static void PrintLinkOptHints(MachOObjectFile *O) {
483 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
484 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
485 uint32_t nloh = LohLC.datasize;
486 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
487 for (uint32_t i = 0; i < nloh;) {
488 unsigned n;
489 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
490 i += n;
491 outs() << " identifier " << identifier << " ";
492 if (i >= nloh)
493 return;
494 switch (identifier) {
495 case 1:
496 outs() << "AdrpAdrp\n";
497 break;
498 case 2:
499 outs() << "AdrpLdr\n";
500 break;
501 case 3:
502 outs() << "AdrpAddLdr\n";
503 break;
504 case 4:
505 outs() << "AdrpLdrGotLdr\n";
506 break;
507 case 5:
508 outs() << "AdrpAddStr\n";
509 break;
510 case 6:
511 outs() << "AdrpLdrGotStr\n";
512 break;
513 case 7:
514 outs() << "AdrpAdd\n";
515 break;
516 case 8:
517 outs() << "AdrpLdrGot\n";
518 break;
519 default:
520 outs() << "Unknown identifier value\n";
521 break;
522 }
523 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
524 i += n;
525 outs() << " narguments " << narguments << "\n";
526 if (i >= nloh)
527 return;
528
529 for (uint32_t j = 0; j < narguments; j++) {
530 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
531 i += n;
532 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
533 if (i >= nloh)
534 return;
535 }
536 }
537}
538
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000539static void PrintDylibs(MachOObjectFile *O, bool JustId) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000540 unsigned Index = 0;
541 for (const auto &Load : O->load_commands()) {
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000542 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
543 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
544 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
545 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
546 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
547 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
548 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
549 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
550 if (dl.dylib.name < dl.cmdsize) {
551 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
552 if (JustId)
553 outs() << p << "\n";
554 else {
555 outs() << "\t" << p;
556 outs() << " (compatibility version "
557 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
558 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
559 << (dl.dylib.compatibility_version & 0xff) << ",";
560 outs() << " current version "
561 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
562 << ((dl.dylib.current_version >> 8) & 0xff) << "."
563 << (dl.dylib.current_version & 0xff) << ")\n";
564 }
565 } else {
566 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
567 if (Load.C.cmd == MachO::LC_ID_DYLIB)
568 outs() << "LC_ID_DYLIB ";
569 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
570 outs() << "LC_LOAD_DYLIB ";
571 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
572 outs() << "LC_LOAD_WEAK_DYLIB ";
573 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
574 outs() << "LC_LAZY_LOAD_DYLIB ";
575 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
576 outs() << "LC_REEXPORT_DYLIB ";
577 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
578 outs() << "LC_LOAD_UPWARD_DYLIB ";
579 else
580 outs() << "LC_??? ";
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000581 outs() << "command " << Index++ << "\n";
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000582 }
583 }
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000584 }
585}
586
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000587typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
588
589static void CreateSymbolAddressMap(MachOObjectFile *O,
590 SymbolAddressMap *AddrMap) {
591 // Create a map of symbol addresses to symbol names.
592 for (const SymbolRef &Symbol : O->symbols()) {
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000593 ErrorOr<SymbolRef::Type> STOrErr = Symbol.getType();
594 if (std::error_code EC = STOrErr.getError())
595 report_fatal_error(EC.message());
596 SymbolRef::Type ST = *STOrErr;
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000597 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
598 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +0000599 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000600 Expected<StringRef> SymNameOrErr = Symbol.getName();
601 if (!SymNameOrErr) {
602 std::string Buf;
603 raw_string_ostream OS(Buf);
604 logAllUnhandledErrors(SymNameOrErr.takeError(), OS, "");
605 OS.flush();
606 report_fatal_error(Buf);
607 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000608 StringRef SymName = *SymNameOrErr;
Kevin Enderby846c0002015-04-16 17:19:59 +0000609 if (!SymName.startswith(".objc"))
610 (*AddrMap)[Address] = SymName;
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000611 }
612 }
613}
614
615// GuessSymbolName is passed the address of what might be a symbol and a
616// pointer to the SymbolAddressMap. It returns the name of a symbol
617// with that address or nullptr if no symbol is found with that address.
618static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
619 const char *SymbolName = nullptr;
620 // A DenseMap can't lookup up some values.
621 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
622 StringRef name = AddrMap->lookup(value);
623 if (!name.empty())
624 SymbolName = name.data();
625 }
626 return SymbolName;
627}
628
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000629static void DumpCstringChar(const char c) {
630 char p[2];
631 p[0] = c;
632 p[1] = '\0';
633 outs().write_escaped(p);
634}
635
Kevin Enderby10ba0412015-02-04 21:38:42 +0000636static void DumpCstringSection(MachOObjectFile *O, const char *sect,
637 uint32_t sect_size, uint64_t sect_addr,
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000638 bool print_addresses) {
Kevin Enderby10ba0412015-02-04 21:38:42 +0000639 for (uint32_t i = 0; i < sect_size; i++) {
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000640 if (print_addresses) {
641 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000642 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000643 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000644 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000645 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000646 for (; i < sect_size && sect[i] != '\0'; i++)
647 DumpCstringChar(sect[i]);
Kevin Enderby10ba0412015-02-04 21:38:42 +0000648 if (i < sect_size && sect[i] == '\0')
649 outs() << "\n";
650 }
651}
652
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000653static void DumpLiteral4(uint32_t l, float f) {
654 outs() << format("0x%08" PRIx32, l);
655 if ((l & 0x7f800000) != 0x7f800000)
656 outs() << format(" (%.16e)\n", f);
657 else {
658 if (l == 0x7f800000)
659 outs() << " (+Infinity)\n";
660 else if (l == 0xff800000)
661 outs() << " (-Infinity)\n";
662 else if ((l & 0x00400000) == 0x00400000)
663 outs() << " (non-signaling Not-a-Number)\n";
664 else
665 outs() << " (signaling Not-a-Number)\n";
666 }
667}
668
669static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
670 uint32_t sect_size, uint64_t sect_addr,
671 bool print_addresses) {
672 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
673 if (print_addresses) {
674 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000675 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000676 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000677 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000678 }
679 float f;
680 memcpy(&f, sect + i, sizeof(float));
681 if (O->isLittleEndian() != sys::IsLittleEndianHost)
682 sys::swapByteOrder(f);
683 uint32_t l;
684 memcpy(&l, sect + i, sizeof(uint32_t));
685 if (O->isLittleEndian() != sys::IsLittleEndianHost)
686 sys::swapByteOrder(l);
687 DumpLiteral4(l, f);
688 }
689}
690
691static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
692 double d) {
693 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
694 uint32_t Hi, Lo;
Davide Italianob627d9f2015-12-12 21:50:11 +0000695 Hi = (O->isLittleEndian()) ? l1 : l0;
696 Lo = (O->isLittleEndian()) ? l0 : l1;
697
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000698 // Hi is the high word, so this is equivalent to if(isfinite(d))
699 if ((Hi & 0x7ff00000) != 0x7ff00000)
700 outs() << format(" (%.16e)\n", d);
701 else {
702 if (Hi == 0x7ff00000 && Lo == 0)
703 outs() << " (+Infinity)\n";
704 else if (Hi == 0xfff00000 && Lo == 0)
705 outs() << " (-Infinity)\n";
706 else if ((Hi & 0x00080000) == 0x00080000)
707 outs() << " (non-signaling Not-a-Number)\n";
708 else
709 outs() << " (signaling Not-a-Number)\n";
710 }
711}
712
713static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
714 uint32_t sect_size, uint64_t sect_addr,
715 bool print_addresses) {
716 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
717 if (print_addresses) {
718 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000719 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000720 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000721 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000722 }
723 double d;
724 memcpy(&d, sect + i, sizeof(double));
725 if (O->isLittleEndian() != sys::IsLittleEndianHost)
726 sys::swapByteOrder(d);
727 uint32_t l0, l1;
728 memcpy(&l0, sect + i, sizeof(uint32_t));
729 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
730 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
731 sys::swapByteOrder(l0);
732 sys::swapByteOrder(l1);
733 }
734 DumpLiteral8(O, l0, l1, d);
735 }
736}
737
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000738static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
739 outs() << format("0x%08" PRIx32, l0) << " ";
740 outs() << format("0x%08" PRIx32, l1) << " ";
741 outs() << format("0x%08" PRIx32, l2) << " ";
742 outs() << format("0x%08" PRIx32, l3) << "\n";
743}
744
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000745static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
746 uint32_t sect_size, uint64_t sect_addr,
747 bool print_addresses) {
748 for (uint32_t i = 0; i < sect_size; i += 16) {
749 if (print_addresses) {
750 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000751 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000752 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000753 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000754 }
755 uint32_t l0, l1, l2, l3;
756 memcpy(&l0, sect + i, sizeof(uint32_t));
757 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
758 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
759 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
760 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
761 sys::swapByteOrder(l0);
762 sys::swapByteOrder(l1);
763 sys::swapByteOrder(l2);
764 sys::swapByteOrder(l3);
765 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000766 DumpLiteral16(l0, l1, l2, l3);
767 }
768}
769
770static void DumpLiteralPointerSection(MachOObjectFile *O,
771 const SectionRef &Section,
772 const char *sect, uint32_t sect_size,
773 uint64_t sect_addr,
774 bool print_addresses) {
775 // Collect the literal sections in this Mach-O file.
776 std::vector<SectionRef> LiteralSections;
777 for (const SectionRef &Section : O->sections()) {
778 DataRefImpl Ref = Section.getRawDataRefImpl();
779 uint32_t section_type;
780 if (O->is64Bit()) {
781 const MachO::section_64 Sec = O->getSection64(Ref);
782 section_type = Sec.flags & MachO::SECTION_TYPE;
783 } else {
784 const MachO::section Sec = O->getSection(Ref);
785 section_type = Sec.flags & MachO::SECTION_TYPE;
786 }
787 if (section_type == MachO::S_CSTRING_LITERALS ||
788 section_type == MachO::S_4BYTE_LITERALS ||
789 section_type == MachO::S_8BYTE_LITERALS ||
790 section_type == MachO::S_16BYTE_LITERALS)
791 LiteralSections.push_back(Section);
792 }
793
794 // Set the size of the literal pointer.
795 uint32_t lp_size = O->is64Bit() ? 8 : 4;
796
Eric Christopher572e03a2015-06-19 01:53:21 +0000797 // Collect the external relocation symbols for the literal pointers.
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000798 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
799 for (const RelocationRef &Reloc : Section.relocations()) {
800 DataRefImpl Rel;
801 MachO::any_relocation_info RE;
802 bool isExtern = false;
803 Rel = Reloc.getRawDataRefImpl();
804 RE = O->getRelocation(Rel);
805 isExtern = O->getPlainRelocationExternal(RE);
806 if (isExtern) {
Rafael Espindola96d071c2015-06-29 23:29:12 +0000807 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000808 symbol_iterator RelocSym = Reloc.getSymbol();
809 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
810 }
811 }
812 array_pod_sort(Relocs.begin(), Relocs.end());
813
814 // Dump each literal pointer.
815 for (uint32_t i = 0; i < sect_size; i += lp_size) {
816 if (print_addresses) {
817 if (O->is64Bit())
818 outs() << format("%016" PRIx64, sect_addr + i) << " ";
819 else
820 outs() << format("%08" PRIx64, sect_addr + i) << " ";
821 }
822 uint64_t lp;
823 if (O->is64Bit()) {
824 memcpy(&lp, sect + i, sizeof(uint64_t));
825 if (O->isLittleEndian() != sys::IsLittleEndianHost)
826 sys::swapByteOrder(lp);
827 } else {
828 uint32_t li;
829 memcpy(&li, sect + i, sizeof(uint32_t));
830 if (O->isLittleEndian() != sys::IsLittleEndianHost)
831 sys::swapByteOrder(li);
832 lp = li;
833 }
834
835 // First look for an external relocation entry for this literal pointer.
David Blaikie33dd45d02015-03-23 18:39:02 +0000836 auto Reloc = std::find_if(
837 Relocs.begin(), Relocs.end(),
838 [&](const std::pair<uint64_t, SymbolRef> &P) { return P.first == i; });
839 if (Reloc != Relocs.end()) {
840 symbol_iterator RelocSym = Reloc->second;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000841 Expected<StringRef> SymName = RelocSym->getName();
842 if (!SymName) {
843 std::string Buf;
844 raw_string_ostream OS(Buf);
845 logAllUnhandledErrors(SymName.takeError(), OS, "");
846 OS.flush();
847 report_fatal_error(Buf);
848 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000849 outs() << "external relocation entry for symbol:" << *SymName << "\n";
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000850 continue;
David Blaikie33dd45d02015-03-23 18:39:02 +0000851 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000852
853 // For local references see what the section the literal pointer points to.
David Blaikie33dd45d02015-03-23 18:39:02 +0000854 auto Sect = std::find_if(LiteralSections.begin(), LiteralSections.end(),
855 [&](const SectionRef &R) {
856 return lp >= R.getAddress() &&
857 lp < R.getAddress() + R.getSize();
858 });
859 if (Sect == LiteralSections.end()) {
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000860 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
David Blaikie33dd45d02015-03-23 18:39:02 +0000861 continue;
862 }
863
864 uint64_t SectAddress = Sect->getAddress();
865 uint64_t SectSize = Sect->getSize();
866
867 StringRef SectName;
868 Sect->getName(SectName);
869 DataRefImpl Ref = Sect->getRawDataRefImpl();
870 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
871 outs() << SegmentName << ":" << SectName << ":";
872
873 uint32_t section_type;
874 if (O->is64Bit()) {
875 const MachO::section_64 Sec = O->getSection64(Ref);
876 section_type = Sec.flags & MachO::SECTION_TYPE;
877 } else {
878 const MachO::section Sec = O->getSection(Ref);
879 section_type = Sec.flags & MachO::SECTION_TYPE;
880 }
881
882 StringRef BytesStr;
883 Sect->getContents(BytesStr);
884 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
885
886 switch (section_type) {
887 case MachO::S_CSTRING_LITERALS:
888 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
889 i++) {
890 DumpCstringChar(Contents[i]);
891 }
892 outs() << "\n";
893 break;
894 case MachO::S_4BYTE_LITERALS:
895 float f;
896 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
897 uint32_t l;
898 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
899 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
900 sys::swapByteOrder(f);
901 sys::swapByteOrder(l);
902 }
903 DumpLiteral4(l, f);
904 break;
905 case MachO::S_8BYTE_LITERALS: {
906 double d;
907 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
908 uint32_t l0, l1;
909 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
910 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
911 sizeof(uint32_t));
912 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
913 sys::swapByteOrder(f);
914 sys::swapByteOrder(l0);
915 sys::swapByteOrder(l1);
916 }
917 DumpLiteral8(O, l0, l1, d);
918 break;
919 }
920 case MachO::S_16BYTE_LITERALS: {
921 uint32_t l0, l1, l2, l3;
922 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
923 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
924 sizeof(uint32_t));
925 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
926 sizeof(uint32_t));
927 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
928 sizeof(uint32_t));
929 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
930 sys::swapByteOrder(l0);
931 sys::swapByteOrder(l1);
932 sys::swapByteOrder(l2);
933 sys::swapByteOrder(l3);
934 }
935 DumpLiteral16(l0, l1, l2, l3);
936 break;
937 }
938 }
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000939 }
940}
941
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000942static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
943 uint32_t sect_size, uint64_t sect_addr,
944 SymbolAddressMap *AddrMap,
945 bool verbose) {
946 uint32_t stride;
Davide Italiano3eb47e22015-12-15 23:14:21 +0000947 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000948 for (uint32_t i = 0; i < sect_size; i += stride) {
949 const char *SymbolName = nullptr;
950 if (O->is64Bit()) {
951 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
952 uint64_t pointer_value;
953 memcpy(&pointer_value, sect + i, stride);
954 if (O->isLittleEndian() != sys::IsLittleEndianHost)
955 sys::swapByteOrder(pointer_value);
956 outs() << format("0x%016" PRIx64, pointer_value);
957 if (verbose)
958 SymbolName = GuessSymbolName(pointer_value, AddrMap);
959 } else {
960 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
961 uint32_t pointer_value;
962 memcpy(&pointer_value, sect + i, stride);
963 if (O->isLittleEndian() != sys::IsLittleEndianHost)
964 sys::swapByteOrder(pointer_value);
965 outs() << format("0x%08" PRIx32, pointer_value);
966 if (verbose)
967 SymbolName = GuessSymbolName(pointer_value, AddrMap);
968 }
969 if (SymbolName)
970 outs() << " " << SymbolName;
971 outs() << "\n";
972 }
973}
974
975static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
976 uint32_t size, uint64_t addr) {
977 uint32_t cputype = O->getHeader().cputype;
978 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
979 uint32_t j;
980 for (uint32_t i = 0; i < size; i += j, addr += j) {
981 if (O->is64Bit())
982 outs() << format("%016" PRIx64, addr) << "\t";
983 else
Kevin Enderbyf0640752015-03-13 17:56:32 +0000984 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000985 for (j = 0; j < 16 && i + j < size; j++) {
986 uint8_t byte_word = *(sect + i + j);
987 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
988 }
989 outs() << "\n";
990 }
991 } else {
992 uint32_t j;
993 for (uint32_t i = 0; i < size; i += j, addr += j) {
994 if (O->is64Bit())
995 outs() << format("%016" PRIx64, addr) << "\t";
996 else
997 outs() << format("%08" PRIx64, sect) << "\t";
998 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
999 j += sizeof(int32_t)) {
1000 if (i + j + sizeof(int32_t) < size) {
1001 uint32_t long_word;
1002 memcpy(&long_word, sect + i + j, sizeof(int32_t));
1003 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1004 sys::swapByteOrder(long_word);
1005 outs() << format("%08" PRIx32, long_word) << " ";
1006 } else {
1007 for (uint32_t k = 0; i + j + k < size; k++) {
1008 uint8_t byte_word = *(sect + i + j);
1009 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1010 }
1011 }
1012 }
1013 outs() << "\n";
1014 }
1015 }
1016}
1017
Kevin Enderby95df54c2015-02-04 01:01:38 +00001018static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1019 StringRef DisSegName, StringRef DisSectName);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001020static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1021 uint32_t size, uint32_t addr);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001022
1023static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1024 bool verbose) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001025 SymbolAddressMap AddrMap;
1026 if (verbose)
1027 CreateSymbolAddressMap(O, &AddrMap);
1028
Colin LeMahieufcc32762015-07-29 19:08:10 +00001029 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1030 StringRef DumpSection = FilterSections[i];
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001031 std::pair<StringRef, StringRef> DumpSegSectName;
1032 DumpSegSectName = DumpSection.split(',');
1033 StringRef DumpSegName, DumpSectName;
1034 if (DumpSegSectName.second.size()) {
1035 DumpSegName = DumpSegSectName.first;
1036 DumpSectName = DumpSegSectName.second;
1037 } else {
1038 DumpSegName = "";
1039 DumpSectName = DumpSegSectName.first;
1040 }
1041 for (const SectionRef &Section : O->sections()) {
1042 StringRef SectName;
1043 Section.getName(SectName);
1044 DataRefImpl Ref = Section.getRawDataRefImpl();
1045 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1046 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1047 (SectName == DumpSectName)) {
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001048
Kevin Enderby95df54c2015-02-04 01:01:38 +00001049 uint32_t section_flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001050 if (O->is64Bit()) {
1051 const MachO::section_64 Sec = O->getSection64(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001052 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001053
1054 } else {
1055 const MachO::section Sec = O->getSection(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001056 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001057 }
Kevin Enderby95df54c2015-02-04 01:01:38 +00001058 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001059
1060 StringRef BytesStr;
1061 Section.getContents(BytesStr);
1062 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1063 uint32_t sect_size = BytesStr.size();
1064 uint64_t sect_addr = Section.getAddress();
1065
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001066 outs() << "Contents of (" << SegName << "," << SectName
1067 << ") section\n";
1068
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001069 if (verbose) {
Kevin Enderby95df54c2015-02-04 01:01:38 +00001070 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1071 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1072 DisassembleMachO(Filename, O, SegName, SectName);
1073 continue;
1074 }
Kevin Enderbycd66be52015-03-11 22:06:32 +00001075 if (SegName == "__TEXT" && SectName == "__info_plist") {
1076 outs() << sect;
1077 continue;
1078 }
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001079 if (SegName == "__OBJC" && SectName == "__protocol") {
1080 DumpProtocolSection(O, sect, sect_size, sect_addr);
1081 continue;
1082 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001083 switch (section_type) {
1084 case MachO::S_REGULAR:
1085 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1086 break;
1087 case MachO::S_ZEROFILL:
1088 outs() << "zerofill section and has no contents in the file\n";
1089 break;
Kevin Enderby10ba0412015-02-04 21:38:42 +00001090 case MachO::S_CSTRING_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001091 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001092 break;
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001093 case MachO::S_4BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001094 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001095 break;
1096 case MachO::S_8BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001097 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001098 break;
1099 case MachO::S_16BYTE_LITERALS:
Kevin Enderby0fc11822015-04-01 20:57:01 +00001100 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1101 break;
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001102 case MachO::S_LITERAL_POINTERS:
1103 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001104 !NoLeadingAddr);
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001105 break;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001106 case MachO::S_MOD_INIT_FUNC_POINTERS:
1107 case MachO::S_MOD_TERM_FUNC_POINTERS:
1108 DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
1109 verbose);
1110 break;
1111 default:
1112 outs() << "Unknown section type ("
1113 << format("0x%08" PRIx32, section_type) << ")\n";
1114 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1115 break;
1116 }
1117 } else {
1118 if (section_type == MachO::S_ZEROFILL)
1119 outs() << "zerofill section and has no contents in the file\n";
1120 else
1121 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1122 }
1123 }
1124 }
1125 }
1126}
1127
Kevin Enderbycd66be52015-03-11 22:06:32 +00001128static void DumpInfoPlistSectionContents(StringRef Filename,
1129 MachOObjectFile *O) {
1130 for (const SectionRef &Section : O->sections()) {
1131 StringRef SectName;
1132 Section.getName(SectName);
1133 DataRefImpl Ref = Section.getRawDataRefImpl();
1134 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1135 if (SegName == "__TEXT" && SectName == "__info_plist") {
1136 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1137 StringRef BytesStr;
1138 Section.getContents(BytesStr);
1139 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1140 outs() << sect;
1141 return;
1142 }
1143 }
1144}
1145
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001146// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1147// and if it is and there is a list of architecture flags is specified then
1148// check to make sure this Mach-O file is one of those architectures or all
1149// architectures were specified. If not then an error is generated and this
1150// routine returns false. Else it returns true.
1151static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1152 if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
1153 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
1154 bool ArchFound = false;
1155 MachO::mach_header H;
1156 MachO::mach_header_64 H_64;
1157 Triple T;
1158 if (MachO->is64Bit()) {
1159 H_64 = MachO->MachOObjectFile::getHeader64();
1160 T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
1161 } else {
1162 H = MachO->MachOObjectFile::getHeader();
1163 T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
1164 }
1165 unsigned i;
1166 for (i = 0; i < ArchFlags.size(); ++i) {
1167 if (ArchFlags[i] == T.getArchName())
1168 ArchFound = true;
1169 break;
1170 }
1171 if (!ArchFound) {
1172 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1173 << "architecture: " + ArchFlags[i] + "\n";
1174 return false;
1175 }
1176 }
1177 return true;
1178}
1179
Kevin Enderby0fc11822015-04-01 20:57:01 +00001180static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1181
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001182// ProcessMachO() is passed a single opened Mach-O file, which may be an
1183// archive member and or in a slice of a universal file. It prints the
1184// the file name and header info and then processes it according to the
1185// command line options.
1186static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
1187 StringRef ArchiveMemberName = StringRef(),
1188 StringRef ArchitectureName = StringRef()) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001189 // If we are doing some processing here on the Mach-O file print the header
1190 // info. And don't print it otherwise like in the case of printing the
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001191 // UniversalHeaders or ArchiveHeaders.
Kevin Enderby131d1772015-01-09 19:22:37 +00001192 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind ||
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001193 LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints ||
Colin LeMahieufcc32762015-07-29 19:08:10 +00001194 DylibsUsed || DylibId || ObjcMetaData || (FilterSections.size() != 0)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001195 outs() << Filename;
1196 if (!ArchiveMemberName.empty())
1197 outs() << '(' << ArchiveMemberName << ')';
1198 if (!ArchitectureName.empty())
1199 outs() << " (architecture " << ArchitectureName << ")";
1200 outs() << ":\n";
1201 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001202
1203 if (Disassemble)
Kevin Enderby95df54c2015-02-04 01:01:38 +00001204 DisassembleMachO(Filename, MachOOF, "__TEXT", "__text");
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001205 if (IndirectSymbols)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001206 PrintIndirectSymbols(MachOOF, !NonVerbose);
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001207 if (DataInCode)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001208 PrintDataInCodeTable(MachOOF, !NonVerbose);
Kevin Enderby9a509442015-01-27 21:28:24 +00001209 if (LinkOptHints)
1210 PrintLinkOptHints(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001211 if (Relocations)
1212 PrintRelocations(MachOOF);
1213 if (SectionHeaders)
1214 PrintSectionHeaders(MachOOF);
1215 if (SectionContents)
1216 PrintSectionContents(MachOOF);
Colin LeMahieufcc32762015-07-29 19:08:10 +00001217 if (FilterSections.size() != 0)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001218 DumpSectionContents(Filename, MachOOF, !NonVerbose);
Kevin Enderbycd66be52015-03-11 22:06:32 +00001219 if (InfoPlist)
1220 DumpInfoPlistSectionContents(Filename, MachOOF);
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001221 if (DylibsUsed)
1222 PrintDylibs(MachOOF, false);
1223 if (DylibId)
1224 PrintDylibs(MachOOF, true);
Kevin Enderby98da6132015-01-20 21:47:46 +00001225 if (SymbolTable)
1226 PrintSymbolTable(MachOOF);
1227 if (UnwindInfo)
1228 printMachOUnwindInfo(MachOOF);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001229 if (PrivateHeaders) {
1230 printMachOFileHeader(MachOOF);
1231 printMachOLoadCommands(MachOOF);
1232 }
1233 if (FirstPrivateHeader)
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001234 printMachOFileHeader(MachOOF);
Kevin Enderby0fc11822015-04-01 20:57:01 +00001235 if (ObjcMetaData)
1236 printObjcMetaData(MachOOF, !NonVerbose);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001237 if (ExportsTrie)
1238 printExportsTrie(MachOOF);
1239 if (Rebase)
1240 printRebaseTable(MachOOF);
1241 if (Bind)
1242 printBindTable(MachOOF);
1243 if (LazyBind)
1244 printLazyBindTable(MachOOF);
1245 if (WeakBind)
1246 printWeakBindTable(MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001247
1248 if (DwarfDumpType != DIDT_Null) {
1249 std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*MachOOF));
1250 // Dump the complete DWARF structure.
1251 DICtx->dump(outs(), DwarfDumpType, true /* DumpEH */);
1252 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001253}
1254
Kevin Enderby131d1772015-01-09 19:22:37 +00001255// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1256static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1257 outs() << " cputype (" << cputype << ")\n";
1258 outs() << " cpusubtype (" << cpusubtype << ")\n";
1259}
1260
1261// printCPUType() helps print_fat_headers by printing the cputype and
1262// pusubtype (symbolically for the one's it knows about).
1263static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1264 switch (cputype) {
1265 case MachO::CPU_TYPE_I386:
1266 switch (cpusubtype) {
1267 case MachO::CPU_SUBTYPE_I386_ALL:
1268 outs() << " cputype CPU_TYPE_I386\n";
1269 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1270 break;
1271 default:
1272 printUnknownCPUType(cputype, cpusubtype);
1273 break;
1274 }
1275 break;
1276 case MachO::CPU_TYPE_X86_64:
1277 switch (cpusubtype) {
1278 case MachO::CPU_SUBTYPE_X86_64_ALL:
1279 outs() << " cputype CPU_TYPE_X86_64\n";
1280 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1281 break;
1282 case MachO::CPU_SUBTYPE_X86_64_H:
1283 outs() << " cputype CPU_TYPE_X86_64\n";
1284 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1285 break;
1286 default:
1287 printUnknownCPUType(cputype, cpusubtype);
1288 break;
1289 }
1290 break;
1291 case MachO::CPU_TYPE_ARM:
1292 switch (cpusubtype) {
1293 case MachO::CPU_SUBTYPE_ARM_ALL:
1294 outs() << " cputype CPU_TYPE_ARM\n";
1295 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1296 break;
1297 case MachO::CPU_SUBTYPE_ARM_V4T:
1298 outs() << " cputype CPU_TYPE_ARM\n";
1299 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1300 break;
1301 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1302 outs() << " cputype CPU_TYPE_ARM\n";
1303 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1304 break;
1305 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1306 outs() << " cputype CPU_TYPE_ARM\n";
1307 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1308 break;
1309 case MachO::CPU_SUBTYPE_ARM_V6:
1310 outs() << " cputype CPU_TYPE_ARM\n";
1311 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1312 break;
1313 case MachO::CPU_SUBTYPE_ARM_V6M:
1314 outs() << " cputype CPU_TYPE_ARM\n";
1315 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1316 break;
1317 case MachO::CPU_SUBTYPE_ARM_V7:
1318 outs() << " cputype CPU_TYPE_ARM\n";
1319 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1320 break;
1321 case MachO::CPU_SUBTYPE_ARM_V7EM:
1322 outs() << " cputype CPU_TYPE_ARM\n";
1323 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1324 break;
1325 case MachO::CPU_SUBTYPE_ARM_V7K:
1326 outs() << " cputype CPU_TYPE_ARM\n";
1327 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1328 break;
1329 case MachO::CPU_SUBTYPE_ARM_V7M:
1330 outs() << " cputype CPU_TYPE_ARM\n";
1331 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1332 break;
1333 case MachO::CPU_SUBTYPE_ARM_V7S:
1334 outs() << " cputype CPU_TYPE_ARM\n";
1335 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1336 break;
1337 default:
1338 printUnknownCPUType(cputype, cpusubtype);
1339 break;
1340 }
1341 break;
1342 case MachO::CPU_TYPE_ARM64:
1343 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1344 case MachO::CPU_SUBTYPE_ARM64_ALL:
1345 outs() << " cputype CPU_TYPE_ARM64\n";
1346 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1347 break;
1348 default:
1349 printUnknownCPUType(cputype, cpusubtype);
1350 break;
1351 }
1352 break;
1353 default:
1354 printUnknownCPUType(cputype, cpusubtype);
1355 break;
1356 }
1357}
1358
1359static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1360 bool verbose) {
1361 outs() << "Fat headers\n";
1362 if (verbose)
1363 outs() << "fat_magic FAT_MAGIC\n";
1364 else
1365 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1366
1367 uint32_t nfat_arch = UB->getNumberOfObjects();
1368 StringRef Buf = UB->getData();
1369 uint64_t size = Buf.size();
1370 uint64_t big_size = sizeof(struct MachO::fat_header) +
1371 nfat_arch * sizeof(struct MachO::fat_arch);
1372 outs() << "nfat_arch " << UB->getNumberOfObjects();
1373 if (nfat_arch == 0)
1374 outs() << " (malformed, contains zero architecture types)\n";
1375 else if (big_size > size)
1376 outs() << " (malformed, architectures past end of file)\n";
1377 else
1378 outs() << "\n";
1379
1380 for (uint32_t i = 0; i < nfat_arch; ++i) {
1381 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1382 uint32_t cputype = OFA.getCPUType();
1383 uint32_t cpusubtype = OFA.getCPUSubType();
1384 outs() << "architecture ";
1385 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1386 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1387 uint32_t other_cputype = other_OFA.getCPUType();
1388 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
Kevin Enderby0512bd72015-01-09 21:55:03 +00001389 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
Kevin Enderby131d1772015-01-09 19:22:37 +00001390 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
Kevin Enderby0512bd72015-01-09 21:55:03 +00001391 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001392 outs() << "(illegal duplicate architecture) ";
1393 break;
Kevin Enderby0512bd72015-01-09 21:55:03 +00001394 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001395 }
1396 if (verbose) {
1397 outs() << OFA.getArchTypeName() << "\n";
1398 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1399 } else {
1400 outs() << i << "\n";
1401 outs() << " cputype " << cputype << "\n";
1402 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1403 << "\n";
1404 }
1405 if (verbose &&
1406 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1407 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1408 else
1409 outs() << " capabilities "
1410 << format("0x%" PRIx32,
1411 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1412 outs() << " offset " << OFA.getOffset();
1413 if (OFA.getOffset() > size)
1414 outs() << " (past end of file)";
1415 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1416 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1417 outs() << "\n";
1418 outs() << " size " << OFA.getSize();
1419 big_size = OFA.getOffset() + OFA.getSize();
1420 if (big_size > size)
1421 outs() << " (past end of file)";
1422 outs() << "\n";
1423 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1424 << ")\n";
1425 }
1426}
1427
Rafael Espindola266b4fe2015-10-31 22:25:59 +00001428static void printArchiveChild(const Archive::Child &C, bool verbose,
Kevin Enderby13023a12015-01-15 23:19:11 +00001429 bool print_offset) {
1430 if (print_offset)
1431 outs() << C.getChildOffset() << "\t";
1432 sys::fs::perms Mode = C.getAccessMode();
1433 if (verbose) {
1434 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1435 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1436 outs() << "-";
Davide Italianobb9a6cc2015-09-07 20:47:03 +00001437 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1438 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1439 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1440 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1441 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1442 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1443 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1444 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1445 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
Kevin Enderby13023a12015-01-15 23:19:11 +00001446 } else {
1447 outs() << format("0%o ", Mode);
1448 }
1449
1450 unsigned UID = C.getUID();
1451 outs() << format("%3d/", UID);
1452 unsigned GID = C.getGID();
1453 outs() << format("%-3d ", GID);
Kevin Enderby7a969422015-11-05 19:24:56 +00001454 ErrorOr<uint64_t> Size = C.getRawSize();
1455 if (std::error_code EC = Size.getError())
1456 report_fatal_error(EC.message());
1457 outs() << format("%5" PRId64, Size.get()) << " ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001458
1459 StringRef RawLastModified = C.getRawLastModified();
1460 if (verbose) {
1461 unsigned Seconds;
1462 if (RawLastModified.getAsInteger(10, Seconds))
1463 outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
1464 else {
1465 // Since cime(3) returns a 26 character string of the form:
1466 // "Sun Sep 16 01:03:52 1973\n\0"
1467 // just print 24 characters.
1468 time_t t = Seconds;
1469 outs() << format("%.24s ", ctime(&t));
1470 }
1471 } else {
1472 outs() << RawLastModified << " ";
1473 }
1474
1475 if (verbose) {
1476 ErrorOr<StringRef> NameOrErr = C.getName();
1477 if (NameOrErr.getError()) {
1478 StringRef RawName = C.getRawName();
1479 outs() << RawName << "\n";
1480 } else {
1481 StringRef Name = NameOrErr.get();
1482 outs() << Name << "\n";
1483 }
1484 } else {
1485 StringRef RawName = C.getRawName();
1486 outs() << RawName << "\n";
1487 }
1488}
1489
1490static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
Rafael Espindola4a782fb2015-10-31 21:03:29 +00001491 for (Archive::child_iterator I = A->child_begin(false), E = A->child_end();
1492 I != E; ++I) {
Kevin Enderby7a969422015-11-05 19:24:56 +00001493 if (std::error_code EC = I->getError())
1494 report_fatal_error(EC.message());
1495 const Archive::Child &C = **I;
Kevin Enderby13023a12015-01-15 23:19:11 +00001496 printArchiveChild(C, verbose, print_offset);
1497 }
1498}
1499
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001500// ParseInputMachO() parses the named Mach-O file in Filename and handles the
1501// -arch flags selecting just those slices as specified by them and also parses
1502// archive files. Then for each individual Mach-O file ProcessMachO() is
1503// called to process the file based on the command line options.
1504void llvm::ParseInputMachO(StringRef Filename) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001505 // Check for -arch all and verifiy the -arch flags are valid.
1506 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1507 if (ArchFlags[i] == "all") {
1508 ArchAll = true;
1509 } else {
1510 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1511 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1512 "'for the -arch option\n";
1513 return;
1514 }
1515 }
1516 }
1517
1518 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00001519 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1520 if (!BinaryOrErr)
1521 report_error(Filename, BinaryOrErr.takeError());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001522 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001523
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001524 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1525 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001526 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001527 printArchiveHeaders(A, !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001528 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
1529 I != E; ++I) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001530 if (std::error_code EC = I->getError())
1531 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001532 auto &C = I->get();
1533 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001534 if (ChildOrErr.getError())
1535 continue;
1536 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1537 if (!checkMachOAndArchFlags(O, Filename))
1538 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001539 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001540 }
1541 }
1542 return;
1543 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001544 if (UniversalHeaders) {
1545 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
Kevin Enderbyf0640752015-03-13 17:56:32 +00001546 printMachOUniversalHeaders(UB, !NonVerbose);
Kevin Enderby131d1772015-01-09 19:22:37 +00001547 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001548 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1549 // If we have a list of architecture flags specified dump only those.
1550 if (!ArchAll && ArchFlags.size() != 0) {
1551 // Look for a slice in the universal binary that matches each ArchFlag.
1552 bool ArchFound;
1553 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1554 ArchFound = false;
1555 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1556 E = UB->end_objects();
1557 I != E; ++I) {
1558 if (ArchFlags[i] == I->getArchTypeName()) {
1559 ArchFound = true;
1560 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
1561 I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001562 std::string ArchitectureName = "";
1563 if (ArchFlags.size() > 1)
1564 ArchitectureName = I->getArchTypeName();
1565 if (ObjOrErr) {
1566 ObjectFile &O = *ObjOrErr.get();
1567 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001568 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001569 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1570 I->getAsArchive()) {
1571 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001572 outs() << "Archive : " << Filename;
1573 if (!ArchitectureName.empty())
1574 outs() << " (architecture " << ArchitectureName << ")";
1575 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001576 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001577 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001578 for (Archive::child_iterator AI = A->child_begin(),
1579 AE = A->child_end();
1580 AI != AE; ++AI) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001581 if (std::error_code EC = AI->getError())
1582 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001583 auto &C = AI->get();
1584 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001585 if (ChildOrErr.getError())
1586 continue;
1587 if (MachOObjectFile *O =
1588 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001589 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001590 }
1591 }
1592 }
1593 }
1594 if (!ArchFound) {
1595 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1596 << "architecture: " + ArchFlags[i] + "\n";
1597 return;
1598 }
1599 }
1600 return;
1601 }
1602 // No architecture flags were specified so if this contains a slice that
1603 // matches the host architecture dump only that.
1604 if (!ArchAll) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001605 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1606 E = UB->end_objects();
1607 I != E; ++I) {
Kevin Enderby0512bd72015-01-09 21:55:03 +00001608 if (MachOObjectFile::getHostArch().getArchName() ==
1609 I->getArchTypeName()) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001610 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001611 std::string ArchiveName;
1612 ArchiveName.clear();
1613 if (ObjOrErr) {
1614 ObjectFile &O = *ObjOrErr.get();
1615 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001616 ProcessMachO(Filename, MachOOF);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001617 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1618 I->getAsArchive()) {
1619 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001620 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001621 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001622 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001623 for (Archive::child_iterator AI = A->child_begin(),
1624 AE = A->child_end();
1625 AI != AE; ++AI) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001626 if (std::error_code EC = AI->getError())
1627 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001628 auto &C = AI->get();
1629 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001630 if (ChildOrErr.getError())
1631 continue;
1632 if (MachOObjectFile *O =
1633 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001634 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001635 }
1636 }
1637 return;
1638 }
1639 }
1640 }
1641 // Either all architectures have been specified or none have been specified
1642 // and this does not contain the host architecture so dump all the slices.
1643 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1644 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1645 E = UB->end_objects();
1646 I != E; ++I) {
1647 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001648 std::string ArchitectureName = "";
1649 if (moreThanOneArch)
1650 ArchitectureName = I->getArchTypeName();
1651 if (ObjOrErr) {
1652 ObjectFile &Obj = *ObjOrErr.get();
1653 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001654 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001655 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
1656 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001657 outs() << "Archive : " << Filename;
1658 if (!ArchitectureName.empty())
1659 outs() << " (architecture " << ArchitectureName << ")";
1660 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001661 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001662 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001663 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
1664 AI != AE; ++AI) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001665 if (std::error_code EC = AI->getError())
1666 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001667 auto &C = AI->get();
1668 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001669 if (ChildOrErr.getError())
1670 continue;
1671 if (MachOObjectFile *O =
1672 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1673 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001674 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1675 ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001676 }
1677 }
1678 }
1679 }
1680 return;
1681 }
1682 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1683 if (!checkMachOAndArchFlags(O, Filename))
1684 return;
1685 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001686 ProcessMachO(Filename, MachOOF);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001687 } else
1688 errs() << "llvm-objdump: '" << Filename << "': "
1689 << "Object is not a Mach-O file type.\n";
Davide Italiano25d84582016-01-13 04:11:36 +00001690 return;
1691 }
1692 llvm_unreachable("Input object can't be invalid at this point");
Rafael Espindola9b709252013-04-13 01:45:40 +00001693}
1694
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001695typedef std::pair<uint64_t, const char *> BindInfoEntry;
1696typedef std::vector<BindInfoEntry> BindTable;
1697typedef BindTable::iterator bind_table_iterator;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001698
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001699// The block of info used by the Symbolizer call backs.
1700struct DisassembleInfo {
1701 bool verbose;
1702 MachOObjectFile *O;
1703 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001704 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001705 std::vector<SectionRef> *Sections;
1706 const char *class_name;
1707 const char *selector_name;
1708 char *method;
Kevin Enderby04bf6932014-10-28 23:39:46 +00001709 char *demangled_name;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001710 uint64_t adrp_addr;
1711 uint32_t adrp_inst;
Kevin Enderby078be602014-10-23 19:53:12 +00001712 BindTable *bindtable;
Kevin Enderbyaac75382015-10-08 16:56:35 +00001713 uint32_t depth;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001714};
1715
1716// SymbolizerGetOpInfo() is the operand information call back function.
1717// This is called to get the symbolic information for operand(s) of an
1718// instruction when it is being done. This routine does this from
1719// the relocation information, symbol table, etc. That block of information
1720// is a pointer to the struct DisassembleInfo that was passed when the
1721// disassembler context was created and passed to back to here when
1722// called back by the disassembler for instruction operands that could have
1723// relocation information. The address of the instruction containing operand is
1724// at the Pc parameter. The immediate value the operand has is passed in
1725// op_info->Value and is at Offset past the start of the instruction and has a
1726// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1727// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1728// names and addends of the symbolic expression to add for the operand. The
1729// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1730// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001731static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1732 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001733 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1734 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001735 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001736
1737 // Make sure all fields returned are zero if we don't set them.
1738 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1739 op_info->Value = value;
1740
1741 // If the TagType is not the value 1 which it code knows about or if no
1742 // verbose symbolic information is wanted then just return 0, indicating no
1743 // information is being returned.
David Blaikie33dd45d02015-03-23 18:39:02 +00001744 if (TagType != 1 || !info->verbose)
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001745 return 0;
1746
1747 unsigned int Arch = info->O->getArch();
1748 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001749 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1750 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001751 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1752 // TODO:
1753 // Search the external relocation entries of a fully linked image
1754 // (if any) for an entry that matches this segment offset.
1755 // uint32_t seg_offset = (Pc + Offset);
1756 return 0;
1757 }
1758 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1759 // for an entry for this section offset.
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001760 uint32_t sect_addr = info->S.getAddress();
1761 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1762 bool reloc_found = false;
1763 DataRefImpl Rel;
1764 MachO::any_relocation_info RE;
1765 bool isExtern = false;
1766 SymbolRef Symbol;
1767 bool r_scattered = false;
1768 uint32_t r_value, pair_r_value, r_type;
1769 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001770 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001771 if (RelocOffset == sect_offset) {
1772 Rel = Reloc.getRawDataRefImpl();
1773 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00001774 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001775 r_scattered = info->O->isRelocationScattered(RE);
1776 if (r_scattered) {
1777 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001778 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1779 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1780 DataRefImpl RelNext = Rel;
1781 info->O->moveRelocationNext(RelNext);
1782 MachO::any_relocation_info RENext;
1783 RENext = info->O->getRelocation(RelNext);
1784 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00001785 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001786 else
1787 return 0;
1788 }
1789 } else {
1790 isExtern = info->O->getPlainRelocationExternal(RE);
1791 if (isExtern) {
1792 symbol_iterator RelocSym = Reloc.getSymbol();
1793 Symbol = *RelocSym;
1794 }
1795 }
1796 reloc_found = true;
1797 break;
1798 }
1799 }
1800 if (reloc_found && isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001801 Expected<StringRef> SymName = Symbol.getName();
1802 if (!SymName) {
1803 std::string Buf;
1804 raw_string_ostream OS(Buf);
1805 logAllUnhandledErrors(SymName.takeError(), OS, "");
1806 OS.flush();
1807 report_fatal_error(Buf);
1808 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001809 const char *name = SymName->data();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001810 op_info->AddSymbol.Present = 1;
1811 op_info->AddSymbol.Name = name;
1812 // For i386 extern relocation entries the value in the instruction is
1813 // the offset from the symbol, and value is already set in op_info->Value.
1814 return 1;
1815 }
1816 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1817 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001818 const char *add = GuessSymbolName(r_value, info->AddrMap);
1819 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001820 uint32_t offset = value - (r_value - pair_r_value);
1821 op_info->AddSymbol.Present = 1;
1822 if (add != nullptr)
1823 op_info->AddSymbol.Name = add;
1824 else
1825 op_info->AddSymbol.Value = r_value;
1826 op_info->SubtractSymbol.Present = 1;
1827 if (sub != nullptr)
1828 op_info->SubtractSymbol.Name = sub;
1829 else
1830 op_info->SubtractSymbol.Value = pair_r_value;
1831 op_info->Value = offset;
1832 return 1;
1833 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001834 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001835 }
1836 if (Arch == Triple::x86_64) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001837 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1838 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001839 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1840 // TODO:
1841 // Search the external relocation entries of a fully linked image
1842 // (if any) for an entry that matches this segment offset.
1843 // uint64_t seg_offset = (Pc + Offset);
1844 return 0;
1845 }
1846 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1847 // for an entry for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00001848 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001849 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1850 bool reloc_found = false;
1851 DataRefImpl Rel;
1852 MachO::any_relocation_info RE;
1853 bool isExtern = false;
1854 SymbolRef Symbol;
1855 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001856 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001857 if (RelocOffset == sect_offset) {
1858 Rel = Reloc.getRawDataRefImpl();
1859 RE = info->O->getRelocation(Rel);
1860 // NOTE: Scattered relocations don't exist on x86_64.
1861 isExtern = info->O->getPlainRelocationExternal(RE);
1862 if (isExtern) {
1863 symbol_iterator RelocSym = Reloc.getSymbol();
1864 Symbol = *RelocSym;
1865 }
1866 reloc_found = true;
1867 break;
1868 }
1869 }
1870 if (reloc_found && isExtern) {
1871 // The Value passed in will be adjusted by the Pc if the instruction
1872 // adds the Pc. But for x86_64 external relocation entries the Value
1873 // is the offset from the external symbol.
1874 if (info->O->getAnyRelocationPCRel(RE))
1875 op_info->Value -= Pc + Offset + Size;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001876 Expected<StringRef> SymName = Symbol.getName();
1877 if (!SymName) {
1878 std::string Buf;
1879 raw_string_ostream OS(Buf);
1880 logAllUnhandledErrors(SymName.takeError(), OS, "");
1881 OS.flush();
1882 report_fatal_error(Buf);
1883 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001884 const char *name = SymName->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001885 unsigned Type = info->O->getAnyRelocationType(RE);
1886 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1887 DataRefImpl RelNext = Rel;
1888 info->O->moveRelocationNext(RelNext);
1889 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1890 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1891 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1892 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1893 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1894 op_info->SubtractSymbol.Present = 1;
1895 op_info->SubtractSymbol.Name = name;
1896 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1897 Symbol = *RelocSymNext;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001898 Expected<StringRef> SymNameNext = Symbol.getName();
1899 if (!SymNameNext) {
1900 std::string Buf;
1901 raw_string_ostream OS(Buf);
1902 logAllUnhandledErrors(SymNameNext.takeError(), OS, "");
1903 OS.flush();
1904 report_fatal_error(Buf);
1905 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001906 name = SymNameNext->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001907 }
1908 }
1909 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1910 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1911 op_info->AddSymbol.Present = 1;
1912 op_info->AddSymbol.Name = name;
1913 return 1;
1914 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001915 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001916 }
1917 if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00001918 if (Offset != 0 || (Size != 4 && Size != 2))
1919 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001920 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1921 // TODO:
1922 // Search the external relocation entries of a fully linked image
1923 // (if any) for an entry that matches this segment offset.
1924 // uint32_t seg_offset = (Pc + Offset);
1925 return 0;
1926 }
1927 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1928 // for an entry for this section offset.
Kevin Enderby930fdc72014-11-06 19:00:13 +00001929 uint32_t sect_addr = info->S.getAddress();
1930 uint32_t sect_offset = (Pc + Offset) - sect_addr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001931 DataRefImpl Rel;
1932 MachO::any_relocation_info RE;
1933 bool isExtern = false;
1934 SymbolRef Symbol;
1935 bool r_scattered = false;
1936 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
David Blaikie33dd45d02015-03-23 18:39:02 +00001937 auto Reloc =
1938 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
1939 [&](const RelocationRef &Reloc) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001940 uint64_t RelocOffset = Reloc.getOffset();
David Blaikie33dd45d02015-03-23 18:39:02 +00001941 return RelocOffset == sect_offset;
1942 });
1943
1944 if (Reloc == info->S.relocations().end())
1945 return 0;
1946
1947 Rel = Reloc->getRawDataRefImpl();
1948 RE = info->O->getRelocation(Rel);
1949 r_length = info->O->getAnyRelocationLength(RE);
1950 r_scattered = info->O->isRelocationScattered(RE);
1951 if (r_scattered) {
1952 r_value = info->O->getScatteredRelocationValue(RE);
1953 r_type = info->O->getScatteredRelocationType(RE);
1954 } else {
1955 r_type = info->O->getAnyRelocationType(RE);
1956 isExtern = info->O->getPlainRelocationExternal(RE);
1957 if (isExtern) {
1958 symbol_iterator RelocSym = Reloc->getSymbol();
1959 Symbol = *RelocSym;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001960 }
1961 }
David Blaikie33dd45d02015-03-23 18:39:02 +00001962 if (r_type == MachO::ARM_RELOC_HALF ||
1963 r_type == MachO::ARM_RELOC_SECTDIFF ||
1964 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1965 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1966 DataRefImpl RelNext = Rel;
1967 info->O->moveRelocationNext(RelNext);
1968 MachO::any_relocation_info RENext;
1969 RENext = info->O->getRelocation(RelNext);
1970 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
1971 if (info->O->isRelocationScattered(RENext))
1972 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1973 }
1974
1975 if (isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001976 Expected<StringRef> SymName = Symbol.getName();
1977 if (!SymName) {
1978 std::string Buf;
1979 raw_string_ostream OS(Buf);
1980 logAllUnhandledErrors(SymName.takeError(), OS, "");
1981 OS.flush();
1982 report_fatal_error(Buf);
1983 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001984 const char *name = SymName->data();
Kevin Enderby930fdc72014-11-06 19:00:13 +00001985 op_info->AddSymbol.Present = 1;
1986 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00001987 switch (r_type) {
1988 case MachO::ARM_RELOC_HALF:
1989 if ((r_length & 0x1) == 1) {
1990 op_info->Value = value << 16 | other_half;
1991 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1992 } else {
1993 op_info->Value = other_half << 16 | value;
1994 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00001995 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00001996 break;
1997 default:
1998 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001999 }
2000 return 1;
2001 }
2002 // If we have a branch that is not an external relocation entry then
2003 // return 0 so the code in tryAddingSymbolicOperand() can use the
2004 // SymbolLookUp call back with the branch target address to look up the
2005 // symbol and possiblity add an annotation for a symbol stub.
David Blaikie33dd45d02015-03-23 18:39:02 +00002006 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2007 r_type == MachO::ARM_THUMB_RELOC_BR22))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002008 return 0;
2009
2010 uint32_t offset = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002011 if (r_type == MachO::ARM_RELOC_HALF ||
2012 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2013 if ((r_length & 0x1) == 1)
2014 value = value << 16 | other_half;
2015 else
2016 value = other_half << 16 | value;
2017 }
2018 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2019 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2020 offset = value - r_value;
2021 value = r_value;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002022 }
2023
David Blaikie33dd45d02015-03-23 18:39:02 +00002024 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002025 if ((r_length & 0x1) == 1)
2026 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2027 else
2028 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002029 const char *add = GuessSymbolName(r_value, info->AddrMap);
2030 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002031 int32_t offset = value - (r_value - pair_r_value);
2032 op_info->AddSymbol.Present = 1;
2033 if (add != nullptr)
2034 op_info->AddSymbol.Name = add;
2035 else
2036 op_info->AddSymbol.Value = r_value;
2037 op_info->SubtractSymbol.Present = 1;
2038 if (sub != nullptr)
2039 op_info->SubtractSymbol.Name = sub;
2040 else
2041 op_info->SubtractSymbol.Value = pair_r_value;
2042 op_info->Value = offset;
2043 return 1;
2044 }
2045
Kevin Enderby930fdc72014-11-06 19:00:13 +00002046 op_info->AddSymbol.Present = 1;
2047 op_info->Value = offset;
David Blaikie33dd45d02015-03-23 18:39:02 +00002048 if (r_type == MachO::ARM_RELOC_HALF) {
2049 if ((r_length & 0x1) == 1)
2050 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2051 else
2052 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002053 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002054 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002055 if (add != nullptr) {
2056 op_info->AddSymbol.Name = add;
2057 return 1;
2058 }
2059 op_info->AddSymbol.Value = value;
2060 return 1;
David Blaikie33dd45d02015-03-23 18:39:02 +00002061 }
2062 if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002063 if (Offset != 0 || Size != 4)
2064 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002065 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2066 // TODO:
2067 // Search the external relocation entries of a fully linked image
2068 // (if any) for an entry that matches this segment offset.
2069 // uint64_t seg_offset = (Pc + Offset);
2070 return 0;
2071 }
2072 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2073 // for an entry for this section offset.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002074 uint64_t sect_addr = info->S.getAddress();
2075 uint64_t sect_offset = (Pc + Offset) - sect_addr;
David Blaikie33dd45d02015-03-23 18:39:02 +00002076 auto Reloc =
2077 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
2078 [&](const RelocationRef &Reloc) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002079 uint64_t RelocOffset = Reloc.getOffset();
David Blaikie33dd45d02015-03-23 18:39:02 +00002080 return RelocOffset == sect_offset;
2081 });
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002082
David Blaikie33dd45d02015-03-23 18:39:02 +00002083 if (Reloc == info->S.relocations().end())
2084 return 0;
2085
2086 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2087 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2088 uint32_t r_type = info->O->getAnyRelocationType(RE);
2089 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2090 DataRefImpl RelNext = Rel;
2091 info->O->moveRelocationNext(RelNext);
2092 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2093 if (value == 0) {
2094 value = info->O->getPlainRelocationSymbolNum(RENext);
2095 op_info->Value = value;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002096 }
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002097 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002098 // NOTE: Scattered relocations don't exist on arm64.
2099 if (!info->O->getPlainRelocationExternal(RE))
2100 return 0;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002101 Expected<StringRef> SymName = Reloc->getSymbol()->getName();
2102 if (!SymName) {
2103 std::string Buf;
2104 raw_string_ostream OS(Buf);
2105 logAllUnhandledErrors(SymName.takeError(), OS, "");
2106 OS.flush();
2107 report_fatal_error(Buf);
2108 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002109 const char *name = SymName->data();
David Blaikie33dd45d02015-03-23 18:39:02 +00002110 op_info->AddSymbol.Present = 1;
2111 op_info->AddSymbol.Name = name;
2112
2113 switch (r_type) {
2114 case MachO::ARM64_RELOC_PAGE21:
2115 /* @page */
2116 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2117 break;
2118 case MachO::ARM64_RELOC_PAGEOFF12:
2119 /* @pageoff */
2120 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2121 break;
2122 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2123 /* @gotpage */
2124 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2125 break;
2126 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2127 /* @gotpageoff */
2128 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2129 break;
2130 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2131 /* @tvlppage is not implemented in llvm-mc */
2132 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2133 break;
2134 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2135 /* @tvlppageoff is not implemented in llvm-mc */
2136 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2137 break;
2138 default:
2139 case MachO::ARM64_RELOC_BRANCH26:
2140 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2141 break;
2142 }
2143 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002144 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002145 return 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002146}
2147
Kevin Enderbybf246f52014-09-24 23:08:22 +00002148// GuessCstringPointer is passed the address of what might be a pointer to a
2149// literal string in a cstring section. If that address is in a cstring section
2150// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002151static const char *GuessCstringPointer(uint64_t ReferenceValue,
2152 struct DisassembleInfo *info) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002153 for (const auto &Load : info->O->load_commands()) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002154 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2155 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2156 for (unsigned J = 0; J < Seg.nsects; ++J) {
2157 MachO::section_64 Sec = info->O->getSection64(Load, J);
2158 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2159 if (section_type == MachO::S_CSTRING_LITERALS &&
2160 ReferenceValue >= Sec.addr &&
2161 ReferenceValue < Sec.addr + Sec.size) {
2162 uint64_t sect_offset = ReferenceValue - Sec.addr;
2163 uint64_t object_offset = Sec.offset + sect_offset;
2164 StringRef MachOContents = info->O->getData();
2165 uint64_t object_size = MachOContents.size();
2166 const char *object_addr = (const char *)MachOContents.data();
2167 if (object_offset < object_size) {
2168 const char *name = object_addr + object_offset;
2169 return name;
2170 } else {
2171 return nullptr;
2172 }
2173 }
2174 }
2175 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2176 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2177 for (unsigned J = 0; J < Seg.nsects; ++J) {
2178 MachO::section Sec = info->O->getSection(Load, J);
2179 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2180 if (section_type == MachO::S_CSTRING_LITERALS &&
2181 ReferenceValue >= Sec.addr &&
2182 ReferenceValue < Sec.addr + Sec.size) {
2183 uint64_t sect_offset = ReferenceValue - Sec.addr;
2184 uint64_t object_offset = Sec.offset + sect_offset;
2185 StringRef MachOContents = info->O->getData();
2186 uint64_t object_size = MachOContents.size();
2187 const char *object_addr = (const char *)MachOContents.data();
2188 if (object_offset < object_size) {
2189 const char *name = object_addr + object_offset;
2190 return name;
2191 } else {
2192 return nullptr;
2193 }
2194 }
2195 }
2196 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002197 }
2198 return nullptr;
2199}
2200
Kevin Enderby85974882014-09-26 22:20:44 +00002201// GuessIndirectSymbol returns the name of the indirect symbol for the
2202// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2203// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2204// symbol name being referenced by the stub or pointer.
2205static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2206 struct DisassembleInfo *info) {
Kevin Enderby85974882014-09-26 22:20:44 +00002207 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2208 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002209 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby85974882014-09-26 22:20:44 +00002210 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2211 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2212 for (unsigned J = 0; J < Seg.nsects; ++J) {
2213 MachO::section_64 Sec = info->O->getSection64(Load, J);
2214 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2215 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2216 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2217 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2218 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2219 section_type == MachO::S_SYMBOL_STUBS) &&
2220 ReferenceValue >= Sec.addr &&
2221 ReferenceValue < Sec.addr + Sec.size) {
2222 uint32_t stride;
2223 if (section_type == MachO::S_SYMBOL_STUBS)
2224 stride = Sec.reserved2;
2225 else
2226 stride = 8;
2227 if (stride == 0)
2228 return nullptr;
2229 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2230 if (index < Dysymtab.nindirectsyms) {
2231 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002232 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002233 if (indirect_symbol < Symtab.nsyms) {
2234 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2235 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002236 Expected<StringRef> SymName = Symbol.getName();
2237 if (!SymName) {
2238 std::string Buf;
2239 raw_string_ostream OS(Buf);
2240 logAllUnhandledErrors(SymName.takeError(), OS, "");
2241 OS.flush();
2242 report_fatal_error(Buf);
2243 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002244 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002245 return name;
2246 }
2247 }
2248 }
2249 }
2250 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2251 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2252 for (unsigned J = 0; J < Seg.nsects; ++J) {
2253 MachO::section Sec = info->O->getSection(Load, J);
2254 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2255 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2256 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2257 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2258 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2259 section_type == MachO::S_SYMBOL_STUBS) &&
2260 ReferenceValue >= Sec.addr &&
2261 ReferenceValue < Sec.addr + Sec.size) {
2262 uint32_t stride;
2263 if (section_type == MachO::S_SYMBOL_STUBS)
2264 stride = Sec.reserved2;
2265 else
2266 stride = 4;
2267 if (stride == 0)
2268 return nullptr;
2269 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2270 if (index < Dysymtab.nindirectsyms) {
2271 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002272 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002273 if (indirect_symbol < Symtab.nsyms) {
2274 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2275 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002276 Expected<StringRef> SymName = Symbol.getName();
2277 if (!SymName) {
2278 std::string Buf;
2279 raw_string_ostream OS(Buf);
2280 logAllUnhandledErrors(SymName.takeError(), OS, "");
2281 OS.flush();
2282 report_fatal_error(Buf);
2283 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002284 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002285 return name;
2286 }
2287 }
2288 }
2289 }
2290 }
Kevin Enderby85974882014-09-26 22:20:44 +00002291 }
2292 return nullptr;
2293}
2294
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002295// method_reference() is called passing it the ReferenceName that might be
2296// a reference it to an Objective-C method call. If so then it allocates and
2297// assembles a method call string with the values last seen and saved in
2298// the DisassembleInfo's class_name and selector_name fields. This is saved
2299// into the method field of the info and any previous string is free'ed.
2300// Then the class_name field in the info is set to nullptr. The method call
2301// string is set into ReferenceName and ReferenceType is set to
2302// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2303// then both ReferenceType and ReferenceName are left unchanged.
2304static void method_reference(struct DisassembleInfo *info,
2305 uint64_t *ReferenceType,
2306 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002307 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002308 if (*ReferenceName != nullptr) {
2309 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002310 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002311 if (info->method != nullptr)
2312 free(info->method);
2313 if (info->class_name != nullptr) {
2314 info->method = (char *)malloc(5 + strlen(info->class_name) +
2315 strlen(info->selector_name));
2316 if (info->method != nullptr) {
2317 strcpy(info->method, "+[");
2318 strcat(info->method, info->class_name);
2319 strcat(info->method, " ");
2320 strcat(info->method, info->selector_name);
2321 strcat(info->method, "]");
2322 *ReferenceName = info->method;
2323 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2324 }
2325 } else {
2326 info->method = (char *)malloc(9 + strlen(info->selector_name));
2327 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002328 if (Arch == Triple::x86_64)
2329 strcpy(info->method, "-[%rdi ");
2330 else if (Arch == Triple::aarch64)
2331 strcpy(info->method, "-[x0 ");
2332 else
2333 strcpy(info->method, "-[r? ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002334 strcat(info->method, info->selector_name);
2335 strcat(info->method, "]");
2336 *ReferenceName = info->method;
2337 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2338 }
2339 }
2340 info->class_name = nullptr;
2341 }
2342 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002343 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002344 if (info->method != nullptr)
2345 free(info->method);
2346 info->method = (char *)malloc(17 + strlen(info->selector_name));
2347 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002348 if (Arch == Triple::x86_64)
2349 strcpy(info->method, "-[[%rdi super] ");
2350 else if (Arch == Triple::aarch64)
2351 strcpy(info->method, "-[[x0 super] ");
2352 else
2353 strcpy(info->method, "-[[r? super] ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002354 strcat(info->method, info->selector_name);
2355 strcat(info->method, "]");
2356 *ReferenceName = info->method;
2357 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2358 }
2359 info->class_name = nullptr;
2360 }
2361 }
2362 }
2363}
2364
2365// GuessPointerPointer() is passed the address of what might be a pointer to
2366// a reference to an Objective-C class, selector, message ref or cfstring.
2367// If so the value of the pointer is returned and one of the booleans are set
2368// to true. If not zero is returned and all the booleans are set to false.
2369static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2370 struct DisassembleInfo *info,
2371 bool &classref, bool &selref, bool &msgref,
2372 bool &cfstring) {
2373 classref = false;
2374 selref = false;
2375 msgref = false;
2376 cfstring = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002377 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002378 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2379 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2380 for (unsigned J = 0; J < Seg.nsects; ++J) {
2381 MachO::section_64 Sec = info->O->getSection64(Load, J);
2382 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2383 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2384 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2385 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2386 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2387 ReferenceValue >= Sec.addr &&
2388 ReferenceValue < Sec.addr + Sec.size) {
2389 uint64_t sect_offset = ReferenceValue - Sec.addr;
2390 uint64_t object_offset = Sec.offset + sect_offset;
2391 StringRef MachOContents = info->O->getData();
2392 uint64_t object_size = MachOContents.size();
2393 const char *object_addr = (const char *)MachOContents.data();
2394 if (object_offset < object_size) {
2395 uint64_t pointer_value;
2396 memcpy(&pointer_value, object_addr + object_offset,
2397 sizeof(uint64_t));
2398 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2399 sys::swapByteOrder(pointer_value);
2400 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2401 selref = true;
2402 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2403 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2404 classref = true;
2405 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2406 ReferenceValue + 8 < Sec.addr + Sec.size) {
2407 msgref = true;
2408 memcpy(&pointer_value, object_addr + object_offset + 8,
2409 sizeof(uint64_t));
2410 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2411 sys::swapByteOrder(pointer_value);
2412 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2413 cfstring = true;
2414 return pointer_value;
2415 } else {
2416 return 0;
2417 }
2418 }
2419 }
2420 }
2421 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002422 }
2423 return 0;
2424}
2425
2426// get_pointer_64 returns a pointer to the bytes in the object file at the
2427// Address from a section in the Mach-O file. And indirectly returns the
2428// offset into the section, number of bytes left in the section past the offset
2429// and which section is was being referenced. If the Address is not in a
2430// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002431static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2432 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002433 DisassembleInfo *info,
2434 bool objc_only = false) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002435 offset = 0;
2436 left = 0;
2437 S = SectionRef();
2438 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2439 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2440 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
Kevin Enderby46e642f2015-10-08 22:50:55 +00002441 if (SectSize == 0)
2442 continue;
Kevin Enderby846c0002015-04-16 17:19:59 +00002443 if (objc_only) {
2444 StringRef SectName;
2445 ((*(info->Sections))[SectIdx]).getName(SectName);
2446 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2447 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2448 if (SegName != "__OBJC" && SectName != "__cstring")
2449 continue;
2450 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002451 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2452 S = (*(info->Sections))[SectIdx];
2453 offset = Address - SectAddress;
2454 left = SectSize - offset;
2455 StringRef SectContents;
2456 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2457 return SectContents.data() + offset;
2458 }
2459 }
2460 return nullptr;
2461}
2462
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002463static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2464 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002465 DisassembleInfo *info,
2466 bool objc_only = false) {
2467 return get_pointer_64(Address, offset, left, S, info, objc_only);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002468}
2469
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002470// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2471// the symbol indirectly through n_value. Based on the relocation information
2472// for the specified section offset in the specified section reference.
Kevin Enderby0fc11822015-04-01 20:57:01 +00002473// If no relocation information is found and a non-zero ReferenceValue for the
2474// symbol is passed, look up that address in the info's AddrMap.
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00002475static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2476 DisassembleInfo *info, uint64_t &n_value,
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002477 uint64_t ReferenceValue = 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002478 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002479 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002480 return nullptr;
2481
2482 // See if there is an external relocation entry at the sect_offset.
2483 bool reloc_found = false;
2484 DataRefImpl Rel;
2485 MachO::any_relocation_info RE;
2486 bool isExtern = false;
2487 SymbolRef Symbol;
2488 for (const RelocationRef &Reloc : S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002489 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002490 if (RelocOffset == sect_offset) {
2491 Rel = Reloc.getRawDataRefImpl();
2492 RE = info->O->getRelocation(Rel);
2493 if (info->O->isRelocationScattered(RE))
2494 continue;
2495 isExtern = info->O->getPlainRelocationExternal(RE);
2496 if (isExtern) {
2497 symbol_iterator RelocSym = Reloc.getSymbol();
2498 Symbol = *RelocSym;
2499 }
2500 reloc_found = true;
2501 break;
2502 }
2503 }
2504 // If there is an external relocation entry for a symbol in this section
2505 // at this section_offset then use that symbol's value for the n_value
2506 // and return its name.
2507 const char *SymbolName = nullptr;
2508 if (reloc_found && isExtern) {
Rafael Espindoladea00162015-07-03 17:44:18 +00002509 n_value = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002510 Expected<StringRef> NameOrError = Symbol.getName();
2511 if (!NameOrError) {
2512 std::string Buf;
2513 raw_string_ostream OS(Buf);
2514 logAllUnhandledErrors(NameOrError.takeError(), OS, "");
2515 OS.flush();
2516 report_fatal_error(Buf);
2517 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002518 StringRef Name = *NameOrError;
2519 if (!Name.empty()) {
2520 SymbolName = Name.data();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002521 return SymbolName;
2522 }
2523 }
2524
2525 // TODO: For fully linked images, look through the external relocation
2526 // entries off the dynamic symtab command. For these the r_offset is from the
2527 // start of the first writeable segment in the Mach-O file. So the offset
2528 // to this section from that segment is passed to this routine by the caller,
2529 // as the database_offset. Which is the difference of the section's starting
2530 // address and the first writable segment.
2531 //
2532 // NOTE: need add passing the database_offset to this routine.
2533
Kevin Enderby0fc11822015-04-01 20:57:01 +00002534 // We did not find an external relocation entry so look up the ReferenceValue
2535 // as an address of a symbol and if found return that symbol's name.
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002536 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002537
2538 return SymbolName;
2539}
2540
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002541static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
2542 DisassembleInfo *info,
2543 uint32_t ReferenceValue) {
2544 uint64_t n_value64;
2545 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
2546}
2547
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002548// These are structs in the Objective-C meta data and read to produce the
2549// comments for disassembly. While these are part of the ABI they are no
2550// public defintions. So the are here not in include/llvm/Support/MachO.h .
2551
2552// The cfstring object in a 64-bit Mach-O file.
2553struct cfstring64_t {
2554 uint64_t isa; // class64_t * (64-bit pointer)
2555 uint64_t flags; // flag bits
2556 uint64_t characters; // char * (64-bit pointer)
2557 uint64_t length; // number of non-NULL characters in above
2558};
2559
2560// The class object in a 64-bit Mach-O file.
2561struct class64_t {
2562 uint64_t isa; // class64_t * (64-bit pointer)
2563 uint64_t superclass; // class64_t * (64-bit pointer)
2564 uint64_t cache; // Cache (64-bit pointer)
2565 uint64_t vtable; // IMP * (64-bit pointer)
2566 uint64_t data; // class_ro64_t * (64-bit pointer)
2567};
2568
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002569struct class32_t {
2570 uint32_t isa; /* class32_t * (32-bit pointer) */
2571 uint32_t superclass; /* class32_t * (32-bit pointer) */
2572 uint32_t cache; /* Cache (32-bit pointer) */
2573 uint32_t vtable; /* IMP * (32-bit pointer) */
2574 uint32_t data; /* class_ro32_t * (32-bit pointer) */
2575};
2576
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002577struct class_ro64_t {
2578 uint32_t flags;
2579 uint32_t instanceStart;
2580 uint32_t instanceSize;
2581 uint32_t reserved;
2582 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2583 uint64_t name; // const char * (64-bit pointer)
2584 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2585 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2586 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2587 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2588 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2589};
2590
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002591struct class_ro32_t {
2592 uint32_t flags;
2593 uint32_t instanceStart;
2594 uint32_t instanceSize;
2595 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
2596 uint32_t name; /* const char * (32-bit pointer) */
2597 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
2598 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
2599 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
2600 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
2601 uint32_t baseProperties; /* const struct objc_property_list *
2602 (32-bit pointer) */
2603};
2604
2605/* Values for class_ro{64,32}_t->flags */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002606#define RO_META (1 << 0)
2607#define RO_ROOT (1 << 1)
2608#define RO_HAS_CXX_STRUCTORS (1 << 2)
2609
2610struct method_list64_t {
2611 uint32_t entsize;
2612 uint32_t count;
2613 /* struct method64_t first; These structures follow inline */
2614};
2615
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002616struct method_list32_t {
2617 uint32_t entsize;
2618 uint32_t count;
2619 /* struct method32_t first; These structures follow inline */
2620};
2621
Kevin Enderby0fc11822015-04-01 20:57:01 +00002622struct method64_t {
2623 uint64_t name; /* SEL (64-bit pointer) */
2624 uint64_t types; /* const char * (64-bit pointer) */
2625 uint64_t imp; /* IMP (64-bit pointer) */
2626};
2627
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002628struct method32_t {
2629 uint32_t name; /* SEL (32-bit pointer) */
2630 uint32_t types; /* const char * (32-bit pointer) */
2631 uint32_t imp; /* IMP (32-bit pointer) */
2632};
2633
Kevin Enderby0fc11822015-04-01 20:57:01 +00002634struct protocol_list64_t {
2635 uint64_t count; /* uintptr_t (a 64-bit value) */
2636 /* struct protocol64_t * list[0]; These pointers follow inline */
2637};
2638
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002639struct protocol_list32_t {
2640 uint32_t count; /* uintptr_t (a 32-bit value) */
2641 /* struct protocol32_t * list[0]; These pointers follow inline */
2642};
2643
Kevin Enderby0fc11822015-04-01 20:57:01 +00002644struct protocol64_t {
2645 uint64_t isa; /* id * (64-bit pointer) */
2646 uint64_t name; /* const char * (64-bit pointer) */
2647 uint64_t protocols; /* struct protocol_list64_t *
2648 (64-bit pointer) */
2649 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
2650 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
2651 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
2652 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
2653 uint64_t instanceProperties; /* struct objc_property_list *
2654 (64-bit pointer) */
2655};
2656
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002657struct protocol32_t {
2658 uint32_t isa; /* id * (32-bit pointer) */
2659 uint32_t name; /* const char * (32-bit pointer) */
2660 uint32_t protocols; /* struct protocol_list_t *
2661 (32-bit pointer) */
2662 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
2663 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
2664 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
2665 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
2666 uint32_t instanceProperties; /* struct objc_property_list *
2667 (32-bit pointer) */
2668};
2669
Kevin Enderby0fc11822015-04-01 20:57:01 +00002670struct ivar_list64_t {
2671 uint32_t entsize;
2672 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002673 /* struct ivar64_t first; These structures follow inline */
2674};
2675
2676struct ivar_list32_t {
2677 uint32_t entsize;
2678 uint32_t count;
2679 /* struct ivar32_t first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002680};
2681
2682struct ivar64_t {
2683 uint64_t offset; /* uintptr_t * (64-bit pointer) */
2684 uint64_t name; /* const char * (64-bit pointer) */
2685 uint64_t type; /* const char * (64-bit pointer) */
2686 uint32_t alignment;
2687 uint32_t size;
2688};
2689
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002690struct ivar32_t {
2691 uint32_t offset; /* uintptr_t * (32-bit pointer) */
2692 uint32_t name; /* const char * (32-bit pointer) */
2693 uint32_t type; /* const char * (32-bit pointer) */
2694 uint32_t alignment;
2695 uint32_t size;
2696};
2697
Kevin Enderby0fc11822015-04-01 20:57:01 +00002698struct objc_property_list64 {
2699 uint32_t entsize;
2700 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002701 /* struct objc_property64 first; These structures follow inline */
2702};
2703
2704struct objc_property_list32 {
2705 uint32_t entsize;
2706 uint32_t count;
2707 /* struct objc_property32 first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002708};
2709
2710struct objc_property64 {
2711 uint64_t name; /* const char * (64-bit pointer) */
2712 uint64_t attributes; /* const char * (64-bit pointer) */
2713};
2714
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002715struct objc_property32 {
2716 uint32_t name; /* const char * (32-bit pointer) */
2717 uint32_t attributes; /* const char * (32-bit pointer) */
2718};
2719
Kevin Enderby0fc11822015-04-01 20:57:01 +00002720struct category64_t {
2721 uint64_t name; /* const char * (64-bit pointer) */
2722 uint64_t cls; /* struct class_t * (64-bit pointer) */
2723 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
2724 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
2725 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
2726 uint64_t instanceProperties; /* struct objc_property_list *
2727 (64-bit pointer) */
2728};
2729
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002730struct category32_t {
2731 uint32_t name; /* const char * (32-bit pointer) */
2732 uint32_t cls; /* struct class_t * (32-bit pointer) */
2733 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
2734 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
2735 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
2736 uint32_t instanceProperties; /* struct objc_property_list *
2737 (32-bit pointer) */
2738};
2739
Kevin Enderby0fc11822015-04-01 20:57:01 +00002740struct objc_image_info64 {
2741 uint32_t version;
2742 uint32_t flags;
2743};
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002744struct objc_image_info32 {
2745 uint32_t version;
2746 uint32_t flags;
2747};
Kevin Enderby846c0002015-04-16 17:19:59 +00002748struct imageInfo_t {
2749 uint32_t version;
2750 uint32_t flags;
2751};
Kevin Enderby0fc11822015-04-01 20:57:01 +00002752/* masks for objc_image_info.flags */
2753#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
2754#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
2755
2756struct message_ref64 {
2757 uint64_t imp; /* IMP (64-bit pointer) */
2758 uint64_t sel; /* SEL (64-bit pointer) */
2759};
2760
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002761struct message_ref32 {
2762 uint32_t imp; /* IMP (32-bit pointer) */
2763 uint32_t sel; /* SEL (32-bit pointer) */
2764};
2765
Kevin Enderby846c0002015-04-16 17:19:59 +00002766// Objective-C 1 (32-bit only) meta data structs.
2767
2768struct objc_module_t {
2769 uint32_t version;
2770 uint32_t size;
2771 uint32_t name; /* char * (32-bit pointer) */
2772 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
2773};
2774
2775struct objc_symtab_t {
2776 uint32_t sel_ref_cnt;
2777 uint32_t refs; /* SEL * (32-bit pointer) */
2778 uint16_t cls_def_cnt;
2779 uint16_t cat_def_cnt;
2780 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
2781};
2782
2783struct objc_class_t {
2784 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2785 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
2786 uint32_t name; /* const char * (32-bit pointer) */
2787 int32_t version;
2788 int32_t info;
2789 int32_t instance_size;
2790 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
2791 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
2792 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
2793 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
2794};
2795
2796#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
2797// class is not a metaclass
2798#define CLS_CLASS 0x1
2799// class is a metaclass
2800#define CLS_META 0x2
2801
2802struct objc_category_t {
2803 uint32_t category_name; /* char * (32-bit pointer) */
2804 uint32_t class_name; /* char * (32-bit pointer) */
2805 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
2806 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
2807 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
2808};
2809
2810struct objc_ivar_t {
2811 uint32_t ivar_name; /* char * (32-bit pointer) */
2812 uint32_t ivar_type; /* char * (32-bit pointer) */
2813 int32_t ivar_offset;
2814};
2815
2816struct objc_ivar_list_t {
2817 int32_t ivar_count;
2818 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
2819};
2820
2821struct objc_method_list_t {
2822 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
2823 int32_t method_count;
2824 // struct objc_method_t method_list[1]; /* variable length structure */
2825};
2826
2827struct objc_method_t {
2828 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2829 uint32_t method_types; /* char * (32-bit pointer) */
2830 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
2831 (32-bit pointer) */
2832};
2833
2834struct objc_protocol_list_t {
2835 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
2836 int32_t count;
2837 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
2838 // (32-bit pointer) */
2839};
2840
2841struct objc_protocol_t {
2842 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2843 uint32_t protocol_name; /* char * (32-bit pointer) */
2844 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
2845 uint32_t instance_methods; /* struct objc_method_description_list *
2846 (32-bit pointer) */
2847 uint32_t class_methods; /* struct objc_method_description_list *
2848 (32-bit pointer) */
2849};
2850
2851struct objc_method_description_list_t {
2852 int32_t count;
2853 // struct objc_method_description_t list[1];
2854};
2855
2856struct objc_method_description_t {
2857 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2858 uint32_t types; /* char * (32-bit pointer) */
2859};
2860
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002861inline void swapStruct(struct cfstring64_t &cfs) {
2862 sys::swapByteOrder(cfs.isa);
2863 sys::swapByteOrder(cfs.flags);
2864 sys::swapByteOrder(cfs.characters);
2865 sys::swapByteOrder(cfs.length);
2866}
2867
2868inline void swapStruct(struct class64_t &c) {
2869 sys::swapByteOrder(c.isa);
2870 sys::swapByteOrder(c.superclass);
2871 sys::swapByteOrder(c.cache);
2872 sys::swapByteOrder(c.vtable);
2873 sys::swapByteOrder(c.data);
2874}
2875
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002876inline void swapStruct(struct class32_t &c) {
2877 sys::swapByteOrder(c.isa);
2878 sys::swapByteOrder(c.superclass);
2879 sys::swapByteOrder(c.cache);
2880 sys::swapByteOrder(c.vtable);
2881 sys::swapByteOrder(c.data);
2882}
2883
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002884inline void swapStruct(struct class_ro64_t &cro) {
2885 sys::swapByteOrder(cro.flags);
2886 sys::swapByteOrder(cro.instanceStart);
2887 sys::swapByteOrder(cro.instanceSize);
2888 sys::swapByteOrder(cro.reserved);
2889 sys::swapByteOrder(cro.ivarLayout);
2890 sys::swapByteOrder(cro.name);
2891 sys::swapByteOrder(cro.baseMethods);
2892 sys::swapByteOrder(cro.baseProtocols);
2893 sys::swapByteOrder(cro.ivars);
2894 sys::swapByteOrder(cro.weakIvarLayout);
2895 sys::swapByteOrder(cro.baseProperties);
2896}
2897
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002898inline void swapStruct(struct class_ro32_t &cro) {
2899 sys::swapByteOrder(cro.flags);
2900 sys::swapByteOrder(cro.instanceStart);
2901 sys::swapByteOrder(cro.instanceSize);
2902 sys::swapByteOrder(cro.ivarLayout);
2903 sys::swapByteOrder(cro.name);
2904 sys::swapByteOrder(cro.baseMethods);
2905 sys::swapByteOrder(cro.baseProtocols);
2906 sys::swapByteOrder(cro.ivars);
2907 sys::swapByteOrder(cro.weakIvarLayout);
2908 sys::swapByteOrder(cro.baseProperties);
2909}
2910
Kevin Enderby0fc11822015-04-01 20:57:01 +00002911inline void swapStruct(struct method_list64_t &ml) {
2912 sys::swapByteOrder(ml.entsize);
2913 sys::swapByteOrder(ml.count);
2914}
2915
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002916inline void swapStruct(struct method_list32_t &ml) {
2917 sys::swapByteOrder(ml.entsize);
2918 sys::swapByteOrder(ml.count);
2919}
2920
Kevin Enderby0fc11822015-04-01 20:57:01 +00002921inline void swapStruct(struct method64_t &m) {
2922 sys::swapByteOrder(m.name);
2923 sys::swapByteOrder(m.types);
2924 sys::swapByteOrder(m.imp);
2925}
2926
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002927inline void swapStruct(struct method32_t &m) {
2928 sys::swapByteOrder(m.name);
2929 sys::swapByteOrder(m.types);
2930 sys::swapByteOrder(m.imp);
2931}
2932
Kevin Enderby0fc11822015-04-01 20:57:01 +00002933inline void swapStruct(struct protocol_list64_t &pl) {
2934 sys::swapByteOrder(pl.count);
2935}
2936
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002937inline void swapStruct(struct protocol_list32_t &pl) {
2938 sys::swapByteOrder(pl.count);
2939}
2940
Kevin Enderby0fc11822015-04-01 20:57:01 +00002941inline void swapStruct(struct protocol64_t &p) {
2942 sys::swapByteOrder(p.isa);
2943 sys::swapByteOrder(p.name);
2944 sys::swapByteOrder(p.protocols);
2945 sys::swapByteOrder(p.instanceMethods);
2946 sys::swapByteOrder(p.classMethods);
2947 sys::swapByteOrder(p.optionalInstanceMethods);
2948 sys::swapByteOrder(p.optionalClassMethods);
2949 sys::swapByteOrder(p.instanceProperties);
2950}
2951
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002952inline void swapStruct(struct protocol32_t &p) {
2953 sys::swapByteOrder(p.isa);
2954 sys::swapByteOrder(p.name);
2955 sys::swapByteOrder(p.protocols);
2956 sys::swapByteOrder(p.instanceMethods);
2957 sys::swapByteOrder(p.classMethods);
2958 sys::swapByteOrder(p.optionalInstanceMethods);
2959 sys::swapByteOrder(p.optionalClassMethods);
2960 sys::swapByteOrder(p.instanceProperties);
2961}
2962
Kevin Enderby0fc11822015-04-01 20:57:01 +00002963inline void swapStruct(struct ivar_list64_t &il) {
2964 sys::swapByteOrder(il.entsize);
2965 sys::swapByteOrder(il.count);
2966}
2967
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002968inline void swapStruct(struct ivar_list32_t &il) {
2969 sys::swapByteOrder(il.entsize);
2970 sys::swapByteOrder(il.count);
2971}
2972
Kevin Enderby0fc11822015-04-01 20:57:01 +00002973inline void swapStruct(struct ivar64_t &i) {
2974 sys::swapByteOrder(i.offset);
2975 sys::swapByteOrder(i.name);
2976 sys::swapByteOrder(i.type);
2977 sys::swapByteOrder(i.alignment);
2978 sys::swapByteOrder(i.size);
2979}
2980
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002981inline void swapStruct(struct ivar32_t &i) {
2982 sys::swapByteOrder(i.offset);
2983 sys::swapByteOrder(i.name);
2984 sys::swapByteOrder(i.type);
2985 sys::swapByteOrder(i.alignment);
2986 sys::swapByteOrder(i.size);
2987}
2988
Kevin Enderby0fc11822015-04-01 20:57:01 +00002989inline void swapStruct(struct objc_property_list64 &pl) {
2990 sys::swapByteOrder(pl.entsize);
2991 sys::swapByteOrder(pl.count);
2992}
2993
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002994inline void swapStruct(struct objc_property_list32 &pl) {
2995 sys::swapByteOrder(pl.entsize);
2996 sys::swapByteOrder(pl.count);
2997}
2998
Kevin Enderby0fc11822015-04-01 20:57:01 +00002999inline void swapStruct(struct objc_property64 &op) {
3000 sys::swapByteOrder(op.name);
3001 sys::swapByteOrder(op.attributes);
3002}
3003
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003004inline void swapStruct(struct objc_property32 &op) {
3005 sys::swapByteOrder(op.name);
3006 sys::swapByteOrder(op.attributes);
3007}
3008
Kevin Enderby0fc11822015-04-01 20:57:01 +00003009inline void swapStruct(struct category64_t &c) {
3010 sys::swapByteOrder(c.name);
3011 sys::swapByteOrder(c.cls);
3012 sys::swapByteOrder(c.instanceMethods);
3013 sys::swapByteOrder(c.classMethods);
3014 sys::swapByteOrder(c.protocols);
3015 sys::swapByteOrder(c.instanceProperties);
3016}
3017
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003018inline void swapStruct(struct category32_t &c) {
3019 sys::swapByteOrder(c.name);
3020 sys::swapByteOrder(c.cls);
3021 sys::swapByteOrder(c.instanceMethods);
3022 sys::swapByteOrder(c.classMethods);
3023 sys::swapByteOrder(c.protocols);
3024 sys::swapByteOrder(c.instanceProperties);
3025}
3026
Kevin Enderby0fc11822015-04-01 20:57:01 +00003027inline void swapStruct(struct objc_image_info64 &o) {
3028 sys::swapByteOrder(o.version);
3029 sys::swapByteOrder(o.flags);
3030}
3031
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003032inline void swapStruct(struct objc_image_info32 &o) {
3033 sys::swapByteOrder(o.version);
3034 sys::swapByteOrder(o.flags);
3035}
3036
Kevin Enderby846c0002015-04-16 17:19:59 +00003037inline void swapStruct(struct imageInfo_t &o) {
3038 sys::swapByteOrder(o.version);
3039 sys::swapByteOrder(o.flags);
3040}
3041
Kevin Enderby0fc11822015-04-01 20:57:01 +00003042inline void swapStruct(struct message_ref64 &mr) {
3043 sys::swapByteOrder(mr.imp);
3044 sys::swapByteOrder(mr.sel);
3045}
3046
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003047inline void swapStruct(struct message_ref32 &mr) {
3048 sys::swapByteOrder(mr.imp);
3049 sys::swapByteOrder(mr.sel);
3050}
3051
Kevin Enderby846c0002015-04-16 17:19:59 +00003052inline void swapStruct(struct objc_module_t &module) {
3053 sys::swapByteOrder(module.version);
3054 sys::swapByteOrder(module.size);
3055 sys::swapByteOrder(module.name);
3056 sys::swapByteOrder(module.symtab);
Jingyue Wufedecc42015-04-16 18:43:44 +00003057}
Kevin Enderby846c0002015-04-16 17:19:59 +00003058
3059inline void swapStruct(struct objc_symtab_t &symtab) {
3060 sys::swapByteOrder(symtab.sel_ref_cnt);
3061 sys::swapByteOrder(symtab.refs);
3062 sys::swapByteOrder(symtab.cls_def_cnt);
3063 sys::swapByteOrder(symtab.cat_def_cnt);
Jingyue Wufedecc42015-04-16 18:43:44 +00003064}
Kevin Enderby846c0002015-04-16 17:19:59 +00003065
3066inline void swapStruct(struct objc_class_t &objc_class) {
3067 sys::swapByteOrder(objc_class.isa);
3068 sys::swapByteOrder(objc_class.super_class);
3069 sys::swapByteOrder(objc_class.name);
3070 sys::swapByteOrder(objc_class.version);
3071 sys::swapByteOrder(objc_class.info);
3072 sys::swapByteOrder(objc_class.instance_size);
3073 sys::swapByteOrder(objc_class.ivars);
3074 sys::swapByteOrder(objc_class.methodLists);
3075 sys::swapByteOrder(objc_class.cache);
3076 sys::swapByteOrder(objc_class.protocols);
Jingyue Wufedecc42015-04-16 18:43:44 +00003077}
Kevin Enderby846c0002015-04-16 17:19:59 +00003078
3079inline void swapStruct(struct objc_category_t &objc_category) {
3080 sys::swapByteOrder(objc_category.category_name);
3081 sys::swapByteOrder(objc_category.class_name);
3082 sys::swapByteOrder(objc_category.instance_methods);
3083 sys::swapByteOrder(objc_category.class_methods);
3084 sys::swapByteOrder(objc_category.protocols);
3085}
3086
3087inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3088 sys::swapByteOrder(objc_ivar_list.ivar_count);
3089}
3090
3091inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3092 sys::swapByteOrder(objc_ivar.ivar_name);
3093 sys::swapByteOrder(objc_ivar.ivar_type);
3094 sys::swapByteOrder(objc_ivar.ivar_offset);
Jingyue Wufedecc42015-04-16 18:43:44 +00003095}
Kevin Enderby846c0002015-04-16 17:19:59 +00003096
3097inline void swapStruct(struct objc_method_list_t &method_list) {
3098 sys::swapByteOrder(method_list.obsolete);
3099 sys::swapByteOrder(method_list.method_count);
3100}
3101
3102inline void swapStruct(struct objc_method_t &method) {
3103 sys::swapByteOrder(method.method_name);
3104 sys::swapByteOrder(method.method_types);
3105 sys::swapByteOrder(method.method_imp);
3106}
3107
3108inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3109 sys::swapByteOrder(protocol_list.next);
3110 sys::swapByteOrder(protocol_list.count);
3111}
3112
3113inline void swapStruct(struct objc_protocol_t &protocol) {
3114 sys::swapByteOrder(protocol.isa);
3115 sys::swapByteOrder(protocol.protocol_name);
3116 sys::swapByteOrder(protocol.protocol_list);
3117 sys::swapByteOrder(protocol.instance_methods);
3118 sys::swapByteOrder(protocol.class_methods);
3119}
3120
3121inline void swapStruct(struct objc_method_description_list_t &mdl) {
3122 sys::swapByteOrder(mdl.count);
3123}
3124
3125inline void swapStruct(struct objc_method_description_t &md) {
3126 sys::swapByteOrder(md.name);
3127 sys::swapByteOrder(md.types);
3128}
3129
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003130static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3131 struct DisassembleInfo *info);
3132
3133// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3134// to an Objective-C class and returns the class name. It is also passed the
3135// address of the pointer, so when the pointer is zero as it can be in an .o
3136// file, that is used to look for an external relocation entry with a symbol
3137// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003138static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3139 uint64_t ReferenceValue,
3140 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003141 const char *r;
3142 uint32_t offset, left;
3143 SectionRef S;
3144
3145 // The pointer_value can be 0 in an object file and have a relocation
3146 // entry for the class symbol at the ReferenceValue (the address of the
3147 // pointer).
3148 if (pointer_value == 0) {
3149 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3150 if (r == nullptr || left < sizeof(uint64_t))
3151 return nullptr;
3152 uint64_t n_value;
3153 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3154 if (symbol_name == nullptr)
3155 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00003156 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003157 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3158 return class_name + 2;
3159 else
3160 return nullptr;
3161 }
3162
3163 // The case were the pointer_value is non-zero and points to a class defined
3164 // in this Mach-O file.
3165 r = get_pointer_64(pointer_value, offset, left, S, info);
3166 if (r == nullptr || left < sizeof(struct class64_t))
3167 return nullptr;
3168 struct class64_t c;
3169 memcpy(&c, r, sizeof(struct class64_t));
3170 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3171 swapStruct(c);
3172 if (c.data == 0)
3173 return nullptr;
3174 r = get_pointer_64(c.data, offset, left, S, info);
3175 if (r == nullptr || left < sizeof(struct class_ro64_t))
3176 return nullptr;
3177 struct class_ro64_t cro;
3178 memcpy(&cro, r, sizeof(struct class_ro64_t));
3179 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3180 swapStruct(cro);
3181 if (cro.name == 0)
3182 return nullptr;
3183 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3184 return name;
3185}
3186
3187// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3188// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003189static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3190 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003191 const char *r, *name;
3192 uint32_t offset, left;
3193 SectionRef S;
3194 struct cfstring64_t cfs;
3195 uint64_t cfs_characters;
3196
3197 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3198 if (r == nullptr || left < sizeof(struct cfstring64_t))
3199 return nullptr;
3200 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3201 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3202 swapStruct(cfs);
3203 if (cfs.characters == 0) {
3204 uint64_t n_value;
3205 const char *symbol_name = get_symbol_64(
3206 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3207 if (symbol_name == nullptr)
3208 return nullptr;
3209 cfs_characters = n_value;
3210 } else
3211 cfs_characters = cfs.characters;
3212 name = get_pointer_64(cfs_characters, offset, left, S, info);
3213
3214 return name;
3215}
3216
3217// get_objc2_64bit_selref() is used for disassembly and is passed a the address
3218// of a pointer to an Objective-C selector reference when the pointer value is
3219// zero as in a .o file and is likely to have a external relocation entry with
3220// who's symbol's n_value is the real pointer to the selector name. If that is
3221// the case the real pointer to the selector name is returned else 0 is
3222// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003223static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3224 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003225 uint32_t offset, left;
3226 SectionRef S;
3227
3228 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3229 if (r == nullptr || left < sizeof(uint64_t))
3230 return 0;
3231 uint64_t n_value;
3232 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3233 if (symbol_name == nullptr)
3234 return 0;
3235 return n_value;
3236}
3237
Kevin Enderby0fc11822015-04-01 20:57:01 +00003238static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3239 const char *sectname) {
3240 for (const SectionRef &Section : O->sections()) {
3241 StringRef SectName;
3242 Section.getName(SectName);
3243 DataRefImpl Ref = Section.getRawDataRefImpl();
3244 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3245 if (SegName == segname && SectName == sectname)
3246 return Section;
3247 }
3248 return SectionRef();
3249}
3250
3251static void
3252walk_pointer_list_64(const char *listname, const SectionRef S,
3253 MachOObjectFile *O, struct DisassembleInfo *info,
3254 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3255 if (S == SectionRef())
3256 return;
3257
3258 StringRef SectName;
3259 S.getName(SectName);
3260 DataRefImpl Ref = S.getRawDataRefImpl();
3261 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3262 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3263
3264 StringRef BytesStr;
3265 S.getContents(BytesStr);
3266 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3267
3268 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3269 uint32_t left = S.getSize() - i;
3270 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3271 uint64_t p = 0;
3272 memcpy(&p, Contents + i, size);
3273 if (i + sizeof(uint64_t) > S.getSize())
3274 outs() << listname << " list pointer extends past end of (" << SegName
3275 << "," << SectName << ") section\n";
3276 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3277
3278 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3279 sys::swapByteOrder(p);
3280
3281 uint64_t n_value = 0;
3282 const char *name = get_symbol_64(i, S, info, n_value, p);
3283 if (name == nullptr)
3284 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3285
3286 if (n_value != 0) {
3287 outs() << format("0x%" PRIx64, n_value);
3288 if (p != 0)
3289 outs() << " + " << format("0x%" PRIx64, p);
3290 } else
3291 outs() << format("0x%" PRIx64, p);
3292 if (name != nullptr)
3293 outs() << " " << name;
3294 outs() << "\n";
3295
3296 p += n_value;
3297 if (func)
3298 func(p, info);
3299 }
3300}
3301
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003302static void
3303walk_pointer_list_32(const char *listname, const SectionRef S,
3304 MachOObjectFile *O, struct DisassembleInfo *info,
3305 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3306 if (S == SectionRef())
3307 return;
3308
3309 StringRef SectName;
3310 S.getName(SectName);
3311 DataRefImpl Ref = S.getRawDataRefImpl();
3312 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3313 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3314
3315 StringRef BytesStr;
3316 S.getContents(BytesStr);
3317 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3318
3319 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3320 uint32_t left = S.getSize() - i;
3321 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3322 uint32_t p = 0;
3323 memcpy(&p, Contents + i, size);
3324 if (i + sizeof(uint32_t) > S.getSize())
3325 outs() << listname << " list pointer extends past end of (" << SegName
3326 << "," << SectName << ") section\n";
Kevin Enderbycf261312015-04-06 22:33:43 +00003327 uint32_t Address = S.getAddress() + i;
3328 outs() << format("%08" PRIx32, Address) << " ";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003329
3330 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3331 sys::swapByteOrder(p);
3332 outs() << format("0x%" PRIx32, p);
3333
3334 const char *name = get_symbol_32(i, S, info, p);
3335 if (name != nullptr)
3336 outs() << " " << name;
3337 outs() << "\n";
3338
3339 if (func)
3340 func(p, info);
3341 }
3342}
3343
3344static void print_layout_map(const char *layout_map, uint32_t left) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003345 if (layout_map == nullptr)
3346 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003347 outs() << " layout map: ";
3348 do {
3349 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3350 left--;
3351 layout_map++;
3352 } while (*layout_map != '\0' && left != 0);
3353 outs() << "\n";
3354}
3355
Kevin Enderby0fc11822015-04-01 20:57:01 +00003356static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3357 uint32_t offset, left;
3358 SectionRef S;
3359 const char *layout_map;
3360
3361 if (p == 0)
3362 return;
3363 layout_map = get_pointer_64(p, offset, left, S, info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003364 print_layout_map(layout_map, left);
3365}
3366
3367static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3368 uint32_t offset, left;
3369 SectionRef S;
3370 const char *layout_map;
3371
3372 if (p == 0)
3373 return;
3374 layout_map = get_pointer_32(p, offset, left, S, info);
3375 print_layout_map(layout_map, left);
Kevin Enderby0fc11822015-04-01 20:57:01 +00003376}
3377
3378static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3379 const char *indent) {
3380 struct method_list64_t ml;
3381 struct method64_t m;
3382 const char *r;
3383 uint32_t offset, xoffset, left, i;
3384 SectionRef S, xS;
3385 const char *name, *sym_name;
3386 uint64_t n_value;
3387
3388 r = get_pointer_64(p, offset, left, S, info);
3389 if (r == nullptr)
3390 return;
3391 memset(&ml, '\0', sizeof(struct method_list64_t));
3392 if (left < sizeof(struct method_list64_t)) {
3393 memcpy(&ml, r, left);
3394 outs() << " (method_list_t entends past the end of the section)\n";
3395 } else
3396 memcpy(&ml, r, sizeof(struct method_list64_t));
3397 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3398 swapStruct(ml);
3399 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3400 outs() << indent << "\t\t count " << ml.count << "\n";
3401
3402 p += sizeof(struct method_list64_t);
3403 offset += sizeof(struct method_list64_t);
3404 for (i = 0; i < ml.count; i++) {
3405 r = get_pointer_64(p, offset, left, S, info);
3406 if (r == nullptr)
3407 return;
3408 memset(&m, '\0', sizeof(struct method64_t));
3409 if (left < sizeof(struct method64_t)) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003410 memcpy(&m, r, left);
3411 outs() << indent << " (method_t extends past the end of the section)\n";
Kevin Enderby0fc11822015-04-01 20:57:01 +00003412 } else
3413 memcpy(&m, r, sizeof(struct method64_t));
3414 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3415 swapStruct(m);
3416
3417 outs() << indent << "\t\t name ";
3418 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3419 info, n_value, m.name);
3420 if (n_value != 0) {
3421 if (info->verbose && sym_name != nullptr)
3422 outs() << sym_name;
3423 else
3424 outs() << format("0x%" PRIx64, n_value);
3425 if (m.name != 0)
3426 outs() << " + " << format("0x%" PRIx64, m.name);
3427 } else
3428 outs() << format("0x%" PRIx64, m.name);
3429 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3430 if (name != nullptr)
3431 outs() << format(" %.*s", left, name);
3432 outs() << "\n";
3433
3434 outs() << indent << "\t\t types ";
3435 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3436 info, n_value, m.types);
3437 if (n_value != 0) {
3438 if (info->verbose && sym_name != nullptr)
3439 outs() << sym_name;
3440 else
3441 outs() << format("0x%" PRIx64, n_value);
3442 if (m.types != 0)
3443 outs() << " + " << format("0x%" PRIx64, m.types);
3444 } else
3445 outs() << format("0x%" PRIx64, m.types);
3446 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3447 if (name != nullptr)
3448 outs() << format(" %.*s", left, name);
3449 outs() << "\n";
3450
3451 outs() << indent << "\t\t imp ";
3452 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3453 n_value, m.imp);
3454 if (info->verbose && name == nullptr) {
3455 if (n_value != 0) {
3456 outs() << format("0x%" PRIx64, n_value) << " ";
3457 if (m.imp != 0)
3458 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3459 } else
3460 outs() << format("0x%" PRIx64, m.imp) << " ";
3461 }
3462 if (name != nullptr)
3463 outs() << name;
3464 outs() << "\n";
3465
3466 p += sizeof(struct method64_t);
3467 offset += sizeof(struct method64_t);
3468 }
3469}
3470
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003471static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3472 const char *indent) {
3473 struct method_list32_t ml;
3474 struct method32_t m;
Kevin Enderby846c0002015-04-16 17:19:59 +00003475 const char *r, *name;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003476 uint32_t offset, xoffset, left, i;
3477 SectionRef S, xS;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003478
3479 r = get_pointer_32(p, offset, left, S, info);
3480 if (r == nullptr)
3481 return;
3482 memset(&ml, '\0', sizeof(struct method_list32_t));
3483 if (left < sizeof(struct method_list32_t)) {
3484 memcpy(&ml, r, left);
3485 outs() << " (method_list_t entends past the end of the section)\n";
3486 } else
3487 memcpy(&ml, r, sizeof(struct method_list32_t));
3488 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3489 swapStruct(ml);
3490 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3491 outs() << indent << "\t\t count " << ml.count << "\n";
3492
3493 p += sizeof(struct method_list32_t);
3494 offset += sizeof(struct method_list32_t);
3495 for (i = 0; i < ml.count; i++) {
3496 r = get_pointer_32(p, offset, left, S, info);
3497 if (r == nullptr)
3498 return;
3499 memset(&m, '\0', sizeof(struct method32_t));
3500 if (left < sizeof(struct method32_t)) {
3501 memcpy(&ml, r, left);
3502 outs() << indent << " (method_t entends past the end of the section)\n";
3503 } else
3504 memcpy(&m, r, sizeof(struct method32_t));
3505 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3506 swapStruct(m);
3507
3508 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
3509 name = get_pointer_32(m.name, xoffset, left, xS, info);
3510 if (name != nullptr)
3511 outs() << format(" %.*s", left, name);
3512 outs() << "\n";
3513
3514 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
3515 name = get_pointer_32(m.types, xoffset, left, xS, info);
3516 if (name != nullptr)
3517 outs() << format(" %.*s", left, name);
3518 outs() << "\n";
3519
3520 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
3521 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
3522 m.imp);
3523 if (name != nullptr)
3524 outs() << " " << name;
3525 outs() << "\n";
3526
3527 p += sizeof(struct method32_t);
3528 offset += sizeof(struct method32_t);
3529 }
3530}
3531
Kevin Enderby846c0002015-04-16 17:19:59 +00003532static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
3533 uint32_t offset, left, xleft;
3534 SectionRef S;
3535 struct objc_method_list_t method_list;
3536 struct objc_method_t method;
3537 const char *r, *methods, *name, *SymbolName;
3538 int32_t i;
3539
3540 r = get_pointer_32(p, offset, left, S, info, true);
3541 if (r == nullptr)
3542 return true;
3543
3544 outs() << "\n";
3545 if (left > sizeof(struct objc_method_list_t)) {
3546 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
3547 } else {
3548 outs() << "\t\t objc_method_list extends past end of the section\n";
3549 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
3550 memcpy(&method_list, r, left);
3551 }
3552 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3553 swapStruct(method_list);
3554
3555 outs() << "\t\t obsolete "
3556 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
3557 outs() << "\t\t method_count " << method_list.method_count << "\n";
3558
3559 methods = r + sizeof(struct objc_method_list_t);
3560 for (i = 0; i < method_list.method_count; i++) {
3561 if ((i + 1) * sizeof(struct objc_method_t) > left) {
3562 outs() << "\t\t remaining method's extend past the of the section\n";
3563 break;
3564 }
3565 memcpy(&method, methods + i * sizeof(struct objc_method_t),
3566 sizeof(struct objc_method_t));
3567 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3568 swapStruct(method);
3569
3570 outs() << "\t\t method_name "
3571 << format("0x%08" PRIx32, method.method_name);
3572 if (info->verbose) {
3573 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
3574 if (name != nullptr)
3575 outs() << format(" %.*s", xleft, name);
3576 else
3577 outs() << " (not in an __OBJC section)";
3578 }
3579 outs() << "\n";
3580
3581 outs() << "\t\t method_types "
3582 << format("0x%08" PRIx32, method.method_types);
3583 if (info->verbose) {
3584 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
3585 if (name != nullptr)
3586 outs() << format(" %.*s", xleft, name);
3587 else
3588 outs() << " (not in an __OBJC section)";
3589 }
3590 outs() << "\n";
3591
3592 outs() << "\t\t method_imp "
3593 << format("0x%08" PRIx32, method.method_imp) << " ";
3594 if (info->verbose) {
3595 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
3596 if (SymbolName != nullptr)
3597 outs() << SymbolName;
3598 }
3599 outs() << "\n";
3600 }
3601 return false;
3602}
3603
Kevin Enderby0fc11822015-04-01 20:57:01 +00003604static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
3605 struct protocol_list64_t pl;
3606 uint64_t q, n_value;
3607 struct protocol64_t pc;
3608 const char *r;
3609 uint32_t offset, xoffset, left, i;
3610 SectionRef S, xS;
3611 const char *name, *sym_name;
3612
3613 r = get_pointer_64(p, offset, left, S, info);
3614 if (r == nullptr)
3615 return;
3616 memset(&pl, '\0', sizeof(struct protocol_list64_t));
3617 if (left < sizeof(struct protocol_list64_t)) {
3618 memcpy(&pl, r, left);
3619 outs() << " (protocol_list_t entends past the end of the section)\n";
3620 } else
3621 memcpy(&pl, r, sizeof(struct protocol_list64_t));
3622 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3623 swapStruct(pl);
3624 outs() << " count " << pl.count << "\n";
3625
3626 p += sizeof(struct protocol_list64_t);
3627 offset += sizeof(struct protocol_list64_t);
3628 for (i = 0; i < pl.count; i++) {
3629 r = get_pointer_64(p, offset, left, S, info);
3630 if (r == nullptr)
3631 return;
3632 q = 0;
3633 if (left < sizeof(uint64_t)) {
3634 memcpy(&q, r, left);
3635 outs() << " (protocol_t * entends past the end of the section)\n";
3636 } else
3637 memcpy(&q, r, sizeof(uint64_t));
3638 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3639 sys::swapByteOrder(q);
3640
3641 outs() << "\t\t list[" << i << "] ";
3642 sym_name = get_symbol_64(offset, S, info, n_value, q);
3643 if (n_value != 0) {
3644 if (info->verbose && sym_name != nullptr)
3645 outs() << sym_name;
3646 else
3647 outs() << format("0x%" PRIx64, n_value);
3648 if (q != 0)
3649 outs() << " + " << format("0x%" PRIx64, q);
3650 } else
3651 outs() << format("0x%" PRIx64, q);
3652 outs() << " (struct protocol_t *)\n";
3653
3654 r = get_pointer_64(q + n_value, offset, left, S, info);
3655 if (r == nullptr)
3656 return;
3657 memset(&pc, '\0', sizeof(struct protocol64_t));
3658 if (left < sizeof(struct protocol64_t)) {
3659 memcpy(&pc, r, left);
3660 outs() << " (protocol_t entends past the end of the section)\n";
3661 } else
3662 memcpy(&pc, r, sizeof(struct protocol64_t));
3663 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3664 swapStruct(pc);
3665
3666 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
3667
3668 outs() << "\t\t\t name ";
3669 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
3670 info, n_value, pc.name);
3671 if (n_value != 0) {
3672 if (info->verbose && sym_name != nullptr)
3673 outs() << sym_name;
3674 else
3675 outs() << format("0x%" PRIx64, n_value);
3676 if (pc.name != 0)
3677 outs() << " + " << format("0x%" PRIx64, pc.name);
3678 } else
3679 outs() << format("0x%" PRIx64, pc.name);
3680 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
3681 if (name != nullptr)
3682 outs() << format(" %.*s", left, name);
3683 outs() << "\n";
3684
3685 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
3686
3687 outs() << "\t\t instanceMethods ";
3688 sym_name =
3689 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
3690 S, info, n_value, pc.instanceMethods);
3691 if (n_value != 0) {
3692 if (info->verbose && sym_name != nullptr)
3693 outs() << sym_name;
3694 else
3695 outs() << format("0x%" PRIx64, n_value);
3696 if (pc.instanceMethods != 0)
3697 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
3698 } else
3699 outs() << format("0x%" PRIx64, pc.instanceMethods);
3700 outs() << " (struct method_list_t *)\n";
3701 if (pc.instanceMethods + n_value != 0)
3702 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
3703
3704 outs() << "\t\t classMethods ";
3705 sym_name =
3706 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
3707 info, n_value, pc.classMethods);
3708 if (n_value != 0) {
3709 if (info->verbose && sym_name != nullptr)
3710 outs() << sym_name;
3711 else
3712 outs() << format("0x%" PRIx64, n_value);
3713 if (pc.classMethods != 0)
3714 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
3715 } else
3716 outs() << format("0x%" PRIx64, pc.classMethods);
3717 outs() << " (struct method_list_t *)\n";
3718 if (pc.classMethods + n_value != 0)
3719 print_method_list64_t(pc.classMethods + n_value, info, "\t");
3720
3721 outs() << "\t optionalInstanceMethods "
3722 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
3723 outs() << "\t optionalClassMethods "
3724 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
3725 outs() << "\t instanceProperties "
3726 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
3727
3728 p += sizeof(uint64_t);
3729 offset += sizeof(uint64_t);
3730 }
3731}
3732
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003733static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
3734 struct protocol_list32_t pl;
3735 uint32_t q;
3736 struct protocol32_t pc;
3737 const char *r;
3738 uint32_t offset, xoffset, left, i;
3739 SectionRef S, xS;
3740 const char *name;
3741
3742 r = get_pointer_32(p, offset, left, S, info);
3743 if (r == nullptr)
3744 return;
3745 memset(&pl, '\0', sizeof(struct protocol_list32_t));
3746 if (left < sizeof(struct protocol_list32_t)) {
3747 memcpy(&pl, r, left);
3748 outs() << " (protocol_list_t entends past the end of the section)\n";
3749 } else
3750 memcpy(&pl, r, sizeof(struct protocol_list32_t));
3751 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3752 swapStruct(pl);
3753 outs() << " count " << pl.count << "\n";
3754
3755 p += sizeof(struct protocol_list32_t);
3756 offset += sizeof(struct protocol_list32_t);
3757 for (i = 0; i < pl.count; i++) {
3758 r = get_pointer_32(p, offset, left, S, info);
3759 if (r == nullptr)
3760 return;
3761 q = 0;
3762 if (left < sizeof(uint32_t)) {
3763 memcpy(&q, r, left);
3764 outs() << " (protocol_t * entends past the end of the section)\n";
3765 } else
3766 memcpy(&q, r, sizeof(uint32_t));
3767 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3768 sys::swapByteOrder(q);
3769 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
3770 << " (struct protocol_t *)\n";
3771 r = get_pointer_32(q, offset, left, S, info);
3772 if (r == nullptr)
3773 return;
3774 memset(&pc, '\0', sizeof(struct protocol32_t));
3775 if (left < sizeof(struct protocol32_t)) {
3776 memcpy(&pc, r, left);
3777 outs() << " (protocol_t entends past the end of the section)\n";
3778 } else
3779 memcpy(&pc, r, sizeof(struct protocol32_t));
3780 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3781 swapStruct(pc);
3782 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
3783 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
3784 name = get_pointer_32(pc.name, xoffset, left, xS, info);
3785 if (name != nullptr)
3786 outs() << format(" %.*s", left, name);
3787 outs() << "\n";
3788 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
3789 outs() << "\t\t instanceMethods "
3790 << format("0x%" PRIx32, pc.instanceMethods)
3791 << " (struct method_list_t *)\n";
3792 if (pc.instanceMethods != 0)
3793 print_method_list32_t(pc.instanceMethods, info, "\t");
3794 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
3795 << " (struct method_list_t *)\n";
3796 if (pc.classMethods != 0)
3797 print_method_list32_t(pc.classMethods, info, "\t");
3798 outs() << "\t optionalInstanceMethods "
3799 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
3800 outs() << "\t optionalClassMethods "
3801 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
3802 outs() << "\t instanceProperties "
3803 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
3804 p += sizeof(uint32_t);
3805 offset += sizeof(uint32_t);
3806 }
3807}
3808
Kevin Enderby846c0002015-04-16 17:19:59 +00003809static void print_indent(uint32_t indent) {
3810 for (uint32_t i = 0; i < indent;) {
3811 if (indent - i >= 8) {
3812 outs() << "\t";
3813 i += 8;
3814 } else {
3815 for (uint32_t j = i; j < indent; j++)
3816 outs() << " ";
3817 return;
3818 }
3819 }
3820}
3821
3822static bool print_method_description_list(uint32_t p, uint32_t indent,
3823 struct DisassembleInfo *info) {
3824 uint32_t offset, left, xleft;
3825 SectionRef S;
3826 struct objc_method_description_list_t mdl;
3827 struct objc_method_description_t md;
3828 const char *r, *list, *name;
3829 int32_t i;
3830
3831 r = get_pointer_32(p, offset, left, S, info, true);
3832 if (r == nullptr)
3833 return true;
3834
3835 outs() << "\n";
3836 if (left > sizeof(struct objc_method_description_list_t)) {
3837 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
3838 } else {
3839 print_indent(indent);
3840 outs() << " objc_method_description_list extends past end of the section\n";
3841 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
3842 memcpy(&mdl, r, left);
3843 }
3844 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3845 swapStruct(mdl);
3846
3847 print_indent(indent);
3848 outs() << " count " << mdl.count << "\n";
3849
3850 list = r + sizeof(struct objc_method_description_list_t);
3851 for (i = 0; i < mdl.count; i++) {
3852 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
3853 print_indent(indent);
3854 outs() << " remaining list entries extend past the of the section\n";
3855 break;
3856 }
3857 print_indent(indent);
3858 outs() << " list[" << i << "]\n";
3859 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
3860 sizeof(struct objc_method_description_t));
3861 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3862 swapStruct(md);
3863
3864 print_indent(indent);
3865 outs() << " name " << format("0x%08" PRIx32, md.name);
3866 if (info->verbose) {
3867 name = get_pointer_32(md.name, offset, xleft, S, info, true);
3868 if (name != nullptr)
3869 outs() << format(" %.*s", xleft, name);
3870 else
3871 outs() << " (not in an __OBJC section)";
3872 }
3873 outs() << "\n";
3874
3875 print_indent(indent);
3876 outs() << " types " << format("0x%08" PRIx32, md.types);
3877 if (info->verbose) {
3878 name = get_pointer_32(md.types, offset, xleft, S, info, true);
3879 if (name != nullptr)
3880 outs() << format(" %.*s", xleft, name);
3881 else
3882 outs() << " (not in an __OBJC section)";
3883 }
3884 outs() << "\n";
3885 }
3886 return false;
3887}
3888
3889static bool print_protocol_list(uint32_t p, uint32_t indent,
3890 struct DisassembleInfo *info);
3891
3892static bool print_protocol(uint32_t p, uint32_t indent,
3893 struct DisassembleInfo *info) {
3894 uint32_t offset, left;
3895 SectionRef S;
3896 struct objc_protocol_t protocol;
3897 const char *r, *name;
3898
3899 r = get_pointer_32(p, offset, left, S, info, true);
3900 if (r == nullptr)
3901 return true;
3902
3903 outs() << "\n";
3904 if (left >= sizeof(struct objc_protocol_t)) {
3905 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
3906 } else {
3907 print_indent(indent);
3908 outs() << " Protocol extends past end of the section\n";
3909 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
3910 memcpy(&protocol, r, left);
3911 }
3912 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3913 swapStruct(protocol);
3914
3915 print_indent(indent);
3916 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
3917 << "\n";
3918
3919 print_indent(indent);
3920 outs() << " protocol_name "
3921 << format("0x%08" PRIx32, protocol.protocol_name);
3922 if (info->verbose) {
3923 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
3924 if (name != nullptr)
3925 outs() << format(" %.*s", left, name);
3926 else
3927 outs() << " (not in an __OBJC section)";
3928 }
3929 outs() << "\n";
3930
3931 print_indent(indent);
3932 outs() << " protocol_list "
3933 << format("0x%08" PRIx32, protocol.protocol_list);
3934 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
3935 outs() << " (not in an __OBJC section)\n";
3936
3937 print_indent(indent);
3938 outs() << " instance_methods "
3939 << format("0x%08" PRIx32, protocol.instance_methods);
3940 if (print_method_description_list(protocol.instance_methods, indent, info))
3941 outs() << " (not in an __OBJC section)\n";
3942
3943 print_indent(indent);
3944 outs() << " class_methods "
3945 << format("0x%08" PRIx32, protocol.class_methods);
3946 if (print_method_description_list(protocol.class_methods, indent, info))
3947 outs() << " (not in an __OBJC section)\n";
3948
3949 return false;
3950}
3951
3952static bool print_protocol_list(uint32_t p, uint32_t indent,
3953 struct DisassembleInfo *info) {
3954 uint32_t offset, left, l;
3955 SectionRef S;
3956 struct objc_protocol_list_t protocol_list;
3957 const char *r, *list;
3958 int32_t i;
3959
3960 r = get_pointer_32(p, offset, left, S, info, true);
3961 if (r == nullptr)
3962 return true;
3963
3964 outs() << "\n";
3965 if (left > sizeof(struct objc_protocol_list_t)) {
3966 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
3967 } else {
3968 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
3969 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
3970 memcpy(&protocol_list, r, left);
3971 }
3972 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3973 swapStruct(protocol_list);
3974
3975 print_indent(indent);
3976 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
3977 << "\n";
3978 print_indent(indent);
3979 outs() << " count " << protocol_list.count << "\n";
3980
3981 list = r + sizeof(struct objc_protocol_list_t);
3982 for (i = 0; i < protocol_list.count; i++) {
3983 if ((i + 1) * sizeof(uint32_t) > left) {
3984 outs() << "\t\t remaining list entries extend past the of the section\n";
3985 break;
3986 }
3987 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
3988 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3989 sys::swapByteOrder(l);
3990
3991 print_indent(indent);
3992 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
3993 if (print_protocol(l, indent, info))
3994 outs() << "(not in an __OBJC section)\n";
3995 }
3996 return false;
3997}
3998
Kevin Enderby0fc11822015-04-01 20:57:01 +00003999static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4000 struct ivar_list64_t il;
4001 struct ivar64_t i;
4002 const char *r;
4003 uint32_t offset, xoffset, left, j;
4004 SectionRef S, xS;
4005 const char *name, *sym_name, *ivar_offset_p;
4006 uint64_t ivar_offset, n_value;
4007
4008 r = get_pointer_64(p, offset, left, S, info);
4009 if (r == nullptr)
4010 return;
4011 memset(&il, '\0', sizeof(struct ivar_list64_t));
4012 if (left < sizeof(struct ivar_list64_t)) {
4013 memcpy(&il, r, left);
4014 outs() << " (ivar_list_t entends past the end of the section)\n";
4015 } else
4016 memcpy(&il, r, sizeof(struct ivar_list64_t));
4017 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4018 swapStruct(il);
4019 outs() << " entsize " << il.entsize << "\n";
4020 outs() << " count " << il.count << "\n";
4021
4022 p += sizeof(struct ivar_list64_t);
4023 offset += sizeof(struct ivar_list64_t);
4024 for (j = 0; j < il.count; j++) {
4025 r = get_pointer_64(p, offset, left, S, info);
4026 if (r == nullptr)
4027 return;
4028 memset(&i, '\0', sizeof(struct ivar64_t));
4029 if (left < sizeof(struct ivar64_t)) {
4030 memcpy(&i, r, left);
4031 outs() << " (ivar_t entends past the end of the section)\n";
4032 } else
4033 memcpy(&i, r, sizeof(struct ivar64_t));
4034 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4035 swapStruct(i);
4036
4037 outs() << "\t\t\t offset ";
4038 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4039 info, n_value, i.offset);
4040 if (n_value != 0) {
4041 if (info->verbose && sym_name != nullptr)
4042 outs() << sym_name;
4043 else
4044 outs() << format("0x%" PRIx64, n_value);
4045 if (i.offset != 0)
4046 outs() << " + " << format("0x%" PRIx64, i.offset);
4047 } else
4048 outs() << format("0x%" PRIx64, i.offset);
4049 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4050 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4051 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4052 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4053 sys::swapByteOrder(ivar_offset);
4054 outs() << " " << ivar_offset << "\n";
4055 } else
4056 outs() << "\n";
4057
4058 outs() << "\t\t\t name ";
4059 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4060 n_value, i.name);
4061 if (n_value != 0) {
4062 if (info->verbose && sym_name != nullptr)
4063 outs() << sym_name;
4064 else
4065 outs() << format("0x%" PRIx64, n_value);
4066 if (i.name != 0)
4067 outs() << " + " << format("0x%" PRIx64, i.name);
4068 } else
4069 outs() << format("0x%" PRIx64, i.name);
4070 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4071 if (name != nullptr)
4072 outs() << format(" %.*s", left, name);
4073 outs() << "\n";
4074
4075 outs() << "\t\t\t type ";
4076 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4077 n_value, i.name);
4078 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4079 if (n_value != 0) {
4080 if (info->verbose && sym_name != nullptr)
4081 outs() << sym_name;
4082 else
4083 outs() << format("0x%" PRIx64, n_value);
4084 if (i.type != 0)
4085 outs() << " + " << format("0x%" PRIx64, i.type);
4086 } else
4087 outs() << format("0x%" PRIx64, i.type);
4088 if (name != nullptr)
4089 outs() << format(" %.*s", left, name);
4090 outs() << "\n";
4091
4092 outs() << "\t\t\talignment " << i.alignment << "\n";
4093 outs() << "\t\t\t size " << i.size << "\n";
4094
4095 p += sizeof(struct ivar64_t);
4096 offset += sizeof(struct ivar64_t);
4097 }
4098}
4099
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004100static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4101 struct ivar_list32_t il;
4102 struct ivar32_t i;
4103 const char *r;
4104 uint32_t offset, xoffset, left, j;
4105 SectionRef S, xS;
4106 const char *name, *ivar_offset_p;
4107 uint32_t ivar_offset;
4108
4109 r = get_pointer_32(p, offset, left, S, info);
4110 if (r == nullptr)
4111 return;
4112 memset(&il, '\0', sizeof(struct ivar_list32_t));
4113 if (left < sizeof(struct ivar_list32_t)) {
4114 memcpy(&il, r, left);
4115 outs() << " (ivar_list_t entends past the end of the section)\n";
4116 } else
4117 memcpy(&il, r, sizeof(struct ivar_list32_t));
4118 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4119 swapStruct(il);
4120 outs() << " entsize " << il.entsize << "\n";
4121 outs() << " count " << il.count << "\n";
4122
4123 p += sizeof(struct ivar_list32_t);
4124 offset += sizeof(struct ivar_list32_t);
4125 for (j = 0; j < il.count; j++) {
4126 r = get_pointer_32(p, offset, left, S, info);
4127 if (r == nullptr)
4128 return;
4129 memset(&i, '\0', sizeof(struct ivar32_t));
4130 if (left < sizeof(struct ivar32_t)) {
4131 memcpy(&i, r, left);
4132 outs() << " (ivar_t entends past the end of the section)\n";
4133 } else
4134 memcpy(&i, r, sizeof(struct ivar32_t));
4135 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4136 swapStruct(i);
4137
4138 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4139 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4140 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4141 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4142 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4143 sys::swapByteOrder(ivar_offset);
4144 outs() << " " << ivar_offset << "\n";
4145 } else
4146 outs() << "\n";
4147
4148 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4149 name = get_pointer_32(i.name, xoffset, left, xS, info);
4150 if (name != nullptr)
4151 outs() << format(" %.*s", left, name);
4152 outs() << "\n";
4153
4154 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4155 name = get_pointer_32(i.type, xoffset, left, xS, info);
4156 if (name != nullptr)
4157 outs() << format(" %.*s", left, name);
4158 outs() << "\n";
4159
4160 outs() << "\t\t\talignment " << i.alignment << "\n";
4161 outs() << "\t\t\t size " << i.size << "\n";
4162
4163 p += sizeof(struct ivar32_t);
4164 offset += sizeof(struct ivar32_t);
4165 }
4166}
4167
Kevin Enderby0fc11822015-04-01 20:57:01 +00004168static void print_objc_property_list64(uint64_t p,
4169 struct DisassembleInfo *info) {
4170 struct objc_property_list64 opl;
4171 struct objc_property64 op;
4172 const char *r;
4173 uint32_t offset, xoffset, left, j;
4174 SectionRef S, xS;
4175 const char *name, *sym_name;
4176 uint64_t n_value;
4177
4178 r = get_pointer_64(p, offset, left, S, info);
4179 if (r == nullptr)
4180 return;
4181 memset(&opl, '\0', sizeof(struct objc_property_list64));
4182 if (left < sizeof(struct objc_property_list64)) {
4183 memcpy(&opl, r, left);
4184 outs() << " (objc_property_list entends past the end of the section)\n";
4185 } else
4186 memcpy(&opl, r, sizeof(struct objc_property_list64));
4187 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4188 swapStruct(opl);
4189 outs() << " entsize " << opl.entsize << "\n";
4190 outs() << " count " << opl.count << "\n";
4191
4192 p += sizeof(struct objc_property_list64);
4193 offset += sizeof(struct objc_property_list64);
4194 for (j = 0; j < opl.count; j++) {
4195 r = get_pointer_64(p, offset, left, S, info);
4196 if (r == nullptr)
4197 return;
4198 memset(&op, '\0', sizeof(struct objc_property64));
4199 if (left < sizeof(struct objc_property64)) {
4200 memcpy(&op, r, left);
4201 outs() << " (objc_property entends past the end of the section)\n";
4202 } else
4203 memcpy(&op, r, sizeof(struct objc_property64));
4204 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4205 swapStruct(op);
4206
4207 outs() << "\t\t\t name ";
4208 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4209 info, n_value, op.name);
4210 if (n_value != 0) {
4211 if (info->verbose && sym_name != nullptr)
4212 outs() << sym_name;
4213 else
4214 outs() << format("0x%" PRIx64, n_value);
4215 if (op.name != 0)
4216 outs() << " + " << format("0x%" PRIx64, op.name);
4217 } else
4218 outs() << format("0x%" PRIx64, op.name);
4219 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4220 if (name != nullptr)
4221 outs() << format(" %.*s", left, name);
4222 outs() << "\n";
4223
4224 outs() << "\t\t\tattributes ";
4225 sym_name =
4226 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4227 info, n_value, op.attributes);
4228 if (n_value != 0) {
4229 if (info->verbose && sym_name != nullptr)
4230 outs() << sym_name;
4231 else
4232 outs() << format("0x%" PRIx64, n_value);
4233 if (op.attributes != 0)
4234 outs() << " + " << format("0x%" PRIx64, op.attributes);
4235 } else
4236 outs() << format("0x%" PRIx64, op.attributes);
4237 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4238 if (name != nullptr)
4239 outs() << format(" %.*s", left, name);
4240 outs() << "\n";
4241
4242 p += sizeof(struct objc_property64);
4243 offset += sizeof(struct objc_property64);
4244 }
4245}
4246
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004247static void print_objc_property_list32(uint32_t p,
4248 struct DisassembleInfo *info) {
4249 struct objc_property_list32 opl;
4250 struct objc_property32 op;
4251 const char *r;
4252 uint32_t offset, xoffset, left, j;
4253 SectionRef S, xS;
4254 const char *name;
4255
4256 r = get_pointer_32(p, offset, left, S, info);
4257 if (r == nullptr)
4258 return;
4259 memset(&opl, '\0', sizeof(struct objc_property_list32));
4260 if (left < sizeof(struct objc_property_list32)) {
4261 memcpy(&opl, r, left);
4262 outs() << " (objc_property_list entends past the end of the section)\n";
4263 } else
4264 memcpy(&opl, r, sizeof(struct objc_property_list32));
4265 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4266 swapStruct(opl);
4267 outs() << " entsize " << opl.entsize << "\n";
4268 outs() << " count " << opl.count << "\n";
4269
4270 p += sizeof(struct objc_property_list32);
4271 offset += sizeof(struct objc_property_list32);
4272 for (j = 0; j < opl.count; j++) {
4273 r = get_pointer_32(p, offset, left, S, info);
4274 if (r == nullptr)
4275 return;
4276 memset(&op, '\0', sizeof(struct objc_property32));
4277 if (left < sizeof(struct objc_property32)) {
4278 memcpy(&op, r, left);
4279 outs() << " (objc_property entends past the end of the section)\n";
4280 } else
4281 memcpy(&op, r, sizeof(struct objc_property32));
4282 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4283 swapStruct(op);
4284
4285 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4286 name = get_pointer_32(op.name, xoffset, left, xS, info);
4287 if (name != nullptr)
4288 outs() << format(" %.*s", left, name);
4289 outs() << "\n";
4290
4291 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4292 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4293 if (name != nullptr)
4294 outs() << format(" %.*s", left, name);
4295 outs() << "\n";
4296
4297 p += sizeof(struct objc_property32);
4298 offset += sizeof(struct objc_property32);
4299 }
4300}
4301
Richard Smith81ff44d2015-10-09 22:09:56 +00004302static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
Kevin Enderby0fc11822015-04-01 20:57:01 +00004303 bool &is_meta_class) {
4304 struct class_ro64_t cro;
4305 const char *r;
4306 uint32_t offset, xoffset, left;
4307 SectionRef S, xS;
4308 const char *name, *sym_name;
4309 uint64_t n_value;
4310
4311 r = get_pointer_64(p, offset, left, S, info);
4312 if (r == nullptr || left < sizeof(struct class_ro64_t))
Richard Smith81ff44d2015-10-09 22:09:56 +00004313 return false;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004314 memset(&cro, '\0', sizeof(struct class_ro64_t));
4315 if (left < sizeof(struct class_ro64_t)) {
4316 memcpy(&cro, r, left);
4317 outs() << " (class_ro_t entends past the end of the section)\n";
4318 } else
4319 memcpy(&cro, r, sizeof(struct class_ro64_t));
4320 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4321 swapStruct(cro);
4322 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4323 if (cro.flags & RO_META)
4324 outs() << " RO_META";
4325 if (cro.flags & RO_ROOT)
4326 outs() << " RO_ROOT";
4327 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4328 outs() << " RO_HAS_CXX_STRUCTORS";
4329 outs() << "\n";
4330 outs() << " instanceStart " << cro.instanceStart << "\n";
4331 outs() << " instanceSize " << cro.instanceSize << "\n";
4332 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4333 << "\n";
4334 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4335 << "\n";
4336 print_layout_map64(cro.ivarLayout, info);
4337
4338 outs() << " name ";
4339 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4340 info, n_value, cro.name);
4341 if (n_value != 0) {
4342 if (info->verbose && sym_name != nullptr)
4343 outs() << sym_name;
4344 else
4345 outs() << format("0x%" PRIx64, n_value);
4346 if (cro.name != 0)
4347 outs() << " + " << format("0x%" PRIx64, cro.name);
4348 } else
4349 outs() << format("0x%" PRIx64, cro.name);
4350 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4351 if (name != nullptr)
4352 outs() << format(" %.*s", left, name);
4353 outs() << "\n";
4354
4355 outs() << " baseMethods ";
4356 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4357 S, info, n_value, cro.baseMethods);
4358 if (n_value != 0) {
4359 if (info->verbose && sym_name != nullptr)
4360 outs() << sym_name;
4361 else
4362 outs() << format("0x%" PRIx64, n_value);
4363 if (cro.baseMethods != 0)
4364 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4365 } else
4366 outs() << format("0x%" PRIx64, cro.baseMethods);
4367 outs() << " (struct method_list_t *)\n";
4368 if (cro.baseMethods + n_value != 0)
4369 print_method_list64_t(cro.baseMethods + n_value, info, "");
4370
4371 outs() << " baseProtocols ";
4372 sym_name =
4373 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4374 info, n_value, cro.baseProtocols);
4375 if (n_value != 0) {
4376 if (info->verbose && sym_name != nullptr)
4377 outs() << sym_name;
4378 else
4379 outs() << format("0x%" PRIx64, n_value);
4380 if (cro.baseProtocols != 0)
4381 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4382 } else
4383 outs() << format("0x%" PRIx64, cro.baseProtocols);
4384 outs() << "\n";
4385 if (cro.baseProtocols + n_value != 0)
4386 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4387
4388 outs() << " ivars ";
4389 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004390 info, n_value, cro.ivars);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004391 if (n_value != 0) {
4392 if (info->verbose && sym_name != nullptr)
4393 outs() << sym_name;
4394 else
4395 outs() << format("0x%" PRIx64, n_value);
4396 if (cro.ivars != 0)
4397 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4398 } else
4399 outs() << format("0x%" PRIx64, cro.ivars);
4400 outs() << "\n";
4401 if (cro.ivars + n_value != 0)
4402 print_ivar_list64_t(cro.ivars + n_value, info);
4403
4404 outs() << " weakIvarLayout ";
4405 sym_name =
4406 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4407 info, n_value, cro.weakIvarLayout);
4408 if (n_value != 0) {
4409 if (info->verbose && sym_name != nullptr)
4410 outs() << sym_name;
4411 else
4412 outs() << format("0x%" PRIx64, n_value);
4413 if (cro.weakIvarLayout != 0)
4414 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4415 } else
4416 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4417 outs() << "\n";
4418 print_layout_map64(cro.weakIvarLayout + n_value, info);
4419
4420 outs() << " baseProperties ";
4421 sym_name =
4422 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4423 info, n_value, cro.baseProperties);
4424 if (n_value != 0) {
4425 if (info->verbose && sym_name != nullptr)
4426 outs() << sym_name;
4427 else
4428 outs() << format("0x%" PRIx64, n_value);
4429 if (cro.baseProperties != 0)
4430 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4431 } else
4432 outs() << format("0x%" PRIx64, cro.baseProperties);
4433 outs() << "\n";
4434 if (cro.baseProperties + n_value != 0)
4435 print_objc_property_list64(cro.baseProperties + n_value, info);
4436
Rafael Espindolab9091322015-10-24 23:19:10 +00004437 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004438 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004439}
4440
Richard Smith81ff44d2015-10-09 22:09:56 +00004441static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004442 bool &is_meta_class) {
4443 struct class_ro32_t cro;
4444 const char *r;
4445 uint32_t offset, xoffset, left;
4446 SectionRef S, xS;
4447 const char *name;
4448
4449 r = get_pointer_32(p, offset, left, S, info);
4450 if (r == nullptr)
Richard Smith81ff44d2015-10-09 22:09:56 +00004451 return false;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004452 memset(&cro, '\0', sizeof(struct class_ro32_t));
4453 if (left < sizeof(struct class_ro32_t)) {
4454 memcpy(&cro, r, left);
4455 outs() << " (class_ro_t entends past the end of the section)\n";
4456 } else
4457 memcpy(&cro, r, sizeof(struct class_ro32_t));
4458 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4459 swapStruct(cro);
4460 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4461 if (cro.flags & RO_META)
4462 outs() << " RO_META";
4463 if (cro.flags & RO_ROOT)
4464 outs() << " RO_ROOT";
4465 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4466 outs() << " RO_HAS_CXX_STRUCTORS";
4467 outs() << "\n";
4468 outs() << " instanceStart " << cro.instanceStart << "\n";
4469 outs() << " instanceSize " << cro.instanceSize << "\n";
4470 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4471 << "\n";
4472 print_layout_map32(cro.ivarLayout, info);
4473
4474 outs() << " name " << format("0x%" PRIx32, cro.name);
4475 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4476 if (name != nullptr)
4477 outs() << format(" %.*s", left, name);
4478 outs() << "\n";
4479
4480 outs() << " baseMethods "
4481 << format("0x%" PRIx32, cro.baseMethods)
4482 << " (struct method_list_t *)\n";
4483 if (cro.baseMethods != 0)
4484 print_method_list32_t(cro.baseMethods, info, "");
4485
4486 outs() << " baseProtocols "
4487 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4488 if (cro.baseProtocols != 0)
4489 print_protocol_list32_t(cro.baseProtocols, info);
4490 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4491 << "\n";
4492 if (cro.ivars != 0)
4493 print_ivar_list32_t(cro.ivars, info);
4494 outs() << " weakIvarLayout "
4495 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4496 print_layout_map32(cro.weakIvarLayout, info);
4497 outs() << " baseProperties "
4498 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4499 if (cro.baseProperties != 0)
4500 print_objc_property_list32(cro.baseProperties, info);
Rafael Espindolab9091322015-10-24 23:19:10 +00004501 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004502 return true;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004503}
4504
Kevin Enderby0fc11822015-04-01 20:57:01 +00004505static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4506 struct class64_t c;
4507 const char *r;
4508 uint32_t offset, left;
4509 SectionRef S;
4510 const char *name;
4511 uint64_t isa_n_value, n_value;
4512
4513 r = get_pointer_64(p, offset, left, S, info);
4514 if (r == nullptr || left < sizeof(struct class64_t))
4515 return;
4516 memset(&c, '\0', sizeof(struct class64_t));
4517 if (left < sizeof(struct class64_t)) {
4518 memcpy(&c, r, left);
4519 outs() << " (class_t entends past the end of the section)\n";
4520 } else
4521 memcpy(&c, r, sizeof(struct class64_t));
4522 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4523 swapStruct(c);
4524
4525 outs() << " isa " << format("0x%" PRIx64, c.isa);
4526 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
4527 isa_n_value, c.isa);
4528 if (name != nullptr)
4529 outs() << " " << name;
4530 outs() << "\n";
4531
4532 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
4533 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
4534 n_value, c.superclass);
4535 if (name != nullptr)
4536 outs() << " " << name;
4537 outs() << "\n";
4538
4539 outs() << " cache " << format("0x%" PRIx64, c.cache);
4540 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
4541 n_value, c.cache);
4542 if (name != nullptr)
4543 outs() << " " << name;
4544 outs() << "\n";
4545
4546 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
4547 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
4548 n_value, c.vtable);
4549 if (name != nullptr)
4550 outs() << " " << name;
4551 outs() << "\n";
4552
4553 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
4554 n_value, c.data);
4555 outs() << " data ";
4556 if (n_value != 0) {
4557 if (info->verbose && name != nullptr)
4558 outs() << name;
4559 else
4560 outs() << format("0x%" PRIx64, n_value);
4561 if (c.data != 0)
4562 outs() << " + " << format("0x%" PRIx64, c.data);
4563 } else
4564 outs() << format("0x%" PRIx64, c.data);
4565 outs() << " (struct class_ro_t *)";
4566
4567 // This is a Swift class if some of the low bits of the pointer are set.
4568 if ((c.data + n_value) & 0x7)
4569 outs() << " Swift class";
4570 outs() << "\n";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004571 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004572 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
4573 return;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004574
Kevin Enderbyaac75382015-10-08 16:56:35 +00004575 if (!is_meta_class &&
4576 c.isa + isa_n_value != p &&
4577 c.isa + isa_n_value != 0 &&
4578 info->depth < 100) {
4579 info->depth++;
4580 outs() << "Meta Class\n";
4581 print_class64_t(c.isa + isa_n_value, info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004582 }
4583}
4584
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004585static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
4586 struct class32_t c;
4587 const char *r;
4588 uint32_t offset, left;
4589 SectionRef S;
4590 const char *name;
4591
4592 r = get_pointer_32(p, offset, left, S, info);
4593 if (r == nullptr)
4594 return;
4595 memset(&c, '\0', sizeof(struct class32_t));
4596 if (left < sizeof(struct class32_t)) {
4597 memcpy(&c, r, left);
4598 outs() << " (class_t entends past the end of the section)\n";
4599 } else
4600 memcpy(&c, r, sizeof(struct class32_t));
4601 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4602 swapStruct(c);
4603
4604 outs() << " isa " << format("0x%" PRIx32, c.isa);
4605 name =
4606 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
4607 if (name != nullptr)
4608 outs() << " " << name;
4609 outs() << "\n";
4610
4611 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
4612 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
4613 c.superclass);
4614 if (name != nullptr)
4615 outs() << " " << name;
4616 outs() << "\n";
4617
4618 outs() << " cache " << format("0x%" PRIx32, c.cache);
4619 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
4620 c.cache);
4621 if (name != nullptr)
4622 outs() << " " << name;
4623 outs() << "\n";
4624
4625 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
4626 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
4627 c.vtable);
4628 if (name != nullptr)
4629 outs() << " " << name;
4630 outs() << "\n";
4631
4632 name =
4633 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
4634 outs() << " data " << format("0x%" PRIx32, c.data)
4635 << " (struct class_ro_t *)";
4636
4637 // This is a Swift class if some of the low bits of the pointer are set.
4638 if (c.data & 0x3)
4639 outs() << " Swift class";
4640 outs() << "\n";
4641 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004642 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
4643 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004644
Hans Wennborgcc9deb42015-09-29 18:02:48 +00004645 if (!is_meta_class) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004646 outs() << "Meta Class\n";
4647 print_class32_t(c.isa, info);
4648 }
4649}
4650
Kevin Enderby846c0002015-04-16 17:19:59 +00004651static void print_objc_class_t(struct objc_class_t *objc_class,
4652 struct DisassembleInfo *info) {
4653 uint32_t offset, left, xleft;
4654 const char *name, *p, *ivar_list;
4655 SectionRef S;
4656 int32_t i;
4657 struct objc_ivar_list_t objc_ivar_list;
4658 struct objc_ivar_t ivar;
4659
4660 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
4661 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
4662 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
4663 if (name != nullptr)
4664 outs() << format(" %.*s", left, name);
4665 else
4666 outs() << " (not in an __OBJC section)";
4667 }
4668 outs() << "\n";
4669
4670 outs() << "\t super_class "
4671 << format("0x%08" PRIx32, objc_class->super_class);
4672 if (info->verbose) {
4673 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
4674 if (name != nullptr)
4675 outs() << format(" %.*s", left, name);
4676 else
4677 outs() << " (not in an __OBJC section)";
4678 }
4679 outs() << "\n";
4680
4681 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
4682 if (info->verbose) {
4683 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
4684 if (name != nullptr)
4685 outs() << format(" %.*s", left, name);
4686 else
4687 outs() << " (not in an __OBJC section)";
4688 }
4689 outs() << "\n";
4690
4691 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
4692 << "\n";
4693
4694 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
4695 if (info->verbose) {
4696 if (CLS_GETINFO(objc_class, CLS_CLASS))
4697 outs() << " CLS_CLASS";
4698 else if (CLS_GETINFO(objc_class, CLS_META))
4699 outs() << " CLS_META";
4700 }
4701 outs() << "\n";
4702
4703 outs() << "\t instance_size "
4704 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
4705
4706 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
4707 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
4708 if (p != nullptr) {
4709 if (left > sizeof(struct objc_ivar_list_t)) {
4710 outs() << "\n";
4711 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
4712 } else {
4713 outs() << " (entends past the end of the section)\n";
4714 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
4715 memcpy(&objc_ivar_list, p, left);
4716 }
4717 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4718 swapStruct(objc_ivar_list);
4719 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
4720 ivar_list = p + sizeof(struct objc_ivar_list_t);
4721 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
4722 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
4723 outs() << "\t\t remaining ivar's extend past the of the section\n";
4724 break;
4725 }
4726 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
4727 sizeof(struct objc_ivar_t));
4728 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4729 swapStruct(ivar);
4730
4731 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
4732 if (info->verbose) {
4733 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
4734 if (name != nullptr)
4735 outs() << format(" %.*s", xleft, name);
4736 else
4737 outs() << " (not in an __OBJC section)";
4738 }
4739 outs() << "\n";
4740
4741 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
4742 if (info->verbose) {
4743 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
4744 if (name != nullptr)
4745 outs() << format(" %.*s", xleft, name);
4746 else
4747 outs() << " (not in an __OBJC section)";
4748 }
4749 outs() << "\n";
4750
4751 outs() << "\t\t ivar_offset "
4752 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
4753 }
4754 } else {
4755 outs() << " (not in an __OBJC section)\n";
4756 }
4757
4758 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
4759 if (print_method_list(objc_class->methodLists, info))
4760 outs() << " (not in an __OBJC section)\n";
4761
4762 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
4763 << "\n";
4764
4765 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
4766 if (print_protocol_list(objc_class->protocols, 16, info))
4767 outs() << " (not in an __OBJC section)\n";
4768}
4769
4770static void print_objc_objc_category_t(struct objc_category_t *objc_category,
4771 struct DisassembleInfo *info) {
4772 uint32_t offset, left;
4773 const char *name;
4774 SectionRef S;
4775
4776 outs() << "\t category name "
4777 << format("0x%08" PRIx32, objc_category->category_name);
4778 if (info->verbose) {
4779 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
4780 true);
4781 if (name != nullptr)
4782 outs() << format(" %.*s", left, name);
4783 else
4784 outs() << " (not in an __OBJC section)";
4785 }
4786 outs() << "\n";
4787
4788 outs() << "\t\t class name "
4789 << format("0x%08" PRIx32, objc_category->class_name);
4790 if (info->verbose) {
4791 name =
4792 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
4793 if (name != nullptr)
4794 outs() << format(" %.*s", left, name);
4795 else
4796 outs() << " (not in an __OBJC section)";
4797 }
4798 outs() << "\n";
4799
4800 outs() << "\t instance methods "
4801 << format("0x%08" PRIx32, objc_category->instance_methods);
4802 if (print_method_list(objc_category->instance_methods, info))
4803 outs() << " (not in an __OBJC section)\n";
4804
4805 outs() << "\t class methods "
4806 << format("0x%08" PRIx32, objc_category->class_methods);
4807 if (print_method_list(objc_category->class_methods, info))
4808 outs() << " (not in an __OBJC section)\n";
4809}
4810
Kevin Enderby0fc11822015-04-01 20:57:01 +00004811static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
4812 struct category64_t c;
4813 const char *r;
4814 uint32_t offset, xoffset, left;
4815 SectionRef S, xS;
4816 const char *name, *sym_name;
4817 uint64_t n_value;
4818
4819 r = get_pointer_64(p, offset, left, S, info);
4820 if (r == nullptr)
4821 return;
4822 memset(&c, '\0', sizeof(struct category64_t));
4823 if (left < sizeof(struct category64_t)) {
4824 memcpy(&c, r, left);
4825 outs() << " (category_t entends past the end of the section)\n";
4826 } else
4827 memcpy(&c, r, sizeof(struct category64_t));
4828 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4829 swapStruct(c);
4830
4831 outs() << " name ";
4832 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
4833 info, n_value, c.name);
4834 if (n_value != 0) {
4835 if (info->verbose && sym_name != nullptr)
4836 outs() << sym_name;
4837 else
4838 outs() << format("0x%" PRIx64, n_value);
4839 if (c.name != 0)
4840 outs() << " + " << format("0x%" PRIx64, c.name);
4841 } else
4842 outs() << format("0x%" PRIx64, c.name);
4843 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
4844 if (name != nullptr)
4845 outs() << format(" %.*s", left, name);
4846 outs() << "\n";
4847
4848 outs() << " cls ";
4849 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
4850 n_value, c.cls);
4851 if (n_value != 0) {
4852 if (info->verbose && sym_name != nullptr)
4853 outs() << sym_name;
4854 else
4855 outs() << format("0x%" PRIx64, n_value);
4856 if (c.cls != 0)
4857 outs() << " + " << format("0x%" PRIx64, c.cls);
4858 } else
4859 outs() << format("0x%" PRIx64, c.cls);
4860 outs() << "\n";
4861 if (c.cls + n_value != 0)
4862 print_class64_t(c.cls + n_value, info);
4863
4864 outs() << " instanceMethods ";
4865 sym_name =
4866 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
4867 info, n_value, c.instanceMethods);
4868 if (n_value != 0) {
4869 if (info->verbose && sym_name != nullptr)
4870 outs() << sym_name;
4871 else
4872 outs() << format("0x%" PRIx64, n_value);
4873 if (c.instanceMethods != 0)
4874 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
4875 } else
4876 outs() << format("0x%" PRIx64, c.instanceMethods);
4877 outs() << "\n";
4878 if (c.instanceMethods + n_value != 0)
4879 print_method_list64_t(c.instanceMethods + n_value, info, "");
4880
4881 outs() << " classMethods ";
4882 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
4883 S, info, n_value, c.classMethods);
4884 if (n_value != 0) {
4885 if (info->verbose && sym_name != nullptr)
4886 outs() << sym_name;
4887 else
4888 outs() << format("0x%" PRIx64, n_value);
4889 if (c.classMethods != 0)
4890 outs() << " + " << format("0x%" PRIx64, c.classMethods);
4891 } else
4892 outs() << format("0x%" PRIx64, c.classMethods);
4893 outs() << "\n";
4894 if (c.classMethods + n_value != 0)
4895 print_method_list64_t(c.classMethods + n_value, info, "");
4896
4897 outs() << " protocols ";
4898 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
4899 info, n_value, c.protocols);
4900 if (n_value != 0) {
4901 if (info->verbose && sym_name != nullptr)
4902 outs() << sym_name;
4903 else
4904 outs() << format("0x%" PRIx64, n_value);
4905 if (c.protocols != 0)
4906 outs() << " + " << format("0x%" PRIx64, c.protocols);
4907 } else
4908 outs() << format("0x%" PRIx64, c.protocols);
4909 outs() << "\n";
4910 if (c.protocols + n_value != 0)
4911 print_protocol_list64_t(c.protocols + n_value, info);
4912
4913 outs() << "instanceProperties ";
4914 sym_name =
4915 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
4916 S, info, n_value, c.instanceProperties);
4917 if (n_value != 0) {
4918 if (info->verbose && sym_name != nullptr)
4919 outs() << sym_name;
4920 else
4921 outs() << format("0x%" PRIx64, n_value);
4922 if (c.instanceProperties != 0)
4923 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
4924 } else
4925 outs() << format("0x%" PRIx64, c.instanceProperties);
4926 outs() << "\n";
4927 if (c.instanceProperties + n_value != 0)
4928 print_objc_property_list64(c.instanceProperties + n_value, info);
4929}
4930
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004931static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
4932 struct category32_t c;
4933 const char *r;
4934 uint32_t offset, left;
4935 SectionRef S, xS;
4936 const char *name;
4937
4938 r = get_pointer_32(p, offset, left, S, info);
4939 if (r == nullptr)
4940 return;
4941 memset(&c, '\0', sizeof(struct category32_t));
4942 if (left < sizeof(struct category32_t)) {
4943 memcpy(&c, r, left);
4944 outs() << " (category_t entends past the end of the section)\n";
4945 } else
4946 memcpy(&c, r, sizeof(struct category32_t));
4947 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4948 swapStruct(c);
4949
4950 outs() << " name " << format("0x%" PRIx32, c.name);
4951 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
4952 c.name);
Hans Wennborgcc9deb42015-09-29 18:02:48 +00004953 if (name)
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004954 outs() << " " << name;
4955 outs() << "\n";
4956
4957 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
4958 if (c.cls != 0)
4959 print_class32_t(c.cls, info);
4960 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
4961 << "\n";
4962 if (c.instanceMethods != 0)
4963 print_method_list32_t(c.instanceMethods, info, "");
4964 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
4965 << "\n";
4966 if (c.classMethods != 0)
4967 print_method_list32_t(c.classMethods, info, "");
4968 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
4969 if (c.protocols != 0)
4970 print_protocol_list32_t(c.protocols, info);
4971 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
4972 << "\n";
4973 if (c.instanceProperties != 0)
4974 print_objc_property_list32(c.instanceProperties, info);
4975}
4976
Kevin Enderby0fc11822015-04-01 20:57:01 +00004977static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
4978 uint32_t i, left, offset, xoffset;
4979 uint64_t p, n_value;
4980 struct message_ref64 mr;
4981 const char *name, *sym_name;
4982 const char *r;
4983 SectionRef xS;
4984
4985 if (S == SectionRef())
4986 return;
4987
4988 StringRef SectName;
4989 S.getName(SectName);
4990 DataRefImpl Ref = S.getRawDataRefImpl();
4991 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
4992 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4993 offset = 0;
4994 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
4995 p = S.getAddress() + i;
4996 r = get_pointer_64(p, offset, left, S, info);
4997 if (r == nullptr)
4998 return;
4999 memset(&mr, '\0', sizeof(struct message_ref64));
5000 if (left < sizeof(struct message_ref64)) {
5001 memcpy(&mr, r, left);
5002 outs() << " (message_ref entends past the end of the section)\n";
5003 } else
5004 memcpy(&mr, r, sizeof(struct message_ref64));
5005 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5006 swapStruct(mr);
5007
5008 outs() << " imp ";
5009 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5010 n_value, mr.imp);
5011 if (n_value != 0) {
5012 outs() << format("0x%" PRIx64, n_value) << " ";
5013 if (mr.imp != 0)
5014 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5015 } else
5016 outs() << format("0x%" PRIx64, mr.imp) << " ";
5017 if (name != nullptr)
5018 outs() << " " << name;
5019 outs() << "\n";
5020
5021 outs() << " sel ";
5022 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5023 info, n_value, mr.sel);
5024 if (n_value != 0) {
5025 if (info->verbose && sym_name != nullptr)
5026 outs() << sym_name;
5027 else
5028 outs() << format("0x%" PRIx64, n_value);
5029 if (mr.sel != 0)
5030 outs() << " + " << format("0x%" PRIx64, mr.sel);
5031 } else
5032 outs() << format("0x%" PRIx64, mr.sel);
5033 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5034 if (name != nullptr)
5035 outs() << format(" %.*s", left, name);
5036 outs() << "\n";
5037
5038 offset += sizeof(struct message_ref64);
5039 }
5040}
5041
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005042static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5043 uint32_t i, left, offset, xoffset, p;
5044 struct message_ref32 mr;
5045 const char *name, *r;
5046 SectionRef xS;
5047
5048 if (S == SectionRef())
5049 return;
5050
5051 StringRef SectName;
5052 S.getName(SectName);
5053 DataRefImpl Ref = S.getRawDataRefImpl();
5054 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5055 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5056 offset = 0;
5057 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5058 p = S.getAddress() + i;
5059 r = get_pointer_32(p, offset, left, S, info);
5060 if (r == nullptr)
5061 return;
5062 memset(&mr, '\0', sizeof(struct message_ref32));
5063 if (left < sizeof(struct message_ref32)) {
5064 memcpy(&mr, r, left);
5065 outs() << " (message_ref entends past the end of the section)\n";
5066 } else
5067 memcpy(&mr, r, sizeof(struct message_ref32));
5068 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5069 swapStruct(mr);
5070
5071 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5072 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5073 mr.imp);
5074 if (name != nullptr)
5075 outs() << " " << name;
5076 outs() << "\n";
5077
5078 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5079 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5080 if (name != nullptr)
5081 outs() << " " << name;
5082 outs() << "\n";
5083
5084 offset += sizeof(struct message_ref32);
5085 }
5086}
5087
Kevin Enderby0fc11822015-04-01 20:57:01 +00005088static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5089 uint32_t left, offset, swift_version;
5090 uint64_t p;
5091 struct objc_image_info64 o;
5092 const char *r;
5093
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00005094 if (S == SectionRef())
5095 return;
5096
Kevin Enderby0fc11822015-04-01 20:57:01 +00005097 StringRef SectName;
5098 S.getName(SectName);
5099 DataRefImpl Ref = S.getRawDataRefImpl();
5100 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5101 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5102 p = S.getAddress();
5103 r = get_pointer_64(p, offset, left, S, info);
5104 if (r == nullptr)
5105 return;
5106 memset(&o, '\0', sizeof(struct objc_image_info64));
5107 if (left < sizeof(struct objc_image_info64)) {
5108 memcpy(&o, r, left);
5109 outs() << " (objc_image_info entends past the end of the section)\n";
5110 } else
5111 memcpy(&o, r, sizeof(struct objc_image_info64));
5112 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5113 swapStruct(o);
5114 outs() << " version " << o.version << "\n";
5115 outs() << " flags " << format("0x%" PRIx32, o.flags);
5116 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5117 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5118 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5119 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5120 swift_version = (o.flags >> 8) & 0xff;
5121 if (swift_version != 0) {
5122 if (swift_version == 1)
5123 outs() << " Swift 1.0";
5124 else if (swift_version == 2)
5125 outs() << " Swift 1.1";
5126 else
5127 outs() << " unknown future Swift version (" << swift_version << ")";
5128 }
5129 outs() << "\n";
5130}
5131
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005132static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5133 uint32_t left, offset, swift_version, p;
5134 struct objc_image_info32 o;
5135 const char *r;
5136
Kevin Enderby19be2512016-04-21 19:49:29 +00005137 if (S == SectionRef())
5138 return;
5139
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005140 StringRef SectName;
5141 S.getName(SectName);
5142 DataRefImpl Ref = S.getRawDataRefImpl();
5143 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5144 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5145 p = S.getAddress();
5146 r = get_pointer_32(p, offset, left, S, info);
5147 if (r == nullptr)
5148 return;
5149 memset(&o, '\0', sizeof(struct objc_image_info32));
5150 if (left < sizeof(struct objc_image_info32)) {
5151 memcpy(&o, r, left);
5152 outs() << " (objc_image_info entends past the end of the section)\n";
5153 } else
5154 memcpy(&o, r, sizeof(struct objc_image_info32));
5155 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5156 swapStruct(o);
5157 outs() << " version " << o.version << "\n";
5158 outs() << " flags " << format("0x%" PRIx32, o.flags);
5159 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5160 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5161 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5162 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5163 swift_version = (o.flags >> 8) & 0xff;
5164 if (swift_version != 0) {
5165 if (swift_version == 1)
5166 outs() << " Swift 1.0";
5167 else if (swift_version == 2)
5168 outs() << " Swift 1.1";
5169 else
5170 outs() << " unknown future Swift version (" << swift_version << ")";
5171 }
5172 outs() << "\n";
5173}
5174
Kevin Enderby846c0002015-04-16 17:19:59 +00005175static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5176 uint32_t left, offset, p;
5177 struct imageInfo_t o;
5178 const char *r;
5179
5180 StringRef SectName;
5181 S.getName(SectName);
5182 DataRefImpl Ref = S.getRawDataRefImpl();
5183 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5184 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5185 p = S.getAddress();
5186 r = get_pointer_32(p, offset, left, S, info);
5187 if (r == nullptr)
5188 return;
5189 memset(&o, '\0', sizeof(struct imageInfo_t));
5190 if (left < sizeof(struct imageInfo_t)) {
5191 memcpy(&o, r, left);
5192 outs() << " (imageInfo entends past the end of the section)\n";
5193 } else
5194 memcpy(&o, r, sizeof(struct imageInfo_t));
5195 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5196 swapStruct(o);
5197 outs() << " version " << o.version << "\n";
5198 outs() << " flags " << format("0x%" PRIx32, o.flags);
5199 if (o.flags & 0x1)
5200 outs() << " F&C";
5201 if (o.flags & 0x2)
5202 outs() << " GC";
5203 if (o.flags & 0x4)
5204 outs() << " GC-only";
5205 else
5206 outs() << " RR";
5207 outs() << "\n";
5208}
5209
Kevin Enderby0fc11822015-04-01 20:57:01 +00005210static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5211 SymbolAddressMap AddrMap;
5212 if (verbose)
5213 CreateSymbolAddressMap(O, &AddrMap);
5214
5215 std::vector<SectionRef> Sections;
5216 for (const SectionRef &Section : O->sections()) {
5217 StringRef SectName;
5218 Section.getName(SectName);
5219 Sections.push_back(Section);
5220 }
5221
5222 struct DisassembleInfo info;
5223 // Set up the block of info used by the Symbolizer call backs.
5224 info.verbose = verbose;
5225 info.O = O;
5226 info.AddrMap = &AddrMap;
5227 info.Sections = &Sections;
5228 info.class_name = nullptr;
5229 info.selector_name = nullptr;
5230 info.method = nullptr;
5231 info.demangled_name = nullptr;
5232 info.bindtable = nullptr;
5233 info.adrp_addr = 0;
5234 info.adrp_inst = 0;
5235
Kevin Enderbyaac75382015-10-08 16:56:35 +00005236 info.depth = 0;
Davide Italiano62507042015-12-11 22:27:59 +00005237 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5238 if (CL == SectionRef())
5239 CL = get_section(O, "__DATA", "__objc_classlist");
5240 info.S = CL;
5241 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005242
Davide Italiano62507042015-12-11 22:27:59 +00005243 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5244 if (CR == SectionRef())
5245 CR = get_section(O, "__DATA", "__objc_classrefs");
5246 info.S = CR;
5247 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005248
Davide Italiano62507042015-12-11 22:27:59 +00005249 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5250 if (SR == SectionRef())
5251 SR = get_section(O, "__DATA", "__objc_superrefs");
5252 info.S = SR;
5253 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005254
Davide Italiano62507042015-12-11 22:27:59 +00005255 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5256 if (CA == SectionRef())
5257 CA = get_section(O, "__DATA", "__objc_catlist");
5258 info.S = CA;
5259 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005260
Davide Italiano62507042015-12-11 22:27:59 +00005261 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5262 if (PL == SectionRef())
5263 PL = get_section(O, "__DATA", "__objc_protolist");
5264 info.S = PL;
5265 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005266
Davide Italiano62507042015-12-11 22:27:59 +00005267 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5268 if (MR == SectionRef())
5269 MR = get_section(O, "__DATA", "__objc_msgrefs");
5270 info.S = MR;
5271 print_message_refs64(MR, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005272
Davide Italiano62507042015-12-11 22:27:59 +00005273 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5274 if (II == SectionRef())
5275 II = get_section(O, "__DATA", "__objc_imageinfo");
5276 info.S = II;
5277 print_image_info64(II, &info);
Kevin Enderby0bc6ed42015-04-01 21:50:45 +00005278
5279 if (info.bindtable != nullptr)
5280 delete info.bindtable;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005281}
5282
5283static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005284 SymbolAddressMap AddrMap;
5285 if (verbose)
5286 CreateSymbolAddressMap(O, &AddrMap);
5287
5288 std::vector<SectionRef> Sections;
5289 for (const SectionRef &Section : O->sections()) {
5290 StringRef SectName;
5291 Section.getName(SectName);
5292 Sections.push_back(Section);
5293 }
5294
5295 struct DisassembleInfo info;
5296 // Set up the block of info used by the Symbolizer call backs.
5297 info.verbose = verbose;
5298 info.O = O;
5299 info.AddrMap = &AddrMap;
5300 info.Sections = &Sections;
5301 info.class_name = nullptr;
5302 info.selector_name = nullptr;
5303 info.method = nullptr;
5304 info.demangled_name = nullptr;
5305 info.bindtable = nullptr;
5306 info.adrp_addr = 0;
5307 info.adrp_inst = 0;
5308
5309 const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5310 if (CL != SectionRef()) {
5311 info.S = CL;
5312 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5313 } else {
5314 const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
5315 info.S = CL;
5316 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5317 }
5318
5319 const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5320 if (CR != SectionRef()) {
5321 info.S = CR;
5322 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5323 } else {
5324 const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
5325 info.S = CR;
5326 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5327 }
5328
5329 const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5330 if (SR != SectionRef()) {
5331 info.S = SR;
5332 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5333 } else {
5334 const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
5335 info.S = SR;
5336 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5337 }
5338
5339 const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5340 if (CA != SectionRef()) {
5341 info.S = CA;
5342 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5343 } else {
5344 const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
5345 info.S = CA;
5346 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5347 }
5348
5349 const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5350 if (PL != SectionRef()) {
5351 info.S = PL;
5352 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5353 } else {
5354 const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
5355 info.S = PL;
5356 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5357 }
5358
5359 const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5360 if (MR != SectionRef()) {
5361 info.S = MR;
5362 print_message_refs32(MR, &info);
5363 } else {
5364 const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
5365 info.S = MR;
5366 print_message_refs32(MR, &info);
5367 }
5368
5369 const SectionRef II = get_section(O, "__OBJC2", "__image_info");
5370 if (II != SectionRef()) {
5371 info.S = II;
5372 print_image_info32(II, &info);
5373 } else {
5374 const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
5375 info.S = II;
5376 print_image_info32(II, &info);
5377 }
Kevin Enderby0fc11822015-04-01 20:57:01 +00005378}
5379
5380static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby846c0002015-04-16 17:19:59 +00005381 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5382 const char *r, *name, *defs;
5383 struct objc_module_t module;
5384 SectionRef S, xS;
5385 struct objc_symtab_t symtab;
5386 struct objc_class_t objc_class;
5387 struct objc_category_t objc_category;
5388
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005389 outs() << "Objective-C segment\n";
Kevin Enderby846c0002015-04-16 17:19:59 +00005390 S = get_section(O, "__OBJC", "__module_info");
5391 if (S == SectionRef())
5392 return false;
5393
5394 SymbolAddressMap AddrMap;
5395 if (verbose)
5396 CreateSymbolAddressMap(O, &AddrMap);
5397
5398 std::vector<SectionRef> Sections;
5399 for (const SectionRef &Section : O->sections()) {
5400 StringRef SectName;
5401 Section.getName(SectName);
5402 Sections.push_back(Section);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005403 }
Kevin Enderby846c0002015-04-16 17:19:59 +00005404
5405 struct DisassembleInfo info;
5406 // Set up the block of info used by the Symbolizer call backs.
5407 info.verbose = verbose;
5408 info.O = O;
5409 info.AddrMap = &AddrMap;
5410 info.Sections = &Sections;
5411 info.class_name = nullptr;
5412 info.selector_name = nullptr;
5413 info.method = nullptr;
5414 info.demangled_name = nullptr;
5415 info.bindtable = nullptr;
5416 info.adrp_addr = 0;
5417 info.adrp_inst = 0;
5418
5419 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5420 p = S.getAddress() + i;
5421 r = get_pointer_32(p, offset, left, S, &info, true);
5422 if (r == nullptr)
5423 return true;
5424 memset(&module, '\0', sizeof(struct objc_module_t));
5425 if (left < sizeof(struct objc_module_t)) {
5426 memcpy(&module, r, left);
5427 outs() << " (module extends past end of __module_info section)\n";
5428 } else
5429 memcpy(&module, r, sizeof(struct objc_module_t));
5430 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5431 swapStruct(module);
5432
5433 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5434 outs() << " version " << module.version << "\n";
5435 outs() << " size " << module.size << "\n";
5436 outs() << " name ";
5437 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5438 if (name != nullptr)
5439 outs() << format("%.*s", left, name);
5440 else
5441 outs() << format("0x%08" PRIx32, module.name)
5442 << "(not in an __OBJC section)";
5443 outs() << "\n";
5444
5445 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5446 if (module.symtab == 0 || r == nullptr) {
5447 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5448 << " (not in an __OBJC section)\n";
5449 continue;
5450 }
5451 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5452 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5453 defs_left = 0;
5454 defs = nullptr;
5455 if (left < sizeof(struct objc_symtab_t)) {
5456 memcpy(&symtab, r, left);
5457 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5458 } else {
5459 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5460 if (left > sizeof(struct objc_symtab_t)) {
5461 defs_left = left - sizeof(struct objc_symtab_t);
5462 defs = r + sizeof(struct objc_symtab_t);
5463 }
5464 }
5465 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5466 swapStruct(symtab);
5467
5468 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5469 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5470 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5471 if (r == nullptr)
5472 outs() << " (not in an __OBJC section)";
5473 outs() << "\n";
5474 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5475 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5476 if (symtab.cls_def_cnt > 0)
5477 outs() << "\tClass Definitions\n";
5478 for (j = 0; j < symtab.cls_def_cnt; j++) {
5479 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5480 outs() << "\t(remaining class defs entries entends past the end of the "
5481 << "section)\n";
5482 break;
5483 }
5484 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5485 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5486 sys::swapByteOrder(def);
5487
5488 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5489 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5490 if (r != nullptr) {
5491 if (left > sizeof(struct objc_class_t)) {
5492 outs() << "\n";
5493 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5494 } else {
5495 outs() << " (entends past the end of the section)\n";
5496 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5497 memcpy(&objc_class, r, left);
5498 }
5499 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5500 swapStruct(objc_class);
5501 print_objc_class_t(&objc_class, &info);
5502 } else {
5503 outs() << "(not in an __OBJC section)\n";
5504 }
5505
5506 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
5507 outs() << "\tMeta Class";
5508 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
5509 if (r != nullptr) {
5510 if (left > sizeof(struct objc_class_t)) {
5511 outs() << "\n";
5512 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5513 } else {
5514 outs() << " (entends past the end of the section)\n";
5515 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5516 memcpy(&objc_class, r, left);
5517 }
5518 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5519 swapStruct(objc_class);
5520 print_objc_class_t(&objc_class, &info);
5521 } else {
5522 outs() << "(not in an __OBJC section)\n";
5523 }
5524 }
5525 }
5526 if (symtab.cat_def_cnt > 0)
5527 outs() << "\tCategory Definitions\n";
5528 for (j = 0; j < symtab.cat_def_cnt; j++) {
5529 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
5530 outs() << "\t(remaining category defs entries entends past the end of "
5531 << "the section)\n";
5532 break;
5533 }
5534 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
5535 sizeof(uint32_t));
5536 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5537 sys::swapByteOrder(def);
5538
5539 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5540 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
5541 << format("0x%08" PRIx32, def);
5542 if (r != nullptr) {
5543 if (left > sizeof(struct objc_category_t)) {
5544 outs() << "\n";
5545 memcpy(&objc_category, r, sizeof(struct objc_category_t));
5546 } else {
5547 outs() << " (entends past the end of the section)\n";
5548 memset(&objc_category, '\0', sizeof(struct objc_category_t));
5549 memcpy(&objc_category, r, left);
5550 }
5551 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5552 swapStruct(objc_category);
5553 print_objc_objc_category_t(&objc_category, &info);
5554 } else {
5555 outs() << "(not in an __OBJC section)\n";
5556 }
5557 }
5558 }
5559 const SectionRef II = get_section(O, "__OBJC", "__image_info");
5560 if (II != SectionRef())
5561 print_image_info(II, &info);
5562
5563 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005564}
5565
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00005566static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
5567 uint32_t size, uint32_t addr) {
5568 SymbolAddressMap AddrMap;
5569 CreateSymbolAddressMap(O, &AddrMap);
5570
5571 std::vector<SectionRef> Sections;
5572 for (const SectionRef &Section : O->sections()) {
5573 StringRef SectName;
5574 Section.getName(SectName);
5575 Sections.push_back(Section);
5576 }
5577
5578 struct DisassembleInfo info;
5579 // Set up the block of info used by the Symbolizer call backs.
5580 info.verbose = true;
5581 info.O = O;
5582 info.AddrMap = &AddrMap;
5583 info.Sections = &Sections;
5584 info.class_name = nullptr;
5585 info.selector_name = nullptr;
5586 info.method = nullptr;
5587 info.demangled_name = nullptr;
5588 info.bindtable = nullptr;
5589 info.adrp_addr = 0;
5590 info.adrp_inst = 0;
5591
5592 const char *p;
5593 struct objc_protocol_t protocol;
5594 uint32_t left, paddr;
5595 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
5596 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
5597 left = size - (p - sect);
5598 if (left < sizeof(struct objc_protocol_t)) {
5599 outs() << "Protocol extends past end of __protocol section\n";
5600 memcpy(&protocol, p, left);
5601 } else
5602 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
5603 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5604 swapStruct(protocol);
5605 paddr = addr + (p - sect);
5606 outs() << "Protocol " << format("0x%" PRIx32, paddr);
5607 if (print_protocol(paddr, 0, &info))
5608 outs() << "(not in an __OBJC section)\n";
5609 }
5610}
5611
Kevin Enderby0fc11822015-04-01 20:57:01 +00005612static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
5613 if (O->is64Bit())
5614 printObjc2_64bit_MetaData(O, verbose);
5615 else {
5616 MachO::mach_header H;
5617 H = O->getHeader();
5618 if (H.cputype == MachO::CPU_TYPE_ARM)
5619 printObjc2_32bit_MetaData(O, verbose);
5620 else {
5621 // This is the 32-bit non-arm cputype case. Which is normally
5622 // the first Objective-C ABI. But it may be the case of a
5623 // binary for the iOS simulator which is the second Objective-C
5624 // ABI. In that case printObjc1_32bit_MetaData() will determine that
5625 // and return false.
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005626 if (!printObjc1_32bit_MetaData(O, verbose))
Kevin Enderby0fc11822015-04-01 20:57:01 +00005627 printObjc2_32bit_MetaData(O, verbose);
5628 }
5629 }
5630}
5631
Kevin Enderbybf246f52014-09-24 23:08:22 +00005632// GuessLiteralPointer returns a string which for the item in the Mach-O file
5633// for the address passed in as ReferenceValue for printing as a comment with
5634// the instruction and also returns the corresponding type of that item
5635// indirectly through ReferenceType.
5636//
5637// If ReferenceValue is an address of literal cstring then a pointer to the
5638// cstring is returned and ReferenceType is set to
5639// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
5640//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005641// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
5642// Class ref that name is returned and the ReferenceType is set accordingly.
5643//
5644// Lastly, literals which are Symbol address in a literal pool are looked for
5645// and if found the symbol name is returned and ReferenceType is set to
5646// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
5647//
5648// If there is no item in the Mach-O file for the address passed in as
5649// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00005650static const char *GuessLiteralPointer(uint64_t ReferenceValue,
5651 uint64_t ReferencePC,
5652 uint64_t *ReferenceType,
5653 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00005654 // First see if there is an external relocation entry at the ReferencePC.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00005655 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
5656 uint64_t sect_addr = info->S.getAddress();
5657 uint64_t sect_offset = ReferencePC - sect_addr;
5658 bool reloc_found = false;
5659 DataRefImpl Rel;
5660 MachO::any_relocation_info RE;
5661 bool isExtern = false;
5662 SymbolRef Symbol;
5663 for (const RelocationRef &Reloc : info->S.relocations()) {
5664 uint64_t RelocOffset = Reloc.getOffset();
5665 if (RelocOffset == sect_offset) {
5666 Rel = Reloc.getRawDataRefImpl();
5667 RE = info->O->getRelocation(Rel);
5668 if (info->O->isRelocationScattered(RE))
5669 continue;
5670 isExtern = info->O->getPlainRelocationExternal(RE);
5671 if (isExtern) {
5672 symbol_iterator RelocSym = Reloc.getSymbol();
5673 Symbol = *RelocSym;
5674 }
5675 reloc_found = true;
5676 break;
Kevin Enderbybf246f52014-09-24 23:08:22 +00005677 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005678 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00005679 // If there is an external relocation entry for a symbol in a section
5680 // then used that symbol's value for the value of the reference.
5681 if (reloc_found && isExtern) {
5682 if (info->O->getAnyRelocationPCRel(RE)) {
5683 unsigned Type = info->O->getAnyRelocationType(RE);
5684 if (Type == MachO::X86_64_RELOC_SIGNED) {
5685 ReferenceValue = Symbol.getValue();
5686 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005687 }
5688 }
5689 }
5690
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005691 // Look for literals such as Objective-C CFStrings refs, Selector refs,
5692 // Message refs and Class refs.
5693 bool classref, selref, msgref, cfstring;
5694 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
5695 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00005696 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005697 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
5698 // And the pointer_value in that section is typically zero as it will be
5699 // set by dyld as part of the "bind information".
5700 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
5701 if (name != nullptr) {
5702 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00005703 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005704 if (class_name != nullptr && class_name[1] == '_' &&
5705 class_name[2] != '\0') {
5706 info->class_name = class_name + 2;
5707 return name;
5708 }
5709 }
5710 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005711
David Blaikie33dd45d02015-03-23 18:39:02 +00005712 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005713 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
5714 const char *name =
5715 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
5716 if (name != nullptr)
5717 info->class_name = name;
5718 else
5719 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00005720 return name;
5721 }
5722
David Blaikie33dd45d02015-03-23 18:39:02 +00005723 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005724 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
5725 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
5726 return name;
5727 }
5728
David Blaikie33dd45d02015-03-23 18:39:02 +00005729 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005730 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
5731
5732 if (pointer_value != 0)
5733 ReferenceValue = pointer_value;
5734
5735 const char *name = GuessCstringPointer(ReferenceValue, info);
5736 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00005737 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005738 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
5739 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00005740 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005741 info->class_name = nullptr;
5742 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
5743 info->selector_name = name;
5744 } else
5745 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
5746 return name;
5747 }
5748
5749 // Lastly look for an indirect symbol with this ReferenceValue which is in
5750 // a literal pool. If found return that symbol name.
5751 name = GuessIndirectSymbol(ReferenceValue, info);
5752 if (name) {
5753 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
5754 return name;
5755 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005756
5757 return nullptr;
5758}
5759
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005760// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00005761// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005762// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
5763// is created and returns the symbol name that matches the ReferenceValue or
5764// nullptr if none. The ReferenceType is passed in for the IN type of
5765// reference the instruction is making from the values in defined in the header
5766// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
5767// Out type and the ReferenceName will also be set which is added as a comment
5768// to the disassembled instruction.
5769//
Kevin Enderby04bf6932014-10-28 23:39:46 +00005770#if HAVE_CXXABI_H
5771// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005772// returned through ReferenceName and ReferenceType is set to
5773// LLVMDisassembler_ReferenceType_DeMangled_Name .
Kevin Enderby04bf6932014-10-28 23:39:46 +00005774#endif
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005775//
5776// When this is called to get a symbol name for a branch target then the
5777// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
5778// SymbolValue will be looked for in the indirect symbol table to determine if
5779// it is an address for a symbol stub. If so then the symbol name for that
5780// stub is returned indirectly through ReferenceName and then ReferenceType is
5781// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
5782//
Kevin Enderbybf246f52014-09-24 23:08:22 +00005783// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005784// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
5785// SymbolValue is checked to be an address of literal pointer, symbol pointer,
5786// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005787// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00005788static const char *SymbolizerSymbolLookUp(void *DisInfo,
5789 uint64_t ReferenceValue,
5790 uint64_t *ReferenceType,
5791 uint64_t ReferencePC,
5792 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005793 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00005794 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00005795 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00005796 *ReferenceName = nullptr;
5797 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005798 return nullptr;
5799 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005800
Kevin Enderbyf6d25852015-01-31 00:37:11 +00005801 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00005802
Kevin Enderby85974882014-09-26 22:20:44 +00005803 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
5804 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00005805 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005806 method_reference(info, ReferenceType, ReferenceName);
5807 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
5808 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
5809 } else
Kevin Enderby04bf6932014-10-28 23:39:46 +00005810#if HAVE_CXXABI_H
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005811 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00005812 if (info->demangled_name != nullptr)
5813 free(info->demangled_name);
5814 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005815 info->demangled_name =
5816 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00005817 if (info->demangled_name != nullptr) {
5818 *ReferenceName = info->demangled_name;
5819 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5820 } else
5821 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5822 } else
5823#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005824 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5825 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
5826 *ReferenceName =
5827 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00005828 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005829 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00005830 else
5831 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00005832 // If this is arm64 and the reference is an adrp instruction save the
5833 // instruction, passed in ReferenceValue and the address of the instruction
5834 // for use later if we see and add immediate instruction.
5835 } else if (info->O->getArch() == Triple::aarch64 &&
5836 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
5837 info->adrp_inst = ReferenceValue;
5838 info->adrp_addr = ReferencePC;
5839 SymbolName = nullptr;
5840 *ReferenceName = nullptr;
5841 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5842 // If this is arm64 and reference is an add immediate instruction and we
5843 // have
5844 // seen an adrp instruction just before it and the adrp's Xd register
5845 // matches
5846 // this add's Xn register reconstruct the value being referenced and look to
5847 // see if it is a literal pointer. Note the add immediate instruction is
5848 // passed in ReferenceValue.
5849 } else if (info->O->getArch() == Triple::aarch64 &&
5850 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
5851 ReferencePC - 4 == info->adrp_addr &&
5852 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5853 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5854 uint32_t addxri_inst;
5855 uint64_t adrp_imm, addxri_imm;
5856
5857 adrp_imm =
5858 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5859 if (info->adrp_inst & 0x0200000)
5860 adrp_imm |= 0xfffffffffc000000LL;
5861
5862 addxri_inst = ReferenceValue;
5863 addxri_imm = (addxri_inst >> 10) & 0xfff;
5864 if (((addxri_inst >> 22) & 0x3) == 1)
5865 addxri_imm <<= 12;
5866
5867 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5868 (adrp_imm << 12) + addxri_imm;
5869
5870 *ReferenceName =
5871 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5872 if (*ReferenceName == nullptr)
5873 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5874 // If this is arm64 and the reference is a load register instruction and we
5875 // have seen an adrp instruction just before it and the adrp's Xd register
5876 // matches this add's Xn register reconstruct the value being referenced and
5877 // look to see if it is a literal pointer. Note the load register
5878 // instruction is passed in ReferenceValue.
5879 } else if (info->O->getArch() == Triple::aarch64 &&
5880 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
5881 ReferencePC - 4 == info->adrp_addr &&
5882 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5883 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5884 uint32_t ldrxui_inst;
5885 uint64_t adrp_imm, ldrxui_imm;
5886
5887 adrp_imm =
5888 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5889 if (info->adrp_inst & 0x0200000)
5890 adrp_imm |= 0xfffffffffc000000LL;
5891
5892 ldrxui_inst = ReferenceValue;
5893 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
5894
5895 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5896 (adrp_imm << 12) + (ldrxui_imm << 3);
5897
5898 *ReferenceName =
5899 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5900 if (*ReferenceName == nullptr)
5901 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5902 }
5903 // If this arm64 and is an load register (PC-relative) instruction the
5904 // ReferenceValue is the PC plus the immediate value.
5905 else if (info->O->getArch() == Triple::aarch64 &&
5906 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
5907 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
5908 *ReferenceName =
5909 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5910 if (*ReferenceName == nullptr)
5911 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby85974882014-09-26 22:20:44 +00005912 }
Kevin Enderby04bf6932014-10-28 23:39:46 +00005913#if HAVE_CXXABI_H
5914 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
5915 if (info->demangled_name != nullptr)
5916 free(info->demangled_name);
5917 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005918 info->demangled_name =
5919 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00005920 if (info->demangled_name != nullptr) {
5921 *ReferenceName = info->demangled_name;
5922 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5923 }
5924 }
5925#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005926 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00005927 *ReferenceName = nullptr;
5928 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5929 }
5930
5931 return SymbolName;
5932}
5933
Kevin Enderbybf246f52014-09-24 23:08:22 +00005934/// \brief Emits the comments that are stored in the CommentStream.
5935/// Each comment in the CommentStream must end with a newline.
5936static void emitComments(raw_svector_ostream &CommentStream,
5937 SmallString<128> &CommentsToEmit,
5938 formatted_raw_ostream &FormattedOS,
5939 const MCAsmInfo &MAI) {
5940 // Flush the stream before taking its content.
Kevin Enderbybf246f52014-09-24 23:08:22 +00005941 StringRef Comments = CommentsToEmit.str();
5942 // Get the default information for printing a comment.
5943 const char *CommentBegin = MAI.getCommentString();
5944 unsigned CommentColumn = MAI.getCommentColumn();
5945 bool IsFirst = true;
5946 while (!Comments.empty()) {
5947 if (!IsFirst)
5948 FormattedOS << '\n';
5949 // Emit a line of comments.
5950 FormattedOS.PadToColumn(CommentColumn);
5951 size_t Position = Comments.find('\n');
5952 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
5953 // Move after the newline character.
5954 Comments = Comments.substr(Position + 1);
5955 IsFirst = false;
5956 }
5957 FormattedOS.flush();
5958
5959 // Tell the comment stream that the vector changed underneath it.
5960 CommentsToEmit.clear();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005961}
5962
Kevin Enderby95df54c2015-02-04 01:01:38 +00005963static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
5964 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005965 const char *McpuDefault = nullptr;
5966 const Target *ThumbTarget = nullptr;
5967 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005968 if (!TheTarget) {
5969 // GetTarget prints out stuff.
5970 return;
5971 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005972 if (MCPU.empty() && McpuDefault)
5973 MCPU = McpuDefault;
5974
Ahmed Charles56440fd2014-03-06 05:51:42 +00005975 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005976 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00005977 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005978 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005979
Kevin Enderbyc9595622014-08-06 23:24:41 +00005980 // Package up features to be passed to target/subtarget
5981 std::string FeaturesStr;
5982 if (MAttrs.size()) {
5983 SubtargetFeatures Features;
5984 for (unsigned i = 0; i != MAttrs.size(); ++i)
5985 Features.AddFeature(MAttrs[i]);
5986 FeaturesStr = Features.getString();
5987 }
5988
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005989 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00005990 std::unique_ptr<const MCRegisterInfo> MRI(
5991 TheTarget->createMCRegInfo(TripleName));
5992 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00005993 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00005994 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +00005995 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00005996 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005997 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005998 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005999 std::unique_ptr<MCSymbolizer> Symbolizer;
6000 struct DisassembleInfo SymbolizerInfo;
6001 std::unique_ptr<MCRelocationInfo> RelInfo(
6002 TheTarget->createMCRelocationInfo(TripleName, Ctx));
6003 if (RelInfo) {
6004 Symbolizer.reset(TheTarget->createMCSymbolizer(
6005 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006006 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006007 DisAsm->setSymbolizer(std::move(Symbolizer));
6008 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006009 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00006010 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006011 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006012 // Set the display preference for hex vs. decimal immediates.
6013 IP->setPrintImmHex(PrintImmHex);
6014 // Comment stream and backing vector.
6015 SmallString<128> CommentsToEmit;
6016 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006017 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
6018 // if it is done then arm64 comments for string literals don't get printed
6019 // and some constant get printed instead and not setting it causes intel
6020 // (32-bit and 64-bit) comments printed with different spacing before the
6021 // comment causing different diffs with the 'C' disassembler library API.
6022 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006023
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006024 if (!AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencerc1363cf2011-10-07 19:25:47 +00006025 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006026 << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006027 return;
6028 }
6029
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006030 // Set up thumb disassembler.
6031 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
6032 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
6033 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006034 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006035 std::unique_ptr<MCInstPrinter> ThumbIP;
6036 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006037 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
6038 struct DisassembleInfo ThumbSymbolizerInfo;
6039 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006040 if (ThumbTarget) {
6041 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
6042 ThumbAsmInfo.reset(
6043 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
6044 ThumbSTI.reset(
6045 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
6046 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
6047 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006048 MCContext *PtrThumbCtx = ThumbCtx.get();
6049 ThumbRelInfo.reset(
6050 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
6051 if (ThumbRelInfo) {
6052 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
6053 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006054 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006055 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
6056 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006057 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
6058 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006059 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
6060 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006061 // Set the display preference for hex vs. decimal immediates.
6062 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006063 }
6064
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006065 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006066 errs() << "error: couldn't initialize disassembler for target "
6067 << ThumbTripleName << '\n';
6068 return;
6069 }
6070
Charles Davis8bdfafd2013-09-01 04:28:48 +00006071 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006072
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006073 // FIXME: Using the -cfg command line option, this code used to be able to
6074 // annotate relocations with the referenced symbol's name, and if this was
6075 // inside a __[cf]string section, the data it points to. This is now replaced
6076 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00006077 std::vector<SectionRef> Sections;
6078 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006079 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00006080 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006081
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00006082 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
Kevin Enderby273ae012013-06-06 17:20:50 +00006083 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006084
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006085 // Sort the symbols by address, just in case they didn't come in that way.
Owen Andersond9243c42011-10-17 21:37:35 +00006086 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006087
Kevin Enderby273ae012013-06-06 17:20:50 +00006088 // Build a data in code table that is sorted on by the address of each entry.
6089 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00006090 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00006091 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00006092 else
6093 BaseAddress = BaseSegmentAddress;
6094 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00006095 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00006096 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006097 uint32_t Offset;
6098 DI->getOffset(Offset);
6099 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6100 }
6101 array_pod_sort(Dices.begin(), Dices.end());
6102
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006103#ifndef NDEBUG
6104 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6105#else
6106 raw_ostream &DebugOut = nulls();
6107#endif
6108
Ahmed Charles56440fd2014-03-06 05:51:42 +00006109 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00006110 ObjectFile *DbgObj = MachOOF;
Benjamin Kramer699128e2011-09-21 01:13:19 +00006111 // Try to find debug info and set up the DIContext for it.
6112 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00006113 // A separate DSym file path was specified, parse it as a macho file,
6114 // get the sections and supply it to the section name parsing machinery.
6115 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00006116 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006117 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00006118 if (std::error_code EC = BufOrErr.getError()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006119 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +00006120 return;
6121 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00006122 DbgObj =
6123 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
6124 .get()
6125 .release();
Benjamin Kramer699128e2011-09-21 01:13:19 +00006126 }
6127
Eric Christopher7370b552012-11-12 21:40:38 +00006128 // Setup the DIContext
Zachary Turner6489d7b2015-04-23 17:37:47 +00006129 diContext.reset(new DWARFContextInMemory(*DbgObj));
Benjamin Kramer699128e2011-09-21 01:13:19 +00006130 }
6131
Colin LeMahieufcc32762015-07-29 19:08:10 +00006132 if (FilterSections.size() == 0)
Kevin Enderby95df54c2015-02-04 01:01:38 +00006133 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006134
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006135 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00006136 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00006137 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6138 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006139
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006140 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006141
Rafael Espindolab0f76a42013-04-05 15:15:22 +00006142 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00006143 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006144 continue;
6145
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006146 StringRef BytesStr;
6147 Sections[SectIdx].getContents(BytesStr);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00006148 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6149 BytesStr.size());
Rafael Espindola80291272014-10-08 15:28:58 +00006150 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00006151
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006152 bool symbolTableWorked = false;
6153
Kevin Enderbybf246f52014-09-24 23:08:22 +00006154 // Create a map of symbol addresses to symbol names for use by
6155 // the SymbolizerSymbolLookUp() routine.
6156 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00006157 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006158 for (const SymbolRef &Symbol : MachOOF->symbols()) {
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006159 ErrorOr<SymbolRef::Type> STOrErr = Symbol.getType();
6160 if (std::error_code EC = STOrErr.getError())
6161 report_fatal_error(EC.message());
6162 SymbolRef::Type ST = *STOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006163 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
6164 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00006165 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006166 Expected<StringRef> SymNameOrErr = Symbol.getName();
6167 if (!SymNameOrErr) {
6168 std::string Buf;
6169 raw_string_ostream OS(Buf);
6170 logAllUnhandledErrors(SymNameOrErr.takeError(), OS, "");
6171 OS.flush();
6172 report_fatal_error(Buf);
6173 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006174 StringRef SymName = *SymNameOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006175 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00006176 if (!DisSymName.empty() && DisSymName == SymName)
6177 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006178 }
6179 }
David Blaikie33dd45d02015-03-23 18:39:02 +00006180 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00006181 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
6182 return;
6183 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006184 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006185 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006186 SymbolizerInfo.O = MachOOF;
6187 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00006188 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006189 SymbolizerInfo.Sections = &Sections;
6190 SymbolizerInfo.class_name = nullptr;
6191 SymbolizerInfo.selector_name = nullptr;
6192 SymbolizerInfo.method = nullptr;
Kevin Enderby04bf6932014-10-28 23:39:46 +00006193 SymbolizerInfo.demangled_name = nullptr;
Kevin Enderby078be602014-10-23 19:53:12 +00006194 SymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006195 SymbolizerInfo.adrp_addr = 0;
6196 SymbolizerInfo.adrp_inst = 0;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006197 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006198 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006199 ThumbSymbolizerInfo.O = MachOOF;
6200 ThumbSymbolizerInfo.S = Sections[SectIdx];
6201 ThumbSymbolizerInfo.AddrMap = &AddrMap;
6202 ThumbSymbolizerInfo.Sections = &Sections;
6203 ThumbSymbolizerInfo.class_name = nullptr;
6204 ThumbSymbolizerInfo.selector_name = nullptr;
6205 ThumbSymbolizerInfo.method = nullptr;
6206 ThumbSymbolizerInfo.demangled_name = nullptr;
6207 ThumbSymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006208 ThumbSymbolizerInfo.adrp_addr = 0;
6209 ThumbSymbolizerInfo.adrp_inst = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006210
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006211 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006212 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006213 Expected<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
6214 if (!SymNameOrErr) {
6215 std::string Buf;
6216 raw_string_ostream OS(Buf);
6217 logAllUnhandledErrors(SymNameOrErr.takeError(), OS, "");
6218 OS.flush();
6219 report_fatal_error(Buf);
6220 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006221 StringRef SymName = *SymNameOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00006222
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006223 ErrorOr<SymbolRef::Type> STOrErr = Symbols[SymIdx].getType();
6224 if (std::error_code EC = STOrErr.getError())
6225 report_fatal_error(EC.message());
6226 SymbolRef::Type ST = *STOrErr;
Kuba Breckade833222015-11-12 09:40:29 +00006227 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
Owen Andersond9243c42011-10-17 21:37:35 +00006228 continue;
6229
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006230 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00006231 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Owen Andersond9243c42011-10-17 21:37:35 +00006232 if (!containsSym)
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006233 continue;
6234
Kevin Enderby6a221752015-03-17 17:10:57 +00006235 // If we are only disassembling one symbol see if this is that symbol.
6236 if (!DisSymName.empty() && DisSymName != SymName)
6237 continue;
6238
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006239 // Start at the address of the symbol relative to the section's address.
Rafael Espindoladea00162015-07-03 17:44:18 +00006240 uint64_t Start = Symbols[SymIdx].getValue();
Rafael Espindola80291272014-10-08 15:28:58 +00006241 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006242 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006243
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006244 // Stop disassembling either at the beginning of the next symbol or at
6245 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00006246 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00006247 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006248 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00006249 while (Symbols.size() > NextSymIdx) {
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006250 ErrorOr<SymbolRef::Type> STOrErr = Symbols[NextSymIdx].getType();
6251 if (std::error_code EC = STOrErr.getError())
6252 report_fatal_error(EC.message());
6253 SymbolRef::Type NextSymType = *STOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00006254 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00006255 containsNextSym =
6256 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Rafael Espindoladea00162015-07-03 17:44:18 +00006257 NextSym = Symbols[NextSymIdx].getValue();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006258 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006259 break;
6260 }
6261 ++NextSymIdx;
6262 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006263
Rafael Espindola80291272014-10-08 15:28:58 +00006264 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006265 uint64_t End = containsNextSym ? NextSym : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00006266 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006267
6268 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00006269
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006270 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
6271 bool isThumb =
6272 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
6273
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006274 outs() << SymName << ":\n";
6275 DILineInfo lastLine;
6276 for (uint64_t Index = Start; Index < End; Index += Size) {
6277 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00006278
Kevin Enderbybf246f52014-09-24 23:08:22 +00006279 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006280 if (!NoLeadingAddr) {
6281 if (FullLeadingAddr) {
6282 if (MachOOF->is64Bit())
6283 outs() << format("%016" PRIx64, PC);
6284 else
6285 outs() << format("%08" PRIx64, PC);
6286 } else {
6287 outs() << format("%8" PRIx64 ":", PC);
6288 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006289 }
6290 if (!NoShowRawInsn)
6291 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00006292
6293 // Check the data in code table here to see if this is data not an
6294 // instruction to be disassembled.
6295 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006296 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006297 dice_table_iterator DTI =
6298 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
6299 compareDiceTableEntries);
6300 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006301 uint16_t Length;
6302 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00006303 uint16_t Kind;
6304 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00006305 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00006306 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
6307 (PC == (DTI->first + Length - 1)) && (Length & 1))
6308 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00006309 continue;
6310 }
6311
Kevin Enderbybf246f52014-09-24 23:08:22 +00006312 SmallVector<char, 64> AnnotationsBytes;
6313 raw_svector_ostream Annotations(AnnotationsBytes);
6314
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006315 bool gotInst;
6316 if (isThumb)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006317 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006318 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006319 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006320 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00006321 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006322 if (gotInst) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006323 if (!NoShowRawInsn) {
Craig Topper0013be12015-09-21 05:32:41 +00006324 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006325 }
6326 formatted_raw_ostream FormattedOS(outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006327 StringRef AnnotationsStr = Annotations.str();
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006328 if (isThumb)
Akira Hatanakab46d0232015-03-27 20:36:02 +00006329 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006330 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00006331 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006332 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00006333
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006334 // Print debug info.
6335 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006336 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006337 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00006338 if (dli != lastLine && dli.Line != 0)
6339 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
6340 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006341 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006342 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006343 outs() << "\n";
6344 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006345 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006346 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006347 outs() << format("\t.byte 0x%02x #bad opcode\n",
6348 *(Bytes.data() + Index) & 0xff);
6349 Size = 1; // skip exactly one illegible byte and move on.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006350 } else if (Arch == Triple::aarch64) {
6351 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6352 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
6353 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
6354 (*(Bytes.data() + Index + 3) & 0xff) << 24;
6355 outs() << format("\t.long\t0x%08x\n", opcode);
6356 Size = 4;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006357 } else {
6358 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6359 if (Size == 0)
6360 Size = 1; // skip illegible bytes
6361 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006362 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006363 }
6364 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006365 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00006366 // Reading the symbol table didn't work, disassemble the whole section.
6367 uint64_t SectAddress = Sections[SectIdx].getAddress();
6368 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00006369 uint64_t InstSize;
6370 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00006371 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00006372
Kevin Enderbybf246f52014-09-24 23:08:22 +00006373 uint64_t PC = SectAddress + Index;
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006374 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
6375 DebugOut, nulls())) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006376 if (!NoLeadingAddr) {
6377 if (FullLeadingAddr) {
6378 if (MachOOF->is64Bit())
6379 outs() << format("%016" PRIx64, PC);
6380 else
6381 outs() << format("%08" PRIx64, PC);
6382 } else {
6383 outs() << format("%8" PRIx64 ":", PC);
6384 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006385 }
6386 if (!NoShowRawInsn) {
6387 outs() << "\t";
Craig Topper0013be12015-09-21 05:32:41 +00006388 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006389 }
Akira Hatanaka1d079942015-03-28 20:44:05 +00006390 IP->printInst(&Inst, outs(), "", *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00006391 outs() << "\n";
6392 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006393 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006394 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006395 outs() << format("\t.byte 0x%02x #bad opcode\n",
6396 *(Bytes.data() + Index) & 0xff);
6397 InstSize = 1; // skip exactly one illegible byte and move on.
6398 } else {
6399 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6400 if (InstSize == 0)
6401 InstSize = 1; // skip illegible bytes
6402 }
Bill Wendling4e68e062012-07-19 00:17:40 +00006403 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00006404 }
6405 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006406 // The TripleName's need to be reset if we are called again for a different
6407 // archtecture.
6408 TripleName = "";
6409 ThumbTripleName = "";
6410
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006411 if (SymbolizerInfo.method != nullptr)
6412 free(SymbolizerInfo.method);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006413 if (SymbolizerInfo.demangled_name != nullptr)
6414 free(SymbolizerInfo.demangled_name);
Kevin Enderby078be602014-10-23 19:53:12 +00006415 if (SymbolizerInfo.bindtable != nullptr)
6416 delete SymbolizerInfo.bindtable;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006417 if (ThumbSymbolizerInfo.method != nullptr)
6418 free(ThumbSymbolizerInfo.method);
6419 if (ThumbSymbolizerInfo.demangled_name != nullptr)
6420 free(ThumbSymbolizerInfo.demangled_name);
6421 if (ThumbSymbolizerInfo.bindtable != nullptr)
6422 delete ThumbSymbolizerInfo.bindtable;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006423 }
6424}
Tim Northover4bd286a2014-08-01 13:07:19 +00006425
Tim Northover39c70bb2014-08-12 11:52:59 +00006426//===----------------------------------------------------------------------===//
6427// __compact_unwind section dumping
6428//===----------------------------------------------------------------------===//
6429
Tim Northover4bd286a2014-08-01 13:07:19 +00006430namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00006431
6432template <typename T> static uint64_t readNext(const char *&Buf) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006433 using llvm::support::little;
6434 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00006435
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006436 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
6437 Buf += sizeof(T);
6438 return Val;
6439}
Tim Northover39c70bb2014-08-12 11:52:59 +00006440
Tim Northover4bd286a2014-08-01 13:07:19 +00006441struct CompactUnwindEntry {
6442 uint32_t OffsetInSection;
6443
6444 uint64_t FunctionAddr;
6445 uint32_t Length;
6446 uint32_t CompactEncoding;
6447 uint64_t PersonalityAddr;
6448 uint64_t LSDAAddr;
6449
6450 RelocationRef FunctionReloc;
6451 RelocationRef PersonalityReloc;
6452 RelocationRef LSDAReloc;
6453
6454 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006455 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006456 if (Is64)
6457 read<uint64_t>(Contents.data() + Offset);
6458 else
6459 read<uint32_t>(Contents.data() + Offset);
6460 }
6461
6462private:
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006463 template <typename UIntPtr> void read(const char *Buf) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006464 FunctionAddr = readNext<UIntPtr>(Buf);
6465 Length = readNext<uint32_t>(Buf);
6466 CompactEncoding = readNext<uint32_t>(Buf);
6467 PersonalityAddr = readNext<UIntPtr>(Buf);
6468 LSDAAddr = readNext<UIntPtr>(Buf);
6469 }
6470};
6471}
6472
6473/// Given a relocation from __compact_unwind, consisting of the RelocationRef
6474/// and data being relocated, determine the best base Name and Addend to use for
6475/// display purposes.
6476///
6477/// 1. An Extern relocation will directly reference a symbol (and the data is
6478/// then already an addend), so use that.
6479/// 2. Otherwise the data is an offset in the object file's layout; try to find
6480// a symbol before it in the same section, and use the offset from there.
6481/// 3. Finally, if all that fails, fall back to an offset from the start of the
6482/// referenced section.
6483static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
6484 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006485 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00006486 StringRef &Name, uint64_t &Addend) {
6487 if (Reloc.getSymbol() != Obj->symbol_end()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006488 Expected<StringRef> NameOrErr = Reloc.getSymbol()->getName();
6489 if (!NameOrErr) {
6490 std::string Buf;
6491 raw_string_ostream OS(Buf);
6492 logAllUnhandledErrors(NameOrErr.takeError(), OS, "");
6493 OS.flush();
6494 report_fatal_error(Buf);
6495 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006496 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00006497 Addend = Addr;
6498 return;
6499 }
6500
6501 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
Keno Fischerc780e8e2015-05-21 21:24:32 +00006502 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
Tim Northover4bd286a2014-08-01 13:07:19 +00006503
Rafael Espindola80291272014-10-08 15:28:58 +00006504 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00006505
6506 auto Sym = Symbols.upper_bound(Addr);
6507 if (Sym == Symbols.begin()) {
6508 // The first symbol in the object is after this reference, the best we can
6509 // do is section-relative notation.
6510 RelocSection.getName(Name);
6511 Addend = Addr - SectionAddr;
6512 return;
6513 }
6514
6515 // Go back one so that SymbolAddress <= Addr.
6516 --Sym;
6517
Rafael Espindola8bab8892015-08-07 23:27:14 +00006518 section_iterator SymSection = *Sym->second.getSection();
Tim Northover4bd286a2014-08-01 13:07:19 +00006519 if (RelocSection == *SymSection) {
6520 // There's a valid symbol in the same section before this reference.
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006521 Expected<StringRef> NameOrErr = Sym->second.getName();
6522 if (!NameOrErr) {
6523 std::string Buf;
6524 raw_string_ostream OS(Buf);
6525 logAllUnhandledErrors(NameOrErr.takeError(), OS, "");
6526 OS.flush();
6527 report_fatal_error(Buf);
6528 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006529 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00006530 Addend = Addr - Sym->first;
6531 return;
6532 }
6533
6534 // There is a symbol before this reference, but it's in a different
6535 // section. Probably not helpful to mention it, so use the section name.
6536 RelocSection.getName(Name);
6537 Addend = Addr - SectionAddr;
6538}
6539
6540static void printUnwindRelocDest(const MachOObjectFile *Obj,
6541 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006542 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006543 StringRef Name;
6544 uint64_t Addend;
6545
Rafael Espindola854038e2015-06-26 14:51:16 +00006546 if (!Reloc.getObject())
Tim Northover0b0add52014-09-09 10:45:06 +00006547 return;
6548
Tim Northover4bd286a2014-08-01 13:07:19 +00006549 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
6550
6551 outs() << Name;
6552 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00006553 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00006554}
6555
6556static void
6557printMachOCompactUnwindSection(const MachOObjectFile *Obj,
6558 std::map<uint64_t, SymbolRef> &Symbols,
6559 const SectionRef &CompactUnwind) {
6560
6561 assert(Obj->isLittleEndian() &&
6562 "There should not be a big-endian .o with __compact_unwind");
6563
6564 bool Is64 = Obj->is64Bit();
6565 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
6566 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
6567
6568 StringRef Contents;
6569 CompactUnwind.getContents(Contents);
6570
6571 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
6572
6573 // First populate the initial raw offsets, encodings and so on from the entry.
6574 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
6575 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
6576 CompactUnwinds.push_back(Entry);
6577 }
6578
6579 // Next we need to look at the relocations to find out what objects are
6580 // actually being referred to.
6581 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00006582 uint64_t RelocAddress = Reloc.getOffset();
Tim Northover4bd286a2014-08-01 13:07:19 +00006583
6584 uint32_t EntryIdx = RelocAddress / EntrySize;
6585 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
6586 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
6587
6588 if (OffsetInEntry == 0)
6589 Entry.FunctionReloc = Reloc;
6590 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
6591 Entry.PersonalityReloc = Reloc;
6592 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
6593 Entry.LSDAReloc = Reloc;
6594 else
6595 llvm_unreachable("Unexpected relocation in __compact_unwind section");
6596 }
6597
6598 // Finally, we're ready to print the data we've gathered.
6599 outs() << "Contents of __compact_unwind section:\n";
6600 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00006601 outs() << " Entry at offset "
6602 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00006603
6604 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006605 outs() << " start: " << format("0x%" PRIx64,
6606 Entry.FunctionAddr) << ' ';
6607 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00006608 outs() << '\n';
6609
6610 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006611 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
6612 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00006613 // 3. The 32-bit compact encoding.
6614 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00006615 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00006616
6617 // 4. The personality function, if present.
Rafael Espindola854038e2015-06-26 14:51:16 +00006618 if (Entry.PersonalityReloc.getObject()) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006619 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00006620 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00006621 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
6622 Entry.PersonalityAddr);
6623 outs() << '\n';
6624 }
6625
6626 // 5. This entry's language-specific data area.
Rafael Espindola854038e2015-06-26 14:51:16 +00006627 if (Entry.LSDAReloc.getObject()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006628 outs() << " LSDA: " << format("0x%" PRIx64,
6629 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00006630 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
6631 outs() << '\n';
6632 }
6633 }
6634}
6635
Tim Northover39c70bb2014-08-12 11:52:59 +00006636//===----------------------------------------------------------------------===//
6637// __unwind_info section dumping
6638//===----------------------------------------------------------------------===//
6639
6640static void printRegularSecondLevelUnwindPage(const char *PageStart) {
6641 const char *Pos = PageStart;
6642 uint32_t Kind = readNext<uint32_t>(Pos);
6643 (void)Kind;
6644 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
6645
6646 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6647 uint16_t NumEntries = readNext<uint16_t>(Pos);
6648
6649 Pos = PageStart + EntriesStart;
6650 for (unsigned i = 0; i < NumEntries; ++i) {
6651 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6652 uint32_t Encoding = readNext<uint32_t>(Pos);
6653
6654 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006655 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6656 << ", "
6657 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006658 }
6659}
6660
6661static void printCompressedSecondLevelUnwindPage(
6662 const char *PageStart, uint32_t FunctionBase,
6663 const SmallVectorImpl<uint32_t> &CommonEncodings) {
6664 const char *Pos = PageStart;
6665 uint32_t Kind = readNext<uint32_t>(Pos);
6666 (void)Kind;
6667 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
6668
6669 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6670 uint16_t NumEntries = readNext<uint16_t>(Pos);
6671
6672 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
6673 readNext<uint16_t>(Pos);
Aaron Ballman80930af2014-08-14 13:53:19 +00006674 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
6675 PageStart + EncodingsStart);
Tim Northover39c70bb2014-08-12 11:52:59 +00006676
6677 Pos = PageStart + EntriesStart;
6678 for (unsigned i = 0; i < NumEntries; ++i) {
6679 uint32_t Entry = readNext<uint32_t>(Pos);
6680 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
6681 uint32_t EncodingIdx = Entry >> 24;
6682
6683 uint32_t Encoding;
6684 if (EncodingIdx < CommonEncodings.size())
6685 Encoding = CommonEncodings[EncodingIdx];
6686 else
6687 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
6688
6689 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006690 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6691 << ", "
6692 << "encoding[" << EncodingIdx
6693 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006694 }
6695}
6696
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006697static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
6698 std::map<uint64_t, SymbolRef> &Symbols,
6699 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00006700
6701 assert(Obj->isLittleEndian() &&
6702 "There should not be a big-endian .o with __unwind_info");
6703
6704 outs() << "Contents of __unwind_info section:\n";
6705
6706 StringRef Contents;
6707 UnwindInfo.getContents(Contents);
6708 const char *Pos = Contents.data();
6709
6710 //===----------------------------------
6711 // Section header
6712 //===----------------------------------
6713
6714 uint32_t Version = readNext<uint32_t>(Pos);
6715 outs() << " Version: "
6716 << format("0x%" PRIx32, Version) << '\n';
6717 assert(Version == 1 && "only understand version 1");
6718
6719 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
6720 outs() << " Common encodings array section offset: "
6721 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
6722 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
6723 outs() << " Number of common encodings in array: "
6724 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
6725
6726 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
6727 outs() << " Personality function array section offset: "
6728 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
6729 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
6730 outs() << " Number of personality functions in array: "
6731 << format("0x%" PRIx32, NumPersonalities) << '\n';
6732
6733 uint32_t IndicesStart = readNext<uint32_t>(Pos);
6734 outs() << " Index array section offset: "
6735 << format("0x%" PRIx32, IndicesStart) << '\n';
6736 uint32_t NumIndices = readNext<uint32_t>(Pos);
6737 outs() << " Number of indices in array: "
6738 << format("0x%" PRIx32, NumIndices) << '\n';
6739
6740 //===----------------------------------
6741 // A shared list of common encodings
6742 //===----------------------------------
6743
6744 // These occupy indices in the range [0, N] whenever an encoding is referenced
6745 // from a compressed 2nd level index table. In practice the linker only
6746 // creates ~128 of these, so that indices are available to embed encodings in
6747 // the 2nd level index.
6748
6749 SmallVector<uint32_t, 64> CommonEncodings;
6750 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
6751 Pos = Contents.data() + CommonEncodingsStart;
6752 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
6753 uint32_t Encoding = readNext<uint32_t>(Pos);
6754 CommonEncodings.push_back(Encoding);
6755
6756 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
6757 << '\n';
6758 }
6759
Tim Northover39c70bb2014-08-12 11:52:59 +00006760 //===----------------------------------
6761 // Personality functions used in this executable
6762 //===----------------------------------
6763
6764 // There should be only a handful of these (one per source language,
6765 // roughly). Particularly since they only get 2 bits in the compact encoding.
6766
6767 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
6768 Pos = Contents.data() + PersonalitiesStart;
6769 for (unsigned i = 0; i < NumPersonalities; ++i) {
6770 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
6771 outs() << " personality[" << i + 1
6772 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
6773 }
6774
6775 //===----------------------------------
6776 // The level 1 index entries
6777 //===----------------------------------
6778
6779 // These specify an approximate place to start searching for the more detailed
6780 // information, sorted by PC.
6781
6782 struct IndexEntry {
6783 uint32_t FunctionOffset;
6784 uint32_t SecondLevelPageStart;
6785 uint32_t LSDAStart;
6786 };
6787
6788 SmallVector<IndexEntry, 4> IndexEntries;
6789
6790 outs() << " Top level indices: (count = " << NumIndices << ")\n";
6791 Pos = Contents.data() + IndicesStart;
6792 for (unsigned i = 0; i < NumIndices; ++i) {
6793 IndexEntry Entry;
6794
6795 Entry.FunctionOffset = readNext<uint32_t>(Pos);
6796 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
6797 Entry.LSDAStart = readNext<uint32_t>(Pos);
6798 IndexEntries.push_back(Entry);
6799
6800 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006801 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
6802 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00006803 << "2nd level page offset="
6804 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006805 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006806 }
6807
Tim Northover39c70bb2014-08-12 11:52:59 +00006808 //===----------------------------------
6809 // Next come the LSDA tables
6810 //===----------------------------------
6811
6812 // The LSDA layout is rather implicit: it's a contiguous array of entries from
6813 // the first top-level index's LSDAOffset to the last (sentinel).
6814
6815 outs() << " LSDA descriptors:\n";
6816 Pos = Contents.data() + IndexEntries[0].LSDAStart;
6817 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
6818 (2 * sizeof(uint32_t));
6819 for (int i = 0; i < NumLSDAs; ++i) {
6820 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6821 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
6822 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006823 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6824 << ", "
6825 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006826 }
6827
6828 //===----------------------------------
6829 // Finally, the 2nd level indices
6830 //===----------------------------------
6831
6832 // Generally these are 4K in size, and have 2 possible forms:
6833 // + Regular stores up to 511 entries with disparate encodings
6834 // + Compressed stores up to 1021 entries if few enough compact encoding
6835 // values are used.
6836 outs() << " Second level indices:\n";
6837 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
6838 // The final sentinel top-level index has no associated 2nd level page
6839 if (IndexEntries[i].SecondLevelPageStart == 0)
6840 break;
6841
6842 outs() << " Second level index[" << i << "]: "
6843 << "offset in section="
6844 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
6845 << ", "
6846 << "base function offset="
6847 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
6848
6849 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
Aaron Ballman80930af2014-08-14 13:53:19 +00006850 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00006851 if (Kind == 2)
6852 printRegularSecondLevelUnwindPage(Pos);
6853 else if (Kind == 3)
6854 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
6855 CommonEncodings);
6856 else
6857 llvm_unreachable("Do not know how to print this kind of 2nd level page");
Tim Northover39c70bb2014-08-12 11:52:59 +00006858 }
6859}
6860
Tim Northover4bd286a2014-08-01 13:07:19 +00006861void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
6862 std::map<uint64_t, SymbolRef> Symbols;
6863 for (const SymbolRef &SymRef : Obj->symbols()) {
6864 // Discard any undefined or absolute symbols. They're not going to take part
6865 // in the convenience lookup for unwind info and just take up resources.
Rafael Espindola8bab8892015-08-07 23:27:14 +00006866 section_iterator Section = *SymRef.getSection();
Tim Northover4bd286a2014-08-01 13:07:19 +00006867 if (Section == Obj->section_end())
6868 continue;
6869
Rafael Espindoladea00162015-07-03 17:44:18 +00006870 uint64_t Addr = SymRef.getValue();
Tim Northover4bd286a2014-08-01 13:07:19 +00006871 Symbols.insert(std::make_pair(Addr, SymRef));
6872 }
6873
6874 for (const SectionRef &Section : Obj->sections()) {
6875 StringRef SectName;
6876 Section.getName(SectName);
6877 if (SectName == "__compact_unwind")
6878 printMachOCompactUnwindSection(Obj, Symbols, Section);
6879 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00006880 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00006881 }
6882}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00006883
6884static void PrintMachHeader(uint32_t magic, uint32_t cputype,
6885 uint32_t cpusubtype, uint32_t filetype,
6886 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
6887 bool verbose) {
6888 outs() << "Mach header\n";
6889 outs() << " magic cputype cpusubtype caps filetype ncmds "
6890 "sizeofcmds flags\n";
6891 if (verbose) {
6892 if (magic == MachO::MH_MAGIC)
6893 outs() << " MH_MAGIC";
6894 else if (magic == MachO::MH_MAGIC_64)
6895 outs() << "MH_MAGIC_64";
6896 else
6897 outs() << format(" 0x%08" PRIx32, magic);
6898 switch (cputype) {
6899 case MachO::CPU_TYPE_I386:
6900 outs() << " I386";
6901 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6902 case MachO::CPU_SUBTYPE_I386_ALL:
6903 outs() << " ALL";
6904 break;
6905 default:
6906 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6907 break;
6908 }
6909 break;
6910 case MachO::CPU_TYPE_X86_64:
6911 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00006912 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6913 case MachO::CPU_SUBTYPE_X86_64_ALL:
6914 outs() << " ALL";
6915 break;
6916 case MachO::CPU_SUBTYPE_X86_64_H:
6917 outs() << " Haswell";
6918 break;
6919 default:
6920 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6921 break;
6922 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00006923 break;
6924 case MachO::CPU_TYPE_ARM:
6925 outs() << " ARM";
6926 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6927 case MachO::CPU_SUBTYPE_ARM_ALL:
6928 outs() << " ALL";
6929 break;
6930 case MachO::CPU_SUBTYPE_ARM_V4T:
6931 outs() << " V4T";
6932 break;
6933 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
6934 outs() << " V5TEJ";
6935 break;
6936 case MachO::CPU_SUBTYPE_ARM_XSCALE:
6937 outs() << " XSCALE";
6938 break;
6939 case MachO::CPU_SUBTYPE_ARM_V6:
6940 outs() << " V6";
6941 break;
6942 case MachO::CPU_SUBTYPE_ARM_V6M:
6943 outs() << " V6M";
6944 break;
6945 case MachO::CPU_SUBTYPE_ARM_V7:
6946 outs() << " V7";
6947 break;
6948 case MachO::CPU_SUBTYPE_ARM_V7EM:
6949 outs() << " V7EM";
6950 break;
6951 case MachO::CPU_SUBTYPE_ARM_V7K:
6952 outs() << " V7K";
6953 break;
6954 case MachO::CPU_SUBTYPE_ARM_V7M:
6955 outs() << " V7M";
6956 break;
6957 case MachO::CPU_SUBTYPE_ARM_V7S:
6958 outs() << " V7S";
6959 break;
6960 default:
6961 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6962 break;
6963 }
6964 break;
6965 case MachO::CPU_TYPE_ARM64:
6966 outs() << " ARM64";
6967 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6968 case MachO::CPU_SUBTYPE_ARM64_ALL:
6969 outs() << " ALL";
6970 break;
6971 default:
6972 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6973 break;
6974 }
6975 break;
6976 case MachO::CPU_TYPE_POWERPC:
6977 outs() << " PPC";
6978 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6979 case MachO::CPU_SUBTYPE_POWERPC_ALL:
6980 outs() << " ALL";
6981 break;
6982 default:
6983 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6984 break;
6985 }
6986 break;
6987 case MachO::CPU_TYPE_POWERPC64:
6988 outs() << " PPC64";
6989 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6990 case MachO::CPU_SUBTYPE_POWERPC_ALL:
6991 outs() << " ALL";
6992 break;
6993 default:
6994 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6995 break;
6996 }
6997 break;
Kevin Enderby40fdbf82016-01-26 18:20:49 +00006998 default:
6999 outs() << format(" %7d", cputype);
7000 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7001 break;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007002 }
7003 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007004 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007005 } else {
7006 outs() << format(" 0x%02" PRIx32,
7007 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7008 }
7009 switch (filetype) {
7010 case MachO::MH_OBJECT:
7011 outs() << " OBJECT";
7012 break;
7013 case MachO::MH_EXECUTE:
7014 outs() << " EXECUTE";
7015 break;
7016 case MachO::MH_FVMLIB:
7017 outs() << " FVMLIB";
7018 break;
7019 case MachO::MH_CORE:
7020 outs() << " CORE";
7021 break;
7022 case MachO::MH_PRELOAD:
7023 outs() << " PRELOAD";
7024 break;
7025 case MachO::MH_DYLIB:
7026 outs() << " DYLIB";
7027 break;
7028 case MachO::MH_DYLIB_STUB:
7029 outs() << " DYLIB_STUB";
7030 break;
7031 case MachO::MH_DYLINKER:
7032 outs() << " DYLINKER";
7033 break;
7034 case MachO::MH_BUNDLE:
7035 outs() << " BUNDLE";
7036 break;
7037 case MachO::MH_DSYM:
7038 outs() << " DSYM";
7039 break;
7040 case MachO::MH_KEXT_BUNDLE:
7041 outs() << " KEXTBUNDLE";
7042 break;
7043 default:
7044 outs() << format(" %10u", filetype);
7045 break;
7046 }
7047 outs() << format(" %5u", ncmds);
7048 outs() << format(" %10u", sizeofcmds);
7049 uint32_t f = flags;
7050 if (f & MachO::MH_NOUNDEFS) {
7051 outs() << " NOUNDEFS";
7052 f &= ~MachO::MH_NOUNDEFS;
7053 }
7054 if (f & MachO::MH_INCRLINK) {
7055 outs() << " INCRLINK";
7056 f &= ~MachO::MH_INCRLINK;
7057 }
7058 if (f & MachO::MH_DYLDLINK) {
7059 outs() << " DYLDLINK";
7060 f &= ~MachO::MH_DYLDLINK;
7061 }
7062 if (f & MachO::MH_BINDATLOAD) {
7063 outs() << " BINDATLOAD";
7064 f &= ~MachO::MH_BINDATLOAD;
7065 }
7066 if (f & MachO::MH_PREBOUND) {
7067 outs() << " PREBOUND";
7068 f &= ~MachO::MH_PREBOUND;
7069 }
7070 if (f & MachO::MH_SPLIT_SEGS) {
7071 outs() << " SPLIT_SEGS";
7072 f &= ~MachO::MH_SPLIT_SEGS;
7073 }
7074 if (f & MachO::MH_LAZY_INIT) {
7075 outs() << " LAZY_INIT";
7076 f &= ~MachO::MH_LAZY_INIT;
7077 }
7078 if (f & MachO::MH_TWOLEVEL) {
7079 outs() << " TWOLEVEL";
7080 f &= ~MachO::MH_TWOLEVEL;
7081 }
7082 if (f & MachO::MH_FORCE_FLAT) {
7083 outs() << " FORCE_FLAT";
7084 f &= ~MachO::MH_FORCE_FLAT;
7085 }
7086 if (f & MachO::MH_NOMULTIDEFS) {
7087 outs() << " NOMULTIDEFS";
7088 f &= ~MachO::MH_NOMULTIDEFS;
7089 }
7090 if (f & MachO::MH_NOFIXPREBINDING) {
7091 outs() << " NOFIXPREBINDING";
7092 f &= ~MachO::MH_NOFIXPREBINDING;
7093 }
7094 if (f & MachO::MH_PREBINDABLE) {
7095 outs() << " PREBINDABLE";
7096 f &= ~MachO::MH_PREBINDABLE;
7097 }
7098 if (f & MachO::MH_ALLMODSBOUND) {
7099 outs() << " ALLMODSBOUND";
7100 f &= ~MachO::MH_ALLMODSBOUND;
7101 }
7102 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
7103 outs() << " SUBSECTIONS_VIA_SYMBOLS";
7104 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
7105 }
7106 if (f & MachO::MH_CANONICAL) {
7107 outs() << " CANONICAL";
7108 f &= ~MachO::MH_CANONICAL;
7109 }
7110 if (f & MachO::MH_WEAK_DEFINES) {
7111 outs() << " WEAK_DEFINES";
7112 f &= ~MachO::MH_WEAK_DEFINES;
7113 }
7114 if (f & MachO::MH_BINDS_TO_WEAK) {
7115 outs() << " BINDS_TO_WEAK";
7116 f &= ~MachO::MH_BINDS_TO_WEAK;
7117 }
7118 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
7119 outs() << " ALLOW_STACK_EXECUTION";
7120 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
7121 }
7122 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
7123 outs() << " DEAD_STRIPPABLE_DYLIB";
7124 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
7125 }
7126 if (f & MachO::MH_PIE) {
7127 outs() << " PIE";
7128 f &= ~MachO::MH_PIE;
7129 }
7130 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
7131 outs() << " NO_REEXPORTED_DYLIBS";
7132 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
7133 }
7134 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
7135 outs() << " MH_HAS_TLV_DESCRIPTORS";
7136 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
7137 }
7138 if (f & MachO::MH_NO_HEAP_EXECUTION) {
7139 outs() << " MH_NO_HEAP_EXECUTION";
7140 f &= ~MachO::MH_NO_HEAP_EXECUTION;
7141 }
7142 if (f & MachO::MH_APP_EXTENSION_SAFE) {
7143 outs() << " APP_EXTENSION_SAFE";
7144 f &= ~MachO::MH_APP_EXTENSION_SAFE;
7145 }
7146 if (f != 0 || flags == 0)
7147 outs() << format(" 0x%08" PRIx32, f);
7148 } else {
7149 outs() << format(" 0x%08" PRIx32, magic);
7150 outs() << format(" %7d", cputype);
7151 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7152 outs() << format(" 0x%02" PRIx32,
7153 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7154 outs() << format(" %10u", filetype);
7155 outs() << format(" %5u", ncmds);
7156 outs() << format(" %10u", sizeofcmds);
7157 outs() << format(" 0x%08" PRIx32, flags);
7158 }
7159 outs() << "\n";
7160}
7161
Kevin Enderby956366c2014-08-29 22:30:52 +00007162static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
7163 StringRef SegName, uint64_t vmaddr,
7164 uint64_t vmsize, uint64_t fileoff,
7165 uint64_t filesize, uint32_t maxprot,
7166 uint32_t initprot, uint32_t nsects,
7167 uint32_t flags, uint32_t object_size,
7168 bool verbose) {
7169 uint64_t expected_cmdsize;
7170 if (cmd == MachO::LC_SEGMENT) {
7171 outs() << " cmd LC_SEGMENT\n";
7172 expected_cmdsize = nsects;
7173 expected_cmdsize *= sizeof(struct MachO::section);
7174 expected_cmdsize += sizeof(struct MachO::segment_command);
7175 } else {
7176 outs() << " cmd LC_SEGMENT_64\n";
7177 expected_cmdsize = nsects;
7178 expected_cmdsize *= sizeof(struct MachO::section_64);
7179 expected_cmdsize += sizeof(struct MachO::segment_command_64);
7180 }
7181 outs() << " cmdsize " << cmdsize;
7182 if (cmdsize != expected_cmdsize)
7183 outs() << " Inconsistent size\n";
7184 else
7185 outs() << "\n";
7186 outs() << " segname " << SegName << "\n";
7187 if (cmd == MachO::LC_SEGMENT_64) {
7188 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
7189 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
7190 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00007191 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
7192 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00007193 }
7194 outs() << " fileoff " << fileoff;
7195 if (fileoff > object_size)
7196 outs() << " (past end of file)\n";
7197 else
7198 outs() << "\n";
7199 outs() << " filesize " << filesize;
7200 if (fileoff + filesize > object_size)
7201 outs() << " (past end of file)\n";
7202 else
7203 outs() << "\n";
7204 if (verbose) {
7205 if ((maxprot &
7206 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7207 MachO::VM_PROT_EXECUTE)) != 0)
7208 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
7209 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00007210 outs() << " maxprot ";
7211 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
7212 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7213 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007214 }
7215 if ((initprot &
7216 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7217 MachO::VM_PROT_EXECUTE)) != 0)
7218 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
7219 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00007220 outs() << " initprot ";
7221 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
7222 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7223 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007224 }
7225 } else {
7226 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
7227 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
7228 }
7229 outs() << " nsects " << nsects << "\n";
7230 if (verbose) {
7231 outs() << " flags";
7232 if (flags == 0)
7233 outs() << " (none)\n";
7234 else {
7235 if (flags & MachO::SG_HIGHVM) {
7236 outs() << " HIGHVM";
7237 flags &= ~MachO::SG_HIGHVM;
7238 }
7239 if (flags & MachO::SG_FVMLIB) {
7240 outs() << " FVMLIB";
7241 flags &= ~MachO::SG_FVMLIB;
7242 }
7243 if (flags & MachO::SG_NORELOC) {
7244 outs() << " NORELOC";
7245 flags &= ~MachO::SG_NORELOC;
7246 }
7247 if (flags & MachO::SG_PROTECTED_VERSION_1) {
7248 outs() << " PROTECTED_VERSION_1";
7249 flags &= ~MachO::SG_PROTECTED_VERSION_1;
7250 }
7251 if (flags)
7252 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
7253 else
7254 outs() << "\n";
7255 }
7256 } else {
7257 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
7258 }
7259}
7260
7261static void PrintSection(const char *sectname, const char *segname,
7262 uint64_t addr, uint64_t size, uint32_t offset,
7263 uint32_t align, uint32_t reloff, uint32_t nreloc,
7264 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
7265 uint32_t cmd, const char *sg_segname,
7266 uint32_t filetype, uint32_t object_size,
7267 bool verbose) {
7268 outs() << "Section\n";
7269 outs() << " sectname " << format("%.16s\n", sectname);
7270 outs() << " segname " << format("%.16s", segname);
7271 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
7272 outs() << " (does not match segment)\n";
7273 else
7274 outs() << "\n";
7275 if (cmd == MachO::LC_SEGMENT_64) {
7276 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
7277 outs() << " size " << format("0x%016" PRIx64, size);
7278 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00007279 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
7280 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00007281 }
7282 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
7283 outs() << " (past end of file)\n";
7284 else
7285 outs() << "\n";
7286 outs() << " offset " << offset;
7287 if (offset > object_size)
7288 outs() << " (past end of file)\n";
7289 else
7290 outs() << "\n";
7291 uint32_t align_shifted = 1 << align;
7292 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
7293 outs() << " reloff " << reloff;
7294 if (reloff > object_size)
7295 outs() << " (past end of file)\n";
7296 else
7297 outs() << "\n";
7298 outs() << " nreloc " << nreloc;
7299 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
7300 outs() << " (past end of file)\n";
7301 else
7302 outs() << "\n";
7303 uint32_t section_type = flags & MachO::SECTION_TYPE;
7304 if (verbose) {
7305 outs() << " type";
7306 if (section_type == MachO::S_REGULAR)
7307 outs() << " S_REGULAR\n";
7308 else if (section_type == MachO::S_ZEROFILL)
7309 outs() << " S_ZEROFILL\n";
7310 else if (section_type == MachO::S_CSTRING_LITERALS)
7311 outs() << " S_CSTRING_LITERALS\n";
7312 else if (section_type == MachO::S_4BYTE_LITERALS)
7313 outs() << " S_4BYTE_LITERALS\n";
7314 else if (section_type == MachO::S_8BYTE_LITERALS)
7315 outs() << " S_8BYTE_LITERALS\n";
7316 else if (section_type == MachO::S_16BYTE_LITERALS)
7317 outs() << " S_16BYTE_LITERALS\n";
7318 else if (section_type == MachO::S_LITERAL_POINTERS)
7319 outs() << " S_LITERAL_POINTERS\n";
7320 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
7321 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
7322 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
7323 outs() << " S_LAZY_SYMBOL_POINTERS\n";
7324 else if (section_type == MachO::S_SYMBOL_STUBS)
7325 outs() << " S_SYMBOL_STUBS\n";
7326 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
7327 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
7328 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
7329 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
7330 else if (section_type == MachO::S_COALESCED)
7331 outs() << " S_COALESCED\n";
7332 else if (section_type == MachO::S_INTERPOSING)
7333 outs() << " S_INTERPOSING\n";
7334 else if (section_type == MachO::S_DTRACE_DOF)
7335 outs() << " S_DTRACE_DOF\n";
7336 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
7337 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
7338 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
7339 outs() << " S_THREAD_LOCAL_REGULAR\n";
7340 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
7341 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
7342 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
7343 outs() << " S_THREAD_LOCAL_VARIABLES\n";
7344 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7345 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
7346 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
7347 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
7348 else
7349 outs() << format("0x%08" PRIx32, section_type) << "\n";
7350 outs() << "attributes";
7351 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
7352 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
7353 outs() << " PURE_INSTRUCTIONS";
7354 if (section_attributes & MachO::S_ATTR_NO_TOC)
7355 outs() << " NO_TOC";
7356 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
7357 outs() << " STRIP_STATIC_SYMS";
7358 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
7359 outs() << " NO_DEAD_STRIP";
7360 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
7361 outs() << " LIVE_SUPPORT";
7362 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
7363 outs() << " SELF_MODIFYING_CODE";
7364 if (section_attributes & MachO::S_ATTR_DEBUG)
7365 outs() << " DEBUG";
7366 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
7367 outs() << " SOME_INSTRUCTIONS";
7368 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
7369 outs() << " EXT_RELOC";
7370 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
7371 outs() << " LOC_RELOC";
7372 if (section_attributes == 0)
7373 outs() << " (none)";
7374 outs() << "\n";
7375 } else
7376 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
7377 outs() << " reserved1 " << reserved1;
7378 if (section_type == MachO::S_SYMBOL_STUBS ||
7379 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
7380 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
7381 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
7382 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7383 outs() << " (index into indirect symbol table)\n";
7384 else
7385 outs() << "\n";
7386 outs() << " reserved2 " << reserved2;
7387 if (section_type == MachO::S_SYMBOL_STUBS)
7388 outs() << " (size of stubs)\n";
7389 else
7390 outs() << "\n";
7391}
7392
David Majnemer73cc6ff2014-11-13 19:48:56 +00007393static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00007394 uint32_t object_size) {
7395 outs() << " cmd LC_SYMTAB\n";
7396 outs() << " cmdsize " << st.cmdsize;
7397 if (st.cmdsize != sizeof(struct MachO::symtab_command))
7398 outs() << " Incorrect size\n";
7399 else
7400 outs() << "\n";
7401 outs() << " symoff " << st.symoff;
7402 if (st.symoff > object_size)
7403 outs() << " (past end of file)\n";
7404 else
7405 outs() << "\n";
7406 outs() << " nsyms " << st.nsyms;
7407 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00007408 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007409 big_size = st.nsyms;
7410 big_size *= sizeof(struct MachO::nlist_64);
7411 big_size += st.symoff;
7412 if (big_size > object_size)
7413 outs() << " (past end of file)\n";
7414 else
7415 outs() << "\n";
7416 } else {
7417 big_size = st.nsyms;
7418 big_size *= sizeof(struct MachO::nlist);
7419 big_size += st.symoff;
7420 if (big_size > object_size)
7421 outs() << " (past end of file)\n";
7422 else
7423 outs() << "\n";
7424 }
7425 outs() << " stroff " << st.stroff;
7426 if (st.stroff > object_size)
7427 outs() << " (past end of file)\n";
7428 else
7429 outs() << "\n";
7430 outs() << " strsize " << st.strsize;
7431 big_size = st.stroff;
7432 big_size += st.strsize;
7433 if (big_size > object_size)
7434 outs() << " (past end of file)\n";
7435 else
7436 outs() << "\n";
7437}
7438
7439static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
7440 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00007441 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007442 outs() << " cmd LC_DYSYMTAB\n";
7443 outs() << " cmdsize " << dyst.cmdsize;
7444 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
7445 outs() << " Incorrect size\n";
7446 else
7447 outs() << "\n";
7448 outs() << " ilocalsym " << dyst.ilocalsym;
7449 if (dyst.ilocalsym > nsyms)
7450 outs() << " (greater than the number of symbols)\n";
7451 else
7452 outs() << "\n";
7453 outs() << " nlocalsym " << dyst.nlocalsym;
7454 uint64_t big_size;
7455 big_size = dyst.ilocalsym;
7456 big_size += dyst.nlocalsym;
7457 if (big_size > nsyms)
7458 outs() << " (past the end of the symbol table)\n";
7459 else
7460 outs() << "\n";
7461 outs() << " iextdefsym " << dyst.iextdefsym;
7462 if (dyst.iextdefsym > nsyms)
7463 outs() << " (greater than the number of symbols)\n";
7464 else
7465 outs() << "\n";
7466 outs() << " nextdefsym " << dyst.nextdefsym;
7467 big_size = dyst.iextdefsym;
7468 big_size += dyst.nextdefsym;
7469 if (big_size > nsyms)
7470 outs() << " (past the end of the symbol table)\n";
7471 else
7472 outs() << "\n";
7473 outs() << " iundefsym " << dyst.iundefsym;
7474 if (dyst.iundefsym > nsyms)
7475 outs() << " (greater than the number of symbols)\n";
7476 else
7477 outs() << "\n";
7478 outs() << " nundefsym " << dyst.nundefsym;
7479 big_size = dyst.iundefsym;
7480 big_size += dyst.nundefsym;
7481 if (big_size > nsyms)
7482 outs() << " (past the end of the symbol table)\n";
7483 else
7484 outs() << "\n";
7485 outs() << " tocoff " << dyst.tocoff;
7486 if (dyst.tocoff > object_size)
7487 outs() << " (past end of file)\n";
7488 else
7489 outs() << "\n";
7490 outs() << " ntoc " << dyst.ntoc;
7491 big_size = dyst.ntoc;
7492 big_size *= sizeof(struct MachO::dylib_table_of_contents);
7493 big_size += dyst.tocoff;
7494 if (big_size > object_size)
7495 outs() << " (past end of file)\n";
7496 else
7497 outs() << "\n";
7498 outs() << " modtaboff " << dyst.modtaboff;
7499 if (dyst.modtaboff > object_size)
7500 outs() << " (past end of file)\n";
7501 else
7502 outs() << "\n";
7503 outs() << " nmodtab " << dyst.nmodtab;
7504 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00007505 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007506 modtabend = dyst.nmodtab;
7507 modtabend *= sizeof(struct MachO::dylib_module_64);
7508 modtabend += dyst.modtaboff;
7509 } else {
7510 modtabend = dyst.nmodtab;
7511 modtabend *= sizeof(struct MachO::dylib_module);
7512 modtabend += dyst.modtaboff;
7513 }
7514 if (modtabend > object_size)
7515 outs() << " (past end of file)\n";
7516 else
7517 outs() << "\n";
7518 outs() << " extrefsymoff " << dyst.extrefsymoff;
7519 if (dyst.extrefsymoff > object_size)
7520 outs() << " (past end of file)\n";
7521 else
7522 outs() << "\n";
7523 outs() << " nextrefsyms " << dyst.nextrefsyms;
7524 big_size = dyst.nextrefsyms;
7525 big_size *= sizeof(struct MachO::dylib_reference);
7526 big_size += dyst.extrefsymoff;
7527 if (big_size > object_size)
7528 outs() << " (past end of file)\n";
7529 else
7530 outs() << "\n";
7531 outs() << " indirectsymoff " << dyst.indirectsymoff;
7532 if (dyst.indirectsymoff > object_size)
7533 outs() << " (past end of file)\n";
7534 else
7535 outs() << "\n";
7536 outs() << " nindirectsyms " << dyst.nindirectsyms;
7537 big_size = dyst.nindirectsyms;
7538 big_size *= sizeof(uint32_t);
7539 big_size += dyst.indirectsymoff;
7540 if (big_size > object_size)
7541 outs() << " (past end of file)\n";
7542 else
7543 outs() << "\n";
7544 outs() << " extreloff " << dyst.extreloff;
7545 if (dyst.extreloff > object_size)
7546 outs() << " (past end of file)\n";
7547 else
7548 outs() << "\n";
7549 outs() << " nextrel " << dyst.nextrel;
7550 big_size = dyst.nextrel;
7551 big_size *= sizeof(struct MachO::relocation_info);
7552 big_size += dyst.extreloff;
7553 if (big_size > object_size)
7554 outs() << " (past end of file)\n";
7555 else
7556 outs() << "\n";
7557 outs() << " locreloff " << dyst.locreloff;
7558 if (dyst.locreloff > object_size)
7559 outs() << " (past end of file)\n";
7560 else
7561 outs() << "\n";
7562 outs() << " nlocrel " << dyst.nlocrel;
7563 big_size = dyst.nlocrel;
7564 big_size *= sizeof(struct MachO::relocation_info);
7565 big_size += dyst.locreloff;
7566 if (big_size > object_size)
7567 outs() << " (past end of file)\n";
7568 else
7569 outs() << "\n";
7570}
7571
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007572static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
7573 uint32_t object_size) {
7574 if (dc.cmd == MachO::LC_DYLD_INFO)
7575 outs() << " cmd LC_DYLD_INFO\n";
7576 else
7577 outs() << " cmd LC_DYLD_INFO_ONLY\n";
7578 outs() << " cmdsize " << dc.cmdsize;
7579 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
7580 outs() << " Incorrect size\n";
7581 else
7582 outs() << "\n";
7583 outs() << " rebase_off " << dc.rebase_off;
7584 if (dc.rebase_off > object_size)
7585 outs() << " (past end of file)\n";
7586 else
7587 outs() << "\n";
7588 outs() << " rebase_size " << dc.rebase_size;
7589 uint64_t big_size;
7590 big_size = dc.rebase_off;
7591 big_size += dc.rebase_size;
7592 if (big_size > object_size)
7593 outs() << " (past end of file)\n";
7594 else
7595 outs() << "\n";
7596 outs() << " bind_off " << dc.bind_off;
7597 if (dc.bind_off > object_size)
7598 outs() << " (past end of file)\n";
7599 else
7600 outs() << "\n";
7601 outs() << " bind_size " << dc.bind_size;
7602 big_size = dc.bind_off;
7603 big_size += dc.bind_size;
7604 if (big_size > object_size)
7605 outs() << " (past end of file)\n";
7606 else
7607 outs() << "\n";
7608 outs() << " weak_bind_off " << dc.weak_bind_off;
7609 if (dc.weak_bind_off > object_size)
7610 outs() << " (past end of file)\n";
7611 else
7612 outs() << "\n";
7613 outs() << " weak_bind_size " << dc.weak_bind_size;
7614 big_size = dc.weak_bind_off;
7615 big_size += dc.weak_bind_size;
7616 if (big_size > object_size)
7617 outs() << " (past end of file)\n";
7618 else
7619 outs() << "\n";
7620 outs() << " lazy_bind_off " << dc.lazy_bind_off;
7621 if (dc.lazy_bind_off > object_size)
7622 outs() << " (past end of file)\n";
7623 else
7624 outs() << "\n";
7625 outs() << " lazy_bind_size " << dc.lazy_bind_size;
7626 big_size = dc.lazy_bind_off;
7627 big_size += dc.lazy_bind_size;
7628 if (big_size > object_size)
7629 outs() << " (past end of file)\n";
7630 else
7631 outs() << "\n";
7632 outs() << " export_off " << dc.export_off;
7633 if (dc.export_off > object_size)
7634 outs() << " (past end of file)\n";
7635 else
7636 outs() << "\n";
7637 outs() << " export_size " << dc.export_size;
7638 big_size = dc.export_off;
7639 big_size += dc.export_size;
7640 if (big_size > object_size)
7641 outs() << " (past end of file)\n";
7642 else
7643 outs() << "\n";
7644}
7645
7646static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
7647 const char *Ptr) {
7648 if (dyld.cmd == MachO::LC_ID_DYLINKER)
7649 outs() << " cmd LC_ID_DYLINKER\n";
7650 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
7651 outs() << " cmd LC_LOAD_DYLINKER\n";
7652 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
7653 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
7654 else
7655 outs() << " cmd ?(" << dyld.cmd << ")\n";
7656 outs() << " cmdsize " << dyld.cmdsize;
7657 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
7658 outs() << " Incorrect size\n";
7659 else
7660 outs() << "\n";
7661 if (dyld.name >= dyld.cmdsize)
7662 outs() << " name ?(bad offset " << dyld.name << ")\n";
7663 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007664 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007665 outs() << " name " << P << " (offset " << dyld.name << ")\n";
7666 }
7667}
7668
7669static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
7670 outs() << " cmd LC_UUID\n";
7671 outs() << " cmdsize " << uuid.cmdsize;
7672 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
7673 outs() << " Incorrect size\n";
7674 else
7675 outs() << "\n";
7676 outs() << " uuid ";
Davide Italianoc74277a2015-12-07 00:03:28 +00007677 for (int i = 0; i < 16; ++i) {
7678 outs() << format("%02" PRIX32, uuid.uuid[i]);
7679 if (i == 3 || i == 5 || i == 7 || i == 9)
7680 outs() << "-";
7681 }
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007682 outs() << "\n";
7683}
7684
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007685static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00007686 outs() << " cmd LC_RPATH\n";
7687 outs() << " cmdsize " << rpath.cmdsize;
7688 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
7689 outs() << " Incorrect size\n";
7690 else
7691 outs() << "\n";
7692 if (rpath.path >= rpath.cmdsize)
7693 outs() << " path ?(bad offset " << rpath.path << ")\n";
7694 else {
7695 const char *P = (const char *)(Ptr) + rpath.path;
7696 outs() << " path " << P << " (offset " << rpath.path << ")\n";
7697 }
7698}
7699
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007700static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
Tim Northoverbfbfb122015-11-02 21:26:58 +00007701 StringRef LoadCmdName;
7702 switch (vd.cmd) {
7703 case MachO::LC_VERSION_MIN_MACOSX:
7704 LoadCmdName = "LC_VERSION_MIN_MACOSX";
7705 break;
7706 case MachO::LC_VERSION_MIN_IPHONEOS:
7707 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
7708 break;
7709 case MachO::LC_VERSION_MIN_TVOS:
7710 LoadCmdName = "LC_VERSION_MIN_TVOS";
7711 break;
7712 case MachO::LC_VERSION_MIN_WATCHOS:
7713 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
7714 break;
7715 default:
7716 llvm_unreachable("Unknown version min load command");
7717 }
7718
7719 outs() << " cmd " << LoadCmdName << '\n';
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007720 outs() << " cmdsize " << vd.cmdsize;
7721 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
7722 outs() << " Incorrect size\n";
7723 else
7724 outs() << "\n";
Davide Italiano56baef32015-08-26 12:26:11 +00007725 outs() << " version "
7726 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
7727 << MachOObjectFile::getVersionMinMinor(vd, false);
7728 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
7729 if (Update != 0)
7730 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007731 outs() << "\n";
7732 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00007733 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007734 else {
Davide Italiano56baef32015-08-26 12:26:11 +00007735 outs() << " sdk "
7736 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
7737 << MachOObjectFile::getVersionMinMinor(vd, true);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007738 }
Davide Italiano56baef32015-08-26 12:26:11 +00007739 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
7740 if (Update != 0)
7741 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007742 outs() << "\n";
7743}
7744
7745static void PrintSourceVersionCommand(MachO::source_version_command sd) {
7746 outs() << " cmd LC_SOURCE_VERSION\n";
7747 outs() << " cmdsize " << sd.cmdsize;
7748 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
7749 outs() << " Incorrect size\n";
7750 else
7751 outs() << "\n";
7752 uint64_t a = (sd.version >> 40) & 0xffffff;
7753 uint64_t b = (sd.version >> 30) & 0x3ff;
7754 uint64_t c = (sd.version >> 20) & 0x3ff;
7755 uint64_t d = (sd.version >> 10) & 0x3ff;
7756 uint64_t e = sd.version & 0x3ff;
7757 outs() << " version " << a << "." << b;
7758 if (e != 0)
7759 outs() << "." << c << "." << d << "." << e;
7760 else if (d != 0)
7761 outs() << "." << c << "." << d;
7762 else if (c != 0)
7763 outs() << "." << c;
7764 outs() << "\n";
7765}
7766
7767static void PrintEntryPointCommand(MachO::entry_point_command ep) {
7768 outs() << " cmd LC_MAIN\n";
7769 outs() << " cmdsize " << ep.cmdsize;
7770 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
7771 outs() << " Incorrect size\n";
7772 else
7773 outs() << "\n";
7774 outs() << " entryoff " << ep.entryoff << "\n";
7775 outs() << " stacksize " << ep.stacksize << "\n";
7776}
7777
Kevin Enderby0804f4672014-12-16 23:25:52 +00007778static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
7779 uint32_t object_size) {
7780 outs() << " cmd LC_ENCRYPTION_INFO\n";
7781 outs() << " cmdsize " << ec.cmdsize;
7782 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
7783 outs() << " Incorrect size\n";
7784 else
7785 outs() << "\n";
7786 outs() << " cryptoff " << ec.cryptoff;
7787 if (ec.cryptoff > object_size)
7788 outs() << " (past end of file)\n";
7789 else
7790 outs() << "\n";
7791 outs() << " cryptsize " << ec.cryptsize;
7792 if (ec.cryptsize > object_size)
7793 outs() << " (past end of file)\n";
7794 else
7795 outs() << "\n";
7796 outs() << " cryptid " << ec.cryptid << "\n";
7797}
7798
Kevin Enderby57538292014-12-17 01:01:30 +00007799static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007800 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00007801 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
7802 outs() << " cmdsize " << ec.cmdsize;
7803 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
7804 outs() << " Incorrect size\n";
7805 else
7806 outs() << "\n";
7807 outs() << " cryptoff " << ec.cryptoff;
7808 if (ec.cryptoff > object_size)
7809 outs() << " (past end of file)\n";
7810 else
7811 outs() << "\n";
7812 outs() << " cryptsize " << ec.cryptsize;
7813 if (ec.cryptsize > object_size)
7814 outs() << " (past end of file)\n";
7815 else
7816 outs() << "\n";
7817 outs() << " cryptid " << ec.cryptid << "\n";
7818 outs() << " pad " << ec.pad << "\n";
7819}
7820
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00007821static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
7822 const char *Ptr) {
7823 outs() << " cmd LC_LINKER_OPTION\n";
7824 outs() << " cmdsize " << lo.cmdsize;
7825 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
7826 outs() << " Incorrect size\n";
7827 else
7828 outs() << "\n";
7829 outs() << " count " << lo.count << "\n";
7830 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
7831 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
7832 uint32_t i = 0;
7833 while (left > 0) {
7834 while (*string == '\0' && left > 0) {
7835 string++;
7836 left--;
7837 }
7838 if (left > 0) {
7839 i++;
7840 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00007841 uint32_t NullPos = StringRef(string, left).find('\0');
7842 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00007843 string += len;
7844 left -= len;
7845 }
7846 }
7847 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007848 outs() << " count " << lo.count << " does not match number of strings "
7849 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00007850}
7851
Kevin Enderbyb4b79312014-12-18 19:24:35 +00007852static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
7853 const char *Ptr) {
7854 outs() << " cmd LC_SUB_FRAMEWORK\n";
7855 outs() << " cmdsize " << sub.cmdsize;
7856 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
7857 outs() << " Incorrect size\n";
7858 else
7859 outs() << "\n";
7860 if (sub.umbrella < sub.cmdsize) {
7861 const char *P = Ptr + sub.umbrella;
7862 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
7863 } else {
7864 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
7865 }
7866}
7867
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00007868static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
7869 const char *Ptr) {
7870 outs() << " cmd LC_SUB_UMBRELLA\n";
7871 outs() << " cmdsize " << sub.cmdsize;
7872 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
7873 outs() << " Incorrect size\n";
7874 else
7875 outs() << "\n";
7876 if (sub.sub_umbrella < sub.cmdsize) {
7877 const char *P = Ptr + sub.sub_umbrella;
7878 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
7879 } else {
7880 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
7881 }
7882}
7883
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00007884static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007885 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00007886 outs() << " cmd LC_SUB_LIBRARY\n";
7887 outs() << " cmdsize " << sub.cmdsize;
7888 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
7889 outs() << " Incorrect size\n";
7890 else
7891 outs() << "\n";
7892 if (sub.sub_library < sub.cmdsize) {
7893 const char *P = Ptr + sub.sub_library;
7894 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
7895 } else {
7896 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
7897 }
7898}
7899
Kevin Enderby186eac32014-12-19 21:06:24 +00007900static void PrintSubClientCommand(MachO::sub_client_command sub,
7901 const char *Ptr) {
7902 outs() << " cmd LC_SUB_CLIENT\n";
7903 outs() << " cmdsize " << sub.cmdsize;
7904 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
7905 outs() << " Incorrect size\n";
7906 else
7907 outs() << "\n";
7908 if (sub.client < sub.cmdsize) {
7909 const char *P = Ptr + sub.client;
7910 outs() << " client " << P << " (offset " << sub.client << ")\n";
7911 } else {
7912 outs() << " client ?(bad offset " << sub.client << ")\n";
7913 }
7914}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00007915
Kevin Enderby52e4ce42014-12-19 22:25:22 +00007916static void PrintRoutinesCommand(MachO::routines_command r) {
7917 outs() << " cmd LC_ROUTINES\n";
7918 outs() << " cmdsize " << r.cmdsize;
7919 if (r.cmdsize != sizeof(struct MachO::routines_command))
7920 outs() << " Incorrect size\n";
7921 else
7922 outs() << "\n";
7923 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
7924 outs() << " init_module " << r.init_module << "\n";
7925 outs() << " reserved1 " << r.reserved1 << "\n";
7926 outs() << " reserved2 " << r.reserved2 << "\n";
7927 outs() << " reserved3 " << r.reserved3 << "\n";
7928 outs() << " reserved4 " << r.reserved4 << "\n";
7929 outs() << " reserved5 " << r.reserved5 << "\n";
7930 outs() << " reserved6 " << r.reserved6 << "\n";
7931}
7932
7933static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
7934 outs() << " cmd LC_ROUTINES_64\n";
7935 outs() << " cmdsize " << r.cmdsize;
7936 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
7937 outs() << " Incorrect size\n";
7938 else
7939 outs() << "\n";
7940 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
7941 outs() << " init_module " << r.init_module << "\n";
7942 outs() << " reserved1 " << r.reserved1 << "\n";
7943 outs() << " reserved2 " << r.reserved2 << "\n";
7944 outs() << " reserved3 " << r.reserved3 << "\n";
7945 outs() << " reserved4 " << r.reserved4 << "\n";
7946 outs() << " reserved5 " << r.reserved5 << "\n";
7947 outs() << " reserved6 " << r.reserved6 << "\n";
7948}
7949
Kevin Enderby48ef5342014-12-23 22:56:39 +00007950static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
7951 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
7952 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
7953 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
7954 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
7955 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
7956 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
7957 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
7958 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
7959 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
7960 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
7961 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
7962 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
7963 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
7964 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
7965 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
7966 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
7967 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
7968 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
7969 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
7970 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
7971 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
7972}
7973
Kevin Enderby227df342014-12-23 23:43:59 +00007974static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00007975 uint32_t f;
7976 outs() << "\t mmst_reg ";
7977 for (f = 0; f < 10; f++)
7978 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
7979 outs() << "\n";
7980 outs() << "\t mmst_rsrv ";
7981 for (f = 0; f < 6; f++)
7982 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
7983 outs() << "\n";
7984}
7985
Kevin Enderbyaefb0032014-12-24 00:16:51 +00007986static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00007987 uint32_t f;
7988 outs() << "\t xmm_reg ";
7989 for (f = 0; f < 16; f++)
7990 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
7991 outs() << "\n";
7992}
7993
7994static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
7995 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
7996 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
7997 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
7998 outs() << " denorm " << fpu.fpu_fcw.denorm;
7999 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
8000 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
8001 outs() << " undfl " << fpu.fpu_fcw.undfl;
8002 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
8003 outs() << "\t\t pc ";
8004 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
8005 outs() << "FP_PREC_24B ";
8006 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
8007 outs() << "FP_PREC_53B ";
8008 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
8009 outs() << "FP_PREC_64B ";
8010 else
8011 outs() << fpu.fpu_fcw.pc << " ";
8012 outs() << "rc ";
8013 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
8014 outs() << "FP_RND_NEAR ";
8015 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
8016 outs() << "FP_RND_DOWN ";
8017 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
8018 outs() << "FP_RND_UP ";
8019 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008020 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008021 outs() << "\n";
8022 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
8023 outs() << " denorm " << fpu.fpu_fsw.denorm;
8024 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
8025 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
8026 outs() << " undfl " << fpu.fpu_fsw.undfl;
8027 outs() << " precis " << fpu.fpu_fsw.precis;
8028 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
8029 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
8030 outs() << " c0 " << fpu.fpu_fsw.c0;
8031 outs() << " c1 " << fpu.fpu_fsw.c1;
8032 outs() << " c2 " << fpu.fpu_fsw.c2;
8033 outs() << " tos " << fpu.fpu_fsw.tos;
8034 outs() << " c3 " << fpu.fpu_fsw.c3;
8035 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
8036 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
8037 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
8038 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
8039 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
8040 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
8041 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
8042 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
8043 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
8044 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
8045 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
8046 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
8047 outs() << "\n";
8048 outs() << "\t fpu_stmm0:\n";
8049 Print_mmst_reg(fpu.fpu_stmm0);
8050 outs() << "\t fpu_stmm1:\n";
8051 Print_mmst_reg(fpu.fpu_stmm1);
8052 outs() << "\t fpu_stmm2:\n";
8053 Print_mmst_reg(fpu.fpu_stmm2);
8054 outs() << "\t fpu_stmm3:\n";
8055 Print_mmst_reg(fpu.fpu_stmm3);
8056 outs() << "\t fpu_stmm4:\n";
8057 Print_mmst_reg(fpu.fpu_stmm4);
8058 outs() << "\t fpu_stmm5:\n";
8059 Print_mmst_reg(fpu.fpu_stmm5);
8060 outs() << "\t fpu_stmm6:\n";
8061 Print_mmst_reg(fpu.fpu_stmm6);
8062 outs() << "\t fpu_stmm7:\n";
8063 Print_mmst_reg(fpu.fpu_stmm7);
8064 outs() << "\t fpu_xmm0:\n";
8065 Print_xmm_reg(fpu.fpu_xmm0);
8066 outs() << "\t fpu_xmm1:\n";
8067 Print_xmm_reg(fpu.fpu_xmm1);
8068 outs() << "\t fpu_xmm2:\n";
8069 Print_xmm_reg(fpu.fpu_xmm2);
8070 outs() << "\t fpu_xmm3:\n";
8071 Print_xmm_reg(fpu.fpu_xmm3);
8072 outs() << "\t fpu_xmm4:\n";
8073 Print_xmm_reg(fpu.fpu_xmm4);
8074 outs() << "\t fpu_xmm5:\n";
8075 Print_xmm_reg(fpu.fpu_xmm5);
8076 outs() << "\t fpu_xmm6:\n";
8077 Print_xmm_reg(fpu.fpu_xmm6);
8078 outs() << "\t fpu_xmm7:\n";
8079 Print_xmm_reg(fpu.fpu_xmm7);
8080 outs() << "\t fpu_xmm8:\n";
8081 Print_xmm_reg(fpu.fpu_xmm8);
8082 outs() << "\t fpu_xmm9:\n";
8083 Print_xmm_reg(fpu.fpu_xmm9);
8084 outs() << "\t fpu_xmm10:\n";
8085 Print_xmm_reg(fpu.fpu_xmm10);
8086 outs() << "\t fpu_xmm11:\n";
8087 Print_xmm_reg(fpu.fpu_xmm11);
8088 outs() << "\t fpu_xmm12:\n";
8089 Print_xmm_reg(fpu.fpu_xmm12);
8090 outs() << "\t fpu_xmm13:\n";
8091 Print_xmm_reg(fpu.fpu_xmm13);
8092 outs() << "\t fpu_xmm14:\n";
8093 Print_xmm_reg(fpu.fpu_xmm14);
8094 outs() << "\t fpu_xmm15:\n";
8095 Print_xmm_reg(fpu.fpu_xmm15);
8096 outs() << "\t fpu_rsrv4:\n";
8097 for (uint32_t f = 0; f < 6; f++) {
8098 outs() << "\t ";
8099 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008100 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008101 outs() << "\n";
8102 }
8103 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
8104 outs() << "\n";
8105}
8106
8107static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
8108 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
8109 outs() << " err " << format("0x%08" PRIx32, exc64.err);
8110 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
8111}
8112
8113static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
8114 bool isLittleEndian, uint32_t cputype) {
8115 if (t.cmd == MachO::LC_THREAD)
8116 outs() << " cmd LC_THREAD\n";
8117 else if (t.cmd == MachO::LC_UNIXTHREAD)
8118 outs() << " cmd LC_UNIXTHREAD\n";
8119 else
8120 outs() << " cmd " << t.cmd << " (unknown)\n";
8121 outs() << " cmdsize " << t.cmdsize;
8122 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
8123 outs() << " Incorrect size\n";
8124 else
8125 outs() << "\n";
8126
8127 const char *begin = Ptr + sizeof(struct MachO::thread_command);
8128 const char *end = Ptr + t.cmdsize;
8129 uint32_t flavor, count, left;
8130 if (cputype == MachO::CPU_TYPE_X86_64) {
8131 while (begin < end) {
8132 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8133 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8134 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008135 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008136 flavor = 0;
8137 begin = end;
8138 }
8139 if (isLittleEndian != sys::IsLittleEndianHost)
8140 sys::swapByteOrder(flavor);
8141 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8142 memcpy((char *)&count, begin, sizeof(uint32_t));
8143 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008144 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008145 count = 0;
8146 begin = end;
8147 }
8148 if (isLittleEndian != sys::IsLittleEndianHost)
8149 sys::swapByteOrder(count);
8150 if (flavor == MachO::x86_THREAD_STATE64) {
8151 outs() << " flavor x86_THREAD_STATE64\n";
8152 if (count == MachO::x86_THREAD_STATE64_COUNT)
8153 outs() << " count x86_THREAD_STATE64_COUNT\n";
8154 else
8155 outs() << " count " << count
8156 << " (not x86_THREAD_STATE64_COUNT)\n";
8157 MachO::x86_thread_state64_t cpu64;
8158 left = end - begin;
8159 if (left >= sizeof(MachO::x86_thread_state64_t)) {
8160 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
8161 begin += sizeof(MachO::x86_thread_state64_t);
8162 } else {
8163 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
8164 memcpy(&cpu64, begin, left);
8165 begin += left;
8166 }
8167 if (isLittleEndian != sys::IsLittleEndianHost)
8168 swapStruct(cpu64);
8169 Print_x86_thread_state64_t(cpu64);
8170 } else if (flavor == MachO::x86_THREAD_STATE) {
8171 outs() << " flavor x86_THREAD_STATE\n";
8172 if (count == MachO::x86_THREAD_STATE_COUNT)
8173 outs() << " count x86_THREAD_STATE_COUNT\n";
8174 else
8175 outs() << " count " << count
8176 << " (not x86_THREAD_STATE_COUNT)\n";
8177 struct MachO::x86_thread_state_t ts;
8178 left = end - begin;
8179 if (left >= sizeof(MachO::x86_thread_state_t)) {
8180 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
8181 begin += sizeof(MachO::x86_thread_state_t);
8182 } else {
8183 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
8184 memcpy(&ts, begin, left);
8185 begin += left;
8186 }
8187 if (isLittleEndian != sys::IsLittleEndianHost)
8188 swapStruct(ts);
8189 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
8190 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
8191 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
8192 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
8193 else
8194 outs() << "tsh.count " << ts.tsh.count
8195 << " (not x86_THREAD_STATE64_COUNT\n";
8196 Print_x86_thread_state64_t(ts.uts.ts64);
8197 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008198 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
8199 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008200 }
8201 } else if (flavor == MachO::x86_FLOAT_STATE) {
8202 outs() << " flavor x86_FLOAT_STATE\n";
8203 if (count == MachO::x86_FLOAT_STATE_COUNT)
8204 outs() << " count x86_FLOAT_STATE_COUNT\n";
8205 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008206 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008207 struct MachO::x86_float_state_t fs;
8208 left = end - begin;
8209 if (left >= sizeof(MachO::x86_float_state_t)) {
8210 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
8211 begin += sizeof(MachO::x86_float_state_t);
8212 } else {
8213 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
8214 memcpy(&fs, begin, left);
8215 begin += left;
8216 }
8217 if (isLittleEndian != sys::IsLittleEndianHost)
8218 swapStruct(fs);
8219 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
8220 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008221 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008222 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
8223 else
8224 outs() << "fsh.count " << fs.fsh.count
8225 << " (not x86_FLOAT_STATE64_COUNT\n";
8226 Print_x86_float_state_t(fs.ufs.fs64);
8227 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008228 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
8229 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008230 }
8231 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
8232 outs() << " flavor x86_EXCEPTION_STATE\n";
8233 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
8234 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
8235 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008236 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00008237 << " (not x86_EXCEPTION_STATE_COUNT)\n";
8238 struct MachO::x86_exception_state_t es;
8239 left = end - begin;
8240 if (left >= sizeof(MachO::x86_exception_state_t)) {
8241 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
8242 begin += sizeof(MachO::x86_exception_state_t);
8243 } else {
8244 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
8245 memcpy(&es, begin, left);
8246 begin += left;
8247 }
8248 if (isLittleEndian != sys::IsLittleEndianHost)
8249 swapStruct(es);
8250 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
8251 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008252 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008253 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
8254 else
8255 outs() << "\t esh.count " << es.esh.count
8256 << " (not x86_EXCEPTION_STATE64_COUNT\n";
8257 Print_x86_exception_state_t(es.ues.es64);
8258 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008259 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
8260 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008261 }
8262 } else {
8263 outs() << " flavor " << flavor << " (unknown)\n";
8264 outs() << " count " << count << "\n";
8265 outs() << " state (unknown)\n";
8266 begin += count * sizeof(uint32_t);
8267 }
8268 }
8269 } else {
8270 while (begin < end) {
8271 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8272 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8273 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008274 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008275 flavor = 0;
8276 begin = end;
8277 }
8278 if (isLittleEndian != sys::IsLittleEndianHost)
8279 sys::swapByteOrder(flavor);
8280 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8281 memcpy((char *)&count, begin, sizeof(uint32_t));
8282 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008283 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008284 count = 0;
8285 begin = end;
8286 }
8287 if (isLittleEndian != sys::IsLittleEndianHost)
8288 sys::swapByteOrder(count);
8289 outs() << " flavor " << flavor << "\n";
8290 outs() << " count " << count << "\n";
8291 outs() << " state (Unknown cputype/cpusubtype)\n";
8292 begin += count * sizeof(uint32_t);
8293 }
8294 }
8295}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008296
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008297static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
8298 if (dl.cmd == MachO::LC_ID_DYLIB)
8299 outs() << " cmd LC_ID_DYLIB\n";
8300 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
8301 outs() << " cmd LC_LOAD_DYLIB\n";
8302 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
8303 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
8304 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
8305 outs() << " cmd LC_REEXPORT_DYLIB\n";
8306 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
8307 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
8308 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
8309 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
8310 else
8311 outs() << " cmd " << dl.cmd << " (unknown)\n";
8312 outs() << " cmdsize " << dl.cmdsize;
8313 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
8314 outs() << " Incorrect size\n";
8315 else
8316 outs() << "\n";
8317 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008318 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008319 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
8320 } else {
8321 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
8322 }
8323 outs() << " time stamp " << dl.dylib.timestamp << " ";
8324 time_t t = dl.dylib.timestamp;
8325 outs() << ctime(&t);
8326 outs() << " current version ";
8327 if (dl.dylib.current_version == 0xffffffff)
8328 outs() << "n/a\n";
8329 else
8330 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
8331 << ((dl.dylib.current_version >> 8) & 0xff) << "."
8332 << (dl.dylib.current_version & 0xff) << "\n";
8333 outs() << "compatibility version ";
8334 if (dl.dylib.compatibility_version == 0xffffffff)
8335 outs() << "n/a\n";
8336 else
8337 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
8338 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
8339 << (dl.dylib.compatibility_version & 0xff) << "\n";
8340}
8341
8342static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
8343 uint32_t object_size) {
8344 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
8345 outs() << " cmd LC_FUNCTION_STARTS\n";
8346 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
8347 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
8348 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
8349 outs() << " cmd LC_FUNCTION_STARTS\n";
8350 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
8351 outs() << " cmd LC_DATA_IN_CODE\n";
8352 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
8353 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
8354 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
8355 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
8356 else
8357 outs() << " cmd " << ld.cmd << " (?)\n";
8358 outs() << " cmdsize " << ld.cmdsize;
8359 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
8360 outs() << " Incorrect size\n";
8361 else
8362 outs() << "\n";
8363 outs() << " dataoff " << ld.dataoff;
8364 if (ld.dataoff > object_size)
8365 outs() << " (past end of file)\n";
8366 else
8367 outs() << "\n";
8368 outs() << " datasize " << ld.datasize;
8369 uint64_t big_size = ld.dataoff;
8370 big_size += ld.datasize;
8371 if (big_size > object_size)
8372 outs() << " (past end of file)\n";
8373 else
8374 outs() << "\n";
8375}
8376
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008377static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
8378 uint32_t cputype, bool verbose) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008379 StringRef Buf = Obj->getData();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008380 unsigned Index = 0;
8381 for (const auto &Command : Obj->load_commands()) {
8382 outs() << "Load command " << Index++ << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008383 if (Command.C.cmd == MachO::LC_SEGMENT) {
8384 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
8385 const char *sg_segname = SLC.segname;
8386 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
8387 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
8388 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
8389 verbose);
8390 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00008391 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00008392 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
8393 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
8394 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
8395 }
8396 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
8397 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
8398 const char *sg_segname = SLC_64.segname;
8399 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
8400 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
8401 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
8402 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
8403 for (unsigned j = 0; j < SLC_64.nsects; j++) {
8404 MachO::section_64 S_64 = Obj->getSection64(Command, j);
8405 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
8406 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
8407 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
8408 sg_segname, filetype, Buf.size(), verbose);
8409 }
8410 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
8411 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00008412 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00008413 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
8414 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
8415 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00008416 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
8417 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008418 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
8419 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
8420 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
8421 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
8422 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
8423 Command.C.cmd == MachO::LC_ID_DYLINKER ||
8424 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
8425 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
8426 PrintDyldLoadCommand(Dyld, Command.Ptr);
8427 } else if (Command.C.cmd == MachO::LC_UUID) {
8428 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
8429 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008430 } else if (Command.C.cmd == MachO::LC_RPATH) {
8431 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
8432 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00008433 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
Tim Northoverbfbfb122015-11-02 21:26:58 +00008434 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
8435 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
8436 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008437 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
8438 PrintVersionMinLoadCommand(Vd);
8439 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
8440 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
8441 PrintSourceVersionCommand(Sd);
8442 } else if (Command.C.cmd == MachO::LC_MAIN) {
8443 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
8444 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00008445 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008446 MachO::encryption_info_command Ei =
8447 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00008448 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00008449 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008450 MachO::encryption_info_command_64 Ei =
8451 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00008452 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008453 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008454 MachO::linker_option_command Lo =
8455 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008456 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00008457 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
8458 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
8459 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00008460 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
8461 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
8462 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008463 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
8464 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
8465 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00008466 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
8467 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
8468 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00008469 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
8470 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
8471 PrintRoutinesCommand(Rc);
8472 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
8473 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
8474 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00008475 } else if (Command.C.cmd == MachO::LC_THREAD ||
8476 Command.C.cmd == MachO::LC_UNIXTHREAD) {
8477 MachO::thread_command Tc = Obj->getThreadCommand(Command);
8478 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00008479 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
8480 Command.C.cmd == MachO::LC_ID_DYLIB ||
8481 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
8482 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
8483 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
8484 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008485 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
8486 PrintDylibCommand(Dl, Command.Ptr);
8487 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
8488 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
8489 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
8490 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
8491 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
8492 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
8493 MachO::linkedit_data_command Ld =
8494 Obj->getLinkeditDataLoadCommand(Command);
8495 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00008496 } else {
8497 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
8498 << ")\n";
8499 outs() << " cmdsize " << Command.C.cmdsize << "\n";
8500 // TODO: get and print the raw bytes of the load command.
8501 }
8502 // TODO: print all the other kinds of load commands.
Kevin Enderby956366c2014-08-29 22:30:52 +00008503 }
8504}
8505
Kevin Enderby0ae163f2016-01-13 00:25:36 +00008506static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008507 if (Obj->is64Bit()) {
8508 MachO::mach_header_64 H_64;
8509 H_64 = Obj->getHeader64();
8510 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
8511 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
8512 } else {
8513 MachO::mach_header H;
8514 H = Obj->getHeader();
8515 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
8516 H.sizeofcmds, H.flags, verbose);
8517 }
8518}
8519
8520void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
8521 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00008522 PrintMachHeader(file, !NonVerbose);
8523}
8524
8525void llvm::printMachOLoadCommands(const object::ObjectFile *Obj) {
8526 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00008527 uint32_t filetype = 0;
8528 uint32_t cputype = 0;
Kevin Enderby0ae163f2016-01-13 00:25:36 +00008529 if (file->is64Bit()) {
8530 MachO::mach_header_64 H_64;
8531 H_64 = file->getHeader64();
8532 filetype = H_64.filetype;
8533 cputype = H_64.cputype;
8534 } else {
8535 MachO::mach_header H;
8536 H = file->getHeader();
8537 filetype = H.filetype;
8538 cputype = H.cputype;
8539 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008540 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008541}
Nick Kledzikd04bc352014-08-30 00:20:14 +00008542
8543//===----------------------------------------------------------------------===//
8544// export trie dumping
8545//===----------------------------------------------------------------------===//
8546
8547void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008548 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
8549 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +00008550 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
8551 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
8552 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8553 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
8554 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8555 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
8556 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
8557 if (ReExport)
8558 outs() << "[re-export] ";
8559 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008560 outs() << format("0x%08llX ",
8561 Entry.address()); // FIXME:add in base address
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008562 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +00008563 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008564 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +00008565 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +00008566 if (WeakDef) {
8567 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008568 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008569 }
8570 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008571 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00008572 outs() << ", ";
8573 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008574 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008575 }
8576 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008577 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00008578 outs() << ", ";
8579 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008580 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008581 }
8582 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008583 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00008584 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008585 outs() << format("resolver=0x%08llX", Entry.other());
8586 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008587 }
8588 outs() << "]";
8589 }
8590 if (ReExport) {
8591 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008592 int Ordinal = Entry.other() - 1;
8593 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
8594 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +00008595 outs() << " (from " << DylibName << ")";
8596 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008597 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +00008598 }
8599 outs() << "\n";
8600 }
8601}
Nick Kledzikac431442014-09-12 21:34:15 +00008602
Nick Kledzikac431442014-09-12 21:34:15 +00008603//===----------------------------------------------------------------------===//
8604// rebase table dumping
8605//===----------------------------------------------------------------------===//
8606
8607namespace {
8608class SegInfo {
8609public:
8610 SegInfo(const object::MachOObjectFile *Obj);
8611
8612 StringRef segmentName(uint32_t SegIndex);
8613 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
8614 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00008615 bool isValidSegIndexAndOffset(uint32_t SegIndex, uint64_t SegOffset);
Nick Kledzikac431442014-09-12 21:34:15 +00008616
8617private:
8618 struct SectionInfo {
8619 uint64_t Address;
8620 uint64_t Size;
8621 StringRef SectionName;
8622 StringRef SegmentName;
8623 uint64_t OffsetInSegment;
8624 uint64_t SegmentStartAddress;
8625 uint32_t SegmentIndex;
8626 };
8627 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
8628 SmallVector<SectionInfo, 32> Sections;
8629};
8630}
8631
8632SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
8633 // Build table of sections so segIndex/offset pairs can be translated.
Nick Kledzik56ebef42014-09-16 01:41:51 +00008634 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
Nick Kledzikac431442014-09-12 21:34:15 +00008635 StringRef CurSegName;
8636 uint64_t CurSegAddress;
8637 for (const SectionRef &Section : Obj->sections()) {
8638 SectionInfo Info;
Davide Italianoccd53fe2015-08-05 07:18:31 +00008639 error(Section.getName(Info.SectionName));
Rafael Espindola80291272014-10-08 15:28:58 +00008640 Info.Address = Section.getAddress();
8641 Info.Size = Section.getSize();
Nick Kledzikac431442014-09-12 21:34:15 +00008642 Info.SegmentName =
8643 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
8644 if (!Info.SegmentName.equals(CurSegName)) {
8645 ++CurSegIndex;
8646 CurSegName = Info.SegmentName;
8647 CurSegAddress = Info.Address;
8648 }
8649 Info.SegmentIndex = CurSegIndex - 1;
8650 Info.OffsetInSegment = Info.Address - CurSegAddress;
8651 Info.SegmentStartAddress = CurSegAddress;
8652 Sections.push_back(Info);
8653 }
8654}
8655
8656StringRef SegInfo::segmentName(uint32_t SegIndex) {
8657 for (const SectionInfo &SI : Sections) {
8658 if (SI.SegmentIndex == SegIndex)
8659 return SI.SegmentName;
8660 }
8661 llvm_unreachable("invalid segIndex");
8662}
8663
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00008664bool SegInfo::isValidSegIndexAndOffset(uint32_t SegIndex,
8665 uint64_t OffsetInSeg) {
8666 for (const SectionInfo &SI : Sections) {
8667 if (SI.SegmentIndex != SegIndex)
8668 continue;
8669 if (SI.OffsetInSegment > OffsetInSeg)
8670 continue;
8671 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
8672 continue;
8673 return true;
8674 }
8675 return false;
8676}
8677
Nick Kledzikac431442014-09-12 21:34:15 +00008678const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
8679 uint64_t OffsetInSeg) {
8680 for (const SectionInfo &SI : Sections) {
8681 if (SI.SegmentIndex != SegIndex)
8682 continue;
8683 if (SI.OffsetInSegment > OffsetInSeg)
8684 continue;
8685 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
8686 continue;
8687 return SI;
8688 }
8689 llvm_unreachable("segIndex and offset not in any section");
8690}
8691
8692StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
8693 return findSection(SegIndex, OffsetInSeg).SectionName;
8694}
8695
8696uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
8697 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
8698 return SI.SegmentStartAddress + OffsetInSeg;
8699}
8700
8701void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
8702 // Build table of sections so names can used in final output.
8703 SegInfo sectionTable(Obj);
8704
8705 outs() << "segment section address type\n";
8706 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
8707 uint32_t SegIndex = Entry.segmentIndex();
8708 uint64_t OffsetInSeg = Entry.segmentOffset();
8709 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8710 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8711 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8712
8713 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008714 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
8715 SegmentName.str().c_str(), SectionName.str().c_str(),
8716 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +00008717 }
8718}
Nick Kledzik56ebef42014-09-16 01:41:51 +00008719
8720static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
8721 StringRef DylibName;
8722 switch (Ordinal) {
8723 case MachO::BIND_SPECIAL_DYLIB_SELF:
8724 return "this-image";
8725 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
8726 return "main-executable";
8727 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
8728 return "flat-namespace";
8729 default:
Nick Kledzikabd29872014-09-16 22:03:13 +00008730 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008731 std::error_code EC =
8732 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +00008733 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +00008734 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +00008735 return DylibName;
8736 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00008737 }
Nick Kledzikabd29872014-09-16 22:03:13 +00008738 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008739}
8740
8741//===----------------------------------------------------------------------===//
8742// bind table dumping
8743//===----------------------------------------------------------------------===//
8744
8745void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
8746 // Build table of sections so names can used in final output.
8747 SegInfo sectionTable(Obj);
8748
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008749 outs() << "segment section address type "
8750 "addend dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008751 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
8752 uint32_t SegIndex = Entry.segmentIndex();
8753 uint64_t OffsetInSeg = Entry.segmentOffset();
8754 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8755 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8756 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8757
8758 // Table lines look like:
8759 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008760 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00008761 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008762 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008763 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008764 << left_justify(SectionName, 18) << " "
8765 << format_hex(Address, 10, true) << " "
8766 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008767 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008768 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008769 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008770 }
8771}
8772
8773//===----------------------------------------------------------------------===//
8774// lazy bind table dumping
8775//===----------------------------------------------------------------------===//
8776
8777void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
8778 // Build table of sections so names can used in final output.
8779 SegInfo sectionTable(Obj);
8780
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008781 outs() << "segment section address "
8782 "dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008783 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
8784 uint32_t SegIndex = Entry.segmentIndex();
8785 uint64_t OffsetInSeg = Entry.segmentOffset();
8786 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8787 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8788 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8789
8790 // Table lines look like:
8791 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008792 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008793 << left_justify(SectionName, 18) << " "
8794 << format_hex(Address, 10, true) << " "
8795 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00008796 << Entry.symbolName() << "\n";
8797 }
8798}
8799
Nick Kledzik56ebef42014-09-16 01:41:51 +00008800//===----------------------------------------------------------------------===//
8801// weak bind table dumping
8802//===----------------------------------------------------------------------===//
8803
8804void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
8805 // Build table of sections so names can used in final output.
8806 SegInfo sectionTable(Obj);
8807
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008808 outs() << "segment section address "
8809 "type addend symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008810 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
8811 // Strong symbols don't have a location to update.
8812 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008813 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +00008814 << Entry.symbolName() << "\n";
8815 continue;
8816 }
8817 uint32_t SegIndex = Entry.segmentIndex();
8818 uint64_t OffsetInSeg = Entry.segmentOffset();
8819 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8820 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8821 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8822
8823 // Table lines look like:
8824 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008825 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008826 << left_justify(SectionName, 18) << " "
8827 << format_hex(Address, 10, true) << " "
8828 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008829 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
8830 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008831 }
8832}
8833
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008834// get_dyld_bind_info_symbolname() is used for disassembly and passed an
8835// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
8836// information for that address. If the address is found its binding symbol
8837// name is returned. If not nullptr is returned.
8838static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
8839 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +00008840 if (info->bindtable == nullptr) {
8841 info->bindtable = new (BindTable);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008842 SegInfo sectionTable(info->O);
8843 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
8844 uint32_t SegIndex = Entry.segmentIndex();
8845 uint64_t OffsetInSeg = Entry.segmentOffset();
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00008846 if (!sectionTable.isValidSegIndexAndOffset(SegIndex, OffsetInSeg))
8847 continue;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008848 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8849 const char *SymbolName = nullptr;
8850 StringRef name = Entry.symbolName();
8851 if (!name.empty())
8852 SymbolName = name.data();
Kevin Enderby078be602014-10-23 19:53:12 +00008853 info->bindtable->push_back(std::make_pair(Address, SymbolName));
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008854 }
8855 }
Kevin Enderby078be602014-10-23 19:53:12 +00008856 for (bind_table_iterator BI = info->bindtable->begin(),
8857 BE = info->bindtable->end();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008858 BI != BE; ++BI) {
8859 uint64_t Address = BI->first;
8860 if (ReferenceValue == Address) {
8861 const char *SymbolName = BI->second;
8862 return SymbolName;
8863 }
8864 }
8865 return nullptr;
8866}