blob: 1632e37063c2a0e4ca9f92acb39cec6b34a8cec9 [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.
Tim Northover9e8eb412016-04-22 23:21:13 +0000145 llvm::Triple TT(TripleName);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000146 if (TripleName.empty()) {
Tim Northover9e8eb412016-04-22 23:21:13 +0000147 TT = MachOObj->getArchTriple(McpuDefault);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000148 TripleName = TT.str();
Tim Northover9e8eb412016-04-22 23:21:13 +0000149 }
150
151 if (TT.getArch() == Triple::arm) {
152 // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
153 // that support ARM are also capable of Thumb mode.
154 llvm::Triple ThumbTriple = TT;
155 std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str();
156 ThumbTriple.setArchName(ThumbName);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000157 ThumbTripleName = ThumbTriple.str();
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000158 }
159
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000160 // Get the target specific parser.
161 std::string Error;
162 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000163 if (TheTarget && ThumbTripleName.empty())
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000164 return TheTarget;
165
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000166 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
167 if (*ThumbTarget)
168 return TheTarget;
169
170 errs() << "llvm-objdump: error: unable to get target for '";
171 if (!TheTarget)
172 errs() << TripleName;
173 else
174 errs() << ThumbTripleName;
175 errs() << "', see --version and --triple.\n";
Craig Toppere6cb63e2014-04-25 04:24:47 +0000176 return nullptr;
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000177}
178
Owen Andersond9243c42011-10-17 21:37:35 +0000179struct SymbolSorter {
180 bool operator()(const SymbolRef &A, const SymbolRef &B) {
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000181 ErrorOr<SymbolRef::Type> ATypeOrErr = A.getType();
182 if (std::error_code EC = ATypeOrErr.getError())
183 report_fatal_error(EC.message());
184 SymbolRef::Type AType = *ATypeOrErr;
185 ErrorOr<SymbolRef::Type> BTypeOrErr = B.getType();
186 if (std::error_code EC = BTypeOrErr.getError())
187 report_fatal_error(EC.message());
Kevin Enderby74f58d42016-03-23 21:45:21 +0000188 SymbolRef::Type BType = *BTypeOrErr;
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000189 uint64_t AAddr = (AType != SymbolRef::ST_Function) ? 0 : A.getValue();
190 uint64_t BAddr = (BType != SymbolRef::ST_Function) ? 0 : B.getValue();
Owen Andersond9243c42011-10-17 21:37:35 +0000191 return AAddr < BAddr;
192 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000193};
194
Kevin Enderby273ae012013-06-06 17:20:50 +0000195// Types for the storted data in code table that is built before disassembly
196// and the predicate function to sort them.
197typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
198typedef std::vector<DiceTableEntry> DiceTable;
199typedef DiceTable::iterator dice_table_iterator;
200
Kevin Enderby930fdc72014-11-06 19:00:13 +0000201// This is used to search for a data in code table entry for the PC being
202// disassembled. The j parameter has the PC in j.first. A single data in code
203// table entry can cover many bytes for each of its Kind's. So if the offset,
204// aka the i.first value, of the data in code table entry plus its Length
205// covers the PC being searched for this will return true. If not it will
206// return false.
David Majnemerea9b8ee2014-11-04 08:41:48 +0000207static bool compareDiceTableEntries(const DiceTableEntry &i,
208 const DiceTableEntry &j) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000209 uint16_t Length;
210 i.second.getLength(Length);
211
212 return j.first >= i.first && j.first < i.first + Length;
Kevin Enderby273ae012013-06-06 17:20:50 +0000213}
214
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000215static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
Kevin Enderby930fdc72014-11-06 19:00:13 +0000216 unsigned short Kind) {
217 uint32_t Value, Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000218
219 switch (Kind) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000220 default:
Charles Davis8bdfafd2013-09-01 04:28:48 +0000221 case MachO::DICE_KIND_DATA:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000222 if (Length >= 4) {
223 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000224 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000225 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000226 outs() << "\t.long " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000227 Size = 4;
228 } else if (Length >= 2) {
229 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000230 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000231 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000232 outs() << "\t.short " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000233 Size = 2;
234 } else {
235 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000236 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000237 Value = bytes[0];
238 outs() << "\t.byte " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000239 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000240 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000241 if (Kind == MachO::DICE_KIND_DATA)
242 outs() << "\t@ KIND_DATA\n";
243 else
244 outs() << "\t@ data in code kind = " << Kind << "\n";
Kevin Enderby273ae012013-06-06 17:20:50 +0000245 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000246 case MachO::DICE_KIND_JUMP_TABLE8:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000247 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000248 dumpBytes(makeArrayRef(bytes, 1), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000249 Value = bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000250 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
251 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000252 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000253 case MachO::DICE_KIND_JUMP_TABLE16:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000254 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000255 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000256 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000257 outs() << "\t.short " << format("%5u", Value & 0xffff)
258 << "\t@ KIND_JUMP_TABLE16\n";
259 Size = 2;
Kevin Enderby273ae012013-06-06 17:20:50 +0000260 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000261 case MachO::DICE_KIND_JUMP_TABLE32:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000262 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
263 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000264 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000265 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000266 outs() << "\t.long " << Value;
267 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
268 outs() << "\t@ KIND_JUMP_TABLE32\n";
269 else
270 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
271 Size = 4;
Kevin Enderby273ae012013-06-06 17:20:50 +0000272 break;
273 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000274 return Size;
Kevin Enderby273ae012013-06-06 17:20:50 +0000275}
276
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000277static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000278 std::vector<SectionRef> &Sections,
279 std::vector<SymbolRef> &Symbols,
280 SmallVectorImpl<uint64_t> &FoundFns,
281 uint64_t &BaseSegmentAddress) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000282 for (const SymbolRef &Symbol : MachOObj->symbols()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000283 Expected<StringRef> SymName = Symbol.getName();
284 if (!SymName) {
285 std::string Buf;
286 raw_string_ostream OS(Buf);
287 logAllUnhandledErrors(SymName.takeError(), OS, "");
288 OS.flush();
289 report_fatal_error(Buf);
290 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000291 if (!SymName->startswith("ltmp"))
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000292 Symbols.push_back(Symbol);
293 }
Owen Andersond9243c42011-10-17 21:37:35 +0000294
Alexey Samsonov48803e52014-03-13 14:37:36 +0000295 for (const SectionRef &Section : MachOObj->sections()) {
Owen Andersond9243c42011-10-17 21:37:35 +0000296 StringRef SectName;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000297 Section.getName(SectName);
298 Sections.push_back(Section);
Owen Andersond9243c42011-10-17 21:37:35 +0000299 }
300
Kevin Enderby273ae012013-06-06 17:20:50 +0000301 bool BaseSegmentAddressSet = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000302 for (const auto &Command : MachOObj->load_commands()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000303 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
Benjamin Kramer699128e2011-09-21 01:13:19 +0000304 // We found a function starts segment, parse the addresses for later
305 // consumption.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000306 MachO::linkedit_data_command LLC =
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000307 MachOObj->getLinkeditDataLoadCommand(Command);
Benjamin Kramer699128e2011-09-21 01:13:19 +0000308
Charles Davis8bdfafd2013-09-01 04:28:48 +0000309 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000310 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
311 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000312 StringRef SegName = SLC.segname;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000313 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
Kevin Enderby273ae012013-06-06 17:20:50 +0000314 BaseSegmentAddressSet = true;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000315 BaseSegmentAddress = SLC.vmaddr;
Kevin Enderby273ae012013-06-06 17:20:50 +0000316 }
317 }
Benjamin Kramer8a529dc2011-09-21 22:16:43 +0000318 }
Benjamin Kramer699128e2011-09-21 01:13:19 +0000319}
320
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000321static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
322 uint32_t n, uint32_t count,
323 uint32_t stride, uint64_t addr) {
324 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
325 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
326 if (n > nindirectsyms)
327 outs() << " (entries start past the end of the indirect symbol "
328 "table) (reserved1 field greater than the table size)";
329 else if (n + count > nindirectsyms)
330 outs() << " (entries extends past the end of the indirect symbol "
331 "table)";
332 outs() << "\n";
333 uint32_t cputype = O->getHeader().cputype;
334 if (cputype & MachO::CPU_ARCH_ABI64)
335 outs() << "address index";
336 else
337 outs() << "address index";
338 if (verbose)
339 outs() << " name\n";
340 else
341 outs() << "\n";
342 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
343 if (cputype & MachO::CPU_ARCH_ABI64)
344 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
345 else
Tim Northover43978372016-04-26 18:29:16 +0000346 outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " ";
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000347 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
348 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
349 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
350 outs() << "LOCAL\n";
351 continue;
352 }
353 if (indirect_symbol ==
354 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
355 outs() << "LOCAL ABSOLUTE\n";
356 continue;
357 }
358 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
359 outs() << "ABSOLUTE\n";
360 continue;
361 }
362 outs() << format("%5u ", indirect_symbol);
Kevin Enderbyf0640752015-03-13 17:56:32 +0000363 if (verbose) {
364 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
365 if (indirect_symbol < Symtab.nsyms) {
366 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
367 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000368 Expected<StringRef> SymName = Symbol.getName();
369 if (!SymName) {
370 std::string Buf;
371 raw_string_ostream OS(Buf);
372 logAllUnhandledErrors(SymName.takeError(), OS, "");
373 OS.flush();
374 report_fatal_error(Buf);
375 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000376 outs() << *SymName;
Kevin Enderbyf0640752015-03-13 17:56:32 +0000377 } else {
378 outs() << "?";
379 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000380 }
381 outs() << "\n";
382 }
383}
384
385static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000386 for (const auto &Load : O->load_commands()) {
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000387 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
388 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
389 for (unsigned J = 0; J < Seg.nsects; ++J) {
390 MachO::section_64 Sec = O->getSection64(Load, J);
391 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
392 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
393 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
394 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
395 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
396 section_type == MachO::S_SYMBOL_STUBS) {
397 uint32_t stride;
398 if (section_type == MachO::S_SYMBOL_STUBS)
399 stride = Sec.reserved2;
400 else
401 stride = 8;
402 if (stride == 0) {
403 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
404 << Sec.sectname << ") "
405 << "(size of stubs in reserved2 field is zero)\n";
406 continue;
407 }
408 uint32_t count = Sec.size / stride;
409 outs() << "Indirect symbols for (" << Sec.segname << ","
410 << Sec.sectname << ") " << count << " entries";
411 uint32_t n = Sec.reserved1;
412 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
413 }
414 }
415 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
416 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
417 for (unsigned J = 0; J < Seg.nsects; ++J) {
418 MachO::section Sec = O->getSection(Load, J);
419 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
420 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
421 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
422 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
423 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
424 section_type == MachO::S_SYMBOL_STUBS) {
425 uint32_t stride;
426 if (section_type == MachO::S_SYMBOL_STUBS)
427 stride = Sec.reserved2;
428 else
429 stride = 4;
430 if (stride == 0) {
431 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
432 << Sec.sectname << ") "
433 << "(size of stubs in reserved2 field is zero)\n";
434 continue;
435 }
436 uint32_t count = Sec.size / stride;
437 outs() << "Indirect symbols for (" << Sec.segname << ","
438 << Sec.sectname << ") " << count << " entries";
439 uint32_t n = Sec.reserved1;
440 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
441 }
442 }
443 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000444 }
445}
446
Kevin Enderby69fe98d2015-01-23 18:52:17 +0000447static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
448 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
449 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
450 outs() << "Data in code table (" << nentries << " entries)\n";
451 outs() << "offset length kind\n";
452 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
453 ++DI) {
454 uint32_t Offset;
455 DI->getOffset(Offset);
456 outs() << format("0x%08" PRIx32, Offset) << " ";
457 uint16_t Length;
458 DI->getLength(Length);
459 outs() << format("%6u", Length) << " ";
460 uint16_t Kind;
461 DI->getKind(Kind);
462 if (verbose) {
463 switch (Kind) {
464 case MachO::DICE_KIND_DATA:
465 outs() << "DATA";
466 break;
467 case MachO::DICE_KIND_JUMP_TABLE8:
468 outs() << "JUMP_TABLE8";
469 break;
470 case MachO::DICE_KIND_JUMP_TABLE16:
471 outs() << "JUMP_TABLE16";
472 break;
473 case MachO::DICE_KIND_JUMP_TABLE32:
474 outs() << "JUMP_TABLE32";
475 break;
476 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
477 outs() << "ABS_JUMP_TABLE32";
478 break;
479 default:
480 outs() << format("0x%04" PRIx32, Kind);
481 break;
482 }
483 } else
484 outs() << format("0x%04" PRIx32, Kind);
485 outs() << "\n";
486 }
487}
488
Kevin Enderby9a509442015-01-27 21:28:24 +0000489static void PrintLinkOptHints(MachOObjectFile *O) {
490 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
491 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
492 uint32_t nloh = LohLC.datasize;
493 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
494 for (uint32_t i = 0; i < nloh;) {
495 unsigned n;
496 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
497 i += n;
498 outs() << " identifier " << identifier << " ";
499 if (i >= nloh)
500 return;
501 switch (identifier) {
502 case 1:
503 outs() << "AdrpAdrp\n";
504 break;
505 case 2:
506 outs() << "AdrpLdr\n";
507 break;
508 case 3:
509 outs() << "AdrpAddLdr\n";
510 break;
511 case 4:
512 outs() << "AdrpLdrGotLdr\n";
513 break;
514 case 5:
515 outs() << "AdrpAddStr\n";
516 break;
517 case 6:
518 outs() << "AdrpLdrGotStr\n";
519 break;
520 case 7:
521 outs() << "AdrpAdd\n";
522 break;
523 case 8:
524 outs() << "AdrpLdrGot\n";
525 break;
526 default:
527 outs() << "Unknown identifier value\n";
528 break;
529 }
530 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
531 i += n;
532 outs() << " narguments " << narguments << "\n";
533 if (i >= nloh)
534 return;
535
536 for (uint32_t j = 0; j < narguments; j++) {
537 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
538 i += n;
539 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
540 if (i >= nloh)
541 return;
542 }
543 }
544}
545
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000546static void PrintDylibs(MachOObjectFile *O, bool JustId) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000547 unsigned Index = 0;
548 for (const auto &Load : O->load_commands()) {
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000549 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
550 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
551 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
552 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
553 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
554 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
555 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
556 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
557 if (dl.dylib.name < dl.cmdsize) {
558 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
559 if (JustId)
560 outs() << p << "\n";
561 else {
562 outs() << "\t" << p;
563 outs() << " (compatibility version "
564 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
565 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
566 << (dl.dylib.compatibility_version & 0xff) << ",";
567 outs() << " current version "
568 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
569 << ((dl.dylib.current_version >> 8) & 0xff) << "."
570 << (dl.dylib.current_version & 0xff) << ")\n";
571 }
572 } else {
573 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
574 if (Load.C.cmd == MachO::LC_ID_DYLIB)
575 outs() << "LC_ID_DYLIB ";
576 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
577 outs() << "LC_LOAD_DYLIB ";
578 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
579 outs() << "LC_LOAD_WEAK_DYLIB ";
580 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
581 outs() << "LC_LAZY_LOAD_DYLIB ";
582 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
583 outs() << "LC_REEXPORT_DYLIB ";
584 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
585 outs() << "LC_LOAD_UPWARD_DYLIB ";
586 else
587 outs() << "LC_??? ";
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000588 outs() << "command " << Index++ << "\n";
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000589 }
590 }
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000591 }
592}
593
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000594typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
595
596static void CreateSymbolAddressMap(MachOObjectFile *O,
597 SymbolAddressMap *AddrMap) {
598 // Create a map of symbol addresses to symbol names.
599 for (const SymbolRef &Symbol : O->symbols()) {
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000600 ErrorOr<SymbolRef::Type> STOrErr = Symbol.getType();
601 if (std::error_code EC = STOrErr.getError())
602 report_fatal_error(EC.message());
603 SymbolRef::Type ST = *STOrErr;
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000604 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
605 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +0000606 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000607 Expected<StringRef> SymNameOrErr = Symbol.getName();
608 if (!SymNameOrErr) {
609 std::string Buf;
610 raw_string_ostream OS(Buf);
611 logAllUnhandledErrors(SymNameOrErr.takeError(), OS, "");
612 OS.flush();
613 report_fatal_error(Buf);
614 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000615 StringRef SymName = *SymNameOrErr;
Kevin Enderby846c0002015-04-16 17:19:59 +0000616 if (!SymName.startswith(".objc"))
617 (*AddrMap)[Address] = SymName;
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000618 }
619 }
620}
621
622// GuessSymbolName is passed the address of what might be a symbol and a
623// pointer to the SymbolAddressMap. It returns the name of a symbol
624// with that address or nullptr if no symbol is found with that address.
625static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
626 const char *SymbolName = nullptr;
627 // A DenseMap can't lookup up some values.
628 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
629 StringRef name = AddrMap->lookup(value);
630 if (!name.empty())
631 SymbolName = name.data();
632 }
633 return SymbolName;
634}
635
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000636static void DumpCstringChar(const char c) {
637 char p[2];
638 p[0] = c;
639 p[1] = '\0';
640 outs().write_escaped(p);
641}
642
Kevin Enderby10ba0412015-02-04 21:38:42 +0000643static void DumpCstringSection(MachOObjectFile *O, const char *sect,
644 uint32_t sect_size, uint64_t sect_addr,
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000645 bool print_addresses) {
Kevin Enderby10ba0412015-02-04 21:38:42 +0000646 for (uint32_t i = 0; i < sect_size; i++) {
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000647 if (print_addresses) {
648 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000649 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000650 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000651 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000652 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000653 for (; i < sect_size && sect[i] != '\0'; i++)
654 DumpCstringChar(sect[i]);
Kevin Enderby10ba0412015-02-04 21:38:42 +0000655 if (i < sect_size && sect[i] == '\0')
656 outs() << "\n";
657 }
658}
659
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000660static void DumpLiteral4(uint32_t l, float f) {
661 outs() << format("0x%08" PRIx32, l);
662 if ((l & 0x7f800000) != 0x7f800000)
663 outs() << format(" (%.16e)\n", f);
664 else {
665 if (l == 0x7f800000)
666 outs() << " (+Infinity)\n";
667 else if (l == 0xff800000)
668 outs() << " (-Infinity)\n";
669 else if ((l & 0x00400000) == 0x00400000)
670 outs() << " (non-signaling Not-a-Number)\n";
671 else
672 outs() << " (signaling Not-a-Number)\n";
673 }
674}
675
676static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
677 uint32_t sect_size, uint64_t sect_addr,
678 bool print_addresses) {
679 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
680 if (print_addresses) {
681 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000682 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000683 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000684 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000685 }
686 float f;
687 memcpy(&f, sect + i, sizeof(float));
688 if (O->isLittleEndian() != sys::IsLittleEndianHost)
689 sys::swapByteOrder(f);
690 uint32_t l;
691 memcpy(&l, sect + i, sizeof(uint32_t));
692 if (O->isLittleEndian() != sys::IsLittleEndianHost)
693 sys::swapByteOrder(l);
694 DumpLiteral4(l, f);
695 }
696}
697
698static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
699 double d) {
700 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
701 uint32_t Hi, Lo;
Davide Italianob627d9f2015-12-12 21:50:11 +0000702 Hi = (O->isLittleEndian()) ? l1 : l0;
703 Lo = (O->isLittleEndian()) ? l0 : l1;
704
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000705 // Hi is the high word, so this is equivalent to if(isfinite(d))
706 if ((Hi & 0x7ff00000) != 0x7ff00000)
707 outs() << format(" (%.16e)\n", d);
708 else {
709 if (Hi == 0x7ff00000 && Lo == 0)
710 outs() << " (+Infinity)\n";
711 else if (Hi == 0xfff00000 && Lo == 0)
712 outs() << " (-Infinity)\n";
713 else if ((Hi & 0x00080000) == 0x00080000)
714 outs() << " (non-signaling Not-a-Number)\n";
715 else
716 outs() << " (signaling Not-a-Number)\n";
717 }
718}
719
720static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
721 uint32_t sect_size, uint64_t sect_addr,
722 bool print_addresses) {
723 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
724 if (print_addresses) {
725 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000726 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000727 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000728 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000729 }
730 double d;
731 memcpy(&d, sect + i, sizeof(double));
732 if (O->isLittleEndian() != sys::IsLittleEndianHost)
733 sys::swapByteOrder(d);
734 uint32_t l0, l1;
735 memcpy(&l0, sect + i, sizeof(uint32_t));
736 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
737 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
738 sys::swapByteOrder(l0);
739 sys::swapByteOrder(l1);
740 }
741 DumpLiteral8(O, l0, l1, d);
742 }
743}
744
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000745static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
746 outs() << format("0x%08" PRIx32, l0) << " ";
747 outs() << format("0x%08" PRIx32, l1) << " ";
748 outs() << format("0x%08" PRIx32, l2) << " ";
749 outs() << format("0x%08" PRIx32, l3) << "\n";
750}
751
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000752static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
753 uint32_t sect_size, uint64_t sect_addr,
754 bool print_addresses) {
755 for (uint32_t i = 0; i < sect_size; i += 16) {
756 if (print_addresses) {
757 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000758 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000759 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000760 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000761 }
762 uint32_t l0, l1, l2, l3;
763 memcpy(&l0, sect + i, sizeof(uint32_t));
764 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
765 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
766 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
767 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
768 sys::swapByteOrder(l0);
769 sys::swapByteOrder(l1);
770 sys::swapByteOrder(l2);
771 sys::swapByteOrder(l3);
772 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000773 DumpLiteral16(l0, l1, l2, l3);
774 }
775}
776
777static void DumpLiteralPointerSection(MachOObjectFile *O,
778 const SectionRef &Section,
779 const char *sect, uint32_t sect_size,
780 uint64_t sect_addr,
781 bool print_addresses) {
782 // Collect the literal sections in this Mach-O file.
783 std::vector<SectionRef> LiteralSections;
784 for (const SectionRef &Section : O->sections()) {
785 DataRefImpl Ref = Section.getRawDataRefImpl();
786 uint32_t section_type;
787 if (O->is64Bit()) {
788 const MachO::section_64 Sec = O->getSection64(Ref);
789 section_type = Sec.flags & MachO::SECTION_TYPE;
790 } else {
791 const MachO::section Sec = O->getSection(Ref);
792 section_type = Sec.flags & MachO::SECTION_TYPE;
793 }
794 if (section_type == MachO::S_CSTRING_LITERALS ||
795 section_type == MachO::S_4BYTE_LITERALS ||
796 section_type == MachO::S_8BYTE_LITERALS ||
797 section_type == MachO::S_16BYTE_LITERALS)
798 LiteralSections.push_back(Section);
799 }
800
801 // Set the size of the literal pointer.
802 uint32_t lp_size = O->is64Bit() ? 8 : 4;
803
Eric Christopher572e03a2015-06-19 01:53:21 +0000804 // Collect the external relocation symbols for the literal pointers.
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000805 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
806 for (const RelocationRef &Reloc : Section.relocations()) {
807 DataRefImpl Rel;
808 MachO::any_relocation_info RE;
809 bool isExtern = false;
810 Rel = Reloc.getRawDataRefImpl();
811 RE = O->getRelocation(Rel);
812 isExtern = O->getPlainRelocationExternal(RE);
813 if (isExtern) {
Rafael Espindola96d071c2015-06-29 23:29:12 +0000814 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000815 symbol_iterator RelocSym = Reloc.getSymbol();
816 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
817 }
818 }
819 array_pod_sort(Relocs.begin(), Relocs.end());
820
821 // Dump each literal pointer.
822 for (uint32_t i = 0; i < sect_size; i += lp_size) {
823 if (print_addresses) {
824 if (O->is64Bit())
825 outs() << format("%016" PRIx64, sect_addr + i) << " ";
826 else
827 outs() << format("%08" PRIx64, sect_addr + i) << " ";
828 }
829 uint64_t lp;
830 if (O->is64Bit()) {
831 memcpy(&lp, sect + i, sizeof(uint64_t));
832 if (O->isLittleEndian() != sys::IsLittleEndianHost)
833 sys::swapByteOrder(lp);
834 } else {
835 uint32_t li;
836 memcpy(&li, sect + i, sizeof(uint32_t));
837 if (O->isLittleEndian() != sys::IsLittleEndianHost)
838 sys::swapByteOrder(li);
839 lp = li;
840 }
841
842 // First look for an external relocation entry for this literal pointer.
David Blaikie33dd45d02015-03-23 18:39:02 +0000843 auto Reloc = std::find_if(
844 Relocs.begin(), Relocs.end(),
845 [&](const std::pair<uint64_t, SymbolRef> &P) { return P.first == i; });
846 if (Reloc != Relocs.end()) {
847 symbol_iterator RelocSym = Reloc->second;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000848 Expected<StringRef> SymName = RelocSym->getName();
849 if (!SymName) {
850 std::string Buf;
851 raw_string_ostream OS(Buf);
852 logAllUnhandledErrors(SymName.takeError(), OS, "");
853 OS.flush();
854 report_fatal_error(Buf);
855 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000856 outs() << "external relocation entry for symbol:" << *SymName << "\n";
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000857 continue;
David Blaikie33dd45d02015-03-23 18:39:02 +0000858 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000859
860 // For local references see what the section the literal pointer points to.
David Blaikie33dd45d02015-03-23 18:39:02 +0000861 auto Sect = std::find_if(LiteralSections.begin(), LiteralSections.end(),
862 [&](const SectionRef &R) {
863 return lp >= R.getAddress() &&
864 lp < R.getAddress() + R.getSize();
865 });
866 if (Sect == LiteralSections.end()) {
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000867 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
David Blaikie33dd45d02015-03-23 18:39:02 +0000868 continue;
869 }
870
871 uint64_t SectAddress = Sect->getAddress();
872 uint64_t SectSize = Sect->getSize();
873
874 StringRef SectName;
875 Sect->getName(SectName);
876 DataRefImpl Ref = Sect->getRawDataRefImpl();
877 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
878 outs() << SegmentName << ":" << SectName << ":";
879
880 uint32_t section_type;
881 if (O->is64Bit()) {
882 const MachO::section_64 Sec = O->getSection64(Ref);
883 section_type = Sec.flags & MachO::SECTION_TYPE;
884 } else {
885 const MachO::section Sec = O->getSection(Ref);
886 section_type = Sec.flags & MachO::SECTION_TYPE;
887 }
888
889 StringRef BytesStr;
890 Sect->getContents(BytesStr);
891 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
892
893 switch (section_type) {
894 case MachO::S_CSTRING_LITERALS:
895 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
896 i++) {
897 DumpCstringChar(Contents[i]);
898 }
899 outs() << "\n";
900 break;
901 case MachO::S_4BYTE_LITERALS:
902 float f;
903 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
904 uint32_t l;
905 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
906 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
907 sys::swapByteOrder(f);
908 sys::swapByteOrder(l);
909 }
910 DumpLiteral4(l, f);
911 break;
912 case MachO::S_8BYTE_LITERALS: {
913 double d;
914 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
915 uint32_t l0, l1;
916 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
917 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
918 sizeof(uint32_t));
919 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
920 sys::swapByteOrder(f);
921 sys::swapByteOrder(l0);
922 sys::swapByteOrder(l1);
923 }
924 DumpLiteral8(O, l0, l1, d);
925 break;
926 }
927 case MachO::S_16BYTE_LITERALS: {
928 uint32_t l0, l1, l2, l3;
929 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
930 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
931 sizeof(uint32_t));
932 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
933 sizeof(uint32_t));
934 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
935 sizeof(uint32_t));
936 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
937 sys::swapByteOrder(l0);
938 sys::swapByteOrder(l1);
939 sys::swapByteOrder(l2);
940 sys::swapByteOrder(l3);
941 }
942 DumpLiteral16(l0, l1, l2, l3);
943 break;
944 }
945 }
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000946 }
947}
948
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000949static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
950 uint32_t sect_size, uint64_t sect_addr,
951 SymbolAddressMap *AddrMap,
952 bool verbose) {
953 uint32_t stride;
Davide Italiano3eb47e22015-12-15 23:14:21 +0000954 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000955 for (uint32_t i = 0; i < sect_size; i += stride) {
956 const char *SymbolName = nullptr;
957 if (O->is64Bit()) {
958 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
959 uint64_t pointer_value;
960 memcpy(&pointer_value, sect + i, stride);
961 if (O->isLittleEndian() != sys::IsLittleEndianHost)
962 sys::swapByteOrder(pointer_value);
963 outs() << format("0x%016" PRIx64, pointer_value);
964 if (verbose)
965 SymbolName = GuessSymbolName(pointer_value, AddrMap);
966 } else {
967 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
968 uint32_t pointer_value;
969 memcpy(&pointer_value, sect + i, stride);
970 if (O->isLittleEndian() != sys::IsLittleEndianHost)
971 sys::swapByteOrder(pointer_value);
972 outs() << format("0x%08" PRIx32, pointer_value);
973 if (verbose)
974 SymbolName = GuessSymbolName(pointer_value, AddrMap);
975 }
976 if (SymbolName)
977 outs() << " " << SymbolName;
978 outs() << "\n";
979 }
980}
981
982static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
983 uint32_t size, uint64_t addr) {
984 uint32_t cputype = O->getHeader().cputype;
985 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
986 uint32_t j;
987 for (uint32_t i = 0; i < size; i += j, addr += j) {
988 if (O->is64Bit())
989 outs() << format("%016" PRIx64, addr) << "\t";
990 else
Kevin Enderbyf0640752015-03-13 17:56:32 +0000991 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000992 for (j = 0; j < 16 && i + j < size; j++) {
993 uint8_t byte_word = *(sect + i + j);
994 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
995 }
996 outs() << "\n";
997 }
998 } else {
999 uint32_t j;
1000 for (uint32_t i = 0; i < size; i += j, addr += j) {
1001 if (O->is64Bit())
1002 outs() << format("%016" PRIx64, addr) << "\t";
1003 else
Kevin Enderbyc4930852016-04-27 22:36:18 +00001004 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001005 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1006 j += sizeof(int32_t)) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001007 if (i + j + sizeof(int32_t) <= size) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001008 uint32_t long_word;
1009 memcpy(&long_word, sect + i + j, sizeof(int32_t));
1010 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1011 sys::swapByteOrder(long_word);
1012 outs() << format("%08" PRIx32, long_word) << " ";
1013 } else {
1014 for (uint32_t k = 0; i + j + k < size; k++) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001015 uint8_t byte_word = *(sect + i + j + k);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001016 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1017 }
1018 }
1019 }
1020 outs() << "\n";
1021 }
1022 }
1023}
1024
Kevin Enderby95df54c2015-02-04 01:01:38 +00001025static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1026 StringRef DisSegName, StringRef DisSectName);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001027static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1028 uint32_t size, uint32_t addr);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001029
1030static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1031 bool verbose) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001032 SymbolAddressMap AddrMap;
1033 if (verbose)
1034 CreateSymbolAddressMap(O, &AddrMap);
1035
Colin LeMahieufcc32762015-07-29 19:08:10 +00001036 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1037 StringRef DumpSection = FilterSections[i];
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001038 std::pair<StringRef, StringRef> DumpSegSectName;
1039 DumpSegSectName = DumpSection.split(',');
1040 StringRef DumpSegName, DumpSectName;
1041 if (DumpSegSectName.second.size()) {
1042 DumpSegName = DumpSegSectName.first;
1043 DumpSectName = DumpSegSectName.second;
1044 } else {
1045 DumpSegName = "";
1046 DumpSectName = DumpSegSectName.first;
1047 }
1048 for (const SectionRef &Section : O->sections()) {
1049 StringRef SectName;
1050 Section.getName(SectName);
1051 DataRefImpl Ref = Section.getRawDataRefImpl();
1052 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1053 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1054 (SectName == DumpSectName)) {
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001055
Kevin Enderby95df54c2015-02-04 01:01:38 +00001056 uint32_t section_flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001057 if (O->is64Bit()) {
1058 const MachO::section_64 Sec = O->getSection64(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001059 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001060
1061 } else {
1062 const MachO::section Sec = O->getSection(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001063 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001064 }
Kevin Enderby95df54c2015-02-04 01:01:38 +00001065 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001066
1067 StringRef BytesStr;
1068 Section.getContents(BytesStr);
1069 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1070 uint32_t sect_size = BytesStr.size();
1071 uint64_t sect_addr = Section.getAddress();
1072
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001073 outs() << "Contents of (" << SegName << "," << SectName
1074 << ") section\n";
1075
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001076 if (verbose) {
Kevin Enderby95df54c2015-02-04 01:01:38 +00001077 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1078 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1079 DisassembleMachO(Filename, O, SegName, SectName);
1080 continue;
1081 }
Kevin Enderbycd66be52015-03-11 22:06:32 +00001082 if (SegName == "__TEXT" && SectName == "__info_plist") {
1083 outs() << sect;
1084 continue;
1085 }
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001086 if (SegName == "__OBJC" && SectName == "__protocol") {
1087 DumpProtocolSection(O, sect, sect_size, sect_addr);
1088 continue;
1089 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001090 switch (section_type) {
1091 case MachO::S_REGULAR:
1092 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1093 break;
1094 case MachO::S_ZEROFILL:
1095 outs() << "zerofill section and has no contents in the file\n";
1096 break;
Kevin Enderby10ba0412015-02-04 21:38:42 +00001097 case MachO::S_CSTRING_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001098 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001099 break;
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001100 case MachO::S_4BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001101 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001102 break;
1103 case MachO::S_8BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001104 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001105 break;
1106 case MachO::S_16BYTE_LITERALS:
Kevin Enderby0fc11822015-04-01 20:57:01 +00001107 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1108 break;
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001109 case MachO::S_LITERAL_POINTERS:
1110 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001111 !NoLeadingAddr);
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001112 break;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001113 case MachO::S_MOD_INIT_FUNC_POINTERS:
1114 case MachO::S_MOD_TERM_FUNC_POINTERS:
1115 DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
1116 verbose);
1117 break;
1118 default:
1119 outs() << "Unknown section type ("
1120 << format("0x%08" PRIx32, section_type) << ")\n";
1121 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1122 break;
1123 }
1124 } else {
1125 if (section_type == MachO::S_ZEROFILL)
1126 outs() << "zerofill section and has no contents in the file\n";
1127 else
1128 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1129 }
1130 }
1131 }
1132 }
1133}
1134
Kevin Enderbycd66be52015-03-11 22:06:32 +00001135static void DumpInfoPlistSectionContents(StringRef Filename,
1136 MachOObjectFile *O) {
1137 for (const SectionRef &Section : O->sections()) {
1138 StringRef SectName;
1139 Section.getName(SectName);
1140 DataRefImpl Ref = Section.getRawDataRefImpl();
1141 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1142 if (SegName == "__TEXT" && SectName == "__info_plist") {
1143 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1144 StringRef BytesStr;
1145 Section.getContents(BytesStr);
1146 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1147 outs() << sect;
1148 return;
1149 }
1150 }
1151}
1152
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001153// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1154// and if it is and there is a list of architecture flags is specified then
1155// check to make sure this Mach-O file is one of those architectures or all
1156// architectures were specified. If not then an error is generated and this
1157// routine returns false. Else it returns true.
1158static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1159 if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
1160 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
1161 bool ArchFound = false;
1162 MachO::mach_header H;
1163 MachO::mach_header_64 H_64;
1164 Triple T;
1165 if (MachO->is64Bit()) {
1166 H_64 = MachO->MachOObjectFile::getHeader64();
Tim Northover9e8eb412016-04-22 23:21:13 +00001167 T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001168 } else {
1169 H = MachO->MachOObjectFile::getHeader();
Tim Northover9e8eb412016-04-22 23:21:13 +00001170 T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001171 }
1172 unsigned i;
1173 for (i = 0; i < ArchFlags.size(); ++i) {
1174 if (ArchFlags[i] == T.getArchName())
1175 ArchFound = true;
1176 break;
1177 }
1178 if (!ArchFound) {
1179 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1180 << "architecture: " + ArchFlags[i] + "\n";
1181 return false;
1182 }
1183 }
1184 return true;
1185}
1186
Kevin Enderby0fc11822015-04-01 20:57:01 +00001187static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1188
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001189// ProcessMachO() is passed a single opened Mach-O file, which may be an
1190// archive member and or in a slice of a universal file. It prints the
1191// the file name and header info and then processes it according to the
1192// command line options.
1193static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
1194 StringRef ArchiveMemberName = StringRef(),
1195 StringRef ArchitectureName = StringRef()) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001196 // If we are doing some processing here on the Mach-O file print the header
1197 // info. And don't print it otherwise like in the case of printing the
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001198 // UniversalHeaders or ArchiveHeaders.
Kevin Enderby131d1772015-01-09 19:22:37 +00001199 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind ||
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001200 LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints ||
Colin LeMahieufcc32762015-07-29 19:08:10 +00001201 DylibsUsed || DylibId || ObjcMetaData || (FilterSections.size() != 0)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001202 outs() << Filename;
1203 if (!ArchiveMemberName.empty())
1204 outs() << '(' << ArchiveMemberName << ')';
1205 if (!ArchitectureName.empty())
1206 outs() << " (architecture " << ArchitectureName << ")";
1207 outs() << ":\n";
1208 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001209
1210 if (Disassemble)
Kevin Enderby95df54c2015-02-04 01:01:38 +00001211 DisassembleMachO(Filename, MachOOF, "__TEXT", "__text");
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001212 if (IndirectSymbols)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001213 PrintIndirectSymbols(MachOOF, !NonVerbose);
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001214 if (DataInCode)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001215 PrintDataInCodeTable(MachOOF, !NonVerbose);
Kevin Enderby9a509442015-01-27 21:28:24 +00001216 if (LinkOptHints)
1217 PrintLinkOptHints(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001218 if (Relocations)
1219 PrintRelocations(MachOOF);
1220 if (SectionHeaders)
1221 PrintSectionHeaders(MachOOF);
1222 if (SectionContents)
1223 PrintSectionContents(MachOOF);
Colin LeMahieufcc32762015-07-29 19:08:10 +00001224 if (FilterSections.size() != 0)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001225 DumpSectionContents(Filename, MachOOF, !NonVerbose);
Kevin Enderbycd66be52015-03-11 22:06:32 +00001226 if (InfoPlist)
1227 DumpInfoPlistSectionContents(Filename, MachOOF);
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001228 if (DylibsUsed)
1229 PrintDylibs(MachOOF, false);
1230 if (DylibId)
1231 PrintDylibs(MachOOF, true);
Kevin Enderby98da6132015-01-20 21:47:46 +00001232 if (SymbolTable)
1233 PrintSymbolTable(MachOOF);
1234 if (UnwindInfo)
1235 printMachOUnwindInfo(MachOOF);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001236 if (PrivateHeaders) {
1237 printMachOFileHeader(MachOOF);
1238 printMachOLoadCommands(MachOOF);
1239 }
1240 if (FirstPrivateHeader)
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001241 printMachOFileHeader(MachOOF);
Kevin Enderby0fc11822015-04-01 20:57:01 +00001242 if (ObjcMetaData)
1243 printObjcMetaData(MachOOF, !NonVerbose);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001244 if (ExportsTrie)
1245 printExportsTrie(MachOOF);
1246 if (Rebase)
1247 printRebaseTable(MachOOF);
1248 if (Bind)
1249 printBindTable(MachOOF);
1250 if (LazyBind)
1251 printLazyBindTable(MachOOF);
1252 if (WeakBind)
1253 printWeakBindTable(MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001254
1255 if (DwarfDumpType != DIDT_Null) {
1256 std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*MachOOF));
1257 // Dump the complete DWARF structure.
1258 DICtx->dump(outs(), DwarfDumpType, true /* DumpEH */);
1259 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001260}
1261
Kevin Enderby131d1772015-01-09 19:22:37 +00001262// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1263static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1264 outs() << " cputype (" << cputype << ")\n";
1265 outs() << " cpusubtype (" << cpusubtype << ")\n";
1266}
1267
1268// printCPUType() helps print_fat_headers by printing the cputype and
1269// pusubtype (symbolically for the one's it knows about).
1270static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1271 switch (cputype) {
1272 case MachO::CPU_TYPE_I386:
1273 switch (cpusubtype) {
1274 case MachO::CPU_SUBTYPE_I386_ALL:
1275 outs() << " cputype CPU_TYPE_I386\n";
1276 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1277 break;
1278 default:
1279 printUnknownCPUType(cputype, cpusubtype);
1280 break;
1281 }
1282 break;
1283 case MachO::CPU_TYPE_X86_64:
1284 switch (cpusubtype) {
1285 case MachO::CPU_SUBTYPE_X86_64_ALL:
1286 outs() << " cputype CPU_TYPE_X86_64\n";
1287 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1288 break;
1289 case MachO::CPU_SUBTYPE_X86_64_H:
1290 outs() << " cputype CPU_TYPE_X86_64\n";
1291 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1292 break;
1293 default:
1294 printUnknownCPUType(cputype, cpusubtype);
1295 break;
1296 }
1297 break;
1298 case MachO::CPU_TYPE_ARM:
1299 switch (cpusubtype) {
1300 case MachO::CPU_SUBTYPE_ARM_ALL:
1301 outs() << " cputype CPU_TYPE_ARM\n";
1302 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1303 break;
1304 case MachO::CPU_SUBTYPE_ARM_V4T:
1305 outs() << " cputype CPU_TYPE_ARM\n";
1306 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1307 break;
1308 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1309 outs() << " cputype CPU_TYPE_ARM\n";
1310 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1311 break;
1312 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1313 outs() << " cputype CPU_TYPE_ARM\n";
1314 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1315 break;
1316 case MachO::CPU_SUBTYPE_ARM_V6:
1317 outs() << " cputype CPU_TYPE_ARM\n";
1318 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1319 break;
1320 case MachO::CPU_SUBTYPE_ARM_V6M:
1321 outs() << " cputype CPU_TYPE_ARM\n";
1322 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1323 break;
1324 case MachO::CPU_SUBTYPE_ARM_V7:
1325 outs() << " cputype CPU_TYPE_ARM\n";
1326 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1327 break;
1328 case MachO::CPU_SUBTYPE_ARM_V7EM:
1329 outs() << " cputype CPU_TYPE_ARM\n";
1330 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1331 break;
1332 case MachO::CPU_SUBTYPE_ARM_V7K:
1333 outs() << " cputype CPU_TYPE_ARM\n";
1334 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1335 break;
1336 case MachO::CPU_SUBTYPE_ARM_V7M:
1337 outs() << " cputype CPU_TYPE_ARM\n";
1338 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1339 break;
1340 case MachO::CPU_SUBTYPE_ARM_V7S:
1341 outs() << " cputype CPU_TYPE_ARM\n";
1342 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1343 break;
1344 default:
1345 printUnknownCPUType(cputype, cpusubtype);
1346 break;
1347 }
1348 break;
1349 case MachO::CPU_TYPE_ARM64:
1350 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1351 case MachO::CPU_SUBTYPE_ARM64_ALL:
1352 outs() << " cputype CPU_TYPE_ARM64\n";
1353 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1354 break;
1355 default:
1356 printUnknownCPUType(cputype, cpusubtype);
1357 break;
1358 }
1359 break;
1360 default:
1361 printUnknownCPUType(cputype, cpusubtype);
1362 break;
1363 }
1364}
1365
1366static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1367 bool verbose) {
1368 outs() << "Fat headers\n";
1369 if (verbose)
1370 outs() << "fat_magic FAT_MAGIC\n";
1371 else
1372 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1373
1374 uint32_t nfat_arch = UB->getNumberOfObjects();
1375 StringRef Buf = UB->getData();
1376 uint64_t size = Buf.size();
1377 uint64_t big_size = sizeof(struct MachO::fat_header) +
1378 nfat_arch * sizeof(struct MachO::fat_arch);
1379 outs() << "nfat_arch " << UB->getNumberOfObjects();
1380 if (nfat_arch == 0)
1381 outs() << " (malformed, contains zero architecture types)\n";
1382 else if (big_size > size)
1383 outs() << " (malformed, architectures past end of file)\n";
1384 else
1385 outs() << "\n";
1386
1387 for (uint32_t i = 0; i < nfat_arch; ++i) {
1388 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1389 uint32_t cputype = OFA.getCPUType();
1390 uint32_t cpusubtype = OFA.getCPUSubType();
1391 outs() << "architecture ";
1392 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1393 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1394 uint32_t other_cputype = other_OFA.getCPUType();
1395 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
Kevin Enderby0512bd72015-01-09 21:55:03 +00001396 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
Kevin Enderby131d1772015-01-09 19:22:37 +00001397 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
Kevin Enderby0512bd72015-01-09 21:55:03 +00001398 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001399 outs() << "(illegal duplicate architecture) ";
1400 break;
Kevin Enderby0512bd72015-01-09 21:55:03 +00001401 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001402 }
1403 if (verbose) {
1404 outs() << OFA.getArchTypeName() << "\n";
1405 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1406 } else {
1407 outs() << i << "\n";
1408 outs() << " cputype " << cputype << "\n";
1409 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1410 << "\n";
1411 }
1412 if (verbose &&
1413 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1414 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1415 else
1416 outs() << " capabilities "
1417 << format("0x%" PRIx32,
1418 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1419 outs() << " offset " << OFA.getOffset();
1420 if (OFA.getOffset() > size)
1421 outs() << " (past end of file)";
1422 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1423 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1424 outs() << "\n";
1425 outs() << " size " << OFA.getSize();
1426 big_size = OFA.getOffset() + OFA.getSize();
1427 if (big_size > size)
1428 outs() << " (past end of file)";
1429 outs() << "\n";
1430 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1431 << ")\n";
1432 }
1433}
1434
Rafael Espindola266b4fe2015-10-31 22:25:59 +00001435static void printArchiveChild(const Archive::Child &C, bool verbose,
Kevin Enderby13023a12015-01-15 23:19:11 +00001436 bool print_offset) {
1437 if (print_offset)
1438 outs() << C.getChildOffset() << "\t";
1439 sys::fs::perms Mode = C.getAccessMode();
1440 if (verbose) {
1441 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1442 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1443 outs() << "-";
Davide Italianobb9a6cc2015-09-07 20:47:03 +00001444 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1445 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1446 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1447 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1448 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1449 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1450 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1451 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1452 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
Kevin Enderby13023a12015-01-15 23:19:11 +00001453 } else {
1454 outs() << format("0%o ", Mode);
1455 }
1456
1457 unsigned UID = C.getUID();
1458 outs() << format("%3d/", UID);
1459 unsigned GID = C.getGID();
1460 outs() << format("%-3d ", GID);
Kevin Enderby7a969422015-11-05 19:24:56 +00001461 ErrorOr<uint64_t> Size = C.getRawSize();
1462 if (std::error_code EC = Size.getError())
1463 report_fatal_error(EC.message());
1464 outs() << format("%5" PRId64, Size.get()) << " ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001465
1466 StringRef RawLastModified = C.getRawLastModified();
1467 if (verbose) {
1468 unsigned Seconds;
1469 if (RawLastModified.getAsInteger(10, Seconds))
1470 outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
1471 else {
1472 // Since cime(3) returns a 26 character string of the form:
1473 // "Sun Sep 16 01:03:52 1973\n\0"
1474 // just print 24 characters.
1475 time_t t = Seconds;
1476 outs() << format("%.24s ", ctime(&t));
1477 }
1478 } else {
1479 outs() << RawLastModified << " ";
1480 }
1481
1482 if (verbose) {
1483 ErrorOr<StringRef> NameOrErr = C.getName();
1484 if (NameOrErr.getError()) {
1485 StringRef RawName = C.getRawName();
1486 outs() << RawName << "\n";
1487 } else {
1488 StringRef Name = NameOrErr.get();
1489 outs() << Name << "\n";
1490 }
1491 } else {
1492 StringRef RawName = C.getRawName();
1493 outs() << RawName << "\n";
1494 }
1495}
1496
1497static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
Rafael Espindola4a782fb2015-10-31 21:03:29 +00001498 for (Archive::child_iterator I = A->child_begin(false), E = A->child_end();
1499 I != E; ++I) {
Kevin Enderby7a969422015-11-05 19:24:56 +00001500 if (std::error_code EC = I->getError())
1501 report_fatal_error(EC.message());
1502 const Archive::Child &C = **I;
Kevin Enderby13023a12015-01-15 23:19:11 +00001503 printArchiveChild(C, verbose, print_offset);
1504 }
1505}
1506
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001507// ParseInputMachO() parses the named Mach-O file in Filename and handles the
1508// -arch flags selecting just those slices as specified by them and also parses
1509// archive files. Then for each individual Mach-O file ProcessMachO() is
1510// called to process the file based on the command line options.
1511void llvm::ParseInputMachO(StringRef Filename) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001512 // Check for -arch all and verifiy the -arch flags are valid.
1513 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1514 if (ArchFlags[i] == "all") {
1515 ArchAll = true;
1516 } else {
1517 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1518 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1519 "'for the -arch option\n";
1520 return;
1521 }
1522 }
1523 }
1524
1525 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00001526 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1527 if (!BinaryOrErr)
1528 report_error(Filename, BinaryOrErr.takeError());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001529 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001530
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001531 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1532 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001533 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001534 printArchiveHeaders(A, !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001535 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
1536 I != E; ++I) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001537 if (std::error_code EC = I->getError())
1538 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001539 auto &C = I->get();
1540 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001541 if (ChildOrErr.getError())
1542 continue;
1543 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1544 if (!checkMachOAndArchFlags(O, Filename))
1545 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001546 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001547 }
1548 }
1549 return;
1550 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001551 if (UniversalHeaders) {
1552 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
Kevin Enderbyf0640752015-03-13 17:56:32 +00001553 printMachOUniversalHeaders(UB, !NonVerbose);
Kevin Enderby131d1772015-01-09 19:22:37 +00001554 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001555 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1556 // If we have a list of architecture flags specified dump only those.
1557 if (!ArchAll && ArchFlags.size() != 0) {
1558 // Look for a slice in the universal binary that matches each ArchFlag.
1559 bool ArchFound;
1560 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1561 ArchFound = false;
1562 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1563 E = UB->end_objects();
1564 I != E; ++I) {
1565 if (ArchFlags[i] == I->getArchTypeName()) {
1566 ArchFound = true;
1567 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
1568 I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001569 std::string ArchitectureName = "";
1570 if (ArchFlags.size() > 1)
1571 ArchitectureName = I->getArchTypeName();
1572 if (ObjOrErr) {
1573 ObjectFile &O = *ObjOrErr.get();
1574 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001575 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001576 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1577 I->getAsArchive()) {
1578 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001579 outs() << "Archive : " << Filename;
1580 if (!ArchitectureName.empty())
1581 outs() << " (architecture " << ArchitectureName << ")";
1582 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001583 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001584 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001585 for (Archive::child_iterator AI = A->child_begin(),
1586 AE = A->child_end();
1587 AI != AE; ++AI) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001588 if (std::error_code EC = AI->getError())
1589 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001590 auto &C = AI->get();
1591 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001592 if (ChildOrErr.getError())
1593 continue;
1594 if (MachOObjectFile *O =
1595 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001596 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001597 }
1598 }
1599 }
1600 }
1601 if (!ArchFound) {
1602 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1603 << "architecture: " + ArchFlags[i] + "\n";
1604 return;
1605 }
1606 }
1607 return;
1608 }
1609 // No architecture flags were specified so if this contains a slice that
1610 // matches the host architecture dump only that.
1611 if (!ArchAll) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001612 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1613 E = UB->end_objects();
1614 I != E; ++I) {
Kevin Enderby0512bd72015-01-09 21:55:03 +00001615 if (MachOObjectFile::getHostArch().getArchName() ==
1616 I->getArchTypeName()) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001617 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001618 std::string ArchiveName;
1619 ArchiveName.clear();
1620 if (ObjOrErr) {
1621 ObjectFile &O = *ObjOrErr.get();
1622 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001623 ProcessMachO(Filename, MachOOF);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001624 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1625 I->getAsArchive()) {
1626 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001627 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001628 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001629 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001630 for (Archive::child_iterator AI = A->child_begin(),
1631 AE = A->child_end();
1632 AI != AE; ++AI) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001633 if (std::error_code EC = AI->getError())
1634 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001635 auto &C = AI->get();
1636 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001637 if (ChildOrErr.getError())
1638 continue;
1639 if (MachOObjectFile *O =
1640 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001641 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001642 }
1643 }
1644 return;
1645 }
1646 }
1647 }
1648 // Either all architectures have been specified or none have been specified
1649 // and this does not contain the host architecture so dump all the slices.
1650 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1651 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1652 E = UB->end_objects();
1653 I != E; ++I) {
1654 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001655 std::string ArchitectureName = "";
1656 if (moreThanOneArch)
1657 ArchitectureName = I->getArchTypeName();
1658 if (ObjOrErr) {
1659 ObjectFile &Obj = *ObjOrErr.get();
1660 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001661 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001662 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
1663 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001664 outs() << "Archive : " << Filename;
1665 if (!ArchitectureName.empty())
1666 outs() << " (architecture " << ArchitectureName << ")";
1667 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001668 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001669 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001670 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
1671 AI != AE; ++AI) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001672 if (std::error_code EC = AI->getError())
1673 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001674 auto &C = AI->get();
1675 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001676 if (ChildOrErr.getError())
1677 continue;
1678 if (MachOObjectFile *O =
1679 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1680 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001681 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1682 ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001683 }
1684 }
1685 }
1686 }
1687 return;
1688 }
1689 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1690 if (!checkMachOAndArchFlags(O, Filename))
1691 return;
1692 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001693 ProcessMachO(Filename, MachOOF);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001694 } else
1695 errs() << "llvm-objdump: '" << Filename << "': "
1696 << "Object is not a Mach-O file type.\n";
Davide Italiano25d84582016-01-13 04:11:36 +00001697 return;
1698 }
1699 llvm_unreachable("Input object can't be invalid at this point");
Rafael Espindola9b709252013-04-13 01:45:40 +00001700}
1701
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001702typedef std::pair<uint64_t, const char *> BindInfoEntry;
1703typedef std::vector<BindInfoEntry> BindTable;
1704typedef BindTable::iterator bind_table_iterator;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001705
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001706// The block of info used by the Symbolizer call backs.
1707struct DisassembleInfo {
1708 bool verbose;
1709 MachOObjectFile *O;
1710 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001711 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001712 std::vector<SectionRef> *Sections;
1713 const char *class_name;
1714 const char *selector_name;
1715 char *method;
Kevin Enderby04bf6932014-10-28 23:39:46 +00001716 char *demangled_name;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001717 uint64_t adrp_addr;
1718 uint32_t adrp_inst;
Kevin Enderby078be602014-10-23 19:53:12 +00001719 BindTable *bindtable;
Kevin Enderbyaac75382015-10-08 16:56:35 +00001720 uint32_t depth;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001721};
1722
1723// SymbolizerGetOpInfo() is the operand information call back function.
1724// This is called to get the symbolic information for operand(s) of an
1725// instruction when it is being done. This routine does this from
1726// the relocation information, symbol table, etc. That block of information
1727// is a pointer to the struct DisassembleInfo that was passed when the
1728// disassembler context was created and passed to back to here when
1729// called back by the disassembler for instruction operands that could have
1730// relocation information. The address of the instruction containing operand is
1731// at the Pc parameter. The immediate value the operand has is passed in
1732// op_info->Value and is at Offset past the start of the instruction and has a
1733// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1734// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1735// names and addends of the symbolic expression to add for the operand. The
1736// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1737// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001738static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1739 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001740 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1741 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001742 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001743
1744 // Make sure all fields returned are zero if we don't set them.
1745 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1746 op_info->Value = value;
1747
1748 // If the TagType is not the value 1 which it code knows about or if no
1749 // verbose symbolic information is wanted then just return 0, indicating no
1750 // information is being returned.
David Blaikie33dd45d02015-03-23 18:39:02 +00001751 if (TagType != 1 || !info->verbose)
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001752 return 0;
1753
1754 unsigned int Arch = info->O->getArch();
1755 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001756 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1757 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001758 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1759 // TODO:
1760 // Search the external relocation entries of a fully linked image
1761 // (if any) for an entry that matches this segment offset.
1762 // uint32_t seg_offset = (Pc + Offset);
1763 return 0;
1764 }
1765 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1766 // for an entry for this section offset.
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001767 uint32_t sect_addr = info->S.getAddress();
1768 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1769 bool reloc_found = false;
1770 DataRefImpl Rel;
1771 MachO::any_relocation_info RE;
1772 bool isExtern = false;
1773 SymbolRef Symbol;
1774 bool r_scattered = false;
1775 uint32_t r_value, pair_r_value, r_type;
1776 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001777 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001778 if (RelocOffset == sect_offset) {
1779 Rel = Reloc.getRawDataRefImpl();
1780 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00001781 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001782 r_scattered = info->O->isRelocationScattered(RE);
1783 if (r_scattered) {
1784 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001785 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1786 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1787 DataRefImpl RelNext = Rel;
1788 info->O->moveRelocationNext(RelNext);
1789 MachO::any_relocation_info RENext;
1790 RENext = info->O->getRelocation(RelNext);
1791 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00001792 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001793 else
1794 return 0;
1795 }
1796 } else {
1797 isExtern = info->O->getPlainRelocationExternal(RE);
1798 if (isExtern) {
1799 symbol_iterator RelocSym = Reloc.getSymbol();
1800 Symbol = *RelocSym;
1801 }
1802 }
1803 reloc_found = true;
1804 break;
1805 }
1806 }
1807 if (reloc_found && isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001808 Expected<StringRef> SymName = Symbol.getName();
1809 if (!SymName) {
1810 std::string Buf;
1811 raw_string_ostream OS(Buf);
1812 logAllUnhandledErrors(SymName.takeError(), OS, "");
1813 OS.flush();
1814 report_fatal_error(Buf);
1815 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001816 const char *name = SymName->data();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001817 op_info->AddSymbol.Present = 1;
1818 op_info->AddSymbol.Name = name;
1819 // For i386 extern relocation entries the value in the instruction is
1820 // the offset from the symbol, and value is already set in op_info->Value.
1821 return 1;
1822 }
1823 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1824 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001825 const char *add = GuessSymbolName(r_value, info->AddrMap);
1826 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001827 uint32_t offset = value - (r_value - pair_r_value);
1828 op_info->AddSymbol.Present = 1;
1829 if (add != nullptr)
1830 op_info->AddSymbol.Name = add;
1831 else
1832 op_info->AddSymbol.Value = r_value;
1833 op_info->SubtractSymbol.Present = 1;
1834 if (sub != nullptr)
1835 op_info->SubtractSymbol.Name = sub;
1836 else
1837 op_info->SubtractSymbol.Value = pair_r_value;
1838 op_info->Value = offset;
1839 return 1;
1840 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001841 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001842 }
1843 if (Arch == Triple::x86_64) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001844 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1845 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001846 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1847 // TODO:
1848 // Search the external relocation entries of a fully linked image
1849 // (if any) for an entry that matches this segment offset.
1850 // uint64_t seg_offset = (Pc + Offset);
1851 return 0;
1852 }
1853 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1854 // for an entry for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00001855 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001856 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1857 bool reloc_found = false;
1858 DataRefImpl Rel;
1859 MachO::any_relocation_info RE;
1860 bool isExtern = false;
1861 SymbolRef Symbol;
1862 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001863 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001864 if (RelocOffset == sect_offset) {
1865 Rel = Reloc.getRawDataRefImpl();
1866 RE = info->O->getRelocation(Rel);
1867 // NOTE: Scattered relocations don't exist on x86_64.
1868 isExtern = info->O->getPlainRelocationExternal(RE);
1869 if (isExtern) {
1870 symbol_iterator RelocSym = Reloc.getSymbol();
1871 Symbol = *RelocSym;
1872 }
1873 reloc_found = true;
1874 break;
1875 }
1876 }
1877 if (reloc_found && isExtern) {
1878 // The Value passed in will be adjusted by the Pc if the instruction
1879 // adds the Pc. But for x86_64 external relocation entries the Value
1880 // is the offset from the external symbol.
1881 if (info->O->getAnyRelocationPCRel(RE))
1882 op_info->Value -= Pc + Offset + Size;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001883 Expected<StringRef> SymName = Symbol.getName();
1884 if (!SymName) {
1885 std::string Buf;
1886 raw_string_ostream OS(Buf);
1887 logAllUnhandledErrors(SymName.takeError(), OS, "");
1888 OS.flush();
1889 report_fatal_error(Buf);
1890 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001891 const char *name = SymName->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001892 unsigned Type = info->O->getAnyRelocationType(RE);
1893 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1894 DataRefImpl RelNext = Rel;
1895 info->O->moveRelocationNext(RelNext);
1896 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1897 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1898 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1899 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1900 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1901 op_info->SubtractSymbol.Present = 1;
1902 op_info->SubtractSymbol.Name = name;
1903 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1904 Symbol = *RelocSymNext;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001905 Expected<StringRef> SymNameNext = Symbol.getName();
1906 if (!SymNameNext) {
1907 std::string Buf;
1908 raw_string_ostream OS(Buf);
1909 logAllUnhandledErrors(SymNameNext.takeError(), OS, "");
1910 OS.flush();
1911 report_fatal_error(Buf);
1912 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001913 name = SymNameNext->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001914 }
1915 }
1916 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1917 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1918 op_info->AddSymbol.Present = 1;
1919 op_info->AddSymbol.Name = name;
1920 return 1;
1921 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001922 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001923 }
1924 if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00001925 if (Offset != 0 || (Size != 4 && Size != 2))
1926 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001927 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1928 // TODO:
1929 // Search the external relocation entries of a fully linked image
1930 // (if any) for an entry that matches this segment offset.
1931 // uint32_t seg_offset = (Pc + Offset);
1932 return 0;
1933 }
1934 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1935 // for an entry for this section offset.
Kevin Enderby930fdc72014-11-06 19:00:13 +00001936 uint32_t sect_addr = info->S.getAddress();
1937 uint32_t sect_offset = (Pc + Offset) - sect_addr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001938 DataRefImpl Rel;
1939 MachO::any_relocation_info RE;
1940 bool isExtern = false;
1941 SymbolRef Symbol;
1942 bool r_scattered = false;
1943 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
David Blaikie33dd45d02015-03-23 18:39:02 +00001944 auto Reloc =
1945 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
1946 [&](const RelocationRef &Reloc) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001947 uint64_t RelocOffset = Reloc.getOffset();
David Blaikie33dd45d02015-03-23 18:39:02 +00001948 return RelocOffset == sect_offset;
1949 });
1950
1951 if (Reloc == info->S.relocations().end())
1952 return 0;
1953
1954 Rel = Reloc->getRawDataRefImpl();
1955 RE = info->O->getRelocation(Rel);
1956 r_length = info->O->getAnyRelocationLength(RE);
1957 r_scattered = info->O->isRelocationScattered(RE);
1958 if (r_scattered) {
1959 r_value = info->O->getScatteredRelocationValue(RE);
1960 r_type = info->O->getScatteredRelocationType(RE);
1961 } else {
1962 r_type = info->O->getAnyRelocationType(RE);
1963 isExtern = info->O->getPlainRelocationExternal(RE);
1964 if (isExtern) {
1965 symbol_iterator RelocSym = Reloc->getSymbol();
1966 Symbol = *RelocSym;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001967 }
1968 }
David Blaikie33dd45d02015-03-23 18:39:02 +00001969 if (r_type == MachO::ARM_RELOC_HALF ||
1970 r_type == MachO::ARM_RELOC_SECTDIFF ||
1971 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1972 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1973 DataRefImpl RelNext = Rel;
1974 info->O->moveRelocationNext(RelNext);
1975 MachO::any_relocation_info RENext;
1976 RENext = info->O->getRelocation(RelNext);
1977 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
1978 if (info->O->isRelocationScattered(RENext))
1979 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1980 }
1981
1982 if (isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001983 Expected<StringRef> SymName = Symbol.getName();
1984 if (!SymName) {
1985 std::string Buf;
1986 raw_string_ostream OS(Buf);
1987 logAllUnhandledErrors(SymName.takeError(), OS, "");
1988 OS.flush();
1989 report_fatal_error(Buf);
1990 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001991 const char *name = SymName->data();
Kevin Enderby930fdc72014-11-06 19:00:13 +00001992 op_info->AddSymbol.Present = 1;
1993 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00001994 switch (r_type) {
1995 case MachO::ARM_RELOC_HALF:
1996 if ((r_length & 0x1) == 1) {
1997 op_info->Value = value << 16 | other_half;
1998 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1999 } else {
2000 op_info->Value = other_half << 16 | value;
2001 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00002002 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002003 break;
2004 default:
2005 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002006 }
2007 return 1;
2008 }
2009 // If we have a branch that is not an external relocation entry then
2010 // return 0 so the code in tryAddingSymbolicOperand() can use the
2011 // SymbolLookUp call back with the branch target address to look up the
2012 // symbol and possiblity add an annotation for a symbol stub.
David Blaikie33dd45d02015-03-23 18:39:02 +00002013 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2014 r_type == MachO::ARM_THUMB_RELOC_BR22))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002015 return 0;
2016
2017 uint32_t offset = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002018 if (r_type == MachO::ARM_RELOC_HALF ||
2019 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2020 if ((r_length & 0x1) == 1)
2021 value = value << 16 | other_half;
2022 else
2023 value = other_half << 16 | value;
2024 }
2025 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2026 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2027 offset = value - r_value;
2028 value = r_value;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002029 }
2030
David Blaikie33dd45d02015-03-23 18:39:02 +00002031 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002032 if ((r_length & 0x1) == 1)
2033 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2034 else
2035 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002036 const char *add = GuessSymbolName(r_value, info->AddrMap);
2037 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002038 int32_t offset = value - (r_value - pair_r_value);
2039 op_info->AddSymbol.Present = 1;
2040 if (add != nullptr)
2041 op_info->AddSymbol.Name = add;
2042 else
2043 op_info->AddSymbol.Value = r_value;
2044 op_info->SubtractSymbol.Present = 1;
2045 if (sub != nullptr)
2046 op_info->SubtractSymbol.Name = sub;
2047 else
2048 op_info->SubtractSymbol.Value = pair_r_value;
2049 op_info->Value = offset;
2050 return 1;
2051 }
2052
Kevin Enderby930fdc72014-11-06 19:00:13 +00002053 op_info->AddSymbol.Present = 1;
2054 op_info->Value = offset;
David Blaikie33dd45d02015-03-23 18:39:02 +00002055 if (r_type == MachO::ARM_RELOC_HALF) {
2056 if ((r_length & 0x1) == 1)
2057 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2058 else
2059 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002060 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002061 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002062 if (add != nullptr) {
2063 op_info->AddSymbol.Name = add;
2064 return 1;
2065 }
2066 op_info->AddSymbol.Value = value;
2067 return 1;
David Blaikie33dd45d02015-03-23 18:39:02 +00002068 }
2069 if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002070 if (Offset != 0 || Size != 4)
2071 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002072 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2073 // TODO:
2074 // Search the external relocation entries of a fully linked image
2075 // (if any) for an entry that matches this segment offset.
2076 // uint64_t seg_offset = (Pc + Offset);
2077 return 0;
2078 }
2079 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2080 // for an entry for this section offset.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002081 uint64_t sect_addr = info->S.getAddress();
2082 uint64_t sect_offset = (Pc + Offset) - sect_addr;
David Blaikie33dd45d02015-03-23 18:39:02 +00002083 auto Reloc =
2084 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
2085 [&](const RelocationRef &Reloc) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002086 uint64_t RelocOffset = Reloc.getOffset();
David Blaikie33dd45d02015-03-23 18:39:02 +00002087 return RelocOffset == sect_offset;
2088 });
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002089
David Blaikie33dd45d02015-03-23 18:39:02 +00002090 if (Reloc == info->S.relocations().end())
2091 return 0;
2092
2093 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2094 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2095 uint32_t r_type = info->O->getAnyRelocationType(RE);
2096 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2097 DataRefImpl RelNext = Rel;
2098 info->O->moveRelocationNext(RelNext);
2099 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2100 if (value == 0) {
2101 value = info->O->getPlainRelocationSymbolNum(RENext);
2102 op_info->Value = value;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002103 }
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002104 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002105 // NOTE: Scattered relocations don't exist on arm64.
2106 if (!info->O->getPlainRelocationExternal(RE))
2107 return 0;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002108 Expected<StringRef> SymName = Reloc->getSymbol()->getName();
2109 if (!SymName) {
2110 std::string Buf;
2111 raw_string_ostream OS(Buf);
2112 logAllUnhandledErrors(SymName.takeError(), OS, "");
2113 OS.flush();
2114 report_fatal_error(Buf);
2115 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002116 const char *name = SymName->data();
David Blaikie33dd45d02015-03-23 18:39:02 +00002117 op_info->AddSymbol.Present = 1;
2118 op_info->AddSymbol.Name = name;
2119
2120 switch (r_type) {
2121 case MachO::ARM64_RELOC_PAGE21:
2122 /* @page */
2123 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2124 break;
2125 case MachO::ARM64_RELOC_PAGEOFF12:
2126 /* @pageoff */
2127 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2128 break;
2129 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2130 /* @gotpage */
2131 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2132 break;
2133 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2134 /* @gotpageoff */
2135 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2136 break;
2137 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2138 /* @tvlppage is not implemented in llvm-mc */
2139 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2140 break;
2141 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2142 /* @tvlppageoff is not implemented in llvm-mc */
2143 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2144 break;
2145 default:
2146 case MachO::ARM64_RELOC_BRANCH26:
2147 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2148 break;
2149 }
2150 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002151 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002152 return 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002153}
2154
Kevin Enderbybf246f52014-09-24 23:08:22 +00002155// GuessCstringPointer is passed the address of what might be a pointer to a
2156// literal string in a cstring section. If that address is in a cstring section
2157// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002158static const char *GuessCstringPointer(uint64_t ReferenceValue,
2159 struct DisassembleInfo *info) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002160 for (const auto &Load : info->O->load_commands()) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002161 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2162 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2163 for (unsigned J = 0; J < Seg.nsects; ++J) {
2164 MachO::section_64 Sec = info->O->getSection64(Load, J);
2165 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2166 if (section_type == MachO::S_CSTRING_LITERALS &&
2167 ReferenceValue >= Sec.addr &&
2168 ReferenceValue < Sec.addr + Sec.size) {
2169 uint64_t sect_offset = ReferenceValue - Sec.addr;
2170 uint64_t object_offset = Sec.offset + sect_offset;
2171 StringRef MachOContents = info->O->getData();
2172 uint64_t object_size = MachOContents.size();
2173 const char *object_addr = (const char *)MachOContents.data();
2174 if (object_offset < object_size) {
2175 const char *name = object_addr + object_offset;
2176 return name;
2177 } else {
2178 return nullptr;
2179 }
2180 }
2181 }
2182 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2183 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2184 for (unsigned J = 0; J < Seg.nsects; ++J) {
2185 MachO::section Sec = info->O->getSection(Load, J);
2186 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2187 if (section_type == MachO::S_CSTRING_LITERALS &&
2188 ReferenceValue >= Sec.addr &&
2189 ReferenceValue < Sec.addr + Sec.size) {
2190 uint64_t sect_offset = ReferenceValue - Sec.addr;
2191 uint64_t object_offset = Sec.offset + sect_offset;
2192 StringRef MachOContents = info->O->getData();
2193 uint64_t object_size = MachOContents.size();
2194 const char *object_addr = (const char *)MachOContents.data();
2195 if (object_offset < object_size) {
2196 const char *name = object_addr + object_offset;
2197 return name;
2198 } else {
2199 return nullptr;
2200 }
2201 }
2202 }
2203 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002204 }
2205 return nullptr;
2206}
2207
Kevin Enderby85974882014-09-26 22:20:44 +00002208// GuessIndirectSymbol returns the name of the indirect symbol for the
2209// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2210// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2211// symbol name being referenced by the stub or pointer.
2212static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2213 struct DisassembleInfo *info) {
Kevin Enderby85974882014-09-26 22:20:44 +00002214 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2215 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002216 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby85974882014-09-26 22:20:44 +00002217 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2218 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2219 for (unsigned J = 0; J < Seg.nsects; ++J) {
2220 MachO::section_64 Sec = info->O->getSection64(Load, J);
2221 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2222 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2223 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2224 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2225 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2226 section_type == MachO::S_SYMBOL_STUBS) &&
2227 ReferenceValue >= Sec.addr &&
2228 ReferenceValue < Sec.addr + Sec.size) {
2229 uint32_t stride;
2230 if (section_type == MachO::S_SYMBOL_STUBS)
2231 stride = Sec.reserved2;
2232 else
2233 stride = 8;
2234 if (stride == 0)
2235 return nullptr;
2236 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2237 if (index < Dysymtab.nindirectsyms) {
2238 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002239 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002240 if (indirect_symbol < Symtab.nsyms) {
2241 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2242 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002243 Expected<StringRef> SymName = Symbol.getName();
2244 if (!SymName) {
2245 std::string Buf;
2246 raw_string_ostream OS(Buf);
2247 logAllUnhandledErrors(SymName.takeError(), OS, "");
2248 OS.flush();
2249 report_fatal_error(Buf);
2250 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002251 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002252 return name;
2253 }
2254 }
2255 }
2256 }
2257 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2258 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2259 for (unsigned J = 0; J < Seg.nsects; ++J) {
2260 MachO::section Sec = info->O->getSection(Load, J);
2261 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2262 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2263 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2264 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2265 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2266 section_type == MachO::S_SYMBOL_STUBS) &&
2267 ReferenceValue >= Sec.addr &&
2268 ReferenceValue < Sec.addr + Sec.size) {
2269 uint32_t stride;
2270 if (section_type == MachO::S_SYMBOL_STUBS)
2271 stride = Sec.reserved2;
2272 else
2273 stride = 4;
2274 if (stride == 0)
2275 return nullptr;
2276 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2277 if (index < Dysymtab.nindirectsyms) {
2278 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002279 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002280 if (indirect_symbol < Symtab.nsyms) {
2281 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2282 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002283 Expected<StringRef> SymName = Symbol.getName();
2284 if (!SymName) {
2285 std::string Buf;
2286 raw_string_ostream OS(Buf);
2287 logAllUnhandledErrors(SymName.takeError(), OS, "");
2288 OS.flush();
2289 report_fatal_error(Buf);
2290 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002291 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002292 return name;
2293 }
2294 }
2295 }
2296 }
2297 }
Kevin Enderby85974882014-09-26 22:20:44 +00002298 }
2299 return nullptr;
2300}
2301
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002302// method_reference() is called passing it the ReferenceName that might be
2303// a reference it to an Objective-C method call. If so then it allocates and
2304// assembles a method call string with the values last seen and saved in
2305// the DisassembleInfo's class_name and selector_name fields. This is saved
2306// into the method field of the info and any previous string is free'ed.
2307// Then the class_name field in the info is set to nullptr. The method call
2308// string is set into ReferenceName and ReferenceType is set to
2309// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2310// then both ReferenceType and ReferenceName are left unchanged.
2311static void method_reference(struct DisassembleInfo *info,
2312 uint64_t *ReferenceType,
2313 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002314 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002315 if (*ReferenceName != nullptr) {
2316 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002317 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002318 if (info->method != nullptr)
2319 free(info->method);
2320 if (info->class_name != nullptr) {
2321 info->method = (char *)malloc(5 + strlen(info->class_name) +
2322 strlen(info->selector_name));
2323 if (info->method != nullptr) {
2324 strcpy(info->method, "+[");
2325 strcat(info->method, info->class_name);
2326 strcat(info->method, " ");
2327 strcat(info->method, info->selector_name);
2328 strcat(info->method, "]");
2329 *ReferenceName = info->method;
2330 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2331 }
2332 } else {
2333 info->method = (char *)malloc(9 + strlen(info->selector_name));
2334 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002335 if (Arch == Triple::x86_64)
2336 strcpy(info->method, "-[%rdi ");
2337 else if (Arch == Triple::aarch64)
2338 strcpy(info->method, "-[x0 ");
2339 else
2340 strcpy(info->method, "-[r? ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002341 strcat(info->method, info->selector_name);
2342 strcat(info->method, "]");
2343 *ReferenceName = info->method;
2344 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2345 }
2346 }
2347 info->class_name = nullptr;
2348 }
2349 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002350 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002351 if (info->method != nullptr)
2352 free(info->method);
2353 info->method = (char *)malloc(17 + strlen(info->selector_name));
2354 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002355 if (Arch == Triple::x86_64)
2356 strcpy(info->method, "-[[%rdi super] ");
2357 else if (Arch == Triple::aarch64)
2358 strcpy(info->method, "-[[x0 super] ");
2359 else
2360 strcpy(info->method, "-[[r? super] ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002361 strcat(info->method, info->selector_name);
2362 strcat(info->method, "]");
2363 *ReferenceName = info->method;
2364 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2365 }
2366 info->class_name = nullptr;
2367 }
2368 }
2369 }
2370}
2371
2372// GuessPointerPointer() is passed the address of what might be a pointer to
2373// a reference to an Objective-C class, selector, message ref or cfstring.
2374// If so the value of the pointer is returned and one of the booleans are set
2375// to true. If not zero is returned and all the booleans are set to false.
2376static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2377 struct DisassembleInfo *info,
2378 bool &classref, bool &selref, bool &msgref,
2379 bool &cfstring) {
2380 classref = false;
2381 selref = false;
2382 msgref = false;
2383 cfstring = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002384 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002385 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2386 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2387 for (unsigned J = 0; J < Seg.nsects; ++J) {
2388 MachO::section_64 Sec = info->O->getSection64(Load, J);
2389 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2390 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2391 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2392 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2393 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2394 ReferenceValue >= Sec.addr &&
2395 ReferenceValue < Sec.addr + Sec.size) {
2396 uint64_t sect_offset = ReferenceValue - Sec.addr;
2397 uint64_t object_offset = Sec.offset + sect_offset;
2398 StringRef MachOContents = info->O->getData();
2399 uint64_t object_size = MachOContents.size();
2400 const char *object_addr = (const char *)MachOContents.data();
2401 if (object_offset < object_size) {
2402 uint64_t pointer_value;
2403 memcpy(&pointer_value, object_addr + object_offset,
2404 sizeof(uint64_t));
2405 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2406 sys::swapByteOrder(pointer_value);
2407 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2408 selref = true;
2409 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2410 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2411 classref = true;
2412 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2413 ReferenceValue + 8 < Sec.addr + Sec.size) {
2414 msgref = true;
2415 memcpy(&pointer_value, object_addr + object_offset + 8,
2416 sizeof(uint64_t));
2417 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2418 sys::swapByteOrder(pointer_value);
2419 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2420 cfstring = true;
2421 return pointer_value;
2422 } else {
2423 return 0;
2424 }
2425 }
2426 }
2427 }
2428 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002429 }
2430 return 0;
2431}
2432
2433// get_pointer_64 returns a pointer to the bytes in the object file at the
2434// Address from a section in the Mach-O file. And indirectly returns the
2435// offset into the section, number of bytes left in the section past the offset
2436// and which section is was being referenced. If the Address is not in a
2437// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002438static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2439 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002440 DisassembleInfo *info,
2441 bool objc_only = false) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002442 offset = 0;
2443 left = 0;
2444 S = SectionRef();
2445 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2446 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2447 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
Kevin Enderby46e642f2015-10-08 22:50:55 +00002448 if (SectSize == 0)
2449 continue;
Kevin Enderby846c0002015-04-16 17:19:59 +00002450 if (objc_only) {
2451 StringRef SectName;
2452 ((*(info->Sections))[SectIdx]).getName(SectName);
2453 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2454 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2455 if (SegName != "__OBJC" && SectName != "__cstring")
2456 continue;
2457 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002458 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2459 S = (*(info->Sections))[SectIdx];
2460 offset = Address - SectAddress;
2461 left = SectSize - offset;
2462 StringRef SectContents;
2463 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2464 return SectContents.data() + offset;
2465 }
2466 }
2467 return nullptr;
2468}
2469
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002470static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2471 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002472 DisassembleInfo *info,
2473 bool objc_only = false) {
2474 return get_pointer_64(Address, offset, left, S, info, objc_only);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002475}
2476
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002477// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2478// the symbol indirectly through n_value. Based on the relocation information
2479// for the specified section offset in the specified section reference.
Kevin Enderby0fc11822015-04-01 20:57:01 +00002480// If no relocation information is found and a non-zero ReferenceValue for the
2481// symbol is passed, look up that address in the info's AddrMap.
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00002482static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2483 DisassembleInfo *info, uint64_t &n_value,
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002484 uint64_t ReferenceValue = 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002485 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002486 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002487 return nullptr;
2488
2489 // See if there is an external relocation entry at the sect_offset.
2490 bool reloc_found = false;
2491 DataRefImpl Rel;
2492 MachO::any_relocation_info RE;
2493 bool isExtern = false;
2494 SymbolRef Symbol;
2495 for (const RelocationRef &Reloc : S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002496 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002497 if (RelocOffset == sect_offset) {
2498 Rel = Reloc.getRawDataRefImpl();
2499 RE = info->O->getRelocation(Rel);
2500 if (info->O->isRelocationScattered(RE))
2501 continue;
2502 isExtern = info->O->getPlainRelocationExternal(RE);
2503 if (isExtern) {
2504 symbol_iterator RelocSym = Reloc.getSymbol();
2505 Symbol = *RelocSym;
2506 }
2507 reloc_found = true;
2508 break;
2509 }
2510 }
2511 // If there is an external relocation entry for a symbol in this section
2512 // at this section_offset then use that symbol's value for the n_value
2513 // and return its name.
2514 const char *SymbolName = nullptr;
2515 if (reloc_found && isExtern) {
Rafael Espindoladea00162015-07-03 17:44:18 +00002516 n_value = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002517 Expected<StringRef> NameOrError = Symbol.getName();
2518 if (!NameOrError) {
2519 std::string Buf;
2520 raw_string_ostream OS(Buf);
2521 logAllUnhandledErrors(NameOrError.takeError(), OS, "");
2522 OS.flush();
2523 report_fatal_error(Buf);
2524 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002525 StringRef Name = *NameOrError;
2526 if (!Name.empty()) {
2527 SymbolName = Name.data();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002528 return SymbolName;
2529 }
2530 }
2531
2532 // TODO: For fully linked images, look through the external relocation
2533 // entries off the dynamic symtab command. For these the r_offset is from the
2534 // start of the first writeable segment in the Mach-O file. So the offset
2535 // to this section from that segment is passed to this routine by the caller,
2536 // as the database_offset. Which is the difference of the section's starting
2537 // address and the first writable segment.
2538 //
2539 // NOTE: need add passing the database_offset to this routine.
2540
Kevin Enderby0fc11822015-04-01 20:57:01 +00002541 // We did not find an external relocation entry so look up the ReferenceValue
2542 // as an address of a symbol and if found return that symbol's name.
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002543 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002544
2545 return SymbolName;
2546}
2547
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002548static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
2549 DisassembleInfo *info,
2550 uint32_t ReferenceValue) {
2551 uint64_t n_value64;
2552 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
2553}
2554
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002555// These are structs in the Objective-C meta data and read to produce the
2556// comments for disassembly. While these are part of the ABI they are no
2557// public defintions. So the are here not in include/llvm/Support/MachO.h .
2558
2559// The cfstring object in a 64-bit Mach-O file.
2560struct cfstring64_t {
2561 uint64_t isa; // class64_t * (64-bit pointer)
2562 uint64_t flags; // flag bits
2563 uint64_t characters; // char * (64-bit pointer)
2564 uint64_t length; // number of non-NULL characters in above
2565};
2566
2567// The class object in a 64-bit Mach-O file.
2568struct class64_t {
2569 uint64_t isa; // class64_t * (64-bit pointer)
2570 uint64_t superclass; // class64_t * (64-bit pointer)
2571 uint64_t cache; // Cache (64-bit pointer)
2572 uint64_t vtable; // IMP * (64-bit pointer)
2573 uint64_t data; // class_ro64_t * (64-bit pointer)
2574};
2575
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002576struct class32_t {
2577 uint32_t isa; /* class32_t * (32-bit pointer) */
2578 uint32_t superclass; /* class32_t * (32-bit pointer) */
2579 uint32_t cache; /* Cache (32-bit pointer) */
2580 uint32_t vtable; /* IMP * (32-bit pointer) */
2581 uint32_t data; /* class_ro32_t * (32-bit pointer) */
2582};
2583
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002584struct class_ro64_t {
2585 uint32_t flags;
2586 uint32_t instanceStart;
2587 uint32_t instanceSize;
2588 uint32_t reserved;
2589 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2590 uint64_t name; // const char * (64-bit pointer)
2591 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2592 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2593 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2594 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2595 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2596};
2597
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002598struct class_ro32_t {
2599 uint32_t flags;
2600 uint32_t instanceStart;
2601 uint32_t instanceSize;
2602 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
2603 uint32_t name; /* const char * (32-bit pointer) */
2604 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
2605 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
2606 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
2607 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
2608 uint32_t baseProperties; /* const struct objc_property_list *
2609 (32-bit pointer) */
2610};
2611
2612/* Values for class_ro{64,32}_t->flags */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002613#define RO_META (1 << 0)
2614#define RO_ROOT (1 << 1)
2615#define RO_HAS_CXX_STRUCTORS (1 << 2)
2616
2617struct method_list64_t {
2618 uint32_t entsize;
2619 uint32_t count;
2620 /* struct method64_t first; These structures follow inline */
2621};
2622
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002623struct method_list32_t {
2624 uint32_t entsize;
2625 uint32_t count;
2626 /* struct method32_t first; These structures follow inline */
2627};
2628
Kevin Enderby0fc11822015-04-01 20:57:01 +00002629struct method64_t {
2630 uint64_t name; /* SEL (64-bit pointer) */
2631 uint64_t types; /* const char * (64-bit pointer) */
2632 uint64_t imp; /* IMP (64-bit pointer) */
2633};
2634
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002635struct method32_t {
2636 uint32_t name; /* SEL (32-bit pointer) */
2637 uint32_t types; /* const char * (32-bit pointer) */
2638 uint32_t imp; /* IMP (32-bit pointer) */
2639};
2640
Kevin Enderby0fc11822015-04-01 20:57:01 +00002641struct protocol_list64_t {
2642 uint64_t count; /* uintptr_t (a 64-bit value) */
2643 /* struct protocol64_t * list[0]; These pointers follow inline */
2644};
2645
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002646struct protocol_list32_t {
2647 uint32_t count; /* uintptr_t (a 32-bit value) */
2648 /* struct protocol32_t * list[0]; These pointers follow inline */
2649};
2650
Kevin Enderby0fc11822015-04-01 20:57:01 +00002651struct protocol64_t {
2652 uint64_t isa; /* id * (64-bit pointer) */
2653 uint64_t name; /* const char * (64-bit pointer) */
2654 uint64_t protocols; /* struct protocol_list64_t *
2655 (64-bit pointer) */
2656 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
2657 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
2658 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
2659 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
2660 uint64_t instanceProperties; /* struct objc_property_list *
2661 (64-bit pointer) */
2662};
2663
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002664struct protocol32_t {
2665 uint32_t isa; /* id * (32-bit pointer) */
2666 uint32_t name; /* const char * (32-bit pointer) */
2667 uint32_t protocols; /* struct protocol_list_t *
2668 (32-bit pointer) */
2669 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
2670 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
2671 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
2672 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
2673 uint32_t instanceProperties; /* struct objc_property_list *
2674 (32-bit pointer) */
2675};
2676
Kevin Enderby0fc11822015-04-01 20:57:01 +00002677struct ivar_list64_t {
2678 uint32_t entsize;
2679 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002680 /* struct ivar64_t first; These structures follow inline */
2681};
2682
2683struct ivar_list32_t {
2684 uint32_t entsize;
2685 uint32_t count;
2686 /* struct ivar32_t first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002687};
2688
2689struct ivar64_t {
2690 uint64_t offset; /* uintptr_t * (64-bit pointer) */
2691 uint64_t name; /* const char * (64-bit pointer) */
2692 uint64_t type; /* const char * (64-bit pointer) */
2693 uint32_t alignment;
2694 uint32_t size;
2695};
2696
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002697struct ivar32_t {
2698 uint32_t offset; /* uintptr_t * (32-bit pointer) */
2699 uint32_t name; /* const char * (32-bit pointer) */
2700 uint32_t type; /* const char * (32-bit pointer) */
2701 uint32_t alignment;
2702 uint32_t size;
2703};
2704
Kevin Enderby0fc11822015-04-01 20:57:01 +00002705struct objc_property_list64 {
2706 uint32_t entsize;
2707 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002708 /* struct objc_property64 first; These structures follow inline */
2709};
2710
2711struct objc_property_list32 {
2712 uint32_t entsize;
2713 uint32_t count;
2714 /* struct objc_property32 first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002715};
2716
2717struct objc_property64 {
2718 uint64_t name; /* const char * (64-bit pointer) */
2719 uint64_t attributes; /* const char * (64-bit pointer) */
2720};
2721
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002722struct objc_property32 {
2723 uint32_t name; /* const char * (32-bit pointer) */
2724 uint32_t attributes; /* const char * (32-bit pointer) */
2725};
2726
Kevin Enderby0fc11822015-04-01 20:57:01 +00002727struct category64_t {
2728 uint64_t name; /* const char * (64-bit pointer) */
2729 uint64_t cls; /* struct class_t * (64-bit pointer) */
2730 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
2731 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
2732 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
2733 uint64_t instanceProperties; /* struct objc_property_list *
2734 (64-bit pointer) */
2735};
2736
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002737struct category32_t {
2738 uint32_t name; /* const char * (32-bit pointer) */
2739 uint32_t cls; /* struct class_t * (32-bit pointer) */
2740 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
2741 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
2742 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
2743 uint32_t instanceProperties; /* struct objc_property_list *
2744 (32-bit pointer) */
2745};
2746
Kevin Enderby0fc11822015-04-01 20:57:01 +00002747struct objc_image_info64 {
2748 uint32_t version;
2749 uint32_t flags;
2750};
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002751struct objc_image_info32 {
2752 uint32_t version;
2753 uint32_t flags;
2754};
Kevin Enderby846c0002015-04-16 17:19:59 +00002755struct imageInfo_t {
2756 uint32_t version;
2757 uint32_t flags;
2758};
Kevin Enderby0fc11822015-04-01 20:57:01 +00002759/* masks for objc_image_info.flags */
2760#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
2761#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
2762
2763struct message_ref64 {
2764 uint64_t imp; /* IMP (64-bit pointer) */
2765 uint64_t sel; /* SEL (64-bit pointer) */
2766};
2767
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002768struct message_ref32 {
2769 uint32_t imp; /* IMP (32-bit pointer) */
2770 uint32_t sel; /* SEL (32-bit pointer) */
2771};
2772
Kevin Enderby846c0002015-04-16 17:19:59 +00002773// Objective-C 1 (32-bit only) meta data structs.
2774
2775struct objc_module_t {
2776 uint32_t version;
2777 uint32_t size;
2778 uint32_t name; /* char * (32-bit pointer) */
2779 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
2780};
2781
2782struct objc_symtab_t {
2783 uint32_t sel_ref_cnt;
2784 uint32_t refs; /* SEL * (32-bit pointer) */
2785 uint16_t cls_def_cnt;
2786 uint16_t cat_def_cnt;
2787 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
2788};
2789
2790struct objc_class_t {
2791 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2792 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
2793 uint32_t name; /* const char * (32-bit pointer) */
2794 int32_t version;
2795 int32_t info;
2796 int32_t instance_size;
2797 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
2798 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
2799 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
2800 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
2801};
2802
2803#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
2804// class is not a metaclass
2805#define CLS_CLASS 0x1
2806// class is a metaclass
2807#define CLS_META 0x2
2808
2809struct objc_category_t {
2810 uint32_t category_name; /* char * (32-bit pointer) */
2811 uint32_t class_name; /* char * (32-bit pointer) */
2812 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
2813 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
2814 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
2815};
2816
2817struct objc_ivar_t {
2818 uint32_t ivar_name; /* char * (32-bit pointer) */
2819 uint32_t ivar_type; /* char * (32-bit pointer) */
2820 int32_t ivar_offset;
2821};
2822
2823struct objc_ivar_list_t {
2824 int32_t ivar_count;
2825 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
2826};
2827
2828struct objc_method_list_t {
2829 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
2830 int32_t method_count;
2831 // struct objc_method_t method_list[1]; /* variable length structure */
2832};
2833
2834struct objc_method_t {
2835 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2836 uint32_t method_types; /* char * (32-bit pointer) */
2837 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
2838 (32-bit pointer) */
2839};
2840
2841struct objc_protocol_list_t {
2842 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
2843 int32_t count;
2844 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
2845 // (32-bit pointer) */
2846};
2847
2848struct objc_protocol_t {
2849 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2850 uint32_t protocol_name; /* char * (32-bit pointer) */
2851 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
2852 uint32_t instance_methods; /* struct objc_method_description_list *
2853 (32-bit pointer) */
2854 uint32_t class_methods; /* struct objc_method_description_list *
2855 (32-bit pointer) */
2856};
2857
2858struct objc_method_description_list_t {
2859 int32_t count;
2860 // struct objc_method_description_t list[1];
2861};
2862
2863struct objc_method_description_t {
2864 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2865 uint32_t types; /* char * (32-bit pointer) */
2866};
2867
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002868inline void swapStruct(struct cfstring64_t &cfs) {
2869 sys::swapByteOrder(cfs.isa);
2870 sys::swapByteOrder(cfs.flags);
2871 sys::swapByteOrder(cfs.characters);
2872 sys::swapByteOrder(cfs.length);
2873}
2874
2875inline void swapStruct(struct class64_t &c) {
2876 sys::swapByteOrder(c.isa);
2877 sys::swapByteOrder(c.superclass);
2878 sys::swapByteOrder(c.cache);
2879 sys::swapByteOrder(c.vtable);
2880 sys::swapByteOrder(c.data);
2881}
2882
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002883inline void swapStruct(struct class32_t &c) {
2884 sys::swapByteOrder(c.isa);
2885 sys::swapByteOrder(c.superclass);
2886 sys::swapByteOrder(c.cache);
2887 sys::swapByteOrder(c.vtable);
2888 sys::swapByteOrder(c.data);
2889}
2890
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002891inline void swapStruct(struct class_ro64_t &cro) {
2892 sys::swapByteOrder(cro.flags);
2893 sys::swapByteOrder(cro.instanceStart);
2894 sys::swapByteOrder(cro.instanceSize);
2895 sys::swapByteOrder(cro.reserved);
2896 sys::swapByteOrder(cro.ivarLayout);
2897 sys::swapByteOrder(cro.name);
2898 sys::swapByteOrder(cro.baseMethods);
2899 sys::swapByteOrder(cro.baseProtocols);
2900 sys::swapByteOrder(cro.ivars);
2901 sys::swapByteOrder(cro.weakIvarLayout);
2902 sys::swapByteOrder(cro.baseProperties);
2903}
2904
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002905inline void swapStruct(struct class_ro32_t &cro) {
2906 sys::swapByteOrder(cro.flags);
2907 sys::swapByteOrder(cro.instanceStart);
2908 sys::swapByteOrder(cro.instanceSize);
2909 sys::swapByteOrder(cro.ivarLayout);
2910 sys::swapByteOrder(cro.name);
2911 sys::swapByteOrder(cro.baseMethods);
2912 sys::swapByteOrder(cro.baseProtocols);
2913 sys::swapByteOrder(cro.ivars);
2914 sys::swapByteOrder(cro.weakIvarLayout);
2915 sys::swapByteOrder(cro.baseProperties);
2916}
2917
Kevin Enderby0fc11822015-04-01 20:57:01 +00002918inline void swapStruct(struct method_list64_t &ml) {
2919 sys::swapByteOrder(ml.entsize);
2920 sys::swapByteOrder(ml.count);
2921}
2922
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002923inline void swapStruct(struct method_list32_t &ml) {
2924 sys::swapByteOrder(ml.entsize);
2925 sys::swapByteOrder(ml.count);
2926}
2927
Kevin Enderby0fc11822015-04-01 20:57:01 +00002928inline void swapStruct(struct method64_t &m) {
2929 sys::swapByteOrder(m.name);
2930 sys::swapByteOrder(m.types);
2931 sys::swapByteOrder(m.imp);
2932}
2933
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002934inline void swapStruct(struct method32_t &m) {
2935 sys::swapByteOrder(m.name);
2936 sys::swapByteOrder(m.types);
2937 sys::swapByteOrder(m.imp);
2938}
2939
Kevin Enderby0fc11822015-04-01 20:57:01 +00002940inline void swapStruct(struct protocol_list64_t &pl) {
2941 sys::swapByteOrder(pl.count);
2942}
2943
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002944inline void swapStruct(struct protocol_list32_t &pl) {
2945 sys::swapByteOrder(pl.count);
2946}
2947
Kevin Enderby0fc11822015-04-01 20:57:01 +00002948inline void swapStruct(struct protocol64_t &p) {
2949 sys::swapByteOrder(p.isa);
2950 sys::swapByteOrder(p.name);
2951 sys::swapByteOrder(p.protocols);
2952 sys::swapByteOrder(p.instanceMethods);
2953 sys::swapByteOrder(p.classMethods);
2954 sys::swapByteOrder(p.optionalInstanceMethods);
2955 sys::swapByteOrder(p.optionalClassMethods);
2956 sys::swapByteOrder(p.instanceProperties);
2957}
2958
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002959inline void swapStruct(struct protocol32_t &p) {
2960 sys::swapByteOrder(p.isa);
2961 sys::swapByteOrder(p.name);
2962 sys::swapByteOrder(p.protocols);
2963 sys::swapByteOrder(p.instanceMethods);
2964 sys::swapByteOrder(p.classMethods);
2965 sys::swapByteOrder(p.optionalInstanceMethods);
2966 sys::swapByteOrder(p.optionalClassMethods);
2967 sys::swapByteOrder(p.instanceProperties);
2968}
2969
Kevin Enderby0fc11822015-04-01 20:57:01 +00002970inline void swapStruct(struct ivar_list64_t &il) {
2971 sys::swapByteOrder(il.entsize);
2972 sys::swapByteOrder(il.count);
2973}
2974
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002975inline void swapStruct(struct ivar_list32_t &il) {
2976 sys::swapByteOrder(il.entsize);
2977 sys::swapByteOrder(il.count);
2978}
2979
Kevin Enderby0fc11822015-04-01 20:57:01 +00002980inline void swapStruct(struct ivar64_t &i) {
2981 sys::swapByteOrder(i.offset);
2982 sys::swapByteOrder(i.name);
2983 sys::swapByteOrder(i.type);
2984 sys::swapByteOrder(i.alignment);
2985 sys::swapByteOrder(i.size);
2986}
2987
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002988inline void swapStruct(struct ivar32_t &i) {
2989 sys::swapByteOrder(i.offset);
2990 sys::swapByteOrder(i.name);
2991 sys::swapByteOrder(i.type);
2992 sys::swapByteOrder(i.alignment);
2993 sys::swapByteOrder(i.size);
2994}
2995
Kevin Enderby0fc11822015-04-01 20:57:01 +00002996inline void swapStruct(struct objc_property_list64 &pl) {
2997 sys::swapByteOrder(pl.entsize);
2998 sys::swapByteOrder(pl.count);
2999}
3000
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003001inline void swapStruct(struct objc_property_list32 &pl) {
3002 sys::swapByteOrder(pl.entsize);
3003 sys::swapByteOrder(pl.count);
3004}
3005
Kevin Enderby0fc11822015-04-01 20:57:01 +00003006inline void swapStruct(struct objc_property64 &op) {
3007 sys::swapByteOrder(op.name);
3008 sys::swapByteOrder(op.attributes);
3009}
3010
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003011inline void swapStruct(struct objc_property32 &op) {
3012 sys::swapByteOrder(op.name);
3013 sys::swapByteOrder(op.attributes);
3014}
3015
Kevin Enderby0fc11822015-04-01 20:57:01 +00003016inline void swapStruct(struct category64_t &c) {
3017 sys::swapByteOrder(c.name);
3018 sys::swapByteOrder(c.cls);
3019 sys::swapByteOrder(c.instanceMethods);
3020 sys::swapByteOrder(c.classMethods);
3021 sys::swapByteOrder(c.protocols);
3022 sys::swapByteOrder(c.instanceProperties);
3023}
3024
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003025inline void swapStruct(struct category32_t &c) {
3026 sys::swapByteOrder(c.name);
3027 sys::swapByteOrder(c.cls);
3028 sys::swapByteOrder(c.instanceMethods);
3029 sys::swapByteOrder(c.classMethods);
3030 sys::swapByteOrder(c.protocols);
3031 sys::swapByteOrder(c.instanceProperties);
3032}
3033
Kevin Enderby0fc11822015-04-01 20:57:01 +00003034inline void swapStruct(struct objc_image_info64 &o) {
3035 sys::swapByteOrder(o.version);
3036 sys::swapByteOrder(o.flags);
3037}
3038
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003039inline void swapStruct(struct objc_image_info32 &o) {
3040 sys::swapByteOrder(o.version);
3041 sys::swapByteOrder(o.flags);
3042}
3043
Kevin Enderby846c0002015-04-16 17:19:59 +00003044inline void swapStruct(struct imageInfo_t &o) {
3045 sys::swapByteOrder(o.version);
3046 sys::swapByteOrder(o.flags);
3047}
3048
Kevin Enderby0fc11822015-04-01 20:57:01 +00003049inline void swapStruct(struct message_ref64 &mr) {
3050 sys::swapByteOrder(mr.imp);
3051 sys::swapByteOrder(mr.sel);
3052}
3053
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003054inline void swapStruct(struct message_ref32 &mr) {
3055 sys::swapByteOrder(mr.imp);
3056 sys::swapByteOrder(mr.sel);
3057}
3058
Kevin Enderby846c0002015-04-16 17:19:59 +00003059inline void swapStruct(struct objc_module_t &module) {
3060 sys::swapByteOrder(module.version);
3061 sys::swapByteOrder(module.size);
3062 sys::swapByteOrder(module.name);
3063 sys::swapByteOrder(module.symtab);
Jingyue Wufedecc42015-04-16 18:43:44 +00003064}
Kevin Enderby846c0002015-04-16 17:19:59 +00003065
3066inline void swapStruct(struct objc_symtab_t &symtab) {
3067 sys::swapByteOrder(symtab.sel_ref_cnt);
3068 sys::swapByteOrder(symtab.refs);
3069 sys::swapByteOrder(symtab.cls_def_cnt);
3070 sys::swapByteOrder(symtab.cat_def_cnt);
Jingyue Wufedecc42015-04-16 18:43:44 +00003071}
Kevin Enderby846c0002015-04-16 17:19:59 +00003072
3073inline void swapStruct(struct objc_class_t &objc_class) {
3074 sys::swapByteOrder(objc_class.isa);
3075 sys::swapByteOrder(objc_class.super_class);
3076 sys::swapByteOrder(objc_class.name);
3077 sys::swapByteOrder(objc_class.version);
3078 sys::swapByteOrder(objc_class.info);
3079 sys::swapByteOrder(objc_class.instance_size);
3080 sys::swapByteOrder(objc_class.ivars);
3081 sys::swapByteOrder(objc_class.methodLists);
3082 sys::swapByteOrder(objc_class.cache);
3083 sys::swapByteOrder(objc_class.protocols);
Jingyue Wufedecc42015-04-16 18:43:44 +00003084}
Kevin Enderby846c0002015-04-16 17:19:59 +00003085
3086inline void swapStruct(struct objc_category_t &objc_category) {
3087 sys::swapByteOrder(objc_category.category_name);
3088 sys::swapByteOrder(objc_category.class_name);
3089 sys::swapByteOrder(objc_category.instance_methods);
3090 sys::swapByteOrder(objc_category.class_methods);
3091 sys::swapByteOrder(objc_category.protocols);
3092}
3093
3094inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3095 sys::swapByteOrder(objc_ivar_list.ivar_count);
3096}
3097
3098inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3099 sys::swapByteOrder(objc_ivar.ivar_name);
3100 sys::swapByteOrder(objc_ivar.ivar_type);
3101 sys::swapByteOrder(objc_ivar.ivar_offset);
Jingyue Wufedecc42015-04-16 18:43:44 +00003102}
Kevin Enderby846c0002015-04-16 17:19:59 +00003103
3104inline void swapStruct(struct objc_method_list_t &method_list) {
3105 sys::swapByteOrder(method_list.obsolete);
3106 sys::swapByteOrder(method_list.method_count);
3107}
3108
3109inline void swapStruct(struct objc_method_t &method) {
3110 sys::swapByteOrder(method.method_name);
3111 sys::swapByteOrder(method.method_types);
3112 sys::swapByteOrder(method.method_imp);
3113}
3114
3115inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3116 sys::swapByteOrder(protocol_list.next);
3117 sys::swapByteOrder(protocol_list.count);
3118}
3119
3120inline void swapStruct(struct objc_protocol_t &protocol) {
3121 sys::swapByteOrder(protocol.isa);
3122 sys::swapByteOrder(protocol.protocol_name);
3123 sys::swapByteOrder(protocol.protocol_list);
3124 sys::swapByteOrder(protocol.instance_methods);
3125 sys::swapByteOrder(protocol.class_methods);
3126}
3127
3128inline void swapStruct(struct objc_method_description_list_t &mdl) {
3129 sys::swapByteOrder(mdl.count);
3130}
3131
3132inline void swapStruct(struct objc_method_description_t &md) {
3133 sys::swapByteOrder(md.name);
3134 sys::swapByteOrder(md.types);
3135}
3136
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003137static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3138 struct DisassembleInfo *info);
3139
3140// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3141// to an Objective-C class and returns the class name. It is also passed the
3142// address of the pointer, so when the pointer is zero as it can be in an .o
3143// file, that is used to look for an external relocation entry with a symbol
3144// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003145static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3146 uint64_t ReferenceValue,
3147 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003148 const char *r;
3149 uint32_t offset, left;
3150 SectionRef S;
3151
3152 // The pointer_value can be 0 in an object file and have a relocation
3153 // entry for the class symbol at the ReferenceValue (the address of the
3154 // pointer).
3155 if (pointer_value == 0) {
3156 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3157 if (r == nullptr || left < sizeof(uint64_t))
3158 return nullptr;
3159 uint64_t n_value;
3160 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3161 if (symbol_name == nullptr)
3162 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00003163 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003164 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3165 return class_name + 2;
3166 else
3167 return nullptr;
3168 }
3169
3170 // The case were the pointer_value is non-zero and points to a class defined
3171 // in this Mach-O file.
3172 r = get_pointer_64(pointer_value, offset, left, S, info);
3173 if (r == nullptr || left < sizeof(struct class64_t))
3174 return nullptr;
3175 struct class64_t c;
3176 memcpy(&c, r, sizeof(struct class64_t));
3177 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3178 swapStruct(c);
3179 if (c.data == 0)
3180 return nullptr;
3181 r = get_pointer_64(c.data, offset, left, S, info);
3182 if (r == nullptr || left < sizeof(struct class_ro64_t))
3183 return nullptr;
3184 struct class_ro64_t cro;
3185 memcpy(&cro, r, sizeof(struct class_ro64_t));
3186 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3187 swapStruct(cro);
3188 if (cro.name == 0)
3189 return nullptr;
3190 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3191 return name;
3192}
3193
3194// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3195// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003196static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3197 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003198 const char *r, *name;
3199 uint32_t offset, left;
3200 SectionRef S;
3201 struct cfstring64_t cfs;
3202 uint64_t cfs_characters;
3203
3204 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3205 if (r == nullptr || left < sizeof(struct cfstring64_t))
3206 return nullptr;
3207 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3208 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3209 swapStruct(cfs);
3210 if (cfs.characters == 0) {
3211 uint64_t n_value;
3212 const char *symbol_name = get_symbol_64(
3213 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3214 if (symbol_name == nullptr)
3215 return nullptr;
3216 cfs_characters = n_value;
3217 } else
3218 cfs_characters = cfs.characters;
3219 name = get_pointer_64(cfs_characters, offset, left, S, info);
3220
3221 return name;
3222}
3223
3224// get_objc2_64bit_selref() is used for disassembly and is passed a the address
3225// of a pointer to an Objective-C selector reference when the pointer value is
3226// zero as in a .o file and is likely to have a external relocation entry with
3227// who's symbol's n_value is the real pointer to the selector name. If that is
3228// the case the real pointer to the selector name is returned else 0 is
3229// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003230static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3231 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003232 uint32_t offset, left;
3233 SectionRef S;
3234
3235 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3236 if (r == nullptr || left < sizeof(uint64_t))
3237 return 0;
3238 uint64_t n_value;
3239 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3240 if (symbol_name == nullptr)
3241 return 0;
3242 return n_value;
3243}
3244
Kevin Enderby0fc11822015-04-01 20:57:01 +00003245static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3246 const char *sectname) {
3247 for (const SectionRef &Section : O->sections()) {
3248 StringRef SectName;
3249 Section.getName(SectName);
3250 DataRefImpl Ref = Section.getRawDataRefImpl();
3251 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3252 if (SegName == segname && SectName == sectname)
3253 return Section;
3254 }
3255 return SectionRef();
3256}
3257
3258static void
3259walk_pointer_list_64(const char *listname, const SectionRef S,
3260 MachOObjectFile *O, struct DisassembleInfo *info,
3261 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3262 if (S == SectionRef())
3263 return;
3264
3265 StringRef SectName;
3266 S.getName(SectName);
3267 DataRefImpl Ref = S.getRawDataRefImpl();
3268 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3269 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3270
3271 StringRef BytesStr;
3272 S.getContents(BytesStr);
3273 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3274
3275 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3276 uint32_t left = S.getSize() - i;
3277 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3278 uint64_t p = 0;
3279 memcpy(&p, Contents + i, size);
3280 if (i + sizeof(uint64_t) > S.getSize())
3281 outs() << listname << " list pointer extends past end of (" << SegName
3282 << "," << SectName << ") section\n";
3283 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3284
3285 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3286 sys::swapByteOrder(p);
3287
3288 uint64_t n_value = 0;
3289 const char *name = get_symbol_64(i, S, info, n_value, p);
3290 if (name == nullptr)
3291 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3292
3293 if (n_value != 0) {
3294 outs() << format("0x%" PRIx64, n_value);
3295 if (p != 0)
3296 outs() << " + " << format("0x%" PRIx64, p);
3297 } else
3298 outs() << format("0x%" PRIx64, p);
3299 if (name != nullptr)
3300 outs() << " " << name;
3301 outs() << "\n";
3302
3303 p += n_value;
3304 if (func)
3305 func(p, info);
3306 }
3307}
3308
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003309static void
3310walk_pointer_list_32(const char *listname, const SectionRef S,
3311 MachOObjectFile *O, struct DisassembleInfo *info,
3312 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3313 if (S == SectionRef())
3314 return;
3315
3316 StringRef SectName;
3317 S.getName(SectName);
3318 DataRefImpl Ref = S.getRawDataRefImpl();
3319 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3320 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3321
3322 StringRef BytesStr;
3323 S.getContents(BytesStr);
3324 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3325
3326 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3327 uint32_t left = S.getSize() - i;
3328 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3329 uint32_t p = 0;
3330 memcpy(&p, Contents + i, size);
3331 if (i + sizeof(uint32_t) > S.getSize())
3332 outs() << listname << " list pointer extends past end of (" << SegName
3333 << "," << SectName << ") section\n";
Kevin Enderbycf261312015-04-06 22:33:43 +00003334 uint32_t Address = S.getAddress() + i;
3335 outs() << format("%08" PRIx32, Address) << " ";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003336
3337 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3338 sys::swapByteOrder(p);
3339 outs() << format("0x%" PRIx32, p);
3340
3341 const char *name = get_symbol_32(i, S, info, p);
3342 if (name != nullptr)
3343 outs() << " " << name;
3344 outs() << "\n";
3345
3346 if (func)
3347 func(p, info);
3348 }
3349}
3350
3351static void print_layout_map(const char *layout_map, uint32_t left) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003352 if (layout_map == nullptr)
3353 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003354 outs() << " layout map: ";
3355 do {
3356 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3357 left--;
3358 layout_map++;
3359 } while (*layout_map != '\0' && left != 0);
3360 outs() << "\n";
3361}
3362
Kevin Enderby0fc11822015-04-01 20:57:01 +00003363static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3364 uint32_t offset, left;
3365 SectionRef S;
3366 const char *layout_map;
3367
3368 if (p == 0)
3369 return;
3370 layout_map = get_pointer_64(p, offset, left, S, info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003371 print_layout_map(layout_map, left);
3372}
3373
3374static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3375 uint32_t offset, left;
3376 SectionRef S;
3377 const char *layout_map;
3378
3379 if (p == 0)
3380 return;
3381 layout_map = get_pointer_32(p, offset, left, S, info);
3382 print_layout_map(layout_map, left);
Kevin Enderby0fc11822015-04-01 20:57:01 +00003383}
3384
3385static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3386 const char *indent) {
3387 struct method_list64_t ml;
3388 struct method64_t m;
3389 const char *r;
3390 uint32_t offset, xoffset, left, i;
3391 SectionRef S, xS;
3392 const char *name, *sym_name;
3393 uint64_t n_value;
3394
3395 r = get_pointer_64(p, offset, left, S, info);
3396 if (r == nullptr)
3397 return;
3398 memset(&ml, '\0', sizeof(struct method_list64_t));
3399 if (left < sizeof(struct method_list64_t)) {
3400 memcpy(&ml, r, left);
3401 outs() << " (method_list_t entends past the end of the section)\n";
3402 } else
3403 memcpy(&ml, r, sizeof(struct method_list64_t));
3404 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3405 swapStruct(ml);
3406 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3407 outs() << indent << "\t\t count " << ml.count << "\n";
3408
3409 p += sizeof(struct method_list64_t);
3410 offset += sizeof(struct method_list64_t);
3411 for (i = 0; i < ml.count; i++) {
3412 r = get_pointer_64(p, offset, left, S, info);
3413 if (r == nullptr)
3414 return;
3415 memset(&m, '\0', sizeof(struct method64_t));
3416 if (left < sizeof(struct method64_t)) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003417 memcpy(&m, r, left);
3418 outs() << indent << " (method_t extends past the end of the section)\n";
Kevin Enderby0fc11822015-04-01 20:57:01 +00003419 } else
3420 memcpy(&m, r, sizeof(struct method64_t));
3421 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3422 swapStruct(m);
3423
3424 outs() << indent << "\t\t name ";
3425 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3426 info, n_value, m.name);
3427 if (n_value != 0) {
3428 if (info->verbose && sym_name != nullptr)
3429 outs() << sym_name;
3430 else
3431 outs() << format("0x%" PRIx64, n_value);
3432 if (m.name != 0)
3433 outs() << " + " << format("0x%" PRIx64, m.name);
3434 } else
3435 outs() << format("0x%" PRIx64, m.name);
3436 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3437 if (name != nullptr)
3438 outs() << format(" %.*s", left, name);
3439 outs() << "\n";
3440
3441 outs() << indent << "\t\t types ";
3442 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3443 info, n_value, m.types);
3444 if (n_value != 0) {
3445 if (info->verbose && sym_name != nullptr)
3446 outs() << sym_name;
3447 else
3448 outs() << format("0x%" PRIx64, n_value);
3449 if (m.types != 0)
3450 outs() << " + " << format("0x%" PRIx64, m.types);
3451 } else
3452 outs() << format("0x%" PRIx64, m.types);
3453 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3454 if (name != nullptr)
3455 outs() << format(" %.*s", left, name);
3456 outs() << "\n";
3457
3458 outs() << indent << "\t\t imp ";
3459 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3460 n_value, m.imp);
3461 if (info->verbose && name == nullptr) {
3462 if (n_value != 0) {
3463 outs() << format("0x%" PRIx64, n_value) << " ";
3464 if (m.imp != 0)
3465 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3466 } else
3467 outs() << format("0x%" PRIx64, m.imp) << " ";
3468 }
3469 if (name != nullptr)
3470 outs() << name;
3471 outs() << "\n";
3472
3473 p += sizeof(struct method64_t);
3474 offset += sizeof(struct method64_t);
3475 }
3476}
3477
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003478static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3479 const char *indent) {
3480 struct method_list32_t ml;
3481 struct method32_t m;
Kevin Enderby846c0002015-04-16 17:19:59 +00003482 const char *r, *name;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003483 uint32_t offset, xoffset, left, i;
3484 SectionRef S, xS;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003485
3486 r = get_pointer_32(p, offset, left, S, info);
3487 if (r == nullptr)
3488 return;
3489 memset(&ml, '\0', sizeof(struct method_list32_t));
3490 if (left < sizeof(struct method_list32_t)) {
3491 memcpy(&ml, r, left);
3492 outs() << " (method_list_t entends past the end of the section)\n";
3493 } else
3494 memcpy(&ml, r, sizeof(struct method_list32_t));
3495 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3496 swapStruct(ml);
3497 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3498 outs() << indent << "\t\t count " << ml.count << "\n";
3499
3500 p += sizeof(struct method_list32_t);
3501 offset += sizeof(struct method_list32_t);
3502 for (i = 0; i < ml.count; i++) {
3503 r = get_pointer_32(p, offset, left, S, info);
3504 if (r == nullptr)
3505 return;
3506 memset(&m, '\0', sizeof(struct method32_t));
3507 if (left < sizeof(struct method32_t)) {
3508 memcpy(&ml, r, left);
3509 outs() << indent << " (method_t entends past the end of the section)\n";
3510 } else
3511 memcpy(&m, r, sizeof(struct method32_t));
3512 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3513 swapStruct(m);
3514
3515 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
3516 name = get_pointer_32(m.name, xoffset, left, xS, info);
3517 if (name != nullptr)
3518 outs() << format(" %.*s", left, name);
3519 outs() << "\n";
3520
3521 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
3522 name = get_pointer_32(m.types, xoffset, left, xS, info);
3523 if (name != nullptr)
3524 outs() << format(" %.*s", left, name);
3525 outs() << "\n";
3526
3527 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
3528 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
3529 m.imp);
3530 if (name != nullptr)
3531 outs() << " " << name;
3532 outs() << "\n";
3533
3534 p += sizeof(struct method32_t);
3535 offset += sizeof(struct method32_t);
3536 }
3537}
3538
Kevin Enderby846c0002015-04-16 17:19:59 +00003539static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
3540 uint32_t offset, left, xleft;
3541 SectionRef S;
3542 struct objc_method_list_t method_list;
3543 struct objc_method_t method;
3544 const char *r, *methods, *name, *SymbolName;
3545 int32_t i;
3546
3547 r = get_pointer_32(p, offset, left, S, info, true);
3548 if (r == nullptr)
3549 return true;
3550
3551 outs() << "\n";
3552 if (left > sizeof(struct objc_method_list_t)) {
3553 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
3554 } else {
3555 outs() << "\t\t objc_method_list extends past end of the section\n";
3556 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
3557 memcpy(&method_list, r, left);
3558 }
3559 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3560 swapStruct(method_list);
3561
3562 outs() << "\t\t obsolete "
3563 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
3564 outs() << "\t\t method_count " << method_list.method_count << "\n";
3565
3566 methods = r + sizeof(struct objc_method_list_t);
3567 for (i = 0; i < method_list.method_count; i++) {
3568 if ((i + 1) * sizeof(struct objc_method_t) > left) {
3569 outs() << "\t\t remaining method's extend past the of the section\n";
3570 break;
3571 }
3572 memcpy(&method, methods + i * sizeof(struct objc_method_t),
3573 sizeof(struct objc_method_t));
3574 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3575 swapStruct(method);
3576
3577 outs() << "\t\t method_name "
3578 << format("0x%08" PRIx32, method.method_name);
3579 if (info->verbose) {
3580 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
3581 if (name != nullptr)
3582 outs() << format(" %.*s", xleft, name);
3583 else
3584 outs() << " (not in an __OBJC section)";
3585 }
3586 outs() << "\n";
3587
3588 outs() << "\t\t method_types "
3589 << format("0x%08" PRIx32, method.method_types);
3590 if (info->verbose) {
3591 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
3592 if (name != nullptr)
3593 outs() << format(" %.*s", xleft, name);
3594 else
3595 outs() << " (not in an __OBJC section)";
3596 }
3597 outs() << "\n";
3598
3599 outs() << "\t\t method_imp "
3600 << format("0x%08" PRIx32, method.method_imp) << " ";
3601 if (info->verbose) {
3602 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
3603 if (SymbolName != nullptr)
3604 outs() << SymbolName;
3605 }
3606 outs() << "\n";
3607 }
3608 return false;
3609}
3610
Kevin Enderby0fc11822015-04-01 20:57:01 +00003611static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
3612 struct protocol_list64_t pl;
3613 uint64_t q, n_value;
3614 struct protocol64_t pc;
3615 const char *r;
3616 uint32_t offset, xoffset, left, i;
3617 SectionRef S, xS;
3618 const char *name, *sym_name;
3619
3620 r = get_pointer_64(p, offset, left, S, info);
3621 if (r == nullptr)
3622 return;
3623 memset(&pl, '\0', sizeof(struct protocol_list64_t));
3624 if (left < sizeof(struct protocol_list64_t)) {
3625 memcpy(&pl, r, left);
3626 outs() << " (protocol_list_t entends past the end of the section)\n";
3627 } else
3628 memcpy(&pl, r, sizeof(struct protocol_list64_t));
3629 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3630 swapStruct(pl);
3631 outs() << " count " << pl.count << "\n";
3632
3633 p += sizeof(struct protocol_list64_t);
3634 offset += sizeof(struct protocol_list64_t);
3635 for (i = 0; i < pl.count; i++) {
3636 r = get_pointer_64(p, offset, left, S, info);
3637 if (r == nullptr)
3638 return;
3639 q = 0;
3640 if (left < sizeof(uint64_t)) {
3641 memcpy(&q, r, left);
3642 outs() << " (protocol_t * entends past the end of the section)\n";
3643 } else
3644 memcpy(&q, r, sizeof(uint64_t));
3645 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3646 sys::swapByteOrder(q);
3647
3648 outs() << "\t\t list[" << i << "] ";
3649 sym_name = get_symbol_64(offset, S, info, n_value, q);
3650 if (n_value != 0) {
3651 if (info->verbose && sym_name != nullptr)
3652 outs() << sym_name;
3653 else
3654 outs() << format("0x%" PRIx64, n_value);
3655 if (q != 0)
3656 outs() << " + " << format("0x%" PRIx64, q);
3657 } else
3658 outs() << format("0x%" PRIx64, q);
3659 outs() << " (struct protocol_t *)\n";
3660
3661 r = get_pointer_64(q + n_value, offset, left, S, info);
3662 if (r == nullptr)
3663 return;
3664 memset(&pc, '\0', sizeof(struct protocol64_t));
3665 if (left < sizeof(struct protocol64_t)) {
3666 memcpy(&pc, r, left);
3667 outs() << " (protocol_t entends past the end of the section)\n";
3668 } else
3669 memcpy(&pc, r, sizeof(struct protocol64_t));
3670 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3671 swapStruct(pc);
3672
3673 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
3674
3675 outs() << "\t\t\t name ";
3676 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
3677 info, n_value, pc.name);
3678 if (n_value != 0) {
3679 if (info->verbose && sym_name != nullptr)
3680 outs() << sym_name;
3681 else
3682 outs() << format("0x%" PRIx64, n_value);
3683 if (pc.name != 0)
3684 outs() << " + " << format("0x%" PRIx64, pc.name);
3685 } else
3686 outs() << format("0x%" PRIx64, pc.name);
3687 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
3688 if (name != nullptr)
3689 outs() << format(" %.*s", left, name);
3690 outs() << "\n";
3691
3692 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
3693
3694 outs() << "\t\t instanceMethods ";
3695 sym_name =
3696 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
3697 S, info, n_value, pc.instanceMethods);
3698 if (n_value != 0) {
3699 if (info->verbose && sym_name != nullptr)
3700 outs() << sym_name;
3701 else
3702 outs() << format("0x%" PRIx64, n_value);
3703 if (pc.instanceMethods != 0)
3704 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
3705 } else
3706 outs() << format("0x%" PRIx64, pc.instanceMethods);
3707 outs() << " (struct method_list_t *)\n";
3708 if (pc.instanceMethods + n_value != 0)
3709 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
3710
3711 outs() << "\t\t classMethods ";
3712 sym_name =
3713 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
3714 info, n_value, pc.classMethods);
3715 if (n_value != 0) {
3716 if (info->verbose && sym_name != nullptr)
3717 outs() << sym_name;
3718 else
3719 outs() << format("0x%" PRIx64, n_value);
3720 if (pc.classMethods != 0)
3721 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
3722 } else
3723 outs() << format("0x%" PRIx64, pc.classMethods);
3724 outs() << " (struct method_list_t *)\n";
3725 if (pc.classMethods + n_value != 0)
3726 print_method_list64_t(pc.classMethods + n_value, info, "\t");
3727
3728 outs() << "\t optionalInstanceMethods "
3729 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
3730 outs() << "\t optionalClassMethods "
3731 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
3732 outs() << "\t instanceProperties "
3733 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
3734
3735 p += sizeof(uint64_t);
3736 offset += sizeof(uint64_t);
3737 }
3738}
3739
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003740static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
3741 struct protocol_list32_t pl;
3742 uint32_t q;
3743 struct protocol32_t pc;
3744 const char *r;
3745 uint32_t offset, xoffset, left, i;
3746 SectionRef S, xS;
3747 const char *name;
3748
3749 r = get_pointer_32(p, offset, left, S, info);
3750 if (r == nullptr)
3751 return;
3752 memset(&pl, '\0', sizeof(struct protocol_list32_t));
3753 if (left < sizeof(struct protocol_list32_t)) {
3754 memcpy(&pl, r, left);
3755 outs() << " (protocol_list_t entends past the end of the section)\n";
3756 } else
3757 memcpy(&pl, r, sizeof(struct protocol_list32_t));
3758 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3759 swapStruct(pl);
3760 outs() << " count " << pl.count << "\n";
3761
3762 p += sizeof(struct protocol_list32_t);
3763 offset += sizeof(struct protocol_list32_t);
3764 for (i = 0; i < pl.count; i++) {
3765 r = get_pointer_32(p, offset, left, S, info);
3766 if (r == nullptr)
3767 return;
3768 q = 0;
3769 if (left < sizeof(uint32_t)) {
3770 memcpy(&q, r, left);
3771 outs() << " (protocol_t * entends past the end of the section)\n";
3772 } else
3773 memcpy(&q, r, sizeof(uint32_t));
3774 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3775 sys::swapByteOrder(q);
3776 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
3777 << " (struct protocol_t *)\n";
3778 r = get_pointer_32(q, offset, left, S, info);
3779 if (r == nullptr)
3780 return;
3781 memset(&pc, '\0', sizeof(struct protocol32_t));
3782 if (left < sizeof(struct protocol32_t)) {
3783 memcpy(&pc, r, left);
3784 outs() << " (protocol_t entends past the end of the section)\n";
3785 } else
3786 memcpy(&pc, r, sizeof(struct protocol32_t));
3787 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3788 swapStruct(pc);
3789 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
3790 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
3791 name = get_pointer_32(pc.name, xoffset, left, xS, info);
3792 if (name != nullptr)
3793 outs() << format(" %.*s", left, name);
3794 outs() << "\n";
3795 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
3796 outs() << "\t\t instanceMethods "
3797 << format("0x%" PRIx32, pc.instanceMethods)
3798 << " (struct method_list_t *)\n";
3799 if (pc.instanceMethods != 0)
3800 print_method_list32_t(pc.instanceMethods, info, "\t");
3801 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
3802 << " (struct method_list_t *)\n";
3803 if (pc.classMethods != 0)
3804 print_method_list32_t(pc.classMethods, info, "\t");
3805 outs() << "\t optionalInstanceMethods "
3806 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
3807 outs() << "\t optionalClassMethods "
3808 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
3809 outs() << "\t instanceProperties "
3810 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
3811 p += sizeof(uint32_t);
3812 offset += sizeof(uint32_t);
3813 }
3814}
3815
Kevin Enderby846c0002015-04-16 17:19:59 +00003816static void print_indent(uint32_t indent) {
3817 for (uint32_t i = 0; i < indent;) {
3818 if (indent - i >= 8) {
3819 outs() << "\t";
3820 i += 8;
3821 } else {
3822 for (uint32_t j = i; j < indent; j++)
3823 outs() << " ";
3824 return;
3825 }
3826 }
3827}
3828
3829static bool print_method_description_list(uint32_t p, uint32_t indent,
3830 struct DisassembleInfo *info) {
3831 uint32_t offset, left, xleft;
3832 SectionRef S;
3833 struct objc_method_description_list_t mdl;
3834 struct objc_method_description_t md;
3835 const char *r, *list, *name;
3836 int32_t i;
3837
3838 r = get_pointer_32(p, offset, left, S, info, true);
3839 if (r == nullptr)
3840 return true;
3841
3842 outs() << "\n";
3843 if (left > sizeof(struct objc_method_description_list_t)) {
3844 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
3845 } else {
3846 print_indent(indent);
3847 outs() << " objc_method_description_list extends past end of the section\n";
3848 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
3849 memcpy(&mdl, r, left);
3850 }
3851 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3852 swapStruct(mdl);
3853
3854 print_indent(indent);
3855 outs() << " count " << mdl.count << "\n";
3856
3857 list = r + sizeof(struct objc_method_description_list_t);
3858 for (i = 0; i < mdl.count; i++) {
3859 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
3860 print_indent(indent);
3861 outs() << " remaining list entries extend past the of the section\n";
3862 break;
3863 }
3864 print_indent(indent);
3865 outs() << " list[" << i << "]\n";
3866 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
3867 sizeof(struct objc_method_description_t));
3868 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3869 swapStruct(md);
3870
3871 print_indent(indent);
3872 outs() << " name " << format("0x%08" PRIx32, md.name);
3873 if (info->verbose) {
3874 name = get_pointer_32(md.name, offset, xleft, S, info, true);
3875 if (name != nullptr)
3876 outs() << format(" %.*s", xleft, name);
3877 else
3878 outs() << " (not in an __OBJC section)";
3879 }
3880 outs() << "\n";
3881
3882 print_indent(indent);
3883 outs() << " types " << format("0x%08" PRIx32, md.types);
3884 if (info->verbose) {
3885 name = get_pointer_32(md.types, offset, xleft, S, info, true);
3886 if (name != nullptr)
3887 outs() << format(" %.*s", xleft, name);
3888 else
3889 outs() << " (not in an __OBJC section)";
3890 }
3891 outs() << "\n";
3892 }
3893 return false;
3894}
3895
3896static bool print_protocol_list(uint32_t p, uint32_t indent,
3897 struct DisassembleInfo *info);
3898
3899static bool print_protocol(uint32_t p, uint32_t indent,
3900 struct DisassembleInfo *info) {
3901 uint32_t offset, left;
3902 SectionRef S;
3903 struct objc_protocol_t protocol;
3904 const char *r, *name;
3905
3906 r = get_pointer_32(p, offset, left, S, info, true);
3907 if (r == nullptr)
3908 return true;
3909
3910 outs() << "\n";
3911 if (left >= sizeof(struct objc_protocol_t)) {
3912 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
3913 } else {
3914 print_indent(indent);
3915 outs() << " Protocol extends past end of the section\n";
3916 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
3917 memcpy(&protocol, r, left);
3918 }
3919 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3920 swapStruct(protocol);
3921
3922 print_indent(indent);
3923 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
3924 << "\n";
3925
3926 print_indent(indent);
3927 outs() << " protocol_name "
3928 << format("0x%08" PRIx32, protocol.protocol_name);
3929 if (info->verbose) {
3930 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
3931 if (name != nullptr)
3932 outs() << format(" %.*s", left, name);
3933 else
3934 outs() << " (not in an __OBJC section)";
3935 }
3936 outs() << "\n";
3937
3938 print_indent(indent);
3939 outs() << " protocol_list "
3940 << format("0x%08" PRIx32, protocol.protocol_list);
3941 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
3942 outs() << " (not in an __OBJC section)\n";
3943
3944 print_indent(indent);
3945 outs() << " instance_methods "
3946 << format("0x%08" PRIx32, protocol.instance_methods);
3947 if (print_method_description_list(protocol.instance_methods, indent, info))
3948 outs() << " (not in an __OBJC section)\n";
3949
3950 print_indent(indent);
3951 outs() << " class_methods "
3952 << format("0x%08" PRIx32, protocol.class_methods);
3953 if (print_method_description_list(protocol.class_methods, indent, info))
3954 outs() << " (not in an __OBJC section)\n";
3955
3956 return false;
3957}
3958
3959static bool print_protocol_list(uint32_t p, uint32_t indent,
3960 struct DisassembleInfo *info) {
3961 uint32_t offset, left, l;
3962 SectionRef S;
3963 struct objc_protocol_list_t protocol_list;
3964 const char *r, *list;
3965 int32_t i;
3966
3967 r = get_pointer_32(p, offset, left, S, info, true);
3968 if (r == nullptr)
3969 return true;
3970
3971 outs() << "\n";
3972 if (left > sizeof(struct objc_protocol_list_t)) {
3973 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
3974 } else {
3975 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
3976 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
3977 memcpy(&protocol_list, r, left);
3978 }
3979 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3980 swapStruct(protocol_list);
3981
3982 print_indent(indent);
3983 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
3984 << "\n";
3985 print_indent(indent);
3986 outs() << " count " << protocol_list.count << "\n";
3987
3988 list = r + sizeof(struct objc_protocol_list_t);
3989 for (i = 0; i < protocol_list.count; i++) {
3990 if ((i + 1) * sizeof(uint32_t) > left) {
3991 outs() << "\t\t remaining list entries extend past the of the section\n";
3992 break;
3993 }
3994 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
3995 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3996 sys::swapByteOrder(l);
3997
3998 print_indent(indent);
3999 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
4000 if (print_protocol(l, indent, info))
4001 outs() << "(not in an __OBJC section)\n";
4002 }
4003 return false;
4004}
4005
Kevin Enderby0fc11822015-04-01 20:57:01 +00004006static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4007 struct ivar_list64_t il;
4008 struct ivar64_t i;
4009 const char *r;
4010 uint32_t offset, xoffset, left, j;
4011 SectionRef S, xS;
4012 const char *name, *sym_name, *ivar_offset_p;
4013 uint64_t ivar_offset, n_value;
4014
4015 r = get_pointer_64(p, offset, left, S, info);
4016 if (r == nullptr)
4017 return;
4018 memset(&il, '\0', sizeof(struct ivar_list64_t));
4019 if (left < sizeof(struct ivar_list64_t)) {
4020 memcpy(&il, r, left);
4021 outs() << " (ivar_list_t entends past the end of the section)\n";
4022 } else
4023 memcpy(&il, r, sizeof(struct ivar_list64_t));
4024 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4025 swapStruct(il);
4026 outs() << " entsize " << il.entsize << "\n";
4027 outs() << " count " << il.count << "\n";
4028
4029 p += sizeof(struct ivar_list64_t);
4030 offset += sizeof(struct ivar_list64_t);
4031 for (j = 0; j < il.count; j++) {
4032 r = get_pointer_64(p, offset, left, S, info);
4033 if (r == nullptr)
4034 return;
4035 memset(&i, '\0', sizeof(struct ivar64_t));
4036 if (left < sizeof(struct ivar64_t)) {
4037 memcpy(&i, r, left);
4038 outs() << " (ivar_t entends past the end of the section)\n";
4039 } else
4040 memcpy(&i, r, sizeof(struct ivar64_t));
4041 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4042 swapStruct(i);
4043
4044 outs() << "\t\t\t offset ";
4045 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4046 info, n_value, i.offset);
4047 if (n_value != 0) {
4048 if (info->verbose && sym_name != nullptr)
4049 outs() << sym_name;
4050 else
4051 outs() << format("0x%" PRIx64, n_value);
4052 if (i.offset != 0)
4053 outs() << " + " << format("0x%" PRIx64, i.offset);
4054 } else
4055 outs() << format("0x%" PRIx64, i.offset);
4056 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4057 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4058 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4059 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4060 sys::swapByteOrder(ivar_offset);
4061 outs() << " " << ivar_offset << "\n";
4062 } else
4063 outs() << "\n";
4064
4065 outs() << "\t\t\t name ";
4066 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4067 n_value, i.name);
4068 if (n_value != 0) {
4069 if (info->verbose && sym_name != nullptr)
4070 outs() << sym_name;
4071 else
4072 outs() << format("0x%" PRIx64, n_value);
4073 if (i.name != 0)
4074 outs() << " + " << format("0x%" PRIx64, i.name);
4075 } else
4076 outs() << format("0x%" PRIx64, i.name);
4077 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4078 if (name != nullptr)
4079 outs() << format(" %.*s", left, name);
4080 outs() << "\n";
4081
4082 outs() << "\t\t\t type ";
4083 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4084 n_value, i.name);
4085 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4086 if (n_value != 0) {
4087 if (info->verbose && sym_name != nullptr)
4088 outs() << sym_name;
4089 else
4090 outs() << format("0x%" PRIx64, n_value);
4091 if (i.type != 0)
4092 outs() << " + " << format("0x%" PRIx64, i.type);
4093 } else
4094 outs() << format("0x%" PRIx64, i.type);
4095 if (name != nullptr)
4096 outs() << format(" %.*s", left, name);
4097 outs() << "\n";
4098
4099 outs() << "\t\t\talignment " << i.alignment << "\n";
4100 outs() << "\t\t\t size " << i.size << "\n";
4101
4102 p += sizeof(struct ivar64_t);
4103 offset += sizeof(struct ivar64_t);
4104 }
4105}
4106
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004107static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4108 struct ivar_list32_t il;
4109 struct ivar32_t i;
4110 const char *r;
4111 uint32_t offset, xoffset, left, j;
4112 SectionRef S, xS;
4113 const char *name, *ivar_offset_p;
4114 uint32_t ivar_offset;
4115
4116 r = get_pointer_32(p, offset, left, S, info);
4117 if (r == nullptr)
4118 return;
4119 memset(&il, '\0', sizeof(struct ivar_list32_t));
4120 if (left < sizeof(struct ivar_list32_t)) {
4121 memcpy(&il, r, left);
4122 outs() << " (ivar_list_t entends past the end of the section)\n";
4123 } else
4124 memcpy(&il, r, sizeof(struct ivar_list32_t));
4125 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4126 swapStruct(il);
4127 outs() << " entsize " << il.entsize << "\n";
4128 outs() << " count " << il.count << "\n";
4129
4130 p += sizeof(struct ivar_list32_t);
4131 offset += sizeof(struct ivar_list32_t);
4132 for (j = 0; j < il.count; j++) {
4133 r = get_pointer_32(p, offset, left, S, info);
4134 if (r == nullptr)
4135 return;
4136 memset(&i, '\0', sizeof(struct ivar32_t));
4137 if (left < sizeof(struct ivar32_t)) {
4138 memcpy(&i, r, left);
4139 outs() << " (ivar_t entends past the end of the section)\n";
4140 } else
4141 memcpy(&i, r, sizeof(struct ivar32_t));
4142 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4143 swapStruct(i);
4144
4145 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4146 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4147 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4148 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4149 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4150 sys::swapByteOrder(ivar_offset);
4151 outs() << " " << ivar_offset << "\n";
4152 } else
4153 outs() << "\n";
4154
4155 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4156 name = get_pointer_32(i.name, xoffset, left, xS, info);
4157 if (name != nullptr)
4158 outs() << format(" %.*s", left, name);
4159 outs() << "\n";
4160
4161 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4162 name = get_pointer_32(i.type, xoffset, left, xS, info);
4163 if (name != nullptr)
4164 outs() << format(" %.*s", left, name);
4165 outs() << "\n";
4166
4167 outs() << "\t\t\talignment " << i.alignment << "\n";
4168 outs() << "\t\t\t size " << i.size << "\n";
4169
4170 p += sizeof(struct ivar32_t);
4171 offset += sizeof(struct ivar32_t);
4172 }
4173}
4174
Kevin Enderby0fc11822015-04-01 20:57:01 +00004175static void print_objc_property_list64(uint64_t p,
4176 struct DisassembleInfo *info) {
4177 struct objc_property_list64 opl;
4178 struct objc_property64 op;
4179 const char *r;
4180 uint32_t offset, xoffset, left, j;
4181 SectionRef S, xS;
4182 const char *name, *sym_name;
4183 uint64_t n_value;
4184
4185 r = get_pointer_64(p, offset, left, S, info);
4186 if (r == nullptr)
4187 return;
4188 memset(&opl, '\0', sizeof(struct objc_property_list64));
4189 if (left < sizeof(struct objc_property_list64)) {
4190 memcpy(&opl, r, left);
4191 outs() << " (objc_property_list entends past the end of the section)\n";
4192 } else
4193 memcpy(&opl, r, sizeof(struct objc_property_list64));
4194 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4195 swapStruct(opl);
4196 outs() << " entsize " << opl.entsize << "\n";
4197 outs() << " count " << opl.count << "\n";
4198
4199 p += sizeof(struct objc_property_list64);
4200 offset += sizeof(struct objc_property_list64);
4201 for (j = 0; j < opl.count; j++) {
4202 r = get_pointer_64(p, offset, left, S, info);
4203 if (r == nullptr)
4204 return;
4205 memset(&op, '\0', sizeof(struct objc_property64));
4206 if (left < sizeof(struct objc_property64)) {
4207 memcpy(&op, r, left);
4208 outs() << " (objc_property entends past the end of the section)\n";
4209 } else
4210 memcpy(&op, r, sizeof(struct objc_property64));
4211 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4212 swapStruct(op);
4213
4214 outs() << "\t\t\t name ";
4215 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4216 info, n_value, op.name);
4217 if (n_value != 0) {
4218 if (info->verbose && sym_name != nullptr)
4219 outs() << sym_name;
4220 else
4221 outs() << format("0x%" PRIx64, n_value);
4222 if (op.name != 0)
4223 outs() << " + " << format("0x%" PRIx64, op.name);
4224 } else
4225 outs() << format("0x%" PRIx64, op.name);
4226 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4227 if (name != nullptr)
4228 outs() << format(" %.*s", left, name);
4229 outs() << "\n";
4230
4231 outs() << "\t\t\tattributes ";
4232 sym_name =
4233 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4234 info, n_value, op.attributes);
4235 if (n_value != 0) {
4236 if (info->verbose && sym_name != nullptr)
4237 outs() << sym_name;
4238 else
4239 outs() << format("0x%" PRIx64, n_value);
4240 if (op.attributes != 0)
4241 outs() << " + " << format("0x%" PRIx64, op.attributes);
4242 } else
4243 outs() << format("0x%" PRIx64, op.attributes);
4244 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4245 if (name != nullptr)
4246 outs() << format(" %.*s", left, name);
4247 outs() << "\n";
4248
4249 p += sizeof(struct objc_property64);
4250 offset += sizeof(struct objc_property64);
4251 }
4252}
4253
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004254static void print_objc_property_list32(uint32_t p,
4255 struct DisassembleInfo *info) {
4256 struct objc_property_list32 opl;
4257 struct objc_property32 op;
4258 const char *r;
4259 uint32_t offset, xoffset, left, j;
4260 SectionRef S, xS;
4261 const char *name;
4262
4263 r = get_pointer_32(p, offset, left, S, info);
4264 if (r == nullptr)
4265 return;
4266 memset(&opl, '\0', sizeof(struct objc_property_list32));
4267 if (left < sizeof(struct objc_property_list32)) {
4268 memcpy(&opl, r, left);
4269 outs() << " (objc_property_list entends past the end of the section)\n";
4270 } else
4271 memcpy(&opl, r, sizeof(struct objc_property_list32));
4272 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4273 swapStruct(opl);
4274 outs() << " entsize " << opl.entsize << "\n";
4275 outs() << " count " << opl.count << "\n";
4276
4277 p += sizeof(struct objc_property_list32);
4278 offset += sizeof(struct objc_property_list32);
4279 for (j = 0; j < opl.count; j++) {
4280 r = get_pointer_32(p, offset, left, S, info);
4281 if (r == nullptr)
4282 return;
4283 memset(&op, '\0', sizeof(struct objc_property32));
4284 if (left < sizeof(struct objc_property32)) {
4285 memcpy(&op, r, left);
4286 outs() << " (objc_property entends past the end of the section)\n";
4287 } else
4288 memcpy(&op, r, sizeof(struct objc_property32));
4289 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4290 swapStruct(op);
4291
4292 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4293 name = get_pointer_32(op.name, xoffset, left, xS, info);
4294 if (name != nullptr)
4295 outs() << format(" %.*s", left, name);
4296 outs() << "\n";
4297
4298 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4299 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4300 if (name != nullptr)
4301 outs() << format(" %.*s", left, name);
4302 outs() << "\n";
4303
4304 p += sizeof(struct objc_property32);
4305 offset += sizeof(struct objc_property32);
4306 }
4307}
4308
Richard Smith81ff44d2015-10-09 22:09:56 +00004309static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
Kevin Enderby0fc11822015-04-01 20:57:01 +00004310 bool &is_meta_class) {
4311 struct class_ro64_t cro;
4312 const char *r;
4313 uint32_t offset, xoffset, left;
4314 SectionRef S, xS;
4315 const char *name, *sym_name;
4316 uint64_t n_value;
4317
4318 r = get_pointer_64(p, offset, left, S, info);
4319 if (r == nullptr || left < sizeof(struct class_ro64_t))
Richard Smith81ff44d2015-10-09 22:09:56 +00004320 return false;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004321 memset(&cro, '\0', sizeof(struct class_ro64_t));
4322 if (left < sizeof(struct class_ro64_t)) {
4323 memcpy(&cro, r, left);
4324 outs() << " (class_ro_t entends past the end of the section)\n";
4325 } else
4326 memcpy(&cro, r, sizeof(struct class_ro64_t));
4327 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4328 swapStruct(cro);
4329 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4330 if (cro.flags & RO_META)
4331 outs() << " RO_META";
4332 if (cro.flags & RO_ROOT)
4333 outs() << " RO_ROOT";
4334 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4335 outs() << " RO_HAS_CXX_STRUCTORS";
4336 outs() << "\n";
4337 outs() << " instanceStart " << cro.instanceStart << "\n";
4338 outs() << " instanceSize " << cro.instanceSize << "\n";
4339 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4340 << "\n";
4341 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4342 << "\n";
4343 print_layout_map64(cro.ivarLayout, info);
4344
4345 outs() << " name ";
4346 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4347 info, n_value, cro.name);
4348 if (n_value != 0) {
4349 if (info->verbose && sym_name != nullptr)
4350 outs() << sym_name;
4351 else
4352 outs() << format("0x%" PRIx64, n_value);
4353 if (cro.name != 0)
4354 outs() << " + " << format("0x%" PRIx64, cro.name);
4355 } else
4356 outs() << format("0x%" PRIx64, cro.name);
4357 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4358 if (name != nullptr)
4359 outs() << format(" %.*s", left, name);
4360 outs() << "\n";
4361
4362 outs() << " baseMethods ";
4363 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4364 S, info, n_value, cro.baseMethods);
4365 if (n_value != 0) {
4366 if (info->verbose && sym_name != nullptr)
4367 outs() << sym_name;
4368 else
4369 outs() << format("0x%" PRIx64, n_value);
4370 if (cro.baseMethods != 0)
4371 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4372 } else
4373 outs() << format("0x%" PRIx64, cro.baseMethods);
4374 outs() << " (struct method_list_t *)\n";
4375 if (cro.baseMethods + n_value != 0)
4376 print_method_list64_t(cro.baseMethods + n_value, info, "");
4377
4378 outs() << " baseProtocols ";
4379 sym_name =
4380 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4381 info, n_value, cro.baseProtocols);
4382 if (n_value != 0) {
4383 if (info->verbose && sym_name != nullptr)
4384 outs() << sym_name;
4385 else
4386 outs() << format("0x%" PRIx64, n_value);
4387 if (cro.baseProtocols != 0)
4388 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4389 } else
4390 outs() << format("0x%" PRIx64, cro.baseProtocols);
4391 outs() << "\n";
4392 if (cro.baseProtocols + n_value != 0)
4393 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4394
4395 outs() << " ivars ";
4396 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004397 info, n_value, cro.ivars);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004398 if (n_value != 0) {
4399 if (info->verbose && sym_name != nullptr)
4400 outs() << sym_name;
4401 else
4402 outs() << format("0x%" PRIx64, n_value);
4403 if (cro.ivars != 0)
4404 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4405 } else
4406 outs() << format("0x%" PRIx64, cro.ivars);
4407 outs() << "\n";
4408 if (cro.ivars + n_value != 0)
4409 print_ivar_list64_t(cro.ivars + n_value, info);
4410
4411 outs() << " weakIvarLayout ";
4412 sym_name =
4413 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4414 info, n_value, cro.weakIvarLayout);
4415 if (n_value != 0) {
4416 if (info->verbose && sym_name != nullptr)
4417 outs() << sym_name;
4418 else
4419 outs() << format("0x%" PRIx64, n_value);
4420 if (cro.weakIvarLayout != 0)
4421 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4422 } else
4423 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4424 outs() << "\n";
4425 print_layout_map64(cro.weakIvarLayout + n_value, info);
4426
4427 outs() << " baseProperties ";
4428 sym_name =
4429 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4430 info, n_value, cro.baseProperties);
4431 if (n_value != 0) {
4432 if (info->verbose && sym_name != nullptr)
4433 outs() << sym_name;
4434 else
4435 outs() << format("0x%" PRIx64, n_value);
4436 if (cro.baseProperties != 0)
4437 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4438 } else
4439 outs() << format("0x%" PRIx64, cro.baseProperties);
4440 outs() << "\n";
4441 if (cro.baseProperties + n_value != 0)
4442 print_objc_property_list64(cro.baseProperties + n_value, info);
4443
Rafael Espindolab9091322015-10-24 23:19:10 +00004444 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004445 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004446}
4447
Richard Smith81ff44d2015-10-09 22:09:56 +00004448static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004449 bool &is_meta_class) {
4450 struct class_ro32_t cro;
4451 const char *r;
4452 uint32_t offset, xoffset, left;
4453 SectionRef S, xS;
4454 const char *name;
4455
4456 r = get_pointer_32(p, offset, left, S, info);
4457 if (r == nullptr)
Richard Smith81ff44d2015-10-09 22:09:56 +00004458 return false;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004459 memset(&cro, '\0', sizeof(struct class_ro32_t));
4460 if (left < sizeof(struct class_ro32_t)) {
4461 memcpy(&cro, r, left);
4462 outs() << " (class_ro_t entends past the end of the section)\n";
4463 } else
4464 memcpy(&cro, r, sizeof(struct class_ro32_t));
4465 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4466 swapStruct(cro);
4467 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4468 if (cro.flags & RO_META)
4469 outs() << " RO_META";
4470 if (cro.flags & RO_ROOT)
4471 outs() << " RO_ROOT";
4472 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4473 outs() << " RO_HAS_CXX_STRUCTORS";
4474 outs() << "\n";
4475 outs() << " instanceStart " << cro.instanceStart << "\n";
4476 outs() << " instanceSize " << cro.instanceSize << "\n";
4477 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4478 << "\n";
4479 print_layout_map32(cro.ivarLayout, info);
4480
4481 outs() << " name " << format("0x%" PRIx32, cro.name);
4482 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4483 if (name != nullptr)
4484 outs() << format(" %.*s", left, name);
4485 outs() << "\n";
4486
4487 outs() << " baseMethods "
4488 << format("0x%" PRIx32, cro.baseMethods)
4489 << " (struct method_list_t *)\n";
4490 if (cro.baseMethods != 0)
4491 print_method_list32_t(cro.baseMethods, info, "");
4492
4493 outs() << " baseProtocols "
4494 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4495 if (cro.baseProtocols != 0)
4496 print_protocol_list32_t(cro.baseProtocols, info);
4497 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4498 << "\n";
4499 if (cro.ivars != 0)
4500 print_ivar_list32_t(cro.ivars, info);
4501 outs() << " weakIvarLayout "
4502 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4503 print_layout_map32(cro.weakIvarLayout, info);
4504 outs() << " baseProperties "
4505 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4506 if (cro.baseProperties != 0)
4507 print_objc_property_list32(cro.baseProperties, info);
Rafael Espindolab9091322015-10-24 23:19:10 +00004508 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004509 return true;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004510}
4511
Kevin Enderby0fc11822015-04-01 20:57:01 +00004512static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4513 struct class64_t c;
4514 const char *r;
4515 uint32_t offset, left;
4516 SectionRef S;
4517 const char *name;
4518 uint64_t isa_n_value, n_value;
4519
4520 r = get_pointer_64(p, offset, left, S, info);
4521 if (r == nullptr || left < sizeof(struct class64_t))
4522 return;
4523 memset(&c, '\0', sizeof(struct class64_t));
4524 if (left < sizeof(struct class64_t)) {
4525 memcpy(&c, r, left);
4526 outs() << " (class_t entends past the end of the section)\n";
4527 } else
4528 memcpy(&c, r, sizeof(struct class64_t));
4529 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4530 swapStruct(c);
4531
4532 outs() << " isa " << format("0x%" PRIx64, c.isa);
4533 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
4534 isa_n_value, c.isa);
4535 if (name != nullptr)
4536 outs() << " " << name;
4537 outs() << "\n";
4538
4539 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
4540 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
4541 n_value, c.superclass);
4542 if (name != nullptr)
4543 outs() << " " << name;
4544 outs() << "\n";
4545
4546 outs() << " cache " << format("0x%" PRIx64, c.cache);
4547 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
4548 n_value, c.cache);
4549 if (name != nullptr)
4550 outs() << " " << name;
4551 outs() << "\n";
4552
4553 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
4554 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
4555 n_value, c.vtable);
4556 if (name != nullptr)
4557 outs() << " " << name;
4558 outs() << "\n";
4559
4560 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
4561 n_value, c.data);
4562 outs() << " data ";
4563 if (n_value != 0) {
4564 if (info->verbose && name != nullptr)
4565 outs() << name;
4566 else
4567 outs() << format("0x%" PRIx64, n_value);
4568 if (c.data != 0)
4569 outs() << " + " << format("0x%" PRIx64, c.data);
4570 } else
4571 outs() << format("0x%" PRIx64, c.data);
4572 outs() << " (struct class_ro_t *)";
4573
4574 // This is a Swift class if some of the low bits of the pointer are set.
4575 if ((c.data + n_value) & 0x7)
4576 outs() << " Swift class";
4577 outs() << "\n";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004578 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004579 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
4580 return;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004581
Kevin Enderbyaac75382015-10-08 16:56:35 +00004582 if (!is_meta_class &&
4583 c.isa + isa_n_value != p &&
4584 c.isa + isa_n_value != 0 &&
4585 info->depth < 100) {
4586 info->depth++;
4587 outs() << "Meta Class\n";
4588 print_class64_t(c.isa + isa_n_value, info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004589 }
4590}
4591
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004592static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
4593 struct class32_t c;
4594 const char *r;
4595 uint32_t offset, left;
4596 SectionRef S;
4597 const char *name;
4598
4599 r = get_pointer_32(p, offset, left, S, info);
4600 if (r == nullptr)
4601 return;
4602 memset(&c, '\0', sizeof(struct class32_t));
4603 if (left < sizeof(struct class32_t)) {
4604 memcpy(&c, r, left);
4605 outs() << " (class_t entends past the end of the section)\n";
4606 } else
4607 memcpy(&c, r, sizeof(struct class32_t));
4608 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4609 swapStruct(c);
4610
4611 outs() << " isa " << format("0x%" PRIx32, c.isa);
4612 name =
4613 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
4614 if (name != nullptr)
4615 outs() << " " << name;
4616 outs() << "\n";
4617
4618 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
4619 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
4620 c.superclass);
4621 if (name != nullptr)
4622 outs() << " " << name;
4623 outs() << "\n";
4624
4625 outs() << " cache " << format("0x%" PRIx32, c.cache);
4626 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
4627 c.cache);
4628 if (name != nullptr)
4629 outs() << " " << name;
4630 outs() << "\n";
4631
4632 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
4633 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
4634 c.vtable);
4635 if (name != nullptr)
4636 outs() << " " << name;
4637 outs() << "\n";
4638
4639 name =
4640 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
4641 outs() << " data " << format("0x%" PRIx32, c.data)
4642 << " (struct class_ro_t *)";
4643
4644 // This is a Swift class if some of the low bits of the pointer are set.
4645 if (c.data & 0x3)
4646 outs() << " Swift class";
4647 outs() << "\n";
4648 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004649 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
4650 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004651
Hans Wennborgcc9deb42015-09-29 18:02:48 +00004652 if (!is_meta_class) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004653 outs() << "Meta Class\n";
4654 print_class32_t(c.isa, info);
4655 }
4656}
4657
Kevin Enderby846c0002015-04-16 17:19:59 +00004658static void print_objc_class_t(struct objc_class_t *objc_class,
4659 struct DisassembleInfo *info) {
4660 uint32_t offset, left, xleft;
4661 const char *name, *p, *ivar_list;
4662 SectionRef S;
4663 int32_t i;
4664 struct objc_ivar_list_t objc_ivar_list;
4665 struct objc_ivar_t ivar;
4666
4667 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
4668 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
4669 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
4670 if (name != nullptr)
4671 outs() << format(" %.*s", left, name);
4672 else
4673 outs() << " (not in an __OBJC section)";
4674 }
4675 outs() << "\n";
4676
4677 outs() << "\t super_class "
4678 << format("0x%08" PRIx32, objc_class->super_class);
4679 if (info->verbose) {
4680 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
4681 if (name != nullptr)
4682 outs() << format(" %.*s", left, name);
4683 else
4684 outs() << " (not in an __OBJC section)";
4685 }
4686 outs() << "\n";
4687
4688 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
4689 if (info->verbose) {
4690 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
4691 if (name != nullptr)
4692 outs() << format(" %.*s", left, name);
4693 else
4694 outs() << " (not in an __OBJC section)";
4695 }
4696 outs() << "\n";
4697
4698 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
4699 << "\n";
4700
4701 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
4702 if (info->verbose) {
4703 if (CLS_GETINFO(objc_class, CLS_CLASS))
4704 outs() << " CLS_CLASS";
4705 else if (CLS_GETINFO(objc_class, CLS_META))
4706 outs() << " CLS_META";
4707 }
4708 outs() << "\n";
4709
4710 outs() << "\t instance_size "
4711 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
4712
4713 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
4714 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
4715 if (p != nullptr) {
4716 if (left > sizeof(struct objc_ivar_list_t)) {
4717 outs() << "\n";
4718 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
4719 } else {
4720 outs() << " (entends past the end of the section)\n";
4721 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
4722 memcpy(&objc_ivar_list, p, left);
4723 }
4724 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4725 swapStruct(objc_ivar_list);
4726 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
4727 ivar_list = p + sizeof(struct objc_ivar_list_t);
4728 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
4729 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
4730 outs() << "\t\t remaining ivar's extend past the of the section\n";
4731 break;
4732 }
4733 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
4734 sizeof(struct objc_ivar_t));
4735 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4736 swapStruct(ivar);
4737
4738 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
4739 if (info->verbose) {
4740 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
4741 if (name != nullptr)
4742 outs() << format(" %.*s", xleft, name);
4743 else
4744 outs() << " (not in an __OBJC section)";
4745 }
4746 outs() << "\n";
4747
4748 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
4749 if (info->verbose) {
4750 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
4751 if (name != nullptr)
4752 outs() << format(" %.*s", xleft, name);
4753 else
4754 outs() << " (not in an __OBJC section)";
4755 }
4756 outs() << "\n";
4757
4758 outs() << "\t\t ivar_offset "
4759 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
4760 }
4761 } else {
4762 outs() << " (not in an __OBJC section)\n";
4763 }
4764
4765 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
4766 if (print_method_list(objc_class->methodLists, info))
4767 outs() << " (not in an __OBJC section)\n";
4768
4769 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
4770 << "\n";
4771
4772 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
4773 if (print_protocol_list(objc_class->protocols, 16, info))
4774 outs() << " (not in an __OBJC section)\n";
4775}
4776
4777static void print_objc_objc_category_t(struct objc_category_t *objc_category,
4778 struct DisassembleInfo *info) {
4779 uint32_t offset, left;
4780 const char *name;
4781 SectionRef S;
4782
4783 outs() << "\t category name "
4784 << format("0x%08" PRIx32, objc_category->category_name);
4785 if (info->verbose) {
4786 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
4787 true);
4788 if (name != nullptr)
4789 outs() << format(" %.*s", left, name);
4790 else
4791 outs() << " (not in an __OBJC section)";
4792 }
4793 outs() << "\n";
4794
4795 outs() << "\t\t class name "
4796 << format("0x%08" PRIx32, objc_category->class_name);
4797 if (info->verbose) {
4798 name =
4799 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
4800 if (name != nullptr)
4801 outs() << format(" %.*s", left, name);
4802 else
4803 outs() << " (not in an __OBJC section)";
4804 }
4805 outs() << "\n";
4806
4807 outs() << "\t instance methods "
4808 << format("0x%08" PRIx32, objc_category->instance_methods);
4809 if (print_method_list(objc_category->instance_methods, info))
4810 outs() << " (not in an __OBJC section)\n";
4811
4812 outs() << "\t class methods "
4813 << format("0x%08" PRIx32, objc_category->class_methods);
4814 if (print_method_list(objc_category->class_methods, info))
4815 outs() << " (not in an __OBJC section)\n";
4816}
4817
Kevin Enderby0fc11822015-04-01 20:57:01 +00004818static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
4819 struct category64_t c;
4820 const char *r;
4821 uint32_t offset, xoffset, left;
4822 SectionRef S, xS;
4823 const char *name, *sym_name;
4824 uint64_t n_value;
4825
4826 r = get_pointer_64(p, offset, left, S, info);
4827 if (r == nullptr)
4828 return;
4829 memset(&c, '\0', sizeof(struct category64_t));
4830 if (left < sizeof(struct category64_t)) {
4831 memcpy(&c, r, left);
4832 outs() << " (category_t entends past the end of the section)\n";
4833 } else
4834 memcpy(&c, r, sizeof(struct category64_t));
4835 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4836 swapStruct(c);
4837
4838 outs() << " name ";
4839 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
4840 info, n_value, c.name);
4841 if (n_value != 0) {
4842 if (info->verbose && sym_name != nullptr)
4843 outs() << sym_name;
4844 else
4845 outs() << format("0x%" PRIx64, n_value);
4846 if (c.name != 0)
4847 outs() << " + " << format("0x%" PRIx64, c.name);
4848 } else
4849 outs() << format("0x%" PRIx64, c.name);
4850 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
4851 if (name != nullptr)
4852 outs() << format(" %.*s", left, name);
4853 outs() << "\n";
4854
4855 outs() << " cls ";
4856 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
4857 n_value, c.cls);
4858 if (n_value != 0) {
4859 if (info->verbose && sym_name != nullptr)
4860 outs() << sym_name;
4861 else
4862 outs() << format("0x%" PRIx64, n_value);
4863 if (c.cls != 0)
4864 outs() << " + " << format("0x%" PRIx64, c.cls);
4865 } else
4866 outs() << format("0x%" PRIx64, c.cls);
4867 outs() << "\n";
4868 if (c.cls + n_value != 0)
4869 print_class64_t(c.cls + n_value, info);
4870
4871 outs() << " instanceMethods ";
4872 sym_name =
4873 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
4874 info, n_value, c.instanceMethods);
4875 if (n_value != 0) {
4876 if (info->verbose && sym_name != nullptr)
4877 outs() << sym_name;
4878 else
4879 outs() << format("0x%" PRIx64, n_value);
4880 if (c.instanceMethods != 0)
4881 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
4882 } else
4883 outs() << format("0x%" PRIx64, c.instanceMethods);
4884 outs() << "\n";
4885 if (c.instanceMethods + n_value != 0)
4886 print_method_list64_t(c.instanceMethods + n_value, info, "");
4887
4888 outs() << " classMethods ";
4889 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
4890 S, info, n_value, c.classMethods);
4891 if (n_value != 0) {
4892 if (info->verbose && sym_name != nullptr)
4893 outs() << sym_name;
4894 else
4895 outs() << format("0x%" PRIx64, n_value);
4896 if (c.classMethods != 0)
4897 outs() << " + " << format("0x%" PRIx64, c.classMethods);
4898 } else
4899 outs() << format("0x%" PRIx64, c.classMethods);
4900 outs() << "\n";
4901 if (c.classMethods + n_value != 0)
4902 print_method_list64_t(c.classMethods + n_value, info, "");
4903
4904 outs() << " protocols ";
4905 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
4906 info, n_value, c.protocols);
4907 if (n_value != 0) {
4908 if (info->verbose && sym_name != nullptr)
4909 outs() << sym_name;
4910 else
4911 outs() << format("0x%" PRIx64, n_value);
4912 if (c.protocols != 0)
4913 outs() << " + " << format("0x%" PRIx64, c.protocols);
4914 } else
4915 outs() << format("0x%" PRIx64, c.protocols);
4916 outs() << "\n";
4917 if (c.protocols + n_value != 0)
4918 print_protocol_list64_t(c.protocols + n_value, info);
4919
4920 outs() << "instanceProperties ";
4921 sym_name =
4922 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
4923 S, info, n_value, c.instanceProperties);
4924 if (n_value != 0) {
4925 if (info->verbose && sym_name != nullptr)
4926 outs() << sym_name;
4927 else
4928 outs() << format("0x%" PRIx64, n_value);
4929 if (c.instanceProperties != 0)
4930 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
4931 } else
4932 outs() << format("0x%" PRIx64, c.instanceProperties);
4933 outs() << "\n";
4934 if (c.instanceProperties + n_value != 0)
4935 print_objc_property_list64(c.instanceProperties + n_value, info);
4936}
4937
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004938static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
4939 struct category32_t c;
4940 const char *r;
4941 uint32_t offset, left;
4942 SectionRef S, xS;
4943 const char *name;
4944
4945 r = get_pointer_32(p, offset, left, S, info);
4946 if (r == nullptr)
4947 return;
4948 memset(&c, '\0', sizeof(struct category32_t));
4949 if (left < sizeof(struct category32_t)) {
4950 memcpy(&c, r, left);
4951 outs() << " (category_t entends past the end of the section)\n";
4952 } else
4953 memcpy(&c, r, sizeof(struct category32_t));
4954 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4955 swapStruct(c);
4956
4957 outs() << " name " << format("0x%" PRIx32, c.name);
4958 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
4959 c.name);
Hans Wennborgcc9deb42015-09-29 18:02:48 +00004960 if (name)
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004961 outs() << " " << name;
4962 outs() << "\n";
4963
4964 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
4965 if (c.cls != 0)
4966 print_class32_t(c.cls, info);
4967 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
4968 << "\n";
4969 if (c.instanceMethods != 0)
4970 print_method_list32_t(c.instanceMethods, info, "");
4971 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
4972 << "\n";
4973 if (c.classMethods != 0)
4974 print_method_list32_t(c.classMethods, info, "");
4975 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
4976 if (c.protocols != 0)
4977 print_protocol_list32_t(c.protocols, info);
4978 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
4979 << "\n";
4980 if (c.instanceProperties != 0)
4981 print_objc_property_list32(c.instanceProperties, info);
4982}
4983
Kevin Enderby0fc11822015-04-01 20:57:01 +00004984static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
4985 uint32_t i, left, offset, xoffset;
4986 uint64_t p, n_value;
4987 struct message_ref64 mr;
4988 const char *name, *sym_name;
4989 const char *r;
4990 SectionRef xS;
4991
4992 if (S == SectionRef())
4993 return;
4994
4995 StringRef SectName;
4996 S.getName(SectName);
4997 DataRefImpl Ref = S.getRawDataRefImpl();
4998 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
4999 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5000 offset = 0;
5001 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5002 p = S.getAddress() + i;
5003 r = get_pointer_64(p, offset, left, S, info);
5004 if (r == nullptr)
5005 return;
5006 memset(&mr, '\0', sizeof(struct message_ref64));
5007 if (left < sizeof(struct message_ref64)) {
5008 memcpy(&mr, r, left);
5009 outs() << " (message_ref entends past the end of the section)\n";
5010 } else
5011 memcpy(&mr, r, sizeof(struct message_ref64));
5012 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5013 swapStruct(mr);
5014
5015 outs() << " imp ";
5016 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5017 n_value, mr.imp);
5018 if (n_value != 0) {
5019 outs() << format("0x%" PRIx64, n_value) << " ";
5020 if (mr.imp != 0)
5021 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5022 } else
5023 outs() << format("0x%" PRIx64, mr.imp) << " ";
5024 if (name != nullptr)
5025 outs() << " " << name;
5026 outs() << "\n";
5027
5028 outs() << " sel ";
5029 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5030 info, n_value, mr.sel);
5031 if (n_value != 0) {
5032 if (info->verbose && sym_name != nullptr)
5033 outs() << sym_name;
5034 else
5035 outs() << format("0x%" PRIx64, n_value);
5036 if (mr.sel != 0)
5037 outs() << " + " << format("0x%" PRIx64, mr.sel);
5038 } else
5039 outs() << format("0x%" PRIx64, mr.sel);
5040 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5041 if (name != nullptr)
5042 outs() << format(" %.*s", left, name);
5043 outs() << "\n";
5044
5045 offset += sizeof(struct message_ref64);
5046 }
5047}
5048
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005049static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5050 uint32_t i, left, offset, xoffset, p;
5051 struct message_ref32 mr;
5052 const char *name, *r;
5053 SectionRef xS;
5054
5055 if (S == SectionRef())
5056 return;
5057
5058 StringRef SectName;
5059 S.getName(SectName);
5060 DataRefImpl Ref = S.getRawDataRefImpl();
5061 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5062 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5063 offset = 0;
5064 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5065 p = S.getAddress() + i;
5066 r = get_pointer_32(p, offset, left, S, info);
5067 if (r == nullptr)
5068 return;
5069 memset(&mr, '\0', sizeof(struct message_ref32));
5070 if (left < sizeof(struct message_ref32)) {
5071 memcpy(&mr, r, left);
5072 outs() << " (message_ref entends past the end of the section)\n";
5073 } else
5074 memcpy(&mr, r, sizeof(struct message_ref32));
5075 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5076 swapStruct(mr);
5077
5078 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5079 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5080 mr.imp);
5081 if (name != nullptr)
5082 outs() << " " << name;
5083 outs() << "\n";
5084
5085 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5086 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5087 if (name != nullptr)
5088 outs() << " " << name;
5089 outs() << "\n";
5090
5091 offset += sizeof(struct message_ref32);
5092 }
5093}
5094
Kevin Enderby0fc11822015-04-01 20:57:01 +00005095static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5096 uint32_t left, offset, swift_version;
5097 uint64_t p;
5098 struct objc_image_info64 o;
5099 const char *r;
5100
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00005101 if (S == SectionRef())
5102 return;
5103
Kevin Enderby0fc11822015-04-01 20:57:01 +00005104 StringRef SectName;
5105 S.getName(SectName);
5106 DataRefImpl Ref = S.getRawDataRefImpl();
5107 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5108 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5109 p = S.getAddress();
5110 r = get_pointer_64(p, offset, left, S, info);
5111 if (r == nullptr)
5112 return;
5113 memset(&o, '\0', sizeof(struct objc_image_info64));
5114 if (left < sizeof(struct objc_image_info64)) {
5115 memcpy(&o, r, left);
5116 outs() << " (objc_image_info entends past the end of the section)\n";
5117 } else
5118 memcpy(&o, r, sizeof(struct objc_image_info64));
5119 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5120 swapStruct(o);
5121 outs() << " version " << o.version << "\n";
5122 outs() << " flags " << format("0x%" PRIx32, o.flags);
5123 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5124 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5125 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5126 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5127 swift_version = (o.flags >> 8) & 0xff;
5128 if (swift_version != 0) {
5129 if (swift_version == 1)
5130 outs() << " Swift 1.0";
5131 else if (swift_version == 2)
5132 outs() << " Swift 1.1";
5133 else
5134 outs() << " unknown future Swift version (" << swift_version << ")";
5135 }
5136 outs() << "\n";
5137}
5138
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005139static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5140 uint32_t left, offset, swift_version, p;
5141 struct objc_image_info32 o;
5142 const char *r;
5143
Kevin Enderby19be2512016-04-21 19:49:29 +00005144 if (S == SectionRef())
5145 return;
5146
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005147 StringRef SectName;
5148 S.getName(SectName);
5149 DataRefImpl Ref = S.getRawDataRefImpl();
5150 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5151 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5152 p = S.getAddress();
5153 r = get_pointer_32(p, offset, left, S, info);
5154 if (r == nullptr)
5155 return;
5156 memset(&o, '\0', sizeof(struct objc_image_info32));
5157 if (left < sizeof(struct objc_image_info32)) {
5158 memcpy(&o, r, left);
5159 outs() << " (objc_image_info entends past the end of the section)\n";
5160 } else
5161 memcpy(&o, r, sizeof(struct objc_image_info32));
5162 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5163 swapStruct(o);
5164 outs() << " version " << o.version << "\n";
5165 outs() << " flags " << format("0x%" PRIx32, o.flags);
5166 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5167 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5168 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5169 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5170 swift_version = (o.flags >> 8) & 0xff;
5171 if (swift_version != 0) {
5172 if (swift_version == 1)
5173 outs() << " Swift 1.0";
5174 else if (swift_version == 2)
5175 outs() << " Swift 1.1";
5176 else
5177 outs() << " unknown future Swift version (" << swift_version << ")";
5178 }
5179 outs() << "\n";
5180}
5181
Kevin Enderby846c0002015-04-16 17:19:59 +00005182static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5183 uint32_t left, offset, p;
5184 struct imageInfo_t o;
5185 const char *r;
5186
5187 StringRef SectName;
5188 S.getName(SectName);
5189 DataRefImpl Ref = S.getRawDataRefImpl();
5190 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5191 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5192 p = S.getAddress();
5193 r = get_pointer_32(p, offset, left, S, info);
5194 if (r == nullptr)
5195 return;
5196 memset(&o, '\0', sizeof(struct imageInfo_t));
5197 if (left < sizeof(struct imageInfo_t)) {
5198 memcpy(&o, r, left);
5199 outs() << " (imageInfo entends past the end of the section)\n";
5200 } else
5201 memcpy(&o, r, sizeof(struct imageInfo_t));
5202 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5203 swapStruct(o);
5204 outs() << " version " << o.version << "\n";
5205 outs() << " flags " << format("0x%" PRIx32, o.flags);
5206 if (o.flags & 0x1)
5207 outs() << " F&C";
5208 if (o.flags & 0x2)
5209 outs() << " GC";
5210 if (o.flags & 0x4)
5211 outs() << " GC-only";
5212 else
5213 outs() << " RR";
5214 outs() << "\n";
5215}
5216
Kevin Enderby0fc11822015-04-01 20:57:01 +00005217static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5218 SymbolAddressMap AddrMap;
5219 if (verbose)
5220 CreateSymbolAddressMap(O, &AddrMap);
5221
5222 std::vector<SectionRef> Sections;
5223 for (const SectionRef &Section : O->sections()) {
5224 StringRef SectName;
5225 Section.getName(SectName);
5226 Sections.push_back(Section);
5227 }
5228
5229 struct DisassembleInfo info;
5230 // Set up the block of info used by the Symbolizer call backs.
5231 info.verbose = verbose;
5232 info.O = O;
5233 info.AddrMap = &AddrMap;
5234 info.Sections = &Sections;
5235 info.class_name = nullptr;
5236 info.selector_name = nullptr;
5237 info.method = nullptr;
5238 info.demangled_name = nullptr;
5239 info.bindtable = nullptr;
5240 info.adrp_addr = 0;
5241 info.adrp_inst = 0;
5242
Kevin Enderbyaac75382015-10-08 16:56:35 +00005243 info.depth = 0;
Davide Italiano62507042015-12-11 22:27:59 +00005244 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5245 if (CL == SectionRef())
5246 CL = get_section(O, "__DATA", "__objc_classlist");
5247 info.S = CL;
5248 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005249
Davide Italiano62507042015-12-11 22:27:59 +00005250 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5251 if (CR == SectionRef())
5252 CR = get_section(O, "__DATA", "__objc_classrefs");
5253 info.S = CR;
5254 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005255
Davide Italiano62507042015-12-11 22:27:59 +00005256 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5257 if (SR == SectionRef())
5258 SR = get_section(O, "__DATA", "__objc_superrefs");
5259 info.S = SR;
5260 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005261
Davide Italiano62507042015-12-11 22:27:59 +00005262 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5263 if (CA == SectionRef())
5264 CA = get_section(O, "__DATA", "__objc_catlist");
5265 info.S = CA;
5266 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005267
Davide Italiano62507042015-12-11 22:27:59 +00005268 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5269 if (PL == SectionRef())
5270 PL = get_section(O, "__DATA", "__objc_protolist");
5271 info.S = PL;
5272 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005273
Davide Italiano62507042015-12-11 22:27:59 +00005274 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5275 if (MR == SectionRef())
5276 MR = get_section(O, "__DATA", "__objc_msgrefs");
5277 info.S = MR;
5278 print_message_refs64(MR, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005279
Davide Italiano62507042015-12-11 22:27:59 +00005280 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5281 if (II == SectionRef())
5282 II = get_section(O, "__DATA", "__objc_imageinfo");
5283 info.S = II;
5284 print_image_info64(II, &info);
Kevin Enderby0bc6ed42015-04-01 21:50:45 +00005285
5286 if (info.bindtable != nullptr)
5287 delete info.bindtable;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005288}
5289
5290static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005291 SymbolAddressMap AddrMap;
5292 if (verbose)
5293 CreateSymbolAddressMap(O, &AddrMap);
5294
5295 std::vector<SectionRef> Sections;
5296 for (const SectionRef &Section : O->sections()) {
5297 StringRef SectName;
5298 Section.getName(SectName);
5299 Sections.push_back(Section);
5300 }
5301
5302 struct DisassembleInfo info;
5303 // Set up the block of info used by the Symbolizer call backs.
5304 info.verbose = verbose;
5305 info.O = O;
5306 info.AddrMap = &AddrMap;
5307 info.Sections = &Sections;
5308 info.class_name = nullptr;
5309 info.selector_name = nullptr;
5310 info.method = nullptr;
5311 info.demangled_name = nullptr;
5312 info.bindtable = nullptr;
5313 info.adrp_addr = 0;
5314 info.adrp_inst = 0;
5315
5316 const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5317 if (CL != SectionRef()) {
5318 info.S = CL;
5319 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5320 } else {
5321 const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
5322 info.S = CL;
5323 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5324 }
5325
5326 const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5327 if (CR != SectionRef()) {
5328 info.S = CR;
5329 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5330 } else {
5331 const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
5332 info.S = CR;
5333 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5334 }
5335
5336 const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5337 if (SR != SectionRef()) {
5338 info.S = SR;
5339 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5340 } else {
5341 const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
5342 info.S = SR;
5343 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5344 }
5345
5346 const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5347 if (CA != SectionRef()) {
5348 info.S = CA;
5349 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5350 } else {
5351 const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
5352 info.S = CA;
5353 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5354 }
5355
5356 const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5357 if (PL != SectionRef()) {
5358 info.S = PL;
5359 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5360 } else {
5361 const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
5362 info.S = PL;
5363 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5364 }
5365
5366 const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5367 if (MR != SectionRef()) {
5368 info.S = MR;
5369 print_message_refs32(MR, &info);
5370 } else {
5371 const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
5372 info.S = MR;
5373 print_message_refs32(MR, &info);
5374 }
5375
5376 const SectionRef II = get_section(O, "__OBJC2", "__image_info");
5377 if (II != SectionRef()) {
5378 info.S = II;
5379 print_image_info32(II, &info);
5380 } else {
5381 const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
5382 info.S = II;
5383 print_image_info32(II, &info);
5384 }
Kevin Enderby0fc11822015-04-01 20:57:01 +00005385}
5386
5387static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby846c0002015-04-16 17:19:59 +00005388 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5389 const char *r, *name, *defs;
5390 struct objc_module_t module;
5391 SectionRef S, xS;
5392 struct objc_symtab_t symtab;
5393 struct objc_class_t objc_class;
5394 struct objc_category_t objc_category;
5395
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005396 outs() << "Objective-C segment\n";
Kevin Enderby846c0002015-04-16 17:19:59 +00005397 S = get_section(O, "__OBJC", "__module_info");
5398 if (S == SectionRef())
5399 return false;
5400
5401 SymbolAddressMap AddrMap;
5402 if (verbose)
5403 CreateSymbolAddressMap(O, &AddrMap);
5404
5405 std::vector<SectionRef> Sections;
5406 for (const SectionRef &Section : O->sections()) {
5407 StringRef SectName;
5408 Section.getName(SectName);
5409 Sections.push_back(Section);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005410 }
Kevin Enderby846c0002015-04-16 17:19:59 +00005411
5412 struct DisassembleInfo info;
5413 // Set up the block of info used by the Symbolizer call backs.
5414 info.verbose = verbose;
5415 info.O = O;
5416 info.AddrMap = &AddrMap;
5417 info.Sections = &Sections;
5418 info.class_name = nullptr;
5419 info.selector_name = nullptr;
5420 info.method = nullptr;
5421 info.demangled_name = nullptr;
5422 info.bindtable = nullptr;
5423 info.adrp_addr = 0;
5424 info.adrp_inst = 0;
5425
5426 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5427 p = S.getAddress() + i;
5428 r = get_pointer_32(p, offset, left, S, &info, true);
5429 if (r == nullptr)
5430 return true;
5431 memset(&module, '\0', sizeof(struct objc_module_t));
5432 if (left < sizeof(struct objc_module_t)) {
5433 memcpy(&module, r, left);
5434 outs() << " (module extends past end of __module_info section)\n";
5435 } else
5436 memcpy(&module, r, sizeof(struct objc_module_t));
5437 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5438 swapStruct(module);
5439
5440 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5441 outs() << " version " << module.version << "\n";
5442 outs() << " size " << module.size << "\n";
5443 outs() << " name ";
5444 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5445 if (name != nullptr)
5446 outs() << format("%.*s", left, name);
5447 else
5448 outs() << format("0x%08" PRIx32, module.name)
5449 << "(not in an __OBJC section)";
5450 outs() << "\n";
5451
5452 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5453 if (module.symtab == 0 || r == nullptr) {
5454 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5455 << " (not in an __OBJC section)\n";
5456 continue;
5457 }
5458 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5459 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5460 defs_left = 0;
5461 defs = nullptr;
5462 if (left < sizeof(struct objc_symtab_t)) {
5463 memcpy(&symtab, r, left);
5464 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5465 } else {
5466 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5467 if (left > sizeof(struct objc_symtab_t)) {
5468 defs_left = left - sizeof(struct objc_symtab_t);
5469 defs = r + sizeof(struct objc_symtab_t);
5470 }
5471 }
5472 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5473 swapStruct(symtab);
5474
5475 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5476 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5477 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5478 if (r == nullptr)
5479 outs() << " (not in an __OBJC section)";
5480 outs() << "\n";
5481 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5482 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5483 if (symtab.cls_def_cnt > 0)
5484 outs() << "\tClass Definitions\n";
5485 for (j = 0; j < symtab.cls_def_cnt; j++) {
5486 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5487 outs() << "\t(remaining class defs entries entends past the end of the "
5488 << "section)\n";
5489 break;
5490 }
5491 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5492 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5493 sys::swapByteOrder(def);
5494
5495 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5496 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5497 if (r != nullptr) {
5498 if (left > sizeof(struct objc_class_t)) {
5499 outs() << "\n";
5500 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5501 } else {
5502 outs() << " (entends past the end of the section)\n";
5503 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5504 memcpy(&objc_class, r, left);
5505 }
5506 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5507 swapStruct(objc_class);
5508 print_objc_class_t(&objc_class, &info);
5509 } else {
5510 outs() << "(not in an __OBJC section)\n";
5511 }
5512
5513 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
5514 outs() << "\tMeta Class";
5515 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
5516 if (r != nullptr) {
5517 if (left > sizeof(struct objc_class_t)) {
5518 outs() << "\n";
5519 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5520 } else {
5521 outs() << " (entends past the end of the section)\n";
5522 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5523 memcpy(&objc_class, r, left);
5524 }
5525 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5526 swapStruct(objc_class);
5527 print_objc_class_t(&objc_class, &info);
5528 } else {
5529 outs() << "(not in an __OBJC section)\n";
5530 }
5531 }
5532 }
5533 if (symtab.cat_def_cnt > 0)
5534 outs() << "\tCategory Definitions\n";
5535 for (j = 0; j < symtab.cat_def_cnt; j++) {
5536 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
5537 outs() << "\t(remaining category defs entries entends past the end of "
5538 << "the section)\n";
5539 break;
5540 }
5541 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
5542 sizeof(uint32_t));
5543 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5544 sys::swapByteOrder(def);
5545
5546 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5547 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
5548 << format("0x%08" PRIx32, def);
5549 if (r != nullptr) {
5550 if (left > sizeof(struct objc_category_t)) {
5551 outs() << "\n";
5552 memcpy(&objc_category, r, sizeof(struct objc_category_t));
5553 } else {
5554 outs() << " (entends past the end of the section)\n";
5555 memset(&objc_category, '\0', sizeof(struct objc_category_t));
5556 memcpy(&objc_category, r, left);
5557 }
5558 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5559 swapStruct(objc_category);
5560 print_objc_objc_category_t(&objc_category, &info);
5561 } else {
5562 outs() << "(not in an __OBJC section)\n";
5563 }
5564 }
5565 }
5566 const SectionRef II = get_section(O, "__OBJC", "__image_info");
5567 if (II != SectionRef())
5568 print_image_info(II, &info);
5569
5570 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005571}
5572
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00005573static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
5574 uint32_t size, uint32_t addr) {
5575 SymbolAddressMap AddrMap;
5576 CreateSymbolAddressMap(O, &AddrMap);
5577
5578 std::vector<SectionRef> Sections;
5579 for (const SectionRef &Section : O->sections()) {
5580 StringRef SectName;
5581 Section.getName(SectName);
5582 Sections.push_back(Section);
5583 }
5584
5585 struct DisassembleInfo info;
5586 // Set up the block of info used by the Symbolizer call backs.
5587 info.verbose = true;
5588 info.O = O;
5589 info.AddrMap = &AddrMap;
5590 info.Sections = &Sections;
5591 info.class_name = nullptr;
5592 info.selector_name = nullptr;
5593 info.method = nullptr;
5594 info.demangled_name = nullptr;
5595 info.bindtable = nullptr;
5596 info.adrp_addr = 0;
5597 info.adrp_inst = 0;
5598
5599 const char *p;
5600 struct objc_protocol_t protocol;
5601 uint32_t left, paddr;
5602 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
5603 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
5604 left = size - (p - sect);
5605 if (left < sizeof(struct objc_protocol_t)) {
5606 outs() << "Protocol extends past end of __protocol section\n";
5607 memcpy(&protocol, p, left);
5608 } else
5609 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
5610 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5611 swapStruct(protocol);
5612 paddr = addr + (p - sect);
5613 outs() << "Protocol " << format("0x%" PRIx32, paddr);
5614 if (print_protocol(paddr, 0, &info))
5615 outs() << "(not in an __OBJC section)\n";
5616 }
5617}
5618
Kevin Enderby0fc11822015-04-01 20:57:01 +00005619static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
5620 if (O->is64Bit())
5621 printObjc2_64bit_MetaData(O, verbose);
5622 else {
5623 MachO::mach_header H;
5624 H = O->getHeader();
5625 if (H.cputype == MachO::CPU_TYPE_ARM)
5626 printObjc2_32bit_MetaData(O, verbose);
5627 else {
5628 // This is the 32-bit non-arm cputype case. Which is normally
5629 // the first Objective-C ABI. But it may be the case of a
5630 // binary for the iOS simulator which is the second Objective-C
5631 // ABI. In that case printObjc1_32bit_MetaData() will determine that
5632 // and return false.
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005633 if (!printObjc1_32bit_MetaData(O, verbose))
Kevin Enderby0fc11822015-04-01 20:57:01 +00005634 printObjc2_32bit_MetaData(O, verbose);
5635 }
5636 }
5637}
5638
Kevin Enderbybf246f52014-09-24 23:08:22 +00005639// GuessLiteralPointer returns a string which for the item in the Mach-O file
5640// for the address passed in as ReferenceValue for printing as a comment with
5641// the instruction and also returns the corresponding type of that item
5642// indirectly through ReferenceType.
5643//
5644// If ReferenceValue is an address of literal cstring then a pointer to the
5645// cstring is returned and ReferenceType is set to
5646// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
5647//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005648// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
5649// Class ref that name is returned and the ReferenceType is set accordingly.
5650//
5651// Lastly, literals which are Symbol address in a literal pool are looked for
5652// and if found the symbol name is returned and ReferenceType is set to
5653// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
5654//
5655// If there is no item in the Mach-O file for the address passed in as
5656// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00005657static const char *GuessLiteralPointer(uint64_t ReferenceValue,
5658 uint64_t ReferencePC,
5659 uint64_t *ReferenceType,
5660 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00005661 // First see if there is an external relocation entry at the ReferencePC.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00005662 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
5663 uint64_t sect_addr = info->S.getAddress();
5664 uint64_t sect_offset = ReferencePC - sect_addr;
5665 bool reloc_found = false;
5666 DataRefImpl Rel;
5667 MachO::any_relocation_info RE;
5668 bool isExtern = false;
5669 SymbolRef Symbol;
5670 for (const RelocationRef &Reloc : info->S.relocations()) {
5671 uint64_t RelocOffset = Reloc.getOffset();
5672 if (RelocOffset == sect_offset) {
5673 Rel = Reloc.getRawDataRefImpl();
5674 RE = info->O->getRelocation(Rel);
5675 if (info->O->isRelocationScattered(RE))
5676 continue;
5677 isExtern = info->O->getPlainRelocationExternal(RE);
5678 if (isExtern) {
5679 symbol_iterator RelocSym = Reloc.getSymbol();
5680 Symbol = *RelocSym;
5681 }
5682 reloc_found = true;
5683 break;
Kevin Enderbybf246f52014-09-24 23:08:22 +00005684 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005685 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00005686 // If there is an external relocation entry for a symbol in a section
5687 // then used that symbol's value for the value of the reference.
5688 if (reloc_found && isExtern) {
5689 if (info->O->getAnyRelocationPCRel(RE)) {
5690 unsigned Type = info->O->getAnyRelocationType(RE);
5691 if (Type == MachO::X86_64_RELOC_SIGNED) {
5692 ReferenceValue = Symbol.getValue();
5693 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005694 }
5695 }
5696 }
5697
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005698 // Look for literals such as Objective-C CFStrings refs, Selector refs,
5699 // Message refs and Class refs.
5700 bool classref, selref, msgref, cfstring;
5701 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
5702 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00005703 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005704 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
5705 // And the pointer_value in that section is typically zero as it will be
5706 // set by dyld as part of the "bind information".
5707 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
5708 if (name != nullptr) {
5709 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00005710 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005711 if (class_name != nullptr && class_name[1] == '_' &&
5712 class_name[2] != '\0') {
5713 info->class_name = class_name + 2;
5714 return name;
5715 }
5716 }
5717 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005718
David Blaikie33dd45d02015-03-23 18:39:02 +00005719 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005720 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
5721 const char *name =
5722 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
5723 if (name != nullptr)
5724 info->class_name = name;
5725 else
5726 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00005727 return name;
5728 }
5729
David Blaikie33dd45d02015-03-23 18:39:02 +00005730 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005731 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
5732 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
5733 return name;
5734 }
5735
David Blaikie33dd45d02015-03-23 18:39:02 +00005736 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005737 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
5738
5739 if (pointer_value != 0)
5740 ReferenceValue = pointer_value;
5741
5742 const char *name = GuessCstringPointer(ReferenceValue, info);
5743 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00005744 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005745 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
5746 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00005747 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005748 info->class_name = nullptr;
5749 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
5750 info->selector_name = name;
5751 } else
5752 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
5753 return name;
5754 }
5755
5756 // Lastly look for an indirect symbol with this ReferenceValue which is in
5757 // a literal pool. If found return that symbol name.
5758 name = GuessIndirectSymbol(ReferenceValue, info);
5759 if (name) {
5760 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
5761 return name;
5762 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005763
5764 return nullptr;
5765}
5766
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005767// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00005768// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005769// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
5770// is created and returns the symbol name that matches the ReferenceValue or
5771// nullptr if none. The ReferenceType is passed in for the IN type of
5772// reference the instruction is making from the values in defined in the header
5773// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
5774// Out type and the ReferenceName will also be set which is added as a comment
5775// to the disassembled instruction.
5776//
Kevin Enderby04bf6932014-10-28 23:39:46 +00005777#if HAVE_CXXABI_H
5778// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005779// returned through ReferenceName and ReferenceType is set to
5780// LLVMDisassembler_ReferenceType_DeMangled_Name .
Kevin Enderby04bf6932014-10-28 23:39:46 +00005781#endif
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005782//
5783// When this is called to get a symbol name for a branch target then the
5784// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
5785// SymbolValue will be looked for in the indirect symbol table to determine if
5786// it is an address for a symbol stub. If so then the symbol name for that
5787// stub is returned indirectly through ReferenceName and then ReferenceType is
5788// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
5789//
Kevin Enderbybf246f52014-09-24 23:08:22 +00005790// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005791// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
5792// SymbolValue is checked to be an address of literal pointer, symbol pointer,
5793// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005794// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00005795static const char *SymbolizerSymbolLookUp(void *DisInfo,
5796 uint64_t ReferenceValue,
5797 uint64_t *ReferenceType,
5798 uint64_t ReferencePC,
5799 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005800 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00005801 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00005802 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00005803 *ReferenceName = nullptr;
5804 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005805 return nullptr;
5806 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005807
Kevin Enderbyf6d25852015-01-31 00:37:11 +00005808 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00005809
Kevin Enderby85974882014-09-26 22:20:44 +00005810 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
5811 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00005812 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005813 method_reference(info, ReferenceType, ReferenceName);
5814 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
5815 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
5816 } else
Kevin Enderby04bf6932014-10-28 23:39:46 +00005817#if HAVE_CXXABI_H
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005818 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00005819 if (info->demangled_name != nullptr)
5820 free(info->demangled_name);
5821 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005822 info->demangled_name =
5823 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00005824 if (info->demangled_name != nullptr) {
5825 *ReferenceName = info->demangled_name;
5826 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5827 } else
5828 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5829 } else
5830#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005831 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5832 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
5833 *ReferenceName =
5834 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00005835 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005836 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00005837 else
5838 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00005839 // If this is arm64 and the reference is an adrp instruction save the
5840 // instruction, passed in ReferenceValue and the address of the instruction
5841 // for use later if we see and add immediate instruction.
5842 } else if (info->O->getArch() == Triple::aarch64 &&
5843 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
5844 info->adrp_inst = ReferenceValue;
5845 info->adrp_addr = ReferencePC;
5846 SymbolName = nullptr;
5847 *ReferenceName = nullptr;
5848 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5849 // If this is arm64 and reference is an add immediate instruction and we
5850 // have
5851 // seen an adrp instruction just before it and the adrp's Xd register
5852 // matches
5853 // this add's Xn register reconstruct the value being referenced and look to
5854 // see if it is a literal pointer. Note the add immediate instruction is
5855 // passed in ReferenceValue.
5856 } else if (info->O->getArch() == Triple::aarch64 &&
5857 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
5858 ReferencePC - 4 == info->adrp_addr &&
5859 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5860 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5861 uint32_t addxri_inst;
5862 uint64_t adrp_imm, addxri_imm;
5863
5864 adrp_imm =
5865 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5866 if (info->adrp_inst & 0x0200000)
5867 adrp_imm |= 0xfffffffffc000000LL;
5868
5869 addxri_inst = ReferenceValue;
5870 addxri_imm = (addxri_inst >> 10) & 0xfff;
5871 if (((addxri_inst >> 22) & 0x3) == 1)
5872 addxri_imm <<= 12;
5873
5874 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5875 (adrp_imm << 12) + addxri_imm;
5876
5877 *ReferenceName =
5878 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5879 if (*ReferenceName == nullptr)
5880 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5881 // If this is arm64 and the reference is a load register instruction and we
5882 // have seen an adrp instruction just before it and the adrp's Xd register
5883 // matches this add's Xn register reconstruct the value being referenced and
5884 // look to see if it is a literal pointer. Note the load register
5885 // instruction is passed in ReferenceValue.
5886 } else if (info->O->getArch() == Triple::aarch64 &&
5887 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
5888 ReferencePC - 4 == info->adrp_addr &&
5889 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5890 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5891 uint32_t ldrxui_inst;
5892 uint64_t adrp_imm, ldrxui_imm;
5893
5894 adrp_imm =
5895 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5896 if (info->adrp_inst & 0x0200000)
5897 adrp_imm |= 0xfffffffffc000000LL;
5898
5899 ldrxui_inst = ReferenceValue;
5900 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
5901
5902 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5903 (adrp_imm << 12) + (ldrxui_imm << 3);
5904
5905 *ReferenceName =
5906 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5907 if (*ReferenceName == nullptr)
5908 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5909 }
5910 // If this arm64 and is an load register (PC-relative) instruction the
5911 // ReferenceValue is the PC plus the immediate value.
5912 else if (info->O->getArch() == Triple::aarch64 &&
5913 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
5914 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
5915 *ReferenceName =
5916 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5917 if (*ReferenceName == nullptr)
5918 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby85974882014-09-26 22:20:44 +00005919 }
Kevin Enderby04bf6932014-10-28 23:39:46 +00005920#if HAVE_CXXABI_H
5921 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
5922 if (info->demangled_name != nullptr)
5923 free(info->demangled_name);
5924 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005925 info->demangled_name =
5926 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00005927 if (info->demangled_name != nullptr) {
5928 *ReferenceName = info->demangled_name;
5929 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5930 }
5931 }
5932#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005933 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00005934 *ReferenceName = nullptr;
5935 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5936 }
5937
5938 return SymbolName;
5939}
5940
Kevin Enderbybf246f52014-09-24 23:08:22 +00005941/// \brief Emits the comments that are stored in the CommentStream.
5942/// Each comment in the CommentStream must end with a newline.
5943static void emitComments(raw_svector_ostream &CommentStream,
5944 SmallString<128> &CommentsToEmit,
5945 formatted_raw_ostream &FormattedOS,
5946 const MCAsmInfo &MAI) {
5947 // Flush the stream before taking its content.
Kevin Enderbybf246f52014-09-24 23:08:22 +00005948 StringRef Comments = CommentsToEmit.str();
5949 // Get the default information for printing a comment.
5950 const char *CommentBegin = MAI.getCommentString();
5951 unsigned CommentColumn = MAI.getCommentColumn();
5952 bool IsFirst = true;
5953 while (!Comments.empty()) {
5954 if (!IsFirst)
5955 FormattedOS << '\n';
5956 // Emit a line of comments.
5957 FormattedOS.PadToColumn(CommentColumn);
5958 size_t Position = Comments.find('\n');
5959 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
5960 // Move after the newline character.
5961 Comments = Comments.substr(Position + 1);
5962 IsFirst = false;
5963 }
5964 FormattedOS.flush();
5965
5966 // Tell the comment stream that the vector changed underneath it.
5967 CommentsToEmit.clear();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005968}
5969
Kevin Enderby95df54c2015-02-04 01:01:38 +00005970static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
5971 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005972 const char *McpuDefault = nullptr;
5973 const Target *ThumbTarget = nullptr;
5974 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005975 if (!TheTarget) {
5976 // GetTarget prints out stuff.
5977 return;
5978 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005979 if (MCPU.empty() && McpuDefault)
5980 MCPU = McpuDefault;
5981
Ahmed Charles56440fd2014-03-06 05:51:42 +00005982 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005983 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00005984 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005985 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005986
Kevin Enderbyc9595622014-08-06 23:24:41 +00005987 // Package up features to be passed to target/subtarget
5988 std::string FeaturesStr;
5989 if (MAttrs.size()) {
5990 SubtargetFeatures Features;
5991 for (unsigned i = 0; i != MAttrs.size(); ++i)
5992 Features.AddFeature(MAttrs[i]);
5993 FeaturesStr = Features.getString();
5994 }
5995
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005996 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00005997 std::unique_ptr<const MCRegisterInfo> MRI(
5998 TheTarget->createMCRegInfo(TripleName));
5999 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00006000 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00006001 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +00006002 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00006003 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006004 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006005 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006006 std::unique_ptr<MCSymbolizer> Symbolizer;
6007 struct DisassembleInfo SymbolizerInfo;
6008 std::unique_ptr<MCRelocationInfo> RelInfo(
6009 TheTarget->createMCRelocationInfo(TripleName, Ctx));
6010 if (RelInfo) {
6011 Symbolizer.reset(TheTarget->createMCSymbolizer(
6012 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006013 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006014 DisAsm->setSymbolizer(std::move(Symbolizer));
6015 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006016 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00006017 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006018 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006019 // Set the display preference for hex vs. decimal immediates.
6020 IP->setPrintImmHex(PrintImmHex);
6021 // Comment stream and backing vector.
6022 SmallString<128> CommentsToEmit;
6023 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006024 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
6025 // if it is done then arm64 comments for string literals don't get printed
6026 // and some constant get printed instead and not setting it causes intel
6027 // (32-bit and 64-bit) comments printed with different spacing before the
6028 // comment causing different diffs with the 'C' disassembler library API.
6029 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006030
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006031 if (!AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencerc1363cf2011-10-07 19:25:47 +00006032 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006033 << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006034 return;
6035 }
6036
Tim Northover09ca33e2016-04-22 23:23:31 +00006037 // Set up separate thumb disassembler if needed.
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006038 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
6039 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
6040 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006041 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006042 std::unique_ptr<MCInstPrinter> ThumbIP;
6043 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006044 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
6045 struct DisassembleInfo ThumbSymbolizerInfo;
6046 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006047 if (ThumbTarget) {
6048 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
6049 ThumbAsmInfo.reset(
6050 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
6051 ThumbSTI.reset(
6052 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
6053 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
6054 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006055 MCContext *PtrThumbCtx = ThumbCtx.get();
6056 ThumbRelInfo.reset(
6057 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
6058 if (ThumbRelInfo) {
6059 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
6060 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006061 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006062 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
6063 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006064 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
6065 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006066 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
6067 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006068 // Set the display preference for hex vs. decimal immediates.
6069 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006070 }
6071
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006072 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006073 errs() << "error: couldn't initialize disassembler for target "
6074 << ThumbTripleName << '\n';
6075 return;
6076 }
6077
Charles Davis8bdfafd2013-09-01 04:28:48 +00006078 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006079
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006080 // FIXME: Using the -cfg command line option, this code used to be able to
6081 // annotate relocations with the referenced symbol's name, and if this was
6082 // inside a __[cf]string section, the data it points to. This is now replaced
6083 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00006084 std::vector<SectionRef> Sections;
6085 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006086 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00006087 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006088
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00006089 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
Kevin Enderby273ae012013-06-06 17:20:50 +00006090 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006091
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006092 // Sort the symbols by address, just in case they didn't come in that way.
Owen Andersond9243c42011-10-17 21:37:35 +00006093 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006094
Kevin Enderby273ae012013-06-06 17:20:50 +00006095 // Build a data in code table that is sorted on by the address of each entry.
6096 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00006097 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00006098 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00006099 else
6100 BaseAddress = BaseSegmentAddress;
6101 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00006102 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00006103 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006104 uint32_t Offset;
6105 DI->getOffset(Offset);
6106 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6107 }
6108 array_pod_sort(Dices.begin(), Dices.end());
6109
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006110#ifndef NDEBUG
6111 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6112#else
6113 raw_ostream &DebugOut = nulls();
6114#endif
6115
Ahmed Charles56440fd2014-03-06 05:51:42 +00006116 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00006117 ObjectFile *DbgObj = MachOOF;
Benjamin Kramer699128e2011-09-21 01:13:19 +00006118 // Try to find debug info and set up the DIContext for it.
6119 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00006120 // A separate DSym file path was specified, parse it as a macho file,
6121 // get the sections and supply it to the section name parsing machinery.
6122 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00006123 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006124 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00006125 if (std::error_code EC = BufOrErr.getError()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006126 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +00006127 return;
6128 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00006129 DbgObj =
6130 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
6131 .get()
6132 .release();
Benjamin Kramer699128e2011-09-21 01:13:19 +00006133 }
6134
Eric Christopher7370b552012-11-12 21:40:38 +00006135 // Setup the DIContext
Zachary Turner6489d7b2015-04-23 17:37:47 +00006136 diContext.reset(new DWARFContextInMemory(*DbgObj));
Benjamin Kramer699128e2011-09-21 01:13:19 +00006137 }
6138
Colin LeMahieufcc32762015-07-29 19:08:10 +00006139 if (FilterSections.size() == 0)
Kevin Enderby95df54c2015-02-04 01:01:38 +00006140 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006141
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006142 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00006143 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00006144 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6145 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006146
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006147 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006148
Rafael Espindolab0f76a42013-04-05 15:15:22 +00006149 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00006150 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006151 continue;
6152
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006153 StringRef BytesStr;
6154 Sections[SectIdx].getContents(BytesStr);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00006155 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6156 BytesStr.size());
Rafael Espindola80291272014-10-08 15:28:58 +00006157 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00006158
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006159 bool symbolTableWorked = false;
6160
Kevin Enderbybf246f52014-09-24 23:08:22 +00006161 // Create a map of symbol addresses to symbol names for use by
6162 // the SymbolizerSymbolLookUp() routine.
6163 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00006164 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006165 for (const SymbolRef &Symbol : MachOOF->symbols()) {
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006166 ErrorOr<SymbolRef::Type> STOrErr = Symbol.getType();
6167 if (std::error_code EC = STOrErr.getError())
6168 report_fatal_error(EC.message());
6169 SymbolRef::Type ST = *STOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006170 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
6171 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00006172 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006173 Expected<StringRef> SymNameOrErr = Symbol.getName();
6174 if (!SymNameOrErr) {
6175 std::string Buf;
6176 raw_string_ostream OS(Buf);
6177 logAllUnhandledErrors(SymNameOrErr.takeError(), OS, "");
6178 OS.flush();
6179 report_fatal_error(Buf);
6180 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006181 StringRef SymName = *SymNameOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006182 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00006183 if (!DisSymName.empty() && DisSymName == SymName)
6184 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006185 }
6186 }
David Blaikie33dd45d02015-03-23 18:39:02 +00006187 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00006188 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
6189 return;
6190 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006191 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006192 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006193 SymbolizerInfo.O = MachOOF;
6194 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00006195 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006196 SymbolizerInfo.Sections = &Sections;
6197 SymbolizerInfo.class_name = nullptr;
6198 SymbolizerInfo.selector_name = nullptr;
6199 SymbolizerInfo.method = nullptr;
Kevin Enderby04bf6932014-10-28 23:39:46 +00006200 SymbolizerInfo.demangled_name = nullptr;
Kevin Enderby078be602014-10-23 19:53:12 +00006201 SymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006202 SymbolizerInfo.adrp_addr = 0;
6203 SymbolizerInfo.adrp_inst = 0;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006204 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006205 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006206 ThumbSymbolizerInfo.O = MachOOF;
6207 ThumbSymbolizerInfo.S = Sections[SectIdx];
6208 ThumbSymbolizerInfo.AddrMap = &AddrMap;
6209 ThumbSymbolizerInfo.Sections = &Sections;
6210 ThumbSymbolizerInfo.class_name = nullptr;
6211 ThumbSymbolizerInfo.selector_name = nullptr;
6212 ThumbSymbolizerInfo.method = nullptr;
6213 ThumbSymbolizerInfo.demangled_name = nullptr;
6214 ThumbSymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006215 ThumbSymbolizerInfo.adrp_addr = 0;
6216 ThumbSymbolizerInfo.adrp_inst = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006217
Kevin Enderby4b627be2016-04-28 20:14:13 +00006218 unsigned int Arch = MachOOF->getArch();
6219
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006220 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006221 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006222 Expected<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
6223 if (!SymNameOrErr) {
6224 std::string Buf;
6225 raw_string_ostream OS(Buf);
6226 logAllUnhandledErrors(SymNameOrErr.takeError(), OS, "");
6227 OS.flush();
6228 report_fatal_error(Buf);
6229 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006230 StringRef SymName = *SymNameOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00006231
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006232 ErrorOr<SymbolRef::Type> STOrErr = Symbols[SymIdx].getType();
6233 if (std::error_code EC = STOrErr.getError())
6234 report_fatal_error(EC.message());
6235 SymbolRef::Type ST = *STOrErr;
Kuba Breckade833222015-11-12 09:40:29 +00006236 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
Owen Andersond9243c42011-10-17 21:37:35 +00006237 continue;
6238
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006239 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00006240 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Owen Andersond9243c42011-10-17 21:37:35 +00006241 if (!containsSym)
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006242 continue;
6243
Kevin Enderby6a221752015-03-17 17:10:57 +00006244 // If we are only disassembling one symbol see if this is that symbol.
6245 if (!DisSymName.empty() && DisSymName != SymName)
6246 continue;
6247
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006248 // Start at the address of the symbol relative to the section's address.
Rafael Espindoladea00162015-07-03 17:44:18 +00006249 uint64_t Start = Symbols[SymIdx].getValue();
Rafael Espindola80291272014-10-08 15:28:58 +00006250 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006251 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006252
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006253 // Stop disassembling either at the beginning of the next symbol or at
6254 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00006255 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00006256 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006257 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00006258 while (Symbols.size() > NextSymIdx) {
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006259 ErrorOr<SymbolRef::Type> STOrErr = Symbols[NextSymIdx].getType();
6260 if (std::error_code EC = STOrErr.getError())
6261 report_fatal_error(EC.message());
6262 SymbolRef::Type NextSymType = *STOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00006263 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00006264 containsNextSym =
6265 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Rafael Espindoladea00162015-07-03 17:44:18 +00006266 NextSym = Symbols[NextSymIdx].getValue();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006267 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006268 break;
6269 }
6270 ++NextSymIdx;
6271 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006272
Rafael Espindola80291272014-10-08 15:28:58 +00006273 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006274 uint64_t End = containsNextSym ? NextSym : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00006275 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006276
6277 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00006278
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006279 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
Tim Northover09ca33e2016-04-22 23:23:31 +00006280 bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
6281
6282 // We only need the dedicated Thumb target if there's a real choice
6283 // (i.e. we're not targeting M-class) and the function is Thumb.
6284 bool UseThumbTarget = IsThumb && ThumbTarget;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006285
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006286 outs() << SymName << ":\n";
6287 DILineInfo lastLine;
6288 for (uint64_t Index = Start; Index < End; Index += Size) {
6289 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00006290
Kevin Enderbybf246f52014-09-24 23:08:22 +00006291 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006292 if (!NoLeadingAddr) {
6293 if (FullLeadingAddr) {
6294 if (MachOOF->is64Bit())
6295 outs() << format("%016" PRIx64, PC);
6296 else
6297 outs() << format("%08" PRIx64, PC);
6298 } else {
6299 outs() << format("%8" PRIx64 ":", PC);
6300 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006301 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00006302 if (!NoShowRawInsn || Arch == Triple::arm)
Kevin Enderbybf246f52014-09-24 23:08:22 +00006303 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00006304
6305 // Check the data in code table here to see if this is data not an
6306 // instruction to be disassembled.
6307 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006308 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006309 dice_table_iterator DTI =
6310 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
6311 compareDiceTableEntries);
6312 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006313 uint16_t Length;
6314 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00006315 uint16_t Kind;
6316 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00006317 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00006318 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
6319 (PC == (DTI->first + Length - 1)) && (Length & 1))
6320 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00006321 continue;
6322 }
6323
Kevin Enderbybf246f52014-09-24 23:08:22 +00006324 SmallVector<char, 64> AnnotationsBytes;
6325 raw_svector_ostream Annotations(AnnotationsBytes);
6326
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006327 bool gotInst;
Tim Northover09ca33e2016-04-22 23:23:31 +00006328 if (UseThumbTarget)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006329 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006330 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006331 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006332 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00006333 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006334 if (gotInst) {
Kevin Enderby4b627be2016-04-28 20:14:13 +00006335 if (!NoShowRawInsn || Arch == Triple::arm) {
Craig Topper0013be12015-09-21 05:32:41 +00006336 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006337 }
6338 formatted_raw_ostream FormattedOS(outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006339 StringRef AnnotationsStr = Annotations.str();
Tim Northover09ca33e2016-04-22 23:23:31 +00006340 if (UseThumbTarget)
Akira Hatanakab46d0232015-03-27 20:36:02 +00006341 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006342 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00006343 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006344 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00006345
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006346 // Print debug info.
6347 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006348 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006349 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00006350 if (dli != lastLine && dli.Line != 0)
6351 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
6352 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006353 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006354 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006355 outs() << "\n";
6356 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006357 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006358 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006359 outs() << format("\t.byte 0x%02x #bad opcode\n",
6360 *(Bytes.data() + Index) & 0xff);
6361 Size = 1; // skip exactly one illegible byte and move on.
Tim Northover09ca33e2016-04-22 23:23:31 +00006362 } else if (Arch == Triple::aarch64 ||
6363 (Arch == Triple::arm && !IsThumb)) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006364 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6365 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
6366 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
6367 (*(Bytes.data() + Index + 3) & 0xff) << 24;
6368 outs() << format("\t.long\t0x%08x\n", opcode);
6369 Size = 4;
Tim Northover09ca33e2016-04-22 23:23:31 +00006370 } else if (Arch == Triple::arm) {
6371 assert(IsThumb && "ARM mode should have been dealt with above");
6372 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6373 (*(Bytes.data() + Index + 1) & 0xff) << 8;
6374 outs() << format("\t.short\t0x%04x\n", opcode);
6375 Size = 2;
6376 } else{
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006377 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6378 if (Size == 0)
6379 Size = 1; // skip illegible bytes
6380 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006381 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006382 }
6383 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006384 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00006385 // Reading the symbol table didn't work, disassemble the whole section.
6386 uint64_t SectAddress = Sections[SectIdx].getAddress();
6387 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00006388 uint64_t InstSize;
6389 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00006390 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00006391
Kevin Enderbybf246f52014-09-24 23:08:22 +00006392 uint64_t PC = SectAddress + Index;
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006393 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
6394 DebugOut, nulls())) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006395 if (!NoLeadingAddr) {
6396 if (FullLeadingAddr) {
6397 if (MachOOF->is64Bit())
6398 outs() << format("%016" PRIx64, PC);
6399 else
6400 outs() << format("%08" PRIx64, PC);
6401 } else {
6402 outs() << format("%8" PRIx64 ":", PC);
6403 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006404 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00006405 if (!NoShowRawInsn || Arch == Triple::arm) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006406 outs() << "\t";
Craig Topper0013be12015-09-21 05:32:41 +00006407 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006408 }
Akira Hatanaka1d079942015-03-28 20:44:05 +00006409 IP->printInst(&Inst, outs(), "", *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00006410 outs() << "\n";
6411 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006412 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006413 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006414 outs() << format("\t.byte 0x%02x #bad opcode\n",
6415 *(Bytes.data() + Index) & 0xff);
6416 InstSize = 1; // skip exactly one illegible byte and move on.
6417 } else {
6418 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6419 if (InstSize == 0)
6420 InstSize = 1; // skip illegible bytes
6421 }
Bill Wendling4e68e062012-07-19 00:17:40 +00006422 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00006423 }
6424 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006425 // The TripleName's need to be reset if we are called again for a different
6426 // archtecture.
6427 TripleName = "";
6428 ThumbTripleName = "";
6429
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006430 if (SymbolizerInfo.method != nullptr)
6431 free(SymbolizerInfo.method);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006432 if (SymbolizerInfo.demangled_name != nullptr)
6433 free(SymbolizerInfo.demangled_name);
Kevin Enderby078be602014-10-23 19:53:12 +00006434 if (SymbolizerInfo.bindtable != nullptr)
6435 delete SymbolizerInfo.bindtable;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006436 if (ThumbSymbolizerInfo.method != nullptr)
6437 free(ThumbSymbolizerInfo.method);
6438 if (ThumbSymbolizerInfo.demangled_name != nullptr)
6439 free(ThumbSymbolizerInfo.demangled_name);
6440 if (ThumbSymbolizerInfo.bindtable != nullptr)
6441 delete ThumbSymbolizerInfo.bindtable;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006442 }
6443}
Tim Northover4bd286a2014-08-01 13:07:19 +00006444
Tim Northover39c70bb2014-08-12 11:52:59 +00006445//===----------------------------------------------------------------------===//
6446// __compact_unwind section dumping
6447//===----------------------------------------------------------------------===//
6448
Tim Northover4bd286a2014-08-01 13:07:19 +00006449namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00006450
6451template <typename T> static uint64_t readNext(const char *&Buf) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006452 using llvm::support::little;
6453 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00006454
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006455 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
6456 Buf += sizeof(T);
6457 return Val;
6458}
Tim Northover39c70bb2014-08-12 11:52:59 +00006459
Tim Northover4bd286a2014-08-01 13:07:19 +00006460struct CompactUnwindEntry {
6461 uint32_t OffsetInSection;
6462
6463 uint64_t FunctionAddr;
6464 uint32_t Length;
6465 uint32_t CompactEncoding;
6466 uint64_t PersonalityAddr;
6467 uint64_t LSDAAddr;
6468
6469 RelocationRef FunctionReloc;
6470 RelocationRef PersonalityReloc;
6471 RelocationRef LSDAReloc;
6472
6473 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006474 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006475 if (Is64)
6476 read<uint64_t>(Contents.data() + Offset);
6477 else
6478 read<uint32_t>(Contents.data() + Offset);
6479 }
6480
6481private:
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006482 template <typename UIntPtr> void read(const char *Buf) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006483 FunctionAddr = readNext<UIntPtr>(Buf);
6484 Length = readNext<uint32_t>(Buf);
6485 CompactEncoding = readNext<uint32_t>(Buf);
6486 PersonalityAddr = readNext<UIntPtr>(Buf);
6487 LSDAAddr = readNext<UIntPtr>(Buf);
6488 }
6489};
6490}
6491
6492/// Given a relocation from __compact_unwind, consisting of the RelocationRef
6493/// and data being relocated, determine the best base Name and Addend to use for
6494/// display purposes.
6495///
6496/// 1. An Extern relocation will directly reference a symbol (and the data is
6497/// then already an addend), so use that.
6498/// 2. Otherwise the data is an offset in the object file's layout; try to find
6499// a symbol before it in the same section, and use the offset from there.
6500/// 3. Finally, if all that fails, fall back to an offset from the start of the
6501/// referenced section.
6502static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
6503 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006504 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00006505 StringRef &Name, uint64_t &Addend) {
6506 if (Reloc.getSymbol() != Obj->symbol_end()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006507 Expected<StringRef> NameOrErr = Reloc.getSymbol()->getName();
6508 if (!NameOrErr) {
6509 std::string Buf;
6510 raw_string_ostream OS(Buf);
6511 logAllUnhandledErrors(NameOrErr.takeError(), OS, "");
6512 OS.flush();
6513 report_fatal_error(Buf);
6514 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006515 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00006516 Addend = Addr;
6517 return;
6518 }
6519
6520 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
Keno Fischerc780e8e2015-05-21 21:24:32 +00006521 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
Tim Northover4bd286a2014-08-01 13:07:19 +00006522
Rafael Espindola80291272014-10-08 15:28:58 +00006523 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00006524
6525 auto Sym = Symbols.upper_bound(Addr);
6526 if (Sym == Symbols.begin()) {
6527 // The first symbol in the object is after this reference, the best we can
6528 // do is section-relative notation.
6529 RelocSection.getName(Name);
6530 Addend = Addr - SectionAddr;
6531 return;
6532 }
6533
6534 // Go back one so that SymbolAddress <= Addr.
6535 --Sym;
6536
Rafael Espindola8bab8892015-08-07 23:27:14 +00006537 section_iterator SymSection = *Sym->second.getSection();
Tim Northover4bd286a2014-08-01 13:07:19 +00006538 if (RelocSection == *SymSection) {
6539 // There's a valid symbol in the same section before this reference.
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006540 Expected<StringRef> NameOrErr = Sym->second.getName();
6541 if (!NameOrErr) {
6542 std::string Buf;
6543 raw_string_ostream OS(Buf);
6544 logAllUnhandledErrors(NameOrErr.takeError(), OS, "");
6545 OS.flush();
6546 report_fatal_error(Buf);
6547 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006548 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00006549 Addend = Addr - Sym->first;
6550 return;
6551 }
6552
6553 // There is a symbol before this reference, but it's in a different
6554 // section. Probably not helpful to mention it, so use the section name.
6555 RelocSection.getName(Name);
6556 Addend = Addr - SectionAddr;
6557}
6558
6559static void printUnwindRelocDest(const MachOObjectFile *Obj,
6560 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006561 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006562 StringRef Name;
6563 uint64_t Addend;
6564
Rafael Espindola854038e2015-06-26 14:51:16 +00006565 if (!Reloc.getObject())
Tim Northover0b0add52014-09-09 10:45:06 +00006566 return;
6567
Tim Northover4bd286a2014-08-01 13:07:19 +00006568 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
6569
6570 outs() << Name;
6571 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00006572 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00006573}
6574
6575static void
6576printMachOCompactUnwindSection(const MachOObjectFile *Obj,
6577 std::map<uint64_t, SymbolRef> &Symbols,
6578 const SectionRef &CompactUnwind) {
6579
6580 assert(Obj->isLittleEndian() &&
6581 "There should not be a big-endian .o with __compact_unwind");
6582
6583 bool Is64 = Obj->is64Bit();
6584 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
6585 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
6586
6587 StringRef Contents;
6588 CompactUnwind.getContents(Contents);
6589
6590 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
6591
6592 // First populate the initial raw offsets, encodings and so on from the entry.
6593 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
6594 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
6595 CompactUnwinds.push_back(Entry);
6596 }
6597
6598 // Next we need to look at the relocations to find out what objects are
6599 // actually being referred to.
6600 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00006601 uint64_t RelocAddress = Reloc.getOffset();
Tim Northover4bd286a2014-08-01 13:07:19 +00006602
6603 uint32_t EntryIdx = RelocAddress / EntrySize;
6604 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
6605 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
6606
6607 if (OffsetInEntry == 0)
6608 Entry.FunctionReloc = Reloc;
6609 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
6610 Entry.PersonalityReloc = Reloc;
6611 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
6612 Entry.LSDAReloc = Reloc;
6613 else
6614 llvm_unreachable("Unexpected relocation in __compact_unwind section");
6615 }
6616
6617 // Finally, we're ready to print the data we've gathered.
6618 outs() << "Contents of __compact_unwind section:\n";
6619 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00006620 outs() << " Entry at offset "
6621 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00006622
6623 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006624 outs() << " start: " << format("0x%" PRIx64,
6625 Entry.FunctionAddr) << ' ';
6626 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00006627 outs() << '\n';
6628
6629 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006630 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
6631 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00006632 // 3. The 32-bit compact encoding.
6633 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00006634 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00006635
6636 // 4. The personality function, if present.
Rafael Espindola854038e2015-06-26 14:51:16 +00006637 if (Entry.PersonalityReloc.getObject()) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006638 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00006639 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00006640 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
6641 Entry.PersonalityAddr);
6642 outs() << '\n';
6643 }
6644
6645 // 5. This entry's language-specific data area.
Rafael Espindola854038e2015-06-26 14:51:16 +00006646 if (Entry.LSDAReloc.getObject()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006647 outs() << " LSDA: " << format("0x%" PRIx64,
6648 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00006649 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
6650 outs() << '\n';
6651 }
6652 }
6653}
6654
Tim Northover39c70bb2014-08-12 11:52:59 +00006655//===----------------------------------------------------------------------===//
6656// __unwind_info section dumping
6657//===----------------------------------------------------------------------===//
6658
6659static void printRegularSecondLevelUnwindPage(const char *PageStart) {
6660 const char *Pos = PageStart;
6661 uint32_t Kind = readNext<uint32_t>(Pos);
6662 (void)Kind;
6663 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
6664
6665 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6666 uint16_t NumEntries = readNext<uint16_t>(Pos);
6667
6668 Pos = PageStart + EntriesStart;
6669 for (unsigned i = 0; i < NumEntries; ++i) {
6670 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6671 uint32_t Encoding = readNext<uint32_t>(Pos);
6672
6673 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006674 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6675 << ", "
6676 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006677 }
6678}
6679
6680static void printCompressedSecondLevelUnwindPage(
6681 const char *PageStart, uint32_t FunctionBase,
6682 const SmallVectorImpl<uint32_t> &CommonEncodings) {
6683 const char *Pos = PageStart;
6684 uint32_t Kind = readNext<uint32_t>(Pos);
6685 (void)Kind;
6686 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
6687
6688 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6689 uint16_t NumEntries = readNext<uint16_t>(Pos);
6690
6691 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
6692 readNext<uint16_t>(Pos);
Aaron Ballman80930af2014-08-14 13:53:19 +00006693 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
6694 PageStart + EncodingsStart);
Tim Northover39c70bb2014-08-12 11:52:59 +00006695
6696 Pos = PageStart + EntriesStart;
6697 for (unsigned i = 0; i < NumEntries; ++i) {
6698 uint32_t Entry = readNext<uint32_t>(Pos);
6699 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
6700 uint32_t EncodingIdx = Entry >> 24;
6701
6702 uint32_t Encoding;
6703 if (EncodingIdx < CommonEncodings.size())
6704 Encoding = CommonEncodings[EncodingIdx];
6705 else
6706 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
6707
6708 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006709 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6710 << ", "
6711 << "encoding[" << EncodingIdx
6712 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006713 }
6714}
6715
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006716static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
6717 std::map<uint64_t, SymbolRef> &Symbols,
6718 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00006719
6720 assert(Obj->isLittleEndian() &&
6721 "There should not be a big-endian .o with __unwind_info");
6722
6723 outs() << "Contents of __unwind_info section:\n";
6724
6725 StringRef Contents;
6726 UnwindInfo.getContents(Contents);
6727 const char *Pos = Contents.data();
6728
6729 //===----------------------------------
6730 // Section header
6731 //===----------------------------------
6732
6733 uint32_t Version = readNext<uint32_t>(Pos);
6734 outs() << " Version: "
6735 << format("0x%" PRIx32, Version) << '\n';
6736 assert(Version == 1 && "only understand version 1");
6737
6738 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
6739 outs() << " Common encodings array section offset: "
6740 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
6741 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
6742 outs() << " Number of common encodings in array: "
6743 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
6744
6745 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
6746 outs() << " Personality function array section offset: "
6747 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
6748 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
6749 outs() << " Number of personality functions in array: "
6750 << format("0x%" PRIx32, NumPersonalities) << '\n';
6751
6752 uint32_t IndicesStart = readNext<uint32_t>(Pos);
6753 outs() << " Index array section offset: "
6754 << format("0x%" PRIx32, IndicesStart) << '\n';
6755 uint32_t NumIndices = readNext<uint32_t>(Pos);
6756 outs() << " Number of indices in array: "
6757 << format("0x%" PRIx32, NumIndices) << '\n';
6758
6759 //===----------------------------------
6760 // A shared list of common encodings
6761 //===----------------------------------
6762
6763 // These occupy indices in the range [0, N] whenever an encoding is referenced
6764 // from a compressed 2nd level index table. In practice the linker only
6765 // creates ~128 of these, so that indices are available to embed encodings in
6766 // the 2nd level index.
6767
6768 SmallVector<uint32_t, 64> CommonEncodings;
6769 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
6770 Pos = Contents.data() + CommonEncodingsStart;
6771 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
6772 uint32_t Encoding = readNext<uint32_t>(Pos);
6773 CommonEncodings.push_back(Encoding);
6774
6775 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
6776 << '\n';
6777 }
6778
Tim Northover39c70bb2014-08-12 11:52:59 +00006779 //===----------------------------------
6780 // Personality functions used in this executable
6781 //===----------------------------------
6782
6783 // There should be only a handful of these (one per source language,
6784 // roughly). Particularly since they only get 2 bits in the compact encoding.
6785
6786 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
6787 Pos = Contents.data() + PersonalitiesStart;
6788 for (unsigned i = 0; i < NumPersonalities; ++i) {
6789 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
6790 outs() << " personality[" << i + 1
6791 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
6792 }
6793
6794 //===----------------------------------
6795 // The level 1 index entries
6796 //===----------------------------------
6797
6798 // These specify an approximate place to start searching for the more detailed
6799 // information, sorted by PC.
6800
6801 struct IndexEntry {
6802 uint32_t FunctionOffset;
6803 uint32_t SecondLevelPageStart;
6804 uint32_t LSDAStart;
6805 };
6806
6807 SmallVector<IndexEntry, 4> IndexEntries;
6808
6809 outs() << " Top level indices: (count = " << NumIndices << ")\n";
6810 Pos = Contents.data() + IndicesStart;
6811 for (unsigned i = 0; i < NumIndices; ++i) {
6812 IndexEntry Entry;
6813
6814 Entry.FunctionOffset = readNext<uint32_t>(Pos);
6815 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
6816 Entry.LSDAStart = readNext<uint32_t>(Pos);
6817 IndexEntries.push_back(Entry);
6818
6819 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006820 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
6821 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00006822 << "2nd level page offset="
6823 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006824 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006825 }
6826
Tim Northover39c70bb2014-08-12 11:52:59 +00006827 //===----------------------------------
6828 // Next come the LSDA tables
6829 //===----------------------------------
6830
6831 // The LSDA layout is rather implicit: it's a contiguous array of entries from
6832 // the first top-level index's LSDAOffset to the last (sentinel).
6833
6834 outs() << " LSDA descriptors:\n";
6835 Pos = Contents.data() + IndexEntries[0].LSDAStart;
6836 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
6837 (2 * sizeof(uint32_t));
6838 for (int i = 0; i < NumLSDAs; ++i) {
6839 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6840 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
6841 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006842 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6843 << ", "
6844 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006845 }
6846
6847 //===----------------------------------
6848 // Finally, the 2nd level indices
6849 //===----------------------------------
6850
6851 // Generally these are 4K in size, and have 2 possible forms:
6852 // + Regular stores up to 511 entries with disparate encodings
6853 // + Compressed stores up to 1021 entries if few enough compact encoding
6854 // values are used.
6855 outs() << " Second level indices:\n";
6856 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
6857 // The final sentinel top-level index has no associated 2nd level page
6858 if (IndexEntries[i].SecondLevelPageStart == 0)
6859 break;
6860
6861 outs() << " Second level index[" << i << "]: "
6862 << "offset in section="
6863 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
6864 << ", "
6865 << "base function offset="
6866 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
6867
6868 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
Aaron Ballman80930af2014-08-14 13:53:19 +00006869 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00006870 if (Kind == 2)
6871 printRegularSecondLevelUnwindPage(Pos);
6872 else if (Kind == 3)
6873 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
6874 CommonEncodings);
6875 else
6876 llvm_unreachable("Do not know how to print this kind of 2nd level page");
Tim Northover39c70bb2014-08-12 11:52:59 +00006877 }
6878}
6879
Tim Northover4bd286a2014-08-01 13:07:19 +00006880void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
6881 std::map<uint64_t, SymbolRef> Symbols;
6882 for (const SymbolRef &SymRef : Obj->symbols()) {
6883 // Discard any undefined or absolute symbols. They're not going to take part
6884 // in the convenience lookup for unwind info and just take up resources.
Rafael Espindola8bab8892015-08-07 23:27:14 +00006885 section_iterator Section = *SymRef.getSection();
Tim Northover4bd286a2014-08-01 13:07:19 +00006886 if (Section == Obj->section_end())
6887 continue;
6888
Rafael Espindoladea00162015-07-03 17:44:18 +00006889 uint64_t Addr = SymRef.getValue();
Tim Northover4bd286a2014-08-01 13:07:19 +00006890 Symbols.insert(std::make_pair(Addr, SymRef));
6891 }
6892
6893 for (const SectionRef &Section : Obj->sections()) {
6894 StringRef SectName;
6895 Section.getName(SectName);
6896 if (SectName == "__compact_unwind")
6897 printMachOCompactUnwindSection(Obj, Symbols, Section);
6898 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00006899 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00006900 }
6901}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00006902
6903static void PrintMachHeader(uint32_t magic, uint32_t cputype,
6904 uint32_t cpusubtype, uint32_t filetype,
6905 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
6906 bool verbose) {
6907 outs() << "Mach header\n";
6908 outs() << " magic cputype cpusubtype caps filetype ncmds "
6909 "sizeofcmds flags\n";
6910 if (verbose) {
6911 if (magic == MachO::MH_MAGIC)
6912 outs() << " MH_MAGIC";
6913 else if (magic == MachO::MH_MAGIC_64)
6914 outs() << "MH_MAGIC_64";
6915 else
6916 outs() << format(" 0x%08" PRIx32, magic);
6917 switch (cputype) {
6918 case MachO::CPU_TYPE_I386:
6919 outs() << " I386";
6920 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6921 case MachO::CPU_SUBTYPE_I386_ALL:
6922 outs() << " ALL";
6923 break;
6924 default:
6925 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6926 break;
6927 }
6928 break;
6929 case MachO::CPU_TYPE_X86_64:
6930 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00006931 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6932 case MachO::CPU_SUBTYPE_X86_64_ALL:
6933 outs() << " ALL";
6934 break;
6935 case MachO::CPU_SUBTYPE_X86_64_H:
6936 outs() << " Haswell";
6937 break;
6938 default:
6939 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6940 break;
6941 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00006942 break;
6943 case MachO::CPU_TYPE_ARM:
6944 outs() << " ARM";
6945 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6946 case MachO::CPU_SUBTYPE_ARM_ALL:
6947 outs() << " ALL";
6948 break;
6949 case MachO::CPU_SUBTYPE_ARM_V4T:
6950 outs() << " V4T";
6951 break;
6952 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
6953 outs() << " V5TEJ";
6954 break;
6955 case MachO::CPU_SUBTYPE_ARM_XSCALE:
6956 outs() << " XSCALE";
6957 break;
6958 case MachO::CPU_SUBTYPE_ARM_V6:
6959 outs() << " V6";
6960 break;
6961 case MachO::CPU_SUBTYPE_ARM_V6M:
6962 outs() << " V6M";
6963 break;
6964 case MachO::CPU_SUBTYPE_ARM_V7:
6965 outs() << " V7";
6966 break;
6967 case MachO::CPU_SUBTYPE_ARM_V7EM:
6968 outs() << " V7EM";
6969 break;
6970 case MachO::CPU_SUBTYPE_ARM_V7K:
6971 outs() << " V7K";
6972 break;
6973 case MachO::CPU_SUBTYPE_ARM_V7M:
6974 outs() << " V7M";
6975 break;
6976 case MachO::CPU_SUBTYPE_ARM_V7S:
6977 outs() << " V7S";
6978 break;
6979 default:
6980 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6981 break;
6982 }
6983 break;
6984 case MachO::CPU_TYPE_ARM64:
6985 outs() << " ARM64";
6986 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6987 case MachO::CPU_SUBTYPE_ARM64_ALL:
6988 outs() << " ALL";
6989 break;
6990 default:
6991 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6992 break;
6993 }
6994 break;
6995 case MachO::CPU_TYPE_POWERPC:
6996 outs() << " PPC";
6997 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6998 case MachO::CPU_SUBTYPE_POWERPC_ALL:
6999 outs() << " ALL";
7000 break;
7001 default:
7002 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7003 break;
7004 }
7005 break;
7006 case MachO::CPU_TYPE_POWERPC64:
7007 outs() << " PPC64";
7008 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7009 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7010 outs() << " ALL";
7011 break;
7012 default:
7013 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7014 break;
7015 }
7016 break;
Kevin Enderby40fdbf82016-01-26 18:20:49 +00007017 default:
7018 outs() << format(" %7d", cputype);
7019 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7020 break;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007021 }
7022 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007023 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007024 } else {
7025 outs() << format(" 0x%02" PRIx32,
7026 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7027 }
7028 switch (filetype) {
7029 case MachO::MH_OBJECT:
7030 outs() << " OBJECT";
7031 break;
7032 case MachO::MH_EXECUTE:
7033 outs() << " EXECUTE";
7034 break;
7035 case MachO::MH_FVMLIB:
7036 outs() << " FVMLIB";
7037 break;
7038 case MachO::MH_CORE:
7039 outs() << " CORE";
7040 break;
7041 case MachO::MH_PRELOAD:
7042 outs() << " PRELOAD";
7043 break;
7044 case MachO::MH_DYLIB:
7045 outs() << " DYLIB";
7046 break;
7047 case MachO::MH_DYLIB_STUB:
7048 outs() << " DYLIB_STUB";
7049 break;
7050 case MachO::MH_DYLINKER:
7051 outs() << " DYLINKER";
7052 break;
7053 case MachO::MH_BUNDLE:
7054 outs() << " BUNDLE";
7055 break;
7056 case MachO::MH_DSYM:
7057 outs() << " DSYM";
7058 break;
7059 case MachO::MH_KEXT_BUNDLE:
7060 outs() << " KEXTBUNDLE";
7061 break;
7062 default:
7063 outs() << format(" %10u", filetype);
7064 break;
7065 }
7066 outs() << format(" %5u", ncmds);
7067 outs() << format(" %10u", sizeofcmds);
7068 uint32_t f = flags;
7069 if (f & MachO::MH_NOUNDEFS) {
7070 outs() << " NOUNDEFS";
7071 f &= ~MachO::MH_NOUNDEFS;
7072 }
7073 if (f & MachO::MH_INCRLINK) {
7074 outs() << " INCRLINK";
7075 f &= ~MachO::MH_INCRLINK;
7076 }
7077 if (f & MachO::MH_DYLDLINK) {
7078 outs() << " DYLDLINK";
7079 f &= ~MachO::MH_DYLDLINK;
7080 }
7081 if (f & MachO::MH_BINDATLOAD) {
7082 outs() << " BINDATLOAD";
7083 f &= ~MachO::MH_BINDATLOAD;
7084 }
7085 if (f & MachO::MH_PREBOUND) {
7086 outs() << " PREBOUND";
7087 f &= ~MachO::MH_PREBOUND;
7088 }
7089 if (f & MachO::MH_SPLIT_SEGS) {
7090 outs() << " SPLIT_SEGS";
7091 f &= ~MachO::MH_SPLIT_SEGS;
7092 }
7093 if (f & MachO::MH_LAZY_INIT) {
7094 outs() << " LAZY_INIT";
7095 f &= ~MachO::MH_LAZY_INIT;
7096 }
7097 if (f & MachO::MH_TWOLEVEL) {
7098 outs() << " TWOLEVEL";
7099 f &= ~MachO::MH_TWOLEVEL;
7100 }
7101 if (f & MachO::MH_FORCE_FLAT) {
7102 outs() << " FORCE_FLAT";
7103 f &= ~MachO::MH_FORCE_FLAT;
7104 }
7105 if (f & MachO::MH_NOMULTIDEFS) {
7106 outs() << " NOMULTIDEFS";
7107 f &= ~MachO::MH_NOMULTIDEFS;
7108 }
7109 if (f & MachO::MH_NOFIXPREBINDING) {
7110 outs() << " NOFIXPREBINDING";
7111 f &= ~MachO::MH_NOFIXPREBINDING;
7112 }
7113 if (f & MachO::MH_PREBINDABLE) {
7114 outs() << " PREBINDABLE";
7115 f &= ~MachO::MH_PREBINDABLE;
7116 }
7117 if (f & MachO::MH_ALLMODSBOUND) {
7118 outs() << " ALLMODSBOUND";
7119 f &= ~MachO::MH_ALLMODSBOUND;
7120 }
7121 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
7122 outs() << " SUBSECTIONS_VIA_SYMBOLS";
7123 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
7124 }
7125 if (f & MachO::MH_CANONICAL) {
7126 outs() << " CANONICAL";
7127 f &= ~MachO::MH_CANONICAL;
7128 }
7129 if (f & MachO::MH_WEAK_DEFINES) {
7130 outs() << " WEAK_DEFINES";
7131 f &= ~MachO::MH_WEAK_DEFINES;
7132 }
7133 if (f & MachO::MH_BINDS_TO_WEAK) {
7134 outs() << " BINDS_TO_WEAK";
7135 f &= ~MachO::MH_BINDS_TO_WEAK;
7136 }
7137 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
7138 outs() << " ALLOW_STACK_EXECUTION";
7139 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
7140 }
7141 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
7142 outs() << " DEAD_STRIPPABLE_DYLIB";
7143 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
7144 }
7145 if (f & MachO::MH_PIE) {
7146 outs() << " PIE";
7147 f &= ~MachO::MH_PIE;
7148 }
7149 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
7150 outs() << " NO_REEXPORTED_DYLIBS";
7151 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
7152 }
7153 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
7154 outs() << " MH_HAS_TLV_DESCRIPTORS";
7155 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
7156 }
7157 if (f & MachO::MH_NO_HEAP_EXECUTION) {
7158 outs() << " MH_NO_HEAP_EXECUTION";
7159 f &= ~MachO::MH_NO_HEAP_EXECUTION;
7160 }
7161 if (f & MachO::MH_APP_EXTENSION_SAFE) {
7162 outs() << " APP_EXTENSION_SAFE";
7163 f &= ~MachO::MH_APP_EXTENSION_SAFE;
7164 }
7165 if (f != 0 || flags == 0)
7166 outs() << format(" 0x%08" PRIx32, f);
7167 } else {
7168 outs() << format(" 0x%08" PRIx32, magic);
7169 outs() << format(" %7d", cputype);
7170 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7171 outs() << format(" 0x%02" PRIx32,
7172 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7173 outs() << format(" %10u", filetype);
7174 outs() << format(" %5u", ncmds);
7175 outs() << format(" %10u", sizeofcmds);
7176 outs() << format(" 0x%08" PRIx32, flags);
7177 }
7178 outs() << "\n";
7179}
7180
Kevin Enderby956366c2014-08-29 22:30:52 +00007181static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
7182 StringRef SegName, uint64_t vmaddr,
7183 uint64_t vmsize, uint64_t fileoff,
7184 uint64_t filesize, uint32_t maxprot,
7185 uint32_t initprot, uint32_t nsects,
7186 uint32_t flags, uint32_t object_size,
7187 bool verbose) {
7188 uint64_t expected_cmdsize;
7189 if (cmd == MachO::LC_SEGMENT) {
7190 outs() << " cmd LC_SEGMENT\n";
7191 expected_cmdsize = nsects;
7192 expected_cmdsize *= sizeof(struct MachO::section);
7193 expected_cmdsize += sizeof(struct MachO::segment_command);
7194 } else {
7195 outs() << " cmd LC_SEGMENT_64\n";
7196 expected_cmdsize = nsects;
7197 expected_cmdsize *= sizeof(struct MachO::section_64);
7198 expected_cmdsize += sizeof(struct MachO::segment_command_64);
7199 }
7200 outs() << " cmdsize " << cmdsize;
7201 if (cmdsize != expected_cmdsize)
7202 outs() << " Inconsistent size\n";
7203 else
7204 outs() << "\n";
7205 outs() << " segname " << SegName << "\n";
7206 if (cmd == MachO::LC_SEGMENT_64) {
7207 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
7208 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
7209 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00007210 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
7211 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00007212 }
7213 outs() << " fileoff " << fileoff;
7214 if (fileoff > object_size)
7215 outs() << " (past end of file)\n";
7216 else
7217 outs() << "\n";
7218 outs() << " filesize " << filesize;
7219 if (fileoff + filesize > object_size)
7220 outs() << " (past end of file)\n";
7221 else
7222 outs() << "\n";
7223 if (verbose) {
7224 if ((maxprot &
7225 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7226 MachO::VM_PROT_EXECUTE)) != 0)
7227 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
7228 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00007229 outs() << " maxprot ";
7230 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
7231 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7232 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007233 }
7234 if ((initprot &
7235 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7236 MachO::VM_PROT_EXECUTE)) != 0)
7237 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
7238 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00007239 outs() << " initprot ";
7240 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
7241 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7242 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007243 }
7244 } else {
7245 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
7246 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
7247 }
7248 outs() << " nsects " << nsects << "\n";
7249 if (verbose) {
7250 outs() << " flags";
7251 if (flags == 0)
7252 outs() << " (none)\n";
7253 else {
7254 if (flags & MachO::SG_HIGHVM) {
7255 outs() << " HIGHVM";
7256 flags &= ~MachO::SG_HIGHVM;
7257 }
7258 if (flags & MachO::SG_FVMLIB) {
7259 outs() << " FVMLIB";
7260 flags &= ~MachO::SG_FVMLIB;
7261 }
7262 if (flags & MachO::SG_NORELOC) {
7263 outs() << " NORELOC";
7264 flags &= ~MachO::SG_NORELOC;
7265 }
7266 if (flags & MachO::SG_PROTECTED_VERSION_1) {
7267 outs() << " PROTECTED_VERSION_1";
7268 flags &= ~MachO::SG_PROTECTED_VERSION_1;
7269 }
7270 if (flags)
7271 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
7272 else
7273 outs() << "\n";
7274 }
7275 } else {
7276 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
7277 }
7278}
7279
7280static void PrintSection(const char *sectname, const char *segname,
7281 uint64_t addr, uint64_t size, uint32_t offset,
7282 uint32_t align, uint32_t reloff, uint32_t nreloc,
7283 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
7284 uint32_t cmd, const char *sg_segname,
7285 uint32_t filetype, uint32_t object_size,
7286 bool verbose) {
7287 outs() << "Section\n";
7288 outs() << " sectname " << format("%.16s\n", sectname);
7289 outs() << " segname " << format("%.16s", segname);
7290 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
7291 outs() << " (does not match segment)\n";
7292 else
7293 outs() << "\n";
7294 if (cmd == MachO::LC_SEGMENT_64) {
7295 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
7296 outs() << " size " << format("0x%016" PRIx64, size);
7297 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00007298 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
7299 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00007300 }
7301 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
7302 outs() << " (past end of file)\n";
7303 else
7304 outs() << "\n";
7305 outs() << " offset " << offset;
7306 if (offset > object_size)
7307 outs() << " (past end of file)\n";
7308 else
7309 outs() << "\n";
7310 uint32_t align_shifted = 1 << align;
7311 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
7312 outs() << " reloff " << reloff;
7313 if (reloff > object_size)
7314 outs() << " (past end of file)\n";
7315 else
7316 outs() << "\n";
7317 outs() << " nreloc " << nreloc;
7318 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
7319 outs() << " (past end of file)\n";
7320 else
7321 outs() << "\n";
7322 uint32_t section_type = flags & MachO::SECTION_TYPE;
7323 if (verbose) {
7324 outs() << " type";
7325 if (section_type == MachO::S_REGULAR)
7326 outs() << " S_REGULAR\n";
7327 else if (section_type == MachO::S_ZEROFILL)
7328 outs() << " S_ZEROFILL\n";
7329 else if (section_type == MachO::S_CSTRING_LITERALS)
7330 outs() << " S_CSTRING_LITERALS\n";
7331 else if (section_type == MachO::S_4BYTE_LITERALS)
7332 outs() << " S_4BYTE_LITERALS\n";
7333 else if (section_type == MachO::S_8BYTE_LITERALS)
7334 outs() << " S_8BYTE_LITERALS\n";
7335 else if (section_type == MachO::S_16BYTE_LITERALS)
7336 outs() << " S_16BYTE_LITERALS\n";
7337 else if (section_type == MachO::S_LITERAL_POINTERS)
7338 outs() << " S_LITERAL_POINTERS\n";
7339 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
7340 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
7341 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
7342 outs() << " S_LAZY_SYMBOL_POINTERS\n";
7343 else if (section_type == MachO::S_SYMBOL_STUBS)
7344 outs() << " S_SYMBOL_STUBS\n";
7345 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
7346 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
7347 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
7348 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
7349 else if (section_type == MachO::S_COALESCED)
7350 outs() << " S_COALESCED\n";
7351 else if (section_type == MachO::S_INTERPOSING)
7352 outs() << " S_INTERPOSING\n";
7353 else if (section_type == MachO::S_DTRACE_DOF)
7354 outs() << " S_DTRACE_DOF\n";
7355 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
7356 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
7357 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
7358 outs() << " S_THREAD_LOCAL_REGULAR\n";
7359 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
7360 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
7361 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
7362 outs() << " S_THREAD_LOCAL_VARIABLES\n";
7363 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7364 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
7365 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
7366 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
7367 else
7368 outs() << format("0x%08" PRIx32, section_type) << "\n";
7369 outs() << "attributes";
7370 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
7371 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
7372 outs() << " PURE_INSTRUCTIONS";
7373 if (section_attributes & MachO::S_ATTR_NO_TOC)
7374 outs() << " NO_TOC";
7375 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
7376 outs() << " STRIP_STATIC_SYMS";
7377 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
7378 outs() << " NO_DEAD_STRIP";
7379 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
7380 outs() << " LIVE_SUPPORT";
7381 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
7382 outs() << " SELF_MODIFYING_CODE";
7383 if (section_attributes & MachO::S_ATTR_DEBUG)
7384 outs() << " DEBUG";
7385 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
7386 outs() << " SOME_INSTRUCTIONS";
7387 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
7388 outs() << " EXT_RELOC";
7389 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
7390 outs() << " LOC_RELOC";
7391 if (section_attributes == 0)
7392 outs() << " (none)";
7393 outs() << "\n";
7394 } else
7395 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
7396 outs() << " reserved1 " << reserved1;
7397 if (section_type == MachO::S_SYMBOL_STUBS ||
7398 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
7399 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
7400 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
7401 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7402 outs() << " (index into indirect symbol table)\n";
7403 else
7404 outs() << "\n";
7405 outs() << " reserved2 " << reserved2;
7406 if (section_type == MachO::S_SYMBOL_STUBS)
7407 outs() << " (size of stubs)\n";
7408 else
7409 outs() << "\n";
7410}
7411
David Majnemer73cc6ff2014-11-13 19:48:56 +00007412static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00007413 uint32_t object_size) {
7414 outs() << " cmd LC_SYMTAB\n";
7415 outs() << " cmdsize " << st.cmdsize;
7416 if (st.cmdsize != sizeof(struct MachO::symtab_command))
7417 outs() << " Incorrect size\n";
7418 else
7419 outs() << "\n";
7420 outs() << " symoff " << st.symoff;
7421 if (st.symoff > object_size)
7422 outs() << " (past end of file)\n";
7423 else
7424 outs() << "\n";
7425 outs() << " nsyms " << st.nsyms;
7426 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00007427 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007428 big_size = st.nsyms;
7429 big_size *= sizeof(struct MachO::nlist_64);
7430 big_size += st.symoff;
7431 if (big_size > object_size)
7432 outs() << " (past end of file)\n";
7433 else
7434 outs() << "\n";
7435 } else {
7436 big_size = st.nsyms;
7437 big_size *= sizeof(struct MachO::nlist);
7438 big_size += st.symoff;
7439 if (big_size > object_size)
7440 outs() << " (past end of file)\n";
7441 else
7442 outs() << "\n";
7443 }
7444 outs() << " stroff " << st.stroff;
7445 if (st.stroff > object_size)
7446 outs() << " (past end of file)\n";
7447 else
7448 outs() << "\n";
7449 outs() << " strsize " << st.strsize;
7450 big_size = st.stroff;
7451 big_size += st.strsize;
7452 if (big_size > object_size)
7453 outs() << " (past end of file)\n";
7454 else
7455 outs() << "\n";
7456}
7457
7458static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
7459 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00007460 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007461 outs() << " cmd LC_DYSYMTAB\n";
7462 outs() << " cmdsize " << dyst.cmdsize;
7463 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
7464 outs() << " Incorrect size\n";
7465 else
7466 outs() << "\n";
7467 outs() << " ilocalsym " << dyst.ilocalsym;
7468 if (dyst.ilocalsym > nsyms)
7469 outs() << " (greater than the number of symbols)\n";
7470 else
7471 outs() << "\n";
7472 outs() << " nlocalsym " << dyst.nlocalsym;
7473 uint64_t big_size;
7474 big_size = dyst.ilocalsym;
7475 big_size += dyst.nlocalsym;
7476 if (big_size > nsyms)
7477 outs() << " (past the end of the symbol table)\n";
7478 else
7479 outs() << "\n";
7480 outs() << " iextdefsym " << dyst.iextdefsym;
7481 if (dyst.iextdefsym > nsyms)
7482 outs() << " (greater than the number of symbols)\n";
7483 else
7484 outs() << "\n";
7485 outs() << " nextdefsym " << dyst.nextdefsym;
7486 big_size = dyst.iextdefsym;
7487 big_size += dyst.nextdefsym;
7488 if (big_size > nsyms)
7489 outs() << " (past the end of the symbol table)\n";
7490 else
7491 outs() << "\n";
7492 outs() << " iundefsym " << dyst.iundefsym;
7493 if (dyst.iundefsym > nsyms)
7494 outs() << " (greater than the number of symbols)\n";
7495 else
7496 outs() << "\n";
7497 outs() << " nundefsym " << dyst.nundefsym;
7498 big_size = dyst.iundefsym;
7499 big_size += dyst.nundefsym;
7500 if (big_size > nsyms)
7501 outs() << " (past the end of the symbol table)\n";
7502 else
7503 outs() << "\n";
7504 outs() << " tocoff " << dyst.tocoff;
7505 if (dyst.tocoff > object_size)
7506 outs() << " (past end of file)\n";
7507 else
7508 outs() << "\n";
7509 outs() << " ntoc " << dyst.ntoc;
7510 big_size = dyst.ntoc;
7511 big_size *= sizeof(struct MachO::dylib_table_of_contents);
7512 big_size += dyst.tocoff;
7513 if (big_size > object_size)
7514 outs() << " (past end of file)\n";
7515 else
7516 outs() << "\n";
7517 outs() << " modtaboff " << dyst.modtaboff;
7518 if (dyst.modtaboff > object_size)
7519 outs() << " (past end of file)\n";
7520 else
7521 outs() << "\n";
7522 outs() << " nmodtab " << dyst.nmodtab;
7523 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00007524 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007525 modtabend = dyst.nmodtab;
7526 modtabend *= sizeof(struct MachO::dylib_module_64);
7527 modtabend += dyst.modtaboff;
7528 } else {
7529 modtabend = dyst.nmodtab;
7530 modtabend *= sizeof(struct MachO::dylib_module);
7531 modtabend += dyst.modtaboff;
7532 }
7533 if (modtabend > object_size)
7534 outs() << " (past end of file)\n";
7535 else
7536 outs() << "\n";
7537 outs() << " extrefsymoff " << dyst.extrefsymoff;
7538 if (dyst.extrefsymoff > object_size)
7539 outs() << " (past end of file)\n";
7540 else
7541 outs() << "\n";
7542 outs() << " nextrefsyms " << dyst.nextrefsyms;
7543 big_size = dyst.nextrefsyms;
7544 big_size *= sizeof(struct MachO::dylib_reference);
7545 big_size += dyst.extrefsymoff;
7546 if (big_size > object_size)
7547 outs() << " (past end of file)\n";
7548 else
7549 outs() << "\n";
7550 outs() << " indirectsymoff " << dyst.indirectsymoff;
7551 if (dyst.indirectsymoff > object_size)
7552 outs() << " (past end of file)\n";
7553 else
7554 outs() << "\n";
7555 outs() << " nindirectsyms " << dyst.nindirectsyms;
7556 big_size = dyst.nindirectsyms;
7557 big_size *= sizeof(uint32_t);
7558 big_size += dyst.indirectsymoff;
7559 if (big_size > object_size)
7560 outs() << " (past end of file)\n";
7561 else
7562 outs() << "\n";
7563 outs() << " extreloff " << dyst.extreloff;
7564 if (dyst.extreloff > object_size)
7565 outs() << " (past end of file)\n";
7566 else
7567 outs() << "\n";
7568 outs() << " nextrel " << dyst.nextrel;
7569 big_size = dyst.nextrel;
7570 big_size *= sizeof(struct MachO::relocation_info);
7571 big_size += dyst.extreloff;
7572 if (big_size > object_size)
7573 outs() << " (past end of file)\n";
7574 else
7575 outs() << "\n";
7576 outs() << " locreloff " << dyst.locreloff;
7577 if (dyst.locreloff > object_size)
7578 outs() << " (past end of file)\n";
7579 else
7580 outs() << "\n";
7581 outs() << " nlocrel " << dyst.nlocrel;
7582 big_size = dyst.nlocrel;
7583 big_size *= sizeof(struct MachO::relocation_info);
7584 big_size += dyst.locreloff;
7585 if (big_size > object_size)
7586 outs() << " (past end of file)\n";
7587 else
7588 outs() << "\n";
7589}
7590
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007591static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
7592 uint32_t object_size) {
7593 if (dc.cmd == MachO::LC_DYLD_INFO)
7594 outs() << " cmd LC_DYLD_INFO\n";
7595 else
7596 outs() << " cmd LC_DYLD_INFO_ONLY\n";
7597 outs() << " cmdsize " << dc.cmdsize;
7598 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
7599 outs() << " Incorrect size\n";
7600 else
7601 outs() << "\n";
7602 outs() << " rebase_off " << dc.rebase_off;
7603 if (dc.rebase_off > object_size)
7604 outs() << " (past end of file)\n";
7605 else
7606 outs() << "\n";
7607 outs() << " rebase_size " << dc.rebase_size;
7608 uint64_t big_size;
7609 big_size = dc.rebase_off;
7610 big_size += dc.rebase_size;
7611 if (big_size > object_size)
7612 outs() << " (past end of file)\n";
7613 else
7614 outs() << "\n";
7615 outs() << " bind_off " << dc.bind_off;
7616 if (dc.bind_off > object_size)
7617 outs() << " (past end of file)\n";
7618 else
7619 outs() << "\n";
7620 outs() << " bind_size " << dc.bind_size;
7621 big_size = dc.bind_off;
7622 big_size += dc.bind_size;
7623 if (big_size > object_size)
7624 outs() << " (past end of file)\n";
7625 else
7626 outs() << "\n";
7627 outs() << " weak_bind_off " << dc.weak_bind_off;
7628 if (dc.weak_bind_off > object_size)
7629 outs() << " (past end of file)\n";
7630 else
7631 outs() << "\n";
7632 outs() << " weak_bind_size " << dc.weak_bind_size;
7633 big_size = dc.weak_bind_off;
7634 big_size += dc.weak_bind_size;
7635 if (big_size > object_size)
7636 outs() << " (past end of file)\n";
7637 else
7638 outs() << "\n";
7639 outs() << " lazy_bind_off " << dc.lazy_bind_off;
7640 if (dc.lazy_bind_off > object_size)
7641 outs() << " (past end of file)\n";
7642 else
7643 outs() << "\n";
7644 outs() << " lazy_bind_size " << dc.lazy_bind_size;
7645 big_size = dc.lazy_bind_off;
7646 big_size += dc.lazy_bind_size;
7647 if (big_size > object_size)
7648 outs() << " (past end of file)\n";
7649 else
7650 outs() << "\n";
7651 outs() << " export_off " << dc.export_off;
7652 if (dc.export_off > object_size)
7653 outs() << " (past end of file)\n";
7654 else
7655 outs() << "\n";
7656 outs() << " export_size " << dc.export_size;
7657 big_size = dc.export_off;
7658 big_size += dc.export_size;
7659 if (big_size > object_size)
7660 outs() << " (past end of file)\n";
7661 else
7662 outs() << "\n";
7663}
7664
7665static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
7666 const char *Ptr) {
7667 if (dyld.cmd == MachO::LC_ID_DYLINKER)
7668 outs() << " cmd LC_ID_DYLINKER\n";
7669 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
7670 outs() << " cmd LC_LOAD_DYLINKER\n";
7671 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
7672 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
7673 else
7674 outs() << " cmd ?(" << dyld.cmd << ")\n";
7675 outs() << " cmdsize " << dyld.cmdsize;
7676 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
7677 outs() << " Incorrect size\n";
7678 else
7679 outs() << "\n";
7680 if (dyld.name >= dyld.cmdsize)
7681 outs() << " name ?(bad offset " << dyld.name << ")\n";
7682 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007683 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007684 outs() << " name " << P << " (offset " << dyld.name << ")\n";
7685 }
7686}
7687
7688static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
7689 outs() << " cmd LC_UUID\n";
7690 outs() << " cmdsize " << uuid.cmdsize;
7691 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
7692 outs() << " Incorrect size\n";
7693 else
7694 outs() << "\n";
7695 outs() << " uuid ";
Davide Italianoc74277a2015-12-07 00:03:28 +00007696 for (int i = 0; i < 16; ++i) {
7697 outs() << format("%02" PRIX32, uuid.uuid[i]);
7698 if (i == 3 || i == 5 || i == 7 || i == 9)
7699 outs() << "-";
7700 }
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007701 outs() << "\n";
7702}
7703
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007704static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00007705 outs() << " cmd LC_RPATH\n";
7706 outs() << " cmdsize " << rpath.cmdsize;
7707 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
7708 outs() << " Incorrect size\n";
7709 else
7710 outs() << "\n";
7711 if (rpath.path >= rpath.cmdsize)
7712 outs() << " path ?(bad offset " << rpath.path << ")\n";
7713 else {
7714 const char *P = (const char *)(Ptr) + rpath.path;
7715 outs() << " path " << P << " (offset " << rpath.path << ")\n";
7716 }
7717}
7718
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007719static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
Tim Northoverbfbfb122015-11-02 21:26:58 +00007720 StringRef LoadCmdName;
7721 switch (vd.cmd) {
7722 case MachO::LC_VERSION_MIN_MACOSX:
7723 LoadCmdName = "LC_VERSION_MIN_MACOSX";
7724 break;
7725 case MachO::LC_VERSION_MIN_IPHONEOS:
7726 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
7727 break;
7728 case MachO::LC_VERSION_MIN_TVOS:
7729 LoadCmdName = "LC_VERSION_MIN_TVOS";
7730 break;
7731 case MachO::LC_VERSION_MIN_WATCHOS:
7732 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
7733 break;
7734 default:
7735 llvm_unreachable("Unknown version min load command");
7736 }
7737
7738 outs() << " cmd " << LoadCmdName << '\n';
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007739 outs() << " cmdsize " << vd.cmdsize;
7740 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
7741 outs() << " Incorrect size\n";
7742 else
7743 outs() << "\n";
Davide Italiano56baef32015-08-26 12:26:11 +00007744 outs() << " version "
7745 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
7746 << MachOObjectFile::getVersionMinMinor(vd, false);
7747 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
7748 if (Update != 0)
7749 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007750 outs() << "\n";
7751 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00007752 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007753 else {
Davide Italiano56baef32015-08-26 12:26:11 +00007754 outs() << " sdk "
7755 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
7756 << MachOObjectFile::getVersionMinMinor(vd, true);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007757 }
Davide Italiano56baef32015-08-26 12:26:11 +00007758 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
7759 if (Update != 0)
7760 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007761 outs() << "\n";
7762}
7763
7764static void PrintSourceVersionCommand(MachO::source_version_command sd) {
7765 outs() << " cmd LC_SOURCE_VERSION\n";
7766 outs() << " cmdsize " << sd.cmdsize;
7767 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
7768 outs() << " Incorrect size\n";
7769 else
7770 outs() << "\n";
7771 uint64_t a = (sd.version >> 40) & 0xffffff;
7772 uint64_t b = (sd.version >> 30) & 0x3ff;
7773 uint64_t c = (sd.version >> 20) & 0x3ff;
7774 uint64_t d = (sd.version >> 10) & 0x3ff;
7775 uint64_t e = sd.version & 0x3ff;
7776 outs() << " version " << a << "." << b;
7777 if (e != 0)
7778 outs() << "." << c << "." << d << "." << e;
7779 else if (d != 0)
7780 outs() << "." << c << "." << d;
7781 else if (c != 0)
7782 outs() << "." << c;
7783 outs() << "\n";
7784}
7785
7786static void PrintEntryPointCommand(MachO::entry_point_command ep) {
7787 outs() << " cmd LC_MAIN\n";
7788 outs() << " cmdsize " << ep.cmdsize;
7789 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
7790 outs() << " Incorrect size\n";
7791 else
7792 outs() << "\n";
7793 outs() << " entryoff " << ep.entryoff << "\n";
7794 outs() << " stacksize " << ep.stacksize << "\n";
7795}
7796
Kevin Enderby0804f4672014-12-16 23:25:52 +00007797static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
7798 uint32_t object_size) {
7799 outs() << " cmd LC_ENCRYPTION_INFO\n";
7800 outs() << " cmdsize " << ec.cmdsize;
7801 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
7802 outs() << " Incorrect size\n";
7803 else
7804 outs() << "\n";
7805 outs() << " cryptoff " << ec.cryptoff;
7806 if (ec.cryptoff > object_size)
7807 outs() << " (past end of file)\n";
7808 else
7809 outs() << "\n";
7810 outs() << " cryptsize " << ec.cryptsize;
7811 if (ec.cryptsize > object_size)
7812 outs() << " (past end of file)\n";
7813 else
7814 outs() << "\n";
7815 outs() << " cryptid " << ec.cryptid << "\n";
7816}
7817
Kevin Enderby57538292014-12-17 01:01:30 +00007818static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007819 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00007820 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
7821 outs() << " cmdsize " << ec.cmdsize;
7822 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
7823 outs() << " Incorrect size\n";
7824 else
7825 outs() << "\n";
7826 outs() << " cryptoff " << ec.cryptoff;
7827 if (ec.cryptoff > object_size)
7828 outs() << " (past end of file)\n";
7829 else
7830 outs() << "\n";
7831 outs() << " cryptsize " << ec.cryptsize;
7832 if (ec.cryptsize > object_size)
7833 outs() << " (past end of file)\n";
7834 else
7835 outs() << "\n";
7836 outs() << " cryptid " << ec.cryptid << "\n";
7837 outs() << " pad " << ec.pad << "\n";
7838}
7839
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00007840static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
7841 const char *Ptr) {
7842 outs() << " cmd LC_LINKER_OPTION\n";
7843 outs() << " cmdsize " << lo.cmdsize;
7844 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
7845 outs() << " Incorrect size\n";
7846 else
7847 outs() << "\n";
7848 outs() << " count " << lo.count << "\n";
7849 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
7850 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
7851 uint32_t i = 0;
7852 while (left > 0) {
7853 while (*string == '\0' && left > 0) {
7854 string++;
7855 left--;
7856 }
7857 if (left > 0) {
7858 i++;
7859 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00007860 uint32_t NullPos = StringRef(string, left).find('\0');
7861 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00007862 string += len;
7863 left -= len;
7864 }
7865 }
7866 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007867 outs() << " count " << lo.count << " does not match number of strings "
7868 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00007869}
7870
Kevin Enderbyb4b79312014-12-18 19:24:35 +00007871static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
7872 const char *Ptr) {
7873 outs() << " cmd LC_SUB_FRAMEWORK\n";
7874 outs() << " cmdsize " << sub.cmdsize;
7875 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
7876 outs() << " Incorrect size\n";
7877 else
7878 outs() << "\n";
7879 if (sub.umbrella < sub.cmdsize) {
7880 const char *P = Ptr + sub.umbrella;
7881 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
7882 } else {
7883 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
7884 }
7885}
7886
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00007887static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
7888 const char *Ptr) {
7889 outs() << " cmd LC_SUB_UMBRELLA\n";
7890 outs() << " cmdsize " << sub.cmdsize;
7891 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
7892 outs() << " Incorrect size\n";
7893 else
7894 outs() << "\n";
7895 if (sub.sub_umbrella < sub.cmdsize) {
7896 const char *P = Ptr + sub.sub_umbrella;
7897 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
7898 } else {
7899 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
7900 }
7901}
7902
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00007903static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007904 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00007905 outs() << " cmd LC_SUB_LIBRARY\n";
7906 outs() << " cmdsize " << sub.cmdsize;
7907 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
7908 outs() << " Incorrect size\n";
7909 else
7910 outs() << "\n";
7911 if (sub.sub_library < sub.cmdsize) {
7912 const char *P = Ptr + sub.sub_library;
7913 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
7914 } else {
7915 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
7916 }
7917}
7918
Kevin Enderby186eac32014-12-19 21:06:24 +00007919static void PrintSubClientCommand(MachO::sub_client_command sub,
7920 const char *Ptr) {
7921 outs() << " cmd LC_SUB_CLIENT\n";
7922 outs() << " cmdsize " << sub.cmdsize;
7923 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
7924 outs() << " Incorrect size\n";
7925 else
7926 outs() << "\n";
7927 if (sub.client < sub.cmdsize) {
7928 const char *P = Ptr + sub.client;
7929 outs() << " client " << P << " (offset " << sub.client << ")\n";
7930 } else {
7931 outs() << " client ?(bad offset " << sub.client << ")\n";
7932 }
7933}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00007934
Kevin Enderby52e4ce42014-12-19 22:25:22 +00007935static void PrintRoutinesCommand(MachO::routines_command r) {
7936 outs() << " cmd LC_ROUTINES\n";
7937 outs() << " cmdsize " << r.cmdsize;
7938 if (r.cmdsize != sizeof(struct MachO::routines_command))
7939 outs() << " Incorrect size\n";
7940 else
7941 outs() << "\n";
7942 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
7943 outs() << " init_module " << r.init_module << "\n";
7944 outs() << " reserved1 " << r.reserved1 << "\n";
7945 outs() << " reserved2 " << r.reserved2 << "\n";
7946 outs() << " reserved3 " << r.reserved3 << "\n";
7947 outs() << " reserved4 " << r.reserved4 << "\n";
7948 outs() << " reserved5 " << r.reserved5 << "\n";
7949 outs() << " reserved6 " << r.reserved6 << "\n";
7950}
7951
7952static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
7953 outs() << " cmd LC_ROUTINES_64\n";
7954 outs() << " cmdsize " << r.cmdsize;
7955 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
7956 outs() << " Incorrect size\n";
7957 else
7958 outs() << "\n";
7959 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
7960 outs() << " init_module " << r.init_module << "\n";
7961 outs() << " reserved1 " << r.reserved1 << "\n";
7962 outs() << " reserved2 " << r.reserved2 << "\n";
7963 outs() << " reserved3 " << r.reserved3 << "\n";
7964 outs() << " reserved4 " << r.reserved4 << "\n";
7965 outs() << " reserved5 " << r.reserved5 << "\n";
7966 outs() << " reserved6 " << r.reserved6 << "\n";
7967}
7968
Kevin Enderby48ef5342014-12-23 22:56:39 +00007969static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
7970 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
7971 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
7972 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
7973 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
7974 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
7975 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
7976 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
7977 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
7978 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
7979 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
7980 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
7981 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
7982 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
7983 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
7984 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
7985 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
7986 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
7987 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
7988 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
7989 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
7990 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
7991}
7992
Kevin Enderby227df342014-12-23 23:43:59 +00007993static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00007994 uint32_t f;
7995 outs() << "\t mmst_reg ";
7996 for (f = 0; f < 10; f++)
7997 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
7998 outs() << "\n";
7999 outs() << "\t mmst_rsrv ";
8000 for (f = 0; f < 6; f++)
8001 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
8002 outs() << "\n";
8003}
8004
Kevin Enderbyaefb0032014-12-24 00:16:51 +00008005static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008006 uint32_t f;
8007 outs() << "\t xmm_reg ";
8008 for (f = 0; f < 16; f++)
8009 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
8010 outs() << "\n";
8011}
8012
8013static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
8014 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
8015 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
8016 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
8017 outs() << " denorm " << fpu.fpu_fcw.denorm;
8018 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
8019 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
8020 outs() << " undfl " << fpu.fpu_fcw.undfl;
8021 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
8022 outs() << "\t\t pc ";
8023 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
8024 outs() << "FP_PREC_24B ";
8025 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
8026 outs() << "FP_PREC_53B ";
8027 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
8028 outs() << "FP_PREC_64B ";
8029 else
8030 outs() << fpu.fpu_fcw.pc << " ";
8031 outs() << "rc ";
8032 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
8033 outs() << "FP_RND_NEAR ";
8034 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
8035 outs() << "FP_RND_DOWN ";
8036 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
8037 outs() << "FP_RND_UP ";
8038 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008039 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008040 outs() << "\n";
8041 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
8042 outs() << " denorm " << fpu.fpu_fsw.denorm;
8043 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
8044 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
8045 outs() << " undfl " << fpu.fpu_fsw.undfl;
8046 outs() << " precis " << fpu.fpu_fsw.precis;
8047 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
8048 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
8049 outs() << " c0 " << fpu.fpu_fsw.c0;
8050 outs() << " c1 " << fpu.fpu_fsw.c1;
8051 outs() << " c2 " << fpu.fpu_fsw.c2;
8052 outs() << " tos " << fpu.fpu_fsw.tos;
8053 outs() << " c3 " << fpu.fpu_fsw.c3;
8054 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
8055 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
8056 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
8057 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
8058 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
8059 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
8060 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
8061 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
8062 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
8063 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
8064 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
8065 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
8066 outs() << "\n";
8067 outs() << "\t fpu_stmm0:\n";
8068 Print_mmst_reg(fpu.fpu_stmm0);
8069 outs() << "\t fpu_stmm1:\n";
8070 Print_mmst_reg(fpu.fpu_stmm1);
8071 outs() << "\t fpu_stmm2:\n";
8072 Print_mmst_reg(fpu.fpu_stmm2);
8073 outs() << "\t fpu_stmm3:\n";
8074 Print_mmst_reg(fpu.fpu_stmm3);
8075 outs() << "\t fpu_stmm4:\n";
8076 Print_mmst_reg(fpu.fpu_stmm4);
8077 outs() << "\t fpu_stmm5:\n";
8078 Print_mmst_reg(fpu.fpu_stmm5);
8079 outs() << "\t fpu_stmm6:\n";
8080 Print_mmst_reg(fpu.fpu_stmm6);
8081 outs() << "\t fpu_stmm7:\n";
8082 Print_mmst_reg(fpu.fpu_stmm7);
8083 outs() << "\t fpu_xmm0:\n";
8084 Print_xmm_reg(fpu.fpu_xmm0);
8085 outs() << "\t fpu_xmm1:\n";
8086 Print_xmm_reg(fpu.fpu_xmm1);
8087 outs() << "\t fpu_xmm2:\n";
8088 Print_xmm_reg(fpu.fpu_xmm2);
8089 outs() << "\t fpu_xmm3:\n";
8090 Print_xmm_reg(fpu.fpu_xmm3);
8091 outs() << "\t fpu_xmm4:\n";
8092 Print_xmm_reg(fpu.fpu_xmm4);
8093 outs() << "\t fpu_xmm5:\n";
8094 Print_xmm_reg(fpu.fpu_xmm5);
8095 outs() << "\t fpu_xmm6:\n";
8096 Print_xmm_reg(fpu.fpu_xmm6);
8097 outs() << "\t fpu_xmm7:\n";
8098 Print_xmm_reg(fpu.fpu_xmm7);
8099 outs() << "\t fpu_xmm8:\n";
8100 Print_xmm_reg(fpu.fpu_xmm8);
8101 outs() << "\t fpu_xmm9:\n";
8102 Print_xmm_reg(fpu.fpu_xmm9);
8103 outs() << "\t fpu_xmm10:\n";
8104 Print_xmm_reg(fpu.fpu_xmm10);
8105 outs() << "\t fpu_xmm11:\n";
8106 Print_xmm_reg(fpu.fpu_xmm11);
8107 outs() << "\t fpu_xmm12:\n";
8108 Print_xmm_reg(fpu.fpu_xmm12);
8109 outs() << "\t fpu_xmm13:\n";
8110 Print_xmm_reg(fpu.fpu_xmm13);
8111 outs() << "\t fpu_xmm14:\n";
8112 Print_xmm_reg(fpu.fpu_xmm14);
8113 outs() << "\t fpu_xmm15:\n";
8114 Print_xmm_reg(fpu.fpu_xmm15);
8115 outs() << "\t fpu_rsrv4:\n";
8116 for (uint32_t f = 0; f < 6; f++) {
8117 outs() << "\t ";
8118 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008119 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008120 outs() << "\n";
8121 }
8122 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
8123 outs() << "\n";
8124}
8125
8126static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
8127 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
8128 outs() << " err " << format("0x%08" PRIx32, exc64.err);
8129 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
8130}
8131
8132static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
8133 bool isLittleEndian, uint32_t cputype) {
8134 if (t.cmd == MachO::LC_THREAD)
8135 outs() << " cmd LC_THREAD\n";
8136 else if (t.cmd == MachO::LC_UNIXTHREAD)
8137 outs() << " cmd LC_UNIXTHREAD\n";
8138 else
8139 outs() << " cmd " << t.cmd << " (unknown)\n";
8140 outs() << " cmdsize " << t.cmdsize;
8141 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
8142 outs() << " Incorrect size\n";
8143 else
8144 outs() << "\n";
8145
8146 const char *begin = Ptr + sizeof(struct MachO::thread_command);
8147 const char *end = Ptr + t.cmdsize;
8148 uint32_t flavor, count, left;
8149 if (cputype == MachO::CPU_TYPE_X86_64) {
8150 while (begin < end) {
8151 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8152 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8153 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008154 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008155 flavor = 0;
8156 begin = end;
8157 }
8158 if (isLittleEndian != sys::IsLittleEndianHost)
8159 sys::swapByteOrder(flavor);
8160 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8161 memcpy((char *)&count, begin, sizeof(uint32_t));
8162 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008163 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008164 count = 0;
8165 begin = end;
8166 }
8167 if (isLittleEndian != sys::IsLittleEndianHost)
8168 sys::swapByteOrder(count);
8169 if (flavor == MachO::x86_THREAD_STATE64) {
8170 outs() << " flavor x86_THREAD_STATE64\n";
8171 if (count == MachO::x86_THREAD_STATE64_COUNT)
8172 outs() << " count x86_THREAD_STATE64_COUNT\n";
8173 else
8174 outs() << " count " << count
8175 << " (not x86_THREAD_STATE64_COUNT)\n";
8176 MachO::x86_thread_state64_t cpu64;
8177 left = end - begin;
8178 if (left >= sizeof(MachO::x86_thread_state64_t)) {
8179 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
8180 begin += sizeof(MachO::x86_thread_state64_t);
8181 } else {
8182 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
8183 memcpy(&cpu64, begin, left);
8184 begin += left;
8185 }
8186 if (isLittleEndian != sys::IsLittleEndianHost)
8187 swapStruct(cpu64);
8188 Print_x86_thread_state64_t(cpu64);
8189 } else if (flavor == MachO::x86_THREAD_STATE) {
8190 outs() << " flavor x86_THREAD_STATE\n";
8191 if (count == MachO::x86_THREAD_STATE_COUNT)
8192 outs() << " count x86_THREAD_STATE_COUNT\n";
8193 else
8194 outs() << " count " << count
8195 << " (not x86_THREAD_STATE_COUNT)\n";
8196 struct MachO::x86_thread_state_t ts;
8197 left = end - begin;
8198 if (left >= sizeof(MachO::x86_thread_state_t)) {
8199 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
8200 begin += sizeof(MachO::x86_thread_state_t);
8201 } else {
8202 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
8203 memcpy(&ts, begin, left);
8204 begin += left;
8205 }
8206 if (isLittleEndian != sys::IsLittleEndianHost)
8207 swapStruct(ts);
8208 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
8209 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
8210 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
8211 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
8212 else
8213 outs() << "tsh.count " << ts.tsh.count
8214 << " (not x86_THREAD_STATE64_COUNT\n";
8215 Print_x86_thread_state64_t(ts.uts.ts64);
8216 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008217 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
8218 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008219 }
8220 } else if (flavor == MachO::x86_FLOAT_STATE) {
8221 outs() << " flavor x86_FLOAT_STATE\n";
8222 if (count == MachO::x86_FLOAT_STATE_COUNT)
8223 outs() << " count x86_FLOAT_STATE_COUNT\n";
8224 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008225 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008226 struct MachO::x86_float_state_t fs;
8227 left = end - begin;
8228 if (left >= sizeof(MachO::x86_float_state_t)) {
8229 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
8230 begin += sizeof(MachO::x86_float_state_t);
8231 } else {
8232 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
8233 memcpy(&fs, begin, left);
8234 begin += left;
8235 }
8236 if (isLittleEndian != sys::IsLittleEndianHost)
8237 swapStruct(fs);
8238 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
8239 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008240 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008241 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
8242 else
8243 outs() << "fsh.count " << fs.fsh.count
8244 << " (not x86_FLOAT_STATE64_COUNT\n";
8245 Print_x86_float_state_t(fs.ufs.fs64);
8246 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008247 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
8248 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008249 }
8250 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
8251 outs() << " flavor x86_EXCEPTION_STATE\n";
8252 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
8253 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
8254 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008255 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00008256 << " (not x86_EXCEPTION_STATE_COUNT)\n";
8257 struct MachO::x86_exception_state_t es;
8258 left = end - begin;
8259 if (left >= sizeof(MachO::x86_exception_state_t)) {
8260 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
8261 begin += sizeof(MachO::x86_exception_state_t);
8262 } else {
8263 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
8264 memcpy(&es, begin, left);
8265 begin += left;
8266 }
8267 if (isLittleEndian != sys::IsLittleEndianHost)
8268 swapStruct(es);
8269 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
8270 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008271 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008272 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
8273 else
8274 outs() << "\t esh.count " << es.esh.count
8275 << " (not x86_EXCEPTION_STATE64_COUNT\n";
8276 Print_x86_exception_state_t(es.ues.es64);
8277 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008278 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
8279 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008280 }
8281 } else {
8282 outs() << " flavor " << flavor << " (unknown)\n";
8283 outs() << " count " << count << "\n";
8284 outs() << " state (unknown)\n";
8285 begin += count * sizeof(uint32_t);
8286 }
8287 }
8288 } else {
8289 while (begin < end) {
8290 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8291 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8292 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008293 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008294 flavor = 0;
8295 begin = end;
8296 }
8297 if (isLittleEndian != sys::IsLittleEndianHost)
8298 sys::swapByteOrder(flavor);
8299 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8300 memcpy((char *)&count, begin, sizeof(uint32_t));
8301 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008302 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008303 count = 0;
8304 begin = end;
8305 }
8306 if (isLittleEndian != sys::IsLittleEndianHost)
8307 sys::swapByteOrder(count);
8308 outs() << " flavor " << flavor << "\n";
8309 outs() << " count " << count << "\n";
8310 outs() << " state (Unknown cputype/cpusubtype)\n";
8311 begin += count * sizeof(uint32_t);
8312 }
8313 }
8314}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008315
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008316static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
8317 if (dl.cmd == MachO::LC_ID_DYLIB)
8318 outs() << " cmd LC_ID_DYLIB\n";
8319 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
8320 outs() << " cmd LC_LOAD_DYLIB\n";
8321 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
8322 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
8323 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
8324 outs() << " cmd LC_REEXPORT_DYLIB\n";
8325 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
8326 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
8327 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
8328 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
8329 else
8330 outs() << " cmd " << dl.cmd << " (unknown)\n";
8331 outs() << " cmdsize " << dl.cmdsize;
8332 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
8333 outs() << " Incorrect size\n";
8334 else
8335 outs() << "\n";
8336 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008337 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008338 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
8339 } else {
8340 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
8341 }
8342 outs() << " time stamp " << dl.dylib.timestamp << " ";
8343 time_t t = dl.dylib.timestamp;
8344 outs() << ctime(&t);
8345 outs() << " current version ";
8346 if (dl.dylib.current_version == 0xffffffff)
8347 outs() << "n/a\n";
8348 else
8349 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
8350 << ((dl.dylib.current_version >> 8) & 0xff) << "."
8351 << (dl.dylib.current_version & 0xff) << "\n";
8352 outs() << "compatibility version ";
8353 if (dl.dylib.compatibility_version == 0xffffffff)
8354 outs() << "n/a\n";
8355 else
8356 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
8357 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
8358 << (dl.dylib.compatibility_version & 0xff) << "\n";
8359}
8360
8361static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
8362 uint32_t object_size) {
8363 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
8364 outs() << " cmd LC_FUNCTION_STARTS\n";
8365 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
8366 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
8367 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
8368 outs() << " cmd LC_FUNCTION_STARTS\n";
8369 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
8370 outs() << " cmd LC_DATA_IN_CODE\n";
8371 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
8372 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
8373 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
8374 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
8375 else
8376 outs() << " cmd " << ld.cmd << " (?)\n";
8377 outs() << " cmdsize " << ld.cmdsize;
8378 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
8379 outs() << " Incorrect size\n";
8380 else
8381 outs() << "\n";
8382 outs() << " dataoff " << ld.dataoff;
8383 if (ld.dataoff > object_size)
8384 outs() << " (past end of file)\n";
8385 else
8386 outs() << "\n";
8387 outs() << " datasize " << ld.datasize;
8388 uint64_t big_size = ld.dataoff;
8389 big_size += ld.datasize;
8390 if (big_size > object_size)
8391 outs() << " (past end of file)\n";
8392 else
8393 outs() << "\n";
8394}
8395
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008396static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
8397 uint32_t cputype, bool verbose) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008398 StringRef Buf = Obj->getData();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008399 unsigned Index = 0;
8400 for (const auto &Command : Obj->load_commands()) {
8401 outs() << "Load command " << Index++ << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008402 if (Command.C.cmd == MachO::LC_SEGMENT) {
8403 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
8404 const char *sg_segname = SLC.segname;
8405 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
8406 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
8407 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
8408 verbose);
8409 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00008410 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00008411 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
8412 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
8413 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
8414 }
8415 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
8416 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
8417 const char *sg_segname = SLC_64.segname;
8418 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
8419 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
8420 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
8421 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
8422 for (unsigned j = 0; j < SLC_64.nsects; j++) {
8423 MachO::section_64 S_64 = Obj->getSection64(Command, j);
8424 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
8425 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
8426 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
8427 sg_segname, filetype, Buf.size(), verbose);
8428 }
8429 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
8430 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00008431 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00008432 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
8433 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
8434 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00008435 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
8436 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008437 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
8438 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
8439 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
8440 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
8441 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
8442 Command.C.cmd == MachO::LC_ID_DYLINKER ||
8443 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
8444 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
8445 PrintDyldLoadCommand(Dyld, Command.Ptr);
8446 } else if (Command.C.cmd == MachO::LC_UUID) {
8447 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
8448 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008449 } else if (Command.C.cmd == MachO::LC_RPATH) {
8450 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
8451 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00008452 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
Tim Northoverbfbfb122015-11-02 21:26:58 +00008453 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
8454 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
8455 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008456 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
8457 PrintVersionMinLoadCommand(Vd);
8458 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
8459 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
8460 PrintSourceVersionCommand(Sd);
8461 } else if (Command.C.cmd == MachO::LC_MAIN) {
8462 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
8463 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00008464 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008465 MachO::encryption_info_command Ei =
8466 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00008467 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00008468 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008469 MachO::encryption_info_command_64 Ei =
8470 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00008471 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008472 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008473 MachO::linker_option_command Lo =
8474 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008475 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00008476 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
8477 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
8478 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00008479 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
8480 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
8481 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008482 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
8483 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
8484 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00008485 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
8486 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
8487 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00008488 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
8489 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
8490 PrintRoutinesCommand(Rc);
8491 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
8492 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
8493 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00008494 } else if (Command.C.cmd == MachO::LC_THREAD ||
8495 Command.C.cmd == MachO::LC_UNIXTHREAD) {
8496 MachO::thread_command Tc = Obj->getThreadCommand(Command);
8497 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00008498 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
8499 Command.C.cmd == MachO::LC_ID_DYLIB ||
8500 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
8501 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
8502 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
8503 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008504 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
8505 PrintDylibCommand(Dl, Command.Ptr);
8506 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
8507 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
8508 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
8509 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
8510 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
8511 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
8512 MachO::linkedit_data_command Ld =
8513 Obj->getLinkeditDataLoadCommand(Command);
8514 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00008515 } else {
8516 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
8517 << ")\n";
8518 outs() << " cmdsize " << Command.C.cmdsize << "\n";
8519 // TODO: get and print the raw bytes of the load command.
8520 }
8521 // TODO: print all the other kinds of load commands.
Kevin Enderby956366c2014-08-29 22:30:52 +00008522 }
8523}
8524
Kevin Enderby0ae163f2016-01-13 00:25:36 +00008525static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008526 if (Obj->is64Bit()) {
8527 MachO::mach_header_64 H_64;
8528 H_64 = Obj->getHeader64();
8529 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
8530 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
8531 } else {
8532 MachO::mach_header H;
8533 H = Obj->getHeader();
8534 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
8535 H.sizeofcmds, H.flags, verbose);
8536 }
8537}
8538
8539void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
8540 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00008541 PrintMachHeader(file, !NonVerbose);
8542}
8543
8544void llvm::printMachOLoadCommands(const object::ObjectFile *Obj) {
8545 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00008546 uint32_t filetype = 0;
8547 uint32_t cputype = 0;
Kevin Enderby0ae163f2016-01-13 00:25:36 +00008548 if (file->is64Bit()) {
8549 MachO::mach_header_64 H_64;
8550 H_64 = file->getHeader64();
8551 filetype = H_64.filetype;
8552 cputype = H_64.cputype;
8553 } else {
8554 MachO::mach_header H;
8555 H = file->getHeader();
8556 filetype = H.filetype;
8557 cputype = H.cputype;
8558 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008559 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008560}
Nick Kledzikd04bc352014-08-30 00:20:14 +00008561
8562//===----------------------------------------------------------------------===//
8563// export trie dumping
8564//===----------------------------------------------------------------------===//
8565
8566void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008567 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
8568 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +00008569 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
8570 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
8571 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8572 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
8573 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8574 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
8575 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
8576 if (ReExport)
8577 outs() << "[re-export] ";
8578 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008579 outs() << format("0x%08llX ",
8580 Entry.address()); // FIXME:add in base address
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008581 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +00008582 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008583 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +00008584 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +00008585 if (WeakDef) {
8586 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008587 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008588 }
8589 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008590 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00008591 outs() << ", ";
8592 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008593 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008594 }
8595 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008596 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00008597 outs() << ", ";
8598 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008599 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008600 }
8601 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008602 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00008603 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008604 outs() << format("resolver=0x%08llX", Entry.other());
8605 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008606 }
8607 outs() << "]";
8608 }
8609 if (ReExport) {
8610 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008611 int Ordinal = Entry.other() - 1;
8612 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
8613 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +00008614 outs() << " (from " << DylibName << ")";
8615 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008616 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +00008617 }
8618 outs() << "\n";
8619 }
8620}
Nick Kledzikac431442014-09-12 21:34:15 +00008621
Nick Kledzikac431442014-09-12 21:34:15 +00008622//===----------------------------------------------------------------------===//
8623// rebase table dumping
8624//===----------------------------------------------------------------------===//
8625
8626namespace {
8627class SegInfo {
8628public:
8629 SegInfo(const object::MachOObjectFile *Obj);
8630
8631 StringRef segmentName(uint32_t SegIndex);
8632 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
8633 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00008634 bool isValidSegIndexAndOffset(uint32_t SegIndex, uint64_t SegOffset);
Nick Kledzikac431442014-09-12 21:34:15 +00008635
8636private:
8637 struct SectionInfo {
8638 uint64_t Address;
8639 uint64_t Size;
8640 StringRef SectionName;
8641 StringRef SegmentName;
8642 uint64_t OffsetInSegment;
8643 uint64_t SegmentStartAddress;
8644 uint32_t SegmentIndex;
8645 };
8646 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
8647 SmallVector<SectionInfo, 32> Sections;
8648};
8649}
8650
8651SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
8652 // Build table of sections so segIndex/offset pairs can be translated.
Nick Kledzik56ebef42014-09-16 01:41:51 +00008653 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
Nick Kledzikac431442014-09-12 21:34:15 +00008654 StringRef CurSegName;
8655 uint64_t CurSegAddress;
8656 for (const SectionRef &Section : Obj->sections()) {
8657 SectionInfo Info;
Davide Italianoccd53fe2015-08-05 07:18:31 +00008658 error(Section.getName(Info.SectionName));
Rafael Espindola80291272014-10-08 15:28:58 +00008659 Info.Address = Section.getAddress();
8660 Info.Size = Section.getSize();
Nick Kledzikac431442014-09-12 21:34:15 +00008661 Info.SegmentName =
8662 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
8663 if (!Info.SegmentName.equals(CurSegName)) {
8664 ++CurSegIndex;
8665 CurSegName = Info.SegmentName;
8666 CurSegAddress = Info.Address;
8667 }
8668 Info.SegmentIndex = CurSegIndex - 1;
8669 Info.OffsetInSegment = Info.Address - CurSegAddress;
8670 Info.SegmentStartAddress = CurSegAddress;
8671 Sections.push_back(Info);
8672 }
8673}
8674
8675StringRef SegInfo::segmentName(uint32_t SegIndex) {
8676 for (const SectionInfo &SI : Sections) {
8677 if (SI.SegmentIndex == SegIndex)
8678 return SI.SegmentName;
8679 }
8680 llvm_unreachable("invalid segIndex");
8681}
8682
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00008683bool SegInfo::isValidSegIndexAndOffset(uint32_t SegIndex,
8684 uint64_t OffsetInSeg) {
8685 for (const SectionInfo &SI : Sections) {
8686 if (SI.SegmentIndex != SegIndex)
8687 continue;
8688 if (SI.OffsetInSegment > OffsetInSeg)
8689 continue;
8690 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
8691 continue;
8692 return true;
8693 }
8694 return false;
8695}
8696
Nick Kledzikac431442014-09-12 21:34:15 +00008697const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
8698 uint64_t OffsetInSeg) {
8699 for (const SectionInfo &SI : Sections) {
8700 if (SI.SegmentIndex != SegIndex)
8701 continue;
8702 if (SI.OffsetInSegment > OffsetInSeg)
8703 continue;
8704 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
8705 continue;
8706 return SI;
8707 }
8708 llvm_unreachable("segIndex and offset not in any section");
8709}
8710
8711StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
8712 return findSection(SegIndex, OffsetInSeg).SectionName;
8713}
8714
8715uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
8716 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
8717 return SI.SegmentStartAddress + OffsetInSeg;
8718}
8719
8720void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
8721 // Build table of sections so names can used in final output.
8722 SegInfo sectionTable(Obj);
8723
8724 outs() << "segment section address type\n";
8725 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
8726 uint32_t SegIndex = Entry.segmentIndex();
8727 uint64_t OffsetInSeg = Entry.segmentOffset();
8728 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8729 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8730 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8731
8732 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008733 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
8734 SegmentName.str().c_str(), SectionName.str().c_str(),
8735 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +00008736 }
8737}
Nick Kledzik56ebef42014-09-16 01:41:51 +00008738
8739static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
8740 StringRef DylibName;
8741 switch (Ordinal) {
8742 case MachO::BIND_SPECIAL_DYLIB_SELF:
8743 return "this-image";
8744 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
8745 return "main-executable";
8746 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
8747 return "flat-namespace";
8748 default:
Nick Kledzikabd29872014-09-16 22:03:13 +00008749 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008750 std::error_code EC =
8751 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +00008752 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +00008753 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +00008754 return DylibName;
8755 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00008756 }
Nick Kledzikabd29872014-09-16 22:03:13 +00008757 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008758}
8759
8760//===----------------------------------------------------------------------===//
8761// bind table dumping
8762//===----------------------------------------------------------------------===//
8763
8764void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
8765 // Build table of sections so names can used in final output.
8766 SegInfo sectionTable(Obj);
8767
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008768 outs() << "segment section address type "
8769 "addend dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008770 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
8771 uint32_t SegIndex = Entry.segmentIndex();
8772 uint64_t OffsetInSeg = Entry.segmentOffset();
8773 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8774 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8775 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8776
8777 // Table lines look like:
8778 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008779 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00008780 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008781 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008782 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008783 << left_justify(SectionName, 18) << " "
8784 << format_hex(Address, 10, true) << " "
8785 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008786 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008787 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008788 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008789 }
8790}
8791
8792//===----------------------------------------------------------------------===//
8793// lazy bind table dumping
8794//===----------------------------------------------------------------------===//
8795
8796void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
8797 // Build table of sections so names can used in final output.
8798 SegInfo sectionTable(Obj);
8799
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008800 outs() << "segment section address "
8801 "dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008802 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
8803 uint32_t SegIndex = Entry.segmentIndex();
8804 uint64_t OffsetInSeg = Entry.segmentOffset();
8805 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8806 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8807 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8808
8809 // Table lines look like:
8810 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008811 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008812 << left_justify(SectionName, 18) << " "
8813 << format_hex(Address, 10, true) << " "
8814 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00008815 << Entry.symbolName() << "\n";
8816 }
8817}
8818
Nick Kledzik56ebef42014-09-16 01:41:51 +00008819//===----------------------------------------------------------------------===//
8820// weak bind table dumping
8821//===----------------------------------------------------------------------===//
8822
8823void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
8824 // Build table of sections so names can used in final output.
8825 SegInfo sectionTable(Obj);
8826
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008827 outs() << "segment section address "
8828 "type addend symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008829 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
8830 // Strong symbols don't have a location to update.
8831 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008832 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +00008833 << Entry.symbolName() << "\n";
8834 continue;
8835 }
8836 uint32_t SegIndex = Entry.segmentIndex();
8837 uint64_t OffsetInSeg = Entry.segmentOffset();
8838 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8839 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8840 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8841
8842 // Table lines look like:
8843 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008844 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008845 << left_justify(SectionName, 18) << " "
8846 << format_hex(Address, 10, true) << " "
8847 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008848 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
8849 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008850 }
8851}
8852
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008853// get_dyld_bind_info_symbolname() is used for disassembly and passed an
8854// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
8855// information for that address. If the address is found its binding symbol
8856// name is returned. If not nullptr is returned.
8857static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
8858 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +00008859 if (info->bindtable == nullptr) {
8860 info->bindtable = new (BindTable);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008861 SegInfo sectionTable(info->O);
8862 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
8863 uint32_t SegIndex = Entry.segmentIndex();
8864 uint64_t OffsetInSeg = Entry.segmentOffset();
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00008865 if (!sectionTable.isValidSegIndexAndOffset(SegIndex, OffsetInSeg))
8866 continue;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008867 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8868 const char *SymbolName = nullptr;
8869 StringRef name = Entry.symbolName();
8870 if (!name.empty())
8871 SymbolName = name.data();
Kevin Enderby078be602014-10-23 19:53:12 +00008872 info->bindtable->push_back(std::make_pair(Address, SymbolName));
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008873 }
8874 }
Kevin Enderby078be602014-10-23 19:53:12 +00008875 for (bind_table_iterator BI = info->bindtable->begin(),
8876 BE = info->bindtable->end();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008877 BI != BE; ++BI) {
8878 uint64_t Address = BI->first;
8879 if (ReferenceValue == Address) {
8880 const char *SymbolName = BI->second;
8881 return SymbolName;
8882 }
8883 }
8884 return nullptr;
8885}