blob: 10cd407e377abc81e86dd7115d52e0053267f556 [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"
Kevin Enderby9873e2c2016-05-23 21:34:12 +000045#include "llvm/Support/ToolOutputFile.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000046#include "llvm/Support/raw_ostream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000047#include <algorithm>
48#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000049#include <system_error>
Kevin Enderby04bf6932014-10-28 23:39:46 +000050
51#if HAVE_CXXABI_H
52#include <cxxabi.h>
53#endif
54
Kevin Enderby9873e2c2016-05-23 21:34:12 +000055#ifdef HAVE_LIBXAR
56extern "C" {
57#include <xar/xar.h>
58}
59#endif
60
Benjamin Kramer43a772e2011-09-19 17:56:04 +000061using namespace llvm;
62using namespace object;
63
64static cl::opt<bool>
Kevin Enderbyb28ed012014-10-29 21:28:24 +000065 UseDbg("g",
66 cl::desc("Print line information from debug info if available"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000067
Kevin Enderbyb28ed012014-10-29 21:28:24 +000068static cl::opt<std::string> DSYMFile("dsym",
69 cl::desc("Use .dSYM file for debug info"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000070
Kevin Enderbyb28ed012014-10-29 21:28:24 +000071static cl::opt<bool> FullLeadingAddr("full-leading-addr",
72 cl::desc("Print full leading address"));
Kevin Enderbybf246f52014-09-24 23:08:22 +000073
Kevin Enderbyab5e6c92015-03-17 21:07:39 +000074static cl::opt<bool> NoLeadingAddr("no-leading-addr",
75 cl::desc("Print no leading address"));
76
Kevin Enderby13023a12015-01-15 23:19:11 +000077cl::opt<bool> llvm::UniversalHeaders("universal-headers",
78 cl::desc("Print Mach-O universal headers "
79 "(requires -macho)"));
80
Kevin Enderby131d1772015-01-09 19:22:37 +000081cl::opt<bool>
Kevin Enderby13023a12015-01-15 23:19:11 +000082 llvm::ArchiveHeaders("archive-headers",
83 cl::desc("Print archive headers for Mach-O archives "
84 "(requires -macho)"));
Kevin Enderby131d1772015-01-09 19:22:37 +000085
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +000086cl::opt<bool>
Kevin Enderby8972e482015-04-30 20:30:42 +000087 ArchiveMemberOffsets("archive-member-offsets",
88 cl::desc("Print the offset to each archive member for "
89 "Mach-O archives (requires -macho and "
90 "-archive-headers)"));
91
92cl::opt<bool>
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +000093 llvm::IndirectSymbols("indirect-symbols",
94 cl::desc("Print indirect symbol table for Mach-O "
95 "objects (requires -macho)"));
96
Kevin Enderby69fe98d2015-01-23 18:52:17 +000097cl::opt<bool>
98 llvm::DataInCode("data-in-code",
99 cl::desc("Print the data in code table for Mach-O objects "
100 "(requires -macho)"));
101
Kevin Enderby9a509442015-01-27 21:28:24 +0000102cl::opt<bool>
103 llvm::LinkOptHints("link-opt-hints",
104 cl::desc("Print the linker optimization hints for "
105 "Mach-O objects (requires -macho)"));
106
Kevin Enderbycd66be52015-03-11 22:06:32 +0000107cl::opt<bool>
108 llvm::InfoPlist("info-plist",
109 cl::desc("Print the info plist section as strings for "
110 "Mach-O objects (requires -macho)"));
111
Kevin Enderbyf0640752015-03-13 17:56:32 +0000112cl::opt<bool>
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000113 llvm::DylibsUsed("dylibs-used",
114 cl::desc("Print the shared libraries used for linked "
115 "Mach-O files (requires -macho)"));
116
117cl::opt<bool>
118 llvm::DylibId("dylib-id",
119 cl::desc("Print the shared library's id for the dylib Mach-O "
120 "file (requires -macho)"));
121
122cl::opt<bool>
Kevin Enderbyf0640752015-03-13 17:56:32 +0000123 llvm::NonVerbose("non-verbose",
124 cl::desc("Print the info for Mach-O objects in "
125 "non-verbose or numeric form (requires -macho)"));
126
Kevin Enderby0fc11822015-04-01 20:57:01 +0000127cl::opt<bool>
128 llvm::ObjcMetaData("objc-meta-data",
129 cl::desc("Print the Objective-C runtime meta data for "
130 "Mach-O files (requires -macho)"));
131
Kevin Enderby6a221752015-03-17 17:10:57 +0000132cl::opt<std::string> llvm::DisSymName(
133 "dis-symname",
134 cl::desc("disassemble just this symbol's instructions (requires -macho"));
135
Kevin Enderby8e29ec92015-03-17 22:26:11 +0000136static cl::opt<bool> NoSymbolicOperands(
137 "no-symbolic-operands",
138 cl::desc("do not symbolic operands when disassembling (requires -macho)"));
139
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000140static cl::list<std::string>
141 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
142 cl::ZeroOrMore);
Hans Wennborgcc9deb42015-09-29 18:02:48 +0000143
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000144bool ArchAll = false;
145
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000146static std::string ThumbTripleName;
147
148static const Target *GetTarget(const MachOObjectFile *MachOObj,
149 const char **McpuDefault,
150 const Target **ThumbTarget) {
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000151 // Figure out the target triple.
Tim Northover9e8eb412016-04-22 23:21:13 +0000152 llvm::Triple TT(TripleName);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000153 if (TripleName.empty()) {
Tim Northover9e8eb412016-04-22 23:21:13 +0000154 TT = MachOObj->getArchTriple(McpuDefault);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000155 TripleName = TT.str();
Tim Northover9e8eb412016-04-22 23:21:13 +0000156 }
157
158 if (TT.getArch() == Triple::arm) {
159 // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
160 // that support ARM are also capable of Thumb mode.
161 llvm::Triple ThumbTriple = TT;
162 std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str();
163 ThumbTriple.setArchName(ThumbName);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000164 ThumbTripleName = ThumbTriple.str();
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000165 }
166
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000167 // Get the target specific parser.
168 std::string Error;
169 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000170 if (TheTarget && ThumbTripleName.empty())
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000171 return TheTarget;
172
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000173 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
174 if (*ThumbTarget)
175 return TheTarget;
176
177 errs() << "llvm-objdump: error: unable to get target for '";
178 if (!TheTarget)
179 errs() << TripleName;
180 else
181 errs() << ThumbTripleName;
182 errs() << "', see --version and --triple.\n";
Craig Toppere6cb63e2014-04-25 04:24:47 +0000183 return nullptr;
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000184}
185
Owen Andersond9243c42011-10-17 21:37:35 +0000186struct SymbolSorter {
187 bool operator()(const SymbolRef &A, const SymbolRef &B) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000188 Expected<SymbolRef::Type> ATypeOrErr = A.getType();
189 if (!ATypeOrErr) {
190 std::string Buf;
191 raw_string_ostream OS(Buf);
192 logAllUnhandledErrors(ATypeOrErr.takeError(), OS, "");
193 OS.flush();
194 report_fatal_error(Buf);
195 }
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000196 SymbolRef::Type AType = *ATypeOrErr;
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000197 Expected<SymbolRef::Type> BTypeOrErr = B.getType();
198 if (!BTypeOrErr) {
199 std::string Buf;
200 raw_string_ostream OS(Buf);
201 logAllUnhandledErrors(BTypeOrErr.takeError(), OS, "");
202 OS.flush();
203 report_fatal_error(Buf);
204 }
Kevin Enderby74f58d42016-03-23 21:45:21 +0000205 SymbolRef::Type BType = *BTypeOrErr;
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000206 uint64_t AAddr = (AType != SymbolRef::ST_Function) ? 0 : A.getValue();
207 uint64_t BAddr = (BType != SymbolRef::ST_Function) ? 0 : B.getValue();
Owen Andersond9243c42011-10-17 21:37:35 +0000208 return AAddr < BAddr;
209 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000210};
211
Kevin Enderby273ae012013-06-06 17:20:50 +0000212// Types for the storted data in code table that is built before disassembly
213// and the predicate function to sort them.
214typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
215typedef std::vector<DiceTableEntry> DiceTable;
216typedef DiceTable::iterator dice_table_iterator;
217
Kevin Enderby930fdc72014-11-06 19:00:13 +0000218// This is used to search for a data in code table entry for the PC being
219// disassembled. The j parameter has the PC in j.first. A single data in code
220// table entry can cover many bytes for each of its Kind's. So if the offset,
221// aka the i.first value, of the data in code table entry plus its Length
222// covers the PC being searched for this will return true. If not it will
223// return false.
David Majnemerea9b8ee2014-11-04 08:41:48 +0000224static bool compareDiceTableEntries(const DiceTableEntry &i,
225 const DiceTableEntry &j) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000226 uint16_t Length;
227 i.second.getLength(Length);
228
229 return j.first >= i.first && j.first < i.first + Length;
Kevin Enderby273ae012013-06-06 17:20:50 +0000230}
231
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000232static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
Kevin Enderby930fdc72014-11-06 19:00:13 +0000233 unsigned short Kind) {
234 uint32_t Value, Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000235
236 switch (Kind) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000237 default:
Charles Davis8bdfafd2013-09-01 04:28:48 +0000238 case MachO::DICE_KIND_DATA:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000239 if (Length >= 4) {
240 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000241 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000242 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000243 outs() << "\t.long " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000244 Size = 4;
245 } else if (Length >= 2) {
246 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000247 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000248 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000249 outs() << "\t.short " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000250 Size = 2;
251 } else {
252 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000253 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000254 Value = bytes[0];
255 outs() << "\t.byte " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000256 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000257 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000258 if (Kind == MachO::DICE_KIND_DATA)
259 outs() << "\t@ KIND_DATA\n";
260 else
261 outs() << "\t@ data in code kind = " << Kind << "\n";
Kevin Enderby273ae012013-06-06 17:20:50 +0000262 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000263 case MachO::DICE_KIND_JUMP_TABLE8:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000264 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000265 dumpBytes(makeArrayRef(bytes, 1), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000266 Value = bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000267 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
268 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000269 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000270 case MachO::DICE_KIND_JUMP_TABLE16:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000271 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000272 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000273 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000274 outs() << "\t.short " << format("%5u", Value & 0xffff)
275 << "\t@ KIND_JUMP_TABLE16\n";
276 Size = 2;
Kevin Enderby273ae012013-06-06 17:20:50 +0000277 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000278 case MachO::DICE_KIND_JUMP_TABLE32:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000279 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
280 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000281 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000282 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000283 outs() << "\t.long " << Value;
284 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
285 outs() << "\t@ KIND_JUMP_TABLE32\n";
286 else
287 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
288 Size = 4;
Kevin Enderby273ae012013-06-06 17:20:50 +0000289 break;
290 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000291 return Size;
Kevin Enderby273ae012013-06-06 17:20:50 +0000292}
293
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000294static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000295 std::vector<SectionRef> &Sections,
296 std::vector<SymbolRef> &Symbols,
297 SmallVectorImpl<uint64_t> &FoundFns,
298 uint64_t &BaseSegmentAddress) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000299 for (const SymbolRef &Symbol : MachOObj->symbols()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000300 Expected<StringRef> SymName = Symbol.getName();
301 if (!SymName) {
302 std::string Buf;
303 raw_string_ostream OS(Buf);
304 logAllUnhandledErrors(SymName.takeError(), OS, "");
305 OS.flush();
306 report_fatal_error(Buf);
307 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000308 if (!SymName->startswith("ltmp"))
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000309 Symbols.push_back(Symbol);
310 }
Owen Andersond9243c42011-10-17 21:37:35 +0000311
Alexey Samsonov48803e52014-03-13 14:37:36 +0000312 for (const SectionRef &Section : MachOObj->sections()) {
Owen Andersond9243c42011-10-17 21:37:35 +0000313 StringRef SectName;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000314 Section.getName(SectName);
315 Sections.push_back(Section);
Owen Andersond9243c42011-10-17 21:37:35 +0000316 }
317
Kevin Enderby273ae012013-06-06 17:20:50 +0000318 bool BaseSegmentAddressSet = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000319 for (const auto &Command : MachOObj->load_commands()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000320 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
Benjamin Kramer699128e2011-09-21 01:13:19 +0000321 // We found a function starts segment, parse the addresses for later
322 // consumption.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000323 MachO::linkedit_data_command LLC =
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000324 MachOObj->getLinkeditDataLoadCommand(Command);
Benjamin Kramer699128e2011-09-21 01:13:19 +0000325
Charles Davis8bdfafd2013-09-01 04:28:48 +0000326 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000327 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
328 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000329 StringRef SegName = SLC.segname;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000330 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
Kevin Enderby273ae012013-06-06 17:20:50 +0000331 BaseSegmentAddressSet = true;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000332 BaseSegmentAddress = SLC.vmaddr;
Kevin Enderby273ae012013-06-06 17:20:50 +0000333 }
334 }
Benjamin Kramer8a529dc2011-09-21 22:16:43 +0000335 }
Benjamin Kramer699128e2011-09-21 01:13:19 +0000336}
337
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000338static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
339 uint32_t n, uint32_t count,
340 uint32_t stride, uint64_t addr) {
341 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
342 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
343 if (n > nindirectsyms)
344 outs() << " (entries start past the end of the indirect symbol "
345 "table) (reserved1 field greater than the table size)";
346 else if (n + count > nindirectsyms)
347 outs() << " (entries extends past the end of the indirect symbol "
348 "table)";
349 outs() << "\n";
350 uint32_t cputype = O->getHeader().cputype;
351 if (cputype & MachO::CPU_ARCH_ABI64)
352 outs() << "address index";
353 else
354 outs() << "address index";
355 if (verbose)
356 outs() << " name\n";
357 else
358 outs() << "\n";
359 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
360 if (cputype & MachO::CPU_ARCH_ABI64)
361 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
362 else
Tim Northover43978372016-04-26 18:29:16 +0000363 outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " ";
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000364 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
365 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
366 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
367 outs() << "LOCAL\n";
368 continue;
369 }
370 if (indirect_symbol ==
371 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
372 outs() << "LOCAL ABSOLUTE\n";
373 continue;
374 }
375 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
376 outs() << "ABSOLUTE\n";
377 continue;
378 }
379 outs() << format("%5u ", indirect_symbol);
Kevin Enderbyf0640752015-03-13 17:56:32 +0000380 if (verbose) {
381 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
382 if (indirect_symbol < Symtab.nsyms) {
383 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
384 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000385 Expected<StringRef> SymName = Symbol.getName();
386 if (!SymName) {
387 std::string Buf;
388 raw_string_ostream OS(Buf);
389 logAllUnhandledErrors(SymName.takeError(), OS, "");
390 OS.flush();
391 report_fatal_error(Buf);
392 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000393 outs() << *SymName;
Kevin Enderbyf0640752015-03-13 17:56:32 +0000394 } else {
395 outs() << "?";
396 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000397 }
398 outs() << "\n";
399 }
400}
401
402static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000403 for (const auto &Load : O->load_commands()) {
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000404 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
405 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
406 for (unsigned J = 0; J < Seg.nsects; ++J) {
407 MachO::section_64 Sec = O->getSection64(Load, J);
408 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
409 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
410 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
411 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
412 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
413 section_type == MachO::S_SYMBOL_STUBS) {
414 uint32_t stride;
415 if (section_type == MachO::S_SYMBOL_STUBS)
416 stride = Sec.reserved2;
417 else
418 stride = 8;
419 if (stride == 0) {
420 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
421 << Sec.sectname << ") "
422 << "(size of stubs in reserved2 field is zero)\n";
423 continue;
424 }
425 uint32_t count = Sec.size / stride;
426 outs() << "Indirect symbols for (" << Sec.segname << ","
427 << Sec.sectname << ") " << count << " entries";
428 uint32_t n = Sec.reserved1;
429 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
430 }
431 }
432 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
433 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
434 for (unsigned J = 0; J < Seg.nsects; ++J) {
435 MachO::section Sec = O->getSection(Load, J);
436 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
437 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
438 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
439 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
440 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
441 section_type == MachO::S_SYMBOL_STUBS) {
442 uint32_t stride;
443 if (section_type == MachO::S_SYMBOL_STUBS)
444 stride = Sec.reserved2;
445 else
446 stride = 4;
447 if (stride == 0) {
448 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
449 << Sec.sectname << ") "
450 << "(size of stubs in reserved2 field is zero)\n";
451 continue;
452 }
453 uint32_t count = Sec.size / stride;
454 outs() << "Indirect symbols for (" << Sec.segname << ","
455 << Sec.sectname << ") " << count << " entries";
456 uint32_t n = Sec.reserved1;
457 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
458 }
459 }
460 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000461 }
462}
463
Kevin Enderby69fe98d2015-01-23 18:52:17 +0000464static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
465 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
466 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
467 outs() << "Data in code table (" << nentries << " entries)\n";
468 outs() << "offset length kind\n";
469 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
470 ++DI) {
471 uint32_t Offset;
472 DI->getOffset(Offset);
473 outs() << format("0x%08" PRIx32, Offset) << " ";
474 uint16_t Length;
475 DI->getLength(Length);
476 outs() << format("%6u", Length) << " ";
477 uint16_t Kind;
478 DI->getKind(Kind);
479 if (verbose) {
480 switch (Kind) {
481 case MachO::DICE_KIND_DATA:
482 outs() << "DATA";
483 break;
484 case MachO::DICE_KIND_JUMP_TABLE8:
485 outs() << "JUMP_TABLE8";
486 break;
487 case MachO::DICE_KIND_JUMP_TABLE16:
488 outs() << "JUMP_TABLE16";
489 break;
490 case MachO::DICE_KIND_JUMP_TABLE32:
491 outs() << "JUMP_TABLE32";
492 break;
493 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
494 outs() << "ABS_JUMP_TABLE32";
495 break;
496 default:
497 outs() << format("0x%04" PRIx32, Kind);
498 break;
499 }
500 } else
501 outs() << format("0x%04" PRIx32, Kind);
502 outs() << "\n";
503 }
504}
505
Kevin Enderby9a509442015-01-27 21:28:24 +0000506static void PrintLinkOptHints(MachOObjectFile *O) {
507 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
508 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
509 uint32_t nloh = LohLC.datasize;
510 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
511 for (uint32_t i = 0; i < nloh;) {
512 unsigned n;
513 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
514 i += n;
515 outs() << " identifier " << identifier << " ";
516 if (i >= nloh)
517 return;
518 switch (identifier) {
519 case 1:
520 outs() << "AdrpAdrp\n";
521 break;
522 case 2:
523 outs() << "AdrpLdr\n";
524 break;
525 case 3:
526 outs() << "AdrpAddLdr\n";
527 break;
528 case 4:
529 outs() << "AdrpLdrGotLdr\n";
530 break;
531 case 5:
532 outs() << "AdrpAddStr\n";
533 break;
534 case 6:
535 outs() << "AdrpLdrGotStr\n";
536 break;
537 case 7:
538 outs() << "AdrpAdd\n";
539 break;
540 case 8:
541 outs() << "AdrpLdrGot\n";
542 break;
543 default:
544 outs() << "Unknown identifier value\n";
545 break;
546 }
547 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
548 i += n;
549 outs() << " narguments " << narguments << "\n";
550 if (i >= nloh)
551 return;
552
553 for (uint32_t j = 0; j < narguments; j++) {
554 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
555 i += n;
556 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
557 if (i >= nloh)
558 return;
559 }
560 }
561}
562
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000563static void PrintDylibs(MachOObjectFile *O, bool JustId) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000564 unsigned Index = 0;
565 for (const auto &Load : O->load_commands()) {
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000566 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
567 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
568 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
569 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
570 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
571 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
572 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
573 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
574 if (dl.dylib.name < dl.cmdsize) {
575 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
576 if (JustId)
577 outs() << p << "\n";
578 else {
579 outs() << "\t" << p;
580 outs() << " (compatibility version "
581 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
582 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
583 << (dl.dylib.compatibility_version & 0xff) << ",";
584 outs() << " current version "
585 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
586 << ((dl.dylib.current_version >> 8) & 0xff) << "."
587 << (dl.dylib.current_version & 0xff) << ")\n";
588 }
589 } else {
590 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
591 if (Load.C.cmd == MachO::LC_ID_DYLIB)
592 outs() << "LC_ID_DYLIB ";
593 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
594 outs() << "LC_LOAD_DYLIB ";
595 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
596 outs() << "LC_LOAD_WEAK_DYLIB ";
597 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
598 outs() << "LC_LAZY_LOAD_DYLIB ";
599 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
600 outs() << "LC_REEXPORT_DYLIB ";
601 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
602 outs() << "LC_LOAD_UPWARD_DYLIB ";
603 else
604 outs() << "LC_??? ";
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000605 outs() << "command " << Index++ << "\n";
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000606 }
607 }
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000608 }
609}
610
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000611typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
612
613static void CreateSymbolAddressMap(MachOObjectFile *O,
614 SymbolAddressMap *AddrMap) {
615 // Create a map of symbol addresses to symbol names.
616 for (const SymbolRef &Symbol : O->symbols()) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000617 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
618 if (!STOrErr) {
619 std::string Buf;
620 raw_string_ostream OS(Buf);
621 logAllUnhandledErrors(STOrErr.takeError(), OS, "");
622 OS.flush();
623 report_fatal_error(Buf);
624 }
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000625 SymbolRef::Type ST = *STOrErr;
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000626 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
627 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +0000628 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000629 Expected<StringRef> SymNameOrErr = Symbol.getName();
630 if (!SymNameOrErr) {
631 std::string Buf;
632 raw_string_ostream OS(Buf);
633 logAllUnhandledErrors(SymNameOrErr.takeError(), OS, "");
634 OS.flush();
635 report_fatal_error(Buf);
636 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000637 StringRef SymName = *SymNameOrErr;
Kevin Enderby846c0002015-04-16 17:19:59 +0000638 if (!SymName.startswith(".objc"))
639 (*AddrMap)[Address] = SymName;
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000640 }
641 }
642}
643
644// GuessSymbolName is passed the address of what might be a symbol and a
645// pointer to the SymbolAddressMap. It returns the name of a symbol
646// with that address or nullptr if no symbol is found with that address.
647static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
648 const char *SymbolName = nullptr;
649 // A DenseMap can't lookup up some values.
650 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
651 StringRef name = AddrMap->lookup(value);
652 if (!name.empty())
653 SymbolName = name.data();
654 }
655 return SymbolName;
656}
657
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000658static void DumpCstringChar(const char c) {
659 char p[2];
660 p[0] = c;
661 p[1] = '\0';
662 outs().write_escaped(p);
663}
664
Kevin Enderby10ba0412015-02-04 21:38:42 +0000665static void DumpCstringSection(MachOObjectFile *O, const char *sect,
666 uint32_t sect_size, uint64_t sect_addr,
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000667 bool print_addresses) {
Kevin Enderby10ba0412015-02-04 21:38:42 +0000668 for (uint32_t i = 0; i < sect_size; i++) {
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000669 if (print_addresses) {
670 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000671 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000672 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000673 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000674 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000675 for (; i < sect_size && sect[i] != '\0'; i++)
676 DumpCstringChar(sect[i]);
Kevin Enderby10ba0412015-02-04 21:38:42 +0000677 if (i < sect_size && sect[i] == '\0')
678 outs() << "\n";
679 }
680}
681
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000682static void DumpLiteral4(uint32_t l, float f) {
683 outs() << format("0x%08" PRIx32, l);
684 if ((l & 0x7f800000) != 0x7f800000)
685 outs() << format(" (%.16e)\n", f);
686 else {
687 if (l == 0x7f800000)
688 outs() << " (+Infinity)\n";
689 else if (l == 0xff800000)
690 outs() << " (-Infinity)\n";
691 else if ((l & 0x00400000) == 0x00400000)
692 outs() << " (non-signaling Not-a-Number)\n";
693 else
694 outs() << " (signaling Not-a-Number)\n";
695 }
696}
697
698static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
699 uint32_t sect_size, uint64_t sect_addr,
700 bool print_addresses) {
701 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
702 if (print_addresses) {
703 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000704 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000705 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000706 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000707 }
708 float f;
709 memcpy(&f, sect + i, sizeof(float));
710 if (O->isLittleEndian() != sys::IsLittleEndianHost)
711 sys::swapByteOrder(f);
712 uint32_t l;
713 memcpy(&l, sect + i, sizeof(uint32_t));
714 if (O->isLittleEndian() != sys::IsLittleEndianHost)
715 sys::swapByteOrder(l);
716 DumpLiteral4(l, f);
717 }
718}
719
720static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
721 double d) {
722 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
723 uint32_t Hi, Lo;
Davide Italianob627d9f2015-12-12 21:50:11 +0000724 Hi = (O->isLittleEndian()) ? l1 : l0;
725 Lo = (O->isLittleEndian()) ? l0 : l1;
726
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000727 // Hi is the high word, so this is equivalent to if(isfinite(d))
728 if ((Hi & 0x7ff00000) != 0x7ff00000)
729 outs() << format(" (%.16e)\n", d);
730 else {
731 if (Hi == 0x7ff00000 && Lo == 0)
732 outs() << " (+Infinity)\n";
733 else if (Hi == 0xfff00000 && Lo == 0)
734 outs() << " (-Infinity)\n";
735 else if ((Hi & 0x00080000) == 0x00080000)
736 outs() << " (non-signaling Not-a-Number)\n";
737 else
738 outs() << " (signaling Not-a-Number)\n";
739 }
740}
741
742static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
743 uint32_t sect_size, uint64_t sect_addr,
744 bool print_addresses) {
745 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
746 if (print_addresses) {
747 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000748 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000749 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000750 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000751 }
752 double d;
753 memcpy(&d, sect + i, sizeof(double));
754 if (O->isLittleEndian() != sys::IsLittleEndianHost)
755 sys::swapByteOrder(d);
756 uint32_t l0, l1;
757 memcpy(&l0, sect + i, sizeof(uint32_t));
758 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
759 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
760 sys::swapByteOrder(l0);
761 sys::swapByteOrder(l1);
762 }
763 DumpLiteral8(O, l0, l1, d);
764 }
765}
766
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000767static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
768 outs() << format("0x%08" PRIx32, l0) << " ";
769 outs() << format("0x%08" PRIx32, l1) << " ";
770 outs() << format("0x%08" PRIx32, l2) << " ";
771 outs() << format("0x%08" PRIx32, l3) << "\n";
772}
773
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000774static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
775 uint32_t sect_size, uint64_t sect_addr,
776 bool print_addresses) {
777 for (uint32_t i = 0; i < sect_size; i += 16) {
778 if (print_addresses) {
779 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000780 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000781 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000782 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000783 }
784 uint32_t l0, l1, l2, l3;
785 memcpy(&l0, sect + i, sizeof(uint32_t));
786 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
787 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
788 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
789 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
790 sys::swapByteOrder(l0);
791 sys::swapByteOrder(l1);
792 sys::swapByteOrder(l2);
793 sys::swapByteOrder(l3);
794 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000795 DumpLiteral16(l0, l1, l2, l3);
796 }
797}
798
799static void DumpLiteralPointerSection(MachOObjectFile *O,
800 const SectionRef &Section,
801 const char *sect, uint32_t sect_size,
802 uint64_t sect_addr,
803 bool print_addresses) {
804 // Collect the literal sections in this Mach-O file.
805 std::vector<SectionRef> LiteralSections;
806 for (const SectionRef &Section : O->sections()) {
807 DataRefImpl Ref = Section.getRawDataRefImpl();
808 uint32_t section_type;
809 if (O->is64Bit()) {
810 const MachO::section_64 Sec = O->getSection64(Ref);
811 section_type = Sec.flags & MachO::SECTION_TYPE;
812 } else {
813 const MachO::section Sec = O->getSection(Ref);
814 section_type = Sec.flags & MachO::SECTION_TYPE;
815 }
816 if (section_type == MachO::S_CSTRING_LITERALS ||
817 section_type == MachO::S_4BYTE_LITERALS ||
818 section_type == MachO::S_8BYTE_LITERALS ||
819 section_type == MachO::S_16BYTE_LITERALS)
820 LiteralSections.push_back(Section);
821 }
822
823 // Set the size of the literal pointer.
824 uint32_t lp_size = O->is64Bit() ? 8 : 4;
825
Eric Christopher572e03a2015-06-19 01:53:21 +0000826 // Collect the external relocation symbols for the literal pointers.
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000827 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
828 for (const RelocationRef &Reloc : Section.relocations()) {
829 DataRefImpl Rel;
830 MachO::any_relocation_info RE;
831 bool isExtern = false;
832 Rel = Reloc.getRawDataRefImpl();
833 RE = O->getRelocation(Rel);
834 isExtern = O->getPlainRelocationExternal(RE);
835 if (isExtern) {
Rafael Espindola96d071c2015-06-29 23:29:12 +0000836 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000837 symbol_iterator RelocSym = Reloc.getSymbol();
838 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
839 }
840 }
841 array_pod_sort(Relocs.begin(), Relocs.end());
842
843 // Dump each literal pointer.
844 for (uint32_t i = 0; i < sect_size; i += lp_size) {
845 if (print_addresses) {
846 if (O->is64Bit())
847 outs() << format("%016" PRIx64, sect_addr + i) << " ";
848 else
849 outs() << format("%08" PRIx64, sect_addr + i) << " ";
850 }
851 uint64_t lp;
852 if (O->is64Bit()) {
853 memcpy(&lp, sect + i, sizeof(uint64_t));
854 if (O->isLittleEndian() != sys::IsLittleEndianHost)
855 sys::swapByteOrder(lp);
856 } else {
857 uint32_t li;
858 memcpy(&li, sect + i, sizeof(uint32_t));
859 if (O->isLittleEndian() != sys::IsLittleEndianHost)
860 sys::swapByteOrder(li);
861 lp = li;
862 }
863
864 // First look for an external relocation entry for this literal pointer.
David Blaikie33dd45d02015-03-23 18:39:02 +0000865 auto Reloc = std::find_if(
866 Relocs.begin(), Relocs.end(),
867 [&](const std::pair<uint64_t, SymbolRef> &P) { return P.first == i; });
868 if (Reloc != Relocs.end()) {
869 symbol_iterator RelocSym = Reloc->second;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000870 Expected<StringRef> SymName = RelocSym->getName();
871 if (!SymName) {
872 std::string Buf;
873 raw_string_ostream OS(Buf);
874 logAllUnhandledErrors(SymName.takeError(), OS, "");
875 OS.flush();
876 report_fatal_error(Buf);
877 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000878 outs() << "external relocation entry for symbol:" << *SymName << "\n";
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000879 continue;
David Blaikie33dd45d02015-03-23 18:39:02 +0000880 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000881
882 // For local references see what the section the literal pointer points to.
David Blaikie33dd45d02015-03-23 18:39:02 +0000883 auto Sect = std::find_if(LiteralSections.begin(), LiteralSections.end(),
884 [&](const SectionRef &R) {
885 return lp >= R.getAddress() &&
886 lp < R.getAddress() + R.getSize();
887 });
888 if (Sect == LiteralSections.end()) {
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000889 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
David Blaikie33dd45d02015-03-23 18:39:02 +0000890 continue;
891 }
892
893 uint64_t SectAddress = Sect->getAddress();
894 uint64_t SectSize = Sect->getSize();
895
896 StringRef SectName;
897 Sect->getName(SectName);
898 DataRefImpl Ref = Sect->getRawDataRefImpl();
899 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
900 outs() << SegmentName << ":" << SectName << ":";
901
902 uint32_t section_type;
903 if (O->is64Bit()) {
904 const MachO::section_64 Sec = O->getSection64(Ref);
905 section_type = Sec.flags & MachO::SECTION_TYPE;
906 } else {
907 const MachO::section Sec = O->getSection(Ref);
908 section_type = Sec.flags & MachO::SECTION_TYPE;
909 }
910
911 StringRef BytesStr;
912 Sect->getContents(BytesStr);
913 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
914
915 switch (section_type) {
916 case MachO::S_CSTRING_LITERALS:
917 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
918 i++) {
919 DumpCstringChar(Contents[i]);
920 }
921 outs() << "\n";
922 break;
923 case MachO::S_4BYTE_LITERALS:
924 float f;
925 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
926 uint32_t l;
927 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
928 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
929 sys::swapByteOrder(f);
930 sys::swapByteOrder(l);
931 }
932 DumpLiteral4(l, f);
933 break;
934 case MachO::S_8BYTE_LITERALS: {
935 double d;
936 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
937 uint32_t l0, l1;
938 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
939 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
940 sizeof(uint32_t));
941 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
942 sys::swapByteOrder(f);
943 sys::swapByteOrder(l0);
944 sys::swapByteOrder(l1);
945 }
946 DumpLiteral8(O, l0, l1, d);
947 break;
948 }
949 case MachO::S_16BYTE_LITERALS: {
950 uint32_t l0, l1, l2, l3;
951 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
952 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
953 sizeof(uint32_t));
954 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
955 sizeof(uint32_t));
956 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
957 sizeof(uint32_t));
958 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
959 sys::swapByteOrder(l0);
960 sys::swapByteOrder(l1);
961 sys::swapByteOrder(l2);
962 sys::swapByteOrder(l3);
963 }
964 DumpLiteral16(l0, l1, l2, l3);
965 break;
966 }
967 }
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000968 }
969}
970
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000971static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
972 uint32_t sect_size, uint64_t sect_addr,
973 SymbolAddressMap *AddrMap,
974 bool verbose) {
975 uint32_t stride;
Davide Italiano3eb47e22015-12-15 23:14:21 +0000976 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000977 for (uint32_t i = 0; i < sect_size; i += stride) {
978 const char *SymbolName = nullptr;
979 if (O->is64Bit()) {
980 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
981 uint64_t pointer_value;
982 memcpy(&pointer_value, sect + i, stride);
983 if (O->isLittleEndian() != sys::IsLittleEndianHost)
984 sys::swapByteOrder(pointer_value);
985 outs() << format("0x%016" PRIx64, pointer_value);
986 if (verbose)
987 SymbolName = GuessSymbolName(pointer_value, AddrMap);
988 } else {
989 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
990 uint32_t pointer_value;
991 memcpy(&pointer_value, sect + i, stride);
992 if (O->isLittleEndian() != sys::IsLittleEndianHost)
993 sys::swapByteOrder(pointer_value);
994 outs() << format("0x%08" PRIx32, pointer_value);
995 if (verbose)
996 SymbolName = GuessSymbolName(pointer_value, AddrMap);
997 }
998 if (SymbolName)
999 outs() << " " << SymbolName;
1000 outs() << "\n";
1001 }
1002}
1003
1004static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
1005 uint32_t size, uint64_t addr) {
1006 uint32_t cputype = O->getHeader().cputype;
1007 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
1008 uint32_t j;
1009 for (uint32_t i = 0; i < size; i += j, addr += j) {
1010 if (O->is64Bit())
1011 outs() << format("%016" PRIx64, addr) << "\t";
1012 else
Kevin Enderbyf0640752015-03-13 17:56:32 +00001013 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001014 for (j = 0; j < 16 && i + j < size; j++) {
1015 uint8_t byte_word = *(sect + i + j);
1016 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1017 }
1018 outs() << "\n";
1019 }
1020 } else {
1021 uint32_t j;
1022 for (uint32_t i = 0; i < size; i += j, addr += j) {
1023 if (O->is64Bit())
1024 outs() << format("%016" PRIx64, addr) << "\t";
1025 else
Kevin Enderbyc4930852016-04-27 22:36:18 +00001026 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001027 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1028 j += sizeof(int32_t)) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001029 if (i + j + sizeof(int32_t) <= size) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001030 uint32_t long_word;
1031 memcpy(&long_word, sect + i + j, sizeof(int32_t));
1032 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1033 sys::swapByteOrder(long_word);
1034 outs() << format("%08" PRIx32, long_word) << " ";
1035 } else {
1036 for (uint32_t k = 0; i + j + k < size; k++) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001037 uint8_t byte_word = *(sect + i + j + k);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001038 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1039 }
1040 }
1041 }
1042 outs() << "\n";
1043 }
1044 }
1045}
1046
Kevin Enderby95df54c2015-02-04 01:01:38 +00001047static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1048 StringRef DisSegName, StringRef DisSectName);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001049static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1050 uint32_t size, uint32_t addr);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001051#ifdef HAVE_LIBXAR
1052static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
1053 uint32_t size, bool verbose,
1054 bool PrintXarHeader, bool PrintXarFileHeaders,
1055 std::string XarMemberName);
1056#endif // defined(HAVE_LIBXAR)
Kevin Enderby95df54c2015-02-04 01:01:38 +00001057
1058static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1059 bool verbose) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001060 SymbolAddressMap AddrMap;
1061 if (verbose)
1062 CreateSymbolAddressMap(O, &AddrMap);
1063
Colin LeMahieufcc32762015-07-29 19:08:10 +00001064 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1065 StringRef DumpSection = FilterSections[i];
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001066 std::pair<StringRef, StringRef> DumpSegSectName;
1067 DumpSegSectName = DumpSection.split(',');
1068 StringRef DumpSegName, DumpSectName;
1069 if (DumpSegSectName.second.size()) {
1070 DumpSegName = DumpSegSectName.first;
1071 DumpSectName = DumpSegSectName.second;
1072 } else {
1073 DumpSegName = "";
1074 DumpSectName = DumpSegSectName.first;
1075 }
1076 for (const SectionRef &Section : O->sections()) {
1077 StringRef SectName;
1078 Section.getName(SectName);
1079 DataRefImpl Ref = Section.getRawDataRefImpl();
1080 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1081 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1082 (SectName == DumpSectName)) {
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001083
Kevin Enderby95df54c2015-02-04 01:01:38 +00001084 uint32_t section_flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001085 if (O->is64Bit()) {
1086 const MachO::section_64 Sec = O->getSection64(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001087 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001088
1089 } else {
1090 const MachO::section Sec = O->getSection(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001091 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001092 }
Kevin Enderby95df54c2015-02-04 01:01:38 +00001093 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001094
1095 StringRef BytesStr;
1096 Section.getContents(BytesStr);
1097 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1098 uint32_t sect_size = BytesStr.size();
1099 uint64_t sect_addr = Section.getAddress();
1100
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001101 outs() << "Contents of (" << SegName << "," << SectName
1102 << ") section\n";
1103
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001104 if (verbose) {
Kevin Enderby95df54c2015-02-04 01:01:38 +00001105 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1106 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1107 DisassembleMachO(Filename, O, SegName, SectName);
1108 continue;
1109 }
Kevin Enderbycd66be52015-03-11 22:06:32 +00001110 if (SegName == "__TEXT" && SectName == "__info_plist") {
1111 outs() << sect;
1112 continue;
1113 }
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001114 if (SegName == "__OBJC" && SectName == "__protocol") {
1115 DumpProtocolSection(O, sect, sect_size, sect_addr);
1116 continue;
1117 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001118#ifdef HAVE_LIBXAR
1119 if (SegName == "__LLVM" && SectName == "__bundle") {
1120 DumpBitcodeSection(O, sect, sect_size, verbose, !NoSymbolicOperands,
1121 ArchiveHeaders, "");
1122 continue;
1123 }
1124#endif // defined(HAVE_LIBXAR)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001125 switch (section_type) {
1126 case MachO::S_REGULAR:
1127 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1128 break;
1129 case MachO::S_ZEROFILL:
1130 outs() << "zerofill section and has no contents in the file\n";
1131 break;
Kevin Enderby10ba0412015-02-04 21:38:42 +00001132 case MachO::S_CSTRING_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001133 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001134 break;
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001135 case MachO::S_4BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001136 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001137 break;
1138 case MachO::S_8BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001139 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001140 break;
1141 case MachO::S_16BYTE_LITERALS:
Kevin Enderby0fc11822015-04-01 20:57:01 +00001142 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1143 break;
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001144 case MachO::S_LITERAL_POINTERS:
1145 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001146 !NoLeadingAddr);
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001147 break;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001148 case MachO::S_MOD_INIT_FUNC_POINTERS:
1149 case MachO::S_MOD_TERM_FUNC_POINTERS:
1150 DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
1151 verbose);
1152 break;
1153 default:
1154 outs() << "Unknown section type ("
1155 << format("0x%08" PRIx32, section_type) << ")\n";
1156 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1157 break;
1158 }
1159 } else {
1160 if (section_type == MachO::S_ZEROFILL)
1161 outs() << "zerofill section and has no contents in the file\n";
1162 else
1163 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1164 }
1165 }
1166 }
1167 }
1168}
1169
Kevin Enderbycd66be52015-03-11 22:06:32 +00001170static void DumpInfoPlistSectionContents(StringRef Filename,
1171 MachOObjectFile *O) {
1172 for (const SectionRef &Section : O->sections()) {
1173 StringRef SectName;
1174 Section.getName(SectName);
1175 DataRefImpl Ref = Section.getRawDataRefImpl();
1176 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1177 if (SegName == "__TEXT" && SectName == "__info_plist") {
1178 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1179 StringRef BytesStr;
1180 Section.getContents(BytesStr);
1181 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1182 outs() << sect;
1183 return;
1184 }
1185 }
1186}
1187
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001188// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1189// and if it is and there is a list of architecture flags is specified then
1190// check to make sure this Mach-O file is one of those architectures or all
1191// architectures were specified. If not then an error is generated and this
1192// routine returns false. Else it returns true.
1193static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1194 if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
1195 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
1196 bool ArchFound = false;
1197 MachO::mach_header H;
1198 MachO::mach_header_64 H_64;
1199 Triple T;
1200 if (MachO->is64Bit()) {
1201 H_64 = MachO->MachOObjectFile::getHeader64();
Tim Northover9e8eb412016-04-22 23:21:13 +00001202 T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001203 } else {
1204 H = MachO->MachOObjectFile::getHeader();
Tim Northover9e8eb412016-04-22 23:21:13 +00001205 T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001206 }
1207 unsigned i;
1208 for (i = 0; i < ArchFlags.size(); ++i) {
1209 if (ArchFlags[i] == T.getArchName())
1210 ArchFound = true;
1211 break;
1212 }
1213 if (!ArchFound) {
1214 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1215 << "architecture: " + ArchFlags[i] + "\n";
1216 return false;
1217 }
1218 }
1219 return true;
1220}
1221
Kevin Enderby0fc11822015-04-01 20:57:01 +00001222static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1223
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001224// ProcessMachO() is passed a single opened Mach-O file, which may be an
1225// archive member and or in a slice of a universal file. It prints the
1226// the file name and header info and then processes it according to the
1227// command line options.
1228static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
1229 StringRef ArchiveMemberName = StringRef(),
1230 StringRef ArchitectureName = StringRef()) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001231 // If we are doing some processing here on the Mach-O file print the header
1232 // info. And don't print it otherwise like in the case of printing the
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001233 // UniversalHeaders or ArchiveHeaders.
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001234 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind || SymbolTable ||
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001235 LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints ||
Colin LeMahieufcc32762015-07-29 19:08:10 +00001236 DylibsUsed || DylibId || ObjcMetaData || (FilterSections.size() != 0)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001237 outs() << Filename;
1238 if (!ArchiveMemberName.empty())
1239 outs() << '(' << ArchiveMemberName << ')';
1240 if (!ArchitectureName.empty())
1241 outs() << " (architecture " << ArchitectureName << ")";
1242 outs() << ":\n";
1243 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001244
1245 if (Disassemble)
Kevin Enderby95df54c2015-02-04 01:01:38 +00001246 DisassembleMachO(Filename, MachOOF, "__TEXT", "__text");
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001247 if (IndirectSymbols)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001248 PrintIndirectSymbols(MachOOF, !NonVerbose);
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001249 if (DataInCode)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001250 PrintDataInCodeTable(MachOOF, !NonVerbose);
Kevin Enderby9a509442015-01-27 21:28:24 +00001251 if (LinkOptHints)
1252 PrintLinkOptHints(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001253 if (Relocations)
1254 PrintRelocations(MachOOF);
1255 if (SectionHeaders)
1256 PrintSectionHeaders(MachOOF);
1257 if (SectionContents)
1258 PrintSectionContents(MachOOF);
Colin LeMahieufcc32762015-07-29 19:08:10 +00001259 if (FilterSections.size() != 0)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001260 DumpSectionContents(Filename, MachOOF, !NonVerbose);
Kevin Enderbycd66be52015-03-11 22:06:32 +00001261 if (InfoPlist)
1262 DumpInfoPlistSectionContents(Filename, MachOOF);
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001263 if (DylibsUsed)
1264 PrintDylibs(MachOOF, false);
1265 if (DylibId)
1266 PrintDylibs(MachOOF, true);
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001267 if (SymbolTable) {
1268 StringRef ArchiveName = ArchiveMemberName == StringRef() ? "" : Filename;
Kevin Enderby9acb1092016-05-31 20:35:34 +00001269 PrintSymbolTable(MachOOF, ArchiveName, ArchitectureName);
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001270 }
Kevin Enderby98da6132015-01-20 21:47:46 +00001271 if (UnwindInfo)
1272 printMachOUnwindInfo(MachOOF);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001273 if (PrivateHeaders) {
1274 printMachOFileHeader(MachOOF);
1275 printMachOLoadCommands(MachOOF);
1276 }
1277 if (FirstPrivateHeader)
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001278 printMachOFileHeader(MachOOF);
Kevin Enderby0fc11822015-04-01 20:57:01 +00001279 if (ObjcMetaData)
1280 printObjcMetaData(MachOOF, !NonVerbose);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001281 if (ExportsTrie)
1282 printExportsTrie(MachOOF);
1283 if (Rebase)
1284 printRebaseTable(MachOOF);
1285 if (Bind)
1286 printBindTable(MachOOF);
1287 if (LazyBind)
1288 printLazyBindTable(MachOOF);
1289 if (WeakBind)
1290 printWeakBindTable(MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001291
1292 if (DwarfDumpType != DIDT_Null) {
1293 std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*MachOOF));
1294 // Dump the complete DWARF structure.
1295 DICtx->dump(outs(), DwarfDumpType, true /* DumpEH */);
1296 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001297}
1298
Kevin Enderby131d1772015-01-09 19:22:37 +00001299// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1300static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1301 outs() << " cputype (" << cputype << ")\n";
1302 outs() << " cpusubtype (" << cpusubtype << ")\n";
1303}
1304
1305// printCPUType() helps print_fat_headers by printing the cputype and
1306// pusubtype (symbolically for the one's it knows about).
1307static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1308 switch (cputype) {
1309 case MachO::CPU_TYPE_I386:
1310 switch (cpusubtype) {
1311 case MachO::CPU_SUBTYPE_I386_ALL:
1312 outs() << " cputype CPU_TYPE_I386\n";
1313 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1314 break;
1315 default:
1316 printUnknownCPUType(cputype, cpusubtype);
1317 break;
1318 }
1319 break;
1320 case MachO::CPU_TYPE_X86_64:
1321 switch (cpusubtype) {
1322 case MachO::CPU_SUBTYPE_X86_64_ALL:
1323 outs() << " cputype CPU_TYPE_X86_64\n";
1324 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1325 break;
1326 case MachO::CPU_SUBTYPE_X86_64_H:
1327 outs() << " cputype CPU_TYPE_X86_64\n";
1328 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1329 break;
1330 default:
1331 printUnknownCPUType(cputype, cpusubtype);
1332 break;
1333 }
1334 break;
1335 case MachO::CPU_TYPE_ARM:
1336 switch (cpusubtype) {
1337 case MachO::CPU_SUBTYPE_ARM_ALL:
1338 outs() << " cputype CPU_TYPE_ARM\n";
1339 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1340 break;
1341 case MachO::CPU_SUBTYPE_ARM_V4T:
1342 outs() << " cputype CPU_TYPE_ARM\n";
1343 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1344 break;
1345 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1346 outs() << " cputype CPU_TYPE_ARM\n";
1347 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1348 break;
1349 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1350 outs() << " cputype CPU_TYPE_ARM\n";
1351 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1352 break;
1353 case MachO::CPU_SUBTYPE_ARM_V6:
1354 outs() << " cputype CPU_TYPE_ARM\n";
1355 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1356 break;
1357 case MachO::CPU_SUBTYPE_ARM_V6M:
1358 outs() << " cputype CPU_TYPE_ARM\n";
1359 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1360 break;
1361 case MachO::CPU_SUBTYPE_ARM_V7:
1362 outs() << " cputype CPU_TYPE_ARM\n";
1363 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1364 break;
1365 case MachO::CPU_SUBTYPE_ARM_V7EM:
1366 outs() << " cputype CPU_TYPE_ARM\n";
1367 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1368 break;
1369 case MachO::CPU_SUBTYPE_ARM_V7K:
1370 outs() << " cputype CPU_TYPE_ARM\n";
1371 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1372 break;
1373 case MachO::CPU_SUBTYPE_ARM_V7M:
1374 outs() << " cputype CPU_TYPE_ARM\n";
1375 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1376 break;
1377 case MachO::CPU_SUBTYPE_ARM_V7S:
1378 outs() << " cputype CPU_TYPE_ARM\n";
1379 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1380 break;
1381 default:
1382 printUnknownCPUType(cputype, cpusubtype);
1383 break;
1384 }
1385 break;
1386 case MachO::CPU_TYPE_ARM64:
1387 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1388 case MachO::CPU_SUBTYPE_ARM64_ALL:
1389 outs() << " cputype CPU_TYPE_ARM64\n";
1390 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1391 break;
1392 default:
1393 printUnknownCPUType(cputype, cpusubtype);
1394 break;
1395 }
1396 break;
1397 default:
1398 printUnknownCPUType(cputype, cpusubtype);
1399 break;
1400 }
1401}
1402
1403static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1404 bool verbose) {
1405 outs() << "Fat headers\n";
Kevin Enderby606a3382016-06-21 21:55:01 +00001406 if (verbose) {
1407 if (UB->getMagic() == MachO::FAT_MAGIC)
1408 outs() << "fat_magic FAT_MAGIC\n";
1409 else // UB->getMagic() == MachO::FAT_MAGIC_64
1410 outs() << "fat_magic FAT_MAGIC_64\n";
1411 } else
Kevin Enderby131d1772015-01-09 19:22:37 +00001412 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1413
1414 uint32_t nfat_arch = UB->getNumberOfObjects();
1415 StringRef Buf = UB->getData();
1416 uint64_t size = Buf.size();
1417 uint64_t big_size = sizeof(struct MachO::fat_header) +
1418 nfat_arch * sizeof(struct MachO::fat_arch);
1419 outs() << "nfat_arch " << UB->getNumberOfObjects();
1420 if (nfat_arch == 0)
1421 outs() << " (malformed, contains zero architecture types)\n";
1422 else if (big_size > size)
1423 outs() << " (malformed, architectures past end of file)\n";
1424 else
1425 outs() << "\n";
1426
1427 for (uint32_t i = 0; i < nfat_arch; ++i) {
1428 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1429 uint32_t cputype = OFA.getCPUType();
1430 uint32_t cpusubtype = OFA.getCPUSubType();
1431 outs() << "architecture ";
1432 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1433 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1434 uint32_t other_cputype = other_OFA.getCPUType();
1435 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
Kevin Enderby0512bd72015-01-09 21:55:03 +00001436 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
Kevin Enderby131d1772015-01-09 19:22:37 +00001437 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
Kevin Enderby0512bd72015-01-09 21:55:03 +00001438 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001439 outs() << "(illegal duplicate architecture) ";
1440 break;
Kevin Enderby0512bd72015-01-09 21:55:03 +00001441 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001442 }
1443 if (verbose) {
1444 outs() << OFA.getArchTypeName() << "\n";
1445 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1446 } else {
1447 outs() << i << "\n";
1448 outs() << " cputype " << cputype << "\n";
1449 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1450 << "\n";
1451 }
1452 if (verbose &&
1453 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1454 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1455 else
1456 outs() << " capabilities "
1457 << format("0x%" PRIx32,
1458 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1459 outs() << " offset " << OFA.getOffset();
1460 if (OFA.getOffset() > size)
1461 outs() << " (past end of file)";
1462 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1463 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1464 outs() << "\n";
1465 outs() << " size " << OFA.getSize();
1466 big_size = OFA.getOffset() + OFA.getSize();
1467 if (big_size > size)
1468 outs() << " (past end of file)";
1469 outs() << "\n";
1470 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1471 << ")\n";
1472 }
1473}
1474
Kevin Enderby6524bd82016-07-19 20:47:07 +00001475static void printArchiveChild(StringRef Filename, const Archive::Child &C,
1476 bool verbose, bool print_offset,
1477 StringRef ArchitectureName = StringRef()) {
Kevin Enderby13023a12015-01-15 23:19:11 +00001478 if (print_offset)
1479 outs() << C.getChildOffset() << "\t";
1480 sys::fs::perms Mode = C.getAccessMode();
1481 if (verbose) {
1482 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1483 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1484 outs() << "-";
Davide Italianobb9a6cc2015-09-07 20:47:03 +00001485 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1486 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1487 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1488 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1489 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1490 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1491 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1492 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1493 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
Kevin Enderby13023a12015-01-15 23:19:11 +00001494 } else {
1495 outs() << format("0%o ", Mode);
1496 }
1497
1498 unsigned UID = C.getUID();
1499 outs() << format("%3d/", UID);
1500 unsigned GID = C.getGID();
1501 outs() << format("%-3d ", GID);
Kevin Enderby6524bd82016-07-19 20:47:07 +00001502 Expected<uint64_t> Size = C.getRawSize();
1503 if (!Size)
1504 report_error(Filename, C, Size.takeError(), ArchitectureName);
Kevin Enderby7a969422015-11-05 19:24:56 +00001505 outs() << format("%5" PRId64, Size.get()) << " ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001506
1507 StringRef RawLastModified = C.getRawLastModified();
1508 if (verbose) {
1509 unsigned Seconds;
1510 if (RawLastModified.getAsInteger(10, Seconds))
1511 outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
1512 else {
1513 // Since cime(3) returns a 26 character string of the form:
1514 // "Sun Sep 16 01:03:52 1973\n\0"
1515 // just print 24 characters.
1516 time_t t = Seconds;
1517 outs() << format("%.24s ", ctime(&t));
1518 }
1519 } else {
1520 outs() << RawLastModified << " ";
1521 }
1522
1523 if (verbose) {
1524 ErrorOr<StringRef> NameOrErr = C.getName();
1525 if (NameOrErr.getError()) {
1526 StringRef RawName = C.getRawName();
1527 outs() << RawName << "\n";
1528 } else {
1529 StringRef Name = NameOrErr.get();
1530 outs() << Name << "\n";
1531 }
1532 } else {
1533 StringRef RawName = C.getRawName();
1534 outs() << RawName << "\n";
1535 }
1536}
1537
Kevin Enderby6524bd82016-07-19 20:47:07 +00001538static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
1539 bool print_offset,
1540 StringRef ArchitectureName = StringRef()) {
Lang Hamesfc209622016-07-14 02:24:01 +00001541 Error Err;
1542 for (const auto &C : A->children(Err, false))
Kevin Enderby6524bd82016-07-19 20:47:07 +00001543 printArchiveChild(Filename, C, verbose, print_offset, ArchitectureName);
1544
Lang Hamesfc209622016-07-14 02:24:01 +00001545 if (Err)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001546 report_error(Filename, std::move(Err));
Kevin Enderby13023a12015-01-15 23:19:11 +00001547}
1548
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001549// ParseInputMachO() parses the named Mach-O file in Filename and handles the
1550// -arch flags selecting just those slices as specified by them and also parses
1551// archive files. Then for each individual Mach-O file ProcessMachO() is
1552// called to process the file based on the command line options.
1553void llvm::ParseInputMachO(StringRef Filename) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001554 // Check for -arch all and verifiy the -arch flags are valid.
1555 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1556 if (ArchFlags[i] == "all") {
1557 ArchAll = true;
1558 } else {
1559 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1560 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1561 "'for the -arch option\n";
1562 return;
1563 }
1564 }
1565 }
1566
1567 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00001568 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1569 if (!BinaryOrErr)
1570 report_error(Filename, BinaryOrErr.takeError());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001571 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001572
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001573 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1574 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001575 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001576 printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets);
1577
Lang Hamesfc209622016-07-14 02:24:01 +00001578 Error Err;
1579 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001580 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1581 if (!ChildOrErr) {
1582 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1583 report_error(Filename, C, std::move(E));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001584 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001585 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001586 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1587 if (!checkMachOAndArchFlags(O, Filename))
1588 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001589 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001590 }
1591 }
Lang Hamesfc209622016-07-14 02:24:01 +00001592 if (Err)
1593 report_error(Filename, std::move(Err));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001594 return;
1595 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001596 if (UniversalHeaders) {
1597 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
Kevin Enderbyf0640752015-03-13 17:56:32 +00001598 printMachOUniversalHeaders(UB, !NonVerbose);
Kevin Enderby131d1772015-01-09 19:22:37 +00001599 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001600 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1601 // If we have a list of architecture flags specified dump only those.
1602 if (!ArchAll && ArchFlags.size() != 0) {
1603 // Look for a slice in the universal binary that matches each ArchFlag.
1604 bool ArchFound;
1605 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1606 ArchFound = false;
1607 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1608 E = UB->end_objects();
1609 I != E; ++I) {
1610 if (ArchFlags[i] == I->getArchTypeName()) {
1611 ArchFound = true;
Kevin Enderby9acb1092016-05-31 20:35:34 +00001612 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001613 I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001614 std::string ArchitectureName = "";
1615 if (ArchFlags.size() > 1)
1616 ArchitectureName = I->getArchTypeName();
1617 if (ObjOrErr) {
1618 ObjectFile &O = *ObjOrErr.get();
1619 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001620 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Kevin Enderby9acb1092016-05-31 20:35:34 +00001621 } else if (auto E = isNotObjectErrorInvalidFileType(
1622 ObjOrErr.takeError())) {
1623 report_error(Filename, StringRef(), std::move(E),
1624 ArchitectureName);
1625 continue;
Kevin Enderby42398052016-06-28 23:16:13 +00001626 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001627 I->getAsArchive()) {
1628 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001629 outs() << "Archive : " << Filename;
1630 if (!ArchitectureName.empty())
1631 outs() << " (architecture " << ArchitectureName << ")";
1632 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001633 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001634 printArchiveHeaders(Filename, A.get(), !NonVerbose,
1635 ArchiveMemberOffsets, ArchitectureName);
Lang Hamesfc209622016-07-14 02:24:01 +00001636 Error Err;
1637 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001638 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1639 if (!ChildOrErr) {
1640 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
Kevin Enderby9acb1092016-05-31 20:35:34 +00001641 report_error(Filename, C, std::move(E), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001642 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001643 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001644 if (MachOObjectFile *O =
1645 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001646 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001647 }
Lang Hamesfc209622016-07-14 02:24:01 +00001648 if (Err)
1649 report_error(Filename, std::move(Err));
Kevin Enderby42398052016-06-28 23:16:13 +00001650 } else {
1651 consumeError(AOrErr.takeError());
1652 error("Mach-O universal file: " + Filename + " for " +
1653 "architecture " + StringRef(I->getArchTypeName()) +
1654 " is not a Mach-O file or an archive file");
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001655 }
1656 }
1657 }
1658 if (!ArchFound) {
1659 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1660 << "architecture: " + ArchFlags[i] + "\n";
1661 return;
1662 }
1663 }
1664 return;
1665 }
1666 // No architecture flags were specified so if this contains a slice that
1667 // matches the host architecture dump only that.
1668 if (!ArchAll) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001669 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1670 E = UB->end_objects();
1671 I != E; ++I) {
Kevin Enderby0512bd72015-01-09 21:55:03 +00001672 if (MachOObjectFile::getHostArch().getArchName() ==
1673 I->getArchTypeName()) {
Kevin Enderby9acb1092016-05-31 20:35:34 +00001674 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001675 std::string ArchiveName;
1676 ArchiveName.clear();
1677 if (ObjOrErr) {
1678 ObjectFile &O = *ObjOrErr.get();
1679 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001680 ProcessMachO(Filename, MachOOF);
Kevin Enderby9acb1092016-05-31 20:35:34 +00001681 } else if (auto E = isNotObjectErrorInvalidFileType(
1682 ObjOrErr.takeError())) {
1683 report_error(Filename, std::move(E));
1684 continue;
Kevin Enderby42398052016-06-28 23:16:13 +00001685 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001686 I->getAsArchive()) {
1687 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001688 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001689 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001690 printArchiveHeaders(Filename, A.get(), !NonVerbose,
1691 ArchiveMemberOffsets);
Lang Hamesfc209622016-07-14 02:24:01 +00001692 Error Err;
1693 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001694 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1695 if (!ChildOrErr) {
1696 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1697 report_error(Filename, C, std::move(E));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001698 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001699 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001700 if (MachOObjectFile *O =
1701 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001702 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001703 }
Lang Hamesfc209622016-07-14 02:24:01 +00001704 if (Err)
1705 report_error(Filename, std::move(Err));
Kevin Enderby42398052016-06-28 23:16:13 +00001706 } else {
1707 consumeError(AOrErr.takeError());
1708 error("Mach-O universal file: " + Filename + " for architecture " +
1709 StringRef(I->getArchTypeName()) +
1710 " is not a Mach-O file or an archive file");
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001711 }
1712 return;
1713 }
1714 }
1715 }
1716 // Either all architectures have been specified or none have been specified
1717 // and this does not contain the host architecture so dump all the slices.
1718 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1719 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1720 E = UB->end_objects();
1721 I != E; ++I) {
Kevin Enderby9acb1092016-05-31 20:35:34 +00001722 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001723 std::string ArchitectureName = "";
1724 if (moreThanOneArch)
1725 ArchitectureName = I->getArchTypeName();
1726 if (ObjOrErr) {
1727 ObjectFile &Obj = *ObjOrErr.get();
1728 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001729 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Kevin Enderby9acb1092016-05-31 20:35:34 +00001730 } else if (auto E = isNotObjectErrorInvalidFileType(
1731 ObjOrErr.takeError())) {
1732 report_error(StringRef(), Filename, std::move(E), ArchitectureName);
1733 continue;
Kevin Enderby42398052016-06-28 23:16:13 +00001734 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
1735 I->getAsArchive()) {
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001736 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001737 outs() << "Archive : " << Filename;
1738 if (!ArchitectureName.empty())
1739 outs() << " (architecture " << ArchitectureName << ")";
1740 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001741 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001742 printArchiveHeaders(Filename, A.get(), !NonVerbose,
1743 ArchiveMemberOffsets, ArchitectureName);
Lang Hamesfc209622016-07-14 02:24:01 +00001744 Error Err;
1745 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001746 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1747 if (!ChildOrErr) {
1748 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
Kevin Enderby9acb1092016-05-31 20:35:34 +00001749 report_error(Filename, C, std::move(E), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001750 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001751 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001752 if (MachOObjectFile *O =
1753 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1754 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001755 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1756 ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001757 }
1758 }
Lang Hamesfc209622016-07-14 02:24:01 +00001759 if (Err)
1760 report_error(Filename, std::move(Err));
Kevin Enderby42398052016-06-28 23:16:13 +00001761 } else {
1762 consumeError(AOrErr.takeError());
1763 error("Mach-O universal file: " + Filename + " for architecture " +
1764 StringRef(I->getArchTypeName()) +
1765 " is not a Mach-O file or an archive file");
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001766 }
1767 }
1768 return;
1769 }
1770 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1771 if (!checkMachOAndArchFlags(O, Filename))
1772 return;
1773 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001774 ProcessMachO(Filename, MachOOF);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001775 } else
1776 errs() << "llvm-objdump: '" << Filename << "': "
1777 << "Object is not a Mach-O file type.\n";
Davide Italiano25d84582016-01-13 04:11:36 +00001778 return;
1779 }
1780 llvm_unreachable("Input object can't be invalid at this point");
Rafael Espindola9b709252013-04-13 01:45:40 +00001781}
1782
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001783typedef std::pair<uint64_t, const char *> BindInfoEntry;
1784typedef std::vector<BindInfoEntry> BindTable;
1785typedef BindTable::iterator bind_table_iterator;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001786
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001787// The block of info used by the Symbolizer call backs.
1788struct DisassembleInfo {
1789 bool verbose;
1790 MachOObjectFile *O;
1791 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001792 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001793 std::vector<SectionRef> *Sections;
1794 const char *class_name;
1795 const char *selector_name;
1796 char *method;
Kevin Enderby04bf6932014-10-28 23:39:46 +00001797 char *demangled_name;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001798 uint64_t adrp_addr;
1799 uint32_t adrp_inst;
Kevin Enderby078be602014-10-23 19:53:12 +00001800 BindTable *bindtable;
Kevin Enderbyaac75382015-10-08 16:56:35 +00001801 uint32_t depth;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001802};
1803
1804// SymbolizerGetOpInfo() is the operand information call back function.
1805// This is called to get the symbolic information for operand(s) of an
1806// instruction when it is being done. This routine does this from
1807// the relocation information, symbol table, etc. That block of information
1808// is a pointer to the struct DisassembleInfo that was passed when the
1809// disassembler context was created and passed to back to here when
1810// called back by the disassembler for instruction operands that could have
1811// relocation information. The address of the instruction containing operand is
1812// at the Pc parameter. The immediate value the operand has is passed in
1813// op_info->Value and is at Offset past the start of the instruction and has a
1814// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1815// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1816// names and addends of the symbolic expression to add for the operand. The
1817// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1818// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001819static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1820 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001821 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1822 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001823 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001824
1825 // Make sure all fields returned are zero if we don't set them.
1826 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1827 op_info->Value = value;
1828
1829 // If the TagType is not the value 1 which it code knows about or if no
1830 // verbose symbolic information is wanted then just return 0, indicating no
1831 // information is being returned.
David Blaikie33dd45d02015-03-23 18:39:02 +00001832 if (TagType != 1 || !info->verbose)
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001833 return 0;
1834
1835 unsigned int Arch = info->O->getArch();
1836 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001837 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1838 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001839 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1840 // TODO:
1841 // Search the external relocation entries of a fully linked image
1842 // (if any) for an entry that matches this segment offset.
1843 // uint32_t seg_offset = (Pc + Offset);
1844 return 0;
1845 }
1846 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1847 // for an entry for this section offset.
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001848 uint32_t sect_addr = info->S.getAddress();
1849 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1850 bool reloc_found = false;
1851 DataRefImpl Rel;
1852 MachO::any_relocation_info RE;
1853 bool isExtern = false;
1854 SymbolRef Symbol;
1855 bool r_scattered = false;
1856 uint32_t r_value, pair_r_value, r_type;
1857 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001858 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001859 if (RelocOffset == sect_offset) {
1860 Rel = Reloc.getRawDataRefImpl();
1861 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00001862 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001863 r_scattered = info->O->isRelocationScattered(RE);
1864 if (r_scattered) {
1865 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001866 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1867 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1868 DataRefImpl RelNext = Rel;
1869 info->O->moveRelocationNext(RelNext);
1870 MachO::any_relocation_info RENext;
1871 RENext = info->O->getRelocation(RelNext);
1872 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00001873 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001874 else
1875 return 0;
1876 }
1877 } else {
1878 isExtern = info->O->getPlainRelocationExternal(RE);
1879 if (isExtern) {
1880 symbol_iterator RelocSym = Reloc.getSymbol();
1881 Symbol = *RelocSym;
1882 }
1883 }
1884 reloc_found = true;
1885 break;
1886 }
1887 }
1888 if (reloc_found && isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001889 Expected<StringRef> SymName = Symbol.getName();
1890 if (!SymName) {
1891 std::string Buf;
1892 raw_string_ostream OS(Buf);
1893 logAllUnhandledErrors(SymName.takeError(), OS, "");
1894 OS.flush();
1895 report_fatal_error(Buf);
1896 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001897 const char *name = SymName->data();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001898 op_info->AddSymbol.Present = 1;
1899 op_info->AddSymbol.Name = name;
1900 // For i386 extern relocation entries the value in the instruction is
1901 // the offset from the symbol, and value is already set in op_info->Value.
1902 return 1;
1903 }
1904 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1905 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001906 const char *add = GuessSymbolName(r_value, info->AddrMap);
1907 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001908 uint32_t offset = value - (r_value - pair_r_value);
1909 op_info->AddSymbol.Present = 1;
1910 if (add != nullptr)
1911 op_info->AddSymbol.Name = add;
1912 else
1913 op_info->AddSymbol.Value = r_value;
1914 op_info->SubtractSymbol.Present = 1;
1915 if (sub != nullptr)
1916 op_info->SubtractSymbol.Name = sub;
1917 else
1918 op_info->SubtractSymbol.Value = pair_r_value;
1919 op_info->Value = offset;
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::x86_64) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001925 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
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 // uint64_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.
Rafael Espindola80291272014-10-08 15:28:58 +00001936 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001937 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1938 bool reloc_found = false;
1939 DataRefImpl Rel;
1940 MachO::any_relocation_info RE;
1941 bool isExtern = false;
1942 SymbolRef Symbol;
1943 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001944 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001945 if (RelocOffset == sect_offset) {
1946 Rel = Reloc.getRawDataRefImpl();
1947 RE = info->O->getRelocation(Rel);
1948 // NOTE: Scattered relocations don't exist on x86_64.
1949 isExtern = info->O->getPlainRelocationExternal(RE);
1950 if (isExtern) {
1951 symbol_iterator RelocSym = Reloc.getSymbol();
1952 Symbol = *RelocSym;
1953 }
1954 reloc_found = true;
1955 break;
1956 }
1957 }
1958 if (reloc_found && isExtern) {
1959 // The Value passed in will be adjusted by the Pc if the instruction
1960 // adds the Pc. But for x86_64 external relocation entries the Value
1961 // is the offset from the external symbol.
1962 if (info->O->getAnyRelocationPCRel(RE))
1963 op_info->Value -= Pc + Offset + Size;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001964 Expected<StringRef> SymName = Symbol.getName();
1965 if (!SymName) {
1966 std::string Buf;
1967 raw_string_ostream OS(Buf);
1968 logAllUnhandledErrors(SymName.takeError(), OS, "");
1969 OS.flush();
1970 report_fatal_error(Buf);
1971 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001972 const char *name = SymName->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001973 unsigned Type = info->O->getAnyRelocationType(RE);
1974 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1975 DataRefImpl RelNext = Rel;
1976 info->O->moveRelocationNext(RelNext);
1977 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1978 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1979 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1980 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1981 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1982 op_info->SubtractSymbol.Present = 1;
1983 op_info->SubtractSymbol.Name = name;
1984 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1985 Symbol = *RelocSymNext;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001986 Expected<StringRef> SymNameNext = Symbol.getName();
1987 if (!SymNameNext) {
1988 std::string Buf;
1989 raw_string_ostream OS(Buf);
1990 logAllUnhandledErrors(SymNameNext.takeError(), OS, "");
1991 OS.flush();
1992 report_fatal_error(Buf);
1993 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001994 name = SymNameNext->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001995 }
1996 }
1997 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1998 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1999 op_info->AddSymbol.Present = 1;
2000 op_info->AddSymbol.Name = name;
2001 return 1;
2002 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002003 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002004 }
2005 if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002006 if (Offset != 0 || (Size != 4 && Size != 2))
2007 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002008 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2009 // TODO:
2010 // Search the external relocation entries of a fully linked image
2011 // (if any) for an entry that matches this segment offset.
2012 // uint32_t seg_offset = (Pc + Offset);
2013 return 0;
2014 }
2015 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2016 // for an entry for this section offset.
Kevin Enderby930fdc72014-11-06 19:00:13 +00002017 uint32_t sect_addr = info->S.getAddress();
2018 uint32_t sect_offset = (Pc + Offset) - sect_addr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002019 DataRefImpl Rel;
2020 MachO::any_relocation_info RE;
2021 bool isExtern = false;
2022 SymbolRef Symbol;
2023 bool r_scattered = false;
2024 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
David Blaikie33dd45d02015-03-23 18:39:02 +00002025 auto Reloc =
2026 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
2027 [&](const RelocationRef &Reloc) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002028 uint64_t RelocOffset = Reloc.getOffset();
David Blaikie33dd45d02015-03-23 18:39:02 +00002029 return RelocOffset == sect_offset;
2030 });
2031
2032 if (Reloc == info->S.relocations().end())
2033 return 0;
2034
2035 Rel = Reloc->getRawDataRefImpl();
2036 RE = info->O->getRelocation(Rel);
2037 r_length = info->O->getAnyRelocationLength(RE);
2038 r_scattered = info->O->isRelocationScattered(RE);
2039 if (r_scattered) {
2040 r_value = info->O->getScatteredRelocationValue(RE);
2041 r_type = info->O->getScatteredRelocationType(RE);
2042 } else {
2043 r_type = info->O->getAnyRelocationType(RE);
2044 isExtern = info->O->getPlainRelocationExternal(RE);
2045 if (isExtern) {
2046 symbol_iterator RelocSym = Reloc->getSymbol();
2047 Symbol = *RelocSym;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002048 }
2049 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002050 if (r_type == MachO::ARM_RELOC_HALF ||
2051 r_type == MachO::ARM_RELOC_SECTDIFF ||
2052 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
2053 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2054 DataRefImpl RelNext = Rel;
2055 info->O->moveRelocationNext(RelNext);
2056 MachO::any_relocation_info RENext;
2057 RENext = info->O->getRelocation(RelNext);
2058 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2059 if (info->O->isRelocationScattered(RENext))
2060 pair_r_value = info->O->getScatteredRelocationValue(RENext);
2061 }
2062
2063 if (isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002064 Expected<StringRef> SymName = Symbol.getName();
2065 if (!SymName) {
2066 std::string Buf;
2067 raw_string_ostream OS(Buf);
2068 logAllUnhandledErrors(SymName.takeError(), OS, "");
2069 OS.flush();
2070 report_fatal_error(Buf);
2071 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002072 const char *name = SymName->data();
Kevin Enderby930fdc72014-11-06 19:00:13 +00002073 op_info->AddSymbol.Present = 1;
2074 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002075 switch (r_type) {
2076 case MachO::ARM_RELOC_HALF:
2077 if ((r_length & 0x1) == 1) {
2078 op_info->Value = value << 16 | other_half;
2079 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2080 } else {
2081 op_info->Value = other_half << 16 | value;
2082 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00002083 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002084 break;
2085 default:
2086 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002087 }
2088 return 1;
2089 }
2090 // If we have a branch that is not an external relocation entry then
2091 // return 0 so the code in tryAddingSymbolicOperand() can use the
2092 // SymbolLookUp call back with the branch target address to look up the
2093 // symbol and possiblity add an annotation for a symbol stub.
David Blaikie33dd45d02015-03-23 18:39:02 +00002094 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2095 r_type == MachO::ARM_THUMB_RELOC_BR22))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002096 return 0;
2097
2098 uint32_t offset = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002099 if (r_type == MachO::ARM_RELOC_HALF ||
2100 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2101 if ((r_length & 0x1) == 1)
2102 value = value << 16 | other_half;
2103 else
2104 value = other_half << 16 | value;
2105 }
2106 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2107 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2108 offset = value - r_value;
2109 value = r_value;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002110 }
2111
David Blaikie33dd45d02015-03-23 18:39:02 +00002112 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002113 if ((r_length & 0x1) == 1)
2114 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2115 else
2116 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002117 const char *add = GuessSymbolName(r_value, info->AddrMap);
2118 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002119 int32_t offset = value - (r_value - pair_r_value);
2120 op_info->AddSymbol.Present = 1;
2121 if (add != nullptr)
2122 op_info->AddSymbol.Name = add;
2123 else
2124 op_info->AddSymbol.Value = r_value;
2125 op_info->SubtractSymbol.Present = 1;
2126 if (sub != nullptr)
2127 op_info->SubtractSymbol.Name = sub;
2128 else
2129 op_info->SubtractSymbol.Value = pair_r_value;
2130 op_info->Value = offset;
2131 return 1;
2132 }
2133
Kevin Enderby930fdc72014-11-06 19:00:13 +00002134 op_info->AddSymbol.Present = 1;
2135 op_info->Value = offset;
David Blaikie33dd45d02015-03-23 18:39:02 +00002136 if (r_type == MachO::ARM_RELOC_HALF) {
2137 if ((r_length & 0x1) == 1)
2138 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2139 else
2140 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002141 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002142 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002143 if (add != nullptr) {
2144 op_info->AddSymbol.Name = add;
2145 return 1;
2146 }
2147 op_info->AddSymbol.Value = value;
2148 return 1;
David Blaikie33dd45d02015-03-23 18:39:02 +00002149 }
2150 if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002151 if (Offset != 0 || Size != 4)
2152 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002153 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2154 // TODO:
2155 // Search the external relocation entries of a fully linked image
2156 // (if any) for an entry that matches this segment offset.
2157 // uint64_t seg_offset = (Pc + Offset);
2158 return 0;
2159 }
2160 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2161 // for an entry for this section offset.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002162 uint64_t sect_addr = info->S.getAddress();
2163 uint64_t sect_offset = (Pc + Offset) - sect_addr;
David Blaikie33dd45d02015-03-23 18:39:02 +00002164 auto Reloc =
2165 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
2166 [&](const RelocationRef &Reloc) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002167 uint64_t RelocOffset = Reloc.getOffset();
David Blaikie33dd45d02015-03-23 18:39:02 +00002168 return RelocOffset == sect_offset;
2169 });
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002170
David Blaikie33dd45d02015-03-23 18:39:02 +00002171 if (Reloc == info->S.relocations().end())
2172 return 0;
2173
2174 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2175 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2176 uint32_t r_type = info->O->getAnyRelocationType(RE);
2177 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2178 DataRefImpl RelNext = Rel;
2179 info->O->moveRelocationNext(RelNext);
2180 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2181 if (value == 0) {
2182 value = info->O->getPlainRelocationSymbolNum(RENext);
2183 op_info->Value = value;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002184 }
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002185 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002186 // NOTE: Scattered relocations don't exist on arm64.
2187 if (!info->O->getPlainRelocationExternal(RE))
2188 return 0;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002189 Expected<StringRef> SymName = Reloc->getSymbol()->getName();
2190 if (!SymName) {
2191 std::string Buf;
2192 raw_string_ostream OS(Buf);
2193 logAllUnhandledErrors(SymName.takeError(), OS, "");
2194 OS.flush();
2195 report_fatal_error(Buf);
2196 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002197 const char *name = SymName->data();
David Blaikie33dd45d02015-03-23 18:39:02 +00002198 op_info->AddSymbol.Present = 1;
2199 op_info->AddSymbol.Name = name;
2200
2201 switch (r_type) {
2202 case MachO::ARM64_RELOC_PAGE21:
2203 /* @page */
2204 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2205 break;
2206 case MachO::ARM64_RELOC_PAGEOFF12:
2207 /* @pageoff */
2208 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2209 break;
2210 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2211 /* @gotpage */
2212 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2213 break;
2214 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2215 /* @gotpageoff */
2216 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2217 break;
2218 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2219 /* @tvlppage is not implemented in llvm-mc */
2220 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2221 break;
2222 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2223 /* @tvlppageoff is not implemented in llvm-mc */
2224 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2225 break;
2226 default:
2227 case MachO::ARM64_RELOC_BRANCH26:
2228 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2229 break;
2230 }
2231 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002232 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002233 return 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002234}
2235
Kevin Enderbybf246f52014-09-24 23:08:22 +00002236// GuessCstringPointer is passed the address of what might be a pointer to a
2237// literal string in a cstring section. If that address is in a cstring section
2238// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002239static const char *GuessCstringPointer(uint64_t ReferenceValue,
2240 struct DisassembleInfo *info) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002241 for (const auto &Load : info->O->load_commands()) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002242 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2243 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2244 for (unsigned J = 0; J < Seg.nsects; ++J) {
2245 MachO::section_64 Sec = info->O->getSection64(Load, J);
2246 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2247 if (section_type == MachO::S_CSTRING_LITERALS &&
2248 ReferenceValue >= Sec.addr &&
2249 ReferenceValue < Sec.addr + Sec.size) {
2250 uint64_t sect_offset = ReferenceValue - Sec.addr;
2251 uint64_t object_offset = Sec.offset + sect_offset;
2252 StringRef MachOContents = info->O->getData();
2253 uint64_t object_size = MachOContents.size();
2254 const char *object_addr = (const char *)MachOContents.data();
2255 if (object_offset < object_size) {
2256 const char *name = object_addr + object_offset;
2257 return name;
2258 } else {
2259 return nullptr;
2260 }
2261 }
2262 }
2263 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2264 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2265 for (unsigned J = 0; J < Seg.nsects; ++J) {
2266 MachO::section Sec = info->O->getSection(Load, J);
2267 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2268 if (section_type == MachO::S_CSTRING_LITERALS &&
2269 ReferenceValue >= Sec.addr &&
2270 ReferenceValue < Sec.addr + Sec.size) {
2271 uint64_t sect_offset = ReferenceValue - Sec.addr;
2272 uint64_t object_offset = Sec.offset + sect_offset;
2273 StringRef MachOContents = info->O->getData();
2274 uint64_t object_size = MachOContents.size();
2275 const char *object_addr = (const char *)MachOContents.data();
2276 if (object_offset < object_size) {
2277 const char *name = object_addr + object_offset;
2278 return name;
2279 } else {
2280 return nullptr;
2281 }
2282 }
2283 }
2284 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002285 }
2286 return nullptr;
2287}
2288
Kevin Enderby85974882014-09-26 22:20:44 +00002289// GuessIndirectSymbol returns the name of the indirect symbol for the
2290// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2291// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2292// symbol name being referenced by the stub or pointer.
2293static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2294 struct DisassembleInfo *info) {
Kevin Enderby85974882014-09-26 22:20:44 +00002295 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2296 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002297 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby85974882014-09-26 22:20:44 +00002298 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2299 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2300 for (unsigned J = 0; J < Seg.nsects; ++J) {
2301 MachO::section_64 Sec = info->O->getSection64(Load, J);
2302 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2303 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2304 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2305 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2306 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2307 section_type == MachO::S_SYMBOL_STUBS) &&
2308 ReferenceValue >= Sec.addr &&
2309 ReferenceValue < Sec.addr + Sec.size) {
2310 uint32_t stride;
2311 if (section_type == MachO::S_SYMBOL_STUBS)
2312 stride = Sec.reserved2;
2313 else
2314 stride = 8;
2315 if (stride == 0)
2316 return nullptr;
2317 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2318 if (index < Dysymtab.nindirectsyms) {
2319 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002320 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002321 if (indirect_symbol < Symtab.nsyms) {
2322 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2323 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002324 Expected<StringRef> SymName = Symbol.getName();
2325 if (!SymName) {
2326 std::string Buf;
2327 raw_string_ostream OS(Buf);
2328 logAllUnhandledErrors(SymName.takeError(), OS, "");
2329 OS.flush();
2330 report_fatal_error(Buf);
2331 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002332 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002333 return name;
2334 }
2335 }
2336 }
2337 }
2338 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2339 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2340 for (unsigned J = 0; J < Seg.nsects; ++J) {
2341 MachO::section Sec = info->O->getSection(Load, J);
2342 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2343 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2344 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2345 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2346 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2347 section_type == MachO::S_SYMBOL_STUBS) &&
2348 ReferenceValue >= Sec.addr &&
2349 ReferenceValue < Sec.addr + Sec.size) {
2350 uint32_t stride;
2351 if (section_type == MachO::S_SYMBOL_STUBS)
2352 stride = Sec.reserved2;
2353 else
2354 stride = 4;
2355 if (stride == 0)
2356 return nullptr;
2357 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2358 if (index < Dysymtab.nindirectsyms) {
2359 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002360 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002361 if (indirect_symbol < Symtab.nsyms) {
2362 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2363 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002364 Expected<StringRef> SymName = Symbol.getName();
2365 if (!SymName) {
2366 std::string Buf;
2367 raw_string_ostream OS(Buf);
2368 logAllUnhandledErrors(SymName.takeError(), OS, "");
2369 OS.flush();
2370 report_fatal_error(Buf);
2371 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002372 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002373 return name;
2374 }
2375 }
2376 }
2377 }
2378 }
Kevin Enderby85974882014-09-26 22:20:44 +00002379 }
2380 return nullptr;
2381}
2382
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002383// method_reference() is called passing it the ReferenceName that might be
2384// a reference it to an Objective-C method call. If so then it allocates and
2385// assembles a method call string with the values last seen and saved in
2386// the DisassembleInfo's class_name and selector_name fields. This is saved
2387// into the method field of the info and any previous string is free'ed.
2388// Then the class_name field in the info is set to nullptr. The method call
2389// string is set into ReferenceName and ReferenceType is set to
2390// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2391// then both ReferenceType and ReferenceName are left unchanged.
2392static void method_reference(struct DisassembleInfo *info,
2393 uint64_t *ReferenceType,
2394 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002395 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002396 if (*ReferenceName != nullptr) {
2397 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002398 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002399 if (info->method != nullptr)
2400 free(info->method);
2401 if (info->class_name != nullptr) {
2402 info->method = (char *)malloc(5 + strlen(info->class_name) +
2403 strlen(info->selector_name));
2404 if (info->method != nullptr) {
2405 strcpy(info->method, "+[");
2406 strcat(info->method, info->class_name);
2407 strcat(info->method, " ");
2408 strcat(info->method, info->selector_name);
2409 strcat(info->method, "]");
2410 *ReferenceName = info->method;
2411 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2412 }
2413 } else {
2414 info->method = (char *)malloc(9 + strlen(info->selector_name));
2415 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002416 if (Arch == Triple::x86_64)
2417 strcpy(info->method, "-[%rdi ");
2418 else if (Arch == Triple::aarch64)
2419 strcpy(info->method, "-[x0 ");
2420 else
2421 strcpy(info->method, "-[r? ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002422 strcat(info->method, info->selector_name);
2423 strcat(info->method, "]");
2424 *ReferenceName = info->method;
2425 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2426 }
2427 }
2428 info->class_name = nullptr;
2429 }
2430 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002431 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002432 if (info->method != nullptr)
2433 free(info->method);
2434 info->method = (char *)malloc(17 + strlen(info->selector_name));
2435 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002436 if (Arch == Triple::x86_64)
2437 strcpy(info->method, "-[[%rdi super] ");
2438 else if (Arch == Triple::aarch64)
2439 strcpy(info->method, "-[[x0 super] ");
2440 else
2441 strcpy(info->method, "-[[r? super] ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002442 strcat(info->method, info->selector_name);
2443 strcat(info->method, "]");
2444 *ReferenceName = info->method;
2445 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2446 }
2447 info->class_name = nullptr;
2448 }
2449 }
2450 }
2451}
2452
2453// GuessPointerPointer() is passed the address of what might be a pointer to
2454// a reference to an Objective-C class, selector, message ref or cfstring.
2455// If so the value of the pointer is returned and one of the booleans are set
2456// to true. If not zero is returned and all the booleans are set to false.
2457static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2458 struct DisassembleInfo *info,
2459 bool &classref, bool &selref, bool &msgref,
2460 bool &cfstring) {
2461 classref = false;
2462 selref = false;
2463 msgref = false;
2464 cfstring = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002465 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002466 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2467 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2468 for (unsigned J = 0; J < Seg.nsects; ++J) {
2469 MachO::section_64 Sec = info->O->getSection64(Load, J);
2470 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2471 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2472 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2473 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2474 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2475 ReferenceValue >= Sec.addr &&
2476 ReferenceValue < Sec.addr + Sec.size) {
2477 uint64_t sect_offset = ReferenceValue - Sec.addr;
2478 uint64_t object_offset = Sec.offset + sect_offset;
2479 StringRef MachOContents = info->O->getData();
2480 uint64_t object_size = MachOContents.size();
2481 const char *object_addr = (const char *)MachOContents.data();
2482 if (object_offset < object_size) {
2483 uint64_t pointer_value;
2484 memcpy(&pointer_value, object_addr + object_offset,
2485 sizeof(uint64_t));
2486 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2487 sys::swapByteOrder(pointer_value);
2488 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2489 selref = true;
2490 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2491 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2492 classref = true;
2493 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2494 ReferenceValue + 8 < Sec.addr + Sec.size) {
2495 msgref = true;
2496 memcpy(&pointer_value, object_addr + object_offset + 8,
2497 sizeof(uint64_t));
2498 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2499 sys::swapByteOrder(pointer_value);
2500 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2501 cfstring = true;
2502 return pointer_value;
2503 } else {
2504 return 0;
2505 }
2506 }
2507 }
2508 }
2509 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002510 }
2511 return 0;
2512}
2513
2514// get_pointer_64 returns a pointer to the bytes in the object file at the
2515// Address from a section in the Mach-O file. And indirectly returns the
2516// offset into the section, number of bytes left in the section past the offset
2517// and which section is was being referenced. If the Address is not in a
2518// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002519static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2520 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002521 DisassembleInfo *info,
2522 bool objc_only = false) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002523 offset = 0;
2524 left = 0;
2525 S = SectionRef();
2526 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2527 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2528 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
Kevin Enderby46e642f2015-10-08 22:50:55 +00002529 if (SectSize == 0)
2530 continue;
Kevin Enderby846c0002015-04-16 17:19:59 +00002531 if (objc_only) {
2532 StringRef SectName;
2533 ((*(info->Sections))[SectIdx]).getName(SectName);
2534 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2535 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2536 if (SegName != "__OBJC" && SectName != "__cstring")
2537 continue;
2538 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002539 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2540 S = (*(info->Sections))[SectIdx];
2541 offset = Address - SectAddress;
2542 left = SectSize - offset;
2543 StringRef SectContents;
2544 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2545 return SectContents.data() + offset;
2546 }
2547 }
2548 return nullptr;
2549}
2550
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002551static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2552 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002553 DisassembleInfo *info,
2554 bool objc_only = false) {
2555 return get_pointer_64(Address, offset, left, S, info, objc_only);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002556}
2557
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002558// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2559// the symbol indirectly through n_value. Based on the relocation information
2560// for the specified section offset in the specified section reference.
Kevin Enderby0fc11822015-04-01 20:57:01 +00002561// If no relocation information is found and a non-zero ReferenceValue for the
2562// symbol is passed, look up that address in the info's AddrMap.
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00002563static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2564 DisassembleInfo *info, uint64_t &n_value,
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002565 uint64_t ReferenceValue = 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002566 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002567 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002568 return nullptr;
2569
2570 // See if there is an external relocation entry at the sect_offset.
2571 bool reloc_found = false;
2572 DataRefImpl Rel;
2573 MachO::any_relocation_info RE;
2574 bool isExtern = false;
2575 SymbolRef Symbol;
2576 for (const RelocationRef &Reloc : S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002577 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002578 if (RelocOffset == sect_offset) {
2579 Rel = Reloc.getRawDataRefImpl();
2580 RE = info->O->getRelocation(Rel);
2581 if (info->O->isRelocationScattered(RE))
2582 continue;
2583 isExtern = info->O->getPlainRelocationExternal(RE);
2584 if (isExtern) {
2585 symbol_iterator RelocSym = Reloc.getSymbol();
2586 Symbol = *RelocSym;
2587 }
2588 reloc_found = true;
2589 break;
2590 }
2591 }
2592 // If there is an external relocation entry for a symbol in this section
2593 // at this section_offset then use that symbol's value for the n_value
2594 // and return its name.
2595 const char *SymbolName = nullptr;
2596 if (reloc_found && isExtern) {
Rafael Espindoladea00162015-07-03 17:44:18 +00002597 n_value = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002598 Expected<StringRef> NameOrError = Symbol.getName();
2599 if (!NameOrError) {
2600 std::string Buf;
2601 raw_string_ostream OS(Buf);
2602 logAllUnhandledErrors(NameOrError.takeError(), OS, "");
2603 OS.flush();
2604 report_fatal_error(Buf);
2605 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002606 StringRef Name = *NameOrError;
2607 if (!Name.empty()) {
2608 SymbolName = Name.data();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002609 return SymbolName;
2610 }
2611 }
2612
2613 // TODO: For fully linked images, look through the external relocation
2614 // entries off the dynamic symtab command. For these the r_offset is from the
2615 // start of the first writeable segment in the Mach-O file. So the offset
2616 // to this section from that segment is passed to this routine by the caller,
2617 // as the database_offset. Which is the difference of the section's starting
2618 // address and the first writable segment.
2619 //
2620 // NOTE: need add passing the database_offset to this routine.
2621
Kevin Enderby0fc11822015-04-01 20:57:01 +00002622 // We did not find an external relocation entry so look up the ReferenceValue
2623 // as an address of a symbol and if found return that symbol's name.
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002624 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002625
2626 return SymbolName;
2627}
2628
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002629static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
2630 DisassembleInfo *info,
2631 uint32_t ReferenceValue) {
2632 uint64_t n_value64;
2633 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
2634}
2635
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002636// These are structs in the Objective-C meta data and read to produce the
2637// comments for disassembly. While these are part of the ABI they are no
2638// public defintions. So the are here not in include/llvm/Support/MachO.h .
2639
2640// The cfstring object in a 64-bit Mach-O file.
2641struct cfstring64_t {
2642 uint64_t isa; // class64_t * (64-bit pointer)
2643 uint64_t flags; // flag bits
2644 uint64_t characters; // char * (64-bit pointer)
2645 uint64_t length; // number of non-NULL characters in above
2646};
2647
2648// The class object in a 64-bit Mach-O file.
2649struct class64_t {
2650 uint64_t isa; // class64_t * (64-bit pointer)
2651 uint64_t superclass; // class64_t * (64-bit pointer)
2652 uint64_t cache; // Cache (64-bit pointer)
2653 uint64_t vtable; // IMP * (64-bit pointer)
2654 uint64_t data; // class_ro64_t * (64-bit pointer)
2655};
2656
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002657struct class32_t {
2658 uint32_t isa; /* class32_t * (32-bit pointer) */
2659 uint32_t superclass; /* class32_t * (32-bit pointer) */
2660 uint32_t cache; /* Cache (32-bit pointer) */
2661 uint32_t vtable; /* IMP * (32-bit pointer) */
2662 uint32_t data; /* class_ro32_t * (32-bit pointer) */
2663};
2664
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002665struct class_ro64_t {
2666 uint32_t flags;
2667 uint32_t instanceStart;
2668 uint32_t instanceSize;
2669 uint32_t reserved;
2670 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2671 uint64_t name; // const char * (64-bit pointer)
2672 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2673 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2674 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2675 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2676 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2677};
2678
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002679struct class_ro32_t {
2680 uint32_t flags;
2681 uint32_t instanceStart;
2682 uint32_t instanceSize;
2683 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
2684 uint32_t name; /* const char * (32-bit pointer) */
2685 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
2686 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
2687 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
2688 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
2689 uint32_t baseProperties; /* const struct objc_property_list *
2690 (32-bit pointer) */
2691};
2692
2693/* Values for class_ro{64,32}_t->flags */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002694#define RO_META (1 << 0)
2695#define RO_ROOT (1 << 1)
2696#define RO_HAS_CXX_STRUCTORS (1 << 2)
2697
2698struct method_list64_t {
2699 uint32_t entsize;
2700 uint32_t count;
2701 /* struct method64_t first; These structures follow inline */
2702};
2703
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002704struct method_list32_t {
2705 uint32_t entsize;
2706 uint32_t count;
2707 /* struct method32_t first; These structures follow inline */
2708};
2709
Kevin Enderby0fc11822015-04-01 20:57:01 +00002710struct method64_t {
2711 uint64_t name; /* SEL (64-bit pointer) */
2712 uint64_t types; /* const char * (64-bit pointer) */
2713 uint64_t imp; /* IMP (64-bit pointer) */
2714};
2715
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002716struct method32_t {
2717 uint32_t name; /* SEL (32-bit pointer) */
2718 uint32_t types; /* const char * (32-bit pointer) */
2719 uint32_t imp; /* IMP (32-bit pointer) */
2720};
2721
Kevin Enderby0fc11822015-04-01 20:57:01 +00002722struct protocol_list64_t {
2723 uint64_t count; /* uintptr_t (a 64-bit value) */
2724 /* struct protocol64_t * list[0]; These pointers follow inline */
2725};
2726
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002727struct protocol_list32_t {
2728 uint32_t count; /* uintptr_t (a 32-bit value) */
2729 /* struct protocol32_t * list[0]; These pointers follow inline */
2730};
2731
Kevin Enderby0fc11822015-04-01 20:57:01 +00002732struct protocol64_t {
2733 uint64_t isa; /* id * (64-bit pointer) */
2734 uint64_t name; /* const char * (64-bit pointer) */
2735 uint64_t protocols; /* struct protocol_list64_t *
2736 (64-bit pointer) */
2737 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
2738 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
2739 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
2740 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
2741 uint64_t instanceProperties; /* struct objc_property_list *
2742 (64-bit pointer) */
2743};
2744
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002745struct protocol32_t {
2746 uint32_t isa; /* id * (32-bit pointer) */
2747 uint32_t name; /* const char * (32-bit pointer) */
2748 uint32_t protocols; /* struct protocol_list_t *
2749 (32-bit pointer) */
2750 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
2751 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
2752 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
2753 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
2754 uint32_t instanceProperties; /* struct objc_property_list *
2755 (32-bit pointer) */
2756};
2757
Kevin Enderby0fc11822015-04-01 20:57:01 +00002758struct ivar_list64_t {
2759 uint32_t entsize;
2760 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002761 /* struct ivar64_t first; These structures follow inline */
2762};
2763
2764struct ivar_list32_t {
2765 uint32_t entsize;
2766 uint32_t count;
2767 /* struct ivar32_t first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002768};
2769
2770struct ivar64_t {
2771 uint64_t offset; /* uintptr_t * (64-bit pointer) */
2772 uint64_t name; /* const char * (64-bit pointer) */
2773 uint64_t type; /* const char * (64-bit pointer) */
2774 uint32_t alignment;
2775 uint32_t size;
2776};
2777
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002778struct ivar32_t {
2779 uint32_t offset; /* uintptr_t * (32-bit pointer) */
2780 uint32_t name; /* const char * (32-bit pointer) */
2781 uint32_t type; /* const char * (32-bit pointer) */
2782 uint32_t alignment;
2783 uint32_t size;
2784};
2785
Kevin Enderby0fc11822015-04-01 20:57:01 +00002786struct objc_property_list64 {
2787 uint32_t entsize;
2788 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002789 /* struct objc_property64 first; These structures follow inline */
2790};
2791
2792struct objc_property_list32 {
2793 uint32_t entsize;
2794 uint32_t count;
2795 /* struct objc_property32 first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002796};
2797
2798struct objc_property64 {
2799 uint64_t name; /* const char * (64-bit pointer) */
2800 uint64_t attributes; /* const char * (64-bit pointer) */
2801};
2802
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002803struct objc_property32 {
2804 uint32_t name; /* const char * (32-bit pointer) */
2805 uint32_t attributes; /* const char * (32-bit pointer) */
2806};
2807
Kevin Enderby0fc11822015-04-01 20:57:01 +00002808struct category64_t {
2809 uint64_t name; /* const char * (64-bit pointer) */
2810 uint64_t cls; /* struct class_t * (64-bit pointer) */
2811 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
2812 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
2813 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
2814 uint64_t instanceProperties; /* struct objc_property_list *
2815 (64-bit pointer) */
2816};
2817
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002818struct category32_t {
2819 uint32_t name; /* const char * (32-bit pointer) */
2820 uint32_t cls; /* struct class_t * (32-bit pointer) */
2821 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
2822 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
2823 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
2824 uint32_t instanceProperties; /* struct objc_property_list *
2825 (32-bit pointer) */
2826};
2827
Kevin Enderby0fc11822015-04-01 20:57:01 +00002828struct objc_image_info64 {
2829 uint32_t version;
2830 uint32_t flags;
2831};
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002832struct objc_image_info32 {
2833 uint32_t version;
2834 uint32_t flags;
2835};
Kevin Enderby846c0002015-04-16 17:19:59 +00002836struct imageInfo_t {
2837 uint32_t version;
2838 uint32_t flags;
2839};
Kevin Enderby0fc11822015-04-01 20:57:01 +00002840/* masks for objc_image_info.flags */
2841#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
2842#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
2843
2844struct message_ref64 {
2845 uint64_t imp; /* IMP (64-bit pointer) */
2846 uint64_t sel; /* SEL (64-bit pointer) */
2847};
2848
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002849struct message_ref32 {
2850 uint32_t imp; /* IMP (32-bit pointer) */
2851 uint32_t sel; /* SEL (32-bit pointer) */
2852};
2853
Kevin Enderby846c0002015-04-16 17:19:59 +00002854// Objective-C 1 (32-bit only) meta data structs.
2855
2856struct objc_module_t {
2857 uint32_t version;
2858 uint32_t size;
2859 uint32_t name; /* char * (32-bit pointer) */
2860 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
2861};
2862
2863struct objc_symtab_t {
2864 uint32_t sel_ref_cnt;
2865 uint32_t refs; /* SEL * (32-bit pointer) */
2866 uint16_t cls_def_cnt;
2867 uint16_t cat_def_cnt;
2868 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
2869};
2870
2871struct objc_class_t {
2872 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2873 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
2874 uint32_t name; /* const char * (32-bit pointer) */
2875 int32_t version;
2876 int32_t info;
2877 int32_t instance_size;
2878 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
2879 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
2880 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
2881 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
2882};
2883
2884#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
2885// class is not a metaclass
2886#define CLS_CLASS 0x1
2887// class is a metaclass
2888#define CLS_META 0x2
2889
2890struct objc_category_t {
2891 uint32_t category_name; /* char * (32-bit pointer) */
2892 uint32_t class_name; /* char * (32-bit pointer) */
2893 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
2894 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
2895 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
2896};
2897
2898struct objc_ivar_t {
2899 uint32_t ivar_name; /* char * (32-bit pointer) */
2900 uint32_t ivar_type; /* char * (32-bit pointer) */
2901 int32_t ivar_offset;
2902};
2903
2904struct objc_ivar_list_t {
2905 int32_t ivar_count;
2906 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
2907};
2908
2909struct objc_method_list_t {
2910 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
2911 int32_t method_count;
2912 // struct objc_method_t method_list[1]; /* variable length structure */
2913};
2914
2915struct objc_method_t {
2916 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2917 uint32_t method_types; /* char * (32-bit pointer) */
2918 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
2919 (32-bit pointer) */
2920};
2921
2922struct objc_protocol_list_t {
2923 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
2924 int32_t count;
2925 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
2926 // (32-bit pointer) */
2927};
2928
2929struct objc_protocol_t {
2930 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2931 uint32_t protocol_name; /* char * (32-bit pointer) */
2932 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
2933 uint32_t instance_methods; /* struct objc_method_description_list *
2934 (32-bit pointer) */
2935 uint32_t class_methods; /* struct objc_method_description_list *
2936 (32-bit pointer) */
2937};
2938
2939struct objc_method_description_list_t {
2940 int32_t count;
2941 // struct objc_method_description_t list[1];
2942};
2943
2944struct objc_method_description_t {
2945 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2946 uint32_t types; /* char * (32-bit pointer) */
2947};
2948
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002949inline void swapStruct(struct cfstring64_t &cfs) {
2950 sys::swapByteOrder(cfs.isa);
2951 sys::swapByteOrder(cfs.flags);
2952 sys::swapByteOrder(cfs.characters);
2953 sys::swapByteOrder(cfs.length);
2954}
2955
2956inline void swapStruct(struct class64_t &c) {
2957 sys::swapByteOrder(c.isa);
2958 sys::swapByteOrder(c.superclass);
2959 sys::swapByteOrder(c.cache);
2960 sys::swapByteOrder(c.vtable);
2961 sys::swapByteOrder(c.data);
2962}
2963
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002964inline void swapStruct(struct class32_t &c) {
2965 sys::swapByteOrder(c.isa);
2966 sys::swapByteOrder(c.superclass);
2967 sys::swapByteOrder(c.cache);
2968 sys::swapByteOrder(c.vtable);
2969 sys::swapByteOrder(c.data);
2970}
2971
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002972inline void swapStruct(struct class_ro64_t &cro) {
2973 sys::swapByteOrder(cro.flags);
2974 sys::swapByteOrder(cro.instanceStart);
2975 sys::swapByteOrder(cro.instanceSize);
2976 sys::swapByteOrder(cro.reserved);
2977 sys::swapByteOrder(cro.ivarLayout);
2978 sys::swapByteOrder(cro.name);
2979 sys::swapByteOrder(cro.baseMethods);
2980 sys::swapByteOrder(cro.baseProtocols);
2981 sys::swapByteOrder(cro.ivars);
2982 sys::swapByteOrder(cro.weakIvarLayout);
2983 sys::swapByteOrder(cro.baseProperties);
2984}
2985
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002986inline void swapStruct(struct class_ro32_t &cro) {
2987 sys::swapByteOrder(cro.flags);
2988 sys::swapByteOrder(cro.instanceStart);
2989 sys::swapByteOrder(cro.instanceSize);
2990 sys::swapByteOrder(cro.ivarLayout);
2991 sys::swapByteOrder(cro.name);
2992 sys::swapByteOrder(cro.baseMethods);
2993 sys::swapByteOrder(cro.baseProtocols);
2994 sys::swapByteOrder(cro.ivars);
2995 sys::swapByteOrder(cro.weakIvarLayout);
2996 sys::swapByteOrder(cro.baseProperties);
2997}
2998
Kevin Enderby0fc11822015-04-01 20:57:01 +00002999inline void swapStruct(struct method_list64_t &ml) {
3000 sys::swapByteOrder(ml.entsize);
3001 sys::swapByteOrder(ml.count);
3002}
3003
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003004inline void swapStruct(struct method_list32_t &ml) {
3005 sys::swapByteOrder(ml.entsize);
3006 sys::swapByteOrder(ml.count);
3007}
3008
Kevin Enderby0fc11822015-04-01 20:57:01 +00003009inline void swapStruct(struct method64_t &m) {
3010 sys::swapByteOrder(m.name);
3011 sys::swapByteOrder(m.types);
3012 sys::swapByteOrder(m.imp);
3013}
3014
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003015inline void swapStruct(struct method32_t &m) {
3016 sys::swapByteOrder(m.name);
3017 sys::swapByteOrder(m.types);
3018 sys::swapByteOrder(m.imp);
3019}
3020
Kevin Enderby0fc11822015-04-01 20:57:01 +00003021inline void swapStruct(struct protocol_list64_t &pl) {
3022 sys::swapByteOrder(pl.count);
3023}
3024
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003025inline void swapStruct(struct protocol_list32_t &pl) {
3026 sys::swapByteOrder(pl.count);
3027}
3028
Kevin Enderby0fc11822015-04-01 20:57:01 +00003029inline void swapStruct(struct protocol64_t &p) {
3030 sys::swapByteOrder(p.isa);
3031 sys::swapByteOrder(p.name);
3032 sys::swapByteOrder(p.protocols);
3033 sys::swapByteOrder(p.instanceMethods);
3034 sys::swapByteOrder(p.classMethods);
3035 sys::swapByteOrder(p.optionalInstanceMethods);
3036 sys::swapByteOrder(p.optionalClassMethods);
3037 sys::swapByteOrder(p.instanceProperties);
3038}
3039
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003040inline void swapStruct(struct protocol32_t &p) {
3041 sys::swapByteOrder(p.isa);
3042 sys::swapByteOrder(p.name);
3043 sys::swapByteOrder(p.protocols);
3044 sys::swapByteOrder(p.instanceMethods);
3045 sys::swapByteOrder(p.classMethods);
3046 sys::swapByteOrder(p.optionalInstanceMethods);
3047 sys::swapByteOrder(p.optionalClassMethods);
3048 sys::swapByteOrder(p.instanceProperties);
3049}
3050
Kevin Enderby0fc11822015-04-01 20:57:01 +00003051inline void swapStruct(struct ivar_list64_t &il) {
3052 sys::swapByteOrder(il.entsize);
3053 sys::swapByteOrder(il.count);
3054}
3055
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003056inline void swapStruct(struct ivar_list32_t &il) {
3057 sys::swapByteOrder(il.entsize);
3058 sys::swapByteOrder(il.count);
3059}
3060
Kevin Enderby0fc11822015-04-01 20:57:01 +00003061inline void swapStruct(struct ivar64_t &i) {
3062 sys::swapByteOrder(i.offset);
3063 sys::swapByteOrder(i.name);
3064 sys::swapByteOrder(i.type);
3065 sys::swapByteOrder(i.alignment);
3066 sys::swapByteOrder(i.size);
3067}
3068
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003069inline void swapStruct(struct ivar32_t &i) {
3070 sys::swapByteOrder(i.offset);
3071 sys::swapByteOrder(i.name);
3072 sys::swapByteOrder(i.type);
3073 sys::swapByteOrder(i.alignment);
3074 sys::swapByteOrder(i.size);
3075}
3076
Kevin Enderby0fc11822015-04-01 20:57:01 +00003077inline void swapStruct(struct objc_property_list64 &pl) {
3078 sys::swapByteOrder(pl.entsize);
3079 sys::swapByteOrder(pl.count);
3080}
3081
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003082inline void swapStruct(struct objc_property_list32 &pl) {
3083 sys::swapByteOrder(pl.entsize);
3084 sys::swapByteOrder(pl.count);
3085}
3086
Kevin Enderby0fc11822015-04-01 20:57:01 +00003087inline void swapStruct(struct objc_property64 &op) {
3088 sys::swapByteOrder(op.name);
3089 sys::swapByteOrder(op.attributes);
3090}
3091
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003092inline void swapStruct(struct objc_property32 &op) {
3093 sys::swapByteOrder(op.name);
3094 sys::swapByteOrder(op.attributes);
3095}
3096
Kevin Enderby0fc11822015-04-01 20:57:01 +00003097inline void swapStruct(struct category64_t &c) {
3098 sys::swapByteOrder(c.name);
3099 sys::swapByteOrder(c.cls);
3100 sys::swapByteOrder(c.instanceMethods);
3101 sys::swapByteOrder(c.classMethods);
3102 sys::swapByteOrder(c.protocols);
3103 sys::swapByteOrder(c.instanceProperties);
3104}
3105
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003106inline void swapStruct(struct category32_t &c) {
3107 sys::swapByteOrder(c.name);
3108 sys::swapByteOrder(c.cls);
3109 sys::swapByteOrder(c.instanceMethods);
3110 sys::swapByteOrder(c.classMethods);
3111 sys::swapByteOrder(c.protocols);
3112 sys::swapByteOrder(c.instanceProperties);
3113}
3114
Kevin Enderby0fc11822015-04-01 20:57:01 +00003115inline void swapStruct(struct objc_image_info64 &o) {
3116 sys::swapByteOrder(o.version);
3117 sys::swapByteOrder(o.flags);
3118}
3119
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003120inline void swapStruct(struct objc_image_info32 &o) {
3121 sys::swapByteOrder(o.version);
3122 sys::swapByteOrder(o.flags);
3123}
3124
Kevin Enderby846c0002015-04-16 17:19:59 +00003125inline void swapStruct(struct imageInfo_t &o) {
3126 sys::swapByteOrder(o.version);
3127 sys::swapByteOrder(o.flags);
3128}
3129
Kevin Enderby0fc11822015-04-01 20:57:01 +00003130inline void swapStruct(struct message_ref64 &mr) {
3131 sys::swapByteOrder(mr.imp);
3132 sys::swapByteOrder(mr.sel);
3133}
3134
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003135inline void swapStruct(struct message_ref32 &mr) {
3136 sys::swapByteOrder(mr.imp);
3137 sys::swapByteOrder(mr.sel);
3138}
3139
Kevin Enderby846c0002015-04-16 17:19:59 +00003140inline void swapStruct(struct objc_module_t &module) {
3141 sys::swapByteOrder(module.version);
3142 sys::swapByteOrder(module.size);
3143 sys::swapByteOrder(module.name);
3144 sys::swapByteOrder(module.symtab);
Jingyue Wufedecc42015-04-16 18:43:44 +00003145}
Kevin Enderby846c0002015-04-16 17:19:59 +00003146
3147inline void swapStruct(struct objc_symtab_t &symtab) {
3148 sys::swapByteOrder(symtab.sel_ref_cnt);
3149 sys::swapByteOrder(symtab.refs);
3150 sys::swapByteOrder(symtab.cls_def_cnt);
3151 sys::swapByteOrder(symtab.cat_def_cnt);
Jingyue Wufedecc42015-04-16 18:43:44 +00003152}
Kevin Enderby846c0002015-04-16 17:19:59 +00003153
3154inline void swapStruct(struct objc_class_t &objc_class) {
3155 sys::swapByteOrder(objc_class.isa);
3156 sys::swapByteOrder(objc_class.super_class);
3157 sys::swapByteOrder(objc_class.name);
3158 sys::swapByteOrder(objc_class.version);
3159 sys::swapByteOrder(objc_class.info);
3160 sys::swapByteOrder(objc_class.instance_size);
3161 sys::swapByteOrder(objc_class.ivars);
3162 sys::swapByteOrder(objc_class.methodLists);
3163 sys::swapByteOrder(objc_class.cache);
3164 sys::swapByteOrder(objc_class.protocols);
Jingyue Wufedecc42015-04-16 18:43:44 +00003165}
Kevin Enderby846c0002015-04-16 17:19:59 +00003166
3167inline void swapStruct(struct objc_category_t &objc_category) {
3168 sys::swapByteOrder(objc_category.category_name);
3169 sys::swapByteOrder(objc_category.class_name);
3170 sys::swapByteOrder(objc_category.instance_methods);
3171 sys::swapByteOrder(objc_category.class_methods);
3172 sys::swapByteOrder(objc_category.protocols);
3173}
3174
3175inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3176 sys::swapByteOrder(objc_ivar_list.ivar_count);
3177}
3178
3179inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3180 sys::swapByteOrder(objc_ivar.ivar_name);
3181 sys::swapByteOrder(objc_ivar.ivar_type);
3182 sys::swapByteOrder(objc_ivar.ivar_offset);
Jingyue Wufedecc42015-04-16 18:43:44 +00003183}
Kevin Enderby846c0002015-04-16 17:19:59 +00003184
3185inline void swapStruct(struct objc_method_list_t &method_list) {
3186 sys::swapByteOrder(method_list.obsolete);
3187 sys::swapByteOrder(method_list.method_count);
3188}
3189
3190inline void swapStruct(struct objc_method_t &method) {
3191 sys::swapByteOrder(method.method_name);
3192 sys::swapByteOrder(method.method_types);
3193 sys::swapByteOrder(method.method_imp);
3194}
3195
3196inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3197 sys::swapByteOrder(protocol_list.next);
3198 sys::swapByteOrder(protocol_list.count);
3199}
3200
3201inline void swapStruct(struct objc_protocol_t &protocol) {
3202 sys::swapByteOrder(protocol.isa);
3203 sys::swapByteOrder(protocol.protocol_name);
3204 sys::swapByteOrder(protocol.protocol_list);
3205 sys::swapByteOrder(protocol.instance_methods);
3206 sys::swapByteOrder(protocol.class_methods);
3207}
3208
3209inline void swapStruct(struct objc_method_description_list_t &mdl) {
3210 sys::swapByteOrder(mdl.count);
3211}
3212
3213inline void swapStruct(struct objc_method_description_t &md) {
3214 sys::swapByteOrder(md.name);
3215 sys::swapByteOrder(md.types);
3216}
3217
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003218static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3219 struct DisassembleInfo *info);
3220
3221// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3222// to an Objective-C class and returns the class name. It is also passed the
3223// address of the pointer, so when the pointer is zero as it can be in an .o
3224// file, that is used to look for an external relocation entry with a symbol
3225// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003226static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3227 uint64_t ReferenceValue,
3228 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003229 const char *r;
3230 uint32_t offset, left;
3231 SectionRef S;
3232
3233 // The pointer_value can be 0 in an object file and have a relocation
3234 // entry for the class symbol at the ReferenceValue (the address of the
3235 // pointer).
3236 if (pointer_value == 0) {
3237 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3238 if (r == nullptr || left < sizeof(uint64_t))
3239 return nullptr;
3240 uint64_t n_value;
3241 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3242 if (symbol_name == nullptr)
3243 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00003244 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003245 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3246 return class_name + 2;
3247 else
3248 return nullptr;
3249 }
3250
3251 // The case were the pointer_value is non-zero and points to a class defined
3252 // in this Mach-O file.
3253 r = get_pointer_64(pointer_value, offset, left, S, info);
3254 if (r == nullptr || left < sizeof(struct class64_t))
3255 return nullptr;
3256 struct class64_t c;
3257 memcpy(&c, r, sizeof(struct class64_t));
3258 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3259 swapStruct(c);
3260 if (c.data == 0)
3261 return nullptr;
3262 r = get_pointer_64(c.data, offset, left, S, info);
3263 if (r == nullptr || left < sizeof(struct class_ro64_t))
3264 return nullptr;
3265 struct class_ro64_t cro;
3266 memcpy(&cro, r, sizeof(struct class_ro64_t));
3267 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3268 swapStruct(cro);
3269 if (cro.name == 0)
3270 return nullptr;
3271 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3272 return name;
3273}
3274
3275// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3276// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003277static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3278 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003279 const char *r, *name;
3280 uint32_t offset, left;
3281 SectionRef S;
3282 struct cfstring64_t cfs;
3283 uint64_t cfs_characters;
3284
3285 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3286 if (r == nullptr || left < sizeof(struct cfstring64_t))
3287 return nullptr;
3288 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3289 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3290 swapStruct(cfs);
3291 if (cfs.characters == 0) {
3292 uint64_t n_value;
3293 const char *symbol_name = get_symbol_64(
3294 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3295 if (symbol_name == nullptr)
3296 return nullptr;
3297 cfs_characters = n_value;
3298 } else
3299 cfs_characters = cfs.characters;
3300 name = get_pointer_64(cfs_characters, offset, left, S, info);
3301
3302 return name;
3303}
3304
3305// get_objc2_64bit_selref() is used for disassembly and is passed a the address
3306// of a pointer to an Objective-C selector reference when the pointer value is
3307// zero as in a .o file and is likely to have a external relocation entry with
3308// who's symbol's n_value is the real pointer to the selector name. If that is
3309// the case the real pointer to the selector name is returned else 0 is
3310// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003311static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3312 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003313 uint32_t offset, left;
3314 SectionRef S;
3315
3316 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3317 if (r == nullptr || left < sizeof(uint64_t))
3318 return 0;
3319 uint64_t n_value;
3320 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3321 if (symbol_name == nullptr)
3322 return 0;
3323 return n_value;
3324}
3325
Kevin Enderby0fc11822015-04-01 20:57:01 +00003326static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3327 const char *sectname) {
3328 for (const SectionRef &Section : O->sections()) {
3329 StringRef SectName;
3330 Section.getName(SectName);
3331 DataRefImpl Ref = Section.getRawDataRefImpl();
3332 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3333 if (SegName == segname && SectName == sectname)
3334 return Section;
3335 }
3336 return SectionRef();
3337}
3338
3339static void
3340walk_pointer_list_64(const char *listname, const SectionRef S,
3341 MachOObjectFile *O, struct DisassembleInfo *info,
3342 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3343 if (S == SectionRef())
3344 return;
3345
3346 StringRef SectName;
3347 S.getName(SectName);
3348 DataRefImpl Ref = S.getRawDataRefImpl();
3349 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3350 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3351
3352 StringRef BytesStr;
3353 S.getContents(BytesStr);
3354 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3355
3356 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3357 uint32_t left = S.getSize() - i;
3358 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3359 uint64_t p = 0;
3360 memcpy(&p, Contents + i, size);
3361 if (i + sizeof(uint64_t) > S.getSize())
3362 outs() << listname << " list pointer extends past end of (" << SegName
3363 << "," << SectName << ") section\n";
3364 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3365
3366 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3367 sys::swapByteOrder(p);
3368
3369 uint64_t n_value = 0;
3370 const char *name = get_symbol_64(i, S, info, n_value, p);
3371 if (name == nullptr)
3372 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3373
3374 if (n_value != 0) {
3375 outs() << format("0x%" PRIx64, n_value);
3376 if (p != 0)
3377 outs() << " + " << format("0x%" PRIx64, p);
3378 } else
3379 outs() << format("0x%" PRIx64, p);
3380 if (name != nullptr)
3381 outs() << " " << name;
3382 outs() << "\n";
3383
3384 p += n_value;
3385 if (func)
3386 func(p, info);
3387 }
3388}
3389
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003390static void
3391walk_pointer_list_32(const char *listname, const SectionRef S,
3392 MachOObjectFile *O, struct DisassembleInfo *info,
3393 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3394 if (S == SectionRef())
3395 return;
3396
3397 StringRef SectName;
3398 S.getName(SectName);
3399 DataRefImpl Ref = S.getRawDataRefImpl();
3400 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3401 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3402
3403 StringRef BytesStr;
3404 S.getContents(BytesStr);
3405 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3406
3407 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3408 uint32_t left = S.getSize() - i;
3409 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3410 uint32_t p = 0;
3411 memcpy(&p, Contents + i, size);
3412 if (i + sizeof(uint32_t) > S.getSize())
3413 outs() << listname << " list pointer extends past end of (" << SegName
3414 << "," << SectName << ") section\n";
Kevin Enderbycf261312015-04-06 22:33:43 +00003415 uint32_t Address = S.getAddress() + i;
3416 outs() << format("%08" PRIx32, Address) << " ";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003417
3418 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3419 sys::swapByteOrder(p);
3420 outs() << format("0x%" PRIx32, p);
3421
3422 const char *name = get_symbol_32(i, S, info, p);
3423 if (name != nullptr)
3424 outs() << " " << name;
3425 outs() << "\n";
3426
3427 if (func)
3428 func(p, info);
3429 }
3430}
3431
3432static void print_layout_map(const char *layout_map, uint32_t left) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003433 if (layout_map == nullptr)
3434 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003435 outs() << " layout map: ";
3436 do {
3437 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3438 left--;
3439 layout_map++;
3440 } while (*layout_map != '\0' && left != 0);
3441 outs() << "\n";
3442}
3443
Kevin Enderby0fc11822015-04-01 20:57:01 +00003444static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3445 uint32_t offset, left;
3446 SectionRef S;
3447 const char *layout_map;
3448
3449 if (p == 0)
3450 return;
3451 layout_map = get_pointer_64(p, offset, left, S, info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003452 print_layout_map(layout_map, left);
3453}
3454
3455static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3456 uint32_t offset, left;
3457 SectionRef S;
3458 const char *layout_map;
3459
3460 if (p == 0)
3461 return;
3462 layout_map = get_pointer_32(p, offset, left, S, info);
3463 print_layout_map(layout_map, left);
Kevin Enderby0fc11822015-04-01 20:57:01 +00003464}
3465
3466static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3467 const char *indent) {
3468 struct method_list64_t ml;
3469 struct method64_t m;
3470 const char *r;
3471 uint32_t offset, xoffset, left, i;
3472 SectionRef S, xS;
3473 const char *name, *sym_name;
3474 uint64_t n_value;
3475
3476 r = get_pointer_64(p, offset, left, S, info);
3477 if (r == nullptr)
3478 return;
3479 memset(&ml, '\0', sizeof(struct method_list64_t));
3480 if (left < sizeof(struct method_list64_t)) {
3481 memcpy(&ml, r, left);
3482 outs() << " (method_list_t entends past the end of the section)\n";
3483 } else
3484 memcpy(&ml, r, sizeof(struct method_list64_t));
3485 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3486 swapStruct(ml);
3487 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3488 outs() << indent << "\t\t count " << ml.count << "\n";
3489
3490 p += sizeof(struct method_list64_t);
3491 offset += sizeof(struct method_list64_t);
3492 for (i = 0; i < ml.count; i++) {
3493 r = get_pointer_64(p, offset, left, S, info);
3494 if (r == nullptr)
3495 return;
3496 memset(&m, '\0', sizeof(struct method64_t));
3497 if (left < sizeof(struct method64_t)) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003498 memcpy(&m, r, left);
3499 outs() << indent << " (method_t extends past the end of the section)\n";
Kevin Enderby0fc11822015-04-01 20:57:01 +00003500 } else
3501 memcpy(&m, r, sizeof(struct method64_t));
3502 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3503 swapStruct(m);
3504
3505 outs() << indent << "\t\t name ";
3506 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3507 info, n_value, m.name);
3508 if (n_value != 0) {
3509 if (info->verbose && sym_name != nullptr)
3510 outs() << sym_name;
3511 else
3512 outs() << format("0x%" PRIx64, n_value);
3513 if (m.name != 0)
3514 outs() << " + " << format("0x%" PRIx64, m.name);
3515 } else
3516 outs() << format("0x%" PRIx64, m.name);
3517 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3518 if (name != nullptr)
3519 outs() << format(" %.*s", left, name);
3520 outs() << "\n";
3521
3522 outs() << indent << "\t\t types ";
3523 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3524 info, n_value, m.types);
3525 if (n_value != 0) {
3526 if (info->verbose && sym_name != nullptr)
3527 outs() << sym_name;
3528 else
3529 outs() << format("0x%" PRIx64, n_value);
3530 if (m.types != 0)
3531 outs() << " + " << format("0x%" PRIx64, m.types);
3532 } else
3533 outs() << format("0x%" PRIx64, m.types);
3534 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3535 if (name != nullptr)
3536 outs() << format(" %.*s", left, name);
3537 outs() << "\n";
3538
3539 outs() << indent << "\t\t imp ";
3540 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3541 n_value, m.imp);
3542 if (info->verbose && name == nullptr) {
3543 if (n_value != 0) {
3544 outs() << format("0x%" PRIx64, n_value) << " ";
3545 if (m.imp != 0)
3546 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3547 } else
3548 outs() << format("0x%" PRIx64, m.imp) << " ";
3549 }
3550 if (name != nullptr)
3551 outs() << name;
3552 outs() << "\n";
3553
3554 p += sizeof(struct method64_t);
3555 offset += sizeof(struct method64_t);
3556 }
3557}
3558
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003559static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3560 const char *indent) {
3561 struct method_list32_t ml;
3562 struct method32_t m;
Kevin Enderby846c0002015-04-16 17:19:59 +00003563 const char *r, *name;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003564 uint32_t offset, xoffset, left, i;
3565 SectionRef S, xS;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003566
3567 r = get_pointer_32(p, offset, left, S, info);
3568 if (r == nullptr)
3569 return;
3570 memset(&ml, '\0', sizeof(struct method_list32_t));
3571 if (left < sizeof(struct method_list32_t)) {
3572 memcpy(&ml, r, left);
3573 outs() << " (method_list_t entends past the end of the section)\n";
3574 } else
3575 memcpy(&ml, r, sizeof(struct method_list32_t));
3576 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3577 swapStruct(ml);
3578 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3579 outs() << indent << "\t\t count " << ml.count << "\n";
3580
3581 p += sizeof(struct method_list32_t);
3582 offset += sizeof(struct method_list32_t);
3583 for (i = 0; i < ml.count; i++) {
3584 r = get_pointer_32(p, offset, left, S, info);
3585 if (r == nullptr)
3586 return;
3587 memset(&m, '\0', sizeof(struct method32_t));
3588 if (left < sizeof(struct method32_t)) {
3589 memcpy(&ml, r, left);
3590 outs() << indent << " (method_t entends past the end of the section)\n";
3591 } else
3592 memcpy(&m, r, sizeof(struct method32_t));
3593 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3594 swapStruct(m);
3595
3596 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
3597 name = get_pointer_32(m.name, xoffset, left, xS, info);
3598 if (name != nullptr)
3599 outs() << format(" %.*s", left, name);
3600 outs() << "\n";
3601
3602 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
3603 name = get_pointer_32(m.types, xoffset, left, xS, info);
3604 if (name != nullptr)
3605 outs() << format(" %.*s", left, name);
3606 outs() << "\n";
3607
3608 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
3609 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
3610 m.imp);
3611 if (name != nullptr)
3612 outs() << " " << name;
3613 outs() << "\n";
3614
3615 p += sizeof(struct method32_t);
3616 offset += sizeof(struct method32_t);
3617 }
3618}
3619
Kevin Enderby846c0002015-04-16 17:19:59 +00003620static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
3621 uint32_t offset, left, xleft;
3622 SectionRef S;
3623 struct objc_method_list_t method_list;
3624 struct objc_method_t method;
3625 const char *r, *methods, *name, *SymbolName;
3626 int32_t i;
3627
3628 r = get_pointer_32(p, offset, left, S, info, true);
3629 if (r == nullptr)
3630 return true;
3631
3632 outs() << "\n";
3633 if (left > sizeof(struct objc_method_list_t)) {
3634 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
3635 } else {
3636 outs() << "\t\t objc_method_list extends past end of the section\n";
3637 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
3638 memcpy(&method_list, r, left);
3639 }
3640 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3641 swapStruct(method_list);
3642
3643 outs() << "\t\t obsolete "
3644 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
3645 outs() << "\t\t method_count " << method_list.method_count << "\n";
3646
3647 methods = r + sizeof(struct objc_method_list_t);
3648 for (i = 0; i < method_list.method_count; i++) {
3649 if ((i + 1) * sizeof(struct objc_method_t) > left) {
3650 outs() << "\t\t remaining method's extend past the of the section\n";
3651 break;
3652 }
3653 memcpy(&method, methods + i * sizeof(struct objc_method_t),
3654 sizeof(struct objc_method_t));
3655 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3656 swapStruct(method);
3657
3658 outs() << "\t\t method_name "
3659 << format("0x%08" PRIx32, method.method_name);
3660 if (info->verbose) {
3661 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
3662 if (name != nullptr)
3663 outs() << format(" %.*s", xleft, name);
3664 else
3665 outs() << " (not in an __OBJC section)";
3666 }
3667 outs() << "\n";
3668
3669 outs() << "\t\t method_types "
3670 << format("0x%08" PRIx32, method.method_types);
3671 if (info->verbose) {
3672 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
3673 if (name != nullptr)
3674 outs() << format(" %.*s", xleft, name);
3675 else
3676 outs() << " (not in an __OBJC section)";
3677 }
3678 outs() << "\n";
3679
3680 outs() << "\t\t method_imp "
3681 << format("0x%08" PRIx32, method.method_imp) << " ";
3682 if (info->verbose) {
3683 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
3684 if (SymbolName != nullptr)
3685 outs() << SymbolName;
3686 }
3687 outs() << "\n";
3688 }
3689 return false;
3690}
3691
Kevin Enderby0fc11822015-04-01 20:57:01 +00003692static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
3693 struct protocol_list64_t pl;
3694 uint64_t q, n_value;
3695 struct protocol64_t pc;
3696 const char *r;
3697 uint32_t offset, xoffset, left, i;
3698 SectionRef S, xS;
3699 const char *name, *sym_name;
3700
3701 r = get_pointer_64(p, offset, left, S, info);
3702 if (r == nullptr)
3703 return;
3704 memset(&pl, '\0', sizeof(struct protocol_list64_t));
3705 if (left < sizeof(struct protocol_list64_t)) {
3706 memcpy(&pl, r, left);
3707 outs() << " (protocol_list_t entends past the end of the section)\n";
3708 } else
3709 memcpy(&pl, r, sizeof(struct protocol_list64_t));
3710 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3711 swapStruct(pl);
3712 outs() << " count " << pl.count << "\n";
3713
3714 p += sizeof(struct protocol_list64_t);
3715 offset += sizeof(struct protocol_list64_t);
3716 for (i = 0; i < pl.count; i++) {
3717 r = get_pointer_64(p, offset, left, S, info);
3718 if (r == nullptr)
3719 return;
3720 q = 0;
3721 if (left < sizeof(uint64_t)) {
3722 memcpy(&q, r, left);
3723 outs() << " (protocol_t * entends past the end of the section)\n";
3724 } else
3725 memcpy(&q, r, sizeof(uint64_t));
3726 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3727 sys::swapByteOrder(q);
3728
3729 outs() << "\t\t list[" << i << "] ";
3730 sym_name = get_symbol_64(offset, S, info, n_value, q);
3731 if (n_value != 0) {
3732 if (info->verbose && sym_name != nullptr)
3733 outs() << sym_name;
3734 else
3735 outs() << format("0x%" PRIx64, n_value);
3736 if (q != 0)
3737 outs() << " + " << format("0x%" PRIx64, q);
3738 } else
3739 outs() << format("0x%" PRIx64, q);
3740 outs() << " (struct protocol_t *)\n";
3741
3742 r = get_pointer_64(q + n_value, offset, left, S, info);
3743 if (r == nullptr)
3744 return;
3745 memset(&pc, '\0', sizeof(struct protocol64_t));
3746 if (left < sizeof(struct protocol64_t)) {
3747 memcpy(&pc, r, left);
3748 outs() << " (protocol_t entends past the end of the section)\n";
3749 } else
3750 memcpy(&pc, r, sizeof(struct protocol64_t));
3751 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3752 swapStruct(pc);
3753
3754 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
3755
3756 outs() << "\t\t\t name ";
3757 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
3758 info, n_value, pc.name);
3759 if (n_value != 0) {
3760 if (info->verbose && sym_name != nullptr)
3761 outs() << sym_name;
3762 else
3763 outs() << format("0x%" PRIx64, n_value);
3764 if (pc.name != 0)
3765 outs() << " + " << format("0x%" PRIx64, pc.name);
3766 } else
3767 outs() << format("0x%" PRIx64, pc.name);
3768 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
3769 if (name != nullptr)
3770 outs() << format(" %.*s", left, name);
3771 outs() << "\n";
3772
3773 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
3774
3775 outs() << "\t\t instanceMethods ";
3776 sym_name =
3777 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
3778 S, info, n_value, pc.instanceMethods);
3779 if (n_value != 0) {
3780 if (info->verbose && sym_name != nullptr)
3781 outs() << sym_name;
3782 else
3783 outs() << format("0x%" PRIx64, n_value);
3784 if (pc.instanceMethods != 0)
3785 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
3786 } else
3787 outs() << format("0x%" PRIx64, pc.instanceMethods);
3788 outs() << " (struct method_list_t *)\n";
3789 if (pc.instanceMethods + n_value != 0)
3790 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
3791
3792 outs() << "\t\t classMethods ";
3793 sym_name =
3794 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
3795 info, n_value, pc.classMethods);
3796 if (n_value != 0) {
3797 if (info->verbose && sym_name != nullptr)
3798 outs() << sym_name;
3799 else
3800 outs() << format("0x%" PRIx64, n_value);
3801 if (pc.classMethods != 0)
3802 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
3803 } else
3804 outs() << format("0x%" PRIx64, pc.classMethods);
3805 outs() << " (struct method_list_t *)\n";
3806 if (pc.classMethods + n_value != 0)
3807 print_method_list64_t(pc.classMethods + n_value, info, "\t");
3808
3809 outs() << "\t optionalInstanceMethods "
3810 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
3811 outs() << "\t optionalClassMethods "
3812 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
3813 outs() << "\t instanceProperties "
3814 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
3815
3816 p += sizeof(uint64_t);
3817 offset += sizeof(uint64_t);
3818 }
3819}
3820
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003821static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
3822 struct protocol_list32_t pl;
3823 uint32_t q;
3824 struct protocol32_t pc;
3825 const char *r;
3826 uint32_t offset, xoffset, left, i;
3827 SectionRef S, xS;
3828 const char *name;
3829
3830 r = get_pointer_32(p, offset, left, S, info);
3831 if (r == nullptr)
3832 return;
3833 memset(&pl, '\0', sizeof(struct protocol_list32_t));
3834 if (left < sizeof(struct protocol_list32_t)) {
3835 memcpy(&pl, r, left);
3836 outs() << " (protocol_list_t entends past the end of the section)\n";
3837 } else
3838 memcpy(&pl, r, sizeof(struct protocol_list32_t));
3839 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3840 swapStruct(pl);
3841 outs() << " count " << pl.count << "\n";
3842
3843 p += sizeof(struct protocol_list32_t);
3844 offset += sizeof(struct protocol_list32_t);
3845 for (i = 0; i < pl.count; i++) {
3846 r = get_pointer_32(p, offset, left, S, info);
3847 if (r == nullptr)
3848 return;
3849 q = 0;
3850 if (left < sizeof(uint32_t)) {
3851 memcpy(&q, r, left);
3852 outs() << " (protocol_t * entends past the end of the section)\n";
3853 } else
3854 memcpy(&q, r, sizeof(uint32_t));
3855 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3856 sys::swapByteOrder(q);
3857 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
3858 << " (struct protocol_t *)\n";
3859 r = get_pointer_32(q, offset, left, S, info);
3860 if (r == nullptr)
3861 return;
3862 memset(&pc, '\0', sizeof(struct protocol32_t));
3863 if (left < sizeof(struct protocol32_t)) {
3864 memcpy(&pc, r, left);
3865 outs() << " (protocol_t entends past the end of the section)\n";
3866 } else
3867 memcpy(&pc, r, sizeof(struct protocol32_t));
3868 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3869 swapStruct(pc);
3870 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
3871 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
3872 name = get_pointer_32(pc.name, xoffset, left, xS, info);
3873 if (name != nullptr)
3874 outs() << format(" %.*s", left, name);
3875 outs() << "\n";
3876 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
3877 outs() << "\t\t instanceMethods "
3878 << format("0x%" PRIx32, pc.instanceMethods)
3879 << " (struct method_list_t *)\n";
3880 if (pc.instanceMethods != 0)
3881 print_method_list32_t(pc.instanceMethods, info, "\t");
3882 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
3883 << " (struct method_list_t *)\n";
3884 if (pc.classMethods != 0)
3885 print_method_list32_t(pc.classMethods, info, "\t");
3886 outs() << "\t optionalInstanceMethods "
3887 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
3888 outs() << "\t optionalClassMethods "
3889 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
3890 outs() << "\t instanceProperties "
3891 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
3892 p += sizeof(uint32_t);
3893 offset += sizeof(uint32_t);
3894 }
3895}
3896
Kevin Enderby846c0002015-04-16 17:19:59 +00003897static void print_indent(uint32_t indent) {
3898 for (uint32_t i = 0; i < indent;) {
3899 if (indent - i >= 8) {
3900 outs() << "\t";
3901 i += 8;
3902 } else {
3903 for (uint32_t j = i; j < indent; j++)
3904 outs() << " ";
3905 return;
3906 }
3907 }
3908}
3909
3910static bool print_method_description_list(uint32_t p, uint32_t indent,
3911 struct DisassembleInfo *info) {
3912 uint32_t offset, left, xleft;
3913 SectionRef S;
3914 struct objc_method_description_list_t mdl;
3915 struct objc_method_description_t md;
3916 const char *r, *list, *name;
3917 int32_t i;
3918
3919 r = get_pointer_32(p, offset, left, S, info, true);
3920 if (r == nullptr)
3921 return true;
3922
3923 outs() << "\n";
3924 if (left > sizeof(struct objc_method_description_list_t)) {
3925 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
3926 } else {
3927 print_indent(indent);
3928 outs() << " objc_method_description_list extends past end of the section\n";
3929 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
3930 memcpy(&mdl, r, left);
3931 }
3932 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3933 swapStruct(mdl);
3934
3935 print_indent(indent);
3936 outs() << " count " << mdl.count << "\n";
3937
3938 list = r + sizeof(struct objc_method_description_list_t);
3939 for (i = 0; i < mdl.count; i++) {
3940 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
3941 print_indent(indent);
3942 outs() << " remaining list entries extend past the of the section\n";
3943 break;
3944 }
3945 print_indent(indent);
3946 outs() << " list[" << i << "]\n";
3947 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
3948 sizeof(struct objc_method_description_t));
3949 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3950 swapStruct(md);
3951
3952 print_indent(indent);
3953 outs() << " name " << format("0x%08" PRIx32, md.name);
3954 if (info->verbose) {
3955 name = get_pointer_32(md.name, offset, xleft, S, info, true);
3956 if (name != nullptr)
3957 outs() << format(" %.*s", xleft, name);
3958 else
3959 outs() << " (not in an __OBJC section)";
3960 }
3961 outs() << "\n";
3962
3963 print_indent(indent);
3964 outs() << " types " << format("0x%08" PRIx32, md.types);
3965 if (info->verbose) {
3966 name = get_pointer_32(md.types, offset, xleft, S, info, true);
3967 if (name != nullptr)
3968 outs() << format(" %.*s", xleft, name);
3969 else
3970 outs() << " (not in an __OBJC section)";
3971 }
3972 outs() << "\n";
3973 }
3974 return false;
3975}
3976
3977static bool print_protocol_list(uint32_t p, uint32_t indent,
3978 struct DisassembleInfo *info);
3979
3980static bool print_protocol(uint32_t p, uint32_t indent,
3981 struct DisassembleInfo *info) {
3982 uint32_t offset, left;
3983 SectionRef S;
3984 struct objc_protocol_t protocol;
3985 const char *r, *name;
3986
3987 r = get_pointer_32(p, offset, left, S, info, true);
3988 if (r == nullptr)
3989 return true;
3990
3991 outs() << "\n";
3992 if (left >= sizeof(struct objc_protocol_t)) {
3993 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
3994 } else {
3995 print_indent(indent);
3996 outs() << " Protocol extends past end of the section\n";
3997 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
3998 memcpy(&protocol, r, left);
3999 }
4000 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4001 swapStruct(protocol);
4002
4003 print_indent(indent);
4004 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
4005 << "\n";
4006
4007 print_indent(indent);
4008 outs() << " protocol_name "
4009 << format("0x%08" PRIx32, protocol.protocol_name);
4010 if (info->verbose) {
4011 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
4012 if (name != nullptr)
4013 outs() << format(" %.*s", left, name);
4014 else
4015 outs() << " (not in an __OBJC section)";
4016 }
4017 outs() << "\n";
4018
4019 print_indent(indent);
4020 outs() << " protocol_list "
4021 << format("0x%08" PRIx32, protocol.protocol_list);
4022 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
4023 outs() << " (not in an __OBJC section)\n";
4024
4025 print_indent(indent);
4026 outs() << " instance_methods "
4027 << format("0x%08" PRIx32, protocol.instance_methods);
4028 if (print_method_description_list(protocol.instance_methods, indent, info))
4029 outs() << " (not in an __OBJC section)\n";
4030
4031 print_indent(indent);
4032 outs() << " class_methods "
4033 << format("0x%08" PRIx32, protocol.class_methods);
4034 if (print_method_description_list(protocol.class_methods, indent, info))
4035 outs() << " (not in an __OBJC section)\n";
4036
4037 return false;
4038}
4039
4040static bool print_protocol_list(uint32_t p, uint32_t indent,
4041 struct DisassembleInfo *info) {
4042 uint32_t offset, left, l;
4043 SectionRef S;
4044 struct objc_protocol_list_t protocol_list;
4045 const char *r, *list;
4046 int32_t i;
4047
4048 r = get_pointer_32(p, offset, left, S, info, true);
4049 if (r == nullptr)
4050 return true;
4051
4052 outs() << "\n";
4053 if (left > sizeof(struct objc_protocol_list_t)) {
4054 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4055 } else {
4056 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4057 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4058 memcpy(&protocol_list, r, left);
4059 }
4060 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4061 swapStruct(protocol_list);
4062
4063 print_indent(indent);
4064 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
4065 << "\n";
4066 print_indent(indent);
4067 outs() << " count " << protocol_list.count << "\n";
4068
4069 list = r + sizeof(struct objc_protocol_list_t);
4070 for (i = 0; i < protocol_list.count; i++) {
4071 if ((i + 1) * sizeof(uint32_t) > left) {
4072 outs() << "\t\t remaining list entries extend past the of the section\n";
4073 break;
4074 }
4075 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4076 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4077 sys::swapByteOrder(l);
4078
4079 print_indent(indent);
4080 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
4081 if (print_protocol(l, indent, info))
4082 outs() << "(not in an __OBJC section)\n";
4083 }
4084 return false;
4085}
4086
Kevin Enderby0fc11822015-04-01 20:57:01 +00004087static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4088 struct ivar_list64_t il;
4089 struct ivar64_t i;
4090 const char *r;
4091 uint32_t offset, xoffset, left, j;
4092 SectionRef S, xS;
4093 const char *name, *sym_name, *ivar_offset_p;
4094 uint64_t ivar_offset, n_value;
4095
4096 r = get_pointer_64(p, offset, left, S, info);
4097 if (r == nullptr)
4098 return;
4099 memset(&il, '\0', sizeof(struct ivar_list64_t));
4100 if (left < sizeof(struct ivar_list64_t)) {
4101 memcpy(&il, r, left);
4102 outs() << " (ivar_list_t entends past the end of the section)\n";
4103 } else
4104 memcpy(&il, r, sizeof(struct ivar_list64_t));
4105 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4106 swapStruct(il);
4107 outs() << " entsize " << il.entsize << "\n";
4108 outs() << " count " << il.count << "\n";
4109
4110 p += sizeof(struct ivar_list64_t);
4111 offset += sizeof(struct ivar_list64_t);
4112 for (j = 0; j < il.count; j++) {
4113 r = get_pointer_64(p, offset, left, S, info);
4114 if (r == nullptr)
4115 return;
4116 memset(&i, '\0', sizeof(struct ivar64_t));
4117 if (left < sizeof(struct ivar64_t)) {
4118 memcpy(&i, r, left);
4119 outs() << " (ivar_t entends past the end of the section)\n";
4120 } else
4121 memcpy(&i, r, sizeof(struct ivar64_t));
4122 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4123 swapStruct(i);
4124
4125 outs() << "\t\t\t offset ";
4126 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4127 info, n_value, i.offset);
4128 if (n_value != 0) {
4129 if (info->verbose && sym_name != nullptr)
4130 outs() << sym_name;
4131 else
4132 outs() << format("0x%" PRIx64, n_value);
4133 if (i.offset != 0)
4134 outs() << " + " << format("0x%" PRIx64, i.offset);
4135 } else
4136 outs() << format("0x%" PRIx64, i.offset);
4137 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4138 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4139 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4140 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4141 sys::swapByteOrder(ivar_offset);
4142 outs() << " " << ivar_offset << "\n";
4143 } else
4144 outs() << "\n";
4145
4146 outs() << "\t\t\t name ";
4147 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4148 n_value, i.name);
4149 if (n_value != 0) {
4150 if (info->verbose && sym_name != nullptr)
4151 outs() << sym_name;
4152 else
4153 outs() << format("0x%" PRIx64, n_value);
4154 if (i.name != 0)
4155 outs() << " + " << format("0x%" PRIx64, i.name);
4156 } else
4157 outs() << format("0x%" PRIx64, i.name);
4158 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4159 if (name != nullptr)
4160 outs() << format(" %.*s", left, name);
4161 outs() << "\n";
4162
4163 outs() << "\t\t\t type ";
4164 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4165 n_value, i.name);
4166 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4167 if (n_value != 0) {
4168 if (info->verbose && sym_name != nullptr)
4169 outs() << sym_name;
4170 else
4171 outs() << format("0x%" PRIx64, n_value);
4172 if (i.type != 0)
4173 outs() << " + " << format("0x%" PRIx64, i.type);
4174 } else
4175 outs() << format("0x%" PRIx64, i.type);
4176 if (name != nullptr)
4177 outs() << format(" %.*s", left, name);
4178 outs() << "\n";
4179
4180 outs() << "\t\t\talignment " << i.alignment << "\n";
4181 outs() << "\t\t\t size " << i.size << "\n";
4182
4183 p += sizeof(struct ivar64_t);
4184 offset += sizeof(struct ivar64_t);
4185 }
4186}
4187
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004188static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4189 struct ivar_list32_t il;
4190 struct ivar32_t i;
4191 const char *r;
4192 uint32_t offset, xoffset, left, j;
4193 SectionRef S, xS;
4194 const char *name, *ivar_offset_p;
4195 uint32_t ivar_offset;
4196
4197 r = get_pointer_32(p, offset, left, S, info);
4198 if (r == nullptr)
4199 return;
4200 memset(&il, '\0', sizeof(struct ivar_list32_t));
4201 if (left < sizeof(struct ivar_list32_t)) {
4202 memcpy(&il, r, left);
4203 outs() << " (ivar_list_t entends past the end of the section)\n";
4204 } else
4205 memcpy(&il, r, sizeof(struct ivar_list32_t));
4206 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4207 swapStruct(il);
4208 outs() << " entsize " << il.entsize << "\n";
4209 outs() << " count " << il.count << "\n";
4210
4211 p += sizeof(struct ivar_list32_t);
4212 offset += sizeof(struct ivar_list32_t);
4213 for (j = 0; j < il.count; j++) {
4214 r = get_pointer_32(p, offset, left, S, info);
4215 if (r == nullptr)
4216 return;
4217 memset(&i, '\0', sizeof(struct ivar32_t));
4218 if (left < sizeof(struct ivar32_t)) {
4219 memcpy(&i, r, left);
4220 outs() << " (ivar_t entends past the end of the section)\n";
4221 } else
4222 memcpy(&i, r, sizeof(struct ivar32_t));
4223 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4224 swapStruct(i);
4225
4226 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4227 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4228 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4229 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4230 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4231 sys::swapByteOrder(ivar_offset);
4232 outs() << " " << ivar_offset << "\n";
4233 } else
4234 outs() << "\n";
4235
4236 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4237 name = get_pointer_32(i.name, xoffset, left, xS, info);
4238 if (name != nullptr)
4239 outs() << format(" %.*s", left, name);
4240 outs() << "\n";
4241
4242 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4243 name = get_pointer_32(i.type, xoffset, left, xS, info);
4244 if (name != nullptr)
4245 outs() << format(" %.*s", left, name);
4246 outs() << "\n";
4247
4248 outs() << "\t\t\talignment " << i.alignment << "\n";
4249 outs() << "\t\t\t size " << i.size << "\n";
4250
4251 p += sizeof(struct ivar32_t);
4252 offset += sizeof(struct ivar32_t);
4253 }
4254}
4255
Kevin Enderby0fc11822015-04-01 20:57:01 +00004256static void print_objc_property_list64(uint64_t p,
4257 struct DisassembleInfo *info) {
4258 struct objc_property_list64 opl;
4259 struct objc_property64 op;
4260 const char *r;
4261 uint32_t offset, xoffset, left, j;
4262 SectionRef S, xS;
4263 const char *name, *sym_name;
4264 uint64_t n_value;
4265
4266 r = get_pointer_64(p, offset, left, S, info);
4267 if (r == nullptr)
4268 return;
4269 memset(&opl, '\0', sizeof(struct objc_property_list64));
4270 if (left < sizeof(struct objc_property_list64)) {
4271 memcpy(&opl, r, left);
4272 outs() << " (objc_property_list entends past the end of the section)\n";
4273 } else
4274 memcpy(&opl, r, sizeof(struct objc_property_list64));
4275 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4276 swapStruct(opl);
4277 outs() << " entsize " << opl.entsize << "\n";
4278 outs() << " count " << opl.count << "\n";
4279
4280 p += sizeof(struct objc_property_list64);
4281 offset += sizeof(struct objc_property_list64);
4282 for (j = 0; j < opl.count; j++) {
4283 r = get_pointer_64(p, offset, left, S, info);
4284 if (r == nullptr)
4285 return;
4286 memset(&op, '\0', sizeof(struct objc_property64));
4287 if (left < sizeof(struct objc_property64)) {
4288 memcpy(&op, r, left);
4289 outs() << " (objc_property entends past the end of the section)\n";
4290 } else
4291 memcpy(&op, r, sizeof(struct objc_property64));
4292 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4293 swapStruct(op);
4294
4295 outs() << "\t\t\t name ";
4296 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4297 info, n_value, op.name);
4298 if (n_value != 0) {
4299 if (info->verbose && sym_name != nullptr)
4300 outs() << sym_name;
4301 else
4302 outs() << format("0x%" PRIx64, n_value);
4303 if (op.name != 0)
4304 outs() << " + " << format("0x%" PRIx64, op.name);
4305 } else
4306 outs() << format("0x%" PRIx64, op.name);
4307 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4308 if (name != nullptr)
4309 outs() << format(" %.*s", left, name);
4310 outs() << "\n";
4311
4312 outs() << "\t\t\tattributes ";
4313 sym_name =
4314 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4315 info, n_value, op.attributes);
4316 if (n_value != 0) {
4317 if (info->verbose && sym_name != nullptr)
4318 outs() << sym_name;
4319 else
4320 outs() << format("0x%" PRIx64, n_value);
4321 if (op.attributes != 0)
4322 outs() << " + " << format("0x%" PRIx64, op.attributes);
4323 } else
4324 outs() << format("0x%" PRIx64, op.attributes);
4325 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4326 if (name != nullptr)
4327 outs() << format(" %.*s", left, name);
4328 outs() << "\n";
4329
4330 p += sizeof(struct objc_property64);
4331 offset += sizeof(struct objc_property64);
4332 }
4333}
4334
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004335static void print_objc_property_list32(uint32_t p,
4336 struct DisassembleInfo *info) {
4337 struct objc_property_list32 opl;
4338 struct objc_property32 op;
4339 const char *r;
4340 uint32_t offset, xoffset, left, j;
4341 SectionRef S, xS;
4342 const char *name;
4343
4344 r = get_pointer_32(p, offset, left, S, info);
4345 if (r == nullptr)
4346 return;
4347 memset(&opl, '\0', sizeof(struct objc_property_list32));
4348 if (left < sizeof(struct objc_property_list32)) {
4349 memcpy(&opl, r, left);
4350 outs() << " (objc_property_list entends past the end of the section)\n";
4351 } else
4352 memcpy(&opl, r, sizeof(struct objc_property_list32));
4353 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4354 swapStruct(opl);
4355 outs() << " entsize " << opl.entsize << "\n";
4356 outs() << " count " << opl.count << "\n";
4357
4358 p += sizeof(struct objc_property_list32);
4359 offset += sizeof(struct objc_property_list32);
4360 for (j = 0; j < opl.count; j++) {
4361 r = get_pointer_32(p, offset, left, S, info);
4362 if (r == nullptr)
4363 return;
4364 memset(&op, '\0', sizeof(struct objc_property32));
4365 if (left < sizeof(struct objc_property32)) {
4366 memcpy(&op, r, left);
4367 outs() << " (objc_property entends past the end of the section)\n";
4368 } else
4369 memcpy(&op, r, sizeof(struct objc_property32));
4370 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4371 swapStruct(op);
4372
4373 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4374 name = get_pointer_32(op.name, xoffset, left, xS, info);
4375 if (name != nullptr)
4376 outs() << format(" %.*s", left, name);
4377 outs() << "\n";
4378
4379 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4380 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4381 if (name != nullptr)
4382 outs() << format(" %.*s", left, name);
4383 outs() << "\n";
4384
4385 p += sizeof(struct objc_property32);
4386 offset += sizeof(struct objc_property32);
4387 }
4388}
4389
Richard Smith81ff44d2015-10-09 22:09:56 +00004390static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
Kevin Enderby0fc11822015-04-01 20:57:01 +00004391 bool &is_meta_class) {
4392 struct class_ro64_t cro;
4393 const char *r;
4394 uint32_t offset, xoffset, left;
4395 SectionRef S, xS;
4396 const char *name, *sym_name;
4397 uint64_t n_value;
4398
4399 r = get_pointer_64(p, offset, left, S, info);
4400 if (r == nullptr || left < sizeof(struct class_ro64_t))
Richard Smith81ff44d2015-10-09 22:09:56 +00004401 return false;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004402 memset(&cro, '\0', sizeof(struct class_ro64_t));
4403 if (left < sizeof(struct class_ro64_t)) {
4404 memcpy(&cro, r, left);
4405 outs() << " (class_ro_t entends past the end of the section)\n";
4406 } else
4407 memcpy(&cro, r, sizeof(struct class_ro64_t));
4408 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4409 swapStruct(cro);
4410 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4411 if (cro.flags & RO_META)
4412 outs() << " RO_META";
4413 if (cro.flags & RO_ROOT)
4414 outs() << " RO_ROOT";
4415 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4416 outs() << " RO_HAS_CXX_STRUCTORS";
4417 outs() << "\n";
4418 outs() << " instanceStart " << cro.instanceStart << "\n";
4419 outs() << " instanceSize " << cro.instanceSize << "\n";
4420 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4421 << "\n";
4422 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4423 << "\n";
4424 print_layout_map64(cro.ivarLayout, info);
4425
4426 outs() << " name ";
4427 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4428 info, n_value, cro.name);
4429 if (n_value != 0) {
4430 if (info->verbose && sym_name != nullptr)
4431 outs() << sym_name;
4432 else
4433 outs() << format("0x%" PRIx64, n_value);
4434 if (cro.name != 0)
4435 outs() << " + " << format("0x%" PRIx64, cro.name);
4436 } else
4437 outs() << format("0x%" PRIx64, cro.name);
4438 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4439 if (name != nullptr)
4440 outs() << format(" %.*s", left, name);
4441 outs() << "\n";
4442
4443 outs() << " baseMethods ";
4444 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4445 S, info, n_value, cro.baseMethods);
4446 if (n_value != 0) {
4447 if (info->verbose && sym_name != nullptr)
4448 outs() << sym_name;
4449 else
4450 outs() << format("0x%" PRIx64, n_value);
4451 if (cro.baseMethods != 0)
4452 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4453 } else
4454 outs() << format("0x%" PRIx64, cro.baseMethods);
4455 outs() << " (struct method_list_t *)\n";
4456 if (cro.baseMethods + n_value != 0)
4457 print_method_list64_t(cro.baseMethods + n_value, info, "");
4458
4459 outs() << " baseProtocols ";
4460 sym_name =
4461 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4462 info, n_value, cro.baseProtocols);
4463 if (n_value != 0) {
4464 if (info->verbose && sym_name != nullptr)
4465 outs() << sym_name;
4466 else
4467 outs() << format("0x%" PRIx64, n_value);
4468 if (cro.baseProtocols != 0)
4469 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4470 } else
4471 outs() << format("0x%" PRIx64, cro.baseProtocols);
4472 outs() << "\n";
4473 if (cro.baseProtocols + n_value != 0)
4474 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4475
4476 outs() << " ivars ";
4477 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004478 info, n_value, cro.ivars);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004479 if (n_value != 0) {
4480 if (info->verbose && sym_name != nullptr)
4481 outs() << sym_name;
4482 else
4483 outs() << format("0x%" PRIx64, n_value);
4484 if (cro.ivars != 0)
4485 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4486 } else
4487 outs() << format("0x%" PRIx64, cro.ivars);
4488 outs() << "\n";
4489 if (cro.ivars + n_value != 0)
4490 print_ivar_list64_t(cro.ivars + n_value, info);
4491
4492 outs() << " weakIvarLayout ";
4493 sym_name =
4494 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4495 info, n_value, cro.weakIvarLayout);
4496 if (n_value != 0) {
4497 if (info->verbose && sym_name != nullptr)
4498 outs() << sym_name;
4499 else
4500 outs() << format("0x%" PRIx64, n_value);
4501 if (cro.weakIvarLayout != 0)
4502 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4503 } else
4504 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4505 outs() << "\n";
4506 print_layout_map64(cro.weakIvarLayout + n_value, info);
4507
4508 outs() << " baseProperties ";
4509 sym_name =
4510 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4511 info, n_value, cro.baseProperties);
4512 if (n_value != 0) {
4513 if (info->verbose && sym_name != nullptr)
4514 outs() << sym_name;
4515 else
4516 outs() << format("0x%" PRIx64, n_value);
4517 if (cro.baseProperties != 0)
4518 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4519 } else
4520 outs() << format("0x%" PRIx64, cro.baseProperties);
4521 outs() << "\n";
4522 if (cro.baseProperties + n_value != 0)
4523 print_objc_property_list64(cro.baseProperties + n_value, info);
4524
Rafael Espindolab9091322015-10-24 23:19:10 +00004525 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004526 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004527}
4528
Richard Smith81ff44d2015-10-09 22:09:56 +00004529static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004530 bool &is_meta_class) {
4531 struct class_ro32_t cro;
4532 const char *r;
4533 uint32_t offset, xoffset, left;
4534 SectionRef S, xS;
4535 const char *name;
4536
4537 r = get_pointer_32(p, offset, left, S, info);
4538 if (r == nullptr)
Richard Smith81ff44d2015-10-09 22:09:56 +00004539 return false;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004540 memset(&cro, '\0', sizeof(struct class_ro32_t));
4541 if (left < sizeof(struct class_ro32_t)) {
4542 memcpy(&cro, r, left);
4543 outs() << " (class_ro_t entends past the end of the section)\n";
4544 } else
4545 memcpy(&cro, r, sizeof(struct class_ro32_t));
4546 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4547 swapStruct(cro);
4548 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4549 if (cro.flags & RO_META)
4550 outs() << " RO_META";
4551 if (cro.flags & RO_ROOT)
4552 outs() << " RO_ROOT";
4553 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4554 outs() << " RO_HAS_CXX_STRUCTORS";
4555 outs() << "\n";
4556 outs() << " instanceStart " << cro.instanceStart << "\n";
4557 outs() << " instanceSize " << cro.instanceSize << "\n";
4558 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4559 << "\n";
4560 print_layout_map32(cro.ivarLayout, info);
4561
4562 outs() << " name " << format("0x%" PRIx32, cro.name);
4563 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4564 if (name != nullptr)
4565 outs() << format(" %.*s", left, name);
4566 outs() << "\n";
4567
4568 outs() << " baseMethods "
4569 << format("0x%" PRIx32, cro.baseMethods)
4570 << " (struct method_list_t *)\n";
4571 if (cro.baseMethods != 0)
4572 print_method_list32_t(cro.baseMethods, info, "");
4573
4574 outs() << " baseProtocols "
4575 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4576 if (cro.baseProtocols != 0)
4577 print_protocol_list32_t(cro.baseProtocols, info);
4578 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4579 << "\n";
4580 if (cro.ivars != 0)
4581 print_ivar_list32_t(cro.ivars, info);
4582 outs() << " weakIvarLayout "
4583 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4584 print_layout_map32(cro.weakIvarLayout, info);
4585 outs() << " baseProperties "
4586 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4587 if (cro.baseProperties != 0)
4588 print_objc_property_list32(cro.baseProperties, info);
Rafael Espindolab9091322015-10-24 23:19:10 +00004589 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004590 return true;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004591}
4592
Kevin Enderby0fc11822015-04-01 20:57:01 +00004593static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4594 struct class64_t c;
4595 const char *r;
4596 uint32_t offset, left;
4597 SectionRef S;
4598 const char *name;
4599 uint64_t isa_n_value, n_value;
4600
4601 r = get_pointer_64(p, offset, left, S, info);
4602 if (r == nullptr || left < sizeof(struct class64_t))
4603 return;
4604 memset(&c, '\0', sizeof(struct class64_t));
4605 if (left < sizeof(struct class64_t)) {
4606 memcpy(&c, r, left);
4607 outs() << " (class_t entends past the end of the section)\n";
4608 } else
4609 memcpy(&c, r, sizeof(struct class64_t));
4610 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4611 swapStruct(c);
4612
4613 outs() << " isa " << format("0x%" PRIx64, c.isa);
4614 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
4615 isa_n_value, c.isa);
4616 if (name != nullptr)
4617 outs() << " " << name;
4618 outs() << "\n";
4619
4620 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
4621 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
4622 n_value, c.superclass);
4623 if (name != nullptr)
4624 outs() << " " << name;
4625 outs() << "\n";
4626
4627 outs() << " cache " << format("0x%" PRIx64, c.cache);
4628 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
4629 n_value, c.cache);
4630 if (name != nullptr)
4631 outs() << " " << name;
4632 outs() << "\n";
4633
4634 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
4635 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
4636 n_value, c.vtable);
4637 if (name != nullptr)
4638 outs() << " " << name;
4639 outs() << "\n";
4640
4641 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
4642 n_value, c.data);
4643 outs() << " data ";
4644 if (n_value != 0) {
4645 if (info->verbose && name != nullptr)
4646 outs() << name;
4647 else
4648 outs() << format("0x%" PRIx64, n_value);
4649 if (c.data != 0)
4650 outs() << " + " << format("0x%" PRIx64, c.data);
4651 } else
4652 outs() << format("0x%" PRIx64, c.data);
4653 outs() << " (struct class_ro_t *)";
4654
4655 // This is a Swift class if some of the low bits of the pointer are set.
4656 if ((c.data + n_value) & 0x7)
4657 outs() << " Swift class";
4658 outs() << "\n";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004659 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004660 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
4661 return;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004662
Kevin Enderbyaac75382015-10-08 16:56:35 +00004663 if (!is_meta_class &&
4664 c.isa + isa_n_value != p &&
4665 c.isa + isa_n_value != 0 &&
4666 info->depth < 100) {
4667 info->depth++;
4668 outs() << "Meta Class\n";
4669 print_class64_t(c.isa + isa_n_value, info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004670 }
4671}
4672
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004673static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
4674 struct class32_t c;
4675 const char *r;
4676 uint32_t offset, left;
4677 SectionRef S;
4678 const char *name;
4679
4680 r = get_pointer_32(p, offset, left, S, info);
4681 if (r == nullptr)
4682 return;
4683 memset(&c, '\0', sizeof(struct class32_t));
4684 if (left < sizeof(struct class32_t)) {
4685 memcpy(&c, r, left);
4686 outs() << " (class_t entends past the end of the section)\n";
4687 } else
4688 memcpy(&c, r, sizeof(struct class32_t));
4689 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4690 swapStruct(c);
4691
4692 outs() << " isa " << format("0x%" PRIx32, c.isa);
4693 name =
4694 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
4695 if (name != nullptr)
4696 outs() << " " << name;
4697 outs() << "\n";
4698
4699 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
4700 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
4701 c.superclass);
4702 if (name != nullptr)
4703 outs() << " " << name;
4704 outs() << "\n";
4705
4706 outs() << " cache " << format("0x%" PRIx32, c.cache);
4707 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
4708 c.cache);
4709 if (name != nullptr)
4710 outs() << " " << name;
4711 outs() << "\n";
4712
4713 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
4714 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
4715 c.vtable);
4716 if (name != nullptr)
4717 outs() << " " << name;
4718 outs() << "\n";
4719
4720 name =
4721 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
4722 outs() << " data " << format("0x%" PRIx32, c.data)
4723 << " (struct class_ro_t *)";
4724
4725 // This is a Swift class if some of the low bits of the pointer are set.
4726 if (c.data & 0x3)
4727 outs() << " Swift class";
4728 outs() << "\n";
4729 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004730 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
4731 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004732
Hans Wennborgcc9deb42015-09-29 18:02:48 +00004733 if (!is_meta_class) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004734 outs() << "Meta Class\n";
4735 print_class32_t(c.isa, info);
4736 }
4737}
4738
Kevin Enderby846c0002015-04-16 17:19:59 +00004739static void print_objc_class_t(struct objc_class_t *objc_class,
4740 struct DisassembleInfo *info) {
4741 uint32_t offset, left, xleft;
4742 const char *name, *p, *ivar_list;
4743 SectionRef S;
4744 int32_t i;
4745 struct objc_ivar_list_t objc_ivar_list;
4746 struct objc_ivar_t ivar;
4747
4748 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
4749 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
4750 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
4751 if (name != nullptr)
4752 outs() << format(" %.*s", left, name);
4753 else
4754 outs() << " (not in an __OBJC section)";
4755 }
4756 outs() << "\n";
4757
4758 outs() << "\t super_class "
4759 << format("0x%08" PRIx32, objc_class->super_class);
4760 if (info->verbose) {
4761 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
4762 if (name != nullptr)
4763 outs() << format(" %.*s", left, name);
4764 else
4765 outs() << " (not in an __OBJC section)";
4766 }
4767 outs() << "\n";
4768
4769 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
4770 if (info->verbose) {
4771 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
4772 if (name != nullptr)
4773 outs() << format(" %.*s", left, name);
4774 else
4775 outs() << " (not in an __OBJC section)";
4776 }
4777 outs() << "\n";
4778
4779 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
4780 << "\n";
4781
4782 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
4783 if (info->verbose) {
4784 if (CLS_GETINFO(objc_class, CLS_CLASS))
4785 outs() << " CLS_CLASS";
4786 else if (CLS_GETINFO(objc_class, CLS_META))
4787 outs() << " CLS_META";
4788 }
4789 outs() << "\n";
4790
4791 outs() << "\t instance_size "
4792 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
4793
4794 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
4795 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
4796 if (p != nullptr) {
4797 if (left > sizeof(struct objc_ivar_list_t)) {
4798 outs() << "\n";
4799 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
4800 } else {
4801 outs() << " (entends past the end of the section)\n";
4802 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
4803 memcpy(&objc_ivar_list, p, left);
4804 }
4805 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4806 swapStruct(objc_ivar_list);
4807 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
4808 ivar_list = p + sizeof(struct objc_ivar_list_t);
4809 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
4810 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
4811 outs() << "\t\t remaining ivar's extend past the of the section\n";
4812 break;
4813 }
4814 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
4815 sizeof(struct objc_ivar_t));
4816 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4817 swapStruct(ivar);
4818
4819 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
4820 if (info->verbose) {
4821 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
4822 if (name != nullptr)
4823 outs() << format(" %.*s", xleft, name);
4824 else
4825 outs() << " (not in an __OBJC section)";
4826 }
4827 outs() << "\n";
4828
4829 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
4830 if (info->verbose) {
4831 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
4832 if (name != nullptr)
4833 outs() << format(" %.*s", xleft, name);
4834 else
4835 outs() << " (not in an __OBJC section)";
4836 }
4837 outs() << "\n";
4838
4839 outs() << "\t\t ivar_offset "
4840 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
4841 }
4842 } else {
4843 outs() << " (not in an __OBJC section)\n";
4844 }
4845
4846 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
4847 if (print_method_list(objc_class->methodLists, info))
4848 outs() << " (not in an __OBJC section)\n";
4849
4850 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
4851 << "\n";
4852
4853 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
4854 if (print_protocol_list(objc_class->protocols, 16, info))
4855 outs() << " (not in an __OBJC section)\n";
4856}
4857
4858static void print_objc_objc_category_t(struct objc_category_t *objc_category,
4859 struct DisassembleInfo *info) {
4860 uint32_t offset, left;
4861 const char *name;
4862 SectionRef S;
4863
4864 outs() << "\t category name "
4865 << format("0x%08" PRIx32, objc_category->category_name);
4866 if (info->verbose) {
4867 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
4868 true);
4869 if (name != nullptr)
4870 outs() << format(" %.*s", left, name);
4871 else
4872 outs() << " (not in an __OBJC section)";
4873 }
4874 outs() << "\n";
4875
4876 outs() << "\t\t class name "
4877 << format("0x%08" PRIx32, objc_category->class_name);
4878 if (info->verbose) {
4879 name =
4880 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
4881 if (name != nullptr)
4882 outs() << format(" %.*s", left, name);
4883 else
4884 outs() << " (not in an __OBJC section)";
4885 }
4886 outs() << "\n";
4887
4888 outs() << "\t instance methods "
4889 << format("0x%08" PRIx32, objc_category->instance_methods);
4890 if (print_method_list(objc_category->instance_methods, info))
4891 outs() << " (not in an __OBJC section)\n";
4892
4893 outs() << "\t class methods "
4894 << format("0x%08" PRIx32, objc_category->class_methods);
4895 if (print_method_list(objc_category->class_methods, info))
4896 outs() << " (not in an __OBJC section)\n";
4897}
4898
Kevin Enderby0fc11822015-04-01 20:57:01 +00004899static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
4900 struct category64_t c;
4901 const char *r;
4902 uint32_t offset, xoffset, left;
4903 SectionRef S, xS;
4904 const char *name, *sym_name;
4905 uint64_t n_value;
4906
4907 r = get_pointer_64(p, offset, left, S, info);
4908 if (r == nullptr)
4909 return;
4910 memset(&c, '\0', sizeof(struct category64_t));
4911 if (left < sizeof(struct category64_t)) {
4912 memcpy(&c, r, left);
4913 outs() << " (category_t entends past the end of the section)\n";
4914 } else
4915 memcpy(&c, r, sizeof(struct category64_t));
4916 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4917 swapStruct(c);
4918
4919 outs() << " name ";
4920 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
4921 info, n_value, c.name);
4922 if (n_value != 0) {
4923 if (info->verbose && sym_name != nullptr)
4924 outs() << sym_name;
4925 else
4926 outs() << format("0x%" PRIx64, n_value);
4927 if (c.name != 0)
4928 outs() << " + " << format("0x%" PRIx64, c.name);
4929 } else
4930 outs() << format("0x%" PRIx64, c.name);
4931 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
4932 if (name != nullptr)
4933 outs() << format(" %.*s", left, name);
4934 outs() << "\n";
4935
4936 outs() << " cls ";
4937 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
4938 n_value, c.cls);
4939 if (n_value != 0) {
4940 if (info->verbose && sym_name != nullptr)
4941 outs() << sym_name;
4942 else
4943 outs() << format("0x%" PRIx64, n_value);
4944 if (c.cls != 0)
4945 outs() << " + " << format("0x%" PRIx64, c.cls);
4946 } else
4947 outs() << format("0x%" PRIx64, c.cls);
4948 outs() << "\n";
4949 if (c.cls + n_value != 0)
4950 print_class64_t(c.cls + n_value, info);
4951
4952 outs() << " instanceMethods ";
4953 sym_name =
4954 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
4955 info, n_value, c.instanceMethods);
4956 if (n_value != 0) {
4957 if (info->verbose && sym_name != nullptr)
4958 outs() << sym_name;
4959 else
4960 outs() << format("0x%" PRIx64, n_value);
4961 if (c.instanceMethods != 0)
4962 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
4963 } else
4964 outs() << format("0x%" PRIx64, c.instanceMethods);
4965 outs() << "\n";
4966 if (c.instanceMethods + n_value != 0)
4967 print_method_list64_t(c.instanceMethods + n_value, info, "");
4968
4969 outs() << " classMethods ";
4970 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
4971 S, info, n_value, c.classMethods);
4972 if (n_value != 0) {
4973 if (info->verbose && sym_name != nullptr)
4974 outs() << sym_name;
4975 else
4976 outs() << format("0x%" PRIx64, n_value);
4977 if (c.classMethods != 0)
4978 outs() << " + " << format("0x%" PRIx64, c.classMethods);
4979 } else
4980 outs() << format("0x%" PRIx64, c.classMethods);
4981 outs() << "\n";
4982 if (c.classMethods + n_value != 0)
4983 print_method_list64_t(c.classMethods + n_value, info, "");
4984
4985 outs() << " protocols ";
4986 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
4987 info, n_value, c.protocols);
4988 if (n_value != 0) {
4989 if (info->verbose && sym_name != nullptr)
4990 outs() << sym_name;
4991 else
4992 outs() << format("0x%" PRIx64, n_value);
4993 if (c.protocols != 0)
4994 outs() << " + " << format("0x%" PRIx64, c.protocols);
4995 } else
4996 outs() << format("0x%" PRIx64, c.protocols);
4997 outs() << "\n";
4998 if (c.protocols + n_value != 0)
4999 print_protocol_list64_t(c.protocols + n_value, info);
5000
5001 outs() << "instanceProperties ";
5002 sym_name =
5003 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
5004 S, info, n_value, c.instanceProperties);
5005 if (n_value != 0) {
5006 if (info->verbose && sym_name != nullptr)
5007 outs() << sym_name;
5008 else
5009 outs() << format("0x%" PRIx64, n_value);
5010 if (c.instanceProperties != 0)
5011 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
5012 } else
5013 outs() << format("0x%" PRIx64, c.instanceProperties);
5014 outs() << "\n";
5015 if (c.instanceProperties + n_value != 0)
5016 print_objc_property_list64(c.instanceProperties + n_value, info);
5017}
5018
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005019static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
5020 struct category32_t c;
5021 const char *r;
5022 uint32_t offset, left;
5023 SectionRef S, xS;
5024 const char *name;
5025
5026 r = get_pointer_32(p, offset, left, S, info);
5027 if (r == nullptr)
5028 return;
5029 memset(&c, '\0', sizeof(struct category32_t));
5030 if (left < sizeof(struct category32_t)) {
5031 memcpy(&c, r, left);
5032 outs() << " (category_t entends past the end of the section)\n";
5033 } else
5034 memcpy(&c, r, sizeof(struct category32_t));
5035 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5036 swapStruct(c);
5037
5038 outs() << " name " << format("0x%" PRIx32, c.name);
5039 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
5040 c.name);
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005041 if (name)
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005042 outs() << " " << name;
5043 outs() << "\n";
5044
5045 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
5046 if (c.cls != 0)
5047 print_class32_t(c.cls, info);
5048 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
5049 << "\n";
5050 if (c.instanceMethods != 0)
5051 print_method_list32_t(c.instanceMethods, info, "");
5052 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
5053 << "\n";
5054 if (c.classMethods != 0)
5055 print_method_list32_t(c.classMethods, info, "");
5056 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
5057 if (c.protocols != 0)
5058 print_protocol_list32_t(c.protocols, info);
5059 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
5060 << "\n";
5061 if (c.instanceProperties != 0)
5062 print_objc_property_list32(c.instanceProperties, info);
5063}
5064
Kevin Enderby0fc11822015-04-01 20:57:01 +00005065static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5066 uint32_t i, left, offset, xoffset;
5067 uint64_t p, n_value;
5068 struct message_ref64 mr;
5069 const char *name, *sym_name;
5070 const char *r;
5071 SectionRef xS;
5072
5073 if (S == SectionRef())
5074 return;
5075
5076 StringRef SectName;
5077 S.getName(SectName);
5078 DataRefImpl Ref = S.getRawDataRefImpl();
5079 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5080 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5081 offset = 0;
5082 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5083 p = S.getAddress() + i;
5084 r = get_pointer_64(p, offset, left, S, info);
5085 if (r == nullptr)
5086 return;
5087 memset(&mr, '\0', sizeof(struct message_ref64));
5088 if (left < sizeof(struct message_ref64)) {
5089 memcpy(&mr, r, left);
5090 outs() << " (message_ref entends past the end of the section)\n";
5091 } else
5092 memcpy(&mr, r, sizeof(struct message_ref64));
5093 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5094 swapStruct(mr);
5095
5096 outs() << " imp ";
5097 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5098 n_value, mr.imp);
5099 if (n_value != 0) {
5100 outs() << format("0x%" PRIx64, n_value) << " ";
5101 if (mr.imp != 0)
5102 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5103 } else
5104 outs() << format("0x%" PRIx64, mr.imp) << " ";
5105 if (name != nullptr)
5106 outs() << " " << name;
5107 outs() << "\n";
5108
5109 outs() << " sel ";
5110 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5111 info, n_value, mr.sel);
5112 if (n_value != 0) {
5113 if (info->verbose && sym_name != nullptr)
5114 outs() << sym_name;
5115 else
5116 outs() << format("0x%" PRIx64, n_value);
5117 if (mr.sel != 0)
5118 outs() << " + " << format("0x%" PRIx64, mr.sel);
5119 } else
5120 outs() << format("0x%" PRIx64, mr.sel);
5121 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5122 if (name != nullptr)
5123 outs() << format(" %.*s", left, name);
5124 outs() << "\n";
5125
5126 offset += sizeof(struct message_ref64);
5127 }
5128}
5129
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005130static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5131 uint32_t i, left, offset, xoffset, p;
5132 struct message_ref32 mr;
5133 const char *name, *r;
5134 SectionRef xS;
5135
5136 if (S == SectionRef())
5137 return;
5138
5139 StringRef SectName;
5140 S.getName(SectName);
5141 DataRefImpl Ref = S.getRawDataRefImpl();
5142 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5143 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5144 offset = 0;
5145 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5146 p = S.getAddress() + i;
5147 r = get_pointer_32(p, offset, left, S, info);
5148 if (r == nullptr)
5149 return;
5150 memset(&mr, '\0', sizeof(struct message_ref32));
5151 if (left < sizeof(struct message_ref32)) {
5152 memcpy(&mr, r, left);
5153 outs() << " (message_ref entends past the end of the section)\n";
5154 } else
5155 memcpy(&mr, r, sizeof(struct message_ref32));
5156 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5157 swapStruct(mr);
5158
5159 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5160 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5161 mr.imp);
5162 if (name != nullptr)
5163 outs() << " " << name;
5164 outs() << "\n";
5165
5166 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5167 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5168 if (name != nullptr)
5169 outs() << " " << name;
5170 outs() << "\n";
5171
5172 offset += sizeof(struct message_ref32);
5173 }
5174}
5175
Kevin Enderby0fc11822015-04-01 20:57:01 +00005176static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5177 uint32_t left, offset, swift_version;
5178 uint64_t p;
5179 struct objc_image_info64 o;
5180 const char *r;
5181
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00005182 if (S == SectionRef())
5183 return;
5184
Kevin Enderby0fc11822015-04-01 20:57:01 +00005185 StringRef SectName;
5186 S.getName(SectName);
5187 DataRefImpl Ref = S.getRawDataRefImpl();
5188 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5189 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5190 p = S.getAddress();
5191 r = get_pointer_64(p, offset, left, S, info);
5192 if (r == nullptr)
5193 return;
5194 memset(&o, '\0', sizeof(struct objc_image_info64));
5195 if (left < sizeof(struct objc_image_info64)) {
5196 memcpy(&o, r, left);
5197 outs() << " (objc_image_info entends past the end of the section)\n";
5198 } else
5199 memcpy(&o, r, sizeof(struct objc_image_info64));
5200 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5201 swapStruct(o);
5202 outs() << " version " << o.version << "\n";
5203 outs() << " flags " << format("0x%" PRIx32, o.flags);
5204 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5205 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5206 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5207 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5208 swift_version = (o.flags >> 8) & 0xff;
5209 if (swift_version != 0) {
5210 if (swift_version == 1)
5211 outs() << " Swift 1.0";
5212 else if (swift_version == 2)
5213 outs() << " Swift 1.1";
5214 else
5215 outs() << " unknown future Swift version (" << swift_version << ")";
5216 }
5217 outs() << "\n";
5218}
5219
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005220static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5221 uint32_t left, offset, swift_version, p;
5222 struct objc_image_info32 o;
5223 const char *r;
5224
Kevin Enderby19be2512016-04-21 19:49:29 +00005225 if (S == SectionRef())
5226 return;
5227
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005228 StringRef SectName;
5229 S.getName(SectName);
5230 DataRefImpl Ref = S.getRawDataRefImpl();
5231 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5232 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5233 p = S.getAddress();
5234 r = get_pointer_32(p, offset, left, S, info);
5235 if (r == nullptr)
5236 return;
5237 memset(&o, '\0', sizeof(struct objc_image_info32));
5238 if (left < sizeof(struct objc_image_info32)) {
5239 memcpy(&o, r, left);
5240 outs() << " (objc_image_info entends past the end of the section)\n";
5241 } else
5242 memcpy(&o, r, sizeof(struct objc_image_info32));
5243 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5244 swapStruct(o);
5245 outs() << " version " << o.version << "\n";
5246 outs() << " flags " << format("0x%" PRIx32, o.flags);
5247 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5248 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5249 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5250 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5251 swift_version = (o.flags >> 8) & 0xff;
5252 if (swift_version != 0) {
5253 if (swift_version == 1)
5254 outs() << " Swift 1.0";
5255 else if (swift_version == 2)
5256 outs() << " Swift 1.1";
5257 else
5258 outs() << " unknown future Swift version (" << swift_version << ")";
5259 }
5260 outs() << "\n";
5261}
5262
Kevin Enderby846c0002015-04-16 17:19:59 +00005263static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5264 uint32_t left, offset, p;
5265 struct imageInfo_t o;
5266 const char *r;
5267
5268 StringRef SectName;
5269 S.getName(SectName);
5270 DataRefImpl Ref = S.getRawDataRefImpl();
5271 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5272 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5273 p = S.getAddress();
5274 r = get_pointer_32(p, offset, left, S, info);
5275 if (r == nullptr)
5276 return;
5277 memset(&o, '\0', sizeof(struct imageInfo_t));
5278 if (left < sizeof(struct imageInfo_t)) {
5279 memcpy(&o, r, left);
5280 outs() << " (imageInfo entends past the end of the section)\n";
5281 } else
5282 memcpy(&o, r, sizeof(struct imageInfo_t));
5283 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5284 swapStruct(o);
5285 outs() << " version " << o.version << "\n";
5286 outs() << " flags " << format("0x%" PRIx32, o.flags);
5287 if (o.flags & 0x1)
5288 outs() << " F&C";
5289 if (o.flags & 0x2)
5290 outs() << " GC";
5291 if (o.flags & 0x4)
5292 outs() << " GC-only";
5293 else
5294 outs() << " RR";
5295 outs() << "\n";
5296}
5297
Kevin Enderby0fc11822015-04-01 20:57:01 +00005298static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5299 SymbolAddressMap AddrMap;
5300 if (verbose)
5301 CreateSymbolAddressMap(O, &AddrMap);
5302
5303 std::vector<SectionRef> Sections;
5304 for (const SectionRef &Section : O->sections()) {
5305 StringRef SectName;
5306 Section.getName(SectName);
5307 Sections.push_back(Section);
5308 }
5309
5310 struct DisassembleInfo info;
5311 // Set up the block of info used by the Symbolizer call backs.
5312 info.verbose = verbose;
5313 info.O = O;
5314 info.AddrMap = &AddrMap;
5315 info.Sections = &Sections;
5316 info.class_name = nullptr;
5317 info.selector_name = nullptr;
5318 info.method = nullptr;
5319 info.demangled_name = nullptr;
5320 info.bindtable = nullptr;
5321 info.adrp_addr = 0;
5322 info.adrp_inst = 0;
5323
Kevin Enderbyaac75382015-10-08 16:56:35 +00005324 info.depth = 0;
Davide Italiano62507042015-12-11 22:27:59 +00005325 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5326 if (CL == SectionRef())
5327 CL = get_section(O, "__DATA", "__objc_classlist");
5328 info.S = CL;
5329 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005330
Davide Italiano62507042015-12-11 22:27:59 +00005331 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5332 if (CR == SectionRef())
5333 CR = get_section(O, "__DATA", "__objc_classrefs");
5334 info.S = CR;
5335 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005336
Davide Italiano62507042015-12-11 22:27:59 +00005337 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5338 if (SR == SectionRef())
5339 SR = get_section(O, "__DATA", "__objc_superrefs");
5340 info.S = SR;
5341 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005342
Davide Italiano62507042015-12-11 22:27:59 +00005343 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5344 if (CA == SectionRef())
5345 CA = get_section(O, "__DATA", "__objc_catlist");
5346 info.S = CA;
5347 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005348
Davide Italiano62507042015-12-11 22:27:59 +00005349 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5350 if (PL == SectionRef())
5351 PL = get_section(O, "__DATA", "__objc_protolist");
5352 info.S = PL;
5353 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005354
Davide Italiano62507042015-12-11 22:27:59 +00005355 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5356 if (MR == SectionRef())
5357 MR = get_section(O, "__DATA", "__objc_msgrefs");
5358 info.S = MR;
5359 print_message_refs64(MR, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005360
Davide Italiano62507042015-12-11 22:27:59 +00005361 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5362 if (II == SectionRef())
5363 II = get_section(O, "__DATA", "__objc_imageinfo");
5364 info.S = II;
5365 print_image_info64(II, &info);
Kevin Enderby0bc6ed42015-04-01 21:50:45 +00005366
5367 if (info.bindtable != nullptr)
5368 delete info.bindtable;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005369}
5370
5371static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005372 SymbolAddressMap AddrMap;
5373 if (verbose)
5374 CreateSymbolAddressMap(O, &AddrMap);
5375
5376 std::vector<SectionRef> Sections;
5377 for (const SectionRef &Section : O->sections()) {
5378 StringRef SectName;
5379 Section.getName(SectName);
5380 Sections.push_back(Section);
5381 }
5382
5383 struct DisassembleInfo info;
5384 // Set up the block of info used by the Symbolizer call backs.
5385 info.verbose = verbose;
5386 info.O = O;
5387 info.AddrMap = &AddrMap;
5388 info.Sections = &Sections;
5389 info.class_name = nullptr;
5390 info.selector_name = nullptr;
5391 info.method = nullptr;
5392 info.demangled_name = nullptr;
5393 info.bindtable = nullptr;
5394 info.adrp_addr = 0;
5395 info.adrp_inst = 0;
5396
5397 const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5398 if (CL != SectionRef()) {
5399 info.S = CL;
5400 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5401 } else {
5402 const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
5403 info.S = CL;
5404 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5405 }
5406
5407 const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5408 if (CR != SectionRef()) {
5409 info.S = CR;
5410 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5411 } else {
5412 const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
5413 info.S = CR;
5414 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5415 }
5416
5417 const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5418 if (SR != SectionRef()) {
5419 info.S = SR;
5420 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5421 } else {
5422 const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
5423 info.S = SR;
5424 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5425 }
5426
5427 const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5428 if (CA != SectionRef()) {
5429 info.S = CA;
5430 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5431 } else {
5432 const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
5433 info.S = CA;
5434 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5435 }
5436
5437 const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5438 if (PL != SectionRef()) {
5439 info.S = PL;
5440 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5441 } else {
5442 const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
5443 info.S = PL;
5444 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5445 }
5446
5447 const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5448 if (MR != SectionRef()) {
5449 info.S = MR;
5450 print_message_refs32(MR, &info);
5451 } else {
5452 const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
5453 info.S = MR;
5454 print_message_refs32(MR, &info);
5455 }
5456
5457 const SectionRef II = get_section(O, "__OBJC2", "__image_info");
5458 if (II != SectionRef()) {
5459 info.S = II;
5460 print_image_info32(II, &info);
5461 } else {
5462 const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
5463 info.S = II;
5464 print_image_info32(II, &info);
5465 }
Kevin Enderby0fc11822015-04-01 20:57:01 +00005466}
5467
5468static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby846c0002015-04-16 17:19:59 +00005469 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5470 const char *r, *name, *defs;
5471 struct objc_module_t module;
5472 SectionRef S, xS;
5473 struct objc_symtab_t symtab;
5474 struct objc_class_t objc_class;
5475 struct objc_category_t objc_category;
5476
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005477 outs() << "Objective-C segment\n";
Kevin Enderby846c0002015-04-16 17:19:59 +00005478 S = get_section(O, "__OBJC", "__module_info");
5479 if (S == SectionRef())
5480 return false;
5481
5482 SymbolAddressMap AddrMap;
5483 if (verbose)
5484 CreateSymbolAddressMap(O, &AddrMap);
5485
5486 std::vector<SectionRef> Sections;
5487 for (const SectionRef &Section : O->sections()) {
5488 StringRef SectName;
5489 Section.getName(SectName);
5490 Sections.push_back(Section);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005491 }
Kevin Enderby846c0002015-04-16 17:19:59 +00005492
5493 struct DisassembleInfo info;
5494 // Set up the block of info used by the Symbolizer call backs.
5495 info.verbose = verbose;
5496 info.O = O;
5497 info.AddrMap = &AddrMap;
5498 info.Sections = &Sections;
5499 info.class_name = nullptr;
5500 info.selector_name = nullptr;
5501 info.method = nullptr;
5502 info.demangled_name = nullptr;
5503 info.bindtable = nullptr;
5504 info.adrp_addr = 0;
5505 info.adrp_inst = 0;
5506
5507 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5508 p = S.getAddress() + i;
5509 r = get_pointer_32(p, offset, left, S, &info, true);
5510 if (r == nullptr)
5511 return true;
5512 memset(&module, '\0', sizeof(struct objc_module_t));
5513 if (left < sizeof(struct objc_module_t)) {
5514 memcpy(&module, r, left);
5515 outs() << " (module extends past end of __module_info section)\n";
5516 } else
5517 memcpy(&module, r, sizeof(struct objc_module_t));
5518 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5519 swapStruct(module);
5520
5521 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5522 outs() << " version " << module.version << "\n";
5523 outs() << " size " << module.size << "\n";
5524 outs() << " name ";
5525 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5526 if (name != nullptr)
5527 outs() << format("%.*s", left, name);
5528 else
5529 outs() << format("0x%08" PRIx32, module.name)
5530 << "(not in an __OBJC section)";
5531 outs() << "\n";
5532
5533 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5534 if (module.symtab == 0 || r == nullptr) {
5535 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5536 << " (not in an __OBJC section)\n";
5537 continue;
5538 }
5539 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5540 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5541 defs_left = 0;
5542 defs = nullptr;
5543 if (left < sizeof(struct objc_symtab_t)) {
5544 memcpy(&symtab, r, left);
5545 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5546 } else {
5547 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5548 if (left > sizeof(struct objc_symtab_t)) {
5549 defs_left = left - sizeof(struct objc_symtab_t);
5550 defs = r + sizeof(struct objc_symtab_t);
5551 }
5552 }
5553 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5554 swapStruct(symtab);
5555
5556 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5557 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5558 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5559 if (r == nullptr)
5560 outs() << " (not in an __OBJC section)";
5561 outs() << "\n";
5562 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5563 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5564 if (symtab.cls_def_cnt > 0)
5565 outs() << "\tClass Definitions\n";
5566 for (j = 0; j < symtab.cls_def_cnt; j++) {
5567 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5568 outs() << "\t(remaining class defs entries entends past the end of the "
5569 << "section)\n";
5570 break;
5571 }
5572 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5573 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5574 sys::swapByteOrder(def);
5575
5576 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5577 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5578 if (r != nullptr) {
5579 if (left > sizeof(struct objc_class_t)) {
5580 outs() << "\n";
5581 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5582 } else {
5583 outs() << " (entends past the end of the section)\n";
5584 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5585 memcpy(&objc_class, r, left);
5586 }
5587 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5588 swapStruct(objc_class);
5589 print_objc_class_t(&objc_class, &info);
5590 } else {
5591 outs() << "(not in an __OBJC section)\n";
5592 }
5593
5594 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
5595 outs() << "\tMeta Class";
5596 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
5597 if (r != nullptr) {
5598 if (left > sizeof(struct objc_class_t)) {
5599 outs() << "\n";
5600 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5601 } else {
5602 outs() << " (entends past the end of the section)\n";
5603 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5604 memcpy(&objc_class, r, left);
5605 }
5606 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5607 swapStruct(objc_class);
5608 print_objc_class_t(&objc_class, &info);
5609 } else {
5610 outs() << "(not in an __OBJC section)\n";
5611 }
5612 }
5613 }
5614 if (symtab.cat_def_cnt > 0)
5615 outs() << "\tCategory Definitions\n";
5616 for (j = 0; j < symtab.cat_def_cnt; j++) {
5617 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
5618 outs() << "\t(remaining category defs entries entends past the end of "
5619 << "the section)\n";
5620 break;
5621 }
5622 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
5623 sizeof(uint32_t));
5624 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5625 sys::swapByteOrder(def);
5626
5627 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5628 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
5629 << format("0x%08" PRIx32, def);
5630 if (r != nullptr) {
5631 if (left > sizeof(struct objc_category_t)) {
5632 outs() << "\n";
5633 memcpy(&objc_category, r, sizeof(struct objc_category_t));
5634 } else {
5635 outs() << " (entends past the end of the section)\n";
5636 memset(&objc_category, '\0', sizeof(struct objc_category_t));
5637 memcpy(&objc_category, r, left);
5638 }
5639 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5640 swapStruct(objc_category);
5641 print_objc_objc_category_t(&objc_category, &info);
5642 } else {
5643 outs() << "(not in an __OBJC section)\n";
5644 }
5645 }
5646 }
5647 const SectionRef II = get_section(O, "__OBJC", "__image_info");
5648 if (II != SectionRef())
5649 print_image_info(II, &info);
5650
5651 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005652}
5653
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00005654static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
5655 uint32_t size, uint32_t addr) {
5656 SymbolAddressMap AddrMap;
5657 CreateSymbolAddressMap(O, &AddrMap);
5658
5659 std::vector<SectionRef> Sections;
5660 for (const SectionRef &Section : O->sections()) {
5661 StringRef SectName;
5662 Section.getName(SectName);
5663 Sections.push_back(Section);
5664 }
5665
5666 struct DisassembleInfo info;
5667 // Set up the block of info used by the Symbolizer call backs.
5668 info.verbose = true;
5669 info.O = O;
5670 info.AddrMap = &AddrMap;
5671 info.Sections = &Sections;
5672 info.class_name = nullptr;
5673 info.selector_name = nullptr;
5674 info.method = nullptr;
5675 info.demangled_name = nullptr;
5676 info.bindtable = nullptr;
5677 info.adrp_addr = 0;
5678 info.adrp_inst = 0;
5679
5680 const char *p;
5681 struct objc_protocol_t protocol;
5682 uint32_t left, paddr;
5683 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
5684 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
5685 left = size - (p - sect);
5686 if (left < sizeof(struct objc_protocol_t)) {
5687 outs() << "Protocol extends past end of __protocol section\n";
5688 memcpy(&protocol, p, left);
5689 } else
5690 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
5691 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5692 swapStruct(protocol);
5693 paddr = addr + (p - sect);
5694 outs() << "Protocol " << format("0x%" PRIx32, paddr);
5695 if (print_protocol(paddr, 0, &info))
5696 outs() << "(not in an __OBJC section)\n";
5697 }
5698}
5699
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005700#ifdef HAVE_LIBXAR
5701inline void swapStruct(struct xar_header &xar) {
5702 sys::swapByteOrder(xar.magic);
5703 sys::swapByteOrder(xar.size);
5704 sys::swapByteOrder(xar.version);
5705 sys::swapByteOrder(xar.toc_length_compressed);
5706 sys::swapByteOrder(xar.toc_length_uncompressed);
5707 sys::swapByteOrder(xar.cksum_alg);
5708}
5709
5710static void PrintModeVerbose(uint32_t mode) {
5711 switch(mode & S_IFMT){
5712 case S_IFDIR:
5713 outs() << "d";
5714 break;
5715 case S_IFCHR:
5716 outs() << "c";
5717 break;
5718 case S_IFBLK:
5719 outs() << "b";
5720 break;
5721 case S_IFREG:
5722 outs() << "-";
5723 break;
5724 case S_IFLNK:
5725 outs() << "l";
5726 break;
5727 case S_IFSOCK:
5728 outs() << "s";
5729 break;
5730 default:
5731 outs() << "?";
5732 break;
5733 }
5734
5735 /* owner permissions */
5736 if(mode & S_IREAD)
5737 outs() << "r";
5738 else
5739 outs() << "-";
5740 if(mode & S_IWRITE)
5741 outs() << "w";
5742 else
5743 outs() << "-";
5744 if(mode & S_ISUID)
5745 outs() << "s";
5746 else if(mode & S_IEXEC)
5747 outs() << "x";
5748 else
5749 outs() << "-";
5750
5751 /* group permissions */
5752 if(mode & (S_IREAD >> 3))
5753 outs() << "r";
5754 else
5755 outs() << "-";
5756 if(mode & (S_IWRITE >> 3))
5757 outs() << "w";
5758 else
5759 outs() << "-";
5760 if(mode & S_ISGID)
5761 outs() << "s";
5762 else if(mode & (S_IEXEC >> 3))
5763 outs() << "x";
5764 else
5765 outs() << "-";
5766
5767 /* other permissions */
5768 if(mode & (S_IREAD >> 6))
5769 outs() << "r";
5770 else
5771 outs() << "-";
5772 if(mode & (S_IWRITE >> 6))
5773 outs() << "w";
5774 else
5775 outs() << "-";
5776 if(mode & S_ISVTX)
5777 outs() << "t";
5778 else if(mode & (S_IEXEC >> 6))
5779 outs() << "x";
5780 else
5781 outs() << "-";
5782}
5783
5784static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
5785 xar_iter_t xi;
5786 xar_file_t xf;
5787 xar_iter_t xp;
5788 const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
5789 char *endp;
5790 uint32_t mode_value;
5791
5792 xi = xar_iter_new();
5793 if (!xi) {
5794 errs() << "Can't obtain an xar iterator for xar archive "
5795 << XarFilename << "\n";
5796 return;
5797 }
5798
5799 // Go through the xar's files.
5800 for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
5801 xp = xar_iter_new();
5802 if(!xp){
5803 errs() << "Can't obtain an xar iterator for xar archive "
5804 << XarFilename << "\n";
5805 return;
5806 }
5807 type = nullptr;
5808 mode = nullptr;
5809 user = nullptr;
5810 group = nullptr;
5811 size = nullptr;
5812 mtime = nullptr;
5813 name = nullptr;
5814 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
5815 const char *val = nullptr;
5816 xar_prop_get(xf, key, &val);
5817#if 0 // Useful for debugging.
5818 outs() << "key: " << key << " value: " << val << "\n";
5819#endif
5820 if(strcmp(key, "type") == 0)
5821 type = val;
5822 if(strcmp(key, "mode") == 0)
5823 mode = val;
5824 if(strcmp(key, "user") == 0)
5825 user = val;
5826 if(strcmp(key, "group") == 0)
5827 group = val;
5828 if(strcmp(key, "data/size") == 0)
5829 size = val;
5830 if(strcmp(key, "mtime") == 0)
5831 mtime = val;
5832 if(strcmp(key, "name") == 0)
5833 name = val;
5834 }
5835 if(mode != nullptr){
5836 mode_value = strtoul(mode, &endp, 8);
5837 if(*endp != '\0')
5838 outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
5839 if(strcmp(type, "file") == 0)
5840 mode_value |= S_IFREG;
5841 PrintModeVerbose(mode_value);
5842 outs() << " ";
5843 }
5844 if(user != nullptr)
5845 outs() << format("%10s/", user);
5846 if(group != nullptr)
5847 outs() << format("%-10s ", group);
5848 if(size != nullptr)
5849 outs() << format("%7s ", size);
5850 if(mtime != nullptr){
5851 for(m = mtime; *m != 'T' && *m != '\0'; m++)
5852 outs() << *m;
5853 if(*m == 'T')
5854 m++;
5855 outs() << " ";
5856 for( ; *m != 'Z' && *m != '\0'; m++)
5857 outs() << *m;
5858 outs() << " ";
5859 }
5860 if(name != nullptr)
5861 outs() << name;
5862 outs() << "\n";
5863 }
5864}
5865
5866static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
5867 uint32_t size, bool verbose,
5868 bool PrintXarHeader, bool PrintXarFileHeaders,
5869 std::string XarMemberName) {
5870 if(size < sizeof(struct xar_header)) {
5871 outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
5872 "of struct xar_header)\n";
5873 return;
5874 }
5875 struct xar_header XarHeader;
5876 memcpy(&XarHeader, sect, sizeof(struct xar_header));
5877 if (sys::IsLittleEndianHost)
5878 swapStruct(XarHeader);
5879 if (PrintXarHeader) {
5880 if (!XarMemberName.empty())
5881 outs() << "In xar member " << XarMemberName << ": ";
5882 else
5883 outs() << "For (__LLVM,__bundle) section: ";
5884 outs() << "xar header\n";
5885 if (XarHeader.magic == XAR_HEADER_MAGIC)
5886 outs() << " magic XAR_HEADER_MAGIC\n";
5887 else
5888 outs() << " magic "
5889 << format_hex(XarHeader.magic, 10, true)
5890 << " (not XAR_HEADER_MAGIC)\n";
5891 outs() << " size " << XarHeader.size << "\n";
5892 outs() << " version " << XarHeader.version << "\n";
5893 outs() << " toc_length_compressed " << XarHeader.toc_length_compressed
5894 << "\n";
5895 outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
5896 << "\n";
5897 outs() << " cksum_alg ";
5898 switch (XarHeader.cksum_alg) {
5899 case XAR_CKSUM_NONE:
5900 outs() << "XAR_CKSUM_NONE\n";
5901 break;
5902 case XAR_CKSUM_SHA1:
5903 outs() << "XAR_CKSUM_SHA1\n";
5904 break;
5905 case XAR_CKSUM_MD5:
5906 outs() << "XAR_CKSUM_MD5\n";
5907 break;
Kevin Enderby42882282016-05-23 22:18:59 +00005908#ifdef XAR_CKSUM_SHA256
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005909 case XAR_CKSUM_SHA256:
5910 outs() << "XAR_CKSUM_SHA256\n";
5911 break;
Kevin Enderby42882282016-05-23 22:18:59 +00005912#endif
5913#ifdef XAR_CKSUM_SHA512
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005914 case XAR_CKSUM_SHA512:
5915 outs() << "XAR_CKSUM_SHA512\n";
5916 break;
Kevin Enderby42882282016-05-23 22:18:59 +00005917#endif
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005918 default:
5919 outs() << XarHeader.cksum_alg << "\n";
5920 }
5921 }
5922
5923 SmallString<128> XarFilename;
5924 int FD;
5925 std::error_code XarEC =
5926 sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
5927 if (XarEC) {
5928 errs() << XarEC.message() << "\n";
5929 return;
5930 }
5931 tool_output_file XarFile(XarFilename, FD);
5932 raw_fd_ostream &XarOut = XarFile.os();
5933 StringRef XarContents(sect, size);
5934 XarOut << XarContents;
5935 XarOut.close();
5936 if (XarOut.has_error())
5937 return;
5938
5939 xar_t xar = xar_open(XarFilename.c_str(), READ);
5940 if (!xar) {
5941 errs() << "Can't create temporary xar archive " << XarFilename << "\n";
5942 return;
5943 }
5944
5945 SmallString<128> TocFilename;
5946 std::error_code TocEC =
5947 sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
5948 if (TocEC) {
5949 errs() << TocEC.message() << "\n";
5950 return;
5951 }
5952 xar_serialize(xar, TocFilename.c_str());
5953
5954 if (PrintXarFileHeaders) {
5955 if (!XarMemberName.empty())
5956 outs() << "In xar member " << XarMemberName << ": ";
5957 else
5958 outs() << "For (__LLVM,__bundle) section: ";
5959 outs() << "xar archive files:\n";
5960 PrintXarFilesSummary(XarFilename.c_str(), xar);
5961 }
5962
5963 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
5964 MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
5965 if (std::error_code EC = FileOrErr.getError()) {
5966 errs() << EC.message() << "\n";
5967 return;
5968 }
5969 std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
5970
5971 if (!XarMemberName.empty())
5972 outs() << "In xar member " << XarMemberName << ": ";
5973 else
5974 outs() << "For (__LLVM,__bundle) section: ";
5975 outs() << "xar table of contents:\n";
5976 outs() << Buffer->getBuffer() << "\n";
5977
5978 // TODO: Go through the xar's files.
5979 xar_iter_t xi = xar_iter_new();
5980 if(!xi){
5981 errs() << "Can't obtain an xar iterator for xar archive "
5982 << XarFilename.c_str() << "\n";
5983 xar_close(xar);
5984 return;
5985 }
5986 for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
5987 const char *key;
5988 xar_iter_t xp;
5989 const char *member_name, *member_type, *member_size_string;
5990 size_t member_size;
5991
5992 xp = xar_iter_new();
5993 if(!xp){
5994 errs() << "Can't obtain an xar iterator for xar archive "
5995 << XarFilename.c_str() << "\n";
5996 xar_close(xar);
5997 return;
5998 }
5999 member_name = NULL;
6000 member_type = NULL;
6001 member_size_string = NULL;
6002 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
6003 const char *val = nullptr;
6004 xar_prop_get(xf, key, &val);
6005#if 0 // Useful for debugging.
6006 outs() << "key: " << key << " value: " << val << "\n";
6007#endif
6008 if(strcmp(key, "name") == 0)
6009 member_name = val;
6010 if(strcmp(key, "type") == 0)
6011 member_type = val;
6012 if(strcmp(key, "data/size") == 0)
6013 member_size_string = val;
6014 }
6015 /*
6016 * If we find a file with a name, date/size and type properties
6017 * and with the type being "file" see if that is a xar file.
6018 */
6019 if (member_name != NULL && member_type != NULL &&
6020 strcmp(member_type, "file") == 0 &&
6021 member_size_string != NULL){
6022 // Extract the file into a buffer.
6023 char *endptr;
6024 member_size = strtoul(member_size_string, &endptr, 10);
6025 if (*endptr == '\0' && member_size != 0) {
6026 char *buffer = (char *) ::operator new (member_size);
6027 if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
6028#if 0 // Useful for debugging.
6029 outs() << "xar member: " << member_name << " extracted\n";
6030#endif
6031 // Set the XarMemberName we want to see printed in the header.
6032 std::string OldXarMemberName;
6033 // If XarMemberName is already set this is nested. So
6034 // save the old name and create the nested name.
6035 if (!XarMemberName.empty()) {
6036 OldXarMemberName = XarMemberName;
6037 XarMemberName =
6038 (Twine("[") + XarMemberName + "]" + member_name).str();
6039 } else {
6040 OldXarMemberName = "";
6041 XarMemberName = member_name;
6042 }
6043 // See if this is could be a xar file (nested).
6044 if (member_size >= sizeof(struct xar_header)) {
6045#if 0 // Useful for debugging.
6046 outs() << "could be a xar file: " << member_name << "\n";
6047#endif
6048 memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
6049 if (sys::IsLittleEndianHost)
6050 swapStruct(XarHeader);
6051 if(XarHeader.magic == XAR_HEADER_MAGIC)
6052 DumpBitcodeSection(O, buffer, member_size, verbose,
6053 PrintXarHeader, PrintXarFileHeaders,
6054 XarMemberName);
6055 }
6056 XarMemberName = OldXarMemberName;
6057 }
6058 delete buffer;
6059 }
6060 }
6061 xar_iter_free(xp);
6062 }
6063 xar_close(xar);
6064}
6065#endif // defined(HAVE_LIBXAR)
6066
Kevin Enderby0fc11822015-04-01 20:57:01 +00006067static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6068 if (O->is64Bit())
6069 printObjc2_64bit_MetaData(O, verbose);
6070 else {
6071 MachO::mach_header H;
6072 H = O->getHeader();
6073 if (H.cputype == MachO::CPU_TYPE_ARM)
6074 printObjc2_32bit_MetaData(O, verbose);
6075 else {
6076 // This is the 32-bit non-arm cputype case. Which is normally
6077 // the first Objective-C ABI. But it may be the case of a
6078 // binary for the iOS simulator which is the second Objective-C
6079 // ABI. In that case printObjc1_32bit_MetaData() will determine that
6080 // and return false.
Hans Wennborgcc9deb42015-09-29 18:02:48 +00006081 if (!printObjc1_32bit_MetaData(O, verbose))
Kevin Enderby0fc11822015-04-01 20:57:01 +00006082 printObjc2_32bit_MetaData(O, verbose);
6083 }
6084 }
6085}
6086
Kevin Enderbybf246f52014-09-24 23:08:22 +00006087// GuessLiteralPointer returns a string which for the item in the Mach-O file
6088// for the address passed in as ReferenceValue for printing as a comment with
6089// the instruction and also returns the corresponding type of that item
6090// indirectly through ReferenceType.
6091//
6092// If ReferenceValue is an address of literal cstring then a pointer to the
6093// cstring is returned and ReferenceType is set to
6094// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6095//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006096// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6097// Class ref that name is returned and the ReferenceType is set accordingly.
6098//
6099// Lastly, literals which are Symbol address in a literal pool are looked for
6100// and if found the symbol name is returned and ReferenceType is set to
6101// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6102//
6103// If there is no item in the Mach-O file for the address passed in as
6104// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006105static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6106 uint64_t ReferencePC,
6107 uint64_t *ReferenceType,
6108 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006109 // First see if there is an external relocation entry at the ReferencePC.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006110 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6111 uint64_t sect_addr = info->S.getAddress();
6112 uint64_t sect_offset = ReferencePC - sect_addr;
6113 bool reloc_found = false;
6114 DataRefImpl Rel;
6115 MachO::any_relocation_info RE;
6116 bool isExtern = false;
6117 SymbolRef Symbol;
6118 for (const RelocationRef &Reloc : info->S.relocations()) {
6119 uint64_t RelocOffset = Reloc.getOffset();
6120 if (RelocOffset == sect_offset) {
6121 Rel = Reloc.getRawDataRefImpl();
6122 RE = info->O->getRelocation(Rel);
6123 if (info->O->isRelocationScattered(RE))
6124 continue;
6125 isExtern = info->O->getPlainRelocationExternal(RE);
6126 if (isExtern) {
6127 symbol_iterator RelocSym = Reloc.getSymbol();
6128 Symbol = *RelocSym;
6129 }
6130 reloc_found = true;
6131 break;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006132 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006133 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006134 // If there is an external relocation entry for a symbol in a section
6135 // then used that symbol's value for the value of the reference.
6136 if (reloc_found && isExtern) {
6137 if (info->O->getAnyRelocationPCRel(RE)) {
6138 unsigned Type = info->O->getAnyRelocationType(RE);
6139 if (Type == MachO::X86_64_RELOC_SIGNED) {
6140 ReferenceValue = Symbol.getValue();
6141 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006142 }
6143 }
6144 }
6145
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006146 // Look for literals such as Objective-C CFStrings refs, Selector refs,
6147 // Message refs and Class refs.
6148 bool classref, selref, msgref, cfstring;
6149 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6150 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00006151 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006152 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6153 // And the pointer_value in that section is typically zero as it will be
6154 // set by dyld as part of the "bind information".
6155 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6156 if (name != nullptr) {
6157 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00006158 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006159 if (class_name != nullptr && class_name[1] == '_' &&
6160 class_name[2] != '\0') {
6161 info->class_name = class_name + 2;
6162 return name;
6163 }
6164 }
6165 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006166
David Blaikie33dd45d02015-03-23 18:39:02 +00006167 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006168 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6169 const char *name =
6170 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6171 if (name != nullptr)
6172 info->class_name = name;
6173 else
6174 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00006175 return name;
6176 }
6177
David Blaikie33dd45d02015-03-23 18:39:02 +00006178 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006179 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6180 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6181 return name;
6182 }
6183
David Blaikie33dd45d02015-03-23 18:39:02 +00006184 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006185 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6186
6187 if (pointer_value != 0)
6188 ReferenceValue = pointer_value;
6189
6190 const char *name = GuessCstringPointer(ReferenceValue, info);
6191 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00006192 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006193 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6194 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00006195 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006196 info->class_name = nullptr;
6197 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6198 info->selector_name = name;
6199 } else
6200 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6201 return name;
6202 }
6203
6204 // Lastly look for an indirect symbol with this ReferenceValue which is in
6205 // a literal pool. If found return that symbol name.
6206 name = GuessIndirectSymbol(ReferenceValue, info);
6207 if (name) {
6208 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6209 return name;
6210 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006211
6212 return nullptr;
6213}
6214
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006215// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00006216// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006217// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6218// is created and returns the symbol name that matches the ReferenceValue or
6219// nullptr if none. The ReferenceType is passed in for the IN type of
6220// reference the instruction is making from the values in defined in the header
6221// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
6222// Out type and the ReferenceName will also be set which is added as a comment
6223// to the disassembled instruction.
6224//
Kevin Enderby04bf6932014-10-28 23:39:46 +00006225#if HAVE_CXXABI_H
6226// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006227// returned through ReferenceName and ReferenceType is set to
6228// LLVMDisassembler_ReferenceType_DeMangled_Name .
Kevin Enderby04bf6932014-10-28 23:39:46 +00006229#endif
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006230//
6231// When this is called to get a symbol name for a branch target then the
6232// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
6233// SymbolValue will be looked for in the indirect symbol table to determine if
6234// it is an address for a symbol stub. If so then the symbol name for that
6235// stub is returned indirectly through ReferenceName and then ReferenceType is
6236// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
6237//
Kevin Enderbybf246f52014-09-24 23:08:22 +00006238// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006239// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
6240// SymbolValue is checked to be an address of literal pointer, symbol pointer,
6241// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006242// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006243static const char *SymbolizerSymbolLookUp(void *DisInfo,
6244 uint64_t ReferenceValue,
6245 uint64_t *ReferenceType,
6246 uint64_t ReferencePC,
6247 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006248 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006249 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00006250 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006251 *ReferenceName = nullptr;
6252 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006253 return nullptr;
6254 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006255
Kevin Enderbyf6d25852015-01-31 00:37:11 +00006256 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006257
Kevin Enderby85974882014-09-26 22:20:44 +00006258 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
6259 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006260 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006261 method_reference(info, ReferenceType, ReferenceName);
6262 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
6263 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
6264 } else
Kevin Enderby04bf6932014-10-28 23:39:46 +00006265#if HAVE_CXXABI_H
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006266 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006267 if (info->demangled_name != nullptr)
6268 free(info->demangled_name);
6269 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006270 info->demangled_name =
6271 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006272 if (info->demangled_name != nullptr) {
6273 *ReferenceName = info->demangled_name;
6274 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6275 } else
6276 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6277 } else
6278#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006279 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6280 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
6281 *ReferenceName =
6282 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00006283 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006284 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00006285 else
6286 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006287 // If this is arm64 and the reference is an adrp instruction save the
6288 // instruction, passed in ReferenceValue and the address of the instruction
6289 // for use later if we see and add immediate instruction.
6290 } else if (info->O->getArch() == Triple::aarch64 &&
6291 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
6292 info->adrp_inst = ReferenceValue;
6293 info->adrp_addr = ReferencePC;
6294 SymbolName = nullptr;
6295 *ReferenceName = nullptr;
6296 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6297 // If this is arm64 and reference is an add immediate instruction and we
6298 // have
6299 // seen an adrp instruction just before it and the adrp's Xd register
6300 // matches
6301 // this add's Xn register reconstruct the value being referenced and look to
6302 // see if it is a literal pointer. Note the add immediate instruction is
6303 // passed in ReferenceValue.
6304 } else if (info->O->getArch() == Triple::aarch64 &&
6305 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
6306 ReferencePC - 4 == info->adrp_addr &&
6307 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6308 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6309 uint32_t addxri_inst;
6310 uint64_t adrp_imm, addxri_imm;
6311
6312 adrp_imm =
6313 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6314 if (info->adrp_inst & 0x0200000)
6315 adrp_imm |= 0xfffffffffc000000LL;
6316
6317 addxri_inst = ReferenceValue;
6318 addxri_imm = (addxri_inst >> 10) & 0xfff;
6319 if (((addxri_inst >> 22) & 0x3) == 1)
6320 addxri_imm <<= 12;
6321
6322 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6323 (adrp_imm << 12) + addxri_imm;
6324
6325 *ReferenceName =
6326 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6327 if (*ReferenceName == nullptr)
6328 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6329 // If this is arm64 and the reference is a load register instruction and we
6330 // have seen an adrp instruction just before it and the adrp's Xd register
6331 // matches this add's Xn register reconstruct the value being referenced and
6332 // look to see if it is a literal pointer. Note the load register
6333 // instruction is passed in ReferenceValue.
6334 } else if (info->O->getArch() == Triple::aarch64 &&
6335 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
6336 ReferencePC - 4 == info->adrp_addr &&
6337 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6338 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6339 uint32_t ldrxui_inst;
6340 uint64_t adrp_imm, ldrxui_imm;
6341
6342 adrp_imm =
6343 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6344 if (info->adrp_inst & 0x0200000)
6345 adrp_imm |= 0xfffffffffc000000LL;
6346
6347 ldrxui_inst = ReferenceValue;
6348 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
6349
6350 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6351 (adrp_imm << 12) + (ldrxui_imm << 3);
6352
6353 *ReferenceName =
6354 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6355 if (*ReferenceName == nullptr)
6356 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6357 }
6358 // If this arm64 and is an load register (PC-relative) instruction the
6359 // ReferenceValue is the PC plus the immediate value.
6360 else if (info->O->getArch() == Triple::aarch64 &&
6361 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
6362 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
6363 *ReferenceName =
6364 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6365 if (*ReferenceName == nullptr)
6366 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby85974882014-09-26 22:20:44 +00006367 }
Kevin Enderby04bf6932014-10-28 23:39:46 +00006368#if HAVE_CXXABI_H
6369 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
6370 if (info->demangled_name != nullptr)
6371 free(info->demangled_name);
6372 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006373 info->demangled_name =
6374 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006375 if (info->demangled_name != nullptr) {
6376 *ReferenceName = info->demangled_name;
6377 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6378 }
6379 }
6380#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006381 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006382 *ReferenceName = nullptr;
6383 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6384 }
6385
6386 return SymbolName;
6387}
6388
Kevin Enderbybf246f52014-09-24 23:08:22 +00006389/// \brief Emits the comments that are stored in the CommentStream.
6390/// Each comment in the CommentStream must end with a newline.
6391static void emitComments(raw_svector_ostream &CommentStream,
6392 SmallString<128> &CommentsToEmit,
6393 formatted_raw_ostream &FormattedOS,
6394 const MCAsmInfo &MAI) {
6395 // Flush the stream before taking its content.
Kevin Enderbybf246f52014-09-24 23:08:22 +00006396 StringRef Comments = CommentsToEmit.str();
6397 // Get the default information for printing a comment.
6398 const char *CommentBegin = MAI.getCommentString();
6399 unsigned CommentColumn = MAI.getCommentColumn();
6400 bool IsFirst = true;
6401 while (!Comments.empty()) {
6402 if (!IsFirst)
6403 FormattedOS << '\n';
6404 // Emit a line of comments.
6405 FormattedOS.PadToColumn(CommentColumn);
6406 size_t Position = Comments.find('\n');
6407 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
6408 // Move after the newline character.
6409 Comments = Comments.substr(Position + 1);
6410 IsFirst = false;
6411 }
6412 FormattedOS.flush();
6413
6414 // Tell the comment stream that the vector changed underneath it.
6415 CommentsToEmit.clear();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006416}
6417
Kevin Enderby95df54c2015-02-04 01:01:38 +00006418static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
6419 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006420 const char *McpuDefault = nullptr;
6421 const Target *ThumbTarget = nullptr;
6422 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006423 if (!TheTarget) {
6424 // GetTarget prints out stuff.
6425 return;
6426 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006427 if (MCPU.empty() && McpuDefault)
6428 MCPU = McpuDefault;
6429
Ahmed Charles56440fd2014-03-06 05:51:42 +00006430 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006431 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006432 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006433 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006434
Kevin Enderbyc9595622014-08-06 23:24:41 +00006435 // Package up features to be passed to target/subtarget
6436 std::string FeaturesStr;
6437 if (MAttrs.size()) {
6438 SubtargetFeatures Features;
6439 for (unsigned i = 0; i != MAttrs.size(); ++i)
6440 Features.AddFeature(MAttrs[i]);
6441 FeaturesStr = Features.getString();
6442 }
6443
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006444 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00006445 std::unique_ptr<const MCRegisterInfo> MRI(
6446 TheTarget->createMCRegInfo(TripleName));
6447 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00006448 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00006449 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +00006450 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00006451 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006452 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006453 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006454 std::unique_ptr<MCSymbolizer> Symbolizer;
6455 struct DisassembleInfo SymbolizerInfo;
6456 std::unique_ptr<MCRelocationInfo> RelInfo(
6457 TheTarget->createMCRelocationInfo(TripleName, Ctx));
6458 if (RelInfo) {
6459 Symbolizer.reset(TheTarget->createMCSymbolizer(
6460 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006461 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006462 DisAsm->setSymbolizer(std::move(Symbolizer));
6463 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006464 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00006465 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006466 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006467 // Set the display preference for hex vs. decimal immediates.
6468 IP->setPrintImmHex(PrintImmHex);
6469 // Comment stream and backing vector.
6470 SmallString<128> CommentsToEmit;
6471 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006472 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
6473 // if it is done then arm64 comments for string literals don't get printed
6474 // and some constant get printed instead and not setting it causes intel
6475 // (32-bit and 64-bit) comments printed with different spacing before the
6476 // comment causing different diffs with the 'C' disassembler library API.
6477 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006478
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006479 if (!AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencerc1363cf2011-10-07 19:25:47 +00006480 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006481 << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006482 return;
6483 }
6484
Tim Northover09ca33e2016-04-22 23:23:31 +00006485 // Set up separate thumb disassembler if needed.
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006486 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
6487 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
6488 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006489 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006490 std::unique_ptr<MCInstPrinter> ThumbIP;
6491 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006492 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
6493 struct DisassembleInfo ThumbSymbolizerInfo;
6494 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006495 if (ThumbTarget) {
6496 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
6497 ThumbAsmInfo.reset(
6498 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
6499 ThumbSTI.reset(
6500 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
6501 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
6502 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006503 MCContext *PtrThumbCtx = ThumbCtx.get();
6504 ThumbRelInfo.reset(
6505 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
6506 if (ThumbRelInfo) {
6507 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
6508 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006509 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006510 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
6511 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006512 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
6513 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006514 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
6515 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006516 // Set the display preference for hex vs. decimal immediates.
6517 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006518 }
6519
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006520 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006521 errs() << "error: couldn't initialize disassembler for target "
6522 << ThumbTripleName << '\n';
6523 return;
6524 }
6525
Charles Davis8bdfafd2013-09-01 04:28:48 +00006526 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006527
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006528 // FIXME: Using the -cfg command line option, this code used to be able to
6529 // annotate relocations with the referenced symbol's name, and if this was
6530 // inside a __[cf]string section, the data it points to. This is now replaced
6531 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00006532 std::vector<SectionRef> Sections;
6533 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006534 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00006535 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006536
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00006537 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
Kevin Enderby273ae012013-06-06 17:20:50 +00006538 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006539
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006540 // Sort the symbols by address, just in case they didn't come in that way.
Owen Andersond9243c42011-10-17 21:37:35 +00006541 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006542
Kevin Enderby273ae012013-06-06 17:20:50 +00006543 // Build a data in code table that is sorted on by the address of each entry.
6544 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00006545 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00006546 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00006547 else
6548 BaseAddress = BaseSegmentAddress;
6549 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00006550 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00006551 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006552 uint32_t Offset;
6553 DI->getOffset(Offset);
6554 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6555 }
6556 array_pod_sort(Dices.begin(), Dices.end());
6557
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006558#ifndef NDEBUG
6559 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6560#else
6561 raw_ostream &DebugOut = nulls();
6562#endif
6563
Ahmed Charles56440fd2014-03-06 05:51:42 +00006564 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00006565 ObjectFile *DbgObj = MachOOF;
Benjamin Kramer699128e2011-09-21 01:13:19 +00006566 // Try to find debug info and set up the DIContext for it.
6567 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00006568 // A separate DSym file path was specified, parse it as a macho file,
6569 // get the sections and supply it to the section name parsing machinery.
6570 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00006571 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006572 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00006573 if (std::error_code EC = BufOrErr.getError()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006574 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +00006575 return;
6576 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00006577 DbgObj =
6578 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
6579 .get()
6580 .release();
Benjamin Kramer699128e2011-09-21 01:13:19 +00006581 }
6582
Eric Christopher7370b552012-11-12 21:40:38 +00006583 // Setup the DIContext
Zachary Turner6489d7b2015-04-23 17:37:47 +00006584 diContext.reset(new DWARFContextInMemory(*DbgObj));
Benjamin Kramer699128e2011-09-21 01:13:19 +00006585 }
6586
Colin LeMahieufcc32762015-07-29 19:08:10 +00006587 if (FilterSections.size() == 0)
Kevin Enderby95df54c2015-02-04 01:01:38 +00006588 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006589
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006590 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00006591 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00006592 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6593 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006594
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006595 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006596
Rafael Espindolab0f76a42013-04-05 15:15:22 +00006597 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00006598 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006599 continue;
6600
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006601 StringRef BytesStr;
6602 Sections[SectIdx].getContents(BytesStr);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00006603 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6604 BytesStr.size());
Rafael Espindola80291272014-10-08 15:28:58 +00006605 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00006606
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006607 bool symbolTableWorked = false;
6608
Kevin Enderbybf246f52014-09-24 23:08:22 +00006609 // Create a map of symbol addresses to symbol names for use by
6610 // the SymbolizerSymbolLookUp() routine.
6611 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00006612 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006613 for (const SymbolRef &Symbol : MachOOF->symbols()) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006614 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
6615 if (!STOrErr) {
6616 std::string Buf;
6617 raw_string_ostream OS(Buf);
6618 logAllUnhandledErrors(STOrErr.takeError(), OS, "");
6619 OS.flush();
6620 report_fatal_error(Buf);
6621 }
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006622 SymbolRef::Type ST = *STOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006623 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
6624 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00006625 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006626 Expected<StringRef> SymNameOrErr = Symbol.getName();
6627 if (!SymNameOrErr) {
6628 std::string Buf;
6629 raw_string_ostream OS(Buf);
6630 logAllUnhandledErrors(SymNameOrErr.takeError(), OS, "");
6631 OS.flush();
6632 report_fatal_error(Buf);
6633 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006634 StringRef SymName = *SymNameOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006635 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00006636 if (!DisSymName.empty() && DisSymName == SymName)
6637 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006638 }
6639 }
David Blaikie33dd45d02015-03-23 18:39:02 +00006640 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00006641 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
6642 return;
6643 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006644 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006645 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006646 SymbolizerInfo.O = MachOOF;
6647 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00006648 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006649 SymbolizerInfo.Sections = &Sections;
6650 SymbolizerInfo.class_name = nullptr;
6651 SymbolizerInfo.selector_name = nullptr;
6652 SymbolizerInfo.method = nullptr;
Kevin Enderby04bf6932014-10-28 23:39:46 +00006653 SymbolizerInfo.demangled_name = nullptr;
Kevin Enderby078be602014-10-23 19:53:12 +00006654 SymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006655 SymbolizerInfo.adrp_addr = 0;
6656 SymbolizerInfo.adrp_inst = 0;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006657 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006658 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006659 ThumbSymbolizerInfo.O = MachOOF;
6660 ThumbSymbolizerInfo.S = Sections[SectIdx];
6661 ThumbSymbolizerInfo.AddrMap = &AddrMap;
6662 ThumbSymbolizerInfo.Sections = &Sections;
6663 ThumbSymbolizerInfo.class_name = nullptr;
6664 ThumbSymbolizerInfo.selector_name = nullptr;
6665 ThumbSymbolizerInfo.method = nullptr;
6666 ThumbSymbolizerInfo.demangled_name = nullptr;
6667 ThumbSymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006668 ThumbSymbolizerInfo.adrp_addr = 0;
6669 ThumbSymbolizerInfo.adrp_inst = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006670
Kevin Enderby4b627be2016-04-28 20:14:13 +00006671 unsigned int Arch = MachOOF->getArch();
6672
Tim Northoverf203ab52016-07-14 22:13:32 +00006673 // Skip all symbols if this is a stubs file.
6674 if (Bytes.size() == 0)
6675 return;
6676
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006677 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006678 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006679 Expected<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
6680 if (!SymNameOrErr) {
6681 std::string Buf;
6682 raw_string_ostream OS(Buf);
6683 logAllUnhandledErrors(SymNameOrErr.takeError(), OS, "");
6684 OS.flush();
6685 report_fatal_error(Buf);
6686 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006687 StringRef SymName = *SymNameOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00006688
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006689 Expected<SymbolRef::Type> STOrErr = Symbols[SymIdx].getType();
6690 if (!STOrErr) {
6691 std::string Buf;
6692 raw_string_ostream OS(Buf);
6693 logAllUnhandledErrors(STOrErr.takeError(), OS, "");
6694 OS.flush();
6695 report_fatal_error(Buf);
6696 }
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006697 SymbolRef::Type ST = *STOrErr;
Kuba Breckade833222015-11-12 09:40:29 +00006698 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
Owen Andersond9243c42011-10-17 21:37:35 +00006699 continue;
6700
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006701 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00006702 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00006703 if (!containsSym) {
6704 if (!DisSymName.empty() && DisSymName == SymName) {
6705 outs() << "-dis-symname: " << DisSymName << " not in the section\n";
6706 return;
6707 }
6708 continue;
6709 }
6710 // The __mh_execute_header is special and we need to deal with that fact
6711 // this symbol is before the start of the (__TEXT,__text) section and at the
6712 // address of the start of the __TEXT segment. This is because this symbol
6713 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
6714 // start of the section in a standard MH_EXECUTE filetype.
6715 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
6716 outs() << "-dis-symname: __mh_execute_header not in any section\n";
6717 return;
6718 }
Tim Northoverfbefee32016-07-14 23:13:03 +00006719 // When this code is trying to disassemble a symbol at a time and in the
6720 // case there is only the __mh_execute_header symbol left as in a stripped
6721 // executable, we need to deal with this by ignoring this symbol so the
6722 // whole section is disassembled and this symbol is then not displayed.
6723 if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
6724 SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
6725 SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006726 continue;
6727
Kevin Enderby6a221752015-03-17 17:10:57 +00006728 // If we are only disassembling one symbol see if this is that symbol.
6729 if (!DisSymName.empty() && DisSymName != SymName)
6730 continue;
6731
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006732 // Start at the address of the symbol relative to the section's address.
Tim Northoverf203ab52016-07-14 22:13:32 +00006733 uint64_t SectSize = Sections[SectIdx].getSize();
Rafael Espindoladea00162015-07-03 17:44:18 +00006734 uint64_t Start = Symbols[SymIdx].getValue();
Rafael Espindola80291272014-10-08 15:28:58 +00006735 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006736 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006737
Tim Northoverf203ab52016-07-14 22:13:32 +00006738 if (Start > SectSize) {
6739 outs() << "section data ends, " << SymName
6740 << " lies outside valid range\n";
6741 return;
6742 }
6743
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006744 // Stop disassembling either at the beginning of the next symbol or at
6745 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00006746 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00006747 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006748 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00006749 while (Symbols.size() > NextSymIdx) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006750 Expected<SymbolRef::Type> STOrErr = Symbols[NextSymIdx].getType();
6751 if (!STOrErr) {
6752 std::string Buf;
6753 raw_string_ostream OS(Buf);
6754 logAllUnhandledErrors(STOrErr.takeError(), OS, "");
6755 OS.flush();
6756 report_fatal_error(Buf);
6757 }
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006758 SymbolRef::Type NextSymType = *STOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00006759 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00006760 containsNextSym =
6761 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Rafael Espindoladea00162015-07-03 17:44:18 +00006762 NextSym = Symbols[NextSymIdx].getValue();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006763 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006764 break;
6765 }
6766 ++NextSymIdx;
6767 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006768
Tim Northoverf203ab52016-07-14 22:13:32 +00006769 uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00006770 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006771
6772 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00006773
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006774 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
Tim Northover09ca33e2016-04-22 23:23:31 +00006775 bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
6776
6777 // We only need the dedicated Thumb target if there's a real choice
6778 // (i.e. we're not targeting M-class) and the function is Thumb.
6779 bool UseThumbTarget = IsThumb && ThumbTarget;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006780
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006781 outs() << SymName << ":\n";
6782 DILineInfo lastLine;
6783 for (uint64_t Index = Start; Index < End; Index += Size) {
6784 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00006785
Kevin Enderbybf246f52014-09-24 23:08:22 +00006786 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006787 if (!NoLeadingAddr) {
6788 if (FullLeadingAddr) {
6789 if (MachOOF->is64Bit())
6790 outs() << format("%016" PRIx64, PC);
6791 else
6792 outs() << format("%08" PRIx64, PC);
6793 } else {
6794 outs() << format("%8" PRIx64 ":", PC);
6795 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006796 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00006797 if (!NoShowRawInsn || Arch == Triple::arm)
Kevin Enderbybf246f52014-09-24 23:08:22 +00006798 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00006799
6800 // Check the data in code table here to see if this is data not an
6801 // instruction to be disassembled.
6802 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006803 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006804 dice_table_iterator DTI =
6805 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
6806 compareDiceTableEntries);
6807 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006808 uint16_t Length;
6809 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00006810 uint16_t Kind;
6811 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00006812 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00006813 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
6814 (PC == (DTI->first + Length - 1)) && (Length & 1))
6815 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00006816 continue;
6817 }
6818
Kevin Enderbybf246f52014-09-24 23:08:22 +00006819 SmallVector<char, 64> AnnotationsBytes;
6820 raw_svector_ostream Annotations(AnnotationsBytes);
6821
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006822 bool gotInst;
Tim Northover09ca33e2016-04-22 23:23:31 +00006823 if (UseThumbTarget)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006824 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006825 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006826 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006827 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00006828 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006829 if (gotInst) {
Kevin Enderby4b627be2016-04-28 20:14:13 +00006830 if (!NoShowRawInsn || Arch == Triple::arm) {
Craig Topper0013be12015-09-21 05:32:41 +00006831 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006832 }
6833 formatted_raw_ostream FormattedOS(outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006834 StringRef AnnotationsStr = Annotations.str();
Tim Northover09ca33e2016-04-22 23:23:31 +00006835 if (UseThumbTarget)
Akira Hatanakab46d0232015-03-27 20:36:02 +00006836 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006837 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00006838 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006839 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00006840
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006841 // Print debug info.
6842 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006843 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006844 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00006845 if (dli != lastLine && dli.Line != 0)
6846 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
6847 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006848 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006849 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006850 outs() << "\n";
6851 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006852 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006853 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006854 outs() << format("\t.byte 0x%02x #bad opcode\n",
6855 *(Bytes.data() + Index) & 0xff);
6856 Size = 1; // skip exactly one illegible byte and move on.
Tim Northover09ca33e2016-04-22 23:23:31 +00006857 } else if (Arch == Triple::aarch64 ||
6858 (Arch == Triple::arm && !IsThumb)) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006859 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6860 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
6861 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
6862 (*(Bytes.data() + Index + 3) & 0xff) << 24;
6863 outs() << format("\t.long\t0x%08x\n", opcode);
6864 Size = 4;
Tim Northover09ca33e2016-04-22 23:23:31 +00006865 } else if (Arch == Triple::arm) {
6866 assert(IsThumb && "ARM mode should have been dealt with above");
6867 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6868 (*(Bytes.data() + Index + 1) & 0xff) << 8;
6869 outs() << format("\t.short\t0x%04x\n", opcode);
6870 Size = 2;
6871 } else{
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006872 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6873 if (Size == 0)
6874 Size = 1; // skip illegible bytes
6875 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006876 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006877 }
6878 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006879 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00006880 // Reading the symbol table didn't work, disassemble the whole section.
6881 uint64_t SectAddress = Sections[SectIdx].getAddress();
6882 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00006883 uint64_t InstSize;
6884 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00006885 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00006886
Kevin Enderbybf246f52014-09-24 23:08:22 +00006887 uint64_t PC = SectAddress + Index;
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006888 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
6889 DebugOut, nulls())) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006890 if (!NoLeadingAddr) {
6891 if (FullLeadingAddr) {
6892 if (MachOOF->is64Bit())
6893 outs() << format("%016" PRIx64, PC);
6894 else
6895 outs() << format("%08" PRIx64, PC);
6896 } else {
6897 outs() << format("%8" PRIx64 ":", PC);
6898 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006899 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00006900 if (!NoShowRawInsn || Arch == Triple::arm) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006901 outs() << "\t";
Craig Topper0013be12015-09-21 05:32:41 +00006902 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006903 }
Akira Hatanaka1d079942015-03-28 20:44:05 +00006904 IP->printInst(&Inst, outs(), "", *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00006905 outs() << "\n";
6906 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006907 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006908 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006909 outs() << format("\t.byte 0x%02x #bad opcode\n",
6910 *(Bytes.data() + Index) & 0xff);
6911 InstSize = 1; // skip exactly one illegible byte and move on.
6912 } else {
6913 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6914 if (InstSize == 0)
6915 InstSize = 1; // skip illegible bytes
6916 }
Bill Wendling4e68e062012-07-19 00:17:40 +00006917 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00006918 }
6919 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006920 // The TripleName's need to be reset if we are called again for a different
6921 // archtecture.
6922 TripleName = "";
6923 ThumbTripleName = "";
6924
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006925 if (SymbolizerInfo.method != nullptr)
6926 free(SymbolizerInfo.method);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006927 if (SymbolizerInfo.demangled_name != nullptr)
6928 free(SymbolizerInfo.demangled_name);
Kevin Enderby078be602014-10-23 19:53:12 +00006929 if (SymbolizerInfo.bindtable != nullptr)
6930 delete SymbolizerInfo.bindtable;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006931 if (ThumbSymbolizerInfo.method != nullptr)
6932 free(ThumbSymbolizerInfo.method);
6933 if (ThumbSymbolizerInfo.demangled_name != nullptr)
6934 free(ThumbSymbolizerInfo.demangled_name);
6935 if (ThumbSymbolizerInfo.bindtable != nullptr)
6936 delete ThumbSymbolizerInfo.bindtable;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006937 }
6938}
Tim Northover4bd286a2014-08-01 13:07:19 +00006939
Tim Northover39c70bb2014-08-12 11:52:59 +00006940//===----------------------------------------------------------------------===//
6941// __compact_unwind section dumping
6942//===----------------------------------------------------------------------===//
6943
Tim Northover4bd286a2014-08-01 13:07:19 +00006944namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00006945
6946template <typename T> static uint64_t readNext(const char *&Buf) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006947 using llvm::support::little;
6948 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00006949
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006950 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
6951 Buf += sizeof(T);
6952 return Val;
6953}
Tim Northover39c70bb2014-08-12 11:52:59 +00006954
Tim Northover4bd286a2014-08-01 13:07:19 +00006955struct CompactUnwindEntry {
6956 uint32_t OffsetInSection;
6957
6958 uint64_t FunctionAddr;
6959 uint32_t Length;
6960 uint32_t CompactEncoding;
6961 uint64_t PersonalityAddr;
6962 uint64_t LSDAAddr;
6963
6964 RelocationRef FunctionReloc;
6965 RelocationRef PersonalityReloc;
6966 RelocationRef LSDAReloc;
6967
6968 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006969 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006970 if (Is64)
6971 read<uint64_t>(Contents.data() + Offset);
6972 else
6973 read<uint32_t>(Contents.data() + Offset);
6974 }
6975
6976private:
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006977 template <typename UIntPtr> void read(const char *Buf) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006978 FunctionAddr = readNext<UIntPtr>(Buf);
6979 Length = readNext<uint32_t>(Buf);
6980 CompactEncoding = readNext<uint32_t>(Buf);
6981 PersonalityAddr = readNext<UIntPtr>(Buf);
6982 LSDAAddr = readNext<UIntPtr>(Buf);
6983 }
6984};
6985}
6986
6987/// Given a relocation from __compact_unwind, consisting of the RelocationRef
6988/// and data being relocated, determine the best base Name and Addend to use for
6989/// display purposes.
6990///
6991/// 1. An Extern relocation will directly reference a symbol (and the data is
6992/// then already an addend), so use that.
6993/// 2. Otherwise the data is an offset in the object file's layout; try to find
6994// a symbol before it in the same section, and use the offset from there.
6995/// 3. Finally, if all that fails, fall back to an offset from the start of the
6996/// referenced section.
6997static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
6998 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006999 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00007000 StringRef &Name, uint64_t &Addend) {
7001 if (Reloc.getSymbol() != Obj->symbol_end()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007002 Expected<StringRef> NameOrErr = Reloc.getSymbol()->getName();
7003 if (!NameOrErr) {
7004 std::string Buf;
7005 raw_string_ostream OS(Buf);
7006 logAllUnhandledErrors(NameOrErr.takeError(), OS, "");
7007 OS.flush();
7008 report_fatal_error(Buf);
7009 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007010 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007011 Addend = Addr;
7012 return;
7013 }
7014
7015 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
Keno Fischerc780e8e2015-05-21 21:24:32 +00007016 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
Tim Northover4bd286a2014-08-01 13:07:19 +00007017
Rafael Espindola80291272014-10-08 15:28:58 +00007018 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00007019
7020 auto Sym = Symbols.upper_bound(Addr);
7021 if (Sym == Symbols.begin()) {
7022 // The first symbol in the object is after this reference, the best we can
7023 // do is section-relative notation.
7024 RelocSection.getName(Name);
7025 Addend = Addr - SectionAddr;
7026 return;
7027 }
7028
7029 // Go back one so that SymbolAddress <= Addr.
7030 --Sym;
7031
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007032 auto SectOrErr = Sym->second.getSection();
7033 if (!SectOrErr) {
7034 std::string Buf;
7035 raw_string_ostream OS(Buf);
7036 logAllUnhandledErrors(SectOrErr.takeError(), OS, "");
7037 OS.flush();
7038 report_fatal_error(Buf);
7039 }
7040 section_iterator SymSection = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007041 if (RelocSection == *SymSection) {
7042 // There's a valid symbol in the same section before this reference.
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007043 Expected<StringRef> NameOrErr = Sym->second.getName();
7044 if (!NameOrErr) {
7045 std::string Buf;
7046 raw_string_ostream OS(Buf);
7047 logAllUnhandledErrors(NameOrErr.takeError(), OS, "");
7048 OS.flush();
7049 report_fatal_error(Buf);
7050 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007051 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007052 Addend = Addr - Sym->first;
7053 return;
7054 }
7055
7056 // There is a symbol before this reference, but it's in a different
7057 // section. Probably not helpful to mention it, so use the section name.
7058 RelocSection.getName(Name);
7059 Addend = Addr - SectionAddr;
7060}
7061
7062static void printUnwindRelocDest(const MachOObjectFile *Obj,
7063 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007064 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007065 StringRef Name;
7066 uint64_t Addend;
7067
Rafael Espindola854038e2015-06-26 14:51:16 +00007068 if (!Reloc.getObject())
Tim Northover0b0add52014-09-09 10:45:06 +00007069 return;
7070
Tim Northover4bd286a2014-08-01 13:07:19 +00007071 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
7072
7073 outs() << Name;
7074 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00007075 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00007076}
7077
7078static void
7079printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7080 std::map<uint64_t, SymbolRef> &Symbols,
7081 const SectionRef &CompactUnwind) {
7082
7083 assert(Obj->isLittleEndian() &&
7084 "There should not be a big-endian .o with __compact_unwind");
7085
7086 bool Is64 = Obj->is64Bit();
7087 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7088 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7089
7090 StringRef Contents;
7091 CompactUnwind.getContents(Contents);
7092
7093 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7094
7095 // First populate the initial raw offsets, encodings and so on from the entry.
7096 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
7097 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
7098 CompactUnwinds.push_back(Entry);
7099 }
7100
7101 // Next we need to look at the relocations to find out what objects are
7102 // actually being referred to.
7103 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00007104 uint64_t RelocAddress = Reloc.getOffset();
Tim Northover4bd286a2014-08-01 13:07:19 +00007105
7106 uint32_t EntryIdx = RelocAddress / EntrySize;
7107 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7108 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7109
7110 if (OffsetInEntry == 0)
7111 Entry.FunctionReloc = Reloc;
7112 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7113 Entry.PersonalityReloc = Reloc;
7114 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7115 Entry.LSDAReloc = Reloc;
7116 else
7117 llvm_unreachable("Unexpected relocation in __compact_unwind section");
7118 }
7119
7120 // Finally, we're ready to print the data we've gathered.
7121 outs() << "Contents of __compact_unwind section:\n";
7122 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00007123 outs() << " Entry at offset "
7124 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00007125
7126 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007127 outs() << " start: " << format("0x%" PRIx64,
7128 Entry.FunctionAddr) << ' ';
7129 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00007130 outs() << '\n';
7131
7132 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007133 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
7134 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007135 // 3. The 32-bit compact encoding.
7136 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007137 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007138
7139 // 4. The personality function, if present.
Rafael Espindola854038e2015-06-26 14:51:16 +00007140 if (Entry.PersonalityReloc.getObject()) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007141 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007142 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007143 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7144 Entry.PersonalityAddr);
7145 outs() << '\n';
7146 }
7147
7148 // 5. This entry's language-specific data area.
Rafael Espindola854038e2015-06-26 14:51:16 +00007149 if (Entry.LSDAReloc.getObject()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007150 outs() << " LSDA: " << format("0x%" PRIx64,
7151 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007152 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7153 outs() << '\n';
7154 }
7155 }
7156}
7157
Tim Northover39c70bb2014-08-12 11:52:59 +00007158//===----------------------------------------------------------------------===//
7159// __unwind_info section dumping
7160//===----------------------------------------------------------------------===//
7161
7162static void printRegularSecondLevelUnwindPage(const char *PageStart) {
7163 const char *Pos = PageStart;
7164 uint32_t Kind = readNext<uint32_t>(Pos);
7165 (void)Kind;
7166 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7167
7168 uint16_t EntriesStart = readNext<uint16_t>(Pos);
7169 uint16_t NumEntries = readNext<uint16_t>(Pos);
7170
7171 Pos = PageStart + EntriesStart;
7172 for (unsigned i = 0; i < NumEntries; ++i) {
7173 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
7174 uint32_t Encoding = readNext<uint32_t>(Pos);
7175
7176 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007177 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7178 << ", "
7179 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007180 }
7181}
7182
7183static void printCompressedSecondLevelUnwindPage(
7184 const char *PageStart, uint32_t FunctionBase,
7185 const SmallVectorImpl<uint32_t> &CommonEncodings) {
7186 const char *Pos = PageStart;
7187 uint32_t Kind = readNext<uint32_t>(Pos);
7188 (void)Kind;
7189 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
7190
7191 uint16_t EntriesStart = readNext<uint16_t>(Pos);
7192 uint16_t NumEntries = readNext<uint16_t>(Pos);
7193
7194 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
7195 readNext<uint16_t>(Pos);
Aaron Ballman80930af2014-08-14 13:53:19 +00007196 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
7197 PageStart + EncodingsStart);
Tim Northover39c70bb2014-08-12 11:52:59 +00007198
7199 Pos = PageStart + EntriesStart;
7200 for (unsigned i = 0; i < NumEntries; ++i) {
7201 uint32_t Entry = readNext<uint32_t>(Pos);
7202 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
7203 uint32_t EncodingIdx = Entry >> 24;
7204
7205 uint32_t Encoding;
7206 if (EncodingIdx < CommonEncodings.size())
7207 Encoding = CommonEncodings[EncodingIdx];
7208 else
7209 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
7210
7211 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007212 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7213 << ", "
7214 << "encoding[" << EncodingIdx
7215 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007216 }
7217}
7218
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007219static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
7220 std::map<uint64_t, SymbolRef> &Symbols,
7221 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00007222
7223 assert(Obj->isLittleEndian() &&
7224 "There should not be a big-endian .o with __unwind_info");
7225
7226 outs() << "Contents of __unwind_info section:\n";
7227
7228 StringRef Contents;
7229 UnwindInfo.getContents(Contents);
7230 const char *Pos = Contents.data();
7231
7232 //===----------------------------------
7233 // Section header
7234 //===----------------------------------
7235
7236 uint32_t Version = readNext<uint32_t>(Pos);
7237 outs() << " Version: "
7238 << format("0x%" PRIx32, Version) << '\n';
7239 assert(Version == 1 && "only understand version 1");
7240
7241 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
7242 outs() << " Common encodings array section offset: "
7243 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
7244 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
7245 outs() << " Number of common encodings in array: "
7246 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
7247
7248 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
7249 outs() << " Personality function array section offset: "
7250 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
7251 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
7252 outs() << " Number of personality functions in array: "
7253 << format("0x%" PRIx32, NumPersonalities) << '\n';
7254
7255 uint32_t IndicesStart = readNext<uint32_t>(Pos);
7256 outs() << " Index array section offset: "
7257 << format("0x%" PRIx32, IndicesStart) << '\n';
7258 uint32_t NumIndices = readNext<uint32_t>(Pos);
7259 outs() << " Number of indices in array: "
7260 << format("0x%" PRIx32, NumIndices) << '\n';
7261
7262 //===----------------------------------
7263 // A shared list of common encodings
7264 //===----------------------------------
7265
7266 // These occupy indices in the range [0, N] whenever an encoding is referenced
7267 // from a compressed 2nd level index table. In practice the linker only
7268 // creates ~128 of these, so that indices are available to embed encodings in
7269 // the 2nd level index.
7270
7271 SmallVector<uint32_t, 64> CommonEncodings;
7272 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
7273 Pos = Contents.data() + CommonEncodingsStart;
7274 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
7275 uint32_t Encoding = readNext<uint32_t>(Pos);
7276 CommonEncodings.push_back(Encoding);
7277
7278 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
7279 << '\n';
7280 }
7281
Tim Northover39c70bb2014-08-12 11:52:59 +00007282 //===----------------------------------
7283 // Personality functions used in this executable
7284 //===----------------------------------
7285
7286 // There should be only a handful of these (one per source language,
7287 // roughly). Particularly since they only get 2 bits in the compact encoding.
7288
7289 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
7290 Pos = Contents.data() + PersonalitiesStart;
7291 for (unsigned i = 0; i < NumPersonalities; ++i) {
7292 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
7293 outs() << " personality[" << i + 1
7294 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
7295 }
7296
7297 //===----------------------------------
7298 // The level 1 index entries
7299 //===----------------------------------
7300
7301 // These specify an approximate place to start searching for the more detailed
7302 // information, sorted by PC.
7303
7304 struct IndexEntry {
7305 uint32_t FunctionOffset;
7306 uint32_t SecondLevelPageStart;
7307 uint32_t LSDAStart;
7308 };
7309
7310 SmallVector<IndexEntry, 4> IndexEntries;
7311
7312 outs() << " Top level indices: (count = " << NumIndices << ")\n";
7313 Pos = Contents.data() + IndicesStart;
7314 for (unsigned i = 0; i < NumIndices; ++i) {
7315 IndexEntry Entry;
7316
7317 Entry.FunctionOffset = readNext<uint32_t>(Pos);
7318 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
7319 Entry.LSDAStart = readNext<uint32_t>(Pos);
7320 IndexEntries.push_back(Entry);
7321
7322 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007323 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
7324 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00007325 << "2nd level page offset="
7326 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007327 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007328 }
7329
Tim Northover39c70bb2014-08-12 11:52:59 +00007330 //===----------------------------------
7331 // Next come the LSDA tables
7332 //===----------------------------------
7333
7334 // The LSDA layout is rather implicit: it's a contiguous array of entries from
7335 // the first top-level index's LSDAOffset to the last (sentinel).
7336
7337 outs() << " LSDA descriptors:\n";
7338 Pos = Contents.data() + IndexEntries[0].LSDAStart;
7339 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
7340 (2 * sizeof(uint32_t));
7341 for (int i = 0; i < NumLSDAs; ++i) {
7342 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
7343 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
7344 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007345 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7346 << ", "
7347 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007348 }
7349
7350 //===----------------------------------
7351 // Finally, the 2nd level indices
7352 //===----------------------------------
7353
7354 // Generally these are 4K in size, and have 2 possible forms:
7355 // + Regular stores up to 511 entries with disparate encodings
7356 // + Compressed stores up to 1021 entries if few enough compact encoding
7357 // values are used.
7358 outs() << " Second level indices:\n";
7359 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
7360 // The final sentinel top-level index has no associated 2nd level page
7361 if (IndexEntries[i].SecondLevelPageStart == 0)
7362 break;
7363
7364 outs() << " Second level index[" << i << "]: "
7365 << "offset in section="
7366 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
7367 << ", "
7368 << "base function offset="
7369 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
7370
7371 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
Aaron Ballman80930af2014-08-14 13:53:19 +00007372 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007373 if (Kind == 2)
7374 printRegularSecondLevelUnwindPage(Pos);
7375 else if (Kind == 3)
7376 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
7377 CommonEncodings);
7378 else
7379 llvm_unreachable("Do not know how to print this kind of 2nd level page");
Tim Northover39c70bb2014-08-12 11:52:59 +00007380 }
7381}
7382
Tim Northover4bd286a2014-08-01 13:07:19 +00007383void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
7384 std::map<uint64_t, SymbolRef> Symbols;
7385 for (const SymbolRef &SymRef : Obj->symbols()) {
7386 // Discard any undefined or absolute symbols. They're not going to take part
7387 // in the convenience lookup for unwind info and just take up resources.
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007388 auto SectOrErr = SymRef.getSection();
7389 if (!SectOrErr) {
7390 // TODO: Actually report errors helpfully.
7391 consumeError(SectOrErr.takeError());
7392 continue;
7393 }
7394 section_iterator Section = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007395 if (Section == Obj->section_end())
7396 continue;
7397
Rafael Espindoladea00162015-07-03 17:44:18 +00007398 uint64_t Addr = SymRef.getValue();
Tim Northover4bd286a2014-08-01 13:07:19 +00007399 Symbols.insert(std::make_pair(Addr, SymRef));
7400 }
7401
7402 for (const SectionRef &Section : Obj->sections()) {
7403 StringRef SectName;
7404 Section.getName(SectName);
7405 if (SectName == "__compact_unwind")
7406 printMachOCompactUnwindSection(Obj, Symbols, Section);
7407 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00007408 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00007409 }
7410}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007411
7412static void PrintMachHeader(uint32_t magic, uint32_t cputype,
7413 uint32_t cpusubtype, uint32_t filetype,
7414 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
7415 bool verbose) {
7416 outs() << "Mach header\n";
7417 outs() << " magic cputype cpusubtype caps filetype ncmds "
7418 "sizeofcmds flags\n";
7419 if (verbose) {
7420 if (magic == MachO::MH_MAGIC)
7421 outs() << " MH_MAGIC";
7422 else if (magic == MachO::MH_MAGIC_64)
7423 outs() << "MH_MAGIC_64";
7424 else
7425 outs() << format(" 0x%08" PRIx32, magic);
7426 switch (cputype) {
7427 case MachO::CPU_TYPE_I386:
7428 outs() << " I386";
7429 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7430 case MachO::CPU_SUBTYPE_I386_ALL:
7431 outs() << " ALL";
7432 break;
7433 default:
7434 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7435 break;
7436 }
7437 break;
7438 case MachO::CPU_TYPE_X86_64:
7439 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00007440 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7441 case MachO::CPU_SUBTYPE_X86_64_ALL:
7442 outs() << " ALL";
7443 break;
7444 case MachO::CPU_SUBTYPE_X86_64_H:
7445 outs() << " Haswell";
7446 break;
7447 default:
7448 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7449 break;
7450 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007451 break;
7452 case MachO::CPU_TYPE_ARM:
7453 outs() << " ARM";
7454 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7455 case MachO::CPU_SUBTYPE_ARM_ALL:
7456 outs() << " ALL";
7457 break;
7458 case MachO::CPU_SUBTYPE_ARM_V4T:
7459 outs() << " V4T";
7460 break;
7461 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
7462 outs() << " V5TEJ";
7463 break;
7464 case MachO::CPU_SUBTYPE_ARM_XSCALE:
7465 outs() << " XSCALE";
7466 break;
7467 case MachO::CPU_SUBTYPE_ARM_V6:
7468 outs() << " V6";
7469 break;
7470 case MachO::CPU_SUBTYPE_ARM_V6M:
7471 outs() << " V6M";
7472 break;
7473 case MachO::CPU_SUBTYPE_ARM_V7:
7474 outs() << " V7";
7475 break;
7476 case MachO::CPU_SUBTYPE_ARM_V7EM:
7477 outs() << " V7EM";
7478 break;
7479 case MachO::CPU_SUBTYPE_ARM_V7K:
7480 outs() << " V7K";
7481 break;
7482 case MachO::CPU_SUBTYPE_ARM_V7M:
7483 outs() << " V7M";
7484 break;
7485 case MachO::CPU_SUBTYPE_ARM_V7S:
7486 outs() << " V7S";
7487 break;
7488 default:
7489 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7490 break;
7491 }
7492 break;
7493 case MachO::CPU_TYPE_ARM64:
7494 outs() << " ARM64";
7495 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7496 case MachO::CPU_SUBTYPE_ARM64_ALL:
7497 outs() << " ALL";
7498 break;
7499 default:
7500 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7501 break;
7502 }
7503 break;
7504 case MachO::CPU_TYPE_POWERPC:
7505 outs() << " PPC";
7506 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7507 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7508 outs() << " ALL";
7509 break;
7510 default:
7511 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7512 break;
7513 }
7514 break;
7515 case MachO::CPU_TYPE_POWERPC64:
7516 outs() << " PPC64";
7517 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7518 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7519 outs() << " ALL";
7520 break;
7521 default:
7522 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7523 break;
7524 }
7525 break;
Kevin Enderby40fdbf82016-01-26 18:20:49 +00007526 default:
7527 outs() << format(" %7d", cputype);
7528 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7529 break;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007530 }
7531 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007532 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007533 } else {
7534 outs() << format(" 0x%02" PRIx32,
7535 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7536 }
7537 switch (filetype) {
7538 case MachO::MH_OBJECT:
7539 outs() << " OBJECT";
7540 break;
7541 case MachO::MH_EXECUTE:
7542 outs() << " EXECUTE";
7543 break;
7544 case MachO::MH_FVMLIB:
7545 outs() << " FVMLIB";
7546 break;
7547 case MachO::MH_CORE:
7548 outs() << " CORE";
7549 break;
7550 case MachO::MH_PRELOAD:
7551 outs() << " PRELOAD";
7552 break;
7553 case MachO::MH_DYLIB:
7554 outs() << " DYLIB";
7555 break;
7556 case MachO::MH_DYLIB_STUB:
7557 outs() << " DYLIB_STUB";
7558 break;
7559 case MachO::MH_DYLINKER:
7560 outs() << " DYLINKER";
7561 break;
7562 case MachO::MH_BUNDLE:
7563 outs() << " BUNDLE";
7564 break;
7565 case MachO::MH_DSYM:
7566 outs() << " DSYM";
7567 break;
7568 case MachO::MH_KEXT_BUNDLE:
7569 outs() << " KEXTBUNDLE";
7570 break;
7571 default:
7572 outs() << format(" %10u", filetype);
7573 break;
7574 }
7575 outs() << format(" %5u", ncmds);
7576 outs() << format(" %10u", sizeofcmds);
7577 uint32_t f = flags;
7578 if (f & MachO::MH_NOUNDEFS) {
7579 outs() << " NOUNDEFS";
7580 f &= ~MachO::MH_NOUNDEFS;
7581 }
7582 if (f & MachO::MH_INCRLINK) {
7583 outs() << " INCRLINK";
7584 f &= ~MachO::MH_INCRLINK;
7585 }
7586 if (f & MachO::MH_DYLDLINK) {
7587 outs() << " DYLDLINK";
7588 f &= ~MachO::MH_DYLDLINK;
7589 }
7590 if (f & MachO::MH_BINDATLOAD) {
7591 outs() << " BINDATLOAD";
7592 f &= ~MachO::MH_BINDATLOAD;
7593 }
7594 if (f & MachO::MH_PREBOUND) {
7595 outs() << " PREBOUND";
7596 f &= ~MachO::MH_PREBOUND;
7597 }
7598 if (f & MachO::MH_SPLIT_SEGS) {
7599 outs() << " SPLIT_SEGS";
7600 f &= ~MachO::MH_SPLIT_SEGS;
7601 }
7602 if (f & MachO::MH_LAZY_INIT) {
7603 outs() << " LAZY_INIT";
7604 f &= ~MachO::MH_LAZY_INIT;
7605 }
7606 if (f & MachO::MH_TWOLEVEL) {
7607 outs() << " TWOLEVEL";
7608 f &= ~MachO::MH_TWOLEVEL;
7609 }
7610 if (f & MachO::MH_FORCE_FLAT) {
7611 outs() << " FORCE_FLAT";
7612 f &= ~MachO::MH_FORCE_FLAT;
7613 }
7614 if (f & MachO::MH_NOMULTIDEFS) {
7615 outs() << " NOMULTIDEFS";
7616 f &= ~MachO::MH_NOMULTIDEFS;
7617 }
7618 if (f & MachO::MH_NOFIXPREBINDING) {
7619 outs() << " NOFIXPREBINDING";
7620 f &= ~MachO::MH_NOFIXPREBINDING;
7621 }
7622 if (f & MachO::MH_PREBINDABLE) {
7623 outs() << " PREBINDABLE";
7624 f &= ~MachO::MH_PREBINDABLE;
7625 }
7626 if (f & MachO::MH_ALLMODSBOUND) {
7627 outs() << " ALLMODSBOUND";
7628 f &= ~MachO::MH_ALLMODSBOUND;
7629 }
7630 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
7631 outs() << " SUBSECTIONS_VIA_SYMBOLS";
7632 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
7633 }
7634 if (f & MachO::MH_CANONICAL) {
7635 outs() << " CANONICAL";
7636 f &= ~MachO::MH_CANONICAL;
7637 }
7638 if (f & MachO::MH_WEAK_DEFINES) {
7639 outs() << " WEAK_DEFINES";
7640 f &= ~MachO::MH_WEAK_DEFINES;
7641 }
7642 if (f & MachO::MH_BINDS_TO_WEAK) {
7643 outs() << " BINDS_TO_WEAK";
7644 f &= ~MachO::MH_BINDS_TO_WEAK;
7645 }
7646 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
7647 outs() << " ALLOW_STACK_EXECUTION";
7648 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
7649 }
7650 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
7651 outs() << " DEAD_STRIPPABLE_DYLIB";
7652 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
7653 }
7654 if (f & MachO::MH_PIE) {
7655 outs() << " PIE";
7656 f &= ~MachO::MH_PIE;
7657 }
7658 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
7659 outs() << " NO_REEXPORTED_DYLIBS";
7660 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
7661 }
7662 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
7663 outs() << " MH_HAS_TLV_DESCRIPTORS";
7664 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
7665 }
7666 if (f & MachO::MH_NO_HEAP_EXECUTION) {
7667 outs() << " MH_NO_HEAP_EXECUTION";
7668 f &= ~MachO::MH_NO_HEAP_EXECUTION;
7669 }
7670 if (f & MachO::MH_APP_EXTENSION_SAFE) {
7671 outs() << " APP_EXTENSION_SAFE";
7672 f &= ~MachO::MH_APP_EXTENSION_SAFE;
7673 }
7674 if (f != 0 || flags == 0)
7675 outs() << format(" 0x%08" PRIx32, f);
7676 } else {
7677 outs() << format(" 0x%08" PRIx32, magic);
7678 outs() << format(" %7d", cputype);
7679 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7680 outs() << format(" 0x%02" PRIx32,
7681 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7682 outs() << format(" %10u", filetype);
7683 outs() << format(" %5u", ncmds);
7684 outs() << format(" %10u", sizeofcmds);
7685 outs() << format(" 0x%08" PRIx32, flags);
7686 }
7687 outs() << "\n";
7688}
7689
Kevin Enderby956366c2014-08-29 22:30:52 +00007690static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
7691 StringRef SegName, uint64_t vmaddr,
7692 uint64_t vmsize, uint64_t fileoff,
7693 uint64_t filesize, uint32_t maxprot,
7694 uint32_t initprot, uint32_t nsects,
7695 uint32_t flags, uint32_t object_size,
7696 bool verbose) {
7697 uint64_t expected_cmdsize;
7698 if (cmd == MachO::LC_SEGMENT) {
7699 outs() << " cmd LC_SEGMENT\n";
7700 expected_cmdsize = nsects;
7701 expected_cmdsize *= sizeof(struct MachO::section);
7702 expected_cmdsize += sizeof(struct MachO::segment_command);
7703 } else {
7704 outs() << " cmd LC_SEGMENT_64\n";
7705 expected_cmdsize = nsects;
7706 expected_cmdsize *= sizeof(struct MachO::section_64);
7707 expected_cmdsize += sizeof(struct MachO::segment_command_64);
7708 }
7709 outs() << " cmdsize " << cmdsize;
7710 if (cmdsize != expected_cmdsize)
7711 outs() << " Inconsistent size\n";
7712 else
7713 outs() << "\n";
7714 outs() << " segname " << SegName << "\n";
7715 if (cmd == MachO::LC_SEGMENT_64) {
7716 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
7717 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
7718 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00007719 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
7720 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00007721 }
7722 outs() << " fileoff " << fileoff;
7723 if (fileoff > object_size)
7724 outs() << " (past end of file)\n";
7725 else
7726 outs() << "\n";
7727 outs() << " filesize " << filesize;
7728 if (fileoff + filesize > object_size)
7729 outs() << " (past end of file)\n";
7730 else
7731 outs() << "\n";
7732 if (verbose) {
7733 if ((maxprot &
7734 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7735 MachO::VM_PROT_EXECUTE)) != 0)
7736 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
7737 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00007738 outs() << " maxprot ";
7739 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
7740 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7741 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007742 }
7743 if ((initprot &
7744 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7745 MachO::VM_PROT_EXECUTE)) != 0)
7746 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
7747 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00007748 outs() << " initprot ";
7749 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
7750 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7751 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007752 }
7753 } else {
7754 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
7755 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
7756 }
7757 outs() << " nsects " << nsects << "\n";
7758 if (verbose) {
7759 outs() << " flags";
7760 if (flags == 0)
7761 outs() << " (none)\n";
7762 else {
7763 if (flags & MachO::SG_HIGHVM) {
7764 outs() << " HIGHVM";
7765 flags &= ~MachO::SG_HIGHVM;
7766 }
7767 if (flags & MachO::SG_FVMLIB) {
7768 outs() << " FVMLIB";
7769 flags &= ~MachO::SG_FVMLIB;
7770 }
7771 if (flags & MachO::SG_NORELOC) {
7772 outs() << " NORELOC";
7773 flags &= ~MachO::SG_NORELOC;
7774 }
7775 if (flags & MachO::SG_PROTECTED_VERSION_1) {
7776 outs() << " PROTECTED_VERSION_1";
7777 flags &= ~MachO::SG_PROTECTED_VERSION_1;
7778 }
7779 if (flags)
7780 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
7781 else
7782 outs() << "\n";
7783 }
7784 } else {
7785 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
7786 }
7787}
7788
7789static void PrintSection(const char *sectname, const char *segname,
7790 uint64_t addr, uint64_t size, uint32_t offset,
7791 uint32_t align, uint32_t reloff, uint32_t nreloc,
7792 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
7793 uint32_t cmd, const char *sg_segname,
7794 uint32_t filetype, uint32_t object_size,
7795 bool verbose) {
7796 outs() << "Section\n";
7797 outs() << " sectname " << format("%.16s\n", sectname);
7798 outs() << " segname " << format("%.16s", segname);
7799 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
7800 outs() << " (does not match segment)\n";
7801 else
7802 outs() << "\n";
7803 if (cmd == MachO::LC_SEGMENT_64) {
7804 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
7805 outs() << " size " << format("0x%016" PRIx64, size);
7806 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00007807 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
7808 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00007809 }
7810 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
7811 outs() << " (past end of file)\n";
7812 else
7813 outs() << "\n";
7814 outs() << " offset " << offset;
7815 if (offset > object_size)
7816 outs() << " (past end of file)\n";
7817 else
7818 outs() << "\n";
7819 uint32_t align_shifted = 1 << align;
7820 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
7821 outs() << " reloff " << reloff;
7822 if (reloff > object_size)
7823 outs() << " (past end of file)\n";
7824 else
7825 outs() << "\n";
7826 outs() << " nreloc " << nreloc;
7827 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
7828 outs() << " (past end of file)\n";
7829 else
7830 outs() << "\n";
7831 uint32_t section_type = flags & MachO::SECTION_TYPE;
7832 if (verbose) {
7833 outs() << " type";
7834 if (section_type == MachO::S_REGULAR)
7835 outs() << " S_REGULAR\n";
7836 else if (section_type == MachO::S_ZEROFILL)
7837 outs() << " S_ZEROFILL\n";
7838 else if (section_type == MachO::S_CSTRING_LITERALS)
7839 outs() << " S_CSTRING_LITERALS\n";
7840 else if (section_type == MachO::S_4BYTE_LITERALS)
7841 outs() << " S_4BYTE_LITERALS\n";
7842 else if (section_type == MachO::S_8BYTE_LITERALS)
7843 outs() << " S_8BYTE_LITERALS\n";
7844 else if (section_type == MachO::S_16BYTE_LITERALS)
7845 outs() << " S_16BYTE_LITERALS\n";
7846 else if (section_type == MachO::S_LITERAL_POINTERS)
7847 outs() << " S_LITERAL_POINTERS\n";
7848 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
7849 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
7850 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
7851 outs() << " S_LAZY_SYMBOL_POINTERS\n";
7852 else if (section_type == MachO::S_SYMBOL_STUBS)
7853 outs() << " S_SYMBOL_STUBS\n";
7854 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
7855 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
7856 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
7857 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
7858 else if (section_type == MachO::S_COALESCED)
7859 outs() << " S_COALESCED\n";
7860 else if (section_type == MachO::S_INTERPOSING)
7861 outs() << " S_INTERPOSING\n";
7862 else if (section_type == MachO::S_DTRACE_DOF)
7863 outs() << " S_DTRACE_DOF\n";
7864 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
7865 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
7866 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
7867 outs() << " S_THREAD_LOCAL_REGULAR\n";
7868 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
7869 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
7870 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
7871 outs() << " S_THREAD_LOCAL_VARIABLES\n";
7872 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7873 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
7874 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
7875 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
7876 else
7877 outs() << format("0x%08" PRIx32, section_type) << "\n";
7878 outs() << "attributes";
7879 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
7880 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
7881 outs() << " PURE_INSTRUCTIONS";
7882 if (section_attributes & MachO::S_ATTR_NO_TOC)
7883 outs() << " NO_TOC";
7884 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
7885 outs() << " STRIP_STATIC_SYMS";
7886 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
7887 outs() << " NO_DEAD_STRIP";
7888 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
7889 outs() << " LIVE_SUPPORT";
7890 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
7891 outs() << " SELF_MODIFYING_CODE";
7892 if (section_attributes & MachO::S_ATTR_DEBUG)
7893 outs() << " DEBUG";
7894 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
7895 outs() << " SOME_INSTRUCTIONS";
7896 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
7897 outs() << " EXT_RELOC";
7898 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
7899 outs() << " LOC_RELOC";
7900 if (section_attributes == 0)
7901 outs() << " (none)";
7902 outs() << "\n";
7903 } else
7904 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
7905 outs() << " reserved1 " << reserved1;
7906 if (section_type == MachO::S_SYMBOL_STUBS ||
7907 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
7908 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
7909 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
7910 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7911 outs() << " (index into indirect symbol table)\n";
7912 else
7913 outs() << "\n";
7914 outs() << " reserved2 " << reserved2;
7915 if (section_type == MachO::S_SYMBOL_STUBS)
7916 outs() << " (size of stubs)\n";
7917 else
7918 outs() << "\n";
7919}
7920
David Majnemer73cc6ff2014-11-13 19:48:56 +00007921static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00007922 uint32_t object_size) {
7923 outs() << " cmd LC_SYMTAB\n";
7924 outs() << " cmdsize " << st.cmdsize;
7925 if (st.cmdsize != sizeof(struct MachO::symtab_command))
7926 outs() << " Incorrect size\n";
7927 else
7928 outs() << "\n";
7929 outs() << " symoff " << st.symoff;
7930 if (st.symoff > object_size)
7931 outs() << " (past end of file)\n";
7932 else
7933 outs() << "\n";
7934 outs() << " nsyms " << st.nsyms;
7935 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00007936 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007937 big_size = st.nsyms;
7938 big_size *= sizeof(struct MachO::nlist_64);
7939 big_size += st.symoff;
7940 if (big_size > object_size)
7941 outs() << " (past end of file)\n";
7942 else
7943 outs() << "\n";
7944 } else {
7945 big_size = st.nsyms;
7946 big_size *= sizeof(struct MachO::nlist);
7947 big_size += st.symoff;
7948 if (big_size > object_size)
7949 outs() << " (past end of file)\n";
7950 else
7951 outs() << "\n";
7952 }
7953 outs() << " stroff " << st.stroff;
7954 if (st.stroff > object_size)
7955 outs() << " (past end of file)\n";
7956 else
7957 outs() << "\n";
7958 outs() << " strsize " << st.strsize;
7959 big_size = st.stroff;
7960 big_size += st.strsize;
7961 if (big_size > object_size)
7962 outs() << " (past end of file)\n";
7963 else
7964 outs() << "\n";
7965}
7966
7967static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
7968 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00007969 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007970 outs() << " cmd LC_DYSYMTAB\n";
7971 outs() << " cmdsize " << dyst.cmdsize;
7972 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
7973 outs() << " Incorrect size\n";
7974 else
7975 outs() << "\n";
7976 outs() << " ilocalsym " << dyst.ilocalsym;
7977 if (dyst.ilocalsym > nsyms)
7978 outs() << " (greater than the number of symbols)\n";
7979 else
7980 outs() << "\n";
7981 outs() << " nlocalsym " << dyst.nlocalsym;
7982 uint64_t big_size;
7983 big_size = dyst.ilocalsym;
7984 big_size += dyst.nlocalsym;
7985 if (big_size > nsyms)
7986 outs() << " (past the end of the symbol table)\n";
7987 else
7988 outs() << "\n";
7989 outs() << " iextdefsym " << dyst.iextdefsym;
7990 if (dyst.iextdefsym > nsyms)
7991 outs() << " (greater than the number of symbols)\n";
7992 else
7993 outs() << "\n";
7994 outs() << " nextdefsym " << dyst.nextdefsym;
7995 big_size = dyst.iextdefsym;
7996 big_size += dyst.nextdefsym;
7997 if (big_size > nsyms)
7998 outs() << " (past the end of the symbol table)\n";
7999 else
8000 outs() << "\n";
8001 outs() << " iundefsym " << dyst.iundefsym;
8002 if (dyst.iundefsym > nsyms)
8003 outs() << " (greater than the number of symbols)\n";
8004 else
8005 outs() << "\n";
8006 outs() << " nundefsym " << dyst.nundefsym;
8007 big_size = dyst.iundefsym;
8008 big_size += dyst.nundefsym;
8009 if (big_size > nsyms)
8010 outs() << " (past the end of the symbol table)\n";
8011 else
8012 outs() << "\n";
8013 outs() << " tocoff " << dyst.tocoff;
8014 if (dyst.tocoff > object_size)
8015 outs() << " (past end of file)\n";
8016 else
8017 outs() << "\n";
8018 outs() << " ntoc " << dyst.ntoc;
8019 big_size = dyst.ntoc;
8020 big_size *= sizeof(struct MachO::dylib_table_of_contents);
8021 big_size += dyst.tocoff;
8022 if (big_size > object_size)
8023 outs() << " (past end of file)\n";
8024 else
8025 outs() << "\n";
8026 outs() << " modtaboff " << dyst.modtaboff;
8027 if (dyst.modtaboff > object_size)
8028 outs() << " (past end of file)\n";
8029 else
8030 outs() << "\n";
8031 outs() << " nmodtab " << dyst.nmodtab;
8032 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00008033 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008034 modtabend = dyst.nmodtab;
8035 modtabend *= sizeof(struct MachO::dylib_module_64);
8036 modtabend += dyst.modtaboff;
8037 } else {
8038 modtabend = dyst.nmodtab;
8039 modtabend *= sizeof(struct MachO::dylib_module);
8040 modtabend += dyst.modtaboff;
8041 }
8042 if (modtabend > object_size)
8043 outs() << " (past end of file)\n";
8044 else
8045 outs() << "\n";
8046 outs() << " extrefsymoff " << dyst.extrefsymoff;
8047 if (dyst.extrefsymoff > object_size)
8048 outs() << " (past end of file)\n";
8049 else
8050 outs() << "\n";
8051 outs() << " nextrefsyms " << dyst.nextrefsyms;
8052 big_size = dyst.nextrefsyms;
8053 big_size *= sizeof(struct MachO::dylib_reference);
8054 big_size += dyst.extrefsymoff;
8055 if (big_size > object_size)
8056 outs() << " (past end of file)\n";
8057 else
8058 outs() << "\n";
8059 outs() << " indirectsymoff " << dyst.indirectsymoff;
8060 if (dyst.indirectsymoff > object_size)
8061 outs() << " (past end of file)\n";
8062 else
8063 outs() << "\n";
8064 outs() << " nindirectsyms " << dyst.nindirectsyms;
8065 big_size = dyst.nindirectsyms;
8066 big_size *= sizeof(uint32_t);
8067 big_size += dyst.indirectsymoff;
8068 if (big_size > object_size)
8069 outs() << " (past end of file)\n";
8070 else
8071 outs() << "\n";
8072 outs() << " extreloff " << dyst.extreloff;
8073 if (dyst.extreloff > object_size)
8074 outs() << " (past end of file)\n";
8075 else
8076 outs() << "\n";
8077 outs() << " nextrel " << dyst.nextrel;
8078 big_size = dyst.nextrel;
8079 big_size *= sizeof(struct MachO::relocation_info);
8080 big_size += dyst.extreloff;
8081 if (big_size > object_size)
8082 outs() << " (past end of file)\n";
8083 else
8084 outs() << "\n";
8085 outs() << " locreloff " << dyst.locreloff;
8086 if (dyst.locreloff > object_size)
8087 outs() << " (past end of file)\n";
8088 else
8089 outs() << "\n";
8090 outs() << " nlocrel " << dyst.nlocrel;
8091 big_size = dyst.nlocrel;
8092 big_size *= sizeof(struct MachO::relocation_info);
8093 big_size += dyst.locreloff;
8094 if (big_size > object_size)
8095 outs() << " (past end of file)\n";
8096 else
8097 outs() << "\n";
8098}
8099
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008100static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8101 uint32_t object_size) {
8102 if (dc.cmd == MachO::LC_DYLD_INFO)
8103 outs() << " cmd LC_DYLD_INFO\n";
8104 else
8105 outs() << " cmd LC_DYLD_INFO_ONLY\n";
8106 outs() << " cmdsize " << dc.cmdsize;
8107 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8108 outs() << " Incorrect size\n";
8109 else
8110 outs() << "\n";
8111 outs() << " rebase_off " << dc.rebase_off;
8112 if (dc.rebase_off > object_size)
8113 outs() << " (past end of file)\n";
8114 else
8115 outs() << "\n";
8116 outs() << " rebase_size " << dc.rebase_size;
8117 uint64_t big_size;
8118 big_size = dc.rebase_off;
8119 big_size += dc.rebase_size;
8120 if (big_size > object_size)
8121 outs() << " (past end of file)\n";
8122 else
8123 outs() << "\n";
8124 outs() << " bind_off " << dc.bind_off;
8125 if (dc.bind_off > object_size)
8126 outs() << " (past end of file)\n";
8127 else
8128 outs() << "\n";
8129 outs() << " bind_size " << dc.bind_size;
8130 big_size = dc.bind_off;
8131 big_size += dc.bind_size;
8132 if (big_size > object_size)
8133 outs() << " (past end of file)\n";
8134 else
8135 outs() << "\n";
8136 outs() << " weak_bind_off " << dc.weak_bind_off;
8137 if (dc.weak_bind_off > object_size)
8138 outs() << " (past end of file)\n";
8139 else
8140 outs() << "\n";
8141 outs() << " weak_bind_size " << dc.weak_bind_size;
8142 big_size = dc.weak_bind_off;
8143 big_size += dc.weak_bind_size;
8144 if (big_size > object_size)
8145 outs() << " (past end of file)\n";
8146 else
8147 outs() << "\n";
8148 outs() << " lazy_bind_off " << dc.lazy_bind_off;
8149 if (dc.lazy_bind_off > object_size)
8150 outs() << " (past end of file)\n";
8151 else
8152 outs() << "\n";
8153 outs() << " lazy_bind_size " << dc.lazy_bind_size;
8154 big_size = dc.lazy_bind_off;
8155 big_size += dc.lazy_bind_size;
8156 if (big_size > object_size)
8157 outs() << " (past end of file)\n";
8158 else
8159 outs() << "\n";
8160 outs() << " export_off " << dc.export_off;
8161 if (dc.export_off > object_size)
8162 outs() << " (past end of file)\n";
8163 else
8164 outs() << "\n";
8165 outs() << " export_size " << dc.export_size;
8166 big_size = dc.export_off;
8167 big_size += dc.export_size;
8168 if (big_size > object_size)
8169 outs() << " (past end of file)\n";
8170 else
8171 outs() << "\n";
8172}
8173
8174static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
8175 const char *Ptr) {
8176 if (dyld.cmd == MachO::LC_ID_DYLINKER)
8177 outs() << " cmd LC_ID_DYLINKER\n";
8178 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
8179 outs() << " cmd LC_LOAD_DYLINKER\n";
8180 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
8181 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
8182 else
8183 outs() << " cmd ?(" << dyld.cmd << ")\n";
8184 outs() << " cmdsize " << dyld.cmdsize;
8185 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
8186 outs() << " Incorrect size\n";
8187 else
8188 outs() << "\n";
8189 if (dyld.name >= dyld.cmdsize)
8190 outs() << " name ?(bad offset " << dyld.name << ")\n";
8191 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008192 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008193 outs() << " name " << P << " (offset " << dyld.name << ")\n";
8194 }
8195}
8196
8197static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
8198 outs() << " cmd LC_UUID\n";
8199 outs() << " cmdsize " << uuid.cmdsize;
8200 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
8201 outs() << " Incorrect size\n";
8202 else
8203 outs() << "\n";
8204 outs() << " uuid ";
Davide Italianoc74277a2015-12-07 00:03:28 +00008205 for (int i = 0; i < 16; ++i) {
8206 outs() << format("%02" PRIX32, uuid.uuid[i]);
8207 if (i == 3 || i == 5 || i == 7 || i == 9)
8208 outs() << "-";
8209 }
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008210 outs() << "\n";
8211}
8212
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008213static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008214 outs() << " cmd LC_RPATH\n";
8215 outs() << " cmdsize " << rpath.cmdsize;
8216 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
8217 outs() << " Incorrect size\n";
8218 else
8219 outs() << "\n";
8220 if (rpath.path >= rpath.cmdsize)
8221 outs() << " path ?(bad offset " << rpath.path << ")\n";
8222 else {
8223 const char *P = (const char *)(Ptr) + rpath.path;
8224 outs() << " path " << P << " (offset " << rpath.path << ")\n";
8225 }
8226}
8227
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008228static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
Tim Northoverbfbfb122015-11-02 21:26:58 +00008229 StringRef LoadCmdName;
8230 switch (vd.cmd) {
8231 case MachO::LC_VERSION_MIN_MACOSX:
8232 LoadCmdName = "LC_VERSION_MIN_MACOSX";
8233 break;
8234 case MachO::LC_VERSION_MIN_IPHONEOS:
8235 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
8236 break;
8237 case MachO::LC_VERSION_MIN_TVOS:
8238 LoadCmdName = "LC_VERSION_MIN_TVOS";
8239 break;
8240 case MachO::LC_VERSION_MIN_WATCHOS:
8241 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
8242 break;
8243 default:
8244 llvm_unreachable("Unknown version min load command");
8245 }
8246
8247 outs() << " cmd " << LoadCmdName << '\n';
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008248 outs() << " cmdsize " << vd.cmdsize;
8249 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
8250 outs() << " Incorrect size\n";
8251 else
8252 outs() << "\n";
Davide Italiano56baef32015-08-26 12:26:11 +00008253 outs() << " version "
8254 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
8255 << MachOObjectFile::getVersionMinMinor(vd, false);
8256 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
8257 if (Update != 0)
8258 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008259 outs() << "\n";
8260 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00008261 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008262 else {
Davide Italiano56baef32015-08-26 12:26:11 +00008263 outs() << " sdk "
8264 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
8265 << MachOObjectFile::getVersionMinMinor(vd, true);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008266 }
Davide Italiano56baef32015-08-26 12:26:11 +00008267 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
8268 if (Update != 0)
8269 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008270 outs() << "\n";
8271}
8272
8273static void PrintSourceVersionCommand(MachO::source_version_command sd) {
8274 outs() << " cmd LC_SOURCE_VERSION\n";
8275 outs() << " cmdsize " << sd.cmdsize;
8276 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
8277 outs() << " Incorrect size\n";
8278 else
8279 outs() << "\n";
8280 uint64_t a = (sd.version >> 40) & 0xffffff;
8281 uint64_t b = (sd.version >> 30) & 0x3ff;
8282 uint64_t c = (sd.version >> 20) & 0x3ff;
8283 uint64_t d = (sd.version >> 10) & 0x3ff;
8284 uint64_t e = sd.version & 0x3ff;
8285 outs() << " version " << a << "." << b;
8286 if (e != 0)
8287 outs() << "." << c << "." << d << "." << e;
8288 else if (d != 0)
8289 outs() << "." << c << "." << d;
8290 else if (c != 0)
8291 outs() << "." << c;
8292 outs() << "\n";
8293}
8294
8295static void PrintEntryPointCommand(MachO::entry_point_command ep) {
8296 outs() << " cmd LC_MAIN\n";
8297 outs() << " cmdsize " << ep.cmdsize;
8298 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
8299 outs() << " Incorrect size\n";
8300 else
8301 outs() << "\n";
8302 outs() << " entryoff " << ep.entryoff << "\n";
8303 outs() << " stacksize " << ep.stacksize << "\n";
8304}
8305
Kevin Enderby0804f4672014-12-16 23:25:52 +00008306static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
8307 uint32_t object_size) {
8308 outs() << " cmd LC_ENCRYPTION_INFO\n";
8309 outs() << " cmdsize " << ec.cmdsize;
8310 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
8311 outs() << " Incorrect size\n";
8312 else
8313 outs() << "\n";
8314 outs() << " cryptoff " << ec.cryptoff;
8315 if (ec.cryptoff > object_size)
8316 outs() << " (past end of file)\n";
8317 else
8318 outs() << "\n";
8319 outs() << " cryptsize " << ec.cryptsize;
8320 if (ec.cryptsize > object_size)
8321 outs() << " (past end of file)\n";
8322 else
8323 outs() << "\n";
8324 outs() << " cryptid " << ec.cryptid << "\n";
8325}
8326
Kevin Enderby57538292014-12-17 01:01:30 +00008327static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008328 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00008329 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
8330 outs() << " cmdsize " << ec.cmdsize;
8331 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
8332 outs() << " Incorrect size\n";
8333 else
8334 outs() << "\n";
8335 outs() << " cryptoff " << ec.cryptoff;
8336 if (ec.cryptoff > object_size)
8337 outs() << " (past end of file)\n";
8338 else
8339 outs() << "\n";
8340 outs() << " cryptsize " << ec.cryptsize;
8341 if (ec.cryptsize > object_size)
8342 outs() << " (past end of file)\n";
8343 else
8344 outs() << "\n";
8345 outs() << " cryptid " << ec.cryptid << "\n";
8346 outs() << " pad " << ec.pad << "\n";
8347}
8348
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008349static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
8350 const char *Ptr) {
8351 outs() << " cmd LC_LINKER_OPTION\n";
8352 outs() << " cmdsize " << lo.cmdsize;
8353 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
8354 outs() << " Incorrect size\n";
8355 else
8356 outs() << "\n";
8357 outs() << " count " << lo.count << "\n";
8358 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
8359 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
8360 uint32_t i = 0;
8361 while (left > 0) {
8362 while (*string == '\0' && left > 0) {
8363 string++;
8364 left--;
8365 }
8366 if (left > 0) {
8367 i++;
8368 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00008369 uint32_t NullPos = StringRef(string, left).find('\0');
8370 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008371 string += len;
8372 left -= len;
8373 }
8374 }
8375 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008376 outs() << " count " << lo.count << " does not match number of strings "
8377 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008378}
8379
Kevin Enderbyb4b79312014-12-18 19:24:35 +00008380static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
8381 const char *Ptr) {
8382 outs() << " cmd LC_SUB_FRAMEWORK\n";
8383 outs() << " cmdsize " << sub.cmdsize;
8384 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
8385 outs() << " Incorrect size\n";
8386 else
8387 outs() << "\n";
8388 if (sub.umbrella < sub.cmdsize) {
8389 const char *P = Ptr + sub.umbrella;
8390 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
8391 } else {
8392 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
8393 }
8394}
8395
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00008396static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
8397 const char *Ptr) {
8398 outs() << " cmd LC_SUB_UMBRELLA\n";
8399 outs() << " cmdsize " << sub.cmdsize;
8400 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
8401 outs() << " Incorrect size\n";
8402 else
8403 outs() << "\n";
8404 if (sub.sub_umbrella < sub.cmdsize) {
8405 const char *P = Ptr + sub.sub_umbrella;
8406 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
8407 } else {
8408 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
8409 }
8410}
8411
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008412static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008413 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008414 outs() << " cmd LC_SUB_LIBRARY\n";
8415 outs() << " cmdsize " << sub.cmdsize;
8416 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
8417 outs() << " Incorrect size\n";
8418 else
8419 outs() << "\n";
8420 if (sub.sub_library < sub.cmdsize) {
8421 const char *P = Ptr + sub.sub_library;
8422 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
8423 } else {
8424 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
8425 }
8426}
8427
Kevin Enderby186eac32014-12-19 21:06:24 +00008428static void PrintSubClientCommand(MachO::sub_client_command sub,
8429 const char *Ptr) {
8430 outs() << " cmd LC_SUB_CLIENT\n";
8431 outs() << " cmdsize " << sub.cmdsize;
8432 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
8433 outs() << " Incorrect size\n";
8434 else
8435 outs() << "\n";
8436 if (sub.client < sub.cmdsize) {
8437 const char *P = Ptr + sub.client;
8438 outs() << " client " << P << " (offset " << sub.client << ")\n";
8439 } else {
8440 outs() << " client ?(bad offset " << sub.client << ")\n";
8441 }
8442}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008443
Kevin Enderby52e4ce42014-12-19 22:25:22 +00008444static void PrintRoutinesCommand(MachO::routines_command r) {
8445 outs() << " cmd LC_ROUTINES\n";
8446 outs() << " cmdsize " << r.cmdsize;
8447 if (r.cmdsize != sizeof(struct MachO::routines_command))
8448 outs() << " Incorrect size\n";
8449 else
8450 outs() << "\n";
8451 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
8452 outs() << " init_module " << r.init_module << "\n";
8453 outs() << " reserved1 " << r.reserved1 << "\n";
8454 outs() << " reserved2 " << r.reserved2 << "\n";
8455 outs() << " reserved3 " << r.reserved3 << "\n";
8456 outs() << " reserved4 " << r.reserved4 << "\n";
8457 outs() << " reserved5 " << r.reserved5 << "\n";
8458 outs() << " reserved6 " << r.reserved6 << "\n";
8459}
8460
8461static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
8462 outs() << " cmd LC_ROUTINES_64\n";
8463 outs() << " cmdsize " << r.cmdsize;
8464 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
8465 outs() << " Incorrect size\n";
8466 else
8467 outs() << "\n";
8468 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
8469 outs() << " init_module " << r.init_module << "\n";
8470 outs() << " reserved1 " << r.reserved1 << "\n";
8471 outs() << " reserved2 " << r.reserved2 << "\n";
8472 outs() << " reserved3 " << r.reserved3 << "\n";
8473 outs() << " reserved4 " << r.reserved4 << "\n";
8474 outs() << " reserved5 " << r.reserved5 << "\n";
8475 outs() << " reserved6 " << r.reserved6 << "\n";
8476}
8477
Kevin Enderby48ef5342014-12-23 22:56:39 +00008478static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
8479 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
8480 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
8481 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
8482 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
8483 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
8484 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
8485 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
8486 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
8487 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
8488 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
8489 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
8490 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
8491 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
8492 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
8493 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
8494 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
8495 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
8496 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
8497 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
8498 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
8499 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
8500}
8501
Kevin Enderby227df342014-12-23 23:43:59 +00008502static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008503 uint32_t f;
8504 outs() << "\t mmst_reg ";
8505 for (f = 0; f < 10; f++)
8506 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
8507 outs() << "\n";
8508 outs() << "\t mmst_rsrv ";
8509 for (f = 0; f < 6; f++)
8510 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
8511 outs() << "\n";
8512}
8513
Kevin Enderbyaefb0032014-12-24 00:16:51 +00008514static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008515 uint32_t f;
8516 outs() << "\t xmm_reg ";
8517 for (f = 0; f < 16; f++)
8518 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
8519 outs() << "\n";
8520}
8521
8522static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
8523 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
8524 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
8525 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
8526 outs() << " denorm " << fpu.fpu_fcw.denorm;
8527 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
8528 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
8529 outs() << " undfl " << fpu.fpu_fcw.undfl;
8530 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
8531 outs() << "\t\t pc ";
8532 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
8533 outs() << "FP_PREC_24B ";
8534 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
8535 outs() << "FP_PREC_53B ";
8536 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
8537 outs() << "FP_PREC_64B ";
8538 else
8539 outs() << fpu.fpu_fcw.pc << " ";
8540 outs() << "rc ";
8541 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
8542 outs() << "FP_RND_NEAR ";
8543 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
8544 outs() << "FP_RND_DOWN ";
8545 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
8546 outs() << "FP_RND_UP ";
8547 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008548 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008549 outs() << "\n";
8550 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
8551 outs() << " denorm " << fpu.fpu_fsw.denorm;
8552 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
8553 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
8554 outs() << " undfl " << fpu.fpu_fsw.undfl;
8555 outs() << " precis " << fpu.fpu_fsw.precis;
8556 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
8557 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
8558 outs() << " c0 " << fpu.fpu_fsw.c0;
8559 outs() << " c1 " << fpu.fpu_fsw.c1;
8560 outs() << " c2 " << fpu.fpu_fsw.c2;
8561 outs() << " tos " << fpu.fpu_fsw.tos;
8562 outs() << " c3 " << fpu.fpu_fsw.c3;
8563 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
8564 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
8565 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
8566 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
8567 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
8568 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
8569 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
8570 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
8571 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
8572 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
8573 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
8574 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
8575 outs() << "\n";
8576 outs() << "\t fpu_stmm0:\n";
8577 Print_mmst_reg(fpu.fpu_stmm0);
8578 outs() << "\t fpu_stmm1:\n";
8579 Print_mmst_reg(fpu.fpu_stmm1);
8580 outs() << "\t fpu_stmm2:\n";
8581 Print_mmst_reg(fpu.fpu_stmm2);
8582 outs() << "\t fpu_stmm3:\n";
8583 Print_mmst_reg(fpu.fpu_stmm3);
8584 outs() << "\t fpu_stmm4:\n";
8585 Print_mmst_reg(fpu.fpu_stmm4);
8586 outs() << "\t fpu_stmm5:\n";
8587 Print_mmst_reg(fpu.fpu_stmm5);
8588 outs() << "\t fpu_stmm6:\n";
8589 Print_mmst_reg(fpu.fpu_stmm6);
8590 outs() << "\t fpu_stmm7:\n";
8591 Print_mmst_reg(fpu.fpu_stmm7);
8592 outs() << "\t fpu_xmm0:\n";
8593 Print_xmm_reg(fpu.fpu_xmm0);
8594 outs() << "\t fpu_xmm1:\n";
8595 Print_xmm_reg(fpu.fpu_xmm1);
8596 outs() << "\t fpu_xmm2:\n";
8597 Print_xmm_reg(fpu.fpu_xmm2);
8598 outs() << "\t fpu_xmm3:\n";
8599 Print_xmm_reg(fpu.fpu_xmm3);
8600 outs() << "\t fpu_xmm4:\n";
8601 Print_xmm_reg(fpu.fpu_xmm4);
8602 outs() << "\t fpu_xmm5:\n";
8603 Print_xmm_reg(fpu.fpu_xmm5);
8604 outs() << "\t fpu_xmm6:\n";
8605 Print_xmm_reg(fpu.fpu_xmm6);
8606 outs() << "\t fpu_xmm7:\n";
8607 Print_xmm_reg(fpu.fpu_xmm7);
8608 outs() << "\t fpu_xmm8:\n";
8609 Print_xmm_reg(fpu.fpu_xmm8);
8610 outs() << "\t fpu_xmm9:\n";
8611 Print_xmm_reg(fpu.fpu_xmm9);
8612 outs() << "\t fpu_xmm10:\n";
8613 Print_xmm_reg(fpu.fpu_xmm10);
8614 outs() << "\t fpu_xmm11:\n";
8615 Print_xmm_reg(fpu.fpu_xmm11);
8616 outs() << "\t fpu_xmm12:\n";
8617 Print_xmm_reg(fpu.fpu_xmm12);
8618 outs() << "\t fpu_xmm13:\n";
8619 Print_xmm_reg(fpu.fpu_xmm13);
8620 outs() << "\t fpu_xmm14:\n";
8621 Print_xmm_reg(fpu.fpu_xmm14);
8622 outs() << "\t fpu_xmm15:\n";
8623 Print_xmm_reg(fpu.fpu_xmm15);
8624 outs() << "\t fpu_rsrv4:\n";
8625 for (uint32_t f = 0; f < 6; f++) {
8626 outs() << "\t ";
8627 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008628 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008629 outs() << "\n";
8630 }
8631 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
8632 outs() << "\n";
8633}
8634
8635static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
8636 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
8637 outs() << " err " << format("0x%08" PRIx32, exc64.err);
8638 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
8639}
8640
8641static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
8642 bool isLittleEndian, uint32_t cputype) {
8643 if (t.cmd == MachO::LC_THREAD)
8644 outs() << " cmd LC_THREAD\n";
8645 else if (t.cmd == MachO::LC_UNIXTHREAD)
8646 outs() << " cmd LC_UNIXTHREAD\n";
8647 else
8648 outs() << " cmd " << t.cmd << " (unknown)\n";
8649 outs() << " cmdsize " << t.cmdsize;
8650 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
8651 outs() << " Incorrect size\n";
8652 else
8653 outs() << "\n";
8654
8655 const char *begin = Ptr + sizeof(struct MachO::thread_command);
8656 const char *end = Ptr + t.cmdsize;
8657 uint32_t flavor, count, left;
8658 if (cputype == MachO::CPU_TYPE_X86_64) {
8659 while (begin < end) {
8660 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8661 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8662 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008663 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008664 flavor = 0;
8665 begin = end;
8666 }
8667 if (isLittleEndian != sys::IsLittleEndianHost)
8668 sys::swapByteOrder(flavor);
8669 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8670 memcpy((char *)&count, begin, sizeof(uint32_t));
8671 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008672 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008673 count = 0;
8674 begin = end;
8675 }
8676 if (isLittleEndian != sys::IsLittleEndianHost)
8677 sys::swapByteOrder(count);
8678 if (flavor == MachO::x86_THREAD_STATE64) {
8679 outs() << " flavor x86_THREAD_STATE64\n";
8680 if (count == MachO::x86_THREAD_STATE64_COUNT)
8681 outs() << " count x86_THREAD_STATE64_COUNT\n";
8682 else
8683 outs() << " count " << count
8684 << " (not x86_THREAD_STATE64_COUNT)\n";
8685 MachO::x86_thread_state64_t cpu64;
8686 left = end - begin;
8687 if (left >= sizeof(MachO::x86_thread_state64_t)) {
8688 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
8689 begin += sizeof(MachO::x86_thread_state64_t);
8690 } else {
8691 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
8692 memcpy(&cpu64, begin, left);
8693 begin += left;
8694 }
8695 if (isLittleEndian != sys::IsLittleEndianHost)
8696 swapStruct(cpu64);
8697 Print_x86_thread_state64_t(cpu64);
8698 } else if (flavor == MachO::x86_THREAD_STATE) {
8699 outs() << " flavor x86_THREAD_STATE\n";
8700 if (count == MachO::x86_THREAD_STATE_COUNT)
8701 outs() << " count x86_THREAD_STATE_COUNT\n";
8702 else
8703 outs() << " count " << count
8704 << " (not x86_THREAD_STATE_COUNT)\n";
8705 struct MachO::x86_thread_state_t ts;
8706 left = end - begin;
8707 if (left >= sizeof(MachO::x86_thread_state_t)) {
8708 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
8709 begin += sizeof(MachO::x86_thread_state_t);
8710 } else {
8711 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
8712 memcpy(&ts, begin, left);
8713 begin += left;
8714 }
8715 if (isLittleEndian != sys::IsLittleEndianHost)
8716 swapStruct(ts);
8717 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
8718 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
8719 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
8720 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
8721 else
8722 outs() << "tsh.count " << ts.tsh.count
8723 << " (not x86_THREAD_STATE64_COUNT\n";
8724 Print_x86_thread_state64_t(ts.uts.ts64);
8725 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008726 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
8727 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008728 }
8729 } else if (flavor == MachO::x86_FLOAT_STATE) {
8730 outs() << " flavor x86_FLOAT_STATE\n";
8731 if (count == MachO::x86_FLOAT_STATE_COUNT)
8732 outs() << " count x86_FLOAT_STATE_COUNT\n";
8733 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008734 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008735 struct MachO::x86_float_state_t fs;
8736 left = end - begin;
8737 if (left >= sizeof(MachO::x86_float_state_t)) {
8738 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
8739 begin += sizeof(MachO::x86_float_state_t);
8740 } else {
8741 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
8742 memcpy(&fs, begin, left);
8743 begin += left;
8744 }
8745 if (isLittleEndian != sys::IsLittleEndianHost)
8746 swapStruct(fs);
8747 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
8748 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008749 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008750 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
8751 else
8752 outs() << "fsh.count " << fs.fsh.count
8753 << " (not x86_FLOAT_STATE64_COUNT\n";
8754 Print_x86_float_state_t(fs.ufs.fs64);
8755 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008756 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
8757 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008758 }
8759 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
8760 outs() << " flavor x86_EXCEPTION_STATE\n";
8761 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
8762 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
8763 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008764 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00008765 << " (not x86_EXCEPTION_STATE_COUNT)\n";
8766 struct MachO::x86_exception_state_t es;
8767 left = end - begin;
8768 if (left >= sizeof(MachO::x86_exception_state_t)) {
8769 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
8770 begin += sizeof(MachO::x86_exception_state_t);
8771 } else {
8772 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
8773 memcpy(&es, begin, left);
8774 begin += left;
8775 }
8776 if (isLittleEndian != sys::IsLittleEndianHost)
8777 swapStruct(es);
8778 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
8779 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008780 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008781 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
8782 else
8783 outs() << "\t esh.count " << es.esh.count
8784 << " (not x86_EXCEPTION_STATE64_COUNT\n";
8785 Print_x86_exception_state_t(es.ues.es64);
8786 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008787 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
8788 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008789 }
8790 } else {
8791 outs() << " flavor " << flavor << " (unknown)\n";
8792 outs() << " count " << count << "\n";
8793 outs() << " state (unknown)\n";
8794 begin += count * sizeof(uint32_t);
8795 }
8796 }
8797 } else {
8798 while (begin < end) {
8799 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8800 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8801 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008802 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008803 flavor = 0;
8804 begin = end;
8805 }
8806 if (isLittleEndian != sys::IsLittleEndianHost)
8807 sys::swapByteOrder(flavor);
8808 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8809 memcpy((char *)&count, begin, sizeof(uint32_t));
8810 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008811 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008812 count = 0;
8813 begin = end;
8814 }
8815 if (isLittleEndian != sys::IsLittleEndianHost)
8816 sys::swapByteOrder(count);
8817 outs() << " flavor " << flavor << "\n";
8818 outs() << " count " << count << "\n";
8819 outs() << " state (Unknown cputype/cpusubtype)\n";
8820 begin += count * sizeof(uint32_t);
8821 }
8822 }
8823}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008824
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008825static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
8826 if (dl.cmd == MachO::LC_ID_DYLIB)
8827 outs() << " cmd LC_ID_DYLIB\n";
8828 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
8829 outs() << " cmd LC_LOAD_DYLIB\n";
8830 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
8831 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
8832 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
8833 outs() << " cmd LC_REEXPORT_DYLIB\n";
8834 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
8835 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
8836 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
8837 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
8838 else
8839 outs() << " cmd " << dl.cmd << " (unknown)\n";
8840 outs() << " cmdsize " << dl.cmdsize;
8841 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
8842 outs() << " Incorrect size\n";
8843 else
8844 outs() << "\n";
8845 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008846 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008847 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
8848 } else {
8849 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
8850 }
8851 outs() << " time stamp " << dl.dylib.timestamp << " ";
8852 time_t t = dl.dylib.timestamp;
8853 outs() << ctime(&t);
8854 outs() << " current version ";
8855 if (dl.dylib.current_version == 0xffffffff)
8856 outs() << "n/a\n";
8857 else
8858 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
8859 << ((dl.dylib.current_version >> 8) & 0xff) << "."
8860 << (dl.dylib.current_version & 0xff) << "\n";
8861 outs() << "compatibility version ";
8862 if (dl.dylib.compatibility_version == 0xffffffff)
8863 outs() << "n/a\n";
8864 else
8865 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
8866 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
8867 << (dl.dylib.compatibility_version & 0xff) << "\n";
8868}
8869
8870static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
8871 uint32_t object_size) {
8872 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
Kevin Enderby1be37a32016-04-28 21:07:20 +00008873 outs() << " cmd LC_CODE_SIGNATURE\n";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008874 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
8875 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
8876 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
8877 outs() << " cmd LC_FUNCTION_STARTS\n";
8878 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
8879 outs() << " cmd LC_DATA_IN_CODE\n";
8880 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
8881 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
8882 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
8883 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
8884 else
8885 outs() << " cmd " << ld.cmd << " (?)\n";
8886 outs() << " cmdsize " << ld.cmdsize;
8887 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
8888 outs() << " Incorrect size\n";
8889 else
8890 outs() << "\n";
8891 outs() << " dataoff " << ld.dataoff;
8892 if (ld.dataoff > object_size)
8893 outs() << " (past end of file)\n";
8894 else
8895 outs() << "\n";
8896 outs() << " datasize " << ld.datasize;
8897 uint64_t big_size = ld.dataoff;
8898 big_size += ld.datasize;
8899 if (big_size > object_size)
8900 outs() << " (past end of file)\n";
8901 else
8902 outs() << "\n";
8903}
8904
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008905static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
8906 uint32_t cputype, bool verbose) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008907 StringRef Buf = Obj->getData();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008908 unsigned Index = 0;
8909 for (const auto &Command : Obj->load_commands()) {
8910 outs() << "Load command " << Index++ << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008911 if (Command.C.cmd == MachO::LC_SEGMENT) {
8912 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
8913 const char *sg_segname = SLC.segname;
8914 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
8915 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
8916 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
8917 verbose);
8918 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00008919 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00008920 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
8921 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
8922 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
8923 }
8924 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
8925 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
8926 const char *sg_segname = SLC_64.segname;
8927 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
8928 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
8929 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
8930 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
8931 for (unsigned j = 0; j < SLC_64.nsects; j++) {
8932 MachO::section_64 S_64 = Obj->getSection64(Command, j);
8933 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
8934 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
8935 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
8936 sg_segname, filetype, Buf.size(), verbose);
8937 }
8938 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
8939 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00008940 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00008941 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
8942 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
8943 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00008944 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
8945 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008946 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
8947 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
8948 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
8949 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
8950 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
8951 Command.C.cmd == MachO::LC_ID_DYLINKER ||
8952 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
8953 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
8954 PrintDyldLoadCommand(Dyld, Command.Ptr);
8955 } else if (Command.C.cmd == MachO::LC_UUID) {
8956 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
8957 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008958 } else if (Command.C.cmd == MachO::LC_RPATH) {
8959 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
8960 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00008961 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
Tim Northoverbfbfb122015-11-02 21:26:58 +00008962 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
8963 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
8964 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008965 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
8966 PrintVersionMinLoadCommand(Vd);
8967 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
8968 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
8969 PrintSourceVersionCommand(Sd);
8970 } else if (Command.C.cmd == MachO::LC_MAIN) {
8971 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
8972 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00008973 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008974 MachO::encryption_info_command Ei =
8975 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00008976 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00008977 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008978 MachO::encryption_info_command_64 Ei =
8979 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00008980 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008981 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008982 MachO::linker_option_command Lo =
8983 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008984 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00008985 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
8986 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
8987 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00008988 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
8989 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
8990 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008991 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
8992 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
8993 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00008994 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
8995 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
8996 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00008997 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
8998 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
8999 PrintRoutinesCommand(Rc);
9000 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
9001 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
9002 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00009003 } else if (Command.C.cmd == MachO::LC_THREAD ||
9004 Command.C.cmd == MachO::LC_UNIXTHREAD) {
9005 MachO::thread_command Tc = Obj->getThreadCommand(Command);
9006 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00009007 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
9008 Command.C.cmd == MachO::LC_ID_DYLIB ||
9009 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
9010 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
9011 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
9012 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009013 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
9014 PrintDylibCommand(Dl, Command.Ptr);
9015 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
9016 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
9017 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
9018 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
9019 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
9020 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
9021 MachO::linkedit_data_command Ld =
9022 Obj->getLinkeditDataLoadCommand(Command);
9023 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009024 } else {
9025 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
9026 << ")\n";
9027 outs() << " cmdsize " << Command.C.cmdsize << "\n";
9028 // TODO: get and print the raw bytes of the load command.
9029 }
9030 // TODO: print all the other kinds of load commands.
Kevin Enderby956366c2014-08-29 22:30:52 +00009031 }
9032}
9033
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009034static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009035 if (Obj->is64Bit()) {
9036 MachO::mach_header_64 H_64;
9037 H_64 = Obj->getHeader64();
9038 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
9039 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
9040 } else {
9041 MachO::mach_header H;
9042 H = Obj->getHeader();
9043 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
9044 H.sizeofcmds, H.flags, verbose);
9045 }
9046}
9047
9048void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
9049 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009050 PrintMachHeader(file, !NonVerbose);
9051}
9052
9053void llvm::printMachOLoadCommands(const object::ObjectFile *Obj) {
9054 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00009055 uint32_t filetype = 0;
9056 uint32_t cputype = 0;
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009057 if (file->is64Bit()) {
9058 MachO::mach_header_64 H_64;
9059 H_64 = file->getHeader64();
9060 filetype = H_64.filetype;
9061 cputype = H_64.cputype;
9062 } else {
9063 MachO::mach_header H;
9064 H = file->getHeader();
9065 filetype = H.filetype;
9066 cputype = H.cputype;
9067 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009068 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009069}
Nick Kledzikd04bc352014-08-30 00:20:14 +00009070
9071//===----------------------------------------------------------------------===//
9072// export trie dumping
9073//===----------------------------------------------------------------------===//
9074
9075void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009076 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
9077 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +00009078 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
9079 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
9080 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9081 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
9082 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9083 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
9084 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
9085 if (ReExport)
9086 outs() << "[re-export] ";
9087 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009088 outs() << format("0x%08llX ",
9089 Entry.address()); // FIXME:add in base address
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009090 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +00009091 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009092 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +00009093 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +00009094 if (WeakDef) {
9095 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009096 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009097 }
9098 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009099 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009100 outs() << ", ";
9101 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009102 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009103 }
9104 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009105 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009106 outs() << ", ";
9107 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009108 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009109 }
9110 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009111 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009112 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009113 outs() << format("resolver=0x%08llX", Entry.other());
9114 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009115 }
9116 outs() << "]";
9117 }
9118 if (ReExport) {
9119 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009120 int Ordinal = Entry.other() - 1;
9121 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
9122 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +00009123 outs() << " (from " << DylibName << ")";
9124 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009125 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +00009126 }
9127 outs() << "\n";
9128 }
9129}
Nick Kledzikac431442014-09-12 21:34:15 +00009130
Nick Kledzikac431442014-09-12 21:34:15 +00009131//===----------------------------------------------------------------------===//
9132// rebase table dumping
9133//===----------------------------------------------------------------------===//
9134
9135namespace {
9136class SegInfo {
9137public:
9138 SegInfo(const object::MachOObjectFile *Obj);
9139
9140 StringRef segmentName(uint32_t SegIndex);
9141 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
9142 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00009143 bool isValidSegIndexAndOffset(uint32_t SegIndex, uint64_t SegOffset);
Nick Kledzikac431442014-09-12 21:34:15 +00009144
9145private:
9146 struct SectionInfo {
9147 uint64_t Address;
9148 uint64_t Size;
9149 StringRef SectionName;
9150 StringRef SegmentName;
9151 uint64_t OffsetInSegment;
9152 uint64_t SegmentStartAddress;
9153 uint32_t SegmentIndex;
9154 };
9155 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
9156 SmallVector<SectionInfo, 32> Sections;
9157};
9158}
9159
9160SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
9161 // Build table of sections so segIndex/offset pairs can be translated.
Nick Kledzik56ebef42014-09-16 01:41:51 +00009162 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
Nick Kledzikac431442014-09-12 21:34:15 +00009163 StringRef CurSegName;
9164 uint64_t CurSegAddress;
9165 for (const SectionRef &Section : Obj->sections()) {
9166 SectionInfo Info;
Davide Italianoccd53fe2015-08-05 07:18:31 +00009167 error(Section.getName(Info.SectionName));
Rafael Espindola80291272014-10-08 15:28:58 +00009168 Info.Address = Section.getAddress();
9169 Info.Size = Section.getSize();
Nick Kledzikac431442014-09-12 21:34:15 +00009170 Info.SegmentName =
9171 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
9172 if (!Info.SegmentName.equals(CurSegName)) {
9173 ++CurSegIndex;
9174 CurSegName = Info.SegmentName;
9175 CurSegAddress = Info.Address;
9176 }
9177 Info.SegmentIndex = CurSegIndex - 1;
9178 Info.OffsetInSegment = Info.Address - CurSegAddress;
9179 Info.SegmentStartAddress = CurSegAddress;
9180 Sections.push_back(Info);
9181 }
9182}
9183
9184StringRef SegInfo::segmentName(uint32_t SegIndex) {
9185 for (const SectionInfo &SI : Sections) {
9186 if (SI.SegmentIndex == SegIndex)
9187 return SI.SegmentName;
9188 }
9189 llvm_unreachable("invalid segIndex");
9190}
9191
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00009192bool SegInfo::isValidSegIndexAndOffset(uint32_t SegIndex,
9193 uint64_t OffsetInSeg) {
9194 for (const SectionInfo &SI : Sections) {
9195 if (SI.SegmentIndex != SegIndex)
9196 continue;
9197 if (SI.OffsetInSegment > OffsetInSeg)
9198 continue;
9199 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
9200 continue;
9201 return true;
9202 }
9203 return false;
9204}
9205
Nick Kledzikac431442014-09-12 21:34:15 +00009206const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
9207 uint64_t OffsetInSeg) {
9208 for (const SectionInfo &SI : Sections) {
9209 if (SI.SegmentIndex != SegIndex)
9210 continue;
9211 if (SI.OffsetInSegment > OffsetInSeg)
9212 continue;
9213 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
9214 continue;
9215 return SI;
9216 }
9217 llvm_unreachable("segIndex and offset not in any section");
9218}
9219
9220StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
9221 return findSection(SegIndex, OffsetInSeg).SectionName;
9222}
9223
9224uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
9225 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
9226 return SI.SegmentStartAddress + OffsetInSeg;
9227}
9228
9229void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
9230 // Build table of sections so names can used in final output.
9231 SegInfo sectionTable(Obj);
9232
9233 outs() << "segment section address type\n";
9234 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
9235 uint32_t SegIndex = Entry.segmentIndex();
9236 uint64_t OffsetInSeg = Entry.segmentOffset();
9237 StringRef SegmentName = sectionTable.segmentName(SegIndex);
9238 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
9239 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9240
9241 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009242 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
9243 SegmentName.str().c_str(), SectionName.str().c_str(),
9244 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +00009245 }
9246}
Nick Kledzik56ebef42014-09-16 01:41:51 +00009247
9248static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
9249 StringRef DylibName;
9250 switch (Ordinal) {
9251 case MachO::BIND_SPECIAL_DYLIB_SELF:
9252 return "this-image";
9253 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
9254 return "main-executable";
9255 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
9256 return "flat-namespace";
9257 default:
Nick Kledzikabd29872014-09-16 22:03:13 +00009258 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009259 std::error_code EC =
9260 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +00009261 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +00009262 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +00009263 return DylibName;
9264 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00009265 }
Nick Kledzikabd29872014-09-16 22:03:13 +00009266 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009267}
9268
9269//===----------------------------------------------------------------------===//
9270// bind table dumping
9271//===----------------------------------------------------------------------===//
9272
9273void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
9274 // Build table of sections so names can used in final output.
9275 SegInfo sectionTable(Obj);
9276
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009277 outs() << "segment section address type "
9278 "addend dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009279 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
9280 uint32_t SegIndex = Entry.segmentIndex();
9281 uint64_t OffsetInSeg = Entry.segmentOffset();
9282 StringRef SegmentName = sectionTable.segmentName(SegIndex);
9283 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
9284 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9285
9286 // Table lines look like:
9287 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009288 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00009289 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009290 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009291 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009292 << left_justify(SectionName, 18) << " "
9293 << format_hex(Address, 10, true) << " "
9294 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009295 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009296 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009297 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009298 }
9299}
9300
9301//===----------------------------------------------------------------------===//
9302// lazy bind table dumping
9303//===----------------------------------------------------------------------===//
9304
9305void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
9306 // Build table of sections so names can used in final output.
9307 SegInfo sectionTable(Obj);
9308
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009309 outs() << "segment section address "
9310 "dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009311 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
9312 uint32_t SegIndex = Entry.segmentIndex();
9313 uint64_t OffsetInSeg = Entry.segmentOffset();
9314 StringRef SegmentName = sectionTable.segmentName(SegIndex);
9315 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
9316 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9317
9318 // Table lines look like:
9319 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009320 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009321 << left_justify(SectionName, 18) << " "
9322 << format_hex(Address, 10, true) << " "
9323 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00009324 << Entry.symbolName() << "\n";
9325 }
9326}
9327
Nick Kledzik56ebef42014-09-16 01:41:51 +00009328//===----------------------------------------------------------------------===//
9329// weak bind table dumping
9330//===----------------------------------------------------------------------===//
9331
9332void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
9333 // Build table of sections so names can used in final output.
9334 SegInfo sectionTable(Obj);
9335
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009336 outs() << "segment section address "
9337 "type addend symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009338 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
9339 // Strong symbols don't have a location to update.
9340 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009341 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +00009342 << Entry.symbolName() << "\n";
9343 continue;
9344 }
9345 uint32_t SegIndex = Entry.segmentIndex();
9346 uint64_t OffsetInSeg = Entry.segmentOffset();
9347 StringRef SegmentName = sectionTable.segmentName(SegIndex);
9348 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
9349 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9350
9351 // Table lines look like:
9352 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009353 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009354 << left_justify(SectionName, 18) << " "
9355 << format_hex(Address, 10, true) << " "
9356 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009357 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
9358 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009359 }
9360}
9361
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009362// get_dyld_bind_info_symbolname() is used for disassembly and passed an
9363// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
9364// information for that address. If the address is found its binding symbol
9365// name is returned. If not nullptr is returned.
9366static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
9367 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +00009368 if (info->bindtable == nullptr) {
9369 info->bindtable = new (BindTable);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009370 SegInfo sectionTable(info->O);
9371 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
9372 uint32_t SegIndex = Entry.segmentIndex();
9373 uint64_t OffsetInSeg = Entry.segmentOffset();
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00009374 if (!sectionTable.isValidSegIndexAndOffset(SegIndex, OffsetInSeg))
9375 continue;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009376 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9377 const char *SymbolName = nullptr;
9378 StringRef name = Entry.symbolName();
9379 if (!name.empty())
9380 SymbolName = name.data();
Kevin Enderby078be602014-10-23 19:53:12 +00009381 info->bindtable->push_back(std::make_pair(Address, SymbolName));
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009382 }
9383 }
Kevin Enderby078be602014-10-23 19:53:12 +00009384 for (bind_table_iterator BI = info->bindtable->begin(),
9385 BE = info->bindtable->end();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009386 BI != BE; ++BI) {
9387 uint64_t Address = BI->first;
9388 if (ReferenceValue == Address) {
9389 const char *SymbolName = BI->second;
9390 return SymbolName;
9391 }
9392 }
9393 return nullptr;
9394}